branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>kindanon/AsciiPlanets<file_sep>/README.md
# AsciiPlanets
3d planets in ascii on the terminal
<file_sep>/AsciiPlanets.py
import math
pi = math.pi
f_len = 50
f_wid = 50
def PointsInCircum(r):
return [(int(25+ math.cos(2*pi/1000*x)*r),int(25+ math.sin(2*pi/1000*x)*r)) for x in range(0,1000+1)]
def Rings(r):
#does not work
return [(int((x-0)**2/25**2),int((x-0)**2/29**2)) for x in range(0,1000+1)]
final_image = [[" " for x in range(f_len)] for y in range(f_wid)]
for x,y in PointsInCircum(20):
try:
final_image[x][y] = "0 "
except IndexError:
pass
for x,y in Rings(20):
try:
final_image[x][y] = "0 "
except IndexError:
pass
print('\n'.join([''.join(['{:1}'.format(item) for item in row])
for row in final_image]))
#def PointsInCircum(r,n=100):
# return [(math.cos(2*pi/n*x)*r,math.sin(2*pi/n*x)*r) for x in range(0,n+1)] | e603121e07597087b5506488228e2b3c98047d2e | [
"Markdown",
"Python"
] | 2 | Markdown | kindanon/AsciiPlanets | fab1b4b17e3431e4fe5736e879db38149231b62e | 7ccba1520d7c97229be4bcda3fcca853c90c0c26 |
refs/heads/master | <file_sep>package solutions.egen.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import solutions.egen.exceptions.AppException;
import solutions.egen.model.Guest;
import solutions.egen.utils.DBUtil;
public class GuestDAO {
public List<Guest> getAll() throws AppException {
List<Guest> guestlist = new ArrayList<Guest>();
Connection con = DBUtil.connectToDB();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = con.prepareStatement("Select * from guest");
rs = ps.executeQuery();
while(rs.next()){
Guest gue = new Guest();
gue.setID(rs.getInt("ID"));
gue.setNAME(rs.getString("NAME"));
gue.setDateTime(rs.getDate("DateTime"));
gue.setContact(rs.getString("Contact"));
gue.setSize(rs.getInt("Size"));
guestlist.add(gue);
}
} catch (SQLException e) {
e.printStackTrace();
throw new AppException("Error in fetching records from database", e.getCause());
}
finally{
DBUtil.closeResources(ps, rs, con);
}
return guestlist;
}
public Guest getPerson(int guestId) throws AppException {
Guest gue = new Guest();
Connection con = DBUtil.connectToDB();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = con.prepareStatement("Select * from guest WHERE ID=?");
ps.setInt(1, guestId);
rs = ps.executeQuery();
if(rs.next()){
gue.setID(rs.getInt("ID"));
gue.setNAME(rs.getString("NAME"));
gue.setDateTime(rs.getDate("DateTime"));
gue.setContact(rs.getString("Contact"));
gue.setSize(rs.getInt("Size"));
}
else{
throw new AppException("Guest with ID=" + guestId + " does not exist in the system.");
}
} catch (SQLException e) {
e.printStackTrace();
throw new AppException("Error in fetching records from database", e.getCause());
}
finally{
DBUtil.closeResources(ps, rs, con);
}
return gue;
}
}
<file_sep>## test git repo project
## step 0: take all the new files and add them to commit list.
## step 1: is move files from folder to local repository via commit.
## step 2: move commits from local repository to origin (remote server).<file_sep>package solutions.egen.rest;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import solutions.egen.dao.GuestDAO;
import solutions.egen.exceptions.AppException;
import solutions.egen.model.Guest;
@Path("/guest")
public class GuestController {
@GET
@Path("/all")
@Produces(MediaType.APPLICATION_JSON)
public AppResponse getAll(){
AppResponse resp = new AppResponse();
try {
GuestDAO dao = new GuestDAO();
List<Guest> guestlist = dao.getAll();
resp.setPayload(guestlist);
} catch (AppException e) {
e.printStackTrace();
resp.setStatus(AppResponse.ERROR);
resp.setMessage(e.getMessage());
}
return resp;
}
@GET
@Path("/get/{ID}")
@Produces(MediaType.APPLICATION_JSON)
public AppResponse getGuest(@PathParam("ID")int guestId){
AppResponse resp = new AppResponse();
try {
GuestDAO dao = new GuestDAO();
Guest gue = dao.getPerson(guestId);
resp.setPayload(gue);
} catch (AppException e) {
e.printStackTrace();
resp.setStatus(AppResponse.ERROR);
resp.setMessage(e.getMessage());
}
return resp;
}
@GET
@Path("/add")
public String addGuest(){
return "added";
}
}
<file_sep>(function(){
'use strict';
angular.module('tabApp,[]');
})();<file_sep>(function() {
angular.module('tabApp', []);
angular.module('tabApp').controller('TabController', TabControllerfn)
function TabControllerfn() {
var mainVm = this;
mainVm.setTab = function (newTab) {
mainVm.tab = newTab;
};
mainVm.isSet = function (tabNum) {
return mainVm.tab === tabNum;
};
mainVm.edit = function (){
}
mainVm.delete = function (num) {
mainVm.people.splice(num, 1);
};
mainVm.addguest = function () {
mainVm.newPerson.id = mainVm.people.length + 1;
mainVm.people.push(mainVm.newPerson);
};
mainVm.people = [
{
"id": 1,
"name": "<NAME>",
"Time": "8 / 7 / 2015, 12.00pm",
"Contact": "317 - 603 - 7168",
"Size": "2",
"edit": "glyphicon glyphicon-edit",
"delete": "glyphicon glyphicon-trash"
},
{
"id": 2,
"name": "<NAME>",
"Time": "8 / 7 / 2015, 1.00pm",
"Contact": "317 - 603 - 7168",
"Size": "3",
"edit": "glyphicon glyphicon-edit",
"delete": "glyphicon glyphicon-trash"
},
{
"id": 3,
"name": "<NAME>",
"Time": "8 / 7 / 2015, 5.00pm",
"Contact": "317 - 603 - 7168",
"Size": "7",
"edit": "glyphicon glyphicon-edit",
"delete": "glyphicon glyphicon-trash"
},
{
"id": 4,
"name": "<NAME>",
"Time": "8 / 7 / 2015, 2.00pm",
"Contact": "317 - 603 - 7168",
"Size": "4",
"edit": "glyphicon glyphicon-edit",
"delete": "glyphicon glyphicon-trash"
},
{
"id": 5,
"name": "<NAME>",
"Time": "8 / 7 / 2015, 4.00pm",
"Contact": "317 - 603 - 7168",
"Size": "2",
"edit": "glyphicon glyphicon-edit",
"delete": "glyphicon glyphicon-trash"
},
{
"id": 6,
"name": "<NAME>",
"Time": "8 / 7 / 2015, 8.00pm",
"Contact": "317 - 603 - 7168",
"Size": "5",
"edit": "glyphicon glyphicon-edit",
"delete": "glyphicon glyphicon-trash"
},
{
"id": 7,
"name": "<NAME>",
"Time": "8 / 7 / 2015, 12.00pm",
"Contact": "317 - 603 - 7168",
"Size": "3",
"edit": "glyphicon glyphicon-edit",
"delete": "glyphicon glyphicon-trash"
},
{
"id": 8,
"name": "<NAME>",
"Time": "8 / 7 / 2015, 8.00pm",
"Contact": "317 - 603 - 7168",
"Size": "5",
"edit": "glyphicon glyphicon-edit",
"delete": "glyphicon glyphicon-trash"
},
{
"id": 9,
"name": "<NAME>",
"Time": "8 / 7 / 2015, 2.00pm",
"Contact": "317 - 603 - 7168",
"Size": "6",
"edit": "glyphicon glyphicon-edit",
"delete": "glyphicon glyphicon-trash"
},
{
"id": 10,
"name": "<NAME>",
"Time": "8 / 7 / 2015, 7.00pm",
"Contact": "317 - 603 - 7168",
"Size": "2",
"edit": "glyphicon glyphicon-edit",
"delete": "glyphicon glyphicon-trash"
},
];
}
})();
| c5fdb5fa68d5295a8a6d43bb8132a11090d34a0b | [
"Markdown",
"Java",
"JavaScript"
] | 5 | Java | shreyaspednekar1/Restaurant-Reservation-System | ca2f88603c94e7b8f840ec692c8a8cdbd988becb | 7dd29f9714b6030bd75542241ad96cbc97c8520f |
refs/heads/master | <repo_name>TiffannyVarela/P3Lab6_TiffannyVarela6<file_sep>/Binario.h
#pragma once
#include <string>
using namespace std;
class Binario: public Numero
{
public:
Binario();
Binario(string);
string getNumero();
string toString();
int entero();
//Binario* operator +(int, int);
/*virtual Numero* Suma(int, int);
virtual Numero* Resta(int, int);
virtual Numero* Mult(int, int);*/
~Binario();
};
<file_sep>/Octal.cpp
#include "Numero.h"
#include "Octal.h"
#include <string>
#include <iostream>
using namespace std;
Octal::Octal():Numero(){
}
Octal::Octal(string num):Numero(num){
this->num=num;
}
string Octal::toString(){
return num;
}
string Octal::getNumero(){
string numero;
numero=num;
return numero;
}
int Octal::entero(){
int retorno;
string numero=getNumero();
string nuevo=numero.substr(2,numero.size()-2);
retorno = stoi(nuevo,nullptr,8);
return retorno;
}
/*Numero* Octal::Suma(int num1, int num2){
Numero* x;
string resultado;
int suma=num1+num2;
int res, i=1, resp;
while(suma!=0){
res = suma%8;
suma/=8;
resp+=res*i;
i*=10;
}
resultado="0c"+to_string(resp);
x = new Octal(resultado);
return x;
}
Numero* Octal::Resta(int num1, int num2){
Numero* x;
string resultado;
int resta=num1-num2;
int res, i=1, resp;
while(resta!=0){
res = resta%8;
resta/=8;
resp+=res*i;
i*=10;
}
resultado="0c"+to_string(resp);
x = new Octal(resultado);
return x;
}
Numero* Octal::Mult(int num1, int num2){
Numero* x;
string resultado;
int multiplicacion=num1*num2;
int res, i=1, resp;
while(multiplicacion!=0){
res = multiplicacion%8;
multiplicacion/=8;
resp+=res*i;
i*=10;
}
resultado="0c"+to_string(resp);
x = new Octal(resultado);
return x;
}*/
Octal::~Octal(){
cout<<"Octal Eliminado"<<endl;
}<file_sep>/Numero.h
#pragma once
#include <string>
using namespace std;
class Numero
{
protected:
string num;
Numero();
Numero(string);
public:
virtual string toString();
virtual int entero();
/*virtual Numero* Suma(int, int);
virtual Numero* Resta(int, int);
virtual Numero* Mult(int, int);*/
~Numero();
};
<file_sep>/Numero.cpp
#include "Numero.h"
#include <string>
#include <iostream>
using namespace std;
Numero::Numero(){}
Numero::Numero(string cnum){
this->num=cnum;
}
string Numero::toString(){
return num;
}
int Numero::entero(){
return 0;
}
/*Numero* Numero::Suma(int num1, int num2){
Numero* x;
return x;
}
Numero* Numero::Resta(int num1, int num2){
Numero* x;
return x;
}
Numero* Numero::Mult(int num1, int num2){
Numero* x;
return x;
}
*/
Numero::~Numero(){
}<file_sep>/Main.cpp
#include <iostream>
#include <string>
#include <vector>
#include "Numero.h"
#include "Binario.h"
#include "Octal.h"
#include "Decimal.h"
#include "Hexadecimal.h"
using namespace std;
int menu();//metodo menu
void Validacion(string);
Numero* numero;
vector<Numero*> numeros = vector<Numero*>();
int menuOperaciones();
void printVector();
string tipo(int);
int main(int argc, char const *argv[])//inicio del main
{
int opc=0, resp=-4;
string num;
int pos1,pos2;
int num1, num2;
do{//inicio del do while
switch(opc=menu()){//inicio switch
case 1://inicio case 1
cout<<"Ingrese el numero: ";
cin>>num;
Validacion(num);
break;//fin case 1
case 2://inicio case 2
printVector();
break;//fin case 2
case 3://inicio case 3
if (numeros.size()>=2)
{
printVector();
cout<<"\nIngrese la posicion del primer numero: ";
cin>>pos1;
cout<<"\nIngrese la posicion del segundo numero: ";
cin>>pos2;
while(pos1<0 || pos1>numeros.size()-1 || pos2<0 || pos2>numeros.size()-1 ){
cout<<"\nINGRESE POSICIONES VALIDAS\n"<<endl;
printVector();
cout<<"\nIngrese la posicion del primer numero: ";
cin>>pos1;
cout<<"\nIngrese la posicion del segundo numero: ";
cin>>pos2;
}
/*if (tipo(pos1=="Binario"))
{
num1=numeros[pos1]
}*/
}
else{
cout<<"No hay suficientes datos"<<endl;
}
break;//fin case 3
}//fin switch
cout<<"Desea volver?\n1.Si\n2.No\n:";
cin>>resp;
}while(resp!=2);//fin del do while
for (int i = 0; i < numeros.size(); i++)
{
delete numeros[i];
numeros[i] = NULL;
}
numeros.clear();
delete numero;
cout<<"Fin del programa"<<endl;
return 0;
}//fin del main
int menu(){//inicio metodo menu
while(true){
cout<<"MENU"<<endl
<<"1.- Ingresar Numero"<<endl
<<"2.- Listar Numeros"<<endl
<<"3.- Operacion"<<endl;
cout<<"Ingrese una opcion: ";
int opcion =0;
cin>>opcion;
if(opcion>=1 && opcion<= 3){
return opcion;
}
else{
cout<<"La opcion elegida no es valida, ingrese una opcion entre 1 y 3"<<endl;
}
}//end del while
return 0;
}//fin metodo menu
int menuOperaciones(){//inicio metodo menu
while(true){
cout<<"MENU"<<endl
<<"1.- Suma"<<endl
<<"2.- Resta"<<endl
<<"3.- Multiplicacion"<<endl;
cout<<"Ingrese una opcion: ";
int opcion =0;
cin>>opcion;
if(opcion>=1 && opcion<= 3){
return opcion;
}
else{
cout<<"La opcion elegida no es valida, ingrese una opcion entre 1 y 3"<<endl;
}
}//end del while
return 0;
}//fin metodo menu
void Validacion(string num){
int resp=-1;
size_t foundbi = num.find("b");
size_t foundhex = num.find("0x");
size_t foundoc = num.find("0c");
//cout<<"tam "<<num.size()<<endl;
//cout<<"Pos "<<foundoc<<endl;
if (foundbi==num.size()-1)
{
for (int i = 0; i < num.size(); ++i)
{
if(num[i]!='0' && num[i]!='1' && num[i] !='b'){
resp=2;
}
}
if(resp==-1){
Binario* bin;
bin = new Binario(num);
numeros.push_back(bin);
//cout<<"Protected "<<bin->getNumero()<<endl;
//cout<<"Decimal "<<bin->entero()<<endl;
//cout << bin->toString() <<endl;
//cout << numeros[numeros.size()-1]->toString() <<endl;
}
else{
cout<<"El numero no es binario"<<endl;
}
}
if (foundhex==0)
{
for (int i = 0; i < num.size(); ++i)
{
if(num[i]!='0' && num[i]!='1' && num[i] !='2' && num[i]!='3' && num[i]!='4' && num[i] !='5' && num[i]!='6' && num[i]!='7' && num[i] !='8' && num[i]!='9' && num[i]!='A' && num[i] !='B' && num[i]!='C' && num[i]!='D' && num[i] !='E' && num[i]!='F'&& num[i]!='a' && num[i] !='b' && num[i]!='c' && num[i]!='d' && num[i] !='e' && num[i]!='f' && num[i] !='X' && num[i]!='x'){
resp=2;
}
}
if(resp==-1){
Hexadecimal* hex;
hex = new Hexadecimal(num);
numeros.push_back(hex);
}
else{
cout<<"El numero no es hexadecimal"<<endl;
}
}
if (foundoc==0)
{
for (int i = 0; i < num.size(); ++i)
{
if(num[i]!='0' && num[i]!='1' && num[i] !='2' && num[i]!='3' && num[i]!='4' && num[i] !='5' && num[i]!='6' && num[i]!='7' && num[i]!='C' && num[i]!='c'){
resp=2;
}
}
if(resp==-1){
Octal* oct;
oct = new Octal(num);
numeros.push_back(oct);
}
else{
cout<<"El numero no es hexadecimal"<<endl;
}
}
else{
for (int i = 0; i < num.size(); ++i)
{
if(num[i]!='0' && num[i]!='1' && num[i] !='2' && num[i]!='3' && num[i]!='4' && num[i] !='5' && num[i]!='6' && num[i]!='7' && num[i]!='8' && num[i]!='9'){
resp=2;
}
}
if(resp==-1){
Decimal* dec;
dec = new Decimal(num);
numeros.push_back(dec);
}
else{
//cout<<"El numero no es decimal"<<endl;
}
}
}
void printVector(){
if (!numeros.empty())
{
for (int i = 0; i < numeros.size(); ++i)
{
cout<<"\nPosicion "<<i<<": "<<numeros[i]->toString()<<endl;
}
}
else{
cout<<"El vector esta vacio"<<endl;
}
}
string tipo (int pos){
numero=numeros[pos];
string num=numero->toString();
string tip;
int resp=-1;
size_t foundbi = num.find("b");
size_t foundhex = num.find("0x");
size_t foundoc = num.find("0c");
if (foundbi==num.size()-1)
{
for (int i = 0; i < num.size(); ++i)
{
if(num[i]!='0' && num[i]!='1' && num[i] !='b'){
resp=2;
}
}
if(resp==-1){
tip="Binario";
}
}
if (foundhex==0)
{
for (int i = 0; i < num.size(); ++i)
{
if(num[i]!='0' && num[i]!='1' && num[i] !='2' && num[i]!='3' && num[i]!='4' && num[i] !='5' && num[i]!='6' && num[i]!='7' && num[i] !='8' && num[i]!='9' && num[i]!='A' && num[i] !='B' && num[i]!='C' && num[i]!='D' && num[i] !='E' && num[i]!='F'&& num[i]!='a' && num[i] !='b' && num[i]!='c' && num[i]!='d' && num[i] !='e' && num[i]!='f' && num[i] !='X' && num[i]!='x'){
resp=2;
}
}
if(resp==-1){
tip="Hexadecimal";
}
}
if (foundoc==0)
{
for (int i = 0; i < num.size(); ++i)
{
if(num[i]!='0' && num[i]!='1' && num[i] !='2' && num[i]!='3' && num[i]!='4' && num[i] !='5' && num[i]!='6' && num[i]!='7' && num[i]!='C' && num[i]!='c'){
resp=2;
}
}
if(resp==-1){
tip="Octal";
}
}
else{
for (int i = 0; i < num.size(); ++i)
{
if(num[i]!='0' && num[i]!='1' && num[i] !='2' && num[i]!='3' && num[i]!='4' && num[i] !='5' && num[i]!='6' && num[i]!='7' && num[i]!='8' && num[i]!='9'){
resp=2;
}
}
if(resp==-1){
tip="Decimal";
}
}
return tip;
}<file_sep>/Binario.cpp
#include "Numero.h"
#include "Binario.h"
#include <string>
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
Binario::Binario():Numero(){
}
Binario::Binario(string cnum):Numero(cnum){
this->num=cnum;
}
string Binario::toString(){
return this->num;
}
string Binario::getNumero(){
string numero;
numero=num;
return numero;
}
int Binario::entero(){
int retorno;
string numero=getNumero();
numero.pop_back();
retorno = stoi(numero,nullptr,2);
return retorno;
}
/*Binario* Binario::operator +(int num1, int num2){
int suma=num1+num2;
int exp=0,digito;
double resp=0;
Binario* bin;
while(suma/2!=0){
digito=suma%2;
resp=resp+suma*pow(10.0,exp);
exp++;
suma=suma/2;
}
bin = new Binario(to_string(resp));
return bin;
}*/
/*Numero* Numero::Suma(int num1, int num2){
Numero* x;
int suma=num1+num2;
string resultado;
int exp=0,digito;
double resp=0;
while(suma/2!=0){
digito=suma%2;
resp=resp+suma*pow(10.0,exp);
exp++;
suma=suma/2;
}
resultado=to_string(resp)+"b";
x = new Binario(resultado);
return x;
}
Numero* Numero::Resta(int num1, int num2){
Numero* x;
int suma=num1-num2;
int exp=0,digito;
double resp=0;
string resultado;
while(suma/2!=0){
digito=suma%2;
resp=resp+suma*pow(10.0,exp);
exp++;
suma=suma/2;
}
resultado=to_string(resp)+"b";
x = new Binario(resultado);
return x;
}
Numero* Numero::Mult(int num1, int num2){
Numero* x;
int suma=num1*num2;
string resultado;
int exp=0,digito;
double resp=0;
while(suma/2!=0){
digito=suma%2;
resp=resp+suma*pow(10.0,exp);
exp++;
suma=suma/2;
}
resultado=to_string(resp)+"b";
x = new Binario(resultado);
return x;
}*/
Binario::~Binario(){
cout<<"Binario Eliminado"<<endl;
}<file_sep>/Octal.h
#pragma once
#include <string>
#include "Numero.h"
using namespace std;
class Octal: public Numero
{
public:
Octal();
Octal(string);
string toString();
string getNumero();
int entero();
/*Numero* Suma(int, int);
Numero* Resta(int, int);
Numero* Mult(int, int);*/
~Octal();
};<file_sep>/Decimal.h
#pragma once
#include <string>
#include "Numero.h"
using namespace std;
class Decimal: public Numero
{
public:
Decimal();
Decimal(string);
string toString();
string getNumero();
int entero();
/*Numero* Suma(int, int);
Numero* Resta(int, int);
Numero* Mult(int, int);*/
~Decimal();
};
<file_sep>/Decimal.cpp
#include "Numero.h"
#include "Decimal.h"
#include <string>
#include <iostream>
using namespace std;
Decimal::Decimal():Numero(){
}
Decimal::Decimal(string num):Numero(num){
this->num=num;
}
string Decimal::toString(){
return num;
}
string Decimal::getNumero(){
string numero;
numero=num;
return numero;
}
int Decimal::entero(){
int retorno;
string numero=getNumero();
retorno = stoi(numero,nullptr,10);
return retorno;
}
/*Numero* Numero::Suma(int num1, int num2){
Numero* x;
int suma=num1+num2;
x = new Decimal(to_string(suma));
return x;
}
Numero* Numero::Resta(int num1, int num2){
Numero* x;
int suma=num1+num2;
x = new Decimal(to_string(suma));
return x;
}
Numero* Numero::Mult(int num1, int num2){
Numero* x;
int suma=num1+num2;
x = new Decimal(to_string(suma));
return x;
}*/
Decimal::~Decimal(){
cout<<"Decimal Eliminado"<<endl;
}<file_sep>/Hexadecimal.h
#pragma once
#include <string>
#include "Numero.h"
using namespace std;
class Hexadecimal: public Numero
{
public:
Hexadecimal();
Hexadecimal(string);
string toString();
string getNumero();
int entero();
/*Numero* Suma(int, int);
Numero* Resta(int, int);
Numero* Mult(int, int);*/
~Hexadecimal();
};<file_sep>/Hexadecimal.cpp
#include "Numero.h"
#include "Hexadecimal.h"
#include <string>
#include <iostream>
using namespace std;
Hexadecimal::Hexadecimal():Numero(){
}
Hexadecimal::Hexadecimal(string num):Numero(num){
this->num=num;
}
string Hexadecimal::toString(){
return num;
}
string Hexadecimal::getNumero(){
string numero;
numero=num;
return numero;
}
int Hexadecimal::entero(){
int retorno;
string numero=getNumero();
string nuevo=numero.substr(2,numero.size()-2);
retorno = stoi(nuevo,nullptr,16);
return retorno;
}
/*Numero* Numero::Suma(int num1, int num2){
Numero* x;
int suma=num1+num2;
int r;
string resp="";
char hex[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
while(suma>0)
{
r = suma % 16;
resp = hex[r] + resp;
suma = suma/16;
}
x = new Hexadecimal(resp);
return x;
}
Numero* Numero::Resta(int num1, int num2){
Numero* x;
int suma=num1-num2;
int r;
string resp="";
char hex[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
while(suma>0)
{
r = suma % 16;
resp = hex[r] + resp;
suma = suma/16;
}
x = new Hexadecimal(resp);
return x;
}
Numero* Numero::Mult(int num1, int num2){
Numero* x;
int suma=num1*num2;
int r;
string resp="";
char hex[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
while(suma>0)
{
r = suma % 16;
resp = hex[r] + resp;
suma = suma/16;
}
x = new Hexadecimal(resp);
return x;
}*/
Hexadecimal::~Hexadecimal(){
cout<<"Hexadecimal Eliminado"<<endl;
} | acdeb46852025537088f51a63b5ffdf71caf4e45 | [
"C++"
] | 11 | C++ | TiffannyVarela/P3Lab6_TiffannyVarela6 | 6026176d4084c26f84aaef1bfcc4e73085f5cde1 | 913ab4be6ed83d77f7ce2ae96c599da2af2739ad |
refs/heads/master | <repo_name>jessetsaoj/myFirstProject<file_sep>/Server.py
# -*- encoding: utf-8 -*-
import socket
import threading
import datetime
from time import gmtime, strftime
class Server:
def __init__(self, host, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock = sock
self.sock.bind((host, port))
self.sock.listen(5)
print('Server', socket.gethostbyname(host), 'listening ...')
self.mylist = list()
self.usrpool= list()
def checkConnection(self):
connection, addr = self.sock.accept()
print('Accept a new connection', connection.getsockname(), connection.fileno())
try:
buf = connection.recv(1024).decode()
if buf == '1':
# start a thread for new connection
mythread = threading.Thread(target=self.subThreadIn, args=(connection, connection.fileno()))
mythread.setDaemon(True)
mythread.start()
else:
connection.send(b'please go out!')
connection.close()
except:
pass
# send whatToSay to every except people in exceptNum
def tellOthers(self, exceptNum, whatToSay):
x = datetime.datetime.now()
for c in self.mylist:
if c.fileno() != exceptNum:
try:
c.send((whatToSay+" ["+str(x.hour)+":"+str(x.minute)+":"+str(x.second)+"]").encode()) #time
except:
pass
def subThreadIn(self, myconnection, connNumber):
while True:
try:
recvedMsg = myconnection.recv(1024).decode()
if recvedMsg.find('Name')!=-1:
str1='let us chat '+recvedMsg.split(' ')[1]
usr=[recvedMsg.split(' ')[1],myconnection.fileno()]
self.usrpool.append(usr)
#print(self.usrpool)
#print(self.usrpool[0][0],self.usrpool[0][1])
self.mylist.append(myconnection)
myconnection.send(str1.encode())
self.tellOthers(connNumber,'系統: '+recvedMsg.split(' ')[1]+' join chat room')
self.tellOthers(connNumber,'系統: --------------------------------聊天數目前人數:'+str(len(self.mylist)))
elif recvedMsg:
for c in self.usrpool:
if c[1] == myconnection.fileno():
usr=c[0]
print(usr+recvedMsg)
self.tellOthers(connNumber, usr+': '+recvedMsg)
else:
pass
except (OSError, ConnectionResetError):
try:
self.mylist.remove(myconnection)
self.tellOthers(connNumber,"系統: "+usr+" exit the chat room") #someone exit the chat room
self.usrpool.remove(myconnection.fileno())
except:
pass
myconnection.close()
return
def main():
s = Server('localhost', 5550)
while True:
s.checkConnection()
if __name__ == "__main__":
main()
<file_sep>/README.md
# myFirstProject
This is my first github project for testing.
<file_sep>/gui_server.py
# -*- encoding: utf-8 -*-
import socket
import threading
import datetime
import wx
import time
from time import gmtime, strftime
class Server:
def __init__(self, host, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock = sock
self.sock.bind((host, port))
self.sock.listen(5)
print('Server', socket.gethostbyname(host), 'listening ...')
self.mylist = list()
self.usrpool= list()
def frame(self):
# 視窗化----------------------------------------------------------------------------------------------
frame_1 = wx.Frame(None,-1,title="Chat room",size=(500,830))
frame_1.Center()# 在螢幕中間
self.panel = wx.Panel(frame_1)
"""self.send_message2 = wx.TextCtrl(self.panel,pos = (115,75),size = (150,100)) # 輸入名字視窗
self.send_message3 = wx.TextCtrl(self.panel,pos = (270,75),size = (140,100),style = wx.TE_PASSWORD) # 輸入密碼視窗
self.send_message4 = wx.TextCtrl(self.panel,pos = (120,175),size = (210,100),style = wx.TE_PASSWORD) # 更改密碼視窗
self.chat_frame = wx.TextCtrl(self.panel,pos = (5,275),size = (485,395),style = wx.TE_READONLY | wx.TE_MULTILINE) #聊天視窗
self.send_message = wx.TextCtrl(self.panel,pos = (5,680),size = (400,100),style=wx.TE_PROCESS_ENTER) # 輸入訊息視窗
self.send_button = wx.Button(self.panel,label = "Send",pos = (410,680),size = (70,100))#送出按鈕
self.send_button2 = wx.Button(self.panel,label = "Login",pos = (410,75),size = (70,100))#登入
self.send_button3 = wx.Button(self.panel,label = "Updata password",pos = (330,175),size = (150,100))#變更密碼
self.name_text = wx.StaticText(self.panel, label='NickName',pos = (5,115)) # NickName文字
self.change_password_text = wx.StaticText(self.panel, label='change password',pos = (5,215)) # change password文字
self.people_text = wx.StaticText(self.panel, label='目前聊天室有',pos = (5,5),size = (485,70),style = wx.ALIGN_CENTER) # 目前聊天室有X人 文字
self.people_text.SetBackgroundColour('green')
self.chat_frame.AppendText('welcome to join us'+'\n') #新增歡迎到聊天室上
self.send_message.Bind(wx.EVT_TEXT_ENTER, self.sendThreadFunc1) #監聽鍵盤
self.send_button.Bind(wx.EVT_BUTTON, self.sendThreadFunc2) #監聽Button
self.send_button2.Bind(wx.EVT_BUTTON, self.sendThreadFunc3) #監聽Button2(輸入名字)"""
frame_1.Show() #顯示frame
def checkConnection(self):
connection, addr = self.sock.accept()
print('Accept a new connection', connection.getsockname(), connection.fileno())
try:
buf = connection.recv(1024).decode()
if buf == '1':
# start a thread for new connection
mythread = threading.Thread(target=self.subThreadIn, args=(connection, connection.fileno()))
mythread.setDaemon(True)
mythread.start()
else:
connection.send(b'please go out!')
connection.close()
except:
pass
# send whatToSay to every except people in exceptNum
def tellOthers(self, exceptNum, whatToSay):
x = datetime.datetime.now()
for c in self.mylist:
if c.fileno() != exceptNum:
try:
c.send((whatToSay+" ["+str(x.hour)+":"+str(x.minute)+":"+str(x.second)+"]"+'\n'+str(len(self.mylist))).encode()) #time
except:
pass
def subThreadIn(self, myconnection, connNumber):
while True:
try:
recvedMsg = myconnection.recv(1024).decode()
if recvedMsg.find('Name')!=-1:
str1='let us chat '+recvedMsg.split(' ')[1]+'\n'
usr=[recvedMsg.split(' ')[1],myconnection.fileno()]
self.usrpool.append(usr)
#print(self.usrpool)
#print(self.usrpool[0][0],self.usrpool[0][1])
self.mylist.append(myconnection)
myconnection.send(str1.encode())
self.tellOthers(connNumber,'系統: '+recvedMsg.split(' ')[1]+' join chat room')
elif recvedMsg:
for c in self.usrpool:
if c[1] == myconnection.fileno():
usr=c[0]
print(usr+recvedMsg)
self.tellOthers(connNumber, usr+': '+recvedMsg)
else:
pass
except (OSError, ConnectionResetError):
try:
self.mylist.remove(myconnection)
self.tellOthers(connNumber,"系統: "+usr+" exit the chat room") #someone exit the chat room
self.usrpool.remove(myconnection.fileno())
except:
pass
myconnection.close()
return
def main():
s = Server('192.168.3.11', 5550)
while True:
s.checkConnection()
if __name__ == "__main__":
app = wx.App()
main()
app.MainLoop()
<file_sep>/gui_client.py
import socket
import threading
import wx
class Client:
def __init__(self, host, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock = sock
self.sock.connect((host, port))
self.sock.send(b'1')
def frame(self):
# 視窗化----------------------------------------------------------------------------------------------
frame_1 = wx.Frame(None,-1,title="Chat room",size=(500,830))
frame_1.Center()# 在螢幕中間
self.panel = wx.Panel(frame_1)
self.send_message2 = wx.TextCtrl(self.panel,pos = (115,75),size = (150,100)) # 輸入名字視窗
self.send_message3 = wx.TextCtrl(self.panel,pos = (270,75),size = (140,100),style = wx.TE_PASSWORD) # 輸入密碼視窗
self.send_message4 = wx.TextCtrl(self.panel,pos = (120,175),size = (210,100),style = wx.TE_PASSWORD) # 更改密碼視窗
self.chat_frame = wx.TextCtrl(self.panel,pos = (5,275),size = (485,395),style = wx.TE_READONLY | wx.TE_MULTILINE) #聊天視窗
self.send_message = wx.TextCtrl(self.panel,pos = (5,680),size = (400,100),style=wx.TE_PROCESS_ENTER) # 輸入訊息視窗
self.send_button = wx.Button(self.panel,label = "Send",pos = (410,680),size = (70,100))#送出按鈕
self.send_button2 = wx.Button(self.panel,label = "Login",pos = (410,75),size = (70,100))#登入
self.send_button3 = wx.Button(self.panel,label = "Updata password",pos = (330,175),size = (150,100))#變更密碼
self.name_text = wx.StaticText(self.panel, label='NickName',pos = (5,115)) # NickName文字
self.change_password_text = wx.StaticText(self.panel, label='change password',pos = (5,215)) # change password文字
self.people_text = wx.StaticText(self.panel, label='目前聊天室有1人',pos = (5,5),size = (485,70),style = wx.ALIGN_CENTER) # 目前聊天室有X人 文字
self.people_text.SetBackgroundColour('green')
self.chat_frame.AppendText('welcome to join us'+'\n') #新增歡迎到聊天室上
self.send_message.Bind(wx.EVT_TEXT_ENTER, self.sendThreadFunc1) #監聽鍵盤
self.send_button.Bind(wx.EVT_BUTTON, self.sendThreadFunc2) #監聽Button
self.send_button2.Bind(wx.EVT_BUTTON, self.sendThreadFunc3) #監聽Button2(輸入名字)
self.send_button3.Bind(wx.EVT_BUTTON, self.sendThreadFunc4) #監聽Button3(更新密碼)
frame_1.Show() #顯示frame
def login(self):
"""self.name=input("Input your nickname:")
self.sock.send(('Name '+self.name).encode())"""
def sendThreadFunc4(self,event): # 監聽button3(更新密碼)
try:
myword = str(self.send_message4.GetLineText(0)).strip()
if myword != "":
self.chat_frame.AppendText('密碼變更成功!\n') #新增到聊天室上
self.send_message4.Clear() # 清空密碼視窗
except ConnectionAbortedError:
print('Server closed this connection!')
except ConnectionResetError:
print('Server is closed!')
def sendThreadFunc3(self,event): #監聽button2 (輸入名字和密碼)
try:
myword = str(self.send_message2.GetLineText(0)).strip()
password = str(self.send_message3.GetLineText(0)).strip()
if myword != "":
self.sock.send(('Name '+myword).encode())
self.send_message2.Disable() # 鎖住輸入名字視窗
self.send_message3.Disable() # 鎖住輸入名字視窗
myobject = event.GetEventObject() # 鎖住button
myobject.Disable() # 鎖住button
except ConnectionAbortedError:
print('Server closed this connection!')
except ConnectionResetError:
print('Server is closed!')
def sendThreadFunc1(self,event): #監聽enter
try:
myword = str(self.send_message.GetLineText(0)).strip()
if myword != "":
self.chat_frame.AppendText(' '+'Me:'+myword+'\n') #新增到聊天室上
self.sock.send(myword.encode())
self.send_message.Clear() #清除輸入內容
except ConnectionAbortedError:
print('Server closed this connection!')
except ConnectionResetError:
print('Server is closed!')
def sendThreadFunc2(self,event): #監聽button
try:
myword = str(self.send_message.GetLineText(0)).strip()
if myword != "":
self.chat_frame.AppendText(' '+'Me:'+myword+'\n')#新增到聊天室上
self.sock.send(myword.encode())
self.send_message.Clear()#清除輸入內容
except ConnectionAbortedError:
print('Server closed this connection!')
except ConnectionResetError:
print('Server is closed!')
def recvThreadFunc(self):
while True:
try:
otherword = self.sock.recv(1024) # socket.recv(recv_size)
num = otherword.decode().find('\n')
self.chat_frame.AppendText(otherword.decode()[0:num+1]) #新增到聊天室上
self.people_text.Label = otherword.decode()[num+2:]
print(otherword)
except ConnectionAbortedError:
print('Server closed this connection!')
except ConnectionResetError:
print('Server is closed!')
def main():
c = Client('192.168.127.12', 5550)#port550
c.login()
th2 = threading.Thread(target=c.recvThreadFunc)
threads = [th2]
c.frame() #顯示視窗
for t in threads:
t.setDaemon(True)
t.start()
if __name__ == "__main__":
app = wx.App()
main()
app.MainLoop()
<file_sep>/ServerFrame.py
import wx
import socket
import threading
import datetime
from pymongo import MongoClient
class Server:
def __init__(self, host, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock = sock
self.sock.bind((host, port))
self.sock.listen(5)
print('Server', socket.gethostbyname(host), 'listening ...')
self.mylist = list()
self.usrpool= list()
def checkConnection(self):
while True:
connection, addr = self.sock.accept()
print('Accept a new connection', connection.getsockname(), connection.fileno())
try:
buf = connection.recv(1024).decode()
if buf == '1':
print("sucessful")
# start a thread for new connection
mythread = threading.Thread(target=self.subThreadIn, args=(connection, connection.fileno()))
mythread.setDaemon(True)
mythread.start()
else:
connection.send(b'please go out!')
connection.close()
except:
pass
# send whatToSay to every except people in exceptNum
def tellOthers(self, exceptNum, whatToSay):
x = datetime.datetime.now()
for c in self.mylist:
if c.fileno() != exceptNum:
try:
c.send((whatToSay+" ["+str(x.hour)+":"+str(x.minute)+":"+str(x.second)+"]"+'\n').encode()) #time
except:
pass
def subThreadIn(self, myconnection, connNumber):
while True:
try:
recvedMsg = myconnection.recv(1024).decode()
if recvedMsg.find('Name')!=-1:
str1='let us chat '+recvedMsg.split(' ')[1]+'\n'
usr=[recvedMsg.split(' ')[1],myconnection.fileno()]
self.usrpool.append(usr)
#print(self.usrpool)
#print(self.usrpool[0][0],self.usrpool[0][1])
self.mylist.append(myconnection)
myconnection.send(str1.encode())
self.tellOthers(connNumber,'系統: '+recvedMsg.split(' ')[1]+' join chat room')
self.tellOthers(connNumber,'系統: --------------------------------聊天數目前人數:'+str(len(self.mylist)))
elif recvedMsg:
for c in self.usrpool:
if c[1] == myconnection.fileno():
usr=c[0]
print(usr+recvedMsg)
self.tellOthers(connNumber, usr+': '+recvedMsg)
else:
pass
except (OSError, ConnectionResetError):
try:
self.mylist.remove(myconnection)
self.tellOthers(connNumber,"系統: "+usr+" exit the chat room") #someone exit the chat room
self.usrpool.remove(myconnection.fileno())
except:
pass
myconnection.close()
return
class DataBaseChatRoom:
def __init__(self):
self.client = MongoClient('localhost', 27017) # 比较常用
self.database = self.client["ChatRoom"] # SQL: Database Name
self.collection = self.database["user"] # SQL: Table Name
def loadData(self):
self.usrList=[]
for ii in self.collection.find():
self.usrList.append(ii['uname'])
return self.usrList
# delete user by uname
# dbChatRoom.deleteUser(['A'])
def deleteUser(self, uname=None):
self.collection.remove({'uname':uname})
return 'successful'
# insert user
# dbChatRoom.insertUser(uname='A', upwd='A')
def insertUser(self, uname=None, upwd=None):
user={
'uname':uname,
'upwd':upwd
}
self.collection.insert(user)
return 'successful'
def updataUser(self, uname=None,upwd=None):
temp = self.collection.find_one({'uname' : uname})
temp['upwd'] = upwd
self.collection.save(temp)
pass
return 'successful'
# check checkUserExist
def checkUserExist(self, uname='A'):
pass
return False
# query user bu uname
# dbChatRoom.queryByuname(uname='A', upwd='A')
def queryByuname(self, uname='A', upwd='A'):
pass
return False
# Init database
# dbChatRoom.Initdatabase()
def Initdatabase(self):
userList = []
userList.append({'uname': 'A', 'upwd': 'A'})
userList.append({'uname': 'B', 'upwd': 'B'})
userList.append({'uname': 'C', 'upwd': 'C'})
userList.append({'uname': 'D', 'upwd': 'D'})
userList.append({'uname': 'E', 'upwd': 'E'})
self.collection.insert_many(userList)
def colseClient(self):
self.client.close()
class frame:
def __init__(self,dbChatroom):
self.ui = wx.Frame(None,-1,title="Chat room",size=(500,650))
self.ui.Center()# 在螢幕中間
self.db=dbChatroom
self.panel = wx.Panel(self.ui)
self.name_text = wx.StaticText(self.panel, label='NickName',pos = (10,10),size=(80,20)) # NickName文字
self.password_text = wx.StaticText(self.panel,label='PassWord',pos =(235,10),size=(80,20))#PassWord文字
self.input_name = wx.TextCtrl(self.panel,pos = (90,10),size = (140,20)) # 輸入名字視窗
self.input_password=wx.TextCtrl(self.panel,pos = (310,10),size = (140,20),style=wx.TE_PASSWORD)#輸入密碼視窗
self.add_Button = wx.Button(self.panel,label = "add",pos = (15,45),size = (450,40))#登入
self.Data=self.db.loadData()#data from db
self.checkboxlist = wx.CheckListBox(self.panel,wx.ID_ANY,(15,95),(200,400),self.Data)#checkboxlist框
self.delete_Button = wx.Button(self.panel,label = "delete",pos = (15,510),size = (98,40))#刪除
self.update_Button = wx.Button(self.panel,label = "update",pos = (115,510),size = (98,40))#更新
self.add_Button.Bind(wx.EVT_BUTTON, self.addUsr) #監聽AddButton
self.delete_Button.Bind(wx.EVT_BUTTON,self.deleteUsr)#監聽DeleteButton
self.update_Button.Bind(wx.EVT_BUTTON,self.updateUsr)#監聽updateButton
#ui.Show() #顯示frame
def show(self):
self.ui.Show()
def updateUsr(self,event):
checked = self.checkboxlist.GetCheckedItems()
print(len(checked))
if len(checked)==1:
myname=self.checkboxlist.GetString(checked[0])
dlg=wx.TextEntryDialog(self.panel, "請輸入"+myname+"的新密碼",'更改密碼',style=wx.TE_PASSWORD|wx.ID_OK)#跳出消息框
if dlg.ShowModal() == wx.ID_OK:
response = dlg.GetValue()
self.db.updataUser(myname,response)
else:
wx.MessageBox("請擇一選取", "Message" ,wx.OK)
def reload(self):
self.Data=self.db.loadData()
for i in range(len(self.Data)):
self.checkboxlist.Append(self.Data[i])
def addUsr(self,event):
myname = str(self.input_name.GetLineText(0)).strip()
mypassword = str(self.input_password.GetLineText(0)).strip()
if myname != "" and mypassword!="":
self.input_name.Clear()#清除輸入內容
self.input_password.Clear()
self.Data.append(myname)
dlg = wx.TextEntryDialog(None, "請再次輸入"+myname+"密碼",'密碼確認',style=wx.TE_PASSWORD|wx.ID_OK)#跳出消息框
if dlg.ShowModal() == wx.ID_OK:
response = dlg.GetValue()
if response==mypassword:
self.db.insertUser(myname,mypassword)#加入新使用者到db
self.checkboxlist.Append(myname)#加入新使用者到checkbox
def deleteUsr(self,event):
checked = self.checkboxlist.GetCheckedItems()
print(len(checked))
if(len(checked)!=0):
for i in range(len(checked)):
self.db.deleteUser(self.checkboxlist.GetString(checked[i]))
self.checkboxlist.Clear()
self.reload()
def main():
s = Server('localhost', 5550)
dbChatRoom = DataBaseChatRoom()
f=frame(dbChatRoom)
th1=threading.Thread(target=s.checkConnection)
th2=threading.Thread(target=f.show)
threads=[th1,th2]
for t in threads:
t.setDaemon(True)
t.start()
dbChatRoom.colseClient()
if __name__ == "__main__":
app = wx.App()
main()
app.MainLoop()
| 4641b129f0ac0be947a791d4da9cd75b65507ce8 | [
"Markdown",
"Python"
] | 5 | Python | jessetsaoj/myFirstProject | e09edb0ce6d566c5d7928f204d4484742f53a8df | e32ad4663e0eb3dcd2aee33a1f11ab3b0d53605e |
refs/heads/master | <file_sep>##Variable information
These signals were used to estimate variables of the feature vector for each pattern:
'-XYZ' is used to denote 3-axial signals in the X, Y and Z directions.
In the summary we've included the average mean and average standard devation for each user-activity pair.
tBodyAcc-XYZ
tGravityAcc-XYZ
tBodyAccJerk-XYZ
tBodyGyro-XYZ
tBodyGyroJerk-XYZ
tBodyAccMag
tGravityAccMag
tBodyAccJerkMag
tBodyGyroMag
tBodyGyroJerkMag
fBodyAcc-XYZ
fBodyAccJerk-XYZ
fBodyGyro-XYZ
fBodyAccMag
fBodyAccJerkMag
fBodyGyroMag
fBodyGyroJerkMag
<file_sep>#Project Description
This project is looking at accelerometer data from the Samsung Galaxy S smartphone from this site:
http://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones
I've extracted all of the mean and standard deviaiton variables in all data sets provided, then summarised them into a grouped table.
This is all performed using run_analysis.R, where each step is commented in the script in this repository. A codebook describing the variables is provided.
<file_sep>#Load libraries
library(dplyr)
#Create data folder
if (!dir.exists("./data")) {
dir.create("./data")
}
#Download and extract files from zip
zipurl <- "https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip"
download.file(zipurl, "./data/Dataset.zip")
unzip("./data/Dataset.zip", exdir = "./data")
datadir <- "./data/UCI HAR Dataset"
#Import Features vec and remove the numbers to get our col names
features <- read.table("./data/UCI HAR Dataset/features.txt")
features <- features[ ,2]
#Find features that are either mean or standard deviation, then tidying up the names
selectionvec <- grep("(mean|std)\\(\\)", features)
selectedfeatures <- features[selectionvec]
selectedfeatures <- gsub("-", "_", selectedfeatures)
selectedfeatures <- gsub("\\(\\)", "", selectedfeatures)
#
#Import all our data into a table then set the column names
#
#Training data
X_train <- read.table("./data/UCI HAR Dataset/train/X_train.txt", header=FALSE)
X_train <- X_train[ ,selectionvec]
colnames(X_train) <- selectedfeatures
activity_labels1 <- read.table("./data/UCI HAR Dataset/train/y_train.txt")
X_train <- mutate(X_train, activity_label = case_when(activity_labels1 == 1 ~ "walking",
activity_labels1 == 2 ~ "walking_upstairs",
activity_labels1 == 3 ~ "walking_downstairs",
activity_labels1 == 4 ~ "sitting",
activity_labels1 == 5 ~ "standing",
activity_labels1 == 6 ~ "laying"))
#Testing data
X_test <- read.table("./data/UCI HAR Dataset/test/X_test.txt", header=FALSE)
X_test <- X_test[ ,selectionvec]
colnames(X_test) <- selectedfeatures
activity_labels2 <- read.table("./data/UCI HAR Dataset/test/y_test.txt")
X_test <- mutate(X_test, activity_label = case_when(activity_labels2 == 1 ~ "walking",
activity_labels2 == 2 ~ "walking_upstairs",
activity_labels2 == 3 ~ "walking_downstairs",
activity_labels2 == 4 ~ "sitting",
activity_labels2 == 5 ~ "standing",
activity_labels2 == 6 ~ "laying"))
trainandtest <- bind_rows(X_train, X_test)
#Get all subjects in correct order
subjects1 <- read.table("./data/UCI HAR Dataset/train/subject_train.txt")
subjects2 <- read.table("./data/UCI HAR Dataset/test/subject_test.txt")
subjects <- bind_rows(subjects1, subjects2)
#Add subjects column to trainandtest
trainandtest <- mutate(trainandtest, subject = subjects$V1)
trainandtest <- as_tibble(trainandtest)
#Group and then summarise the mean for each variable, then export our data
tidydata <- trainandtest %>% group_by(activity_label, subject)
tidysummary <- summarise_all(tidydata, mean, na.rm = TRUE)
write.csv(tidysummary, "./data/tidysummary.csv", row.names = FALSE)
| ba4c1d7f4c7005f45f66dfb38ab7fcef9f181506 | [
"Markdown",
"R"
] | 3 | Markdown | Dylanb1299/GettingAndCleaningData | 7a4cbfaf72212e7b9d6299e66c7b3c5f103603e0 | f3bf126c49f7edff0fb264570cf3ffc1f5577b84 |
refs/heads/main | <repo_name>MSajedian/Todo-App-with-Hooks<file_sep>/src/store/index.js
import { createStore } from 'redux'
import rootReducer from './reducers'
import { initialState } from './reducers'
export default createStore(
rootReducer,
initialState,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
<file_sep>/src/components/List.jsx
import React from "react";
import { toggleCompleted, reset } from "../store/actions";
import { Button } from "react-bootstrap";
import { useSelector, useDispatch } from "react-redux";
// const mapDispatchToProps = (dispatch) => ({
// toggleCompleted: (id) => dispatch(toggleCompleted(id)),
// reset: () => dispatch(reset())
// });
// class List extends Component {
// render() {}
const List = () => {
const list = useSelector((state) => state.list)
const dispatch = useDispatch()
return (
<>
<ul>
{list.map((todo) => (
<li
key={todo.id}
onClick={() => dispatch(toggleCompleted(todo))}
className={todo.completed ? "strikethrough" : ""}
>
{todo.description}
</li>
))}
</ul>
<Button onClick={() => dispatch(reset())}>reset</Button>
</>
);
}
export default (List);
// export default connect((s) => s, mapDispatchToProps)(List);
| 06c6768e19e993e5860cd1eaa06d9349118e4d76 | [
"JavaScript"
] | 2 | JavaScript | MSajedian/Todo-App-with-Hooks | ebd54e25256eeaf5cb4d88eae375ba639015481b | 99b9dfc38c85ca716257a85afe736b02577708bf |
refs/heads/master | <repo_name>rgranger/dota-windstrom<file_sep>/src/send-email.js
export function sendEmail(data = {}) {
return fetch(`https://${window.location.host}/api/send-email`, {
method: 'POST',
mode: 'cors',
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
})
}
<file_sep>/src/App.js
import React, { useState, useCallback } from 'react'
import Form from 'react-bootstrap/Form'
import FormGroup from 'react-bootstrap/FormGroup'
import FormLabel from 'react-bootstrap/FormLabel'
import Button from 'react-bootstrap/Button'
import Jumbotron from 'react-bootstrap/Jumbotron'
import Container from 'react-bootstrap/Container'
import './App.css'
import { sendEmail } from './send-email'
const STATUS = {
PENDING: 'PENDING',
SUCCESS: 'SUCCESS',
ERROR: 'ERROR',
}
function App () {
const [type, setType] = useState('')
const [gameID, setGameID] = useState('')
const [division, setDivision] = useState('')
const [team, setTeam] = useState('')
const [playerName, setPlayerName] = useState('')
const [heroes, setHeroes] = useState('')
const [minReplay, setMinReplay] = useState('')
const [description, setDescription] = useState('')
const [status, setStatus] = useState('')
const handleTypeChange = useCallback((e) => setType(e.currentTarget.value), [])
const handleGameIDChange = useCallback((e) => setGameID(e.currentTarget.value), [])
const handleDivisionChange = useCallback((e) => setDivision(e.currentTarget.value), [])
const handleTeamChange = useCallback((e) => setTeam(e.currentTarget.value), [])
const handlePlayerNameChange = useCallback((e) => setPlayerName(e.currentTarget.value), [])
const handleHeroesChange = useCallback((e) => setHeroes(e.currentTarget.value), [])
const handleMinReplayChange = useCallback((e) => setMinReplay(e.currentTarget.value), [])
const handleDescriptionChange = useCallback((e) => setDescription(e.currentTarget.value), [])
const handleSubmit = useCallback((e) => {
e.preventDefault()
setStatus(STATUS.PENDING)
sendEmail({ type, gameID, division, team, playerName, heroes, minReplay, description })
.then((response) => {
if (response.status === 200) {
setType('')
setGameID('')
setDivision('')
setTeam('')
setDescription('')
setHeroes('')
setPlayerName('')
setMinReplay('')
setStatus(STATUS.SUCCESS)
} else {
setStatus(STATUS.ERROR)
}
})
.catch((err) => setStatus(STATUS.ERROR))
}, [type, gameID, division, team, playerName, heroes, minReplay, description])
const renderStatus = useCallback(() => {
if (!status) return null
if (status === STATUS.PENDING) return <div className="lds-hourglass" />
if (status === STATUS.ERROR) return <div className="alert alert-danger" role="alert">We were unable to send your data ! 😞</div>
if (status === STATUS.SUCCESS) return <div className="alert alert-success" role="alert">Data uploaded with success ! 🎉</div>
}, [status])
return (
<Container className="App-container align-items-center justify-content-center">
<Jumbotron className="">
<h1 className='display-4'>Submit your Clip</h1>
<Form onSubmit={handleSubmit}>
<FormGroup>
<FormLabel htmlFor="type">Type</FormLabel>
<input className='form-control' type="text" required id="type" name="type" value={type} onChange={handleTypeChange} placeholder="Rampage / Fail / Save / Juke / Dodge..." autoFocus />
</FormGroup>
<FormGroup>
<FormLabel htmlFor="gameID">Game ID</FormLabel>
<input className='form-control' type="text" required id="gameID" name="Game ID" value={gameID} onChange={handleGameIDChange} placeholder="123456789 (obligatoire)" />
</FormGroup>
<FormGroup>
<FormLabel htmlFor="division">Division</FormLabel>
<input className='form-control' type="text" required id="division" name="Division" value={division} onChange={handleDivisionChange} placeholder="d1" />
</FormGroup>
<FormGroup>
<FormLabel htmlFor="team">Teams</FormLabel>
<input className='form-control' type="text" required id="team" name="Team" value={team} onChange={handleTeamChange} placeholder="The Feeders vs The Masters" />
</FormGroup>
<FormGroup>
<FormLabel htmlFor="playerName">Player Name</FormLabel>
<input className='form-control' type="text" required id="playerName" name="Player Name" value={playerName} onChange={handlePlayerNameChange} placeholder="WindStorm" />
</FormGroup>
<FormGroup>
<FormLabel htmlFor="heroes">Heroes</FormLabel>
<input className='form-control' type="text" id="heroes" name="heroes" required value={heroes} onChange={handleHeroesChange} placeholder="Earth Spirit" />
</FormGroup>
<FormGroup>
<FormLabel htmlFor="min replay">Min Replay</FormLabel>
<input className='form-control' type="text" id="min replay" name="min replay" required value={minReplay} onChange={handleMinReplayChange} placeholder="12" />
</FormGroup>
<FormGroup>
<FormLabel htmlFor="description">Description</FormLabel>
<textarea className='form-control' id="description" name="description" required value={description} onChange={handleDescriptionChange} placeholder="Die like a noob (soyez le plus précis possible)" />
</FormGroup>
<FormGroup className="text-center">
<Button type="submit" className='form-control mb-3' disabled={status === STATUS.PENDING}>Submit</Button>
{renderStatus()}
</FormGroup>
</Form>
</Jumbotron>
</Container>
)
}
export default App
<file_sep>/server.js
require('dotenv').config()
const http = require('http')
const polka = require('polka')
const { join } = require('path')
const serveStatic = require('serve-static')
const { json } = require('body-parser')
const nodemailer = require('nodemailer')
const { PORT = 80, MAIL_USERNAME, MAIL_PASSWORD } = process.env
const buildDir = join(__dirname, 'build')
const serve = serveStatic(buildDir)
const transporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: MAIL_USERNAME,
pass: MAIL_PASSWORD,
}
})
polka()
.use(serve)
.use(json())
.post('/api/send-email', async (req, res) => {
try {
const { type, gameID, division, team, playerName, heroes, minReplay, description } = req.body
const info = await transporter.sendMail({
from: '<NAME>',
to: '<EMAIL>',
subject: `Dota Wadafaaaak - ${type}`,
text: getEmailText(type, gameID, division, team, playerName, heroes, minReplay, description),
html: getEmailText(type, gameID, division, team, playerName, heroes, minReplay, description, true),
})
res.writeHead(200);
res.end()
} catch (err) {
res.writeHead(500)
res.end(err.message)
}
})
.listen(PORT, (err) => {
if (err) throw err
console.log(`> Running on localhost:${PORT}`)
})
function getEmailText(type, gameID, division, team, playerName, heroes, minReplay, description, isHtml = false) {
if (isHtml) {
return `<h3>Type</h3>
${type}
<h3>gameID</h3>
${gameID}
<h3>Division</h3>
${division}
<h3>Team</h3>
${team}
<h3>Player Name</h3>
${playerName}
<h3>Heroes</h3>
${heroes}
<h3>Min Replay</h3>
${minReplay}
<h3>Description</h3>
${description}
`
} else {
return `# Type
${type}
# gameID
${gameID}
# Division
${division}
# Team
${team}
# Player Name
${playerName}
# Heroes
${heroes}
# Min Replay
${minReplay}
# Description
${description}
`
}
}
// setInterval(() => {
// Prevents heroku from "sleeping"
// http.get('http://dota-windstrom.herokuapp.com/')
// }, 300000) // Every 5 minutes
| 3d0c2a1f3e7a01adaf6f376bced0360dfb6dd9d4 | [
"JavaScript"
] | 3 | JavaScript | rgranger/dota-windstrom | adba3546e4364c479beeccf1b0b6ffd1a6675ec2 | 9c674ab4c5913a68ab9f483bb9e23b3e4a6b084c |
refs/heads/master | <file_sep>import os
import unittest
import ccodegen as cg
class TestCodeGen(unittest.TestCase):
def test_ifndef(self):
tmp = cg.Ifndef('__TEST_H__')
self.assertEqual(str(tmp), '#ifndef __TEST_H__\n')
def test_endif(self):
self.assertEqual(str(cg.Endif()), '#endif')
def test_cfile(self):
cfile = cg.CFile('test.c')
cfile.add_include('stdio.h')
cfile.add_include('stdlib.h')
cfile.generate()
if __name__ == '__main__':
unittest.main()
<file_sep>import sys
import ccodegen as cg
def check_version():
try:
assert sys.version_info >= (3, 5)
except AssertionError:
print('Python version is too low: ', sys.version_info, file=sys.stderr)
print('Minimum required version: 3.5', file=sys.stderr)
sys.exit(-1)
if __name__ == '__main__':
check_version()
cfile = cg.CFile('test.c')
cfile.add_include(cg.Include('stdio.h', True))
c_code = cfile.code
main_func = cg.Function('main', 'int')
main_func.block = cg.Block()
main_func.block.append(cg.Statement(cg.Variable('int', 'a')))
main_func.block.append(cg.Statement('a = 10'))
main_func.block.append(cg.FuncCall('printf', [repr("a is %d\n"), 'a']))
c_code.append(main_func)
cfile.generate()
<file_sep>"""
Description for Package
"""
from ccodegen.ccodegen import *
__all__ = ['ccodegen']
__version__ = '0.1.0'
<file_sep># ccodegen
### How to install
```bash
pip install ccodegen
```
### Example
This is a ccodegen package.
#### Code
```python
import ccodegen as cg
cfile = cg.CFile('test.c')
cfile.add_include(cg.Include('stdio.h', True))
c_code = cfile.code
main_func = cg.Function('main', 'int')
main_func.block = cg.Block()
main_func.block.append(cg.Statement(cg.Variable('int', 'a')))
main_func.block.append(cg.Statement('a = 10'))
main_func.block.append(cg.FuncCall('printf', [repr("a is %d\n"), 'a']))
c_code.append(main_func)
cfile.generate()
```
#### Result : test.c
```c
#include <stdio.h>
int main()
{
int a;
a = 10;
printf('a is %d/\n', a);
}
```
<file_sep>import setuptools
setuptools.setup(
name='ccodegen',
version='0.1',
description="C code generator",
author="<NAME>",
author_email="<EMAIL>",
license="MIT",
url="https://github.com/linuxias/C_CodeGen",
packages=setuptools.find_packages(),
keywords=["C", "Generator"],
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
],
)
<file_sep>import os
import re
class Code():
def __init__(self):
self.elements = []
def __str__(self):
result = []
for e in self.elements:
if e is None:
result.append('')
else:
result.append(str(e))
if not isinstance(e, Blank):
result.append('\n')
return ''.join(result)
def __len__(self):
return len(self.elements)
def append(self, element):
self.elements.append(element)
return self
def extend(self, element):
self.elements.extend(element)
def lines(self):
lines = []
for e in self.elements:
if hasattr(e, 'lines') and callable(e.lines):
lines.extend(e.lines())
else:
lines.extend(str(e).split('\n'))
return lines
class _File(object):
def __init__(self, path):
self.path = path
self.code = Code()
def generate(self):
with open(self.path, 'w') as f:
f.write(str(self))
class CFile(_File):
def __init__(self, path):
super().__init__(path)
self.include = []
self.extern = []
def add_include(self, include):
self.include.append(include)
def add_extern(self, extern):
self.extern.append(extern)
def __str__(self):
_str = ''
for _include in self.include:
_str += '#include <' + _include.__str__() + '>\n'
_str += '\n'
for _extern in self.extern:
_str += 'extern ' + _extern.__str__() + '\n'
_str += '\n'
_str += str(self.code)
_str += '\n'
return _str
def lines(self):
return self.code.lines()
class HFile(_File):
def __init__(self, path):
super().__init__(path)
_basename = os.path.basename(self.path)
_splitname = os.path.splitext(_basename)[0]
_guard = re.findall('[A-Z][^A-Z]*', _splitname)
self.guard = '__' + '_'.join(_guard).upper() + '_H__'
def __str__(self):
_str = ''
_str += str(Ifndef(self.guard))
_str += str(Define(self.guard))
_str += str(self.code)
_str += str(Endif())
return _str
def set_guard(self, guard):
self.guard = guard
class Block():
def __init__(self):
self.code = Code()
self.tail = ''
def __str__(self):
_str = '{\n'
_lines = []
for e in self.code.elements:
_lines.append(str(e))
_str += '\n'.join(_lines) + '\n'
_str += '}' + '%s' % (self.tail)
return _str
def append(self, element):
self.code.append(element)
def extend(self, code):
self.code.extend(code)
def lines(self):
lines = []
lines.append('{')
for e in self.code.elements:
lines.append(str(e))
lines.append('}%s' % self.tail)
return lines
class Ifndef():
def __init__(self, text):
self.text = "#ifndef " + text + '\n'
def __str__(self):
return self.text
class Endif():
def __str__(self):
return "#endif"
class Define():
def __init__(self, text):
self.text = "#define " + text + '\n'
def __str__(self):
return str(self.text)
class Blank():
def __init__(self, lines=1):
self.lines = lines
def __str__(self):
return '\n' * self.lines
def lines(self):
return ['' for x in range(self.lines)]
class Variable():
def __init__(self, type, name, initialization=None):
self.type = type
self.name = name
self.initialization = initialization
def __str__(self):
if self.initialization is None:
return str(self.type + ' ' + self.name)
else:
return str(self.type + ' ' + self.name) + '=' + str(self.initialization)
def setprefix(self, prefix):
self.type = str(prefix) + ' ' +self.type
class Array(Variable):
def __init__(self, type, name, *args):
super().__init__(type, name)
self.index = 0
self.data = []
for a in args:
self.data.append(str(a))
def __str__(self):
return super().__str__() + '[' + str(len(self.data)) + '] = {' + ','.join(self.data) + '}'
def add(self, value):
self.data.append(str(value))
class Pointer(Variable):
def __init__(self, type, name, initialization=None):
super().__init__(type, name, initialization)
def __str__(self):
_str = super().__str__().split()
_str.insert(1, '* ')
return str(''.join(_str))
class Typedef:
def __init__(self, base, definition):
self.base = base
self.definition = definition
def __str__(self):
return 'typedef %s %s' % (str(self.base), str(self.definition))
class Struct:
def __init__(self, name, block=None):
self.block = block if block is not None else Block()
self.name = name
self._typedef = False
def __str__(self):
_str = ''
_suffix = ''
if self._typedef is True:
_str += 'typedef struct {\n'
_suffix = self.name
else:
_str += 'struct %s {\n' % (self.name)
_str += ';\n'.join(self.block.code.lines())
_str += ';\n} %s' % (_suffix)
return _str
@property
def typedef(self):
return self._typedef
@typedef.setter
def typedef(self, set: bool):
self._typedef = set
def append(self, value):
if isinstance(value, list):
self.append_list(value)
else:
self.block.append('%s' % value)
def append_list(self, value_list):
for value in value_list:
self.append(value)
class Union:
def __init__(self, name, block=None):
self._block = block if block is not None else Block()
self._name = name
self._typedef = False
def __str__(self):
_str = ''
_suffix = ''
if self._typedef is True:
_str += 'typedef union {\n'
_suffix = self.name
else:
_str += 'union %s {\n' % (self.name)
_str += ';\n'.join(self.block.code.lines())
_str += ';\n} %s' % (_suffix)
return _str
@property
def typedef(self):
return self._typedef
@typedef.setter
def typedef(self, set: bool):
self._typedef = set
def append(self, value):
self.block.append(value)
def append(self, type, name):
self.block.append(str(type) + ' ' + str(name))
class Enum:
def __init__(self, name, block=None):
self.block = block if block is not None else Block()
self.name = name
self._typedef = False
def __str__(self):
_str = ''
_suffix = ''
if self._typedef is True:
_str += 'typedef enum {\n'
_suffix = self.name
else :
_str += 'enum %s {\n' % (self.name)
_str += ',\n'.join(self.block.code.lines())
_str += '\n} %s' % (_suffix)
return _str
@property
def typedef(self):
return self._typedef
@typedef.setter
def typedef(self, set: bool):
self._typedef = set
def append(self, value):
self.block.append(str(value))
def append_with_init(self, value, init):
self.append('%s = %s' % (value, init))
class Statement:
def __init__(self, state):
self.state = state
def __str__(self):
return str(self.state) + ';'
class Include:
def __init__(self, header, system=False):
self.header = header
self.system = system
def __str__(self):
if self.system == True:
return '#include <%s>' % self.header
else:
return '#include "%s"' % self.header
class Extern:
def __init__(self, extern):
self.extern = extern
def __str__(self):
return 'extern ' + str(self.extern) +';'
class ForIter:
def __init__(self, init='', expression='', increment='', block=None):
self.iter = 'for(%s;%s;%s)' % (init, expression, increment)
self.block = block if block is not None else Block()
def __str__(self):
_str = ''
_str += self.iter
_str += str(self.block)
return _str
def addline(self, line):
self.block.append(line)
def setblock(self, block):
self.block = block
def lines(self):
lines = []
lines.append(self.iter)
lines.append(self.block.lines())
return lines
class _IfElse():
def __init__(self, condition, block):
self.condition = condition
self.block = block
class IfStatement:
def __init__(self, condition, block):
self.else_statement = None
_if = _IfElse(condition, block)
self.statements = []
self.statements.append(_if)
def __str__(self):
_str = ''
if_state = self.statements[0]
_str += 'if (%s) ' % if_state.condition
_str += str(if_state.block) + '\n'
for elif_state in self.statements[1:]:
_str += 'else if (%s) ' % elif_state.condition
_str += str(elif_state.block) + '\n'
if self.else_statement is not None:
_str += 'else ' + str(self.else_statement)
return _str
def append_elif(self, condition, block):
_if = _IfElse(condition, block)
self.statements.append(_if)
def set_else(self, block):
self.else_statement = block
def lines(self):
lines = []
lines.append('')
class Function:
def __init__(self, name, ret_type, parameters=None, block=None):
self._name = name
self._ret_type = ret_type
self._parameters = [] if parameters is None else list(parameters)
self._block = block if block is not None else Block()
self._static = False
def __str__(self):
_str = ''
_str += 'static ' if self.static is True else ''
_str += '%s %s(%s) \n' % (self._ret_type, self._name, ', '.join(self._parameters))
_str += str(self._block)
_str += '\n'
return _str
@property
def static(self):
return self._static
@static.setter
def static(self, value:bool):
if isinstance(value, bool) is False:
raise ValueError('static property expect bool type')
self._static = value
def add_parameter(self, parameters):
self._parameters.extend(parameters)
@property
def block(self):
return self._block
@block.setter
def block(self, block):
if isinstance(block, Block) is False:
raise ValueError('block property expect Block object')
self._block = block
def addline(self, line):
self._block.append(line)
class FuncCall():
def __init__(self, name, args=None):
self._name = name
self._args = [] if args is None else list(args)
def __str__(self):
_str = '%s(%s);' % (self._name, ', '.join(str(x) for x in self._args))
return _str
def add_arg(self, arg):
self._args.append(arg)
class Switch():
def __init__(self, arg, block = None):
self._arg = arg
self._block = block if block is not None else Block()
self._case = []
def __str__(self):
_str = ''
_str += 'switch(%s)\n'% self._arg + '{'
for _case in self._case:
_str += _case.__str__()
_str += '}'
return _str
def add_case(self, case):
self._case.append(case)
@property
def block(self):
return self._block
@block.setter
def block(self, block):
if isinstance(block, Block) is False:
raise ValueError('block property expect Block object')
self._block = block
def addline(self, line):
self._block.append(line)
class Case():
def __init__(self, arg, code=None):
self._arg = arg
self._code = code if code is not None else Code()
def __str__(self):
_str = ''
_str += 'case %s:\n'% self._arg
_str += str(self._code)
_str += 'break;\n\n'
return _str
@property
def block(self):
return self._block
def addline(self, line):
self._code.append(line)
| 0c99977963cabca1de7c2382e6333c7b10f4f3d6 | [
"Markdown",
"Python"
] | 6 | Python | linuxias/ccodegen | 2704dfbe3fd297cb5add0d22a8d4399e614e6b95 | a574fe52a0e0b513740378d153a144eb967365c6 |
refs/heads/master | <repo_name>snakecy/R-Projects<file_sep>/ipindata/api/wr_predict_test.R
library(methods)
library(curl,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
library(foreach,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
library(Matrix,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
library(FeatureHashing,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
library(glmnet,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
library(dplyr,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
library(lubridate,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
library(jsonlite,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
Args <- commandArgs(TRUE)
request <- Args[1]
# wr_predict <- function(request){
json_req <- fromJSON(request)
json_par <- fromJSON(json_req$json)
# data.frame elements in json_req
days <- day(json_req$create_datetime)%%7
hours <- hour(json_req$create_datetime)
exchange_id <- json_req$exchange_id
# data.frame elements in json_par
app_id <- if(is.null(json_par$app$id)){'0'}else{json_par$app$id}
publiser_id <- if(is.null(json_par$app$publisher$id)){'null'}else{json_par$app$publisher$id}
bidfloor <- if(is.null(json_par$imp$bidfloor)){'0'}else{json_par$imp$bidfloor}
w <- if(is.null(json_par$imp$banner$w)){'0'}else{json_par$imp$banner$w}
h <- if(is.null(json_par$imp$banner$h)){'0'}else{json_par$imp$banner$h}
os <- if(tolower(json_par$device$os) == "android"){'1'}else if(tolower(json_par$device$os) == "ios"){'2'} else{'0'}
os_ver <- if(is.null(json_par$device$osv)){'0'}else{json_par$device$osv}
model <- if(is.null(json_par$device$model)){'null'}else{json_par$device$model}
connectiontype <- if(is.null(json_par$device$connectiontype)){'0'}else(json_par$device$connectiontype)
country <- json_par$device$geo$country
carrier <- if(is.null(json_par$device$geo$carrier)){'null'}else{json_par$device$geo$carrier}
js <- if(is.null(json_par$device$js)){'0'}else{json_par$device$js}
user <- if(is.null(json_par$user)){'0'}else{'1'}
carriername <- if(is.null(json_par$ext$carriername)){'-'}else{json_par$ext$carriername}
app_cat <- paste(if(is.null(json_par$app$cat)){'null'}else{json_par$app$cat},collapse=",")
btype <- paste(if(is.null(json_par$imp$banner$btype)){'null'}else{json_par$imp$banner$btype},collapse = ",")
mimes <- paste(if(is.null(json_par$imp$banner$mimes)){'null'}else{json_par$imp$banner$mimes[[1]]},collapse = ",")
badv <- paste(if(is.null(json_par$badv)){'null'}else{json_par$badv},collapse = ",")
bcat <- paste(if(is.null(json_par$bcat)){'null'}else{json_par$bcat},collapse = ",")
operators <- c('windows', 'ios', 'mac', 'android', 'linux')
browsers <- c('chrome', 'sogou', 'maxthon', 'safari', 'firefox', 'theworld', 'opera', 'ie')
operation <- 'other'
browser <- 'other'
regularForm <- if(!is.null(json_par$device$ua)){
for(i in 1:length(operators)){
if(grepl(operators[i],json_par$device$ua)){
operation <- operators[i]
break
}
}
for (i in 1:length(browsers)){
if(grepl(browsers[i],json_par$device$ua)){
browser <- browsers[i]
break
}
}
paste(operation,browser,sep="_")
}else{
'null'
}
bidimp <- data.frame(days=days,hours=hours,exchange_id=exchange_id,app_id=app_id,publiser_id=publiser_id,bidfloor=bidfloor,w=w,h=h,os=os,Osv=os_ver,model=model,connectiontype=connectiontype,country=country,ua=regularForm,carrier=carrier,js=js,user=user,carriername=carriername,app_cat=app_cat,btype=btype,mimes=mimes,badv=badv,bcat=bcat)
f <- ~ days + hours + exchange_id + app_id + publiser_id + bidfloor + w + h + os + Osv + model + connectiontype + country + ua + carrier + js + user + carriername + split(app_cat,delim =",") + split(btype,delim =",") +
split(mimes,delim =",") + split(badv,delim =",") +
split(bcat,delim =",")
m.test <- hashed.model.matrix(f, bidimp, 2^20)
# cv.g.lr <- readRDS("wr_model_26.Rds")
load("wr.rda")
p.lr <- predict(cv.g.lr, m.test, s="lambda.min", type = "response")
sprintf("Win rate is : %s", p.lr)
# }
<file_sep>/onlineapi/R/wp_predict_api.R
#' Prepare the data of the experiments
wp_predict_api <- function(request){
json_req <- fromJSON(request)
json_par <- fromJSON(json_req$json)
# data.frame elements in json_req
days <- day(json_req$create_datetime)%%7
hours <- hour(json_req$create_datetime)
exchange_id <- json_req$exchange_id
# data.frame elements in json_par
app_id <- if(is.null(json_par$app$id)){'0'}else{json_par$app$id}
publiser_id <- if(is.null(json_par$app$publisher$id)){'null'}else{json_par$app$publisher$id}
bidfloor <- if(is.null(json_par$imp$bidfloor)){'0'}else{json_par$imp$bidfloor}
w <- if(is.null(json_par$imp$banner$w)){'0'}else{json_par$imp$banner$w}
h <- if(is.null(json_par$imp$banner$h)){'0'}else{json_par$imp$banner$h}
os <- if(tolower(json_par$device$os) == "android"){'1'}else if(tolower(json_par$device$os) == "ios"){'2'} else{'0'}
os_ver <- if(is.null(json_par$device$osv)){'0'}else{json_par$device$osv}
model <- if(is.null(json_par$device$model)){'null'}else{json_par$device$model}
connectiontype <- if(is.null(json_par$device$connectiontype)){'0'}else(json_par$device$connectiontype)
country <- json_par$device$geo$country
carrier <- if(is.null(json_par$device$geo$carrier)){'null'}else{json_par$device$geo$carrier}
js <- if(is.null(json_par$device$js)){'0'}else{json_par$device$js}
user <- if(is.null(json_par$user)){'0'}else{'1'}
carriername <- if(is.null(json_par$ext$carriername)){'-'}else{json_par$ext$carriername}
app_cat <- paste(if(is.null(json_par$app$cat)){'null'}else{json_par$app$cat},collapse=",")
btype <- paste(if(is.null(json_par$imp$banner$btype)){'null'}else{json_par$imp$banner$btype},collapse = ",")
mimes <- paste(if(is.null(json_par$imp$banner$mimes)){'null'}else{json_par$imp$banner$mimes[[1]]},collapse = ",")
badv <- paste(if(is.null(json_par$badv)){'null'}else{json_par$badv},collapse = ",")
bcat <- paste(if(is.null(json_par$bcat)){'null'}else{json_par$bcat},collapse = ",")
operators <- c('windows', 'ios', 'mac', 'android', 'linux')
browsers <- c('chrome', 'sogou', 'maxthon', 'safari', 'firefox', 'theworld', 'opera', 'ie')
operation <- 'other'
browser <- 'other'
regularForm <- if(!is.null(json_par$device$ua)){
for(i in 1:length(operators)){
if(grepl(operators[i],json_par$device$ua)){
operation <- operators[i]
break
}
}
for (i in 1:length(browsers)){
if(grepl(browsers[i],json_par$device$ua)){
browser <- browsers[i]
break
}
}
paste(operation,browser,sep="_")
}else{
'null'
}
bidimpclk <- data.frame(days=days,hours=hours,exchange_id=exchange_id,app_id=app_id,publiser_id=publiser_id,bidfloor=bidfloor,w=w,h=h,os=os,Osv=os_ver,model=model,connectiontype=connectiontype,country=country,ua=regularForm,carrier=carrier,js=js,user=user,carriername=carriername,app_cat=app_cat,btype=btype,mimes=mimes,badv=badv,bcat=bcat)
model <- ~ wr * (days + hours + exchange_id + app_id + publiser_id + bidfloor + w + h + os +
Osv + model + connectiontype + country + ua + carrier + js + user + carriername +
split(app_cat,delim =",") + split(btype,delim =",") + split(mimes,delim =",") + split(badv,delim =",") + split(bcat,delim =","))
apply_win_loose <- function(df) {
df <- as.data.frame(df)
function(f, ...) {
f(df, ...)
}
}
formula <- ~ days + hours + exchange_id + app_id + publiser_id + bidfloor + w + h + os + Osv + model + connectiontype + country + ua + carrier + js + user + carriername + split(app_cat,delim =",") + split(btype,delim =",") +
split(mimes,delim =",") + split(badv,delim =",") +
split(bcat,delim =",")
predict.test <- hashed.model.matrix(formula, bidimpclk, 2^20)
# load(cv.g.lr)
# cv.g.lr <- readRDS("wr.rda")
# win rate model
wr <- predict(cv.g.lr, predict.test, s="lambda.min", type = "response")
tmp <- cbind(bidimpclk,wr=c(wr))
bidimpclk$wr <- tmp$wr
apply_f <- apply_win_loose(bidimpclk)
m <- apply_f(hashed.model.matrix, formula = model, hash.size = 2^20, transpose = TRUE, is.dgCMatrix = FALSE)
# l.lm <- readRDS("lm.rda")
#lm.26model.Rds
# l.clm2 <- readRDS("clm.rda")
#clm.26model.Rds
# lm + clm with wr as weighted
#ptm <- proc.time()
wpPre <- wr * l.win_lm$predict(m) + (1 - wr) * l.clm2$predict(m)
#return(proc.time()-ptm)
return(wpPre)
}
<file_sep>/training/testing_day.R
#' Prepare the data of the experiments
#'
#' Loading required library
# library(methods)
# library(data.table)
library(dplyr)
library(FeatureHashing)
library(glmnet)
model <- ~ wr * (days + hours + exchange_id + app_id + publiser_id + bidfloor + w + h + os +
Osv + model + connectiontype + country + ua + carrier + js + user + carriername +
split(app_cat,delim =",") + split(btype,delim =",") + split(mimes,delim =",") + split(badv,delim =",") + split(bcat,delim =","))
mseloss <- function(y, y.hat) {
mean((y - y.hat)^2)
}
apply_win_loose <- function(df) {
df <- as.data.frame(df)
function(f, ...) {
f(df, ...)
}
}
Args <- commandArgs()
bidimpclk <- read.table(Args[6],header = TRUE, sep="\t")
formula <- ~ days + hours + exchange_id + app_id + publiser_id + bidfloor + w + h + os + Osv + model + connectiontype + country + ua + carrier + js + user + carriername + split(app_cat,delim =",") + split(btype,delim =",") +
split(mimes,delim =",") + split(badv,delim =",") +
split(bcat,delim =",")
predict.test <- hashed.model.matrix(formula, bidimpclk, 2^20)
# load(cv.g.lr)
cv.g.lr <- readRDS(Args[7])
# win rate model
wr <- predict(cv.g.lr, predict.test, s="lambda.min", type = "response")
sprintf("************** win rate statistic************************")
AcuWin <- auc(bidimpclk$is_win, p.lr)
AveWr <- sum(p.lr)/nrow(p.lr)
loginfo("Average Win rate is : %s", AveWr)
loginfo("Accuracy win rate is : %s", AcuWin)
tmp <- cbind(bidimpclk,wr=c(wr))
bidimpclk$wr <- tmp$wr
apply_f <- apply_win_loose(bidimpclk)
m <- apply_f(hashed.model.matrix, formula = model, hash.size = 2^20, transpose = TRUE, is.dgCMatrix = FALSE)
l.lm <- readRDS(Args[8])
#lm.26model.Rds
l.clm2 <- readRDS(Args[9])
#clm.26model.Rds
# for linear part
linPre <- l.lm$predict(m)
linAvewp <- sum(linPre)/nrow(linPre)
sprintf("Linear average winning price is : %s", linAvewp)
linStaAUC <- data.frame(payp=c(bidimpclk$payingprice), wp = c(linPre))
linwinNum <- with(linStaAUC,linStaAUC[payp < wp, ])
linAcuWin <- nrow(linwinNum)/nrow(linStaAUC)
sprintf("Accuracy using winning price : %s", linAcuWin)
# for censored part
cenPre <- l.clm2$predict(m)
cenAvewp <- sum(cenPre)/nrow(cenPre)
sprintf("Censored average winning price is : %s", cenAvewp)
cenStaAUC <- data.frame(payp=c(bidimpclk$payingprice), wp = c(cenPre))
cenwinNum <- with(cenStaAUC,cenStaAUC[payp < wp, ])
cenAcuWin <- nrow(cenwinNum)/nrow(cenStaAUC)
sprintf("Accuracy using winning price : %s", cenAcuWin)
# lm + clm with wr as weighted
resultPredict <- wr * l.lm$predict(m) + (1 - wr) * l.clm2$predict(m)
# png(Args[10])
# png(file="wp_dis26.png")
# plot(resultPredict)
# dev.off()
Avewp <- sum(resultPredict)/nrow(resultPredict)
sprintf("Average winning price is : %s", Avewp)
StaAUC <- data.frame(payp=c(bidimpclk$payingprice), wp = c(resultPredict))
winNum <- with(StaAUC,StaAUC[payp < wp, ])
AcuWin <- nrow(winNum)/nrow(StaAUC)
sprintf("Accuracy using winning price : %s", AcuWin)
# saveRDS(resultPredict, sprintf("result.predict.Rds"))
<file_sep>/php-example/test_pre.php
<?php
$zero1=strtotime (date("y-m-d h:i:s"));
echo "<form action='test_pre.php' method='post'>";
echo "Input json log: <input type='text' name='request' />";
echo "<input type='submit' name='sub' value='submit'/>";
echo "</form>";
if(isset($_POST["sub"])){
$request=$_POST["request"];
exec("Rscript /usr/share/nginx/html/example/api/wr_predict_test.R $request 2>&1",$output,$return_val);
print_r($output);
echo "<br />";
print_r($return_val);
echo "<br />";
exec("Rscript /usr/share/nginx/html/example/api/wp_predict_test.R $request 2>&1",$output,$return_val);
print_r($output);
echo "<br />";
print_r($return_val);
echo "<br />";
$zero2=strtotime (date("y-m-d h:i:s"));
$guonian=floor(($zero2-$zero1)%86400%60);
echo "<strong>$guonian</strong>s<br />";
}
?>
<file_sep>/README.md
## R Project for Advertising
Some experiments using R to simulate prediction, combining the [ipinyou](http://data.computational-advertising.org/) open data sets
## Getting Started
```sh
git clone https://github.com/snakecy/R-Projects.git
```
<file_sep>/ipindata/api/wp_predict_online.R
#' Prepare the data of the experiments
library(methods)
library(foreach,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
library(Matrix,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
library(FeatureHashing,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
library(glmnet,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
library(dplyr,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
model <- ~ wr * (days + hours + exchange_id + app_id + publiser_id + bidfloor + w + h + os +
Osv + model + connectiontype + country + ua + carrier + js + user + carriername +
split(app_cat,delim =",") + split(btype,delim =",") + split(mimes,delim =",") + split(badv,delim =",") + split(bcat,delim =","))
apply_win_loose <- function(df) {
df <- as.data.frame(df)
function(f, ...) {
f(df, ...)
}
}
Args <- commandArgs(TRUE)
# bidimpclk <- read.table(Args[6],header = TRUE, sep="\t")
bidimpclk <- data.frame(exchange_id=Args[1],days=Args[2],hours=Args[3],country=Args[4],carrier=Args[5],user=Args[6],app_cat=Args[7],app_id=Args[8],publiser_id=Args[9],Osv=Args[10],ua=Args[11],model=Args[12],js=Args[13],os=Args[14],carriername=Args[15],connectiontype=Args[16],w=Args[17],h=Args[18],mimes=Args[19],bidfloor=Args[20],btype=Args[21],badv=Args[22],bcat=Args[23])
formula <- ~ days + hours + exchange_id + app_id + publiser_id + bidfloor + w + h + os + Osv + model + connectiontype + country + ua + carrier + js + user + carriername + split(app_cat,delim =",") + split(btype,delim =",") +
split(mimes,delim =",") + split(badv,delim =",") +
split(bcat,delim =",")
predict.test <- hashed.model.matrix(formula, bidimpclk, 2^20)
# load(cv.g.lr)
cv.g.lr <- readRDS("lr.Rds")
# win rate model
wr <- predict(cv.g.lr, predict.test, s="lambda.min", type = "response")
tmp <- cbind(bidimpclk,wr=c(wr))
bidimpclk$wr <- tmp$wr
apply_f <- apply_win_loose(bidimpclk)
m <- apply_f(hashed.model.matrix, formula = model, hash.size = 2^20, transpose = TRUE, is.dgCMatrix = FALSE)
l.lm <- readRDS("lm.Rds")
#lm.26model.Rds
l.clm2 <- readRDS("clm.Rds")
#clm.26model.Rds
# lm + clm with wr as weighted
wpPre <- wr * l.lm$predict(m) + (1 - wr) * l.clm2$predict(m)
sprintf("winning price is : %s", wpPre)
<file_sep>/php-example/Ref.php
<?php
$zero1=strtotime (date("y-m-d h:i:s"));
echo "OK<br />";
exec("Rscript /usr/share/nginx/html/test.R 2>&1",$output,$return_val);
print_r($output);
echo "<br />";
print_r($return_val);
echo "<br />";
$zero2=strtotime (date("y-m-d h:i:s"));
$guonian=floor(($zero2-$zero1)%86400%60%1000);
echo "<strong>$guonian</strong>ms<br />";
?>
<file_sep>/training/run.sh
# rda format
Rscript train_day.R data.txt lr.rda lm.rda clm.rda
Rscript testing_day.R data.txt lr.rda lm.rda clm.rda
<file_sep>/ipindata/timeT.php
<?php
//PHP计算两个时间差的方法
echo date(time());
$startdate="2012-12-11 11:40:00";
$enddate="2012-12-12 11:45:09";
$date=floor((strtotime($enddate)-strtotime($startdate))/86400);
$hour=floor((strtotime($enddate)-strtotime($startdate))%86400/3600);
$minute=floor((strtotime($enddate)-strtotime($startdate))%86400/60);
$second=floor((strtotime($enddate)-strtotime($startdate))%86400%60);
echo $date."day<br>";
echo $hour."hour<br>";
echo $minute."minutes<br>";
echo $second."sec<br>";
echo "<br>";
echo date(time());
?>
<file_sep>/onlineapi/R/onLoad.R
.onLoad <- function(lib, pkg){
#automatically loads the dataset when package is loaded
#do not use this in combination with lazydata=true
utils::data(wr,lm,clm, package = pkg, envir = parent.env(environment()))
library(methods)
library(foreach)
library(Matrix)
library(FeatureHashing)
library(glmnet)
library(jsonlite)
library(lubridate)
library(dplyr)
}
<file_sep>/php-example/ua_operation.php
<?php
$arr = array('a','b','c','d','e');
$html = '';
foreach($arr as $key => $value){
if($value=='b'){
$html .= $value;
continue; // 当 $value为b时,跳出本次循环
}
if($value=='c'){
$html .= $value;
break; // 当 $value为c时,终止循环
}
$html .= $value;
}
echo $html; // 输出: abc
?>
<file_sep>/ipindata/test.R
library(methods)
library(foreach,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
library(Matrix,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
library(FeatureHashing,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
library(glmnet,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
# Args <- commandArgs()
bidimp <- read.table("/usr/share/nginx/html/pred.txt",sep = "\t", header = TRUE)
# bidimp <- read.table(Args[6],sep = "\t", header = TRUE)
f <- ~ days + hours + exchange_id + app_id + publiser_id + bidfloor + w + h + os + Osv + model + connectiontype + country + ua + carrier + js + user + carriername + split(app_cat,delim =",") + split(btype,delim =",") +
split(mimes,delim =",") + split(badv,delim =",") +
split(bcat,delim =",")
m.test <- hashed.model.matrix(f, bidimp, 2^20)
cv.g.lr <- readRDS("/usr/share/nginx/html/wr_model_26.Rds")
p.lr <- predict(cv.g.lr, m.test, s="lambda.min", type = "response")
sprintf("Win rate is : %s", p.lr)
<file_sep>/php-example/ua.php
<?php
$deviceua = "Dalvik/1.6.0 (Linux; U; Android 4.1.2; GT-I8190N Build/JZO54K)";
$operators = array('windows', 'ios', 'mac', 'android', 'linux');
$browsers = array('chrome', 'sogou', 'maxthon', 'safari', 'firefox', 'theworld', 'opera', 'ie');
// $regularForm = '';
$operation = 'other';
$browser = 'other';
if (!empty($deviceua)){
foreach ($operators as $key => $value){
if( strstr(strtolower($deviceua),$value)){
$operation = $value;
break;
}
}
foreach ($browsers as $key => $value){
if(strstr(strtolower($deviceua),$value)){
$browser = $value;
break;
}
}
$regularForm = $operation._.$browser;
}else{
$regularForm = null;
}
echo $regularForm;
?>
<file_sep>/php-example/wrtest.R
#' Prepare the data of the experiments
#'
#' Loading required library
library(methods)
library(foreach,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
library(Matrix,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
library(FeatureHashing,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
library(glmnet,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
Args <- commandArgs(TRUE)
# bidtmp <- Args[1]
# sprintf(bidtmp)
bidimp <- data.frame(exchange_id=Args[1],days=Args[2],hours=Args[3],country=Args[4],carrier=Args[5],user=Args[6],app_cat=Args[7],app_id=Args[8],publiser_id=Args[9],Osv=Args[10],ua=Args[11],model=Args[12],js=Args[13],os=Args[14],carriername=Args[15],connectiontype=Args[16],w=Args[17],h=Args[18],mimes=Args[19],bidfloor=Args[20],btype=Args[21],badv=Args[22],bcat=Args[23])
f <- ~ days + hours + exchange_id + app_id + publiser_id + bidfloor + w + h + os + Osv + model + connectiontype + country + ua + carrier + js + user + carriername + split(app_cat,delim =",") + split(btype,delim =",") +
split(mimes,delim =",") + split(badv,delim =",") +
split(bcat,delim =",")
m.test <- hashed.model.matrix(f, bidimp, 2^20)
cv.g.lr <- readRDS("wr_model_26.Rds")
p.lr <- predict(cv.g.lr, m.test, s="lambda.min", type = "response")
sprintf("Win rate is : %s", p.lr)
<file_sep>/onlineapi/R/wr_predict_api.R
wr_predict_api <- function(request){
json_req <- fromJSON(request)
json_par <- fromJSON(json_req$json)
# data.frame elements in json_req
days <- day(json_req$create_datetime)%%7
hours <- hour(json_req$create_datetime)
exchange_id <- json_req$exchange_id
# data.frame elements in json_par
app_id <- if(is.null(json_par$app$id)){'0'}else{json_par$app$id}
publiser_id <- if(is.null(json_par$app$publisher$id)){'null'}else{json_par$app$publisher$id}
bidfloor <- if(is.null(json_par$imp$bidfloor)){'0'}else{json_par$imp$bidfloor}
w <- if(is.null(json_par$imp$banner$w)){'0'}else{json_par$imp$banner$w}
h <- if(is.null(json_par$imp$banner$h)){'0'}else{json_par$imp$banner$h}
os <- if(tolower(json_par$device$os) == "android"){'1'}else if(tolower(json_par$device$os) == "ios"){'2'} else{'0'}
os_ver <- if(is.null(json_par$device$osv)){'0'}else{json_par$device$osv}
model <- if(is.null(json_par$device$model)){'null'}else{json_par$device$model}
connectiontype <- if(is.null(json_par$device$connectiontype)){'0'}else(json_par$device$connectiontype)
country <- json_par$device$geo$country
carrier <- if(is.null(json_par$device$geo$carrier)){'null'}else{json_par$device$geo$carrier}
js <- if(is.null(json_par$device$js)){'0'}else{json_par$device$js}
user <- if(is.null(json_par$user)){'0'}else{'1'}
carriername <- if(is.null(json_par$ext$carriername)){'-'}else{json_par$ext$carriername}
app_cat <- paste(if(is.null(json_par$app$cat)){'null'}else{json_par$app$cat},collapse=",")
btype <- paste(if(is.null(json_par$imp$banner$btype)){'null'}else{json_par$imp$banner$btype},collapse = ",")
mimes <- paste(if(is.null(json_par$imp$banner$mimes)){'null'}else{json_par$imp$banner$mimes[[1]]},collapse = ",")
badv <- paste(if(is.null(json_par$badv)){'null'}else{json_par$badv},collapse = ",")
bcat <- paste(if(is.null(json_par$bcat)){'null'}else{json_par$bcat},collapse = ",")
operators <- c('windows', 'ios', 'mac', 'android', 'linux')
browsers <- c('chrome', 'sogou', 'maxthon', 'safari', 'firefox', 'theworld', 'opera', 'ie')
operation <- 'other'
browser <- 'other'
regularForm <- if(!is.null(json_par$device$ua)){
for(i in 1:length(operators)){
if(grepl(operators[i],json_par$device$ua)){
operation <- operators[i]
break
}
}
for (i in 1:length(browsers)){
if(grepl(browsers[i],json_par$device$ua)){
browser <- browsers[i]
break
}
}
paste(operation,browser,sep="_")
}else{
'null'
}
bidimp <- data.frame(days=days,hours=hours,exchange_id=exchange_id,app_id=app_id,publiser_id=publiser_id,bidfloor=bidfloor,w=w,h=h,os=os,Osv=os_ver,model=model,connectiontype=connectiontype,country=country,ua=regularForm,carrier=carrier,js=js,user=user,carriername=carriername,app_cat=app_cat,btype=btype,mimes=mimes,badv=badv,bcat=bcat)
f <- ~ days + hours + exchange_id + app_id + publiser_id + bidfloor + w + h + os + Osv + model + connectiontype + country + ua + carrier + js + user + carriername + split(app_cat,delim =",") + split(btype,delim =",") +
split(mimes,delim =",") + split(badv,delim =",") +
split(bcat,delim =",")
m.test <- hashed.model.matrix(f, bidimp, 2^20)
# cv.g.lr <- readRDS("wr_model_26.Rds")
ptm <- proc.time()
p.lr <- predict(cv.g.lr, m.test, s="lambda.min", type = "response")
return(proc.time()-ptm)
# return(p.lr)
}
<file_sep>/php-example/wp_predict.R
#' Prepare the data of the experiments
library(methods)
library(curl,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
library(foreach,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
library(Matrix,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
library(FeatureHashing,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
library(glmnet,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
library(dplyr,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
library(lubridate,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
library(jsonlite,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
Args <- commandArgs(TRUE)
request <- Args[1]
# wp_predict_api <- function(request){
json_req <- fromJSON(request)
json_par <- fromJSON(json_req$json)
# data.frame elements in json_req
days <- day(json_req$create_datetime)%%7
hours <- hour(json_req$create_datetime)
exchange_id <- json_req$exchange_id
# data.frame elements in json_par
app_id <- if(is.null(json_par$app$id)){'0'}else{json_par$app$id}
publiser_id <- if(is.null(json_par$app$publisher$id)){'null'}else{json_par$app$publisher$id}
bidfloor <- if(is.null(json_par$imp$bidfloor)){'0'}else{json_par$imp$bidfloor}
w <- if(is.null(json_par$imp$banner$w)){'0'}else{json_par$imp$banner$w}
h <- if(is.null(json_par$imp$banner$h)){'0'}else{json_par$imp$banner$h}
os <- if(tolower(json_par$device$os) == "android"){'1'}else if(tolower(json_par$device$os) == "ios"){'2'} else{'0'}
os_ver <- if(is.null(json_par$device$osv)){'0'}else{json_par$device$osv}
model <- if(is.null(json_par$device$model)){'null'}else{json_par$device$model}
connectiontype <- if(is.null(json_par$device$connectiontype)){'0'}else(json_par$device$connectiontype)
country <- json_par$device$geo$country
carrier <- if(is.null(json_par$device$geo$carrier)){'null'}else{json_par$device$geo$carrier}
js <- if(is.null(json_par$device$js)){'0'}else{json_par$device$js}
user <- if(is.null(json_par$user)){'0'}else{'1'}
carriername <- if(is.null(json_par$ext$carriername)){'-'}else{json_par$ext$carriername}
app_cat <- paste(if(is.null(json_par$app$cat)){'null'}else{json_par$app$cat},collapse=",")
btype <- paste(if(is.null(json_par$imp$banner$btype)){'null'}else{json_par$imp$banner$btype},collapse = ",")
mimes <- paste(if(is.null(json_par$imp$banner$mimes)){'null'}else{json_par$imp$banner$mimes[[1]]},collapse = ",")
badv <- paste(if(is.null(json_par$badv)){'null'}else{json_par$badv},collapse = ",")
bcat <- paste(if(is.null(json_par$bcat)){'null'}else{json_par$bcat},collapse = ",")
operators <- c('windows', 'ios', 'mac', 'android', 'linux')
browsers <- c('chrome', 'sogou', 'maxthon', 'safari', 'firefox', 'theworld', 'opera', 'ie')
operation <- 'other'
browser <- 'other'
regularForm <- if(!is.null(json_par$device$ua)){
for(i in 1:length(operators)){
if(grepl(operators[i],json_par$device$ua)){
operation <- operators[i]
break
}
}
for (i in 1:length(browsers)){
if(grepl(browsers[i],json_par$device$ua)){
browser <- browsers[i]
break
}
}
paste(operation,browser,sep="_")
}else{
'null'
}
bidimpclk <- data.frame(days=days,hours=hours,exchange_id=exchange_id,app_id=app_id,publiser_id=publiser_id,bidfloor=bidfloor,w=w,h=h,os=os,Osv=os_ver,model=model,connectiontype=connectiontype,country=country,ua=regularForm,carrier=carrier,js=js,user=user,carriername=carriername,app_cat=app_cat,btype=btype,mimes=mimes,badv=badv,bcat=bcat)
model <- ~ wr * (days + hours + exchange_id + app_id + publiser_id + bidfloor + w + h + os +
Osv + model + connectiontype + country + ua + carrier + js + user + carriername +
split(app_cat,delim =",") + split(btype,delim =",") + split(mimes,delim =",") + split(badv,delim =",") + split(bcat,delim =","))
apply_win_loose <- function(df) {
df <- as.data.frame(df)
function(f, ...) {
f(df, ...)
}
}
formula <- ~ days + hours + exchange_id + app_id + publiser_id + bidfloor + w + h + os + Osv + model + connectiontype + country + ua + carrier + js + user + carriername + split(app_cat,delim =",") + split(btype,delim =",") +
split(mimes,delim =",") + split(badv,delim =",") +
split(bcat,delim =",")
predict.test <- hashed.model.matrix(formula, bidimpclk, 2^20)
# load(cv.g.lr)
# cv.g.lr <- readRDS("wr.rda")
load("wr.rda")
# win rate model
wr <- predict(cv.g.lr, predict.test, s="lambda.min", type = "response")
tmp <- cbind(bidimpclk,wr=c(wr))
bidimpclk$wr <- tmp$wr
apply_f <- apply_win_loose(bidimpclk)
m <- apply_f(hashed.model.matrix, formula = model, hash.size = 2^20, transpose = TRUE, is.dgCMatrix = FALSE)
# l.lm <- readRDS("lm.rda")
#lm.26model.Rds
# l.clm2 <- readRDS("clm.rda")
#clm.26model.Rds
load("lm.rda")
load("clm.rda")
# lm + clm with wr as weighted
wpPre <- wr * l.win_lm$predict(m) + (1 - wr) * l.clm2$predict(m)
sprintf("winning price is : %s", wpPre)
# }
<file_sep>/predicting/predicting_day.R
#' Prepare the data of the experiments
#' Loading required library
library(methods)
library(FeatureHashing)
library(glmnet)
loginfo <- function(fmt, ...) {
cat(sprintf("(%s) ", Sys.time()))
cat(sprintf(fmt, ...))
cat("\n")
}
Args <- commandArgs()
bidimpclk <- read.table(Args[6],sep = "\t", header = TRUE)
model <- ~ wr * (days + hours + exchange_id + app_id + publiser_id + bidfloor + w + h + os + Osv + model + connectiontype + country + ua + carrier + js + user + carriername + split(app_cat,delim =",") + split(btype,delim =",") + split(mimes,delim =",") + split(badv,delim =",") + split(bcat,delim =","))
apply_win_loose <- function(df) {
df <- as.data.frame(df)
function(f, ...) {
f(df, ...)
}
}
formula <- ~ days + hours + exchange_id + app_id + publiser_id + bidfloor + w + h + os + Osv + model + connectiontype + country + ua + carrier + js + user + carriername + split(app_cat,delim =",") + split(btype,delim =",") + split(mimes,delim =",") + split(badv,delim =",") + split(bcat,delim =",")
predict.test <- hashed.model.matrix(formula, bidimpclk, 2^20)
# load(cv.g.lr)
cv.g.lr <- readRDS(Args[7])
# load("wr.rda")
# win rate model
wr <- predict(cv.g.lr, predict.test, s="lambda.min", type = "response")
loginfo("win rate is : %s", wr)
tmp <- cbind(bidimpclk,wr=c(wr))
bidimpclk$wr <- tmp$wr
apply_f <- apply_win_loose(bidimpclk)
m <- apply_f(hashed.model.matrix, formula = model, hash.size = 2^20, transpose = TRUE, is.dgCMatrix = FALSE)
l.lm <- readRDS(Args[8])
# load(Args[8])
#lm.26model.Rds
l.clm2 <- readRDS(Args[9])
# load(Args[9])
#clm.26model.Rds
# lm + clm with wr as weighted
wpre <- wr * l.win_lm$predict(m) + (1 - wr) * l.clm2$predict(m)
sprintf("winning price is : %s", wpre)
<file_sep>/ipindata/test.php
<?php
//$zero1=strtotime (date("y-m-d h:i:s"));
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$zero1=microtime_float();
echo $zero1."<br>";
echo "OK<br />";
exec("Rscript /usr/share/nginx/html/test.R 2>&1",$output,$return_val);
print_r($output);
echo "<br />";
print_r($output[1][2][1]);
echo "<br />";
print_r($return_val);
echo "<br />";
//$zero2=strtotime (date("y-m-d h:i:s"));
$zero2=microtime_float();
echo $zero2."<br>";
$guonian=floor(($zero2-$zero1)%86400%60);
echo "<strong>$guonian</strong> s<br />";
?>
<file_sep>/ipindata/api/predict.php
<?php
$zero1=strtotime (date("y-m-d h:i:s"));
echo "<form action='predict.php' method='post'>";
echo "Input json log: <input type='text' name='request' />";
echo "<input type='submit' name='sub' value='submit'/>";
echo "</form>";
if(isset($_POST["sub"])){
$request=$_POST["request"];
// $jsonreq = var_dump(json_decode($req,TRUE));
// $request = utf8_encode($request);
$jsonreq = json_decode($request,TRUE);
// if (json_last_error() === JSON_ERROR_NONE) {
// echo "true"; //do something with $json. It's ready to use
// } else {
// echo "false";//yep, it's not JSON. Log error or alert someone or do nothing
// }
// $data = call_user_func_array('parseBidRequest',array($jsonreq));
$dataout = parseBidRequestO($jsonreq);
$jsonreq = $dataout["json"];
$jsonreq = json_decode($jsonreq,TRUE);
$data = parseBidRequest($jsonreq);
$data = array_merge($dataout,$data);
echo "<br>";
unset($data[json],$data[ad_space_id],$data[ad_space_cat],$data[ad_space_type],$data[ad_space_name],$data[ad_space_publisher_id],$data[mimeArr],$data[btypeArr],$data[bcatArr],$data[badvArr],$data[ad_type],$data[app_name],$data[imp_id],$data[strictbannersize],$data[datetime],$data[os_str],$data[imp_type]);
// print_r($data);
$data = implode("\t",$data);
print_r($data);
echo "<br>";
// exec R script
exec("Rscript wr_predict_online.R $data",$output,$return_val);
print_r($output["0"]);
echo "<br />";
//print_r($return_val);
//exec("Rscript wp_predict_online.R $data 2>&1",$output1,$return_val1);
exec("Rscript wp_predict_online.R $data",$output1,$return_val1);
//print_r($output1);
echo "<br />";
echo $output1["0"];
//echo implode($output1);
//print_r($return_val1);
echo "<br />";
$zero2=strtotime (date("y-m-d h:i:s"));
$guonian=floor(($zero2-$zero1)%86400%60);
echo "<strong>$guonian</strong>s<br />";
}
function parseBidRequestO($jsonin){
$data = array();
#exchange_id & time
$data["exchange_id"] = ($jsonin["exchange_id"] ?: null);
$data["datetime"] = ($jsonin["create_datetime"] ?: null);
$data["days"] = ((int)substr($data["datetime"],8,2) % 7);
$data["hours"] = ((int)substr($data["datetime"],11,2));
$data["json"] = ($jsonin["json"] ?:null);
return $data;
}
function parseBidRequest($req) {
$data = array();
# Geo Location
$data["country"] = ($req["device"]["geo"]["country"] ?: null);
// $data["ip_address"] = ($req["device"]["ip"] ?: '0.0.0.0');
// $data["ip"] = $data["ip_address"]; // For backward compatibility
$data["carrier"] = ($req["device"]["geo"]["carrier"] ?: "null");
$data["user"] = ($req["user"] ? "1" : "0"); // 0:non-exsit, 1:exsit
# Ad Space
$data["ad_space_type"] = ($req["app"] ? "1" : "2"); // 1:app, 2:site
if ($data["ad_space_type"] == 1) {
$data["ad_space_id"] = ($req["app"]["id"] ?: null);
$data["ad_space_cat"] = ($req["app"]["cat"] ?: array("null"));
$data["ad_space_name"] = ($req["app"]["name"] ?: null);
$data["ad_space_publisher_id"] = ($req["app"]["publisher"]["id"] ?: null);
} else {
$data["ad_space_id"] = ($req["site"]["id"] ?: null);
$data["ad_space_cat"] = ($req["site"]["cat"] ?: array("null"));
$data["ad_space_name"] = ($req["site"]["name"] ?: null);
$data["ad_space_publisher_id"] = ($req["site"]["publisher"]["id"] ?: null);
}
$data["app_cat"] = implode(",",$data["ad_space_cat"]);
$data["app_id"] = $data["ad_space_id"]; // For backward compatibility
$data["app_name"] = $data["ad_space_name"];
$data["publiser_id"] = $data["ad_space_publisher_id"];
# Device
$data["os_str"] = ($req["device"]["os"] ?: "Unknown");
$data["os_ver"] = ($req["device"]["osv"] ?: 0);
$data["ua"] = ($req["device"]["ua"] ?: null);
$data["model"] = ($req["device"]["model"] ?: null);
$deviceua = $data["ua"];
$operators = array('windows', 'ios', 'mac', 'android', 'linux');
$browsers = array('chrome', 'sogou', 'maxthon', 'safari', 'firefox', 'theworld', 'opera', 'ie');
// $regularForm = '';
$operation = 'other';
$browser = 'other';
if (!empty($deviceua)){
foreach ($operators as $key => $value){
if( strstr(strtolower($deviceua),$value)){
$operation = $value;
break;
}
}
foreach ($browsers as $key => $value){
if(strstr(strtolower($deviceua),$value)){
$browser = $value;
break;
}
}
$regularForm = $operation._.$browser;
}else{
$regularForm = null;
}
$data["ua"]= $regularForm;
$data["js"] = ($req["device"]["js"] ?: 0);
if (strtolower($data["os_str"]) == "android") {
$data["os"] = 1;
} else if (strtolower($data["os_str"]) == "ios") {
$data["os"] = 2;
} else {
$data["os"] = 0;
}
# Connection
$data["carrier_name"] = trim($req["ext"]["carriername"] ?: "-"); // Specific to Smaato
$data["conn_type"] = ($req["device"]["connectiontype"] ?: 0);
# Creative attributes
$imp = $req["imp"][0];
# Check if the Banner or Video obj exist
$isbanner = isset($imp["banner"]);
$isvideo = isset($imp["video"]);
$data["ad_type"] = ($isbanner? "banner":"");
$data["ad_type"] = ($isvideo? "video":$data["ad_type"]);
// For logging imp object type. 1=banner, 2=video, 3=both
$data["imp_type"] = ($isbanner ? 1 : 0) + ($isvideo ? 2 : 0);
// imp object can contain both banner and video. Only one type will be catered. Banner has higher priority.
if ($imp["banner"]){
$data["ad_width"] = ($imp["banner"]["w"] ?: 0);
$data["ad_height"] = ($imp["banner"]["h"] ?: 0);
$data["strictbannersize"] = ($imp["ext"]["strictbannersize"] ?: 0); // Specific to Smaato
$data["mimeArr"] = ($imp["banner"]["mimes"] ?: array("null"));
} else if ($imp["video"]){
$data["mimeArr"] = ($imp["video"]["mimes"]?: array("null"));
$data["ad_minduration"] = ($imp["video"]["minduration"]?: 0);
$data["ad_maxduration"] = ($imp["video"]["maxduration"]?: "+inf");
$data["ad_protocols"] = ($imp["video"]["protocols"]?: array());
$data["ad_width"] = ($imp["video"]["w"] ?: 0);
$data["ad_height"] = ($imp["video"]["h"] ?: 0);
$data["ad_minbitrate"] = ($imp["video"]["minbitrate"] ?: 0);
$data["ad_maxbitrate"] = ($imp["video"]["maxbitrate"] ?: "+inf");
}
$data["mimes"] = implode(",",$data["mimeArr"]);
$data["imp_id"] = trim($imp["id"]);
$data["bid_floor"] = ($imp["bidfloor"] ?: 0);
# Banned lists
$data["btypeArr"] = ($imp["banner"]["btype"] ?: array("null"));
$data["badvArr"] = ($req["badv"] ?: array("null"));
$data["bcatArr"] = ($req["bcat"] ?: array("null"));
$data["btype"] = implode(",",$data["btypeArr"]);
$data["badv"] = implode(",",$data["badvArr"]);
$data["bcat"] = implode(",",$data["bcatArr"]);
return $data;
}
?>
<file_sep>/php-example/wr_predict_online.R
#' Prepare the data of the experiments
#'
#' Loading required library
library(methods)
library(foreach,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
library(Matrix,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
library(FeatureHashing,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
library(glmnet,lib="/home/azureuser/R/x86_64-pc-linux-gnu-library/3.2")
Args <- commandArgs(TRUE)
bidtmp <- Args[1]
bidimp <- cbind(days=bidtmp["days"],hours=bidtmp["hours"],exchange_id=bidtmp["exchange_id"],app_id=bidtmp["app_id"],publiser_id=bidtmp["publiser_id"],bidfloor=bidtmp["bid_floor"],w=bidtmp["ad_width"],h=bidtmp["ad_height"],os=bidtmp["os"],Osv=bidtmp["os_ver"],model=bidtmp["model"],connectiontype=bidtmp["conn_type"],country=bidtmp["country"],ua=bidtmp["ua"],carrier=bidtmp["carrier"],js=bidtmp["js"],user=bidtmp["user"],carriername=bidtmp["carrier_name"],app_cat=bidtmp["app_cat"],btype=bidtmp["btype"],mimes=bidtmp["mimes"],badv=bidtmp["badv"],bcat=bidtmp["bcat"])
f <- ~ days + hours + exchange_id + app_id + publiser_id + bidfloor + w + h + os + Osv + model + connectiontype + country + ua + carrier + js + user + carriername + split(app_cat,delim =",") + split(btype,delim =",") +
split(mimes,delim =",") + split(badv,delim =",") +
split(bcat,delim =",")
m.test <- hashed.model.matrix(f, bidimp, 2^20)
cv.g.lr <- readRDS("wr_model_26.Rds")
p.lr <- predict(cv.g.lr, m.test, s="lambda.min", type = "response")
sprintf("Win rate is : %s", p.lr)
<file_sep>/trainingnwr/train_c.R
# load library
library(methods)
library(dplyr)
library(FeatureHashing)
library(glmnet)
loginfo <- function(fmt, ...) {
cat(sprintf("(%s) ", Sys.time()))
cat(sprintf(fmt, ...))
cat("\n")
}
linear_regression <- function(m, y, lambda2 = 1000, start = rep(0.0, nrow(m))) {
f <- function(w) {
sum((w %*% m - y)^2) + lambda2 * sum(tail(w, -1)^2) / 2
}
g <- function(w) {
2 * (m %*% (w %*% m - y)) + lambda2 * c(0, tail(w, -1))
}
r <- optim(start, f, g, method = "L-BFGS-B", control = list(maxit = ifelse(interactive(), 100, 20000), trace = ifelse(interactive(), 1, 0)))
list(predict = function(m) r$par %*% m, r = r)
}
censored_regression2 <- function(m, y, is_win, sigma, lambda2 = 1000, start = rep(0.0, nrow(m))) {
f.w <- function(w) {
z <- (w %*% m - y) / sigma
- (sum(dnorm(z[is_win], log = TRUE)) + sum(pnorm(z[!is_win], lower.tail = TRUE, log.p = TRUE))) + lambda2 * sum(tail(w, -1)^2) / 2
}
g.w <- function(w) {
z <- (w %*% m - y) / sigma
z.observed <- dzdl.observed <- z[is_win]
z.censored <- z[!is_win]
dzdl.censored <- -exp(dnorm(z.censored, log = TRUE) - pnorm(z.censored, log.p = TRUE))
dzdl <- z
dzdl[!is_win] <- dzdl.censored
(m %*% dzdl) / sigma + c(0, tail(w, -1))
}
r.w <- optim(start, f.w, g.w, method = "L-BFGS-B", control = list(maxit = ifelse(interactive(), 100, 20000), trace = ifelse(interactive(), 1, 0)))
list(predict = function(m) r.w$par %*% m, r = r.w)
}
mseloss <- function(y, y.hat) {
mean((y - y.hat)^2)
}
apply_win_loose <- function(df) {
df.win <- dplyr::filter(df, is_win) %>% as.data.frame
df.loose <- dplyr::filter(df, !is_win) %>% as.data.frame
function(f, ...) {
list(all = f(df, ...), win = f(df.win, ...), loose = f(df.loose, ...))
}
}
do_exp <- function (model1, model_name) {
# browser()
loginfo("processing exp with model:%s", model_name)
m1 <- apply_f(hashed.model.matrix, formula = model1, hash.size = 2^20, transpose = TRUE, is.dgCMatrix = FALSE)
m1.next <- apply_f.next(hashed.model.matrix, formula = model1, hash.size = 2^20, transpose = TRUE, is.dgCMatrix = FALSE)
for(name in c("all", "win", "loose")) {
loginfo("mse of averaged observed y at training on data %s is %f", name, mseloss(y[[name]], mean(y$win)))
loginfo("mse of averaged observed y at testing on data %s is %f", name, mseloss(y.next[[name]], mean(y$win)))
}
{ # lm on win
.start <- rep(0, nrow(m1$win));.start[1] <- mean(y$win)
progressive.cv <- list()
for(lambda2 in c(1000, 2000)) {
l.win_lm <- linear_regression(m1$win, y$win, lambda2, start = .start)
loginfo("lambda2: %d", lambda2)
for(name in c("all", "win", "loose")) {
loginfo("mse of lm (winning bids) at training on data %s is %f", name, mseloss(y[[name]], l.win_lm$predict(m1[[name]])))
loginfo("mse of lm (winning bids) at testing on data %s is %f", name, mseloss(y.next[[name]], l.win_lm$predict(m1.next[[name]])))
lm.pre <- l.win_lm$predict(m1[[name]])
loginfo("average winning price of lm (winning bids) at training on data %s is %f", name, sum(lm.pre)/length(lm.pre))
lm.prenext <- l.win_lm$predict(m1.next[[name]])
loginfo("average winning price of lm (winning bids) at testing on data %s is %f", name, sum(lm.prenext)/length(lm.prenext))
linStaAUC <- data.frame(payp=c(y[[name]]), wp = c(l.win_lm$predict(m1[[name]])))
linwinNum <- with(linStaAUC,linStaAUC[payp < wp, ])
loginfo("accuracy winning price of lm (winning bids) at training on data %s is %f", name, nrow(linwinNum)/nrow(linStaAUC))
}
progressive.cv[[paste(lambda2)]] <- mseloss(y.next[["all"]], l.win_lm$predict(m1.next[["all"]]))
}
lambda2 <- unlist(progressive.cv) %>% which.min %>% names %>% as.numeric
loginfo("lambda2: %d", lambda2)
l.win_lm <- linear_regression(m1$win, y$win, lambda2, start = .start)
# save(l.win_lm, file=Args[8])
# saveRDS(l.win_lm,sprintf(Args[8]))
# saveRDS(l.win_lm,sprintf("lm.26model.Rds"))
}
{ # lm on loose
.start <- l.win_lm$r$par
l.loose_lm <- linear_regression(m1$loose, y$loose, lambda2 = lambda2, start = .start)
for(name in c("all", "win", "loose")) {
loginfo("mse of lm (losing bids) at training on data %s is %f",name, mseloss(y[[name]], l.loose_lm$predict(m1[[name]])))
loginfo("mse of lm (losing bids) at testing on data %s is %f", name, mseloss(y.next[[name]], l.loose_lm$predict(m1.next[[name]])))
}
loginfo("the mean of the absolute difference between lm on win and loose is: %f", mean(abs(l.win_lm$r$par - l.loose_lm$r$par)))
}
y.observed <- y$all
y.observed[!bidimpclk$is_win] <- bid$loose
{ # clm without sigma
.start <- l.win_lm$r$par
l.clm2 <- censored_regression2(m1$all, y.observed, bidimpclk$is_win, sigma = sd(y$win), lambda2, .start)
# saveRDS(l.clm2,sprintf("clm.26model.Rds"))
# saveRDS(l.clm2,sprintf(Args[9]))
# save(l.clm2, file =Args[9])
for(name in c("all", "win", "loose")) {
loginfo("mse of clm with sigma at training on data %s is %f", name, mseloss(y[[name]], l.clm2$predict(m1[[name]])))
loginfo("mse of clm with sigma at testing on data %s is %f", name, mseloss(y.next[[name]], l.clm2$predict(m1.next[[name]])))
clm.pre <- l.clm2$predict(m1[[name]])
loginfo("average winning price of clm with sigma at training on data %s is %f", name, sum(clm.pre)/length(clm.pre))
clm.prenext <- l.clm2$predict(m1.next[[name]])
loginfo("average winning price of clm with sigma at testing on data %s is %f", name, sum(clm.prenext)/length(clm.prenext))
cenStaAUC <- data.frame(payp=c(y[[name]]), wp = c(l.clm2$predict(m1[[name]])))
cenwinNum <- with(cenStaAUC,cenStaAUC[payp < wp, ])
loginfo("accuracy winning price of clm with sigma at training on data %s is %f", name, nrow(cenwinNum)/nrow(cenStaAUC))
}
}
{ # lm + clm with wr as weighted
l.lm_clm2 <- function(l.lm, l.clm2) {
function(m, wr) {
wr * l.lm$predict(m) + (1 - wr) * l.clm2$predict(m)
}
}
f <- l.lm_clm2(l.win_lm, l.clm2)
for(name in c("all", "win", "loose")) {
loginfo("mse of mixing lm and clm at training on data %s is %f", name, mseloss(y[[name]], f(m1[[name]], wr[[name]])))
loginfo("mse of mixing lm and clm at testing on data %s is %f", name, mseloss(y.next[[name]], f(m1.next[[name]], wr.next[[name]])))
mix.pre <- f(m1[[name]], wr[[name]])
loginfo("average winning price of mixing lm and clm with sigma at training on data %s is %f", name, sum(mix.pre)/length(mix.pre))
mix.prenext <- f(m1.next[[name]], wr.next[[name]])
loginfo("average winning price of mixing lm and clm with sigma at testing on data %s is %f", name, sum(mix.prenext)/length(mix.prenext))
StaAUC <- data.frame(payp=c(y[[name]]), wp = c(f(m1.next[[name]], wr.next[[name]])))
winNum <- with(StaAUC,StaAUC[payp < wp, ])
loginfo("accuracy winning price of mixing lm and clm with sigma at training on data %s is %f", name, nrow(winNum)/nrow(StaAUC))
}
}
# list(l.win_lm, l.loose_lm, l.clm, l.clm2)
list(l.win_lm, l.loose_lm, l.clm2)
}
# Args <- commandArgs()
bidimpclk <- read.table("newbid.2015-09-10.txt",header=TRUE,sep = "\t")
# bidimpclk <- read.table(Args[6],header=TRUE,sep = "\t")
model1 <- ~ days + hours + exchange_id + app_id + publiser_id + bidfloor + w + h + os +
Osv + model + connectiontype + country + ua + carrier + js + user + carriername +
split(app_cat,delim =",") + split(btype,delim =",") + split(mimes,delim =",") + split(badv,delim =",") + split(bcat,delim =",")
formula <- ~ days + hours + exchange_id + app_id + publiser_id + bidfloor + w + h + os + Osv + model + connectiontype + country + ua + carrier + js + user + carriername + split(app_cat,delim =",") + split(btype,delim =",") +
split(mimes,delim =",") + split(badv,delim =",") +
split(bcat,delim =",")
m.train <- hashed.model.matrix(formula, bidimpclk, 2^20)
m.test <- m.train
cv.g.lr <- cv.glmnet(m.train, bidimpclk$is_win, family = "binomial")#, type.measure = "auc")
# saveRDS(cv.g.lr, sprintf(Args[7]))
p.lr <- predict(cv.g.lr, m.test, s="lambda.min", type = "response")
sprintf("************** win rate statistic************************")
AcuWin <- auc(bidimpclk$is_win, p.lr)
AveWr <- sum(p.lr)/nrow(p.lr)
loginfo("Average Win rate is : %s", AveWr)
loginfo("Accuracy win rate is : %s", AcuWin)
tmp <- cbind(bidimpclk,wr=c(p.lr))
bidimpclk$wr <- tmp$wr
apply_f <- apply_win_loose(bidimpclk)
wr <- apply_f(`[[`, "wr")
y <- apply_f(`[[`, "payingprice")
bid <- apply_f(`[[`, "bid_price") %>% lapply(`*`, 0.5)
#lapply(bid, `*`, 0.5)
# bidimpclk.next <- read.table("newbid.2015-09-10.txt", header=TRUE,sep="\t")
bidimpclk.next <- bidimpclk
# predict.next <- hashed.model.matrix(formula, bidimpclk.next, 2^20)
# p.lrnext <- predict(cv.g.lr, predict.next, s="lambda.min", type = "response")
p.lrnext <- p.lr
tmp.next <- cbind(bidimpclk.next,wr=c(p.lrnext))
bidimpclk.next$wr <- tmp.next$wr
apply_f.next <- apply_win_loose(bidimpclk.next)
y.next <- apply_f.next(`[[`, "payingprice")
wr.next <- apply_f.next(`[[`, "wr")
sprintf("****** do simulation of winning price statistic*********")
r1 <- do_exp(model1, "model with wr")
sprintf("****************** finish statistic ********************")
<file_sep>/php-example/decode_nice.php
<?php
echo "<form action='decode_nice.php' method='get'>";
echo "Input json log: <input type='text' name='req' />";
echo "<input type='submit' name='sub' value='submit'/>";
echo "</form>";
if(isset($_GET["sub"])){
$req=$_GET["req"];
echo $req;
echo "<br />";
// $jsonreq = var_dump(json_decode($req,TRUE));
$jsonreq = json_decode($req,TRUE);
echo $jsonreq;
echo "<br>";
print_r($jsonreq);
echo "<br>";
print_r($jsonreq["json"]);
$data = $jsonreq["json"];
echo "<br>";
echo "<br>";
print_r($data);
echo "<br>";
echo "<br>";
$output = json_decode($data,TRUE);
print_r($output);
$data=array_merge($jsonreq,$output);
echo "<br>";
echo "<br>";
print_r($data);
echo "<br>";
echo "<br>";
echo "<br>";
if (json_last_error() === JSON_ERROR_NONE) {
echo "true"; //do something with $json. It's ready to use
} else {
echo "false";//yep, it's not JSON. Log error or alert someone or do nothing
}
}
// // http://www.php.net/manual/en/function.json-decode.php#95782
// function json_decode_nice($json, $assoc = FALSE){
// $json = str_replace(array("\n","\r"),"",$json);
// $json = preg_replace('/([{,]+)(\s*)([^"]+?)\s*:/','$1"$3":',$json);
// $json = preg_replace('/(,)\s*}$/','}',$json);
// return json_decode($json,$assoc);
// }
?>
| d75069e9cafc74c591662c148c4571563480da46 | [
"Markdown",
"R",
"PHP",
"Shell"
] | 22 | R | snakecy/R-Projects | efc6e6dcb42d3b11daac0c5ac2d7fcd2a6b6bf7d | de838ed2611efb162e176bb495945af92e304017 |
refs/heads/master | <repo_name>lpcuellar/web-2020<file_sep>/ejemplos_django/example/owners/views.py
from django.shortcuts import render
from guardian.shortcuts import assign_perm
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework import status
from django.core.exceptions import PermissionDenied
from permissions.services import APIPermissionClassFactory
from owners.models import Owner
from owners.serializers import OwnerSerializer
class OwnerViewSet(viewsets.ModelViewSet):
queryset = Owner.objects.all()
serializer_class = OwnerSerializer
permission_classes = (
APIPermissionClassFactory(
name='OwnerPermission',
permission_configuration={
'bases':{
'create': True,
'list': True,
},
'instance': {
'retrieve': True,
'desrtoy': True,
'update': True,
'partial_update': True,
'delete': True,
}
},
),
)<file_sep>/ejemplos_redux/src/sagas/petOwner.js
import {
call,
takeEvery,
put,
// race,
// all,
delay,
select,
} from 'redux-saga/effects';
import { v4 as uuid } from 'uuid'
import * as selectors from '../reducers';
import * as actions from '../actions/petOwners';
import * as types from '../types/petOwners';
const API_BASE_URL = 'http://localhost:8000/api/v1';
function* fetchPetOwners(actions) {
try {
const isAuth = yield select(selectors.isAuthenticated);
if(isAuth){
const token = yield select(selectors.isAuthenticated);
const response = yield call (
fetch,
`${API_BASE_URL}/owners/`,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `JWT ${token}`,
},
}
);
if(response.status === 200) {
let entities = {};
let order = [];
const info = yield response.json();
info.forEach( owner => {
const id = uuid();
entities = {...entities, [id]: owner,}
order = [...order, id]
});
yield put(actions.completedFetchingPetOwners(entities, order));
}
}
} catch(error) {
yield put(actions.failedFetchdingOwner('Ha sucedido un error!'));
}
}
function* addPetOwner(action) {
try{
const isAuth = yield select(selectors.isAuthenticated);
if(isAuth){
const token = yield select(selectors.isAuthenticated);
const response = yield call (
fetch,
`${API_BASE_URL}/owners/`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `JWT ${token}`,
},
}
);
if(response.status === 201) {
yield put(actions.completedAddingPetOwner(action.payload.id, action.payload));
} else {
const { non_field_errors } = yield response.json();
yield put(actions.failedAddingOwner(action.payload.id, non_field_errors[0]));
}
}
} catch (error) {
console.log(error);
yield put(actions.failedAddingOwner(action.payload.id, 'Ha sucedido un error!'))
}
}
function* removePetOwner(action) {
try{
const isAuth = yield select(selectors.isAuthenticated);
if(isAuth){
const token = yield select(selectors.isAuthenticated);
const response = yield call (
fetch,
`${API_BASE_URL}/owners/`,
{
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
'Authorization': `JWT ${token}`,
},
}
);
if(response.status === 204) {
yield put(actions.completedRemovingPetOwner());
} else {
const { non_field_errors } = yield response.json();
yield put(actions.failedAddingOwner(action.payload.id, non_field_errors[0]));
}
}
} catch (error) {
console.log(error);
yield put(actions.failedAddingOwner(action.payload.id, 'Ha sucedido un error!'));
}
}
export function* watchFetchPetOwners() {
yield takeEvery(
types.PET_OWNERS_FETCH_STARTED,
fetchPetOwners,
);
}
export function* watchAddPetOwner() {
yield takeEvery(
types.PET_OWNER_ADD_STARTED,
addPetOwner,
);
}
export function* watchRemovePetOwner() {
yield takeEvery(
types.PET_OWNER_REMOVE_STARTED,
removePetOwner,
);
} | ee03c9bd0d071ce9f993aa07156a72bf67c0ff5a | [
"JavaScript",
"Python"
] | 2 | Python | lpcuellar/web-2020 | 9cadf5bbcd4837252ee916fe4b99b6cb76b8eeb3 | 8cbe50bc92ce7e0b867fd30eca173fb78fbf2deb |
refs/heads/master | <file_sep>'''
Created on Jan 29, 2017
@author: saldivar
'''
import os
from itertools import cycle
board = list(map(lambda x: '-', list(range(9))))
player = ['X', 'O']
player_next = cycle(player)
# Uncomment for console
clear = lambda: os.system("clear")
def print_board():
for p in reversed(range(0,9,3)):
print(board[p] + ' ' + board[p + 1] + ' ' + board[p + 2])
def draw_player_option(player_option, number):
if check_free_space(number):
board[number - 1] = player_option
return True
else:
return False
def reset_board():
global board
board = list(map(lambda x: '-', list(range(9))))
def is_full():
for i in board:
if i == '-':
return False
else:
return True
def check_free_space(number):
if board[number - 1] == '-':
return True
else:
return False
def check_win():
# Horizontal Check and Vertical Check
for count,p in enumerate(range(0,9,3)):
if (board[p] == board[p + 1] == board[p + 2] and board[p] != '-') or (board[count] == board[count + 3] == board[count + 6] and board[count] != '-'):
return True
# Horizontal Check
if (board[0] == board[4] == board[8] and board[0] != '-') or (board[2] == board[4] == board[6] and board[2] != '-'):
return True
return False
def input_number():
while True:
try:
number = int(input("Input a number between 1 and 9 on the key pad: "))
if number in range(1,10):
break
else:
print('Number not in range')
except:
print ('Not a number')
return number
def play_again():
while True:
restart = input('Play again? Y or N: ')
if restart in ('Y','y'):
return True
elif restart in ('N','n'):
return False
else:
print('invalid answer')
def display_turn(player):
print('Player ' + player)
def start_game():
reset_board()
while not check_win() and not is_full():
clear()
print_board()
player = next(player_next)
display_turn(player)
number = input_number()
while not draw_player_option(player, number):
number = input_number()
else:
print_board()
if check_win():
print('Player ' + player + ' win')
elif is_full():
print('Board is Full')
if play_again():
start_game()
start_game() | a352fe4e6c059c963cb5886b66fc11d6dfb17b5a | [
"Python"
] | 1 | Python | j7saldivar/python-tic-tac-toe | 7a15779bde0d6be4c620c06832a00ddc0c720e29 | f7e7705f02b483f8f1dcb6e15092cbdc56b597d5 |
refs/heads/master | <repo_name>RhadMax/Psychic-Game<file_sep>/README.md
# Psychic-Game
This was the irst javascript homework assignment for UCSD Extension coding bootcamp. We were tasked with creating a site where the user is asked to take guesses at a letter of the alphabet chosen at random with each play. The user starts with 10 guesses and if the letter isn't guessed correctly they lose the game and may play again. The game will keep track of wins and losses. I chose to pay homage to a Sega Genesis title from my childhood with the theme I created, namely Shining Force II. I also made use of sound clips and music from the game which I was able to find online.
To view the app on github pages use this link: https://rhadmax.github.io/Psychic-Game/
<file_sep>/assets/javascript/game.js
var computerChoices = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
// var computerChoices = ['a', 'b']
var winsCounter = document.getElementById("winsCounter");
var lossesCounter = document.getElementById("lossesCounter");
var userGuessText = document.getElementById("userGuess");
var guessCounter = document.getElementById("guessCounter");
var alerter = document.getElementById("alerting");
var wins = 0
var losses = 0
var guessesLeft = 9
var taunts = ["Haha, not that one!", "Nope! Keep guessing!", "Ha! Some hero you are.", "Goblins guess better!", "Hee hee hee, try again!", "You'll never win like this!", "Your chances dwindle...", "I'll soon win!!", "I would never choose that!", "You will never win!", "Magic guards my mind"]
// function toggleMute() {
// var music = $("#music");
// console.log(music);
// music.unMute();
// }
var winAudio = new Audio("assets/images/victory.mp3");
winAudio.volume = .3;
var lossAudio = new Audio("assets/images/defeat.mp3");
lossAudio.volume = .2;
var soundsToggle = document.getElementById("soundStatus");
soundsToggle.textContent = "-On-";
document.onkeyup = function (event) {
taunt = taunts[Math.floor(Math.random() * taunts.length)];
var userGuess = event.key;
if (guessesLeft === 9) {
window.computerGuess = computerChoices[Math.floor(Math.random() * computerChoices.length)];
guessesLeft--;
}
if (guessesLeft > 0 && guessesLeft < 9 && userGuess === window.computerGuess) {
wins++;
guessesLeft = 9;
// console.log("Computer chose letter: " + computerGuess);
// console.log("Player chose letter: " + userGuess);
// console.log("You Won! Let's play again.");
// alert("You Won! Let's play again.");
alerter.textContent = "Dang! You guessed it!";
winAudio.play();
} else if (guessesLeft === 8 && userGuess !== window.computerGuess) {
guessesLeft--;
// console.log("Computer chose letter: " + computerGuess);
// console.log("Player chose letter: " + userGuess);
// console.log("Player has " + (guessesLeft + 1) + " guesses left.");
alerter.textContent = taunt;
} else if (guessesLeft > 0 && guessesLeft < 8 && userGuess !== window.computerGuess) {
guessesLeft--;
// console.log("Computer chose letter: " + computerGuess);
// console.log("Player chose letter: " + userGuess);
// console.log("Player has " + (guessesLeft + 1) + " guesses left.");
alerter.textContent = taunt;
} else if (guessesLeft === 0 && userGuess !== window.computerGuess) {
guessesLeft--;
losses++;
// console.log("You ran out of guesses. You lose!");
guessesLeft = 9;
alerter.textContent = "Tee hee hee! I win!";
lossAudio.play();
// alert("You Lost! Let's play again.")
}
winsCounter.textContent = " " + wins + " ";
lossesCounter.textContent = " " + losses + " ";
if (guessesLeft === 9) {
userGuessText.textContent = "...";
} else {
userGuessText.textContent += (userGuess + ", ");
}
if (guessesLeft === 9) {
guessCounter.textContent = " " + guessesLeft + " ";
} else {
guessCounter.textContent = " " + (guessesLeft + 1) + " ";
}
}
$("h3").click(function () {
if (soundsToggle.textContent == "-On-") {
winAudio.volume = 0;
lossAudio.volume = 0;
console.log("sound muted");
soundsToggle.textContent = "-Off-"
} else {
winAudio.volume = .3;
lossAudio.volume = .2;
console.log("sound unmuted");
soundsToggle.textContent = "-On-"
}
}); | 3381fab19e07201ddd2018075f941d0b87628314 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | RhadMax/Psychic-Game | a0da564847363a05996601d6464a45b343829865 | 54edcfd2c522b2d3dd84f27f24f94399cf19bf87 |
refs/heads/master | <repo_name>Dauphine-M1-Java-20/td00-brulej<file_sep>/td00/src/test/java/fr/dauphine/ja/brulejeremie/td00/PrimeCollectionTest.java
package fr.dauphine.ja.brulejeremie.td00;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class PrimeCollectionTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public PrimeCollectionTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( PrimeCollectionTest.class );
}
/**
* Rigourous Test :-)
*/
public void testPrimeCollection()
{
assertTrue( true );
}
public void test0IsPrime() {
PrimeCollection collec = new PrimeCollection();
assert(collec.isPrime(0));
}
public void testTwoIsPrime() {
PrimeCollection collec = new PrimeCollection();
assert(collec.isPrime(2));
}
public void test9IsNotPrime() {
PrimeCollection collec = new PrimeCollection();
assert(!collec.isPrime(9));
}
}
| 73b5e6d43fb8349d75de506ad491dd3b895a53ee | [
"Java"
] | 1 | Java | Dauphine-M1-Java-20/td00-brulej | 28a034b7b90de4aea86ddd3f51f554d7761433f1 | 70bbccc92be4e17e0b3119ba1f8fcc19871456fa |
refs/heads/master | <file_sep>#include<iostream>
#include<climits>
#include<vector>
#include"student.h"
#include"timetable.h"
#include"submission.h"
using namespace std;
student::student()
{
cout<<"Enter the number of students in the class";cin>>size;
while(cin.fail())
{
cin.clear();
cin.ignore(INT_MAX, '\n'); // ignore last input
cout << "You can only enter numbers.\n";
cout << "ENTER the number of student again.\n";
cin >>size;
}
s.resize(size);
}
void student::get_info()
{
cout<<"Enter the details of the student";
for(int i=0;i<size;i++)
{
cin.ignore();
cout<<"Name";getline(cin,s[i].name);
cout<<"Class";getline(cin,s[i].cls);
}
}
void student::get_info(int rn)
{
cout<<"Enter your details=>"<<endl;
{ cin.ignore();
cout<<"Contact details =>";getline(cin,s[rn].cont);
cout<<"Address =>";getline(cin,s[rn].address);
}
cout<<endl;
}
void student::display()
{
for(int i=0;i<size;i++)
{
cout<<s[i].name<<" "<<s[i].cls<<" ";
cout<<s[i].cont<<" "<<s[i].address<<" "<<s[i].address<<endl;
}
}
void student::display(int rn)
{
cout<<s[rn].name<<" "<<s[rn].cls<<" "<<s[rn].cont<<" "<<s[rn].address<<" "<<s[rn].atd<<endl;
}
bool student::check(int rn)
{
if(rn<s.size())
return true;
else
return false;
}
/*char* student::create_new()
{
char *s;
cin.ignore();
cout<<"Enter the name of the file";
getline(cin,*s);
fstream *fs=new fstream(*s);
return *s;
}
*/
void stud_menu(int rn,student s1)
{
cout<<"******MENU********";
cout<<"Select your choice";
cout<<"1:Edit info \n 2:View info \n 3:Check Attendance\n 4:View timetable\n 5:Check submission\n "<<endl;
int cho;//choice
cin>>cho;
switch(cho)
{
case 1:s1.get_info(rn);break;
case 2:s1.display(rn);break;
case 3:cout<<"Work in progress";break;
case 4:tt_display();break;
case 5:stud_chsub();break;
default: cout<<"INVALID CHOICE";
}
cout<<"Do u wish to continue";
cout<<"Press 1 for yes and 0 to exit";
int x;
cin>>x;
if(x)
stud_menu(rn,s1);
else return;
}
void stud_if(student &s1)//student interface
{
cout<<"Enter the roll number of the student";
int rn;
cin>>rn;
if(cin.fail())
{
cin.ignore();
}
if(s1.check(rn))
stud_menu(rn,s1);
else
cout<<"Sorry roll number is not registerd please talk to your teacher or the admin";
cout<<"Do u wish to enter the roll no again";
int x=0;//temporary variable to form the loop
do
{
cout<<"Press 1 for yes and 0 for exit";
cin>>x;
if(x==1)
stud_if(s1);
else if(x==0)
return;
else
{
cin.ignore(INT_MAX,'\n');
cout<<"Wrong input";
}
}while(x!=1&&x!=0);
}
<file_sep>#include<iostream>
#include<vector>
#include<climits>
#include"teacher.h"
#include"student.h"
#include"admin.h"
using namespace std;
void admin_if(student &s,teacher &t)
{
int check;
cout<<"*******ADMIN'S MENU*******";
do
{cout<<"\n 1:Edit students info\n 2:Edit teachers info\n 3:Send holiday notice\n 4:EXIT\n";
cin>>check;
switch(check)
{
case 1:students(s);break;
case 2:teac_(t);break;
case 3:cout<<"Working";break;
case 4:return;
default:cout<<"INVALID INPUT";break;
}
}while(1);
}
void students(student &s)
{
cout<<"Press 1:READ FROM DATA BASE ,0:OverWrite the previous data base."<<endl;
int check;
cin>>check;
if(check)
{
//s.read();
s.display();
}
else
{
s.get_info();
s.display();
}
}
void teac_(teacher &t)
{
cout<<"Press 1:READ FROM DATA BASE ,0:OverWrite the previous data base."<<endl;
int check;
cin>>check;
if(check)
//t.read();
t.display();
else
{
t.get_info();
t.display();
}
}
<file_sep>using namespace std;
class teacher
{
public:
void
}
<file_sep>#include<iostream>
#include<fstream>
using namespace std;
int main()
{
int a[2][2]={(1,2),(3,4)};
fstream f;
f.open("Try.txt",ios::out);
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
{
f<<a[i][j];f<<"\t";
}
f<<endl;
return 0;
}
<file_sep>#include<iostream>
#include<vector>
#include<climits>
void admin_if(student& ,teacher&);
void students(student& );
void teac_(teacher& );
<file_sep>/*1.A class will be a struct or object having data field : Hash table which would be all encompasing of student data, a list of teachers(along with their roles) allocated to the class, the time table of the class.
2.Hash(NOT REALLY) table will consist of the students detail along with his marks and attendance, as well as teacher review.
3.Hash(NOT REALLY) is based on roll no assignment.
4.Roll_no will be consisting of te following information
5.Class will consist of an array of all students,timetable,and list of teachers
6.Check for first time log-in or registered student,
sign-in can be throught the mail.
7.GR number generator.
8.Decide whether to read or write from excel or from sql.
9.Format output data.
10.Read from sql tables or excel tables.
*/
#include<iostream>
#include<vector>
#include<fstream>
using namespace std;
class student
{
struct details
{
string name;
int roll_no;
string phone_no;
string mail_id;
//NOTE USING HASH table use for class details where class may be stored in trees
};
fstream register_student;
vector<details> Table;
public:
student(){}
void registe()
{
register_student.open("registered student.txt",ios::app);
details temp;
cout<<"Enter the name of the student";
getline(cin,temp.name);
cout<<"Enter the phone no of the student";
getline(cin,temp.phone_no);
register_student<<temp.name<<":"<<temp.phone_no<<endl;
register_student.close();
}
void sign_in() // allowing user to sign-in or not letting them any access.
{
int set_permission=0;
do
{
string name,password;
cout<<"Enter your name";
cin>>name;
cout<<"Enter password";
cin>>password;
if(name=="admin"&&password=="<PASSWORD>")
{
cout<<"Welcome";
set_permission=1;
}
else
cout<<"Wrong password";
}while(set_permission!=1);
}
void accept()
{
cout<<"Enter the following details respectively";
string name,p_no,gr_n;
cout<<"Enter your name";
cin>>name;
cout<<"Enter your phone number";
cin>>p_no;
cout<<"Enter your GR number";
cin>>gr_n;
}
void display()
{
cout<<"The details are as follows:\n";
cout<<"Name: "<<"\tGR.NO: "<<"\tPhone number\n";
cout<<"Rahul: "<<"\t17u652: "<<"\t9867275096\n";
}
void edit() // allow a person to edit the detail
{}
void change_password() // allows user to change the password.
{
}
};
int main()
{
student s;
//s.sign_in();
//s.accept();
//s.display();
s.registe();
return 0;
}
<file_sep>#include<isotream>\
#include<fstream>
using namespace std;
class student()
{
struct data()
{
string name, roll_no, address;
};
vector<data> Table;
public:
void copy(string s)
{
data temp;
string t;
int i=0;
while(s[i]!='\0')
{
while(s[i]!=':')
{
t+=s[i];
i++;
}
temp.name+=t;
i++;
t
while(s[i])
}
}
void read()
{
fstream file;
string s="",temp;
int i=0;
file.open("Student.txt",ios::in);
while(getline(file,s)
{
copy(s);
}
}
}
int main()
{}
<file_sep>#include<iostream>
#include<fstream>
#include<cstring>
using namespace std;
void teach_setsub()
{int sub;
cout<<"Please enter 1 ahead of student roll number is the submission is done and 0 if not done(serially)\n";
ofstream fout("aaa.txt",ios::out);//opening the file where the teacher will write
for(int i=0;i<5;i++)
{
cout<<"\n"<<i+1<<".\t";
cin>>sub;
fout<<sub<<" ";
}
fout.close();
}
void stud_chsub()
{int roll_no;
cout<<"Please enter your roll number to check if you've done the submission\n";
cin>>roll_no;
ifstream fin("aaa.txt");//reading from the file for the display
int temp=1,flag=0;
string s;
fin>>s;
while(fin.good())
{
if(temp==roll_no)
{
flag=1;
if(s.compare("1")==0)
cout<<"\nSubmission done.";
else
cout<<"\nSubmission not done.(You won't get the noc)";
break;
}
temp++;
fin>>s;
}
if(flag==0)
{
cout<<"\nInvalid roll entered....";
}
}
<file_sep>
void teach_setsub();
void stud_chsub();
<file_sep>#include<iostream>
#include<cstring>
#include<climits>
#include<vector>
#include<fstream>
using namespace std;
class teacher
{
int size=0;
struct teach
{
string name;
int review; //review by students
string cab_no;
string cont;
string address;
string spec;
};
vector<teach> t;
fstream f1;
public:
teacher();
void get_info();
void get_info(int);
void display();
void display(int);
bool check(int);
void save();
int review(int);
};
void teach_menu(teacher&, int);
void teach_if(teacher&);
<file_sep>#include<iostream>
#include<climits>
#include<vector>
#include<fstream>
#include"teacher.h"
#include"submission.h"
using namespace std;
template<class t>
inline void check(t &t1)
{
do
{
cin.clear();
cin.ignore(INT_MAX,'\n');
cin>>t1;
}while(cin.fail());
}
teacher::teacher()
{
cout<<"Enter the no of teachers";
cin>>size;
t.resize(size);
}
void teacher:: get_info()
{
cout<<"Enter the details of the teachers";
for(int i=0;i<size;i++)
{
cin.ignore();
cout<<"Name";getline(cin,t[i].name);
// cout<<"Contact details";getline(cin,t[i].cont);
// cout<<"Address";getline(cin,t[i].address);
cout<<"Enter the cabinet number of the teacher";
getline(cin,t[i].cab_no);
cout<<"Specialization of the teacher";getline(cin,t[i].spec);
t[i].review=0;
cout<<endl;
}
/* int x;
cout<<"DO U WANT TO SAVE THE ENTRIES(1-for yes 0-for no)";
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cin>>x;*/
}
void teacher::get_info(int id)
{
cout<<"Enter your details"<<endl;
cin.ignore();
cout<<"Name";getline(cin,t[id].name);
cout<<"Contact details";getline(cin,t[id].cont);
cout<<"Address";getline(cin,t[id].address);
/* cout<<"Enter the cabinet number of the teacher";
getline(cin,t[i].cab_no);*/
cout<<"Your Specialization";getline(cin,t[id].spec);
cout<<endl;
}
void teacher::display()
{
for(int i=0;i<size;i++)
{
cout<<"DETAILS OF ALL THE TEACHERS =>";
cout<<t[i].name<<" "<<t[i].cab_no<<" "<<t[i].spec<<" "<<t[i].cont;
}
}
void teacher::display(int rn)
{
cout<<"DETAILS OF ALL THE TEACHERS =>";
cout<<t[rn].name<<" "<<t[rn].cab_no<<" "<<t[rn].spec<<" "<<t[rn].cont;
}
bool teacher:: check(int id)
{
if(id<t.size())
return true;
else
return false;
}
void teacher::save()
{
fstream f;
f.open("teachers.txt");
while(f)
{
for(int i=0;i<t.size(); i++)
f<<i<<"\t"<<t[i].name<<"\t"<<t[i].cab_no<<"\t"<<t[i].cont<<"\t"<<t[i].address<<"\t"<<t[i].spec<<"\t"<<t[i].review<<endl;
break; }
f.close();
return;
}
//friend void attendance();
int teacher::review(int r)
{if(r!=1)
{
cout<<"Enter the rating of the teacher out of 10";
for(int i=0;i<t.size();i++)
{int review;
do{
cin>>review;
if(cin.fail())
check(review);
}while(0>review||review>10);
if(t[i].review==0)
t[i].review=review;
else
t[i].review=(t[i].review+review)/2;
}
return 1;
}
else if(r==1)
{cout<<"Review already completed";return 1;}
}
void teach_menu(teacher &t,int id)
{
int cho,x;
cout<<"***TEACHERS MENU***"<<endl;
cout<<"Select your choice"<<endl;
do{
cout<<"\n 1:VIEW YOUR DETAILS\n 2:EDIT YOUR DETAILS\n 3:TAKE ATTENDANCE\n 4:Update subission status\n 5:EXIT"<<endl;
cin>>cho;
if(cin.fail())
check(cho);
else if(!cin.fail())
switch(cho)
{
case 1:t.display(id);break;
case 2:t.get_info(id);break;
case 3://t.attendance(id);
cout<<"Working";break;
case 4:teach_setsub();break;
case 5:{cout<<"DO you want to save the changes before leaving press 1:Save&Exit 0:Exit withouy saving";
cin.ignore();
cin>>x;
// if(cin.fail())
// check(x);
if(x)
{t.save();return;}
else
return;
}
default:cout<<"Enter a valid input";
}
}while(cho!=4);
}
void teach_if(teacher &t1)
{
int id;
cout<<"Enter your teachers id no=";
cin>>id;
if(cin.fail())
check(id);
if(t1.check(id))
teach_menu(t1,id);
else
return;//corr(t1);//correction
}
<file_sep>class data{
string name;
string roll_no;
string phone_no;
string mail_id;
friend class student;
public:
data():name("-1"),roll_no("-1"),phone_no("-1"),mail_id("-1"){}
friend istream & operator>>(istream &in,data &s) //Final for printing the data and reading the entire data at one time
{
cout<<"Enter the name: ";
getline(in,s.name);
cout<<"Enter the roll_no: ";
in>>s.roll_no;
cin.ignore();
cout<<"Enter the phone_no: ";
getline(in,s.phone_no);
cout<<"Enter the mail_id: ";
getline(in,s.mail_id);
return in;
}
friend ostream & operator<<(ostream &out,data &s)//works fine though edit the way it is wriiten in output file as reading misbehaves.
{
out<<"Name: "<<s.name<<"\nRoll_no: "<<s.roll_no<<"\nPhone NUmber: "<<s.phone_no<<"\nEmail id: "<<s.mail_id<<endl<<endl;
return out;
}
void read(string temp)
{
stringstream inter(temp);
if(getline(inter,name,':'))
if(getline(inter,roll_no,':'))
if(getline(inter,phone_no,':'))
if(getline(inter,mail_id,':'));
}
int save()
{
int temp;
fstream file;
file.open("studentlist.txt",ios::app);
temp=file.tellg();
file<<name<<":"<<roll_no<<":"<<phone_no<<":"<<mail_id<<":"<<endl;
file.close();
return temp;
}
};
<file_sep>#include"Student.h"
using namespace std;
data::data():name("-1"),roll_no("-1"),phone_no("-1"),mail_id("-1"){}
istream & operator>>(istream &in,data &s) //Final for printing the data and reading the entire data at one time
{
cin.ignore();
cout<<"Enter the name: ";
getline(in,s.name);
cout<<"Enter the roll_no: ";
in>>s.roll_no;
cin.ignore();
cout<<"Enter the phone_no: ";
getline(in,s.phone_no);
cout<<"Enter the mail_id: ";
getline(in,s.mail_id);
return in;
}
ostream & operator<<(ostream &out,data &s)//works fine though edit the way it is wriiten in output file as reading misbehaves.
{
out<<"Name: "<<s.name<<"\nRoll_no: "<<s.roll_no<<"\nPhone NUmber: "<<s.phone_no<<"\nEmail id: "<<s.mail_id<<endl<<endl;
return out;
}
void data::read(string temp)
{
stringstream inter(temp);
if(getline(inter,name,':'))
if(getline(inter,roll_no,':'))
if(getline(inter,phone_no,':'))
if(getline(inter,mail_id,':'));
}
int data::save()
{
int temp;
fstream file;
file.open("studentlist.txt",ios::app);
temp=file.tellg();
file<<name<<":"<<roll_no<<":"<<phone_no<<":"<<mail_id<<":"<<endl;
file.close();
return temp;
}
// an object of the class represents a class of students with maximum of 80 students
student::student()
{
string temp;
file.open("studentlist.txt");
do
{
index.push_back(file.tellg());
}while(getline(file,temp));
file.close();
}
void student::dis() //successfully indexed
{
file.open("studentlist.txt");
int i=0;
string temp;
data d;
while(i<index.size())
{
file.seekg(index[i]);
if(getline(file,temp))
{
d.read(temp);
cout<<d;
i++;
}
else
break;
}
}
/* void accept()
{
data temp;
cin>>temp;
Table.push_back(temp);
}*/
void student::accept_registration() //to register a student
{
data temp;
cin>>temp;
index.push_back(temp.save()+1);
}
data student::search()//works perfectly properly constructs an object and returns it after succesffuly reading from a file.
{
int roll_no;
cout<<"Enter your roll no";
cin>>roll_no;
if(roll_no<index.size())
{
string s;
fstream file;
file.open("studentlist.txt");
file.seekg(index[roll_no-1],ios::beg);
data temp;
getline(file,s);
temp.read(s);
file.close();
//cout<<temp;
return temp;
}
else
{ data temp;
return temp;
}
}
void student_interface()
//int main()
{
student s;
int choice;
do{
cout<<"Enter your choice;";
cout<<"\n1.Register a student \n2.Search for a student \n3.Display \n4.Exit";
cin>>choice;
switch(choice)
{
//s.dis(); //verified working
case 1:s.accept_registration();break;// registers a student into the student list.
case 2:s.search();break;
case 3:s.dis();break;
case 4:return;
default:cout<<"Enter the correct option";
}
}while(1);
}
<file_sep>#include<iostream>
using namespace std;
int main()
{
do {
cout<<"Select \n1.Admin \n2.Teacher \n3.Student \n4.Exit. \n";
int cho;
cin>>cho;
switch (cho)
{
case 1:cout<<"Admin is being worked on.\n";break;
case 2:cout<<"Teacher is being workerd on.\n";break;
case 3:cout<<"Student is being worked on.\n";break;
case 4:return 0;break;
default:cout<<"Enter the correct value";break;
}
} while(1);
}
<file_sep>#include<iostream>
#include<fstream>
#include<vector>
#include<sstream>
using namespace std;
//class student;
class data{
string name;
string roll_no;
string phone_no;
string mail_id;
friend class student;
public:
data();
friend ostream & operator <<(ostream &out,data &s);
friend istream & operator>>(istream &in,data &s);
void read(string temp);
int save();
};
data::data():name("-1"),roll_no("-1"),phone_no("-1"),mail_id("-1"){}
istream & operator>>(istream &in,data &s) //Final for printing the data and reading the entire data at one time
{ //Eliminate new line from the istream
cout<<"Enter the name:";
getline(in,s.name);
cout<<"Enter the roll_no: ";
in>>s.roll_no;
cin.ignore();
cout<<"Enter the phone_no: ";
getline(in,s.phone_no);
cout<<"Enter the mail_id: ";
getline(in,s.mail_id);
return in;
}
ostream & operator<<(ostream &out,data &s)//works fine though edit the way it is wriiten in output file as reading misbehaves.
{
out<<"Name: "<<s.name<<"\nRoll_no: "<<s.roll_no<<"\nPhone NUmber: "<<s.phone_no<<"\nEmail id: "<<s.mail_id<<endl<<endl;
return out;
}
void data::read(string temp)
{
stringstream inter(temp);
if(getline(inter,name,':'))
if(getline(inter,roll_no,':'))
if(getline(inter,phone_no,':'))
if(getline(inter,mail_id,':'));
}
int data::save()
{
int temp;
fstream file;
file.open("teacher.txt",ios::app);
temp=file.tellg();
file<<name<<":"<<roll_no<<":"<<phone_no<<":"<<mail_id<<":"<<endl;
file.close();
return temp;
}
class teacher
{
fstream file;
vector<int> index;
public:
teacher();
void dis();
void accept_registration();
data search();
};
void teacher_interface();
teacher::teacher()
{
string temp;
file.open("teacher.txt");
do{
index.push_back(file.tellg());
}while(getline(file,temp));
file.close();
}
void teacher::dis()
{
file.open("teacher.txt");
data d;
int i=0;
string s;
while(1)
{
if(getline(file,s))
{d.read(s);
cout<<d;
}
else
{cout<<"Error";break;}
}
file.close();
}
void teacher::accept_registration()
{
data temp;
cin>>temp;
index.push_back(temp.save()+1);
}
data teacher::search()
{
int roll_no;
cout<<"Enter your roll no";
cin>>roll_no;
if(roll_no<index.size())
{
string s;
fstream file;
file.open("teacher.txt");
file.seekg(index[roll_no-1],ios::beg);
data temp;
getline(file,s);
temp.read(s);
file.close();
return temp;
}
else
{ data temp;
return temp;
}
}
int main()
{
teacher t;
data d;
t.dis();
t.accept_registration();
d=t.search();cout<<d;return 0;
}
<file_sep>#include<iostream>
#include<fstream>
#include<vector>
#include<sstream>
using namespace std;
//class student;
class data{
string name;
string roll_no;
string phone_no;
string mail_id;
friend class student;
public:
data();
friend ostream & operator <<(ostream &out,data &s);
friend istream & operator>>(istream &in,data &s);
void read(string temp);
int save();
};
class student
{
fstream file;
vector<int> index;
public:
student();
void dis();
void accept_registration();
data search();
};
void student_interface();
<file_sep>#include<iostream>
#include<cstring>
using namespace std;
struct tt
{
string sub1,sub2,sub3,sub4,rec,day,t_extra;
string days;
char t1[20],t2[20],t3[20],t4[20],t5[20];
struct tt *next;
}*start=NULL;
void create()
{
tt *n=new tt;
n->next=NULL;
strcpy(n->t1,"8:00 AM-9:00 AM");
strcpy(n->t2,"9:00 AM-10:00 AM");
strcpy(n->t3,"10:00 AM-11:00 AM");
strcpy(n->t4,"11:00 AM-12:00 NOON");
strcpy(n->t5,"12:00 NOON-1:00 PM");
if(start==NULL)
{
start=n;
}
else{
tt *temp=start;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=n;
}
}
void c7()
{
tt *n=start;
for(int i=0;i<7;i++)
{
create();
}
}
void initialize()
{
tt *n=start;
int i=0;
while(i<7)
{
if(i==0)
{
n->day="MONDAY";
n->sub1="DSGT";
n->sub2="DSLD";
n->rec="RECESS";
n->sub3="FDS";
n->sub4="OOP";
}
if(i==1)
{
n->day="TUESDAY";
n->sub1="DSLD";
n->sub2="FDS";
n->rec="RECESS";
n->sub3="COMT";
n->sub4="OOP";
}
if(i==2)
{
n->day="WEDNESDAY";
n->sub1="DSGT";
n->sub2="COMT";
n->rec="RECESS";
n->sub3="DSLD";
n->sub4="FDS";
}
if(i==3)
{
n->day="THURSDAY";
n->sub1="DSGT";
n->sub2="DSLD";
n->rec="RECESS";
n->sub3="OOP";
n->sub4="COMT";
}
if(i==4)
{
n->day="FRIDAY";
n->sub1="FDS";
n->sub2="FDS";
n->rec="RECESS";
n->sub3="DSGT";
n->sub4="COMT";
}
if(i==5)
{
n->day="SATURDAY";
n->sub1="NO LECTURES";
n->sub2="NO LECTURES";
n->rec="NO LECTURES";
n->sub3="NO LECTURES";
n->sub4="NO LECTURES";
}
if(i==6)
{
n->day="SUNDAY";
n->sub1="NO LECTURES";
n->sub2="NO LECTURES";
n->rec="NO LECTURES";
n->sub3="NO LECTURES";
n->sub4="NO LECTURES";
}
i++;
n=n->next;
}
}
void tt_display()
{c7();
initialize();
tt *temp=start;
while(temp!=NULL)
{
cout<<"\n"<<temp->day<<"\n"<<temp->t1<<"\t\t"<<temp->sub1<<"\n"<<temp->t2<<"\t"<<temp->sub2<<"\n"<<temp->t3<<"\t"<<temp->rec<<"\n"<<temp->t4<<"\t"<<temp->sub3<<"\n"<<temp->t5<<"\t"<<temp->sub4<<"\t";
temp=temp->next;
}
}
<file_sep>/*1.Admin's will need to be preconfigured
2.Privilege level.
3.Registration of a student(Call students routine).
*/
#include<iostream>
#include<vector>
#include<fstream>
#include<iomanip>
using namespace std;
class data{
string name;
string admin_id;
string phone_no;
string mail_id;
friend class admin;
public:
data():name("-1"),roll_no("-1"),phone_no("-1"),mail_id("-1"){}
friend istream & operator>>(istream &in,data &s) //Final for printing the data and reading the entire data at one time
{
cout<<"Enter the name: ";
getline(in,s.name);
cout<<"Enter the roll_no: ";
in>>s.roll_no;
cin.ignore();
cout<<"Enter the phone_no: ";
getline(in,s.phone_no);
cout<<"Enter the mail_id: ";
getline(in,s.mail_id);
return in;
}
friend ostream & operator<<(ostream &out,data &s)//works fine though edit the way it is wriiten in output file as reading misbehaves.
{
out<<"Name: "<<s.name<<"\nRoll_no: "<<s.roll_no<<"\nPhone NUmber: "<<s.phone_no<<"\nEmail id: "<<s.mail_id<<endl<<endl;
return out;
}
void read(string temp)
{
stringstream inter(temp);
if(getline(inter,name,':'))
if(getline(inter,roll_no,':'))
if(getline(inter,phone_no,':'))
if(getline(inter,mail_id,':'));
}
int save()
{
int temp;
fstream file;
file.open("studentlist.txt",ios::app);
temp=file.tellg();
file<<name<<":"<<roll_no<<":"<<phone_no<<":"<<mail_id<<":"<<endl;
file.close();
return temp;
}
};
class Admin
{
fstream admin;
vector<admin_detail> list_admin;
public:
Admin()
{
list_admin.clear();
}
void read_admin()
{
string s="";
data temp;
admin.open("Admins.txt",ios::in);
while(getline(admin,s))
{
if(s[0]!='#')//Work on comments later
{
temp=seperate(s);
list_admin.push_back(temp);
}
}
admin.close();
}
admin_detail seperate(string s)
{
admin_detail temp;
int i=0;
while(1)
{
while(s[i]!=':')
{
temp.name+=s[i];
i++;
}
i++;
temp.passwd="";
while(s[i]!='\0')
{
temp.passwd+=s[i];
i++;
}
return temp;
}
}
void register_admin()
{
admin_detail temp; // temporary variable for storing values before pushing it into the vector.
cout<<"Enter your username ";
cin>>temp.name;
cout<<"Enter the phone_no";
cin>>temp.phone_no;
list_admin.push_back(temp);
}
void display()
{ cout<<endl;
for(int i=0;i<list_admin.size();i++)
cout<<i<<"\t"<<left<<setw(10)<<list_admin[i].name<<"\t"<<list_admin[i].passwd<<endl;
}
void save()
{
admin_detail temp;
temp.name="Ra";temp.passwd="xyz";temp.phone_no="789";
admin.open("Admins.txt",ios::app);
admin<<temp.name<<":"<<temp.passwd<<":"<<temp.phone_no;
}
};
int main()
{
Admin a;
a.save();
a.read_admin();// done
a.display();//done
a.accept_admin_details();
a.display();
switch (choice)
{
case 1://Add a new admin.
case 2://Edit the admin's detail.
case 3://Registration details.
case 4://Editing the teachers details.
case 5://Editing the Students details.
case 6:return 0;
}
}
<file_sep>//file indexed well enough
#include<iostream>
#include<fstream>
#include<sstream>
using namespace std;
struct at
{
int index;
int offset;
};
int main()
{
/*string line="Hey : there: This :shit :is :crazy ";
/*stringstream check1(line);
string in;
while(getline(check1,in,':'))
{
cout<<in<<endl;
}*/
string s;
fstream file;
file.open("try.txt");
int off[5];
string temp="";
int i=0;
while(getline(file,s))
{
if(i==0)
{
off[i]=0;
}
else
off[i]=off[i-1]+temp.size()+1;
temp=s;
i++;
}
for(int i=0;i<5;i++)
{
cout<<off[i]<<endl;
}
file.close();
cout<<"1st part Done\n";
file.open("try.txt");
i=4;
s="";
while(i>=0)
{
file.seekg(off[i],ios::beg);
getline(file,s);
// if(seekg(off[i]=='\n'))
cout<<s<<"\n";
i--;
}
return 0;
}
<file_sep>//Work on an algorithm for timetable creation.
//Three solutions for the problem
//Solution number 1: Bruteforce: Pick a room when its free and check if the student and teacher are free , if yes then remove the time slot from the teacher and the student's list and add it to the final timetable.
//2.Back tracking aka picking up all possible moves and combinations trying them and coming back from the step where it goes wrong.
//3.Some shit called Genetic Algorithm.
#include<iostream>
#include<vector>
#include<utility>
using namespace std;
class timetable
{
vector<vector<string>> tt;
public:
timetable()
{
tt.resize(7);
for(int i=0;i<tt.size();i++)
tt[i].resize(5);
tt[0][0]="Sunday";
tt[1][0]="Monday";
tt[2][0]="Tuesday";
tt[3][0]="Wednesday";
tt[4][0]="Thursday";
tt[5][0]="Friday";
tt[6][0]="Saturday";
}
void display()
{
for(int i=0;i<tt.size();i++)
cout<<tt[i][0];
}
void accept()
{
cout<<"Enter the subjects and their frequency";
vector<pair<string,int>> table;
}
};
int main()
{
timetable t;
t.display();
}
<file_sep>#include "../Student/Student.h"
using namespace std;
class admin
{struct admin_data
{
string name;
string passwd;
};
admin_data def;
public:
admin()
{
def.name="admin";
def.passwd="<PASSWORD>";
}
void switch_to_student()
{
student_interface();
}
bool login()
{
admin_data temp;
cout<<"Enter the name";
cin>>temp.name;
cout<<"Enter the password";
cin>>temp.passwd;
if(temp.name==def.name&&temp.passwd==def.passwd)
return true;
else
return false;
}
};
int main()
{
admin a;
if(a.login())
a.switch_to_student();
else
return 0;
}
<file_sep>#include<iostream>
#include<vector>
#include<climits>
#include"teacher.h"
#include"student.h"
#include"admin.h"
using namespace std;
#define clr cout<<"\033[H\033[2J";
int check_password(int user)
{
string pass;
cout<<"Enter your password";
cin>>pass;
switch(user)
{
case 1:{if(pass=="<PASSWORD>")
return 1;
else
return 0;break;}
case 2:{if(pass=="<PASSWORD>")
return 1;
else
return 0;break;
}
case 3:{if(pass=="<PASSWORD>")
return 1;
else
return 0;break;
}
}
}
int main()
{
clr;
student s;
teacher t;
int check;
do
{
cout<<"1:ADMIN/ 2:STUDENT/ 3:TEACHER"<<endl;
int user;
cin>>user;
if(check_password(user))
{switch(user)
{
case 1:admin_if(s,t);break;
case 2:stud_if(s);break;//open student interface
case 3:teach_if(t);break;
default:cout<<"The input is invalid";
}
cout<<"Press 1 to continue and 0 to exit"<<endl;
cin>>check;
}
else
cout<<"Wrong password input";
cout<<"Press 1 to continue and 0 to exit";
cin>>check;
}while(check);
return 0;
}
<file_sep>
#include<iostream>
#include<cstring>
#include<climits>
#include<vector>
#include<fstream>
using namespace std;
class student
{
int size=0;
struct stud
{
string name;
int atd;//attendance
string cls;
char div;
string cont;
string pass;//<PASSWORD>
string address;
};
vector<stud> s;
public:
student();
void get_info();
void get_info(int);
void display();
void display(int);
bool check(int);
};
void stud_if(student &s);
void stud_menu(int ,student);
| 098e079eec57dbfe92e75ac0fcda6537d4bb7401 | [
"C",
"C++"
] | 23 | C++ | RahulJha06/Student_Teacher-interface | 8f55466ed8509198b765ada59ada853e87144575 | 8afe07ca59c607e1b6f479619b41abcbd42484dd |
refs/heads/master | <file_sep>/*
---
script: localize-html.js
description: Provides automatic localization of HTML nodes and attributes using strings.json $L() command
license: MIT license <http://www.opensource.org/licenses/mit-license.php>
authors:
- <NAME>
version: 1.0.0
To use, call `start_localize_html()` in your first scene's setup function.
To prevent memory leaks, `stop_localize_html()` should be called in your
first scene's cleanup function.
If using a multi-stage app, make sure to pass your stage's body element
to both functions.
Use the special x-localize attribute to trigger localization:
<div x-localize="innerHTML">Localized Text</div>
<img src="localize_text.jpg" alt="Localized Text" x-localize="alt" />
...
*/
// This starts the event listeners to localize HTML as it's loaded
var start_localize_html = function(stageBody) {
if (Object.isUndefined(stageBody)) {
var stageBody = document.body;
}
Element.extend(stageBody).observe('DOMNodeInserted', function(event) {
x_localize_html(event.relatedNode);
});
};
// This stops the event listeners for localizing HTML
var stop_localize_html = function(stageBody) {
if (Object.isUndefined(stageBody)) {
var stageBody = document.body;
}
Element.extend(stageBody).stopObserving('DOMNodeInserted');
};
// This function does all the dirty work
var x_localize_html = function(baseNode) {
// Default to searching the body
if (Object.isUndefined(baseNode)) {
var baseNode = Element.extend(document.body);
} else {
baseNode = Element.extend(baseNode);
}
baseNode.select('*[x-localize]').each(function(el) {
var target = el.readAttribute('x-localize');
var key = null;
if (target.toLowerCase() == 'innerhtml') {
// Trying to fetch innerHTML, so grab it directly
key = el.innerHTML.strip();
} else {
// Presumably looking for an attribute of some sort
key = el.readAttribute(target);
}
// Don't mess with empty keys
if (key == null) {
Mojo.Log.warn('Empty key found by localize_html');
return;
}
// Grab the localized version
var localizedStr = $L(key);
if (target.toLowerCase() == 'innerhtml') {
el.innerHTML = localizedStr;
} else {
// Write the localized version
el.writeAttribute(target, localizedStr);
}
// Remove the x-localize attribute to prevent redundant translations
el.writeAttribute('x-localize', null);
});
};<file_sep>The localize-html.js script provides automatic localization of
HTML nodes and attributes using `strings.json` and the `$L()` command.
For some use cases, it makes sense to duplicate your HTML for each
language, but in many instances when you just have short phrases that
need localization it is preferable to use the `$L()` method.
## Installation
To use this script, download the localize-html.js file and put it
somewhere in your app (I usually use a top-level `javascripts` folder
for this kind of generic script).
Assuming you're also using a `javascripts` folder, add the following
line to your `sources.json` file:
{"source": "javascripts/localize-html.js"}
Then in your first scene assistant, start it running in the setup
function:
start_localize_html();
And to prevent memory leaks, stop it in the cleanup function:
stop_localize_html();
If you are using multiple stages, you'll need to pass the stage's body
element as an argument to both functions.
In your HTML view files for any elements that need to be localized
add the special `x-localize` attribute:
<div x-localize="innerHTML">Localized Text</div>
<img src="localize_text.jpg" alt="Localized Text" x-localize="alt" />
Valid values for `x-localize` are any attribute name, or "innerHTML".
The specified attribute (or the element's contents) will be replaced
by the value in the appropriate `strings.json` file.
## In the wild
I wrote `localize-html.js` for use in [TouchNote][1]. If I hear of
it being used anywhere else, I'll note it here.
[1]: http://onecrayon.com/touchnote/
## Released under an MIT license
Copyright (c) 2010 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. | 8621298126a650230d85acbbbc6c5cbe57b8e9c5 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | onecrayon/localize-html-webos | c33200fae6974ee27725da94a6fca53114002a6e | 84bd34eb671146e8733200493c0272ce00263357 |
refs/heads/master | <file_sep>#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <cmath>
// ABANDON ALL HOPE,
// YE WHO ENTER HERE...
using namespace std;
string name;
char race;
int playerPos[2];
int playerHP;
int playerAtk;
int playerDef;
int playerGold;
int enemyPos[40];
int enemyHP[20];
int enemyAtk[20];
int enemyDef[20];
bool merchantAggro;
int potionType[10];
int potionPos[20];
int treasureType[30];
int treasurePos[60];
int treasureCount = 10;
int level = 1;
char board[2000];
char defaultBoard[2000];
int boardCol = 80;
int boardRow = 25;
int boardSize = 2000;
void readBoard(string fname) {
ifstream ifs(fname.c_str());
ifs >> noskipws;
boardSize = 0;
boardRow = 0;
boardCol = 0;
char c;
while(ifs >> c) {
if(c == '\n') ++boardRow;
board[boardSize] = c;
if(c == '|' || c == '-' || c == '#' || c == '+') defaultBoard[boardSize] = c;
else defaultBoard[boardSize] = '.';
++boardSize;
}
boardCol = boardSize / boardRow;
ifs.close();
int pot = 0;
int tre = 0;
int ene = 0;
for(int i = 0; i < boardSize; ++i) {
if(board[i] == '@') {
playerPos[0] = i % boardCol;
playerPos[1] = i / boardCol;
}
if(board[i] == '0') {
potionPos[pot] = i % boardCol;
potionPos[pot + 10] = i / boardCol;
potionType[pot] = 0;
++pot;
board[i] = 'P';
defaultBoard[i] = 'P';
} else if(board[i] == '1') {
potionPos[pot] = i % boardCol;
potionPos[pot + 10] = i / boardCol;
potionType[pot] = 1;
++pot;
board[i] = 'P';
defaultBoard[i] = 'P';
} else if(board[i] == '2') {
potionPos[pot] = i % boardCol;
potionPos[pot + 10] = i / boardCol;
potionType[pot] = 2;
++pot;
board[i] = 'P';
defaultBoard[i] = 'P';
} else if(board[i] == '3') {
potionPos[pot] = i % boardCol;
potionPos[pot + 10] = i / boardCol;
potionType[pot] = 3;
++pot;
board[i] = 'P';
defaultBoard[i] = 'P';
} else if(board[i] == '4') {
potionPos[pot] = i % boardCol;
potionPos[pot + 10] = i / boardCol;
potionType[pot] = 4;
++pot;
board[i] = 'P';
defaultBoard[i] = 'P';
} else if(board[i] == '5') {
potionPos[pot] = i % boardCol;
potionPos[pot + 10] = i / boardCol;
potionType[pot] = 5;
++pot;
board[i] = 'P';
defaultBoard[i] = 'P';
}
if(board[i] == '6') {
treasurePos[tre] = i % boardCol;
treasurePos[tre + 10] = i / boardCol;
treasureType[tre] = 0;
++tre;
board[i] = 'G';
} else if(board[i] == '7') {
treasurePos[tre] = i % boardCol;
treasurePos[tre + 10] = i / boardCol;
treasureType[tre] = 1;
++tre;
board[i] = 'G';
} else if(board[i] == '8') {
treasurePos[tre] = i % boardCol;
treasurePos[tre + 10] = i / boardCol;
treasureType[tre] = 3;
++tre;
board[i] = 'G';
} else if(board[i] == '9') {
treasurePos[tre] = i % boardCol;
treasurePos[tre + 10] = i / boardCol;
treasureType[tre] = 2;
++tre;
board[i] = 'G';
}
if(board[i] == 'D') {
enemyPos[ene] = i % boardCol;
enemyPos[ene + 20] = i / boardCol;
enemyHP[ene] = 150;
enemyAtk[ene] = 20;
enemyDef[ene] = 20;
++ene;
} else if(board[i] == 'W') {
enemyPos[ene] = i % boardCol;
enemyPos[ene + 20] = i / boardCol;
enemyHP[ene] = 150;
enemyAtk[ene] = 20;
enemyDef[ene] = 20;
++ene;
} else if(board[i] == 'V') {
enemyPos[ene] = i % boardCol;
enemyPos[ene + 20] = i / boardCol;
enemyHP[ene] = 50;
enemyAtk[ene] = 25;
enemyDef[ene] = 25;
++ene;
} else if(board[i] == 'N') {
enemyPos[ene] = i % boardCol;
enemyPos[ene + 20] = i / boardCol;
enemyHP[ene] = 70;
enemyAtk[ene] = 5;
enemyDef[ene] = 10;
++ene;
} else if(board[i] == 'T') {
enemyPos[ene] = i % boardCol;
enemyPos[ene + 20] = i / boardCol;
enemyHP[ene] = 120;
enemyAtk[ene] = 25;
enemyDef[ene] = 15;
++ene;
} else if(board[i] == 'X') {
enemyPos[ene] = i % boardCol;
enemyPos[ene + 20] = i / boardCol;
enemyHP[ene] = 50;
enemyAtk[ene] = 35;
enemyDef[ene] = 20;
++ene;
} else if(board[i] == 'M') {
enemyPos[ene] = i % boardCol;
enemyPos[ene + 20] = i / boardCol;
enemyHP[ene] = 30;
enemyAtk[ene] = 70;
enemyDef[ene] = 5;
++ene;
}
}
}
void generateBoard() {
ifstream ifs("default.txt");
ifs >> noskipws;
for(int i = 0; i < 2000; ++i) ifs >> board[i];
for(int i = 0; i < 2000; ++i) defaultBoard[i] = board[i];
ifs.close();
}
void fixBoard() {
for(int i = 0; i < boardSize; ++i) if(board[i] == '.') board[i] = defaultBoard[i];
}
void populateBoard() {
int playerChamber = rand() % 5;
if(playerChamber == 0) {
playerPos[0] = rand() % 26 + 3;
playerPos[1] = rand() % 4 + 3;
board[playerPos[0] + boardCol * playerPos[1]] = '@';
} else if(playerChamber == 1) {
playerPos[0] = rand() % 21 + 4;
playerPos[1] = rand() % 7 + 15;
board[playerPos[0] + boardCol * playerPos[1]] = '@';
} else if(playerChamber == 2) {
playerPos[0] = rand() % 12 + 38;
playerPos[1] = rand() % 3 + 10;
board[playerPos[0] + boardCol * playerPos[1]] = '@';
} else if(playerChamber == 3) {
PLAYER_RESPAWN_C3:
playerPos[0] = rand() % 37 + 39;
playerPos[1] = rand() % 10 + 3;
if(playerPos[0] > 61 && playerPos[1] < 5) goto PLAYER_RESPAWN_C3;
if(playerPos[0] > 69 && playerPos[1] < 6) goto PLAYER_RESPAWN_C3;
if(playerPos[0] > 72 && playerPos[1] < 7) goto PLAYER_RESPAWN_C3;
if(playerPos[0] < 61 && playerPos[1] > 6) goto PLAYER_RESPAWN_C3;
board[playerPos[0] + boardCol * playerPos[1]] = '@';
} else if(playerChamber == 4) {
PLAYER_RESPAWN_C4:
playerPos[0] = rand() % 39 + 37;
playerPos[1] = rand() % 6 + 16;
if(playerPos[0] < 65 && playerPos[1] < 19) goto PLAYER_RESPAWN_C4;
board[playerPos[0] + boardCol * playerPos[1]] = '@';
}
STAIR_RESPAWN:
int stairChamber = rand() % 5;
if(stairChamber == playerChamber) goto STAIR_RESPAWN;
if(stairChamber == 0) board[(rand() % 26 + 3) + boardCol * (rand() % 4 + 3)] = '\\';
else if(stairChamber == 1) board[(rand() % 21 + 4) + boardCol * (rand() % 7 + 15)] = '\\';
else if(stairChamber == 2) board[(rand() % 12 + 38) + boardCol * (rand() % 3 + 10)] = '\\';
else if(stairChamber == 3) {
STAIR_RESPAWN_C3:
int c = rand() % 37 + 39;
int r = rand() % 10 + 3;
if(c > 61 && r < 5) goto STAIR_RESPAWN_C3;
if(c > 69 && r < 6) goto STAIR_RESPAWN_C3;
if(c > 72 && r < 7) goto STAIR_RESPAWN_C3;
if(c < 61 && r > 6) goto STAIR_RESPAWN_C3;
board[c + boardCol * r] = '\\';
}
else if(stairChamber == 4) {
STAIR_RESPAWN_C4:
int c = rand() % 39 + 37;
int r = rand() % 6 + 16;
if(c < 65 && r < 19) goto STAIR_RESPAWN_C4;
board[c + boardCol * r] = '\\';
}
for(int i = 0; i < 10; ++i) {
POTION_RESPAWN:
int potionChamber = rand() % 5;
if(potionChamber == 0) {
potionPos[i] = rand() % 26 + 3;
potionPos[i + 10] = rand() % 4 + 3;
if(board[potionPos[i] + boardCol * potionPos[i + 10]] != '.') goto POTION_RESPAWN;
board[potionPos[i] + boardCol * potionPos[i + 10]] = 'P';
defaultBoard[potionPos[i] + boardCol * potionPos[i + 10]] = 'P';
} else if(potionChamber == 1) {
potionPos[i] = rand() % 21 + 4;
potionPos[i + 10] = rand() % 7 + 15;
if(board[potionPos[i] + boardCol * potionPos[i + 10]] != '.') goto POTION_RESPAWN;
board[potionPos[i] + boardCol * potionPos[i + 10]] = 'P';
defaultBoard[potionPos[i] + boardCol * potionPos[i + 10]] = 'P';
} else if(potionChamber == 2) {
potionPos[i] = rand() % 12 + 38;
potionPos[i + 10] = rand() % 3 + 10;
if(board[potionPos[i] + boardCol * potionPos[i + 10]] != '.') goto POTION_RESPAWN;
board[potionPos[i] + boardCol * potionPos[i + 10]] = 'P';
defaultBoard[potionPos[i] + boardCol * potionPos[i + 10]] = 'P';
} else if(potionChamber == 3) {
POTION_RESPAWN_C3:
potionPos[i] = rand() % 37 + 39;
potionPos[i + 10] = rand() % 10 + 3;
if(board[potionPos[i] + boardCol * potionPos[i + 10]] != '.') goto POTION_RESPAWN;
if(potionPos[i] > 61 && potionPos[i + 10] < 5) goto POTION_RESPAWN_C3;
if(potionPos[i] > 69 && potionPos[i + 10] < 6) goto POTION_RESPAWN_C3;
if(potionPos[i] > 72 && potionPos[i + 10] < 7) goto POTION_RESPAWN_C3;
if(potionPos[i] < 61 && potionPos[i + 10] > 6) goto POTION_RESPAWN_C3;
board[potionPos[i] + boardCol * potionPos[i + 10]] = 'P';
defaultBoard[potionPos[i] + boardCol * potionPos[i + 10]] = 'P';
} else if(potionChamber == 4) {
POTION_RESPAWN_C4:
potionPos[i] = rand() % 39 + 37;
potionPos[i + 10] = rand() % 6 + 16;
if(board[potionPos[i] + boardCol * potionPos[i + 10]] != '.') goto POTION_RESPAWN;
if(potionPos[i] < 65 && potionPos[i + 10] < 19) goto POTION_RESPAWN_C4;
board[potionPos[i] + boardCol * potionPos[i + 10]] = 'P';
defaultBoard[potionPos[i] + boardCol * potionPos[i + 10]] = 'P';
}
potionType[i] = rand() % 6;
}
int dragons = 0;
for(int i = 0; i < 10; ++i) {
TREASURE_RESPAWN:
int treasureChamber = rand() % 5;
if(treasureChamber == 0) {
treasurePos[i] = rand() % 26 + 3;
treasurePos[i + 10] = rand() % 4 + 3;
if(board[treasurePos[i] + boardCol * treasurePos[i + 10]] != '.') goto TREASURE_RESPAWN;
board[treasurePos[i] + boardCol * treasurePos[i + 10]] = 'G';
} else if(treasureChamber == 1) {
treasurePos[i] = rand() % 21 + 4;
treasurePos[i + 10] = rand() % 7 + 15;
if(board[treasurePos[i] + boardCol * treasurePos[i + 10]] != '.') goto TREASURE_RESPAWN;
board[treasurePos[i] + boardCol * treasurePos[i + 10]] = 'G';
} else if(treasureChamber == 2) {
treasurePos[i] = rand() % 12 + 38;
treasurePos[i + 10] = rand() % 3 + 10;
if(board[treasurePos[i] + boardCol * treasurePos[i + 10]] != '.') goto TREASURE_RESPAWN;
board[treasurePos[i] + boardCol * treasurePos[i + 10]] = 'G';
} else if(treasureChamber == 3) {
TREASURE_RESPAWN_C3:
treasurePos[i] = rand() % 37 + 39;
treasurePos[i + 10] = rand() % 10 + 3;
if(board[treasurePos[i] + boardCol * treasurePos[i + 10]] != '.') goto TREASURE_RESPAWN;
if(treasurePos[i] > 61 && treasurePos[i + 10] < 5) goto TREASURE_RESPAWN_C3;
if(treasurePos[i] > 69 && treasurePos[i + 10] < 6) goto TREASURE_RESPAWN_C3;
if(treasurePos[i] > 72 && treasurePos[i + 10] < 7) goto TREASURE_RESPAWN_C3;
if(treasurePos[i] < 61 && treasurePos[i + 10] > 6) goto TREASURE_RESPAWN_C3;
board[treasurePos[i] + boardCol * treasurePos[i + 10]] = 'G';
} else if(treasureChamber == 4) {
TREASURE_RESPAWN_C4:
treasurePos[i] = rand() % 39 + 37;
treasurePos[i + 10] = rand() % 6 + 16;
if(board[treasurePos[i] + boardCol * treasurePos[i + 10]] != '.') goto TREASURE_RESPAWN;
if(treasurePos[i] < 65 && treasurePos[i + 10] < 19) goto TREASURE_RESPAWN_C4;
board[treasurePos[i] + boardCol * treasurePos[i + 10]] = 'G';
}
RETYPE_TREASURE:
int treasureType = rand() % 8;
if(treasureType >= 0 && treasureType <= 4) ::treasureType[i] = 0;
else if(treasureType >= 5 && treasureType <= 6) ::treasureType[i] = 1;
else if(treasureType == 7) {
::treasureType[i] = 2;
int safety = 0;
RESPAWN_DRAGON:
++safety;
if(safety >= 100) goto RETYPE_TREASURE;
int rShift = rand() % 3;
if(rShift == 2) rShift = -1;
int cShift = rand() % 3;
if(cShift == 2) cShift = -1;
if(rShift == 0 && cShift == 0) goto RESPAWN_DRAGON;
if(board[treasurePos[i] + cShift + boardCol * (treasurePos[i + 10] + rShift)] != '.') goto RESPAWN_DRAGON;
board[treasurePos[i] + cShift + boardCol * (treasurePos[i + 10] + rShift)] = 'D';
enemyPos[dragons] = treasurePos[i] + cShift;
enemyPos[dragons + 20] = treasurePos[i + 10] + rShift;
enemyHP[dragons] = 150;
enemyAtk[dragons] = 20;
enemyDef[dragons] = 20;
++dragons;
}
}
for(int i = dragons; i < 20; ++i) {
char enemyChar = '\0';
int enemyType = rand() % 18;
if(enemyType < 4) {
enemyChar = 'W';
enemyHP[i] = 120;
enemyAtk[i] = 30;
enemyDef[i] = 5;
} else if(enemyType < 7) {
enemyChar = 'V';
enemyHP[i] = 50;
enemyAtk[i] = 25;
enemyDef[i] = 25;
} else if(enemyType < 12) {
enemyChar = 'N';
enemyHP[i] = 70;
enemyAtk[i] = 5;
enemyDef[i] = 10;
} else if(enemyType < 14) {
enemyChar = 'T';
enemyHP[i] = 120;
enemyAtk[i] = 25;
enemyDef[i] = 15;
} else if(enemyType < 16) {
enemyChar = 'X';
enemyHP[i] = 50;
enemyAtk[i] = 35;
enemyDef[i] = 20;
} else if(enemyType < 18) {
enemyChar = 'M';
enemyHP[i] = 30;
enemyAtk[i] = 70;
enemyDef[i] = 5;
}
ENEMY_RESPAWN:
int enemyChamber = rand() % 5;
if(enemyChamber == 0) {
enemyPos[i] = rand() % 26 + 3;
enemyPos[i + 20] = rand() % 4 + 3;
if(board[enemyPos[i] + boardCol * enemyPos[i + 20]] != '.') goto ENEMY_RESPAWN;
board[enemyPos[i] + boardCol * enemyPos[i + 20]] = enemyChar;
} else if(enemyChamber == 1) {
enemyPos[i] = rand() % 21 + 4;
enemyPos[i + 20] = rand() % 7 + 15;
if(board[enemyPos[i] + boardCol * enemyPos[i + 20]] != '.') goto ENEMY_RESPAWN;
board[enemyPos[i] + boardCol * enemyPos[i + 20]] = enemyChar;
} else if(enemyChamber == 2) {
enemyPos[i] = rand() % 12 + 38;
enemyPos[i + 20] = rand() % 3 + 10;
if(board[enemyPos[i] + boardCol * enemyPos[i + 20]] != '.') goto ENEMY_RESPAWN;
board[enemyPos[i] + boardCol * enemyPos[i + 20]] = enemyChar;
} else if(enemyChamber == 3) {
ENEMY_RESPAWN_C3:
enemyPos[i] = rand() % 37 + 39;
enemyPos[i + 20] = rand() % 10 + 3;
if(board[enemyPos[i] + boardCol * enemyPos[i + 20]] != '.') goto ENEMY_RESPAWN;
if(enemyPos[i] > 61 && enemyPos[i + 20] < 5) goto ENEMY_RESPAWN_C3;
if(enemyPos[i] > 69 && enemyPos[i + 20] < 6) goto ENEMY_RESPAWN_C3;
if(enemyPos[i] > 72 && enemyPos[i + 20] < 7) goto ENEMY_RESPAWN_C3;
if(enemyPos[i] < 61 && enemyPos[i + 20] > 6) goto ENEMY_RESPAWN_C3;
board[enemyPos[i] + boardCol * enemyPos[i + 20]] = enemyChar;
} else if(enemyChamber == 4) {
ENEMY_RESPAWN_C4:
enemyPos[i] = rand() % 39 + 37;
enemyPos[i + 20] = rand() % 6 + 16;
if(board[enemyPos[i] + boardCol * enemyPos[i + 20]] != '.') goto ENEMY_RESPAWN;
if(enemyPos[i] < 65 && enemyPos[i + 20] < 19) goto ENEMY_RESPAWN_C4;
board[enemyPos[i] + boardCol * enemyPos[i + 20]] = enemyChar;
}
}
}
void printBoard(string action) {
for(int i = 0; i < boardSize; ++i) cout << board[i];
cout << "Race: ";
if(race == 'h') cout << "Human ";
else if(race == 'd') cout << "Dwarf ";
else if(race == 'e') cout << "Elf ";
else if(race == 'o') cout << "Orc ";
cout << "Gold: " << playerGold;
for(int i = 0; i < 50; ++i) cout << " ";
cout << "Floor " << level << endl;
cout << "HP: " << playerHP << endl;
cout << "Atk: " << playerAtk << endl;
cout << "Def: " << playerDef << endl;
cout << "Action: " << action << endl;
}
string decode(char c) {
if(c == '-' || c == '|' || c == ' ') return "wall";
if(c == '+') return "door";
if(c == 'V') return "vampire";
if(c == 'W') return "werewolf";
if(c == 'N') return "goblin";
if(c == 'M') return "merchant";
if(c == 'D') return "dragon";
if(c == 'X') return "phoenix";
if(c == 'T') return "troll";
if(c == 'P') return "mysterious potion";
if(c == '\\') return "staircase";
return "";
}
string lookAround() {
string look = "";
for(int j = 0; j < 8; ++j) {
int r = 0;
int c = 0;
if(j == 0) {c = playerPos[0]; r = playerPos[1] - 1;}
if(j == 1) {c = playerPos[0] - 1; r = playerPos[1] - 1;}
if(j == 2) {c = playerPos[0] + 1; r = playerPos[1] - 1;}
if(j == 3) {c = playerPos[0] - 1; r = playerPos[1] + 1;}
if(j == 4) {c = playerPos[0] + 1; r = playerPos[1] + 1;}
if(j == 5) {c = playerPos[0]; r = playerPos[1] + 1;}
if(j == 6) {c = playerPos[0] - 1; r = playerPos[1];}
if(j == 7) {c = playerPos[0] + 1; r = playerPos[1];}
char obj = board[c + boardCol * r];
if(obj == 'G') {
for(int i = 0; i < treasureCount; ++i) {
if(treasurePos[i] == c && treasurePos[i + 10] == r) {
if(treasureType[i] == 0) look = look + " and sees a gold coin";
if(treasureType[i] == 1) look = look + " and sees a small horde";
if(treasureType[i] == 2) look = look + " and sees a dragon horde";
if(treasureType[i] == 3) look = look + " and sees a merchant horde";
break;
}
}
} else if(obj != '.' && obj != '-' && obj != '|' && obj != '+' && obj != ' ' && obj != '#')
look = look + " and sees a " + decode(obj);
}
return look;
}
void moveEnemies() {
for(int i = 0; i < 20; ++i) {
if(board[enemyPos[i] + boardCol * enemyPos[i + 20]] != 'D' && enemyHP[i] != 0) {
bool player = false;
if(board[(enemyPos[i]) + boardCol * (enemyPos[i + 20] - 1)] == '@') player = true;
if(board[(enemyPos[i] - 1) + boardCol * (enemyPos[i + 20] - 1)] == '@') player = true;
if(board[(enemyPos[i] + 1) + boardCol * (enemyPos[i + 20] - 1)] == '@') player = true;
if(board[(enemyPos[i] - 1) + boardCol * (enemyPos[i + 20] + 1)] == '@') player = true;
if(board[(enemyPos[i] + 1) + boardCol * (enemyPos[i + 20] + 1)] == '@') player = true;
if(board[(enemyPos[i]) + boardCol * (enemyPos[i + 20] + 1)] == '@') player = true;
if(board[(enemyPos[i] - 1) + boardCol * (enemyPos[i + 20])] == '@') player = true;
if(board[(enemyPos[i] + 1) + boardCol * (enemyPos[i + 20])] == '@') player = true;
if(!player) {
RECALCULATE_MOVE:
int rShift = rand() % 3;
if(rShift == 2) rShift = -1;
int cShift = rand() % 3;
if(cShift == 2) cShift = -1;
if(rShift == 0 && cShift == 0) goto RECALCULATE_MOVE;
if(board[enemyPos[i] + cShift + boardCol * (enemyPos[i + 20] + rShift)] != '.' &&
board[enemyPos[i] + cShift + boardCol * (enemyPos[i + 20] + rShift)] != '+' &&
board[enemyPos[i] + cShift + boardCol * (enemyPos[i + 20] + rShift)] != '#') goto RECALCULATE_MOVE;
board[enemyPos[i] + cShift + boardCol * (enemyPos[i + 20] + rShift)] = board[enemyPos[i] + boardCol * enemyPos[i + 20]];
board[enemyPos[i] + boardCol * enemyPos[i + 20]] = '.';
enemyPos[i] = enemyPos[i] + cShift;
enemyPos[i + 20] = enemyPos[i + 20] + rShift;
}
}
}
}
string attackPlayer() {
string action = "";
for(int i = 0; i < 20; ++i) {
if(enemyHP[i] != 0) {
bool player = false;
if(board[(enemyPos[i]) + boardCol * (enemyPos[i + 20] - 1)] == '@') player = true;
if(board[(enemyPos[i] - 1) + boardCol * (enemyPos[i + 20] - 1)] == '@') player = true;
if(board[(enemyPos[i] + 1) + boardCol * (enemyPos[i + 20] - 1)] == '@') player = true;
if(board[(enemyPos[i] - 1) + boardCol * (enemyPos[i + 20] + 1)] == '@') player = true;
if(board[(enemyPos[i] + 1) + boardCol * (enemyPos[i + 20] + 1)] == '@') player = true;
if(board[(enemyPos[i]) + boardCol * (enemyPos[i + 20] + 1)] == '@') player = true;
if(board[(enemyPos[i] - 1) + boardCol * (enemyPos[i + 20])] == '@') player = true;
if(board[(enemyPos[i] + 1) + boardCol * (enemyPos[i + 20])] == '@') player = true;
if(player && (board[enemyPos[i] + boardCol * enemyPos[i + 20]] != 'M' || merchantAggro)) {
int damage = (int) ceil((100.0 / (100.0 + playerDef)) * enemyAtk[i]);
stringstream ss;
ss << damage;
string damageStr = ss.str();
if(playerHP < damage) playerHP = 0;
else playerHP -= damage;
action = action + ", " + decode(board[(enemyPos[i]) + boardCol * (enemyPos[i + 20])]) +
" deals " + damageStr + " damage to " + name;
}
}
}
return action;
}
string killEnemies() {
string action = "";
for(int i = 0; i < 20; ++i) {
if(enemyHP[i] == 0 && (enemyPos[i] != 0 || enemyPos[i + 20] != 0)) {
action = action + ", " + decode(board[(enemyPos[i]) + boardCol * (enemyPos[i + 20])]) +
" has been slain";
if(board[enemyPos[i] + boardCol * enemyPos[i + 20]] == 'M') {
board[enemyPos[i] + boardCol * enemyPos[i + 20]] = 'G';
treasurePos[treasureCount] = enemyPos[i];
treasurePos[treasureCount + 10] = enemyPos[i + 20];
treasureType[treasureCount] = 3;
++treasureCount;
action = action + " and drops a merchant horde";
} else if (board[enemyPos[i] + boardCol * enemyPos[i + 20]] != 'D'){
playerGold += 1;
board[enemyPos[i] + boardCol * enemyPos[i + 20]] = '.';
action = action + " and " + name + " picks up a gold coin";
} else board[enemyPos[i] + boardCol * enemyPos[i + 20]] = '.';
enemyPos[i] = enemyPos[i + 20] = 0;
}
}
return action;
}
int main(int argc, char *argv[]) {
cout << "Welcome to ChamberCrawler3000!" << endl;
cout << "Who are you?" << endl;
cout << "> ";
cin >> name;
srand(time(NULL));
RESTART:
string action = "";
string enemyAction = "";
cout << "Select your race: (h)uman (d)warf (e)lf (o)rc" << endl;
while(true) {
cout << "> ";
cin >> race;
if(race == 'h') break;
else if(race == 'd') break;
else if(race == 'e') break;
else if(race == 'o') break;
else cout << "invalid" << endl;
}
playerGold = 0;
level = 1;
merchantAggro = false;
if(race == 'h') playerHP = 140;
if(race == 'd') playerHP = 100;
if(race == 'e') playerHP = 140;
if(race == 'o') playerHP = 180;
NEXT_LEVEL:
if(race == 'h') playerAtk = 20;
if(race == 'd') playerAtk = 20;
if(race == 'e') playerAtk = 30;
if(race == 'o') playerAtk = 30;
if(race == 'h') playerDef = 20;
if(race == 'd') playerDef = 30;
if(race == 'e') playerDef = 10;
if(race == 'o') playerDef = 25;
if(argc == 1) {
generateBoard();
populateBoard();
} else {
string fname(argv[1]);
readBoard(fname);
}
if(level == 1) action = name + " has spawned" + lookAround();
string cmd;
while(true) {
if(level == 6) {
cout << "Congratulations! you have completed the game" << endl;
cout << "Score: " << (race == 'h' ? playerGold * 1.5: playerGold * 1.0) << endl;
cout << "Would you like to play again? (y, n)" << endl;
cout << "> ";
string opt;
while(true) {
cin >> opt;
if(opt == "y") {
cout << "New game" << endl;
goto RESTART;
} else if(opt == "n") {
cout << "Goodbye" << endl;
return 0;
} else cout << "invalid" << endl;
}
}
fixBoard();
enemyAction = enemyAction + killEnemies();
printBoard(action + enemyAction);
if(playerHP == 0) {
cout << "You died" << endl;
cout << "Score: " << (race == 'h' ? playerGold * 1.5: playerGold * 1.0) << endl;
cout << "Would you like to play again? (y, n)" << endl;
cout << "> ";
string opt;
while(true) {
cin >> opt;
if(opt == "y") {
cout << "New game" << endl;
goto RESTART;
} else if(opt == "n") {
cout << "Goodbye" << endl;
return 0;
} else cout << "invalid" << endl;
}
}
enemyAction = attackPlayer();
moveEnemies();
cout << "> ";
cin >> cmd;
if(cmd == "r") {
cout << "New game" << endl;
goto RESTART;
} else if(cmd == "q") {
cout << "Goodbye" << endl;
break;
} else if(cmd == "u") {
string dir;
cout << "Which direction? (no, so, ea, we, ne, nw, se, sw, dn)" << endl;
int index;
while(true) {
cout << "> ";
cin >> dir;
if(dir == "no") {
for(index = 0; index < 10; ++index) {
if(potionPos[index] == (playerPos[0]) && potionPos[index + 10] == (playerPos[1] - 1))
goto POTION_FOUND;
}
break;
} else if(dir == "so") {
for(index = 0; index < 10; ++index) {
if(potionPos[index] == (playerPos[0]) && potionPos[index + 10] == (playerPos[1] + 1))
goto POTION_FOUND;
}
break;
} else if(dir == "ea") {
for(index = 0; index < 10; ++index) {
if(potionPos[index] == (playerPos[0] + 1) && potionPos[index + 10] == (playerPos[1]))
goto POTION_FOUND;
}
break;
} else if(dir == "we") {
for(index = 0; index < 10; ++index) {
if(potionPos[index] == (playerPos[0] - 1) && potionPos[index + 10] == (playerPos[1]))
goto POTION_FOUND;
}
break;
} else if(dir == "ne") {
for(index = 0; index < 10; ++index) {
if(potionPos[index] == (playerPos[0] + 1) && potionPos[index + 10] == (playerPos[1] - 1))
goto POTION_FOUND;
}
break;
} else if(dir == "nw") {
for(index = 0; index < 10; ++index) {
if(potionPos[index] == (playerPos[0] - 1) && potionPos[index + 10] == (playerPos[1] - 1))
goto POTION_FOUND;
}
break;
} else if(dir == "se") {
for(index = 0; index < 10; ++index) {
if(potionPos[index] == (playerPos[0] + 1) && potionPos[index + 10] == (playerPos[1] + 1))
goto POTION_FOUND;
}
break;
} else if(dir == "sw") {
for(index = 0; index < 10; ++index) {
if(potionPos[index] == (playerPos[0] - 1) && potionPos[index + 10] == (playerPos[1] + 1))
goto POTION_FOUND;
}
break;
} else if(dir == "dn") {
for(index = 0; index < 10; ++index) {
if(potionPos[index] == (playerPos[0]) && potionPos[index + 10] == (playerPos[1]))
goto POTION_FOUND;
}
break;
} else cout << "invalid" << endl;
}
action = "there is no potion there";
goto POTION_NOT_FOUND;
POTION_FOUND:
if(dir != "dn") board[potionPos[index] + boardCol * potionPos[index + 10]] = '.';
defaultBoard[potionPos[index] + boardCol * potionPos[index + 10]] = '.';
potionPos[index] = potionPos[index + 10] = 0;
if(potionType[index] == 0) {
action = name + " drinks RH";
if(race == 'h') playerHP = (playerHP >= 130 ? 140: playerHP + 10);
if(race == 'd') playerHP = (playerHP >= 90 ? 100: playerHP + 10);
if(race == 'e') playerHP = (playerHP >= 130 ? 140: playerHP + 10);
if(race == 'o') playerHP = (playerHP >= 170 ? 180: playerHP + 10);
} else if(potionType[index] == 1) {
action = name + " drinks BA";
playerAtk += 5;
} else if(potionType[index] == 2) {
action = name + " drinks BD";
playerDef += 5;
} else if(potionType[index] == 3) {
action = name + " drinks PH";
if(race == 'e') playerHP = (playerHP >= 130 ? 140: playerHP + 10);
else playerHP = (playerHP >= 10 ? playerHP - 10: 0);
} else if(potionType[index] == 4) {
action = name + " drinks WA";
if(race == 'e') playerAtk += 5;
else playerAtk -= 5;
} else if(potionType[index] == 5) {
action = name + " drinks WD";
if(race == 'e') playerDef += 5;
else playerDef -= 5;
}
POTION_NOT_FOUND:;
} else if(cmd == "a") {
string dir;
string damageStr;
stringstream ss;
cout << "Which direction? (no, so, ea, we, ne, nw, se, sw)" << endl;
int index = 0;
int damage = 0;
while(true) {
cout << "> ";
cin >> dir;
if(dir == "no") {
for(index = 0; index < 20; ++index) {
if(enemyPos[index] == (playerPos[0]) && enemyPos[index + 20] == (playerPos[1] - 1))
goto ENEMY_FOUND;
}
break;
} else if(dir == "so") {
for(index = 0; index < 20; ++index) {
if(enemyPos[index] == (playerPos[0]) && enemyPos[index + 20] == (playerPos[1] + 1))
goto ENEMY_FOUND;
}
break;
} else if(dir == "ea") {
for(index = 0; index < 20; ++index) {
if(enemyPos[index] == (playerPos[0] + 1) && enemyPos[index + 20] == (playerPos[1]))
goto ENEMY_FOUND;
}
break;
} else if(dir == "we") {
for(index = 0; index < 20; ++index) {
if(enemyPos[index] == (playerPos[0] - 1) && enemyPos[index + 20] == (playerPos[1]))
goto ENEMY_FOUND;
}
break;
} else if(dir == "ne") {
for(index = 0; index < 20; ++index) {
if(enemyPos[index] == (playerPos[0] + 1) && enemyPos[index + 20] == (playerPos[1] - 1))
goto ENEMY_FOUND;
}
break;
} else if(dir == "nw") {
for(index = 0; index < 20; ++index) {
if(enemyPos[index] == (playerPos[0] - 1) && enemyPos[index + 20] == (playerPos[1] - 1))
goto ENEMY_FOUND;
}
break;
} else if(dir == "se") {
for(index = 0; index < 20; ++index) {
if(enemyPos[index] == (playerPos[0] + 1) && enemyPos[index + 20] == (playerPos[1] + 1))
goto ENEMY_FOUND;
}
break;
} else if(dir == "sw") {
for(index = 0; index < 20; ++index) {
if(enemyPos[index] == (playerPos[0] - 1) && enemyPos[index + 20] == (playerPos[1] + 1))
goto ENEMY_FOUND;
}
break;
} else cout << "invalid" << endl;
}
action = "there is no enemy there";
goto ENEMY_NOT_FOUND;
ENEMY_FOUND:
damage = (int) ceil((100.0 / (100.0 + enemyDef[index])) * playerAtk);
ss << damage;
damageStr = ss.str();
if(enemyHP[index] < damage) enemyHP[index] = 0;
else enemyHP[index] -= damage;
action = decode(board[(enemyPos[index]) + boardCol * (enemyPos[index + 20])]) +
" receives " + damageStr + " damage from " + name;
if(board[(enemyPos[index]) + boardCol * (enemyPos[index + 20])] == 'M') {
if(!merchantAggro) action = action + ", merchants are now hostile";
merchantAggro = true;
}
ENEMY_NOT_FOUND:;
} else if(cmd == "no") {
if(board[(playerPos[0]) + boardCol * (playerPos[1] - 1)] == '.' ||
board[(playerPos[0]) + boardCol * (playerPos[1] - 1)] == '#' ||
board[(playerPos[0]) + boardCol * (playerPos[1] - 1)] == '+') {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0]) + boardCol * (playerPos[1] - 1)] = '@';
--playerPos[1];
action = name + " moves north" + lookAround();
} else if(board[(playerPos[0]) + boardCol * (playerPos[1] - 1)] == 'G') {
for(int i = 0; i < treasureCount; ++i) {
if(treasurePos[i] == (playerPos[0]) && treasurePos[i + 10] == (playerPos[1] - 1)) {
if(treasureType[i] == 0) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0]) + boardCol * (playerPos[1] - 1)] = '@';
--playerPos[1];
if(race == 'h' || race == 'e') playerGold += 1;
if(race == 'd') playerGold += 2;
if(race == 'o') playerGold += 1;
action = name + " moves north and picks up a gold coin";
} else if(treasureType[i] == 1) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0]) + boardCol * (playerPos[1] - 1)] = '@';
--playerPos[1];
if(race == 'h' || race == 'e') playerGold += 2;
if(race == 'd') playerGold += 4;
if(race == 'o') playerGold += 1;
action = name + " moves north and picks up a small horde";
} else if(treasureType[i] == 2) {
bool dragon = false;
if(board[(treasurePos[i]) + boardCol * (treasurePos[i + 10] - 1)] == 'D') dragon = true;
if(board[(treasurePos[i] - 1) + boardCol * (treasurePos[i + 10] - 1)] == 'D') dragon = true;
if(board[(treasurePos[i] + 1) + boardCol * (treasurePos[i + 10] - 1)] == 'D') dragon = true;
if(board[(treasurePos[i] - 1) + boardCol * (treasurePos[i + 10] + 1)] == 'D') dragon = true;
if(board[(treasurePos[i] + 1) + boardCol * (treasurePos[i + 10] + 1)] == 'D') dragon = true;
if(board[(treasurePos[i]) + boardCol * (treasurePos[i + 10] + 1)] == 'D') dragon = true;
if(board[(treasurePos[i] - 1) + boardCol * (treasurePos[i + 10])] == 'D') dragon = true;
if(board[(treasurePos[i] + 1) + boardCol * (treasurePos[i + 10])] == 'D') dragon = true;
if(!dragon) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0]) + boardCol * (playerPos[1] - 1)] = '@';
--playerPos[1];
if(race == 'h' || race == 'e') playerGold += 6;
if(race == 'd') playerGold += 12;
if(race == 'o') playerGold += 3;
action = name + " moves north and picks up a dragon horde";
} else action = "the dragon defends its horde";
} else if(treasureType[i] == 3) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0]) + boardCol * (playerPos[1] - 1)] = '@';
--playerPos[1];
if(race == 'h' || race == 'e') playerGold += 4;
if(race == 'd') playerGold += 8;
if(race == 'o') playerGold += 2;
action = name + " moves north and picks up a merchant horde";
}
break;
}
}
} else if(board[(playerPos[0]) + boardCol * (playerPos[1] - 1)] == 'P') {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0]) + boardCol * (playerPos[1] - 1)] = '@';
--playerPos[1];
action = name + " moves north, on top of a potion" + lookAround();
} else if(board[(playerPos[0]) + boardCol * (playerPos[1] - 1)] == '\\') {
++level;
action = name + " has reached the next level";
goto NEXT_LEVEL;
} else action = name + " bumps into a " + decode(board[(playerPos[0]) + boardCol * (playerPos[1] - 1)]);
} else if(cmd == "so") {
if(board[(playerPos[0]) + boardCol * (playerPos[1] + 1)] == '.' ||
board[(playerPos[0]) + boardCol * (playerPos[1] + 1)] == '#'||
board[(playerPos[0]) + boardCol * (playerPos[1] + 1)] == '+') {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0]) + boardCol * (playerPos[1] + 1)] = '@';
++playerPos[1];
action = name + " moves south" + lookAround();
} else if(board[(playerPos[0]) + boardCol * (playerPos[1] + 1)] == 'G') {
for(int i = 0; i < treasureCount; ++i) {
if(treasurePos[i] == (playerPos[0]) && treasurePos[i + 10] == (playerPos[1] + 1)) {
if(treasureType[i] == 0) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0]) + boardCol * (playerPos[1] + 1)] = '@';
++playerPos[1];
if(race == 'h' || race == 'e') playerGold += 1;
if(race == 'd') playerGold += 2;
if(race == 'o') playerGold += 1;
action = name + " moves south and picks up a gold coin";
} else if(treasureType[i] == 1) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0]) + boardCol * (playerPos[1] + 1)] = '@';
++playerPos[1];
if(race == 'h' || race == 'e') playerGold += 2;
if(race == 'd') playerGold += 4;
if(race == 'o') playerGold += 1;
action = name + " moves south and picks up a small horde";
} else if(treasureType[i] == 2) {
bool dragon = false;
if(board[(treasurePos[i]) + boardCol * (treasurePos[i + 10] - 1)] == 'D') dragon = true;
if(board[(treasurePos[i] - 1) + boardCol * (treasurePos[i + 10] - 1)] == 'D') dragon = true;
if(board[(treasurePos[i] + 1) + boardCol * (treasurePos[i + 10] - 1)] == 'D') dragon = true;
if(board[(treasurePos[i] - 1) + boardCol * (treasurePos[i + 10] + 1)] == 'D') dragon = true;
if(board[(treasurePos[i] + 1) + boardCol * (treasurePos[i + 10] + 1)] == 'D') dragon = true;
if(board[(treasurePos[i]) + boardCol * (treasurePos[i + 10] + 1)] == 'D') dragon = true;
if(board[(treasurePos[i] - 1) + boardCol * (treasurePos[i + 10])] == 'D') dragon = true;
if(board[(treasurePos[i] + 1) + boardCol * (treasurePos[i + 10])] == 'D') dragon = true;
if(!dragon) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0]) + boardCol * (playerPos[1] + 1)] = '@';
++playerPos[1];
if(race == 'h' || race == 'e') playerGold += 6;
if(race == 'd') playerGold += 12;
if(race == 'o') playerGold += 3;
action = name + " moves south and picks up a dragon horde";
} else action = "the dragon defends its horde";
} else if(treasureType[i] == 3) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0]) + boardCol * (playerPos[1] + 1)] = '@';
++playerPos[1];
if(race == 'h' || race == 'e') playerGold += 4;
if(race == 'd') playerGold += 8;
if(race == 'o') playerGold += 2;
action = name + " moves south and picks up a merchant horde";
}
break;
}
}
} else if(board[(playerPos[0]) + boardCol * (playerPos[1] + 1)] == 'P') {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0]) + boardCol * (playerPos[1] + 1)] = '@';
++playerPos[1];
action = name + " moves south, on top of a potion" + lookAround();
} else if(board[(playerPos[0]) + boardCol * (playerPos[1] + 1)] == '\\') {
++level;
action = name + " has reached the next level";
goto NEXT_LEVEL;
} else action = name + " bumps into a " + decode(board[(playerPos[0]) + boardCol * (playerPos[1] + 1)]);
} else if(cmd == "ea") {
if(board[(playerPos[0] + 1) + boardCol * (playerPos[1])] == '.' ||
board[(playerPos[0] + 1) + boardCol * (playerPos[1])] == '#' ||
board[(playerPos[0] + 1) + boardCol * (playerPos[1])] == '+') {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] + 1) + boardCol * (playerPos[1])] = '@';
++playerPos[0];
action = name + " moves east" + lookAround();
} else if(board[(playerPos[0] + 1) + boardCol * (playerPos[1])] == 'G') {
for(int i = 0; i < treasureCount; ++i) {
if(treasurePos[i] == (playerPos[0] + 1) && treasurePos[i + 10] == (playerPos[1])) {
if(treasureType[i] == 0) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] + 1) + boardCol * (playerPos[1])] = '@';
++playerPos[0];
if(race == 'h' || race == 'e') playerGold += 1;
if(race == 'd') playerGold += 2;
if(race == 'o') playerGold += 1;
action = name + " moves east and picks up a gold coin";
} else if(treasureType[i] == 1) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] + 1) + boardCol * (playerPos[1])] = '@';
++playerPos[0];
if(race == 'h' || race == 'e') playerGold += 2;
if(race == 'd') playerGold += 4;
if(race == 'o') playerGold += 1;
action = name + " moves east and picks up a small horde";
} else if(treasureType[i] == 2) {
bool dragon = false;
if(board[(treasurePos[i]) + boardCol * (treasurePos[i + 10] - 1)] == 'D') dragon = true;
if(board[(treasurePos[i] - 1) + boardCol * (treasurePos[i + 10] - 1)] == 'D') dragon = true;
if(board[(treasurePos[i] + 1) + boardCol * (treasurePos[i + 10] - 1)] == 'D') dragon = true;
if(board[(treasurePos[i] - 1) + boardCol * (treasurePos[i + 10] + 1)] == 'D') dragon = true;
if(board[(treasurePos[i] + 1) + boardCol * (treasurePos[i + 10] + 1)] == 'D') dragon = true;
if(board[(treasurePos[i]) + boardCol * (treasurePos[i + 10] + 1)] == 'D') dragon = true;
if(board[(treasurePos[i] - 1) + boardCol * (treasurePos[i + 10])] == 'D') dragon = true;
if(board[(treasurePos[i] + 1) + boardCol * (treasurePos[i + 10])] == 'D') dragon = true;
if(!dragon) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] + 1) + boardCol * (playerPos[1])] = '@';
++playerPos[0];
if(race == 'h' || race == 'e') playerGold += 6;
if(race == 'd') playerGold += 12;
if(race == 'o') playerGold += 3;
action = name + " moves east and picks up a dragon horde";
} else action = "the dragon defends its horde";
} else if(treasureType[i] == 3) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] + 1) + boardCol * (playerPos[1])] = '@';
++playerPos[0];
if(race == 'h' || race == 'e') playerGold += 4;
if(race == 'd') playerGold += 8;
if(race == 'o') playerGold += 2;
action = name + " moves east and picks up a merchant horde";
}
break;
}
}
} else if(board[(playerPos[0] + 1) + boardCol * (playerPos[1])] == 'P') {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] + 1) + boardCol * (playerPos[1])] = '@';
++playerPos[0];
action = name + " moves east, on top of a potion" + lookAround();
} else if(board[(playerPos[0] + 1) + boardCol * (playerPos[1])] == '\\') {
++level;
action = name + " has reached the next level";
goto NEXT_LEVEL;
} else action = name + " bumps into a " + decode(board[(playerPos[0] + 1) + boardCol * (playerPos[1])]);
} else if(cmd == "we") {
if(board[(playerPos[0] - 1) + boardCol * (playerPos[1])] == '.' ||
board[(playerPos[0] - 1) + boardCol * (playerPos[1])] == '#' ||
board[(playerPos[0] - 1) + boardCol * (playerPos[1])] == '+') {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] - 1) + boardCol * (playerPos[1])] = '@';
--playerPos[0];
action = name + " moves west" + lookAround();
} else if(board[(playerPos[0] - 1) + boardCol * (playerPos[1])] == 'G') {
for(int i = 0; i < treasureCount; ++i) {
if(treasurePos[i] == (playerPos[0] - 1) && treasurePos[i + 10] == (playerPos[1])) {
if(treasureType[i] == 0) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] - 1) + boardCol * (playerPos[1])] = '@';
--playerPos[0];
if(race == 'h' || race == 'e') playerGold += 1;
if(race == 'd') playerGold += 2;
if(race == 'o') playerGold += 1;
action = name + " moves west and picks up a gold coin";
} else if(treasureType[i] == 1) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] - 1) + boardCol * (playerPos[1])] = '@';
--playerPos[0];
if(race == 'h' || race == 'e') playerGold += 2;
if(race == 'd') playerGold += 4;
if(race == 'o') playerGold += 1;
action = name + " moves west and picks up a small horde";
} else if(treasureType[i] == 2) {
bool dragon = false;
if(board[(treasurePos[i]) + boardCol * (treasurePos[i + 10] - 1)] == 'D') dragon = true;
if(board[(treasurePos[i] - 1) + boardCol * (treasurePos[i + 10] - 1)] == 'D') dragon = true;
if(board[(treasurePos[i] + 1) + boardCol * (treasurePos[i + 10] - 1)] == 'D') dragon = true;
if(board[(treasurePos[i] - 1) + boardCol * (treasurePos[i + 10] + 1)] == 'D') dragon = true;
if(board[(treasurePos[i] + 1) + boardCol * (treasurePos[i + 10] + 1)] == 'D') dragon = true;
if(board[(treasurePos[i]) + boardCol * (treasurePos[i + 10] + 1)] == 'D') dragon = true;
if(board[(treasurePos[i] - 1) + boardCol * (treasurePos[i + 10])] == 'D') dragon = true;
if(board[(treasurePos[i] + 1) + boardCol * (treasurePos[i + 10])] == 'D') dragon = true;
if(!dragon) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] - 1) + boardCol * (playerPos[1])] = '@';
--playerPos[0];
if(race == 'h' || race == 'e') playerGold += 6;
if(race == 'd') playerGold += 12;
if(race == 'o') playerGold += 3;
action = name + " moves west and picks up a dragon horde";
} else action = "the dragon defends its horde";
} else if(treasureType[i] == 3) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] - 1) + boardCol * (playerPos[1])] = '@';
--playerPos[0];
if(race == 'h' || race == 'e') playerGold += 4;
if(race == 'd') playerGold += 8;
if(race == 'o') playerGold += 2;
action = name + " moves west and picks up a merchant horde";
}
break;
}
}
} else if(board[(playerPos[0] - 1) + boardCol * (playerPos[1])] == 'P') {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] - 1) + boardCol * (playerPos[1])] = '@';
--playerPos[0];
action = name + " moves west, on top of a potion" + lookAround();
} else if(board[(playerPos[0] - 1) + boardCol * (playerPos[1])] == '\\') {
++level;
action = name + " has reached the next level";
goto NEXT_LEVEL;
} else action = name + " bumps into a " + decode(board[(playerPos[0] - 1) + boardCol * (playerPos[1])]);
} else if(cmd == "ne") {
if(board[(playerPos[0] + 1) + boardCol * (playerPos[1] - 1)] == '.' ||
board[(playerPos[0] + 1) + boardCol * (playerPos[1] - 1)] == '#' ||
board[(playerPos[0] + 1) + boardCol * (playerPos[1] - 1)] == '+') {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] + 1) + boardCol * (playerPos[1] - 1)] = '@';
++playerPos[0];
--playerPos[1];
action = name + " moves north-east" + lookAround();
} else if(board[(playerPos[0] + 1) + boardCol * (playerPos[1] - 1)] == 'G') {
for(int i = 0; i < treasureCount; ++i) {
if(treasurePos[i] == (playerPos[0] + 1) && treasurePos[i + 10] == (playerPos[1] - 1)) {
if(treasureType[i] == 0) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] + 1) + boardCol * (playerPos[1] - 1)] = '@';
++playerPos[0];
--playerPos[1];
if(race == 'h' || race == 'e') playerGold += 1;
if(race == 'd') playerGold += 2;
if(race == 'o') playerGold += 1;
action = name + " moves north-east and picks up a gold coin";
} else if(treasureType[i] == 1) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] + 1) + boardCol * (playerPos[1] - 1)] = '@';
++playerPos[0];
--playerPos[1];
if(race == 'h' || race == 'e') playerGold += 2;
if(race == 'd') playerGold += 4;
if(race == 'o') playerGold += 1;
action = name + " moves north-east and picks up a small horde";
} else if(treasureType[i] == 2) {
bool dragon = false;
if(board[(treasurePos[i]) + boardCol * (treasurePos[i + 10] - 1)] == 'D') dragon = true;
if(board[(treasurePos[i] - 1) + boardCol * (treasurePos[i + 10] - 1)] == 'D') dragon = true;
if(board[(treasurePos[i] + 1) + boardCol * (treasurePos[i + 10] - 1)] == 'D') dragon = true;
if(board[(treasurePos[i] - 1) + boardCol * (treasurePos[i + 10] + 1)] == 'D') dragon = true;
if(board[(treasurePos[i] + 1) + boardCol * (treasurePos[i + 10] + 1)] == 'D') dragon = true;
if(board[(treasurePos[i]) + boardCol * (treasurePos[i + 10] + 1)] == 'D') dragon = true;
if(board[(treasurePos[i] - 1) + boardCol * (treasurePos[i + 10])] == 'D') dragon = true;
if(board[(treasurePos[i] + 1) + boardCol * (treasurePos[i + 10])] == 'D') dragon = true;
if(!dragon) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] + 1) + boardCol * (playerPos[1] - 1)] = '@';
++playerPos[0];
--playerPos[1];
if(race == 'h' || race == 'e') playerGold += 6;
if(race == 'd') playerGold += 12;
if(race == 'o') playerGold += 3;
action = name + " moves north-east and picks up a dragon horde";
} else action = "the dragon defends its horde";
} else if(treasureType[i] == 3) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] + 1) + boardCol * (playerPos[1] - 1)] = '@';
++playerPos[0];
--playerPos[1];
if(race == 'h' || race == 'e') playerGold += 4;
if(race == 'd') playerGold += 8;
if(race == 'o') playerGold += 2;
action = name + " moves north-east and picks up a merchant horde";
}
break;
}
}
} else if(board[(playerPos[0] + 1) + boardCol * (playerPos[1] - 1)] == 'P') {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] + 1) + boardCol * (playerPos[1] - 1)] = '@';
++playerPos[0];
--playerPos[1];
action = name + " moves north-east, on top of a potion" + lookAround();
} else if(board[(playerPos[0] + 1) + boardCol * (playerPos[1] - 1)] == '\\') {
++level;
action = name + " has reached the next level";
goto NEXT_LEVEL;
} else action = name + " bumps into a " + decode(board[(playerPos[0] + 1) + boardCol * (playerPos[1] - 1)]);
} else if(cmd == "nw") {
if(board[(playerPos[0] - 1) + boardCol * (playerPos[1] - 1)] == '.' ||
board[(playerPos[0] - 1) + boardCol * (playerPos[1] - 1)] == '#' ||
board[(playerPos[0] - 1) + boardCol * (playerPos[1] - 1)] == '+') {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] - 1) + boardCol * (playerPos[1] - 1)] = '@';
--playerPos[0];
--playerPos[1];
action = name + " moves north-west" + lookAround();
} else if(board[(playerPos[0] - 1) + boardCol * (playerPos[1] - 1)] == 'G') {
for(int i = 0; i < treasureCount; ++i) {
if(treasurePos[i] == (playerPos[0] - 1) && treasurePos[i + 10] == (playerPos[1] - 1)) {
if(treasureType[i] == 0) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] - 1) + boardCol * (playerPos[1] - 1)] = '@';
--playerPos[0];
--playerPos[1];
if(race == 'h' || race == 'e') playerGold += 1;
if(race == 'd') playerGold += 2;
if(race == 'o') playerGold += 1;
action = name + " moves north-west and picks up a gold coin";
} else if(treasureType[i] == 1) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] - 1) + boardCol * (playerPos[1] - 1)] = '@';
--playerPos[0];
--playerPos[1];
if(race == 'h' || race == 'e') playerGold += 2;
if(race == 'd') playerGold += 4;
if(race == 'o') playerGold += 1;
action = name + " moves north-west and picks up a small horde";
} else if(treasureType[i] == 2) {
bool dragon = false;
if(board[(treasurePos[i]) + boardCol * (treasurePos[i + 10] - 1)] == 'D') dragon = true;
if(board[(treasurePos[i] - 1) + boardCol * (treasurePos[i + 10] - 1)] == 'D') dragon = true;
if(board[(treasurePos[i] + 1) + boardCol * (treasurePos[i + 10] - 1)] == 'D') dragon = true;
if(board[(treasurePos[i] - 1) + boardCol * (treasurePos[i + 10] + 1)] == 'D') dragon = true;
if(board[(treasurePos[i] + 1) + boardCol * (treasurePos[i + 10] + 1)] == 'D') dragon = true;
if(board[(treasurePos[i]) + boardCol * (treasurePos[i + 10] + 1)] == 'D') dragon = true;
if(board[(treasurePos[i] - 1) + boardCol * (treasurePos[i + 10])] == 'D') dragon = true;
if(board[(treasurePos[i] + 1) + boardCol * (treasurePos[i + 10])] == 'D') dragon = true;
if(!dragon) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] - 1) + boardCol * (playerPos[1] - 1)] = '@';
--playerPos[0];
--playerPos[1];
if(race == 'h' || race == 'e') playerGold += 6;
if(race == 'd') playerGold += 12;
if(race == 'o') playerGold += 3;
action = name + " moves north-west and picks up a dragon horde";
} else action = "the dragon defends its horde";
} else if(treasureType[i] == 3) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] - 1) + boardCol * (playerPos[1] - 1)] = '@';
--playerPos[0];
--playerPos[1];
if(race == 'h' || race == 'e') playerGold += 4;
if(race == 'd') playerGold += 8;
if(race == 'o') playerGold += 2;
action = name + " moves north-west and picks up a merchant horde";
}
break;
}
}
} else if(board[(playerPos[0] - 1) + boardCol * (playerPos[1] - 1)] == 'P') {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] - 1) + boardCol * (playerPos[1] - 1)] = '@';
--playerPos[0];
--playerPos[1];
action = name + " moves north-west, on top of a potion" + lookAround();
} else if(board[(playerPos[0] - 1) + boardCol * (playerPos[1] - 1)] == '\\') {
++level;
action = name + " has reached the next level";
goto NEXT_LEVEL;
} else action = name + " bumps into a " + decode(board[(playerPos[0] - 1) + boardCol * (playerPos[1] - 1)]);
} else if(cmd == "sw") {
if(board[(playerPos[0] - 1) + boardCol * (playerPos[1] + 1)] == '.' ||
board[(playerPos[0] - 1) + boardCol * (playerPos[1] + 1)] == '#' ||
board[(playerPos[0] - 1) + boardCol * (playerPos[1] + 1)] == '+') {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] - 1) + boardCol * (playerPos[1] + 1)] = '@';
--playerPos[0];
++playerPos[1];
action = name + " moves south-west" + lookAround();
} else if(board[(playerPos[0] - 1) + boardCol * (playerPos[1] + 1)] == 'G') {
for(int i = 0; i < treasureCount; ++i) {
if(treasurePos[i] == (playerPos[0] - 1) && treasurePos[i + 10] == (playerPos[1] + 1)) {
if(treasureType[i] == 0) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] - 1) + boardCol * (playerPos[1] + 1)] = '@';
--playerPos[0];
++playerPos[1];
if(race == 'h' || race == 'e') playerGold += 1;
if(race == 'd') playerGold += 2;
if(race == 'o') playerGold += 1;
action = name + " moves south-west and picks up a gold coin";
} else if(treasureType[i] == 1) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] - 1) + boardCol * (playerPos[1] + 1)] = '@';
--playerPos[0];
++playerPos[1];
if(race == 'h' || race == 'e') playerGold += 2;
if(race == 'd') playerGold += 4;
if(race == 'o') playerGold += 1;
action = name + " moves south-west and picks up a small horde";
} else if(treasureType[i] == 2) {
bool dragon = false;
if(board[(treasurePos[i]) + boardCol * (treasurePos[i + 10] - 1)] == 'D') dragon = true;
if(board[(treasurePos[i] - 1) + boardCol * (treasurePos[i + 10] - 1)] == 'D') dragon = true;
if(board[(treasurePos[i] + 1) + boardCol * (treasurePos[i + 10] - 1)] == 'D') dragon = true;
if(board[(treasurePos[i] - 1) + boardCol * (treasurePos[i + 10] + 1)] == 'D') dragon = true;
if(board[(treasurePos[i] + 1) + boardCol * (treasurePos[i + 10] + 1)] == 'D') dragon = true;
if(board[(treasurePos[i]) + boardCol * (treasurePos[i + 10] + 1)] == 'D') dragon = true;
if(board[(treasurePos[i] - 1) + boardCol * (treasurePos[i + 10])] == 'D') dragon = true;
if(board[(treasurePos[i] + 1) + boardCol * (treasurePos[i + 10])] == 'D') dragon = true;
if(!dragon) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] - 1) + boardCol * (playerPos[1] + 1)] = '@';
--playerPos[0];
++playerPos[1];
if(race == 'h' || race == 'e') playerGold += 6;
if(race == 'd') playerGold += 12;
if(race == 'o') playerGold += 3;
action = name + " moves south-west and picks up a dragon horde";
} else action = "the dragon defends its horde";
} else if(treasureType[i] == 3) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] - 1) + boardCol * (playerPos[1] + 1)] = '@';
--playerPos[0];
++playerPos[1];
if(race == 'h' || race == 'e') playerGold += 4;
if(race == 'd') playerGold += 8;
if(race == 'o') playerGold += 2;
action = name + " moves south-west and picks up a merchant horde";
}
break;
}
}
} else if(board[(playerPos[0] - 1) + boardCol * (playerPos[1] + 1)] == 'P') {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] - 1) + boardCol * (playerPos[1] + 1)] = '@';
--playerPos[0];
++playerPos[1];
action = name + " moves south-west, on top of a potion" + lookAround();
} else if(board[(playerPos[0] - 1) + boardCol * (playerPos[1] + 1)] == '\\') {
++level;
action = name + " has reached the next level";
goto NEXT_LEVEL;
} else action = name + " bumps into a " + decode(board[(playerPos[0] - 1) + boardCol * (playerPos[1] + 1)]);
} else if(cmd == "se") {
if(board[(playerPos[0] + 1) + boardCol * (playerPos[1] + 1)] == '.' ||
board[(playerPos[0] + 1) + boardCol * (playerPos[1] + 1)] == '#' ||
board[(playerPos[0] + 1) + boardCol * (playerPos[1] + 1)] == '+') {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] + 1) + boardCol * (playerPos[1] + 1)] = '@';
++playerPos[0];
++playerPos[1];
action = name + " moves south-east" + lookAround();
} else if(board[(playerPos[0] + 1) + boardCol * (playerPos[1] + 1)] == 'G') {
for(int i = 0; i < treasureCount; ++i) {
if(treasurePos[i] == (playerPos[0] + 1) && treasurePos[i + 10] == (playerPos[1] + 1)) {
if(treasureType[i] == 0) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] + 1) + boardCol * (playerPos[1] + 1)] = '@';
++playerPos[0];
++playerPos[1];
if(race == 'h' || race == 'e') playerGold += 1;
if(race == 'd') playerGold += 2;
if(race == 'o') playerGold += 1;
action = name + " moves south-east and picks up a gold coin";
} else if(treasureType[i] == 1) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] + 1) + boardCol * (playerPos[1] + 1)] = '@';
++playerPos[0];
++playerPos[1];
if(race == 'h' || race == 'e') playerGold += 2;
if(race == 'd') playerGold += 4;
if(race == 'o') playerGold += 1;
action = name + " moves south-east and picks up a small horde";
} else if(treasureType[i] == 2) {
bool dragon = false;
if(board[(treasurePos[i]) + boardCol * (treasurePos[i + 10] - 1)] == 'D') dragon = true;
if(board[(treasurePos[i] - 1) + boardCol * (treasurePos[i + 10] - 1)] == 'D') dragon = true;
if(board[(treasurePos[i] + 1) + boardCol * (treasurePos[i + 10] - 1)] == 'D') dragon = true;
if(board[(treasurePos[i] - 1) + boardCol * (treasurePos[i + 10] + 1)] == 'D') dragon = true;
if(board[(treasurePos[i] + 1) + boardCol * (treasurePos[i + 10] + 1)] == 'D') dragon = true;
if(board[(treasurePos[i]) + boardCol * (treasurePos[i + 10] + 1)] == 'D') dragon = true;
if(board[(treasurePos[i] - 1) + boardCol * (treasurePos[i + 10])] == 'D') dragon = true;
if(board[(treasurePos[i] + 1) + boardCol * (treasurePos[i + 10])] == 'D') dragon = true;
if(!dragon) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] + 1) + boardCol * (playerPos[1] + 1)] = '@';
++playerPos[0];
++playerPos[1];
if(race == 'h' || race == 'e') playerGold += 6;
if(race == 'd') playerGold += 12;
if(race == 'o') playerGold += 3;
action = name + " moves south-east and picks up a dragon horde";
} else action = "the dragon defends its horde";
} else if(treasureType[i] == 3) {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] + 1) + boardCol * (playerPos[1] + 1)] = '@';
++playerPos[0];
++playerPos[1];
if(race == 'h' || race == 'e') playerGold += 4;
if(race == 'd') playerGold += 8;
if(race == 'o') playerGold += 2;
action = name + " moves south-east and picks up a merchant horde";
}
break;
}
}
} else if(board[(playerPos[0] + 1) + boardCol * (playerPos[1] + 1)] == 'P') {
board[playerPos[0] + boardCol * playerPos[1]] = '.';
board[(playerPos[0] + 1) + boardCol * (playerPos[1] + 1)] = '@';
++playerPos[0];
++playerPos[1];
action = name + " moves south-east, on top of a potion" + lookAround();
} else if(board[(playerPos[0] + 1) + boardCol * (playerPos[1] + 1)] == '\\') {
++level;
action = name + " has reached the next level";
goto NEXT_LEVEL;
} else action = name + " bumps into a " + decode(board[(playerPos[0] + 1) + boardCol * (playerPos[1] + 1)]);
} else action = "invalid";
}
return 0;
}
<file_sep>all:
g++ cc3k.cc -o cc3k
| b02d91f24ebf26aef2e5855c90e00290709f779d | [
"Makefile",
"C++"
] | 2 | C++ | erik-kz/cc3k | 20dafa62b337cedbc657d573cdb7b6e43c49d724 | eb1cda011a15e850ca018d5bc403e04d5774de7e |
refs/heads/master | <repo_name>email2rishi13/myprofile-app<file_sep>/src/controllers/feedback.controller.js
const httpStatus = require('http-status');
const feedbackService = require('../services/feedbackService.service');
module.exports.saveFeedback = async (req, res, next) => {
try {
const { name, email, message } = req.body;
console.log('data from service ',name , email, message)
// const response = await communityService.createJoinCommunityRequest(User, partnerId, communityId);
// if (response.message === 'Already Requested') {
// res.status(httpStatus.ALREADY_REPORTED).json(response);
// } else {
// res.status(httpStatus.OK).json(response);
const returnValue = await feedbackService.insert(name,email,message)
// }
res.status(httpStatus.OK).json({result:returnValue})
} catch (e) {
next(e);
}
}
module.exports.getFeedbacks = async (req, res, next) => {
try {
const name = req.params.name;
const result = await feedbackService.fetch();
res.status(httpStatus.OK).json({result:result, name: name});
} catch(e) {
next(e);
}
}<file_sep>/src/routes/index.route.js
const express = require('express');
const router = express.Router();
const fileRoutes = require('./files.route');
const feedRoutes = require('./feedback.route');
router.get('/health-check', (req, res) => {
res.send('Up and Running!');
});
router.use('/files', fileRoutes);
router.use('/feedback', feedRoutes);
module.exports = router;<file_sep>/src/services/mailer.js
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
module.exports.sendMail = (to, subject, message,html) => {
msg = {to: to, subject: subject, message: message,html: html, from: 'SriMaharshi<<EMAIL>>'}
sgMail.send(msg).then(data => {
console.log('mail sent')
}).catch( err => {
console.log('error ', err)
});
}<file_sep>/src/routes/files.route.js
const express = require('express');
const router = express.Router();
const fileController = require('../controllers/files.controller');
router.get('/resume/:fileName',fileController.getResume);
module.exports = router;<file_sep>/src/routes/feedback.route.js
const express = require("express");
const router = express.Router();
const validate = require("express-validation");
const asyncHandler = require("express-async-handler");
const feedbackValidate = require("../validations/feedback.validation");
const feedbackController = require("../controllers/feedback.controller");
router
.route("/request")
.post(
validate(feedbackValidate.save),
asyncHandler(feedbackController.saveFeedback)
);
router
.route("/request/:name")
.get(
validate(feedbackValidate.fetch),
asyncHandler(feedbackController.getFeedbacks)
);
module.exports = router;
<file_sep>/src/config/config.js
const Joi = require("joi");
require("dotenv").config();
const envVarsSchema = Joi.object({
NODE_ENV: Joi.string()
.allow(["development", "production", "test", "provision"])
.default("development"),
PORT: Joi.number().default(1920),
MONGO_HOST: Joi.string().description("Mongo DB host url"),
MONGO_PORT: Joi.number().default(27017),
MONGOOSE_DEBUG: Joi.boolean().when("NODE_ENV", {
is: Joi.string().equal("development"),
then: Joi.boolean().default(true),
otherwise: Joi.boolean().default(false)
}),
LOGS_FOLDER: Joi.string().description('folder where logs are stored')
})
.unknown()
.required();
const { error, value: envVars } = Joi.validate(process.env, envVarsSchema);
if (error) {
throw new Error(`Config validation error: ${error.message}`);
}
const config = {
env: envVars.NODE_ENV,
port: envVars.PORT,
mongooseDebug: envVars.MONGOOSE_DEBUG,
frontend: envVars.MEAN_FRONTEND || 'angular',
mongo: {
host: envVars.MONGO_HOST,
port: envVars.MONGO_PORT
},
logsFolder: envVars.LOGS_FOLDER
};
module.exports = config;
| b534fc1d67be7ebee6cacfad9f511a476c3c767a | [
"JavaScript"
] | 6 | JavaScript | email2rishi13/myprofile-app | 8cd848f6113193e4b11359a6faae042c8dbe4732 | d3214e5e039de7bae1d3e6118cd43c24f5e8f730 |
refs/heads/master | <file_sep>package com.epam.Dedeepya;
public class kajubarfi extends sweets{
public int calculateweight(int quantity,int weight)
{
return quantity*weight;
}
}
<file_sep># V.Dedeepya_Maven
This is maven project.
<file_sep>package com.epam.Dedeepya;
public class rasmalai extends sweets{
public int calculateweight(int quantity,int weight)
{
return quantity*weight;
}
}
<file_sep>package com.epam.Dedeepya;
public class snickers extends sweets{
public int calculateweight(int quantity,int weight)
{
return weight*quantity;
}
}
| 79a5878ba1b2a0d2b4d930a3cbf17c87b7c5cc02 | [
"Markdown",
"Java"
] | 4 | Java | dedeepyavaddi/V.Dedeepya_Maven | 166196e80367327bc24f46cdab507004852bfb83 | 790e41c2657eb1dce81f8ab7ac509dae6f63329d |
refs/heads/master | <repo_name>Genskill2/07-ssort-aparnasuresh28<file_sep>/swap.c
void swap_max(int a[], int l, int n )
{
int i,temp=0,count=0,max=0;
temp=a[n];
for(i=n+1;i<l;i++)
{
if(a[i]>temp)
{temp=a[i];
count=i;
}
else continue;
}
if(temp>a[n])
{
a[count]=a[n];
a[n]=temp;
}
}
void ssort(int a[], int l)
{
int i;
for(i=0;i<l;++i)
swap_max(a,l,i);
}
| d05935718b3e0d8c09ce5776c266d0a3a15c7ff8 | [
"C"
] | 1 | C | Genskill2/07-ssort-aparnasuresh28 | d8c6cc7d08e82376d7feadef308b3931f73d9828 | a2cdc03e8c651b59309183744077cd71c8ce3ee6 |
refs/heads/master | <repo_name>Maxineshiiba/GameIndustryTrendAnalysis<file_sep>/feed_keyword_index.py
#!/usr/bin/env python
#-*- coding: utf-8 -*-
# Objective: to analyze the leverage ratio of external factors which would affect game performance
# in the market, thereby facilitating the execution of the marketing process in a more cost-effective way
#Logic for current model: Keyword Index is calculated by using the document frequency(DF) of a keyword in the 10 past days, and then attenuate
#the DF value (current day has the largest weight, decay with time), and finally sum all the DF values
#PageRank method is also added in the model
import json,os,string,datetime,time,getopt,math
import sys
parentdir=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0,parentdir)
from BIReport.BI_Engine import *
import numpy as np
import pandas as pd
reload(sys)
sys.setdefaultencoding('utf-8')
class Parameters():
def __init__(self):
self.epsilon = math.pow(10, -5)
self.damp = 0.85
self.weight_list = []
for i in range(10):
self.weight_list.append(math.exp(-i))
self.weight_list.reverse()
def execute(date_begin, date_end):
print 'date_begin=', date_begin, ' date_end=', date_end
if date_begin > date_end:
return 'FAILED: begin_date > end_date'
begin_date = date_begin
end_date = date_end
para = Parameters()
insert_list = []
# print weight_list
while begin_date <= end_date:
insert_list_d = []
date_10d_list = []
for i in range(10):
date_10d_list.append(int((datetime.datetime.strptime(str(begin_date), '%Y%m%d') + datetime.timedelta(days=-i)).strftime('%Y%m%d')))
date_10d_list.reverse()
begin_date_10d = int((datetime.datetime.strptime(str(begin_date), '%Y%m%d') + datetime.timedelta(days=-9)).strftime('%Y%m%d'))
sql_1 = '''
select publish_date, keyword, sum(text_cnt) text_cnt
from (
select a.publish_date
,regexp_split_to_table(keywords,';') as keyword
,1 text_cnt
from spider_feed_wordlist_data a
where a.publish_date >= %s and a.publish_date <= %s
and length(keywords)>0
and a.is_game = 1
) a
--where keyword='android'
group by publish_date, keyword
''' % (begin_date_10d, begin_date)
data_1 = Data(
fields=[Field(code='publish_date'), Field(code='keyword'), Field(code='text_cnt')],
rows=Model('pg', sql_1).getSelect())
sql_keywords = '''
select distinct keyword
from (
select a.publish_date
,regexp_split_to_table(a.keywords,';') as keyword
from spider_feed_wordlist_data a
where a.publish_date >= %s and a.publish_date <= %s
and length(a.keywords)>0
and a.is_game = 1
) a
group by keyword
''' % (begin_date_10d, begin_date)
keywords = Data(fields=[Field(code='keyword')], rows=Model('pg', sql_keywords).getSelect())
# page_rank
keywords_list, PR = text_rank(keywords, date_10d_list)
for i, keyword in enumerate(keywords_list):
data_keyword = data_1.selectData('publish_date,text_cnt', '${keyword} == \"' + keyword + '\"')
data_keyword.orderBy('publish_date')
# print data_keyword
text_cnt_list = []
for date in date_10d_list:
for i, r in enumerate(data_keyword.rows):
if r[0] == date:
text_cnt_list.append(r[1])
break
elif i == len(data_keyword.rows) - 1:
text_cnt_list.append(0)
keyword_pr = PR[i]
keyword_df = 0
for i, w in enumerate(para.weight_list):
keyword_df = keyword_df + w * text_cnt_list[i]
# print begin_date, keyword.decode('utf-8'), text_cnt_list[9], keyword_df, math.exp(keyword_df)
# if begin_date == 20181008 and keyword == '环世界':
# print begin_date, keyword.decode('utf-8'), text_cnt_list[9], keyword_df, math.exp(keyword_df)
# print text_cnt_list, data_keyword.rows, date_10d_list
insert_list_d.append([begin_date, keyword, text_cnt_list[9], 0.8 * keyword_df + (1 - 0.8) * 200 * keyword_pr,
math.pow(0.8 * keyword_df + 0.2 * 100 * keyword_pr, 1.5) * 545, keyword_pr, keyword_df])
# break
insert_list_d.sort(key=lambda x: (x[4]), reverse=True)
for i, ii in enumerate(insert_list_d):
ii.insert(2, i)
insert_list.extend(insert_list_d)
begin_date = int((datetime.datetime.strptime(str(begin_date), '%Y%m%d') + datetime.timedelta(days=1)).strftime('%Y%m%d'))
delete_sql = 'delete from spider_feed_keyword_index where publish_date between %s and %s;' % (date_begin, date_end)
insert_sql = ''
for i in insert_list:
insert_sql = insert_sql + "insert into spider_feed_keyword_index (publish_date, keyword, sort, df_1d, keyword_index, keyword_index_e, pr, df) values (%s, '%s', %s, %s, %s, %s, %s, %s);" \
% (i[0], i[1].replace("'", "''"), i[2], i[3], i[4], i[5], i[6], i[7])
sql = delete_sql + insert_sql
try:
conn = DBHelper().getPGDB()
cur = conn.cursor()
cur.execute(sql)
conn.commit()
cur.close()
conn.close()
except:
print sql
# print sql
return 'done'
def text_rank(keywords_all, date_10d_list):
PR_all = np.ones((len(keywords_all.rows), len(date_10d_list))) / len(keywords_all.rows)
PR_all_result = np.zeros(len(keywords_all.rows))
keywords_list_all = []
for row in keywords_all.rows:
keywords_list_all.append(row[0])
para = Parameters()
sql = '''
select publish_date, keywords
from spider_feed_wordlist_data a
where a.publish_date >= %s and a.publish_date <= %s
and length(keywords)>0 and a.keywords like '%%;%%'
and a.is_game = 1
''' % (date_10d_list[0], date_10d_list[9])
data = Data(fields=[Field(code='publish_date'), Field(code='keywords')], rows=Model('pg', sql).getSelect())
df_data = pd.DataFrame(data.rows, columns=[a.getCode() for a in data.fields])
for d, date in enumerate(date_10d_list):
sql_keywords = '''
select distinct keyword
from (
select a.publish_date
,regexp_split_to_table(a.keywords,';') as keyword
from spider_feed_wordlist_data a
where a.publish_date = %s
and length(a.keywords)>0 and a.keywords like '%%;%%'
and a.is_game = 1
) a
group by keyword
''' % (date)
keywords = Data(fields=[Field(code='keyword')], rows=Model('pg', sql_keywords).getSelect())
keywords_list = []
for row in keywords.rows:
keywords_list.append(row[0])
n = len(keywords.rows)
W = np.zeros((n, n))
# print str(date), "Preprocessing start = ", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
for i, i_row in enumerate(keywords.rows):
for j, j_row in enumerate(keywords.rows):
if i > j:
i_or_j_cnt = len(
df_data.query('(keywords.str.contains(\"' + i_row[0] + '\") or keywords.str.contains(\"' + j_row[0] + '\")) and publish_date==' + str(date)))
if i_or_j_cnt > 0:
i_and_j_cnt = len(
df_data.query('keywords.str.contains(\"' + i_row[0] + '\") and keywords.str.contains(\"' + j_row[0] + '\") and publish_date==' + str(date)))
w_i_j = i_and_j_cnt * 1.0 / i_or_j_cnt
W[i, j] = w_i_j
W[j, i] = w_i_j
# if w_i_j > 0:
# print i, str(date), i_row[0], j_row[0], i_j_cnt, '/', i_cnt, '=', w_i_j
# print str(date), "Preprocessing end = ", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# print 'keywords_list, W', json.dumps(keywords_list, encoding="UTF-8", ensure_ascii=False), W
# print str(date), "PageRank training start = ", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
index0 = np.where(np.max(W, axis=1) == 0)
# print 'indexs_full0 = ', str(index0)
for i in index0:
W[i, :] = 1. / n
W[:, i] = 1. / n
# print 'date=', date, 'n=', n, datetime.datetime.now()
# index_tmp = np.where(np.max(W, axis=1) != 0)
PR = np.ones(n) / n # pagerank score rank
PR_last = np.zeros(n) # ave the score from last time, used for final caculation after iteration is finished
while np.max(abs(PR - PR_last)) > para.epsilon:
PR_last = PR.copy()
PR = (1 - para.damp) / n + para.damp * (PR / (np.sum(W, axis=1).T + para.epsilon)).dot(W)
# print "np.max(abs(PR - PR_last) = ", str(np.max(abs(PR - PR_last)))
# print "PR = ", str(PR)
# print str(date), "PageRank training end = ", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
for i, kw in enumerate(keywords_list):
idx = keywords_list_all.index(kw)
PR_all[idx, d] = PR[i]
for i in range(len(keywords_list_all)):
t_list = []
for j, w in enumerate(para.weight_list):
PR_all_result[i] = PR_all_result[i] + w * PR_all[i][j]
t_list.append(PR_all[i][j])
# print keywords_list_all[i], t_list
return keywords_list_all, PR_all_result
if __name__ == '__main__':
starttime = datetime.datetime.now()
print 'starttime=', starttime
try:
opts, args = getopt.getopt(sys.argv[1:], "b:e:", ["begin_date=", "end_date="])
except getopt.GetoptError:
print "FAILED: input arguments error"
sys.exit()
begin_date = None
end_date = None
for name, value in opts:
if name in ("--begin_date", "-b"):
if value is None or value[0:1] == '-':
print "FAILED: input arguments -b error"
sys.exit()
date_begin = int(value)
if name in ("--end_date", "-e"):
if value is None or value[0:1] == '-':
print "FAILED: input arguments -e error"
sys.exit()
date_end = int(value)
date_begin_1 = int((datetime.datetime.strptime(str(date_begin), '%Y%m%d') + datetime.timedelta(days=-1)).strftime('%Y%m%d'))
date_end_1 = int((datetime.datetime.strptime(str(date_end), '%Y%m%d') + datetime.timedelta(days=-1)).strftime('%Y%m%d'))
result = execute(date_begin_1, date_end_1)
# result = execute(20180920, 20181024)
# result = execute(20181026, 20181027)
print result
endtime = datetime.datetime.now()
interval = endtime - starttime
print '\ntime_consuming:', str(interval)
| d37480f2d913a09291073c37478f116287724501 | [
"Python"
] | 1 | Python | Maxineshiiba/GameIndustryTrendAnalysis | 979827c8f7355ef804e6d9f36d809e65a1e21400 | 284c3c2f0bf2833f0dd8c7a81c899fe8061bd525 |
refs/heads/master | <repo_name>ArtRand/signalAlign_notebook<file_sep>/experiment_scripts/ErrorRate.py
#!/usr/bin/env python
"""ErrorRate.py randomly selects alignments from two experiments and tests their accuracy at a given coverage
The input to this script is a directory of PCR generated alignments and a directory of genomic DNA generated
alignments. The program then randomly selects a given number of alignments and calls VClr to make variant
calls on the sites. The script then records the number of sites called as methyl/non-methyl and compares it
to ground truth (methylated in the genomic DNA case, non-methyl in the PCR case). It then records the error
rate and repeats with more alignments (without replacement).
"""
from __future__ import print_function, division
import sys
import glob
import subprocess as sp
import pandas as pd
import numpy as np
from argparse import ArgumentParser
from random import shuffle
def parse_reads_probs(alignment_files):
lines = []
assert len(alignment_files) > 0, "Didn't provide any alignment files"
for f in alignment_files:
for line in open(f, "r"):
lines.append(line)
assert len(lines) > 0, "Problem parsing files"
return lines
def variant_call_stats(probs, read_score, strand, threshold):
assert len(probs) > 0, "Probs length 0"
vclr_command = ["VClr", "-tool=methyl"]
if strand is not None:
vclr_command.append("-strand={}".format(strand))
if threshold is not None:
vclr_command.append("-t={}".format(threshold))
if read_score is not None:
vclr_command.append("-s={}".format(read_score))
vclr = sp.Popen(vclr_command, stdin=sp.PIPE, stdout=sp.PIPE)
for l in probs:
vclr.stdin.write(l)
output = vclr.communicate()[0]
output = output.split("\n")[1:-1]
vc_dat = {
"site": [],
"call": [],
"coverage": [],
}
for l in output:
l = l.strip().split()
vc_dat["site"].append(int(l[0]))
vc_dat["call"].append(str(l[1]))
vc_dat["coverage"].append(int(l[2]))
vc_dat = pd.DataFrame(vc_dat)
methyl_calls = len(vc_dat[(vc_dat["call"] == "E") | (vc_dat["call"] == "I")])
canonical_calls = len(vc_dat[(vc_dat["call"] == "C") | (vc_dat["call"] == "A")])
mean_coverage = np.mean(vc_dat["coverage"])
return methyl_calls, canonical_calls, mean_coverage
def main(args):
def parse_args():
parser = ArgumentParser(description=__doc__)
parser.add_argument("-pcr", action="store", dest="pcr", required=True)
parser.add_argument("-gen", action="store", dest="genomic", required=True)
parser.add_argument("-N", action="store", dest="N", type=int, required=False, default=10)
parser.add_argument("-i", action="store", dest="iter", type=int, required=False, default=None)
parser.add_argument("-t", action="store", dest="threshold", required=False, default=None)
parser.add_argument("-strand", action="store", dest="strand", required=False, default=None)
parser.add_argument("-s", action="store", dest="read_score", required=False, default=None)
args = parser.parse_args()
return args
args = parse_args()
print("accuracy\tsensitivity\tspecificity\tprecision\tfallout\tmiss_rate\tFDR\tNPV\tmean_coverage")
if args.iter is not None:
i = 0
block_size = args.N
# collect alignments from the PCR directory
pcr_alignments = [x for x in glob.glob(args.pcr)]
shuffle(pcr_alignments)
# collect alignments from genomic directory
gen_alignments = [x for x in glob.glob(args.genomic)]
shuffle(gen_alignments)
if len(gen_alignments) >= len(pcr_alignments):
limit = len(pcr_alignments)
else:
limit = len(gen_alignments)
while i < args.iter:
block_start = i * block_size
block_end = block_start + block_size
if block_end >= limit:
break
pcr_batch = pcr_alignments[block_start:block_end]
gen_batch = gen_alignments[block_start:block_end]
pcr_probs = parse_reads_probs(pcr_batch)
gen_probs = parse_reads_probs(gen_batch)
false_positive, true_negative, pcr_coverage = variant_call_stats(probs=pcr_probs,
strand=args.strand,
threshold=args.threshold,
read_score=args.read_score)
true_positive, false_negative, gen_coverage = variant_call_stats(probs=gen_probs,
strand=args.strand,
threshold=args.threshold,
read_score=args.read_score)
accuracy = (true_positive + true_negative) / (false_positive + true_negative +
true_positive + false_negative)
sensitivity = true_positive / (true_positive + false_negative) # hit rate, recall
specificity = true_negative / (true_negative + false_positive) # true negative rate
precision = true_positive / (true_positive + false_positive) # positive predictive value
fall_out = false_positive / (false_positive + true_negative) # false positive rate
miss_rate = false_negative / (true_positive + false_negative) # false negative rate
fdr = false_positive / (true_positive + false_positive) # false discovery rate
npv = true_negative / (true_negative + false_negative) # negative predictive value
mean_cov = np.mean([pcr_coverage, gen_coverage])
print(accuracy, sensitivity, specificity, precision, fall_out, miss_rate, fdr, npv, mean_cov, sep="\t", end="\n")
i += 1
else:
pcr_dat = parse_reads_probs([args.pcr])
genomic_dat = parse_reads_probs([args.genomic])
false_positive, true_negative, pcr_coverage = variant_call_stats(probs=pcr_dat,
strand=args.strand,
threshold=args.threshold,
read_score=args.read_score)
true_positive, false_negative, gen_coverage = variant_call_stats(probs=genomic_dat,
strand=args.strand,
threshold=args.threshold,
read_score=args.read_score)
accuracy = (true_positive + true_negative) / (false_positive + true_negative + true_positive + false_negative)
sensitivity = true_positive / (true_positive + false_negative) # hit rate, recall
specificity = true_negative / (true_negative + false_positive) # true negative rate
precision = true_positive / (true_positive + false_positive) # positive predictive value
fall_out = false_positive / (false_positive + true_negative) # false positive rate
miss_rate = false_negative / (true_positive + false_negative) # false negative rate
fdr = false_positive / (true_positive + false_positive) # false discovery rate
npv = true_negative / (true_negative + false_negative) # negative predictive value
mean_cov = np.mean([pcr_coverage, gen_coverage])
print(accuracy, sensitivity, specificity, precision, fall_out, miss_rate, fdr, npv, mean_cov, sep="\t", end="\n")
if __name__ == "__main__":
sys.exit(main(sys.argv))
<file_sep>/experiment_scripts/Build1DModel.py
#!/usr/bin/env python
"""This script takes a directory of assignments, which are tab-seperated files containing k-mer to ionic
current pairs with a posterior probability it consolidates them, and reformats the whole thing for
HdpBuildUtil and runs it"""
from __future__ import print_function
import sys
import os
import re
import subprocess
from itertools import product, izip
from argparse import ArgumentParser
from BuildModels import \
make_master_assignment_table,\
make_bulk_build_alignment,\
kmer_length_from_model,\
write_kmers,\
ENTRY_LINE
PATH_TO_SIGNALALIGN = "../../signalAlign/bin"
PATH_TO_5MER_MODEL = "../../signalAlign/models/testModelR9p4_5mer_acegt_template.model"
NUCLEOTIDES = "ACGT"
NUCLEOTIDES_METHYLC = "ACGTE"
def getKmers(kmer_length):
return ["".join(k) for k in product(NUCLEOTIDES, repeat=kmer_length)]
def count_lines_in_build_alignment(build_alignment_path):
count = 0
with open(build_alignment_path, "r") as fH:
for line in fH.xreadlines():
count += 1
return count
def getCGMotifKmers(kmer_length=5):
def find_CGs(k):
return [m.start() for m in re.finditer("CG", k)]
def find_GCs(k):
return [m.start() + 1 for m in re.finditer("GC", k)]
def methylate_kmers(kmers, positions, methyl="E"):
for kmer, pos in izip(kmers, positions):
l_kmer = list(kmer)
for p in pos:
l_kmer[p] = methyl
yield ''.join(l_kmer)
# handle CG containing kmers
kmers = getKmers(kmer_length)
cg_kmers = [k for k in kmers if "CG" in k]
CGs = [find_CGs(k) for k in cg_kmers]
mcg_kmers = [k for k in methylate_kmers(cg_kmers, CGs)]
# handle the complement (GC) kmers
gc_kmers = [k for k in kmers if "GC" in k]
GCs = [find_GCs(k) for k in gc_kmers]
mgc_kmers = [k for k in methylate_kmers(gc_kmers, GCs)]
return mcg_kmers + mgc_kmers
def make_cg_build_alignment(assignments, n_assignments, outfile, threshold=0.8, kmer_length=5):
kmers = ["".join(k) for k in product(NUCLEOTIDES_METHYLC, repeat=kmer_length)]
fH = open(outfile, "w")
strands = ["t"]
write_kmers(assignments, threshold, n_assignments, kmers, ENTRY_LINE, fH, strands=strands)
fH.close()
def main(args):
def parse_args():
parser = ArgumentParser(description=__doc__)
parser.add_argument("-pcr", action="store", dest="pcr", required=True)
parser.add_argument("-gen", action="store", dest="gen", required=True)
parser.add_argument("-o", action="store", dest="out_dir", required=True)
parser.add_argument("--bulk", action="store_true", dest="bulk", required=False, default=False)
parser.add_argument("-s", action="store", dest="assignments", required=False, type=int, default=30)
parser.add_argument("-c", action="store", dest="methyl_assignments", required=False, type=int, default=200)
parser.add_argument("-d", action="store", dest="assignment_threshold", required=False, type=float, default=0.8)
parser.add_argument("-g", action="store", dest="samples", required=False, type=int, default=15000)
parser.add_argument('-t', action='store', type=int, default=100, dest='thinning')
return parser.parse_args()
args = parse_args()
print("Commandline: %s " % " ".join(sys.argv[:]), file=sys.stderr)
workdir = os.path.abspath(args.out_dir)
# routines to make the `build alignment` that is input to the HDP builder
assignments = make_master_assignment_table([args.pcr, args.gen])
out_aln_filename = "build_alignment_CG_{mC}_{C}_{t}.tsv".format(mC=args.methyl_assignments,
C=args.assignments,
t=args.assignment_threshold)
out_build_alignment = os.path.join(workdir, out_aln_filename)
if args.bulk:
make_bulk_build_alignment(assignments, "cytosine2",
n_canonical_assignments=args.assignments,
n_methyl_assignments=args.methyl_assignments,
threshold=args.assignment_threshold,
outfile=out_build_alignment,
strands=["t"])
assert(os.path.exists(out_build_alignment))
else:
make_cg_build_alignment(assignments=assignments,
n_assignments=args.assignments,
outfile=out_build_alignment,
threshold=args.assignment_threshold)
# routines to run the HDP builder
binary = os.path.join(os.path.abspath(PATH_TO_SIGNALALIGN), "buildHdpUtil")
kmer_model = os.path.abspath(PATH_TO_5MER_MODEL)
hdp_type = 10 # singleLevelPrior
grid_start = 50
grid_end = 140
grid_length = 1800
burn_in = 32 * count_lines_in_build_alignment(out_build_alignment)
out_hdp = os.path.join(workdir, "template.singleLevelPrior.nhdp")
build_command = " ".join([binary,
"--verbose",
"--oneD",
"-p %s" % hdp_type,
"-v %s" % out_hdp,
"-l %s" % out_build_alignment,
"-a %s" % kmer_length_from_model(kmer_model),
"-n %s" % args.samples,
"-I %s" % burn_in,
"-t %s" % args.thinning,
"-s %s" % grid_start,
"-e %s" % grid_end,
"-k %s" % grid_length,
"-T %s" % kmer_model,
"-g 1",
"-r 1",
"-j 1",
"-y 1",
"-i 1",
"-u 1"])
subprocess.check_call(build_command.split(), stdout=sys.stdout, stderr=sys.stderr)
sys.exit(0)
if __name__ == "__main__":
sys.exit(main(sys.argv))
<file_sep>/README.md
#### signalAlign Notebooks
This repo contains scripts for running [signalAlign](https://github.com/ArtRand/signalAlign) pipelines. All of the scripts are pretty self explanatory.
Obviously these programs require **signalAlign**.
<file_sep>/experiment_scripts/TrainAndRunModel.py
#!/usr/bin/env python
"""TrainAndRunModel.py trains the transitions for an HMM-HDP then runs a classification experiment
"""
from __future__ import print_function
import sys
import os
from argparse import ArgumentParser
from BuildModels import train_model_transitions, run_variant_calling_experiment
PATH_TO_SIGNALALIGN = os.path.abspath("../../signalAlign/")
PATH_TO_BINS = PATH_TO_SIGNALALIGN + "/bin/"
def main(args):
def parse_args():
parser = ArgumentParser(description=__doc__)
parser.add_argument("-r", action="store", dest="reference", required=True)
parser.add_argument("--pcr_train", action="store", dest="pcr_fofn_train", required=True)
parser.add_argument("--gen_train", action="store", dest="genomic_fofn_train", required=True)
parser.add_argument("--pcr_test", action="store", dest="pcr_fofn_test", required=True)
parser.add_argument("--gen_test", action="store", dest="genomic_fofn_test", required=True)
parser.add_argument('--positions', action='append', dest='positions_file', required=True)
parser.add_argument('--motif', action='append', dest='motif_file', required=True)
parser.add_argument("-tH", action="store", dest="t_hdp", required=True)
parser.add_argument("-cH", action="store", dest="c_hdp", required=True)
parser.add_argument("-T", action="store", dest="t_hmm", required=True)
parser.add_argument("-C", action="store", dest="c_hmm", required=True)
parser.add_argument("-a", action="store", dest="batch", type=int, required=True)
parser.add_argument("-i", action="store", dest="iterations", type=int, required=True)
parser.add_argument("-n", action="store", dest="n_test_alns", type=int, required=True)
parser.add_argument("-x", action="store", dest="degenerate", required=True)
parser.add_argument("-j", action="store", dest="jobs", type=int, required=True)
parser.add_argument("-o", action="store", dest="outpath", required=True)
args = parser.parse_args()
return args
command_line = " ".join(sys.argv[:])
print("Command Line: {cmdLine}\n".format(cmdLine=command_line), file=sys.stderr)
args = parse_args()
working_path = os.path.abspath(args.outpath)
assert len(args.positions_file) == 2 and len(args.motif_file) == 2, "need to give training and testing " \
"positions/motif files"
for i in range(2):
assert os.path.exists(args.positions_file[i]), "Didn't find positions file, looked " \
"{}".format(args.positions_file)
assert os.path.exists(args.motif_file[i]), "Didn't find motif file, looked {}".format(args.motif_file)
positions_file = args.positions_file[0]
#motif_file = args.motif_file[0]
test_positions = args.positions_file[1]
test_motifs = args.motif_file[1]
models = train_model_transitions(fasta=os.path.abspath(args.reference),
pcr_fofn=args.pcr_fofn_train,
genomic_fofn=args.genomic_fofn_train,
degenerate=args.degenerate,
jobs=args.jobs,
positions_file=positions_file,
iterations=args.iterations,
batch_size=args.batch,
outpath=working_path,
stateMachine="threeStateHdp",
t_hdp=args.t_hdp,
c_hdp=args.c_hdp,
t_model=os.path.abspath(args.t_hmm),
c_model=os.path.abspath(args.c_hmm))
run_variant_calling_experiment(fasta=os.path.abspath(args.reference),
pcr_fofn=args.pcr_fofn_test,
genomic_fofn=args.genomic_fofn_test,
jobs=args.jobs,
positions_file=test_positions,
motif_file=test_motifs,
t_model=models[0],
c_model=models[1],
t_hdp=models[2],
c_hdp=models[3],
outpath=working_path,
n=args.n_test_alns,
degenerate=args.degenerate)
if __name__ == "__main__":
sys.exit(main(sys.argv))
<file_sep>/experiment_scripts/BuildModels.py
#!/usr/bin/env python
from __future__ import print_function, division
import os
import sys
import glob
import pandas as pd
import numpy as np
import string
from argparse import ArgumentParser
from subprocess import Popen
from itertools import product
from random import shuffle
from commonFunctions import get_first_seq, make_motif_file, get_all_sequence_kmers, make_CCWGG_positions_file, \
find_ccwgg_motifs
PATH_TO_SIGNALALIGN = os.path.abspath("../../signalAlign/")
PATH_TO_BINS = PATH_TO_SIGNALALIGN + "/bin/"
ENTRY_LINE = "blank\t0\tblank\tblank\t{strand}\t0\t0.0\t0.0\t0.0\t{kmer}\t0.0\t0.0\t{prob}\t{event}\t0.0\n"
def train_test_split_fofn(pcr_reads_dir, genomic_reads_dir, working_directory, split=0.5):
def split_files(files):
shuffle(files)
split_point = int(split * len(files))
return files[:split_point], files[split_point:]
def write_fofn(outfile, files):
with open(outfile, "w") as fH:
for f in files:
fH.write("{filepath}\n".format(filepath=f))
return outfile
pcr_read_files = [pcr_reads_dir + x for x in os.listdir(pcr_reads_dir) if x.endswith(".fast5")]
genomic_read_files = [genomic_reads_dir + x for x in os.listdir(genomic_reads_dir) if x.endswith(".fast5")]
assert len(pcr_read_files) > 0 and len(genomic_read_files) > 0
train_pcr_files, test_pcr_files = split_files(pcr_read_files)
train_gen_files, test_gen_files = split_files(genomic_read_files)
pcr_train_fofn = write_fofn(working_directory + "/pcr_train.fofn", train_pcr_files)
pcr_test_fofn = write_fofn(working_directory + "/pcr_test.fofn", test_pcr_files)
gen_train_fofn = write_fofn(working_directory + "/gen_train.fofn", train_gen_files)
gen_test_fofn = write_fofn(working_directory + "/gen_test.fofn", test_gen_files)
return (pcr_train_fofn, pcr_test_fofn), (gen_train_fofn, gen_test_fofn)
def kmer_length_from_model(model_file):
with open(model_file, "r") as model:
line = model.readline().split()
kmer_length = int(line[-1])
model.close()
assert kmer_length == 5 or kmer_length == 6
return kmer_length
def get_methyl_char(degenerate):
if degenerate == "adenosine":
return "I"
else:
return "E"
def make_positions_file(fasta, degenerate, outfile):
if degenerate == "adenosine":
return make_gatc_position_file(fasta, outfile)
else:
return make_CCWGG_positions_file(fasta, outfile)
def gatc_kmers(sequence_kmers, kmerlength):
assert kmerlength == 5 or kmerlength == 6, "only works with kmer lengths 5 and 6"
# NNNNGATCNNN
methyl_core = "GITC"
normal_core = "GATC"
nucleotides = "ACGT"
fourmers = [''.join(x) for x in product(nucleotides, repeat=4)]
threemers = [''.join(x) for x in product(nucleotides, repeat=3)]
twomers = [''.join(x) for x in product(nucleotides, repeat=2)]
labeled_kmers = []
# add NNNNGA*
if kmerlength == 6:
for fourmer in fourmers:
labeled_kmer = (fourmer + methyl_core)[:kmerlength]
normal_kmer = (fourmer + normal_core)[:kmerlength]
if normal_kmer in sequence_kmers:
labeled_kmers.append(labeled_kmer)
# add NNNGA*T and NNNGA*
for threemer in threemers:
labeled_kmer = (threemer + methyl_core)[:kmerlength]
normal_kmer = (threemer + normal_core)[:kmerlength]
if normal_kmer in sequence_kmers:
labeled_kmers.append(labeled_kmer)
# A*TCNNN
if kmerlength == 6:
labeled_kmer = (methyl_core + threemer)[1:]
normal_kmer = (normal_core + threemer)[1:]
if normal_kmer in sequence_kmers:
labeled_kmers.append(labeled_kmer)
# add NNGA*TC and NNGA*T
for twomer in twomers:
labeled_kmer = (twomer + methyl_core)[:kmerlength]
normal_kmer = (twomer + normal_core)[:kmerlength]
if normal_kmer in sequence_kmers:
labeled_kmers.append(labeled_kmer)
# A*TCNN
if kmerlength == 5:
labeled_kmer = (methyl_core + twomer)[1:]
normal_kmer = (normal_core + twomer)[1:]
if normal_kmer in sequence_kmers:
labeled_kmers.append(labeled_kmer)
# NGA*TCN
if kmerlength == 6:
labeled_kmer = (twomer[0] + methyl_core + twomer[1])
normal_kmer = (twomer[0] + normal_core + twomer[1])
if normal_kmer in sequence_kmers:
labeled_kmers.append(labeled_kmer)
# TODO forgot GA*TCNN for 6mers!
labeled_kmer = (methyl_core + twomer)
normal_kmer = (normal_core + twomer)
if normal_kmer in sequence_kmers:
labeled_kmers.append(labeled_kmer)
if kmerlength == 5:
for onemer in "ACTG":
labeled_kmer = onemer + methyl_core
normal_kmer = onemer + normal_core
if normal_kmer in sequence_kmers:
labeled_kmers.append(labeled_kmer)
labeled_kmer = methyl_core + onemer
normal_kmer = normal_core + onemer
if normal_kmer in sequence_kmers:
labeled_kmers.append(labeled_kmer)
return set(labeled_kmers)
def ctag_kmers(sequence_kmers, kmerlength):
assert kmerlength == 5 or kmerlength == 6, "only works with kmer lengths 5 and 6"
# NNNCTAGNNNN
methyl_core = "CTIG"
normal_core = "CTAG"
nucleotides = "ACGT"
fourmers = [''.join(x) for x in product(nucleotides, repeat=4)]
threemers = [''.join(x) for x in product(nucleotides, repeat=3)]
twomers = [''.join(x) for x in product(nucleotides, repeat=2)]
labeled_kmers = []
# add A*GNNNN
if kmerlength == 6:
for fourmer in fourmers:
labeled_kmer = (methyl_core + fourmer)[2:]
normal_kmer = (normal_core + fourmer)[2:]
if normal_kmer in sequence_kmers:
labeled_kmers.append(labeled_kmer)
# add NNNCTA*
for threemer in threemers:
if kmerlength == 6:
labeled_kmer = (threemer + methyl_core)[:kmerlength]
normal_kmer = (threemer + normal_core)[:kmerlength]
if normal_kmer in sequence_kmers:
labeled_kmers.append(labeled_kmer)
labeled_kmer = (methyl_core + threemer)[1:]
normal_kmer = (normal_core + threemer)[1:]
if normal_kmer in sequence_kmers:
labeled_kmers.append(labeled_kmer)
# A*GNNN
if kmerlength == 5:
labeled_kmer = (methyl_core + threemer)[2:]
normal_kmer = (normal_core + threemer)[2:]
if normal_kmer in sequence_kmers:
labeled_kmers.append(labeled_kmer)
# add NNCTA*G and NNCTA*
for twomer in twomers:
labeled_kmer = (twomer + methyl_core)[:kmerlength]
normal_kmer = (twomer + normal_core)[:kmerlength]
if normal_kmer in sequence_kmers:
labeled_kmers.append(labeled_kmer)
# CTA*GNN
if kmerlength == 6:
labeled_kmer = (methyl_core + twomer)[:kmerlength]
normal_kmer = (normal_core + twomer)[:kmerlength]
if normal_kmer in sequence_kmers:
labeled_kmers.append(labeled_kmer)
# TA*GNN
if kmerlength == 5:
labeled_kmer = (methyl_core + twomer)[1:]
normal_kmer = (normal_core + twomer)[1:]
if normal_kmer in sequence_kmers:
labeled_kmers.append(labeled_kmer)
if kmerlength == 5:
for onemer in nucleotides:
labeled_kmer = onemer + methyl_core
normal_kmer = onemer + normal_core
if normal_kmer in sequence_kmers:
labeled_kmers.append(labeled_kmer)
labeled_kmer = methyl_core + onemer
normal_kmer = normal_core + onemer
if normal_kmer in sequence_kmers:
labeled_kmers.append(labeled_kmer)
return set(labeled_kmers)
def ccwgg_kmers(sequence_kmers, kmer_length):
def check_and_add(methyl_kmer):
normal_kmer = string.translate(methyl_kmer, demethylate)
if normal_kmer in sequence_kmers:
labeled_kmers.append(methyl_kmer)
labeled_kmers = []
methyl_core1 = "CEAGG"
methyl_core2 = "CETGG"
demethylate = string.maketrans("E", "C")
nucleotides = "ACGT"
fourmers = [''.join(x) for x in product(nucleotides, repeat=4)]
threemers = [''.join(x) for x in product(nucleotides, repeat=3)]
twomers = [''.join(x) for x in product(nucleotides, repeat=2)]
# NNNNCC*WGGNN
# NNNNCC*
if kmer_length == 6:
for fourmer in fourmers:
labeled_kmer1 = (fourmer + methyl_core1)[:kmer_length]
labeled_kmer2 = (fourmer + methyl_core2)[:kmer_length]
check_and_add(labeled_kmer1)
check_and_add(labeled_kmer2)
# NNNCC*W and NNNCC*
for threemer in threemers:
labeled_kmer1 = (threemer + methyl_core1)[:kmer_length]
labeled_kmer2 = (threemer + methyl_core2)[:kmer_length]
check_and_add(labeled_kmer1)
check_and_add(labeled_kmer2)
# NNCC*WG and NNCC*W
for twomer in twomers:
labeled_kmer1 = (twomer + methyl_core1)[:kmer_length]
labeled_kmer2 = (twomer + methyl_core2)[:kmer_length]
check_and_add(labeled_kmer1)
check_and_add(labeled_kmer2)
# C*WGGNN
if kmer_length == 6:
labeled_kmer1 = (methyl_core1 + twomer)[1:]
labeled_kmer2 = (methyl_core2 + twomer)[1:]
check_and_add(labeled_kmer1)
check_and_add(labeled_kmer2)
for onemer in nucleotides:
# CC*WGGN and C*WGGN
labeled_kmer1 = methyl_core1 + onemer
labeled_kmer2 = methyl_core2 + onemer
if kmer_length == 6:
check_and_add(labeled_kmer1)
check_and_add(labeled_kmer2)
if kmer_length == 5:
check_and_add(labeled_kmer1[1:])
check_and_add(labeled_kmer2[1:])
labeled_kmer1 = (onemer + methyl_core1)[:kmer_length]
labeled_kmer2 = (onemer + methyl_core2)[:kmer_length]
check_and_add(labeled_kmer1)
check_and_add(labeled_kmer2)
if kmer_length == 5:
check_and_add(methyl_core1)
check_and_add(methyl_core2)
return set(labeled_kmers)
def ggwcc_kmers(sequence_kmers, kmer_length):
def check_and_add(methyl_kmer):
normal_kmer = string.translate(methyl_kmer, demethylate)
if normal_kmer in sequence_kmers:
labeled_kmers.append(methyl_kmer)
labeled_kmers = []
methyl_core1 = "GGAEC"
methyl_core2 = "GGTEC"
demethylate = string.maketrans("E", "C")
nucleotides = "ACGT"
fourmers = [''.join(x) for x in product(nucleotides, repeat=4)]
threemers = [''.join(x) for x in product(nucleotides, repeat=3)]
twomers = [''.join(x) for x in product(nucleotides, repeat=2)]
# NNGGWC*CNNN
# C*CNNNN
for fourmer in fourmers:
labeled_kmer1 = (methyl_core1 + fourmer)[3:]
labeled_kmer2 = (methyl_core2 + fourmer)[3:]
check_and_add(labeled_kmer1)
check_and_add(labeled_kmer2)
# WC*CNNN and C*CNNN
for threemer in threemers:
labeled_kmer1 = (methyl_core1 + threemer)[2:] if kmer_length == 6 else (methyl_core1 + threemer)[3:]
labeled_kmer2 = (methyl_core2 + threemer)[2:] if kmer_length == 6 else (methyl_core2 + threemer)[3:]
check_and_add(labeled_kmer1)
check_and_add(labeled_kmer2)
# GWC*CNN and WC*CNN
for twomer in twomers:
labeled_kmer1 = (methyl_core1 + twomer)[1:] if kmer_length == 6 else (methyl_core1 + twomer)[2:]
labeled_kmer2 = (methyl_core2 + twomer)[1:] if kmer_length == 6 else (methyl_core2 + twomer)[2:]
check_and_add(labeled_kmer1)
check_and_add(labeled_kmer2)
# NNGGWC*
if kmer_length == 6:
labeled_kmer1 = (twomer + methyl_core1)[:kmer_length]
labeled_kmer2 = (twomer + methyl_core2)[:kmer_length]
check_and_add(labeled_kmer1)
check_and_add(labeled_kmer2)
for onemer in nucleotides:
# NGGWC* and NGGWC*C
labeled_kmer1 = (onemer + methyl_core1)[:kmer_length]
labeled_kmer2 = (onemer + methyl_core2)[:kmer_length]
check_and_add(labeled_kmer1)
check_and_add(labeled_kmer2)
# GGWC*CN GWC*CN
labeled_kmer1 = methyl_core1 + onemer if kmer_length == 6 else (methyl_core1 + onemer)[1:]
labeled_kmer2 = methyl_core2 + onemer if kmer_length == 6 else (methyl_core2 + onemer)[1:]
check_and_add(labeled_kmer1)
check_and_add(labeled_kmer2)
if kmer_length == 5:
check_and_add(methyl_core1)
check_and_add(methyl_core2)
return set(labeled_kmers)
def motif_kmers(core, kmer_length=5, multiplier=5):
motifs = []
repeat = kmer_length - len(core)
if repeat == 0:
return [core] * multiplier
else:
for k in product("ACGT", repeat=repeat):
fix = ''.join(k)
motifs.append(fix + core)
motifs.append(core + fix)
return motifs * multiplier
def find_gatc_motifs(sequence):
motif = "GATC"
motif_length = len(motif)
for i, _ in enumerate(sequence):
if sequence[i:i+motif_length] == motif:
yield i + 1
def make_gatc_position_file(fasta, outfile):
outfile = os.path.abspath(outfile)
fH = open(outfile, 'w')
fH.write("X\t")
seq = get_first_seq(fasta)
for i in find_gatc_motifs(seq):
assert seq[i] == "A"
fH.write("{}\t".format(i))
fH.write("\n")
fH.write("X\t")
for i in find_gatc_motifs(seq):
t_pos = i + 1
assert seq[t_pos] == "T"
fH.write("{}\t".format(t_pos)) # + 1 because this is for the reverse complement
fH.write("\n")
fH.close()
return outfile
def make_gatc_or_ccwgg_motif_file(fasta, degenerate, outfile):
if degenerate == "adenosine":
motif_finder = find_gatc_motifs
else:
motif_finder = find_ccwgg_motifs
outfile = os.path.abspath(outfile)
seq = get_first_seq(fasta)
positions = [x for x in motif_finder(seq)]
make_motif_file(positions, seq, outfile)
return outfile
def run_guide_alignment(fasta, pcr_fofn, genomic_fofn, jobs, positions_file, motif_file, t_model, c_model,
outpath, n, degenerate, em_iteration="", t_hdp=None, c_hdp=None):
def get_labels():
if degenerate == "adenosine":
return ["A", "I"]
else:
return ["C", "E"]
working_path = os.path.abspath(outpath)
commands = []
c = PATH_TO_BINS + "runSignalAlign -fofn={fofn} -r={fasta} -T={tModel} -C={cModel} -f=assignments " \
"-o={outpath} -p={positions} -q={targetFile} -X={sub} -n={n} -j={jobs} "
if t_hdp is not None and c_hdp is not None:
c += "-tH={tHdp} -cH={cHdp} ".format(tHdp=os.path.abspath(t_hdp), cHdp=os.path.abspath(c_hdp))
read_sets = [pcr_fofn, genomic_fofn]
labels = get_labels()
working_directories = [working_path + "/pcr_{}".format(em_iteration),
working_path + "/genomic_{}".format(em_iteration)]
assert os.path.exists(t_model), "Didn't find template model, looked {}".format(t_model)
assert os.path.exists(c_model), "Didn't find complement model, looked {}".format(c_model)
for fofn, label, working_directory in zip(read_sets, labels, working_directories):
# assemble the command
command = c.format(fofn=fofn, fasta=fasta, tModel=t_model, cModel=c_model, outpath=working_directory,
positions=positions_file, targetFile=motif_file, sub=label, n=n, jobs=int(jobs/2))
commands.append(command)
os.chdir(PATH_TO_BINS)
procs = [Popen(x.split(), stdout=sys.stdout, stderr=sys.stderr) for x in commands]
status = [p.wait() for p in procs]
os.chdir(working_path)
working_directories = [d + "tempFiles_alignment/*.assignments" for d in working_directories]
return working_directories
def run_variant_calling_experiment(fasta, pcr_fofn, genomic_fofn, jobs, positions_file, motif_file, t_model, c_model,
outpath, n, degenerate, t_hdp, c_hdp):
working_path = os.path.abspath(outpath)
commands = []
c = PATH_TO_BINS + "runSignalAlign -fofn={fofn} -r={fasta} -T={tModel} -C={cModel} -f=variantCaller " \
"-o={outpath} -p={positions} -q={targetFile} -n={n} -j={jobs} -x={degenerate} " \
"-tH={tHdp} -cH={cHdp} -smt=threeStateHdp"
read_sets = [pcr_fofn, genomic_fofn]
working_directories = [working_path + "/{}_pcr_".format(degenerate),
working_path + "/{}_genomic_".format(degenerate)]
assert os.path.exists(t_model), "Didn't find template model, looked {}".format(t_model)
assert os.path.exists(c_model), "Didn't find complement model, looked {}".format(c_model)
assert os.path.exists(t_hdp), "Didn't find template model, looked {}".format(t_hdp)
assert os.path.exists(c_hdp), "Didn't find complement model, looked {}".format(c_hdp)
for fofn, working_directory in zip(read_sets, working_directories):
# assemble the command
command = c.format(fofn=fofn, fasta=fasta, tModel=t_model, cModel=c_model, outpath=working_directory,
positions=positions_file, targetFile=motif_file, n=n, jobs=int(jobs/2), tHdp=t_hdp,
cHdp=c_hdp, degenerate=degenerate)
commands.append(command)
os.chdir(PATH_TO_BINS)
procs = [Popen(x.split(), stdout=sys.stdout, stderr=sys.stderr) for x in commands]
status = [p.wait() for p in procs]
os.chdir(working_path)
return
def make_master_assignment_table(assignment_directories):
def parse_assignment_file(file):
data = pd.read_table(file,
usecols=(0, 1, 2, 3),
names=["kmer", "strand", "level_mean", "prob"],
dtype={"kmer": np.str, "strand": np.str, "level_mean": np.float64, "prob": np.float64},
header=None
)
return data
assignments = []
for d in assignment_directories:
assignments += [x for x in glob.glob(d) if os.stat(x).st_size != 0]
assignment_dfs = []
for f in assignments:
assignment_dfs.append(parse_assignment_file(f))
return pd.concat(assignment_dfs)
def train_model_transitions(fasta, pcr_fofn, genomic_fofn, degenerate, jobs, positions_file, iterations, batch_size,
outpath, t_model, c_model, hdp_type, stateMachine="threeState", t_hdp=None, c_hdp=None,
em_iteration=""):
working_path = os.path.abspath(outpath) + "/"
model_directory = working_path + "{sm}_{it}".format(sm=stateMachine, it=em_iteration)
assert os.path.exists(t_model), "Didn't find template model, looked {}".format(t_model)
assert os.path.exists(c_model), "Didn't find complement model, looked {}".format(c_model)
methyl_char = get_methyl_char(degenerate)
os.chdir(PATH_TO_BINS)
c = "trainModels -fofn={pcr} -fofn={genomic} -X=C -X={methylChar} -r={fasta} -i={iter} -a={batch} --transitions " \
"-smt={smt} -T={tModel} -C={cModel} -j={jobs} -p={positions} -o={out} " \
"".format(pcr=pcr_fofn, genomic=genomic_fofn, fasta=fasta, iter=iterations, batch=batch_size,
smt=stateMachine, tModel=t_model, cModel=c_model, jobs=jobs, methylChar=methyl_char,
positions=positions_file, out=model_directory)
if t_hdp is not None and c_hdp is not None:
c += "-tH={tHdp} -cH={cHdp} ".format(tHdp=os.path.abspath(t_hdp), cHdp=os.path.abspath(c_hdp))
c = PATH_TO_BINS + c
os.system(c)
models = [model_directory + "tempFiles_expectations/template_trained.hmm",
model_directory + "tempFiles_expectations/complement_trained.hmm"]
if t_hdp is not None and c_hdp is not None:
models.append(model_directory + "tempFiles_expectations/template.{}.nhdp".format(hdp_type))
models.append(model_directory + "tempFiles_expectations/complement.{}.nhdp".format(hdp_type))
os.chdir(working_path)
return models
def write_kmers(assignments, threshold, max_assignments, kmer_list, entry_line, fH, strands=["t", "c"]):
for strand in strands:
by_strand = assignments.ix[(assignments['strand'] == strand) & (assignments['prob'] >= threshold)]
for k in kmer_list:
kmer_assignments = by_strand.ix[by_strand['kmer'] == k]
if kmer_assignments.empty:
print("missing kmer {}, continuing".format(k))
continue
kmer_assignments = kmer_assignments.sort_values(['prob'], ascending=0)
n = 0
for _, r in kmer_assignments.iterrows():
fH.write(
entry_line.format(strand=r['strand'], kmer=r['kmer'], event=r['level_mean'], prob=r['prob']))
n += 1
if n >= max_assignments:
break
if n < max_assignments:
print("WARNING didn't find {max} requested assignments for {kmer} only found {found}"
"".format(max=max_assignments, kmer=k, found=n))
def make_build_alignment(assignments, degenerate, kmer_length, ref_fasta, n_canonical_assignments,
n_methyl_assignments, outfile, threshold):
seq = get_first_seq(ref_fasta)
sequence_kmers = get_all_sequence_kmers(seq, kmer_length).keys()
if degenerate == "adenosine":
methyl_kmers = list(gatc_kmers(sequence_kmers=sequence_kmers, kmerlength=kmer_length))
methyl_kmers += list(ctag_kmers(sequence_kmers=sequence_kmers, kmerlength=kmer_length))
else:
methyl_kmers = list(ccwgg_kmers(sequence_kmers=sequence_kmers, kmer_length=kmer_length))
methyl_kmers += list(ggwcc_kmers(sequence_kmers=sequence_kmers, kmer_length=kmer_length))
fH = open(outfile, "w")
write_kmers(assignments, threshold, n_canonical_assignments, sequence_kmers, ENTRY_LINE, fH)
write_kmers(assignments, threshold, n_methyl_assignments, methyl_kmers, ENTRY_LINE, fH)
fH.close()
return outfile
def make_bulk_build_alignment(assignments, degenerate, n_canonical_assignments, n_methyl_assignments, threshold,
outfile, strands=["t", "c"]):
def write_bulk_assignments(assignment_df, max_assignments):
for strand in strands:
by_strand = assignment_df.ix[(assignment_df['strand'] == strand) & (assignment_df['prob'] >= threshold)]
n = 0
for i, r in by_strand.iterrows():
fH.write(
entry_line.format(strand=r['strand'], kmer=r['kmer'], event=r['level_mean'], prob=r['prob']))
n += 1
if n >= max_assignments:
break
if n < max_assignments:
print("WARNING: only found {found} assignments when {requested} were requested"
"".format(found=n, requested=max_assignments))
fH = open(outfile, "w")
methyl_char = get_methyl_char(degenerate)
entry_line = "blank\t0\tblank\tblank\t{strand}\t0\t0.0\t0.0\t0.0\t{kmer}\t0.0\t0.0\t{prob}\t{event}\t0.0\n"
labeled = assignments.loc[assignments["kmer"].str.contains(methyl_char)]
canonical = assignments.loc[~(assignments["kmer"].str.contains(methyl_char))]
write_bulk_assignments(labeled, n_methyl_assignments)
write_bulk_assignments(canonical, n_canonical_assignments)
fH.close()
return outfile
def build_hdp(build_alignment_path, template_model, complement_model, outpath, hdp_type, samples=15000,
em_iteration=""):
working_path = os.path.abspath(outpath) + "/"
build_alignment = os.path.abspath(build_alignment_path)
t_model = os.path.abspath(template_model)
c_model = os.path.abspath(complement_model)
outpath = os.path.abspath(outpath) + "/"
hdp_pipeline_dir = outpath + "hdpPipeline{}/".format(em_iteration)
os.makedirs(hdp_pipeline_dir)
os.chdir(PATH_TO_BINS)
c = "hdp_pipeline --build_alignment={build} -tM={tModel} -cM={cModel} -Ba=1 -Bb=1 -Ma=1 -Mb=1 -La=1 -Lb=1 " \
"-s={samples} --verbose --grid_start=50 --grid_end=140 --grid_length=1800 --verbose -o={out} " \
"--hdp_type=ecoli".format(build=build_alignment, tModel=t_model, cModel=c_model, samples=samples,
out=hdp_pipeline_dir)
c = PATH_TO_BINS + c
os.system(c)
os.chdir(working_path)
return [hdp_pipeline_dir + "template.{}.nhdp".format(hdp_type),
hdp_pipeline_dir + "complement.{}.nhdp".format(hdp_type)]
def HDP_EM(ref_fasta, pcr_fofn, gen_fofn, degenerate, jobs, positions_file, motif_file, n_assignment_alns,
n_canonical_assns, n_methyl_assns, iterations, batch_size, working_path, start_hdps, threshold,
hdp_type, start_temp_hmm, start_comp_hmm, n_iterations, gibbs_samples, bulk):
template_hdp = start_hdps[0]
complement_hdp = start_hdps[1]
template_hmm = start_temp_hmm
complement_hmm = start_comp_hmm
for i in xrange(n_iterations):
# first train the model transitions
hdp_models = train_model_transitions(fasta=ref_fasta,
pcr_fofn=pcr_fofn,
genomic_fofn=gen_fofn,
degenerate=degenerate,
jobs=jobs,
positions_file=positions_file,
iterations=iterations,
batch_size=batch_size,
outpath=working_path,
em_iteration="{}_".format(i),
stateMachine="threeStateHdp",
t_hdp=template_hdp,
c_hdp=complement_hdp,
t_model=template_hmm,
c_model=complement_hmm,
hdp_type=hdp_type)
# next get assignments
assignment_dirs = run_guide_alignment(fasta=ref_fasta,
pcr_fofn=pcr_fofn,
genomic_fofn=gen_fofn,
jobs=jobs,
positions_file=positions_file,
motif_file=motif_file,
n=n_assignment_alns,
em_iteration="{}_".format(i),
degenerate=degenerate,
t_model=hdp_models[0],
c_model=hdp_models[1],
t_hdp=hdp_models[2],
c_hdp=hdp_models[3],
outpath=working_path)
assert kmer_length_from_model(hdp_models[0]) == kmer_length_from_model(
hdp_models[1]), "Models had different kmer lengths"
# assemble them into a big table
master = make_master_assignment_table(assignment_directories=assignment_dirs)
# make the build alignment of assignments
if bulk is True:
build_alignment = make_bulk_build_alignment(assignments=master,
degenerate=degenerate,
n_canonical_assignments=n_canonical_assns,
n_methyl_assignments=n_methyl_assns,
threshold=threshold,
outfile=working_path + "/buildAlignment_{}.tsv".format(i))
else:
build_alignment = make_build_alignment(assignments=master,
degenerate=degenerate,
kmer_length=kmer_length_from_model(hdp_models[0]),
ref_fasta=ref_fasta,
n_canonical_assignments=n_canonical_assns,
n_methyl_assignments=n_methyl_assns,
outfile=working_path + "/buildAlignment_{}.tsv".format(i),
threshold=threshold)
# make new hdps
new_hdps = build_hdp(build_alignment_path=build_alignment,
template_model=hdp_models[0],
complement_model=hdp_models[1],
hdp_type=hdp_type,
outpath=working_path,
samples=gibbs_samples,
em_iteration="_{}".format(i))
template_hdp, template_hmm = new_hdps[0], hdp_models[0]
complement_hdp, complement_hmm = new_hdps[1], hdp_models[1]
return template_hmm, complement_hmm, template_hdp, complement_hdp
def main(args):
def parse_args():
parser = ArgumentParser(description=__doc__)
parser.add_argument("-r", action="store", dest="reference", required=True)
parser.add_argument("-pcr", action="store", dest="pcr_reads", required=True)
parser.add_argument("-gen", action="store", dest="genomic_reads", required=True)
parser.add_argument('--in_template_hmm', '-T', action='store', dest='in_T_Hmm', required=True, type=str)
parser.add_argument('--in_complement_hmm', '-C', action='store', dest='in_C_Hmm', required=True, type=str)
parser.add_argument("-o", action="store", dest="outpath", required=True)
parser.add_argument("-x", action="store", dest="degenerate", required=True)
parser.add_argument('--positions', action='append', dest='positions_file', required=False, default=None)
parser.add_argument('--motif', action='append', dest='motif_file', required=False, default=None)
parser.add_argument('--bulk', action='store_true', dest='bulk', required=False, default=False)
parser.add_argument('--hdp_type', action='store', dest='hdp_type', required=False, default="multiset")
parser.add_argument("-j", action="store", dest="jobs", required=False, default=4, type=int)
parser.add_argument("-i", action="store", dest="iterations", required=False, type=int, default=20)
parser.add_argument("-a", action="store", dest="batch", required=False, type=int, default=15000)
parser.add_argument("-s", action="store", dest="assignments", required=False, type=int, default=30)
parser.add_argument("-c", action="store", dest="methyl_assignments", required=False, type=int, default=200)
parser.add_argument("-n", action="store", dest="n_aligns", required=False, type=int, default=1000)
parser.add_argument("-e", action="store", dest="n_test_alns", required=False, type=int, default=1000)
parser.add_argument("-t", action="store", dest="assignment_threshold", required=False, type=float, default=0.8)
parser.add_argument("-g", action="store", dest="samples", required=False, type=int, default=15000)
parser.add_argument("--hdp_em", action="store", dest="HDP_EM", required=False, type=int, default=None)
parser.add_argument("--split", action="store", dest="split", required=False, type=float, default=0.5)
args = parser.parse_args()
return args
command_line = " ".join(sys.argv[:])
print("Command Line: {cmdLine}\n".format(cmdLine=command_line), file=sys.stderr)
args = parse_args()
# decide which type of HDP to carry through the pipeline
if args.hdp_type == "multiset":
HDP_type = "multisetPriorEcoli"
else:
HDP_type = "singleLevelPriorEcoli"
working_path = os.path.abspath(args.outpath)
reference_location = os.path.abspath(args.reference)
# make the positions and motif file
if args.positions_file is not None and args.motif_file is not None:
assert len(args.positions_file) == 2 and len(args.motif_file) == 2, "need to give training and testing " \
"positions/motif files"
for i in range(2):
assert os.path.exists(args.positions_file[i]), "Didn't find positions file, looked " \
"{}".format(args.positions_file)
assert os.path.exists(args.motif_file[i]), "Didn't find motif file, looked {}".format(args.motif_file)
positions_file = args.positions_file[0]
motif_file = args.motif_file[0]
test_positions = args.positions_file[1]
test_motifs = args.motif_file[1]
else:
# make the positions file
positions_file = make_positions_file(fasta=args.reference,
degenerate=args.degenerate,
outfile=working_path + "/{}_positions.positions".format(args.degenerate))
# make the motif file
motif_file = make_gatc_or_ccwgg_motif_file(fasta=args.reference,
degenerate=args.degenerate,
outfile=working_path + "/{}_target.target".format(args.degenerate))
test_positions = positions_file
test_motifs = motif_file
# make the fofns for training and testing
pcr_fofns, gen_fofns = train_test_split_fofn(pcr_reads_dir=args.pcr_reads,
genomic_reads_dir=args.genomic_reads,
working_directory=working_path,
split=args.split)
# train the transitions
models = train_model_transitions(fasta=reference_location,
pcr_fofn=pcr_fofns[0],
genomic_fofn=gen_fofns[0],
degenerate=args.degenerate,
jobs=args.jobs,
positions_file=positions_file,
iterations=args.iterations,
batch_size=args.batch,
outpath=working_path,
hdp_type=HDP_type,
t_model=os.path.abspath(args.in_T_Hmm),
c_model=os.path.abspath(args.in_C_Hmm))
# do the initial alignments
assignment_dirs = run_guide_alignment(fasta=reference_location,
pcr_fofn=pcr_fofns[0],
genomic_fofn=gen_fofns[0],
jobs=args.jobs,
positions_file=positions_file,
motif_file=motif_file,
n=args.n_aligns,
degenerate=args.degenerate,
t_model=models[0],
c_model=models[1],
outpath=working_path)
assert kmer_length_from_model(models[0]) == kmer_length_from_model(models[1]), "Models had different kmer lengths"
# concatenate the assignments into table
master = make_master_assignment_table(assignment_dirs)
if args.bulk is True:
build_alignment = make_bulk_build_alignment(assignments=master,
degenerate=args.degenerate,
n_canonical_assignments=args.assignments,
n_methyl_assignments=args.methyl_assignments,
threshold=args.assignment_threshold,
outfile=working_path + "/buildAlignment.tsv")
else:
build_alignment = make_build_alignment(assignments=master,
degenerate=args.degenerate,
kmer_length=kmer_length_from_model(models[0]),
ref_fasta=reference_location,
n_canonical_assignments=args.assignments,
n_methyl_assignments=args.methyl_assignments,
outfile=working_path + "/buildAlignment.tsv",
threshold=args.assignment_threshold)
# build hdp
hdps = build_hdp(build_alignment_path=build_alignment,
template_model=models[0],
complement_model=models[1],
hdp_type=HDP_type,
outpath=working_path,
samples=args.samples)
if args.HDP_EM is not None:
hdp_models = HDP_EM(ref_fasta=reference_location,
pcr_fofn=pcr_fofns[0],
gen_fofn=gen_fofns[0],
degenerate=args.degenerate,
jobs=args.jobs,
positions_file=positions_file,
motif_file=motif_file,
n_assignment_alns=args.n_aligns,
n_canonical_assns=args.assignments,
n_methyl_assns=args.methyl_assignments,
iterations=args.iterations,
batch_size=args.batch,
working_path=working_path,
start_hdps=hdps,
threshold=args.assignment_threshold,
start_temp_hmm=models[0],
start_comp_hmm=models[1],
n_iterations=args.HDP_EM,
gibbs_samples=args.samples,
bulk=args.bulk,
hdp_type=HDP_type)
else:
# train HMM/HDP
hdp_models = train_model_transitions(fasta=reference_location,
pcr_fofn=pcr_fofns[0],
genomic_fofn=gen_fofns[0],
degenerate=args.degenerate,
jobs=args.jobs,
positions_file=positions_file,
iterations=args.iterations,
batch_size=args.batch,
outpath=working_path,
stateMachine="threeStateHdp",
t_hdp=hdps[0],
c_hdp=hdps[1],
hdp_type=HDP_type,
t_model=os.path.abspath(args.in_T_Hmm),
c_model=os.path.abspath(args.in_C_Hmm))
# run methylation variant calling experiment
run_variant_calling_experiment(fasta=reference_location,
pcr_fofn=pcr_fofns[1],
genomic_fofn=gen_fofns[1],
jobs=args.jobs,
positions_file=test_positions,
motif_file=test_motifs,
t_model=hdp_models[0],
c_model=hdp_models[1],
outpath=working_path,
n=args.n_test_alns,
degenerate=args.degenerate,
t_hdp=hdp_models[2],
c_hdp=hdp_models[3])
# run the control experiment
#run_variant_calling_experiment(fasta=os.path.abspath(args.reference),
# pcr_reads=os.path.abspath(args.pcr_reads) + "/",
# genomic_reads=os.path.abspath(args.genomic_reads) + "/",
# jobs=args.jobs,
# positions_file=positions_file,
# motif_file=motif_file,
# t_model=hdp_models[0],
# c_model=hdp_models[1],
# outpath=working_path,
# n=args.n_test_alns,
# degenerate="variant",
# t_hdp=hdp_models[2],
# c_hdp=hdp_models[3])
if __name__ == "__main__":
sys.exit(main(sys.argv))
| c84d00337d355c62649eee55f547c62a7cb39300 | [
"Markdown",
"Python"
] | 5 | Python | ArtRand/signalAlign_notebook | e9e40348f0d18328bbc925db8852ab6dc997aceb | ee0803735d76353584408616bc88a125042fd37e |
refs/heads/master | <file_sep>import React from 'react'
import cx from 'classnames'
import styles from '../../assets/css/header.module.scss';
import {HiClipboardList} from 'react-icons/hi'
function index() {
return (
<div className={cx(styles.header)} >
<span><HiClipboardList className={styles.appIcon}/></span>
<h2 className={styles.appTitle}>Drello</h2>
</div>
)
}
export default index
<file_sep>import React from 'react'
import { useState,useEffect } from 'react'
import drello1 from '../../assets/img/drello_1.jpg'
import drello2 from '../../assets/img/drello2.gif'
import drello3 from '../../assets/img/drello3.gif'
import useMediaQuery from "@material-ui/core/useMediaQuery";
import { indigo, blue, blueGrey } from "@material-ui/core/colors";
import { AutoRotatingCarousel, Slide } from "material-auto-rotating-carousel";
function Index() {
const [handleOpen, setHandleOpen] = useState({ open: true });
useEffect(() =>{
let modalState = localStorage.getItem('modalState');
if(modalState){
setHandleOpen({ open:false})
}
},[])
const matches = useMediaQuery("(max-width:800px)");
// Carousel Modal
const AutoRotatingCarouselModal = ({ handleOpen, setHandleOpen, isMobile }) => {
return (
<div>
<AutoRotatingCarousel
label="Get started"
open={handleOpen.open}
interval = {16000}
onClose={() =>
{ localStorage.setItem('modalState',JSON.stringify('true'));
setHandleOpen({ open: false })}}
onStart={() => {
localStorage.setItem('modalState',JSON.stringify('true'));
setHandleOpen({ open: false })}
}
autoplay={true}
mobile={isMobile}
style={{ position: "absolute" }}
>
<Slide
media={
<img alt="intoImg0" className="stylesImg" src={drello1} />
}
mediaBackgroundStyle={{ backgroundColor: indigo[600] }}
style={{ backgroundColor: indigo[900] }}
title="Welcome to Drello"
subtitle="Your Go to app for managing your tasks"
/>
<Slide
media={
<img alt="introImg1" className="stylesImg" src={drello2} />
}
mediaBackgroundStyle={{ backgroundColor: blue[600] }}
style={{ backgroundColor: blue[900] }}
title="Manage Tasks"
subtitle="Manage your tasks across the Todo,Doing and Done Task lists. Drag and drop tasks among them or outside to remove a task"
/>
<Slide
media={
<img alt="introImg2" className="stylesImg" src={drello3} />
}
mediaBackgroundStyle={{ backgroundColor: blueGrey[600] }}
style={{ backgroundColor: blueGrey[800] }}
title="Change Background"
subtitle="Change the background just the way you like it. Either be it an image from unsplash or a color of your choice"
/>
</AutoRotatingCarousel>
</div>
);
};
return (
<div>
<AutoRotatingCarouselModal
autoplay = {true}
interval = {500}
isMobile={matches}
handleOpen={handleOpen}
setHandleOpen={setHandleOpen}
/>
</div>
)
}
export default Index
<file_sep>import './App.css';
import Header from './components/header'
import Subheader from './components/subheader';
import Board from './components/board';
import SideBar from './components/sideBar';
import IntroModal from './components/introModal'
import { css } from "@emotion/core";
import HashLoader from "react-spinners/HashLoader";
import { useState } from 'react'
function App() {
let [sideBarState,setSideBarState] = useState("hide");
// Loader
let [loading, setLoading] = useState(true);
let color = ("#111");
const override = css`
display: block;
color:black;
margin: 0 auto;
`;
setTimeout(()=>{
setLoading(false);
},3000)
let showSideBar = ()=>{
setSideBarState("show")
}
let hideSideBar = ()=>{
setSideBarState("hide");
}
if(loading){
return (
<div className="loaderContainer">
<HashLoader color={color} loading={loading} css={override} size={80} />
</div>
)
}
else{
return (
<div >
<IntroModal/>
<Header/>
<Subheader showSideBar = {showSideBar}/>
<Board/>
<SideBar sideBarState={sideBarState} hideSideBar={hideSideBar} />
</div>
);
}
}
export default App;
<file_sep>const initialData= {
// All Actual Tasks
tasks:{
},
// The Tasks in a specific column
columns:{
'todo':{
id:'todo',
taskIds:[]
},
'doing':{
id:'doing',
taskIds:[]
},
'done':{
id:'done',
taskIds:[]
}
},
// For Reordering of columns
columnOrder:['todo','doing','done']
}
export default initialData;<file_sep>import React,{useState,useEffect} from 'react'
import cx from 'classnames'
import styles from '../../assets/css/sidebar.module.scss'
import photosImg from '../../assets/img/photos.jpg'
import colorsImg from '../../assets/img/colors.jpg'
import errorImg from '../../assets/img/errorImg.png'
import {SketchPicker} from 'react-color';
import { createApi } from 'unsplash-js';
import {BsArrowLeft,BsSearch} from 'react-icons/bs'
import {FaTimesCircle} from 'react-icons/fa'
import ClipLoader from "react-spinners/ClipLoader";
function Index(props) {
// Loader State
let [loading, setLoading] = useState(false);
let color = "#ffffff"
// Elements State
let [buttonsState,setButtonsState] = useState(true);
let [photoState,setPhotoState] = useState(false);
let [colorPickerState,setColorPickerState] = useState(false);
// Background State
let [images,setImages] = useState('');
let [bgColor,setBgColor] = useState('');
let [bgImg,setBgImg] = useState('');
let [errImgState,setErrImgState] = useState('');
let [imgInputTxt,setImgInputTxt] = useState('');
// Getting saved background State
useEffect(() =>{
let bgUrl = JSON.parse(localStorage.getItem("bgUrl"))
let bgColor = JSON.parse(localStorage.getItem("bgColor"))
if(bgColor){
setBgColor(bgColor);
setBgImg('');
}
else{
setBgImg('https://images.unsplash.com/photo-1460355976672-71c3f0a4bdac?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D®ular=format&fit=crop&w=1500&q=80');
}
if(bgUrl){
setBgImg(bgUrl)
}
},[])
// Fetch Images From Unsplash
const unsplash = createApi({ accessKey: "<KEY>" });
let fetchImages= async (searchQuery)=>{
setLoading(true);
if(!searchQuery){
searchQuery = "nature landscape"
}
unsplash.search.getPhotos({
query: searchQuery,
perPage: 14,
page:1,
orientation: 'landscape'
}).then((result)=>{
console.log(result.response)
setImages(result.response.results);
setLoading(false);
setErrImgState(false);
}).catch((err)=>{
setErrImgState(true);
setLoading(false)
})
}
// Handle Background Change
let handleBgImage = (url)=>{
setBgColor('');
setBgImg(url);
localStorage.setItem('bgUrl',JSON.stringify(url));
}
let onBgColorChange = (color) => {
localStorage.setItem('bgColor',JSON.stringify(color.hex));
localStorage.setItem('bgUrl',JSON.stringify(''));
setBgColor(color.hex);
setBgImg(null);
};
// Images Jsx
let renderImages = ()=>{
if(errImgState){
return ;
}
else if(images){
return images.map(image =>{
return (
<div key={image.id} className={styles.board_boarder}>
<span onClick={()=>{handleBgImage(image.urls.regular)}} className={styles.bgImg} style={{ backgroundImage: `url(${image.urls.small})` }}>
</span>
</div>
)
})
}
}
// Showing and Hiding SideBar Internal Elements
let showPhotos =()=>{
setImgInputTxt('');
setPhotoState(true);
setButtonsState(false);
fetchImages();
}
let showColorPicker=()=>{
setButtonsState(false);
setPhotoState(false);
setColorPickerState(true);
}
let hideSideBar = ()=>{
setColorPickerState(false);
setImgInputTxt('');
setPhotoState(false)
props.hideSideBar();
setButtonsState(true)
}
return (
<div className={cx(styles.sideBar,props.sideBarState==='hide'? styles.hideSideBar:styles.showSideBar )}>
<div className={styles.sideBarWrapper}>
<style>{`body {background: url(${bgImg}) ${bgColor} no-repeat center/cover fixed !important;}`}</style>
{/* Error Image */}
<div className={cx(styles.errImgWrapper,errImgState ? styles.showErrImg: styles.hideErrImg)}>
<img alt="errorImg" className={styles.errImg} src={errorImg} ></img>
</div>
<h4 className={styles.sideBarTitle}>Change Background </h4>
<span onClick={hideSideBar}><FaTimesCircle className={styles.hideSideBarBtn}/></span>
{/* Initial Option Buttons */}
<div className={cx(styles.buttonsContainer,buttonsState ? styles.buttonsContainerShow: styles.buttonsContainerHide)}>
<div className={styles.buttonWrapper}
onClick={showPhotos}>
<img alt="randImg" className={styles.photosImg} src={photosImg}></img>
<h3>Photos</h3>
</div>
<div className={styles.buttonWrapper}
onClick={showColorPicker}>
<img alt="randImg 1" className={styles.colorsImg} src={colorsImg}></img>
<h3>Colors</h3>
</div>
</div>
<div>
{/* Images Section */}
<div className={cx(styles.imageSectionContainer,photoState ? styles.photoContainerShow: styles.photoContainerHide)}>
<BsArrowLeft className={styles.backArrow} onClick={()=>{setButtonsState(true);setPhotoState(false); setErrImgState(false)}}/>
<h4 className={styles.sideBarSubTitle}>Photos by Unsplash</h4>
<div></div>
<div className={styles.imgInputWrapper}>
<input placeholder="Search..." className={styles.imgInput} value = {imgInputTxt} type="text" onChange={(e)=>{setImgInputTxt(e.target.value);fetchImages(imgInputTxt)}}/>
<BsSearch onClick={()=>{fetchImages(imgInputTxt)}} className={styles.searchIcon}/>
</div>
<div className={styles.imageGalleryWrapper}>
{renderImages()}
</div>
</div>
{/* Color Picker */}
<div className={cx(styles.colorPalette,colorPickerState ? styles.colorPickerShow: styles.colorPickerHide)}>
<BsArrowLeft className={styles.backArrow} onClick={()=>{setButtonsState(true);setColorPickerState(false)}}/>
<SketchPicker width={220} className={styles.colorPaletteActual} color={bgColor} onChangeComplete={ onBgColorChange }/>
</div>
</div>
{/* Loader */}
<div className={styles.loaderContainer}>
<ClipLoader css={styles.cliploader} color={color} loading={loading} size={50} />
</div>
</div>
</div>
)
}
export default Index
| 6b6b59d73d3254ff9c08b2bb5419b33edba87261 | [
"JavaScript"
] | 5 | JavaScript | hassanalimalek/Drello | 131a0bf058eeebc7c6b3d8553c3c4cf9ccba0257 | cc9775f9757cf631d5249c2afe03eb08f267abbd |
refs/heads/main | <file_sep># Sorteio-times
⚽ Site desenvolvido com HTML, CSS e JavaScript com o objetivo de recolher nomes dos jogadores da sua partida de futebol e sortear times aleatórios
<file_sep>// Array que armazena os jogadores
jogadores = []
let nomeJogador = document.querySelector('input#txtjogador')
// Variáveis que recebem os inputs necessários
let addJogador = document.querySelector('input#btnjogador')
let removeJogador = document.querySelector('input#btnexclusao')
let txtExclusao = document.querySelector('input#txtexclusao')
let qtdJogadores = document.querySelector('input#numeroJogadores')
let btnEscalar = document.querySelector('input#btnescalar')
let txtQtdJogadores = document.querySelector('select#numeroJogadores')
let btnSortear = document.querySelector('input#btnsorteio')
let areaTime = document.querySelector('div.conteudo-times')
// Array que armazena os nomes dos jogadores dos cards time
let players = []
for(let i = 0; i < 25; i++){
players[i] = document.querySelector(`h1#j${i+1}`)
}
// Variáveis que armazenam os inputs presentes nos alertas
let alerta = document.querySelector('div.alerta')
// let cancelar = document.querySelector('input#btncancelar')
let cancelar2 = document.querySelector('input#btncancelar2')
let confirmar = document.querySelector('input#btnconfirmar')
let confirmar2 = document.querySelector('input#btnconfirmar2')
// Variável que a lista de jogadores
let lista = document.querySelector('div.lista-jogadores')
function paginaJogadores(){
// Atribuição de eventos aos inputs
addJogador.addEventListener('click', adicionarJogador)
confirmar.addEventListener('click', fecharAlerta)
confirmar2.addEventListener('click', fecharAlerta)
removeJogador.addEventListener('click', removerJogador)
btnEscalar.addEventListener('click', exibirAreaTimes)
btnSortear.addEventListener('click', gerarTimes)
// Alertas iniciam desabilitados
document.getElementById("alerta").style.display = "none"
document.getElementById("alerta2").style.display = "none"
document.getElementById("alerta3").style.display = "none"
}
// Função que adiciona os jogadores ao array e cria os cards do front
function adicionarJogador(){
if(nomeJogador.value != ''){
jogadores.push(nomeJogador.value)
let h1Lista = document.querySelector('h1#titulo-lista-jogadores')
h1Lista.innerHTML = 'Jogadores Convocados'
document.getElementById("chuteira").style.display = "none"
let itemLista = document.createElement('div')
itemLista.setAttribute('class', 'item-jogadores')
itemLista.setAttribute('id', nomeJogador.value)
let tituloLista = document.createElement('div')
tituloLista.setAttribute('class', 'nome-jogador')
let labelTitulo = document.createElement('h1')
labelTitulo.innerHTML = nomeJogador.value
let botaoItem = document.createElement('div')
botaoItem.setAttribute('class', 'botao-jogador')
let botao = document.createElement('input')
botao.setAttribute("type", "button")
botao.value = 'X'
botao.setAttribute('id', 'btnremover')
botao.setAttribute('onclick', 'exibirAlerta()')
document.getElementById("area-escalar").style.display = "block"
document.getElementById("btnescalar").style.display = "block"
lista.appendChild(itemLista)
itemLista.appendChild(tituloLista)
tituloLista.appendChild(labelTitulo)
itemLista.appendChild(botaoItem)
botaoItem.appendChild(botao)
nomeJogador.value = ''
nomeJogador.focus()
}else{
document.getElementById("alerta2").style.display = "block"
document.getElementById("lista-jogadores").style.display = "none"
}
}
// Função que remove os jogadores do array e desabilita o card do front
function removerJogador(){
if(txtExclusao.value != ''){
if(jogadores.indexOf(txtExclusao.value) != -1){
jogadores.splice(jogadores.indexOf(txtExclusao.value), 1);
document.getElementById("alerta").style.display = "none"
document.getElementById(txtExclusao.value).style.display = "none"
txtExclusao.value = ''
document.getElementById("alerta3").style.display = "block"
}else{
alert('Jogador inexistente!')
}
}else{
document.getElementById("alerta").style.display = "none"
document.getElementById("alerta2").style.display = "block"
}
}
function exibirAlerta(){
document.getElementById("alerta").style.display = "block"
document.getElementById("lista-jogadores").style.display = "none"
}
function fecharAlerta(){
document.getElementById("alerta").style.display = "none"
document.getElementById("alerta2").style.display = "none"
document.getElementById("alerta3").style.display = "none"
document.getElementById("lista-jogadores").style.display = "block"
}
function exibirAreaTimes(){
document.getElementById("area-times").style.display = "block"
document.getElementById("section-jogadores").style.display = "none"
}
// Função que determina o número de jogadores por time
let verificador = 0
function gerarTimes(){
if(txtQtdJogadores.value != "0"){
let times = sortearTime()
if(txtQtdJogadores.value == 5){
separarTimes()
}else if(txtQtdJogadores.value == 11){
alert('11 jogadores')
}
}else{
alert('Opaa, selecione o número de jogadores!')
}
}
// Função que retorna um array com valores sorteados
function sortearTime(){
let times = [jogadores[0]]
while(times.length <= jogadores.length - 1){
let pos = Math.random() * (jogadores.length - 1) + 1
if(times.indexOf(jogadores[Math.floor(pos)]) == -1){
times.push(jogadores[Math.floor(pos)])
}
}
return times
}
// Função que separa os times de 5 em 5
function separarTimes(){
let times = sortearTime()
if(verificador == 0){
for(let i in players){
players[i].innerHTML = times[i]
}
if(times.length < 5){
alert('Número de jogadores insuficientes!')
}else if(times.length == 5){
document.getElementById("card-time1").style.display = "block"
}else if(times.length > 5 && times.length < 11){
doisTimes()
}else if(times.length > 10 && times.length < 16){
tresTimes()
}else if(times.length > 15 && times.length < 21){
quatroTimes()
}else if(times.length > 20 && times.length < 26){
cincoTimes()
}
verificador++
}else{
document.getElementById("card-time1").style.display = "none"
document.getElementById("card-time2").style.display = "none"
document.getElementById("card-time3").style.display = "none"
document.getElementById("card-time4").style.display = "none"
document.getElementById("card-time5").style.display = "none"
for(let i in players){
players[i].innerHTML = times[i]
}
if(times.length == 5){
document.getElementById("card-time1").style.display = "block"
}else if(times.length > 5 && times.length < 11){
doisTimes()
}else if(times.length > 10 && times.length < 16){
tresTimes()
}else if(times.length > 15 && times.length < 21){
quatroTimes()
}else if(times.length > 20 && times.length < 26){
cincoTimes()
}
}
}
function doisTimes(){
document.getElementById("card-time1").style.display = "block"
document.getElementById("card-time2").style.display = "block"
}
function tresTimes(){
document.getElementById("card-time1").style.display = "block"
document.getElementById("card-time2").style.display = "block"
document.getElementById("card-time3").style.display = "block"
}
function quatroTimes(){
document.getElementById("card-time1").style.display = "block"
document.getElementById("card-time2").style.display = "block"
document.getElementById("card-time3").style.display = "block"
document.getElementById("card-time4").style.display = "block"
}
function cincoTimes(){
document.getElementById("card-time1").style.display = "block"
document.getElementById("card-time2").style.display = "block"
document.getElementById("card-time3").style.display = "block"
document.getElementById("card-time4").style.display = "block"
document.getElementById("card-time5").style.display = "block"
}
| ac453471eb77cb718819cfcc2d1335f907ef004f | [
"Markdown",
"JavaScript"
] | 2 | Markdown | PauloLeal22/Sorteio-Equipes | 248c9aded749bc5225a8697a95f7661fbc979750 | 7b8dd5ccfd6c28f436e4bdec07a276a421f4f8b8 |
refs/heads/master | <repo_name>williamdistler/elevadorIndustrial<file_sep>/Elevador.java
class Elevador {
private String codigo;
private int estado; //0, 1, 2 ou 3
private int posicao;
private int totalRun; //historico deslocamento
public void inicializar(String codigo) {
if (this.estaDesligado()) {
this.codigo = codigo;
this.totalRun = 0;
this.estado = 1;
} else {
System.out.println("(log) falha ao inicializar!");
}
}
public void ligar() {
if(this.estado == 0)
this.estado = 1;
else
System.out.println("(log) falha, no ligar!");
}
public void desligar() {
if(this.estado == 1 && this.posicao == 0) //ligado e esta no terreo
this.estado = 0;
else
System.out.println("(log) falha, ao desligar!");
}
public void mover(int destino) {
if(destino >= 0 && estado ==1){
int distancia;
if(destino > posicao){
System.out.println("(log) subindo ...!");
distancia = destino - posicao;
} else {
System.out.println("(log) descendo ...!");
distancia = posicao - destino;
}
totalRun = this.totalRun + distancia;
this.posicao = destino;
} else {
System.out.println("(log) falha, no mover!");
}
}
public String getCodigo() {
return this.codigo;
}
public int getPosicao() {
return posicao;
}
public int getTotalRun() {
return totalRun;
}
public boolean estaDesligado() {
if (estado == 0)
return true;
return false;
}
} | 85c4ed021b4b78035d4eab46774b39ab8a870bef | [
"Java"
] | 1 | Java | williamdistler/elevadorIndustrial | d41fa4e8f44a2cd5cf5355c9733ad4e2117af034 | 86bb15e005ac31754075b8ba7fc1fb0cdbddb9b6 |
refs/heads/master | <file_sep>s = "BEEKEEPER"
binarydict = {
"B": "1 ",
"E": "0 ",
"K": "01 ",
"P": "00 ",
"R": "10 "
}
def binary_replace(string, dictionary):
for letter in string:
if letter in dictionary.keys():
string = string.replace(letter, dictionary[letter])
return string
print(binary_replace(s, binarydict))
<file_sep># StringManipulation
Hopefully this is done correctly, I was thinking of coding it with only 0's in the dictionary as to be fastest but am unsure if it would make a difference. E.G. 0, 00, 000, 0000...
| 7697baa3c15c9f64a54aa684aba6fa4f2c991837 | [
"Markdown",
"Python"
] | 2 | Python | BenLanden/StringManipulation | 9fb8621722c984d42d307419ab3c4eca12c0ecd3 | 2bc8761d085a2e30e0ef27bf09c431349c9b29cd |
refs/heads/master | <file_sep>package cmds
import (
"bufio"
"fmt"
"os"
"strings"
"github.com/pachyderm/pachyderm/src/client"
"github.com/pachyderm/pachyderm/src/client/auth"
"github.com/pachyderm/pachyderm/src/client/pkg/config"
"github.com/pachyderm/pachyderm/src/server/pkg/cmdutil"
"github.com/spf13/cobra"
)
var githubAuthLink = `https://github.com/login/oauth/authorize?client_id=d3481e92b4f09ea74ff8&redirect_uri=https%3A%2F%2Fpachyderm.io%2Flogin-hook%2Fdisplay-token.html`
// ActivateCmd returns a cobra.Command to activate the security features of
// Pachyderm within a Pachyderm cluster. All repos will go from
// publicly-accessible to accessible only by the owner, who can subsequently add
// users
func ActivateCmd() *cobra.Command {
var admins []string
activate := &cobra.Command{
Use: "activate activation-code",
Short: "Activate the security features of pachyderm with an activation " +
"code",
Long: "Activate the security features of pachyderm with an activation " +
"code",
Run: cmdutil.RunFixedArgs(1, func(args []string) error {
activationCode := args[0]
if len(admins) == 0 {
return fmt.Errorf("must specify at least one cluster admin to enable " +
"auth")
}
c, err := client.NewOnUserMachine(true, "user")
if err != nil {
return fmt.Errorf("could not connect: %s", err.Error())
}
_, err = c.AuthAPIClient.Activate(
c.Ctx(),
&auth.ActivateRequest{
ActivationCode: activationCode,
Admins: admins,
})
return err
}),
}
activate.PersistentFlags().StringSliceVar(&admins, "admins", []string{},
"Comma-separated list of users who will be cluster admins once security "+
"is enabled. This list cannot be empty, as only admins can appoint new "+
"admins, so if a cluster has no admins to begin with, none can be "+
"appointed.")
return activate
}
// LoginCmd returns a cobra.Command to login to a Pachyderm cluster with your
// GitHub account. Any resources that have been restricted to the email address
// registered with your GitHub account will subsequently be accessible.
func LoginCmd() *cobra.Command {
var username string
login := &cobra.Command{
Use: "login",
Short: "Login to Pachyderm with your GitHub account",
Long: "Login to Pachyderm with your GitHub account. Any resources that " +
"have been restricted to the email address registered with your GitHub " +
"account will subsequently be accessible.",
Run: cmdutil.Run(func([]string) error {
fmt.Println("(1) Please paste this link into a browser:\n\n" +
githubAuthLink + "\n\n" +
"(You will be directed to GitHub and asked to authorize Pachyderm's " +
"login app on Github. If you accept, you will be given a token to " +
"paste here, which will give you an externally verified account in " +
"this Pachyderm cluster)\n\n(2) Please paste the token you receive " +
"from GitHub here:")
token, err := bufio.NewReader(os.Stdin).ReadString('\n')
if err != nil {
return fmt.Errorf("error reading token: %s", err.Error())
}
token = strings.TrimSpace(token) // drop trailing newline
cfg, err := config.Read()
if err != nil {
return fmt.Errorf("error reading Pachyderm config (for cluster "+
"address): %s", err.Error())
}
c, err := client.NewOnUserMachine(true, "user")
if err != nil {
return fmt.Errorf("could not connect: %s", err.Error())
}
resp, err := c.AuthAPIClient.Authenticate(
c.Ctx(),
&auth.AuthenticateRequest{GithubUsername: username, GithubToken: token})
if err != nil {
return fmt.Errorf("error authenticating with Pachyderm cluster: %s",
err.Error())
}
if cfg.V1 == nil {
cfg.V1 = &config.ConfigV1{}
}
cfg.V1.SessionToken = resp.PachToken
return cfg.Write()
}),
}
login.PersistentFlags().StringVar(&username, "user", "", "GitHub username of "+
"the user logging in. If unset, the username will be inferred from the "+
"github authorization code")
return login
}
// CheckCmd returns a cobra command that sends an "Authorize" RPC to Pachd, to
// determine whether the specified user has access to the specified repo.
func CheckCmd() *cobra.Command {
check := &cobra.Command{
Use: "check (none|reader|writer|owner) repo",
Short: "Check whether you have reader/writer/etc-level access to 'repo'",
Long: "Check whether you or another user has a reader/writer/etc-level " +
"access to 'repo'. For " +
"example, 'pachctl auth check reader private-data' prints " +
"\"true\" if the you have at least \"reader\" access " +
"to the repo \"private-data\" (you could be a reader, writer, " +
"or owner). Unlike. `pachctl get-acl`, you do not need to have access " +
"to 'repo' to discover your own acess level.",
Run: cmdutil.RunFixedArgs(2, func(args []string) error {
scope, err := auth.ParseScope(args[0])
if err != nil {
return err
}
repo := args[1]
c, err := client.NewOnUserMachine(true, "user")
if err != nil {
return fmt.Errorf("could not connect: %s", err.Error())
}
resp, err := c.AuthAPIClient.Authorize(
c.Ctx(),
&auth.AuthorizeRequest{
Repo: repo,
Scope: scope,
})
if err != nil {
return err
}
fmt.Printf("%t\n", resp.Authorized)
return nil
}),
}
return check
}
// GetCmd returns a cobra command that gets either the ACL for a Pachyderm
// repo or another user's scope of access to that repo
func GetCmd() *cobra.Command {
setScope := &cobra.Command{
Use: "get [username] repo",
Short: "Get the ACL for 'repo' or the access that 'username' has to 'repo'",
Long: "Get the ACL for 'repo' or the access that 'username' has to " +
"'repo'. For example, 'pachctl auth get github-alice private-data' " +
"prints \"reader\", \"writer\", \"owner\", or \"none\", depending on " +
"the privileges that \"github-alice\" has in \"repo\". Currently all " +
"Pachyderm authentication uses GitHub OAuth, so 'username' must be a " +
"GitHub username",
Run: cmdutil.RunBoundedArgs(1, 2, func(args []string) error {
c, err := client.NewOnUserMachine(true, "user")
if err != nil {
return fmt.Errorf("could not connect: %s", err.Error())
}
if len(args) == 1 {
// Get ACL for a repo
repo := args[0]
resp, err := c.AuthAPIClient.GetACL(
c.Ctx(),
&auth.GetACLRequest{
Repo: repo,
})
if err != nil {
return err
}
fmt.Println(resp.ACL.String())
return nil
}
// Get User's scope on an acl
username, repo := args[0], args[1]
resp, err := c.AuthAPIClient.GetScope(
c.Ctx(),
&auth.GetScopeRequest{
Repos: []string{repo},
Username: username,
})
if err != nil {
return err
}
fmt.Println(resp.Scopes[0].String())
return nil
}),
}
return setScope
}
// SetScopeCmd returns a cobra command that lets a user set the level of access
// that another user has to a repo
func SetScopeCmd() *cobra.Command {
setScope := &cobra.Command{
Use: "set username (none|reader|writer|owner) repo",
Short: "Set the scope of access that 'username' has to 'repo'",
Long: "Set the scope of access that 'username' has to 'repo'. For " +
"example, 'pachctl auth set github-alice none private-data' prevents " +
"\"github-alice\" from interacting with the \"private-data\" repo in any " +
"way (the default). Similarly, 'pachctl auth set github-alice reader " +
"private-data' would let \"github-alice\" read from \"private-data\" but " +
"not create commits (writer) or modify the repo's access permissions " +
"(owner). Currently all Pachyderm authentication uses GitHub OAuth, so " +
"'username' must be a GitHub username",
Run: cmdutil.RunFixedArgs(3, func(args []string) error {
scope, err := auth.ParseScope(args[1])
if err != nil {
return err
}
username, repo := args[0], args[2]
c, err := client.NewOnUserMachine(true, "user")
if err != nil {
return fmt.Errorf("could not connect: %s", err.Error())
}
_, err = c.AuthAPIClient.SetScope(
c.Ctx(),
&auth.SetScopeRequest{
Repo: repo,
Scope: scope,
Username: username,
})
return err
}),
}
return setScope
}
// Cmds returns a list of cobra commands for authenticating and authorizing
// users in an auth-enabled Pachyderm cluster.
func Cmds() []*cobra.Command {
auth := &cobra.Command{
Use: "auth",
Short: "Auth commands manage access to data in a Pachyderm cluster",
Long: "Auth commands manage access to data in a Pachyderm cluster",
}
auth.AddCommand(ActivateCmd())
auth.AddCommand(CheckCmd())
auth.AddCommand(SetScopeCmd())
auth.AddCommand(GetCmd())
return []*cobra.Command{LoginCmd(), auth}
}
<file_sep>package testing
import (
"golang.org/x/net/context"
"github.com/pachyderm/pachyderm/src/client/auth"
)
// InactiveAPIServer (in the auth/testing package) is an implementation of the
// pachyderm auth api that returns NotActivatedError for all requests. This is
// meant to be used with local PFS and PPS servers for testing, and should
// never be used in a real Pachyderm cluster
type InactiveAPIServer struct{}
// Activate implements the Pachdyerm Auth Activate RPC, but just returns NotActivatedError
func (a *InactiveAPIServer) Activate(ctx context.Context, req *auth.ActivateRequest) (resp *auth.ActivateResponse, retErr error) {
return nil, auth.NotActivatedError{}
}
// Authenticate implements the Pachdyerm Auth Authenticate RPC, but just returns NotActivatedError
func (a *InactiveAPIServer) Authenticate(ctx context.Context, req *auth.AuthenticateRequest) (resp *auth.AuthenticateResponse, retErr error) {
return nil, auth.NotActivatedError{}
}
// Authorize implements the Pachdyerm Auth Authorize RPC, but just returns NotActivatedError
func (a *InactiveAPIServer) Authorize(ctx context.Context, req *auth.AuthorizeRequest) (resp *auth.AuthorizeResponse, retErr error) {
return nil, auth.NotActivatedError{}
}
// WhoAmI implements the Pachdyerm Auth WhoAmI RPC, but just returns NotActivatedError
func (a *InactiveAPIServer) WhoAmI(ctx context.Context, req *auth.WhoAmIRequest) (resp *auth.WhoAmIResponse, retErr error) {
return nil, auth.NotActivatedError{}
}
// SetScope implements the Pachdyerm Auth SetScope RPC, but just returns NotActivatedError
func (a *InactiveAPIServer) SetScope(ctx context.Context, req *auth.SetScopeRequest) (resp *auth.SetScopeResponse, retErr error) {
return nil, auth.NotActivatedError{}
}
// GetScope implements the Pachdyerm Auth GetScope RPC, but just returns NotActivatedError
func (a *InactiveAPIServer) GetScope(ctx context.Context, req *auth.GetScopeRequest) (resp *auth.GetScopeResponse, retErr error) {
return nil, auth.NotActivatedError{}
}
// GetACL implements the Pachdyerm Auth GetACL RPC, but just returns NotActivatedError
func (a *InactiveAPIServer) GetACL(ctx context.Context, req *auth.GetACLRequest) (resp *auth.GetACLResponse, retErr error) {
return nil, auth.NotActivatedError{}
}
// SetACL implements the Pachdyerm Auth SetACL RPC, but just returns NotActivatedError
func (a *InactiveAPIServer) SetACL(ctx context.Context, req *auth.SetACLRequest) (resp *auth.SetACLResponse, retErr error) {
return nil, auth.NotActivatedError{}
}
// GetCapability implements the Pachdyerm Auth GetCapability RPC, but just returns NotActivatedError
func (a *InactiveAPIServer) GetCapability(ctx context.Context, req *auth.GetCapabilityRequest) (resp *auth.GetCapabilityResponse, retErr error) {
return nil, auth.NotActivatedError{}
}
// RevokeAuthToken implements the Pachdyerm Auth RevokeAuthToken RPC, but just returns NotActivatedError
func (a *InactiveAPIServer) RevokeAuthToken(ctx context.Context, req *auth.RevokeAuthTokenRequest) (resp *auth.RevokeAuthTokenResponse, retErr error) {
return nil, auth.NotActivatedError{}
}
<file_sep>package auth
import (
"crypto"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"os"
"path"
"sync/atomic"
"time"
"google.golang.org/grpc/metadata"
etcd "github.com/coreos/etcd/clientv3"
"github.com/google/go-github/github"
logrus "github.com/sirupsen/logrus"
"golang.org/x/net/context"
"golang.org/x/oauth2"
"github.com/pachyderm/pachyderm/src/client"
authclient "github.com/pachyderm/pachyderm/src/client/auth"
"github.com/pachyderm/pachyderm/src/client/pkg/uuid"
"github.com/pachyderm/pachyderm/src/server/pkg/backoff"
col "github.com/pachyderm/pachyderm/src/server/pkg/collection"
"github.com/pachyderm/pachyderm/src/server/pkg/log"
"github.com/pachyderm/pachyderm/src/server/pkg/watch"
)
const (
// DisableAuthenticationEnvVar specifies an environment variable that, if set, causes
// Pachyderm authentication to ignore github and authmatically generate a
// pachyderm token for any username in the AuthenticateRequest.GithubToken field
DisableAuthenticationEnvVar = "PACHYDERM_AUTHENTICATION_DISABLED_FOR_TESTING"
tokensPrefix = "/auth/tokens"
aclsPrefix = "/auth/acls"
adminsPrefix = "/auth/admins"
defaultTokenTTLSecs = 24 * 60 * 60
publicKey = `-----BEGIN PUBLIC KEY-----
MIICIj<KEY>
-----END PUBLIC KEY-----
`
)
type apiServer struct {
pachLogger log.Logger
etcdClient *etcd.Client
// 'activated' stores a timestamp that is effectively a cache of whether the
// auth service has been activated. If 'activated' is 1/1/1, then the auth
// service has been activated. Otherwise, return "NotActivatedError" until the
// timestamp in 'activated' passes and then re-check etc to see if it has been
activated atomic.Value
// tokens is a collection of hashedToken -> User mappings.
tokens col.Collection
// acls is a collection of repoName -> ACL mappings.
acls col.Collection
// admins is a collection of username -> User mappings.
admins col.Collection
}
// LogReq is like log.Logger.Log(), but it assumes that it's being called from
// the top level of a GRPC method implementation, and correspondingly extracts
// the method name from the parent stack frame
func (a *apiServer) LogReq(request interface{}) {
a.pachLogger.Log(request, nil, nil, 0)
}
// LogResp is like log.Logger.Log(). However,
// 1) It assumes that it's being called from a defer() statement in a GRPC
// method , and correspondingly extracts the method name from the grandparent
// stack frame
// 2) It logs NotActivatedError at DebugLevel instead of ErrorLevel, as, in most
// cases, this error is expected, and logging it frequently may confuse users
func (a *apiServer) LogResp(request interface{}, response interface{}, err error, duration time.Duration) {
if err == nil {
a.pachLogger.LogAtLevelFromDepth(request, response, err, duration, logrus.InfoLevel, 4)
} else if authclient.IsNotActivatedError(err) {
a.pachLogger.LogAtLevelFromDepth(request, response, err, duration, logrus.DebugLevel, 4)
} else {
a.pachLogger.LogAtLevelFromDepth(request, response, err, duration, logrus.ErrorLevel, 4)
}
}
// NewAuthServer returns an implementation of auth.APIServer.
func NewAuthServer(etcdAddress string, etcdPrefix string) (authclient.APIServer, error) {
etcdClient, err := etcd.New(etcd.Config{
Endpoints: []string{etcdAddress},
DialOptions: client.EtcdDialOptions(),
})
if err != nil {
return nil, fmt.Errorf("error constructing etcdClient: %v", err)
}
s := &apiServer{
pachLogger: log.NewLogger("auth.API"),
etcdClient: etcdClient,
tokens: col.NewCollection(
etcdClient,
path.Join(etcdPrefix, tokensPrefix),
nil,
&authclient.User{},
nil,
),
acls: col.NewCollection(
etcdClient,
path.Join(etcdPrefix, aclsPrefix),
nil,
&authclient.ACL{},
nil,
),
admins: col.NewCollection(
etcdClient,
path.Join(etcdPrefix, adminsPrefix),
nil,
&authclient.User{},
nil,
),
}
s.activated.Store(false)
go s.activationCheck()
return s, nil
}
func (a *apiServer) activationCheck() {
backoff.RetryNotify(func() error {
// Watch for the addition/removal of new admins. Note that this will return
// any existing admins, so if the auth service is already activated, it will
// stay activated.
watcher, err := a.admins.ReadOnly(context.Background()).Watch()
if err != nil {
return err
}
defer watcher.Close()
// The auth service is activated if we have admins, and not
// activated otherwise.
var numAdmins int
for {
ev, ok := <-watcher.Watch()
if !ok {
return errors.New("admin watch closed unexpectedly")
}
switch ev.Type {
case watch.EventPut:
numAdmins++
case watch.EventDelete:
numAdmins--
case watch.EventError:
return ev.Err
}
a.activated.Store(numAdmins > 0)
}
}, backoff.NewInfiniteBackOff(), func(err error, d time.Duration) error {
logrus.Printf("error from activation check: %v; retrying in %v", err, d)
return nil
})
}
func (a *apiServer) Activate(ctx context.Context, req *authclient.ActivateRequest) (resp *authclient.ActivateResponse, retErr error) {
a.LogReq(req)
defer func(start time.Time) { a.LogResp(req, resp, retErr, time.Since(start)) }(time.Now())
// Activating an already activated auth service should fail, because
// otherwise anyone can just activate the service again and set
// themselves as an admin.
if a.isActivated() {
return nil, fmt.Errorf("already activated")
}
// Validate the activation code
if err := validateActivationCode(req.ActivationCode); err != nil {
return nil, fmt.Errorf("error validating activation code: %v", err)
}
// Initialize admins
_, err := col.NewSTM(ctx, a.etcdClient, func(stm col.STM) error {
admins := a.admins.ReadWrite(stm)
for _, admin := range req.Admins {
admins.Put(admin, &authclient.User{
Username: admin,
Admin: true,
})
}
return nil
})
if err != nil {
return nil, err
}
a.activated.Store(true)
return &authclient.ActivateResponse{}, nil
}
func (a *apiServer) isActivated() bool {
return a.activated.Load().(bool)
}
// AccessTokenToUsername takes a OAuth access token issued by GitHub and uses
// it discover the username of the user who obtained the code. This is how
// Pachyderm currently implements authorization in a production cluster
func AccessTokenToUsername(ctx context.Context, token string) (string, error) {
ts := oauth2.StaticTokenSource(
&oauth2.Token{
AccessToken: token,
},
)
tc := oauth2.NewClient(ctx, ts)
gclient := github.NewClient(tc)
// Passing the empty string gets us the authenticated user
user, _, err := gclient.Users.Get(ctx, "")
if err != nil {
return "", fmt.Errorf("error getting the authenticated user: %v", err)
}
return user.GetName(), nil
}
func (a *apiServer) Authenticate(ctx context.Context, req *authclient.AuthenticateRequest) (resp *authclient.AuthenticateResponse, retErr error) {
// We don't want to actually log the request/response since they contain
// credentials.
defer func(start time.Time) { a.LogResp(nil, nil, retErr, time.Since(start)) }(time.Now())
if !a.isActivated() {
return nil, authclient.NotActivatedError{}
}
var username string
if os.Getenv(DisableAuthenticationEnvVar) == "true" {
// Test mode--the caller automatically authenticates as whoever is requested
username = req.GithubUsername
} else {
// Prod mode--send access code to GitHub to discover authenticating user
var err error
username, err = AccessTokenToUsername(ctx, req.GithubToken)
if err != nil {
return nil, err
}
if req.GithubUsername != "" && req.GithubUsername != username {
return nil, fmt.Errorf("attempted to authenticate as %s, but Github " +
"token did not originate from that account")
}
}
// Check if the user is an admin. If they are, authenticate them as
// an admin.
var u authclient.User
var admin bool
if err := a.admins.ReadOnly(ctx).Get(username, &u); err != nil {
if _, ok := err.(col.ErrNotFound); !ok {
return nil, fmt.Errorf("error checking if user %v is an admin: %v", username, err)
}
} else {
admin = true
}
pachToken := uuid.NewWithoutDashes()
_, err := col.NewSTM(ctx, a.etcdClient, func(stm col.STM) error {
tokens := a.tokens.ReadWrite(stm)
return tokens.PutTTL(hashToken(pachToken), &authclient.User{
Username: username,
Admin: admin,
}, defaultTokenTTLSecs)
})
if err != nil {
return nil, fmt.Errorf("error storing auth token for user %v: %v", username, err)
}
return &authclient.AuthenticateResponse{
PachToken: pachToken,
}, nil
}
func (a *apiServer) Authorize(ctx context.Context, req *authclient.AuthorizeRequest) (resp *authclient.AuthorizeResponse, retErr error) {
a.LogReq(req)
defer func(start time.Time) { a.LogResp(req, resp, retErr, time.Since(start)) }(time.Now())
if !a.isActivated() {
return nil, authclient.NotActivatedError{}
}
user, err := a.getAuthenticatedUser(ctx)
if err != nil {
return nil, err
}
if user.Admin {
// admins are always authorized
return &authclient.AuthorizeResponse{
Authorized: true,
}, nil
}
var acl authclient.ACL
if err := a.acls.ReadOnly(ctx).Get(req.Repo, &acl); err != nil {
if _, ok := err.(col.ErrNotFound); ok {
return nil, fmt.Errorf("ACL not found for repo %v", req.Repo)
}
return nil, fmt.Errorf("error getting ACL for repo %v: %v", req.Repo, err)
}
return &authclient.AuthorizeResponse{
Authorized: req.Scope <= acl.Entries[user.Username],
}, nil
}
func (a *apiServer) WhoAmI(ctx context.Context, req *authclient.WhoAmIRequest) (resp *authclient.WhoAmIResponse, retErr error) {
a.LogReq(req)
defer func(start time.Time) { a.LogResp(req, resp, retErr, time.Since(start)) }(time.Now())
if !a.isActivated() {
return nil, authclient.NotActivatedError{}
}
user, err := a.getAuthenticatedUser(ctx)
if err != nil {
return nil, err
}
return &authclient.WhoAmIResponse{
Username: user.Username,
}, nil
}
func validateSetScopeRequest(req *authclient.SetScopeRequest) error {
if req.Username == "" {
return fmt.Errorf("invalid request: must set username")
}
if req.Repo == "" {
return fmt.Errorf("invalid request: must set repo")
}
return nil
}
func (a *apiServer) SetScope(ctx context.Context, req *authclient.SetScopeRequest) (resp *authclient.SetScopeResponse, retErr error) {
a.LogReq(req)
defer func(start time.Time) { a.LogResp(req, resp, retErr, time.Since(start)) }(time.Now())
if !a.isActivated() {
return nil, authclient.NotActivatedError{}
}
if err := validateSetScopeRequest(req); err != nil {
return nil, err
}
user, err := a.getAuthenticatedUser(ctx)
if err != nil {
return nil, err
}
_, err = col.NewSTM(ctx, a.etcdClient, func(stm col.STM) error {
acls := a.acls.ReadWrite(stm)
var acl authclient.ACL
if err := acls.Get(req.Repo, &acl); err != nil {
// Might be creating a new ACL. Check that 'req' sets the caller to be an owner
// TODO(msteffen): check that the repo exists?
if req.Username != user.Username || req.Scope != authclient.Scope_OWNER {
return fmt.Errorf("ACL not found for repo %v", req.Repo)
}
acl.Entries = make(map[string]authclient.Scope)
}
if len(acl.Entries) > 0 && !user.Admin &&
acl.Entries[user.Username] != authclient.Scope_OWNER {
return fmt.Errorf("user %v is not authorized to update ACL for repo %v", user, req.Repo)
}
if req.Scope != authclient.Scope_NONE {
acl.Entries[req.Username] = req.Scope
} else {
delete(acl.Entries, req.Username)
}
acls.Put(req.Repo, &acl)
return nil
})
if err != nil {
return nil, err
}
return &authclient.SetScopeResponse{}, nil
}
func (a *apiServer) GetScope(ctx context.Context, req *authclient.GetScopeRequest) (resp *authclient.GetScopeResponse, retErr error) {
a.LogReq(req)
defer func(start time.Time) { a.LogResp(req, resp, retErr, time.Since(start)) }(time.Now())
if !a.isActivated() {
return nil, authclient.NotActivatedError{}
}
var username string
if req.Username != "" {
username = req.Username
} else {
user, err := a.getAuthenticatedUser(ctx)
if err != nil {
return nil, err
}
username = user.Username
}
// For now, we don't return OWNER if the user is an admin, even though that's
// their effective access scope for all repos--the caller may want to know
// what will happen if the user's admin privileges are revoked
// Read repo ACL from etcd
resp = new(authclient.GetScopeResponse)
for _, repo := range req.Repos {
var acl authclient.ACL
err := a.acls.ReadOnly(ctx).Get(repo, &acl)
if err != nil || acl.Entries == nil {
// ACL not found. User has no scope
resp.Scopes = append(resp.Scopes, authclient.Scope_NONE)
} else {
resp.Scopes = append(resp.Scopes, acl.Entries[username])
}
}
return resp, nil
}
func (a *apiServer) GetACL(ctx context.Context, req *authclient.GetACLRequest) (resp *authclient.GetACLResponse, retErr error) {
a.LogReq(req)
defer func(start time.Time) { a.LogResp(req, resp, retErr, time.Since(start)) }(time.Now())
if !a.isActivated() {
return nil, authclient.NotActivatedError{}
}
// Validate request
if req.Repo == "" {
return nil, fmt.Errorf("invalid request: must provide name of repo to get that repo's ACL")
}
// Get calling user
user, err := a.getAuthenticatedUser(ctx)
if err != nil {
return nil, err
}
// Read repo ACL from etcd
resp = &authclient.GetACLResponse{
ACL: &authclient.ACL{},
}
if err = a.acls.ReadOnly(ctx).Get(req.Repo, resp.ACL); err != nil {
if _, ok := err.(col.ErrNotFound); !ok {
return nil, err
}
}
// For now, require READER access to read repo metadata (commits, and ACLs)
if !user.Admin && resp.ACL.Entries[user.Username] < authclient.Scope_READER {
return nil, fmt.Errorf("you must have at least READER access to %s to read its ACL", req.Repo)
}
return resp, nil
}
func (a *apiServer) SetACL(ctx context.Context, req *authclient.SetACLRequest) (resp *authclient.SetACLResponse, retErr error) {
a.LogReq(req)
defer func(start time.Time) { a.LogResp(req, resp, retErr, time.Since(start)) }(time.Now())
if !a.isActivated() {
return nil, authclient.NotActivatedError{}
}
// Validate request
if req.Repo == "" {
return nil, fmt.Errorf("invalid request: must provide name of repo you want to modify")
}
// Get calling user
user, err := a.getAuthenticatedUser(ctx)
if err != nil {
return nil, err
}
// Read repo ACL from etcd
_, err = col.NewSTM(ctx, a.etcdClient, func(stm col.STM) error {
acls := a.acls.ReadWrite(stm)
// Require OWNER access to modify repo ACL
var acl authclient.ACL
acls.Get(req.Repo, &acl)
if !user.Admin && acl.Entries[user.Username] < authclient.Scope_OWNER {
return fmt.Errorf("you must have OWNER access to %s to modify its ACL", req.Repo)
}
// Set new ACL
if req.NewACL == nil || len(req.NewACL.Entries) == 0 {
return acls.Delete(req.Repo)
}
return acls.Put(req.Repo, req.NewACL)
})
if err != nil {
return nil, fmt.Errorf("could not put new ACL: %v", err)
}
return &authclient.SetACLResponse{}, nil
}
func (a *apiServer) GetCapability(ctx context.Context, req *authclient.GetCapabilityRequest) (resp *authclient.GetCapabilityResponse, retErr error) {
a.LogReq(req)
defer func(start time.Time) { a.LogResp(req, resp, retErr, time.Since(start)) }(time.Now())
var user *authclient.User
if !a.isActivated() {
// If auth service is not activated, we want to return a capability
// that's able to access any repo. That way, when we create a
// pipeline, we can assign it with a capability that would allow
// it to access any repo after the auth service has been activated.
user = &authclient.User{
Admin: true,
}
} else {
var err error
user, err = a.getAuthenticatedUser(ctx)
if err != nil {
return nil, err
}
}
capability := uuid.NewWithoutDashes()
_, err := col.NewSTM(ctx, a.etcdClient, func(stm col.STM) error {
tokens := a.tokens.ReadWrite(stm)
// Capabilities are forver; they don't expire.
return tokens.Put(hashToken(capability), user)
})
if err != nil {
return nil, fmt.Errorf("error storing capability for user %v: %v", user.Username, err)
}
return &authclient.GetCapabilityResponse{
Capability: capability,
}, nil
}
func (a *apiServer) RevokeAuthToken(ctx context.Context, req *authclient.RevokeAuthTokenRequest) (resp *authclient.RevokeAuthTokenResponse, retErr error) {
a.LogReq(req)
defer func(start time.Time) { a.LogResp(req, resp, retErr, time.Since(start)) }(time.Now())
if !a.isActivated() {
return nil, authclient.NotActivatedError{}
}
// Even though anyone can revoke anyone's auth token, we still want
// the user to be authenticated.
if _, err := a.getAuthenticatedUser(ctx); err != nil {
return nil, err
}
_, err := col.NewSTM(ctx, a.etcdClient, func(stm col.STM) error {
tokens := a.tokens.ReadWrite(stm)
// Capabilities are forver; they don't expire.
if err := tokens.Delete(hashToken(req.Token)); err != nil {
// We ignore NotFound errors, since it's ok to revoke a
// nonexistent token.
if _, ok := err.(col.ErrNotFound); !ok {
return err
}
}
return nil
})
if err != nil {
return nil, fmt.Errorf("error revoking token: %v", err)
}
return &authclient.RevokeAuthTokenResponse{}, nil
}
// hashToken converts a token to a cryptographic hash.
// We don't want to store tokens verbatim in the database, as then whoever
// that has access to the database has access to all tokens.
func hashToken(token string) string {
sum := sha256.Sum256([]byte(token))
return fmt.Sprintf("%x", sum)
}
func (a *apiServer) getAuthenticatedUser(ctx context.Context) (*authclient.User, error) {
// TODO(msteffen) cache these lookups, especially since users always authorize
// themselves at the beginning of a request. Don't want to look up the same
// token -> username entry twice.
md, ok := metadata.FromContext(ctx)
if !ok {
return nil, fmt.Errorf("no authentication metadata found in context")
}
if len(md[authclient.ContextTokenKey]) != 1 {
return nil, fmt.Errorf("auth token not found in context")
}
token := md[authclient.ContextTokenKey][0]
var user authclient.User
if err := a.tokens.ReadOnly(ctx).Get(hashToken(token), &user); err != nil {
if _, ok := err.(col.ErrNotFound); ok {
return nil, fmt.Errorf("token not found")
}
return nil, fmt.Errorf("error getting token: %v", err)
}
return &user, nil
}
type activationCode struct {
Token string
Signature string
}
type token struct {
Expiry string
}
// validateActivationCode checks the validity of an activation code
func validateActivationCode(code string) error {
// Parse the public key. If these steps fail, something is seriously
// wrong and we should crash the service by panicking.
block, _ := pem.Decode([]byte(publicKey))
if block == nil {
panic("failed to pem decode public key")
}
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
panic(fmt.Sprintf("failed to parse DER encoded public key: %+v", err))
}
rsaPub, ok := pub.(*rsa.PublicKey)
if !ok {
panic("public key isn't an RSA key")
}
// Decode the base64-encoded activation code
decodedActivationCode, err := base64.StdEncoding.DecodeString(code)
if err != nil {
return fmt.Errorf("activation code is not base64 encoded")
}
activationCode := &activationCode{}
if err := json.Unmarshal(decodedActivationCode, &activationCode); err != nil {
return fmt.Errorf("activation code is not valid JSON")
}
// Decode the signature
decodedSignature, err := base64.StdEncoding.DecodeString(activationCode.Signature)
if err != nil {
return fmt.Errorf("signature is not base64 encoded")
}
// Compute the sha256 checksum of the token
hashedToken := sha256.Sum256([]byte(activationCode.Token))
// Verify that the signature is valid
if err := rsa.VerifyPKCS1v15(rsaPub, crypto.SHA256, hashedToken[:], decodedSignature); err != nil {
return fmt.Errorf("invalid signature in activation code")
}
// Unmarshal the token
token := token{}
if err := json.Unmarshal([]byte(activationCode.Token), &token); err != nil {
return fmt.Errorf("token is not valid JSON")
}
// Parse the expiry
expiry, err := time.Parse(time.RFC3339, token.Expiry)
if err != nil {
return fmt.Errorf("expiry is not valid ISO 8601 string")
}
// Check that the activation code has not expired
if time.Now().After(expiry) {
return fmt.Errorf("the activation code has expired")
}
return nil
}
| 5f04868f7dcbdfce1cf4c726c460037449ca10f5 | [
"Go"
] | 3 | Go | kluikens/pachyderm | 4b791e5453778b57db4e907eb1796bdbb9810cf2 | 2b1916b6a3b2395dad00ea1678e2945eee1521bc |
refs/heads/main | <file_sep>#include "core/init.h"
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <termios.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
pid_t shell_pgid;
struct termios shell_tmodes;
int shell_terminal;
int shell_is_interactive;
void init_shell() {
shell_terminal = STDIN_FILENO;
shell_is_interactive = isatty(shell_terminal);
if (shell_is_interactive) {
while (tcgetpgrp(shell_terminal) != (shell_pgid = getpgrp()))
kill(-shell_pgid, SIGTTIN);
signal(SIGINT, SIG_IGN);
signal(SIGQUIT, SIG_IGN);
signal(SIGTSTP, SIG_IGN);
signal(SIGTTIN, SIG_IGN);
signal(SIGTTOU, SIG_IGN);
signal(SIGCHLD, SIG_IGN);
shell_pgid = getpid();
if (setpgid(shell_pgid, shell_pgid) < 0) {
perror("Couldn't put the shell in its own process group");
exit(1);
}
tcsetpgrp(shell_terminal, shell_pgid);
tcgetattr(shell_terminal, &shell_tmodes);
}
}<file_sep>#include <sys/types.h>
#include <termios.h>
pid_t shell_pgid;
struct termios shell_tmodes;
int shell_terminal;
int shell_is_interactive;
void init_shell();<file_sep>#include "./commands/cp.h"
#include "./commands/handler.h"
#include "./core/init.h"
#include "./core/job.h"
#include "./datastructures/job.h"
#include "./utils/stringUtils.h"
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
init_shell();
while (1) {
char cmd[32];
strcpy(cmd, "");
char args[1024];
strcpy(args, "");
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL) {
printf("%s$ ", cwd);
}
fscanf(stdin, "%s", cmd);
fgets(args, 100, stdin);
size_t i = 1;
while (1) {
if (args[i] == 10) {
break;
} else {
i++;
}
}
while (i < 1024) {
args[i] = 0;
i++;
}
memcpy(args, args + 1, sizeof(args) - 1);
char fullCmd[1024];
strcpy(fullCmd, "");
strcat(fullCmd, cmd);
char space[] = " ";
strcat(fullCmd, space);
strcat(fullCmd, args);
if (!strcmp(cmd, "exit")) {
exit(1);
} else if (!strcmp(cmd, "cd")) {
if (chdir(args) != 0) {
perror("Failed");
}
} else if (!strcmp(cmd, "mkdir")) {
if (mkdir(args, S_IRWXU) != 0) {
perror("Failed");
}
} else if (!strcmp(cmd, "cp")) {
char *argsSplit[3];
int argsNum;
splitStringCmd(fullCmd, argsSplit, &argsNum);
maincp(argsNum, argsSplit);
} else {
handleCommand(fullCmd);
}
}
return 0;
}<file_sep>void testsStrtokToFullStringArg() {
char cmd[128] = "Hier j'ai voulu manger une pomme de type \"pomme golden\" et, c'est de mon point de vue exquis.";
char* args[64];
int nbArgs;
splitStringCmd(cmd, args, &nbArgs);
if (strcmp(args[0], "Hier")) { printf("Erreur : splitStringCmd aurait du renvoyer 'Hier'. (%s)\n", args[0]); }
if (strcmp(args[8], "pomme golden")) { printf("Erreur : splitStringCmd aurait du renvoyer 'pomme golden'. (%s)\n", args[8]); }
if (strcmp(args[9], "et,")) { printf("Erreur : splitStringCmd aurait du renvoyer 'et,'. (%s)\n", args[9]); }
if (strcmp(args[16], "exquis.")) { printf("Erreur : splitStringCmd aurait du renvoyer 'exquis.' (%s)\n", args[16]); }
if (nbArgs != 17) { printf("Erreur : splitStringCmd aurait du renvoyer une longueur de 17. (%d).\n", nbArgs); }
}<file_sep>
/*
Divise une commande (cmd) en un tableau d'arguments (args, de taille definie a l'avance)
Renvoie 0 si succes et -1 si syntaxe incorrecte
*/
int splitStringCmd(char* cmd, char** args, int* len);<file_sep>#include "core/job.h"
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include "datastructures/info/jobinfo.h"
void launch_process(struct process *p, pid_t pgid, int infile, int outfile,
int errfile, int foreground) {
pid_t pid;
if (shell_is_interactive) {
/* Put the process into the process group and give the process group
the terminal, if appropriate.
This has to be done both by the shell and in the individual
child processes because of potential race conditions. */
pid = getpid();
if (pgid == 0)
pgid = pid;
setpgid(pid, pgid);
if (foreground)
tcsetpgrp(shell_terminal, pgid);
/* Set the handling for job control signals back to the default. */
signal(SIGINT, SIG_DFL);
signal(SIGQUIT, SIG_DFL);
signal(SIGTSTP, SIG_DFL);
signal(SIGTTIN, SIG_DFL);
signal(SIGTTOU, SIG_DFL);
signal(SIGCHLD, SIG_DFL);
}
/* Set the standard input/output channels of the new process. */
if (infile != STDIN_FILENO) {
dup2(infile, STDIN_FILENO);
close(infile);
}
if (outfile != STDOUT_FILENO) {
dup2(outfile, STDOUT_FILENO);
close(outfile);
}
if (errfile != STDERR_FILENO) {
dup2(errfile, STDERR_FILENO);
close(errfile);
}
//printf("Après set standard i/o channels of process\n");
/* Exec the new process. Make sure we exit. */
//printf("argv : %s, %s, %s, ...\n", p->argv[0], p->argv[1], p->argv[2]);
execvp(p->argv[0], p->argv);
perror("execvp");
exit(1);
}
void launch_job(struct job *j, int foreground) {
//printf("Debut launch_job, avec in %d et out %d, et foreground %d\n", j->stdin, j->stdout, foreground);
struct process *p;
pid_t pid;
int mypipe[2], infile, outfile;
infile = j->stdin;
for (p = j->first_process; p; p = p->next) {
/*if (p->next) {
printf("1 processus : %s, %s, %s (suiv : %s)\n", p->argv[0], p->argv[1], p->argv[2], p->next->argv[0]);
} else {
printf("1 processus : %s, %s, %s (suiv : %s)\n", p->argv[0], p->argv[1], p->argv[2], "aucun");
}*/
/* Set up pipes, if necessary. */
if (p->next) {
if (pipe(mypipe) < 0) {
perror("pipe");
exit(1);
}
outfile = mypipe[1];
} else
outfile = j->stdout;
/* Fork the child processes. */
pid = fork();
if (pid == 0)
/* This is the child process. */
launch_process(p, j->pgid, infile, outfile, j->stderr, foreground);
else if (pid < 0) {
/* The fork failed. */
perror("fork");
exit(1);
} else {
/* This is the parent process. */
p->pid = pid;
if (shell_is_interactive) {
if (!j->pgid)
j->pgid = pid;
setpgid(pid, j->pgid);
}
}
/* Clean up after pipes. */
if (infile != j->stdin)
close(infile);
if (outfile != j->stdout)
close(outfile);
infile = mypipe[0];
}
//format_job_info(j, "launched");
if (!shell_is_interactive)
wait_for_job(j);
else if (foreground)
put_job_in_foreground(j, 0);
else
put_job_in_background(j, 0);
}
void put_job_in_foreground(struct job *j, int cont) {
/* Put the job into the foreground. */
tcsetpgrp(shell_terminal, j->pgid);
/* Send the job a continue signal, if necessary. */
if (cont) {
tcsetattr(shell_terminal, TCSADRAIN, &j->tmodes);
if (kill(-j->pgid, SIGCONT) < 0)
perror("kill (SIGCONT)");
}
/* Wait for it to report. */
wait_for_job(j);
/* Put the shell back in the foreground. */
tcsetpgrp(shell_terminal, shell_pgid);
/* Restore the shell’s terminal modes. */
tcgetattr(shell_terminal, &j->tmodes);
tcsetattr(shell_terminal, TCSADRAIN, &shell_tmodes);
}
void put_job_in_background(struct job *j, int cont) {
/* Send the job a continue signal, if necessary. */
if (cont)
if (kill(-j->pgid, SIGCONT) < 0)
perror("kill (SIGCONT)");
}
<file_sep>#include "init.h"
#include <sys/types.h>
#include "../datastructures/job.h"
void launch_process(struct process* p, pid_t pgid, int infile, int outfile,
int errfile, int foreground);
void launch_job(struct job* j, int foreground);
void put_job_in_foreground(struct job* j, int cont);
void put_job_in_background(struct job* j, int cont);<file_sep>#include "../job.h"
/* Store the status of the process pid that was returned by waitpid.
Return 0 if all went well, nonzero otherwise. */
int mark_process_status(pid_t pid, int status);
/* Check for processes that have status information available,
without blocking. */
void update_status(void);
/* Check for processes that have status information available,
blocking until all processes in the given job have reported. */
void wait_for_job(struct job* j);
/* Format information about job status for the user to look at. */
void format_job_info(struct job* j, const char* status);
/* Notify the user about stopped or terminated jobs.
Delete terminated jobs from the active job list. */
void do_job_notification(void);<file_sep>/*
Fait le necessaire etant donne une commande
*/
int handleCommand(char *cmd);
<file_sep>#include "commands/handler.h"
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "core/job.h"
#include "datastructures/job.h"
#include "utils/stringUtils.h"
#define PROCHAIN_TOKEN_FICHIER 0
#define PROCHAIN_TOKEN_SYMBOLE 1
#define PROCHAIN_TOKEN_ENTREE 2
#define PROCHAIN_TOKEN_SORTIE 3
#define MAX_ARGS_CMD 64
int handleCommand(char *cmd) {
// Variables de boucle
char *args[MAX_ARGS_CMD];
int nbArgs;
int result = splitStringCmd(cmd, args, &nbArgs);
if (result == -1) {
return -1;
}
int prochain = PROCHAIN_TOKEN_FICHIER;
struct process **processus = nouvProcess(32);
int iProc = 0;
// Variables job
struct job j;
int isForeground = 1; // Par défaut, on met la commande au premier plan
j.command = "";
j.next = NULL;
j.notified = 0;
int idesc = STDIN_FILENO; // Entrée
int odesc = STDOUT_FILENO; // Sortie
j.stdin = idesc;
j.stdout = odesc;
for (int i = 0; i < nbArgs; i++) {
// ----------------------------
// Entr�e du flux
// ----------------------------
if (args[i][0] == '<') {
// printf("Entr�e : %s\n", args[i]);
if (prochain != PROCHAIN_TOKEN_SYMBOLE) {
perror("Erreur syntaxe : '<' ne peut pas être placé ici.\n");
return -1;
}
prochain = PROCHAIN_TOKEN_ENTREE;
}
// ----------------------------
// Sortie du flux
// ----------------------------
else if (args[i][0] == '>') {
// printf("Sortie : %s\n", args[i]);
if (prochain != PROCHAIN_TOKEN_SYMBOLE) {
perror("Erreur syntaxe : '>' ne peut pas �tre plac� ici.\n");
return -1;
}
prochain = PROCHAIN_TOKEN_SORTIE;
}
// ----------------------------
// S�parateur de programmes
// ----------------------------
else if (args[i][0] == '|') {
// printf("Séparateur : %s\n", args[i]);
if (prochain != PROCHAIN_TOKEN_SYMBOLE) {
perror("Erreur syntaxe : '|' ne peut pas �tre plac� ici.\n");
return -1;
}
prochain = PROCHAIN_TOKEN_FICHIER;
}
// ----------------------------
// Inverseur de plan (switch foreground/background)
// ----------------------------
else if (args[i][0] == '*' && strlen(args[i]) == 1) {
// printf("Foreground : %s\n", args[i]);
isForeground = !isForeground;
}
// ----------------------------
// Fichier
// ----------------------------
else {
// printf("Fichier : %s\n", args[i]);
switch (prochain) {
// Si l'entrée est attendue
case PROCHAIN_TOKEN_ENTREE:;
idesc = open(args[i], O_RDONLY);
if (idesc == -1) {
perror("Le fichier d'entree n'a pas ete trouve.\n");
return -1;
}
j.stdin = idesc;
prochain = PROCHAIN_TOKEN_SYMBOLE;
break;
// Si la sortie est attendue
case PROCHAIN_TOKEN_SORTIE:;
odesc = open(args[i], O_WRONLY | O_CREAT | O_EXCL, 0666);
if (odesc == -1) {
perror("Une erreur s'est produite lors de l'ouverture du flux de "
"sortie.\n");
return -1;
}
j.stdout = odesc;
prochain = PROCHAIN_TOKEN_SYMBOLE;
break;
// Si un nom de ficher est attendu
case PROCHAIN_TOKEN_FICHIER:;
if (iProc == 0) {
j.first_process = processus[iProc];
} else {
processus[iProc - 1]->next = processus[iProc];
}
char motSlash[32] = "./";
strcat(motSlash, args[i]);
char *tabMotPtr[33];
int lenTab;
splitStringCmd(motSlash, tabMotPtr, &lenTab);
tabMotPtr[lenTab] = NULL;
processus[iProc]->argv = tabMotPtr;
processus[iProc]->completed = 0;
processus[iProc]->stopped = 0;
iProc++;
prochain = PROCHAIN_TOKEN_SYMBOLE;
break;
default:
perror("Un fichier n'était pas attendu ici.\n");
return -1;
break;
}
}
}
// ----------------------------
// V�rification rien en attente
// ----------------------------
if (prochain != PROCHAIN_TOKEN_SYMBOLE) {
perror("La commande ne peut pas finir par un symbole.\n");
return -1;
}
// Exécution du programme
if (!isForeground && (j.stdin == STDIN_FILENO || j.stdout == STDOUT_FILENO)) {
perror("Vous avez demande une execution en mode background, mais n'avez "
"defini ni entree ni sortie.");
return -1;
}
launch_job(&j, isForeground);
return 0;
}
<file_sep>#include "./commands/cp.h"
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <error.h>
#include <fcntl.h>
#include <libgen.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#define MAX_BUF_SIZE 1024
void cp(char *source, char *destination, struct stat src_stat);
void copy(int argc, char *argv[], bool recursive);
void recur(char *source, char *destination);
int maincp(int argc, char *argv[]);
void cp(char *source, char *destination, struct stat src_stat) {
int src, dst;
int numbytesread;
char buf[MAX_BUF_SIZE];
src = open(source, O_RDONLY);
dst = open(destination, O_WRONLY | O_CREAT | O_TRUNC, src_stat.st_mode);
while ((numbytesread = read(src, buf, MAX_BUF_SIZE)) > 0) {
write(dst, buf, numbytesread);
}
close(src);
close(dst);
}
void copy(int argc, char *argv[], bool recursive) {
struct stat src_stat, dst_stat;
bool is_dir = false;
if (lstat(argv[argc - 1], &dst_stat) == -1) {
} else {
if (S_ISDIR(dst_stat.st_mode)) {
is_dir = true;
}
}
for (int i = 0; i < argc - 1; i++) {
char *source = argv[i];
char *destination;
lstat(source, &src_stat);
if (S_ISDIR(src_stat.st_mode)) {
if (recursive) {
recur(source, argv[argc - 1]);
continue;
}
}
if (is_dir) {
char *src_filename = basename(source);
char *dir_name = argv[argc - 1];
char path[strlen(dir_name) + 1 + strlen(src_filename)];
char *slash = (dir_name[strlen(dir_name) - 1] == '/') ? "" : "/";
strcpy(path, dir_name);
strcat(path, slash);
strcat(path, src_filename);
destination = strdup(path);
} else {
destination = strdup(argv[argc - 1]);
}
if (lstat(destination, &dst_stat) == -1) {
// le fichier n'existe pas
}
cp(source, destination, src_stat);
free(destination);
}
}
void recur(char *source, char *destination) {
DIR *src_dir;
struct dirent *src_dirent;
struct stat src_stat, dst_stat;
lstat(source, &src_stat);
if (lstat(destination, &dst_stat) == -1) {
mkdir(destination, src_stat.st_mode);
}
src_dir = opendir(source);
while ((src_dirent = readdir(src_dir)) != NULL) {
char *arg[2];
char *filename = src_dirent->d_name;
if (strcmp(filename, ".") == 0)
continue;
if (strcmp(filename, "..") == 0)
continue;
char path[strlen(source) + 1 + strlen(filename)];
char *slash = (source[strlen(source) - 1] == '/') ? "" : "/";
struct stat ent_stat;
strcpy(path, source);
strcat(path, slash);
strcat(path, filename);
lstat(path, &ent_stat);
if (S_ISDIR(ent_stat.st_mode)) {
char dst_path[strlen(destination) + 1 + strlen(filename)];
slash = (source[strlen(source) - 1] == '/') ? "" : "/";
strcpy(dst_path, destination);
strcat(dst_path, slash);
strcat(dst_path, filename);
recur(path, dst_path);
} else {
arg[0] = path;
arg[1] = destination;
copy(2, arg, true);
}
}
}
int maincp(int argc, char *argv[]) {
bool recursive = false;
if (getopt(argc, argv, "r") == 'r') {
recursive = true;
}
if (argc - optind >= 2) {
copy(argc - optind, argv + optind, recursive);
}
return 0;
}<file_sep>#include "datastructures/job.h"
#include <unistd.h>
#include <stdlib.h>
/* Creer une instance de process */
struct process** nouvProcess(int nbProcess) {
struct process** processArray = malloc(sizeof(struct process)*nbProcess);
for (int i = 0; i < nbProcess; i++) {
processArray[i] = malloc(sizeof(struct process));
if (processArray[i] == NULL)
return NULL;
}
return processArray;
}
//Here are some utility functions that are used for operating on job objects.
/* Find the active job with the indicated pgid. */
struct job*
find_job(pid_t pgid)
{
job* j;
for (j = first_job; j; j = j->next)
if (j->pgid == pgid)
return j;
return NULL;
}
/* Return true if all processes in the job have stopped or completed. */
int
job_is_stopped(struct job * j)
{
process* p;
for (p = j->first_process; p; p = p->next)
if (!p->completed && !p->stopped)
return 0;
return 1;
}
/* Return true if all processes in the job have completed. */
int
job_is_completed(struct job * j)
{
process* p;
for (p = j->first_process; p; p = p->next)
if (!p->completed)
return 0;
return 1;
}<file_sep>#include "./utils/stringUtils.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/*
Divise une commande (cmd) en un tableau d'arguments (args, de taille definie a l'avance)
Renvoie 0 si succes et -1 si syntaxe incorrecte
*/
int splitStringCmd(char* cmd, char** args, int* len) {
char* mot = malloc(sizeof(char) * 2048);
char argTemp[4096];
int i = 0;
int isQuoteOpen = 0;
mot = strtok(cmd, " ");
while (mot != NULL) {
if (!isQuoteOpen) {
if (mot[0] == '"') { // Si l'argument commence par un guillemet, on va laisser les mots s'accumuler
mot++; // Suppression du premier char (le guillemet)
if (mot[strlen(mot) - 1] == '"') { // Si le mot finit deja par un guillemet
mot[strlen(mot) - 1] = '\0';
args[i] = malloc(sizeof(char) * strlen(mot));
strcpy(args[i], mot);
i++;
}
else {
strcpy(argTemp, mot);
isQuoteOpen = 1;
}
mot--;
}
else { // Si l'argument ne commence pas par un guillemet, alors on le renvoie directement
args[i] = malloc(sizeof(char) * strlen(mot));
strcpy(args[i], mot);
i++;
}
}
// Si on n'a pas renvoyé, on vérifie qu'on n'a pas un guillemet de fin et on ajoute
else {
strcat(argTemp, " ");
strcat(argTemp, mot);
if (mot[strlen(mot) - 1] == '"') {
argTemp[strlen(argTemp) - 1] = '\0';
args[i] = malloc(sizeof(char) * strlen(argTemp));
strcpy(args[i], argTemp);
isQuoteOpen = 0;
i++;
}
}
mot = strtok(NULL, " ");
}
len[0] = i;
free(mot);
if (isQuoteOpen) {
printf("L'argument %s ne se termine jamais (par un guillemet).\n", argTemp);
return -1;
}
return 0;
} | 023953e32fdea4d7d23476a70dcf158a5867bc8d | [
"C"
] | 13 | C | GaelErhlich/shell-linux | e9d7e575927c58c6e8b0ed167c3ab1421909c5e1 | 1fe53fefcf91815e9b7159d62b365c8dc7b199ca |
refs/heads/master | <file_sep># Skill Test From Refactory.id -- Q2
- file palindrome.cpp :
Program to check string are palindrome or not.
- file leap_year.cpp :
Program to find the leap year list of ranges between 2 inputs.
How to build :
1. Create folder build using ```mkdir build```
3. ```cd build/```
4. ```cmake ..```
5. ```make```
How to run palindrome.cpp :
1. ```cd build/```
2. ```./palindrome```
How to run leap_year.cpp :
1. ```cd build/```
2. ```./leap_year```<file_sep>#include <iostream>
int main()
{
int year = 0, year_begin = 0, year_last = 0;
bool status = false;
std::cout << "Input begin year :"; std::cin >> year_begin;
std::cout << "Input last year :"; std::cin >> year_last;
std::cout << "\nleap years range between " << year_begin << " and " << year_last << " are : \n\n";
year = year_begin;
while(year <= year_last){
if(year%400 == 0)
status = true;
else if(year%400 != 0 && year%100 == 0)
status = false;
else if(year%400 != 0 && year%100 != 0 && year%4 == 0)
status = true;
else if(year%400 != 0 && year%100 != 0 && year%4 != 0)
status = false;
if(status){
std::cout << year << ", ";
status = false;
}
year++;
}
return 0;
}<file_sep>file(REMOVE_RECURSE
"CMakeFiles/run-q-1.dir/q_1.cpp.o"
"run-q-1.pdb"
"run-q-1"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/run-q-1.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>#include "q_1.h"
PaymentReceipt::PaymentReceipt() {
flag_exit = true;
tot_item = 0;
}
PaymentReceipt::~PaymentReceipt() {
}
void PaymentReceipt::setInput() {
std::cout << " Payment Receipt \n";
std::cout << "================================\n";
std::cout << "Resto Name : "; getline (std::cin, resto_name);
std::cout << "Date : "; std::cin >> date_of_print;
std::cout << "Cashier Name : "; std::cin >> cashier_name;
std::cout << "================================\n";
std::string tmp_item;
int tmp_price;
while(flag_exit){
std::cout << "Item-" << tot_item + 1 << " : ";
std::cin >> tmp_item;
if(tmp_item == "exit")
flag_exit = false;
else{
std::cout << "Price : ";
std::cin >> tmp_price;
item.push_back(tmp_item);
price.push_back(tmp_price);
tot_item++;
}
}
}
void PaymentReceipt::setOutput() {
int count_dot = 0, total = 0;
std::stringstream ss;
std::string str_price;
for(size_t i = 0; i < item.size(); i++){
std::cout << item[i];
if(item[i].size() >= 30)
std::cout << "\n";
ss << price[i];
ss >> str_price;
count_dot = 30 - (item[i].size() + str_price.size());
for(int j = 0; j < count_dot; j++)
std::cout << ".";
if(item[i].size() >= 30){
count_dot = 30 - str_price.size();
for(int j = 0; j < count_dot; j++)
std::cout << ".";
std::cout << "Rp" << price[i] << "\n";
} else
std::cout << "Rp" << price[i] << "\n";
total+=price[i];
count_dot = 0;
ss.clear();
}
std::cout << "\n\nTotal";
ss << total;
ss >> str_price;
count_dot = 25 - str_price.size();
for (int i = 0; i < count_dot; i++)
{
std::cout<<".";
}
std::cout << "Rp" << total << "\n";
}
void PaymentReceipt::loadTimeandDate() {
time_t now = time(0);
tm *ltm = localtime(&now);
// std::cout << "Tanggal : " << 1900 + ltm->tm_year << "/" << 1 + ltm->tm_mon << "/" << ltm->tm_mday << " ";
std::cout << "Tanggal : ";
std::cout << std::setw(13);
std::cout << date_of_print << " " << 5+ltm->tm_hour << ":" << 30+ltm->tm_min << ":" << ltm->tm_sec << "\n";
}
void PaymentReceipt::process() {
setInput();
std::cout << "\n\n";
unsigned int padding_resto_name = 16 + (resto_name.size() / 2);
std::cout << std::setw(padding_resto_name);
std::cout << resto_name << "\n";
loadTimeandDate();
std::cout << "Nama Kasir : ";
std::cout << std::setw(19);
std::cout << cashier_name << "\n";
std::cout << "================================\n";
setOutput();
}
int main()
{
PaymentReceipt payment_receipt;
payment_receipt.process();
}<file_sep>const dotenv = require("dotenv");
process.env.NODE_ENV = process.env.NODE_ENV || "development";
const config = {
port: process.env.PORT,
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
oauthUrl: process.env.OAUTH_URL,
apiUrl: process.env.API_URL,
}
const envFound = dotenv.config();
if (envFound.error) {
throw new Error("⚠️ Couldn't find .env file ⚠️");
}
module.exports = { config };
<file_sep>const axios = require("axios");
const UserServices = require("./userInfoService");
const config = require("../config");
function callback(req, res) {
const body = {
client_id: config.clientId,
client_secret: config.clientSecret,
code: req.query.code,
};
const options = { headers: { accept: "application/json" } };
axios
.post(`${config.oauthUrl}/access_token`, body, options)
.then((res) => resp.data["accessToken"])
.then((accessToken) => {
const user = UserServices.getUserInfo(accessToken);
res.json({
data: {
login: user.login,
githubId: user.id,
avatar: user.avatar_url,
email: user.email,
name: user.name,
location: user.location,
},
});
})
.catch((err) => res.status(500).json({ message: err.message }));
}
module.exports = {
callback: callback,
};
<file_sep>const axios = require("axios");
const config = require("../config");
function getUserInfo(token) {
axios({
method: "get",
url: `${config.apiUrl}/users`,
headers: {
Authorization: "token " + token,
},
}).then((response) => {
return response.data;
});
}
module.export = getUserInfo
<file_sep># CodeDebugging
Code debugging built with NodeJs<file_sep># Skill Test From Refactory.id -- Q3
Program json with python
How to run palindrome.cpp :
```python js_manip2.py```<file_sep>#include <iostream>
#include <cstring>
#include <stdio.h>
#include <ctype.h>
bool checkPalindrome(char input[]) {
int length = 0;
bool result = true;
length = strlen(input);
for(int i = 0; i < length ; i++){
if(input[i] != input[length-i-1]){
result = false;
break;
}
}
return result;
}
int main()
{
char input_str[99], tmp_input_str[99];
bool status = false;
int i = 0;
std::cout << "Input a string: "; std::cin.getline(input_str, 99);
while (input_str[i])
{
tmp_input_str[i] = tolower(input_str[i]);
i++;
}
status = checkPalindrome(tmp_input_str);
if (status)
std::cout << input_str << " --> palindrome\n";
else
std::cout << input_str << " --> not palindrome\n";
return 0;
}<file_sep># Skill Test From Refactory.id -- Q1
This is a payment receipt program for a restaurant.
There are five pieces of input that must be filled in.
There are :
1. Resto name.
2. Date of print.
3. Cashier name.
4. The item.
5. The price.
How to build :
1. Create folder build using ```mkdir build```
3. ```cd build/```
4. ```cmake ..```
5. ```make```
How to run :
1. ```cd build/```
2. ```./run-q-1```
<file_sep>const config = require("../config");
function redirectUri() {
return `${config.oauthUrl}/authorize?client_id=${config.clientId}`;
}
module.export = {
redirectUri: redirectUri
}
<file_sep>cmake_minimum_required(VERSION 2.8.3)
project(palindrome)
add_compile_options(-std=c++11)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTOUIC ON)
## Declare a C++ executable
## With catkin_make all packages are built within a single CMake context
## The recommended prefix ensures that target names across packages don't collide
add_executable(${PROJECT_NAME}
palindrome.cpp
)<file_sep>#!/usr/bin/python
# -*- coding: utf-8 -*-
# Find items in the Meeting Room.
# Find all electronic devices.
# Find all the furniture.
# Find all items were purchased on 16 Januari 2020.
# Find all items with brown color.
import json
database = "json_manip2_data.json"
data = json.loads(open(database).read())
print("items in the Meeting Room : ")
for i in data:
if i["placement"]["name"] == "Meeting Room":
print i["name"]
print("\nall electronic devices : ")
for i in data:
if i["type"] == "electronic":
print i["name"]
print("\nall the furniture : ")
for i in data:
if i["type"] == "furniture":
print i["name"]
print("\nall items were purchased on 16 Januari 2020 : ")
for i in data:
if i["purchased_at"] == 200116:
print i["name"]
print("Nothing")
print("\nall items with brown color : ")
for i in data:
for j in i["tags"]:
if j == "brown":
print i["name"]<file_sep># Skill Test From Refactory.id
- Q1 (Answer from Questions 1)
- Q2 (Answer from Questions 2)
- Q3 (Answer from Questions 3)
- Q4 (Answer from Questions 4)
- Q5 (Answer from Questions 5)
- Q6 (Answer from Questions 6)
<file_sep>#pragma once
#include <iostream>
#include <sstream>
#include <string>
#include <ctime>
#include <stdlib.h>
#include <iomanip>
#include <vector>
class PaymentReceipt
{
public:
PaymentReceipt();
~PaymentReceipt();
void loadTimeandDate();
void setInput();
void setOutput();
void process();
private:
std::string resto_name;
std::string date_of_print;
std::string cashier_name;
std::vector<std::string> item;
std::vector<int> price;
int tot_item;
bool flag_exit;
};<file_sep>#!/usr/bin/python
# -*- coding: utf-8 -*-
# Find users who don't have any phone numbers.
# Find users who have articles.
# Find users who have "annis" on their name.
# Find users who have articles on the year 2020.
# Find users who are born in 1986.
# Find articles that contain "tips" on the title.
# Find articles published before August 2019.
import json
database = "json_manip_data.json"
data = json.loads(open(database).read())
empty = []
flag = False
print("users who don't have any phone numbers : ")
for i in data:
if i["profile"]["phones"] == empty:
print i["username"]
print("\nusers who have articles : ")
for i in data:
for j in i["articles:"]:
if j["title"]:
flag = True
if(flag):
print i["username"]
flag = False
print("\nusers who have 'annis' on their name : ")
for i in data:
if i["profile"]["full_name"].lower() == "annis":
print i["profile"]["full_name"]
print("\nusers who have articles on the year 2020 : ")
print("\nusers who are born in 1986 : ")
for i in data:
if i["profile"]["birthday"] == "1986":
print i["username"]
print("\narticles that contain 'tips' on the title : ")
print("\narticles published before August 2019 : ")<file_sep>NODE_ENV=development
PORT=3000
CLIENT_ID=
CLIENT_SECRET=
OAUTH_URL=
API_URL=<file_sep>file(REMOVE_RECURSE
"CMakeFiles/leap_year.dir/leap_year.cpp.o"
"leap_year.pdb"
"leap_year"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/leap_year.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>const express = require("express");
const authService = require("./src/services/authService");
const AuthCallbackService = require("./src/services/authCallbackService");
const config = require("./src/config");
const app = express();
app.get("/", (req, res) => {
const auth = authService.redirectUri();
res.redirect(auth);
});
app.get("/oauth-github-callback", (req, res) => {
return AuthCallbackService.callback(req, res);
});
app.listen(config.port);
console.log(`App listening on http://localhost:${config.port}`);
<file_sep># Skill Test From Refactory.id -- Q4
Program json with python
How to run palindrome.cpp :
```python js_manip2.py``` | 14a8af0baa7e63134366ac56e40f5abc933a6973 | [
"CMake",
"Markdown",
"JavaScript",
"Python",
"C++",
"Shell"
] | 21 | Markdown | hernantak/answer-test-refactoryid | 3917b7f5f112677ed34c23bde5a83fd71f62d0b3 | 2911a66183a01f3692ba72b23e9293d3f47eaa59 |
refs/heads/main | <file_sep># COSC-3P93-Parallel-Computing
Parallel Computing
<file_sep># include <bits/stdc++.h>
# include "mpi.h"
# include <string.h>
# include <time.h>
using namespace std;
// compile command: mpic++ -g -Wall -o test PS3.cpp
// execute command: mpiexec -n <desired # of processors> ./test
const string GENES = "abcdefghijklmnopqrstuvwsyzABDCDEFGHIJKLMNOPQRSTUVWSYZ"\
"1234567890,./<>? ;':[]{}!@#$%^&*()_+-=";
string target = "Hello world.Hello world.Hello world.Hello world.Hello world.Hello world.Hello world.Hello world.Hello world.Hello world.";
int size = 1024;
int pop_size = 1000;
/**
* This function generates a random integer in the range of the given min and max.
*
* **/
int random(int str, int end) {
int range = (end-str)+1;
int ran = str + (rand()%range);
return ran;
}
/**
* This function returns a random characters in the GENES pool.
*
* **/
char mutation(){
int rand = random(0, GENES.size()-1);
return GENES[rand];
}
/**
* This function creates a chromosome by randomly picking a characters from the GENES pool adds them together.
*
* **/
string populate(int size){
string new_chromosome = "";
for(int i=0; i<size; i++){
new_chromosome += mutation();
}
return new_chromosome;
}
/**
* This class represents the gene in which it contains a string as chromosome and an int as fitness score.
*
* **/
class gene{
public:
string chromosome;
int fitness;
int get_fitness();
gene(string chromosome);
gene create_offspring(gene partner);
};
/**
* This function initializes a gene when it is created.
*
* **/
gene::gene (string chromosome){
this->chromosome = chromosome;
fitness = get_fitness();
}
/**
* This function calculates the fitness score for a chromosome by matching it with the target string.
*
* **/
int gene::get_fitness(){
int score = 0;
int size = chromosome.size();
for(int i=0; i<size; i++){
if(chromosome[i] == target[i]){
score += 1;
}
}
return score;
}
/**
* This function manages the sort method of vector. high to low. (highest in the front)
*
* **/
bool operator<(const gene gene1, const gene gene2) {
return gene1.fitness > gene2.fitness;
}
/**
* This function creates a new chromosome by taking a character from parent1 or parent2 based on the random number or mutate the gene with random characters.
* rand is the randome num, rand <0.5 -> take chromosome of parent1
* 0.5< rand <0.9 -> take chromosome of parent2
* 0.9< rand <1 -> mutation: random characters from GENES pool
*
* **/
gene gene::create_offspring(gene partner){
string child = "";
int size = chromosome.size();
for(int i=0; i<size; i++){
int rand = random(0, 100)/100;
if (rand < 0.5){
child += chromosome[i];
}else if(rand < 0.9){
child += partner.chromosome[i];
}else{
child += mutation();
}
}
return gene (child);
}
/**
* This function removes the last element from the vector until the size of vector is equal to the given integer.
*
* **/
vector<gene> correct_vector_size(vector<gene> pop, int pop_size){
while((unsigned)pop.size()>(unsigned)pop_size){
pop.erase(pop.end());
}
return pop;
}
int main(){
clock_t start = clock(); // initalize vairables
int rank, comm_size;
MPI_Init(NULL, NULL);
MPI_Comm_size(MPI_COMM_WORLD, &comm_size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
srand ((unsigned)1);
int generation = 0;
vector<gene> population;
int result = 0;
string new_pop;
char characters[size]; // initalize vairables
int partition = ceil(pop_size/(double)(comm_size-1)); // partition is calculate so that the processors give the exact # of population or more.
// see report for more details
if (rank != 0) { // slave processors
for(int i=0; i< partition; i++){ // create random chromosomes and send it to the master processor.
new_pop = populate(target.size());
sprintf(characters, "%s", new_pop.c_str());
MPI_Send(characters, strlen(characters)+1, MPI_CHAR, 0, 0, MPI_COMM_WORLD);
}
string temp[2];
int num_mate = (90 * pop_size)/100;
partition = ceil(num_mate/(double)comm_size-1); // partition is adjusted to 90% of population because elitism already handle 10%.
while(result ==0){
for(int p=0; p<partition; p++){ // start receive parents and create offsrpings and send to master processor
for(int i=0; i<2; i++){
MPI_Recv(characters, size, MPI_CHAR, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); //receive parents' chromosomes
temp[i] = characters;
}
gene parent1 = gene(temp[0]);
gene parent2 = gene(temp[1]);
gene child = parent1.create_offspring(parent2);
sprintf(characters, "%s", child.chromosome.c_str());
MPI_Send(characters, strlen(characters)+1, MPI_CHAR, 0, 0, MPI_COMM_WORLD);
}
}
} else { // master processor
for(int i=0; i< partition; i++){ // receives random chromosomes
for (int q = 1; q < comm_size; q++) {
MPI_Recv(characters, size, MPI_CHAR, q, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
population.push_back(gene(characters));
}
}
population = correct_vector_size(population, pop_size); // correct the vector size
while(result==0){
sort(population.begin(), population.end()); // sort from high to low
if((unsigned)population[0].fitness == target.size()){ // break if found the solution
result = 1;
break;
}
vector<gene> new_gen;
int elite = (10 * pop_size)/100; // perfrom elitism on top 10% of population
for(int i=0; i<elite; i++){
new_gen.push_back(population[i]);
}
int num_mate = (90 * pop_size)/100;
partition = ceil(num_mate/(double)comm_size-1);
for(int p=0; p<partition; p++){ // send parents' chromosomes and receive offspring chromosome
for(int j=0; j<2; j++){
for(int i=1; i<comm_size; i++){
int rand = random(0, num_mate);
string temp = population[rand].chromosome;
sprintf(characters, "%s", temp.c_str());
MPI_Send(characters, strlen(characters)+1, MPI_CHAR, i, 0, MPI_COMM_WORLD);
}
}
for (int q = 1; q < comm_size; q++) {
MPI_Recv(characters, size, MPI_CHAR, q, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
new_gen.push_back(gene(characters));
}
}
sort(population.begin(), population.end());
population = new_gen; /** // uncomment to print the fittest in each generation
cout << "Generation: " << generation << "\t";
cout << "Chromosome: " << population[0].chromosome <<"\t";
cout << "Fitness score: " << population[0].fitness << "\n";
**/
generation++;
}
cout << "Generation: " << generation << "\t";
cout << "Chromosome: " << population[0].chromosome <<"\t";
cout << "Fitness score: " << population[0].fitness << "\n";
printf("Execution time is: %.2fs\n", (double)(clock()-start)/CLOCKS_PER_SEC);
}
MPI_Abort(MPI_COMM_WORLD, 1); // terminate all processes
MPI_Finalize();
return 0;
} | 32a2c1fa9cee1420e5e9f480483edac80b9f79e3 | [
"Markdown",
"C++"
] | 2 | Markdown | danny150799/COSC-3P93-Parallel-Computing | b179e99b960b67a2a1766dc67e4b9c49a5bdbba1 | a3e3e34c2f71eca9ab66083ceca305d827410dbb |
refs/heads/main | <file_sep>-- Overview of the database
SELECT 'Customers' AS table_name,
13 AS number_of_attribute,
COUNT(*) AS number_of_row
FROM Customers
UNION ALL
SELECT 'Products' AS table_name,
9 AS number_of_attribute,
COUNT(*) AS number_of_row
FROM Products
UNION ALL
SELECT 'ProductLines' AS table_name,
4 AS number_of_attribute,
COUNT(*) AS number_of_row
FROM ProductLines
UNION ALL
SELECT 'Orders' AS table_name,
7 AS number_of_attribute,
COUNT(*) AS number_of_row
FROM Orders
UNION ALL
SELECT 'OrderDetails' AS table_name,
5 AS number_of_attribute,
COUNT(*) AS number_of_row
FROM OrderDetails
UNION ALL
SELECT 'Payments' AS table_name,
4 AS number_of_attribute,
COUNT(*) AS number_of_row
FROM Payments
UNION ALL
SELECT 'Employees' AS table_name,
8 AS number_of_attribute,
COUNT(*) AS number_of_row
FROM Employees
UNION ALL
SELECT 'Offices' AS table_name,
9 AS number_of_attribute,
COUNT(*) AS number_of_row
FROM Offices;
/*
Question #1: Which products should we order more of or less of?
This question refers to inventory reports, including low stock and product performance.
This will optimize the supply and the user experience by preventing the best-selling products from going out-of-stock.
- The low stock represents the quantity of each product sold divided by the quantity of product in stock.
We can consider the ten lowest rates. These will be the top ten products that are (almost) out-of-stock.
- The product performance represents the sum of sales per product.
- Priority products for restocking are those with high product performance that are on the brink of being out of stock.
*/
-- 1.1 Finding which products are low on stock
SELECT p.productCode, ROUND(SUM(od.quantityOrdered) * 1.0 / p.quantityInStock, 2) AS low_stock
FROM products p
JOIN Orderdetails od
ON p.productCode = od.productCode
GROUP BY p.productCode
ORDER BY low_stock
LIMIT 10;
-- 1.2 Finding the products that sell more
SELECT productCode, SUM(quantityOrdered * priceEach) AS product_performance
FROM orderdetails
GROUP BY productCode
ORDER BY product_performance DESC
LIMIT 10;
-- 1.3 Combining queries to answer Question #1
WITH
low_stock_table AS (SELECT p.productCode,
p.productName,
p.productLine,
ROUND(SUM(od.quantityOrdered) * 1.0 / p.quantityInStock, 2) AS low_stock
FROM products p
JOIN Orderdetails od
ON p.productCode = od.productCode
GROUP BY p.productCode
ORDER BY low_stock
LIMIT 10
)
SELECT lst.productCode,
lst.productName,
lst.productLine,
SUM(quantityOrdered * priceEach) AS product_performance
FROM low_stock_table lst
JOIN orderdetails od
ON lst.productCode = od.productCode
GROUP BY lst.productCode
ORDER BY product_performance DESC
LIMIT 10;
/*
Question #2: How Should We Match Marketing and Communication Strategies to Customer Behavior?
We’ll explore customer information by answering the second question:
how should we match marketing and communication strategies to customer behaviors?
This involves categorizing customers:
finding the VIP (very important person) customers and those who are less engaged.
*/
-- 2.1 Profit for each customer
SELECT o.customerNumber, SUM(quantityOrdered * (priceEach - buyPrice)) AS revenue
FROM products p
JOIN orderdetails od
ON p.productCode = od.productCode
JOIN orders o
ON o.orderNumber = od.orderNumber
GROUP BY o.customerNumber;
-- 2.2 (CTE) Top Five VIP Customers
WITH
money_in_by_customer_table AS (
SELECT o.customerNumber, SUM(quantityOrdered * (priceEach - buyPrice)) AS revenue
FROM products p
JOIN orderdetails od
ON p.productCode = od.productCode
JOIN orders o
ON o.orderNumber = od.orderNumber
GROUP BY o.customerNumber
)
SELECT contactFirstName, contactLastName, city, country, mc.revenue
FROM customers c
JOIN money_in_by_customer_table mc
ON mc.customerNumber = c.customerNumber
ORDER BY mc.revenue DESC
LIMIT 5;
-- Alternative way (using subqueries)
-- 2.1.1 Profit for each customer
SELECT o.customerNumber, SUM(quantityOrdered * (priceEach - buyPrice)) AS revenue
FROM products p
JOIN orderdetails od
ON p.productCode = od.productCode
JOIN orders o
ON o.orderNumber = od.orderNumber
GROUP BY o.customerNumber;
ORDER BY proft_per_customer DESC
LIMIT 5;
-- 2.2.2 (CTE) Top Five VIP Customers
WITH
top_five AS ( SELECT o.customerNumber, SUM(quantityOrdered * (priceEach - buyPrice)) AS revenue
FROM products p
JOIN orderdetails od
ON p.productCode = od.productCode
JOIN orders o
ON o.orderNumber = od.orderNumber
GROUP BY o.customerNumber
ORDER BY revenue DESC
LIMIT 5
)
SELECT customerNumber,
contactLastName,
contactFirstName,
city,
country,
(SELECT revenue
FROM top_five
WHERE customerNumber = c.customerNumber) AS revenue
FROM customers c
WHERE c.customerNumber IN (SELECT customerNumber
FROM top_five)
GROUP BY customerNumber
ORDER BY revenue DESC;
-- 2.3 Top five least engaged customers
WITH
less_engaged AS (
SELECT o.customerNumber, SUM(quantityOrdered * (priceEach - buyPrice)) AS revenue
FROM products p
JOIN orderdetails od
ON p.productCode = od.productCode
JOIN orders o
ON o.orderNumber = od.orderNumber
GROUP BY o.customerNumber
)
SELECT c.customerNumber,
contactFirstName,
contactLastName,
city,
country,
ls.revenue
FROM less_engaged ls
JOIN customers c
ON ls.customerNumber = c.customerNumber
ORDER BY revenue
LIMIT 5;
/* Question #3: How much we can spend on marketing for each customer?
To determine how much money we can spend acquiring new customers,
we can compute the Customer Lifetime Value (LTV),
representing the average amount of money a customer generates.
We can then determine how much we can spend on marketing.
*/
-- 3.1 CLV
WITH
money_in_by_customer_table AS(
SELECT o.customerNumber, SUM(quantityOrdered * (priceEach - buyPrice)) AS revenue
FROM products p
JOIN orderdetails od
ON p.productCode = od.productCode
JOIN orders o
ON o.orderNumber = od.orderNumber
GROUP BY o.customerNumber
)
SELECT ROUND(AVG(revenue), 2) AS CLV
FROM money_in_by_customer_table mc;
| 7a32f982e6b1eede59d73d6ae523fc5e238e0a45 | [
"SQL"
] | 1 | SQL | davidetaraborrelli/Projects_cars | 56dd1339a4c149622bfa9d3dd61dc256443fced3 | dc4d21de4b57523955a59426c333605c4782abf7 |
refs/heads/dev_test | <repo_name>zhouhang95/blender_mmd_tools<file_sep>/mmd_tools/core/pmd/__init__.py
# -*- coding: utf-8 -*-
import struct
import os
import re
import logging
import collections
class InvalidFileError(Exception):
pass
class UnsupportedVersionError(Exception):
pass
class FileStream:
def __init__(self, path, file_obj):
self.__path = path
self.__file_obj = file_obj
self.__header = None
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def path(self):
return self.__path
def header(self):
if self.__header is None:
raise Exception
return self.__header
def setHeader(self, pmx_header):
self.__header = pmx_header
def close(self):
if self.__file_obj is not None:
logging.debug('close the file("%s")', self.__path)
self.__file_obj.close()
self.__file_obj = None
class FileReadStream(FileStream):
def __init__(self, path, pmx_header=None):
self.__fin = open(path, 'rb')
FileStream.__init__(self, path, self.__fin)
# READ / WRITE methods for general types
def readInt(self):
v, = struct.unpack('<i', self.__fin.read(4))
return v
def readUnsignedInt(self):
v, = struct.unpack('<I', self.__fin.read(4))
return v
def readShort(self):
v, = struct.unpack('<h', self.__fin.read(2))
return v
def readUnsignedShort(self):
v, = struct.unpack('<H', self.__fin.read(2))
return v
def readStr(self, size):
buf = self.__fin.read(size)
if buf[0] == b'\xfd':
return ''
return buf.split(b'\x00')[0].decode('shift_jis', errors='replace')
def readFloat(self):
v, = struct.unpack('<f', self.__fin.read(4))
return v
def readVector(self, size):
return struct.unpack('<'+'f'*size, self.__fin.read(4*size))
def readByte(self):
v, = struct.unpack('<B', self.__fin.read(1))
return v
def readBytes(self, length):
return self.__fin.read(length)
def readSignedByte(self):
v, = struct.unpack('<b', self.__fin.read(1))
return v
class Header:
PMD_SIGN = b'Pmd'
VERSION = 1.0
def __init__(self):
self.sign = self.PMD_SIGN
self.version = self.VERSION
self.model_name = ''
self.comment = ''
def load(self, fs):
sign = fs.readBytes(3)
if sign != self.PMD_SIGN:
raise InvalidFileError('Not PMD file')
version = fs.readFloat()
if version != self.version:
raise InvalidFileError('Not suppored version')
self.model_name = fs.readStr(20)
self.comment = fs.readStr(256)
class Vertex:
def __init__(self):
self.position = [0.0, 0.0, 0.0]
self.normal = [1.0, 0.0, 0.0]
self.uv = [0.0, 0.0]
self.bones = [-1, -1]
self.weight = 0 # min:0, max:100
self.enable_edge = 0 # 0: on, 1: off
def load(self, fs):
self.position = fs.readVector(3)
self.normal = fs.readVector(3)
self.uv = fs.readVector(2)
self.bones[0] = fs.readUnsignedShort()
self.bones[1] = fs.readUnsignedShort()
self.weight = fs.readByte()
self.enable_edge = fs.readByte()
class Material:
def __init__(self):
self.diffuse = []
self.shininess = 0
self.specular = []
self.ambient = []
self.toon_index = 0
self.edge_flag = 0
self.vertex_count = 0
self.texture_path = ''
self.sphere_path = ''
self.sphere_mode = 1
def load(self, fs):
self.diffuse = fs.readVector(4)
self.shininess = fs.readFloat()
self.specular = fs.readVector(3)
self.ambient = fs.readVector(3)
self.toon_index = fs.readSignedByte()
self.edge_flag = fs.readByte()
self.vertex_count = fs.readUnsignedInt()
tex_path = fs.readStr(20)
tex_path = tex_path.replace('\\', os.path.sep)
t = tex_path.split('*')
if not re.search(r'\.sp([ha])$', t[0], flags=re.I):
self.texture_path = t.pop(0)
if len(t) > 0:
self.sphere_path = t.pop(0)
if 'aA'.find(self.sphere_path[-1]) != -1:
self.sphere_mode = 2
class Bone:
def __init__(self):
self.name = ''
self.name_e = ''
self.parent = 0xffff
self.tail_bone = 0xffff
self.type = 1
self.ik_bone = 0
self.position = []
def load(self, fs):
self.name = fs.readStr(20)
self.parent = fs.readUnsignedShort()
if self.parent == 0xffff:
self.parent = -1
self.tail_bone = fs.readUnsignedShort()
if self.tail_bone == 0xffff:
self.tail_bone = -1
self.type = fs.readByte()
if self.type == 9:
self.ik_bone = fs.readShort()
else:
self.ik_bone = fs.readUnsignedShort()
self.position = fs.readVector(3)
class IK:
def __init__(self):
self.bone = 0
self.target_bone = 0
self.ik_chain = 0
self.iterations = 0
self.control_weight = 0.0
self.ik_child_bones = []
def __str__(self):
return '<IK bone: %d, target: %d, chain: %s, iter: %d, weight: %f, ik_children: %s'%(
self.bone,
self.target_bone,
self.ik_chain,
self.iterations,
self.control_weight,
self.ik_child_bones)
def load(self, fs):
self.bone = fs.readUnsignedShort()
self.target_bone = fs.readUnsignedShort()
self.ik_chain = fs.readByte()
self.iterations = fs.readUnsignedShort()
self.control_weight = fs.readFloat()
self.ik_child_bones = []
for i in range(self.ik_chain):
self.ik_child_bones.append(fs.readUnsignedShort())
class MorphData:
def __init__(self):
self.index = 0
self.offset = []
def load(self, fs):
self.index = fs.readUnsignedInt()
self.offset = fs.readVector(3)
class VertexMorph:
def __init__(self):
self.name = ''
self.name_e = ''
self.type = 0
self.data = []
def load(self, fs):
self.name = fs.readStr(20)
data_size = fs.readUnsignedInt()
self.type = fs.readByte()
for i in range(data_size):
t = MorphData()
t.load(fs)
self.data.append(t)
class RigidBody:
def __init__(self):
self.name = ''
self.bone = -1
self.collision_group_number = 0
self.collision_group_mask = 0
self.type = 0
self.size = []
self.location = []
self.rotation = []
self.mass = 0.0
self.velocity_attenuation = 0.0
self.rotation_attenuation = 0.0
self.friction = 0.0
self.bounce = 0.0
self.mode = 0
def load(self, fs):
self.name = fs.readStr(20)
self.bone = fs.readUnsignedShort()
if self.bone == 0xffff:
self.bone = -1
self.collision_group_number = fs.readByte()
self.collision_group_mask = fs.readUnsignedShort()
self.type = fs.readByte()
self.size = fs.readVector(3)
self.location = fs.readVector(3)
self.rotation = fs.readVector(3)
self.mass = fs.readFloat()
self.velocity_attenuation = fs.readFloat()
self.rotation_attenuation = fs.readFloat()
self.bounce = fs.readFloat()
self.friction = fs.readFloat()
self.mode = fs.readByte()
class Joint:
def __init__(self):
self.name = ''
self.src_rigid = 0
self.dest_rigid = 0
self.location = []
self.rotation = []
self.maximum_location = []
self.minimum_location = []
self.maximum_rotation = []
self.minimum_rotation = []
self.spring_constant = []
self.spring_rotation_constant = []
def load(self, fs):
self.name = fs.readStr(20)
self.src_rigid = fs.readUnsignedInt()
self.dest_rigid = fs.readUnsignedInt()
self.location = fs.readVector(3)
self.rotation = fs.readVector(3)
self.minimum_location = fs.readVector(3)
self.maximum_location = fs.readVector(3)
self.minimum_rotation = fs.readVector(3)
self.maximum_rotation = fs.readVector(3)
self.spring_constant = fs.readVector(3)
self.spring_rotation_constant = fs.readVector(3)
class Model:
def __init__(self):
self.header = None
self.vertices = []
self.faces = []
self.materials = []
self.iks = []
self.morphs = []
self.facial_disp_names = []
self.bone_disp_names = []
self.bone_disp_lists = {}
self.name = ''
self.comment = ''
self.name_e = ''
self.comment_e = ''
self.toon_textures = []
self.rigid_bodies = []
self.joints = []
def load(self, fs):
logging.info('importing pmd model from %s...', fs.path())
header = Header()
header.load(fs)
self.name = header.model_name
self.comment = header.comment
logging.info('Model name: %s', self.name)
logging.info('Comment: %s', self.comment)
logging.info('')
logging.info('------------------------------')
logging.info('Load Vertices')
logging.info('------------------------------')
self.vertices = []
vert_count = fs.readUnsignedInt()
for i in range(vert_count):
v = Vertex()
v.load(fs)
self.vertices.append(v)
logging.info('the number of vetices: %d', len(self.vertices))
logging.info('finished importing vertices.')
logging.info('')
logging.info('------------------------------')
logging.info(' Load Faces')
logging.info('------------------------------')
self.faces = []
face_vert_count = fs.readUnsignedInt()
for i in range(int(face_vert_count/3)):
f1 = fs.readUnsignedShort()
f2 = fs.readUnsignedShort()
f3 = fs.readUnsignedShort()
self.faces.append((f3, f2, f1))
logging.info('the number of faces: %d', len(self.faces))
logging.info('finished importing faces.')
logging.info('')
logging.info('------------------------------')
logging.info(' Load Materials')
logging.info('------------------------------')
self.materials = []
material_count = fs.readUnsignedInt()
for i in range(material_count):
mat = Material()
mat.load(fs)
self.materials.append(mat)
logging.info('Material %d', i)
logging.debug(' Vertex Count: %d', mat.vertex_count)
logging.debug(' Diffuse: (%.2f, %.2f, %.2f, %.2f)', *mat.diffuse)
logging.debug(' Specular: (%.2f, %.2f, %.2f)', *mat.specular)
logging.debug(' Shininess: %f', mat.shininess)
logging.debug(' Ambient: (%.2f, %.2f, %.2f)', *mat.ambient)
logging.debug(' Toon Index: %d', mat.toon_index)
logging.debug(' Edge Type: %d', mat.edge_flag)
logging.debug(' Texture Path: %s', str(mat.texture_path))
logging.debug(' Sphere Texture Path: %s', str(mat.sphere_path))
logging.debug('')
logging.info('Loaded %d materials', len(self.materials))
logging.info('')
logging.info('------------------------------')
logging.info(' Load Bones')
logging.info('------------------------------')
self.bones = []
bone_count = fs.readUnsignedShort()
for i in range(bone_count):
bone = Bone()
bone.load(fs)
self.bones.append(bone)
logging.info('Bone %d: %s', i, bone.name)
logging.debug(' Name(english): %s', bone.name_e)
logging.debug(' Location: (%f, %f, %f)', *bone.position)
logging.debug(' Parent: %s', str(bone.parent))
logging.debug(' Related Bone: %s', str(bone.tail_bone))
logging.debug(' Type: %s', bone.type)
logging.debug(' IK bone: %s', str(bone.ik_bone))
logging.debug('')
logging.info('----- Loaded %d bones', len(self.bones))
logging.info('')
logging.info('------------------------------')
logging.info(' Load IKs')
logging.info('------------------------------')
self.iks = []
ik_count = fs.readUnsignedShort()
for i in range(ik_count):
ik = IK()
ik.load(fs)
self.iks.append(ik)
logging.info('IK %d', i)
logging.debug(' Bone: %s(index: %d)', self.bones[ik.bone].name, ik.bone)
logging.debug(' Target Bone: %s(index: %d)', self.bones[ik.target_bone].name, ik.target_bone)
logging.debug(' IK Chain: %d', ik.ik_chain)
logging.debug(' IK Iterations: %d', ik.iterations)
logging.debug(' Wegiht: %d', ik.control_weight)
for j, c in enumerate(ik.ik_child_bones):
logging.debug(' Bone %d: %s(index: %d)', j, self.bones[c].name, c)
logging.debug('')
logging.info('----- Loaded %d IKs', len(self.iks))
logging.info('')
logging.info('------------------------------')
logging.info(' Load Morphs')
logging.info('------------------------------')
self.morphs = []
morph_count = fs.readUnsignedShort()
for i in range(morph_count):
morph = VertexMorph()
morph.load(fs)
self.morphs.append(morph)
logging.info('Vertex Morph %d: %s', i, morph.name)
logging.info('----- Loaded %d morphs', len(self.morphs))
logging.info('')
logging.info('------------------------------')
logging.info(' Load Display Items')
logging.info('------------------------------')
self.facial_disp_morphs = []
t = fs.readByte()
for i in range(t):
u = fs.readUnsignedShort()
self.facial_disp_morphs.append(u)
logging.info('Facial %d: %s', i, self.morphs[u].name)
self.bone_disp_lists = collections.OrderedDict()
bone_disps = []
t = fs.readByte()
for i in range(t):
name = fs.readStr(50)
self.bone_disp_lists[name] = []
bone_disps.append(name)
self.bone_disp_names = [bone_disps, None]
t = fs.readUnsignedInt()
for i in range(t):
bone_index = fs.readUnsignedShort()
disp_index = fs.readByte()
self.bone_disp_lists[bone_disps[disp_index-1]].append(bone_index)
for i, (k, items) in enumerate(self.bone_disp_lists.items()):
logging.info(' Frame %d: %s', i, k.rstrip())
for j, b in enumerate(items):
logging.info(' Bone %d: %s(index: %d)', j, self.bones[b].name, b)
logging.info('----- Loaded display items')
logging.info('')
logging.info('===============================')
logging.info(' Load Display Items')
logging.info(' try to load extended data sections...')
logging.info('')
# try to load extended data sections.
try:
eng_flag = fs.readByte()
except Exception:
logging.info('found no extended data sections')
logging.info('===============================')
return
logging.info('===============================')
logging.info('')
logging.info('------------------------------')
logging.info(' Load a extended data for english')
logging.info('------------------------------')
if eng_flag:
logging.info('found a extended data for english.')
self.name_e = fs.readStr(20)
self.comment_e = fs.readStr(256)
for i in range(len(self.bones)):
self.bones[i].name_e = fs.readStr(20)
for i in range(1, len(self.morphs)):
self.morphs[i].name_e = fs.readStr(20)
logging.info(' Name(english): %s', self.name_e)
logging.info(' Comment(english): %s', self.comment_e)
bone_disps_e = []
for i in range(len(bone_disps)):
t = fs.readStr(50)
bone_disps_e.append(t)
logging.info(' Bone name(english) %d: %s', i, t)
self.bone_disp_names[1] = bone_disps_e
logging.info('----- Loaded english data.')
logging.info('')
logging.info('------------------------------')
logging.info(' Load toon textures')
logging.info('------------------------------')
self.toon_textures = []
for i in range(10):
t = fs.readStr(100)
t = t.replace('\\', os.path.sep)
self.toon_textures.append(t)
logging.info('Toon Texture %d: %s', i, t)
logging.info('----- Loaded %d textures', len(self.toon_textures))
logging.info('')
logging.info('------------------------------')
logging.info(' Load Rigid Bodies')
logging.info('------------------------------')
try:
rigid_count = fs.readUnsignedInt()
except struct.error:
logging.info('no physics data')
logging.info('===============================')
return
self.rigid_bodies = []
for i in range(rigid_count):
rigid = RigidBody()
rigid.load(fs)
self.rigid_bodies.append(rigid)
logging.info('Rigid Body %d: %s', i, rigid.name)
logging.debug(' Bone: %s', rigid.bone)
logging.debug(' Collision group: %d', rigid.collision_group_number)
logging.debug(' Collision group mask: 0x%x', rigid.collision_group_mask)
logging.debug(' Size: (%f, %f, %f)', *rigid.size)
logging.debug(' Location: (%f, %f, %f)', *rigid.location)
logging.debug(' Rotation: (%f, %f, %f)', *rigid.rotation)
logging.debug(' Mass: %f', rigid.mass)
logging.debug(' Bounce: %f', rigid.bounce)
logging.debug(' Friction: %f', rigid.friction)
logging.debug('')
logging.info('----- Loaded %d rigid bodies', len(self.rigid_bodies))
logging.info('')
logging.info('------------------------------')
logging.info(' Load Joints')
logging.info('------------------------------')
joint_count = fs.readUnsignedInt()
self.joints = []
for i in range(joint_count):
joint = Joint()
joint.load(fs)
self.joints.append(joint)
logging.info('Joint %d: %s', i, joint.name)
logging.debug(' Rigid A: %s', joint.src_rigid)
logging.debug(' Rigid B: %s', joint.dest_rigid)
logging.debug(' Location: (%f, %f, %f)', *joint.location)
logging.debug(' Rotation: (%f, %f, %f)', *joint.rotation)
logging.debug(' Location Limit: (%f, %f, %f) - (%f, %f, %f)', *(joint.minimum_location + joint.maximum_location))
logging.debug(' Rotation Limit: (%f, %f, %f) - (%f, %f, %f)', *(joint.minimum_rotation + joint.maximum_rotation))
logging.debug(' Spring: (%f, %f, %f)', *joint.spring_constant)
logging.debug(' Spring(rotation): (%f, %f, %f)', *joint.spring_rotation_constant)
logging.debug('')
logging.info('----- Loaded %d joints', len(self.joints))
logging.info('finished importing the model.')
def load(path):
with FileReadStream(path) as fs:
logging.info('****************************************')
logging.info(' mmd_tools.pmd module')
logging.info('----------------------------------------')
logging.info(' Start load model data form a pmd file')
logging.info(' by the mmd_tools.pmd modlue.')
logging.info('')
model = Model()
try:
model.load(fs)
except struct.error as e:
logging.error(' * Corrupted file: %s', e)
#raise
logging.info(' Finish loading.')
logging.info('----------------------------------------')
logging.info(' mmd_tools.pmd module')
logging.info('****************************************')
return model
<file_sep>/mmd_tools/core/shader.py
# -*- coding: utf-8 -*-
import bpy
class _NodeTreeUtils:
def __init__(self, shader):
self.shader, self.nodes, self.links = shader, shader.nodes, shader.links
def _find_node(self, node_type):
return next((n for n in self.nodes if n.bl_idname == node_type), None)
def new_node(self, idname, pos):
node = self.nodes.new(idname)
node.location = (pos[0]*210, pos[1]*220)
return node
def new_math_node(self, operation, pos, value1=None, value2=None):
node = self.new_node('ShaderNodeMath', pos)
node.operation = operation
if value1 is not None:
node.inputs[0].default_value = value1
if value2 is not None:
node.inputs[1].default_value = value2
return node
def new_vector_math_node(self, operation, pos, vector1=None, vector2=None):
node = self.new_node('ShaderNodeVectorMath', pos)
node.operation = operation
if vector1 is not None:
node.inputs[0].default_value = vector1
if vector2 is not None:
node.inputs[1].default_value = vector2
return node
def new_mix_node(self, blend_type, pos, fac=None, color1=None, color2=None):
node = self.new_node('ShaderNodeMixRGB', pos)
node.blend_type = blend_type
if fac is not None:
node.inputs['Fac'].default_value = fac
if color1 is not None:
node.inputs[0].default_value = color1
if color2 is not None:
node.inputs[1].default_value = color2
return node
class _NodeGroupUtils(_NodeTreeUtils):
def __init__(self, shader):
super().__init__(shader)
self.__node_input = self.__node_output = None
@property
def node_input(self):
if not self.__node_input:
self.__node_input = self._find_node('NodeGroupInput') or self.new_node('NodeGroupInput', (-2, 0))
return self.__node_input
@property
def node_output(self):
if not self.__node_output:
self.__node_output = self._find_node('NodeGroupOutput') or self.new_node('NodeGroupOutput', (2, 0))
return self.__node_output
def hide_nodes(self, hide_sockets=True):
skip_nodes = {self.__node_input, self.__node_output}
for n in (x for x in self.nodes if x not in skip_nodes):
n.hide = True
if hide_sockets:
for s in n.inputs:
s.hide = not s.is_linked
for s in n.outputs:
s.hide = not s.is_linked
def new_input_socket(self, io_name, socket, default_val=None, min_max=None):
self.__new_io(self.shader.inputs, self.node_input.outputs, io_name, socket, default_val, min_max)
def new_output_socket(self, io_name, socket, default_val=None, min_max=None):
self.__new_io(self.shader.outputs, self.node_output.inputs, io_name, socket, default_val, min_max)
def __new_io(self, shader_io, io_sockets, io_name, socket, default_val=None, min_max=None):
if io_name in io_sockets:
self.links.new(io_sockets[io_name], socket)
else:
self.links.new(io_sockets[-1], socket)
shader_io[-1].name = io_name
if default_val is not None:
shader_io[io_name].default_value = default_val
if min_max is not None:
shader_io[io_name].min_value, shader_io[io_name].max_value = min_max
class _MaterialMorph:
@classmethod
def update_morph_inputs(cls, material, morph):
if material and material.node_tree and morph.name in material.node_tree.nodes:
cls.__update_node_inputs(material.node_tree.nodes[morph.name], morph)
cls.update_morph_inputs(bpy.data.materials.get('mmd_edge.'+material.name, None), morph)
@classmethod
def setup_morph_nodes(cls, material, morphs):
node, nodes = None, []
for m in morphs:
node = cls.__morph_node_add(material, m, node)
nodes.append(node)
if node:
node = cls.__morph_node_add(material, None, node) or node
for n in reversed(nodes):
n.location += node.location
if n.node_tree.name != node.node_tree.name:
n.location.x -= 100
if node.name.startswith('mmd_'):
n.location.y += 1000
node = n
return nodes
@classmethod
def __update_node_inputs(cls, node, morph):
node.inputs['Ambient2'].default_value[:3] = morph.ambient_color[:3]
node.inputs['Diffuse2'].default_value[:3] = morph.diffuse_color[:3]
node.inputs['Specular2'].default_value[:3] = morph.specular_color[:3]
node.inputs['Reflect2'].default_value = morph.shininess
node.inputs['Alpha2'].default_value = morph.diffuse_color[3]
node.inputs['Edge2 RGB'].default_value[:3] = morph.edge_color[:3]
node.inputs['Edge2 A'].default_value = morph.edge_color[3]
node.inputs['Base2 RGB'].default_value[:3] = morph.texture_factor[:3]
node.inputs['Base2 A'].default_value = morph.texture_factor[3]
node.inputs['Toon2 RGB'].default_value[:3] = morph.toon_texture_factor[:3]
node.inputs['Toon2 A'].default_value = morph.toon_texture_factor[3]
node.inputs['Sphere2 RGB'].default_value[:3] = morph.sphere_texture_factor[:3]
node.inputs['Sphere2 A'].default_value = morph.sphere_texture_factor[3]
@classmethod
def __morph_node_add(cls, material, morph, prev_node):
nodes, links = material.node_tree.nodes, material.node_tree.links
shader = nodes.get('mmd_shader', None)
if morph:
node = nodes.new('ShaderNodeGroup')
node.location = (-250, 0)
node.node_tree = cls.__get_shader('Add' if morph.offset_type == 'ADD' else 'Mul')
cls.__update_node_inputs(node, morph)
if prev_node:
for id_name in ('Ambient', 'Diffuse', 'Specular' , 'Reflect','Alpha'):
links.new(prev_node.outputs[id_name], node.inputs[id_name+'1'])
for id_name in ('Edge', 'Base', 'Toon' , 'Sphere'):
links.new(prev_node.outputs[id_name+' RGB'], node.inputs[id_name+'1 RGB'])
links.new(prev_node.outputs[id_name+' A'], node.inputs[id_name+'1 A'])
else: # initial first node
mmd_mat = material.mmd_material
node.inputs['Ambient1'].default_value[:3] = mmd_mat.ambient_color[:3]
node.inputs['Diffuse1'].default_value[:3] = mmd_mat.diffuse_color[:3]
node.inputs['Specular1'].default_value[:3] = mmd_mat.specular_color[:3]
node.inputs['Reflect1'].default_value = mmd_mat.shininess
node.inputs['Alpha1'].default_value = mmd_mat.alpha
node.inputs['Edge1 RGB'].default_value[:3] = mmd_mat.edge_color[:3]
node.inputs['Edge1 A'].default_value = mmd_mat.edge_color[3]
if node.node_tree.name.endswith('Add'):
node.inputs['Base1 A'].default_value = 1
node.inputs['Toon1 A'].default_value = 1
node.inputs['Sphere1 A'].default_value = 1
for id_name in ('Base', 'Toon', 'Sphere'): #FIXME toon only affect shadow color
mmd_tex = nodes.get('mmd_%s_tex'%id_name.lower(), None)
if mmd_tex:
links.new(mmd_tex.outputs['Color'], node.inputs['%s1 RGB'%id_name])
elif shader:
node.inputs['%s1 RGB'%id_name].default_value[:3] = shader.inputs[id_name+' Tex'].default_value[:3]
return node
# connect last node to shader
if shader:
links.new(prev_node.outputs['Ambient'], shader.inputs['Ambient Color'])
links.new(prev_node.outputs['Diffuse'], shader.inputs['Diffuse Color'])
links.new(prev_node.outputs['Specular'], shader.inputs['Specular Color'])
links.new(prev_node.outputs['Reflect'], shader.inputs['Reflect'])
links.new(prev_node.outputs['Alpha'], shader.inputs['Alpha'])
#links.new(prev_node.outputs['Edge RGB'], shader.inputs['Edge Color'])
#links.new(prev_node.outputs['Edge A'], shader.inputs['Edge Alpha'])
links.new(prev_node.outputs['Base Tex'], shader.inputs['Base Tex'])
links.new(prev_node.outputs['Toon Tex'], shader.inputs['Toon Tex'])
if shader.inputs['Sphere Mul/Add'].default_value < 0.5:
links.new(prev_node.outputs['Sphere Tex'], shader.inputs['Sphere Tex'])
else:
links.new(prev_node.outputs['Sphere Tex Add'], shader.inputs['Sphere Tex'])
elif 'mmd_edge_preview' in nodes:
shader = nodes['mmd_edge_preview']
links.new(prev_node.outputs['Edge RGB'], shader.inputs['Color'])
links.new(prev_node.outputs['Edge A'], shader.inputs['Alpha'])
return shader
_LEGACY_MODE = '-' if bpy.app.version < (2, 75, 0) else ''
@classmethod
def __get_shader(cls, morph_type):
group_name = 'MMDMorph' + cls._LEGACY_MODE + morph_type
shader = bpy.data.node_groups.get(group_name, None) or bpy.data.node_groups.new(name=group_name, type='ShaderNodeTree')
if len(shader.nodes):
return shader
ng = _NodeGroupUtils(shader)
nodes, links = ng.nodes, ng.links
use_mul = (morph_type == 'Mul')
def __value_to_color_wrap(out_value, pos):
if cls._LEGACY_MODE: # for viewport
node_wrap = ng.new_node('ShaderNodeCombineRGB', pos)
links.new(out_value, node_wrap.inputs[0])
links.new(out_value, node_wrap.inputs[1])
links.new(out_value, node_wrap.inputs[2])
return node_wrap.outputs[0]
return out_value
############################################################################
node_input = ng.new_node('NodeGroupInput', (-4, 0))
node_output = ng.new_node('NodeGroupOutput', (5, 0))
node_invert = ng.new_math_node('SUBTRACT', (-3, 1), value1=1.0)
node_dummy_vec = ng.new_node('ShaderNodeVectorMath', (-3, -6))
default_vector = (use_mul,)*len(node_dummy_vec.inputs[0].default_value)
ng.new_input_socket('Fac', node_invert.inputs[1], 0)
out_color = __value_to_color_wrap(node_input.outputs['Fac'], (-3, 2))
if use_mul:
out_color_inv = __value_to_color_wrap(node_invert.outputs[0], (-2, 2))
else:
nodes.remove(node_invert)
del node_invert
def __new_io_vector_wrap(io_name, pos):
if cls._LEGACY_MODE: # for cycles
node_wrap = ng.new_vector_math_node('ADD', pos, vector2=(0, 0, 0))
ng.new_input_socket(io_name, node_wrap.inputs[0], default_vector)
return node_wrap.outputs[0]
ng.new_input_socket(io_name, node_dummy_vec.inputs[0], default_vector)
return node_input.outputs[io_name]
def __blend_color_add(id_name, pos, tag=''):
# ColorMul = Color1 * (Fac * Color2 + (1 - Fac))
# ColorAdd = Color1 + Fac * Color2
if use_mul:
node_mul = ng.new_mix_node('MULTIPLY', (pos[0]+1, pos[1]), fac=1.0)
node_blend = ng.new_mix_node('ADD', (pos[0]+2, pos[1]), fac=1.0)
links.new(out_color_inv, node_blend.inputs['Color1'])
links.new(node_mul.outputs['Color'], node_blend.inputs['Color2'])
else:
node_mul = node_blend = ng.new_mix_node('MULTIPLY', (pos[0]+1, pos[1]), fac=1.0)
node_final = ng.new_mix_node('MULTIPLY' if use_mul else 'ADD', (pos[0]+2+use_mul, pos[1]), fac=1.0)
out_vector1 = __new_io_vector_wrap('%s1'%id_name+tag, (pos[0]+1.5+use_mul, pos[1]+0.1))
out_vector2 = __new_io_vector_wrap('%s2'%id_name+tag, (pos[0]+0.5, pos[1]-0.1))
links.new(out_vector1, node_final.inputs['Color1'])
links.new(out_vector2, node_mul.inputs['Color2'])
links.new(out_color, node_mul.inputs['Color1'])
links.new(node_blend.outputs['Color'], node_final.inputs['Color2'])
ng.new_output_socket(id_name+tag, node_final.outputs['Color'])
return node_final
def __blend_value_add(id_name, pos, tag=''):
# ValueMul = Value1 * (Fac * Value2 + (1 - Fac))
# ValueAdd = Value1 + Fac * Value2
if use_mul:
node_mul = ng.new_math_node('MULTIPLY', (pos[0]+1, pos[1]))
node_blend = ng.new_math_node('ADD', (pos[0]+2, pos[1]))
links.new(node_invert.outputs['Value'], node_blend.inputs[0])
links.new(node_mul.outputs['Value'], node_blend.inputs[1])
else:
node_mul = node_blend = ng.new_math_node('MULTIPLY', (pos[0]+1, pos[1]))
node_final = ng.new_math_node('MULTIPLY' if use_mul else 'ADD', (pos[0]+2+use_mul, pos[1]))
ng.new_input_socket('%s1'%id_name+tag, node_final.inputs[0], use_mul)
ng.new_input_socket('%s2'%id_name+tag, node_mul.inputs[1], use_mul)
ng.new_output_socket(id_name+tag, node_final.outputs['Value'])
links.new(node_input.outputs['Fac'], node_mul.inputs[0])
links.new(node_blend.outputs['Value'], node_final.inputs[1])
return node_final
def __blend_tex_color(id_name, pos, node_tex_rgb, node_tex_a):
# Tex Color = tex_rgb * tex_a + (1 - tex_a)
# : tex_rgb = TexRGB * ColorMul + ColorAdd
# : tex_a = TexA * ValueMul + ValueAdd
node_inv = ng.new_math_node('SUBTRACT', (pos[0], pos[1]-0.5), value1=1.0)
node_mul = ng.new_mix_node('MULTIPLY', (pos[0], pos[1]), fac=1.0)
node_blend = ng.new_mix_node('ADD', (pos[0]+1, pos[1]), fac=1.0)
out_tex_a = __value_to_color_wrap(node_tex_a.outputs[0], (pos[0]-0.5, pos[1]-0.1))
out_tex_a_inv = __value_to_color_wrap(node_inv.outputs[0], (pos[0]+0.5, pos[1]-0.1))
links.new(node_tex_a.outputs['Value'], node_inv.inputs[1])
links.new(node_tex_rgb.outputs['Color'], node_mul.inputs['Color1'])
links.new(out_tex_a, node_mul.inputs['Color2'])
links.new(node_mul.outputs['Color'], node_blend.inputs['Color1'])
links.new(out_tex_a_inv, node_blend.inputs['Color2'])
ng.new_output_socket(id_name+' Tex', node_blend.outputs['Color'])
if id_name == 'Sphere':
ng.new_output_socket(id_name+' Tex Add', node_mul.outputs['Color'])
pos_x = -2
__blend_color_add('Ambient', (pos_x, 1.5))
__blend_color_add('Diffuse', (pos_x, 1))
__blend_color_add('Specular', (pos_x, 0.5))
__blend_value_add('Reflect', (pos_x, 0))
__blend_value_add('Alpha', (pos_x, -0.5))
__blend_color_add('Edge', (pos_x, -1), ' RGB')
__blend_value_add('Edge', (pos_x, -1.5), ' A')
for id_name, dy in zip(('Base', 'Toon', 'Sphere'), (0, 1, 2)):
node_tex_rgb = __blend_color_add(id_name, (pos_x, -2-dy), ' RGB')
node_tex_a = __blend_value_add(id_name, (pos_x, -2.5-dy), ' A')
__blend_tex_color(id_name, (pos_x+4+use_mul, -2-dy), node_tex_rgb, node_tex_a)
nodes.remove(node_dummy_vec)
del node_dummy_vec
ng.hide_nodes()
return ng.shader
<file_sep>/tests/test_pmx_exporter.py
# -*- coding: utf-8 -*-
import os
import shutil
import unittest
import bpy
from math import pi
from mathutils import Euler
from mathutils import Vector
from mmd_tools.core import pmx
from mmd_tools.core.model import Model
from mmd_tools.core.pmd.importer import import_pmd_to_pmx
from mmd_tools.core.pmx.importer import PMXImporter
TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
SAMPLES_DIR = os.path.join(os.path.dirname(TESTS_DIR), 'samples')
class TestPmxExporter(unittest.TestCase):
@classmethod
def setUpClass(cls):
'''
Clean up output from previous tests
'''
output_dir = os.path.join(TESTS_DIR, 'output')
for item in os.listdir(output_dir):
if item.endswith('.OUTPUT'):
continue # Skip the placeholder
item_fp = os.path.join(output_dir, item)
if os.path.isfile(item_fp):
os.remove(item_fp)
elif os.path.isdir(item_fp):
shutil.rmtree(item_fp)
def setUp(self):
'''
'''
import logging
logger = logging.getLogger()
logger.setLevel('ERROR')
#********************************************
# Utils
#********************************************
def __axis_error(self, axis0, axis1):
return (Vector(axis0).normalized() - Vector(axis1).normalized()).length
def __vector_error(self, vec0, vec1):
return (Vector(vec0) - Vector(vec1)).length
def __quaternion_error(self, quat0, quat1):
angle = quat0.rotation_difference(quat1).angle % pi
assert(angle >= 0)
return min(angle, pi-angle)
#********************************************
# Header & Informations
#********************************************
def __check_pmx_header_info(self, source_model, result_model, import_types):
'''
Test pmx model info, header
'''
# Informations ================
self.assertEqual(source_model.name, result_model.name)
self.assertEqual(source_model.name_e, result_model.name_e)
self.assertEqual(source_model.comment.replace('\r', ''), result_model.comment.replace('\r', ''))
self.assertEqual(source_model.comment_e.replace('\r', ''), result_model.comment_e.replace('\r', ''))
# Header ======================
if source_model.header:
source_header = source_model.header
result_header = result_model.header
self.assertEqual(source_header.sign, result_header.sign)
self.assertEqual(source_header.version, result_header.version)
self.assertEqual(source_header.encoding.index, result_header.encoding.index)
self.assertEqual(source_header.encoding.charset, result_header.encoding.charset)
if 'MESH' in import_types:
self.assertEqual(source_header.additional_uvs, result_header.additional_uvs)
self.assertEqual(source_header.vertex_index_size, result_header.vertex_index_size)
self.assertEqual(source_header.texture_index_size, result_header.texture_index_size)
self.assertEqual(source_header.material_index_size, result_header.material_index_size)
if 'ARMATURE' in import_types:
self.assertEqual(source_header.bone_index_size, result_header.bone_index_size)
if 'MORPHS' in import_types:
self.assertEqual(source_header.morph_index_size, result_header.morph_index_size)
if 'PHYSICS' in import_types:
self.assertEqual(source_header.rigid_index_size, result_header.rigid_index_size)
#********************************************
# Mesh
#********************************************
def __get_pmx_textures(self, textures):
ret = []
for t in textures:
path = t.path
path = os.path.basename(path)
ret.append(path)
return ret
def __get_texture(self, tex_id, textures):
if 0 <= tex_id < len(textures):
return textures[tex_id]
return tex_id
def __get_toon_texture(self, tex_id, textures, is_shared):
return tex_id if is_shared else self.__get_texture(tex_id, textures)
def __check_pmx_mesh(self, source_model, result_model):
'''
Test pmx textures, materials, vertices, faces
'''
# textures ====================
# TODO
source_textures = self.__get_pmx_textures(source_model.textures)
result_textures = self.__get_pmx_textures(result_model.textures)
self.assertEqual(len(source_textures), len(result_textures))
for tex0, tex1 in zip(sorted(source_textures), sorted(result_textures)):
self.assertEqual(tex0, tex1)
# materials ===================
source_materials = source_model.materials
result_materials = result_model.materials
self.assertEqual(len(source_materials), len(result_materials))
for mat0, mat1 in zip(source_materials, result_materials):
msg = mat0.name
self.assertEqual(mat0.name, mat1.name, msg)
self.assertEqual(mat0.name_e or mat0.name, mat1.name_e, msg)
self.assertEqual(mat0.diffuse, mat1.diffuse, msg)
self.assertEqual(mat0.specular, mat1.specular, msg)
self.assertEqual(mat0.shininess, mat1.shininess, msg)
self.assertEqual(mat0.ambient, mat1.ambient, msg)
self.assertEqual(mat0.is_double_sided, mat1.is_double_sided, msg)
self.assertEqual(mat0.enabled_drop_shadow, mat1.enabled_drop_shadow, msg)
self.assertEqual(mat0.enabled_self_shadow_map, mat1.enabled_self_shadow_map, msg)
self.assertEqual(mat0.enabled_self_shadow, mat1.enabled_self_shadow, msg)
self.assertEqual(mat0.enabled_toon_edge, mat1.enabled_toon_edge, msg)
self.assertEqual(mat0.edge_color, mat1.edge_color, msg)
self.assertEqual(mat0.edge_size, mat1.edge_size, msg)
self.assertEqual(mat0.comment, mat1.comment, msg)
self.assertEqual(mat0.vertex_count, mat1.vertex_count, msg)
tex0 = self.__get_texture(mat0.texture, source_textures)
tex1 = self.__get_texture(mat1.texture, result_textures)
self.assertEqual(tex0, tex1, msg)
self.assertEqual(mat0.sphere_texture_mode, mat1.sphere_texture_mode, msg)
sph0 = self.__get_texture(mat0.sphere_texture, source_textures)
sph1 = self.__get_texture(mat1.sphere_texture, result_textures)
self.assertEqual(sph0, sph1, msg)
self.assertEqual(mat0.is_shared_toon_texture, mat1.is_shared_toon_texture, msg)
toon0 = self.__get_toon_texture(mat0.toon_texture, source_textures, mat0.is_shared_toon_texture)
toon1 = self.__get_toon_texture(mat1.toon_texture, result_textures, mat1.is_shared_toon_texture)
self.assertEqual(toon0, toon1, msg)
# vertices & faces ============
# TODO
source_vertices = source_model.vertices
result_vertices = result_model.vertices
#self.assertEqual(len(source_vertices), len(result_vertices))
source_faces = source_model.faces
result_faces = result_model.faces
self.assertEqual(len(source_faces), len(result_faces))
for f0, f1 in zip(source_faces, result_faces):
seq0 = [source_vertices[i] for i in f0]
seq1 = [result_vertices[i] for i in f1]
for v0, v1 in zip(seq0, seq1):
self.assertLess(self.__vector_error(v0.co, v1.co), 1e-6)
self.assertLess(self.__vector_error(v0.uv, v1.uv), 1e-6)
#self.assertLess(self.__vector_error(v0.normal, v1.normal), 1e-3)
self.assertEqual(v0.additional_uvs, v1.additional_uvs)
self.assertEqual(v0.edge_scale, v1.edge_scale)
#self.assertEqual(v0.weight.weights, v1.weight.weights)
#self.assertEqual(v0.weight.bones, v1.weight.bones)
#********************************************
# Armature
#********************************************
def __get_bone(self, bone_id, bones):
if bone_id is not None and 0 <= bone_id < len(bones):
return bones[bone_id]
return bone_id
def __get_bone_name(self, bone_id, bones):
if bone_id is not None and 0 <= bone_id < len(bones):
return bones[bone_id].name
return bone_id
def __get_bone_display_connection(self, bone, bones):
displayConnection = bone.displayConnection
if displayConnection == -1 or displayConnection == [0.0, 0.0, 0.0]:
return [0.0, 0.0, 0.0]
if isinstance(displayConnection, int):
tail_bone = self.__get_bone(displayConnection, bones)
if self.__get_bone_name(tail_bone.parent, bones) == bone.name and not tail_bone.isMovable:
return tail_bone.name
return list(Vector(tail_bone.location) - Vector(bone.location))
return displayConnection
def __check_pmx_bones(self, source_model, result_model):
'''
Test pmx bones
'''
source_bones = source_model.bones
result_bones = result_model.bones
self.assertEqual(len(source_bones), len(result_bones))
# check bone order
bone_order0 = [x.name for x in source_bones]
bone_order1 = [x.name for x in result_bones]
self.assertEqual(bone_order0, bone_order1)
for bone0, bone1 in zip(source_bones, result_bones):
msg = bone0.name
self.assertEqual(bone0.name, bone1.name, msg)
self.assertEqual(bone0.name_e or bone0.name, bone1.name_e, msg)
self.assertLess(self.__vector_error(bone0.location, bone1.location), 1e-6, msg)
parent0 = self.__get_bone_name(bone0.parent, source_bones)
parent1 = self.__get_bone_name(bone1.parent, result_bones)
self.assertEqual(parent0, parent1, msg)
self.assertEqual(bone0.transform_order, bone1.transform_order, msg)
self.assertEqual(bone0.isRotatable, bone1.isRotatable, msg)
self.assertEqual(bone0.isMovable, bone1.isMovable, msg)
self.assertEqual(bone0.visible, bone1.visible, msg)
self.assertEqual(bone0.isControllable, bone1.isControllable, msg)
self.assertEqual(bone0.isIK, bone1.isIK, msg)
self.assertEqual(bone0.transAfterPhis, bone1.transAfterPhis, msg)
self.assertEqual(bone0.externalTransKey, bone1.externalTransKey, msg)
if bone0.axis and bone1.axis:
self.assertLess(self.__axis_error(bone0.axis, bone1.axis), 1e-6, msg)
else:
self.assertEqual(bone0.axis, bone1.axis, msg)
if bone0.localCoordinate and bone1.localCoordinate:
self.assertLess(self.__axis_error(bone0.localCoordinate.x_axis, bone1.localCoordinate.x_axis), 1e-6, msg)
self.assertLess(self.__axis_error(bone0.localCoordinate.z_axis, bone1.localCoordinate.z_axis), 1e-6, msg)
else:
self.assertEqual(bone0.localCoordinate, bone1.localCoordinate, msg)
self.assertEqual(bone0.hasAdditionalRotate, bone1.hasAdditionalRotate, msg)
self.assertEqual(bone0.hasAdditionalLocation, bone1.hasAdditionalLocation, msg)
if bone0.additionalTransform and bone1.additionalTransform:
at_target0, at_infl0 = bone0.additionalTransform
at_target1, at_infl1 = bone1.additionalTransform
at_target0 = self.__get_bone_name(at_target0, source_bones)
at_target1 = self.__get_bone_name(at_target1, result_bones)
self.assertEqual(at_target0, at_target1, msg)
self.assertLess(abs(at_infl0 - at_infl1), 1e-4, msg)
else:
self.assertEqual(bone0.additionalTransform, bone1.additionalTransform, msg)
target0 = self.__get_bone_name(bone0.target, source_bones)
target1 = self.__get_bone_name(bone1.target, result_bones)
self.assertEqual(target0, target1, msg)
self.assertEqual(bone0.loopCount, bone1.loopCount, msg)
self.assertEqual(bone0.rotationConstraint, bone1.rotationConstraint, msg)
self.assertEqual(len(bone0.ik_links), len(bone1.ik_links), msg)
for link0, link1 in zip(bone0.ik_links, bone1.ik_links):
target0 = self.__get_bone_name(link0.target, source_bones)
target1 = self.__get_bone_name(link1.target, result_bones)
self.assertEqual(target0, target1, msg)
maximumAngle0 = link0.maximumAngle
maximumAngle1 = link1.maximumAngle
if maximumAngle0 and maximumAngle1:
self.assertLess(self.__vector_error(maximumAngle0, maximumAngle1), 1e-6, msg)
else:
self.assertEqual(maximumAngle0, maximumAngle1, msg)
minimumAngle0 = link0.minimumAngle
minimumAngle1 = link1.minimumAngle
if minimumAngle0 and minimumAngle1:
self.assertLess(self.__vector_error(minimumAngle0, minimumAngle1), 1e-6, msg)
else:
self.assertEqual(minimumAngle0, minimumAngle1, msg)
for bone0, bone1 in zip(source_bones, result_bones):
msg = bone0.name
displayConnection0 = self.__get_bone_display_connection(bone0, source_bones)
displayConnection1 = self.__get_bone_display_connection(bone1, result_bones)
if isinstance(displayConnection0, list) and isinstance(displayConnection1, list):
self.assertLess(self.__vector_error(displayConnection0, displayConnection1), 1e-4, msg)
else:
self.assertEqual(displayConnection0, displayConnection1, msg)
#********************************************
# Physics
#********************************************
def __get_rigid_name(self, rigid_id, rigids):
if rigid_id is not None and 0 <= rigid_id < len(rigids):
return rigids[rigid_id].name
return rigid_id
def __check_pmx_physics(self, source_model, result_model):
'''
Test pmx rigids, joints
'''
# rigids ======================
source_rigids = source_model.rigids
result_rigids = result_model.rigids
self.assertEqual(len(source_rigids), len(result_rigids))
source_bones = source_model.bones
result_bones = result_model.bones
for rigid0, rigid1 in zip(source_rigids, result_rigids):
msg = rigid0.name
self.assertEqual(rigid0.name, rigid1.name, msg)
self.assertEqual(rigid0.name_e, rigid1.name_e, msg)
bone0 = self.__get_bone_name(rigid0.bone, source_bones)
bone1 = self.__get_bone_name(rigid0.bone, source_bones)
self.assertEqual(bone0, bone1, msg)
self.assertEqual(rigid0.collision_group_number, rigid1.collision_group_number, msg)
self.assertEqual(rigid0.collision_group_mask, rigid1.collision_group_mask, msg)
self.assertEqual(rigid0.type, rigid1.type, msg)
if rigid0.type == 0: # SHAPE_SPHERE
self.assertLess(abs(rigid0.size[0]-rigid1.size[0]), 1e-6, msg)
elif rigid0.type == 1: # SHAPE_BOX
self.assertLess(self.__vector_error(rigid0.size, rigid1.size), 1e-6, msg)
elif rigid0.type == 2: # SHAPE_CAPSULE
self.assertLess(self.__vector_error(rigid0.size[0:2], rigid1.size[0:2]), 1e-6, msg)
self.assertLess(self.__vector_error(rigid0.location, rigid1.location), 1e-6, msg)
rigid0_rotation = Euler(rigid0.rotation,'YXZ').to_quaternion()
rigid1_rotation = Euler(rigid1.rotation,'YXZ').to_quaternion()
self.assertLess(self.__quaternion_error(rigid0_rotation, rigid1_rotation), 1e-6, msg)
self.assertEqual(rigid0.mass, rigid1.mass, msg)
self.assertEqual(rigid0.velocity_attenuation, rigid1.velocity_attenuation, msg)
self.assertEqual(rigid0.rotation_attenuation, rigid1.rotation_attenuation, msg)
self.assertEqual(rigid0.bounce, rigid1.bounce, msg)
self.assertEqual(rigid0.friction, rigid1.friction, msg)
self.assertEqual(rigid0.mode, rigid1.mode, msg)
# joints ======================
source_joints = source_model.joints
result_joints = result_model.joints
self.assertEqual(len(source_joints), len(result_joints))
for joint0, joint1 in zip(source_joints, result_joints):
msg = joint0.name
self.assertEqual(joint0.name, joint1.name, msg)
self.assertEqual(joint0.name_e, joint1.name_e, msg)
self.assertEqual(joint0.mode, joint1.mode, msg)
src_rigid0 = self.__get_rigid_name(joint0.src_rigid, source_rigids)
src_rigid1 = self.__get_rigid_name(joint1.src_rigid, result_rigids)
self.assertEqual(src_rigid0, src_rigid1, msg)
dest_rigid0 = self.__get_rigid_name(joint0.dest_rigid, source_rigids)
dest_rigid1 = self.__get_rigid_name(joint1.dest_rigid, result_rigids)
self.assertEqual(dest_rigid0, dest_rigid1, msg)
self.assertEqual(joint0.location, joint1.location, msg)
joint0_rotation = Euler(joint0.rotation,'YXZ').to_quaternion()
joint1_rotation = Euler(joint1.rotation,'YXZ').to_quaternion()
self.assertLess(self.__quaternion_error(joint0_rotation, joint1_rotation), 1e-6, msg)
self.assertEqual(joint0.maximum_location, joint1.maximum_location, msg)
self.assertEqual(joint0.minimum_location, joint1.minimum_location, msg)
self.assertEqual(joint0.maximum_rotation, joint1.maximum_rotation, msg)
self.assertEqual(joint0.minimum_rotation, joint1.minimum_rotation, msg)
self.assertEqual(joint0.spring_constant, joint1.spring_constant, msg)
self.assertEqual(joint0.spring_rotation_constant, joint1.spring_rotation_constant, msg)
#********************************************
# Morphs
#********************************************
def __get_material(self, index, materials):
if 0 <= index < len(materials):
return materials[index]
class _dummy:
name = None
return _dummy
def __check_pmx_morphs(self, source_model, result_model):
'''
Test pmx morphs
'''
source_morphs = source_model.morphs
result_morphs = result_model.morphs
self.assertEqual(len(source_morphs), len(result_morphs))
source_table = {}
for m in source_morphs:
source_table.setdefault(type(m), []).append(m)
result_table = {}
for m in result_morphs:
result_table.setdefault(type(m), []).append(m)
self.assertEqual(source_table.keys(), result_table.keys(), 'types mismatch')
#source_vertices = source_model.vertices
#result_vertices = result_model.vertices
# VertexMorph =================
# TODO
source = source_table.get(pmx.VertexMorph, [])
result = result_table.get(pmx.VertexMorph, [])
self.assertEqual(len(source), len(result))
for m0, m1 in zip(source, result):
msg = 'VertexMorph %s'%m0.name
self.assertEqual(m0.name, m1.name, msg)
self.assertEqual(m0.name_e, m1.name_e, msg)
self.assertEqual(m0.category, m1.category, msg)
#self.assertEqual(len(m0.offsets), len(m1.offsets), msg)
# UVMorph =====================
# TODO
source = source_table.get(pmx.UVMorph, [])
result = result_table.get(pmx.UVMorph, [])
self.assertEqual(len(source), len(result))
for m0, m1 in zip(source, result):
msg = 'UVMorph %s'%m0.name
self.assertEqual(m0.name, m1.name, msg)
self.assertEqual(m0.name_e, m1.name_e, msg)
self.assertEqual(m0.category, m1.category, msg)
self.assertEqual(len(m0.offsets), len(m1.offsets), msg)
#for s0, s1 in zip(m0.offsets, m1.offsets):
# self.assertEqual(s0.index, s1.index, msg)
# self.assertEqual(s0.offset, s1.offset, msg)
# BoneMorph ===================
source_bones = source_model.bones
result_bones = result_model.bones
source = source_table.get(pmx.BoneMorph, [])
result = result_table.get(pmx.BoneMorph, [])
self.assertEqual(len(source), len(result))
for m0, m1 in zip(source, result):
msg = 'BoneMorph %s'%m0.name
self.assertEqual(m0.name, m1.name, msg)
self.assertEqual(m0.name_e, m1.name_e, msg)
self.assertEqual(m0.category, m1.category, msg)
# the source may contains invalid data
source_offsets = [m for m in m0.offsets if 0 <= m.index < len(source_bones)]
result_offsets = m1.offsets
self.assertEqual(len(source_offsets), len(result_offsets), msg)
for s0, s1 in zip(source_offsets, result_offsets):
bone0 = source_bones[s0.index]
bone1 = result_bones[s1.index]
self.assertEqual(bone0.name, bone1.name, msg)
self.assertLess(self.__vector_error(s0.location_offset, s1.location_offset), 1e-5, msg)
self.assertLess(self.__vector_error(s0.rotation_offset, s1.rotation_offset), 1e-5, msg)
# MaterialMorph ===============
source_materials = source_model.materials
result_materials = result_model.materials
source = source_table.get(pmx.MaterialMorph, [])
result = result_table.get(pmx.MaterialMorph, [])
self.assertEqual(len(source), len(result))
for m0, m1 in zip(source, result):
msg = 'MaterialMorph %s'%m0.name
self.assertEqual(m0.name, m1.name, msg)
self.assertEqual(m0.name_e, m1.name_e, msg)
self.assertEqual(m0.category, m1.category, msg)
source_offsets = m0.offsets
result_offsets = m1.offsets
self.assertEqual(len(source_offsets), len(result_offsets), msg)
for s0, s1 in zip(source_offsets, result_offsets):
mat0 = self.__get_material(s0.index, source_materials)
mat1 = self.__get_material(s1.index, result_materials)
self.assertEqual(mat0.name, mat1.name, msg)
self.assertEqual(s0.offset_type, s1.offset_type, msg)
self.assertEqual(s0.diffuse_offset, s1.diffuse_offset, msg)
self.assertEqual(s0.specular_offset, s1.specular_offset, msg)
self.assertEqual(s0.shininess_offset, s1.shininess_offset, msg)
self.assertEqual(s0.ambient_offset, s1.ambient_offset, msg)
self.assertEqual(s0.edge_color_offset, s1.edge_color_offset, msg)
self.assertEqual(s0.edge_size_offset, s1.edge_size_offset, msg)
self.assertEqual(s0.texture_factor, s1.texture_factor, msg)
self.assertEqual(s0.sphere_texture_factor, s1.sphere_texture_factor, msg)
self.assertEqual(s0.toon_texture_factor, s1.toon_texture_factor, msg)
# GroupMorph ==================
source = source_table.get(pmx.GroupMorph, [])
result = result_table.get(pmx.GroupMorph, [])
self.assertEqual(len(source), len(result))
for m0, m1 in zip(source, result):
msg = 'GroupMorph %s'%m0.name
self.assertEqual(m0.name, m1.name, msg)
self.assertEqual(m0.name_e, m1.name_e, msg)
self.assertEqual(m0.category, m1.category, msg)
# the source may contains invalid data
source_offsets = [m for m in m0.offsets if 0 <= m.morph < len(source_morphs)]
result_offsets = m1.offsets
self.assertEqual(len(source_offsets), len(result_offsets), msg)
for s0, s1 in zip(source_offsets, result_offsets):
morph0 = source_morphs[s0.morph]
morph1 = result_morphs[s1.morph]
self.assertEqual(morph0.name, morph1.name, msg)
self.assertEqual(morph0.category, morph1.category, msg)
self.assertEqual(s0.factor, s1.factor, msg)
#********************************************
# Display
#********************************************
def __check_pmx_display_data(self, source_model, result_model, check_morphs):
'''
Test pmx display
'''
source_display = source_model.display
result_display = result_model.display
self.assertEqual(len(source_display), len(result_display))
for source, result in zip(source_display, result_display):
self.assertEqual(source.name, result.name)
self.assertEqual(source.name_e, result.name_e)
self.assertEqual(source.isSpecial, result.isSpecial)
source_items = source.data
if not check_morphs:
source_items = [i for i in source_items if i[0] == 0]
result_items = result.data
self.assertEqual(len(source_items), len(result_items))
for item0, item1 in zip(source_items, result_items):
disp_type0, index0 = item0
disp_type1, index1 = item1
self.assertEqual(disp_type0, disp_type1)
if disp_type0 == 0:
bone_name0 = source_model.bones[index0].name
bone_name1 = result_model.bones[index1].name
self.assertEqual(bone_name0, bone_name1)
elif disp_type0 == 1:
morph0 = source_model.morphs[index0]
morph1 = result_model.morphs[index1]
self.assertEqual(morph0.name, morph1.name)
self.assertEqual(morph0.category, morph1.category)
#********************************************
# Test Function
#********************************************
def __get_import_types(self, types):
types = types.copy()
if 'PHYSICS' in types:
types.add('ARMATURE')
if 'DISPLAY' in types:
types.add('ARMATURE')
if 'MORPHS' in types:
types.add('ARMATURE')
types.add('MESH')
return types
def __list_sample_files(self, file_types):
ret = []
for file_type in file_types:
file_ext ='.' + file_type
for root, dirs, files in os.walk(os.path.join(SAMPLES_DIR, file_type)):
for name in files:
if name.lower().endswith(file_ext):
ret.append(os.path.join(root, name))
return ret
def __enable_mmd_tools(self):
bpy.ops.wm.read_homefile() # reload blender startup file
pref = getattr(bpy.context, 'preferences', None) or bpy.context.user_preferences
if not pref.addons.get('mmd_tools', None):
addon_enable = bpy.ops.wm.addon_enable if 'addon_enable' in dir(bpy.ops.wm) else bpy.ops.preferences.addon_enable
addon_enable(module='mmd_tools') # make sure addon 'mmd_tools' is enabled
def test_pmx_exporter(self):
'''
'''
input_files = self.__list_sample_files(('pmd', 'pmx'))
if len(input_files) < 1:
self.fail('required pmd/pmx sample file(s)!')
check_types = set()
check_types.add('MESH')
check_types.add('ARMATURE')
check_types.add('PHYSICS')
check_types.add('MORPHS')
check_types.add('DISPLAY')
import_types = self.__get_import_types(check_types)
print('\n Check: %s | Import: %s'%(str(check_types), str(import_types)))
for test_num, filepath in enumerate(input_files):
print('\n - %2d/%d | filepath: %s'%(test_num+1, len(input_files), filepath))
try:
self.__enable_mmd_tools()
file_loader = pmx.load
if filepath.lower().endswith('.pmd'):
file_loader = import_pmd_to_pmx
source_model = file_loader(filepath)
PMXImporter().execute(
pmx=source_model,
types=import_types,
scale=1,
clean_model=False,
)
#bpy.context.scene.update()
bpy.context.scene.frame_set(bpy.context.scene.frame_current)
except Exception:
self.fail('Exception happened during import %s'%filepath)
else:
try:
output_pmx = os.path.join(TESTS_DIR, 'output', '%d.pmx'%test_num)
bpy.ops.mmd_tools.export_pmx(
filepath=output_pmx,
scale=1,
copy_textures=False,
sort_materials=False,
log_level='ERROR',
)
except Exception:
self.fail('Exception happened during export %s'%output_pmx)
else:
self.assertTrue(os.path.isfile(output_pmx), 'File was not created') # Is this a race condition?
try:
result_model = pmx.load(output_pmx)
except:
self.fail('Failed to load output file %s'%output_pmx)
self.__check_pmx_header_info(source_model, result_model, import_types)
if 'MESH' in check_types:
self.__check_pmx_mesh(source_model, result_model)
if 'ARMATURE' in check_types:
self.__check_pmx_bones(source_model, result_model)
if 'PHYSICS' in check_types:
self.__check_pmx_physics(source_model, result_model)
if 'MORPHS' in check_types:
self.__check_pmx_morphs(source_model, result_model)
if 'DISPLAY' in check_types:
self.__check_pmx_display_data(source_model, result_model, 'MORPHS' in check_types)
if __name__ == '__main__':
import sys
sys.argv = [__file__] + (sys.argv[sys.argv.index('--') + 1:] if '--' in sys.argv else [])
unittest.main()
<file_sep>/README.md
mmd_tools
===========
Overview
----
mmd_tools is a blender addon for importing MMD (MikuMikuDance) model data (.pmd, .pmx), motion data (.vmd) and pose data (.vpd). Exporting model data (.pmx), motion data (.vmd) and pose data (.vpd) are supported as well.
mmd_toolsはMMD(MikuMikuDance)のモデルデータ(.pmd, .pmx)、モーションデータ(.vmd)、ポーズデータ(.vpd)をインポートするためのBlenderアドオンです。モデルデータ(.pmx)、モーションデータ(.vmd)、ポーズデータ(.vpd)のエクスポートにも対応しています。
The detailed documentation can be found at Wiki Documentation Page.
- [Documentation](../../wiki/Documentation)
- [日本語ドキュメント](../../wiki/Documentation.ja)
### Environment
#### Compatible Versions
- Blender 2.70 or later (Blender 2.75+ is recommended)
Usage
---------
### Download
* Download mmd_tools from [the github repository](https://github.com/powroupi/blender_mmd_tools/tree/dev_test) (dev_test branch)
* https://github.com/powroupi/blender_mmd_tools/archive/dev_test.zip
### Install
Extract the archive and put the folder mmd_tools into the addon folder of blender.
.../blender-2.70-windows64/2.70/scripts/addons/
### Loading Addon
1. User Preferences -> addon tab -> select the User filter with Community in 'Supported Level' check, then click the checkbox before mmd_tools (you can also find the addon using the search function)
2. After the installation, you can find two panels called mmd_tools and mmd_utils on the left of the 3D view
### Configuring Addon
The following settings can be configured under mmd_tools Addon Preferences.
* Shared Toon Texture Folder
* The `Data` directory within of your MikuMikuDance directory for toon textures (_toon01.bmp ~ toon10.bmp_).
* Base Texture Folder
* Path for textures shared between models. In order to copy textures properly while exporting to pmx file.
* Dictionary Folder
* Path for searching custom csv dictionaries. You can create your own dictionary or download from [Hogarth-MMD/mmd_tools_translation](https://github.com/Hogarth-MMD/mmd_tools_translation).
### Importing a model
1. Go to the mmd_tools panel
2. Press _Import Model_ and select a .pmx or .pmd file
### Importing motion data
1. Load the MMD model. Then, select the imported model's Mesh, Armature and Camera.
2. Click the _Import Motion_ button of the mmd_tools panel.
3. If a rigid body simulation is needed, press the _Build_ button in the same panel.
Turn on the "update scene settings" checkbox to automatically update scene settings such as frame range after the motion import.
Various functions in detail
-------------------------------
### Import Model
Imports a MMD model. Corresponding file formats are .pmd and .pmx (version 2.0).
* Scale
* Size of the model
* Rename bones
* Renames the bones to be more blender suitable
* Use MIP map for UV textures
* Specify if mipmaps will be generated
* Please turn it off when the textures seem messed up
* Influence of .sph textures and influence of .spa textures
* Used to set the diffuse_color_factor of texture slot for sphere textures.
### Import Motion
Apply motion imported from vmd file to the Armature, Mesh and Camera currently selected.
* Scale
* Recommended to make it the same as the imported model's scale
* Margin
* It is used to add/offset some frames before the motion start, so the rigid bodies can have more smooth transition at the beginning
* Update scene settings
* Performs automatic setting of the camera range and frame rate after the motion data read.
Notes
------
* If camera and character motions are not in one file, import two times. First, select Armature and Mesh and import the character motion. Second, select Camera and import the camera motion.
* When mmd_tool imports motion data, mmd_tool uses the bone name to apply motion to each bone.
* If the bone name and the bones structure matches with MMD model, you can import the motion to any model.
* When you import MMD model by using other than mmd_tools, match bone names to those in MMD model.
* mmd_tools creates an empty model named "MMD_Camera" and assigns the motion to the object.
* If you want to import multiple motions or want to import motion with offset, edit the motion with NLA editor.
* If the origin point of the motion is significantly different from the origin point of the model, rigid body simulation might break. If this happens, increase "margin" parameter in vmd import.
* mmd_tool adds blank frames to avoid the glitch from physics simulation. The number of the blank frames is "margin" parameter in vmd import.
* The imported motion starts from the frame number "margin" + 1. (e.g. If margin is 5, frame 6 is frame 0 in vmd motion)
* pmx import
* If the weight information is SDEF, mmd_tool processes as if it is in BDEF2.
* mmd_tool only supports vertex morph.
* mmd_tool treats "Physics + Bone location match" in rigid body setting as "Physics simulation".
* Use the same scale in case you import multiple pmx files.
More Informations
----------
* See https://github.com/powroupi/blender_mmd_tools/wiki
Known issues
----------
* See https://github.com/powroupi/blender_mmd_tools/issues
License
----------
© 2012-2014 sugiany, 2015-2017 powroupi.
Distributed under the MIT License.
<file_sep>/mmd_tools/core/rigid_body.py
# -*- coding: utf-8 -*-
import bpy
SHAPE_SPHERE = 0
SHAPE_BOX = 1
SHAPE_CAPSULE = 2
MODE_STATIC = 0
MODE_DYNAMIC = 1
MODE_DYNAMIC_BONE = 2
def shapeType(collision_shape):
return ('SPHERE', 'BOX', 'CAPSULE').index(collision_shape)
def collisionShape(shape_type):
return ('SPHERE', 'BOX', 'CAPSULE')[shape_type]
def setRigidBodyWorldEnabled(enable):
rigidbody_world = bpy.context.scene.rigidbody_world
if rigidbody_world is None:
if enable:
bpy.ops.rigidbody.world_add()
return False
enabled = rigidbody_world.enabled
rigidbody_world.enabled = enable
return enabled
class RigidBodyMaterial:
COLORS = [
0x7fddd4,
0xf0e68c,
0xee82ee,
0xffe4e1,
0x8feeee,
0xadff2f,
0xfa8072,
0x9370db,
0x40e0d0,
0x96514d,
0x5a964e,
0xe6bfab,
0xd3381c,
0x165e83,
0x701682,
0x828216,
]
@classmethod
def getMaterial(cls, number):
number = int(number)
material_name = 'mmd_tools_rigid_%d'%(number)
if material_name not in bpy.data.materials:
mat = bpy.data.materials.new(material_name)
color = cls.COLORS[number]
mat.diffuse_color[:3] = [((0xff0000 & color) >> 16) / float(255), ((0x00ff00 & color) >> 8) / float(255), (0x0000ff & color) / float(255)]
mat.specular_intensity = 0
if bpy.app.version < (2, 80, 0):
mat.diffuse_intensity = 1
mat.alpha = 0.5
mat.use_transparency = True
mat.use_shadeless = True
else:
if len(mat.diffuse_color) > 3:
mat.diffuse_color[3] = 0.5
mat.blend_method = 'BLEND'
mat.shadow_method = 'NONE'
mat.use_backface_culling = True
mat.show_transparent_back = False
mat.use_nodes = True
nodes, links = mat.node_tree.nodes, mat.node_tree.links
nodes.clear()
node_color = nodes.new('ShaderNodeBackground')
node_color.inputs['Color'].default_value = mat.diffuse_color
node_output = nodes.new('ShaderNodeOutputMaterial')
links.new(node_color.outputs[0], node_output.inputs['Surface'])
else:
mat = bpy.data.materials[material_name]
return mat
<file_sep>/mmd_tools/panels/util_tools.py
# -*- coding: utf-8 -*-
from bpy.types import Panel, UIList
from mmd_tools import register_wrap
from mmd_tools.bpyutils import SceneOp
from mmd_tools.core.model import Model
from mmd_tools.panels.tool import TRIA_UP_BAR, TRIA_DOWN_BAR
from mmd_tools.panels.tool import _PanelBase
@register_wrap
class MMD_TOOLS_UL_Materials(UIList):
def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index):
if self.layout_type in {'DEFAULT'}:
if item:
row = layout.row(align=True)
item_prop = getattr(item, 'mmd_material')
row.prop(item_prop, 'name_j', text='', emboss=False, icon='MATERIAL')
row.prop(item_prop, 'name_e', text='', emboss=True)
else:
layout.label(text='UNSET', translate=False, icon='ERROR')
elif self.layout_type in {'COMPACT'}:
pass
elif self.layout_type in {'GRID'}:
layout.alignment = 'CENTER'
layout.label(text="", icon_value=icon)
def draw_filter(self, context, layout):
layout.label(text="Use the arrows to sort", icon='INFO')
@register_wrap
class MMDMaterialSorter(_PanelBase, Panel):
bl_idname = 'OBJECT_PT_mmd_tools_material_sorter'
bl_label = 'Material Sorter'
bl_context = ''
bl_options = {'DEFAULT_CLOSED'}
def draw(self, context):
layout = self.layout
active_obj = context.active_object
if (active_obj is None or active_obj.type != 'MESH' or
active_obj.mmd_type != 'NONE'):
layout.label(text='Select a mesh object')
return
col = layout.column(align=True)
row = col.row()
row.template_list("MMD_TOOLS_UL_Materials", "",
active_obj.data, "materials",
active_obj, "active_material_index")
tb = row.column()
tb1 = tb.column(align=True)
tb1.operator('mmd_tools.move_material_up', text='', icon='TRIA_UP')
tb1.operator('mmd_tools.move_material_down', text='', icon='TRIA_DOWN')
@register_wrap
class MMD_TOOLS_UL_ModelMeshes(UIList):
def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index):
if self.layout_type in {'DEFAULT'}:
layout.label(text=item.name, translate=False, icon='OBJECT_DATA')
elif self.layout_type in {'COMPACT'}:
pass
elif self.layout_type in {'GRID'}:
layout.alignment = 'CENTER'
layout.label(text="", icon_value=icon)
def draw_filter(self, context, layout):
layout.label(text="Use the arrows to sort", icon='INFO')
def filter_items(self, context, data, propname):
# We will use the filtering to sort the mesh objects to match the rig order
objects = getattr(data, propname)
flt_flags = [~self.bitflag_filter_item] * len(objects)
flt_neworder = list(range(len(objects)))
active_root = Model.findRoot(context.active_object)
#rig = Model(active_root)
#for i, obj in enumerate(objects):
# if (obj.type == 'MESH' and obj.mmd_type == 'NONE'
# and Model.findRoot(obj) == active_root):
# flt_flags[i] = self.bitflag_filter_item
# new_index = rig.getMeshIndex(obj.name)
# flt_neworder[i] = new_index
name_dict = {}
for i, obj in enumerate(objects):
if (obj.type == 'MESH' and obj.mmd_type == 'NONE'
and Model.findRoot(obj) == active_root):
flt_flags[i] = self.bitflag_filter_item
name_dict[obj.name] = i
for new_index, name in enumerate(sorted(name_dict.keys())):
i = name_dict[name]
flt_neworder[i] = new_index
return flt_flags, flt_neworder
@register_wrap
class MMDMeshSorter(_PanelBase, Panel):
bl_idname = 'OBJECT_PT_mmd_tools_meshes_sorter'
bl_label = 'Meshes Sorter'
bl_context = ''
bl_options = {'DEFAULT_CLOSED'}
def draw(self, context):
layout = self.layout
active_obj = context.active_object
root = Model.findRoot(active_obj)
if root is None:
layout.label(text='Select a MMD Model')
return
col = layout.column(align=True)
row = col.row()
row.template_list("MMD_TOOLS_UL_ModelMeshes", "",
SceneOp(context).id_scene, 'objects',
root.mmd_root, "active_mesh_index")
tb = row.column()
tb1 = tb.column(align=True)
tb1.enabled = active_obj.type == 'MESH' and active_obj.mmd_type == 'NONE'
tb1.operator('mmd_tools.object_move', text='', icon=TRIA_UP_BAR).type = 'TOP'
tb1.operator('mmd_tools.object_move', text='', icon='TRIA_UP').type = 'UP'
tb1.operator('mmd_tools.object_move', text='', icon='TRIA_DOWN').type = 'DOWN'
tb1.operator('mmd_tools.object_move', text='', icon=TRIA_DOWN_BAR).type = 'BOTTOM'
<file_sep>/mmd_tools/core/vmd/__init__.py
# -*- coding: utf-8 -*-
import struct
import collections
class InvalidFileError(Exception):
pass
## vmd仕様の文字列をstringに変換
def _toShiftJisString(byteString):
return byteString.split(b'\x00')[0].decode('shift_jis', errors='replace')
def _toShiftJisBytes(string):
return string.encode('shift_jis', errors='replace')
class Header:
VMD_SIGN = b'Vocaloid Motion Data 0002'
def __init__(self):
self.signature = None
self.model_name = ''
def load(self, fin):
self.signature, = struct.unpack('<30s', fin.read(30))
if self.signature[:len(self.VMD_SIGN)] != self.VMD_SIGN:
raise InvalidFileError('File signature "%s" is invalid.'%self.signature)
self.model_name = _toShiftJisString(struct.unpack('<20s', fin.read(20))[0])
print(self)
def save(self, fin):
fin.write(struct.pack('<30s', self.VMD_SIGN))
fin.write(struct.pack('<20s', _toShiftJisBytes(self.model_name)))
def __repr__(self):
return '<Header model_name %s>'%(self.model_name)
class BoneFrameKey:
def __init__(self):
self.frame_number = 0
self.location = []
self.rotation = []
self.interp = []
def load(self, fin):
self.frame_number, = struct.unpack('<L', fin.read(4))
self.location = list(struct.unpack('<fff', fin.read(4*3)))
self.rotation = list(struct.unpack('<ffff', fin.read(4*4)))
self.interp = list(struct.unpack('<64b', fin.read(64)))
def save(self, fin):
fin.write(struct.pack('<L', self.frame_number))
fin.write(struct.pack('<fff', *self.location))
fin.write(struct.pack('<ffff', *self.rotation))
fin.write(struct.pack('<64b', *self.interp))
def __repr__(self):
return '<BoneFrameKey frame %s, loa %s, rot %s>'%(
str(self.frame_number),
str(self.location),
str(self.rotation),
)
class ShapeKeyFrameKey:
def __init__(self):
self.frame_number = 0
self.weight = 0.0
def load(self, fin):
self.frame_number, = struct.unpack('<L', fin.read(4))
self.weight, = struct.unpack('<f', fin.read(4))
def save(self, fin):
fin.write(struct.pack('<L', self.frame_number))
fin.write(struct.pack('<f', self.weight))
def __repr__(self):
return '<ShapeKeyFrameKey frame %s, weight %s>'%(
str(self.frame_number),
str(self.weight),
)
class CameraKeyFrameKey:
def __init__(self):
self.frame_number = 0
self.distance = 0.0
self.location = []
self.rotation = []
self.interp = []
self.angle = 0.0
self.persp = True
def load(self, fin):
self.frame_number, = struct.unpack('<L', fin.read(4))
self.distance, = struct.unpack('<f', fin.read(4))
self.location = list(struct.unpack('<fff', fin.read(4*3)))
self.rotation = list(struct.unpack('<fff', fin.read(4*3)))
self.interp = list(struct.unpack('<24b', fin.read(24)))
self.angle, = struct.unpack('<L', fin.read(4))
self.persp, = struct.unpack('<b', fin.read(1))
self.persp = (self.persp == 0)
def save(self, fin):
fin.write(struct.pack('<L', self.frame_number))
fin.write(struct.pack('<f', self.distance))
fin.write(struct.pack('<fff', *self.location))
fin.write(struct.pack('<fff', *self.rotation))
fin.write(struct.pack('<24b', *self.interp))
fin.write(struct.pack('<L', self.angle))
fin.write(struct.pack('<b', 0 if self.persp else 1))
def __repr__(self):
return '<CameraKeyFrameKey frame %s, distance %s, loc %s, rot %s, angle %s, persp %s>'%(
str(self.frame_number),
str(self.distance),
str(self.location),
str(self.rotation),
str(self.angle),
str(self.persp),
)
class LampKeyFrameKey:
def __init__(self):
self.frame_number = 0
self.color = []
self.direction = []
def load(self, fin):
self.frame_number, = struct.unpack('<L', fin.read(4))
self.color = list(struct.unpack('<fff', fin.read(4*3)))
self.direction = list(struct.unpack('<fff', fin.read(4*3)))
def save(self, fin):
fin.write(struct.pack('<L', self.frame_number))
fin.write(struct.pack('<fff', *self.color))
fin.write(struct.pack('<fff', *self.direction))
def __repr__(self):
return '<LampKeyFrameKey frame %s, color %s, direction %s>'%(
str(self.frame_number),
str(self.color),
str(self.direction),
)
class SelfShadowFrameKey:
def __init__(self):
self.frame_number = 0
self.mode = 0 # 0: none, 1: mode1, 2: mode2
self.distance = 0.0
def load(self, fin):
self.frame_number, = struct.unpack('<L', fin.read(4))
self.mode, = struct.unpack('<b', fin.read(1))
if self.mode not in range(3):
print(' * Invalid self shadow mode %d at frame %d'%(self.mode, self.frame_number))
raise struct.error
distance, = struct.unpack('<f', fin.read(4))
self.distance = 10000 - distance*100000
print(' ', self)
def save(self, fin):
fin.write(struct.pack('<L', self.frame_number))
fin.write(struct.pack('<b', self.mode))
distance = (10000 - self.distance)/100000
fin.write(struct.pack('<f', distance))
def __repr__(self):
return '<SelfShadowFrameKey frame %s, mode %s, distance %s>'%(
str(self.frame_number),
str(self.mode),
str(self.distance),
)
class PropertyFrameKey:
def __init__(self):
self.frame_number = 0
self.visible = True
self.ik_states = [] # list of (ik_name, enable/disable)
def load(self, fin):
self.frame_number, = struct.unpack('<L', fin.read(4))
self.visible, = struct.unpack('<b', fin.read(1))
count, = struct.unpack('<L', fin.read(4))
for i in range(count):
ik_name = _toShiftJisString(struct.unpack('<20s', fin.read(20))[0])
state, = struct.unpack('<b', fin.read(1))
self.ik_states.append((ik_name, state))
print(' ', self)
def save(self, fin):
fin.write(struct.pack('<L', self.frame_number))
fin.write(struct.pack('<b', 1 if self.visible else 0))
fin.write(struct.pack('<L', len(self.ik_states)))
for ik_name, state in self.ik_states:
fin.write(struct.pack('<20s', _toShiftJisBytes(ik_name)))
fin.write(struct.pack('<b', 1 if state else 0))
def __repr__(self):
return '<PropertyFrameKey frame %s, visible %s, ik_states %s>'%(
str(self.frame_number),
str(self.visible),
str(self.ik_states),
)
class _AnimationBase(collections.defaultdict):
def __init__(self):
collections.defaultdict.__init__(self, list)
@staticmethod
def frameClass():
raise NotImplementedError
def load(self, fin):
count, = struct.unpack('<L', fin.read(4))
print('loading %s... %d'%(self.__class__.__name__, count))
for i in range(count):
name = _toShiftJisString(struct.unpack('<15s', fin.read(15))[0])
cls = self.frameClass()
frameKey = cls()
frameKey.load(fin)
self[name].append(frameKey)
def save(self, fin):
count = sum([len(i) for i in self.values()])
fin.write(struct.pack('<L', count))
for name, frameKeys in self.items():
name_data = struct.pack('<15s', _toShiftJisBytes(name))
for frameKey in frameKeys:
fin.write(name_data)
frameKey.save(fin)
class _AnimationListBase(list):
def __init__(self):
list.__init__(self)
@staticmethod
def frameClass():
raise NotImplementedError
def load(self, fin):
count, = struct.unpack('<L', fin.read(4))
print('loading %s... %d'%(self.__class__.__name__, count))
for i in range(count):
cls = self.frameClass()
frameKey = cls()
frameKey.load(fin)
self.append(frameKey)
def save(self, fin):
fin.write(struct.pack('<L', len(self)))
for frameKey in self:
frameKey.save(fin)
class BoneAnimation(_AnimationBase):
def __init__(self):
_AnimationBase.__init__(self)
@staticmethod
def frameClass():
return BoneFrameKey
class ShapeKeyAnimation(_AnimationBase):
def __init__(self):
_AnimationBase.__init__(self)
@staticmethod
def frameClass():
return ShapeKeyFrameKey
class CameraAnimation(_AnimationListBase):
def __init__(self):
_AnimationListBase.__init__(self)
@staticmethod
def frameClass():
return CameraKeyFrameKey
class LampAnimation(_AnimationListBase):
def __init__(self):
_AnimationListBase.__init__(self)
@staticmethod
def frameClass():
return LampKeyFrameKey
class SelfShadowAnimation(_AnimationListBase):
def __init__(self):
_AnimationListBase.__init__(self)
@staticmethod
def frameClass():
return SelfShadowFrameKey
class PropertyAnimation(_AnimationListBase):
def __init__(self):
_AnimationListBase.__init__(self)
@staticmethod
def frameClass():
return PropertyFrameKey
class File:
def __init__(self):
self.filepath = None
self.header = None
self.boneAnimation = None
self.shapeKeyAnimation = None
self.cameraAnimation = None
self.lampAnimation = None
self.selfShadowAnimation = None
self.propertyAnimation = None
def load(self, **args):
path = args['filepath']
with open(path, 'rb') as fin:
self.filepath = path
self.header = Header()
self.boneAnimation = BoneAnimation()
self.shapeKeyAnimation = ShapeKeyAnimation()
self.cameraAnimation = CameraAnimation()
self.lampAnimation = LampAnimation()
self.selfShadowAnimation = SelfShadowAnimation()
self.propertyAnimation = PropertyAnimation()
self.header.load(fin)
try:
self.boneAnimation.load(fin)
self.shapeKeyAnimation.load(fin)
self.cameraAnimation.load(fin)
self.lampAnimation.load(fin)
self.selfShadowAnimation.load(fin)
self.propertyAnimation.load(fin)
except struct.error:
pass # no valid camera/lamp data
def save(self, **args):
path = args.get('filepath', self.filepath)
header = self.header or Header()
boneAnimation = self.boneAnimation or BoneAnimation()
shapeKeyAnimation = self.shapeKeyAnimation or ShapeKeyAnimation()
cameraAnimation = self.cameraAnimation or CameraAnimation()
lampAnimation = self.lampAnimation or LampAnimation()
selfShadowAnimation = self.selfShadowAnimation or SelfShadowAnimation()
propertyAnimation = self.propertyAnimation or PropertyAnimation()
with open(path, 'wb') as fin:
header.save(fin)
boneAnimation.save(fin)
shapeKeyAnimation.save(fin)
cameraAnimation.save(fin)
lampAnimation.save(fin)
selfShadowAnimation.save(fin)
propertyAnimation.save(fin)
<file_sep>/mmd_tools/cycles_converter.py
# -*- coding: utf-8 -*-
import bpy
import mathutils
def __switchToCyclesRenderEngine():
if bpy.context.scene.render.engine != 'CYCLES':
bpy.context.scene.render.engine = 'CYCLES'
def __exposeNodeTreeInput(in_socket, name, default_value, node_input, shader):
t = len(node_input.outputs)-1
i = node_input.outputs[t]
shader.links.new(in_socket, i)
if default_value is not None:
shader.inputs[t].default_value = default_value
shader.inputs[t].name = name
def __exposeNodeTreeOutput(out_socket, name, node_output, shader):
t = len(node_output.inputs)-1
i = node_output.inputs[t]
shader.links.new(i, out_socket)
shader.outputs[t].name = name
def __getMaterialOutput(nodes):
for node in nodes:
if isinstance(node, bpy.types.ShaderNodeOutputMaterial):
return node
o = nodes.new('ShaderNodeOutputMaterial')
o.name = 'Material Output'
return o
def create_MMDAlphaShader():
__switchToCyclesRenderEngine()
if 'MMDAlphaShader' in bpy.data.node_groups:
return bpy.data.node_groups['MMDAlphaShader']
shader = bpy.data.node_groups.new(name='MMDAlphaShader', type='ShaderNodeTree')
node_input = shader.nodes.new('NodeGroupInput')
node_output = shader.nodes.new('NodeGroupOutput')
node_output.location.x += 250
node_input.location.x -= 500
trans = shader.nodes.new('ShaderNodeBsdfTransparent')
trans.location.x -= 250
trans.location.y += 150
mix = shader.nodes.new('ShaderNodeMixShader')
shader.links.new(mix.inputs[1], trans.outputs['BSDF'])
__exposeNodeTreeInput(mix.inputs[2], 'Shader', None, node_input, shader)
__exposeNodeTreeInput(mix.inputs['Fac'], 'Alpha', 1.0, node_input, shader)
__exposeNodeTreeOutput(mix.outputs['Shader'], 'Shader', node_output, shader)
return shader
def create_MMDBasicShader():
__switchToCyclesRenderEngine()
if 'MMDBasicShader' in bpy.data.node_groups:
return bpy.data.node_groups['MMDBasicShader']
shader = bpy.data.node_groups.new(name='MMDBasicShader', type='ShaderNodeTree')
node_input = shader.nodes.new('NodeGroupInput')
node_output = shader.nodes.new('NodeGroupOutput')
node_output.location.x += 250
node_input.location.x -= 500
dif = shader.nodes.new('ShaderNodeBsdfDiffuse')
dif.location.x -= 250
dif.location.y += 150
glo = shader.nodes.new('ShaderNodeBsdfGlossy')
glo.location.x -= 250
glo.location.y -= 150
mix = shader.nodes.new('ShaderNodeMixShader')
shader.links.new(mix.inputs[1], dif.outputs['BSDF'])
shader.links.new(mix.inputs[2], glo.outputs['BSDF'])
__exposeNodeTreeInput(dif.inputs['Color'], 'diffuse', [1.0, 1.0, 1.0, 1.0], node_input, shader)
__exposeNodeTreeInput(glo.inputs['Color'], 'glossy', [1.0, 1.0, 1.0, 1.0], node_input, shader)
__exposeNodeTreeInput(glo.inputs['Roughness'], 'glossy_rough', 0.0, node_input, shader)
__exposeNodeTreeInput(mix.inputs['Fac'], 'reflection', 0.02, node_input, shader)
__exposeNodeTreeOutput(mix.outputs['Shader'], 'shader', node_output, shader)
return shader
def convertToCyclesShader(obj):
mmd_basic_shader_grp = create_MMDBasicShader()
mmd_alpha_shader_grp = create_MMDAlphaShader()
__switchToCyclesRenderEngine()
for i in obj.material_slots:
if i.material is None or i.material.use_nodes:
continue
i.material.use_nodes = True
for j in i.material.node_tree.nodes:
print(j)
if any(filter(lambda x: isinstance(x, bpy.types.ShaderNodeGroup) and x.node_tree.name in ['MMDBasicShader', 'MMDAlphaShader'], i.material.node_tree.nodes)):
continue
i.material.node_tree.links.clear()
# Delete the redundant node
for node in i.material.node_tree.nodes:
if node.bl_idname in {'ShaderNodeBsdfDiffuse', 'ShaderNodeBsdfPrincipled'}:
i.material.node_tree.nodes.remove(node)
break
# Add nodes for Cycles Render
shader = i.material.node_tree.nodes.new('ShaderNodeGroup')
shader.node_tree = mmd_basic_shader_grp
shader.inputs[0].default_value[:3] = i.material.diffuse_color[:3]
shader.inputs[1].default_value[:3] = i.material.specular_color[:3]
shader.inputs['glossy_rough'].default_value = 1.0/getattr(i.material, 'specular_hardness', 50)
outplug = shader.outputs[0]
node_tex, node_alpha = None, None
location = shader.location.copy()
location.x -= 1000
reuse_nodes = {}
for j in getattr(i.material, 'texture_slots', ()):
if j and j.use and isinstance(j.texture, bpy.types.ImageTexture) and getattr(j.texture.image, 'depth', 0):
if not (j.use_map_color_diffuse or j.use_map_alpha):
continue
if j.texture_coords not in {'UV', 'NORMAL'}:
continue
uv_tag = j.uv_layer if j.texture_coords == 'UV' else ''
key_node_tex = j.texture.name + j.texture_coords + uv_tag
tex_img = reuse_nodes.get(key_node_tex)
if tex_img is None:
tex_img = i.material.node_tree.nodes.new('ShaderNodeTexImage')
tex_img.location = location
tex_img.image = j.texture.image
if j.texture_coords == 'NORMAL' and j.blend_type == 'ADD':
tex_img.color_space = 'NONE'
reuse_nodes[key_node_tex] = tex_img
location.x += 250
location.y -= 150
key_node_vec = j.texture_coords + uv_tag
plug_vector = reuse_nodes.get(key_node_vec)
if plug_vector is None:
plug_vector = 0
if j.texture_coords == 'UV':
if j.uv_layer and hasattr(bpy.types, 'ShaderNodeUVMap'):
node_vector = i.material.node_tree.nodes.new('ShaderNodeUVMap')
node_vector.uv_map = j.uv_layer
node_vector.location.x = shader.location.x - 1500
node_vector.location.y = tex_img.location.y - 50
plug_vector = node_vector.outputs[0]
elif j.uv_layer:
node_vector = i.material.node_tree.nodes.new('ShaderNodeAttribute')
node_vector.attribute_name = j.uv_layer
node_vector.location.x = shader.location.x - 1500
node_vector.location.y = tex_img.location.y - 50
plug_vector = node_vector.outputs[1]
elif j.texture_coords == 'NORMAL':
tex_coord = i.material.node_tree.nodes.new('ShaderNodeTexCoord')
tex_coord.location.x = shader.location.x - 1900
tex_coord.location.y = shader.location.y - 600
vec_trans = i.material.node_tree.nodes.new('ShaderNodeVectorTransform')
vec_trans.vector_type = 'NORMAL'
vec_trans.convert_from = 'OBJECT'
vec_trans.convert_to = 'CAMERA'
vec_trans.location.x = tex_coord.location.x + 200
vec_trans.location.y = tex_coord.location.y
i.material.node_tree.links.new(vec_trans.inputs[0], tex_coord.outputs['Normal'])
node_vector = i.material.node_tree.nodes.new('ShaderNodeMapping')
node_vector.vector_type = 'POINT'
node_vector.translation = (0.5, 0.5, 0.0)
node_vector.scale = (0.5, 0.5, 1.0)
node_vector.location.x = vec_trans.location.x + 200
node_vector.location.y = vec_trans.location.y
i.material.node_tree.links.new(node_vector.inputs[0], vec_trans.outputs[0])
plug_vector = node_vector.outputs[0]
reuse_nodes[key_node_vec] = plug_vector
if plug_vector:
i.material.node_tree.links.new(tex_img.inputs[0], plug_vector)
if j.use_map_color_diffuse:
if node_tex is None and tuple(i.material.diffuse_color) == (1.0, 1.0, 1.0):
node_tex = tex_img
else:
node_tex_last = node_tex
node_tex = i.material.node_tree.nodes.new('ShaderNodeMixRGB')
try:
node_tex.blend_type = j.blend_type
except TypeError as e:
print(node_tex, e)
node_tex.inputs[0].default_value = 1.0
node_tex.inputs[1].default_value = shader.inputs[0].default_value
node_tex.location.x = tex_img.location.x + 250
node_tex.location.y = tex_img.location.y + 150
i.material.node_tree.links.new(node_tex.inputs[2], tex_img.outputs['Color'])
if node_tex_last:
i.material.node_tree.links.new(node_tex.inputs[1], node_tex_last.outputs[0])
if j.use_map_alpha:
if node_alpha is None and i.material.alpha == 1.0:
node_alpha = tex_img
else:
node_alpha_last = node_alpha
node_alpha = i.material.node_tree.nodes.new('ShaderNodeMath')
try:
node_alpha.operation = j.blend_type
except TypeError as e:
print(node_alpha, e)
node_alpha.inputs[0].default_value = i.material.alpha
node_alpha.location.x = tex_img.location.x + 250
node_alpha.location.y = tex_img.location.y - 500
i.material.node_tree.links.new(node_alpha.inputs[1], tex_img.outputs['Alpha'])
if node_alpha_last:
i.material.node_tree.links.new(node_alpha.inputs[0], node_alpha_last.outputs[-1])
if node_tex:
i.material.node_tree.links.new(shader.inputs[0], node_tex.outputs[0])
alpha_value = 1.0
if hasattr(i.material, 'alpha'):
alpha_value = i.material.alpha
elif len(i.material.diffuse_color) > 3:
alpha_value = i.material.diffuse_color[3]
if node_alpha or alpha_value < 1.0:
alpha_shader = i.material.node_tree.nodes.new('ShaderNodeGroup')
alpha_shader.location.x = shader.location.x + 250
alpha_shader.location.y = shader.location.y - 150
alpha_shader.node_tree = mmd_alpha_shader_grp
alpha_shader.inputs[1].default_value = alpha_value
i.material.node_tree.links.new(alpha_shader.inputs[0], outplug)
outplug = alpha_shader.outputs[0]
if node_alpha:
i.material.node_tree.links.new(alpha_shader.inputs[1], node_alpha.outputs[-1])
material_output = __getMaterialOutput(i.material.node_tree.nodes)
i.material.node_tree.links.new(material_output.inputs['Surface'], outplug)
material_output.location.x = shader.location.x + 500
material_output.location.y = shader.location.y - 150
if not hasattr(bpy.types, 'ShaderNodeMaterial'):
return
# Add necessary nodes to retain Blender Render functionality
mat_node = i.material.node_tree.nodes.new('ShaderNodeMaterial')
out_node = i.material.node_tree.nodes.new('ShaderNodeOutput')
mat_node.material = i.material
mat_node.location.x = shader.location.x - 250
mat_node.location.y = shader.location.y + 500
out_node.location.x = mat_node.location.x + 750
out_node.location.y = mat_node.location.y
i.material.node_tree.links.new(out_node.inputs['Color'], mat_node.outputs['Color'])
i.material.node_tree.links.new(out_node.inputs['Alpha'], mat_node.outputs['Alpha'])
<file_sep>/mmd_tools/properties/__init__.py
# -*- coding: utf-8 -*-
if "bpy" in locals():
if bpy.app.version < (2, 71, 0):
import imp as importlib
else:
import importlib
importlib.reload(morph)
importlib.reload(root)
importlib.reload(camera)
importlib.reload(material)
importlib.reload(bone)
importlib.reload(rigid_body)
else:
import bpy
from . import (
morph,
root,
camera,
material,
bone,
rigid_body,
)
__properties = {
bpy.types.Object: {
'mmd_type': bpy.props.EnumProperty(
name='Type',
description='Internal MMD type of this object (DO NOT CHANGE IT DIRECTLY)',
default='NONE',
items=[
('NONE', 'None', '', 1),
('ROOT', 'Root', '', 2),
('RIGID_GRP_OBJ', 'Rigid Body Grp Empty', '', 3),
('JOINT_GRP_OBJ', 'Joint Grp Empty', '', 4),
('TEMPORARY_GRP_OBJ', 'Temporary Grp Empty', '', 5),
('PLACEHOLDER', 'Place Holder', '', 6),
('CAMERA', 'Camera', '', 21),
('JOINT', 'Joint', '', 22),
('RIGID_BODY', 'Rigid body', '', 23),
('LIGHT', 'Light', '', 24),
('TRACK_TARGET', 'Track Target', '', 51),
('NON_COLLISION_CONSTRAINT', 'Non Collision Constraint', '', 52),
('SPRING_CONSTRAINT', 'Spring Constraint', '', 53),
('SPRING_GOAL', 'Spring Goal', '', 54),
]
),
'mmd_root': bpy.props.PointerProperty(type=root.MMDRoot),
'mmd_camera': bpy.props.PointerProperty(type=camera.MMDCamera),
'mmd_rigid': bpy.props.PointerProperty(type=rigid_body.MMDRigidBody),
'mmd_joint': bpy.props.PointerProperty(type=rigid_body.MMDJoint),
'is_mmd_glsl_light': bpy.props.BoolProperty(name='is_mmd_glsl_light', default=False),
},
bpy.types.Material: {
'mmd_material': bpy.props.PointerProperty(type=material.MMDMaterial),
},
bpy.types.PoseBone: {
'mmd_bone': bpy.props.PointerProperty(type=bone.MMDBone),
'is_mmd_shadow_bone': bpy.props.BoolProperty(name='is_mmd_shadow_bone', default=False),
'mmd_shadow_bone_type': bpy.props.StringProperty(name='mmd_shadow_bone_type'),
'mmd_ik_toggle': bone._MMDPoseBoneProp.mmd_ik_toggle,
}
}
def __patch(properties): # temporary patching, should be removed in the future
prop_obj = properties.setdefault(bpy.types.Object, {})
prop_arm = properties.setdefault(bpy.types.Armature, {})
prop_cam = properties.setdefault(bpy.types.Camera, {})
prop_obj['select'] = bpy.props.BoolProperty(
get=lambda prop: prop.select_get(),
set=lambda prop, value: prop.select_set(value),
)
prop_obj['hide'] = bpy.props.BoolProperty(
get=lambda prop: prop.hide_get(),
set=lambda prop, value: prop.hide_set(value) or setattr(prop, 'hide_viewport', False),
)
prop_obj['show_x_ray'] = bpy.props.BoolProperty(
get=lambda prop: prop.show_in_front,
set=lambda prop, value: setattr(prop, 'show_in_front', value),
)
prop_obj['empty_draw_size'] = bpy.props.FloatProperty(
get=lambda prop: prop.empty_display_size,
set=lambda prop, value: setattr(prop, 'empty_display_size', value),
)
prop_obj['empty_draw_type'] = bpy.props.StringProperty(
get=lambda prop: prop.empty_display_type,
set=lambda prop, value: setattr(prop, 'empty_display_type', value),
)
prop_obj['draw_type'] = bpy.props.StringProperty(
get=lambda prop: prop.display_type,
set=lambda prop, value: setattr(prop, 'display_type', value),
)
prop_arm['draw_type'] = bpy.props.StringProperty(
get=lambda prop: prop.display_type,
set=lambda prop, value: setattr(prop, 'display_type', value),
)
prop_cam['draw_size'] = bpy.props.FloatProperty(
get=lambda prop: prop.display_size,
set=lambda prop, value: setattr(prop, 'display_size', value),
)
if bpy.app.version >= (2, 80, 0):
__patch(__properties)
def register():
for typ, t in __properties.items():
for attr, prop in t.items():
if hasattr(typ, attr):
print(' * warning: overwrite ', typ, attr)
setattr(typ, attr, prop)
def unregister():
for typ, t in __properties.items():
for attr in t.keys():
if hasattr(typ, attr):
delattr(typ, attr)
<file_sep>/mmd_tools/core/pmx/__init__.py
# -*- coding: utf-8 -*-
import struct
import os
import logging
class InvalidFileError(Exception):
pass
class UnsupportedVersionError(Exception):
pass
class FileStream:
def __init__(self, path, file_obj, pmx_header):
self.__path = path
self.__file_obj = file_obj
self.__header = pmx_header
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def path(self):
return self.__path
def header(self):
if self.__header is None:
raise Exception
return self.__header
def setHeader(self, pmx_header):
self.__header = pmx_header
def close(self):
if self.__file_obj is not None:
logging.debug('close the file("%s")', self.__path)
self.__file_obj.close()
self.__file_obj = None
class FileReadStream(FileStream):
def __init__(self, path, pmx_header=None):
self.__fin = open(path, 'rb')
FileStream.__init__(self, path, self.__fin, pmx_header)
def __readIndex(self, size, typedict):
index = None
if size in typedict :
index, = struct.unpack(typedict[size], self.__fin.read(size))
else:
raise ValueError('invalid data size %s'%str(size))
return index
def __readSignedIndex(self, size):
return self.__readIndex(size, { 1 :"<b", 2 :"<h", 4 :"<i"})
def __readUnsignedIndex(self, size):
return self.__readIndex(size, { 1 :"<B", 2 :"<H", 4 :"<I"})
# READ methods for indexes
def readVertexIndex(self):
return self.__readUnsignedIndex(self.header().vertex_index_size)
def readBoneIndex(self):
return self.__readSignedIndex(self.header().bone_index_size)
def readTextureIndex(self):
return self.__readSignedIndex(self.header().texture_index_size)
def readMorphIndex(self):
return self.__readSignedIndex(self.header().morph_index_size)
def readRigidIndex(self):
return self.__readSignedIndex(self.header().rigid_index_size)
def readMaterialIndex(self):
return self.__readSignedIndex(self.header().material_index_size)
# READ / WRITE methods for general types
def readInt(self):
v, = struct.unpack('<i', self.__fin.read(4))
return v
def readShort(self):
v, = struct.unpack('<h', self.__fin.read(2))
return v
def readUnsignedShort(self):
v, = struct.unpack('<H', self.__fin.read(2))
return v
def readStr(self):
length = self.readInt()
buf, = struct.unpack('<%ds'%length, self.__fin.read(length))
return str(buf, self.header().encoding.charset, errors='replace')
def readFloat(self):
v, = struct.unpack('<f', self.__fin.read(4))
return v
def readVector(self, size):
return struct.unpack('<'+'f'*size, self.__fin.read(4*size))
def readByte(self):
v, = struct.unpack('<B', self.__fin.read(1))
return v
def readBytes(self, length):
return self.__fin.read(length)
def readSignedByte(self):
v, = struct.unpack('<b', self.__fin.read(1))
return v
class FileWriteStream(FileStream):
def __init__(self, path, pmx_header=None):
self.__fout = open(path, 'wb')
FileStream.__init__(self, path, self.__fout, pmx_header)
def __writeIndex(self, index, size, typedict):
if size in typedict :
self.__fout.write(struct.pack(typedict[size], int(index)))
else:
raise ValueError('invalid data size %s'%str(size))
return
def __writeSignedIndex(self, index, size):
return self.__writeIndex(index, size, { 1 :"<b", 2 :"<h", 4 :"<i"})
def __writeUnsignedIndex(self, index, size):
return self.__writeIndex(index, size, { 1 :"<B", 2 :"<H", 4 :"<I"})
# WRITE methods for indexes
def writeVertexIndex(self, index):
return self.__writeUnsignedIndex(index, self.header().vertex_index_size)
def writeBoneIndex(self, index):
return self.__writeSignedIndex(index, self.header().bone_index_size)
def writeTextureIndex(self, index):
return self.__writeSignedIndex(index, self.header().texture_index_size)
def writeMorphIndex(self, index):
return self.__writeSignedIndex(index, self.header().morph_index_size)
def writeRigidIndex(self, index):
return self.__writeSignedIndex(index, self.header().rigid_index_size)
def writeMaterialIndex(self, index):
return self.__writeSignedIndex(index, self.header().material_index_size)
def writeInt(self, v):
self.__fout.write(struct.pack('<i', int(v)))
def writeShort(self, v):
self.__fout.write(struct.pack('<h', int(v)))
def writeUnsignedShort(self, v):
self.__fout.write(struct.pack('<H', int(v)))
def writeStr(self, v):
data = v.encode(self.header().encoding.charset)
self.writeInt(len(data))
self.__fout.write(data)
def writeFloat(self, v):
self.__fout.write(struct.pack('<f', float(v)))
def writeVector(self, v):
self.__fout.write(struct.pack('<'+'f'*len(v), *v))
def writeByte(self, v):
self.__fout.write(struct.pack('<B', int(v)))
def writeBytes(self, v):
self.__fout.write(v)
def writeSignedByte(self, v):
self.__fout.write(struct.pack('<b', int(v)))
class Encoding:
_MAP = [
(0, 'utf-16-le'),
(1, 'utf-8'),
]
def __init__(self, arg):
self.index = 0
self.charset = ''
t = None
if isinstance(arg, str):
t = list(filter(lambda x: x[1]==arg, self._MAP))
if len(t) == 0:
raise ValueError('invalid charset %s'%arg)
elif isinstance(arg, int):
t = list(filter(lambda x: x[0]==arg, self._MAP))
if len(t) == 0:
raise ValueError('invalid index %d'%arg)
else:
raise ValueError('invalid argument type')
t = t[0]
self.index = t[0]
self.charset = t[1]
def __repr__(self):
return '<Encoding charset %s>'%self.charset
class Coordinate:
""" """
def __init__(self, xAxis, zAxis):
self.x_axis = xAxis
self.z_axis = zAxis
class Header:
PMX_SIGN = b'PMX '
VERSION = 2.0
def __init__(self, model=None):
self.sign = self.PMX_SIGN
self.version = 0
self.encoding = Encoding('utf-16-le')
self.additional_uvs = 0
self.vertex_index_size = 1
self.texture_index_size = 1
self.material_index_size = 1
self.bone_index_size = 1
self.morph_index_size = 1
self.rigid_index_size = 1
if model is not None:
self.updateIndexSizes(model)
def updateIndexSizes(self, model):
self.vertex_index_size = self.__getIndexSize(len(model.vertices), False)
self.texture_index_size = self.__getIndexSize(len(model.textures), True)
self.material_index_size = self.__getIndexSize(len(model.materials), True)
self.bone_index_size = self.__getIndexSize(len(model.bones), True)
self.morph_index_size = self.__getIndexSize(len(model.morphs), True)
self.rigid_index_size = self.__getIndexSize(len(model.rigids), True)
@staticmethod
def __getIndexSize(num, signed):
s = 1
if signed:
s = 2
if (1<<8)/s > num:
return 1
elif (1<<16)/s > num:
return 2
else:
return 4
def load(self, fs):
logging.info('loading pmx header information...')
self.sign = fs.readBytes(4)
logging.debug('File signature is %s', self.sign)
if self.sign[:3] != self.PMX_SIGN[:3]:
logging.info('File signature is invalid')
logging.error('This file is unsupported format, or corrupt file.')
raise InvalidFileError('File signature is invalid.')
self.version = fs.readFloat()
logging.info('pmx format version: %f', self.version)
if self.version != self.VERSION:
logging.error('PMX version %.1f is unsupported', self.version)
raise UnsupportedVersionError('unsupported PMX version: %.1f'%self.version)
if fs.readByte() != 8 or self.sign[3] != self.PMX_SIGN[3]:
logging.warning(' * This file might be corrupted.')
self.encoding = Encoding(fs.readByte())
self.additional_uvs = fs.readByte()
self.vertex_index_size = fs.readByte()
self.texture_index_size = fs.readByte()
self.material_index_size = fs.readByte()
self.bone_index_size = fs.readByte()
self.morph_index_size = fs.readByte()
self.rigid_index_size = fs.readByte()
logging.info('----------------------------')
logging.info('pmx header information')
logging.info('----------------------------')
logging.info('pmx version: %.1f', self.version)
logging.info('encoding: %s', str(self.encoding))
logging.info('number of uvs: %d', self.additional_uvs)
logging.info('vertex index size: %d byte(s)', self.vertex_index_size)
logging.info('texture index: %d byte(s)', self.texture_index_size)
logging.info('material index: %d byte(s)', self.material_index_size)
logging.info('bone index: %d byte(s)', self.bone_index_size)
logging.info('morph index: %d byte(s)', self.morph_index_size)
logging.info('rigid index: %d byte(s)', self.rigid_index_size)
logging.info('----------------------------')
def save(self, fs):
fs.writeBytes(self.PMX_SIGN)
fs.writeFloat(self.VERSION)
fs.writeByte(8)
fs.writeByte(self.encoding.index)
fs.writeByte(self.additional_uvs)
fs.writeByte(self.vertex_index_size)
fs.writeByte(self.texture_index_size)
fs.writeByte(self.material_index_size)
fs.writeByte(self.bone_index_size)
fs.writeByte(self.morph_index_size)
fs.writeByte(self.rigid_index_size)
def __repr__(self):
return '<Header encoding %s, uvs %d, vtx %d, tex %d, mat %d, bone %d, morph %d, rigid %d>'%(
str(self.encoding),
self.additional_uvs,
self.vertex_index_size,
self.texture_index_size,
self.material_index_size,
self.bone_index_size,
self.morph_index_size,
self.rigid_index_size,
)
class Model:
def __init__(self):
self.filepath = ''
self.header = None
self.name = ''
self.name_e = ''
self.comment = ''
self.comment_e = ''
self.vertices = []
self.faces = []
self.textures = []
self.materials = []
self.bones = []
self.morphs = []
self.display = []
dsp_root = Display()
dsp_root.isSpecial = True
dsp_root.name = 'Root'
dsp_root.name_e = 'Root'
self.display.append(dsp_root)
dsp_face = Display()
dsp_face.isSpecial = True
dsp_face.name = '表情'
dsp_face.name_e = 'Facial'
self.display.append(dsp_face)
self.rigids = []
self.joints = []
def load(self, fs):
self.filepath = fs.path()
self.header = fs.header()
self.name = fs.readStr()
self.name_e = fs.readStr()
self.comment = fs.readStr()
self.comment_e = fs.readStr()
logging.info('Model name: %s', self.name)
logging.info('Model name(english): %s', self.name_e)
logging.info('Comment:%s', self.comment)
logging.info('Comment(english):%s', self.comment_e)
logging.info('')
logging.info('------------------------------')
logging.info('Load Vertices')
logging.info('------------------------------')
num_vertices = fs.readInt()
self.vertices = []
for i in range(num_vertices):
v = Vertex()
v.load(fs)
self.vertices.append(v)
logging.info('----- Loaded %d vertices', len(self.vertices))
logging.info('')
logging.info('------------------------------')
logging.info(' Load Faces')
logging.info('------------------------------')
num_faces = fs.readInt()
self.faces = []
for i in range(int(num_faces/3)):
f1 = fs.readVertexIndex()
f2 = fs.readVertexIndex()
f3 = fs.readVertexIndex()
self.faces.append((f3, f2, f1))
logging.info(' Load %d faces', len(self.faces))
logging.info('')
logging.info('------------------------------')
logging.info(' Load Textures')
logging.info('------------------------------')
num_textures = fs.readInt()
self.textures = []
for i in range(num_textures):
t = Texture()
t.load(fs)
self.textures.append(t)
logging.info('Texture %d: %s', i, t.path)
logging.info(' ----- Loaded %d textures', len(self.textures))
logging.info('')
logging.info('------------------------------')
logging.info(' Load Materials')
logging.info('------------------------------')
num_materials = fs.readInt()
self.materials = []
for i in range(num_materials):
m = Material()
m.load(fs, num_textures)
self.materials.append(m)
logging.info('Material %d: %s', i, m.name)
logging.debug(' Name(english): %s', m.name_e)
logging.debug(' Comment: %s', m.comment)
logging.debug(' Vertex Count: %d', m.vertex_count)
logging.debug(' Diffuse: (%.2f, %.2f, %.2f, %.2f)', *m.diffuse)
logging.debug(' Specular: (%.2f, %.2f, %.2f)', *m.specular)
logging.debug(' Shininess: %f', m.shininess)
logging.debug(' Ambient: (%.2f, %.2f, %.2f)', *m.ambient)
logging.debug(' Double Sided: %s', str(m.is_double_sided))
logging.debug(' Drop Shadow: %s', str(m.enabled_drop_shadow))
logging.debug(' Self Shadow: %s', str(m.enabled_self_shadow))
logging.debug(' Self Shadow Map: %s', str(m.enabled_self_shadow_map))
logging.debug(' Edge: %s', str(m.enabled_toon_edge))
logging.debug(' Edge Color: (%.2f, %.2f, %.2f, %.2f)', *m.edge_color)
logging.debug(' Edge Size: %.2f', m.edge_size)
if m.texture != -1:
logging.debug(' Texture Index: %d', m.texture)
else:
logging.debug(' Texture: None')
if m.sphere_texture != -1:
logging.debug(' Sphere Texture Index: %d', m.sphere_texture)
logging.debug(' Sphere Texture Mode: %d', m.sphere_texture_mode)
else:
logging.debug(' Sphere Texture: None')
logging.debug('')
logging.info('----- Loaded %d materials.', len(self.materials))
logging.info('')
logging.info('------------------------------')
logging.info(' Load Bones')
logging.info('------------------------------')
num_bones = fs.readInt()
self.bones = []
for i in range(num_bones):
b = Bone()
b.load(fs)
self.bones.append(b)
logging.info('Bone %d: %s', i, b.name)
logging.debug(' Name(english): %s', b.name_e)
logging.debug(' Location: (%f, %f, %f)', *b.location)
logging.debug(' displayConnection: %s', str(b.displayConnection))
logging.debug(' Parent: %s', str(b.parent))
logging.debug(' Transform Order: %s', str(b.transform_order))
logging.debug(' Rotatable: %s', str(b.isRotatable))
logging.debug(' Movable: %s', str(b.isMovable))
logging.debug(' Visible: %s', str(b.visible))
logging.debug(' Controllable: %s', str(b.isControllable))
logging.debug(' Additional Location: %s', str(b.hasAdditionalLocation))
logging.debug(' Additional Rotation: %s', str(b.hasAdditionalRotate))
if b.additionalTransform is not None:
logging.debug(' Additional Transform: Bone:%d, influence: %f', *b.additionalTransform)
logging.debug(' IK: %s', str(b.isIK))
if b.isIK:
logging.debug(' Target: %d', b.target)
for j, link in enumerate(b.ik_links):
if isinstance(link.minimumAngle, list) and len(link.minimumAngle) == 3:
min_str = '(%f, %f, %f)'%tuple(link.minimumAngle)
else:
min_str = '(None, None, None)'
if isinstance(link.maximumAngle, list) and len(link.maximumAngle) == 3:
max_str = '(%f, %f, %f)'%tuple(link.maximumAngle)
else:
max_str = '(None, None, None)'
logging.debug(' IK Link %d: %d, %s - %s', j, link.target, min_str, max_str)
logging.debug('')
logging.info('----- Loaded %d bones.', len(self.bones))
logging.info('')
logging.info('------------------------------')
logging.info(' Load Morphs')
logging.info('------------------------------')
num_morph = fs.readInt()
self.morphs = []
display_categories = {0: 'System', 1: 'Eyebrow', 2: 'Eye', 3: 'Mouth', 4: 'Other'}
for i in range(num_morph):
m = Morph.create(fs)
self.morphs.append(m)
logging.info('%s %d: %s', m.__class__.__name__, i, m.name)
logging.debug(' Name(english): %s', m.name_e)
logging.debug(' Category: %s (%d)', display_categories.get(m.category, '#Invalid'), m.category)
logging.debug('')
logging.info('----- Loaded %d morphs.', len(self.morphs))
logging.info('')
logging.info('------------------------------')
logging.info(' Load Display Items')
logging.info('------------------------------')
num_disp = fs.readInt()
self.display = []
for i in range(num_disp):
d = Display()
d.load(fs)
self.display.append(d)
logging.info('Display Item %d: %s', i, d.name)
logging.debug(' Name(english): %s', d.name_e)
logging.debug('')
logging.info('----- Loaded %d display items.', len(self.display))
logging.info('')
logging.info('------------------------------')
logging.info(' Load Rigid Bodies')
logging.info('------------------------------')
num_rigid = fs.readInt()
self.rigids = []
rigid_types = {0: 'Sphere', 1: 'Box', 2: 'Capsule'}
rigid_modes = {0: 'Static', 1: 'Dynamic', 2: 'Dynamic(track to bone)'}
for i in range(num_rigid):
r = Rigid()
r.load(fs)
self.rigids.append(r)
logging.info('Rigid Body %d: %s', i, r.name)
logging.debug(' Name(english): %s', r.name_e)
logging.debug(' Type: %s', rigid_types[r.type])
logging.debug(' Mode: %s (%d)', rigid_modes.get(r.mode, '#Invalid'), r.mode)
logging.debug(' Related bone: %s', r.bone)
logging.debug(' Collision group: %d', r.collision_group_number)
logging.debug(' Collision group mask: 0x%x', r.collision_group_mask)
logging.debug(' Size: (%f, %f, %f)', *r.size)
logging.debug(' Location: (%f, %f, %f)', *r.location)
logging.debug(' Rotation: (%f, %f, %f)', *r.rotation)
logging.debug(' Mass: %f', r.mass)
logging.debug(' Bounce: %f', r.bounce)
logging.debug(' Friction: %f', r.friction)
logging.debug('')
logging.info('----- Loaded %d rigid bodies.', len(self.rigids))
logging.info('')
logging.info('------------------------------')
logging.info(' Load Joints')
logging.info('------------------------------')
num_joints = fs.readInt()
self.joints = []
for i in range(num_joints):
j = Joint()
j.load(fs)
self.joints.append(j)
logging.info('Joint %d: %s', i, j.name)
logging.debug(' Name(english): %s', j.name_e)
logging.debug(' Rigid A: %s', j.src_rigid)
logging.debug(' Rigid B: %s', j.dest_rigid)
logging.debug(' Location: (%f, %f, %f)', *j.location)
logging.debug(' Rotation: (%f, %f, %f)', *j.rotation)
logging.debug(' Location Limit: (%f, %f, %f) - (%f, %f, %f)', *(j.minimum_location + j.maximum_location))
logging.debug(' Rotation Limit: (%f, %f, %f) - (%f, %f, %f)', *(j.minimum_rotation + j.maximum_rotation))
logging.debug(' Spring: (%f, %f, %f)', *j.spring_constant)
logging.debug(' Spring(rotation): (%f, %f, %f)', *j.spring_rotation_constant)
logging.debug('')
logging.info('----- Loaded %d joints.', len(self.joints))
def save(self, fs):
fs.writeStr(self.name)
fs.writeStr(self.name_e)
fs.writeStr(self.comment)
fs.writeStr(self.comment_e)
logging.info('''exportings pmx model data...
name: %s
name(english): %s
comment:
%s
comment(english):
%s
''', self.name, self.name_e, self.comment, self.comment_e)
logging.info('exporting vertices... %d', len(self.vertices))
fs.writeInt(len(self.vertices))
for i in self.vertices:
i.save(fs)
logging.info('finished exporting vertices.')
logging.info('exporting faces... %d', len(self.faces))
fs.writeInt(len(self.faces)*3)
for f3, f2, f1 in self.faces:
fs.writeVertexIndex(f1)
fs.writeVertexIndex(f2)
fs.writeVertexIndex(f3)
logging.info('finished exporting faces.')
logging.info('exporting textures... %d', len(self.textures))
fs.writeInt(len(self.textures))
for i in self.textures:
i.save(fs)
logging.info('finished exporting textures.')
logging.info('exporting materials... %d', len(self.materials))
fs.writeInt(len(self.materials))
for i in self.materials:
i.save(fs)
logging.info('finished exporting materials.')
logging.info('exporting bones... %d', len(self.bones))
fs.writeInt(len(self.bones))
for i in self.bones:
i.save(fs)
logging.info('finished exporting bones.')
logging.info('exporting morphs... %d', len(self.morphs))
fs.writeInt(len(self.morphs))
for i in self.morphs:
i.save(fs)
logging.info('finished exporting morphs.')
logging.info('exporting display items... %d', len(self.display))
fs.writeInt(len(self.display))
for i in self.display:
i.save(fs)
logging.info('finished exporting display items.')
logging.info('exporting rigid bodies... %d', len(self.rigids))
fs.writeInt(len(self.rigids))
for i in self.rigids:
i.save(fs)
logging.info('finished exporting rigid bodies.')
logging.info('exporting joints... %d', len(self.joints))
fs.writeInt(len(self.joints))
for i in self.joints:
i.save(fs)
logging.info('finished exporting joints.')
logging.info('finished exporting the model.')
def __repr__(self):
return '<Model name %s, name_e %s, comment %s, comment_e %s, textures %s>'%(
self.name,
self.name_e,
self.comment,
self.comment_e,
str(self.textures),
)
class Vertex:
def __init__(self):
self.co = [0.0, 0.0, 0.0]
self.normal = [0.0, 0.0, 0.0]
self.uv = [0.0, 0.0]
self.additional_uvs = []
self.weight = None
self.edge_scale = 1
def __repr__(self):
return '<Vertex co %s, normal %s, uv %s, additional_uvs %s, weight %s, edge_scale %s>'%(
str(self.co),
str(self.normal),
str(self.uv),
str(self.additional_uvs),
str(self.weight),
str(self.edge_scale),
)
def load(self, fs):
self.co = fs.readVector(3)
self.normal = fs.readVector(3)
self.uv = fs.readVector(2)
self.additional_uvs = []
for i in range(fs.header().additional_uvs):
self.additional_uvs.append(fs.readVector(4))
self.weight = BoneWeight()
self.weight.load(fs)
self.edge_scale = fs.readFloat()
def save(self, fs):
fs.writeVector(self.co)
fs.writeVector(self.normal)
fs.writeVector(self.uv)
for i in self.additional_uvs:
fs.writeVector(i)
for i in range(fs.header().additional_uvs-len(self.additional_uvs)):
fs.writeVector((0,0,0,0))
self.weight.save(fs)
fs.writeFloat(self.edge_scale)
class BoneWeightSDEF:
def __init__(self, weight=0, c=None, r0=None, r1=None):
self.weight = weight
self.c = c
self.r0 = r0
self.r1 = r1
class BoneWeight:
BDEF1 = 0
BDEF2 = 1
BDEF4 = 2
SDEF = 3
TYPES = [
(BDEF1, 'BDEF1'),
(BDEF2, 'BDEF2'),
(BDEF4, 'BDEF4'),
(SDEF, 'SDEF'),
]
def __init__(self):
self.bones = []
self.weights = []
self.type = self.BDEF1
def convertIdToName(self, type_id):
t = list(filter(lambda x: x[0]==type_id, self.TYPES))
if len(t) > 0:
return t[0][1]
else:
return None
def convertNameToId(self, type_name):
t = list(filter(lambda x: x[1]==type_name, self.TYPES))
if len(t) > 0:
return t[0][0]
else:
return None
def load(self, fs):
self.type = fs.readByte()
self.bones = []
self.weights = []
if self.type == self.BDEF1:
self.bones.append(fs.readBoneIndex())
elif self.type == self.BDEF2:
self.bones.append(fs.readBoneIndex())
self.bones.append(fs.readBoneIndex())
self.weights.append(fs.readFloat())
elif self.type == self.BDEF4:
self.bones.append(fs.readBoneIndex())
self.bones.append(fs.readBoneIndex())
self.bones.append(fs.readBoneIndex())
self.bones.append(fs.readBoneIndex())
self.weights = fs.readVector(4)
elif self.type == self.SDEF:
self.bones.append(fs.readBoneIndex())
self.bones.append(fs.readBoneIndex())
self.weights = BoneWeightSDEF()
self.weights.weight = fs.readFloat()
self.weights.c = fs.readVector(3)
self.weights.r0 = fs.readVector(3)
self.weights.r1 = fs.readVector(3)
else:
raise ValueError('invalid weight type %s'%str(self.type))
def save(self, fs):
fs.writeByte(self.type)
if self.type == self.BDEF1:
fs.writeBoneIndex(self.bones[0])
elif self.type == self.BDEF2:
for i in range(2):
fs.writeBoneIndex(self.bones[i])
fs.writeFloat(self.weights[0])
elif self.type == self.BDEF4:
for i in range(4):
fs.writeBoneIndex(self.bones[i])
for i in range(4):
fs.writeFloat(self.weights[i])
elif self.type == self.SDEF:
for i in range(2):
fs.writeBoneIndex(self.bones[i])
if not isinstance(self.weights, BoneWeightSDEF):
raise ValueError
fs.writeFloat(self.weights.weight)
fs.writeVector(self.weights.c)
fs.writeVector(self.weights.r0)
fs.writeVector(self.weights.r1)
else:
raise ValueError('invalid weight type %s'%str(self.type))
class Texture:
def __init__(self):
self.path = ''
def __repr__(self):
return '<Texture path %s>'%str(self.path)
def load(self, fs):
self.path = fs.readStr()
self.path = self.path.replace('\\', os.path.sep)
if not os.path.isabs(self.path):
self.path = os.path.normpath(os.path.join(os.path.dirname(fs.path()), self.path))
def save(self, fs):
try:
relPath = os.path.relpath(self.path, os.path.dirname(fs.path()))
except ValueError:
relPath = self.path
relPath = relPath.replace(os.path.sep, '\\') # always save using windows path conventions
logging.info('writing to pmx file the relative texture path: %s', relPath)
fs.writeStr(relPath)
class SharedTexture(Texture):
def __init__(self):
self.number = 0
self.prefix = ''
class Material:
SPHERE_MODE_OFF = 0
SPHERE_MODE_MULT = 1
SPHERE_MODE_ADD = 2
SPHERE_MODE_SUBTEX = 3
def __init__(self):
self.name = ''
self.name_e = ''
self.diffuse = []
self.specular = []
self.shininess = 0
self.ambient = []
self.is_double_sided = True
self.enabled_drop_shadow = True
self.enabled_self_shadow_map = True
self.enabled_self_shadow = True
self.enabled_toon_edge = False
self.edge_color = []
self.edge_size = 1
self.texture = -1
self.sphere_texture = -1
self.sphere_texture_mode = 0
self.is_shared_toon_texture = True
self.toon_texture = 0
self.comment = ''
self.vertex_count = 0
def __repr__(self):
return '<Material name %s, name_e %s, diffuse %s, specular %s, shininess %s, ambient %s, double_side %s, drop_shadow %s, self_shadow_map %s, self_shadow %s, toon_edge %s, edge_color %s, edge_size %s, toon_texture %s, comment %s>'%(
self.name,
self.name_e,
str(self.diffuse),
str(self.specular),
str(self.shininess),
str(self.ambient),
str(self.is_double_sided),
str(self.enabled_drop_shadow),
str(self.enabled_self_shadow_map),
str(self.enabled_self_shadow),
str(self.enabled_toon_edge),
str(self.edge_color),
str(self.edge_size),
str(self.texture),
str(self.sphere_texture),
str(self.toon_texture),
str(self.comment),)
def load(self, fs, num_textures):
def __tex_index(index):
return index if 0 <= index < num_textures else -1
self.name = fs.readStr()
self.name_e = fs.readStr()
self.diffuse = fs.readVector(4)
self.specular = fs.readVector(3)
self.shininess = fs.readFloat()
self.ambient = fs.readVector(3)
flags = fs.readByte()
self.is_double_sided = bool(flags & 1)
self.enabled_drop_shadow = bool(flags & 2)
self.enabled_self_shadow_map = bool(flags & 4)
self.enabled_self_shadow = bool(flags & 8)
self.enabled_toon_edge = bool(flags & 16)
self.edge_color = fs.readVector(4)
self.edge_size = fs.readFloat()
self.texture = __tex_index(fs.readTextureIndex())
self.sphere_texture = __tex_index(fs.readTextureIndex())
self.sphere_texture_mode = fs.readSignedByte()
self.is_shared_toon_texture = fs.readSignedByte()
self.is_shared_toon_texture = (self.is_shared_toon_texture == 1)
if self.is_shared_toon_texture:
self.toon_texture = fs.readSignedByte()
else:
self.toon_texture = __tex_index(fs.readTextureIndex())
self.comment = fs.readStr()
self.vertex_count = fs.readInt()
def save(self, fs):
fs.writeStr(self.name)
fs.writeStr(self.name_e)
fs.writeVector(self.diffuse)
fs.writeVector(self.specular)
fs.writeFloat(self.shininess)
fs.writeVector(self.ambient)
flags = 0
flags |= int(self.is_double_sided)
flags |= int(self.enabled_drop_shadow) << 1
flags |= int(self.enabled_self_shadow_map) << 2
flags |= int(self.enabled_self_shadow) << 3
flags |= int(self.enabled_toon_edge) << 4
fs.writeByte(flags)
fs.writeVector(self.edge_color)
fs.writeFloat(self.edge_size)
fs.writeTextureIndex(self.texture)
fs.writeTextureIndex(self.sphere_texture)
fs.writeSignedByte(self.sphere_texture_mode)
if self.is_shared_toon_texture:
fs.writeSignedByte(1)
fs.writeSignedByte(self.toon_texture)
else:
fs.writeSignedByte(0)
fs.writeTextureIndex(self.toon_texture)
fs.writeStr(self.comment)
fs.writeInt(self.vertex_count)
class Bone:
def __init__(self):
self.name = ''
self.name_e = ''
self.location = []
self.parent = None
self.transform_order = 0
# 接続先表示方法
# 座標オフセット(float3)または、boneIndex(int)
self.displayConnection = -1
self.isRotatable = True
self.isMovable = True
self.visible = True
self.isControllable = True
self.isIK = False
# 回転付与
self.hasAdditionalRotate = False
# 移動付与
self.hasAdditionalLocation = False
# 回転付与および移動付与の付与量
self.additionalTransform = None
# 軸固定
# 軸ベクトルfloat3
self.axis = None
# ローカル軸
self.localCoordinate = None
self.transAfterPhis = False
# 外部親変形
self.externalTransKey = None
# 以下IKボーンのみ有効な変数
self.target = None
self.loopCount = 8
# IKループ計三時の1回あたりの制限角度(ラジアン)
self.rotationConstraint = 0.03
# IKLinkオブジェクトの配列
self.ik_links = []
def __repr__(self):
return '<Bone name %s, name_e %s>'%(
self.name,
self.name_e,)
def load(self, fs):
self.name = fs.readStr()
self.name_e = fs.readStr()
self.location = fs.readVector(3)
self.parent = fs.readBoneIndex()
self.transform_order = fs.readInt()
flags = fs.readShort()
if flags & 0x0001:
self.displayConnection = fs.readBoneIndex()
else:
self.displayConnection = fs.readVector(3)
self.isRotatable = ((flags & 0x0002) != 0)
self.isMovable = ((flags & 0x0004) != 0)
self.visible = ((flags & 0x0008) != 0)
self.isControllable = ((flags & 0x0010) != 0)
self.isIK = ((flags & 0x0020) != 0)
self.hasAdditionalRotate = ((flags & 0x0100) != 0)
self.hasAdditionalLocation = ((flags & 0x0200) != 0)
if self.hasAdditionalRotate or self.hasAdditionalLocation:
t = fs.readBoneIndex()
v = fs.readFloat()
self.additionalTransform = (t, v)
else:
self.additionalTransform = None
if flags & 0x0400:
self.axis = fs.readVector(3)
else:
self.axis = None
if flags & 0x0800:
xaxis = fs.readVector(3)
zaxis = fs.readVector(3)
self.localCoordinate = Coordinate(xaxis, zaxis)
else:
self.localCoordinate = None
self.transAfterPhis = ((flags & 0x1000) != 0)
if flags & 0x2000:
self.externalTransKey = fs.readInt()
else:
self.externalTransKey = None
if self.isIK:
self.target = fs.readBoneIndex()
self.loopCount = fs.readInt()
self.rotationConstraint = fs.readFloat()
iklink_num = fs.readInt()
self.ik_links = []
for i in range(iklink_num):
link = IKLink()
link.load(fs)
self.ik_links.append(link)
def save(self, fs):
fs.writeStr(self.name)
fs.writeStr(self.name_e)
fs.writeVector(self.location)
fs.writeBoneIndex(-1 if self.parent is None else self.parent)
fs.writeInt(self.transform_order)
flags = 0
flags |= int(isinstance(self.displayConnection, int))
flags |= int(self.isRotatable) << 1
flags |= int(self.isMovable) << 2
flags |= int(self.visible) << 3
flags |= int(self.isControllable) << 4
flags |= int(self.isIK) << 5
flags |= int(self.hasAdditionalRotate) << 8
flags |= int(self.hasAdditionalLocation) << 9
flags |= int(self.axis is not None) << 10
flags |= int(self.localCoordinate is not None) << 11
flags |= int(self.transAfterPhis) << 12
flags |= int(self.externalTransKey is not None) << 13
fs.writeShort(flags)
if flags & 0x0001:
fs.writeBoneIndex(self.displayConnection)
else:
fs.writeVector(self.displayConnection)
if self.hasAdditionalRotate or self.hasAdditionalLocation:
fs.writeBoneIndex(self.additionalTransform[0])
fs.writeFloat(self.additionalTransform[1])
if flags & 0x0400:
fs.writeVector(self.axis)
if flags & 0x0800:
fs.writeVector(self.localCoordinate.x_axis)
fs.writeVector(self.localCoordinate.z_axis)
if flags & 0x2000:
fs.writeInt(self.externalTransKey)
if self.isIK:
fs.writeBoneIndex(self.target)
fs.writeInt(self.loopCount)
fs.writeFloat(self.rotationConstraint)
fs.writeInt(len(self.ik_links))
for i in self.ik_links:
i.save(fs)
class IKLink:
def __init__(self):
self.target = None
self.maximumAngle = None
self.minimumAngle = None
def __repr__(self):
return '<IKLink target %s>'%(str(self.target))
def load(self, fs):
self.target = fs.readBoneIndex()
flag = fs.readByte()
if flag == 1:
self.minimumAngle = fs.readVector(3)
self.maximumAngle = fs.readVector(3)
else:
self.minimumAngle = None
self.maximumAngle = None
def save(self, fs):
fs.writeBoneIndex(self.target)
if isinstance(self.minimumAngle, list) and isinstance(self.maximumAngle, list):
fs.writeByte(1)
fs.writeVector(self.minimumAngle)
fs.writeVector(self.maximumAngle)
else:
fs.writeByte(0)
class Morph:
CATEGORY_SYSTEM = 0
CATEGORY_EYEBROW = 1
CATEGORY_EYE = 2
CATEGORY_MOUTH = 3
CATEGORY_OHTER = 4
def __init__(self, name, name_e, category, **kwargs):
self.offsets = []
self.name = name
self.name_e = name_e
self.category = category
def __repr__(self):
return '<Morph name %s, name_e %s>'%(self.name, self.name_e)
def type_index(self):
raise NotImplementedError
@staticmethod
def create(fs):
_CLASSES = {
0: GroupMorph,
1: VertexMorph,
2: BoneMorph,
3: UVMorph,
4: UVMorph,
5: UVMorph,
6: UVMorph,
7: UVMorph,
8: MaterialMorph,
}
name = fs.readStr()
name_e = fs.readStr()
logging.debug('morph: %s', name)
category = fs.readSignedByte()
typeIndex = fs.readSignedByte()
ret = _CLASSES[typeIndex](name, name_e, category, type_index = typeIndex)
ret.load(fs)
return ret
def load(self, fs):
""" Implement for loading morph data.
"""
raise NotImplementedError
def save(self, fs):
fs.writeStr(self.name)
fs.writeStr(self.name_e)
fs.writeSignedByte(self.category)
fs.writeSignedByte(self.type_index())
fs.writeInt(len(self.offsets))
for i in self.offsets:
i.save(fs)
class VertexMorph(Morph):
def __init__(self, *args, **kwargs):
Morph.__init__(self, *args, **kwargs)
def type_index(self):
return 1
def load(self, fs):
num = fs.readInt()
for i in range(num):
t = VertexMorphOffset()
t.load(fs)
self.offsets.append(t)
class VertexMorphOffset:
def __init__(self):
self.index = 0
self.offset = []
def load(self, fs):
self.index = fs.readVertexIndex()
self.offset = fs.readVector(3)
def save(self, fs):
fs.writeVertexIndex(self.index)
fs.writeVector(self.offset)
class UVMorph(Morph):
def __init__(self, *args, **kwargs):
self.uv_index = kwargs.get('type_index', 3) - 3
Morph.__init__(self, *args, **kwargs)
def type_index(self):
return self.uv_index + 3
def load(self, fs):
self.offsets = []
num = fs.readInt()
for i in range(num):
t = UVMorphOffset()
t.load(fs)
self.offsets.append(t)
class UVMorphOffset:
def __init__(self):
self.index = 0
self.offset = []
def load(self, fs):
self.index = fs.readVertexIndex()
self.offset = fs.readVector(4)
def save(self, fs):
fs.writeVertexIndex(self.index)
fs.writeVector(self.offset)
class BoneMorph(Morph):
def __init__(self, *args, **kwargs):
Morph.__init__(self, *args, **kwargs)
def type_index(self):
return 2
def load(self, fs):
self.offsets = []
num = fs.readInt()
for i in range(num):
t = BoneMorphOffset()
t.load(fs)
self.offsets.append(t)
class BoneMorphOffset:
def __init__(self):
self.index = None
self.location_offset = []
self.rotation_offset = []
def load(self, fs):
self.index = fs.readBoneIndex()
self.location_offset = fs.readVector(3)
self.rotation_offset = fs.readVector(4)
def save(self, fs):
fs.writeBoneIndex(self.index)
fs.writeVector(self.location_offset)
fs.writeVector(self.rotation_offset)
class MaterialMorph(Morph):
def __init__(self, *args, **kwargs):
Morph.__init__(self, *args, **kwargs)
def type_index(self):
return 8
def load(self, fs):
self.offsets = []
num = fs.readInt()
for i in range(num):
t = MaterialMorphOffset()
t.load(fs)
self.offsets.append(t)
class MaterialMorphOffset:
TYPE_MULT = 0
TYPE_ADD = 1
def __init__(self):
self.index = 0
self.offset_type = 0
self.diffuse_offset = []
self.specular_offset = []
self.shininess_offset = 0
self.ambient_offset = []
self.edge_color_offset = []
self.edge_size_offset = []
self.texture_factor = []
self.sphere_texture_factor = []
self.toon_texture_factor = []
def load(self, fs):
self.index = fs.readMaterialIndex()
self.offset_type = fs.readSignedByte()
self.diffuse_offset = fs.readVector(4)
self.specular_offset = fs.readVector(3)
self.shininess_offset = fs.readFloat()
self.ambient_offset = fs.readVector(3)
self.edge_color_offset = fs.readVector(4)
self.edge_size_offset = fs.readFloat()
self.texture_factor = fs.readVector(4)
self.sphere_texture_factor = fs.readVector(4)
self.toon_texture_factor = fs.readVector(4)
def save(self, fs):
fs.writeMaterialIndex(self.index)
fs.writeSignedByte(self.offset_type)
fs.writeVector(self.diffuse_offset)
fs.writeVector(self.specular_offset)
fs.writeFloat(self.shininess_offset)
fs.writeVector(self.ambient_offset)
fs.writeVector(self.edge_color_offset)
fs.writeFloat(self.edge_size_offset)
fs.writeVector(self.texture_factor)
fs.writeVector(self.sphere_texture_factor)
fs.writeVector(self.toon_texture_factor)
class GroupMorph(Morph):
def __init__(self, *args, **kwargs):
Morph.__init__(self, *args, **kwargs)
def type_index(self):
return 0
def load(self, fs):
self.offsets = []
num = fs.readInt()
for i in range(num):
t = GroupMorphOffset()
t.load(fs)
self.offsets.append(t)
class GroupMorphOffset:
def __init__(self):
self.morph = None
self.factor = 0.0
def load(self, fs):
self.morph = fs.readMorphIndex()
self.factor = fs.readFloat()
def save(self, fs):
fs.writeMorphIndex(self.morph)
fs.writeFloat(self.factor)
class Display:
def __init__(self):
self.name = ''
self.name_e = ''
self.isSpecial = False
self.data = []
def __repr__(self):
return '<Display name %s, name_e %s>'%(
self.name,
self.name_e,
)
def load(self, fs):
self.name = fs.readStr()
self.name_e = fs.readStr()
self.isSpecial = (fs.readByte() == 1)
num = fs.readInt()
self.data = []
for i in range(num):
disp_type = fs.readByte()
index = None
if disp_type == 0:
index = fs.readBoneIndex()
elif disp_type == 1:
index = fs.readMorphIndex()
else:
raise Exception('invalid value.')
self.data.append((disp_type, index))
logging.debug('the number of display elements: %d', len(self.data))
def save(self, fs):
fs.writeStr(self.name)
fs.writeStr(self.name_e)
fs.writeByte(int(self.isSpecial))
fs.writeInt(len(self.data))
for disp_type, index in self.data:
fs.writeByte(disp_type)
if disp_type == 0:
fs.writeBoneIndex(index)
elif disp_type == 1:
fs.writeMorphIndex(index)
else:
raise Exception('invalid value.')
class Rigid:
TYPE_SPHERE = 0
TYPE_BOX = 1
TYPE_CAPSULE = 2
MODE_STATIC = 0
MODE_DYNAMIC = 1
MODE_DYNAMIC_BONE = 2
def __init__(self):
self.name = ''
self.name_e = ''
self.bone = None
self.collision_group_number = 0
self.collision_group_mask = 0
self.type = 0
self.size = []
self.location = []
self.rotation = []
self.mass = 1
self.velocity_attenuation = []
self.rotation_attenuation = []
self.bounce = []
self.friction = []
self.mode = 0
def __repr__(self):
return '<Rigid name %s, name_e %s>'%(
self.name,
self.name_e,
)
def load(self, fs):
self.name = fs.readStr()
self.name_e = fs.readStr()
boneIndex = fs.readBoneIndex()
if boneIndex != -1:
self.bone = boneIndex
else:
self.bone = None
self.collision_group_number = fs.readSignedByte()
self.collision_group_mask = fs.readUnsignedShort()
self.type = fs.readSignedByte()
self.size = fs.readVector(3)
self.location = fs.readVector(3)
self.rotation = fs.readVector(3)
self.mass = fs.readFloat()
self.velocity_attenuation = fs.readFloat()
self.rotation_attenuation = fs.readFloat()
self.bounce = fs.readFloat()
self.friction = fs.readFloat()
self.mode = fs.readSignedByte()
def save(self, fs):
fs.writeStr(self.name)
fs.writeStr(self.name_e)
if self.bone is None:
fs.writeBoneIndex(-1)
else:
fs.writeBoneIndex(self.bone)
fs.writeSignedByte(self.collision_group_number)
fs.writeUnsignedShort(self.collision_group_mask)
fs.writeSignedByte(self.type)
fs.writeVector(self.size)
fs.writeVector(self.location)
fs.writeVector(self.rotation)
fs.writeFloat(self.mass)
fs.writeFloat(self.velocity_attenuation)
fs.writeFloat(self.rotation_attenuation)
fs.writeFloat(self.bounce)
fs.writeFloat(self.friction)
fs.writeSignedByte(self.mode)
class Joint:
MODE_SPRING6DOF = 0
def __init__(self):
self.name = ''
self.name_e = ''
self.mode = 0
self.src_rigid = None
self.dest_rigid = None
self.location = []
self.rotation = []
self.maximum_location = []
self.minimum_location = []
self.maximum_rotation = []
self.minimum_rotation = []
self.spring_constant = []
self.spring_rotation_constant = []
def load(self, fs):
self.name = fs.readStr()
self.name_e = fs.readStr()
self.mode = fs.readSignedByte()
self.src_rigid = fs.readRigidIndex()
self.dest_rigid = fs.readRigidIndex()
if self.src_rigid == -1:
self.src_rigid = None
if self.dest_rigid == -1:
self.dest_rigid = None
self.location = fs.readVector(3)
self.rotation = fs.readVector(3)
self.minimum_location = fs.readVector(3)
self.maximum_location = fs.readVector(3)
self.minimum_rotation = fs.readVector(3)
self.maximum_rotation = fs.readVector(3)
self.spring_constant = fs.readVector(3)
self.spring_rotation_constant = fs.readVector(3)
def save(self, fs):
fs.writeStr(self.name)
fs.writeStr(self.name_e)
fs.writeSignedByte(self.mode)
if self.src_rigid is not None:
fs.writeRigidIndex(self.src_rigid)
else:
fs.writeRigidIndex(-1)
if self.dest_rigid is not None:
fs.writeRigidIndex(self.dest_rigid)
else:
fs.writeRigidIndex(-1)
fs.writeVector(self.location)
fs.writeVector(self.rotation)
fs.writeVector(self.minimum_location)
fs.writeVector(self.maximum_location)
fs.writeVector(self.minimum_rotation)
fs.writeVector(self.maximum_rotation)
fs.writeVector(self.spring_constant)
fs.writeVector(self.spring_rotation_constant)
def load(path):
with FileReadStream(path) as fs:
logging.info('****************************************')
logging.info(' mmd_tools.pmx module')
logging.info('----------------------------------------')
logging.info(' Start to load model data form a pmx file')
logging.info(' by the mmd_tools.pmx modlue.')
logging.info('')
header = Header()
header.load(fs)
fs.setHeader(header)
model = Model()
try:
model.load(fs)
except struct.error as e:
logging.error(' * Corrupted file: %s', e)
#raise
logging.info(' Finished loading.')
logging.info('----------------------------------------')
logging.info(' mmd_tools.pmx module')
logging.info('****************************************')
return model
def save(path, model, add_uv_count=0):
with FileWriteStream(path) as fs:
header = Header(model)
header.additional_uvs = max(0, min(4, add_uv_count)) # UV1~UV4
header.save(fs)
fs.setHeader(header)
model.save(fs)
| 04212b8056f9a15f5378bb23655d17235b95548e | [
"Markdown",
"Python"
] | 10 | Python | zhouhang95/blender_mmd_tools | 2cee07602a50747c0839234eebaef9b2c89efb74 | 070df3ddc76bd87439140c3fd6aa1f18ee119335 |
refs/heads/master | <repo_name>YAR-Y1/myprog<file_sep>/program.py
# Я автор этой наисложнейшей программы
print('Моя первая программа!!!')
# rffdsdfafsafsas
print('Hello, Python 3.8')
| ea0a1ba431c27343a38451e0bc3275932cd5fd1f | [
"Python"
] | 1 | Python | YAR-Y1/myprog | 0bd5e6ede9d7d5d880aced85cf69786727c27596 | 947030cf49f3d5f8bfcf504531a4c5a0741666e2 |
refs/heads/master | <file_sep># Legacy Session Manager
A COM+ .NET DLL that provides cross site Session Management for ASP Classic and ASP.NET over Load Balancer
# Installation:
ASP Classic
----------------------------------------------
1- Register the "LegacySessionManager" under "Administrative Tools"->"Component Services".
1-1- Copy "LegacySessionManager.dll" and "LegacySessionManager.dll.config" to a {your_folder_name} folder on the Server which ASP site has access.
1-2- Under "Console Root" -> Computers -> My Computer -> COM+ Applications -> Right Click and "New" -> "Application"
1-3- Select "Create an empty Application". Use "Legacy Session Manager" as Name and Select "Library application" and Click "Next" & "Finish"
1-4- Right click under "Legacy Session Manager"->"Compontents" and select "New"->"Component".
1-5- Select "Install new component(s)" and select "LegacySessionManager.dll" from {your_folder_name} folder, and Click "Next" & "Finish"
2- Add "globalInclude.asp" to your ASP project.
3- Add "LegacySessionManager.dll.config" to your ASP project.
4- Use "<!-- #include file=globalinclude.asp -->" in the beginning of each ASP Classic Page.
5- Make sure you provided proper use account under App Pool to autherize database connection
ASP.NET
----------------------------------------------
1- Add a reference to "LegacySessionManager.dll" in your project.
2- Add "LegacySessionManager.dll.config" to your project.
3- Make sure all of your ASP.NET pages inherits from SessionPage
Inherits="LegacySessionManager.SessionPage"
4- Make sure your ASP.NET application runs under 32bit architecture.
5- Make sure you provided proper user account under App Pool to autherize database connection
SQL Server (Or other databases)
----------------------------------------------
1- Make sure both ASP and ASP.NET machines has access to SQL Server
2- Update the SQL Server connection string in the LegacySessionManager.dll.config file.
<file_sep>using System;
using System.Collections.Generic;
using System.Configuration;
using System.Reflection;
namespace LegacySessionManager
{
internal class ApplicationConfiguration
{
public static string SessionDatabase => ApplicationConfigSetting<string>("SessionDatabase");
public static int SessionTimeout => ApplicationConfigSetting<int>("SessionTimeout",20);
private static T ApplicationConfigSetting<T>(string settingName, object defaultValue = null)
{
var assemLocation = Assembly.GetExecutingAssembly().Location;
var configLocation = assemLocation + ".config";
if (!System.IO.File.Exists(configLocation ))
{
var fileInfo = new System.IO.FileInfo(assemLocation);
configLocation = System.Web.HttpRuntime.AppDomainAppPath + fileInfo.Name + ".config";
}
T value;
try
{
var configMap = new ExeConfigurationFileMap()
{
ExeConfigFilename = configLocation,
};
var appConfig = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
var setting = appConfig.AppSettings.Settings[settingName];
value = (T)Convert.ChangeType(setting.Value, typeof(T));
}
catch (Exception)
{
value = (T)Convert.ChangeType(defaultValue, typeof(T));
}
if (value == null)
throw new NullReferenceException(
$"Missing configuration in the config file (*.config) under <appSettings> tag. \r\nKey = {settingName}. \r\nAssembly Location = {assemLocation}\r\nConfig Location = {configLocation}");
return value;
}
}
}<file_sep>using System.Collections.Specialized;
namespace LegacySessionManager
{
[System.Runtime.InteropServices.ProgId(nameof(LegacySessionManager) + "." + nameof(Session))]
[System.EnterpriseServices.Transaction(System.EnterpriseServices.TransactionOption.NotSupported)]
/// <summary>
/// Current Session
/// </summary>
public class Session : System.EnterpriseServices.ServicedComponent,ISession
{
private string _SessionId = string.Empty;
private HybridDictionary _SessionDictionary = null;
/// <summary>
/// Current Session ID
/// </summary>
public string SessionId
{
get
{
if (string.IsNullOrEmpty(_SessionId))
_SessionId = SessionManager.GenerateNewSessionId();
return _SessionId;
}
set
{
_SessionId = value;
}
}
public string CookieName => SessionManager.SessionCookieName;
/// <summary>
/// Collection of Session Objects
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public object this[string name]
{
get
{
_SessionDictionary = SessionManager.LoadSession(
SessionId,
ApplicationConfiguration.SessionTimeout);
return (object)_SessionDictionary[name.ToLower()];
}
set
{
if (_SessionDictionary == null)
_SessionDictionary = SessionManager.LoadSession(
SessionId,
ApplicationConfiguration.SessionTimeout);
_SessionDictionary[name.ToLower()] = value;
SessionManager.SaveSession(
SessionId,
ApplicationConfiguration.SessionDatabase,
_SessionDictionary);
}
}
/// <summary>
/// Abandon Session
/// </summary>
public void Abandon()
{
_SessionDictionary = new HybridDictionary();
SessionManager.SaveSession(SessionId, ApplicationConfiguration.SessionDatabase, _SessionDictionary);
}
}
}
<file_sep>namespace LegacySessionManager
{
/// <summary>
/// Current Session Interface
/// </summary>
public interface ISession
{
/// <summary>
/// Current Session ID
/// </summary>
string SessionId { get; set; }
string CookieName { get; }
}
}<file_sep>using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Data.Entity.Infrastructure;
namespace LegacySessionManager
{
[DbConfigurationType(typeof(SessionDbConfiguration))]
class SessionContext : DbContext
{
public SessionContext()
: base(ApplicationConfiguration.SessionDatabase)
{
}
public virtual DbSet<SessionState> SessionStates { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<SessionState>()
.Property(e => e.SessionId)
.IsUnicode(false);
}
}
class SessionDbConfiguration : DbConfiguration
{
public SessionDbConfiguration()
{
this.SetDefaultConnectionFactory(new System.Data.Entity.Infrastructure.SqlConnectionFactory());
this.SetProviderServices("System.Data.SqlClient",
System.Data.Entity.SqlServer.SqlProviderServices.Instance);
//SetDefaultConnectionFactory(new LocalDbConnectionFactory("v11.0"));
//SetExecutionStrategy("System.Data.SqlClient",
// () => new System.Data.Entity.Infrastructure.SqlConnectionFactory()) ;
}
}
}
<file_sep>using System;
using System.Xml;
using System.Collections.Specialized;
using System.Web;
using System.Configuration;
using System.Web.SessionState;
namespace LegacySessionManager
{
/// <summary>
/// Session Page for ASP.NET
/// </summary>
public class SessionPage : System.Web.UI.Page
{
private Session _session = null;
/// <summary>
/// Represent Shared Session Object
/// </summary>
public new Session Session {
get
{
if (_session == null)
InitializeSessionManager();
return _session;
}
}
private void InitializeSessionManager()
{
if (_session == null)
{
_session = new Session();
}
var cookie = HttpContext.Current.Request.Cookies[SessionManager.SessionCookieName];
if (cookie == null)
{
cookie = new HttpCookie(SessionManager.SessionCookieName, SessionManager.GenerateNewSessionId());
HttpContext.Current.Response.Cookies.Add(cookie);
}
_session.SessionId = cookie.Value;
}
/// <summary>
/// Raises the System.Web.UI.Control.Init event to initialize the page.
/// </summary>
/// <param name="e">An System.EventArgs that contains the event data.</param>
protected override void OnInit(EventArgs e)
{
InitializeSessionManager();
base.OnInit(e);
}
}
}
<file_sep>namespace LegacySessionManager
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("SessionState")]
public partial class SessionState
{
[Key]
[StringLength(100)]
public string SessionId { get; set; }
[Column(TypeName = "image")]
public byte[] SessionDictionary { get; set; }
public DateTime LastAccessed { get; set; }
}
}
<file_sep>using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
using System.Collections.Specialized;
using System.Linq;
using System.Data.Entity;
namespace LegacySessionManager
{
internal static class SessionManager
{
public const string SessionCookieName = "LegacySessionManagerCookieName";
/// <summary>
/// Load Session from Database
/// </summary>
/// <param name="sessionId"></param>
/// <param name="connectionString"></param>
/// <param name="sessionExpiration"></param>
/// <returns></returns>
public static HybridDictionary LoadSession(string sessionId, int sessionExpiration)
{
using (var context = new SessionContext())
{
var sessionDictionary = new HybridDictionary();
var session = context.SessionStates.Where(s => s.SessionId == sessionId)
.Where(s => DateTime.Now <= DbFunctions.AddMinutes(s.LastAccessed, sessionExpiration))
.FirstOrDefault();
if (session != null)
{
sessionDictionary = Deserialize(session.SessionDictionary);
}
return sessionDictionary;
}
}
/// <summary>
/// Saves the Session into the database
/// </summary>
/// <param name="key"></param>
/// <param name="connectionString"></param>
/// <param name="sessionDictionary"></param>
public static void SaveSession(string key, string connectionString, HybridDictionary sessionDictionary)
{
using (var context = new SessionContext())
{
var session = context.SessionStates.FirstOrDefault(s => s.SessionId == key);
if (session == null)
{
session = new SessionState()
{
SessionId = key,
SessionDictionary = Serialize(sessionDictionary),
LastAccessed = DateTime.Now
};
context.SessionStates.Add(session);
}
else
{
session.SessionDictionary = Serialize(sessionDictionary);
session.LastAccessed = DateTime.Now;
context.Entry(session).Property(x => x.SessionDictionary).IsModified = true;
context.Entry(session).Property(x => x.LastAccessed).IsModified = true;
}
context.SaveChanges();
}
}
/// <summary>
/// Generate New Session ID
/// </summary>
/// <returns></returns>
public static string GenerateNewSessionId()
{
return Guid.NewGuid().ToString();
}
private static byte[] Serialize(HybridDictionary dictionary)
{
Stream stream = null;
byte[] state = null;
try
{
IFormatter formatter = new BinaryFormatter();
stream = new MemoryStream();
formatter.Serialize(stream, dictionary);
state = new byte[stream.Length];
stream.Position = 0;
stream.Read(state, 0, (int) stream.Length);
stream.Close();
}
finally
{
stream?.Close();
}
return state;
}
private static HybridDictionary Deserialize(byte[] binaryDictionary)
{
HybridDictionary dictionary = null;
Stream stream = null;
try
{
stream = new MemoryStream();
stream.Write(binaryDictionary, 0, binaryDictionary.Length);
stream.Position = 0;
IFormatter formatter = new BinaryFormatter();
dictionary = (HybridDictionary) formatter.Deserialize(stream);
}
finally
{
stream?.Close();
}
return dictionary;
}
}
}
<file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LegacySessionManager.UnitTest
{
[TestClass]
public class SessionTest
{
[TestMethod]
public void VerifyCookieName()
{
var session = new Session();
Assert.AreEqual(session.CookieName, "LegacySessionManagerCookieName");
}
[TestMethod]
public void VerifyNewSessionId()
{
var session = new Session();
var sessionId = session.SessionId;
Assert.IsNotNull(sessionId);
Assert.AreNotEqual(sessionId, string.Empty);
}
[TestMethod]
public void VerifySessionValue()
{
var session = new Session();
const string firstKey = "FirstKey";
const string firstValue = "<NAME>";
const string secondKey = "SecondKey";
const string secondValue = "<NAME>";
session[firstKey] = firstValue;
session[secondKey] = secondValue;
Assert.AreEqual(session[firstKey] , firstValue);
Assert.AreEqual(session[secondKey] , secondValue);
}
[TestMethod]
public void SessionAbondon()
{
var session = new Session();
const string firstKey = "FirstKey";
const string firstValue = "<NAME>";
const string secondKey = "SecondKey";
const string secondValue = "<NAME>";
session[firstKey] = firstValue;
session[secondKey] = secondValue;
session.Abandon();
Assert.AreEqual(session[firstKey],null);
Assert.AreEqual(session[secondKey],null);
}
[TestMethod]
public void VerifyCustomSessionId()
{
var sessionId = Guid.NewGuid().ToString();
var session = new Session { SessionId = sessionId };
const string firstKey = "FirstKey";
const string firstValue = "<NAME>";
const string secondKey = "SecondKey";
const string secondValue = "<NAME>";
session[firstKey] = firstValue;
session[secondKey] = secondValue;
Assert.AreEqual(session[firstKey], firstValue);
Assert.AreEqual(session[secondKey], secondValue);
Assert.AreEqual(session.SessionId ,sessionId);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Routing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LegacySessionManager.UnitTest
{
[TestClass]
public class SessionPageTest
{
private static void SetupMocks()
{
HttpContext.Current = new HttpContext(
new HttpRequest("", "http://tempuri.org", ""),
new HttpResponse(new StringWriter())
)
{
User = new GenericPrincipal(
new GenericIdentity("username"),
new string[0]
)
};
// User is logged in
// User is logged out
HttpContext.Current.User = new GenericPrincipal(
new GenericIdentity(String.Empty),
new string[0]
);
}
[TestMethod]
public void CreateSessionPage()
{
SetupMocks();
var sessionPage = new SessionPage();
Assert.IsNotNull(sessionPage.Session);
}
}
}
| b72af0469f1e22048c2944585d85d06f3ef36e97 | [
"Markdown",
"C#"
] | 10 | Markdown | barsham/LegacySessionManager | 48e4ac794adefda4e8a07ab94da06eec55c6a6ec | 2775bd2a941883290e286f4cc4ed5a179dcfef09 |
refs/heads/master | <repo_name>RiskaAndriani/soal1<file_sep>/data-diri.md
Data Diri
===
Nama : <NAME>
NIM : 15515020111080
Kelas : IF-E
<file_sep>/Soal_1/src/soal_1/Mahasiswa.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mahasiswa;
public class Mahasiswa {
private String nama;
private String nim;
private String kelas;
private String absen;
private String fakultas;
public void setNama(String r) {
nama = r;
}
public void setNim(String s) {
nim = s;
}
public void setKelas(String t) {
kelas = t;
}
public void setAbsen(String u) {
absen = u;
}
public void setFakultas(String v) {
fakultas = v;
}
public void displayMessage() {
System.out.println("Nama : " + nama);
System.out.println("NIM : " + nim);
System.out.println("Kelas : " + kelas);
System.out.println("Absen : " + absen);
System.out.println("Fakultas : " + fakultas);
}
}
| 4aa75ba5fa8049a28457643be6a298b78c9e30d9 | [
"Markdown",
"Java"
] | 2 | Markdown | RiskaAndriani/soal1 | d02f7dfc4228a36f0e469b991d5159095feb1df0 | e2c2bfca08a1b59ab6a3516268f722647093a922 |
refs/heads/master | <repo_name>PJ81/colorSort<file_sep>/src/state.ts
import * as Const from "./const.js";
import Column from "./column.js";
class BubbleMove {
from: number;
to: number;
constructor(f: number = -1, t: number = -1) {
this.from = f;
this.to = t;
}
}
export default class State {
id: number;
parentID: number;
moves: BubbleMove[];
steps: BubbleMove[];
pz: Column[];
level: number;
constructor(cols: Column[], l: number, id: number, parent: number) {
this.pz = new Array();
this.moves = new Array();
this.steps = new Array();
this.level = l;
this.id = id;
this.parentID = parent;
for (let i: number = 0; i < cols.length; i++) {
let c: Column = new Column(0);
c.copy(cols[i]);
this.pz.push(c);
}
}
getMoves(): void {
let target: number[] = new Array();
for (let i = 0; i < this.pz.length; i++) {
if (this.pz[i].isEmpty() || !this.pz[i].isFull()) {
target.push(i);
}
}
let a: number;
for (let i = 0; i < this.pz.length; i++) {
a = this.pz[i].peek();
if (a != Const.EMPTY) {
for (let t: number = 0; t < target.length; t++) {
if (this.pz[target[t]].isEmpty()) {
this.moves.push(new BubbleMove(i, target[t]));
} else {
if (a == this.pz[target[t]].peek()) {
this.moves.push(new BubbleMove(i, target[t]));
}
}
}
}
}
}
}<file_sep>/src/undo.ts
import Move from "./move.js";
export default class UndoMove {
undo: Move[];
constructor() {
this.clear();
}
UndoMove(): void {
this.clear();
}
push(m: Move): void {
this.undo.push(m);
}
clear(): void {
this.undo = [];
}
pop(): Move {
if (this.undo.length === 0) return null;
const m = this.undo.pop();
return m;
}
}<file_sep>/src/index.ts
import Game from "./game.js";
import Sound from "./sound.js";
import PuzzleStruct from "./puzzleStruct.js";
import Tube from "./tube.js";
import Point from "./point.js";
import Bubbles from "./bubbles.js";
import Selection from "./selection.js";
import UndoMove from "./undo.js";
import Move from "./move.js";
class Sort extends Game {
sound: any;
actualPz: PuzzleStruct;
nextPz: PuzzleStruct;
built: boolean;
tubes: Tube[];
selection: Selection;
moveCounter: number;
undo: UndoMove;
constructor() {
super();
this.undo = new UndoMove();
this.tubes = [];
this.actualPz = new PuzzleStruct(0, 0, 0, null);
this.nextPz = new PuzzleStruct(0, 0, 0, null);
this.built = false;
this.selection = new Selection();
this.moveCounter = 0;
document.getElementById("undo").addEventListener("mousedown", () => this.undoMove());
document.getElementById("reset").addEventListener("mousedown", () => this.restart());
this.canvas.addEventListener("click", (ev: MouseEvent) => this.click(null, ev));
this.canvas.addEventListener("touchstart", (ev: TouchEvent) => this.click(ev, null));
this.sound = new Sound([
"./snd/blop.mp3", "./snd/clank.mp3", "./snd/click.mp3", "./snd/complete.mp3"
]);
this.res.loadImages(["00.png", "01.png", "02.png", "03.png", "04.png", "05.png", "06.png",
"07.png", "08.png", "09.png", "10.png", "short.png", "long.png"], () => {
const myWorker: Worker = new Worker("./dist/gen.js", { type: 'module' });
myWorker.onmessage = (p) => {
let pz = p.data as PuzzleStruct;
this.actualPz = new PuzzleStruct(pz.maxBubbles, pz.maxColors, pz.solutionLength, pz.colors);
myWorker.terminate();
this.createPuzzle();
this.loop();
}
myWorker.postMessage(true);
});
}
restart(): void {
let m = this.undo.pop();
if (m == null) return;
if (this.selection.bubble) this.selection.bubble.pos.y = this.selection.oldY;
while (m != null) {
this.selection.tube = this.tubes[m.newTubeIndex];
this.selection.bubble = this.selection.tube.getBubble();
this.drop(this.tubes[m.oldTubeIndex], false);
m = this.undo.pop();
}
}
undoMove(): void {
let m: Move = this.undo.pop();
if (m == null) return;
if (this.selection.bubble) this.selection.bubble.pos.y = this.selection.oldY;
this.selection.tube = this.tubes[m.newTubeIndex];
this.selection.bubble = this.selection.tube.getBubble();
this.drop(this.tubes[m.oldTubeIndex], false);
}
check(): boolean {
if (this.selection.bubble) return false;
for (let t = 0; t < this.tubes.length; t++) {
if (!this.tubes[t].sameColor()) return false;
}
return true;
}
tryDrop(tube: Tube): boolean {
if (tube === this.selection.tube || !tube.isFull() && this.selection.tube.peek() === tube.peek()) {
this.drop(tube);
return true;
}
return false;
}
drop(tube: Tube, saveUndo: Boolean = true) {
if (saveUndo && tube != this.selection.tube)
this.undo.push(new Move(tube.index, this.selection.tube.index));
this.selection.tube.removeBubble(this.selection.bubble);
tube.addBubble(this.selection.bubble);
const topPos = 50 + (this.actualPz.maxBubbles === 3 ? 34 : 0);
const j = tube.count();
this.selection.bubble.pos.x = tube.pos.x + 6;
this.selection.bubble.pos.y = topPos + tube.height() - (3 + this.selection.bubble.height() * j + j * 2);
this.selection.tube = null;
this.selection.bubble = null;
this.moveCounter--;
if (this.moveCounter < 0) this.ctx.fillStyle = "#f00";
//sound.clank();
if (this.check()) {
//sound.complete();
//btns.play.visible = true;
this.actualPz.copy(this.nextPz);
this.createPuzzle();
}
}
click(tev: TouchEvent, mev: MouseEvent) {
const pt = new Point();
if (tev) {
pt.set(tev.touches[0].clientX - (tev.srcElement as HTMLCanvasElement).offsetLeft, tev.touches[0].clientY - (tev.srcElement as HTMLCanvasElement).offsetTop);
tev.preventDefault();
} else {
pt.set(mev.clientX - (mev.srcElement as HTMLCanvasElement).offsetLeft, mev.clientY - (mev.srcElement as HTMLCanvasElement).offsetTop);
mev.preventDefault();
}
let t = 0
for (; t < this.tubes.length; t++) {
if (this.tubes[t].inRect(pt)) break;
}
if (t < this.tubes.length) {
const tube = this.tubes[t];
if (!this.selection.bubble && tube.isEmpty()) return;
if (tube.isEmpty() && this.selection.bubble) {
this.drop(tube);
} else {
if (this.selection.bubble) {
this.selection.bubble.pos.y = this.selection.oldY;
if (this.tryDrop(tube)) return;
}
this.selection.bubble = tube.getBubble();
this.selection.tube = tube;
this.selection.oldY = this.selection.bubble.pos.y;
this.selection.bubble.pos.y = tube.pos.y - 16;
//sound.blop();
}
}
}
buildPuzzle() {
this.built = false;
this.moveCounter = this.actualPz.solutionLength;
this.tubes = [];
let cn = 0, x = 0;
const pw = ((this.actualPz.maxColors + (this.actualPz.maxBubbles === 3 ? 1 : 2)) * this.res.images[11].width + 10 * (this.actualPz.maxColors)) / 2;
const ox = this.canvas.width / 2 - pw;
const topPos = 50 + (this.actualPz.maxBubbles === 3 ? 34 : 0);
const pt = new Point(0, topPos), bp = new Point();
for (; x < this.actualPz.maxColors; x++) {
pt.x = 10 * x + this.res.images[11].width * x + ox;
const tube = new Tube(this.actualPz.maxBubbles, this.actualPz.maxBubbles == 3 ? this.res.images[11] : this.res.images[12], pt, x);
for (let z = 0; z < this.actualPz.maxBubbles; z++) {
const c = this.actualPz.colors[z + cn];
if (c < 0) continue;
const j = z + 1;
bp.set(pt.x + 6, topPos + tube.height() - (3 + this.res.images[0].height * j + j * 2));
const bb = new Bubbles(this.res.images[c], c, bp);
tube.addBubble(bb);
}
cn += this.actualPz.maxBubbles;
this.tubes.push(tube);
}
pt.x = 10 * x + this.res.images[11].width * x + ox;
this.tubes.push(new Tube(this.actualPz.maxBubbles, this.actualPz.maxBubbles == 3 ? this.res.images[11] : this.res.images[12], pt, x));
if (this.actualPz.maxBubbles === 4) {
x++;
pt.x = 10 * x + this.res.images[11].width * x + ox;
this.tubes.push(new Tube(this.actualPz.maxBubbles, this.res.images[12], pt, x));
}
}
update(dt: number) {
if (this.built) this.buildPuzzle();
this.tubes.forEach(tube => {
tube.update(dt);
});
}
draw() {
this.tubes.forEach(tube => {
tube.draw(this.ctx);
});
}
createPuzzle(): void {
this.built = true;
this.undo.clear();
const myWorker: Worker = new Worker("./dist/gen.js", { type: 'module' });
myWorker.onmessage = (p) => {
let pz = p.data as PuzzleStruct;
this.nextPz = new PuzzleStruct(pz.maxBubbles, pz.maxColors, pz.solutionLength, pz.colors);
myWorker.terminate();
}
myWorker.postMessage(false);
}
}
if (window.Worker) new Sort()
else console.log("WORKERS ARE NOT AVAILABLE!!!");
<file_sep>/src/move.ts
export default class Move {
newTubeIndex: number;
oldTubeIndex: number;
constructor(nIndex: number = -1, oIndex: number = -1) {
this.newTubeIndex = nIndex;
this.oldTubeIndex = oIndex;
}
}<file_sep>/src/const.ts
export const
EMPTY = -1,
RED = 0,
BLUE = 1,
GREEN = 2,
YELLOW = 3,
MAGENTA = 4,
CYAN = 5,
ORANGE = 6,
POOL = 7,
ROSE = 8,
LILA = 9,
BROWN = 10;<file_sep>/src/tube.ts
import Point from "./point.js";
import Bubble from "./bubbles.js";
export default class Tube {
column: Bubble[];
img: HTMLImageElement;
pos: Point;
index: number;
maxBubbles: number;
rect: Point[];
addBubble: (bubble: Bubble) => void;
inRect: (pt: Point) => boolean;
isEmpty: () => boolean;
height: () => number;
count: () => number;
constructor(mx: number, img: HTMLImageElement, pos: Point, index: number) {
this.pos = new Point(pos.x, pos.y);
this.img = img;
this.column = [];
this.maxBubbles = mx;
this.index = index;
this.rect = [];
this.rect.push(new Point(pos.x, pos.y));
this.rect.push(new Point(pos.x + img.width, pos.y + img.height));
this.height = () => this.img.height;
this.count = () => this.column.length;
this.isEmpty = () => this.column.length < 1;
this.addBubble = (bubble: Bubble) => { this.column.push(bubble); }
this.inRect = (pt: Point): boolean => { return pt.x >= this.rect[0].x && pt.y >= this.rect[0].y && pt.x <= this.rect[1].x && pt.y <= this.rect[1].y; }
}
sameColor(): boolean {
if (this.isEmpty()) return true;
if (this.column.length < this.maxBubbles) return false;
const b = this.column[0];
for (let t = 1; t < this.column.length; t++) {
let c = this.column[t].color;
if (c > -1 && b.color !== c) return false;
}
return true;
}
removeBubble(bb: Bubble) {
for (let z = this.column.length - 1, b = z; b >= 0; b--)
if (this.column[b] === bb) {
this.column.splice(b, 1);
return
}
}
peek(): number {
if (this.column.length < 1) return null;
return this.column[this.column.length - 1].color;
}
isFull(): boolean {
return this.column.length === this.maxBubbles;
}
getBubble(): Bubble {
return this.column[this.column.length - 1];
}
draw(ctx: CanvasRenderingContext2D) {
ctx.drawImage(this.img, this.pos.x, this.pos.y);
this.column.forEach(bubble => {
bubble.draw(ctx);
});
}
update(dt: number) {
this.column.forEach(bubble => {
bubble.update(dt);
});
}
}<file_sep>/src/puzzleStruct.ts
import Column from "./column.js";
export default class PuzzleStruct {
maxColors: number;
maxBubbles: number;
solutionLength: number;
colors: number[];
constructor(mb: number = 0, mc: number = 0, sl: number = 0, clrs: number[]) {
this.maxBubbles = mb;
this.maxColors = mc;
this.solutionLength = sl;
if (clrs) this.colors = [...clrs];
}
copy(p: PuzzleStruct): void {
this.maxColors = p.maxColors;
this.maxBubbles = p.maxBubbles;
this.solutionLength = p.solutionLength;
this.colors = [...p.colors];
}
}<file_sep>/src/column.ts
import * as Const from "./const.js";
export default class Column {
maxBubbles: number;
bubbleCount: number;
bubbleIndex: number;
colors: number[];
constructor(blocks: number) {
this.maxBubbles = blocks;
this.bubbleCount = this.bubbleIndex = 0;
this.colors = new Array(3);
this.colors[0] = this.colors[1] = this.colors[2] = this.colors[3] = Const.EMPTY;
}
isFull(): Boolean {
return this.bubbleCount === this.maxBubbles;
}
isEmpty(): Boolean {
return this.bubbleCount === 0;
}
peek(): number {
if (this.bubbleCount === 0) return Const.EMPTY;
return this.colors[this.bubbleIndex - 1];
}
set(c: number): void {
if (this.bubbleCount === this.maxBubbles) return;
this.colors[this.bubbleIndex] = c;
this.bubbleIndex++;
this.bubbleCount++;
}
get(): number {
if (this.bubbleCount === 0) return Const.EMPTY;
this.bubbleIndex--;
this.bubbleCount--;
let c = this.colors[this.bubbleIndex];
this.colors[this.bubbleIndex] = Const.EMPTY;
return c;
}
getColor(i: number): number {
if (i < this.maxBubbles) return this.colors[i];
return Const.EMPTY;
}
copy(c: Column): void {
this.maxBubbles = c.maxBubbles;
this.bubbleIndex = c.bubbleIndex;
this.bubbleCount = c.bubbleCount;
for (let i = 0; i < 4; i++) {
this.colors[i] = c.colors[i];
}
}
sameColor(): boolean {
if (this.isEmpty()) return false;
const b = this.colors[0];
for (let t = 1; t < this.colors.length; t++) {
let c = this.colors[t];
if (c > -1 && b !== c) return false;
}
return true;
}
getColors(): string {
let s: string = "";
for (let x: number = 0; x < this.maxBubbles; x++) {
switch (this.colors[x]) {
case Const.RED: s += 'R'; break;
case Const.BLUE: s += 'B'; break;
case Const.GREEN: s += 'G'; break;
case Const.YELLOW: s += 'Y'; break;
case Const.MAGENTA: s += 'M'; break;
case Const.CYAN: s += 'C'; break;
case Const.ORANGE: s += 'O'; break;
case Const.POOL: s += 'P'; break;
case Const.ROSE: s += 'S'; break;
case Const.LILA: s += 'L'; break;
case Const.BROWN: s += 'W'; break;
case Const.EMPTY: s += 'E'; break;
default: break;
}
}
return s;
}
}<file_sep>/src/point.ts
export default class Point {
x: number;
y: number;
constructor(x = 0, y = 0) {
this.x;
this.y;
this.set(x, y);
}
set(x: number, y: number) {
this.x = x;
this.y = y;
}
equals(pt: Point): boolean {
return pt.x === this.x && pt.y === this.y;
}
length(): number {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
normalize() {
const len = this.length();
this.x /= len;
this.y /= len;
}
rotate(a: number) {
const cos = Math.cos(a),
sin = Math.sin(a);
this.set(this.x * cos - this.y * sin, this.x * sin + this.y * cos);
}
clamp(min: number, max: number) {
this.x = Math.min(Math.max(this.x, min), max);
this.y = Math.min(Math.max(this.y, min), max);
}
dist(pt: Point): number {
let a = pt.x - this.x,
b = pt.y - this.y;
return Math.sqrt(a * a + b * b);
}
copy(): Point {
return new Point(this.x, this.y);
}
heading(pt: Point): Point {
const h = new Point(pt.x - this.x, pt.y - this.y);
h.normalize();
return h;
}
angleBetween(pt: Point): number {
return Math.atan2(-(pt.y - this.y), -(pt.x - this.x));
//return Math.atan((pt.y - this.y) / (pt.x - this.x));
}
angle(): number {
return Math.atan2(this.y, this.x);
}
magSq(): number {
return this.x * this.x + this.y * this.y;
}
limit(max: number) {
if (this.magSq() > max * max) {
this.normalize();
this.x *= max;
this.y *= max;
}
}
}<file_sep>/src/sound.ts
export default class Sound {
sounds: HTMLAudioElement[];
muted: boolean;
constructor(sndList: string[]) {
this.sounds = new Array(sndList.length);
this.muted = false;
sndList.forEach((src, i) => {
const snd: HTMLAudioElement = new Audio(src);
snd.setAttribute("preload", "auto");
snd.setAttribute("controls", "none");
snd.style.display = "none";
document.body.appendChild(snd);
this.sounds[i] = snd;
});
}
play(snd: number) {
(!this.muted) && this.sounds[snd].play();
}
stop(snd: number) {
this.sounds[snd].pause();
}
mute() {
this.muted = !this.muted;
return this.muted;
}
}<file_sep>/src/solver.ts
import State from "./state.js";
import Column from "./column.js";
export default class Solver {
visited: string[];
parents: State[];
states: State[];
maxBubbles: number;
id: number;
solve(cls: Column[]): number {
this.visited = [];
this.parents = [];
this.states = [];
this.id = 1;
this.states.push(new State(cls, 0, this.id, 0));
this.maxBubbles = cls[0].maxBubbles;
return this.solveDFS();
}
solveDFS(): number {
let st: State = null;
let s = "";
while (this.states.length) {
st = this.states.pop();
if (st.steps.length > 1000) return -1;
s = this.getPuzzle(st.pz);
if (this.isCompleted(s)) {
if (st.steps.length > 30) {
return st.steps.length;//this.traceBack();
}
return -1;
}
this.parents.push(st);
if (this.visited.indexOf(s) === -1) {
this.visited.push(s);
st.getMoves();
if (st.moves.length) this.createStates(st);
if (this.states.length > 4000) break;
}
}
return -1;
}
getPuzzle(pz: Column[]): string {
let p: string = "";
for (let t = 0; t < pz.length; t++) {
p += pz[t].getColors();
}
return p;
}
isCompleted(s: string): Boolean {
for (let i = 0; i < s.length; i += this.maxBubbles) {
for (let j = i + 1; j < i + this.maxBubbles; j++) {
if (s.charAt(i) != s.charAt(j)) return false;
}
}
return true;
}
createStates(st: State): void {
for (let t = 0; t < st.moves.length; t++) {
let cols: Column[] = new Array();
for (let i = 0; i < st.pz.length; i++) {
let c: Column = new Column(0);
c.copy(st.pz[i]);
cols.push(c);
}
cols[st.moves[t].to].set(cols[st.moves[t].from].get());
let s: State = new State(cols, st.level + 1, ++this.id, st.id);
for (let i = 0; i < st.steps.length; i++) {
s.steps.push(st.steps[i]);
}
s.steps.push(st.moves[t]);
this.states.push(s);
}
}
/*traceBack(): number {
let st = this.states.pop();
let steps = 0;
while (true) {
if (st.parentID === 0) break;
st = this.parents.find((e) => e.id === st.parentID);
steps++;
}
return steps;
}*/
}<file_sep>/src/gen.ts
import Creator from "./puzzleGen.js";
onmessage = (e) => {
postMessage(new Creator().createPuzzle(e.data));
}<file_sep>/src/bubbles.ts
import Point from "./point.js";
export default class Bubble {
img: HTMLImageElement;
pos: Point;
color: number;
height: () => number;
constructor(img: HTMLImageElement, color: number, pos: Point) {
this.img = img;
this.color = color;
this.pos = new Point(pos.x, pos.y);
this.height = () => this.img.height;
}
draw(ctx: CanvasRenderingContext2D) {
ctx.drawImage(this.img, this.pos.x, this.pos.y);
}
update(dt: number) {
//
}
}<file_sep>/src/puzzleGen.ts
import Column from "./column.js";
import Solver from "./solver.js";
import PuzzleStruct from "./puzzleStruct.js";
export default class Creator {
columns: Column[];
build(maxBubbles: number, maxColors: number, shuffle: number): PuzzleStruct {
const s = new Solver()
while (true) {
this.columns = [];
for (let x = 0; x < maxColors; x++) {
let c: Column = new Column(maxBubbles);
for (let z = 0; z < maxBubbles; z++) {
c.set(x);
}
this.columns.push(c);
}
this.columns.push(new Column(maxBubbles));
if (maxBubbles == 4) this.columns.push(new Column(maxBubbles));
//this.mix(shuffle);
let z = true;
while (z) {
this.mix(shuffle);
z = false;
for (let r = 0; r < this.columns.length; r++) {
if (this.columns[r].sameColor()) {
z = true;
break;
}
}
}
let sl = s.solve(this.columns);
if (sl > -1) {
const tmp = [];
for (let i = 0; i < this.columns.length; i++) {
for (let j = 0; j < maxBubbles; j++) {
tmp.push(this.columns[i].getColor(j));
}
}
return new PuzzleStruct(maxBubbles, maxColors, sl, tmp);
}
}
}
mix(shuffle: number): void {
let maxBub: number = this.columns[0].maxBubbles,
empCnt: number = maxBub === 4 ? 2 : 1,
colCnt: number = this.columns.length - empCnt, i: number, a: number;
for (let d = 0; d < shuffle; d++) {
for (let e = 0; e < empCnt; e++) {
for (let b = 0; b < maxBub; b++) {
do {
i = Math.floor(Math.random() * colCnt);
//i = this.rnd.rndI(0, colCnt);
} while (this.columns[i].isEmpty());
a = this.columns[i].get();
this.columns[colCnt + e].set(a);
}
}
for (let e = 0; e < empCnt; e++) {
for (let b = 0; b < maxBub; b++) {
a = this.columns[colCnt + e].get();
while (true) {
i = Math.floor(Math.random() * colCnt);
//i = this.rnd.rndI(0, colCnt);
if (!this.columns[i].isFull()) {
this.columns[i].set(a);
break;
}
}
}
}
}
}
createPuzzle(simple: boolean) {
let bubbles: number, columns: number, shuffle: number;
if (simple) {
bubbles = 3;
columns = Math.floor(Math.random() * 5) + 6;
shuffle = 900;
} else {
bubbles = Math.random() > .5 ? 4 : 3;
columns = Math.floor(Math.random() * 5) + 6;
shuffle = 1800;
}
return this.build(bubbles, columns, shuffle);
}
}<file_sep>/src/selection.ts
import Tube from "./tube.js";
import Bubble from "./bubbles.js";
export default class Selection {
bubble: Bubble;
tube: Tube;
oldY: number;
constructor() {
this.bubble = null;
this.oldY = 0;
this.tube = null;
}
} | d68ee7b103f0cd9b75b6cf47ca1af06c148bba47 | [
"TypeScript"
] | 15 | TypeScript | PJ81/colorSort | 4e434ca2f99e89bc45a902a29f9991020d6f3fad | 28ee3b01c71933f8d9903e2807948a7ac27f8048 |
refs/heads/main | <file_sep>const express = require('express');
const app = express();
const SocketIO = require('socket.io');
//setting
app.set('port', process.env.PORT || 3001);
//Middlewares
//app.disable('x-powered-by');
//Server
const server = app.listen(app.get('port'), () => {
console.log('server en el puierto 4001', app.get('port'));
});
//Socket
const io = SocketIO(server, {
cors: {
origin: 'http://192.168.1.56:19006',
methods: ['GET', 'POST']
}
});
io.on('connection', (client) => {
console.log(client.id);
console.log(io.engine.clientsCount);
//=====================================
//ESCUCHANDO NUEVO MIEMBRO Y EMITIENDO
//=====================================
client.on('NewMember', (DataNewMember) => {
client.broadcast.emit('NewMember', DataNewMember);
});
//=====================================
//ESCUCHANDO NUEVO MENSAJE Y EMITIENDO
//=====================================
client.on('NewMessage', (DataNewMessage) => {
console.log(DataNewMessage.strUserName);
client.broadcast.emit('NewMessage', DataNewMessage);
});
//=====================================
//ESCUCHANDO DESCONEXIÓN
//=====================================
client.on('disconnect', (id) => {
console.log(client.id, id, 'me fui');
/* … */
});
});
console.log('Listening for the port 3000');
| 9389036487e32624f7e966ac24d93e8c4a4ef8fc | [
"TypeScript"
] | 1 | TypeScript | whccc/ChatWhcSocket | 9acc9c82d9013c305bd0dde7cfe8c16b09bbeb9e | f33219930f280814080783258c494103a77c2be2 |
refs/heads/master | <file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package np;
/**
*
* @author Sid
*/
public class Value {
public Boolean getValue(){
System.out.println("Must be overriden");
return null;
}
public Interval getInterval(){
System.out.println("Must be overriden");
return null;
}
public String toIneqString(String var){
return "ineq form not implemented";
}
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package np;
/**
*
* @author Sid
*/
public class Assignment {
private String var;
private String op;
private Integer value;
private Integer landmark = null;
Assignment(String s){
/*
*
* Handles xi=ci or xi>0
*/
String tuple[];
tuple = s.split("=");
if (tuple.length <2){
tuple = s.split(">");
}
var = tuple[0];
value = Integer.parseInt(tuple[1].trim());
if (value != 0){
landmark=value;
}
}
Assignment(String s, Integer v){
var =s;
value = v;
}
public String getVar(){ return var;}
public Integer getVal(){ return value;}
public String getOp(){ return op;}
public Integer getLandmark(){ return landmark;}
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package np;
import org.jgrapht.alg.StrongConnectivityInspector;
import org.jgrapht.graph.DirectedMultigraph;
import java.util.*;
/**
*
* @author Sid
*/
public class Trace {
private DirectedMultigraph<String, String> traceGraph;
private Map<String, AbstractState> nodeMap;
private List<Action> actionSequence;
private Domain currentDomain;
private int numNodes = 0;
Trace(Domain aDomain, List<String> actionStrs, ConcreteState c){
traceGraph = new DirectedMultigraph<String, String>(String.class);
nodeMap = new HashMap<String, AbstractState>();
actionSequence = new ArrayList<Action>();
currentDomain = aDomain;
Action tempAxn;
String axnName;
for(String axnArgStr:actionStrs){
axnName = axnArgStr.split(";")[0].trim();
tempAxn = currentDomain.actionMap.get(axnName);
if (tempAxn == null){
System.out.println("Couldn't find action >>"+axnName+"<<");
System.exit(-1);
}
actionSequence.add(tempAxn);
}
this.generateTraceGraph(c);
}
public DirectedMultigraph<String, String> getGraph(){
return traceGraph;
}
public AbstractState getNodeStruc(String node){
return nodeMap.get(node);
}
public String addNode(AbstractState s){
nodeMap.put(Integer.toString(numNodes), s);
traceGraph.addVertex(Integer.toString(numNodes));
numNodes ++;
return Integer.toString(numNodes-1);
}
public String getConsistentNode(ConcreteState c, List<String> nodes){
AbstractState s;
s = c.getAbstraction(currentDomain.getLandmarks());
for (String node:nodes){
if (s.equivalent(this.nodeMap.get(node))){
return node;
}
}
return null;
}
public void generateTraceGraph(ConcreteState s){
ConcreteState concState, prevConcState = s;
AbstractState initAbs=s.getAbstraction(currentDomain.getLandmarks());
AbstractState prevState = initAbs;
Set<AbstractState> nextStates;
List<String> addedNodes= new ArrayList<String>();
String addedNode, prevNode;
Map<AbstractState, Map<String, Value>> diffLabels;
prevNode = this.addNode(prevState);
for (Action axn:actionSequence){
nextStates = axn.applyAction(prevState, currentDomain.getLandmarks());
for (AbstractState state:nextStates){
addedNode = this.addNode(state);
traceGraph.addEdge(prevNode, addedNode, axn.getName()+"_"+
prevNode + "_" + addedNode);
addedNodes.add(addedNode);
}
concState = axn.applyAction(prevConcState);
if ((prevNode = getConsistentNode(concState, addedNodes)) == null){
System.out.println("No matching node found while applying action "+
axn.getName());
//System.out.println("Previous state:");
//System.out.println(this.nodeMap.get(prevNode).toString());
System.out.println("Next concrete states\n");
System.out.println(concState.toString());
System.out.println("Next abstract states:\n");
for (AbstractState state2:nextStates){
System.out.println(state2.toString()+"\n--\n");
}
System.exit(-1);
}
prevConcState = concState;
prevState = this.nodeMap.get(prevNode);
addedNodes.clear();
}
}
public void writeTraceDot(String path){
Utils.writeToFile(Utils.GPToDotString(traceGraph, this.nodeMap, this.currentDomain), path);
}
public String getTraceDot(){
return Utils.GPToDotString(traceGraph, this.nodeMap, this.currentDomain);
}
public String test(String x){
DirectedMultigraph<String, String> g =
new DirectedMultigraph<String, String>(String.class);
x="test";
g.addVertex("1");
g.addVertex("2");
g.addEdge("1", "2", "e");
g.addEdge("1", "2", "e2");
g.addEdge("2", "1", "e2_2_1");
System.out.println(g.toString());
StrongConnectivityInspector gc = new StrongConnectivityInspector<String, String>(g);
System.out.println(gc.stronglyConnectedSets().toString());
return x;
}
}
<file_sep>
We want to study the computation of plans with loops for numeric
planning problems with different forms of observability and
non-determinism in action effects.
Given a set of variables, define the landmarks for a variable as a
finite set of nautral numbers. The set of intervals defined by a set
of landmarks {l1, ..., lk} is the set {[0, l1), [l1, l2), [l2, l3), ... [lk, \infinity) }.
Action effects: [+]x or [-]x for any x in the set of
variables. [+]/[-]x can be interpreted as one of the following:
1. x gets x+1 or x -1 respectively. This is the deterministic case.
2. x gets increased (or decreased) by an epsilon bounded
delta. Non-deterministic but the epsilon-boundedness induces some good
properties.
3. x is possibly incremented or decremented by 1. Also
non-determinstic; if the effect takes place it is always of magnitude 1.
Define [Action]: An action consists of a precondition, defined as a
mapping from each variable in X to a union of intervals defined by the
landmarks for that variable and a set of action effects (at
most one for each variable).
<Define the effect of actions on concrete and abstract states>
Define [Planning Domain]: A planning domain is defined by a set of
variables X, a set of landmarks in N for each variable X, and a set of
actions A. A state in a domain is defined by an assignment of natural
numbers to the variables in X. An abstract state in the domain
associates each variable to one of the intervals defined by its landmarks.
We restrict the landmarks so that a single action application can only
change the value of a variable from an interval to one of its
neighboring intervals. Thus, any two landmarks for a variable must be
at least 2 units apart.
Planning problems:
Partially observable: A planning domain, an initial abstract state and
a goal specified as a mapping from variables to intervals in
N.
Fully observable: A planning domain, an initial state and a goal
specified as a mapping from variables to intervals in N.
Solutions to planning problems:
A policy \pi is a partial mapping from the set of abstract states
to actions such that \pi is defined for all states s that are
reachable under \pi from the initial state s0, but do not satisfy the
goal condition.
Policy test algorithm:
1. Construct the transition graph ts for the policy
2. Let sieve(ts) be the return value of the sieve algorithm on ts
3. If sieve(ts)==terminating and all open nodes of ts are goal nodes,
return "terminating solution"
4. If for every connected component in ts, all open nodes are goal nodes, return
"strong cyclic solution".
5. return "non-solution".
Key Questions:
For each interpretation of [+]/[-],
1. Is the policy test algorithm sound and/or complete for all its return values?
2. Is it possible to develop a sound and complete algorithm for
all return values?
For each interpretation of [+]/[-] and each of the two settings of
observability:
3. Are policies sufficient to represent a solution when an
executable solution exists? [Alternatively, is the
abstract state a sufficient representation of a belief state?]
4. For any policy, is there a set E of sequences of the form
s_1 --a_1--> s_2 --a_2--> ... s_n-1 --a_3-->s_n
where s_i are states //with values in N// and a_i are actions with
deterministic interpretations of [+]/[-], such that the sequences in E
abstract to the solution policy?
//Note: in cases where 4 is true, hybrid search using example plans
that manipulate only natural numbers can be considered to
be "complete" in the sense that there is a finite set of examples
which can be used to create abstract policy for solving the general
problem.
5. Does any problem with an executable solution have a refined policy as a solution?
[[Can also state properties of the abstraction: whether every abstract
transition sequence corresponds to a sequence of concrete transitions.
This is false for deterministic interpretations, but true for the
other two. ]]
1.
For deterministic interpretation of [+]/[-]: Sound but not complete
for "terminating solution" (abacus program result); sound and complete
for the rest.
For epsilon-bounded interpretation of [+]/[-]: sound and complete in
all cases.
For possible increment/decrement interpretation: sound and complete in
all cases ("terminating solution" will never be returned)
2.
For deterministic interpretation of [+]/[-]: Undecidable for the
"Terminating solution case"
For epsilon-bounded interpretation of [+]/[-] the presented algorithm
is the desired solution.
For possible increment/decrement interpretation: terminating policies
with strongly connected components do not exist.
3. If there exists an executable solution by the agent be represented as a
solution policy?
For deterministic interpretation of [+]/[-]:
No.
Counter-example for full observability:
a1 enables a2 enables a3; all add 1 to x1; after a3, x1 in [7,-1) enables goal sequence
o.w. dead end
a4 enables a5; both add 1 to x1; after a5, x1 in [2, 7) enables goal sequence,
o.w. dead end
both a1 and a4 available at start.
Solution policy:
x1 in [4,-1): use a1, a2, a3
x1 in [0,4): use a4, a5
but 4 is not a landmark so this solution cannot be represented as a policy.
Counter-example for partial observability:
Include the action a6 which decrements x in the problem above.
Solution policy:
Given x1 in any interval, apply decrements k times where k is the
upper bound of the interval. This must make x1=0. Now, apply a4 then
a5. This solves the problem described above although the solution
cannot be represented as a policy.
For epsilon-bounded interpretation of [+]/[-]:
Conjecture: true for full observability, and hence for
partial observability. Requires separate proofs for terminating and
strong-cyclic cases.
For possible increment/decrement interpretation:
Conjecture: True for both full and partial observability.
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package np;
import java.util.*;
/**
* Class for representing conditions on variables. Used as preconditions and goal.
*
* @author siddharth
*/
public class Precondition {
private Map<String, Interval> preconMap = new HashMap<String, Interval>();
private Map<String, Boolean> boolMap = new HashMap<String, Boolean>();
Precondition(){}
Precondition(Map<String, Boolean> booleans){
boolMap.putAll(booleans);
}
Precondition(List<Inequality> inequalities){
Map<String, Integer> ubMap = new HashMap<String, Integer>();
Map<String, Integer> lbMap = new HashMap<String, Integer>();
Map<String, Integer> appropriateMap= null;
Set<String> varSet = new HashSet<String>();
int bound = 0;
Boolean tval = null;
for (Inequality ineq: inequalities){
if (ineq.getComparator().equals(">")) {
appropriateMap = lbMap;
bound = ineq.getConstant()+1;
varSet.add(ineq.getVar());
}
else if (ineq.getComparator().equals("<")){
appropriateMap = ubMap;
bound = ineq.getConstant();
varSet.add(ineq.getVar());
}
if (appropriateMap != null && (!appropriateMap.containsKey(ineq.getVar()))){
appropriateMap.put(ineq.getVar(), bound);
}
else if (appropriateMap != null){
System.out.format("Error: two lower bounds for %s in "
+ "precondition: %s\n", ineq.getVar(), ineq.getString());
System.exit(-1);
}
if (ineq.getComparator().equals("=")){
if (!ubMap.containsKey(ineq.getVar()) && !lbMap.containsKey(ineq.getVar())){
ubMap.put(ineq.getVar(), ineq.getConstant()+1);
lbMap.put(ineq.getVar(), ineq.getConstant());
varSet.add(ineq.getVar());
}
else{
System.out.format("Error: two lower bounds for %s in "
+ "precondition: %s\n", ineq.getVar(), ineq.getString());
System.exit(-1);
}
}
if (ineq.isBoolean()){
boolMap.put(ineq.getVar(),ineq.getBoolVal());
}
else{
/* Convert ub, lb lists to intervals */
int ub, lb;
for (String var:varSet){
ub = -1;
lb = 0;
if (ubMap.containsKey(var)){ ub = ubMap.get(var);}
if (lbMap.containsKey(var)){ lb = lbMap.get(var);}
preconMap.put(var, new Interval(lb, ub));
}
}
}
}
public Map<String, Interval> getPreconMap(){
return this.preconMap;
}
public Map<String, Boolean> getBoolMap(){
return this.boolMap;
}
public void addFrom(Precondition precon2){
Map<String, Interval> srcMap = precon2.getPreconMap();
for (String var:srcMap.keySet()){
preconMap.put(var.toString(), new Interval(srcMap.get(var).getLB(),
srcMap.get(var).getUB()));
}
Map<String, Boolean> srcBoolMap = precon2.getBoolMap();
for (String var:srcBoolMap.keySet()){
boolMap.put(var.toString(), srcBoolMap.get(var));
}
}
@Override
public String toString(){
return toString("raw", true, false);
}
public String toPDDLString(){
return toString("PDDL", true, false);
}
public String toPDDLGoalString(){
return toString("PDDL", false, false);
}
public String toPDDLInitString(){
return toString("PDDL", false, true);
}
/*
* Return a readable string form of precons.
*/
public String toString(String mode, boolean qmark, boolean initMode){
String s = new String();
String obj;
if (qmark){
obj = "?o";}
else{
obj = "o1";}
if (mode.equals("raw")){
for (String var:preconMap.keySet()){
s += var + " -> " + preconMap.get(var).toString() +"; ";
}
for (String var:boolMap.keySet()){
s += var + " -> " + boolMap.get(var).toString() +"; ";
}
s += "\n";
}
Integer lb, ub;
if (mode.equals("PDDL")){
for (String var:preconMap.keySet()){
lb = preconMap.get(var).getLB();
ub = preconMap.get(var).getUB();
if (lb == ub-1) {
s += "(= (" + var + " " + obj + ") "+ lb.toString() +") ";
}
else{
s += "(>= (" + var + " " + obj + ") "+ lb.toString()+ ") ";
if (ub!=-1){
s += "(< (" + var + " " + obj + ") " + ub.toString() + ") ";
}
}
}
String terminator, negatedVal;
for (String var:this.boolMap.keySet()){
terminator = "";
negatedVal = "";
if (!this.boolMap.get(var)){
if (!initMode){
negatedVal = "(not ";
terminator = ")";
}else{
continue;}
}
s += negatedVal + "(" + var + " " + obj + ")" + terminator;
}
if (!initMode){
s="(and " + s + ")";}
}
return s;
}
/*
* Test if the given state's vars satisfy the precons
*/
public boolean satisfied(AbstractState s){
Boolean satisfied = true;
for (String var:preconMap.keySet()){
if (!preconMap.get(var).greaterOrEqualTo(s.getInterval(var))){
satisfied = false;
break;
}
}
for (String var:this.boolMap.keySet()){
satisfied = (this.boolMap.get(var) == s.getBoolValues().get(var));
if (!satisfied) {
break;
}
}
return satisfied;
}
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package np;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
*
* @author siddharth
*
* The main class.
*/
public class NP {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws java.io.IOException, InterruptedException{
System.out.print("Enter input filename (in GNPFinal/inputs/): ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String inputFile = "quad_hall.txt";
//String inputFile = "laundry_basket.txt";
// try {
// inputFile = br.readLine();
// } catch (IOException e) {
// System.out.println("Error!");
// System.exit(1);
// }
Domain myDomain = NPinput.getDomainFromFile("inputs/"+inputFile);
System.out.format("%s\n\n",myDomain.toString());
HybridSearch searchObj = new HybridSearch(myDomain);
searchObj.doSearch("outputs/output");
}
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package np;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
*Extends the PlannerOutput class with specific methods for extracting
* plan actions, and begin/end markers.
*
* @author Sid
*/
public class FFOutput extends PlannerOutput {
FFOutput(String output){
super(output);
}
@Override
public String getBeginMarker(){
return "follows\n\nstep ";
}
@Override
public String getEndMarker(){
return "time spent";
}
@Override
public List<String> getPlanActions(){
List<String> planActions = new ArrayList<String>();
ArrayList<String> lines = new ArrayList<String>(Arrays.asList(
this.getPlanText(getBeginMarker(), getEndMarker()).split("\n")));
for (String line: lines){
System.out.println("Line >>"+line+"<<");
String[] indexAxn = line.split(":");
if (indexAxn.length == 1) {
System.out.println("Found no `:'. Stopping search for actions.");
break;
}
planActions.add(indexAxn[1].trim().replaceFirst(" ", "; ").toLowerCase());
}
System.out.println("Extracted plan with " +
Integer.toString(planActions.size()) + " actions.\n");
return planActions;
}
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package np;
/**
*
* @author Sid
*/
public class Interval extends Value {
/*
* Intervals will be closed below and open above.
*/
private Integer lowerBound = 0;
private Integer upperBound = 0; //-1 indicates infinity
Interval(int lb, int ub){
lowerBound = lb;
upperBound = ub;
}
public Interval getInterval(){
return new Interval(lowerBound,upperBound);
}
public int getLB(){
return lowerBound;
}
public int getUB(){
return upperBound;
}
public Interval getNeighboringInterval(LandmarkBunch lbunch, int delta, String var){
int newLB = lbunch.getNeighboringLandmark(var, lowerBound, delta);
int newUB = lbunch.getNeighboringLandmark(var, upperBound, delta);
if ((newLB == lowerBound) || (newUB == upperBound)){
return this;
}
return new Interval(newLB, newUB);
}
@Override
public String toString(){
return "["+ lowerBound.toString() + ", " + upperBound.toString() + ")";
}
public String toIneqString(String var){
String ubString = upperBound.toString();
if (ubString.equals("-1")){
ubString = "INF";
}
return lowerBound.toString() + " <= " + var + " < " + ubString;
}
public Boolean greaterOrEqualTo(Interval v){
boolean lowerBoundOK = (lowerBound <= v.getLB());
boolean upperBoundOK;
int vUB = v.getUB();
if (upperBound==-1){
upperBoundOK = true;
}
else {
if (vUB==-1){
upperBoundOK = false;
}
else{
upperBoundOK = (upperBound >= vUB);
}
}
/* if ((lowerBound <= v.getLB()) && ( (upperBound >= v.getUB())||(upperBound ==-1))){*/
if (lowerBoundOK && upperBoundOK){
return true;
}
return false;
}
public Boolean equals(Interval i2){
return ((this.getLB() == i2.getLB()) && (this.getUB() == i2.getUB()));
}
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package np;
import java.util.List;
/**
*
* An abstract class denoting what every planner output must have:
* the output string. Different planner-specific refinements set up the begin
* and end markers as well as methods to get the plan actions.
*
*
*
* * Never use directly. Use a class like FFOutput instead.
*
* @author Sid
*/
abstract class PlannerOutput {
private String outputString;
PlannerOutput(String text){
outputString = text;
}
public String getBeginMarker(){
return "";
}
public String getEndMarker(){
return "";
}
/*
* Return the substring between begin and end markers. To be used
* in all planner-specific classes.
*
*/
public String getPlanText(String begin, String end){
String plan;
String planBeginMarker = begin;
String planEndMarker = end;
int planBeginOffset = outputString.indexOf(getBeginMarker())+getBeginMarker().length()-1;
int planEndOffset = outputString.indexOf(getEndMarker());
plan = outputString.substring(planBeginOffset, planEndOffset);
return plan;
}
public abstract List<String> getPlanActions();
/**
* @return the outputString
*/
public String getOutputString() {
return outputString;
}
/**
* @param outputString the outputString to set
*/
public void setOutputString(String outputString) {
this.outputString = outputString;
}
}
| f58eac3fc1af045c3f74972f75cbfb2ccb2f5857 | [
"Java",
"Text"
] | 9 | Java | sidsrivast/GNP | 22ae883820cf6a1f90d318e7937a33730fb0aa8c | e75fc9f4d7980faf50c828b3cf83087ac385fee5 |
refs/heads/master | <repo_name>marianalx/CSharpDB<file_sep>/RentACar/FormAddCar.cs
using MySql.Data.MySqlClient;
using RentACar.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RentACar
{
public partial class FormAddCar : Form
{
//pole do przekazywania ID rekordu
public int RowId = 0;
public FormAddCar()
{
InitializeComponent();
}
private void FormAddCar_Load(object sender, EventArgs e)
{
LoadDictionaryData();
numYear.Maximum = DateTime.Now.Year; //ograniczenie do biezacego roku
if (RowId>0)
{
// do refaktoryzacji
String sql = @"
SELECT c.*, m.brand_id
FROM cars c , car_models m
WHERE c.id = {0} AND c.model_id = m.id";
sql = String.Format(sql, RowId);
MySqlCommand cmd = new MySqlCommand(sql, GlobalData.connection);
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
numEngine.Value = Convert.ToInt32( reader["engine"] );
numYear.Value = Convert.ToInt32(reader["manufacturer_year"]);
tbRegPlate.Text = reader["registration_plate"].ToString();
cbFuel.SelectedIndex = cbFuel.Items.IndexOf(reader["fuel"].ToString());
cbTypes.SelectedValue = reader["type_id"];
cbBrands.SelectedValue = reader["brand_id"];
cbModels.SelectedValue = reader["model_id"];
cbModels.Enabled = true;
if (!(reader["image"] is DBNull))
{
byte[] b = (byte[])reader["image"];
using(var ms = new MemoryStream(b))
{
picCar.Image = Image.FromStream(ms);
}
}
reader.Close();
}
}
// tunning GUI
if (RowId>0)
{
btnOK.Text = "Zapisz zmiany";
this.Text = "Edycja pojazdu";
} else
{
btnOK.Text = "Dodaj nowy";
this.Text = "Nowy pojazd";
}
}
BindingSource bsBrands = new BindingSource();
BindingSource bsModels = new BindingSource();
BindingSource bsTypes = new BindingSource();
private void LoadDictionaryData()
{
try
{
// ładowanie słownika producentów
MySqlDataAdapter adapter = new MySqlDataAdapter();
String sql = "select id, name from car_brands order by name";
adapter.SelectCommand = new MySqlCommand(sql, GlobalData.connection);
DataTable dt = new DataTable();
adapter.Fill(dt);
bsBrands.DataSource = dt;
cbBrands.DataSource = bsBrands;
cbBrands.DisplayMember = "name";
cbBrands.ValueMember = "id";
cbBrands.SelectedIndex = -1;
// podpinanie oblsugi zdarzenia
cbBrands.SelectedIndexChanged += CbBrands_SelectedIndexChanged;
// ładowanie słownika modeli
adapter = new MySqlDataAdapter();
sql = "select id, brand_id, name from car_models order BY brand_id asc, NAME asc";
adapter.SelectCommand = new MySqlCommand(sql, GlobalData.connection);
dt = new DataTable();
adapter.Fill(dt);
bsModels.DataSource = dt;
cbModels.DataSource = bsModels;
cbModels.DisplayMember = "name";
cbModels.ValueMember = "id";
cbModels.SelectedIndex = -1;
cbModels.Enabled = false;
// ładowanie słownika typów własnosci
adapter = new MySqlDataAdapter();
sql = "select id, name from car_types order BY NAME asc";
adapter.SelectCommand = new MySqlCommand(sql, GlobalData.connection);
dt = new DataTable();
adapter.Fill(dt);
bsTypes.DataSource = dt;
cbTypes.DataSource = bsTypes;
cbTypes.DisplayMember = "name";
cbTypes.ValueMember = "id";
cbTypes.SelectedIndex = -1;
} catch (Exception exc)
{
DialogHelper.Error(exc.Message);
}
}
private void CbBrands_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbBrands.SelectedIndex>-1)
{
bsModels.Filter = "brand_id = "+ cbBrands.SelectedValue;
cbModels.DataSource = bsModels;
cbModels.SelectedIndex = -1;
cbModels.Enabled = true;
}
}
private void tbRegPlate_KeyPress(object sender, KeyPressEventArgs e)
{
e.KeyChar = Char.ToUpper(e.KeyChar);
}
private void btnRemovePic_Click(object sender, EventArgs e)
{
if (picCar.Image != null)
{
picCar.Image.Dispose();
picCar.Image = null; //dobra praktyka
pictureFileName = null;
}
}
private String pictureFileName = null;
private void btnInsertPic_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Pliki graficzne|*.jpg;*.png;*.jpeg;*.gif;*.bmp";
if (dialog.ShowDialog()==DialogResult.OK)
{
// ładujemy grafikę do komponentu
picCar.Image = new Bitmap(dialog.FileName);
pictureFileName = dialog.FileName;
}
}
private void btnOK_Click(object sender, EventArgs e)
{
if (ValidateData())
{
// zapis do bazy
SaveData();
}
}
private void SaveData()
{
try
{
String sql = "";
if (RowId > 0)
{
// update SQL
sql = @" UPDATE cars SET
model_id=@model_id, type_id=@type_id, registration_plate=@reg_plate,
engine=@engine, manufacturer_year=@year, fuel=@fuel, image=@image
WHERE
id = @row_id
";
}
else
{
sql = @"
INSERT INTO cars
(model_id, type_id, registration_plate, engine, manufacturer_year,
image, fuel, avail )
VALUES
(@model_id, @type_id, @reg_plate, @engine, @year, @image, @fuel, 1)
";
}
MySqlCommand cmd = new MySqlCommand(sql, GlobalData.connection);
cmd.Parameters.Add("@model_id", MySqlDbType.Int32);
cmd.Parameters.Add("@type_id", MySqlDbType.Int32);
cmd.Parameters.Add("@reg_plate", MySqlDbType.VarChar, 50);
cmd.Parameters.Add("@engine", MySqlDbType.Int32);
cmd.Parameters.Add("@year", MySqlDbType.Int32);
cmd.Parameters.Add("@fuel", MySqlDbType.VarChar, 10);
cmd.Parameters.Add("@image", MySqlDbType.MediumBlob);
cmd.Parameters.Add("@row_id", MySqlDbType.Int32);
cmd.Parameters["@model_id"].Value = cbModels.SelectedValue;
cmd.Parameters["@type_id"].Value = cbTypes.SelectedValue;
cmd.Parameters["@reg_plate"].Value = tbRegPlate.Text.Trim();
cmd.Parameters["@year"].Value = numYear.Value;
cmd.Parameters["@engine"].Value = numEngine.Value;
cmd.Parameters["@fuel"].Value = cbFuel.SelectedItem;
cmd.Parameters["@row_id"].Value = RowId;
if (pictureFileName!=null)
{
cmd.Parameters["@image"].Value = File.ReadAllBytes(pictureFileName);
} else
{
cmd.Parameters["@image"].Value = null;
}
cmd.ExecuteNonQuery();
DialogResult = DialogResult.OK;
Close();
} catch (Exception exc)
{
DialogHelper.Error(exc.Message);
}
}
private bool ValidateData()
{
if (cbBrands.SelectedIndex > -1 &&
cbModels.SelectedIndex > -1 &&
cbTypes.SelectedIndex > -1 &&
cbFuel.SelectedIndex>-1 &&
tbRegPlate.Text.Replace(" ","").Length>0 )
{
return true;
} else
{
DialogHelper.Error("Sprawdź formularz");
return false;
}
}
}
}
| b061337a5e16a499dc403334ad57ab47723d4d38 | [
"C#"
] | 1 | C# | marianalx/CSharpDB | c8c69be7c7df3c33ab820c6336c5bb751e4ffba2 | 29a569712c62e1b189d63364c1da5360416007ee |
refs/heads/master | <repo_name>hartmjo/Lab5<file_sep>/Main.java
import java.util.*;
class Main {
public static void main(String[] args) {
Student student1 = new Student();
Student student2 = new Student();
ArrayList<Double> gpas = new ArrayList<Double>();
double sum =0;
student1.setName("<NAME>");
student1.setGPA(4.0);
student1.setMajor("Electrical Engineering");
gpas.add(student1.gpa);
student2.setName("<NAME>");
student2.setGPA(3.2);
student2.setMajor("Information Systems");
gpas.add(student2.gpa);
for(double i : gpas){
sum = sum + i;
}
student1.print();
student2.print();
System.out.println("The Average GPA is" + sum/gpas.size());
}
} | e6e39820df87334b0880868db9f62eb4f229d04b | [
"Java"
] | 1 | Java | hartmjo/Lab5 | 6e4b2a42dddd521625c03d62b7fba94e906bf019 | c9faab6ba3d982f5a7e7faf01306e96de5ef392a |
refs/heads/master | <file_sep>import unittest
from server import app
from model import example_data, connect_to_db, db, User, Log, Location, Type, LocationType
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
import helper
class UnitTest(unittest.TestCase):
def test_format_time(self):
test_time_1 = helper.format_time([u'12:00', u'AM'])
test_time_2 = helper.format_time([u'2:00', u'PM'])
self.assertEqual(test_time_1, '00:00')
self.assertEqual(test_time_2, '14:00')
def test_check_overlap_times(self):
test_times_1 = helper.check_overlap_times([('15:00', '16:00')], '12:00',
'14:30')
test_times_2 = helper.check_overlap_times(['12:00', '14:00'], '10:00',
'17:00')
self.assertNotEqual(test_times_1, 'False')
self.assertEqual(test_times_2, 'False')
def test_format_date(self):
# test_date_1 = helper.format_date({'dateRequest': 'datepicker'})
test_date_2 = helper.format_date({'dateRequest': 'next',
'showDate': 'Sunday, May 29, 2016'})
self.assertEqual(test_date_2, '2016-05-30')
class ProjectTestDatabase(unittest.TestCase):
"""Tests that use the database"""
def setUp(self):
# Connect to test database
connect_to_db(app, "postgresql:///testdb")
# Create tables and add sample data
db.create_all()
example_data()
# self.client = app.test_client()
# app.config['TESTING'] = True
# app.config['SECRET_KEY'] = 'ABC'
def tearDown(self):
db.session.close()
db.drop_all()
def test_check_login(self):
login_return_1 = helper.check_login('bbuild', 'password')
login_return_2 = helper.check_login('bbuilder', 'hi')
self.assertEqual(login_return_1, 'True')
self.assertEqual(login_return_2, 'False')
def test_check_username(self):
username_test_1 = helper.check_username_exists('bbuild')
self.assertEqual(username_test_1, 'True')
self.assertEqual(helper.check_username_exists('bbuilder'), 'False')
if __name__ == '__main__':
unittest.main()<file_sep>blinker==1.4
coverage==4.1
Flask==0.10.1
Flask-DebugToolbar==0.10.0
Flask-SQLAlchemy==2.1
itsdangerous==0.24
Jinja2==2.8
MarkupSafe==0.23
psycopg2==2.6.1
selenium==2.53.2
SQLAlchemy==1.0.12
Werkzeug==0.11.9
<file_sep>from flask import Flask, render_template, redirect, request, flash, session, jsonify
from flask_debugtoolbar import DebugToolbarExtension
from jinja2 import StrictUndefined
from model import connect_to_db, db, User, Log, Location, Type, LocationType
from datetime import datetime, timedelta
import os
from sqlalchemy import or_, func, desc, update
import helper
app = Flask(__name__)
app.secret_key = 'ABC'
def check_login(username, password):
"""Check if username and password match credentials in database"""
try:
# if username exists in db, check to see if user-entered username and
# passwords match. If so, store username and home lat/long in session
user = User.query.filter(User.username == username).one()
if user.username == username and user.password == <PASSWORD>:
return 'True'
else:
return 'False'
except:
print "I don't know what's happening"
return 'False'
def check_username_exists(username):
try:
User.query.filter(User.username == username).one()
return 'True'
except:
return 'False'
def create_user(args):
fname = args.get('fname')
lname = args.get('lname')
email = args.get('email')
username = args.get('createUsername')
password = args.get('pw')
date_created = datetime.now()
# create new field in User table
user = User(email=email, username=username,
password=<PASSWORD>, fname=fname, lname=lname,
date_created=date_created)
return user
def format_time(log_time):
log_time_hrs = (log_time[0].split(':'))[0]
log_time_mins = (log_time[0].split(':'))[1]
if log_time[1] == 'PM':
if log_time_hrs != '12':
log_time_hrs = int(log_time_hrs) + 12
else:
if log_time_hrs not in ['10', '11', '12']:
log_time_hrs = '0'+log_time_hrs
if log_time_hrs == '12' and log_time[1] == 'AM':
log_time_hrs = '00'
log_time = '{}:{}'.format(log_time_hrs, log_time_mins)
print type(log_time)
return log_time
def format_date(args):
# if user selects date from dropdown calendar, select logs from that date
if args.get('dateRequest') == 'datepicker':
date_of_logs = datetime.strptime(args.get('showDate')[0:15], '%a %b %d %Y').strftime('%Y-%m-%d')
# elif user clicks for previous day's info, calculate previous day's date
elif args.get('dateRequest') == 'previous':
d = args.get('showDate')
current_date = datetime.strptime(d, '%A, %B %d, %Y')
previous_day = current_date - timedelta(days=1)
date_of_logs = previous_day.strftime('%Y-%m-%d')
# elif user clicks for next day's info, calculate next day's date
elif args.get('dateRequest') == 'next':
d = args.get('showDate')
current_date = datetime.strptime(d, '%A, %B %d, %Y')
next_day = current_date + timedelta(days=1)
date_of_logs = next_day.strftime('%Y-%m-%d')
return date_of_logs
def check_overlap_times(logged_times, start_time, end_time):
for start_end in logged_times:
# if there are any overlapping times in entries for the day, return False
if ((start_end[0] <= start_time <= start_end[1]) or (start_end[0] <= end_time <= start_end[1])):
return 'False'
elif ((start_time <= start_end[0]) and (end_time >= start_end[1])):
return 'False'
return
def format_place_types(l_type):
l_type = l_type.replace('[', '')
l_type = l_type.replace(']', '')
l_type = l_type.replace('"', '')
l_type = l_type.replace('_', ' ')
return l_type
def add_location(location):
# if this location already exists, don't do anything additional to db
try:
Location.query.filter(Location.location_id == location.location_id).one()
# if location does not exist in location table, add new field
except:
db.session.add(location)
db.session.commit()
return
if __name__ == '__main__':
connect_to_db(app)
app.debug = True<file_sep># Locography
Locography is a location-based journal that creates concrete views of where users have spent their time.

### Table of Contents
- [Technologies Used](#tech-used)
- [How To Run Locally](#run-local)
- [Features](#features)
## <a name="tech-used"></a>Technologies Used
- Python
- Flask
- PostgresSQL
- Javascript/jQuery
- AJAX/JSON
- Jinja2
- Chart.js
- Bootstrap
- Google Maps API
- Google Locations API
Dependencies are listed in requirements.txt
## <a name="run-local"></a>How To Run Locally
Locography is not deployed.
- Create a python virtual environment and install all dependencies
```sh
$ pip install -r requirements.txt
```
- Have PostgreSQL running. Create a database called _locations_:
```sh
$ psql
# CREATE DATABASE locations
```
- Create the tables in the database:
```sh
$ python model.py
```
- Start Flask server:
```sh
$ python server.py
```
- Access the web app at localhost:5000
## <a name='features'></a>Features
- Account setup and user login
- Add a log/location (uses Google Locations API to collect information about the location -- lat, long, address, phone, website -- and save it in the locations database)
- View logs:
* On home page load, browser receives a JSON object of any logs a user has already created for the current date.
* User can scroll through day by day (using << and >> buttons) or select a date on the dropdown datepicker menu to jump to that specific day's logs.
* Ways to interact with logs on homepage:

- View a directory of all locations a user has visited and search directory
* View details about each location, including any logs about that location
- Edit username and home location
Author: [<NAME>](https://www.linkedin.com/in/sarahstringer)<file_sep>import unittest
from server import app
from model import connect_to_db, db, User, Log, Location, Type, LocationType
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
import helper
##############################
# browser = webdriver.Chrome('/Users/Sarah/Downloads/chromedriver')
# browser.get('http://localhost:5000')
# test if browser title matches assumed page title
# assert browser.title == 'Project', 'Browser title was ' + browser.title
class ProjectTestFunctional(unittest.TestCase):
"""Tests for Hackbright Project"""
def setUp(self):
self.browser = webdriver.Chrome('/Users/Sarah/Downloads/chromedriver')
self.browser.implicitly_wait(3)
def tearDown(self):
self.browser.quit()
# User visits homepage and is greeted with homepage.
# def test_homepage_title(self):
# """Test for correct browser page title"""
# self.browser.get('http://localhost:5000')
# self.assertEqual('Project', self.browser.title)
# User does not have an account yet and decides to create one.
def test_signup_form(self):
self.browser.get('http://localhost:5000')
lnk = self.browser.find_element_by_id('signupLink')
lnk.click()
try:
element = self.browser.find_element_by_id('signup')
if element.is_displayed():
print 'Element found on page'
else:
self.fail('Element not on page')
hidden_element = self.browser.find_element_by_id('login-form')
if hidden_element.is_displayed():
self.fail('Element should not display on page')
else:
print 'Element hidden'
except NoSuchElementException:
print 'Not an element exception'
return False
class ProjectTestUnit(unittest.TestCase):
"""Unit tests for Hackbright Project"""
def setUp(self):
app.config['TESTING'] = True
app.config['SECRET_KEY'] = 'key'
self.client = app.test_client()
def test_homepage(self):
"""Test to see if home page text appears"""
result = self.client.get('/')
self.assertIn('Go do the things', result.data)
class ProjectTestDatabase(unittest.TestCase):
"""Tests that use the database"""
def setUp(self):
self.client = app.test_client()
app.config['TESTING'] = True
connect_to_db(app, "postgresql:///testdb")
app.config['SECRET_KEY'] = 'ABC'
def tearDown(self):
db.session.close()
def test_login(self):
"""test if user can login and see profile page info"""
with self.client as c:
with c.session_transaction() as sess:
sess['user'] = 'bbuilder'
sess['home_lat'] = '37.794434'
sess['home_long'] = '-122.39520160000001'
result = c.get('/', follow_redirects=True)
self.assertIn('Welcome back', result.data)
if __name__ == "__main__":
unittest.main()<file_sep>"""Hackbright Project"""
from flask import Flask, render_template, redirect, request, flash, session, jsonify
from flask_debugtoolbar import DebugToolbarExtension
from jinja2 import StrictUndefined
from model import connect_to_db, db, User, Log, Location, Type, LocationType
from datetime import datetime, timedelta
import os
from sqlalchemy import or_, func, desc, update
import helper
app = Flask(__name__)
#for debug toolbar
app.secret_key = 'ABC'
# create global API key for google maps API (*currently not using key in app*)
google_api = os.environ['GOOGLE_LOC_API']
global google_location_api
google_location_api = "https://maps.googleapis.com/maps/api/js?key="+google_api+"&libraries=places&callback=initialize"
app.jinja_env.undefined = StrictUndefined
@app.context_processor
def inject_google_api():
"""Create global variable to use in base html for google map API credentials"""
return dict(google_location_api=google_location_api)
@app.route('/')
def homepage():
"""Render homepage template if no user in session, redirect user to profile if logged in"""
#if user in session, redirect to profile page
try:
session['user']
return redirect('/profile/'+session['user'])
#otherwise, render the homepage.html template
except:
return render_template('homepage.html')
@app.route('/check-login', methods=['POST'])
def check_login():
"""Check if username and password match user credentials in database"""
# # collect username and password from post request
username = request.form.get('username')
password = request.form.get('<PASSWORD>')
if helper.check_login(username, password) == 'True':
# add user info to session
user = User.query.filter(User.username == username).one()
session['user'] = username
session['home_lat'] = user.home_lat
session['home_long'] = user.home_long
return 'True'
else:
return 'False'
@app.route('/logout')
def logout():
"""Delete username from session, flash logout message and redirect to homepage"""
flash('Successfully logged out')
session.pop('user')
return redirect('/')
@app.route('/create-profile', methods=['POST'])
def create_profile():
"""Create profile for user"""
# receive information via POST request from signup form
form_args = request.form
user = helper.create_user(form_args)
# add and commit
db.session.add(user)
db.session.commit()
# store username in session
session['user'] = user.username
return render_template('profile.html', fname=user.fname, lname=user.lname,
username=user.username)
@app.route('/check-username', methods=['POST'])
def check_username():
"""Check to see if username is already in database"""
username = request.form.get('username')
return helper.check_username_exists(username)
@app.route('/set-home', methods=['POST'])
def set_home():
"""Set user home location"""
home_lat = request.form.get('lat')
home_long = request.form.get('long')
home_address = request.form.get('address')
home_id = request.form.get('home_id')
# retrieve user from User table
user = User.query.filter(User.username == session['user']).one()
# set user attributes
setattr(user, 'home_lat', home_lat)
setattr(user, 'home_long', home_long)
setattr(user, 'home_address', home_address)
setattr(user, 'home_id', home_id)
# commit changes to user
db.session.commit()
# add home longitude and latitude to session
session['home_lat'] = home_lat
session['home_long'] = home_long
return "True"
@app.route('/profile/<username>')
def profile_page(username):
"""Render profile page for specific user"""
# retrieve user object from database to pass to profile page template
user = User.query.filter(User.username == username).one()
return render_template('profile_page.html',
username=username,
user=user)
@app.route('/set-date', methods=['POST'])
def set_date():
"""Get date of the logs the user is currently viewing, store in session"""
# if there is a value for "date" in the post data, retrieve that
if request.form.get('date'):
date = request.form.get('date')
# otherwise, use today's date
else:
date = datetime.now().strftime('%A, %B %d, %Y')
# format date
date = datetime.strptime(date, '%A, %B %d, %Y').strftime('%m/%d/%Y')
# store that date in session info
session['date'] = date
return 'true'
@app.route('/profile/<username>/add-location')
def add_location(username):
"""Render template for page to add a location/log"""
user = User.query.filter(User.username == username).one()
return render_template('add_location.html', user=user)
@app.route('/profile/<username>/view-locations')
def view_locations(username):
"""View a user's directory of locations they've visited"""
return render_template('view_locations.html')
@app.route('/log-new-location', methods=['POST'])
def log_new_location():
"""Create new log in database from user entry"""
latitude = request.form.get('lat')
longitude = request.form.get('long')
address = request.form.get('address')
location_id = request.form.get('location_id')
name = request.form.get('name')
title = request.form.get('title')
arrived = request.form.get('arrival')
departed = request.form.get('departure')
visit_date = datetime.strptime(request.form.get('date')[0:15], '%a %b %d %Y').strftime('%Y-%m-%d')
created_at = datetime.now()
comments = request.form.get('comments')
place_types = request.form.get('place_types').split(',')
website = request.form.get('website')
if website == None:
website = 'N/A'
phone = request.form.get('phone')
if phone == None:
phone = 'N/A'
# retrieve user from db
user = User.query.filter(User.username == session['user']).one()
# # create new location object
location = Location(location_id=location_id, latitude=latitude,
longitude=longitude, address=address, name=name,
website=website, phone=phone)
helper.add_location(location)
# Clean up the string list of establishment types
for l_type in place_types:
l_type = helper.format_place_types(l_type)
try:
Type.query.filter(Type.type_name == l_type).one()
# if it doesn't, add it to the table
except:
add_location_type = Type(type_name=l_type)
db.session.add(add_location_type)
db.session.commit()
type_obj = Type.query.filter(Type.type_name == l_type).one()
# see if the location-type connection exists in table
try:
LocationType.query.filter(LocationType.location_id == location_id &
LocationType.type_id == type_obj.type_id).one()
except:
type_obj = Type.query.filter(Type.type_name == l_type).one()
location_type_log = LocationType(location_id=location_id,
type_id=type_obj.type_id)
db.session.add(location_type_log)
db.session.commit()
# create a log for this location for the user
log = Log(user_id=user.user_id, location_id=location_id,
created_at=created_at, visit_date=visit_date, arrived=arrived,
departed=departed, comments=comments, title=title)
db.session.add(log)
db.session.commit()
return "True"
@app.route('/check-times', methods=['POST'])
def check_times():
"""Check if times for a log do not overlap with other logs on that day"""
# get information about log
start_time = request.form.get('arrival')
end_time = request.form.get('departure')
date = datetime.strptime(request.form.get('date')[0:15], '%a %b %d %Y').strftime('%Y-%m-%d')
# query database for logs matching that date
logged_times = db.session.query(Log.arrived,
Log.departed).filter(Log.visit_date == date).all()
# loop through the logs on that day and get their start/end times
if helper.check_overlap_times(logged_times, start_time, end_time) == 'False':
return 'False'
return 'True'
@app.route('/change-time-range', methods=['POST'])
def change_time_range():
"""Return logs that match a given user-entered time range"""
# get date the user is viewing and string format
d = request.form.get('showDate')
if not d:
d = datetime.now().strftime('%A, %B %d, %Y')
current_date = datetime.strptime(d, '%A, %B %d, %Y')
date_of_logs = current_date.strftime('%Y-%m-%d')
# get user information
user = User.query.filter(User.username == session['user']).one()
start_time = request.form.get('startTime').split(' ')
print "****", start_time
start_time = helper.format_time(start_time)
print start_time
end_time = request.form.get('endTime').split(' ')
end_time = helper.format_time(end_time)
# query database and create list of logs matching filters
logs = [{'locationId': log.location_id,
'locationName': log.location.name,
'locationAddress': log.location.address,
'visitDate': log.visit_date,
'arrived': log.arrived,
'departed': log.departed,
'comments': log.comments,
'title': log.title,
'user': log.user_id,
'locationLat': log.location.latitude,
'locationLong': log.location.longitude,
'log_id': log.log_id
}
# filter for user's logs matching date and in between specificed time range
for log in Log.query.filter(Log.user_id == user.user_id,
Log.visit_date == unicode(date_of_logs),
Log.arrived <= end_time,
Log.departed >= start_time)
.order_by(Log.arrived)
.all()]
date_of_logs = datetime.strptime(date_of_logs, '%Y-%m-%d')
# create dictionary to jsonify and return to browser
info = {'date': date_of_logs.strftime('%A, %B %d, %Y'),
'logs': logs}
return jsonify(info)
@app.route('/load_today')
def load_today():
"""Load today's information"""
# get current date
current_date = datetime.now().strftime('%A, %B %d, %Y')
date_of_logs = datetime.now().strftime('%Y-%m-%d')
# get information about user
user = User.query.filter(User.username == session['user']).one()
# query database and create list of logs matching filters
logs = [{'locationId': log.location_id,
'locationName': log.location.name,
'locationAddress': log.location.address,
'visitDate': log.visit_date,
'arrived': log.arrived,
'departed': log.departed,
'comments': log.comments,
'title': log.title,
'user': log.user_id,
'locationLat': log.location.latitude,
'locationLong': log.location.longitude,
'log_id': log.log_id
}
for log in Log.query.filter(Log.user_id == user.user_id,
Log.visit_date == unicode(date_of_logs))
.order_by(Log.arrived)
.all()]
# create dictionary to jsonify and return to browser
info = {'date': current_date,
'logs': logs}
return jsonify(info)
@app.route('/change-date', methods=['POST'])
def change_date():
"""Return logs for specified date"""
date_of_logs = helper.format_date(request.form)
# retrieve user's info
user = User.query.filter(User.username == session['user']).one()
# format start time
start_time = request.form.get('startTime').split(' ')
start_time = helper.format_time(start_time)
# # format end time
end_time = request.form.get('endTime').split(' ')
end_time = helper.format_time(end_time)
# retrieve logs that match database query
logs = [{'locationId': log.location_id,
'locationName': log.location.name,
'locationAddress': log.location.address,
'visitDate': log.visit_date,
'arrived': log.arrived,
'departed': log.departed,
'comments': log.comments,
'title': log.title,
'user': log.user_id,
'locationLat': log.location.latitude,
'locationLong': log.location.longitude,
'log_id': log.log_id
}
for log in Log.query.filter(Log.user_id == user.user_id,
Log.visit_date == unicode(date_of_logs),
Log.arrived <= end_time,
Log.departed >= start_time)
.order_by(Log.arrived)
.all()]
# format date to display on page
date_of_logs = datetime.strptime(date_of_logs, '%Y-%m-%d')
# create dictionary to pass to browser
info = {'date': date_of_logs.strftime('%A, %B %d, %Y'),
'logs': logs}
return jsonify(info)
@app.route('/location-directory')
def location_directory():
"""List all locations in user's logs"""
user = User.query.filter(User.username == session['user']).one()
# query database for list of all locations a user has visited
locations = {
log.location.name+log.location.location_id: {
'name': log.location.name,
'address': log.location.address,
'locationId': log.location.location_id,
'locationName': log.location.name,
'locationAddress': log.location.address,
'lat': log.location.latitude,
'long': log.location.longitude,
'loc_types': str([loc_type.location_type.type_name.replace('_', ' ') for loc_type in log.location.locationtypes])
}
for log in Log.query.filter(Log.user_id == user.user_id)
.all()}
return jsonify(locations)
@app.route('/search-location-directory', methods=['POST'])
def search_location_directory():
"""List all locations in user's logs"""
# get user information
user = User.query.filter(User.username == session['user']).one()
# retrieve user's search term
search_term = request.form.get('search')
# query database for location names matching that search term
locations = {
log.location.name+log.location.location_id: {
'name': log.location.name,
'address': log.location.address,
'locationId': log.location.location_id,
'locationName': log.location.name,
'locationAddress': log.location.address,
'lat': log.location.latitude,
'long': log.location.longitude,
'loc_types': str([loc_type.location_type.type_name.replace('_', ' ') for loc_type in log.location.locationtypes])
}
for log in db.session.query(Log).join(Location)
.filter(Log.user_id == user.user_id,
func.lower(Location.name).like('%'+search_term+'%'))
.all()}
return jsonify(locations)
@app.route('/profile/location-info/<location_id>')
def get_location_information(location_id):
"""Display logs and location information for given location and user"""
# get user info
user = User.query.filter(User.username == session['user']).one()
# get list of logs a person has created for a given location
location_logs = Log.query.filter(Log.user_id == user.user_id, Log.location_id == location_id).order_by(desc(Log.visit_date)).all()
# get details about location from Location table
location_info = Location.query.filter(Location.location_id == location_id).one()
return render_template('location_info.html', location_info=location_info,
location_logs=location_logs)
@app.route('/profile/<username>/view-profile')
def view_profile(username):
"""Retrieve information about user to display on view_profile page"""
# retrieve user information
user = User.query.filter(User.username == username).one()
user_start_date = user.date_created
user_start_date= user_start_date.strftime('%m/%d/%Y')
# retrieve number of logs user has created
num_logs = len(Log.query.filter(Log.user_id == user.user_id).all())
return render_template('view_profile.html', user_start_date=user_start_date,
user=user, username=username, num_logs=num_logs)
@app.route('/edit-username-check', methods=['POST'])
def edit_username_check():
"""check if username the user requests already exists in database"""
username = request.form.get('username')
try:
User.query.filter(User.username == username).one()
return 'True'
except:
return 'False'
@app.route('/add-new-username', methods=['POST'])
def add_new_username():
"""update user's username in database"""
new_username = request.form.get('username')
# query for user
user = User.query.filter(User.username == session['user']).one()
# set new username for user
user.username = new_username
# commit change to database
db.session.commit()
# set session with new username
session['user'] = new_username
# query for updated user information
user = User.query.filter(User.username == new_username).one()
return jsonify({'user': user.username})
@app.route('/delete-log', methods=['POST'])
def delete_log():
"""delete log from database"""
log_id = request.form.get('logID')
# get the id of the log to be deleted
log_id = int(log_id.replace('log',''))
# query the database for this log
log = Log.query.get(log_id)
# delete the log
db.session.delete(log)
# commit changes
db.session.commit()
return 'True'
@app.route('/save-log', methods=['POST'])
def save_log():
"""save new information about a log that already exists in db"""
log_id = request.form.get('logID')
# retrieve log id
log_id = int(log_id.replace('log',''))
# retrieve log information from db
log = Log.query.get(log_id)
# retrieve information user entered for updated log entry
log.title = request.form.get('newTitle')
if request.form['newComments'] != '':
log.comments = request.form.get('newComments')
visit_date = request.form.get('newDate')
start_time = request.form.get('newArrival')
end_time = request.form.get('newDeparture')
data = {}
# query db for the other logs a user has entered for that day to make sure
# there are no overlapping time entries
logged_times = db.session.query(Log.arrived,
Log.departed).filter(Log.visit_date == visit_date,
Log.log_id != log_id).all()
if helper.check_overlap_times(logged_times, start_time, end_time) == 'False':
data['status'] = 'False'
return
# if no logs that overlap in time for this day, update details for the log
log.visit_date = visit_date
log.arrived = start_time
log.departed = end_time
db.session.commit()
log = Log.query.get(log_id)
data['status'] = 'True'
data['title'] = log.title
data['arrived'] = log.arrived
data['departed'] = log.departed
data['comments'] = log.comments
data['location'] = log.location.name
data['visited'] = log.visit_date
return jsonify(data)
@app.route('/test-log-info', methods=['POST'])
def test_log_info():
start_date = request.form.get('startDate')
end_date = request.form.get('endDate')
start_date = datetime.strptime(start_date, '%m/%d/%Y')
start_date = start_date.strftime('%Y-%m-%d')
end_date = datetime.strptime(end_date, '%m/%d/%Y')
end_date = end_date + timedelta(days=1)
end_date = end_date.strftime('%Y-%m-%d')
num_logs = {}
this_day = start_date
data_dict = {
'labels': [],
'datasets': [
{
# 'label': 'Test',
"fillColor": "rgba(220,220,220,0.2)",
"strokeColor": "rgba(220,220,220,1)",
"pointColor": "rgba(220,220,220,1)",
"pointStrokeColor": "#fff",
"pointHighlightFill": "#fff",
"pointHighlightStroke": "rgba(220,220,220,1)",
'data': []
}
]
}
while this_day != end_date:
num_logs_this_day = db.session.query(func.count(Log.log_id)).filter(Log.visit_date==this_day).all()
num_logs[this_day] = int(num_logs_this_day[0][0])
this_day = datetime.strptime(this_day, '%Y-%m-%d')
this_day = this_day + timedelta(days=1)
this_day = this_day.strftime('%Y-%m-%d')
for key in sorted(num_logs.keys()):
data_dict['labels'].append(key)
data_dict['datasets'][0]['data'].append(num_logs[key])
return jsonify(data_dict)
###################
if __name__ == '__main__':
connect_to_db(app)
# app.debug = True
# Use the DebugToolbar
# DebugToolbarExtension(app)
app.run()<file_sep>"""Models and database functions for Hackbright project"""
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from sqlalchemy import or_, func, desc, update
from datetime import datetime, timedelta
db = SQLAlchemy()
###########################
# Model definitions
class User(db.Model):
__tablename__ = 'users'
user_id = db.Column(db.Integer, autoincrement=True, primary_key=True)
email = db.Column(db.String(80), nullable=False, unique=True)
fname = db.Column(db.String(20), nullable=False)
lname = db.Column(db.String(25), nullable=False )
username = db.Column(db.String(20), nullable=False)
password = db.Column(db.String(25), nullable=False)
home_lat = db.Column(db.String(40), nullable=True)
home_long = db.Column(db.String(40), nullable=True)
home_address = db.Column(db.String(250), nullable=True)
home_id = db.Column(db.String(100), nullable=True)
date_created = db.Column(db.DateTime, nullable=False)
def __repr__(self):
return "<User user_id={}, username={}".format(self.user_id,
self.username)
class Location(db.Model):
__tablename__ = 'locations'
location_id = db.Column(db.String(100), primary_key=True)
latitude = db.Column(db.String(40), nullable=False)
longitude = db.Column(db.String(40), nullable=False)
address = db.Column(db.String(500), nullable=False)
name = db.Column(db.String(100), nullable = False)
website = db.Column(db.String(200))
phone = db.Column(db.String(200))
def __repr__(self):
return "<Location location_name={}, address={}".format(self.name, self.address)
class Log(db.Model):
__tablename__ = 'logs'
log_id = db.Column(db.Integer, autoincrement=True, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.user_id'),
nullable=False)
location_id = db.Column(db.String(100), db.ForeignKey('locations.location_id'),
nullable=False)
created_at = db.Column(db.DateTime, nullable=False)
visit_date = db.Column(db.String(50), nullable=False)
arrived = db.Column(db.String(20), nullable=False)
departed = db.Column(db.String(20), nullable=False)
comments = db.Column(db.Text, nullable=False)
title = db.Column(db.String(50), nullable=False)
user = db.relationship('User', backref=db.backref('logs'))
location = db.relationship('Location', backref=db.backref('logs'),
order_by='desc(Location.name)')
def __repr__(self):
return "<Log title: {}, created on{}".format(self.title, self.created_at)
############### useful if wanting to do something with establishment types in the future;
# not currently using the Type and LocationType tables
class Type(db.Model):
__tablename__ = 'types'
type_id = db.Column(db.Integer, autoincrement=True, primary_key=True)
type_name = db.Column(db.String(50), nullable=False, unique=True)
def __repr__(self):
return "<Location type {}".format(self.type_name)
class LocationType (db.Model):
__tablename__ = 'location_types'
loc_type_id = db.Column(db.Integer, autoincrement=True, primary_key=True)
location_id = db.Column(db.String(100), db.ForeignKey('locations.location_id'),
nullable=False)
type_id = db.Column(db.Integer, db.ForeignKey('types.type_id'), nullable=False)
location = db.relationship('Location', backref=db.backref('locationtypes'),
order_by='desc(Location.name)')
location_type = db.relationship('Type', backref=db.backref('locationtypes'))
def __repr__(self):
return "<Location type {} for {}".format(self.type_id, self.location_id)
def example_data():
user1 = User(email='<EMAIL>', fname='Bob', lname='Builder',
username='bbuild', password='<PASSWORD>', home_lat='37.794434',
home_long='-122.39520160000001',
home_address='50 Market St, San Francisco, CA 94105, USA',
home_id='ARi1KXmVCb5Rc',
date_created=datetime.strptime('2016-05-19 16:13:42.940831',
'%Y-%m-%d %H:%M:%S.%f'))
db.session.add(user1)
db.session.commit()
user_id = db.session.query(User.user_id).filter(User.username == 'bbuild').one()
location1 = Location(location_id='ChIJOWCTNGSAhYARLxosf_Izuy4',
latitude='37.7936231', longitude='-122.39299269999998',
address='8 Mission St, San Francisco, CA 94105, USA',
name='Hotel Vitale',
website='http://www.jdvhotels.com/hotels/california/san-francisco-hotels/hotel-vitale',
phone='(415) 278-3700')
db.session.add(location1)
db.session.commit()
log1 = Log(user_id=user_id[0], location_id='ChIJOWCTNGSAhYARLxosf_Izuy4',
created_at=datetime.strptime('2016-05-29 14:08:51.615528',
'%Y-%m-%d %H:%M:%S.%f'),
visit_date='2016-05-29', arrived='16:00', departed='17:00',
comments='Lovely wedding', title='Wedding')
db.session.add(log1)
db.session.commit()
def connect_to_db(app, db_uri='postgresql:///locations'):
app.config['SQLALCHEMY_DATABASE_URI'] = db_uri
# app.config['SQLALCHEMY_ECHO'] = True
db.app = app
db.init_app(app)
if __name__ == '__main__':
from server import app
connect_to_db(app)
db.create_all()
print "Connected to DB."
| b002cd3562d9370976da50fd950c5fcde06a0c15 | [
"Markdown",
"Python",
"Text"
] | 7 | Python | sarahcstringer/hackbright-project | 6baf65f99ed414fb911170b7a9c0c31e656fdc13 | 70dee14b7f39ed54d8bfcfedbed286511e85a7ed |
refs/heads/master | <file_sep># Write your code here.
katz_deli = []
def line(array)
if array.length > 0
list = []
array.each_with_index do |person, index|
list << "#{index + 1}. #{person}"
end
puts "The line is currently: " + list.join(" ")
else
puts "The line is currently empty."
end
end
def take_a_number(array, person)
#Welcome, <person>. You are number <number> in line.
array << person
puts "Welcome, #{person}. You are number #{array.index(person) + 1} in line."
end
def now_serving(array)
if array.length > 0
puts "Currently serving #{array.shift}."
else
puts "There is nobody waiting to be served!"
end
end
| b6cd4fdf72ddbb7f8488cf3a1ccda8e45ffeb1f3 | [
"Ruby"
] | 1 | Ruby | joshlacey/deli-counter-prework | 64df2d377f5e7fcd279d510f5d28397f641893b0 | 468080237489f3f9e9e36f582315624637869b1a |
refs/heads/master | <file_sep>#!/usr/bin/env node
"use strict";
// Load Coffeescript for node tasks
require("coffee-script/register");
var EventEmitter = new (require("events").EventEmitter)();
var Domain = require("domain").create();
var Path = require("path")
GLOBAL.Tool = "norma"
GLOBAL.Norma = {
watchStarted: false,
events: EventEmitter,
domain: Domain,
prefix: "Ø ",
packages: []
}
// EVENTS ---------------------------------------------------------------
// Event shorthand
Norma.subscribe = function(evt, cb) {
return Norma.events.on(evt, cb);
};
Norma.emit = function(evt, obj) {
return Norma.events.emit(evt, obj);
};
var MapTree = require("./../lib/utilities/directory-tools").mapTree
var loadEvents = function() {
var events,
evt,
eventDir,
_i,
_len,
_ref,
_results;
eventDir = Path.resolve(__dirname, "./../lib/events/")
events = MapTree(eventDir);
_ref = events.children;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
evt = _ref[_i];
if (evt.path) {
_results.push(require(evt.path)());
} else {
_results.push(void 0);
}
}
return _results;
}
loadEvents();
// ERRORS ---------------------------------------------------------------
Domain.on("error", function(err){
// err.level = "crash";
// handle the error safely
Norma.events.emit("error", err);
});
// Domain.add(Norma.events)
// APPLICATION ----------------------------------------------------------
process.on('SIGINT', function() {
Norma.events.emit("stop");
});
Domain.run(function(){
// Require main file
require("../lib/" + Tool + "-main");
});
| 7eb59e3ca072c228cc00f83930ae3f7de1c9c5d8 | [
"JavaScript"
] | 1 | JavaScript | johnthepink/Norma | a51c1114179ca9c223563cfbccb0b5b447b94575 | 36c5dc92aad13f782d0e34e9911ef112ee2eab9b |
refs/heads/master | <file_sep>
## Guidelines
1. It should run fizzbuzz in one line
2. You should update the CI in `.github/workflows/main.yml` to run it against our test
file
<file_sep>#!/usr/bin/env node
[...Array(100).keys()].forEach(x=>console.log((x+1)%3!=0&&(x+1)%5!=0?(x+1):((x+1)%3==0&&(x+1)%5==0?"fizzbuzz":((x+1)%3==0?"fizz":"buzz"))));
| 51c19f13a91bf3531ba4e9cfe4258ee7ab0c7c28 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | noyoshi/fizzbuzz | 9405210ee4d51c1d26ae43a5c669323fdaaf1574 | a38ed68a868df7575d1c18e8d5bb8cc9682cb935 |
refs/heads/master | <repo_name>CEMSARI9576/ClassMetotDemo<file_sep>/ClassMetotDemo/Program.cs
using System;
namespace ClassMetotDemo
{
class Program
{
static void Main(string[] args)
{
Customers customer1 = new Customers();
customer1.CustomerId = 1000;
customer1.CustomerName = "Cem";
customer1.CustomerLastName = "Sarı";
customer1.CustomerAdress = "İstanbul";
Customers customer2 = new Customers();
customer2.CustomerId = 1001;
customer2.CustomerName = "Sefa";
customer2.CustomerLastName = "Güler";
customer2.CustomerAdress = "Kocaeli";
Customers customer3 = new Customers();
customer3.CustomerId = 1003;
customer3.CustomerName = "İlkcan";
customer3.CustomerLastName = "Ceylan";
customer3.CustomerAdress = "Konya";
Customers[] array = new Customers[] { customer1, customer2,customer3 };
CustomerManager manage = new CustomerManager();
manage.AddCustomer(customer3);
manage.DeleteCustomer(customer3);
manage.ListCustomers(array);
}
}
}
<file_sep>/ClassMetotDemo/CustomerManager.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace ClassMetotDemo
{
class CustomerManager
{
public void AddCustomer(Customers cust)
{
Console.WriteLine("----------------Add---------------------");
Console.WriteLine(cust.CustomerId + " ID numaralı" + cust.CustomerName +" "+ cust.CustomerLastName + " adlı müşteri eklenmiştir.");
}
public void DeleteCustomer(Customers cust)
{
Console.WriteLine("----------------Delete---------------------");
Console.WriteLine(cust.CustomerId + " ID numaralı" + cust.CustomerName + " " +cust.CustomerLastName + " adlı müşteri silinmiştir.");
}
public void ListCustomers(Customers[] array)
{
Console.WriteLine("----------------List---------------------");
foreach (Customers item in array)
{
Console.WriteLine(item.CustomerId + ":" + item.CustomerName + " " + item.CustomerLastName + " --->" + item.CustomerAdress+" kullanıcılar");
}
}
}
}
| 84b8b3492702ebadcdd6651d624ebb3b839ab005 | [
"C#"
] | 2 | C# | CEMSARI9576/ClassMetotDemo | 00e7d2f78c625fe0a894ec18d2df6a8bd18ca303 | 60b59494823e802009110cc51266b530d05530ec |
refs/heads/main | <file_sep>import { vuexfireMutations, firestoreAction } from 'vuexfire'
import 'firebase/firestore'
import firebase from '~/plugins/firebase.js'
const db = firebase.firestore()
const studentsRef = db.collection('students')
export const state = () => ({
students: [],
})
export const mutations = {
...vuexfireMutations
}
export const getters = {
getStudents: state => {
return state.students
}
}
export const actions = {
setStudentsRef: firestoreAction(({ bindFirestoreRef }, studentsRef) => {
bindFirestoreRef('students', studentsRef)
}),
registration: firestoreAction(({context}, {
firstName,
familyName,
familyNameKana,
firstNameKana,
parentsFirstNameKana,
gender,
relationship,
pickerDate,
phoneNumber,
address,
zipcode,
building,
message,
}) => {
const studentData =
'firstName:'+ firstName
'familyName:' + familyName,
'familyNameKana:' + familyNameKana,
'firstNameKana:' + firstNameKana,
'parentsFirstNameKana:' + parentsFirstNameKana,
'gender:' + gender,
'relationship:' + relationship,
'pickerDate:' + pickerDate,
'phoneNumber:' + phoneNumber,
'address:' + address,
'zipcode:' + zipcode,
'building:' + building,
'message:' + message,
studentsRef.add({
studentData,
'entranced': firebase.firestore.FieldValue.serverTimestamp()
})
}),
deleteData: firestoreAction((context, id) => {
return studentsRef.doc(id).delete()
}),
// fetchLevel: firestoreAction((context,id) => {
// return studentsRef.doc(id).update({
// level: level
// })
// })
}<file_sep>道場生管理アプリ
====
## Overview
このアプリは道場生の登録閲覧ができるアプリです。
## Description
道場生の登録を行い管理していきます。
## set up
①URLをクリックすると道場生の一覧が表示されます。
②右側に生徒を追加するボタンがありますのでそこをクリックすると登録画面に移ります。
③初期では、ボタンは非活性となっており各項目を入力するとボタンが押せるようになるので全項目を入力後ボタンをクリックし送信します。
④追加すると一覧に表示がされるようになります。
## イメージ図
- インデックスページです(右上のボタンを押すと道場生の追加ができるようになります。)
[](https://gyazo.com/1b7ae94dec70ac2dcdde0be38b006214)
- 道場生追加画面です(初期ではボタンは非活性となっており押すことができません)
[](https://gyazo.com/32f9e3114c1b6c1d3100a0a90914a26f)
[](https://gyazo.com/7e1764d7a4dbb7b100b0116dd3b6438b)
- 必須項目を全て入力するようになるとボタンが押せるようになります
[](https://gyazo.com/30b08a9ab505de2c324f0937a92ccc59)
- バリデーションにも対応しており、郵便番号を入力すると自動で住所が表示されます。
[](https://gyazo.com/5098d7ba7da7c1553a1906a596aa346c)
- 詳細画面です。
[](https://gyazo.com/e458e380089efad4a60cc3d882124987)
## 接続先URL
https://karatemanagement-e9371.web.app/
## 開発環境
- 言語:Javascript
- ツール:Visual Studio Code/ Nuxt.js/Vuetify
- DB:firebase
- サーバー:firebasehosting
## 実装機能
- 道場生作成・編集・削除機能、
## 実装予定機能
- 一覧表示で生年月日から年齢を表示できるようにしたい
- ログイン機能
- 現在の保持級をセレクト表示できるようにしたい
## 企画背景
- 道場の経営をしている弟の手助けができるようなアプリを作りたかったからです。
<file_sep>import Vue from 'vue';
import { ValidationProvider, ValidationObserver, extend, localize } from 'vee-validate';
import { required, numeric, max_value, max } from 'vee-validate/dist/rules';
import { PhoneNumberUtil } from 'google-libphonenumber'
import ja from 'vee-validate/dist/locale/ja.json';
extend('required', required);
extend('numeric', numeric);
extend('max_value', max_value);
extend('max', max);
extend('phone', {
message: '電話番号を入力してください',
validate(value) {
const util = PhoneNumberUtil.getInstance()
try {
const phoneNumber = util.parseAndKeepRawInput(value, 'JP')
return util.isValidNumber(phoneNumber)
} catch (err) {
return false
}
}
});
extend('katakana', {
message: 'カタカナで入力してください',
validate(value) {
return /^[ァ-ン]+$/.test(value);
}
});
extend('zenkaku', {
message: '全角で入力してください',
validate(value) {
return /^[ぁ-んァ-ン一-龥]/.test(value);
}
})
// メッセージを設定
localize('ja', ja);
Vue.component('ValidationProvider', ValidationProvider);
Vue.component('ValidationObserver', ValidationObserver); | 1bcfbe02f44c7287717b96c5e1a96dce345ea604 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | wattyo0314/karate_management | 28094392d5494c3fdcffad7c7ba0a22d05108645 | 9fd100da47ee71039897ce72123a5ea27551d0e7 |
refs/heads/master | <repo_name>hyeonsook95/crawling<file_sep>/crawler2.py
from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
search_term = '진돗개'
url = 'https://www.google.co.in/search?q='+search_term+"&tbm=isch"
browser = webdriver.Chrome("chromedriver.exe", chrome_options=chrome_options)
browser.get(url)
for idx, el in enumerate(browser.find_elements_by_class_name("rg_ic")):
el.screenshot(search_term + str(idx) + ".png")
browser.close()
<file_sep>/pyqt5.py
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QGridLayout, QLabel, QLineEdit, QTextEdit)
class MyApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
grid = QGridLayout()
self.setLayout(grid)
grid.addWidget(QLabel('Title:'), 0, 0)
grid.addWidget(QLabel('Author:'), 1, 0)
grid.addWidget(QLabel('Review:'), 2, 0)
grid.addWidget(QLineEdit(), 0, 1)
grid.addWidget(QLineEdit(), 1, 1)
<file_sep>/crawler1.py
# https://data-make.tistory.com/172
# https://pinocc.tistory.com/168
# encoding = utf-8
import os
import ssl
from google_images_download import google_images_download
ssl._create_default_https_context
class MyCrawler:
def __init__(self):
super().__init__()
self.crawler()
def imageCrawling(self, keyword, dir, limit):
response = google_images_download.googleimagesdownload()
arguments = {"keywords": keyword,
"limit": limit,
"print_urls": True,
"no_directory": True,
"output_directory": dir,
"chromedriver": "./chromedriver.exe"}
paths = response.download(arguments)
print(paths)
def renameFiles(self, keyword, dir):
file_list = os.listdir(dir)
idx=0
for i in file_list:
idx += 1
os.rename(dir+'\\'+i, dir+'\\{}.jpg'.format(idx))
def crawler(self):
path='C:\\Users\\user\\Documents\\github\\downloads'
keyword='진돗개'
new_path=path+'\\'+keyword
os.mkdir(new_path)
self.imageCrawling('진돗개', new_path, 10)
self.renameFiles('진돗개', new_path)
if __name__ == '__main__':
cr = MyCrawler()<file_sep>/pyqt6.py
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLineEdit, QInputDialog
class MyApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.btn = QPushButton('Dialog', self) | 43b0472e8203020dbd2668d74753502c93ebd98e | [
"Python"
] | 4 | Python | hyeonsook95/crawling | 56fa12a11f06d2d1e57b8a7fe3d9b7b22d3a485c | 497d2f9f6c474d74f5c51401357ff96c7cc74570 |
refs/heads/master | <repo_name>ioptime/Betty<file_sep>/src/com/ioptime/betty/MessageThreadFragment.java
package com.ioptime.betty;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.ioptime.adapters.MessageThreadAdapter;
import com.ioptime.betty.model.Message;
import com.ioptime.extendablelibrary.IoptimeFragment;
public class MessageThreadFragment extends IoptimeFragment {
int sender_id, reciever_id;
Boolean again = false;
ListView listMessagesThread;
ProgressBar progressBar;
ArrayList<Message> arrayThread = new ArrayList<Message>();
Button btSend;
EditText etMessage;
int rec_id, rec_type, count;
boolean IsStarted;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
sender_id = Integer.parseInt(getArguments().getString("sender_id"));
reciever_id = Integer.parseInt(getArguments().getString("reciever_id"));
count = getArguments().getInt("count");
View rootView = inflater.inflate(R.layout.messages_thread, container,
false);
IsStarted = true;
listMessagesThread = (ListView) rootView
.findViewById(R.id.messageThreadList);
progressBar = (ProgressBar) rootView
.findViewById(R.id.messageThreadProgressBar);
btSend = (Button) rootView.findViewById(R.id.buttonSend);
etMessage = (EditText) rootView.findViewById(R.id.replyETMessageThread);
new GetMessageThreadBT().execute();
btSend.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new SendMessageBTTask(sender_id, rec_type).execute();
}
});
return rootView;
}
private class GetMessageThreadBT extends AsyncTask<Void, Void, Void> {
String result = "-";
@Override
protected void onPreExecute() {
if (IsStarted)
progressBar.setVisibility(View.VISIBLE);
}
@Override
protected Void doInBackground(Void... arg0) {
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sender_id", "" + sender_id));//
params.add(new BasicNameValuePair("reciever_id", "" + reciever_id));
result = getJSONfromURL(Appconstants.Server
+ "messages_get_conversation.php", params, 0);
Log.d("result", "--" + result + " for " + sender_id);
if (result.equalsIgnoreCase("") | result.contains("empty")
| result.equalsIgnoreCase("ERROR GETTING RESULTS IOPTIME")) {
// not valid
} else {
JSONArray jArray;
try {
jArray = new JSONArray(result);
arrayThread = new ArrayList<Message>();
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
arrayThread.add(new Message(Integer.parseInt(json_data
.getString("message_id").trim()), Integer
.parseInt(json_data.getString("message_to")
.trim()), json_data
.getString("message_subject"), json_data
.getString("message_status"), json_data
.getString("group_message"), json_data
.getString("group_message_id"), json_data
.getString("message_created").trim(), json_data
.getString("message_reference_id"), json_data
.getString("message_sub_reference_id"),
json_data.getString("message_customer_id"),
json_data.getString("message_user_id"),
json_data.getString("message_order_id"),
json_data.getString("message_last_update"),
json_data.getString("message_last_modified"),
Integer.parseInt(json_data.getString(
"customer_read").trim()), Integer
.parseInt(json_data.getString(
"fcustomer_read").trim()),
Integer.parseInt(json_data.getString(
"support_read").trim()), Integer
.parseInt(json_data.getString(
"user_type").trim()), Integer
.parseInt(json_data.getString(
"admin_status").trim()),
Integer.parseInt(json_data.getString(
"vendor_status").trim()), Integer
.parseInt(json_data.getString(
"customer_status").trim()),
Integer.parseInt(json_data.getString(
"transfer_status").trim()), Integer
.parseInt(json_data.getString(
"transfer_message_id").trim()),
json_data.getString("Attachment"), Integer
.parseInt(json_data.getString(
"content_id").trim()),
json_data.getString("content"), Integer
.parseInt(json_data
.getString("is_user").trim()),
Integer.parseInt(json_data.getString(
"sender_id").trim()), Integer
.parseInt(json_data.getString(
"reply_status").trim()),
Integer.parseInt(json_data.getString(
"message_read_customer").trim()),
Integer.parseInt(json_data.getString(
"message_read_support").trim()),
json_data.getString("created"), json_data
.getString("file"),json_data
.getString("file")));
Log.d("receiver", "-use id"
+ arrayThread.get(i).getMessage_user_id()
+ "-customer id-"
+ arrayThread.get(i).getMessage_customer_id()
+ "---" + Appconstants.user.getCustomer_id());
rec_type = arrayThread.get(0).getUser_type();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(Void params) {
if (result.equalsIgnoreCase("") | result.contains("empty")
| result.equalsIgnoreCase("ERROR GETTING RESULTS IOPTIME")
&& !again) {
// not valid
new GetMessageThreadBT().execute();
again = true;
Toast.makeText(getActivity(),
"Wonky Internet connection , trying again",
Toast.LENGTH_SHORT).show();
} else {
populateListView();
progressBar.setVisibility(View.GONE);
}
}
}
private void populateListView() {
if (arrayThread.size() > 0) {
MessageThreadAdapter messageAdapter = new MessageThreadAdapter(
getActivity(), arrayThread);
listMessagesThread.setAdapter(messageAdapter);
messageAdapter.notifyDataSetChanged();
listMessagesThread
.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
new ReadOrUnreadBTTask(arrayThread.get(position)
.getMessage_id()).execute();
// MessageThreadFragment messageFrag = new
// MessageThreadFragment();
// Bundle bundle = new Bundle();
// bundle.putString("sender_id", inboxMessageArray
// .get(position).getMessage_customer_id());
// messageFrag.setArguments(bundle);
// getFragmentManager().beginTransaction()
// .replace(R.id.frame_container, messageFrag)
// .addToBackStack(null).commit();
}
});
} else {
Toast.makeText(getActivity(), "Check your internet connection",
Toast.LENGTH_SHORT).show();
}
}
private class SendMessageBTTask extends AsyncTask<Void, Void, Void> {
String result = "-";
int reciever_id;
int reciever;
SendMessageBTTask(int recv_id, int recv) {
reciever_id = recv_id;
reciever = recv;
}
@Override
protected void onPreExecute() {
Toast.makeText(getActivity(), "Sending message", Toast.LENGTH_SHORT)
.show();
btSend.setClickable(false);
IsStarted = false;
}
@Override
protected Void doInBackground(Void... arg0) {
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("reciever_id", "" + reciever_id));//
params.add(new BasicNameValuePair("reciever", "" + reciever));//
if (count == 1) {
params.add(new BasicNameValuePair("sender_id", ""
+ Appconstants.user.getCustomer_id()));
}
else if (count == 0) {
params.add(new BasicNameValuePair("sender_id", ""
+ Appconstants.vendor.getUser_id()));
}
params.add(new BasicNameValuePair("message", ""
+ etMessage.getText().toString()));
params.add(new BasicNameValuePair("subject", ""));
result = getJSONfromURL(Appconstants.Server + "messages_send.php",
params, 0);
if (result.equalsIgnoreCase("") | result.contains("empty")
| result.contains("err")) {
// not valid
} else {
}
Log.d("result Message", "--" + result);
return null;
}
@Override
protected void onPostExecute(Void params) {
btSend.setClickable(true);
if (MessageThreadFragment.this.isVisible()) {
Toast.makeText(getActivity(), "Message sent",
Toast.LENGTH_SHORT).show();
new GetMessageThreadBT().execute();
etMessage.setText("");
}
}
}
private class ReadOrUnreadBTTask extends AsyncTask<Void, Void, Void> {
int msg_id;
public ReadOrUnreadBTTask(int msg_id) {
// TODO Auto-generated constructor stub
this.msg_id = msg_id;
}
@Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("message_id", "" + msg_id));//
String result = getJSONfromURL(Appconstants.Server
+ "message_read.php", params, 0);
if (result.equalsIgnoreCase("") | result.contains("empty")
| result.contains("err")) {
// not valid
} else {
}
Log.d("result Message", "--" + result);
return null;
}
}
}
<file_sep>/src/com/ioptime/adapters/BlogAdapter.java
package com.ioptime.adapters;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.image.loader.ImageLoader;
import com.ioptime.betty.R;
import com.ioptime.betty.model.Blog;
public class BlogAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<Blog> blogArray;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
public BlogAdapter(Activity a, ArrayList<Blog> i) {
activity = a;
blogArray = i;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext(),
ImageLoader.OTHER);
}
public int getCount() {
return blogArray.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.item_blog, null);
//
TextView textName = (TextView) vi.findViewById(R.id.blogListName);
TextView textDesc = (TextView) vi.findViewById(R.id.blogListDesc);
TextView textAuthor = (TextView) vi.findViewById(R.id.blogListAuthor);
ImageView image = (ImageView) vi.findViewById(R.id.blogListImage);
textName.setText(blogArray.get(position).getTitle());
textDesc.setText(Html.fromHtml(""
+ Html.fromHtml(blogArray.get(position).getIntro_text())));
// textAuthor.setText("" + blogArray.get(position).getIntro_text());
// imageLoader.DisplayImage(blogArray.get(position).getImage(),
// image);
return vi;
}
}<file_sep>/src/com/ioptime/vendor/adapters/ProductReportsAdapter.java
package com.ioptime.vendor.adapters;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.image.loader.ImageLoader;
import com.ioptime.betty.R;
import com.ioptime.betty.model.ProductReportsModel;
public class ProductReportsAdapter extends BaseAdapter {
private Activity activity;
private static LayoutInflater inflater = null;
public boolean wish;
public ImageLoader imageLoader;
ArrayList<ProductReportsModel> productsList;
public ProductReportsAdapter(Activity a,
ArrayList<ProductReportsModel> products) {
activity = a;
productsList = products;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext(),
R.drawable.ic_launcher);
}
@Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
public int getCount() {
return productsList.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.custom_product_reports, null);
//
try {
LinearLayout layout = (LinearLayout) vi.findViewById(R.id.ll);
TextView textPName = (TextView) vi.findViewById(R.id.PNameReports);
TextView textPModel = (TextView) vi
.findViewById(R.id.PModelReports);
TextView textPViewed = (TextView) vi
.findViewById(R.id.PViewedReports);
TextView textPPercentage = (TextView) vi
.findViewById(R.id.PPercentageReports);
TextView textPQuantity = (TextView) vi
.findViewById(R.id.PQuantityReports);
TextView textPOrderID = (TextView) vi
.findViewById(R.id.POrdereIDReports);
ProductReportsModel data = productsList.get(position);
textPName.setText(data.getProductName());
textPModel.setText(data.getpModel());
textPViewed.setText("" + data.getViewed());
textPPercentage.setText(data.getPerecent());
textPQuantity.setText("" + data.getQuantity());
Log.d("values", "" + data.getQuantity() + R.id.PModelReports);
StringBuilder builder = new StringBuilder();
String[] arr = data.getOrderID();
StringBuilder sb = new StringBuilder();
for (String n : arr) {
if (sb.length() > 0) sb.append(',');
sb.append("").append(n).append("");
textPOrderID.setText(sb.toString());
}
// for (String s : arr) {
// builder.append(s);
// builder.append(",");
//
// textPOrderID.setText(builder.toString());
//
// }
// builder.deleteCharAt(builder.length() - 1);
} catch (Exception e) {
e.printStackTrace();
}
return vi;
}
}
<file_sep>/src/com/ioptime/betty/model/BlogComment.java
package com.ioptime.betty.model;
public class BlogComment {
int comment_id;
int blog_id;
public BlogComment(int comment_id, int blog_id, String text, int status,
String created, String user, String email) {
super();
this.comment_id = comment_id;
this.blog_id = blog_id;
this.text = text;
this.status = status;
this.created = created;
this.user = user;
this.email = email;
}
String text;
int status;
String created;
String user;
String email;
public int getComment_id() {
return comment_id;
}
public void setComment_id(int comment_id) {
this.comment_id = comment_id;
}
public int getBlog_id() {
return blog_id;
}
public void setBlog_id(int blog_id) {
this.blog_id = blog_id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
<file_sep>/src/com/ioptime/adapters/ShopAdapter.java
package com.ioptime.adapters;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.image.loader.ImageLoader;
import com.ioptime.betty.Appconstants;
import com.ioptime.betty.R;
import com.ioptime.betty.model.Shops;
import com.ioptime.extendablelibrary.IoptimeRoot;
public class ShopAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<Shops> shopArray;
private static LayoutInflater inflater = null;
boolean wish;
public ImageLoader imageLoader;
public ShopAdapter(Activity a, ArrayList<Shops> shopsList, boolean wish) {
activity = a;
this.wish = wish;
shopArray = shopsList;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext(),
R.drawable.ic_launcher);
if (Appconstants.user.getFollowList().size() > 0) {
for (int i = 0; i < shopArray.size(); i++) {
for (int j = 0; j < Appconstants.user.getFollowList().size(); j++) {
shopArray.get(i).setFollowed(false);
if (shopArray.get(i).getId() == Appconstants.user
.getFollowList().get(j).getId()) {
shopArray.get(i).setFollowed(true);
break;
}
}
}
}
}
public int getCount() {
return shopArray.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.item_shops, null);
//
RelativeLayout shopList = (RelativeLayout) vi
.findViewById(R.id.shopList);
TextView textName = (TextView) vi.findViewById(R.id.shopListName);
ImageView image = (ImageView) vi.findViewById(R.id.shopListImage);
textName.setText(shopArray.get(position).getName());
imageLoader.DisplayImage(shopArray.get(position).getUrl(), image,
R.drawable.ic_launcher);
ImageView followList = (ImageView) vi.findViewById(R.id.shopListFollow);
if (wish) {
if (shopArray.get(position).isFollowed()) {
followList.setImageResource(R.drawable.unfolllow);
} else if (!shopArray.get(position).isFollowed()) {
followList.setImageResource(R.drawable.follow);
shopList.setVisibility(View.GONE);
shopList.getLayoutParams().height = 0;
}
} else if (!wish) {
if (shopArray.get(position).isFollowed()) {
followList.setImageResource(R.drawable.unfolllow);
} else if (!shopArray.get(position).isFollowed()) {
followList.setImageResource(R.drawable.follow);
}
}
followList.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (shopArray.get(position).isFollowed()) {
shopArray.get(position).setFollowed(false);
new RemoveFromFollowList(shopArray.get(position).getId(),
position).execute();
} else if (!shopArray.get(position).isFollowed()) {
// adding to wish list locally
shopArray.get(position).setFollowed(true);
new AddToFollowList(shopArray.get(position).getId(),
position).execute();
}
notifyDataSetChanged();
}
});
return vi;
}
/** for adding a store in follow list **/
private class AddToFollowList extends AsyncTask<Void, Void, Void> {
int storeid;
String result = "result";
int position;
AddToFollowList(int storeid, int pos) {
this.storeid = storeid;
this.position = pos;
}
@Override
protected Void doInBackground(Void... arg0) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs
.add(new BasicNameValuePair("store_id", "" + storeid));
nameValuePairs.add(new BasicNameValuePair("customer_id", ""
+ Appconstants.user.getCustomer_id()));
try {
//
result = IoptimeRoot.getJSONfromURL(Appconstants.Server
+ "follow_store.php", nameValuePairs, 0);
Log.d("result", "--" + result);
if (result.equalsIgnoreCase("") | result.contains("empty")
| result.contains("err")) {
// not valid
} else {
// JSONArray jArray = new JSONArray(result);
//
// for (int i = 0; i < jArray.length(); i++) {
// JSONObject json_data = jArray.getJSONObject(i);
// userid = Integer.parseInt(json_data.getString(
// "customer_id").trim());
//
// }
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
@Override
protected void onPostExecute(Void params) {
if (result.equalsIgnoreCase("")) {
Toast.makeText(activity.getApplicationContext(),
"Successfully added", Toast.LENGTH_SHORT).show();
} else {
// if failed removing
Toast.makeText(activity.getApplicationContext(),
"Error while following", Toast.LENGTH_LONG).show();
shopArray.get(position).setFollowed(false);
notifyDataSetChanged();
}
}
}
/** removing from follow list **/
private class RemoveFromFollowList extends AsyncTask<Void, Void, Void> {
int storeid;
String result = "result";
int position;
RemoveFromFollowList(int storeid, int pos) {
this.storeid = storeid;
position = pos;
}
@Override
protected Void doInBackground(Void... arg0) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs
.add(new BasicNameValuePair("store_id", "" + storeid));
nameValuePairs.add(new BasicNameValuePair("customer_id", ""
+ Appconstants.user.getCustomer_id()));
try {
//
result = IoptimeRoot.getJSONfromURL(Appconstants.Server
+ "unfollow_store.php", nameValuePairs, 0);
Log.d("result", "--" + result);
if (result.equalsIgnoreCase("") | result.contains("empty")
| result.contains("err")) {
} else {
// JSONArray jArray = new JSONArray(result);
//
// for (int i = 0; i < jArray.length(); i++) {
// JSONObject json_data = jArray.getJSONObject(i);
// userid = Integer.parseInt(json_data.getString(
// "customer_id").trim());
//
// }
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
@Override
protected void onPostExecute(Void params) {
if (result.equalsIgnoreCase("")) {
Toast.makeText(activity.getApplicationContext(), "Removed",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(activity.getApplicationContext(),
"Error while removing", Toast.LENGTH_LONG).show();
// if failed removing
shopArray.get(position).setFollowed(true);
notifyDataSetChanged();
}
}
}
}
<file_sep>/src/com/iopitme/betty/vendor/ProductReportsFragment.java
package com.iopitme.betty.vendor;
import java.util.ArrayList;
import com.ioptime.betty.R;
import com.ioptime.betty.R.id;
import com.ioptime.betty.R.layout;
import com.ioptime.betty.model.ProductReportsModel;
import com.ioptime.extendablelibrary.IoptimeFragment;
import com.ioptime.vendor.adapters.ProductReportsAdapter;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
public class ProductReportsFragment extends IoptimeFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.product_reports_fragment,
container, false);
String[] OID = new String[3];
OID[0] = "1";
OID[1] = "5";
OID[2] = "2";
ArrayList<ProductReportsModel> pdata = new ArrayList<ProductReportsModel>();
for (int i = 0; i < OID.length; i++) {
ProductReportsModel Ritems = new ProductReportsModel(0,
"rasasasasklopasasas sdhasjkhdjka", "ras007", 3, "60%", 5,
OID);
pdata.add(Ritems);
}
ListView pRecordsLV = (ListView) rootView.findViewById(R.id.pReportsLV);
ProductReportsAdapter adapter = new ProductReportsAdapter(
getActivity(), pdata);
pRecordsLV.setAdapter(adapter);
return rootView;
}
@Override
public void onResume() {
super.onResume();
((MainMenuVendor) getActivity()).getActionBar().setTitle(
"Products Report");
}
}
<file_sep>/src/com/ioptime/betty/model/WorldCountries.java
package com.ioptime.betty.model;
import android.os.Parcel;
import android.os.Parcelable;
public class WorldCountries implements Parcelable {
int id;
String name;
String iso_code_3;
String addressFormat;
int postcodeRequired;
int status;
public WorldCountries(int id, String name, String iso_code_3,
String addressFormat, int postcodeRequired, int status) {
super();
this.id = id;
this.name = name;
this.iso_code_3 = iso_code_3;
this.addressFormat = addressFormat;
this.postcodeRequired = postcodeRequired;
this.status = status;
}
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;
}
public String getIso_code_3() {
return iso_code_3;
}
public void setIso_code_3(String iso_code_3) {
this.iso_code_3 = iso_code_3;
}
public String getAddressFormat() {
return addressFormat;
}
public void setAddressFormat(String addressFormat) {
this.addressFormat = addressFormat;
}
public int getPostcodeRequired() {
return postcodeRequired;
}
public void setPostcodeRequired(int postcodeRequired) {
this.postcodeRequired = postcodeRequired;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public static final Parcelable.Creator<WorldCountries> CREATOR = new Parcelable.Creator<WorldCountries>() {
public WorldCountries createFromParcel(Parcel in) {
return new WorldCountries(in);
}
public WorldCountries[] newArray(int size) {
return new WorldCountries[size];
}
};
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeInt(id);
dest.writeString(iso_code_3);
dest.writeString(addressFormat);
dest.writeString(name);
dest.writeInt(postcodeRequired);
dest.writeInt(status);
}
private WorldCountries(Parcel in) {
this.id = in.readInt();
this.iso_code_3 = in.readString();
this.addressFormat = in.readString();
this.name = in.readString();
this.postcodeRequired = in.readInt();
this.status = in.readInt();
}
}
<file_sep>/src/com/ioptime/betty/ProfileFragment.java
package com.ioptime.betty;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.ioptime.extendablelibrary.IoptimeFragment;
public class ProfileFragment extends IoptimeFragment {
FragmentTabHost mTabHost;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.profile, container, false);
mTabHost = (FragmentTabHost) rootView
.findViewById(android.R.id.tabhost);
mTabHost.setup(getActivity(), getChildFragmentManager(),
android.R.id.tabcontent);
Bundle b = new Bundle();
b.putBoolean("wish", true);
mTabHost.addTab(
mTabHost.newTabSpec("tab1").setIndicator("WishList", null),
ProductListFragment.class, b);
mTabHost.addTab(
mTabHost.newTabSpec("tab2").setIndicator("Followed", null),
ShopFollowedFragment.class, b);
mTabHost.addTab(
mTabHost.newTabSpec("tab3").setIndicator("My Blogs", null),
MyBlogsFragment.class, b);
mTabHost.addTab(
mTabHost.newTabSpec("tab4").setIndicator("Profile", null),
ProfileEditFragment.class, b);
return rootView;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
List<Fragment> fragments = getChildFragmentManager().getFragments();
if (fragments != null) {
for (Fragment fragment : fragments) {
fragment.onActivityResult(requestCode, resultCode, data);
}
}
}
@Override
public void onResume() {
super.onResume();
((MainMenu) getActivity()).getActionBar().setTitle("Profile");
}
}<file_sep>/src/com/ioptime/betty/ShopProductsFragment.java
package com.ioptime.betty;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.iopitme.betty.vendor.MainMenuVendor;
import com.ioptime.adapters.ShopProductAdapter;
import com.ioptime.betty.model.Product;
import com.ioptime.extendablelibrary.IoptimeFragment;
public class ShopProductsFragment extends IoptimeFragment {
ProgressDialog progressDialog;
int id;
String name;
ListView listViewCategories;
TextView tvFollowers, tvName;
public ArrayList<Product> productList = new ArrayList<Product>();
public ShopProductsFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
id = getArguments().getInt("id");
name = getArguments().getString("name");
View rootView = inflater.inflate(R.layout.shop_products, container,
false);
listViewCategories = (ListView) rootView
.findViewById(R.id.shopProductsList);
tvFollowers = (TextView) rootView
.findViewById(R.id.shopProductTVShopFollowers);
tvName = (TextView) rootView.findViewById(R.id.shopProductTVShopName);
tvName.setText("" + name);
new ProductListBT().execute();
new FollowersBT().execute();
// }
return rootView;
}
private class ProductListBT extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(getActivity(),
"Please wait ...", "Getting products ...", true);
progressDialog.setCancelable(true);
}
@Override
protected Void doInBackground(Void... arg0) {
try {
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("store_id", "" + id));//
String result = "";
result = getJSONfromURL(Appconstants.Server
+ "products_get_by_store.php", params, 0);
Log.d("result", "--" + result);
if (result.equalsIgnoreCase("") | result.contains("empty")
| result.contains("err")) {
// not valid
} else {
productList = new ArrayList<Product>();
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
productList.add(new Product(Integer.parseInt(json_data
.getString("product_id").trim()), json_data
.getString("model").trim(), json_data
.getString("location").trim(),
Appconstants.ImageUrl
+ json_data.getString("image").trim(),
json_data.getString("date_available").trim(),
Integer.parseInt(json_data.getString("status")
.trim()), json_data.getString(
"date_added").trim(), json_data
.getString("product_name").trim(),
json_data.getString("description").trim(),
Integer.parseInt(json_data
.getString("store_id").trim()),
json_data.getString("store_name").trim(),
json_data.getString("url").trim(), Float
.parseFloat(json_data
.getString("price").trim()),
false));
}
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
@Override
protected void onPostExecute(Void params) {
progressDialog.cancel();
populateListView();
}
}
private class FollowersBT extends AsyncTask<Void, Void, Void> {
int followers = 0;
@Override
protected Void doInBackground(Void... arg0) {
try {
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("store_id", "" + id));//
String result = "";
result = getJSONfromURL(Appconstants.Server
+ "number_of_followers_store.php", params, 0);
Log.d("result", "--" + result);
if (result.equalsIgnoreCase("") | result.contains("empty")
| result.contains("err")) {
// not valid
} else {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
followers = Integer.parseInt(json_data.getString(
"number_of_followers").trim());
}
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
@Override
protected void onPostExecute(Void params) {
tvFollowers.setText(followers + " Followers");
}
}
public void populateListView() {
if (productList.size() > 0) {
ShopProductAdapter catAdapter = new ShopProductAdapter(
getActivity(), productList);
listViewCategories.setAdapter(catAdapter);
catAdapter.notifyDataSetChanged();
listViewCategories
.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
//
ProductDetailFragment prodFrag = new ProductDetailFragment();
Bundle bundle = new Bundle();
bundle.putInt("position", position);
prodFrag.setArguments(bundle);
getFragmentManager().beginTransaction()
.replace(R.id.frame_container, prodFrag)
.addToBackStack(null).commit();
}
});
} else {
Toast.makeText(getActivity(), "There are no products to show",
Toast.LENGTH_LONG).show();
}
}
@Override
public void onResume() {
super.onResume();
((MainMenu) getActivity()).getActionBar().setTitle(
"Shop Products");
}
}
<file_sep>/src/com/ioptime/adapters/MessageInboxAdapter.java
package com.ioptime.adapters;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.image.loader.ImageLoader;
import com.ioptime.betty.R;
import com.ioptime.betty.model.Message;
public class MessageInboxAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<Message> messageArray;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
public MessageInboxAdapter(Activity a, ArrayList<Message> i) {
activity = a;
messageArray = i;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext(),
R.drawable.ic_launcher);
}
public int getCount() {
return messageArray.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null) {
vi = inflater.inflate(R.layout.item_inbox, null);
}
//
TextView textMessage = (TextView) vi.findViewById(R.id.inboxTVMessage);
TextView textHeading = (TextView) vi.findViewById(R.id.inboxTVHeading);
textMessage.setText(messageArray.get(position).getMessage_subject());
textHeading.setText(messageArray.get(position).getSenderName());
return vi;
}
}<file_sep>/src/com/ioptime/adapters/CartAdapter.java
package com.ioptime.adapters;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.image.loader.ImageLoader;
import com.ioptime.betty.Appconstants;
import com.ioptime.betty.MainMenu;
import com.ioptime.betty.R;
import com.ioptime.betty.model.Cart;
import com.ioptime.betty.model.Product;
public class CartAdapter extends BaseAdapter {
private Activity activity;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
ArrayList<Cart> cartList;
public CartAdapter(Activity a, ArrayList<Cart> cartlist) {
activity = a;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext(),
R.drawable.ic_launcher);
cartList = new ArrayList<Cart>();
Log.d("cart", "-" + cartlist.size());
for (int i = 0; i < cartlist.size(); i++) {
if (Collections.frequency(cartlist, cartlist.get(i)) == 1) {
Cart c = cartlist.get(i);
c.setQty(1);
cartList.add(c);
} else {
Cart c = cartlist.get(i);
int freq = Collections.frequency(cartlist, c);
c.setQty(freq);
cartList.add(c);
}
}
// removing duplicates from list
cartList = new ArrayList<Cart>(new LinkedHashSet<Cart>(cartList));
}
@Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
public int getCount() {
return cartList.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.item_cart, null);
//
try {
LinearLayout layout = (LinearLayout) vi.findViewById(R.id.cartList);
TextView textName = (TextView) vi.findViewById(R.id.cartListName);
TextView textStoreName = (TextView) vi
.findViewById(R.id.cartListStore);
TextView textPrice = (TextView) vi.findViewById(R.id.cartListPrice);
TextView textQty = (TextView) vi.findViewById(R.id.cartListQty);
TextView textTotPrice = (TextView) vi
.findViewById(R.id.cartListTPrice);
ImageView image = (ImageView) vi.findViewById(R.id.cartImage);
TextView tvRemove = (TextView) vi.findViewById(R.id.cartListRemove);
tvRemove.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
cartList.get(position).setQty(
cartList.get(position).getQty() - 1);
removeFromCart(cartList.get(position).getProductid());
if (cartList.get(position).getQty() == 0) {
// remove element
cartList.remove(position);
}
notifyDataSetChanged();
}
});
int index = Collections.binarySearch(Appconstants.productsList,
new Product(cartList.get(position).getProductid(), true),
Product.c);
if (index >= 0) {
textName.setText(Appconstants.productsList.get(index).getName());
textStoreName.setText(Appconstants.productsList.get(index)
.getStoreName());
textPrice.setText(""
+ Appconstants.productsList.get(index).getPrice());
textTotPrice.setText(" = " + cartList.get(position).getQty()
* Appconstants.productsList.get(index).getPrice());
imageLoader.DisplayImage(Appconstants.productsList.get(index)
.getImage(), image, R.drawable.ic_launcher);
}
textQty.setText("X " + cartList.get(position).getQty());
} catch (Exception e) {
e.printStackTrace();
}
return vi;
}
protected void removeFromCart(int prod_id) {
ArrayList<Cart> cartTemp = Appconstants.getCartList(activity
.getApplicationContext());
for (int i = 0; i < cartTemp.size(); i++) {
Cart c = cartTemp.get(i);
if (c.getProductid() == prod_id
&& c.getUser_id() == Appconstants.user.getCustomer_id()) {
cartTemp.remove(i);
break;
}
}
Appconstants.setCartList(cartTemp, activity.getApplicationContext());
((MainMenu) activity).updateCartCount(cartTemp.size());
}
}
<file_sep>/src/com/ioptime/betty/model/Message.java
package com.ioptime.betty.model;
public class Message {
int message_id;
int message_to;
String senderName;
public String getSenderName() {
return senderName;
}
public void setSenderName(String senderName) {
this.senderName = senderName;
}
public int getMessage_id() {
return message_id;
}
public void setMessage_id(int message_id) {
this.message_id = message_id;
}
public int getMessage_to() {
return message_to;
}
public void setMessage_to(int message_to) {
this.message_to = message_to;
}
public Message(int message_id, int message_to, String message_subject,
String message_status, String group_message,
String group_message_id, String message_created_date,
String message_reference_id, String message_sub_reference_id,
String message_customer_id, String message_user_id,
String message_order_id, String message_last_update,
String message_last_modified, int customer_read,
int fcustomer_read, int support_read, int user_type,
int admin_status, int vendor_status, int customer_status,
int transfer_status, int transfer_message_id, String attachment,
int content_id, String content, int is_user, int sender_id,
int reply_status, int message_read_customer,
int message_read_support, String created, String file,String senderName) {
super();
this.message_id = message_id;
this.message_to = message_to;
this.message_subject = message_subject;
this.message_status = message_status;
this.group_message = group_message;
this.group_message_id = group_message_id;
this.senderName=senderName;
try {
// parsing date to date and time
String dateTime[] = message_created_date.split(" ");
this.message_created_date = dateTime[0];
this.message_created_time = dateTime[1];
} catch (Exception e) {
e.printStackTrace();
}
this.message_reference_id = message_reference_id;
this.message_sub_reference_id = message_sub_reference_id;
this.message_customer_id = message_customer_id;
this.message_user_id = message_user_id;
this.message_order_id = message_order_id;
this.message_last_update = message_last_update;
this.message_last_modified = message_last_modified;
this.customer_read = customer_read;
this.fcustomer_read = fcustomer_read;
this.support_read = support_read;
this.user_type = user_type;
this.admin_status = admin_status;
this.vendor_status = vendor_status;
this.customer_status = customer_status;
this.transfer_status = transfer_status;
this.transfer_message_id = transfer_message_id;
Attachment = attachment;
this.content_id = content_id;
this.content = content;
this.is_user = is_user;
this.sender_id = sender_id;
this.reply_status = reply_status;
this.message_read_customer = message_read_customer;
this.message_read_support = message_read_support;
this.created = created;
this.file = file;
}
public String getMessage_subject() {
return message_subject;
}
public void setMessage_subject(String message_subject) {
this.message_subject = message_subject;
}
public String getMessage_status() {
return message_status;
}
public void setMessage_status(String message_status) {
this.message_status = message_status;
}
public String getGroup_message() {
return group_message;
}
public void setGroup_message(String group_message) {
this.group_message = group_message;
}
public String getGroup_message_id() {
return group_message_id;
}
public void setGroup_message_id(String group_message_id) {
this.group_message_id = group_message_id;
}
public String getMessage_created_date() {
return message_created_date;
}
public void setMessage_created_date(String message_created_date) {
this.message_created_date = message_created_date;
}
public String getMessage_created_time() {
return message_created_time;
}
public void setMessage_created_time(String message_created_time) {
this.message_created_time = message_created_time;
}
public String getMessage_reference_id() {
return message_reference_id;
}
public void setMessage_reference_id(String message_reference_id) {
this.message_reference_id = message_reference_id;
}
public String getMessage_sub_reference_id() {
return message_sub_reference_id;
}
public void setMessage_sub_reference_id(String message_sub_reference_id) {
this.message_sub_reference_id = message_sub_reference_id;
}
public String getMessage_customer_id() {
return message_customer_id;
}
public void setMessage_customer_id(String message_customer_id) {
this.message_customer_id = message_customer_id;
}
public String getMessage_user_id() {
return message_user_id;
}
public void setMessage_user_id(String message_user_id) {
this.message_user_id = message_user_id;
}
public String getMessage_order_id() {
return message_order_id;
}
public void setMessage_order_id(String message_order_id) {
this.message_order_id = message_order_id;
}
public String getMessage_last_update() {
return message_last_update;
}
public void setMessage_last_update(String message_last_update) {
this.message_last_update = message_last_update;
}
public String getMessage_last_modified() {
return message_last_modified;
}
public void setMessage_last_modified(String message_last_modified) {
this.message_last_modified = message_last_modified;
}
public int getCustomer_read() {
return customer_read;
}
public void setCustomer_read(int customer_read) {
this.customer_read = customer_read;
}
public int getFcustomer_read() {
return fcustomer_read;
}
public void setFcustomer_read(int fcustomer_read) {
this.fcustomer_read = fcustomer_read;
}
public int getSupport_read() {
return support_read;
}
public void setSupport_read(int support_read) {
this.support_read = support_read;
}
public int getUser_type() {
return user_type;
}
public void setUser_type(int user_type) {
this.user_type = user_type;
}
public int getAdmin_status() {
return admin_status;
}
public void setAdmin_status(int admin_status) {
this.admin_status = admin_status;
}
public int getVendor_status() {
return vendor_status;
}
public void setVendor_status(int vendor_status) {
this.vendor_status = vendor_status;
}
public int getCustomer_status() {
return customer_status;
}
public void setCustomer_status(int customer_status) {
this.customer_status = customer_status;
}
public int getTransfer_status() {
return transfer_status;
}
public void setTransfer_status(int transfer_status) {
this.transfer_status = transfer_status;
}
public int getTransfer_message_id() {
return transfer_message_id;
}
public void setTransfer_message_id(int transfer_message_id) {
this.transfer_message_id = transfer_message_id;
}
public String getAttachment() {
return Attachment;
}
public void setAttachment(String attachment) {
Attachment = attachment;
}
public int getContent_id() {
return content_id;
}
public void setContent_id(int content_id) {
this.content_id = content_id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getIs_user() {
return is_user;
}
public void setIs_user(int is_user) {
this.is_user = is_user;
}
public int getSender_id() {
return sender_id;
}
public void setSender_id(int sender_id) {
this.sender_id = sender_id;
}
public int getReply_status() {
return reply_status;
}
public void setReply_status(int reply_status) {
this.reply_status = reply_status;
}
public int getMessage_read_customer() {
return message_read_customer;
}
public void setMessage_read_customer(int message_read_customer) {
this.message_read_customer = message_read_customer;
}
public int getMessage_read_support() {
return message_read_support;
}
public void setMessage_read_support(int message_read_support) {
this.message_read_support = message_read_support;
}
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
String message_subject;
String message_status;
String group_message;
String group_message_id;
String message_created_date;
String message_created_time;
String message_reference_id;
String message_sub_reference_id;
String message_customer_id;
String message_user_id;
String message_order_id;
String message_last_update;
String message_last_modified;
int customer_read;
int fcustomer_read;
int support_read;
/////user type is reciever
int user_type;
int admin_status;
int vendor_status;
int customer_status;
int transfer_status;
int transfer_message_id;
String Attachment;
int content_id;
String content;
int is_user;
////reciever id
int sender_id;
int reply_status;
int message_read_customer;
int message_read_support;
String created;
String file;
}
<file_sep>/src/com/ioptime/betty/SubCategoryFragment.java
package com.ioptime.betty;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import com.ioptime.adapters.CategoryAdapter;
import com.ioptime.betty.model.Category;
import com.ioptime.extendablelibrary.IoptimeFragment;
public class SubCategoryFragment extends IoptimeFragment {
ProgressDialog progressDialog;
int position;
ListView listViewCategories;
public ArrayList<Category> subCatList = new ArrayList<Category>();
public SubCategoryFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
position = getArguments().getInt("position");
View rootView = inflater.inflate(R.layout.categories, container, false);
listViewCategories = (ListView) rootView
.findViewById(R.id.categoryList);
if (Appconstants.categoryList.size() == 0) {
// new ProductListBT().execute();
Toast.makeText(getActivity(), "Check your internet connection",
Toast.LENGTH_LONG).show();
} else {
new SubCatListBT().execute();
}
return rootView;
}
private class SubCatListBT extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(getActivity(),
"Please wait ...", "Getting sub categories ...", true);
progressDialog.setCancelable(true);
}
@Override
protected Void doInBackground(Void... arg0) {
try {
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("category_id", ""
+ Appconstants.categoryList.get(position)
.getCategoryId()));//
String result = "";
result = getJSONfromURL(Appconstants.Server
+ "category_get_sub.php", params, 0);
Log.d("result", "--" + result);
if (result.equalsIgnoreCase("") | result.contains("empty")
| result.contains("err")) {
// not valid
} else {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
subCatList.add(new Category(Integer.parseInt(json_data
.getString("category_id").trim()),
Appconstants.ImageUrl
+ json_data.getString("image").trim(),
Integer.parseInt(json_data.getString(
"parent_id").trim()), Integer
.parseInt(json_data.getString("top")
.trim()), Integer
.parseInt(json_data.getString("column")
.trim()), Integer
.parseInt(json_data.getString(
"sort_order").trim()), Integer
.parseInt(json_data.getString("status")
.trim()), json_data.getString(
"date_added").trim(), json_data
.getString("date_modified").trim(),
Integer.parseInt(json_data.getString(
"language_id").trim()), json_data
.getString("name").trim(), json_data
.getString("description").trim(),
json_data.getString("meta_description").trim(),
json_data.getString("meta_keyword").trim()));
}
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
@Override
protected void onPostExecute(Void params) {
progressDialog.cancel();
populateListView();
}
}
public void populateListView() {
if (subCatList.size() > 0) {
CategoryAdapter catAdapter = new CategoryAdapter(getActivity(),
subCatList);
listViewCategories.setAdapter(catAdapter);
catAdapter.notifyDataSetChanged();
listViewCategories
.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
//
// ProductDetailFragment prodFrag = new
// ProductDetailFragment();
// Bundle bundle = new Bundle();
// bundle.putInt("position", position);
// prodFrag.setArguments(bundle);
// getFragmentManager().beginTransaction()
// .replace(R.id.frame_container, prodFrag)
// .addToBackStack(null).commit();
}
});
} else {
Toast.makeText(getActivity(),
"There are no sub categories to show", Toast.LENGTH_LONG)
.show();
}
}
}
<file_sep>/src/com/ioptime/betty/model/Comment.java
package com.ioptime.betty.model;
public class Comment {
int review_id;
int product_id;
int customer_id;
String text;
int rating;
String company;
int company_id;
public Comment(int review_id, int product_id, int customer_id, String text,
int rating, String company, int company_id, String author) {
super();
this.review_id = review_id;
this.product_id = product_id;
this.customer_id = customer_id;
this.text = text;
this.rating = rating;
this.company = company;
this.company_id = company_id;
this.author = author;
}
String author;
public int getReview_id() {
return review_id;
}
public void setReview_id(int review_id) {
this.review_id = review_id;
}
public int getProduct_id() {
return product_id;
}
public void setProduct_id(int product_id) {
this.product_id = product_id;
}
public int getCustomer_id() {
return customer_id;
}
public void setCustomer_id(int customer_id) {
this.customer_id = customer_id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public int getCompany_id() {
return company_id;
}
public void setCompany_id(int company_id) {
this.company_id = company_id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
<file_sep>/src/com/ioptime/betty/MainActivity.java
package com.ioptime.betty;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import com.ioptime.extendablelibrary.IoptimeActivity;
public class MainActivity extends IoptimeActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void signUp(View v) {
finish();
startActivitySwipe(MainActivity.this, new Intent(MainActivity.this,
SignUp.class));
}
public void login(View v) {
finish();
startActivitySwipe(MainActivity.this, new Intent(MainActivity.this,
Login.class));
}
@Override
protected int getLayoutResourceId() {
// TODO Auto-generated method stub
return R.layout.activity_main;
}
}
<file_sep>/src/com/ioptime/betty/ContactFragment.java
package com.ioptime.betty;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.iopitme.betty.vendor.MainMenuVendor;
import com.ioptime.extendablelibrary.IoptimeFragment;
public class ContactFragment extends IoptimeFragment {
EditText etName, etPhone, etIssue;
ArrayList<EditText> editTextArray = new ArrayList<EditText>();
ProgressDialog progressDialog;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.contact, container, false);
etName = (EditText) rootView.findViewById(R.id.contactETName);
editTextArray.add(etName);
etName.setText(Appconstants.user.getFirstName() + " "
+ Appconstants.user.getFirstName());
etPhone = (EditText) rootView.findViewById(R.id.contactETPhone);
editTextArray.add(etPhone);
etPhone.setText(Appconstants.user.getTelephone());
etIssue = (EditText) rootView.findViewById(R.id.contactETIssue);
editTextArray.add(etIssue);
Button btSend = (Button) rootView.findViewById(R.id.contactBtSend);
btSend.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (inputAll()) {
if (isConnectedToInternet(getActivity())) {
new ContactBTTask().execute();
} else {
Toast.makeText(getActivity(),
"Check your internet connection",
Toast.LENGTH_SHORT).show();
}
}
}
});
return rootView;
}
public boolean inputAll() {
for (EditText edit : editTextArray) {
if (TextUtils.isEmpty(edit.getText().toString().trim())) {
edit.setError(edit.getHint() + " can not be empty");
return false;
} else {
edit.setError(null, null);
}
}
return true;
}
private class ContactBTTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(getActivity(),
"Please wait ...", "Submitting issue ...", true);
progressDialog.setCancelable(true);
}
@Override
protected Void doInBackground(Void... arg0) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email",
Appconstants.user.getEmail()));
nameValuePairs.add(new BasicNameValuePair("name", etName.getText()
.toString()));
nameValuePairs.add(new BasicNameValuePair("phone", etPhone
.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("message", etIssue
.getText().toString()));
try {
//
String result = "";
result = getJSONfromURL(Appconstants.Server + "contact.php",
nameValuePairs, 0);
Log.d("result", "--" + result);
if (result.equalsIgnoreCase("") | result.contains("empty")
| result.contains("err")) {
// not valid
} else {
// JSONArray jArray = new JSONArray(result);
// for (int i = 0; i < jArray.length(); i++) {
// JSONObject json_data = jArray.getJSONObject(i);
// userid = Integer.parseInt(json_data.getString(
// "customer_id").trim());
//
// }
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
@Override
protected void onPostExecute(Void params) {
progressDialog.cancel();
Toast.makeText(getActivity(), "Issue submitted", Toast.LENGTH_LONG)
.show();
}
}
@Override
public void onResume() {
super.onResume();
((MainMenu) getActivity()).getActionBar().setTitle("Contact Us");
}
}
<file_sep>/src/com/ioptime/betty/Login.java
package com.ioptime.betty;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.iopitme.betty.vendor.MainMenuVendor;
import com.ioptime.betty.model.User;
import com.ioptime.betty.model.Vendor;
import com.ioptime.extendablelibrary.IoptimeActivity;
public class Login extends IoptimeActivity {
EditText etPass, etEmail;
ArrayList<EditText> editTextArray = new ArrayList<EditText>();
ProgressDialog progressDialog;
ToggleButton tbCustOrVend;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
etPass = (EditText) findViewById(R.id.loginETPass);
editTextArray.add(etPass);
etEmail = (EditText) findViewById(R.id.loginETEmail);
editTextArray.add(etEmail);
tbCustOrVend = (ToggleButton) findViewById(R.id.loginTBCustOrVend);
tbCustOrVend.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (tbCustOrVend.getText().toString()
.equalsIgnoreCase("Customer")) {
etPass.setText("<PASSWORD>");
etEmail.setText("mharoon");
}
if (tbCustOrVend.getText().toString()
.equalsIgnoreCase("Vendor")) {
etPass.setText("<PASSWORD>6");
etEmail.setText("rasheed");
}
}
});
}
@Override
protected int getLayoutResourceId() {
// TODO Auto-generated method stub
return R.layout.login;
}
public void login(View v) {
if (inputAll()) {
if (isConnectedToInternet(Login.this)) {
if (tbCustOrVend.getText().toString()
.equalsIgnoreCase("Customer")) {
new LoginUserBT().execute();
} else if (tbCustOrVend.getText().toString()
.equalsIgnoreCase("Vendor")) {
new LoginVendorBT().execute();
}
} else {
Toast.makeText(getApplicationContext(),
"Check your internet connection", Toast.LENGTH_LONG)
.show();
}
} else {
}
}
public boolean inputAll() {
for (EditText edit : editTextArray) {
if (TextUtils.isEmpty(edit.getText().toString().trim())) {
edit.setError(edit.getHint() + " can not be empty");
return false;
} else {
edit.setError(null, null);
}
}
return true;
}
private class LoginUserBT extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(Login.this, "Please wait ...",
"Logging in ...", true);
progressDialog.setCancelable(true);
}
@Override
protected Void doInBackground(Void... arg0) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email", etEmail
.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("password", etPass
.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("ip",
getIPofDevicePublic()));
try {
//
String result = "";
result = getJSONfromURL(Appconstants.Server
+ "login_customer.php", nameValuePairs, 0);
Log.d("result", "--" + result);
if (result.equalsIgnoreCase("") | result.contains("empty")
| result.contains("err")) {
// not valid
Appconstants.user = new User();
Appconstants.user.setCustomer_id(0);
} else {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Appconstants.user = new User(Integer.parseInt(json_data
.getString("customer_id").trim()),
Integer.parseInt(json_data
.getString("store_id").trim()),
json_data.getString("firstname").trim(),
json_data.getString("lastname").trim(),
json_data.getString("email").trim(), json_data
.getString("telephone").trim(),
json_data.getString("fax").trim(), json_data
.getString("cart").trim(), null, null,
json_data.getString("newsletter").trim(),
Integer.parseInt(json_data.getString(
"address_id").trim()),
Integer.parseInt(json_data.getString(
"customer_group_id").trim()), json_data
.getString("ip").trim(),
Integer.parseInt(json_data.getString("status")
.trim()), Integer.parseInt(json_data
.getString("approved").trim()),
json_data.getString("logo").trim(), json_data
.getString("pay_status").trim(),
json_data.getString("topic").trim());
}
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
@Override
protected void onPostExecute(Void params) {
if (progressDialog.isShowing()) {
progressDialog.cancel();
}
if (Appconstants.user.getCustomer_id() != 0) {
savePref(Appconstants.user.getCustomer_id());
Toast.makeText(getApplicationContext(), "Successful login",
Toast.LENGTH_LONG).show();
startActivitySwipe(Login.this, new Intent(Login.this,
MainMenu.class));
finish();
} else {
Toast.makeText(getApplicationContext(),
"Error while login in, try again", Toast.LENGTH_LONG)
.show();
}
}
}
private class LoginVendorBT extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(Login.this, "Please wait ...",
"Logging in ...", true);
progressDialog.setCancelable(true);
}
@Override
protected Void doInBackground(Void... arg0) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", etEmail
.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("password", <PASSWORD>
.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("ip",
getIPofDevicePublic()));
try {
//
String result = "";
result = getJSONfromURL(Appconstants.Server
+ "login_vendor_admin.php", nameValuePairs, 0);
Log.d("result", "--Vender--" + result);
if (result.equalsIgnoreCase("")
| result.equalsIgnoreCase("empty")) {
// not valid
Appconstants.vendor = new Vendor();
Appconstants.vendor.setUser_id(0);
} else {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Appconstants.vendor = new Vendor(
Integer.parseInt(json_data.getString("user_id")
.trim()), json_data.getString(
"firstname").trim(), json_data
.getString("lastname").trim(),
json_data.getString("email").trim(), json_data
.getString("telephone").trim(),
json_data.getString("topic").trim(), json_data
.getString("vendor_image").trim(),
json_data.getString("username".trim()));
Log.d("vederID",
""
+ Integer.parseInt(json_data.getString(
"user_id").trim()));
}
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
@Override
protected void onPostExecute(Void params) {
if (progressDialog.isShowing()) {
progressDialog.cancel();
}
if (Appconstants.vendor.getUser_id() != 0) {
savePref(Appconstants.vendor.getUser_id());
Toast.makeText(getApplicationContext(), "Successful login",
Toast.LENGTH_LONG).show();
startActivitySwipe(Login.this, new Intent(Login.this,
MainMenuVendor.class));
Appconstants.isVendor = true;
finish();
} else {
Toast.makeText(getApplicationContext(),
"Error while login in, try again", Toast.LENGTH_LONG)
.show();
}
}
}
private void savePref(int userid) {
SharedPreferences settings;
settings = getSharedPreferences(Appconstants.PREFNAME,
Context.MODE_PRIVATE);
// set the sharedpref
Editor editor = settings.edit();
editor.putInt("userid", userid);
editor.putString("email", etEmail.getText().toString());
editor.commit();
}
}
<file_sep>/src/com/ioptime/betty/WishlistFragment.java
package com.ioptime.betty;
import com.ioptime.extendablelibrary.IoptimeFragment;
public class WishlistFragment extends IoptimeFragment {
}
<file_sep>/src/com/iopitme/betty/vendor/ProductListFragmentVendor.java
package com.iopitme.betty.vendor;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.image.loader.ImageLoader;
import com.ioptime.betty.Appconstants;
import com.ioptime.betty.R;
import com.ioptime.betty.model.Product;
import com.ioptime.extendablelibrary.IoptimeFragment;
import com.ioptime.vendor.adapters.ProductAdapterVendors;
public class ProductListFragmentVendor extends IoptimeFragment {
ProgressBar progressDialog;
EditText pdEtSearch;
Button pdBtSearch;
ListView listViewProducts;
ProductAdapterVendors productAdapter;
ImageView StoreLogoIV;
ImageLoader imageloader;
String VenderFollowers;
TextView vendorFollTV;
public ProductListFragmentVendor() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.product, container, false);
listViewProducts = (ListView) rootView.findViewById(R.id.productList);
Button btnAddpd = (Button) rootView.findViewById(R.id.pdBtAdd);
LinearLayout ll = (LinearLayout) rootView.findViewById(R.id.ll);
TextView StoreDecTV = (TextView) rootView
.findViewById(R.id.StoreDescriptionTV);
vendorFollTV = (TextView) rootView.findViewById(R.id.vendorFollTV);
StoreLogoIV = (ImageView) rootView.findViewById(R.id.IVStoreLogo);
btnAddpd.setVisibility(View.VISIBLE);
ll.setVisibility(View.VISIBLE);
progressDialog = (ProgressBar) rootView
.findViewById(R.id.productProgressBar);
// / Setting logo
imageloader = new ImageLoader(getActivity(), R.drawable.store_logo);
imageloader.DisplayImage("http://sandbox.baitymall.com/image/"
+ Appconstants.vendor.getLogoURl(), StoreLogoIV,
ImageLoader.NORMAL);
// Set Vendor Description /
StoreDecTV.setText(Appconstants.vendor.getTopic());
// Set Followers
new VendorFollowersBTTask().execute();
if (Appconstants.productsList.size() == 0) {
Log.d("pop", "size-" + Appconstants.productsList.size());
new ProductListBT().execute();
} else {
populateListView();
}
pdEtSearch = (EditText) rootView.findViewById(R.id.pdETSearch);
pdEtSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
if (pdEtSearch.getText().toString().equalsIgnoreCase("")) {
new ProductListBT().execute();
}
}
});
pdBtSearch = (Button) rootView.findViewById(R.id.pdBtSearch);
pdBtSearch.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (pdEtSearch.getText().toString().trim().equalsIgnoreCase("")) {
pdEtSearch.setError("Search field cannot be empty");
} else {
String search = pdEtSearch.getText().toString();
new ProductListSearchBT(search).execute();
} // TODO Auto-generated method stub
}
});
btnAddpd.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
AddNewProductFragment prodFrag = new AddNewProductFragment();
Bundle bundle = new Bundle();
bundle.putInt("position", 0);
bundle.putInt("switch", 0);
prodFrag.setArguments(bundle);
getFragmentManager().beginTransaction()
.replace(R.id.frame_container, prodFrag)
.addToBackStack(null).commit();
}
});
return rootView;
}
private class ProductListBT extends AsyncTask<Void, Void, Void> {
String result = "";
@Override
protected void onPreExecute() {
progressDialog.setVisibility(View.VISIBLE);
}
@Override
protected Void doInBackground(Void... arg0) {
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("user_id", ""+Appconstants.vendor.getUser_id()));
result = "";
result = getJSONfromURL(Appconstants.Server
+ "products_get_vendor.php", nameValuePairs, 0);
Log.d("result", "--" + result);
if (result.equalsIgnoreCase("") | result.contains("empty")
| result.contains("err")) {
// not valid
} else {
JSONArray jArray = new JSONArray(result);
Appconstants.productsList = new ArrayList<Product>();
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Product p = new Product(Integer.parseInt(json_data
.getString("product_id").trim()), json_data
.getString("model").trim(), json_data
.getString("location").trim(),
Appconstants.ImageUrl
+ json_data.getString("image").trim(),
json_data.getString("date_available").trim(),
Integer.parseInt(json_data.getString("status")
.trim()), json_data.getString(
"date_added").trim(), json_data
.getString("product_name").trim(),
json_data.getString("description").trim(),
Integer.parseInt(json_data
.getString("store_id").trim()),
json_data.getString("store_name").trim(),
json_data.getString("url").trim(),
Float.parseFloat(json_data.getString("price")
.trim()), false);
p.setCategory(json_data.getString("category_name"));
p.setManufacturer(json_data
.getString("manufacturer_name"));
p.setQuantity(json_data.getInt("product_quanitity"));
Appconstants.productsList.add(p);
}
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
@Override
protected void onPostExecute(Void params) {
progressDialog.setVisibility(View.GONE);
populateListView();
}
}
private void populateListView() {
if (Appconstants.productsList != null) {
if (Appconstants.productsList.size() > 0) {
productAdapter = new ProductAdapterVendors(getActivity(),
false, Appconstants.productsList);
listViewProducts.setAdapter(productAdapter);
productAdapter.notifyDataSetChanged();
listViewProducts
.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
AddNewProductFragment prodFrag = new AddNewProductFragment();
Bundle bundle = new Bundle();
bundle.putInt("position", position);
bundle.putInt("switch", 1);
prodFrag.setArguments(bundle);
getFragmentManager()
.beginTransaction()
.replace(R.id.frame_container, prodFrag)
.addToBackStack(null).commit();
}
});
}
}
}
private class ProductListSearchBT extends AsyncTask<Void, Void, Void> {
String search;
String result = "";
ProductListSearchBT(String search) {
this.search = search;
}
@Override
protected void onPreExecute() {
progressDialog.setVisibility(View.VISIBLE);
}
@Override
protected Void doInBackground(Void... arg0) {
try {
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user_id", ""
+ Appconstants.vendor.getUser_id()));
params.add(new BasicNameValuePair("search", "" + search));
//
result = "";
result = getJSONfromURL(Appconstants.Server
+ "products_search_vendor.php", params, 0);
Log.d("result", "--" + result);
if (result.equalsIgnoreCase("") | result.contains("empty")
| result.contains("err")) {
// not valid
} else {
JSONArray jArray = new JSONArray(result);
Appconstants.productsList.clear();
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Appconstants.productsList.add(new Product(Integer
.parseInt(json_data.getString("product_id")
.trim()), json_data.getString("model")
.trim(),
json_data.getString("location").trim(),
Appconstants.ImageUrl
+ json_data.getString("image").trim(),
json_data.getString("date_available").trim(),
Integer.parseInt(json_data.getString("status")
.trim()), json_data.getString(
"date_added").trim(), json_data
.getString("product_name").trim(),
json_data.getString("description").trim(),
Integer.parseInt(json_data
.getString("store_id").trim()),
json_data.getString("store_name").trim(),
json_data.getString("url").trim(), Float
.parseFloat(json_data
.getString("price").trim()),
false));
}
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
@Override
protected void onPostExecute(Void params) {
progressDialog.setVisibility(View.GONE);
if (result.equalsIgnoreCase("") | result.contains("empty")
| result.contains("err")) {
Toast.makeText(getActivity(), "No resut to show ",
Toast.LENGTH_LONG).show();
} else {
populateListView();
}
}
}
private class VendorFollowersBTTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... arg0) {
// TODO Auto-generated method stub
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user_id", ""
+ Appconstants.vendor.getUser_id()));//
String result = getJSONfromURL(Appconstants.Server
+ "store_followers_vendor.php", params, 0);
if (result.equalsIgnoreCase("") | result.contains("empty")
| result.contains("err")) {
// not valid
} else {
JSONArray jArray;
try {
jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
VenderFollowers = json_data
.getString("num_store_followers");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Log.d("result Message", "--" + result);
return result;
}
@Override
protected void onPostExecute(String params) {
vendorFollTV.setText(VenderFollowers);
}
}
// private class GetWishListBTTask extends AsyncTask<Void, Void, Void> {
// int customer_id;
//
// public GetWishListBTTask() {
// // TODO Auto-generated constructor stub
// customer_id = Appconstants.user.getCustomer_id();
// }
//
// @Override
// protected Void doInBackground(Void... arg0) {
//
// ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// nameValuePairs.add(new BasicNameValuePair("customer_id",
// customer_id + ""));
//
// try {
//
// //
// String result = "";
// result = getJSONfromURL(Appconstants.Server
// + "product_wishlist_get.php", nameValuePairs, 0);
// Log.d("result", "--" + result);
// ArrayList<Product> arrayWish = new ArrayList<Product>();
// Appconstants.user.setWishlist(arrayWish);
// if (result.equalsIgnoreCase("") | result.contains("empty")
// | result.contains("err")) {
// // not valid
//
// } else {
// JSONArray jArray = new JSONArray(result);
// for (int i = 0; i < jArray.length(); i++) {
// JSONObject json_data = jArray.getJSONObject(i);
// arrayWish.add(new Product(Integer.parseInt(json_data
// .getString("product_id").trim()), json_data
// .getString("model").trim(), json_data
// .getString("location").trim(),
// Appconstants.ImageUrl
// + json_data.getString("image").trim(),
// json_data.getString("date_available").trim(),
// Integer.parseInt(json_data.getString("status")
// .trim()), json_data.getString(
// "date_added").trim(), json_data
// .getString("product_name").trim(),
// json_data.getString("description").trim(),
// Integer.parseInt(json_data
// .getString("store_id").trim()),
// json_data.getString("store_name").trim(),
// json_data.getString("url").trim(), Float
// .parseFloat(json_data
// .getString("price").trim()),
// true));
//
// }
// }
// Appconstants.user.setWishlist(arrayWish);
// } catch (Exception e) {
//
// e.printStackTrace();
// return null;
// }
// return null;
// }
//
// @Override
// protected void onPostExecute(Void params) {
// if (productAdapter != null) {
// makeWishListLocal(Appconstants.productsList);
// productAdapter.notifyDataSetChanged();
// } else {
// if (ProductListFragment.this.isVisible()) {
// populateListView();
// }
// }
// }
// }
public void onBackPressed() {
FragmentManager fm = getActivity().getSupportFragmentManager();
fm.popBackStack();
}
@Override
public void onResume() {
super.onResume();
((MainMenuVendor) getActivity()).getActionBar().setTitle("Products");
}
}
<file_sep>/src/com/ioptime/betty/model/Shops.java
package com.ioptime.betty.model;
public class Shops {
public Shops(int id, String name, String url, String ssl, boolean follow) {
super();
this.id = id;
this.name = name;
this.url = url;
this.ssl = ssl;
this.isFollowed = follow;
}
int id;
String name;
String url;
String ssl;
boolean isFollowed;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean isFollowed() {
return isFollowed;
}
public void setFollowed(Boolean follow) {
this.isFollowed = follow;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getSsl() {
return ssl;
}
public void setSsl(String ssl) {
this.ssl = ssl;
}
}
<file_sep>/src/com/ioptime/betty/model/Category.java
package com.ioptime.betty.model;
public class Category {
int categoryId;
String image;
int parentId;
int top;
int column;
int sortOrder;
int status;
String dateAdded;
String dateModified;
int languageId;
String name;
String description;
String metaDescription;
String metaKeyword;
public int getCategoryId() {
return categoryId;
}
public void setCategoryId(int categoryId) {
this.categoryId = categoryId;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public int getParentId() {
return parentId;
}
public void setParentId(int parentId) {
this.parentId = parentId;
}
public int getTop() {
return top;
}
public void setTop(int top) {
this.top = top;
}
public int getColumn() {
return column;
}
public void setColumn(int column) {
this.column = column;
}
public int getSortOrder() {
return sortOrder;
}
public void setSortOrder(int sortOrder) {
this.sortOrder = sortOrder;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getDateAdded() {
return dateAdded;
}
public void setDateAdded(String dateAdded) {
this.dateAdded = dateAdded;
}
public String getDateModified() {
return dateModified;
}
public void setDateModified(String dateModified) {
this.dateModified = dateModified;
}
public int getLanguageId() {
return languageId;
}
public void setLanguageId(int languageId) {
this.languageId = languageId;
}
public String getName() {
return name;
}
public Category(int categoryId, String image, int parentId, int top,
int column, int sortOrder, int status, String dateAdded,
String dateModified, int languageId, String name,
String description, String metaDescription, String metaKeyword) {
super();
this.categoryId = categoryId;
this.image = image;
this.parentId = parentId;
this.top = top;
this.column = column;
this.sortOrder = sortOrder;
this.status = status;
this.dateAdded = dateAdded;
this.dateModified = dateModified;
this.languageId = languageId;
this.name = name;
this.description = description;
this.metaDescription = metaDescription;
this.metaKeyword = metaKeyword;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getMetaDescription() {
return metaDescription;
}
public void setMetaDescription(String metaDescription) {
this.metaDescription = metaDescription;
}
public String getMetaKeyword() {
return metaKeyword;
}
public void setMetaKeyword(String metaKeyword) {
this.metaKeyword = metaKeyword;
}
}
<file_sep>/src/com/ioptime/betty/Splash.java
package com.ioptime.betty;
import com.crashlytics.android.Crashlytics;
import io.fabric.sdk.android.Fabric;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.ioptime.betty.model.Category;
import com.ioptime.betty.model.CompanyM;
import com.ioptime.betty.model.WorldCountries;
import com.ioptime.extendablelibrary.IoptimeActivity;
public class Splash extends IoptimeActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
if (isConnectedToInternet(Splash.this)) {
new CategoryListBT().execute();
} else {
finish();
Toast.makeText(getApplicationContext(),
"Please check your internet connectivity",
Toast.LENGTH_LONG).show();
}
}
@Override
protected int getLayoutResourceId() {
// TODO Auto-generated method stub
return R.layout.splash;
}
private class GetCountriesBTTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
}
@Override
protected Void doInBackground(Void... arg0) {
String result = getJSONfromURL(Appconstants.Server
+ "country_get.php", null, 0);
Log.d("result", "--" + result);
Appconstants.world = new ArrayList<WorldCountries>();
// Create an array to populate the spinner
Appconstants.worldlist = new ArrayList<String>();
JSONArray jArray;
try {
jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Appconstants.world.add(new WorldCountries(
Integer.parseInt(json_data.getString("country_id")
.trim()), json_data.getString("name")
.trim(), json_data.getString("iso_code_3")
.trim(), json_data.getString(
"address_format").trim(), Integer
.parseInt(json_data.getString(
"postcode_required").trim()),
Integer.parseInt(json_data.getString("status")
.trim())));
Appconstants.worldlist.add(json_data.getString("name")
.trim());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void params) {
startActivitySwipe(Splash.this, new Intent(Splash.this,
MainActivity.class));
finish();
}
}
public class CategoryListBT extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
}
@Override
protected Void doInBackground(Void... arg0) {
try {
//
String result = "";
result = getJSONfromURL(Appconstants.Server
+ "category_get.php", null, 0);
Log.d("result", "--" + result);
if (result.equalsIgnoreCase("") | result.contains("empty")
| result.contains("err")) {
// not valid
} else {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Appconstants.categoryList.add(new Category(Integer
.parseInt(json_data.getString("category_id")
.trim()), Appconstants.ImageUrl
+ json_data.getString("image").trim(), Integer
.parseInt(json_data.getString("parent_id")
.trim()), Integer.parseInt(json_data
.getString("top").trim()),
Integer.parseInt(json_data.getString("column")
.trim()), Integer.parseInt(json_data
.getString("sort_order").trim()),
Integer.parseInt(json_data.getString("status")
.trim()), json_data.getString(
"date_added").trim(), json_data
.getString("date_modified").trim(),
Integer.parseInt(json_data.getString(
"language_id").trim()), json_data
.getString("name").trim(), json_data
.getString("description").trim(),
json_data.getString("meta_description").trim(),
json_data.getString("meta_keyword").trim()));
}
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
@Override
protected void onPostExecute(Void params) {
new MessageNameBT().execute();
}
}
private class MessageNameBT extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
}
@Override
protected Void doInBackground(Void... arg0) {
try {
//
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("timestamp", ""
+ System.currentTimeMillis()));
String result = "";
result = getJSONfromURL(Appconstants.Server
+ "store_name_get_send_message_vendor.php",
nameValuePairs, 0);
Log.d("resultVendor", "--" + result);
if (result.equalsIgnoreCase("") | result.contains("empty")
| result.contains("err")) {
// not valid
} else {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Appconstants.messageNamesArray.add(new CompanyM(Integer
.parseInt(json_data.getString("store_id")
.trim()), json_data
.getString("store_name"),
Integer.parseInt(json_data.getString("user_id")
.trim())));
Appconstants.vendors = i;
}
// calling for customer names
result = getJSONfromURL(Appconstants.Server
+ "company_name_get_send_message_customer.php",
nameValuePairs, 0);
Log.d("resultCustomer", "--" + result);
if (result.equalsIgnoreCase("") | result.contains("empty")
| result.contains("err")) {
// not valid
} else {
jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Appconstants.messageNamesArray.add(new CompanyM(0,
json_data.getString("company"), Integer
.parseInt(json_data.getString(
"customer_id").trim())));
Appconstants.customers = i;
}
}
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
@Override
protected void onPostExecute(Void params) {
new GetCountriesBTTask().execute();
}
}
}
<file_sep>/src/com/ioptime/betty/TermsActivity.java
package com.ioptime.betty;
import android.os.Bundle;
import com.ioptime.extendablelibrary.IoptimeActivity;
public class TermsActivity extends IoptimeActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected int getLayoutResourceId() {
// TODO Auto-generated method stub
return R.layout.activity_terms;
}
}
<file_sep>/src/com/ioptime/betty/Appconstants.java
package com.ioptime.betty;
import java.util.ArrayList;
import android.content.Context;
import android.content.SharedPreferences;
import com.ioptime.betty.model.Blog;
import com.ioptime.betty.model.Cart;
import com.ioptime.betty.model.Category;
import com.ioptime.betty.model.CompanyM;
import com.ioptime.betty.model.Product;
import com.ioptime.betty.model.User;
import com.ioptime.betty.model.Vendor;
import com.ioptime.betty.model.WorldCountries;
import com.ioptime.extendablelibrary.TinyDB;
public class Appconstants {
public static final String Server = "http://sandbox.baitymall.com/mobile_app/";
public static final String PREFNAME = "com.ioptime.betty";
public static final String ImageUrl = "http://sandbox.baitymall.com/image/";
public static ArrayList<Product> productsList = new ArrayList<Product>();
public static ArrayList<Category> categoryList = new ArrayList<Category>();
public static ArrayList<Blog> blogArray = new ArrayList<Blog>();
public static User user = new User();
public static Vendor vendor = new Vendor();
public static boolean isVendor = false;
public static String[] allPath;
public static final String TAB_Product = ShopFollowedFragment.class
.getSimpleName();
public static final String TAB_WishList = ProductListFragment.class
.getSimpleName();
public static final String TAB_BlogList = MyBlogsFragment.class
.getSimpleName();
public static final String TAB_Profile = ProfileEditFragment.class
.getSimpleName();
public static ArrayList<String> worldlist;
public static ArrayList<WorldCountries> world;
/**
* First contain all vendors then all the customers , customer have a
*
*
* shop_id of 0
*/
public static ArrayList<CompanyM> messageNamesArray = new ArrayList<CompanyM>();
public static int customers = 0;
public static int vendors = 0;
public static int getUserID(Context ctx) {
SharedPreferences prefs = ctx.getSharedPreferences(PREFNAME,
Context.MODE_PRIVATE);
int userID = prefs.getInt("userid", 0);
return userID;
}
/**
* every item contains of first is user id , then product id seperated by
* commas
*/
public static ArrayList<Cart> getCartList(Context ctx) {
TinyDB tinydb = new TinyDB(ctx);
ArrayList<String> string = tinydb.getListString("cart");
ArrayList<Cart> cart = new ArrayList<Cart>();
if (string == null) {
return cart;
} else {// return for
for (int i = 0; i < string.size(); i++) {
// spliting list over commas and adding it into arraylist to
// return
String[] cartArray = string.get(i).split(",");
cart.add(new Cart(Integer.parseInt(cartArray[0]), Integer
.parseInt(cartArray[1])));
}
}
return cart;
}
public static void setCartList(ArrayList<Cart> cart, Context ctx) {
TinyDB tinydb = new TinyDB(ctx);
ArrayList<String> string = new ArrayList<String>();
for (int i = 0; i < cart.size(); i++) {
// spliting list over commas and adding it into arraylist to
// return
string.add(cart.get(i).getProductid() + ","
+ cart.get(i).getUser_id());
}
tinydb.putListString("cart", string);
}
}
<file_sep>/src/com/ioptime/betty/ShopFragment.java
package com.ioptime.betty;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.iopitme.betty.vendor.MainMenuVendor;
import com.ioptime.adapters.ShopAdapter;
import com.ioptime.betty.model.Product;
import com.ioptime.betty.model.Shops;
import com.ioptime.extendablelibrary.IoptimeFragment;
public class ShopFragment extends IoptimeFragment {
ListView listViewShop;
boolean wish = false;
ArrayList<Shops> shopArray = new ArrayList<Shops>();
ProgressBar shopsProgressBar;
EditText shopEtSearch;
Button shopBtSearch;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (getArguments() != null && getArguments().containsKey("wish"))
wish = getArguments().getBoolean("wish");
View rootView = inflater.inflate(R.layout.shops, container, false);
listViewShop = (ListView) rootView.findViewById(R.id.shopList);
shopsProgressBar = (ProgressBar) rootView
.findViewById(R.id.shopsProgressBar);
shopsProgressBar.setVisibility(View.VISIBLE);
new GetShopsListBTTask().execute();
shopEtSearch = (EditText) rootView.findViewById(R.id.shopsETSearch);
shopEtSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
if (shopEtSearch.getText().toString().equalsIgnoreCase("")) {
new GetShopsListBTTask().execute();
}
}
});
shopBtSearch = (Button) rootView.findViewById(R.id.shopsBtSearch);
shopBtSearch.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (shopEtSearch.getText().toString().trim()
.equalsIgnoreCase("")) {
shopEtSearch.setError("Search field cannot be empty");
} else {
String search = shopEtSearch.getText().toString();
new ShopListSearchBT(search).execute();
}
}
});
return rootView;
}
private void populateListView() {
if (shopArray.size() > 0) {
ShopAdapter catAdapter;
catAdapter = new ShopAdapter(getActivity(), shopArray, wish);
listViewShop.setAdapter(catAdapter);
catAdapter.notifyDataSetChanged();
listViewShop.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//
// Open the products of the store from clicking here
ShopProductsFragment subCatFrag = new ShopProductsFragment();
Bundle bundle = new Bundle();
bundle.putInt("id", shopArray.get(position).getId());
bundle.putString("name", shopArray.get(position).getName());
subCatFrag.setArguments(bundle);
getFragmentManager().beginTransaction()
.replace(R.id.frame_container, subCatFrag)
.addToBackStack(null).commit();
}
});
}
else {
}
}
private class GetShopsListBTTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
}
@Override
protected Void doInBackground(Void... arg0) {
try {
//
String result = "";
result = getJSONfromURL(Appconstants.Server + "store_get.php",
null, 0);
Log.d("result", "--" + result);
if (result.equalsIgnoreCase("") | result.contains("empty")
| result.contains("err")) {
// not valid
} else {
shopArray = new ArrayList<Shops>();
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
shopArray.add(new Shops(Integer.parseInt(json_data
.getString("store_id").trim()), (json_data
.getString("name").trim()), (json_data
.getString("url").trim()), json_data.getString(
"ssl").trim(), false));
}
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
@Override
protected void onPostExecute(Void params) {
new GetFollowStoreListBTTask(Appconstants.user.getCustomer_id())
.execute();
}
}
private class GetFollowStoreListBTTask extends AsyncTask<Void, Void, Void> {
int customer_id;
public GetFollowStoreListBTTask(int cust_id) {
// TODO Auto-generated constructor stub
customer_id = cust_id;
}
@Override
protected Void doInBackground(Void... arg0) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("customer_id",
customer_id + ""));
try {
//
String result = "";
result = getJSONfromURL(Appconstants.Server
+ "stores_followed_by_customer.php", nameValuePairs, 0);
Log.d("result", "--" + result);
ArrayList<Shops> arrayFollow = new ArrayList<Shops>();
Appconstants.user.setFollowList(arrayFollow);
if (result.equalsIgnoreCase("") | result.contains("empty")
| result.contains("err")) {
// not valid
} else {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
arrayFollow.add(new Shops(Integer.parseInt(json_data
.getString("store_id").trim()), (json_data
.getString("name").trim()), (json_data
.getString("url").trim()), json_data.getString(
"ssl").trim(), true));
}
}
Appconstants.user.setFollowList(arrayFollow);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
@Override
protected void onPostExecute(Void params) {
shopsProgressBar.setVisibility(View.GONE);
populateListView();
}
}
private class ShopListSearchBT extends AsyncTask<Void, Void, Void> {
String search;
String result = "";
ShopListSearchBT(String search) {
this.search = search;
}
@Override
protected void onPreExecute() {
shopsProgressBar.setVisibility(View.VISIBLE);
}
@Override
protected Void doInBackground(Void... arg0) {
try {
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("timestamp", ""
+ System.currentTimeMillis()));
params.add(new BasicNameValuePair("search", "" + search));
//
result = "";
result = getJSONfromURL(Appconstants.Server
+ "store_search.php", params, 0);
Log.d("result", "--" + result);
if (result.equalsIgnoreCase("") | result.contains("empty")
| result.contains("err")) {
// not valid
} else {
shopArray = new ArrayList<Shops>();
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
shopArray.add(new Shops(Integer.parseInt(json_data
.getString("store_id").trim()), (json_data
.getString("name").trim()), (json_data
.getString("url").trim()), json_data.getString(
"ssl").trim(), false));
}
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
@Override
protected void onPostExecute(Void params) {
shopsProgressBar.setVisibility(View.GONE);
if (result.equalsIgnoreCase("") | result.contains("empty")
| result.contains("err")) {
Toast.makeText(getActivity(), "No resut to show ",
Toast.LENGTH_LONG).show();
} else {
new GetFollowStoreListBTTask(Appconstants.user.getCustomer_id())
.execute();
}
}
}
@Override
public void onResume() {
super.onResume();
((MainMenu) getActivity()).getActionBar().setTitle("Shop");
}
}
<file_sep>/src/com/ioptime/adapters/MessageThreadAdapter.java
package com.ioptime.adapters;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.image.loader.ImageLoader;
import com.ioptime.betty.Appconstants;
import com.ioptime.betty.R;
import com.ioptime.betty.model.Message;
public class MessageThreadAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<Message> messageArray;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
public MessageThreadAdapter(Activity a, ArrayList<Message> i) {
activity = a;
messageArray = i;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext(),
R.drawable.ic_launcher);
}
public int getCount() {
return messageArray.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.item_thread, null);
//
TextView textMessage = (TextView) vi
.findViewById(R.id.threadTVMessageContent);
TextView textHeading = (TextView) vi
.findViewById(R.id.threadTVMessageSubject);
TextView textDate = (TextView) vi
.findViewById(R.id.threadTVMessageDate);
TextView textTime = (TextView) vi
.findViewById(R.id.threadTVMessageTime);
ImageView IVlogo = (ImageView) vi
.findViewById(R.id.IVLogo);
LinearLayout llMain = (LinearLayout) vi.findViewById(R.id.threadLLMain);
LinearLayout ll = (LinearLayout) vi.findViewById(R.id.threadLL);
textMessage.setText(messageArray.get(position).getContent());
textHeading.setText(messageArray.get(position).getMessage_subject());
textDate.setText(messageArray.get(position).getMessage_created_date());
textTime.setText(messageArray.get(position).getMessage_created_time());
// checking for user id
if (Integer.parseInt(messageArray.get(position)
.getMessage_customer_id()) == Appconstants.getUserID(activity)) {
// this message is sent from our side
IVlogo.setImageResource(R.drawable.person1);
ll.setBackground(null);
// llMain.setBackgroundColor(Color.BLUE);
llMain.setBackground(activity.getResources().getDrawable(
R.drawable.balloon_incoming_normal));
ll.setGravity(Gravity.LEFT);
} else if (Integer.parseInt(messageArray.get(position)
.getMessage_customer_id()) != Appconstants.getUserID(activity)) {
IVlogo.setImageResource(R.drawable.person2);
// this message is recieved
ll.setBackground(null);
// llMain.setBackgroundColor(Color.RED);
llMain.setBackground(activity.getResources().getDrawable(
R.drawable.balloon_outgoing_normal));
ll.setGravity(Gravity.RIGHT);
}
// textAuthor.setText("" + blogArray.get(position).getIntro_text());
// imageLoader.DisplayImage(blogArray.get(position).getImage(),
// image);
return vi;
}
}<file_sep>/src/com/iopitme/betty/vendor/ProfileEditVendorFragment.java
package com.iopitme.betty.vendor;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.image.loader.ImageLoader;
import com.ioptime.betty.Appconstants;
import com.ioptime.betty.R;
import com.ioptime.betty.model.Vendor;
import com.ioptime.extendablelibrary.IoptimeFragment;
public class ProfileEditVendorFragment extends IoptimeFragment {
EditText etFirstName, etLastName, etEmail, etTopic;
Button editBTSignUp;
ArrayList<EditText> editTextArray = new ArrayList<EditText>();
ProgressDialog progressDialog;
ImageView profilePicVendor;
ImageLoader imageloader;
File fileImage;
int serverResponseCode = 0;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.profile_edit_vendor,
container, false);
etFirstName = (EditText) rootView.findViewById(R.id.editETFName);
editTextArray.add(etFirstName);
etLastName = (EditText) rootView.findViewById(R.id.editETLName);
editTextArray.add(etLastName);
etEmail = (EditText) rootView.findViewById(R.id.editETEmail);
editTextArray.add(etEmail);
etTopic = (EditText) rootView.findViewById(R.id.editETTopic);
editBTSignUp = (Button) rootView.findViewById(R.id.editBTSignUp);
profilePicVendor = (ImageView) rootView.findViewById(R.id.VendorimgIV);
TextView vendorTopic = (TextView) rootView
.findViewById(R.id.VendortopicTV);
imageloader = new ImageLoader(getActivity(), R.drawable.cust_logo);
imageloader.DisplayImage(
"http://sandbox.baitymall.com/image/data/"
+ Appconstants.vendor.getUserName() + "/"
+ Appconstants.vendor.getUser_id() + ".png",
profilePicVendor, ImageLoader.NORMAL);
profilePicVendor.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
openAlert();
}
});
editBTSignUp.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (inputAll()) {
if (isConnectedToInternet(getActivity())) {
new UpdateUserBT().execute();
} else {
Toast.makeText(getActivity(),
"Please check your internet connectivity",
Toast.LENGTH_LONG).show();
}
}
}
});
vendorTopic.setText("" + Appconstants.vendor.getTopic());
etFirstName.setText("" + Appconstants.vendor.getFirstname());
etLastName.setText("" + Appconstants.vendor.getLastname());
etEmail.setText("" + Appconstants.vendor.getEmail());
etTopic.setText("" + Appconstants.vendor.getTopic());
return rootView;
}
public boolean inputAll() {
for (EditText edit : editTextArray) {
if (TextUtils.isEmpty(edit.getText().toString().trim())) {
edit.setError(edit.getHint() + " can not be empty");
return false;
} else {
edit.setError(null, null);
}
}
return true;
}
private class UpdateUserBT extends AsyncTask<Void, Void, Void> {
int userid = 0;
String result;
@Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(getActivity(),
"Please wait ...", "Updating profile ...", true);
progressDialog.setCancelable(true);
}
@Override
protected Void doInBackground(Void... arg0) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("firstname", etFirstName
.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("lastname", etLastName
.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("email", etEmail
.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("topic", etTopic
.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("telephone",
Appconstants.vendor.getTelephone().toString()));
nameValuePairs.add(new BasicNameValuePair("user_id",
Appconstants.vendor.getUser_id() + ""));
try {
//
result = "";
result = getJSONfromURL(Appconstants.Server
+ "vendor_profile_update.php", nameValuePairs, 0);
Log.d("result", "--" + result);
if (result.equalsIgnoreCase("")
| result.equalsIgnoreCase("empty")) {
} else {
userid = 0;
Appconstants.vendor = new Vendor();
Appconstants.vendor.setUser_id(0);
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Appconstants.vendor = new Vendor(
Integer.parseInt(json_data.getString("user_id")
.trim()), json_data.getString(
"firstname").trim(), json_data
.getString("lastname").trim(),
json_data.getString("email").trim(), json_data
.getString("telephone").trim(),
json_data.getString("topic").trim(), json_data
.getString("vendor_image").trim(),
json_data.getString("username").trim());
}
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
@Override
protected void onPostExecute(Void params) {
if (Appconstants.vendor.getUser_id() != 0) {
if (result.equalsIgnoreCase("")
| result.equalsIgnoreCase("empty")) {
Toast.makeText(getActivity(), "Error while updating",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "Successful update",
Toast.LENGTH_SHORT).show();
new BTSavePic().execute();
}
etEmail.setText("" + Appconstants.vendor.getEmail());
etFirstName.setText("" + Appconstants.vendor.getFirstname());
etLastName.setText("" + Appconstants.vendor.getLastname());
etTopic.setText("" + Appconstants.vendor.getTopic());
}
progressDialog.cancel();
}
}
private void openAlert() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
getActivity());
alertDialogBuilder.setTitle("Adding Picture");
alertDialogBuilder.setMessage("Upload your picture");
// set positive button: Yes message
alertDialogBuilder.setPositiveButton("From Camera",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 2);
}
});
// set negative button: No message
alertDialogBuilder.setNegativeButton("From Gallery",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent photoPickerIntent = new Intent(
Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
// show alert
alertDialog.show();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("activityreult", requestCode + "aaaa");
if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
try {
String file_path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Betty";
File dir = new File(file_path);
if (!dir.exists())
dir.mkdirs();
fileImage = new File(dir, "temp" + ".jpeg");
InputStream inputStream = getActivity().getContentResolver()
.openInputStream(data.getData());
FileOutputStream fileOutputStream = new FileOutputStream(
fileImage);
copyStream(inputStream, fileOutputStream);
Bitmap bMap = BitmapFactory.decodeFile(fileImage.getPath());
bMap = Bitmap.createScaledBitmap(bMap, 640, 640, true);
try {
fileOutputStream = new FileOutputStream(fileImage);
bMap.compress(Bitmap.CompressFormat.JPEG, 50,
fileOutputStream);
profilePicVendor.setImageBitmap(bMap);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fileOutputStream.close();
inputStream.close();
} catch (Exception e) {
Log.e("adding pictre from gallery",
"Error while creating temp file", e);
}
}
if (requestCode == 2 && resultCode == Activity.RESULT_OK) {
// get the cropped bitmap
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
String file_path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Betty";
File dir = new File(file_path);
if (!dir.exists())
dir.mkdirs();
fileImage = new File(dir, "temp" + ".jpeg");
FileOutputStream fOut;
try {
fOut = new FileOutputStream(fileImage);
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fOut);
bitmap = Bitmap.createScaledBitmap(bitmap, 640, 640, true);
profilePicVendor.setImageBitmap(bitmap);
fOut.flush();
fOut.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void copyStream(InputStream input, OutputStream output)
throws IOException {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}
private class BTSavePic extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
}
@Override
protected Void doInBackground(Void... arg0) {
if (fileImage != null) {
String file_path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Betty";
File dir = new File(file_path);
if (!dir.exists())
dir.mkdirs();
// userid_name.jpeg
File fileImageTag = new File(dir, ""
+ Appconstants.vendor.getUser_id() + ".png");
fileImage.renameTo(fileImageTag);
fileImage.delete();
uploadFile(fileImageTag.getPath());
}
return null;
}
}
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
getActivity().runOnUiThread(new Runnable() {
public void run() {
}
});
return 0;
} else {
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(Appconstants.Server
+ "store_image_upload.php?username="
+ Appconstants.vendor.getUserName() + "&vendor_id="
+ Appconstants.vendor.getUser_id());
Log.d("url", url + "");
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if (serverResponseCode == 200) {
getActivity().runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getActivity(),
"File Upload Complete.", Toast.LENGTH_SHORT)
.show();
}
});
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
getActivity().runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getActivity(), "MalformedURLException",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
getActivity().runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getActivity(),
"Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception",
"Exception : " + e.getMessage(), e);
}
return serverResponseCode;
} // End else block
}
@Override
public void onResume() {
super.onResume();
((MainMenuVendor) getActivity()).getActionBar().setTitle("Profile");
}
}
<file_sep>/src/com/ioptime/betty/BlogFragment.java
package com.ioptime.betty;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.iopitme.betty.vendor.MainMenuVendor;
import com.ioptime.adapters.BlogAdapter;
import com.ioptime.betty.model.Blog;
import com.ioptime.betty.model.Product;
import com.ioptime.extendablelibrary.IoptimeFragment;
public class BlogFragment extends IoptimeFragment {
ImageView ivAdd;
ListView listBLog;
EditText blogEtSearch;
Button blogBtSearch;
ProgressBar blogProgressBar;
public BlogFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.blog, container, false);
listBLog = (ListView) rootView.findViewById(R.id.blogList);
ivAdd = (ImageView) rootView.findViewById(R.id.blogIVAddNew);
blogProgressBar = (ProgressBar) rootView
.findViewById(R.id.blogProgressBar);
ivAdd.setVisibility(View.GONE);
if (Appconstants.blogArray.size() == 0) {
if (isConnectedToInternet(getActivity())) {
new BlogListBT().execute();
} else {
Toast.makeText(getActivity(), "Check your internet connection",
Toast.LENGTH_LONG).show();
}
} else if (Appconstants.blogArray.size() > 0) {
populateListView();
}
blogEtSearch = (EditText) rootView.findViewById(R.id.blogETSearch);
blogEtSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
if (blogEtSearch.getText().toString().equalsIgnoreCase("")) {
new BlogListBT().execute();
}
}
});
blogBtSearch = (Button) rootView.findViewById(R.id.blogBtSearch);
blogBtSearch.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (blogEtSearch.getText().toString().trim()
.equalsIgnoreCase("")) {
blogEtSearch.setError("Search field cannot be empty");
} else {
String search = blogEtSearch.getText().toString();
new BlogListSearchBT(search).execute();
} // TODO Auto-generated method stub
}
});
return rootView;
}
public class BlogListBT extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
blogProgressBar.setVisibility(View.VISIBLE);
}
@Override
protected Void doInBackground(Void... arg0) {
try {
//
String result = "";
result = getJSONfromURL(Appconstants.Server + "blog_get.php",
null, 0);
Log.d("result", "--" + result);
if (result.equalsIgnoreCase("")
| result.equalsIgnoreCase("empty")) {
// not valid
} else {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Appconstants.blogArray
.add(new Blog(Integer.parseInt(json_data
.getString("blog_id")),
Integer.parseInt(json_data
.getString("status")),
Integer.parseInt(json_data
.getString("sort_order")),
json_data.getString("create_time"),
json_data.getString("update_time"),
json_data.getString("date"),
Integer.parseInt(json_data
.getString("language_id")),
json_data.getString("title"), json_data
.getString("intro_text"),
json_data.getString("text"), json_data
.getString("meta_description"),
json_data.getString("meta_keyword")));
}
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
@Override
protected void onPostExecute(Void params) {
blogProgressBar.setVisibility(View.GONE);
populateListView();
}
}
public void populateListView() {
if (Appconstants.blogArray.size() > 0) {
BlogAdapter blogAdapter = new BlogAdapter(getActivity(),
Appconstants.blogArray);
listBLog.setAdapter(blogAdapter);
blogAdapter.notifyDataSetChanged();
listBLog.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//
BlogDetailFragments blogFrags = new BlogDetailFragments();
Bundle bundle = new Bundle();
bundle.putInt("position", position);
blogFrags.setArguments(bundle);
getFragmentManager().beginTransaction()
.replace(R.id.frame_container, blogFrags)
.addToBackStack(null).commit();
}
});
} else {
Toast.makeText(getActivity(), "No blogs to show at the moment",
Toast.LENGTH_LONG).show();
}
}
private class BlogListSearchBT extends AsyncTask<Void, Void, Void> {
String search;
String result = "";
BlogListSearchBT(String search) {
this.search = search;
}
@Override
protected void onPreExecute() {
blogProgressBar.setVisibility(View.VISIBLE);
}
@Override
protected Void doInBackground(Void... arg0) {
try {
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("timestamp", ""
+ System.currentTimeMillis()));
params.add(new BasicNameValuePair("search", "" + search));
//
result = "";
result = getJSONfromURL(
Appconstants.Server + "blog_search.php", params, 0);
Log.d("result", "--" + result);
if (result.equalsIgnoreCase("")
| result.equalsIgnoreCase("empty")) {
// not valid
} else {
JSONArray jArray = new JSONArray(result);
Appconstants.blogArray = new ArrayList<Blog>();
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Appconstants.blogArray
.add(new Blog(Integer.parseInt(json_data
.getString("blog_id")),
Integer.parseInt(json_data
.getString("status")),
Integer.parseInt(json_data
.getString("sort_order")),
json_data.getString("create_time"),
json_data.getString("update_time"),
json_data.getString("date"),
Integer.parseInt(json_data
.getString("language_id")),
json_data.getString("title"), json_data
.getString("intro_text"),
json_data.getString("text"), json_data
.getString("meta_description"),
json_data.getString("meta_keyword")));
}
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
@Override
protected void onPostExecute(Void params) {
blogProgressBar.setVisibility(View.GONE);
populateListView();
}
}
@Override
public void onResume() {
super.onResume();
((MainMenu) getActivity()).getActionBar().setTitle("Blog");
}
}
<file_sep>/src/com/iopitme/betty/vendor/MainMenuVendor.java
package com.iopitme.betty.vendor;
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.ioptime.adapters.NavDrawerListAdapter;
import com.ioptime.betty.R;
import com.ioptime.betty.model.NavDrawerItem;
public class MainMenuVendor extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
TextView tvCart;
boolean doubleBackToExitPressedOnce;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(
R.array.nav_drawer_items_vendor);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Products
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons
.getResourceId(0, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons
.getResourceId(1, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons
.getResourceId(2, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons
.getResourceId(3, -1)));
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.menu, // nav menu toggle icon
R.string.app_name, // nav drawer open - description for
// accessibility
R.string.app_name // nav drawer close - description for
// accessibility
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
//
// MenuInflater menuInflater = getMenuInflater();
// menuInflater.inflate(R.menu.main, menu);
// final View menu_hotlist = menu.findItem(R.id.action_cart)
// .getActionView();
// tvCart = (TextView) menu_hotlist.findViewById(R.id.hotlist_hot);
// ArrayList<Cart> cart = Appconstants
// .getCartList(getApplicationContext());
// updateCartCount(cart.size());
// new MyMenuItemStuffListener(menu_hotlist, "Show hot message") {
// @Override
// public void onClick(View v) {
// // opencart here
//
// CartFragment newCartFrag = new CartFragment();
// Bundle bundle = new Bundle();
//
// newCartFrag.setArguments(bundle);
// getSupportFragmentManager().beginTransaction()
// .replace(R.id.frame_container, newCartFrag)
// .addToBackStack(null).commit();
//
// }
// };
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_cart:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
// menu.findItem(R.id.action_cart).setTitle("12");
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new ProductListFragmentVendor();
break;
// case 1:
// fragment = new CategoryFragment();
// break;
// case 2:
// fragment = new BlogFragment();
// break;
// case 3:
// fragment = new ShopFragment();
// break;
case 1:
fragment = new ProductReportsFragment();
break;
case 2:
fragment = new ProfileVendorFragment();
break;
case 3:
fragment = new MessagesVendorFragment();
break;
//
// case 6:
// fragment = new ContactFragment();
// break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment)
.addToBackStack("fragback").commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
// call the updating code on the main thread,
// so we can call this asynchronously
public void updateCartCount(final int new_hot_number) {
if (tvCart == null)
return;
runOnUiThread(new Runnable() {
@Override
public void run() {
if (new_hot_number == 0)
tvCart.setVisibility(View.INVISIBLE);
else {
tvCart.setVisibility(View.VISIBLE);
tvCart.setText(Integer.toString(new_hot_number));
}
}
});
}
static abstract class MyMenuItemStuffListener implements
View.OnClickListener, View.OnLongClickListener {
private String hint;
private View view;
MyMenuItemStuffListener(View view, String hint) {
this.view = view;
this.hint = hint;
view.setOnClickListener(this);
view.setOnLongClickListener(this);
}
@Override
abstract public void onClick(View v);
@Override
public boolean onLongClick(View v) {
final int[] screenPos = new int[2];
final Rect displayFrame = new Rect();
view.getLocationOnScreen(screenPos);
view.getWindowVisibleDisplayFrame(displayFrame);
final Context context = view.getContext();
final int width = view.getWidth();
final int height = view.getHeight();
final int midy = screenPos[1] + height / 2;
final int screenWidth = context.getResources().getDisplayMetrics().widthPixels;
Toast cheatSheet = Toast
.makeText(context, hint, Toast.LENGTH_SHORT);
if (midy < displayFrame.height()) {
cheatSheet.setGravity(Gravity.TOP | Gravity.RIGHT, screenWidth
- screenPos[0] - width / 2, height);
} else {
cheatSheet.setGravity(Gravity.BOTTOM
| Gravity.CENTER_HORIZONTAL, 0, height);
}
cheatSheet.show();
return true;
}
}
@Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 1) {
fm.popBackStack();
fm.getBackStackEntryCount();
// super.onBackPressed();
// return;
} else {
if (doubleBackToExitPressedOnce) {
fm.popBackStack();
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Press one more time to exit",
Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 3000);
}
}
}<file_sep>/src/com/ioptime/betty/MainTabBar.java
//package com.ioptime.betty;
//
//import android.animation.Animator;
//import android.animation.Animator.AnimatorListener;
//import android.animation.AnimatorListenerAdapter;
//import android.animation.ObjectAnimator;
//import android.app.TabActivity;
//import android.content.Intent;
//import android.os.Bundle;
//import android.util.Log;
//import android.view.View;
//import android.view.Window;
//import android.widget.LinearLayout;
//import android.widget.TabHost;
//import android.widget.TabHost.OnTabChangeListener;
//
//public class MainTabBar extends TabActivity implements OnTabChangeListener {
//
// /** Called when the activity is first created. */
// TabHost tabHost;
// LinearLayout mainLLMenu;
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// setContentView(R.layout.tab_main);
// mainLLMenu = (LinearLayout) findViewById(R.id.mainLLMenu);
// // Get TabHost Refference
// tabHost = getTabHost();
//
// // Set TabChangeListener called when tab changed
// tabHost.setOnTabChangedListener(this);
//
// TabHost.TabSpec spec;
// Intent intent;
//
// /************* TAB1 ************/
// // Create Intents to launch an Activity for the tab (to be reused)
// intent = new Intent().setClass(this, LatestQuestion.class);
// spec = tabHost.newTabSpec("First").setIndicator("").setContent(intent);
//
// // Add intent to tab
// tabHost.addTab(spec);
//
// /************* TAB2 ************/
// intent = new Intent().setClass(this, People.class);
// spec = tabHost.newTabSpec("Second").setIndicator("").setContent(intent);
// tabHost.addTab(spec);
// tabHost.getTabWidget().getChildAt(0)
// .setBackgroundResource(R.drawable.tab_questions);
// tabHost.getTabWidget().getChildAt(1)
// .setBackgroundResource(R.drawable.tab_people);
// // Set Tab1 as Default tab and change image
// tabHost.getTabWidget().setCurrentTab(0);
//
// }
//
// @Override
// public void onTabChanged(String tabId) {
//
// /************ Called when tab changed *************/
//
// // ********* Check current selected tab and change according images
// // *******/
// //
// // for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
// // if (i == 0)
// // tabHost.getTabWidget().getChildAt(i)
// // .setBackgroundResource(R.drawable.button);
// // else if (i == 1)
// // tabHost.getTabWidget().getChildAt(i)
// // .setBackgroundResource(R.drawable.button);
// // }
//
// Log.i("tabs", "CurrentTab: " + tabHost.getCurrentTab());
//
// // if (tabHost.getCurrentTab() == 0)
// // tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab())
// // .setBackgroundResource(R.drawable.tab1_over);
// // else if (tabHost.getCurrentTab() == 1)
// // tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab())
// // .setBackgroundResource(R.drawable.tab2_over);
// // else if (tabHost.getCurrentTab() == 2)
// // tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab())
// // .setBackgroundResource(R.drawable.tab3_over);
//
// }
//
// public void openMenu(View v) {
// // startActivity(new Intent(MainTabBar.this, MenuDrop.class));
// if (!mainLLMenu.isShown()) {
// SlideToDown(mainLLMenu);
// } else {
// SlideToAbove(mainLLMenu);
// }
// }
//
// public void SlideToDown(final View view) {
// view.setVisibility(View.VISIBLE);
//
// // Start the animation
// ObjectAnimator mSlidInAnimator = ObjectAnimator.ofFloat(view,
// "translationY", 0);
// mSlidInAnimator.setDuration(200);
// mSlidInAnimator.start();
// mSlidInAnimator.addListener(new AnimatorListener() {
//
// @Override
// public void onAnimationStart(Animator animation) {
// // TODO Auto-generated method stub
// }
//
// @Override
// public void onAnimationRepeat(Animator animation) {
// // TODO Auto-generated method stub
//
// }
//
// @Override
// public void onAnimationEnd(Animator animation) {
// // TODO Auto-generated method stub
// view.setVisibility(View.VISIBLE);
// }
//
// @Override
// public void onAnimationCancel(Animator animation) {
// // TODO Auto-generated method stub
//
// }
// });
// }
//
// public void SlideToAbove(final View view) {
// ObjectAnimator mSlidOutAnimator = ObjectAnimator.ofFloat(view,
// "translationY", -100);
// mSlidOutAnimator.setDuration(200);
// mSlidOutAnimator.start();
// mSlidOutAnimator.addListener(new AnimatorListener() {
//
// @Override
// public void onAnimationStart(Animator animation) {
// // TODO Auto-generated method stub
//
// }
//
// @Override
// public void onAnimationRepeat(Animator animation) {
// // TODO Auto-generated method stub
//
// }
//
// @Override
// public void onAnimationEnd(Animator animation) {
// // TODO Auto-generated method stub
// view.setVisibility(View.GONE);
// }
//
// @Override
// public void onAnimationCancel(Animator animation) {
// // TODO Auto-generated method stub
//
// }
// });
// }
//
// public void close(View v) {
// finish();
//
// }
//
// public void editProfile(View v) {
// startActivity(new Intent(MainTabBar.this, Edit_Profile.class));
//
// }
//
// public void help(View v) {
// startActivity(new Intent(MainTabBar.this, Help.class));
//
// }
//
// public void account(View v) {
// startActivity(new Intent(MainTabBar.this, Profile.class));
// }
//
// public void ask(View v) {
// // startActivity(new Intent(MenuDrop.this, Ask.class));
//
// }
//
// public void settings(View v) {
// startActivity(new Intent(MainTabBar.this, Settings.class));
//
// }
//
// } | a6d34439c2f87a1ec71d6c959aa88fcf7e613b4c | [
"Java"
] | 30 | Java | ioptime/Betty | 74d5332b96649f5118752d76d62f912ba2731a1a | accb2aa95bc86f2c68767a1cdf5168aeb8bc6000 |
refs/heads/master | <file_sep># DC String
String handling functions and wrappers.
<file_sep>#ifndef DC_STRING_CONFIG
#define DC_STRING_CONFIG 1
#endif // !DC_STRING_CONFIG
<file_sep>#include "data/scripts/dc_string/config.h"
// Caskey, <NAME>.
// 2010-06-18
//
// Crop the right side of a string (haystack)
// starting with last occurence of needle.
// Example:
// - haystack: "data/scripts/hello.c"
// - needle: "/"
// - output: "data/scripts"
char dc_string_crop_right(char haystack, char needle)
{
char temp_string;
int index;
// Get string length, minus 1
// to account for zero indexing.
index = strlength(haystack);
// The strinlast function doesn't work, so we'll just build
// our own naive search algorithm here.
//
// We create a temporary string from haystack, starting
// at the far right character. We then use stringinfirst
// to see if our needle is in the temp_string, and if it
// is we now have an index to use for strleft.
//
// If the result is invalid (-1), then we build the
// tempstring from haystack, now one character back, and
// continue until our strinfirst gets a good result.
do
{
index--;
// Get the right end of haystack, starting
// from index.
temp_string = strright(haystack, index);
} while (strinfirst(temp_string, needle) == -1);
// Now that we have our index pointing to the last
// occurence of needle in haystack, we can use strleft
// to return the preceeding characters.
return strleft(haystack, index);
}<file_sep>#include "data/scripts/dc_string/config.h"
#import "data/scripts/dc_string/crop.c" | 44426b3645ae3c0df52b7798acb762fea5dc502f | [
"Markdown",
"C"
] | 4 | Markdown | DCurrent/openbor-script-string | 2f7d7276cdd9e3a021e1b48a9bb39207457f8ada | 430dadbb29862015a80a6fac996f714e796270fc |
refs/heads/master | <file_sep><?php
namespace christophe\blog\model;
require_once('model/Manager.php');
class UserManager extends Manager
{
public function inscriptionUser($pseudo, $password, $email)
{
$bdd = $this->dbConnect();
$req = $bdd->prepare('INSERT INTO user(pseudo, password, email) VALUES(:pseudo, :password, :email)');
$result_inscription = $req->execute(array(
'pseudo' => $pseudo,
'password' => $password,
'email' => $email));
return $result_inscription;
}
public function connexionUser($pseudo, $password)
{
$bdd = $this->dbConnect();
$req = $bdd->prepare('SELECT password FROM user WHERE pseudo = ?');
$resultConnexion = $req->execute(array($pseudo));
if($req->rowCount() != 0)
{
$resultConnexion = $req->fetch();
if($resultConnexion['password'] == $password)
{
$_SESSION['pseudo'] = $pseudo;
}
else
{
$_SESSION['password_connexion_inconnu'] = 'in<PASSWORD>';
}
}
else
{
$_SESSION['pseudo_inconnu'] = 'inconnu';
}
}
public function sendMailUser($pseudo)
{
$bdd = $this->dbConnect();
$req = $bdd->prepare('SELECT * FROM user WHERE pseudo = ?');
$req->execute(array($pseudo));
if($req->rowCount() != 0)
{
$resultMail = $req->fetch();
return $resultMail;
}
else
{
$resultMail = 'erreur';
return $resultMail;
}
}
public function validAccessAdministration($login)
{
$bdd = $this->dbConnect();
$req = $bdd->prepare('SELECT password FROM administrator WHERE login = ?');
$resultAccessAdmin = $req->execute(array($login));
if($req->rowCount() != 0)
{
$resultAccessAdmin = $req->fetch();
return $resultAccessAdmin;
}
else
{
return $resultAccessAdmin;
}
}
public function sendMailAdministrator($login)
{
$bdd = $this->dbConnect();
$req = $bdd->prepare('SELECT * FROM administrateur WHERE login = ?');
$req->execute(array($login));
if($req->rowCount() != 0)
{
$resultMail = $req->fetch();
return $resultMail;
}
else
{
$resultMail = 'erreur';
return $resultMail;
}
}
public function getTotalUser()
{
$bdd = $this->dbConnect();
$reponse = $bdd->query('SELECT COUNT(id) AS total_user FROM user');
$req = $reponse->fetch();
return $req;
}
public function modificationPassword($n<PASSWORD>_password, $login)
{
$bdd = $this->dbConnect();
$req = $bdd->prepare('UPDATE administrateur SET password = :<PASSWORD> WHERE login = :login');
$req->execute(array(
'nouveau_password' => $<PASSWORD>,
'login' => $login));
return $req;
}
}<file_sep>class Modal {
constructor(id, id_enfant){
this.id = id;
this.id_enfant = id_enfant;
this.construction();
}
construction(){// CREATION DU MODAL
$("<div>", {id: this.id}).appendTo("main");
$("<div>", {id:this.id_enfant, class:"modal_enfant"}).appendTo("#"+this.id);
$("<p>",{id:"texte_modal"}).appendTo("#"+this.id_enfant)
$("<button>", {class:"ferme_modal"}).appendTo("#"+this.id_enfant)
$(".ferme_modal").text("X");
$(".ferme_modal").click(()=>{
$(".texte_modal").text("");
$("#"+this.id).hide()});
}
ajoute_texte(texte){// AJOUTE UN TEXTE
$("#texte_modal").text(texte);
}
inscription(){
let controle_password1 = /^(?=.*[a-zA-Z])(?=.*[0-9])(?=.{8,})/;
let controle_email = /.+@.+\..+/;
$("<h3>", {id:"titre_modal_inscription"}).appendTo("#"+this.id_enfant);
$("#titre_modal_inscription").text("S'INSCRIRE");
$("<form>", {action: "index.php?action=inscriptionUsers", method: "post",
id:"form_modal_inscription", class: "form_modal"}).appendTo("#"+this.id_enfant);
$("<input>", {type:"text", name: "pseudo", id:"pseudo", placeholder: "votre pseudo", required:"required"}).appendTo("#form_modal_inscription");
$("<input>", {type: "email", name: "email", id: "email", placeholder: "votre adresse mail", required:"required"}).appendTo("#form_modal_inscription");
$("<input>", {type:"text", name: "password", id:"password", placeholder: "votre mot de passe (lettre ET chiffre)", required:"required"}).appendTo("#form_modal_inscription");
$("<input>", {type:"text", id:"verif_password", placeholder: "confirmer votre mot de passe", required:"required"}).appendTo("#form_modal_inscription");
$("<input>", {type:"submit", value:"inscription", id:"boutton_inscription"}).appendTo("#form_modal_inscription");
$("#boutton_inscription").on("click", (e)=>{
if(!controle_password1.test($("#password").val()))
{
e.preventDefault();
$("#password").val("password invalide");
}
else if($("#password").val() != $("#verif_password").val())
{
e.preventDefault();
$("#verif_password").val("ce n'est pas <PASSWORD>");
}
else if(!controle_email.test($("#email").val()))
{
e.preventDefault();
$("#email").val("email invalide");
}
})
}
connexion(){
$("<h3>", {id:"titre_modal_connexion"}).appendTo("#"+this.id_enfant);
$("#titre_modal_connexion").text("SE CONNECTER");
$("<form>", {action: "index.php?action=connexionUsers", method: "post",
id:"form_modal_connexion", class: "form_modal"}).appendTo("#"+this.id_enfant);
$("<input>", {type:"text", name: "pseudo", id:"pseudo", placeholder: "votre pseudo", required:"required"}).appendTo("#form_modal_connexion");
$("<input>", {type:"text", name: "password", id:"password", placeholder: "votre mot de passe", required:"required"}).appendTo("#form_modal_connexion");
$("<a>", {class:"oublie_password", href:"index.php?action=askPassword"}).appendTo("#form_modal_connexion");
$(".oublie_password").text("mot de passe o<PASSWORD>");
$("<input>", {type:"submit", value:"connexion", id:"boutton_connexion"}).appendTo("#form_modal_connexion");
}
}<file_sep><?php
namespace christophe\blog\model;
require_once('model/Manager.php');
class ChapterManager extends Manager
{
public function getAllChapter()
{
$bdd = $this->dbConnect();
$req = $bdd->query('SELECT id, title, resumer, DATE_FORMAT(date_creation, "%d/%m/%Y")AS date_creation FROM chapters WHERE publish = "oui"');
return $req;
}
public function getChapter($id_chapter)
{
$bdd = $this->dbConnect();
$req = $bdd->prepare('SELECT autor,title, chapter, DATE_FORMAT(date_creation, "%d/%m/%Y") AS date_creation FROM chapters WHERE id= ?');
$req->execute(array($id_chapter));
$chapter = $req->fetch();
return $chapter;
}
public function getChapters()
{
$bdd = $this->dbConnect();
$req = $bdd->query('SELECT id, title, publish, DATE_FORMAT(date_creation, "%d/%m/%Y")AS date_creation FROM chapters');
return $req;
}
public function changePublicationChapter($chapterID, $publish)
{
$bdd = $this->dbConnect();
$req = $bdd->prepare('UPDATE chapters SET publish = :publish WHERE id = :id');
$req->execute(array(
'publish' => $publish,
'id' => $chapterID));
return $req;
}
public function suppressionChapter($id_chapter)
{
$bdd = $this->dbConnect();
$req = $bdd->prepare('DELETE FROM chapters WHERE id = ?');
$req->execute(array($id_chapter));
return $req;
}
public function changeExistChapter($new_title, $new_text, $new_resumer, $id, $publish)
{
$bdd = $this->dbConnect();
$req = $bdd->prepare('UPDATE chapters SET title = :new_title, chapter = :new_text, resumer = :new_resumer, publish = :publish WHERE id = :id');
$req->execute(array(
'new_title' => $new_title,
'new_text' => $new_text,
'new_resumer' => $new_resumer,
'publish' => $publish,
'id' => $id));
return $req;
}
public function writeNewChapter($new_title, $new_text, $new_resumer, $publish)
{
$bdd = $this->dbConnect();
$req = $bdd->prepare('INSERT INTO chapters(autor, title, chapter, resumer, publish, date_creation) VALUES("<NAME>", :title, :chapter, :resumer, :publish, NOW())');
$req->execute(array(
'title' => $_POST['new_title'],
'chapter' => $_POST['new_text'],
'resumer' => $_POST['new_resumer'],
'publish' => $publish));
return $req;
}
public function getChapterForModification($id)
{
$bdd = $this->dbConnect();
$req = $bdd->prepare('SELECT * from chapters WHERE id = ?');
$req->execute(array($id));
return $req;
}
}<file_sep>class Modal {
constructor(id, id_enfant, id_texte, remove_texte=false){
this.id = id;
this.id_enfant = id_enfant;
this.id_texte = id_texte;
this.remove_texte = remove_texte;
this.construction();
}
construction(){// CREATION DU MODAL
$("<div>", {id: this.id}).appendTo("main");
$("<div>", {id:this.id_enfant, class:"modal_enfant"}).appendTo("#"+this.id);
$("<p>",{id:"texte_modal"+this.id_texte, class:"texte_modal"}).appendTo("#"+this.id_enfant)
$("<button>", {class:"ferme_modal"}).appendTo("#"+this.id_enfant)
$(".ferme_modal").text("X");
$(".ferme_modal").click(()=>{
if(this.remove_texte == true)
{
$(".texte_modal").text("");
}
$("#"+this.id).hide()});
}
ajoute_texte(texte){// AJOUTE UN TEXTE
$("#texte_modal"+this.id_texte).text(texte);
}
inscription(){
let controle_password1 = /^(?=.*[a-zA-Z])(?=.*[0-9])(?=.{8,})/;
let controle_email = /.+@.+\..+/;
$("<h3>", {id:"titre_modal_inscription"}).appendTo("#"+this.id_enfant);
$("#titre_modal_inscription").text("S'INSCRIRE");
$("<form>", {action: "index.php?action=inscriptionUsers", method: "post",
id:"form_modal_inscription", class: "form_modal"}).appendTo("#"+this.id_enfant);
$("<input>", {type:"text", name: "pseudo", id:"pseudo_inscription", placeholder: "votre pseudo", required:"required"}).appendTo("#form_modal_inscription");
$("<input>", {type: "email", name: "email", id: "email", placeholder: "votre adresse mail", required:"required"}).appendTo("#form_modal_inscription");
$("<p>", {id: "erreur_email"}).appendTo("#form_modal_inscription");
$("<input>", {type:"password", name: "password", id:"password_inscription", placeholder: "mot de passe", required:"required"}).appendTo("#form_modal_inscription");
$("<p>", {id: "erreur_password_inscription"}).appendTo("#form_modal_inscription");
$("#erreur_password_inscription").text("minimum : 8 charactères; 1 lettre; 1 chiffre");
$("<input>", {type:"password", id:"verif_password_inscription", placeholder: "confirmer votre mot de passe", required:"required"}).appendTo("#form_modal_inscription");
$("<p>", {id: "erreur_verif_password_inscription"}).appendTo("#form_modal_inscription");
$("<input>", {type:"submit", value:"inscription", id:"boutton_inscription"}).appendTo("#form_modal_inscription");
$("#boutton_inscription").on("click", (e)=>{
if(!controle_password1.test($("#password_inscription").val()))
{
e.preventDefault();
console.log("1");
$("#erreur_password_inscription").text("password invalide");
}
else if($("#password_inscription").val() != $("#verif_password_inscription").val())
{
e.preventDefault();
console.log("2");
$("#erreur_verif_password_inscription").text("ce n'est pas le même");
}
else if(!controle_email.test($("#email").val()))
{
e.preventDefault();
console.log("3");
$("#erreur_email").text("email invalide");
}
})
}
connexion(){
$("<h3>", {id:"titre_modal_connexion"}).appendTo("#"+this.id_enfant);
$("#titre_modal_connexion").text("SE CONNECTER");
$("<form>", {action: "index.php?action=connexionUsers", method: "post",
id:"form_modal_connexion", class: "form_modal"}).appendTo("#"+this.id_enfant);
$("<input>", {type:"text", name: "pseudo", id:"pseudo_connexion", placeholder: "votre pseudo", required:"required"}).appendTo("#form_modal_connexion");
$("<input>", {type:"text", name: "password", id:"password_connexion", placeholder: "votre mot de passe", required:"required"}).appendTo("#form_modal_connexion");
$("<a>", {class:"oublie_password", href:"index.php?action=askPasswordUser"}).appendTo("#form_modal_connexion");
$(".oublie_password").text("<PASSWORD>");
$("<input>", {type:"submit", value:"connexion", id:"boutton_connexion"}).appendTo("#form_modal_connexion");
}
}
<file_sep>
<?php $content = ob_start(); ?>
<main>
<section id="accueil">
<h1>Billet simple pour l'alaska</h1>
</section>
<h2 id="presentation_livre">Le nouveau livre de <NAME></h2>
<details>
<summary>A propos de l'auteur</summary>
<?= $biography->biography();?>
</details>
<section id="livre">
<div id="page1" class="page_livre">
<?php
while ($chapter = $req_chapter->fetch())
{
$chapter = new \christophe\blog\model\Chapter($chapter);
?>
<article class="article">
<div class="titre_article">
<?= $chapter->title();?>
</div>
<div class="resumer_article">
<?= $chapter->resumer();?>
</div>
<div class="info_article">
<p><strong>publié le : </strong><?= $chapter->date_creation();?></p>
<a href="index.php?action=chapter&id_chapter=<?php echo $chapter->id(); ?>">lire le chapitre</a>
</div>
</article>
<?php
}
$req_chapter->closeCursor();
?>
</div>
</section>
<section id="commentaires">
<h2>Commentaires sur le livre</h2>
<?php
if($req_comments->rowCount() != 0)
{
while($donnees = $req_comments->fetch())
{
$comment = new \christophe\blog\model\Comment($donnees);
?>
<div class="un_commentaire">
<div class="info_commentaire">
<p><strong>pseudo : </strong><?= $comment->pseudo(); ?></p>
<p><strong>Date : </strong><?= $comment->date_comment(); ?></p>
</div>
<div class="texte_commentaire">
<p><?= $comment->comment(); ?></p>
<form action="index.php?action=reportAComment" method="post" class="form_signaler_commentaire">
<input type="hidden" name="id_chapter" value="0">
<input type="hidden" name="id_commentaire_signaler" value="<?= $comment->id(); ?>">
<input type="submit" value="signaler ce commentaire">
</form>
</div>
</div>
<?php
}
$req_comments->closeCursor();
}
else
{?>
<p id="no_comment">Il n'y a aucun commentaire pour le moment</p>
<?php
}
?>
</section>
<?php
if(! isset($_SESSION['pseudo']))
{?>
<section id="demande_connexion">
<p>Vous devez vous connecter pour faire un commentaire</p>
<div id="demande_connexion_bouton">
<button class="connexion">connexion</button>
<button class="inscription">s'inscrire</button>
</div>
</section>
<?php
}
else
{?>
<section id="laisser_commentaire">
<form action="index.php?action=postComment" method="post" id="formulaire_laisser_commentaire">
<h3>Un commentaires?</h3>
<textarea name="commentaire" id="commentaire"></textarea>
<input type="hidden" name="id_chapter" value="0">
<input type="submit" value="laisser un commentaire">
</form>
</section>
<?php
}
?>
</main>
<?php $content = ob_get_clean();
require('template.php');
?>
<file_sep><?php $content_chapter = ob_start(); ?>
<a href="index.php?action=newChapter"><button id="creer_nouvelle_page">ajouter une page</button></a>
<?php
while($resultChapters = $resultGetChapters->fetch())
{
$chapter = new \christophe\blog\model\Chapter($resultChapters);
?>
<div class="affichage_pages">
<?= $chapter->title(); ?>
<div class="fenetre_date_boutton">
<p>publié le <?= $chapter->date_creation(); ?></p>
<div id="button_modif_chapter">
<!--<form method="post" action="index.php?action=changePublishChapter">-->
<input type="hidden" name="id_chapter" value="<?= $chapter->id(); ?>" class="id_chapter">
<?php
if ($chapter->publish() === 'oui')
{?>
<input type="hidden" name="changePublishBy" value="non" class="changePublishBy">
<input type="submit" name="button_remove" value="retirer" class="button_remove_chapter" data-id="<?= $chapter->id(); ?>">
<?php
}
else
{?>
<input type="hidden" name="changePublishBy" value="oui" class="changePublishBy">
<input type="submit" name="button_publish" value="publier">
<?php
}?>
<!--</form>-->
<form method="post" action="index.php?action=chapterModification" class="form_modif_chapitre">
<input type="hidden" name="id_chapitre_modif" value="<?= $chapter->id(); ?>">
<input type="submit" value="modifier" class="modifier">
</form>
<button class="supprimer_chapitre" data-id="<?= $chapter->id(); ?>">supprimer</button>
</div>
</div>
</div>
<?php
}
?><!--A VOIR CE QUE C'EST!!!!!!!!!!!!!!!!!!!-->
<?php $content_chapter = ob_get_clean(); ?>
<?php require('administrationView.php');?><file_sep>
var menuSmartphoneVisible = false;
// FAIRE APPARAITRE LE MENU SMARTPHONE
$(".icon_user").on("click", ()=>{
if(menuSmartphoneVisible == false)
{
$("#content_menu").css("display", "flex");
menuSmartphoneVisible = true;
}
else
{
$("#content_menu").hide();
menuSmartphoneVisible = false;
}
})
// REAPPARITION DU MENU SI FENETRE SUP A 700PX
$(window).resize(()=>{
if($(window).width() >700)
{
$("#content_menu").show();
menuSmartphoneVisible = true;
}
else
{
$("#content_menu").hide();
menuSmartphoneVisible = false;
}
})
// SI JE CLIQUE SUR INSCRIPTION
$(".inscription").on("click", ()=>{
if($("#titre_modal_inscription").text() === "S'INSCRIRE")
{
$("#modal_inscription").show();
$("#password").val("");
$("#email").val("");
$("#verif_password").val("");
}
else
{
const modal_inscription = new Modal("modal_inscription", "modal_enfant_inscription");
modal_inscription.inscription();
}
})
// SI JE CLIQUE SUR CONNEXION
$(".connexion").on("click", ()=>{
if($("#titre_modal_connexion").text() === "SE CONNECTER")
{
$("#modal_connexion").show();
}
else
{
const modal_connexion = new Modal("modal_connexion", "modal_enfant_connexion");
modal_connexion.connexion();
}
})
// TESTE AJAX CONNEXION
$("#boutton_connexion").on("click", (e)=>{
e.preventDefault();
console.log("ok");
$.ajax({
url : "index.php?action=connexionUsers",
type : "POST",
data : {
pseudo : $("#pseudo_connexion").val(),
password : $("#<PASSWORD>").val()
},
dataType : "html",
success : load("index.php?action=listChapter"),
error : alert('erreur')
})
})<file_sep>
<?php $content = ob_start(); ?>
<main>
<section id="accueil">
<h1>Billet simple pour l'alaska</h1>
</section>
<article class="affiche_article">
<div class="affiche_info_article">
<p><strong>auteur : </strong><?= $chapter->autor();?></p>
<p><strong>publié le : </strong><?= $chapter->date_creation();?></p>
</div>
<div class="affiche_texte_article">
<h3 id="chapter_title"><?= $chapter->title();?></h3>
<p><?= $chapter->chapter();?></p>
</div>
</article>
<section id="commentaires">
<?php
if ($req_comments->rowCount() != 0)
{
while($comment = $req_comments->fetch())
{
$comment = new \christophe\blog\model\Comment($comment);
?>
<div class="un_commentaire">
<div class="info_commentaire">
<p><strong>pseudo : </strong><?= $comment->pseudo(); ?></p>
<p>Date : <?= $comment->date_comment(); ?></p>
</div>
<div class="texte_commentaire">
<p><?= $comment->comment(); ?></p>
<form action="index.php?action=reportAComment" method="post" id="form_signaler_commentaire">
<input type="hidden" name="id_chapter" value="<?= $comment->id_chapter(); ?>">
<input type="hidden" name="id_commentaire_signaler" value="<?= $comment->id(); ?>">
<input type="submit" value="signaler ce commentaire">
</form>
</div>
</div>
<?php
}
$req_comments->closeCursor();
}
else
{?>
<p id="no_comment">Il n'y a aucun commentaire pour le moment.</p>
<?php
}
?>
</section>
<?php
if(! isset($_SESSION['pseudo']))
{?>
<section id="demande_connexion">
<p>Vous devez vous connecter pour faire un commentaire</p>
<div id="demande_connexion_bouton">
<button class="connexion">connexion</button>
<button class="inscription">s'inscrire</button>
</div>
</section>
<?php
}
else
{?>
<form action="index.php?action=postComment" method="post" id="formulaire_laisser_commentaire">
<section id="laisser_commentaire">
<h3>Un commentaires?</h3>
<textarea name="commentaire" id="commentaire"></textarea>
<input type="hidden" name="id_chapter" value="<?= $_GET['id_chapter']; ?>">
<input type="submit" value="laisser un commentaire">
</section>
</form>
<?php
}
?>
</main>
<?php $content = ob_get_clean();
require('template.php'); ?>
<file_sep><?php
namespace christophe\blog\model;
require_once('model/Manager.php');
class BiographieManager extends Manager
{
public function getBiographie()
{
$bdd = $this->dbConnect();
$req = $bdd->query('SELECT biography FROM autor WHERE id = 1');
$req_biographie = $req->fetch();
return $req_biographie;
}
public function getBiographieAutor()
{
$bdd = $this->dbConnect();
$req = $bdd->query('SELECT biography FROM autor');
$resultBiographie = $req->fetch();
return $resultBiographie;
}
public function modificationBiographie($biography)
{
$bdd = $this->dbConnect();
$req = $bdd->prepare('UPDATE autor SET biography = ?');
$req->execute(array($biography));
return $req;
}
}<file_sep><?php
session_start();
function loadClass($nomClass)
{
$nom = str_replace("christophe\blog\model\\", "", $nomClass);
require_once 'model\\'.$nom.'.php';
}
spl_autoload_register('loadClass');
require('controller/Frontend.php');
require('controller/Backend.php');
try
{
if(isset($_GET['action']))
{
switch($_GET['action'])
{
case 'listChapter':
$listChapter = new Frontend();
$listChapter->listChapter();
break;
case 'id_chapter':
if(isset($_GET['id_chapter']))
{
$id_chapter = new Frontend();
$id_chapter->chapter();
break;
}
else
{
throw new Exception('erreur : aucun identifiant de chapitre n\'a été envoyé.');
break;
}
case 'chapter':
if(isset($_GET['id_chapter']))
{
$chapter = new Frontend();
$chapter->chapter();
break;
}
else
{
throw new Exception('erreur : aucun identifiant de chapitre n\'a été envoyé.');
break;
}
case 'askPasswordUser':
$askPasswordUser = new Frontend();
$askPasswordUser->askPasswordUser();
break;
case 'askPasswordAdministrator':
$askPasswordAdministrator = new Backend();
$askPasswordAdministrator->askPasswordAdministrator();
break;
case 'reportAComment':
if(isset($_POST['id_commentaire_signaler']) and isset($_POST['id_chapter']))
{
$id_commentaire = htmlspecialchars($_POST['id_commentaire_signaler']);
$reportAComment = new Frontend();
$reportAComment->reportAComment($id_commentaire, $_POST['id_chapter']);
break;
}
else
{
throw new Exception('erreur dans le traitement du signalement.');
break;
}
case 'postComment':
if(isset($_POST['commentaire']) and isset($_POST['id_chapter']))
{
$commentaire = htmlspecialchars($_POST['commentaire']);
$postComment = new Frontend();
$postComment->postComment($_SESSION['pseudo'], $_POST['commentaire'], $_POST['id_chapter']);
}
else
{
throw new Exception('erreur : le commentaire n\'a pas pu être ajouté.');
}
break;
case 'inscriptionUsers':
if(isset($_POST['pseudo']) and isset($_POST['email']) and isset($_POST['password']))
{
$pseudo = htmlspecialchars($_POST['pseudo']);
$_SESSION['pseudo'] = $pseudo;
$email = htmlspecialchars($_POST['email']);
$password = htmlspecialchars($_POST['password']);
$inscriptionUsers = new Frontend();
$inscriptionUsers->inscriptionUsers($pseudo, $password, $email);
}
else
{
echo $_POST['pseudo'];
throw new Exception('erreur : l\'inscription n\'a pas pu aboutir.');
}
break;
case 'connexionUsers':
if(isset($_POST['pseudo']) and isset($_POST['password']))
{
$pseudo = htmlspecialchars($_POST['pseudo']);
$password = htmlspecialchars($_POST['password']);
$connexionUsers = new Frontend();
$connexionUsers->connexionUsers($pseudo, $password);
}
else
{
throw new Exception('erreur : problème de connexion.');
}
break;
case 'deconnexion':
$deconnexion = new Frontend();
$deconnexion->deconnexion();
break;
case 'sendEmail':
if(isset($_POST['pseudo']))
{
$pseudo = htmlspecialchars($_POST['pseudo']);
$sendEmail = new Frontend();
$sendEmail->sendEmailUser($pseudo);
}
elseif(isset($_POST['login']))
{
$login = htmlspecialchars($_POST['login']);
$sendEmail = new Backend();
$sendEmail->sendEmailAdministrator($login);
}
else
{
throw new Exception('erreur: le mail n\'a pas pu être envoyé.');
}
break;
case 'administrationSecurity':
$administrationSecurity = new Backend();
$administrationSecurity->administrationSecurity();
break;
case 'accessAdministration':
if(isset($_POST['login']) and isset($_POST['login_password']))
{
$accessAdministration = new Backend();
$accessAdministration->accessAdministration($_POST['login'], $_POST['login_password']);
}
else
{
throw new Exception('erreur : acces administration problème');
}
break;
case 'accessMenuAdministration':
$accessMenuAdministration = new Backend();
$accessMenuAdministration->accessMenuAdministration();
break;
case 'newChapter':
$newChapter = new Backend();
$newChapter->newChapter();
break;
case 'changePublishChapter':
if(isset($_POST['id_chapter']))
{
$chapterID = $_POST['id_chapter'];
if(isset($_POST['button_remove']))
{
$publish = 'non';
$changePublishChapter = new Backend();
$changePublishChapter->changePublishChapter($chapterID, $publish);
}
elseif(isset($_POST['button_publish']))
{
$publish = 'oui';
$changePublishChapter = new Backend();
$changePublishChapter->changePublishChapter($chapterID, $publish);
}
else
{
throw new Exception('erreur : publier ou pas?');
}
}
else
{
throw new Exception('erreur : données manquantes.');
}
break;
case 'removeChapter':
if(isset($_POST['id_chapter_to_remove']))
{
$id_chapter = $_POST['id_chapter_to_remove'];
$removeChapter = new Backend();
$removeChapter->removeChapter($id_chapter);
}
else
{
throw new Exception('probleme lors de la suppression du chapitre.');
}
break;
case 'validComment':
if(isset($_POST['commentaire_id']) and isset($_POST['signaler']))
{
$validComment = new Backend();
$validComment->validComment($_POST['commentaire_id'], $_POST['signaler']);
}
else
{
throw new Exception('probleme lors de la validation du commentaire');
}
break;
case 'removeComment':
if(isset($_POST['id_comment_to_remove']))
{
$id_comment = $_POST['id_comment_to_remove'];
$removeComment = new Backend();
$removeComment->removeComment($id_comment);
}
else
{
throw new Exception('probleme lors de la suppression du commentaire');
}
break;
case 'modifBiographie':
if(isset($_POST['modif_biographie']))
{
$biographie = htmlspecialchars($_POST['modif_biographie']);
$modifBiographie = new Backend();
$modifBiographie->modifBiographie($biographie);
}
else
{
throw new Exception('probleme survenue lors de la modif de la biographie');
}
break;
case 'changePassword':
if(isset($_POST['ancien_password']) and isset($_POST['nouveau_password1']) and isset($_POST['nouveau_password2']))
{
$ancien_password = htmlspecialchars($_POST['ancien_password']);
$nouveau_password = htmlspecialchars($_POST['<PASSWORD>']);
$login = $_SESSION['pseudo'];
$changePassword = new Backend();
$changePassword->changePassword($ancien_password, $nouveau_password, $login);
}
else
{
throw new Exception('probleme lors de la modif du password');
}
break;
case 'chapterModification':
if(isset($_POST['id_chapitre_modif']))
{
$chapterModification = new Backend();
$chapterModification->chapterModification($_POST['id_chapitre_modif']);
}
else
{
throw new Exception('probleme pour afficher la page de modification du chapitre');
}
break;
case 'changeChapter':
if(isset($_POST['nouveau_titre']) and isset($_POST['nouveau_texte']) and isset($_POST['nouveau_resume']))
{
$publier = 'non';
if(isset($_POST['publier']))
{
$publier = 'oui';
}
if(isset($_POST['chapterID']))
{
$changeChapter = new Backend();
$changeChapter->changeExistedChapter($_POST['nouveau_titre'], $_POST['nouveau_texte'], $_POST['nouveau_resume'], $_POST['chapterID'], $publier);
}
else
{
$changeChapter = new Backend();
$changeChapter->writeChapter($_POST['nouveau_titre'], $_POST['nouveau_texte'], $_POST['nouveau_resume'], $publier);
}
}
else
{
throw new Exception('probleme lors du changement du chapitre');
}
break;
}
}
else
{
$chapter = new Frontend();
$chapter->listChapter();
}
}
catch(Exception $e)
{
echo 'erreur : '.$e->getMessage();
}
<file_sep><?php $content = ob_start(); ?>
<main id="main_administration">
<div id="menu_administratif">
<button id="choix_accueil" class="choix">
<span class="icon_menu_administration"><i class="icon_accueil"></i></span>
<span class="menu_administration">Accueil</span>
</button>
<button id="choix_pages" class="choix">
<span class="icon_menu_administration"><i class="icon_chapitres"></i></span>
<span class="menu_administration">Chapitres</span>
</button>
<button id="choix_commentaires" class="choix">
<span class="icon_menu_administration"><i class="icon_commentaires"></i></span>
<span class="menu_administration">Commentaires</span>
</button>
<button id="choix_parametres" class="choix">
<span class="icon_menu_administration"><i class="icon_parametres"></i></span>
<span class="menu_administration">Paramètres</span>
</button>
</div>
<section id="section_administration">
<!--*****************************************************************************************************-->
<!-- ADMINISTRATION ACCUEIL -->
<section id="section_accueil">
<div id="partie_accueil">
<p>Nombre d'inscrit : <span><?= $resultTotalUsers['total_user'];?></span></p>
<p>Nombre de commentaire : <span><?= $resultTotalComment['total_comment'];?></span></p>
<p>Nombre de commentaire signaler : <span><?= $resultTotalRportComment['total_comment_report'];?></span></p>
</div>
</section>
<!--*****************************************************************************************************-->
<!-- ADMINISTRATION PAGES -->
<section id="section_pages">
<a href="index.php?action=newChapter"><button id="creer_nouvelle_page">ajouter une page</button></a>
<?php
while($resultChapters = $resultGetChapters->fetch())
{
$chapter = new \christophe\blog\model\Chapter($resultChapters);
?>
<div class="affichage_pages">
<?= $chapter->title(); ?>
<div class="fenetre_date_boutton">
<p>publié le <?= $chapter->date_creation(); ?></p>
<div id="button_modif_chapter">
<form method="post" action="index.php?action=changePublishChapter">
<input type="hidden" name="id_chapter" value="<?= $chapter->id(); ?>" class="id_chapter">
<?php
if ($chapter->publish() === 'oui')
{?>
<input type="hidden" name="changePublishBy" value="non" class="changePublishBy" id="retire_chapter_<?= $chapter->id(); ?>">
<input type="submit" name="button_remove" value="retirer" class="button_remove_chapter" data-id="<?= $chapter->id(); ?>">
<?php
}
else
{?>
<input type="hidden" name="changePublishBy" value="oui" class="changePublishBy">
<input type="submit" name="button_publish" value="publier" class="button_publish_chapter">
<?php
}?>
</form>
<form method="post" action="index.php?action=chapterModification" class="form_modif_chapitre">
<input type="hidden" name="id_chapitre_modif" value="<?= $chapter->id(); ?>">
<input type="submit" value="modifier" class="modifier">
</form>
<button class="supprimer_chapitre" data-id="<?= $chapter->id(); ?>">supprimer</button>
</div>
</div>
</div>
<?php
}?>
</section>
<!--*****************************************************************************************************-->
<!-- ADMINISTRATION COMMENTAIRES -->
<section id="section_commentaires">
<div id="choix_des_commentaires">
<label for="affiche_choix_commentaire">afficher :</label>
<select name="affiche_choix_commentaire" id="affiche_choix_commentaire">
<option value="all" selected="selected">tous les commentaires</option>
<?php
while($option = $resultChaptersOption->fetch())
{
$chapter = new \christophe\blog\model\Chapter($option);
?>
<option value="<?= $chapter->id(); ?>"><?= $chapter->title();?></option>
<?php
}
$resultChaptersOption->closeCursor(); ?>
?>
</select>
<input type="checkbox" name="signaler" id="ckeckbox_signaler"><label for="signaler">signaler</label>
</div>
<?php
while($donnees = $resultGetComments->fetch())
{
$comment = new \christophe\blog\model\Comment($donnees);
?>
<div class="fenetre_commentaire <?= $comment->id_chapter().' '.$comment->report();?>">
<div class="affiche_commentaire">
<div class="affiche_info_commentaire">
<p><?= $comment->pseudo(); ?></p>
<p>le <?= $comment->date_comment(); ?></p>
</div>
<div class="affiche_chapitre_commentaire">
<?php
if($comment->id_chapter() == 0)
{?>
<p>Billet simple pour l'alaska</p>
<?php
}
else
{
echo $donnees['title'];
}
echo $comment->comment(); ?>
</div>
</div>
<div class="fenetre_boutton_modif_comment">
<?php
if($comment->report() === 'signaler')
{?>
<form method="post" action="index.php?action=validComment">
<input type="hidden" name="signaler" value="">
<input type="hidden" name="commentaire_id" value="<?= $comment->id(); ?>">
<input type="submit" value="valider">
</form>
<?php
}?>
<button class="supprimer_commentaire" data-id="<?= $comment->id(); ?>">supprimer</button>
</div>
</div>
<?php
}
$resultGetComments->closeCursor();
?>
</section>
<!--*****************************************************************************************************-->
<!-- ADMINISTRATION PARAMETRES -->
<section id="section_parametres">
<fieldset id="parametre_auteur">
<legend>Biographie de l'auteur</legend>
<form id="form_modif_biographie" method="post" action="index.php?action=modifBiographie">
<label for="modif_biographie">Ma biographie</label>
<textarea name="modif_biographie"><?= $biography->biography();?></textarea>
<input type="submit" value="publié">
</form>
</fieldset>
<fieldset id="parametre_password">
<legend>Changer mot de passe administratif</legend>
<form id="form_modif_password" method="post" action="index.php?action=changePassword">
<div id="ancien_password">
<label for="ancien_password">ancien password</label>
<input type="<PASSWORD>" name="<PASSWORD>" required>
</div>
<p id="message_erreur_old_password"></p>
<div id="nouveau_password1">
<label for="<PASSWORD>_password1">nouveau password</label>
<input type="<PASSWORD>" name="<PASSWORD>" id="<PASSWORD>" required>
</div>
<p id="message_erreur_new_password1"></p>
<div id="nouveau_password2">
<label for="nou<PASSWORD>"><PASSWORD></label>
<input type="<PASSWORD>" name="<PASSWORD>" id="<PASSWORD>" required>
</div>
<p id="message_erreur_new_password2"></p>
<input type="submit" value="valider" id="valid_new_password">
</form>
</fieldset>
</section>
</section>
</main>
<?php $content = ob_get_clean(); ?>
<?php require('template.php');?>
<file_sep>
<?php $content = ob_start(); ?>
<main>
<section id="formulaire_recupere_password">
<form id="formulaire_recupere_password_user" method="post" action="index.php?action=sendEmail">
<div>
<label for="pseudo">pseudo</label>
<?php
if(isset($_SESSION['pseudo_invalide']) and $_SESSION['pseudo_invalide'] == TRUE)
{?>
<input type="text" name="pseudo" placeholder="invalide" required>
<?php
$_SESSION['pseudo_invalide'] = "";
}
else
{?>
<input type="text" name="pseudo" required>
<?php
}
?>
</div>
<p>un mail contenant votre mot de passe vous sera envoyé</p>
<input type="submit" value="récupérer">
</form>
</section>
</main>
<?php $content = ob_get_clean();
require('template.php');<file_sep><!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css?family=Amatic+SC|Caveat|Courgette|Indie+Flower|Permanent+Marker|Satisfy&display=swap" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="public/css/style_administration.css">
<title>Billet simple pour l'Alaska. Administration</title>
</head>
<body>
<header>
<a href="index.php"><img id="logo" src="public/images/logo_auteur.png" alt="logo"></a>
<?php
if(isset($_SESSION['login']))
{?>
<div id="menu">
<a href="index.php?action=accessMenuAdministration">
<span class="icon_menu_administration"><i class="icon_accueil"></i></span>
<span class="menu_administration">Accueil</span>
</a>
<div id="content_login">
<i class="icon_user"></i>
<span class="menu_administration" id="text_deconnexion">
<a href="index.php?action=deconnexion">déconnexion</a>
</span>
</div>
</div>
<?php
}?>
</header>
<?= $content; ?>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="<KEY>
crossorigin="anonymous"></script>
<script src="https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js"></script>
<script>tinymce.init({selector:'textarea'});</script>
<script src="public/js/modal.js"></script>
<script src="public/js/main_administration.js"></script>
</body>
</html><file_sep>class Header {
constructor(url_logo, alt){
this.url_logo = url_logo;
this.alt = alt;
this.icon_actif = false;
this.mon_header();
}
mon_header(){// CREATION DU HEADER AVEC LE LOGO
$("<main>").prependTo("body");
$("<header>").prependTo("body");
$("<div>", {id: "mon_header"}).appendTo("header");
$("<img>", {id:"logo", src:this.url_logo, alt:this.alt}).prependTo("#mon_header");
}
mon_menu(menu){// CREATION DU MENU
$("<nav>", {id: "contenant_menu"}).appendTo("#mon_header");
$("<i>", {id: "icon_menu"}).appendTo("#contenant_menu");
$("<div>", {id: "mon_menu"}).appendTo("#contenant_menu");//MENU POUR ECRAN SUP A 600PX
$("<div>", {id: "mon_menu_small"}).appendTo("header");//MENU POUR ECRAN INF A 600PX
for(let element of menu){
$("<a>", { id: element.nom.replace(' ',''), href : element.href}).appendTo("#mon_menu");
$("<a>", { id: element.nom.replace(' ','')+"_small", href : element.href}).appendTo("#mon_menu_small");
$("#"+element.nom.replace(' ','')).text(element.nom);
$("#"+element.nom.replace(' ','')+"_small").text(element.nom);
}
$("#mon_menu_small").hide();
$("#icon_menu").click(()=> {//SI JE CLIQUE SUR L'ICON MENU JE FAIS APPARAITRE OU DISPARAITRE LE MENU
if(this.icon_actif === false) {
$("#mon_menu_small").show();
this.icon_actif = true;
}
else {
$("#mon_menu_small").hide();
this.icon_actif = false;
}
});
}
}<file_sep><?php
namespace christophe\blog\model;
class User
{
private $_id;
private $_pseudo;
private $_password;
private $_email;
public function __construct($donnees)
{
$this->hydrate($donnees);
}
public function hydrate(array $donnees)
{
foreach($donnees as $key => $value)
{
$method = 'set'.ucfirst($key);
if(method_exists($this, $method))
{
$this->$method($value);
}
}
}
// DECLARATION DES GETTERS
public function id(){return $this->_id;}
public function pseudo(){return $this->_pseudo;}
public function password(){return $this->_password;}
public function email(){return $this->_email;}
// DECLARATION DES SETTERS
public function setId($id){
$id = int($id);
if($id > 0)
{
$this->_id = $id;
}
}
public function setPseudo($pseudo){
if(is_string($pseudo))
{
$this->_pseudo = $pseudo;
}
}
public function setPassword($password){
if(is_string($password))
{
$this->_password = $password;
}
}
public function setEmail($email){
if(is_string($email))
{
$this->_email = $email;
}
}
}<file_sep><?php
use \christophe\blog\model\CommentManager;
use \christophe\blog\model\Comment;
use \christophe\blog\model\ChapterManager;
use \christophe\blog\model\Chapter;
use \christophe\blog\model\UserManager;
use \christophe\blog\model\User;
use \christophe\blog\model\BiographieManager;
use \christophe\blog\model\Biography;
class Frontend
{
public function listChapter()
{
$chapter = new ChapterManager();
$biography = new BiographieManager();
$commentManager = new CommentManager();
$req_biography = $biography->getBiographie();
$biography = new Biography($req_biography);
$req_chapter = $chapter->getAllChapter();
$req_comments = $commentManager->getCommentaires(0);
require('view/frontend/listChapterView.php');
}
public function chapter()
{
$chapter = new ChapterManager();
$commentManager = new CommentManager();
$id_chapter = htmlspecialchars($_GET['id_chapter']);
$chapter = $chapter->getChapter($id_chapter);
$chapter = new Chapter($chapter);
$req_comments = $commentManager->getCommentaires($id_chapter);
require('view/frontend/chapterView.php');
}
public function askPasswordUser()
{
require('view/frontend/askPasswordView.php');
}
public function sendEmailUser($pseudo)
{
$userManager = new UserManager();
$resultEmail = $userManager->sendMailUser($pseudo);
if($resultEmail === 'erreur')
{
$_SESSION['pseudo_invalide'] = TRUE;
header('Location: index.php?action=askPassword');
}
else
{
ini_set("SMTP", "smtp.projet4.christophecoach.ovh");
mail('$resultEmail[\'email\']', 'récupération mot de passe',
'Bonjour $resultEmail[\'pseudo\'],\n\rVotre mot de passe : $resultEmail[\'password\']');
header('Location: index.php?action=listChapter');
}
}
public function reportAComment($id_commentaire_signaler, $id_chapter)
{
$commentManager = new CommentManager();
$resultReport = $commentManager->reportComment($_POST['id_commentaire_signaler']);
if($resultReport === false)
{
throw new Exception('Désole, impossible de signaler ce commentaires.');
}
else
{
if ($id_chapter == 0)
{
header('Location: index.php?action=listChapter');
}
else
{
header('Location: index.php?action=chapter&id_chapter='.$id_chapter);
}
}
}
public function postComment($pseudo, $comment, $id_chapter)
{
$commentManager = new CommentManager();
$resultPost = $commentManager->addComment($pseudo, $comment, $id_chapter);
if($resultPost === false)
{
throw new Exception('Désolé, le commentaire n\'a pas pu être ajouté.');
}
else
{
if ($id_chapter == 0)
{
header('Location: index.php?action=listChapter');
}
else
{
header('Location: index.php?action=chapter&id_chapter='.$id_chapter);
}
}
}
public function inscriptionUsers($pseudo, $password, $email)
{
$userManager = new UserManager();
$resultInscription = $userManager->inscriptionUser($pseudo, $password, $email);
if($resultInscription === false)
{
throw new Exception('Désolé, l\'inscription n\'a pas pu être faite.');
}
else
{
header('Location: index.php?action=listChapter');
}
}
public function connexionUsers($pseudo, $password)
{
$userManager = new UserManager();
$resultConnexion = $userManager->connexionUser($pseudo, $password);
header('Location: index.php?action=listChapter');
}
public function deconnexion()
{
session_destroy();
header('Location: index.php?action=listChapter');
}
}<file_sep><?php
namespace christophe\blog\model;
class Manager
{
protected function dbConnect()
{
$bdd = new \PDO('mysql:host=localhost;dbname=projet4;charset=utf8', 'root', '', array(\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION));
return $bdd;
}
}<file_sep>
<?php $content = ob_start(); ?>
<main>
<form id="fenetre_password" action="index.php?action=accessAdministration" method="post">
<div class="boite_information">
<label for="login">LOGIN</label>
<?php
if(isset($_SESSION['login']) and $_SESSION['login'] == 'invalide')
{?>
<input type="text" name="login" placeholder="invalide" required></br>
<?php $_SESSION['login'] = "";
}
else
{?>
<input type="text" name="login" required></br>
<?php
}?>
</div>
<div class="boite_information">
<label for="login_password">MOT DE PASSE</label>
<?php
if(isset($_SESSION['login_password']) and $_SESSION['login_password'] == '<PASSWORD>')
{?>
<input type="password" name="login_password" placeholder="<PASSWORD>" required>
<?php $_SESSION['login_password'] = "";
}
else
{?>
<input type="<PASSWORD>" name="login_password" required>
<?php
}?>
</div>
<a href="index.php?action=askPasswordAdministrator" class="password_oublie">j'ai oublié mon mot de passe</a>
<input type="submit" value="valider">
</form>
</main>
<?php $content = ob_get_clean(); ?>
<?php require('template.php');?>
<file_sep><?php
namespace christophe\blog\model;
class Comment
{
private $_id;
private $_pseudo;
private $_comment;
private $_report;
private $_id_chapter;
private $_date_comment;
public function __construct($donnees)
{
$this->hydrate($donnees);
}
public function hydrate(array $donnees)
{
foreach($donnees as $key => $value)
{
$method = 'set'.ucfirst($key);
if(method_exists($this, $method))
{
$this->$method($value);
}
}
}
// DECLARATION DES GETTERS
public function id(){return $this->_id;}
public function pseudo(){return $this->_pseudo;}
public function comment(){return $this->_comment;}
public function report(){return $this->_report;}
public function id_chapter(){return $this->_id_chapter;}
public function date_comment(){return $this->_date_comment;}
// DECLARATION DES GETTERS
public function setId($id){
$id = (int)$id;
if($id >0)
{
$this->_id = $id;
}
}
public function setPseudo($pseudo){
if(is_string($pseudo))
{
$this->_pseudo = $pseudo;
}
}
public function setComment($comment){
if(is_string($comment))
{
$this->_comment = $comment;
}
}
public function setReport($report){
if(is_string($report))
{
$this->_report = $report;
}
}
public function setId_chapter($id_chapter){
$id_chapter = (int)$id_chapter;
if($id_chapter > 0)
{
$this->_id_chapter = $id_chapter;
}
}
public function setDate_comment($date_comment){
$this->_date_comment = $date_comment;
}
}<file_sep><!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css?family=Amatic+SC|Caveat|Courgette|Indie+Flower|Permanent+Marker|Satisfy&display=swap" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="public/css/style.css">
<title>Billet simple pour l'Alaska.</title>
</head>
<body>
<header>
<a href="index.php"><img id="logo" src="public/images/logo_auteur.png" alt="logo"></a>
<div id="menu">
<i class="icon_user"></i>
<div id="content_menu">
<?php
if(isset($_SESSION['pseudo']))
{?>
<p>Bienvenue <?= $_SESSION['pseudo']; ?></p>
<a href="index.php?action=deconnexion">Déconnexion</a>
<?php
if($_SESSION['pseudo'] == 'forteroche')
{
?>
<a href="index.php?action=administrationSecurity">Administration</a>
<?php
}
}
else
{
if(isset($_SESSION['pseudo_inconnu']) or isset($_SESSION['password_connexion_inconnu']))
{
if(isset($_SESSION['pseudo_inconnu']))
{?>
<p class="inconnu">pseudo inconnu</p>
<?php
}
else
{?>
<p class="inconnu">password invalide</p>
<?php
}
session_destroy();
}
?>
<button class="connexion">se connecter</button>
<button class="inscription">s'inscrire</button>
<?php
}
?>
</div>
</div>
</header>
<?= $content; ?>
<footer>
<a href="#">BIBLIOGRAPHIE</a>
</footer>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="<KEY>
crossorigin="anonymous"></script>
<!--<script src="public/js/accueil.js"></script>-->
<script src="public/js/modal.js"></script>
<script src="public/js/main.js"></script>
</body>
</html><file_sep><?php
use \christophe\blog\model\CommentManager;
use \christophe\blog\model\Comment;
use \christophe\blog\model\ChapterManager;
use \christophe\blog\model\Chapter;
use \christophe\blog\model\UserManager;
use \christophe\blog\model\User;
use \christophe\blog\model\BiographieManager;
use \christophe\blog\model\Biography;
class Backend
{
public function administrationSecurity()
{
if(isset($_SESSION['login']))
{
$commentManager = new CommentManager();
$chapterManager = new ChapterManager();
$userManager = new UserManager();
$biographie = new BiographieManager();
$chapter = new Chapter();
$resultTotalUsers = $userManager->getTotalUser();
$resultTotalComment = $commentManager->getTotalComment();
$resultTotalRportComment = $commentManager->getTotalReportComment();
$resultGetChapters = $chapterManager->getChapters();
$resultChaptersOption = $chapterManager->getChapters();
$resultGetComments = $commentManager->getComments();
$resultBiographieAutor = $biographie->getBiographieAutor();
$biography = new Biography($resultBiographieAutor);
require('view/backend/administrationView.php');
}
else
{
require('view/backend/administrationSecurityView.php');
}
}
public function askPasswordAdministrator()
{
require('view/backend/askPasswordView.php');
}
public function sendEmailAdministrator($login)
{
$userManager = new UserManager();
$resultEmail = $userManager->sendMailAdministrator($login);
if($resultEmail === 'erreur')
{
$_SESSION['login_invalide'] = TRUE;
header('Location: index.php?action=administrationSecurity');
}
else
{
mail('$resultEmail[\'email\']', 'récupération mot de passe',
'Bonjour $resultEmail[\'login\'],\n\rVotre mot de passe : $resultEmail[\'password\']');
header('Location: index.php?action=administrationSecurity');
}
}
public function accessAdministration($login, $password)
{
$login = htmlspecialchars($login);
$password = htmlspecialchars($password);
$userManager = new UserManager();
$resultValidAccessAdmin = $userManager->validAccessAdministration($login, $password);
if ($resultValidAccessAdmin === false)
{
$_SESSION['login'] = 'invalide';
require('view/backend/administrationSecurityView.php');
}
else
{
if($resultValidAccessAdmin['password'] == $password)
{
$_SESSION['login'] = $login;
$commentManager = new CommentManager();
$chapterManager = new ChapterManager();
$userManager = new UserManager();
$biographie = new BiographieManager();
$resultTotalUsers = $userManager->getTotalUser();
$resultTotalComment = $commentManager->getTotalComment();
$resultTotalRportComment = $commentManager->getTotalReportComment();
$resultGetChapters = $chapterManager->getChapters();
$resultChaptersOption = $chapterManager->getChapters();
$resultGetComments = $commentManager->getComments();
$resultBiographieAutor = $biographie->getBiographieAutor();
$biography = new Biography($resultBiographieAutor);
require('view/backend/administrationView.php');
}
else
{
$_SESSION['login_password'] = '<PASSWORD>';
require('view/backend/administrationSecurityView.php');
}
}
}
public function accessMenuAdministration()
{
$commentManager = new CommentManager();
$chapterManager = new ChapterManager();
$userManager = new UserManager();
$biographie = new BiographieManager();
$resultTotalUsers = $userManager->getTotalUser();
$resultTotalComment = $commentManager->getTotalComment();
$resultTotalRportComment = $commentManager->getTotalReportComment();
$resultGetChapters = $chapterManager->getChapters();
$resultChaptersOption = $chapterManager->getChapters();
$resultGetComments = $commentManager->getComments();
$resultBiographieAutor = $biographie->getBiographieAutor();
$biography = new Biography($resultBiographieAutor);
require('view/backend/administrationView.php');
}
public function newChapter()
{
require('view/backend/newChapterView.php');
}
public function changePublishChapter($chapterID, $publish)
{
$chapterManager = new ChapterManager();
$resultChangePublishChapter = $chapterManager->changePublicationChapter($chapterID, $publish);
if($resultChangePublishChapter == false)
{
throw new Exception('Désole, impossible de modifier la publication.');
}
else
{
$commentManager = new CommentManager();
$chapterManager = new ChapterManager();
$userManager = new UserManager();
$biographie = new BiographieManager();
$resultTotalUsers = $userManager->getTotalUser();
$resultTotalComment = $commentManager->getTotalComment();
$resultTotalRportComment = $commentManager->getTotalReportComment();
$resultGetChapters = $chapterManager->getChapters();
$resultChaptersOption = $chapterManager->getChapters();
$resultGetComments = $commentManager->getComments();
$resultBiographieAutor = $biographie->getBiographieAutor();
$biography = new Biography($resultBiographieAutor);
require('view/backend/administrationView.php');
}
}
public function removeChapter($id_chapter)
{
$chapterManager = new ChapterManager();
$resultSuppression = $chapterManager->suppressionChapter($id_chapter);
if($resultSuppression == false)
{
throw new Exception('Désole, suppression du chapitre impossible.');
}
else
{
$commentManager = new CommentManager();
$chapterManager = new ChapterManager();
$userManager = new UserManager();
$biographie = new BiographieManager();
$resultTotalUsers = $userManager->getTotalUser();
$resultTotalComment = $commentManager->getTotalComment();
$resultTotalRportComment = $commentManager->getTotalReportComment();
$resultGetChapters = $chapterManager->getChapters();
$resultChaptersOption = $chapterManager->getChapters();
$resultGetComments = $commentManager->getComments();
$resultBiographieAutor = $biographie->getBiographieAutor();
$biography = new Biography($resultBiographieAutor);
require('view/backend/administrationView.php');
}
}
public function validComment($id_comment, $signaler)
{
$commentManager = new CommentManager();
$resultValidation = $commentManager->validationComment($id_comment, $signaler);
if($resultValidation == false)
{
throw new Exception('Désole, validation du commentaire impossible.');
}
else
{
$commentManager = new CommentManager();
$chapterManager = new ChapterManager();
$userManager = new UserManager();
$biographie = new BiographieManager();
$resultTotalUsers = $userManager->getTotalUser();
$resultTotalComment = $commentManager->getTotalComment();
$resultTotalRportComment = $commentManager->getTotalReportComment();
$resultGetChapters = $chapterManager->getChapters();
$resultChaptersOption = $chapterManager->getChapters();
$resultGetComments = $commentManager->getComments();
$resultBiographieAutor = $biographie->getBiographieAutor();
$biography = new Biography($resultBiographieAutor);
require('view/backend/administrationView.php');
}
}
public function removeComment($id_comment)
{
$commentManager = new CommentManager();
$resultSuppression = $commentManager->suppressionComment($id_comment);
if($resultSuppression == false)
{
throw new Exception('Désole, suppression du commentaire impossible.');
}
else
{
$commentManager = new CommentManager();
$chapterManager = new ChapterManager();
$userManager = new UserManager();
$biographie = new BiographieManager();
$resultTotalUsers = $userManager->getTotalUser();
$resultTotalComment = $commentManager->getTotalComment();
$resultTotalRportComment = $commentManager->getTotalReportComment();
$resultGetChapters = $chapterManager->getChapters();
$resultChaptersOption = $chapterManager->getChapters();
$resultGetComments = $commentManager->getComments();
$resultBiographieAutor = $biographie->getBiographieAutor();
$biography = new Biography($resultBiographieAutor);
require('view/backend/administrationView.php');
}
}
public function modifBiographie($biographie)
{
$biographie = new BiographieManager();
$resultModificationBiographie = $biographie->modificationBiographie($biographie);
if($resultModificationBiographie == false)
{
throw new Exception('Désole, erreur lors de la modification de la biographie.');
}
else
{
$commentManager = new CommentManager();
$chapterManager = new ChapterManager();
$userManager = new UserManager();
$biographie = new BiographieManager();
$resultTotalUsers = $userManager->getTotalUser();
$resultTotalComment = $commentManager->getTotalComment();
$resultTotalRportComment = $commentManager->getTotalReportComment();
$resultGetChapters = $chapterManager->getChapters();
$resultChaptersOption = $chapterManager->getChapters();
$resultGetComments = $commentManager->getComments();
$resultBiographieAutor = $biographie->getBiographieAutor();
$biography = new Biography($resultBiographieAutor);
require('view/backend/administrationView.php');
}
}
public function changePassword($ancien_password, $nouveau_password, $login)
{
$userManager = new UserManager();
$resultlogin = $userManager->validAccessAdministration($login);
if($resultlogin == false)
{
$_SESSION['login'] = 'inconnu';
$commentManager = new CommentManager();
$chapterManager = new ChapterManager();
$userManager = new UserManager();
$biographie = new BiographieManager();
$resultTotalUsers = $userManager->getTotalUser();
$resultTotalComment = $commentManager->getTotalComment();
$resultTotalRportComment = $commentManager->getTotalReportComment();
$resultGetChapters = $chapterManager->getChapters();
$resultChaptersOption = $chapterManager->getChapters();
$resultGetComments = $commentManager->getComments();
$resultBiographieAutor = $biographie->getBiographieAutor();
$biography = new Biography($resultBiographieAutor);
require('view/backend/administrationView.php');
}
else
{
if($resultlogin['password'] != $ancien_password)
{
$_SESSION['ancien_password'] = '<PASSWORD>';
$commentManager = new CommentManager();
$chapterManager = new ChapterManager();
$userManager = new UserManager();
$biographie = new BiographieManager();
$resultTotalUsers = $userManager->getTotalUser();
$resultTotalComment = $commentManager->getTotalComment();
$resultTotalRportComment = $commentManager->getTotalReportComment();
$resultGetChapters = $chapterManager->getChapters();
$resultChaptersOption = $chapterManager->getChapters();
$resultGetComments = $commentManager->getComments();
$resultBiographieAutor = $biographie->getBiographieAutor();
$biography = new Biography($resultBiographieAutor);
require('view/backend/administrationView.php');
}
else
{
$userManager = new UserManager();
$resultChangePassword = $userManager->modificationPassword($nouveau_password, $login);
if($resultChangePassword == false)
{
throw new Exception('Désole, erreur lors de la modification du password.');
}
else
{
$commentManager = new CommentManager();
$chapterManager = new ChapterManager();
$userManager = new UserManager();
$biographie = new BiographieManager();
$resultTotalUsers = $userManager->getTotalUser();
$resultTotalComment = $commentManager->getTotalComment();
$resultTotalRportComment = $commentManager->getTotalReportComment();
$resultGetChapters = $chapterManager->getChapters();
$resultChaptersOption = $chapterManager->getChapters();
$resultGetComments = $commentManager->getComments();
$resultBiographieAutor = $biographie->getBiographieAutor();
$biography = new Biography($resultBiographieAutor);
require('view/backend/administrationView.php');
}
}
}
}
public function chapterModification($id)
{
$chapterManager = new ChapterManager();
$resultGetChapter = $chapterManager->getChapterForModification($id);
if($resultGetChapter == false)
{
throw new Exception('Désole, probleme survenu lors de la recupération du chapitre.');
}
else
{
$chapter = $resultGetChapter->fetch();
$chapter = new Chapter($chapter);
require('view/backend/newChapterView.php');
}
}
public function changeExistedChapter($nouveau_titre, $nouveau_texte, $nouveau_resumer, $id, $publier)
{
$chapterManager = new ChapterManager();
$resultchangeExistedChapter = $chapterManager->changeExistChapter($nouveau_titre, $nouveau_texte, $nouveau_resumer, $id, $publier);
if($resultchangeExistedChapter == false)
{
throw new Exception('Désole, probleme survenu lors de la modif du chapitre.');
}
else
{
$commentManager = new CommentManager();
$chapterManager = new ChapterManager();
$userManager = new UserManager();
$biographie = new BiographieManager();
$resultTotalUsers = $userManager->getTotalUser();
$resultTotalComment = $commentManager->getTotalComment();
$resultTotalRportComment = $commentManager->getTotalReportComment();
$resultGetChapters = $chapterManager->getChapters();
$resultChaptersOption = $chapterManager->getChapters();
$resultGetComments = $commentManager->getComments();
$resultBiographieAutor = $biographie->getBiographieAutor();
$biography = new Biography($resultBiographieAutor);
require('view/backend/administrationView.php');
}
}
public function writeChapter($nouveau_titre, $nouveau_texte, $nouveau_resumer, $publier)
{
$chapterManager = new ChapterManager();
$resultWriteChapter = $chapterManager->writeNewChapter($nouveau_titre, $nouveau_texte, $nouveau_resumer, $publier);
if($resultWriteChapter == false)
{
throw new Exception('Désole, probleme survenu lors de l\'ajout du nouveau chapitre.');
}
else
{
$commentManager = new CommentManager();
$chapterManager = new ChapterManager();
$userManager = new UserManager();
$biographie = new BiographieManager();
$resultTotalUsers = $userManager->getTotalUser();
$resultTotalComment = $commentManager->getTotalComment();
$resultTotalRportComment = $commentManager->getTotalReportComment();
$resultGetChapters = $chapterManager->getChapters();
$resultChaptersOption = $chapterManager->getChapters();
$resultGetComments = $commentManager->getComments();
$resultBiographieAutor = $biographie->getBiographieAutor();
$biography = new Biography($resultBiographieAutor);
require('view/backend/administrationView.php');
}
}
}
<file_sep><?php
namespace christophe\blog\model;
require_once('model/Manager.php');
class CommentManager extends Manager
{
public function addComment($pseudo, $comment, $id_chapter)
{
$bdd = $this->dbConnect();
$req = $bdd->prepare('INSERT INTO comments(pseudo, comment, report, id_chapter, date_comment) VALUES(:pseudo, :comment, "", :id_chapter, NOW())') or die(print_r($bdd->errorInfo()));
$resultat_req = $req->execute(array(
'pseudo' => $pseudo,
'comment' => $comment,
'id_chapter' => $id_chapter));
return $resultat_req;
}
public function getCommentaires($id_chapter)
{
$bdd = $this->dbConnect();
$req = $bdd->prepare('SELECT id, pseudo, comment, report, id_chapter, DATE_FORMAT(date_comment, "%d/%m/%Y à %Hh%imin") AS date_comment FROM comments WHERE id_chapter = ? ORDER BY date_comment DESC LIMIT 0, 10');
$req->execute(array($id_chapter));
return $req;
}
public function reportComment($id_comment)
{
$bdd = $this->dbConnect();
$req = $bdd->prepare('UPDATE comments SET report = "signaler" WHERE id = ?');
$resultReport = $req->execute(array($id_comment));
return $resultReport;
}
public function getTotalComment()
{
$bdd = $this->dbConnect();
$reponse = $bdd->query('SELECT COUNT(id) AS total_comment FROM comments');
$req = $reponse->fetch();
return $req;
}
public function getTotalReportComment()
{
$bdd = $this->dbConnect();
$reponse = $bdd->query('SELECT COUNT(id) AS total_comment_report FROM comments WHERE report = "signaler"');
$req = $reponse->fetch();
return $req;
}
public function getComments()
{
$bdd = $this->dbConnect();
$req = $bdd->query('SELECT c.id id, c.pseudo pseudo, c.comment comment, c.report report, c.id_chapter id_chapter, DATE_FORMAT(c.date_comment, "%d/%m/%Y à %Hh%imin")AS date_comment, p.title title FROM comments c LEFT JOIN chapters p ON c.id_chapter = p.id ORDER BY date_comment DESC');
return $req;
}
public function validationComment($id_comment, $report)
{
$bdd = $this->dbConnect();
$req = $bdd->prepare('UPDATE comments SET report = :signaler WHERE id = :id');
$req->execute(array(
'report' => $report,
'id' => $id_comment));
return $req;
}
public function suppressionComment($id_comment)
{
$bdd = $this->dbConnect();
$req = $bdd->prepare('DELETE FROM comments WHERE id = ?');
$req->execute(array($id_comment));
return $req;
}
}<file_sep><?php $content = ob_start(); ?>
<main>
<section id="nouveau_chapitre">
<form action="index.php?action=changeChapter" method="post">
<div id="nouveau_chapitre_partie_titre" class="nouveau_chapitre_partie">
<label for="nouveau_titre">Titre du chapitre</label>
<textarea id="nouveau_titre" name="nouveau_titre">
<?php
if(isset($chapter))
{
echo $chapter->title();
}
?>
</textarea>
</div>
<div id="nouveau_chapitre_partie_texte" class="nouveau_chapitre_partie">
<label for="nouveau_texte">Texte du chapitre</label>
<textarea id="nouveau_texte" name="nouveau_texte">
<?php
if(isset($chapter))
{
echo $chapter->chapter();
}?>
</textarea>
</div>
<div id="nouveau_chapitre_partie_resume" class="nouveau_chapitre_partie">
<label for="nouveau_resume">Résumé du chapitre</label>
<textarea id="nouveau_resume" name="nouveau_resume">
<?php
if(isset($chapter))
{
echo $chapter->resumer();
}?>
</textarea>
</div>
<div id="bouton_nouveau_chapitre">
<?php
if(isset($chapter))
{?>
<input type="hidden" name="chapterID" value="<?= $chapter->id();?>">
<?php
}?>
<input type="submit" name="enregistrer" value="enregistrer">
<input type="submit" name="publier" value="publier">
</div>
</form>
</section>
</main>
<?php $content = ob_get_clean(); ?>
<?php require('template.php');?><file_sep><?php
namespace christophe\blog\model;
class Chapter
{
private $_id;
private $_autor;
private $_title;
private $_chapter;
private $_resumer;
private $_publish;
private $_date_creation;
public function __construct($donnees)
{
$this->hydrate($donnees);
}
public function hydrate(array $donnees)
{
foreach($donnees as $key => $value)
{
$method = 'set'.ucfirst($key);
if(method_exists($this, $method))
{
$this->$method($value);
}
}
}
// DECLARATION DES GETTERS
public function id(){return $this->_id;}
public function autor(){return $this->_autor;}
public function title(){return $this->_title;}
public function chapter(){return $this->_chapter;}
public function resumer(){return $this->_resumer;}
public function publish(){return $this->_publish;}
public function date_creation(){return $this->_date_creation;}
// DECLARATION DES GETTERS
public function setId($id){
$id = (int)$id;
if($id >0)
{
$this->_id = $id;
}
}
public function setAutor($autor){
if(is_string($autor))
{
$this->_autor = $autor;
}
}
public function setTitle($title){
if(is_string($title))
{
$this->_title = $title;
}
}
public function setChapter($chapter){
if(is_string($chapter))
{
$this->_chapter = $chapter;
}
}
public function setResumer($resumer){
if(is_string($resumer))
{
$this->_resumer = $resumer;
}
}
public function setPublish($publish){
if(is_string($publish))
{
$this->_publish = $publish;
}
}
public function setDate_creation($date_creation){
$this->_date_creation = $date_creation;
}
} | f524a1c65ec8ca5a46b6409b0542262bdf455e97 | [
"JavaScript",
"PHP"
] | 24 | PHP | chris91300/projet-4 | c70ba9fa3b02035ef80cf5f36cc7d4d3aad1f116 | 88c4c2fad8d0ff40de1d4e8d0cdf189e5d58ffb1 |
refs/heads/main | <repo_name>Paleruudaykiran/Python-projects<file_sep>/calculator/calculator.py
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 7 16:05:59 2021
@author: <NAME>
"""
from tkinter import *
root = Tk()
root.title("Calculator")
first_operand = 0.0
second_operand = 0.0
symbol = str()
def evaluate() :
global first_operand
global second_operand
global symbol
if symbol == '+' :
return first_operand + second_operand
elif symbol == '-' :
return first_operand - second_operand
elif symbol == '/' :
return first_operand / second_operand
elif symbol == '*' :
return first_operand * second_operand
elif symbol == '%':
return first_operand % second_operand
def Done() :
global second_operand
second_operand = float(e.get())
clear_event()
res = evaluate()
e.insert(0,str(res))
def op_click(op) :
global symbol
global first_operand
symbol = op
first_operand = float(e.get())
clear_event()
def my_click(n) :
current = e.get()
e.delete(0,END)
e.insert(0,current+str(n))
def clear_event() :
e.delete(0,END)
e = Entry(root,width=40,borderwidth = 5,font = 15)
button_1 = Button(root,text = "1",padx = 40,pady = 20,command = lambda : my_click(1))
button_2 = Button(root,text = "2",padx = 40,pady = 20,command = lambda : my_click(2))
button_3 = Button(root,text = "3",padx = 40,pady = 20,command = lambda : my_click(3))
button_4 = Button(root,text = "4",padx = 40,pady = 20,command = lambda : my_click(4))
button_5 = Button(root,text = "5",padx = 40,pady = 20,command = lambda : my_click(5))
button_6 = Button(root,text = "6",padx = 40,pady = 20,command = lambda : my_click(6))
button_7 = Button(root,text = "7",padx = 40,pady = 20,command = lambda : my_click(7))
button_8 = Button(root,text = "8",padx = 40,pady = 20,command = lambda : my_click(8))
button_9 = Button(root,text = "9",padx = 40,pady = 20,command = lambda : my_click(9))
button_clear = Button(root,text = "clr",padx = 40,pady = 20,command = clear_event)
button_0 = Button(root,text = "0",padx = 40,pady = 20,command = lambda : my_click(0))
button_dot = Button(root,text = ".",padx = 40,pady = 20,command = lambda : my_click('.'))
button_add = Button(root,text = "+",padx = 40,pady = 20,command = lambda : op_click('+'))
button_sub = Button(root,text = "-",padx = 40,pady = 20,command = lambda : op_click('-'))
button_mul = Button(root,text = "*",padx = 40,pady = 20,command = lambda : op_click('*'))
button_div = Button(root,text = "/",padx = 40,pady = 20,command = lambda : op_click('/'))
button_done = Button(root,text = "Dn",padx = 40,pady = 20,command = Done)
button_mod = Button(root,text = "%",padx = 40,pady = 20,command = lambda : op_click('%'))
e.grid(row = 0,column = 0,columnspan = 30)
button_1.grid(row = 3 ,column =0)
button_2.grid(row = 3,column = 1)
button_3.grid(row = 3,column = 2)
button_4.grid(row = 2,column = 0)
button_5.grid(row = 2,column = 1)
button_6.grid(row = 2,column = 2)
button_7.grid(row = 1,column =0)
button_8.grid(row = 1,column = 1)
button_9.grid(row = 1,column = 2)
button_mod.grid(row = 4,column = 0)
button_0.grid(row = 4,column = 1)
button_dot.grid(row =4 ,column =2 )
button_add.grid(row = 4,column = 4)
button_sub.grid(row = 3,column = 4)
button_mul.grid(row = 2,column = 4)
button_div.grid(row = 1,column =4 )
button_done.grid(row = 5,column = 0)
button_clear.grid(row = 5,column = 1 )
root.mainloop() | c65b5c6103c0fa854f2d99b351c99e238da03768 | [
"Python"
] | 1 | Python | Paleruudaykiran/Python-projects | 88645538da39ff2ac0be30f5fb703911bff2c454 | 586dd26249c9556c38ece3d67d1a628cf0e19469 |
refs/heads/master | <file_sep>#include "./dataType.h"
#include <locale.h>
int procurar(int partyId)
{
for (int i = 0; i < 30; i++)
{
if (partyVet[i].partyId == partyId)
{
return i;
}
}
printf("ID não encontrado!\n");
return -1;
}
int getLastId()
{
int last;
for (int i = 0; i < 30; i++)
{
if (i == 0 || last < partyVet[i].partyId)
{
last = partyVet[i].partyId;
}
}
return last;
}
void calcValor(int partyId)
{
int i = procurar(partyId);
float total1 = 0;
float total2 = 0;
float total3 = 0;
float soma = 0;
float totalDevassa = 0;
float totalSkol = 0;
float totalBrahma = 0;
float totalSubzero = 0;
if (partyVet[i].skol == 1)
{
totalSkol = partyVet[i].uSkol * 3.0;
}
else
{
totalSkol = 0;
}
if (partyVet[i].devassa == 1)
{
totalDevassa = partyVet[i].uDevassa * 3.5;
}
else
{
totalDevassa = 0;
}
if (partyVet[i].subzero == 1)
{
totalSubzero = partyVet[i].uSubzero * 2.5;
}
else
{
totalSubzero = 0;
}
if (partyVet[i].brahma == 1)
{
totalBrahma = partyVet[i].uBrahma * 3.5;
}
else
{
totalDevassa = 0;
}
soma = totalSkol + totalDevassa + totalSubzero + totalBrahma;
if (partyVet[i].barType == 2)
{
total1 = ((soma * 0.5) + 60);
partyVet[i].costIng1 = total1;
total2 = total1 + (total1 * 0.1);
partyVet[i].costIng2 = total2;
total3 = total1 + (total1 * 0.15);
partyVet[i].costIng3 = total3;
}
else
{
total1 = partyVet[i].costOrg / partyVet[i].quantIng;
partyVet[i].costIng1 = total1;
total2 = total1 + (total1 * 0.1);
partyVet[i].costIng2 = total2;
total3 = total1 + (total1 * 0.15);
partyVet[i].costIng3 = total3;
}
menu();
}
void lucroEvento(parties party)
{
int i;
float total;
int partyId;
system("cls");
printf("------------------Resultado do Evento-----------------\n\n");
printf("Digite o número da festa que deseja pesquisar\n");
scanf("%d", &partyId);
i = procurar(partyId);
if (i != -1)
{
total = partyVet[i].money - partyVet[i].costOrg; //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@consertar isso
if (total < 0.0)
{
printf("Prejuizo de %.2f\n\n", total);
}
else
{
printf("Nao teve prejuízo\n");
printf("Lucro de R$:%.2f\n", total);
}
}
printf("\n");
system("pause");
printf("\n");
menu();
}
// fazer função para subtrair o "quantIng" pelo número que for inserido (OP-03)
void vendaIngresso(parties party)
{
system("cls");
int partyId = 0;
float add = 0;
printf("------------------Resultado do Evento-----------------\n\n");
printf("Digite o número da festa que deseja pesquisar\n");
scanf("%d", &partyId);
int i = procurar(partyId);
if (partyId != partyVet[i].partyId)
{
printf("\n");
system("pause");
menu();
}
else
{
int ingVendidos = 0;
back6:
printf("Qual o tipo de ingresso?\n\n");
printf("Popular (1) \n");
printf("R$:%.2f\n\n", partyVet[i].costIng1);
printf("Normal (2) \n");
printf("R$:%.2f\n\n", partyVet[i].costIng2);
printf("Especial (3) \n");
printf("R$:%.2f\n\n", partyVet[i].costIng3);
scanf("%d%*c", &partyVet[i].partyType);
if (partyVet[i].partyType < 1 || partyVet[i].partyType > 3)
{
printf("\n");
printf("Error!\n");
printf("Nonexistent option\n\n");
goto back6;
}
else
{
printf("\n");
printf("Quantos ingressos vendidos?\n");
scanf("%d", &ingVendidos);
if (partyVet[i].quantIng >= ingVendidos)
{
partyVet[i].quantIng = partyVet[i].quantIng - ingVendidos;
printf("\n");
printf("Foram vendidos %d\n", ingVendidos);
printf("Sobraram %d ingressos\n\n", partyVet[i].quantIng);
if (partyVet[i].partyType == 1)
{
partyVet[i].money = partyVet[i].money + partyVet[i].costIng1 * ingVendidos;
}
if (partyVet[i].partyType == 2)
{
partyVet[i].money = partyVet[i].money + partyVet[i].costIng2 * ingVendidos;
}
if (partyVet[i].partyType == 3)
{
partyVet[i].money = partyVet[i].money + partyVet[i].costIng3 * ingVendidos;
}
printf("Há agora R$:%.2f na carteira da sua festa\n\n", partyVet[i].money);
system("pause");
menu();
}
else
{
printf("\n");
printf("Ingressos insuficientes!\n\n");
system("pause");
menu();
}
}
}
}
void resulGeral(parties party)
{
system("cls");
printf("-------------------Exibir Resultado Geral-------------------\n\n");
int i;
float total = 0;
for (i = 0; i <= 30; i++)
{
total = total + partyVet[i].money;
}
printf("Foi conseguido até agora com as festas R$:%.2f\n\n", total);
system("pause");
menu();
}
// fazer função para somar todos os "Lucros" e "prejuízos" do promoter para definir seu saldo (OP-05)
<file_sep>
#include "./dataType.h"
#ifndef MENU_H
#define MENU_H
extern parties party;
void cadastrar(parties party);
void menu();
int procurar();
void pesquisarEvento();
int getLastId();
void calcValor();
void lucroEvento();
void vendaIngresso();
void resulGeral();
#endif
<file_sep>#include "./dataType.h"
#include "./menu.h"
#include <ctype.h>
#include "./funcs.c"
#include <locale.h>
void cadastrar(parties party)
{
int i;
system("cls");
// getLastId();// Não vou usar mais
printf("-------------------Cadastro de Evento-------------------\n");
i = vetorCont;
printf("Nome do evento\n");
scanf("%s%*c", &partyVet[i].partyName);
printf("Local do evento\n");
scanf("%s%*c", &partyVet[i].local);
printf("Data\n");
scanf("%s%*c", &partyVet[i].data);
printf("ID da festa\n");
scanf("%d%*c", &partyVet[i].partyId);
printf("Custo da organização\n");
scanf("%f%*c", &partyVet[i].costOrg);
printf("Quantos ingressos serão colocados à venda?\n");
scanf("%d%*c", &partyVet[i].quantIng);
// Escolhendo as bebidas
printf("Quais bebidas terão na festa? \n");
printf("Entre com (1) para sim e (2) para não \n\n");
back1: //BACKSSSS
printf("Skol\n");
printf("R$ 03,00\n");
printf("Graduação alcoólica 4,7%vol\n");
scanf("%d%*c", &partyVet[i].skol);
if (partyVet[i].skol < 1 || partyVet[i].skol > 2)
{
printf("Error!\n");
printf("Nonexistent option\n\n");
goto back1;
}
else if (partyVet[i].skol == 1)
{
printf("Quantas unidades?\n");
scanf("%d%*c", &partyVet[i].uSkol);
printf("\n");
}
back2: //BACKKKK
printf("Devassa\n");
printf("R$ 03,50\n");
printf("Graduação alcoólica 4,8%vol\n");
scanf("%d%*c", &partyVet[i].devassa);
if (partyVet[i].devassa < 1 || partyVet[i].devassa > 2)
{
printf("Error!\n");
printf("Nonexistent option\n\n");
goto back2;
}
else if (partyVet[i].devassa == 1)
{
printf("Quantas unidades?\n");
scanf("%d%*c", &partyVet[i].uDevassa);
printf("\n");
}
back3: //BACCK3
printf("Subzero\n");
printf("R$ 02,50\n");
printf("Graduação alcoólica 4,6%vol\n");
scanf("%d%*c", &partyVet[i].subzero);
if (partyVet[i].subzero < 1 || partyVet[i].subzero > 2)
{
printf("Error!\n");
printf("Nonexistent option\n\n");
goto back3;
}
else if (partyVet[i].subzero == 1)
{
printf("Quantas unidades?\n");
scanf("%d%*c", &partyVet[i].uSubzero);
printf("\n");
}
back4: //BACK4
printf("Brahma\n");
printf("R$ 03,50\n");
printf("Graduação alcoólica 5,0%vol\n");
scanf("%d%*c", &partyVet[i].brahma);
if (partyVet[i].brahma < 1 || partyVet[i].brahma > 2)
{
printf("Error!\n");
printf("Nonexistent option\n\n");
goto back4;
}
else if (partyVet[i].brahma == 1)
{
printf("Quantas unidades?\n");
scanf("%d%*c", &partyVet[i].uBrahma);
printf("\n");
}
// Finalização, escolhendo se a festa é open bar e o tipo dela
back5:
printf("A festa será normal ou open bar\n");
printf("Normal (1)\n");
printf("Open Bar (2)\n");
scanf("%d%*c", &partyVet[i].barType);
if (partyVet[i].barType < 1 || partyVet[i].barType > 2)
{
printf("Error!\n");
printf("Nonexistent option\n\n");
goto back5;
}
else
{
printf("\n");
}
printf("-------------------Festa cadastrada!-------------------\n");
vetorCont += 1;
printf("\n");
system("pause");
calcValor(partyVet[i].partyId);
}<file_sep>#include "./dataType.h"
#include "./menu.h"
#include <ctype.h>
#include <locale.h>
void pesquisarEvento(parties party)
{
int i;
int partyId;
system("cls");
printf("-------------------Pesquisar Evento-------------------\n\n");
printf("Digite o número da festa que deseja pesquisar\n");
scanf("%d", &partyId);
i = procurar(partyId);
if (i != -1)
{
printf("Nome da festa: ");
printf("%s", partyVet[i].partyName);
printf("\n");
printf("Local da festa: ");
printf("%s", partyVet[i].local);
printf("\n");
printf("Data da festa: ");
printf("%s", partyVet[i].data);
printf("\n");
printf("ID da festa: ");
printf("%d", partyVet[i].partyId);
printf("\n");
printf("Custo da festa: ");
printf("%.2f", partyVet[i].costOrg);
printf("\n");
printf("Quantidade de ingressos: ");
printf("%d", partyVet[i].quantIng);
printf("\n");
printf("Preço do ingresso normal: ");
printf("%.2f", partyVet[i].costIng1);
printf("\n");
printf("Preço do ingresso popular: ");
printf("%.2f", partyVet[i].costIng2);
printf("\n");
printf("Preço do ingresso especial: ");
printf("%.2f", partyVet[i].costIng3);
printf("\n");
printf("\n");
printf("\n");
}
system("pause");
printf("\n");
menu();
}<file_sep>#ifndef DATATYPE_H
#define DATATYPE_H
typedef struct
{
char partyName[50];
char local[50];
char data[50];
int quantIng;
float costOrg;
float costIng;
float costIng1;
float costIng2;
float costIng3;
int partyId;
float money;
int drinks;
int barType; // Normal ou open bar
int partyType; // Normal; especial; popular
int skol;
int brahma;
int subzero;
int devassa;
int uSkol;
int uBrahma;
int uSubzero;
int uDevassa;
} parties;
parties partyVet[30];
int vetorCont;
#endif<file_sep>#include "./dataType.h"
#include "./menu.h"
#include <ctype.h>
#include <locale.h>
parties party;
void menu()
{
setlocale(LC_ALL, "");
back :
system("cls");
int menuSelect = 0;
system("cls");
printf("Bem vindo!\n\n");
printf("1 - Cadastrar evento\n");
printf("2 - Pesquisar evento\n");
printf("3 - Ingressos Vendidos\n");
printf("4 - Resultado por Evento\n");
printf("5 - Exibir Resultado Geral\n");
printf("6 - Sair\n\n");
scanf("%d", &menuSelect);
switch (menuSelect)
{
case 1:
cadastrar(party);
break;
case 2:
pesquisarEvento(party);
break;
case 3:
vendaIngresso(party);
break;
case 4:
lucroEvento(party);
break;
case 5:
resulGeral();
break;
case 6:
system("exit");
break;
default:
goto back;
}
// ...
}
<file_sep>#include "./dataType.h"
#ifndef CADASTRO_H
#define CADASTRO_H
extern parties party;
void cadastrar(parties party);
void menu();
void calcValor();
#endif<file_sep>#include <stdio.h>
#include <stdlib.h>
#include "./dataType.h"
#include "./menu.c"
#include "./cadastro.c"
#include <ctype.h>
#include "./pesquisarEvento.c"
int main()
{
parties party;
menu();
return 0;
}
| 500d8ce096979100590851b13318147986f23241 | [
"C"
] | 8 | C | Drayerr/TCD | 4c68e0c5466cb3f6a819a43c9cb144813e4a1624 | 95c62780b48b84c44c3a4fabf894ec328f3d4710 |
refs/heads/master | <repo_name>LYLeon/eNose<file_sep>/src/es/pymasde/blueterm/DataHandler.java
package es.pymasde.blueterm;
// Here are totally 3 classes in this .java file
// 1. DataHandler
// 2. DrawingThread extends Thread
// 3. DataPipe
// Purposes for each class is stated right above the class.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.lang.reflect.Array;
import java.util.Arrays;
import android.R.integer;
import android.annotation.TargetApi;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;
@TargetApi(8)
public class DataHandler {
//DataHandler should be a singleton.
private static DataHandler mDataHandler ;
//we need a pipe for data from BluetoothSerialService thread to flow into our drawing thread
PipedInputStream pistream;
// where we manipulate buffer computation,
//we may need an allocator to decide which buffer should receive data from grabDataBuffer.
//private byte[] buffer1= new byte[4096];
private byte[] tmpbuffer = new byte[1024];
private int tmpbuffercount = 0;
private int [] intbuffer = new int[1024]; //this is where we actually store our integers to draw
private int intbuffercount=0;
private static byte [] grabDataBuffer = new byte[1024];
private int tail=-1;// tail points to the latest unprocessed byte.
public static dataSet[] mDataSet=new dataSet[8];
private boolean collectNewData=true;
//graphviews
public GraphView graphview1;
public GlobalView globalview1;
public radarChart radar1;
public histChart hist1;
public static TextView textview1;
public TextView textview2;
public GlobalViewInPercentage globalViewInPercentage1;
public radarChartInPercentage radarChartInPercentage1;
public HisChartInPercentage hisChartInPercentage1;
public static GasType[] gasArray;
//threads
private DrawingThread mDrawingThread;
//miscellaneous
private final String TAG = "DataHander";
public static boolean receivedData1=false;
private int sensorcount = 1;
private static boolean Thread_State=false;
private boolean IsTheFirstTime = true;
public static boolean showWords=false;
long startTime;
long currentTime;
long afterHowLong=90000;
private long delayTime=10000;//milisec
private boolean newTime=true;
public static boolean finalReady=false;
public static int FinalResult=-1;
public static String outPutFile ="sdcard/gas/gasData";
public static String predictFile ="sdcard/gas/predictData";
public static String modelFile ="sdcard/gas/gasData.model";
public static String predictOutFile="sdcard/gas/predictData.out";
public static String logFile="sdcard/gas/logFile";
public static String categoryFile="sdcard/gas/categoryFile";
public static int typeNum=0;
public static boolean typeLock=true;
//+++++++Constructor++++++++++++
private DataHandler(){
//initialize dataSet
for(int i=0;i<8;i++){
mDataSet[i]=new dataSet();
}
typeNum=countClassNum();
gasArray=GraphPage.getGasTypes();
}
//++++++++++++
public static DataHandler getInstance(){
if(mDataHandler == null)
mDataHandler = new DataHandler();
return mDataHandler;
}
//+++
//load views & stuffs from GraphPage
public void loadViews(GraphView graphview1,GlobalView globalview1,GlobalViewInPercentage globalViewInPercentage1, radarChart radar1,radarChartInPercentage radarChartInPercentage1, histChart hist1,HisChartInPercentage hisChartInPercentage1, TextView textview1,TextView textview2){
this.graphview1=graphview1;
this.radar1=radar1;
this.hist1=hist1;
this.textview1=textview1;
this.textview2=textview2;
this.globalview1=globalview1;
this.globalViewInPercentage1=globalViewInPercentage1;
this.radarChartInPercentage1=radarChartInPercentage1;
this.hisChartInPercentage1=hisChartInPercentage1;
IsTheFirstTime = false;
}
//++++
//Knn predict
public static void knnPredict(){
int knn=5;
float [][]knnDisAndCat=new float[knn][2];
// initialize knnDisAndCat
for (int i = 0; i < knn; i++) {
knnDisAndCat[i][0]=1000;
knnDisAndCat[i][1]=-1;
}
File file = new File(outPutFile);
InputStream ft;
try {
ft = new FileInputStream(file);
InputStreamReader inReader= new InputStreamReader(ft);
BufferedReader bReader=new BufferedReader(inReader);
String tmp;
int c=1;
int []sensorData=new int[8];
double dis=0;
try {
while((tmp=bReader.readLine())!=null){
//calculate the dis of current gas data and the data set
int cat=Integer.parseInt(tmp.substring(0,tmp.indexOf(" ")));
for(int i =0;i<8;i++){
sensorData[i]=Integer.parseInt((String) tmp.subSequence(tmp.indexOf((i+1)+":"), tmp.indexOf((i+1)+":")+1));
Log.d("DataHandler-KNN","senorData of KNN is "+(i+1)+": "+sensorData[i]);
dis+=Math.pow((mDataSet[0].variationInPercentage()-sensorData[0]), 2);
}
dis=Math.sqrt(dis);
Log.d("DataHandler-KNN","dis to point "+c+"is "+dis);
boolean knnFull=false;
int knnFullCount=0;
for (int i = 0; i < knn; i++) {
if(knnDisAndCat[i][0]==1000)
{
knnFullCount++;
}
}
if(knnFullCount==0)
{
knnFull=true;
}
for(int i =0;i<knn;i++){
if (knnFull==true) {
if (dis<knnDisAndCat[i][0]) {
knnDisAndCat[i][0]=(float) dis;
knnDisAndCat[i][1]=cat;
break;
}
}else {
if (dis<knnDisAndCat[i][0]&&knnDisAndCat[i][0]!=1000) {
knnDisAndCat[i][0]=(float) dis;
knnDisAndCat[i][1]=cat;
break;
}
}
}
}
ft.close();
//count how many times that each gas has occurred
int[] knnCount=new int [typeNum];
for (int i = 0; i < knn; i++) {
if(knnDisAndCat[i][1]!=-1){
knnCount[(int)knnDisAndCat[i][1]-1]++;}
}
//choose the most possible gas
int tmpFinalAnswer=1;
float tmpFinalAnswerNum=knnCount[0];
for (int i = 0; i < typeNum; i++) {
if (tmpFinalAnswerNum<knnCount[i]) {
tmpFinalAnswer=i+1;
tmpFinalAnswerNum=knnCount[i];
}
Log.d("DataHandler_Knn", "knnCount"+i+" is "+knnCount[i]);
}
Log.d("DataHandler_Knn","tmpFinalAnswer is "+tmpFinalAnswer);
if(gasArray[tmpFinalAnswer-1]==null){
appendTextToTV1("Unidentified.\n");
Log.i("RESULT","Unidentified.\n");
}else{
appendTextToTV1("KNN prediction result: "+(int)(tmpFinalAnswerNum/knn*100)+"% to be "+gasArray[tmpFinalAnswer-1].getName()+".\n");
appendTextToTV1("Other possible choice: ");
for (int i = 0; i < typeNum; i++) {
if (knnCount[i]!=0) {
appendTextToTV1("| "+" "+gasArray[i].getName()+" "+(int)((knnCount[i]*100)/knn)+" % "+" | ");
}
}
appendTextToTV1("\n");
}
Log.d("DataHandler_KNN","the finalResault= "+FinalResult);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//++++
//set type num
public static void setTypeNum(int s){
if (typeLock==false) {
typeNum=s;
Log.i("DataHandler", "TypeNum is "+typeNum);
}else Log.i("DataHandler", "type is locked");
typeLock = true;
}
//+++
//unlock type lock
public static void unLockType(){
typeLock=false;
}
//++++
//count class number
public int countClassNum(){
int count=0;
File currentFile=new File(categoryFile);
if (currentFile.exists()==false) {
try {
currentFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//count the # of different classes first
InputStream ft;
try {
ft = new FileInputStream(currentFile);
InputStreamReader inReader= new InputStreamReader(ft);
BufferedReader bReader=new BufferedReader(inReader);
String tmp;
try {
while((tmp=bReader.readLine())!=null){
count++;
}
Log.d("DataStorage","there are "+count+" type of gases recorded.");
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return count;
}
//++++
//check if the incoming data is a new one
public void checkIsNew(int num,String name){
int count=0;
File currentFile=new File(categoryFile);
count=countClassNum();
//if num>count it means that a new class is added
if(num>count){
try {
FileOutputStream ff= new FileOutputStream(currentFile,true);
String ttString;
ttString=""+num+" "+name+"\n";
ff.write(ttString.getBytes());
ff.close();
/*
String tmpString;
tmpString="1 Ethanol\n";
ff.write(tmpString.getBytes());
tmpString="2 Methanol\n";
ff.write(tmpString.getBytes());
tmpString="3 Water\n";
ff.write(tmpString.getBytes());
tmpString="4 Isopropanol\n";
ff.write(tmpString.getBytes());
tmpString="5 Oil";
ff.close();*/
// TODO Auto-generated catch block
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if (num<count) {
//if num<=count it means we want to override old class
File tmpFile=new File(categoryFile+"tmp");
int count1 =1;
try {
InputStream ft2=new FileInputStream(currentFile);
InputStreamReader inReader2= new InputStreamReader(ft2);
BufferedReader bReader2=new BufferedReader(inReader2);
String tmp;
FileOutputStream ff= new FileOutputStream(tmpFile, true);
while((tmp=bReader2.readLine())!=null){
if(count1==num){count1++;
String ttString=""+num+" "+name+"\n";
ff.write(ttString.getBytes());
continue;}
else{
ff.write((tmp+"\n").getBytes());
count1++;}
}
currentFile.delete();
currentFile.createNewFile();
tmpFile.renameTo(currentFile);
ff.close();
ft2.close();
} catch (Exception e) {
// TODO: handle exception
}
}else{
}
}
//++++
//predict target gas
public static void predict(){
File preF = new File(predictFile);
if(preF.exists()==false){
try {
preF.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
FileOutputStream ff= new FileOutputStream(preF);
String tmpString="1 "+"1:"+mDataSet[0].variationInPercentage()+" 2:"+mDataSet[1].variationInPercentage()
+" 3:"+mDataSet[2].variationInPercentage()+" 4:"+mDataSet[3].variationInPercentage()+" 5:"+mDataSet[4].variationInPercentage()
+" 6:"+mDataSet[5].variationInPercentage()+" 7:"+mDataSet[6].variationInPercentage()+" 8:"+mDataSet[7].variationInPercentage()+"\n";
Log.i("DataStorage","what i wrote is "+tmpString);
Log.i("HDataStorage","where i stored it"+preF.getPath());
try {
ff.write(tmpString.getBytes());
ff.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}//append to file
String [] argPredict=new String[3];
argPredict[0]=predictFile;
argPredict[1]=modelFile;
argPredict[2]=predictOutFile;
File tmpPre=new File(predictOutFile);
if(tmpPre.exists())
tmpPre.delete();
try {
svm_predict.main(argPredict);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File result = new File(predictOutFile);
int count =1;
try{
InputStream ft=new FileInputStream(result);
InputStreamReader inReader= new InputStreamReader(ft);
BufferedReader bReader=new BufferedReader(inReader);
String tmp;
float r=-1;
while((tmp=bReader.readLine())!=null){
Log.i("DataStorage",count+" : "+tmp);
r= Float.parseFloat(tmp);
count++;
}
int j =(int)r;
//int r =Integer.getInteger(tmp);
Log.i("RESULT","answer is "+j);
FinalResult=j;
ft.close();
}catch(Exception e){}
}
//++++
//train model
public static void trainModel(){
String [] argTrain=new String[1];
argTrain[0]=outPutFile;
try {
svm_train.main(argTrain);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//+++++
//delete certain line of data
public static void deleteLine(int l){
Log.i("DataStorage","Line to delete = "+l);
File oldFile=new File(outPutFile);
File tmpFile=new File(outPutFile+"tmp");
int count =1;
try {
InputStream ft=new FileInputStream(oldFile);
InputStreamReader inReader= new InputStreamReader(ft);
BufferedReader bReader=new BufferedReader(inReader);
String tmp;
FileOutputStream ff= new FileOutputStream(tmpFile, true);
while((tmp=bReader.readLine())!=null){
if(count==l){count++;continue;}
else{
ff.write((tmp+"\n").getBytes());
count++;}
}
oldFile.delete();
oldFile.createNewFile();
tmpFile.renameTo(oldFile);
ff.close();
ft.close();
} catch (Exception e) {
// TODO: handle exception
}
}
//+++++
//post text to textview1
public static void appendTextToTV1(String s){
GraphPage.view1Count++;
textview1.append(s);
if(GraphPage.view1Count>=13){
textview1.scrollBy(0,4);
}
}
//+++++++
//check file
public void checkFile(){
int count=1;
File file =new File(outPutFile);
File logfile=new File(logFile);
File currentFile=new File(categoryFile);
if(file.exists()==false){
Log.i("DataStorage","No such File.");
}else{
try{
//print the log file first
InputStream ft1=new FileInputStream(logfile);
InputStreamReader inReader1= new InputStreamReader(ft1);
BufferedReader bReader1=new BufferedReader(inReader1);
String tmp;
while((tmp=bReader1.readLine())!=null){
appendTextToTV1(tmp+"\n");
}
//print the category file
InputStream ft2=new FileInputStream(currentFile);
InputStreamReader inReader2= new InputStreamReader(ft2);
BufferedReader bReader2=new BufferedReader(inReader2);
String tm2;
while((tm2=bReader2.readLine())!=null){
appendTextToTV1(tm2+"\n");
}
// print the data set
InputStream ft=new FileInputStream(file);
InputStreamReader inReader= new InputStreamReader(ft);
BufferedReader bReader=new BufferedReader(inReader);
while((tmp=bReader.readLine())!=null){
appendTextToTV1(count+" : "+tmp+"\n");
Log.i("DataStorage",count+" : "+tmp);
count++;
}
ft.close();}catch (Exception e) {
// TODO: handle exception
}
}
}
//+++++
//reset all data and start over
public void resetAll(){
}
//+++++++++
//if finalReady == true, then save the collected data
public static void saveData(){
File file=new File(outPutFile);
if(file.exists()==false){
try {
file.createNewFile();
Log.i("DataStorage","New file created.");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
FileOutputStream ff= new FileOutputStream(file, true);//append to file
try {
//write file!!
//typenum represents different target gas
// 1: Ethanol
// 2: Methanol
// 3: Water
String tmpString=typeNum+" "+"1:"+mDataSet[0].variationInPercentage()+" 2:"+mDataSet[1].variationInPercentage()
+" 3:"+mDataSet[2].variationInPercentage()+" 4:"+mDataSet[3].variationInPercentage()+" 5:"+mDataSet[4].variationInPercentage()
+" 6:"+mDataSet[5].variationInPercentage()+" 7:"+mDataSet[6].variationInPercentage()+" 8:"+mDataSet[7].variationInPercentage()+"\n";
Log.i("DataStorage","what i wrote is "+tmpString);
Log.i("HDataStorage","where i stored it"+file.getPath());
ff.write(tmpString.getBytes());
//check the # of data set used
InputStream ft=new FileInputStream(file);
InputStreamReader inReader= new InputStreamReader(ft);
BufferedReader bReader=new BufferedReader(inReader);
String tmp;
int cc=0;
while((tmp=bReader.readLine())!=null){
cc++;
}
ff.close();
//update the logFile
//if the logFile doesn't exist, create one
File llFile = new File(logFile);
if(llFile.exists()==false){
try {
llFile.createNewFile();
Log.i("DataStorage","New LogFile created.");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
llFile.delete();
llFile.createNewFile();
}
/*
* Log file should show the user the following information
*
* 1. Number of data set used in the training model
* 2. Information of different gases
*/
FileOutputStream fflog= new FileOutputStream(llFile, true);//append to file
tmp="# of data set used: "+(cc)+"\n";
fflog.write(tmp.getBytes());
tmp="Category of gases:\n";
fflog.write(tmp.getBytes());
/*
for(int i=0;i<GraphPage.currentMaxTypeNum;i++){
if(gasArray[i]!=null){
tmp=gasArray[i].getNumber()+" : "+gasArray[i].getName()+"\n";
fflog.write(tmp.getBytes());
}else break;
}*/
fflog.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//++++++++++++
//++++++++
public boolean checkIsTheFirstTime(){
return IsTheFirstTime;
}
//++++++++
public static void resetByteBuffer(byte[] buffer){
for(int i = buffer.length; i>0;i--)
buffer[i-1]=0;
}
private void resetIntBuffer(int[] buffer){
for(int i = buffer.length; i>0;i--)
buffer[i-1]=0;
}
//++++++
public synchronized void startDrawingThread (){
try{
if(mDrawingThread!=null){
Thread_State=false;
mDrawingThread=null;
}
mDrawingThread = new DrawingThread();
Thread_State=true;
mDrawingThread.start();
Log.i(TAG,"A drawingthread has been created.");
}
catch(Exception e){
Log.e(TAG,"at startDrawingThread=>"+e);
}
}
//++++++
public void killHandler(){
try{
Thread_State=false;
mDataHandler = null;
DataPipe.DrawingThread=false;
Log.i(TAG,"Handler killed.");
}catch (Exception e){Log.e(TAG,"at stopDrawingThread=>"+e);}
}
public static void onDestory(){
}
//++++++++++
public static boolean getThreadState(){
return Thread_State;
}
//$$$$$$
private class dataSet{
// this class records the starting and final value of a particular sensor
int start=0;
int finals=0;
boolean isSteady=false;
int[] tmpbuffer=new int[10];
int tmpcount=0;
public dataSet() {
// TODO Auto-generated constructor stub
}
public void setStart(int s){
if(tmpcount!=-1){
if(tmpcount<=2){
tmpbuffer[tmpcount++]+=s;
}
else{
int avg=(int)(tmpbuffer[0]+tmpbuffer[1]+tmpbuffer[2])/3;
start=avg;
resetIntBuffer(tmpbuffer);
tmpcount=-1;}}
}
public void setSteadyBuffer(int v){
if(tmpcount==-1)tmpcount=0;
tmpbuffer[tmpcount]=v;
tmpcount=(++tmpcount)%10;
}
public int[] getSteadyBuffer(){
return tmpbuffer;
}
public void setFinals(int f){
finals=f;
}
public int getStart(){
return start;
}
public int getFinals(){
return finals;
}
public void isSteady(){
isSteady=true;
}
public boolean checkSteady(){
return isSteady;
}
public float variationInPercentage(){
Log.i("DataStorage","start="+start);
Log.i("DataStorage","Final="+finals);
Log.i("DataStorage","return="+(((finals-start)*100/start)));
return (((finals-start)*100/start));
}
}
//$$$$$$$
private class DrawingThread extends Thread{
//when the integer buffer is full, write it into a file (design)
private DrawingThread (){
pistream = DataPipe.getPipe().getPistream();
}
//+++++++++++++++
//this method handle the ACII to Integer conversion
private void dataHandling(byte [] databuffer){
Log.i(TAG,"Start handling.");
int count = 0;
int empty =0;
//only the numbers and chars part are considered
while(count<databuffer.length){
//Log.i(TAG,"count: "+count+" databuffer[count]: "+databuffer[count]+" databuffer.length :"+databuffer.length);
if(databuffer[count]>32&&databuffer[count]<126||databuffer[count]==13){
if(databuffer[count]==13&&tmpbuffercount>0&&tmpbuffercount!=tail){
startConversion();
//Log.i(TAG,"break.");
// Log.i(TAG,"sensor at datahandling: "+sensorcount);
// this depends on the number of the sensor
}//after conversion we should remember to clean tmpbuffer
else {
if(databuffer[count]!=13)
saveIntoTmpBuffer(databuffer[count]);
// Log.i(TAG,"here");
}
}else{//Log.i(TAG,"databuffer: "+databuffer[count]+" count: "+count);
//break;
}
if(databuffer[count]==0){
empty++;
//Log.i(TAG,"empty =: "+empty);
if(empty>20)
break;
}
else
empty=0;
count++;}
resetByteBuffer(grabDataBuffer);
//resetByteBuffer(tmpbuffer);
//tmpbuffercount = 0;
//tail=-1;
}
//+++++++++++
private void saveIntoTmpBuffer(byte tmpByte){
//Log.i(TAG,"Save tmpByte into tmpBuffer: "+tmpByte);
// To ensure no data loss, we need a tmptmpbuffer for incoming data when
// tmpbuffer is full and under resetting.
if(tmpbuffer.length-tmpbuffercount < 2){
byte[] tmptmpbuffer = new byte[128];
System.arraycopy(tmpbuffer, tail, tmptmpbuffer, 0, tmpbuffercount-tail+1);
resetByteBuffer(tmpbuffer);
System.arraycopy(tmptmpbuffer, 0, tmpbuffer, 0, tmpbuffercount-tail+1);
tmpbuffercount = tmpbuffercount - tail;
tail = 0 ;
}
// tmp byte waits here for the complete set of bytes for converting into integer
if(tmpbuffer[tmpbuffercount]==0){
tmpbuffer[tmpbuffercount] = tmpByte;
tmpbuffercount++;}
else {
Log.e(TAG,"something goes wrong in tmpbuffer.");
}
}
//+++++++++++
private void startConversion(){
Log.i(TAG,"StartConversion.");
//(design) if char is involved later, we need to distinguish them
// digits of the number are needed to make a correct conversion
int base =1;
int tmpint =0;
try{
for(int j=tmpbuffercount-1; j>=tail;j--){
if(j>tail){
tmpint+=Character.getNumericValue((char)tmpbuffer[j])*base;
//Log.i(TAG,"tmpbuffer value in char: "+(char)tmpbuffer[j]+" j: "+j);
base*=10;}
else{
sensorcount = Character.getNumericValue((char)tmpbuffer[j]);
Log.i(TAG,"sensorcount: "+sensorcount);
}
}}catch (Exception e){Log.e(TAG,"error here: "+e+" tmpbuffercount: "+tmpbuffercount);}
if(intbuffercount<intbuffer.length){
intbuffer[intbuffercount]=tmpint;
//Log.i(TAG,"Incoming int is:"+" "+tmpint);
sendPointToCanvas(tmpint,sensorcount);//this method actually start the drawing
// when collecting gas data, we should take the avg. value of three continuous values
// in order to diminish the noise.
if(GraphPage.checkCollect()==true&&mDataSet[sensorcount-1].checkSteady()==false){
int state=0;
float result;
result=recordData(tmpint,sensorcount);
mDataSet[sensorcount-1].setFinals((int)result);
//TODO
if(result==0||result==-1){
state=(int)result;
//Log.i(TAG,"state="+state);
}
else {
state=1;
// Log.i(TAG,"state="+state);
}
switch(state){
case 0:// 0 indicates nothing has changed, continue
break;
case -1:// 1 indicates starting point is decided, draw the view
markStartingPoint();
break;
case 1:// sensor s has recorded the final value
markFinalPoint(sensorcount);
}
//if all final values have been collected, write the data to a tmpbuffer
//is the save button is clicked, then save the tmpbuffer into train modle file
if(mDataSet[0].checkSteady()==true&&mDataSet[1].checkSteady()==true&&mDataSet[2].checkSteady()==true&&
mDataSet[3].checkSteady()==true&&mDataSet[4].checkSteady()==true&&
mDataSet[5].checkSteady()==true&&mDataSet[6].checkSteady()==true&&
mDataSet[7].checkSteady()==true){
finalReady=true;
currentTime=System.currentTimeMillis();
new postTextToView1().execute("Data is steady:\nTime Spent: "+((int)(currentTime-startTime)/1000)+"secs\n");
new postTextToView1().execute("Finals:\nSN1: "+mDataSet[0].variationInPercentage()+"% SN2: "+mDataSet[1].variationInPercentage()
+"% SN3: "+mDataSet[2].variationInPercentage()+"% SN4: "+mDataSet[3].variationInPercentage()+"%\n");
new postTextToView1().execute("SN5: "+mDataSet[4].variationInPercentage()+"% SN6: "+mDataSet[5].variationInPercentage()+"% SN7: "
+mDataSet[6].variationInPercentage()+"% SN8: "+mDataSet[7].variationInPercentage()+"%\n");
}
}
intbuffercount++; }
else{
// (design) start writing intbuffer into file here
Log.e(TAG,"intbuffer is full.");
// (tmp) should be modified later. write into a file
intbuffercount=0;
resetIntBuffer(intbuffer);
}
tail = tmpbuffercount;
}
public void markFinalPoint(int s){
graphview1.markFinalPoint(s);
}
private float recordData(int v,int s){
if(collectNewData==true){
//collect starting data
// delay a proper time and record the starting value
if(newTime==true){
startTime=System.currentTimeMillis();
newTime=false;
}
currentTime=System.currentTimeMillis();
if(currentTime-startTime>=delayTime){
if(mDataSet[0].getStart()!=0&&mDataSet[1].getStart()!=0&&mDataSet[2].getStart()!=0
&&mDataSet[3].getStart()!=0&&mDataSet[4].getStart()!=0&&mDataSet[5].getStart()!=0
&&mDataSet[6].getStart()!=0&&mDataSet[7].getStart()!=0){
collectNewData=false;
//Log.e(TAG,"markStartingPoint.");
return -1;}
else {
/*Log.i(TAG,"mDataSet= "+mDataSet[0].getStart()+" "+mDataSet[1].getStart()+" "+mDataSet[2].getStart()+" "+mDataSet[3].getStart()+" "
+mDataSet[4].getStart()+" "+mDataSet[5].getStart()+" "+mDataSet[6].getStart()+" "+mDataSet[7].getStart()+" ");
*/mDataSet[s-1].setStart(v);
return 0;
}
}
else return 0;
}
else{
//collect final data
float t;
t=isSteady(v,s-1);
if(t!=-100){
return t;
}else return 0;
}
}
public float isSteady(int v,int s){
/*
*
*/
int [] steadyBuffer;
mDataSet[s].setSteadyBuffer(v);
steadyBuffer=mDataSet[s].getSteadyBuffer();
//check if mDataset[s] is steady
float diff=(float) 1;
float avg1=(steadyBuffer[0]+steadyBuffer[1]+steadyBuffer[2]+steadyBuffer[3]+steadyBuffer[4])/5;
float avg2=(steadyBuffer[5]+steadyBuffer[6]+steadyBuffer[7]+steadyBuffer[8]+steadyBuffer[9])/5;
Log.i("DataStorage","avg1="+avg1);
Log.i("DataStorage","avg2="+avg2);
currentTime=System.currentTimeMillis();
//
if((((avg1-avg2<=diff)&&(avg1>=avg2))||((avg2-avg1<=diff)&&(avg2>=avg1)))&¤tTime-startTime>=afterHowLong){
mDataSet[s].isSteady();
return (avg1+avg2)/2;
}else
return -100;
}
public void markStartingPoint(){
graphview1.markStartingPoint();
globalViewInPercentage1.setIsSteady();
radarChartInPercentage1.setSteady();
hisChartInPercentage1.setSteady();
}
private void updateText(int point, int sensor){
String string="s "+sensor+" : "+point+" ";
if(sensor==8){
string=string+"\n";
GraphPage.view2Count++;
}
new postTextToView2().execute(string);
}
//++++++++++++++
//this method actually start the drawing
private void sendPointToCanvas(int point, int sensor){
//Log.i(TAG,"sensor: "+sensor);
graphview1.getWhichsensor(sensor);
graphview1.setData(point);
globalview1.getWhichsensor(sensor);
globalview1.setData(point);
radar1.getWhichsensor(sensor);
radar1.setData(point);
hist1.getWhichsensor(sensor);
hist1.setData(point);
globalViewInPercentage1.getWhichsensor(sensor);
globalViewInPercentage1.setData(point);
radarChartInPercentage1.getWhichsensor(sensor);
radarChartInPercentage1.setData(point);
hisChartInPercentage1.getWhichsensor(sensor);
hisChartInPercentage1.setData(point);
updateText(point, sensor);
}
//+++++++++++++++
@Override
public void run(){
Log.i(TAG,"Thread's running.");
try{
DataPipe.DrawingThread = true;
Log.i(TAG,"Thread_State=> "+Thread_State);
while(Thread_State){
if(DataPipe.posready){
pistream.read(grabDataBuffer, 0, 1024);
/*Log.i("DataHandler","Data received. The first six bytes are: "
+" "+(char)DataHandler.grabDataBuffer[0]+" "+DataHandler.grabDataBuffer[1]+" "+DataHandler.grabDataBuffer[2]
+" "+DataHandler.grabDataBuffer[3]+" "+DataHandler.grabDataBuffer[4]+" "+DataHandler.grabDataBuffer[5]);*/
dataHandling(grabDataBuffer);
}
//clean the buffer to reuse.
}
}catch(Exception e ){Log.e(TAG,"Something worng when running drawing thread:"+e);}
DataPipe.DrawingThread = false;
Log.i(TAG,"Thread's terminated.");
}
//++++++++++
//the asynctask to update textview1
protected class postTextToView1 extends AsyncTask<String,Void,String> {
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return params[0];
}
protected void onPostExecute(String result) {
textview1.append(result);
if(GraphPage.view1Count>=13){
textview1.scrollBy(0,2);
}
}
}
//the asynctask to update textview2
protected class postTextToView2 extends AsyncTask<String,Void,String> {
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return params[0];
}
protected void onPostExecute(String result) {
textview2.append(result);
if(GraphPage.view2Count>=13){
textview2.scrollBy(0,2);
}
}
}
}//end of DrawingThread
}//end of DataHandler
//$$$$$$$$$$$$$$$$$$
class DataPipe{
public static boolean DrawingThread = false;
public static boolean posready =false;
private static DataPipe datapipe = new DataPipe();
private static PipedInputStream pistream ;
private static PipedOutputStream postream ;
private DataPipe(){
try{
if(pistream!=null){
pistream.close();}
pistream = new PipedInputStream();
if(postream!=null)
postream.close();
postream = new PipedOutputStream(pistream);}catch (Exception e){Log.e("DataPipe","error in datapipe: "+e); }
}
public static DataPipe getPipe(){return datapipe;}
public PipedInputStream getPistream(){return pistream;}
public PipedOutputStream getPostream(){return postream;}
}
<file_sep>/src/es/pymasde/blueterm/GraphView.java
package es.pymasde.blueterm;
/*
Amarino - A prototyping software toolkit for Android and Arduino
Copyright (c) 2010 <NAME>. All right reserved.
This application and its 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 3 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.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.Toast;
public class GraphView extends Visualizer {
private boolean lockbitmap = false;
private static final String TAG = "GraphView";
private static boolean DEBUG = true;
private boolean RedrawBaseLine = false;
public boolean drawn = false;
private Bitmap mBitmap;
private Canvas mCanvas = new Canvas();
private int positioncount = 0;
private int whichsensor=-1;
private Paint paint = new Paint();
private float mSpeed = 10f;
private float[] mLastX = new float[8];
private float[] mLastValue = new float[8]; // 10 should be more than enough
private int[] mColor = new int[10];
public GraphView(Context context) {
super(context);
init();
}
public GraphView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public void markStartingPoint(){
paint.setStyle(Paint.Style.FILL);
for(int i=0;i<8;i++){
paint.setColor(mColor[i]);
mCanvas.drawCircle(mLastX[i], mLastValue[i]-20, 10, paint);
mCanvas.drawText("Start", mLastX[i], mLastValue[i]-5,paint);
}
postInvalidate();
}
public void markFinalPoint(int s){
paint.setColor(mColor[s-1]);
paint.setStyle(Paint.Style.FILL);
mCanvas.drawCircle(mLastX[s-1], mLastValue[s-1]-20, 10, paint);
mCanvas.drawText("Final", mLastX[s-1], mLastValue[s-1]-5,paint);
postInvalidate();
}
private void init(){
mColor[0] = Color.argb(255, 0, 255, 0); // g
mColor[1] = Color.argb(255, 50, 50, 255); // y
mColor[2] = Color.argb(255, 255, 0, 0); // r
mColor[3] = Color.argb(255, 100, 50, 150); // c
mColor[4] = Color.argb(255, 255, 255, 255); //
mColor[5] = Color.argb(255, 50, 150, 50); //
mColor[6] = Color.argb(255, 255, 150, 200); //
mColor[7] = Color.argb(255, 255, 0, 200); //
paint.setFlags(paint.ANTI_ALIAS_FLAG);
//mLastX = 0;
}
//this function is used to determined which sensor is the incoming data belong to
public void getWhichsensor(int s){
whichsensor=s;
}
// reset the view
public void resetAll(){
}
public void setData(float value){
if(whichsensor ==-1)
Log.e(TAG,"Something's wrong about whichsensor");
else{
addDataPoint(value, mColor[whichsensor-1], mLastValue[whichsensor-1], whichsensor-1);
postInvalidate();
}
}
public void setData(float[] values){
final int length = values.length;
try {
boolean tail = false;
for (int i=0;i<length;i++){
if(!tail){
if (values[i]==0)tail=true;
else{
addDataPoint(values[i], mColor[i%4], mLastValue[i], i);
//Log.i(TAG,"values[i] :"+values[i]);
}
}
else break;
}
} catch (ArrayIndexOutOfBoundsException e){
/* mLastValue might run into this in extreme situations */
// but then we just do not want to support more than 10 values in our little graph
Log.e(TAG, "Too many data points for our little graph"+length);
}
postInvalidate();
}
private void addDataPoint(float value, final int color, final float lastValue, final int pos){
value += minValue;
// if(DEBUG)
//Log.i(TAG,"value is :"+value);
float newX = mLastX[pos] + mSpeed;
final float v =mYOffset+ value * mScaleY;// origin :mYOffset + value * mScaleY;
//if(DEBUG)
//Log.i(TAG,"v is :"+v);
paint.setColor(color);
mCanvas.drawLine(mLastX[pos], lastValue, newX, v, paint);
if(positioncount%10==0)
mCanvas.drawText(Float.toString(value), newX, v-1, paint);
if(positioncount>=77&&pos==0){
scrollBy(10,0);
}
//if(DEBUG)
//Log.i(TAG,"Line should be drawn:"+" mLastX: "+mLastX+" LastValue: "+lastValue+" newX: "+newX+" v: "+v);
mLastValue[pos] = v;
// if (pos == 0)
mLastX[pos] += mSpeed;
if (pos == 0){
positioncount ++;
Log.i(TAG, "positioncount"+positioncount);}
}
public void setSpeed(float speed){
mSpeed = speed;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// TODO when screen size changes sometimes w or h == 0 -> Exception
//Log.e(TAG, "w: " + w + " h: " + h+"oldw: "+oldw+"oldh: "+oldh);
if(!lockbitmap){
mBitmap = Bitmap.createBitmap(4*4096, h, Bitmap.Config.RGB_565);
mCanvas.setBitmap(mBitmap);
mCanvas.drawColor(0xFF111111);
//mLastX = mWidth;
// set origin to zero
for (int i=0;i<mLastValue.length;i++)
mLastValue[i] = minValue;
//Log.i(TAG,"BitmapCreated");
int x = 60;
paint.setColor(0xaa996666);
while (x < 4960){
mCanvas.drawLine(x, mYOffset, x, 0, paint);
x+=60;
}
final float v = mYOffset + minValue * mScaleY;
// draw the zero line
mCanvas.drawLine(0, v, 4*4096, v, paint);
//mCanvas.drawLine(0, , stopX, stopY, paint)
lockbitmap=true;
//Log.i(TAG,"bitmap locked");
}
}
public void redrawBaseLine(){
RedrawBaseLine = true;
}
@Override
protected void onDraw(Canvas canvas) {
synchronized (this) {
if (mBitmap != null) {
paint.setColor(0xaa996666);
mCanvas.drawText(min, 1, mYOffset-1, paint);
mCanvas.drawText(max, 1, textHeight-1, paint);
//this line actually do the drawing
canvas.drawBitmap(mBitmap, 0, 0, null);
drawn=true;
}
}
}
}
<file_sep>/src/es/pymasde/blueterm/HisChartInPercentage.java
package es.pymasde.blueterm;
//this chart display the sensor data in histogram
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
public class HisChartInPercentage extends Visualizer {
private boolean lockbitmap = false;
private static final String TAG = "histChart";
private Bitmap mBitmap;
private Canvas mCanvas = new Canvas();
private int whichsensor=-1;
public Paint paint = new Paint();
//define max value of our data
//TODO
private float[] mSensorValue = new float[8]; // sensor value
private int[] mColor = new int[8];
int background=0xFF111111;
int line =0x33DDFFDD;
private boolean isSteady=false;
private float[] initialValue=new float[8];
//rectangles for radarchart
//Rect(int left, int top, int right, int bottom)
Rect r1,r2,r3,r4,r5,r6,r7,r8;
int reW;
float maxL;
float maxW;
float x;
float p;
public HisChartInPercentage(Context context) {
super(context);
init();
}
public HisChartInPercentage(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public void setSteady(){isSteady=true;}
private void init(){
mColor[0] = Color.argb(255, 0, 255, 0); // g
mColor[1] = Color.argb(255, 50, 50, 255); // y
mColor[2] = Color.argb(255, 255, 0, 0); // r
mColor[3] = Color.argb(255, 100, 50, 150); // c
mColor[4] = Color.argb(255, 255, 255, 255); //
mColor[5] = Color.argb(255, 50, 150, 50); //
mColor[6] = Color.argb(255, 255, 150, 200); //
mColor[7] = Color.argb(255, 255, 0, 200); //
}
//this function is used to determined which sensor is the incoming data belong to
public void getWhichsensor(int s){
whichsensor=s;
}
public void setData(float value){
if(whichsensor ==-1)
Log.e(TAG,"Something's wrong about whichsensor");
else{
addDataPoint(value,whichsensor-1);
postInvalidate();
}
}
private void addDataPoint(float value,int pos){
//synchronized (this) {
value += minValue;
if(isSteady==false)
value=0;
if(initialValue[pos]==0&&isSteady==true)
initialValue[pos]=value;
//, mColor[whichsensor-1], mSensorValue[whichsensor-1], whichsensor-1
float v =((value-initialValue[pos])/initialValue[pos])*5;//reminder I multiply an additional "5" here in order to amplify the result.
//if(DEBUG)
Log.i(TAG,"v is :"+v);
paint.setColor(background);//line gray
mCanvas.drawRect(40+pos*reW, 0, 40+pos*reW+reW-3, maxL,paint);
paint.setColor(mColor[pos]);
mSensorValue[pos]=v;
mCanvas.drawRect(40+pos*reW, (maxL-maxL*mSensorValue[pos]), 40+pos*reW+reW-3, maxL,paint);
mCanvas.drawText(""+(int)(v*20)+" %", 55+pos*reW, (maxL-maxL*mSensorValue[pos])-20, paint);
paint.setTextSize(20);
mCanvas.drawText("SN"+(pos+1), 63+pos*reW, 30, paint);
float tp=p;
float tx=x;
paint.setColor(0xaa996666);
while(tp>0){
mCanvas.drawLine(20, tp, maxW-20, tp, paint);
tp-=tx;
}
}
// }
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// TODO when screen size changes sometimes w or h == 0 -> Exception
if(!lockbitmap){
mBitmap = Bitmap.createBitmap(2048, h, Bitmap.Config.RGB_565);
mCanvas.setBitmap(mBitmap);
mCanvas.drawColor(background);
for (int i=0;i<mSensorValue.length;i++)
mSensorValue[i] = minValue;
//draw the coordinate
paint.setColor(line);
mCanvas.drawLine(20, 0, 20, h-15, paint);
mCanvas.drawLine(20, h-15, w-20, h-15, paint);
mCanvas.drawLine(w-20, 0, w-20, h-15, paint);
x=(h-15)/5;
p=(h-15);
float tx=x;
float tp=p;
reW=(w-80)/8;
maxL=h-15;
maxW=w;
while(tp>0){
mCanvas.drawLine(20, tp, w-20, tp, paint);
tp-=tx;
}
/*
p=(w-80);
x=p/8;
while(p>=0){
mCanvas.drawLine(p+40, h-15, p+40, 0, paint);
p-=x;
}*/
lockbitmap=true;
}
}
@Override
protected void onDraw(Canvas canvas) {
//this line actually do the drawing
canvas.drawBitmap(mBitmap, 0, 0, null);
}
@Override
public void setData(float[] values) {
// TODO Auto-generated method stub
}
}
<file_sep>/src/es/pymasde/blueterm/GraphPage.java
package es.pymasde.blueterm;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.os.Bundle;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class GraphPage extends Activity {
public static String TAG= "GraphPage";
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
public static boolean DEBUG = true;
public static boolean receivedData=false;//will become true when new data comes
public GraphView graphview1;
public GlobalView globalview1;
public GlobalViewInPercentage globalViewInPercentage1;
public radarChartInPercentage radarChartInPercentage1;
public radarChart radar1;
public histChart hist1;
public HisChartInPercentage hisChartInPercentage1;
public TextView textview1;
public TextView textView2;
public EditText editText1;
public EditText editText2;
public Legend legend1;
private BluetoothAdapter mBluetoothAdapter = null;
private static BluetoothService mSerialService = null;
private Button button1;
private Button button2;
private Button button3;
private Button button4;
private Button button5;
private Button button6;
private Button button7;
private Button button8;
private Button button9;
private Button button10;
private Button button11;
private Button button12;
private boolean mEnablingBT;
private boolean built=true;
private static boolean startCollect=false;
public static int view1Count=0;
public static int view2Count=0;
public String delLine;
//we pre-define the max. # of classes available
public static GasType[] gasArray=new GasType[20];
public static int currentMaxTypeNum=5;
public static int currentTypeNum;
public static String currentTypeName;
public boolean editLock=false;
/*public GraphView graphview2;
public GraphView graphview3;
public GraphView graphview4;
public GraphView graphview5;
public GraphView graphview6;
public GraphView graphview7;
public GraphView graphview8;*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_graph_page);
if(DataHandler.getInstance().checkIsTheFirstTime()){
}
for(int i =0;i<20;i++){
gasArray[i]=new GasType();
}
if(DEBUG)
Log.i(TAG,"setContentViewSucceeded");
graphview1 = (GraphView)findViewById(R.id.graphview1);
graphview1.setBoundaries(0f,1024f);
globalview1 = (GlobalView)findViewById(R.id.globalview1);
globalview1.setBoundaries(0f,1024f);
globalViewInPercentage1=(GlobalViewInPercentage)findViewById(R.id.globalviewInpercentage1);
globalViewInPercentage1.setBoundaries(0f,1024f);
radarChartInPercentage1=(radarChartInPercentage)findViewById(R.id.radarChartInPercentage1);
radarChartInPercentage1.setBoundaries(0f,1024f);
radar1 = (radarChart)findViewById(R.id.radarChart1);
radar1.setBoundaries(0f,1024f);
hist1 =(histChart)findViewById(R.id.histChart1);
hist1.setBoundaries(0f,1024f);
hisChartInPercentage1=(HisChartInPercentage)findViewById(R.id.histChartInPercentage1);
hisChartInPercentage1.setBoundaries(0f,1024f);
textview1=(TextView)findViewById(R.id.textfield1);
textView2=(TextView)findViewById(R.id.textfield2);
editText1=(EditText)findViewById(R.id.editText1);
editText2=(EditText)findViewById(R.id.editText2);
button1=(Button)findViewById(R.id.button1);
button2=(Button)findViewById(R.id.button2);
button3=(Button)findViewById(R.id.button3);
button4=(Button)findViewById(R.id.button4);
button5=(Button)findViewById(R.id.button5);
button6=(Button)findViewById(R.id.button6);
button7=(Button)findViewById(R.id.button7);
button8=(Button)findViewById(R.id.button8);
button9=(Button)findViewById(R.id.button9);
button10=(Button)findViewById(R.id.button10);
button11=(Button)findViewById(R.id.button11);
button12=(Button)findViewById(R.id.button12);
legend1=(Legend)findViewById(R.id.legend1);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
finishDialogNoBluetooth();
return;
}
mSerialService = new BluetoothService(textview1);
DataHandler.getInstance().loadViews(graphview1,globalview1,globalViewInPercentage1,radar1,radarChartInPercentage1,hist1,hisChartInPercentage1,textview1,textView2);
/*,graphview2,graphview3,graphview4,
graphview5,graphview6,graphview7,graphview8*/
}
public static GasType[] getGasTypes(){
return gasArray;
}
public void finishDialogNoBluetooth() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.alert_dialog_no_bt)
.setIcon(android.R.drawable.ic_dialog_info)
.setTitle(R.string.app_name)
.setCancelable( false )
.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(DEBUG) Log.d(TAG, "onActivityResult " + resultCode);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
// Get the device MAC address
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BLuetoothDevice object
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
mSerialService.connect(device);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
Log.d(TAG, "BT not enabled");
finishDialogNoBluetooth();
}
}
}
//+++++++++++
@Override
public void onResume(){
super.onResume();
setContentView(findViewById(R.id.graphpage));
//update the current gasArray first
File currentFile=new File(DataHandler.categoryFile);
InputStream ft;
try {
ft = new FileInputStream(currentFile);
InputStreamReader inReader= new InputStreamReader(ft);
BufferedReader bReader=new BufferedReader(inReader);
try {
String tmpString;
int i=0;
while((tmpString=bReader.readLine())!=null){
gasArray[i].setNumber(Integer.parseInt(tmpString.substring(0,tmpString.indexOf(' '))));
gasArray[i].setName(tmpString.substring(tmpString.indexOf(' ')+1, tmpString.length()));
i++;
}
} catch (NumberFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(DEBUG)
Log.i(TAG,"+++onResume+++");
if(built==true){
//set up BTconnect button
button1.setOnClickListener(new View.OnClickListener() {
//button1 is to connect blue tooth
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
appendTextToTV1("Try to establsih BT connection.....\n");
if(built==true){
if (getConnectionState() == BluetoothSerialService.STATE_NONE) {
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(getBaseContext(), DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
}
else
if (getConnectionState() == BluetoothSerialService.STATE_CONNECTED) {
mSerialService.stop();
mSerialService.start();
}
}
}
});
//send collection signal through BT
button2.setOnClickListener(new View.OnClickListener() {
//button1 is to connect blue tooth
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(startCollect==false){
appendTextToTV1("Try to start collecting data.....\n");
byte[] o=new byte[1];
o[0]=8;
mSerialService.write(o);
startCollect=true;
appendTextToTV1("Start collecting data.\n");
}
else{
appendTextToTV1("Collection is already started.\n");
}
}
});
//send forceStop signal through BT
button3.setOnClickListener(new View.OnClickListener() {
//button1 is to connect blue tooth
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
appendTextToTV1("Try to stop collection.....\n");
byte[] o=new byte[1];
o[0]=7;
mSerialService.write(o);
startCollect=false;
appendTextToTV1("Collection Stoped.\n");
}
});
//set button4 for training model
button4.setOnClickListener(new View.OnClickListener() {
//button1 is to connect blue tooth
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
appendTextToTV1("Start training...\n");
DataHandler.trainModel();
appendTextToTV1("Model created.\n");
}
});
//set button5 for target prediction
button5.setOnClickListener(new View.OnClickListener() {
//button1 is to connect blue tooth
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
appendTextToTV1("SVMPredicting...\n");
DataHandler.predict();
if(gasArray[DataHandler.FinalResult-1]==null){
appendTextToTV1("Unidentified.\n");
Log.i("RESULT","Unidentified.\n");
}else{
appendTextToTV1("This is "+gasArray[DataHandler.FinalResult-1].getName()+".\n");
Log.i("RESULT","This is"+gasArray[DataHandler.FinalResult-1].getName()+".\n");
}
}
});
//set button6 for saving data
button6.setOnClickListener(new View.OnClickListener() {
//button1 is to connect blue tooth
@Override
public void onClick(View v) {
if(built==true){
if(DataHandler.finalReady==true){
DataHandler.saveData();
appendTextToTV1("Data saved.\n");
}
}
}
});
//set button7 for checking data
button7.setOnClickListener(new View.OnClickListener() {
//button1 is to connect blue tooth
@Override
public void onClick(View v) {
if(built==true){
DataHandler.getInstance().checkFile();
}
}
});
// set button8 to delete certain line of data
button8.setOnClickListener(new View.OnClickListener() {
//button1 is to connect blue tooth
@Override
public void onClick(View v) {
if(built==true){
DataHandler.deleteLine(Integer.valueOf(delLine));
//Integer.valueOf(delLine)
}
}
});
// set button9 to reset and start over
button9.setOnClickListener(new View.OnClickListener() {
//button1 is to connect blue tooth
@Override
public void onClick(View v) {
if(built==true){
appendTextToTV1("Reseting...\n");
//Integer.valueOf(delLine)
resetAll();
}
}
});
// set button10 to scroll textview1 up
button10.setOnClickListener(new View.OnClickListener() {
//button1 is to connect blue tooth
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview1.scrollBy(0, -25);
}
});
// set button11 to scroll textview1 down
button11.setOnClickListener(new View.OnClickListener() {
//button1 is to connect blue tooth
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview1.scrollBy(0, 25);
}
});
//set button12 for KNN predict
button12.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
appendTextToTV1("KNNPredicting...\n");
DataHandler.knnPredict();
}
});
//This text editor takes care of the target line to delete.
editText1.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
delLine=s.toString();
}
});
//we can decide the sample type from here
//1=Ethanol
//2=Methanol
//3=Water
editText2.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
if(s.length()>0&&editLock==false){
Log.d(TAG,"gg"+editLock);
if(s.charAt(s.length()-1)=='\n'&&editLock==false){
editLock=true;
String tmpString=s.toString();
Log.d(TAG,"s="+s.toString());
if(tmpString.indexOf(' ')==-1){
currentTypeNum=Integer.parseInt(tmpString.substring(0,tmpString.indexOf('\n')));
DataHandler.getInstance().unLockType();
DataHandler.getInstance().setTypeNum(currentTypeNum);}
else{
currentTypeNum=Integer.parseInt(tmpString.substring(0,tmpString.indexOf(' ')));
currentTypeName=tmpString.substring(tmpString.indexOf(" "), tmpString.length()-1);
Log.d(TAG,"num="+currentTypeNum+" name="+currentTypeName);
DataHandler.getInstance().unLockType();
DataHandler.getInstance().setTypeNum(currentTypeNum);
//check if the incoming data is a new one or an old one
//HERE TODO
DataHandler.getInstance().checkIsNew(currentTypeNum, currentTypeName);
}
}
}
}
});
if (!mEnablingBT) { // If we are turning on the BT we cannot check if it's enabled
if ( (mBluetoothAdapter != null) && (!mBluetoothAdapter.isEnabled()) ) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.alert_dialog_turn_on_bt)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.alert_dialog_warning_title)
.setCancelable( false )
.setPositiveButton(R.string.alert_dialog_yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mEnablingBT = true;
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
})
.setNegativeButton(R.string.alert_dialog_no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finishDialogNoBluetooth();
}
});
AlertDialog alert = builder.create();
alert.show();
}
if (mSerialService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mSerialService.getState() == BluetoothSerialService.STATE_NONE) {
// Start the Bluetooth chat services
mSerialService.start();
}
}
}}
try{
// in case of muti-threads being started, we have to check state of thread
if(!DataHandler.getThreadState()){
DataHandler.getInstance().startDrawingThread();
}
else
Log.i(TAG,"Thread already exists.");
}catch(Exception e){if(DEBUG)Log.e(TAG,"Something went worng.=> "+e); }
}
public static boolean checkCollect(){
if(startCollect==true){return true;}
else return false;
}
public int getConnectionState() {
return mSerialService.getState();
}
//reset all data and start over
private void resetAll(){
DataHandler.getInstance().resetAll();
}
@Override
public void onStart() {
super.onStart();
if (DEBUG)
Log.e(TAG, "++ ON START ++");
mEnablingBT = false;
}
public void onDestory(){
Log.i(TAG,"+++GarphPage onDestroy+++++");
byte[] o=new byte[1];
o[0]=7;
mSerialService.write(o);
DataHandler.getInstance().killHandler();
super.onDestroy();
}
public void onPause(){
Log.i(TAG,"+++GarphPage onPause+++++");
super.onPause();
}
@Override
public void onStop(){
Log.i(TAG,"+++GarphPage onStop+++++");
super.onStop();
}
@Override
public void finish(){
Log.i(TAG,"+++GarphPage onFinish+++++");
byte[] o=new byte[1];
o[0]=7;
mSerialService.write(o);
DataHandler.getInstance().killHandler();
super.finish();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_graph_page, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
}
return false;
}
public void appendTextToTV1(String s){
view1Count++;
textview1.append(s);
if(view1Count>=13){
textview1.scrollBy(0,4);
}
}
}
| a77d077e9d7b810d9b3163d9ea67e888c2c83524 | [
"Java"
] | 4 | Java | LYLeon/eNose | c500bde6e4fa74e9b70691b1cc9c89b4ece49b2c | 92c6e71171659081b98cc841e06831d0d5007d0a |
refs/heads/master | <repo_name>kebele/react_anime_search<file_sep>/react_anime_search/src/components/Header.js
import React from 'react'
export default function Header() {
return (
<header>
<h1>the <strong>anime</strong> db</h1>
</header>
)
}
| d9dd8edacae5735d57eb2a4fac25882f656adb3f | [
"JavaScript"
] | 1 | JavaScript | kebele/react_anime_search | 79f4e0ece83fe228f6c0f1ee1ddb5a87669e81bd | d7c05d7095bdc1894d1d005ed1ffe4bb2156f24e |
refs/heads/master | <repo_name>drzackyll/js-donut-lab-web-0916<file_sep>/js/donut-counter.js
//JS Donut Counter Lab
//declare 2 variables one for guests and one for donuts
//use prompt method to bring up a dialog box in the browser for the user to insert the number of guests and donuts.
//use parseInt to convert the users answer from a string to an integer.
//write a conditional to check if there are enough donuts
//alert the user with a message telling them the numbers of donuts and guests, and if there are enough donuts for each guest.
var guests = prompt("Enter the number of guests")
var donuts = prompt("Enter the number of donuts")
function enough(guests, donuts) {
if (parseInt(guests) <= parseInt(donuts)) {
alert("There are enough donuts for all!")
} else {
alert("There are not enough donuts :(")
}
}
enough(guests, donuts)
| d942ed6a225f3e00a5db6268882fee255b35a598 | [
"JavaScript"
] | 1 | JavaScript | drzackyll/js-donut-lab-web-0916 | 48d1b37fe4e48c89100fde02bf9b1d816b28f6fd | cdeff4ba20cb093f57e4f5f39e63e33bc60309c1 |
refs/heads/main | <repo_name>cameronthrntn/intellisense-technical-test<file_sep>/cypress/integration/graph.spec.js
describe("Table functionality", () => {
beforeEach(() => {
cy.visit("http://localhost:3000");
});
it("Initially shows that there is no data to graph", () => {
cy.get("[data-name=emptyGraph]").should("exist");
});
it("Clicking an item in the table adds it to the graph", () => {
cy.get("[data-name=sample-name]")
.first()
.click()
.get("[data-name=emptyGraph]")
.should("not.exist");
});
it("Clicking an item already added to the graph should remove it from the graph", () => {
cy.get("[data-name=sample-name]")
.first()
.click()
.click()
.get("[data-name=emptyGraph]")
.should("exist");
});
it("Clicking the clear graph button should clear the graph", () => {
cy.get("[data-name=sample-name]").each((sample) => {
sample.click();
});
cy.get("[data-name=clearGraph]")
.click()
.get("[data-name=emptyGraph]")
.should("exist");
});
});
<file_sep>/src/components/organisms/index.ts
export { default as GraphicContainer } from './GraphicContainer';<file_sep>/src/interfaces.ts
export interface DataSampleInterface {
name: string,
times: number[],
values: number[]
}
export interface DataState {
table: DataSampleInterface[];
graph: DataSampleInterface[];
}
export interface StatusState {
loading: boolean;
error: boolean;
sortBy: string;
}
export interface TopState {
data: DataState;
status: StatusState;
}<file_sep>/README.md
<h1 align="center" style="color: #824FDF">
Intellisense Technical Test ⛏️
</h1>
<p align="center" style="font-size: 1.2rem;">
Querying data from a provided API and displaying as both a table and graph.
</p>
<hr />
This application uses an [**API**][a] provided by [**Intellisense.io**][i]. The specification for this tech test outlined 3 key goals:
- Create a single page application with a table and line graph
- Access the data from the provided API
- Allow different columns in the dataset to be selected for graphing
The code provided attempts to fulfill all tasks as well as adding a few extra features in an effort to provide a better user experience. A collection of planned features that didn't make it into the current build can likely be found on the [**issues tab of the github repo**][is].
[a]: https://reference.intellisense.io/thickenernn/v1/referencia
[i]: https://www.intellisense.io/
[is]: https://github.com/Shubwub/intellisense-technical-test/issues
[at]: https://atomicdesign.bradfrost.com/chapter-2/
[r]: https://redux.js.org/
[c]: https://www.cypress.io/
[aa]: https://www.w3.org/WAI/WCAG2AAA-Conformance.html
- ## 📋 Requirements
The requirements for running this application locally are the same as any standard `create-react-app` react application, of course with additional dependancies provided by npm. The currently supported browsers are Firefox and Chrome.
- ## 🎉 Installation and setup
Once this repository is cloned, dependencies must be met through:
```bash
npm i
```
A local development server can then be spun up through
```bash
npm start
```
- ## 📖 Documentation
- ### 🚧 Structure
This project uses React hooks for state management such as **useState** and **useEffect**. Functional components should be used where possible due to their reduced compile size and the phasing out of class-components by the react development team.
The project also tries to follow an [**atomic**][at] component structure. The basic idea being to split components into organisms, molecules and atoms. organisms being made of many molecules, and molecules being made of many atoms.
- ### ⚙️ Redux
App-wide state management is done through [**Redux**][r]. The structure of which is as follows:
```JSON
"data": {
"table": [
{
"name": "string",
"times": "number",
"values": "number",
}
],
"graph": [
{
"name": "string",
"times": "number",
"values": "number",
},
]
},
"status": {
"loading": "boolean",
"error": "boolean",
"sortBy": "string"
}
```
Data stored under `table` is what is returned from the API and is rendered in the table. Graph data should be a subset of that stored under `data`. Items under `status` should ideally refer to the `state` of the app - as opposed to data being used and presented to users.
- ### 🏷️ TypeScript
This project uses TypeScript throughout. Variables, functions, and parameters should be typed where possible. There are a number of custom interfaces for describing data returned from the API as well as various levels of the redux state.
- ### ♿ Accessibility
Accessibility for this project should be kept to at least a [**AA standard**][aa] (In compliance with the W3C Web Content Accessibility Guidelines) as best as posssible. aXe-react has been installed as a means of complying with these standards. Current warning can be viewed from the console when the application is being ran in development mode.
- ### 🐶 Husky
Husky pre-commit hooks are used to ensure breaking or poor-quality code is not commited to the git repo. The pre-commit hook script can be found in `.husky/_/pre-commit`. This scrippt will run the cypress tests as well as linting all tsx files.
- ## 🧪 Testing
This project uses [**Cypress**][c] for it's testing. Cypress was chosen as it's what's most familiar and better reflects a user journey through an application.
Tests can be found in `/cypress/integration`. Elements should be selected using data-name attributes. This is the apporach recommended by Cypress as it's least intrusive to the DOM.
To run the test suite run
```bash
npm test
```
<file_sep>/src/redux/reducers/data.reducer.ts
import { SET_DATA, ADD_TO_GRAPH, SORT_DATA, EMPTY_GRAPH, REMOVE_FROM_GRAPH } from '../constants/actionTypes';
import { DataState, DataSampleInterface } from '../../interfaces'
const INITIAL_STATE: DataState = {
table: [],
graph: []
};
const reducer = (state = INITIAL_STATE, action: any): DataState => {
switch (action.type) {
/**
* Stores retrieved data from API to data array.
*/
case SET_DATA:
return {
...state, table: action.payload,
};
/**
* A switch for sorting the data in the redux store.
*/
case SORT_DATA:
switch (action.payload) {
/**
* Sorts the table alphabetically in descending order.
*/
case 'stringDESC':
return {
...state, table: [...state.table].sort((a: DataSampleInterface, b: DataSampleInterface): number => {
const aName = a.name.toUpperCase();
const bName = b.name.toUpperCase();
if (aName < bName) {
return -1;
}
return 1;
})
}
/**
* Sorts the table alphabetically in ascending order.
*/
case 'stringASC':
return {
...state, table: [...state.table].sort((a: DataSampleInterface, b: DataSampleInterface): number => {
const aName = a.name.toUpperCase();
const bName = b.name.toUpperCase();
if (aName > bName) {
return -1;
}
return 1;
})
}
/**
* Sorts the table numerically in descending order.
*/
case 'numberDESC':
return {
...state, table: [...state.table].sort(
(a: DataSampleInterface, b: DataSampleInterface): number =>
b.values[b.values.length - 1] -
a.values[a.values.length - 1]
)
}
/**
* Sorts the table numerically in ascending order.
*/
case 'numberASC':
return {
...state, table: [...state.table].sort(
(a: DataSampleInterface, b: DataSampleInterface): number =>
a.values[a.values.length - 1] -
b.values[b.values.length - 1]
)
}
/**
* If there is currently no sorting method it will return them
* in the order they are loaded from the API
*/
default: return state;
}
/**
* Adds a given sample to the graph.
*/
case ADD_TO_GRAPH:
return {
...state, graph: [...state.graph, action.payload]
}
/**
* Removes a sample from the graph by name.
*/
case REMOVE_FROM_GRAPH:
return {
...state, graph: state.graph.filter((data: DataSampleInterface) => data.name !== action.payload)
}
/**
* Sets the graph data to an empty array.
*/
case EMPTY_GRAPH:
return {
...state, graph: []
}
default: return state;
}
};
export default reducer;<file_sep>/src/redux/reducers/index.ts
import { combineReducers } from 'redux';
import dataReducer from './data.reducer';
import statusReducer from './status.reducer';
const rootReducer = combineReducers({
data: dataReducer,
status: statusReducer
})
export default rootReducer;<file_sep>/src/redux/actions/index.ts
import { SET_DATA, SET_ERROR, SET_LOADING, ADD_TO_GRAPH, SORT_DATA, SET_SORT, EMPTY_GRAPH, REMOVE_FROM_GRAPH } from '../constants/actionTypes'
import { DataSampleInterface } from '../../interfaces'
/**
* @param {DataSampleInterface[]} payload - The array of data samples retrieved from the API.
*/
export const setData = (payload: DataSampleInterface[]) => ({ type: SET_DATA, payload })
/**
* @param {DataSampleInterface} payload - A singular data entry, to be plotted to the graph.
*/
export const addData = (payload: DataSampleInterface) => ({ type: ADD_TO_GRAPH, payload })
/**
* @param {string} payload - The name of a data sample that is present on the graph and is to be removed.
*/
export const removeData = (payload: string) => ({ type: REMOVE_FROM_GRAPH, payload })
/**
* @param {string} payload - A string from the sortBy property to trigger the sorting of data.
*/
export const sortData = (payload: string) => ({ type: SORT_DATA, payload })
/**
* @param {null[]} payload - An empty array, to empty the data subset fo graph plotting.
*/
export const setGraph = (payload: null[]) => ({ type: EMPTY_GRAPH, payload })
/**
* @param {boolean} payload - If true, sets loads the spinner. Likely just for API calls.
*/
export const setLoading = (payload: boolean) => ({ type: SET_LOADING, payload })
/**
* @param {boolean} payload - If there was an error retrieving data from the API. Loads error component.
*/
export const setError = (payload: boolean) => ({ type: SET_ERROR, payload })
/**
* @param {string} payload - Used for setting "sortBy". Can be either: "stringASC", "stringDESC", "numberASC", or"numberDESC".
*/
export const setSort = (payload: string) => ({ type: SET_SORT, payload })
<file_sep>/src/redux/constants/actionTypes.ts
/**
* This file is to avoid discrepancies in strings as these constants
* are used in both the action and reducers files.
*/
export const SET_DATA: string = "SET_DATA";
export const SORT_DATA: string = "SORT_DATA";
export const SET_SORT: string = "SET_SORT";
export const ADD_TO_GRAPH: string = "ADD_TO_GRAPH";
export const REMOVE_FROM_GRAPH: string = "REMOVE_FROM_GRAPH";
export const EMPTY_GRAPH: string = "EMPTY_GRAPH";
export const SET_ERROR: string = "SET_ERROR";
export const SET_LOADING: string = "SET_LOADING";<file_sep>/src/components/molecules/index.ts
export { default as DataTable } from './DataTable';
export { default as DataGraph } from './DataGraph';<file_sep>/src/redux/reducers/status.reducer.ts
import { SET_LOADING, SET_ERROR, SET_SORT } from '../constants/actionTypes';
import { StatusState } from '../../interfaces'
const INITIAL_STATE: StatusState = {
loading: true,
error: false,
sortBy: ''
};
const reducer = (state = INITIAL_STATE, action: any): StatusState => {
switch (action.type) {
case SET_LOADING:
return {
...state, loading: action.payload,
};
case SET_ERROR:
return {
...state, error: action.payload,
};
/**
* Takes a string and sets the current sorting method.
*/
case SET_SORT:
return { ...state, sortBy: action.payload }
default: return state;
}
};
export default reducer;<file_sep>/src/services/api.ts
import axios from 'axios';
import { DataSampleInterface } from '../interfaces'
/**
* A custom axios instance, ideally would have extra options like a
* timeout and headers, however it was felt these would not be
* needed for such a simple request. a baseURL is provided so it can
* easily be swapped out and would not need to be referenced in every
* future axios call.
*/
const instance = axios.create({
baseURL: "https://reference.intellisense.io/thickenernn/v1/referencia"
});
/**
* @param {number} ms - The number of milliseconds to pause execution
*
* This function is just to add an artificial delay to retreiving API
* data. Would likely be removed in a production environment, but
* given the small payload, allows time to show the loading spinner.
*/
const delay = (ms: number) => new Promise(res => setTimeout(res, ms));
/**
* An API call to fetch the needed data. Once all records have been
* retrieved, filters out all those that aren't needed using a simple
* regex.
*
* Occasionally the API will return a 500 status and no data. Under
* this circumstance this function will throw an error, triggering the
* error state and component.
*/
export const getData = async () => {
try {
const { data: { current: { data } } } = await instance.get(`/`);
const pt2 = data["pt2-scaled"];
const samples: DataSampleInterface[] = []
for (let key in pt2) {
if (/^RD:647/.test(key)) samples.push({ name: key, times: pt2[key].times, values: pt2[key].values })
}
await delay(1000)
// eslint-disable-next-line no-throw-literal
if (pt2.status) throw 'API ERROR';
return samples;
} catch (e) {
throw e;
}
}<file_sep>/cypress/integration/table.spec.js
describe("Table functionality", () => {
beforeEach(() => {
cy.visit("http://localhost:3000");
});
it("Loads data from API and displays it in a table when no faults", () => {
cy.get("[data-name=error]").should("not.exist");
});
it("Table data can be sorted alphabetically by metric", () => {
const original = [];
let sorted = [];
cy.get("[data-name=sample-name]")
.each((sample) => {
original.push(sample.text());
})
.then(() => {
cy.get("[data-name=metric-sort]")
.click({ force: true })
.get("[data-name=sample-name]")
.each((sample) => {
sorted.push(sample.text());
})
.then(() => {
const sortedTest = original.sort((a, b) => {
if (a.toUpperCase() > b.toUpperCase()) {
return -1;
}
return 1;
});
expect(sorted).to.eql(sortedTest);
sorted = [];
});
cy.get("[data-name=metric-sort]")
.click({ force: true })
.get("[data-name=sample-name]")
.each((sample) => {
sorted.push(sample.text());
})
.then(() => {
const sortedTest = original.sort((a, b) => {
if (a.toUpperCase() < b.toUpperCase()) {
return -1;
}
return 1;
});
expect(sorted).to.eql(sortedTest);
});
});
});
it("Table data can be sorted numerically by value", () => {
const original = [];
let sorted = [];
cy.get("[data-name=sample-value]")
.each((sample) => {
original.push(parseFloat(sample.text()));
})
.then(() => {
cy.get("[data-name=value-sort]")
.click({ force: true })
.get("[data-name=sample-value]")
.each((sample) => {
sorted.push(parseFloat(sample.text()));
})
.then(() => {
const sortedTest = original.sort((a, b) => a - b);
expect(sorted).to.eql(sortedTest);
sorted = [];
});
cy.get("[data-name=value-sort]")
.click({ force: true })
.get("[data-name=sample-value]")
.each((sample) => {
sorted.push(parseFloat(sample.text()));
})
.then(() => {
const sortedTest = original.sort((a, b) => b - a);
expect(sorted).to.eql(sortedTest);
});
});
});
});
<file_sep>/.husky/pre-commit
#!/bin/sh
. "$(dirname $0)/_/husky.sh"
npm test && npx eslint "**/*.tsx" --fix --max-warnings=0 | 495d0926e834dc768f8942da425c68ada0fbc3bb | [
"JavaScript",
"TypeScript",
"Markdown",
"Shell"
] | 13 | JavaScript | cameronthrntn/intellisense-technical-test | e2bb12548c2906456e4f06168b99dc5a1d3ea316 | d03de9c8df040e064456bc8580c70f37cca00278 |
refs/heads/master | <repo_name>drsubs/ev3webapp.js<file_sep>/libws++/port-data.cpp
/*
*/
using namespace std;
//#include "server.h"
#include "ev3.h"
#include <string.h>
/* Port Data protocol */
/*
*
* Send port status polled from a tread timer loop.
*
*/
int port_data_handshake_info(struct lws *wsi) {
return 0;
}
int callback_port_data(struct lws *wsi, enum lws_callback_reasons reason,
void *user, void *in, size_t len)
{
size_t remaining;
unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 512 +
LWS_SEND_BUFFER_POST_PADDING];
struct per_session_data__port_data *psd =
(struct per_session_data__port_data *)user;
unsigned char *p = &buf[LWS_SEND_BUFFER_PRE_PADDING];
int m, l=0;
switch (reason) {
case LWS_CALLBACK_CLOSED:
ports->removePsd(psd);
break;
case LWS_CALLBACK_ESTABLISHED:
//findPorts();
psd->currPort=0;
psd->msgNum=0;
psd->pbuf=0;
psd->fragged=0;
psd->msgque = new msgQue();
ports->addPsd(psd);
break;
case LWS_CALLBACK_SERVER_WRITEABLE:
// puts("Call ports msg");
l = ports->msg((char*)p,psd);
// printf("After ports->msg : %s\n",p);
// lwsl_notice((char*)p);
if(l>0) {
m = lws_write(wsi, p, l, LWS_WRITE_TEXT);
if (m < l) {
lwsl_err("ERROR writing to di socket\n");
return -1;
}
}
break;
case LWS_CALLBACK_RECEIVE:
remaining = lws_remaining_packet_payload(wsi);
if((!remaining) && (!psd->fragged)) {
*((char*)in+len+1)=0;
ports->dispatch((char*) in);
}
if((remaining) && (psd->fragged)) {
psd->fragbuf=(char*)realloc((void*)psd->fragbuf,psd->pbuf+len);
memcpy((void*)(psd->fragbuf+psd->pbuf),in,len);
psd->pbuf+=len;
}
if((remaining) && (!psd->fragged)) {
psd->fragged=1;
psd->fragbuf=(char*)malloc(len);
memcpy((void*)psd->fragbuf,in,len);
psd->pbuf+=len;
}
if((!remaining) && (psd->fragged)) {
psd->fragbuf=(char*)realloc((void*)psd->fragbuf,psd->pbuf+len+1);
memcpy((void*)(psd->fragbuf+psd->pbuf),in,len);
psd->pbuf+=len;
psd->fragbuf[psd->pbuf]=0;
ports->dispatch((char*) psd->fragbuf);
free(psd->fragbuf);
psd->pbuf=0;
psd->fragged=0;
}
break;
/*
* this just demonstrates how to use the protocol filter. If you won't
* study and reject connections based on header content, you don't need
* to handle this callback
*/
case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
port_data_handshake_info(wsi);
/* you could return non-zero here and kill the connection */
break;
default:
break;
}
return 0;
}
<file_sep>/html/lib/touch.js
/*
*
* File touch.js
*
* Touch object.
*
* Eksample:
* var t=new Touch({sensor:Sensors.In1,down:function() { startstuf(); }});
* And then in loop:
* t.run();
*
*/
function Touch(o) {
for(opt in o) {
this[opt]=o[opt];
}
this._state=0;
if(this._create) this._create();
}
Touch.prototype.up=function() { Msg.log("Button Up"); }
Touch.prototype.down=function() { Msg.log("Button Down"); }
Touch.prototype.run = function() {
var n=this.sensor.read("value0");
if(n!=this._state) {
this._state=n;
if(n==1) this.down(); else this.up();
}
}
<file_sep>/html/dom.js
/*
* dom.js
* Dom constructor kit.
* All DCK element have a contructor function like Div here,
* and all setter return "this", that makes them cascadeable.
*
* var div=Div("Hej").id("someid").addClass("someclass").addStyle("color:red;");
*
* Then we render it into a elemnt on the page.
*
* div.render($("#sometarget"),true);
*
* All DCK elements have the following metodes:
* add(attribute,value)
* addClass(classes)
* addStyle(style)
* append(element)
* prepend(element)
* id(id)
* value([value])
* render([target][,purgeflag])
*
* Dom elements:
* Div
* Span
* Fieldset
* Legend
* Label
* Li
* Ul
* Button
* Select
* Option
*
* Svg elements:
* Svg
* G
* Rect
* Circle
* Line
* Path
*/
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
function Dom(c) {
this.cnt=[];
if(c) this.cnt.push(c);
this.attr={};
}
Dom.prototype.append = function(c) { this.cnt.push(c); return this; }
Dom.prototype.prepend = function(c) { this.cnt.shift(c); return this; }
Dom.prototype.render = function(elem,purge) {
var dom=this.build();
for(var i=0;i<this.cnt.length;i++) {
if(this.cnt[i] instanceof Dom) dom.append(this.cnt[i].render());
else dom.append(this.cnt[i])
}
if(elem instanceof jQuery) if(purge===true) elem.html(dom); else elem.append(dom);
return dom;
}
Dom.prototype.addStyle = function(s) {
if(!this.attr.style) this.attr.style="";
this.attr.style+=s;
return this;
}
Dom.prototype.addClass = function(s) {
if(!this.attr.class) this.attr.class="";
this.attr.class+=s;
return this;
}
Dom.prototype.tag = function() { return ""; };
Dom.prototype.build = function() {
var astr="";
for(var a in this.attr) astr+=" " + a + '="' + this.attr[a] +'"';
return $('<' + this.tag() + astr + '>');
}
Dom.prototype.value=function(v) {
if(v === undefined) return this.attr.value;
this.attr.value=v;
return this;
}
Dom.prototype.id=function(v) {
if(v === undefined) return this.attr.id;
this.attr.id=v;
return this;
}
Dom.prototype.add=function(a,v) {
this.attr[a]=v;
return this;
}
// Element Option
function _Option(c) { Dom.apply(this,[c]); }
__extends(_Option,Dom);
_Option.prototype.tag = function() { return "option"; }
function Option(c) { return new _Option(c); }
// Element Select
function _Select(c) { Dom.apply(this,[c]); }
__extends(_Select,Dom);
_Select.prototype.tag = function() { return "select"; }
_Select.prototype.newOption = function(v,c) {
var opt=Option(c).value(v);
this.append(opt);
return opt;
}
_Select.prototype.options = function(a,selected) {
if( Object.prototype.toString.call( a ) === '[object Array]' ) {
for(var i=0;i<a.length;i++) if(selected == a[i]) this.newOption(a[i],a[i]).add("selected","selected"); else this.newOption(a[i],a[i]);
} else {
for(var v in a) if(selected != v) this.newOption(v,a[v]); this.newOption(v,a[v]).add("selected","selected");
}
return this;
}
function Select(c) { return new _Select(c); }
// Element Button
function _Button(c) { Dom.apply(this,[c]); }
__extends(_Button,Dom);
_Button.prototype.tag = function() { return "button"; }
function Button(c) { return new _Button(c); }
// Element Div
function _Div(c) { Dom.apply(this,[c]); }
__extends(_Div,Dom);
_Div.prototype.tag = function() { return "div"; }
function Div(c) { return new _Div(c); }
// Element Fieldset
function _Fieldset(c) { Dom.apply(this,[c]); }
__extends(_Fieldset,Dom);
_Fieldset.prototype.legend = function(c) { this.prepend(Legend(c)); return this; }
_Fieldset.prototype.tag = function() { return "fieldset"; }
function Fieldset(c) { return new _Fieldset(c); }
// Element Legend
function _Legend(c) { Dom.apply(this,[c]); }
__extends(_Legend,Dom);
_Legend.prototype.tag = function() { return "legend"; }
function Legend(c) { return new _Legend(c); }
// Element Li
function _Li(c) { Dom.apply(this,[c]); }
__extends(_Li,Dom);
_Li.prototype.tag = function() { return "li"; }
function Li(c) { return new _Li(c); }
// Element Ul
function _Ul(c) { Dom.apply(this,[c]); }
__extends(_Ul,Dom);
_Ul.prototype.tag = function() { return "ul"; }
function Ul(c) { return new _Ul(c); }
// Element Label
function _Label(c) { Dom.apply(this,[c]); }
__extends(_Label,Dom);
_Label.prototype.tag = function() { return "label"; }
_Label.prototype.for = function(v) { this.add("for",v); return this; }
function Label(c) { return new _Label(c); }
// Element Span
function _Span(c) { Dom.apply(this,[c]); }
__extends(_Span,Dom);
_Span.prototype.tag = function() { return "span"; }
function Span(c) { return new _Span(c); }
// Element G
function _G(c) { Dom.apply(this,[c]); }
__extends(_G,Dom);
_G.prototype.render = function(elem,purge) {
var astr="";
for(var a in this.attr) astr+=" " + a + '="' + this.attr[a] +'"';
var str="<g" + astr + ">";
for(var i=0;i<this.cnt.length;i++) {
if(this.cnt[i] instanceof Dom) str+=this.cnt[i].render();
else str+=this.cnt[i];
}
str+="</g>";
if(elem instanceof jQuery) {
if(purge) elem.html(str); else elem.append(str);
}
return str;
}
_G.prototype.stroke = function(s) { return this.add("stroke",s); }
_G.prototype.stroke_width = function(w) { return this.add("stroke-width",w); }
function G(c) {
return new _G(c);
}
// Element Path
function _Path(c) { Dom.apply(this,[c]); }
__extends(_Path,Dom);
_Path.prototype.render = function(elem,purge) {
var astr="";
for(var a in this.attr) astr+=" " + a + '="' + this.attr[a] +'"';
var str="<path" + astr + ">";
for(var i=0;i<this.cnt.length;i++) {
if(this.cnt[i] instanceof Dom) str+=this.cnt[i].render();
else str+=this.cnt[i];
}
str+="</path>";
if(elem instanceof jQuery) {
if(purge) elem.html(str); else elem.append(str);
}
return str;
}
_Path.prototype.qbezier = function(a,b,c,d) {
if(attr.d==undefined) attr.d="";
attr.d+="Q " + a + " " + b + " " + c + " " + d + " ";
}
_Path.prototype.move = function(x,y) {
if(attr.d==undefined) attr.d="";
attr.d+="m " + x + " " + y + " ";
}
_Path.prototype.line = function(x,y) {
if(attr.d==undefined) attr.d="";
attr.d+="l " + x + " " + y + " ";
}
_Path.prototype.moveTo = function(x,y) {
if(attr.d==undefined) attr.d="";
attr.d+="M " + x + " " + y + " ";
}
_Path.prototype.lineTo = function(x,y) {
if(attr.d==undefined) attr.d="";
attr.d+="L " + x + " " + y + " ";
}
_Path.prototype.stroke = function(s) { return this.add("stroke",s); }
_Path.prototype.stroke_width = function(w) { return this.add("stroke-width",w); }
function Path(c) {
return new _Path(c);
}
// Element Svg
function _Svg() { Dom.apply(this); }
__extends(_Svg,Dom);
_Svg.prototype.tag = function() { return "svg"; }
_Svg.prototype.render = function(elem,purge) {
var astr="";
for(var a in this.attr) astr+=" " + a + '="' + this.attr[a] +'"';
var str="<svg" + astr + ">";
for(var i=0;i<this.cnt.length;i++) {
if(this.cnt[i] instanceof Dom) str+=this.cnt[i].render();
else str+=this.cnt[i];
}
str+="</svg>";
if(elem instanceof jQuery) {
if(purge) elem.html(str); else elem.append(str);
}
return str;
}
function Svg(w,h) {
var s=new _Svg();
return s.add("width",w).add("height",h);
}
// Element Line
function _Line(c) { Dom.apply(this,[c]); }
__extends(_Line,Dom);
_Line.prototype.tag = function() { return "line"; }
_Line.prototype.build = function() {
var astr="";
for(var a in this.attr) astr+=" " + a + '="' + this.attr[a] +'"';
return '<' + this.tag() + astr + ' />';
}
_Line.prototype.set = function(x1,y1,x2,y2) { return this.add("x1",x1).add("y1",y1).add("x2",x2).add("y2",y2); }
_Line.prototype.stroke = function(s) { return this.add("stroke",s); }
_Line.prototype.stroke_width = function(w) { return this.add("stroke-width",w); }
function Line(x1,y1,x2,y2) {
var l=new _Line(); if(y2 != undefined) return l.set(x1,y1,x2,y2);
return l;
}
// Element Circle
function _Circle(c) { Dom.apply(this,[c]); }
__extends(_Circle,Dom);
_Circle.prototype.build = function() {
var astr="";
for(var a in this.attr) astr+=" " + a + '="' + this.attr[a] +'"';
return "<circle" + astr + " />";
}
_Circle.prototype.render = function() {
return this.build();
}
_Circle.prototype.set = function(cx,cy,r) { return this.add("cx",cx).add("cy",cy).add("r",r); }
_Circle.prototype.stroke = function(s) { return this.add("stroke",s); }
_Circle.prototype.fill = function(f) { return this.add("fill",f); }
_Circle.prototype.stroke_width = function(w) { return this.add("stroke-width",w); }
function Circle(cx,cy,r) {
var l=new _Circle(); if(r != undefined) return l.set(cx,cy,r);
return l;
}
// Element Rect
function _Rect(c) { Dom.apply(this,[c]); }
__extends(_Rect,Dom);
_Rect.prototype.build = function() {
var astr="";
for(var a in this.attr) astr+=" " + a + '="' + this.attr[a] +'"';
return "<rect" + astr + " />";
}
_Rect.prototype.render = function() {
return this.build();
}
_Rect.prototype.set = function(w,h) { return this.add("width",w).add("height",h); }
_Rect.prototype.stroke = function(s) { return this.add("stroke",s); }
_Rect.prototype.fill = function(f) { return this.add("fill",f); }
_Rect.prototype.stroke_width = function(w) { return this.add("stroke-width",w); }
function Rect(w,h) {
var l=new _Rect(); if(h != undefined) return l.set(w,h);
return l;
}
<file_sep>/html/projects/color/ui.js
/*
*
* File ui.js
* Ui example.
*
* First define a new ui widget via widget factory.
*
*/
Fieldset(Legend("In1")).id("sensorin1")
.addClass("sensor")
.append(Div().addClass("sensormodes"))
.append(Div().addClass("sensorcontainer")).render($("#custom1"),true);
$("#sensorin1").sensor({port:"in1"});
console.log("ui.js loaded ok");
<file_sep>/html/projects/remote/loop.js
/*
*
* File loop.js
* Example program.
* How to use the IrRemA class to read IR sensor in IR-REM-A mode.
*/
lib("sensor.js"); // For updateSensor
lib("limiter.js"); // For Limiter
lib("remote.js"); // For IrRemA
lib("leds.js"); // For System.Leds.get
lib("power.js"); // For Power.run
/*
* Create a limiter.
* All it does is, to call the function every Nth time.
* Here we call it every 10th time to update sensor data in the web app, notis port option.
* To recieve the sensor data we create a sensor widget in the web app, (see ui.js)
*/
var limiter = new Limiter(10,function() {
updateSensor("in1");
});
/*
* Create a remote controller object from IrRemA class.
*/
var remote=new IrRemA(Sensors.in1);
/*
* Create an array of led device for short hand use in updateLeds.
* Notis that element 0(zero) is empty, sinces the buttons is numbers 1 to 4 (not 0 to 3).
*/
var leds=[ 0, System.Leds.get("left","green"),System.Leds.get("left","red"),System.Leds.get("right","green"),System.Leds.get("right","red") ];
/*
* Function updateLeds.
* Set led brightness to either 255 for button down or 0 for button up. And
* write the buttons states to the log.
* In the array leds the order of the leds is set.
*/
function updateLeds() {
var s="Buttons:";
for(var i=1;i<5;i++) {
leds[i].write("brightness",remote.get(i) ? 255 : 0);
s+=" " + remote.get(i);
}
Msg.log(s);
}
/*
* loop function.
* Here we run the limiter and check if the buttons states has changed,
* if so, we update the leds.
*/
var loop = function() {
limiter.run();
if(remote.update()) {
updateLeds();
}
Power.run();
}
var epilog=function() {
for(port in Motors) Motors[port].write("command","reset");
}
<file_sep>/html/lib/color.js
/*
*
* color.js
*
*/
function Color(s) {
this.sensor=s;
this.colors = ["none","Black","Blue","Green","Yellow","Red","White","Brown"];
this.sensor.write("mode","COL-COLOR");
Color.prototype.get = function() {
var c=this.sensor.read("value0");
return this.colors[c & 7];
}
}<file_sep>/html/projects/.tmpl/ui.js
/*
* File ui.js
*/
console.log("ui.js loaded ok");
<file_sep>/html/projects/touch/loop.js
/*
*
* File loop.js
*
* First include touch.js containing the Touch class.
*
*
*/
/*
* Load some standart lib files.
*/
lib("touch.js");
lib("leds.js");
/*
* Constructor function mytouch.
*
* Constructs a Touch class object at sensor port in1. Adds up and down callback function
* to catch the sensor action. When the sensor is down we turn on the rigth red led and off
* when it´s up.
*/
function mytouch() {
return new Touch({
sensor:Sensors.in1, // choose a sensor port. Here in1.
led : new Led(System.Leds.get("right","red")),
up:function() { // Declare up function. Stop motor on outA, log action and send new state to web app.
this.led.set(0);
Msg.send("touchstate","{state:0}");
Msg.log("Up");
},
down:function() { // Declare down function. Set motor speed, start motor, log action and send new state to web app.
this.led.set(255);
Msg.send("touchstate","{state:1}");
Msg.log("Down");
},
});
}
var touch = mytouch(); // create the Touch object.
/*
* loop function.
*
* This is the main function in the robot program.
* The loop function is being call perpetualy as long as the javascript is running. Between the calls,
* the web server is being runned. So all messages send to the web app, is not being send until the loop returns
* controlle to the server enginen.
* So it must return as soon as posible.
*
* All we do is to poll the touch sensor by calling touch.run()
*
*/
Msg.log("Sensor modes: " + Sensors.in1.modes + " num_values: " + Sensors.in1.values);
var loop = function() {
touch.run(); // Poll sensor state.
};
var epilog=function() {
}
<file_sep>/libws++/server.h
#pragma GCC diagnostic ignored "-Wwrite-strings"
#include "lws_config.h"
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <signal.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <assert.h>
#include <syslog.h>
#include <sys/time.h>
#include <unistd.h>
#include <libwebsockets.h>
extern int close_testing;
extern int max_poll_elements;
extern volatile int force_exit;
extern struct lws_context *context;
extern const char *resource_path;
void server_lock(int care);
void server_unlock(int care);
void findPorts();
void freePortData();
void rescanPorts();
#ifndef __func__
#define __func__ __FUNCTION__
#endif
struct per_session_data__http {
lws_filefd_type fd;
};
class msgQue;
struct per_session_data__port_data {
int currPort;
int msgNum;
int fragged;
size_t pbuf;
char *fragbuf;
msgQue *msgque;
};
/*
* one of these is auto-created for each connection and a pointer to the
* appropriate instance is passed to the callback in the user parameter
*
* for this example protocol we use it to individualize the count for each
* connection.
*/
struct per_session_data__lws_mirror {
struct lws *wsi;
int ringbuffer_tail;
};
extern int
callback_http(struct lws *wsi, enum lws_callback_reasons reason, void *user,
void *in, size_t len);
extern int
callback_lws_mirror(struct lws *wsi, enum lws_callback_reasons reason,
void *user, void *in, size_t len);
extern int
callback_dumb_increment(struct lws *wsi, enum lws_callback_reasons reason,
void *user, void *in, size_t len);
extern int
callback_port_data (struct lws *wsi, enum lws_callback_reasons reason,
void *user, void *in, size_t len);
//extern void
//dump_handshake_info(struct lws *wsi);
<file_sep>/startup.cpp
/*
* Start up module.
*
* Do the start from main.
*
*/
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <fstream>
#include <iostream>
#include "ev3.h"
using namespace std;
void loop();
void init();
void epilog();
int main(int argc,char *arg[]) {
ports=new Ports();
ws_main(argc,arg);
server_lock(1);
init();
server_unlock(1);
while(!force_exit) {
_pump();
loop();
}
server_lock(1);
epilog();
server_unlock(1);
destroyLwsl();
}
<file_sep>/html/projects/touch/mytouch.js
/*
* mytouch.js
*
*/
var led = new Led(System.Leds.get("right","red"));
function mytouch() {
return new Touch({
sensor:Sensors.in1, // choose a sensor port. Here in1.
motor: new Motor(Motors.outA), // Add Motor to Touch class.
speed:50, // Add speed to Touch class, by setting it to 50.
_create:function() {
Msg.on("touchdir","touchdir",this); //Add touchdir callback function to recive from web app, on channel touchdir.
},
up:function() { // Declare up function. Stop motor on outA, log action and send new state to web app.
led.set(0);
this.motor.stop();
Msg.log("Motor stop");
Msg.send("touchstate","{state:0}");
},
down:function() { // Declare down function. Set motor speed, start motor, log action and send new state to web app.
led.set(255);
this.motor.duty_cycle_sp(this.speed);
this.motor.command("run-forever");
if(this.speed>0) Msg.log("Start Motor Speed " + this.speed + " forward");
else Msg.log("Start Motor Speed " + this.speed + " backwards");
Msg.send("touchstate","{state:1}");
},
/*
* touchdir function.
* Toggle speed direction(from positiv to negative and versus). And log action.
* This message is send from ui.js using:
* chnlman.send("touchdir:toggle;");
*/
touchdir: function(cmd) {
if(this.speed===undefined) this.speed=-50;
Msg.log("Touchdir msg rcv " + cmd);
if(this.speed>0) this.speed=-50; else this.speed=50;
}
});
}
<file_sep>/libws++/Makefile
CC=g++
C_FLAGS = -Wall -std=gnu++11 -fvisibility=hidden -pthread -O3 -DNDEBUG -I/home/robot/libwebsockets-1.6.2/build -I/home/robot/libwebsockets-1.6.2/lib
C++_FLAGS = -Wall
L_FLAGS = -I/usr/local/include -lpthread -lz -lssl -lcrypto -lwebsockets
C_DEFINES = -DWWWROOT=\"/home/robot/ws/html\"
DEPS = server.h ev3.h v7.h
OBJ = ev3.o server.o server-http.o port-data.o v7.o
libws++: $(OBJ)
ar ruv libws++.a $(OBJ)
ranlib libws++.a
v7.o: v7.cpp v7.h
$(CC) -c -o v7.o v7.cpp $(C_FLAGS) $(C_DEFINES)
%.o: %.cpp $(DEPS)
$(CC) -c -o $@ $< $(C_FLAGS) $(C_DEFINES)
clean:
rm $(OBJ) libws++.a
<file_sep>/html/widgets.js
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
Sensor widget.
*/
$.widget("costum.sensor",{
splist:{driver_name:"Driver",mode:"Mode",value0:"Value"},
painters: {
"allsensor":[sensorInit,sensorUpdate],
"TOUCH":[sensorTouchInit,sensorTouchUpdate],
"IR-PROX":[irProxInit,irProxUpdate],
"COL-AMBIENT":[colorAmbientInit,colorAmbientUpdate],
"RGB-RAW":[colorRGBInit,colorRGBUpdate],
"COL-COLOR":[colorColorInit,colorColorUpdate],
"IR-REM-A":[irRemoteInit,irRemoteUpdate],
"IR-SEEK":[irSeekInit,irSeekUpdate]
},
painter:"",
options:{
port : "in1",
painterInit: sensorInit,
painterUpdate: sensorUpdate,
selector:false,
},
rcv: function(data) {
this.update(data);
},
_create: function() {
this.options.painterInit.apply(this,[this]);
chnlman.on("sensordata."+ this.options.port,this.rcv,this);
chnlman.send("sensordata:" + this.options.port + ";");
},
_destroy: function() {
chnlman.removeListenerContex(this);
},
update: function(data) {
if(this.painter!="COSTUM") {
if(data.mode==0) m="allsensor";
else m=data.mode;
if(!this.painters[m]) m="allsensor";
if(this.painter!=m) {
this.options.painterInit=this.painters[m][0];
this.options.painterUpdate=this.painters[m][1];
this.options.painterInit.apply(this,[this]);
var mds = data.modes.split(' ');
if(mds.length > 1 && this.options.selector) {
var slct = Select().options(mds,data.mode).render(this.element.find('.sensormodes'),true);
this.element.find('select').selectmenu({
width: 195,
change: function(event,ui) {
console.log("select",ui.item.value);
chnlman.send(data.address + ":mode " + ui.item.value + ";");
}
});
}
}
}
this.options.painterUpdate.apply(this,[data]);
},
clear: function() {
console.log("Clear");
this.painter="allsensor";
this.options.painterInit=this.painters.allsensor[0];
this.options.painterUpdate=this.painters.allsensor[1];
this.options.painterInit.apply(this,[this]);
},
});
/*
Motor widget.
*/
function loadMotor(target,port) {
Fieldset(Legend(port)).id("motor" + port)
.addClass("motor").render($("#" + target));
$("#motor" + port).motor({port:port,controls:false});
}
$.widget("costum.motor",{
_create: function() {
var self = this;
this.element.html("<legend>" + self.options.port + "</legend>");
this.element.append("<div>PortData <span class='portstatus'>Disconnected</span></div>");
for(var p in this.commands) {
this.element.append("<div>" + this.commands[p] + ":<span class='motorvalue " + p + "'>0</span></div>");
}
if(options.controls) {
cmds = $('<div>');
cmds.motorctrl({port:this.options.port,cmd:function(event,data){ if(self.options.connected) self._trigger("cmd",null,data); } } );
this.element.append(cmds);
}
chnlman.on("motordata." + this.options.port,this.update,this);
},
_destroy: function() {
chnlman.removeListenerContex(this);
},
update: function(data) {
this.options.connected=true;
this.element.find(".portstatus").html("Connected");
for(var p in this.commands) {
this.element.find("." + p).html(data[p]);
}
},
commands:{stop_command:"Stop command",duty_cycle_sp:"Duty cycle sp",speed:"Speed",state:"State",position:"Position"},
options:{
port : "outA",
cmd:function(event,data) {console.log("Command catch in fallback ",data);},
connected:false,
controls:false,
},
});
/*
MotorCtrl widgit.
*/
$.widget("costum.motorctrl",{
_create: function() {
var self = this;
var port=this.options.port;
Div(Select().addClass("cmdselect")
.options(this.commands,this.options.command))
.addClass("cmd")
.append(Button("send").addClass("runcmd")).render(this.element);
Div(Select()
.addClass("stopcmdselect")
.options(this.stop_commands,this.options.stop_command))
.addClass("cmd")
.append(Button("send").addClass("runscmd")).render(this.element);
var sldrid = "motorslider" + port;
var sldrlabelid = "motorsliderlabel" + port;
Div(Label("Duty Cycle").for(sldrid).id(sldrlabelid).append(Span("0").addStyle("float:right;")))
.append(Div().id(sldrid)).render(this.element);
this.element.find(".runcmd").button().click(function() {
self._trigger("cmd",null,{property:"command",port:self.options.port,value:self.options.command});
});
this.element.find(".runscmd").button().click(function() {
self._trigger("cmd",null,{property:"command",port:self.options.port,value:self.options.stop_command});
});
this.element.find('.cmdselect').selectmenu({
width: 190,
change: function(event,ui) {
self.options.command=ui.item.value;
}
});
this.element.find('.stopcmdselect').selectmenu({
width: 190,
change: function(event,ui) {
self.options.stop_command=ui.item.value;
}
});
this.element.find("#" + sldrid).slider({
max:100,
min:-100,
value:0,
change:function(event,ui) {
console.log("Duty cycles port " + port,$(this).slider("value"));
var sp = Span(ui.value.toString()).addStyle("float:right;");
$('#' + sldrlabelid).html("Duty Cycles").append(sp.render());
self._trigger("cmd",null,{property:"duty_cycles_sp",port:self.options.port,value:ui.value.toString()});
},
slide:function(event,ui) {
var sp = Span(ui.value.toString()).addStyle("float:right;");
$('#' + sldrlabelid).html("Duty Cycles ").append(sp.render());
},
});
},
commands : ["run-forever", "run-to-abs-pos", "run-to-rel-pos", "run-timed", "run-direct", "stop", "reset"],
stop_commands : ["coast", "brake", "hold"],
options: {
port: "outA",
command: "run-forever",
stop_command: "coast",
duty_cycles:0
},
});
/*
* doc widget and loadDoc function.
* Loads the index.html of the project into element of target.
*
* loadDoc("custom1");
*/
$.widget("custom.doc",{
_create:function() {
var self=this;
$.get("/projects/" + config.current + "/index.html",function(data) {
self.element.html(data);
});
},
});
function loadDoc(target) {
var div=Div().id(target + "doc").render($("#" + target));
$("#" + target + "doc").doc();
}
function loadSensor(target,port) {
Fieldset(Legend("In1")).id("sensor" + port)
.addClass("sensor")
.append(Div().addClass("sensormodes"))
.append(Div().addClass("sensorcontainer")).render($("#" + target));
$("#sensor" + port).sensor({port:port,selector:false});
}
/*
Painter functions for sensors.
*/
function portData(con) {
return Div("PortData").append(Span(con ? "Connected":"Disconnected").addClass("sensorvalue")).render();
}
function irProxInit() {
this.element.find('legend').html(this.options.port + " ir proximation");
this.element.find('.sensorcontainer').html(portData(false));
for(var p in this.splist) {
Div(this.splist[p] + ":")
.append(Span("0")
.addClass("sensorvalue " + p))
.render(this.element.find('.sensorcontainer'));
}
// for(var p in this.splist) {
// this.element.find('.sensorcontainer').append("<div>" + this.splist[p] + ":<span class='sensorvalue " + p + "'>0</span></div>");
// }
this.dataline=[];
svg = Svg(190,50);
svg.append(Rect(190,50).stroke("green").stroke_width(2).fill("yellow"));
for(i=0;i<100;i++) {
this.dataline.push(0);
var x=i*2;
var y1=0;
var y2=1;
svg.append(Line(x,y1,x,y2).stroke("black").stroke_width(4));
}
svg.render(this.element.find('.sensorcontainer'));
}
function irProxUpdate(data) {
this.painter="IR-PROX";
this.element.find('legend').html(this.options.port + " Ir proximation");
this.element.find('.sensorcontainer').html(portData(true));
for(var p in this.splist) {
Div(this.splist[p] + ":")
.append(Span(data[p])
.addClass("sensorvalue " + p))
.render(this.element.find('.sensorcontainer'));
}
// for(var p in this.splist) {
// this.element.find('.sensorcontainer').append("<div>" + this.splist[p] + ":<span class='sensorvalue " + p + "'>" + data[p] + "</span></div>");
// }
svg = Svg(190,50);
svg.append(Rect(190,50).stroke("green").stroke_width(2).fill("yellow"));
this.dataline.unshift(data.value0);
this.dataline.pop();
for(i=0;i<100;i++) {
var x=i*2;
var y2=(this.dataline[i]/2)+2;
var y1=y2-2;
svg.append(Line(x,y1,x,y2).stroke("black").stroke_width(4));
}
svg.render(this.element.find('.sensorcontainer'));
}
function sensorValue(lbl,v) {
return Div(lbl + ":").append(Span(v).addClass("sensorvalue")).render();
}
function sensorTouchInit() {}
function sensorTouchUpdate(data) {
this.painter="TOUCH";
this.element.find('legend').html(data.address + " Touch");
this.element.find('.sensorcontainer').html(portData(true));
this.element.find('.sensorcontainer').append(sensorValue("Mode",data.mode));
this.element.find('.sensorcontainer').append(sensorValue("State",(parseInt(data.value0) ? "Down" : "Up")));
}
function sensorInit() {
this.element.find('legend').html(this.options.port);
this.element.find('.sensorcontainer').html(portData(false));
for(var p in this.splist) {
Div(this.splist[p] + ":")
.append(Span("0")
.addClass("sensorvalue " + p))
.render(this.element.find('.sensorcontainer'));
}
}
function sensorUpdate(data) {
this.painter="allsensor";
this.element.find(".portstatus").html("Connected");
for(var p in this.splist) {
this.element.find("." + p).html(data[p]);
}
}
function colorAmbientInit() {
}
function colorAmbientUpdate(data) {
this.painter="COL-AMBIENT";
this.element.find('legend').html(data.address + " Color Ambient");
this.element.find('.sensorcontainer').html(portData(true));
this.element.find('.sensorcontainer').append(sensorValue("Mode",data.mode));
this.element.find('.sensorcontainer').append(sensorValue("Value",data.value0));
}
function colorRGBInit() {
}
function RGB(r,g,b) {
return "RGB(" + parseInt(r) + "," + parseInt(g) + "," + parseInt(b) + ")";
}
function colorRGBUpdate(data) {
this.painter="RGB-RAW";
this.element.find('legend').html(data.address + " Color Ambient");
this.element.find('.sensorcontainer').html(portData(true));
this.element.find('.sensorcontainer').append(sensorValue("Mode",data.mode));
var clrEx = $('<div>').css("width",16)
.css("height",16)
.css("background-color", RGB(data.value0[0]/2,data.value0[1]/2,data.value0[2]/2) )
.css("float","right");
var vl = sensorValue("Value","R " + data.value0[0] + " G " + data.value0[1] + " B " + data.value0[2]);
vl.append(clrEx);
this.element.find('.sensorcontainer').append(vl);
}
function colorColorInit() {
}
var clrTable = ["None","Black","Blue","Green","Yellow","Red","White","Brown"];
function colorColorUpdate(data) {
this.painter="COL-COLOR";
this.element.find('legend').html(data.address + " Color Name");
this.element.find('.sensorcontainer').html(portData(true));
this.element.find('.sensorcontainer').append(sensorValue("Mode",data.mode));
this.element.find('.sensorcontainer').append(sensorValue("Value",clrTable[data.value0 & 7]));
}
function irSeekInit() {
this.element.find('legend').html(this.options.port);
this.element.find('.sensorcontainer').html(portData(false));
for(var p in this.splist) {
this.element.find('.sensorcontainer').append("<div>" + this.splist[p] + ":<span class='sensorvalue " + p + "'>0</span></div>");
}
}
function irSeekUpdate(data) {
this.painter="IR-SEEK";
this.element.find(".portstatus").html("Connected");
for(var p in this.splist) {
this.element.find("." + p).html(data[p]);
}
var str="";
for(var i=0;i<data.value0.length;i++) {
str+=data.value0[i] + " ";
}
this.element.find(".value0").html(str);
}
function irRemoteInit() {
this.btnstate=[0,0,0,0,0];
}
function irRemoteUpdate(data) {
this.painter="IR-REM-A";
if(data.value0!=384) {
for(i=1;i<5;i++) {
if(this.btnstate[i]) {
var b=(data.value0 & 0xf0) >> 4;
if(! (b & (1 << (i-1))) ) this.btnstate[i]=0;
} else {
var b=(data.value0 & 0xf0) >> 4;
if((b & (1 << (i-1))) ) this.btnstate[i]=1;
}
}
}
this.element.find('legend').html(data.address + " ir remote");
this.element.find('.sensorcontainer').html(portData(true));
this.element.find('.sensorcontainer').append(sensorValue("Value",data.value0==384 ? "Idle" : data.value0));
var btns = $('<div>');
for(i=1;i<5;i++) {
var btn = $('<button>').addClass((this.btnstate[i] ? "btn-down":"btn-up")).html(i);
btns.append(btn);
}
this.element.find('.sensorcontainer').append(btns);
}
<file_sep>/libws++/ev3.h
#pragma GCC diagnostic ignored "-Wwrite-strings"
#ifndef __EV3_H
#define __EV3_H
#define MOTOR_PATH "/sys/class/tacho-motor/"
#define SENSOR_PATH "/sys/class/lego-sensor/"
#include "server.h"
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <deque>
using namespace std;
enum PORT_TYPES {
PORT_POWER = 0,
PORT_PORT,
PORT_MESSAGE
};
class Ports;
extern Ports *ports;
extern int file_error;
int ws_main(int argc,char *arg[]);
int _pump();
void destroyLwsl();
class Port {
public:
Port(char *p);
Port() : msgNum(0) { portType=PORT_PORT; }
virtual ~Port() {}
int write(char const *p,int value);
int write(char const *p,char *value);
int readInt(char const *p);
char *readStr(char *buf,char const *p);
inline char *probertyName(char *b,char *p) {
return strcat(strcat(strcpy(b,path),"/"),p);
};
char address[32];
char path[128];
int portType;
char mode[16];
char driver_name[16];
int msgNum;
};
class Power : public Port{
public:
Power() : Port() {
strcpy(path,"/sys/class/power_supply/legoev3-battery");
strcpy(address,"power");
strcpy(driver_name,"power");
}
~Power() {}
};
class Led : public Port{
public:
Led(char *led) : Port() {
strcat(strcpy(path,"/sys/class/leds/"),led);
strcpy(address, led);
strcpy(driver_name,"Led");
}
~Led() {}
};
typedef int (*evCallback)(char*,char*,char*);
class Message {
public:
Message(char *c,char *m) : chnl(c),msg(m) { }
~Message() { }
char *channel() { return (char*)chnl.c_str(); }
char *message() { return (char*)msg.c_str(); }
string chnl;
string msg;
};
class msgQue {
public:
msgQue() {}
~msgQue() {
while(que.size()) {
delete que[0];
que.pop_front();
}
}
void send(char *chnl,char *m) {
Message *msg=new Message(chnl,m);
que.push_back(msg);
}
int msg(char *p) {
if(que.size()>0) {
Message *msg=(Message*) que.front();
que.pop_front();
sprintf(p,"{\"channel\":\"%s\",\"data\":%s}",msg->channel(),msg->message());
delete msg;
return strlen(p);
}
return 0;
}
std::deque<Message*> que;
};
class Ports {
public:
Ports();
~Ports() {
if(psdlist.size()) {
std::vector<per_session_data__port_data*>::iterator v=psdlist.begin();
while(v != psdlist.end()) {
delete (*v)->msgque;
v++;
}
}
}
void addPsd(per_session_data__port_data *psd) {
psdlist.push_back(psd);
}
void removePsd(per_session_data__port_data *psd) {
for(unsigned int i=0;i<psdlist.size();i++) {
if(psdlist[i] == psd) psdlist.erase(psdlist.begin()+i);
}
}
int isMsgque() {
for(unsigned int i=0;i<psdlist.size();i++) {
if(psdlist[i]->msgque->que.size() > 0) {
return 1;
}
}
return 0;
}
int msg(char *p,per_session_data__port_data *psd) {
if(psd->msgque->que.size()) {
return psd->msgque->msg(p);
}
return 0;
}
void addListener(evCallback cb) {
cblist.push_back(cb);
}
void send(char* chnl,char *m) {
if(psdlist.size()) {
std::vector<per_session_data__port_data*>::iterator v=psdlist.begin();
while(v!=psdlist.end()) {
(*v)->msgque->send(chnl,m);
v++;
}
}
}
void dispatch(char *p) {
char *sp=p;
while(*sp) {
char *target=sp;
sp=strchr(sp,':');
sp[0]=0;
char *cmd=sp+1;
sp=strchr(cmd,';');
sp[0]=0;
sp++;
printf("dispatch rcv target %s command %s\n",target,cmd);
std::vector<evCallback>::iterator v = cblist.begin();
int done=0;
while(v != cblist.end()) {
evCallback cb=*v;
int res = cb(target,cmd,sp);
if(res==1) done=1;
if(res==2) return;
v++;
}
if(!done) {
printf("Unknown target %s command %s\n",target,cmd);
}
}
}
std::vector<evCallback> cblist;
std::vector<per_session_data__port_data*> psdlist;
};
#endif
<file_sep>/libws++/server.cpp
/*
* server.cpp
*
* Main server processes and initialisation.
*
*/
#include "server.h"
#include <pthread.h>
int close_testing;
int max_poll_elements;
volatile int force_exit = 0;
struct lws_context *context;
int data_thread_created = 0;
int file_error=0;
pthread_mutex_t lock_established_conns;
pthread_t pthread_port_data;
/* http server gets files from this path */
#define LOCAL_RESOURCE_PATH WWWROOT
const char *resource_path = LOCAL_RESOURCE_PATH;
/*
* multithreaded version - protect wsi lifecycle changes in the library
* these are called from protocol 0 callbacks
*/
void server_lock(int care)
{
if (care)
pthread_mutex_lock(&lock_established_conns);
}
void server_unlock(int care)
{
if (care)
pthread_mutex_unlock(&lock_established_conns);
}
/*
*/
enum demo_protocols {
/* always first */
PROTOCOL_HTTP = 0,
PROTOCOL_PORT_DATA,
/* always last */
DEMO_PROTOCOL_COUNT
};
/* list of supported protocols and callbacks */
static struct lws_protocols protocols[] = {
/* first protocol must always be HTTP handler */
{
"http-only", /* name */
callback_http, /* callback */
sizeof (struct per_session_data__http), /* per_session_data_size */
0, /* max frame size / rx buffer */
},
{
"port-data-protocol",
callback_port_data,
sizeof(struct per_session_data__port_data),
128,
},
{ NULL, NULL, 0, 0 } /* terminator */
};
int isMsgque();
void *thread_port_data(void *threadid)
{
while (!force_exit) {
/*
* If isMsgque() returns none zero, there is one or more messages in the que.
*/
pthread_mutex_lock(&lock_established_conns);
if(isMsgque()) lws_callback_on_writable_all_protocol(context,&protocols[PROTOCOL_PORT_DATA]);
pthread_mutex_unlock(&lock_established_conns);
usleep(50000);
}
pthread_exit(NULL);
}
void sighandler(int sig)
{
force_exit = 1;
lws_cancel_service(context);
}
static struct option options[] = {
{ "help", no_argument, NULL, 'h' },
{ "debug", required_argument, NULL, 'd' },
{ "port", required_argument, NULL, 'p' },
{ "ssl", no_argument, NULL, 's' },
{ "allow-non-ssl", no_argument, NULL, 'a' },
{ "interface", required_argument, NULL, 'i' },
{ "closetest", no_argument, NULL, 'c' },
{ "libev", no_argument, NULL, 'e' },
#ifndef LWS_NO_DAEMONIZE
{ "daemonize", no_argument, NULL, 'D' },
#endif
{ "resource_path", required_argument, NULL, 'r' },
{ NULL, 0, 0, 0 }
};
void destroyLwsl();
int ws_main(int argc, char **argv)
{
struct lws_context_creation_info info;
char interface_name[128] = "";
const char *iface = NULL;
//pthread_t pthread_dumb;
char cert_path[1024];
char key_path[1024];
int debug_level = 7;
int use_ssl = 0;
// void *retval;
int opts = 0;
int n = 0;
int syslog_options = LOG_PID | LOG_PERROR;
#ifndef LWS_NO_DAEMONIZE
int daemonize = 0;
#endif
/*
* take care to zero down the info struct, he contains random garbaage
* from the stack otherwise
*/
memset(&info, 0, sizeof info);
info.port = 7681;
pthread_mutex_init(&lock_established_conns, NULL);
while (n >= 0) {
n = getopt_long(argc, argv, "eci:hsap:d:Dr:", options, NULL);
if (n < 0)
continue;
switch (n) {
case 'e':
opts |= LWS_SERVER_OPTION_LIBEV;
break;
#ifndef LWS_NO_DAEMONIZE
case 'D':
daemonize = 1;
#ifndef _WIN32
syslog_options &= ~LOG_PERROR;
#endif
break;
#endif
case 'd':
debug_level = atoi(optarg);
break;
case 's':
use_ssl = 1;
break;
case 'a':
opts |= LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT;
break;
case 'p':
info.port = atoi(optarg);
break;
case 'i':
strncpy(interface_name, optarg, sizeof interface_name);
interface_name[(sizeof interface_name) - 1] = '\0';
iface = interface_name;
break;
case 'c':
close_testing = 1;
fprintf(stderr, " Close testing mode -- closes on "
"client after 50 dumb increments"
"and suppresses lws_mirror spam\n");
break;
case 'r':
resource_path = optarg;
printf("Setting resource path to \"%s\"\n", resource_path);
break;
case 'h':
fprintf(stderr, "Usage: test-server "
"[--port=<p>] [--ssl] "
"[-d <log bitfield>] "
"[--resource_path <path>]\n");
exit(1);
}
}
#if !defined(LWS_NO_DAEMONIZE)
/*
* normally lock path would be /var/lock/lwsts or similar, to
* simplify getting started without having to take care about
* permissions or running as root, set to /tmp/.lwsts-lock
*/
if (daemonize && lws_daemonize("/tmp/.lwsts-lock")) {
fprintf(stderr, "Failed to daemonize\n");
return 1;
}
#endif
signal(SIGINT, sighandler);
/* we will only try to log things according to our debug_level */
setlogmask(LOG_UPTO (LOG_DEBUG));
openlog("lwsts", syslog_options, LOG_DAEMON);
/* tell the library what debug level to emit and to send it to syslog */
lws_set_log_level(debug_level, lwsl_emit_syslog);
lwsl_notice("EV3 Development server - "
"(C) Copyright 2016 <NAME> - "
"licensed under LGPL2.1\n");
printf("Using resource path \"%s\"\n", resource_path);
info.iface = iface;
info.protocols = protocols;
#ifndef LWS_NO_EXTENSIONS
info.extensions = lws_get_internal_extensions();
#endif
info.ssl_cert_filepath = NULL;
info.ssl_private_key_filepath = NULL;
if (use_ssl) {
if (strlen(resource_path) > sizeof(cert_path) - 32) {
lwsl_err("resource path too long\n");
return -1;
}
sprintf(cert_path, "%s/libwebsockets-test-server.pem",
resource_path);
if (strlen(resource_path) > sizeof(key_path) - 32) {
lwsl_err("resource path too long\n");
return -1;
}
sprintf(key_path, "%s/libwebsockets-test-server.key.pem",
resource_path);
info.ssl_cert_filepath = cert_path;
info.ssl_private_key_filepath = key_path;
}
info.gid = -1;
info.uid = -1;
info.options = opts;
context = lws_create_context(&info);
if (context == NULL) {
lwsl_err("libwebsocket init failed\n");
return -1;
}
/* start the port data thread */
data_thread_created = 0;
n = pthread_create(&pthread_port_data, NULL, thread_port_data, 0);
if (n) {
lwsl_err("Unable to create motor status thread\n");
destroyLwsl();
}
data_thread_created = 1;
return 0;
}
int _pump() {
return lws_service(context, 50);
}
void destroyLwsl() {
void *retval;
/* wait for pthread_port_data to exit */
if(data_thread_created) pthread_join(pthread_port_data, &retval);
if(context!=NULL) lws_context_destroy(context);
pthread_mutex_destroy(&lock_established_conns);
lwsl_notice("libwebsockets server exited cleanly\n");
closelog();
}
<file_sep>/libws++/ev3.cpp
/*
* Ev3 module.
*
* Ev3 api objects.
*
* Sensors: Collect sensors.
*/
#include <cstring>
#include <stdlib.h>
#include <stdio.h>
#include <dirent.h>
#include <cstdio>
#pragma GCC diagnostic ignored "-Wwrite-strings"
#include "ev3.h"
int isMsgque() {
return ports->isMsgque();
}
Ports *ports;
Port::Port(char *p) {
portType=PORT_PORT;
strcpy(path,p);
readStr(address,"address");
readStr(driver_name,"driver_name");
}
int Port::write(char const *p,int value) {
char buf[64];
ofstream outfile;
outfile.open(strcat(strcat(strcpy(buf,path),"/"),p));
if(!outfile.is_open() || !outfile.good()) {
file_error=1;
return -1;
}
outfile << value << "\n";
outfile.close();
return 0;
}
int Port::write(char const *p,char *value) {
char buf[64];
ofstream outfile;
outfile.open(strcat(strcat(strcpy(buf,path),"/"),p));
if(!outfile.is_open() || !outfile.good()) {
file_error=1;
return -1;
}
outfile << value << "\n";
outfile.close();
return 0;
}
int Port::readInt(char const *p) {
ifstream infile;
char buf[64];
infile.open(strcat(strcat(strcpy(buf,path),"/"),p));
if(!infile.is_open() || !infile.good()) {
file_error=1;
return -1;
}
infile >> buf;
infile.close();
return atoi(buf);
}
char *Port::readStr(char *buf,char const *p) {
ifstream infile;
char b[64];
buf[0]=0;
infile.open(strcat(strcat(strcpy(b,path),"/"),p));
if(!infile.is_open() || !infile.good()) {
file_error=1;
return buf;
}
int first=1;
while(infile >> b) {
if(!first) strcat(buf," ");
first=0;
strcat(buf,b);
}
infile.close();
return buf;
}
Ports::Ports() {
}
<file_sep>/html/projects/remote/ui.js
/*
* File ui.js
*
* Here we just use the build in functions to load index.html from project folder
* and a stock sensor widget.
*/
loadDoc("custom1");
$("#custom2").html(""); // Clear first
loadSensor("custom2","in1"); // then add sensor widget. The widget recieves the data from
// updateSensor. Notis the port option.
console.log("ui.js loaded ok"); // We are loaded.
<file_sep>/html/projects/.tmpl/loop.js
/*
*
* File loop.js
*
*/
for(port in Motors) {
Msg.log("Active motor on " + port);
}
for(port in Sensors) {
Msg.log("Active sensor on " + port);
}
/*
* loop function.
*/
var loop = function() {
};
var epilog=function() {
for(port in Motors) Motors[port].write("command","reset");
}
<file_sep>/html/projects/radar/radarui.js
/*
Radar widget.
*/
$.widget("costum.radar",{
options:{},
_create: function() {
chnlman.on("radar",function(data) { this.update(data); },this);
svg = Svg(400,200).append(Circle(200,200,200).stroke("green").stroke_width(4).fill("yellow"));
var g=G().stroke("black").stroke_width(4);
for(i=1;i<45;i++) {
var pos1 = ((i-1)*4) - 90;
var pos2 = (i*4) - 90;
var rad1=0.0174532925*(pos1 % 360);
var rad2=0.0174532925*(pos2 % 360);
var x1=200+(Math.sin(rad1)*20);
var y1=200-(Math.cos(rad1)*20);
var x2=200+(Math.sin(rad2)*20);
var y2=200-(Math.cos(rad2)*20);
g.append(Line(x1,y1,x2,y2));
}
svg.append(g);
svg.render(this.element,true);
},
update: function(data) {
svg = Svg(400,200).append(Circle(200,200,200).stroke("green").stroke_width(4).fill("yellow"));
var g=G().stroke("black").stroke_width(4);
for(i=1;i<45;i++) if(data.samples[i]==0) data.samples[i]=data.samples[i-1];
for(i=1;i<45;i++) {
var pos1 = ((i-1)*4) - 90;
var pos2 = (i*4) - 90;
var rad1=0.0174532925*(pos1 % 360);
var rad2=0.0174532925*(pos2 % 360);
var x1=200+(Math.sin(rad1)*data.samples[i-1]*2);
var y1=200-(Math.cos(rad1)*data.samples[i-1]*2);
var x2=200+(Math.sin(rad2)*data.samples[i]*2);
var y2=200-(Math.cos(rad2)*data.samples[i]*2);
g.append(Line(x1,y1,x2,y2));
}
svg.append(g);
svg.render(this.element,true);
},
});
$.widget("costum.modesmenu",{
options:{address:"in1"},
_create: function() {
chnlman.on("modes." + this.options.address,function(data) {
this.update(data);
},this);
var div=Div(Select().addStyle("margin: 0.5em;").options(["None"]));
div.render(this.element);
this.element.find("select").selectmenu({width:150});
chnlman.send("modes:" + this.options.address + ";");
},
update: function(data) {
var div=Div(Select().addStyle("margin: 0.5em;").id("sensor" + this.options.address).options(data.modes,data.mode));
div.render(this.element,true);
this.element.find("select").selectmenu({width:150});
}
});
var rdr=Div().id("radar").render($("#custom1"),true);
var rdr=Div().id("modesmenu").render($("#custom2"),true);
$("#radar").radar();
$("#modesmenu").modesmenu({address:"in1"});
console.log("radarui.js loaded");
<file_sep>/html/lib/remote.js
/*
* File remote.js
*
* Ir sensor in remote mode classes.
*
*/
function IrRemA(s) {
this.sensor = s;
this.state=0;
this.btnstate=[0,0,0,0,0];
this.sensor.write("mode","IR-REM-A");
IrRemA.prototype.get = function(b) { return this.btnstate[b]};
IrRemA.prototype.update = function() {
var v=this.sensor.read("value0");
var changed=0;
if(v!=384) {
for(i=1;i<5;i++) {
if(this.btnstate[i]) {
var b=(v & 0xf0) >> 4;
if(! (b & (1 << (i-1))) ) {
this.btnstate[i]=0;
changed=1;
}
} else {
var b=(v & 0xf0) >> 4;
if((b & (1 << (i-1))) ) {
this.btnstate[i]=1;
changed=1;
}
}
}
}
return changed;
}
}
var statelist = [
[0,0],
[1,0],
[-1,0],
[0,1],
[0,-1],
[1,1],
[1,-1],
[-1,1],
[-1,-1],
[0,0]
];
function IrRemote(s,cb,bcb) {
if(s) this.sensor = s;
else this.sensor=Sensors.in1;
if(cb) this.cb=cb;
if(bcb) this.beaconCallback=bcb;
this.beaconstate=-1;
this.chnlstate=[[0,0],[0,0],[0,0],[0,0]];
this.sensor.write("mode","IR-REMOTE");
IrRemote.prototype.setCb= function(cb) {
this.cb=cb;
return this;
}
IrRemote.prototype.setBeaconCb=function(cb) {
this.beaconCallback = cb;
return this;
}
IrRemote.prototype.update = function() {
for(var i=0;i<4;i++) {
var v=this.sensor.read("value" + i);
if(v > 8) {
if(this.beaconstate==-1 && v==9) {
this.beaconCallback(1);
this.beaconstate=i;
}
} else {
if(this.beaconstate==i && v < 9) {
this.beaconCallback(0);
this.beaconstate=-1;
}
var b=statelist[v];
if(b!=this.chnlstate[i]) {
this.chnlstate[i]=b;
// Msg.log("Remote (" + i + ") " + b);
this.cb(i,b);
}
}
}
}
}<file_sep>/html/chnlmanager.js
/*
* chnlmanager.js
*
* chnlManager handles websocket connection and dispatch messages according to channel.
*
*/
function get_appropriate_ws_url() {
var pcol;
var u = document.URL;
if (u.substring(0, 5) == "https") {
pcol = "wss://";
u = u.substr(8);
} else {
pcol = "ws://";
if (u.substring(0, 4) == "http")
u = u.substr(7);
}
u = u.split('/');
return pcol + u[0] + "/xxx";
}
function chnlManager() {
this.listener = [];
var chnlm = this;
if (typeof MozWebSocket != "undefined") {
this.socket_di = new MozWebSocket(get_appropriate_ws_url(),"port-data-protocol");
} else {
this.socket_di = new WebSocket(get_appropriate_ws_url(),"port-data-protocol");
}
try {
this.socket_di.onopen = function() {
chnlm.dispatch('{channel:"network",data:{status:"connected"}}');
}
this.socket_di.onmessage =function (msg) {
chnlm.dispatch(msg.data.toString());
}
this.socket_di.onclose = function(){
chnlm.dispatch('{channel:"network",data:{status:"disconnected"}}');
}
} catch(exception) {
alert('<p>Error' + exception);
}
}
chnlManager.prototype.send = function(msg) {
this.socket_di.send(msg);
}
chnlManager.prototype.on = function(chnl,cb,cntx) { this.listener.push({channel:chnl,callback:cb,contex:cntx}); }
chnlManager.prototype.removeListenerContex = function(cntx) {
var nl = [];
while(this.listener.length>0) {
var e = this.listener.pop();
if(e.contex!=cntx) nl.push(e);
}
this.listener = nl;
}
chnlManager.prototype.removeListener = function(chnl,cb) {
var nl = [];
while(this.listener.length>0) {
var e = this.listener.pop();
if(e.channel!=chnl && e.callback!=cb) nl.push(e);
}
this.listener = nl;
}
chnlManager.prototype.dispatch = function(data) {
eval("var od=" + data + ";");
for(var i=0;i < this.listener.length;i++) {
var cntx = this.listener[i].contex!=undefined ? this.listener[i].contex : this;
if(this.listener[i].channel == od.channel) this.listener[i].callback.apply(cntx,[od.data]);
}
}
<file_sep>/html/projects/radar/radar.js
/*
* radar.js
*
*/
lib("motor.js");
lib("sensor.js");
lib("power.js");
lib("leds.js");
lib("limiter.js");
function Radar() {
var motor=new Motor(Motors.outA);
var sensor=new Sensor(Sensors.in1);
var rightled = new Led(System.Leds.right.red);
var leftled = new Led(System.Leds.left.red);
var dc_sp=40;
var ratio=2.2;
var cw=(ratio*180)+5;
var state="init";
var data=[];
var ostate="";
motor.position(0);
Radar.prototype.run = function() {
if(ostate!=state) {
ostate=state;
//Msg.log("New state " + state);
}
switch(state) {
case "init":
motor.runTo(cw,dc_sp);
state="runningCW";
data = [];
leftled.set(0);
rightled.set(255);
break;
case "runningCW":
var p=motor.position();
if((p>0) && (p<cw)) {
data[parseInt(p/8)]=parseInt(sensor.value());
}
if(p>cw) {
state="turnCCW";
motor.stop();
}
break;
case "turnCCW":
leftled.set(255);
motor.runTo(-5,dc_sp);
state="runningCCW";
break;
case "runningCCW":
rightled.set(0);
var p=motor.position();
if((p>0) && (p<cw)) {
data[parseInt( p/8 )]=parseInt(sensor.value());
}
if(p<0) {
state="turnCW";
motor.stop();
}
break;
case "turnCW":
rightled.set(255);
var s={samples:[]};
for(var i=0;i< data.length;i++) {
if(data[i]==undefined) data[i]=0;
s.samples[i]=data[i];
}
Msg.send("radar",JSON.stringify(s));
state="init";
break;
}
}
}
function ModesMenu(s) {
Msg.on("modes","rcv",this);
ModesMenu.prototype.rcv = function(cmd) {
var mds = Sensors[cmd].modes.split(" ");
var md = Sensors[cmd].read("mode");
var msg={modes:mds,mode:md};
Msg.send("modes." + cmd,JSON.stringify(msg));
}
}
var mm=new ModesMenu();
var r=new Radar();
var pwr=new Power();
var limiter = new Limiter(100,function() {
pwr.update();
});
function loop() {
r.run();
limiter.run();
}
function epilog() {
for(port in Motors) Motors[port].write("command","reset"); // Reset motors.
Msg.log("Radar ended.");
}
Msg.log("radar.js loaded");
<file_sep>/html/projects/remote2/ui.js
/*
* File ui.js
*/
$.widget("costum.speedgauge",{
options:{
port:"outA",
value:0,
text:"Ticks",
start:220,
end: 130,
ratio: 270/2000,
},
_create:function() {
chnlman.on("motordata." + this.options.port,this.update,this);
this.draw();
},
_destroy: function() {
chnlman.removeListenerContex(this);
},
draw: function() {
var svg=Svg(100,100).append(Circle(50,50,50).stroke("green").stroke_width(4).fill("yellow"));
var g=G().stroke("black").stroke_width(4);
var deg = (this.options.value*this.options.ratio);
var rad=0.0174532925*(deg % 360);
var x=50+(Math.sin(rad)*50);
var y=50-(Math.cos(rad)*50);
g.append(Line(50,50,x,y));
svg.append(g);
svg.render(this.element,true);
Div(this.options.text + " " + this.options.port).addClass("gaugevalue").addStyle("width:100%;text-align:center;margin-top:-45;margin-bottom:30").render(this.element);
Div(this.options.value).addClass("gaugevalue").addStyle("width:100%;text-align:center;margin-top:-32;margin-bottom:12").render(this.element);
return this;
},
update:function(data) {
this.options.value=data.speed;
this.draw();
// console.log("gague update",data.speed);
return this;
}
});
var gauges=Div("Hej").id("gauge1").render($("#custom1"),true);
var gauges=Div("Hej").id("gauge2").render($("#custom1"));
var gauge1=$("#gauge1").speedgauge({port:"outA"});
var gauge2=$("#gauge2").speedgauge({port:"outB"});
$("#custom2").html("");
loadMotor("custom2","outA");
loadMotor("custom2","outB");
loadSensor("custom2","in1");
console.log("ui.js loaded ok");
<file_sep>/webd.cpp
/*
*
*/
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fstream>
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
using namespace std;
#include <ev3.h>
#include <v7.h>
#include "js.h"
void getProject(char *buf) {
string line;
string file("");
ifstream infile(CONFIG_FILE);
if(infile.is_open()) {
while(!infile.eof()) {
getline(infile,line);
file.append(line);
}
} else perror ("Couldn't open the config file");
infile.close();
strcpy(buf,file.c_str());
}
char *getConfigfile(char *cbuf) {
cbuf[0]=0;
string line;
string file("");
char cnf[32];
char profn[128];
getProject(cnf);
strcat(strcat(strcpy(profn,CONFIG_PATH),cnf),"/.project.json");
puts(profn);
file="";
ifstream infile2(profn);
if(infile2.is_open()) {
while(!infile2.eof()) {
getline(infile2,line);
file.append(line);
file.append(string("\n"));
}
} else perror ("Couldn't open the config file");
infile2.close();
strcpy(cbuf,file.c_str());
puts(cbuf);
return cbuf;
}
void writefile(char *fn,char *buf) {
ofstream outfile(fn,ios::trunc | ios::out);
if(outfile.is_open()) {
outfile << buf;
}else perror ("Couldn't save file");
outfile.close();
}
int savefile(char *target,char *cmd,char *buf) {
if(strcmp(target,"savefile")!=0) return 0; // not to os.
char fn[64];
strcat(strcpy(fn,SRC_PATH),cmd);
writefile(fn,buf);
return 2;
}
int saveproject(char *target,char *cmd,char *buf) {
if(strcmp(target,"saveproject")!=0) return 0; // not to os.
char fn[64];
if(strcmp(buf,"none")!=0) {
strcat(strcat(strcpy(fn,SRC_PATH),cmd),"/.project.json");
ofstream outfile(fn,ios::trunc | ios::out);
if(outfile.is_open()) {
outfile << buf;
} else perror ("Couldn't save file");
outfile.close();
}
strcat(strcpy(fn,SRC_PATH),"config");
ofstream outfile2(fn,ios::trunc | ios::out);
if(outfile2.is_open()) {
outfile2 << cmd;
} else perror ("Couldn't save file");
outfile2.close();
// puts(fn);
// puts(buf);
return 2;
}
int getfiles(char *target,char *cmd,char *b) {
if(strcmp(target,"files")!=0) return 0; // not to os.
char buf[1024];
strcpy(buf,"{files:[");
DIR *dp;
struct dirent *ep;
char dirpath[64];
strcat(strcpy(dirpath,SRC_PATH),cmd);
dp = opendir (dirpath);
if (dp != NULL) {
int first=1;
while ((ep = readdir (dp))) {
//puts (ep->d_name);
if((strcmp(ep->d_name,".")!=0) && (strcmp(ep->d_name,"..")!=0) && (ep->d_type==DT_REG)) {
char fb[32];
sprintf(fb,"%s\"%s\"",(!first? ",":""),ep->d_name);
first=0;
strcat(buf,fb);
}
}
closedir (dp);
strcat(buf,"]}");
} else perror ("Couldn't open the directory");
ports->send("files",buf);
return 1;
}
int getprojects(char *target,char *cmd,char *b) {
if(strcmp(target,"projects")!=0) return 0; // not to os.
char buf[1024];
strcpy(buf,"{projects:[");
DIR *dp;
struct dirent *ep;
dp = opendir (SRC_PATH);
if (dp != NULL) {
int first=1;
while ((ep = readdir (dp))) {
//puts (ep->d_name);
if((strcmp(ep->d_name,".")!=0) && (strcmp(ep->d_name,"..")!=0) && (ep->d_type==DT_DIR)) {
char fb[32];
sprintf(fb,"%s\"%s\"",(!first? ",":""),ep->d_name);
first=0;
strcat(buf,fb);
}
}
closedir (dp);
char cnfbuf[1024];
char cnf[1060];
getConfigfile(cnfbuf);
sprintf(cnf,"],config:%s}",cnfbuf);
//puts(cnf);
strcat(buf,cnf);
} else perror ("Couldn't open the directory");
// puts(buf);
ports->send("projects",buf);
return 1;
}
int newproject(char *target,char *cmd,char *b) {
if(strcmp(target,"newproject")!=0) return 0; // not to os.
char dn[64];
char tp[64];
char cmdln[128];
strcat(strcpy(dn,SRC_PATH),cmd);
strcat(strcpy(tp,SRC_PATH),".tmpl/*");
sprintf(cmdln,"cp %s %s/",tp,dn);
mkdir(dn, 0755);
system(cmdln);
sprintf(cmdln,"{\"current\":\"%s\",\"startscript\":\"loop.js\",\"uiscript\":\"ui.js\"}",cmd);
strcat(dn,"/.project.json");
writefile(dn,cmdln);
return 1;
}
/*
webd
*/
void init() {
ports->addListener(&getfiles);
ports->addListener(&getprojects);
ports->addListener(&newproject);
ports->addListener(&savefile);
ports->addListener(&saveproject);
ports->addListener(&runscript);
ports->addListener(&jsControl);
ports->addListener(&jsDispatcher);
}
void loop() {
if(script_flag) {
call_loop();
}
}
void epilog() {
if(script_flag) {
call_epilog();
}
}
<file_sep>/README.md
# ev3webapp.js
<file_sep>/html/lib/limiter.js
/*
*
* limiter.js
*
*/
function Limiter(rate,fnc) {
this.cnt=0;
this.fnc=fnc;
this.rate=rate;
Limiter.prototype.run = function() {
if(this.cnt++ > this.rate) {
this.cnt=0;
this.fnc();
}
}
Limiter.prototype.force = function() {
this.cnt=0;
this.fnc();
}
}
<file_sep>/html/lib/power.js
/*
*
* power.js
*
*/
var Power = {
plist:["current_now","voltage_now","type"],
cnt:0,
update: function(chnl) {
msg={};
for(var i=0;i<Power.plist.length;i++) {
msg[Power.plist[i]]=System.Power.read(Power.plist[i]);
}
Msg.send("power",JSON.stringify(msg));
},
run: function() {
if(Power.cnt++ > 15) {
Power.cnt=0;
Power.update();
}
}
}
<file_sep>/Makefile
C++_FLAGS = -Wall -std=gnu++11 -Ilibws++
L_FLAGS = -I/usr/local/include -lpthread -lz -lssl -lcrypto -lwebsockets
C_DEFINES =
DEPS = js.h libws++/ev3.h
OBJ = startup.o js.o libws++/libws++.a
TARGETS=webd
all: $(TARGETS) libws++/libws++.a
%.o: %.cpp $(DEPS)
g++ -c -o $@ $< $(C++_FLAGS) $(C_DEFINES)
webd: webd.o $(OBJ)
g++ -o $@ $^ $(L_FLAGS)
libws++/libws++.a: libws++/ev3.cpp libws++/server.cpp libws++/port-data.cpp libws++/ev3.h libws++/server.h
cd libws++ ; make
clean:
rm *.o $(TARGETS)
<file_sep>/js.h
/*
* js.h
*
*/
#include <vector>
#define SRC_PATH "/home/robot/ws/html/projects/"
#define LIB_PATH "/home/robot/ws/html/lib/"
#define CONFIG_PATH "/home/robot/ws/html/projects/"
#define CONFIG_FILE "/home/robot/ws/html/projects/config"
void getProject(char *buf);
extern volatile int script_flag;
class jscb {
public:
jscb(string c,string cb,v7_val_t cnx=0) : chnl(c),callback(cb),cnxt(cnx) {}
string chnl;
string callback;
v7_val_t cnxt;
};
extern vector<jscb*> jscblist;
char *loadFile(char *fn);
char *getString(struct v7 *v7,int arg);
v7_val_t mkString(char *p,int copy=0);
enum v7_err js_ev3Read(struct v7 *v7, v7_val_t *res);
enum v7_err js_ev3Write(struct v7 *v7, v7_val_t *res);
enum v7_err js_ev3Log(struct v7 *v7, v7_val_t *res);
enum v7_err js_ev3On(struct v7 *v7, v7_val_t *res);
enum v7_err js_ev3(struct v7 *v7, v7_val_t *res);
enum v7_err js_ev3Send(struct v7 *v7, v7_val_t *res);
enum v7_err js_ev3Require(struct v7 *v7, v7_val_t *res);
v7_val_t mkUtils(struct v7 *v7);
v7_val_t mkMotors(struct v7 *v7);
v7_val_t mkSensors(struct v7 *v7);
int jsControl(char *target,char *cmd,char *b);
int runscript(char *target,char *cmd,char *b);
void call_loop();
int jsDispatcher(char *target,char *cmd,char *b);
void call_epilog();
<file_sep>/html/lib/leds.js
/*
*
* leds.js
*
*/
function Led(led) {
this.led=led;
Led.prototype.set = function(v) {
this.led.write("brightness",v);
return this;
}
Led.prototype.get = function() {
return this.led.read("brightness");
}
}
System.Leds.get = function(side,clr) {
return System.Leds[side][clr];
}
<file_sep>/js.cpp
/*
*
* js.cpp
*
* Javascript objects, methods and functions.
*
*
*/
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <dirent.h>
#include <fstream>
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
#include <ev3.h>
#include <v7.h>
#include "js.h"
#define SRC_PATH "/home/robot/ws/html/projects/"
v7_val_t exec_result;
struct v7 *v7=NULL;
vector<jscb*> jscblist;
volatile int script_flag=0;
char *loadFilex(char *fn) {
string line;
string file("");
string fname(SRC_PATH);
fname.append(string(fn));
ifstream infile(fname);
if(infile.is_open()) {
while(!infile.eof()) {
getline(infile,line);
file.append(line);
file.append(string("\n"));
}
} else printf ("Couldn't open the %s file",fn);
infile.close();
size_t len=file.length();
char *p=(char*) malloc(len+1);
strcpy(p,file.c_str());
return p;
}
v7_val_t mkString(char *p,int copy) {
return v7_mk_string(v7,p, strlen(p),copy);
}
enum v7_err js_ev3Read(struct v7 *v7, v7_val_t *res) {
v7_val_t arg0 = v7_arg(v7, 0);
char *prb=(char*)v7_to_cstring(v7,&arg0);
v7_val_t this_obj = v7_get_this(v7);
Port *prt=(Port*)v7_to_foreign(v7_get(v7,this_obj,"device",~0));
char buf[256];
prt->readStr(buf,prb);
if(file_error) {
char msg[128];
sprintf(msg,"{message:\"Error reading from property %s\"}",prb);
ports->send("log",msg);
file_error=0;
}
*res = mkString(buf,true);
return V7_OK;
}
enum v7_err js_ev3Write(struct v7 *v7, v7_val_t *res) {
v7_val_t arg0 = v7_arg(v7, 0);
v7_val_t arg1 = v7_arg(v7, 1);
char prb[32];
char val[32];
double nval;
strcpy(prb,(char*)v7_to_cstring(v7,&arg0));
v7_val_t this_obj = v7_get_this(v7);
Port *prt=(Port*)v7_to_foreign(v7_get(v7,this_obj,"device",~0));
if(v7_is_number(arg1)) {
nval = v7_to_number(arg1);
if(prt->write((const char*)prb,(int)nval)==-1) {
char msg[128];
sprintf(msg,"{message:\"Error writeing to property %s\"}",prb);
ports->send("log",msg);
file_error=0;
}
}
if(v7_is_string(arg1)) {
strcpy(val,v7_to_cstring(v7, &arg1));
if(prt->write((const char*)prb,val)==-1) {
char msg[128];
sprintf(msg,"{message:\"Error writeing to property %s\"}",prb);
ports->send("log",msg);
file_error=0;
}
}
return V7_OK;
}
vector<Port*> jsportlist;
v7_val_t mkDevice(struct v7 *v7,Port *port) {
jsportlist.push_back(port);
v7_val_t obj = v7_mk_object(v7);
v7_set(v7,obj,"device",~0,v7_mk_foreign(port));
v7_val_t result=v7_set_method(v7, obj, "read", &js_ev3Read);
if(result!=0) {
ports->send("log","{message:\"Error building javascript enviorment adding read function to object.\"}");
return obj;
}
result=v7_set_method(v7, obj, "write", &js_ev3Write);
if(result!=0) {
ports->send("log","{message:\"Error building javascript enviorment adding write tunction to object.\"}");
return obj;
}
return obj;
}
v7_val_t mkDev(struct v7 *v7) {
v7_val_t mobj= v7_mk_object(v7);
v7_val_t rightleds= v7_mk_object(v7);
v7_val_t leftleds= v7_mk_object(v7);
v7_val_t leds= v7_mk_object(v7);
v7_val_t obj = mkDevice(v7,new Power());
v7_set(v7,mobj,"Power",~0,obj);
v7_val_t ledrr=mkDevice(v7,new Led("ev3:right:red:ev3dev"));
v7_set(v7,rightleds,"red",~0,ledrr);
v7_val_t ledrg=mkDevice(v7,new Led("ev3:right:green:ev3dev"));
v7_set(v7,rightleds,"green",~0,ledrg);
v7_set(v7,leds,"right",~0,rightleds);
v7_val_t ledlr=mkDevice(v7,new Led("ev3:left:red:ev3dev"));
v7_set(v7,leftleds,"red",~0,ledlr);
v7_val_t ledlg=mkDevice(v7,new Led("ev3:left:green:ev3dev"));
v7_set(v7,leftleds,"green",~0,ledlg);
v7_set(v7,leds,"left",~0,leftleds);
v7_set(v7,mobj,"Leds",~0,leds);
return mobj;
}
v7_val_t mkMotors(struct v7 *v7) {
DIR *dp;
struct dirent *ep;
v7_val_t mobj= v7_mk_object(v7);
dp = opendir ("/sys/class/tacho-motor/");
if (dp != NULL) {
while ((ep = readdir (dp))) {
if((strcmp(ep->d_name,".")!=0) && (strcmp(ep->d_name,"..")!=0)) {
string path("/sys/class/tacho-motor/");
path.append(string(ep->d_name));
v7_val_t obj = v7_mk_object(v7);
Port *mtr=new Port((char*)path.c_str());
jsportlist.push_back(mtr);
v7_set(v7,obj,"device",~0,v7_mk_foreign(mtr));
char commands[128];
mtr->readStr(commands,"commands");
v7_set(v7,obj,"commands",~0,mkString(commands,true));
char stop_commands[128];
mtr->readStr(stop_commands,"stop_commands");
v7_set(v7,obj,"stop_commands",~0,mkString(stop_commands,true));
v7_val_t result=v7_set_method(v7, obj, "read", &js_ev3Read);
if(result!=0) {
ports->send("log","{message:\"Error building javascript enviorment adding read to Motor object.\"}");
return obj;
}
result=v7_set_method(v7, obj, "write", &js_ev3Write);
if(result!=0) {
ports->send("log","{message:\"Error building javascript enviorment adding write to Motor object.\"}");
return obj;
}
v7_set(v7,mobj,mtr->address,~0,obj);
}
}
closedir (dp);
}
return mobj;
}
v7_val_t mkSensors(struct v7 *v7) {
DIR *dp;
struct dirent *ep;
v7_val_t mobj= v7_mk_object(v7);
dp = opendir ("/sys/class/lego-sensor/");
if (dp != NULL) {
while ((ep = readdir (dp))) {
if((strcmp(ep->d_name,".")!=0) && (strcmp(ep->d_name,"..")!=0)) {
string path("/sys/class/lego-sensor/");
path.append(string(ep->d_name));
v7_val_t obj = v7_mk_object(v7);
Port *snsr=new Port((char*)path.c_str());
jsportlist.push_back(snsr);
v7_set(v7,obj,"device",~0,v7_mk_foreign((void*)snsr));
char modes[128];
snsr->readStr(modes,"modes");
int values=snsr->readInt("num_values");
v7_set(v7,obj,"modes",~0,mkString(modes,true));
v7_set(v7,obj,"values",~0,v7_mk_number((double)values));
v7_val_t result=v7_set_method(v7, obj, "read", &js_ev3Read);
if(result!=0) {
ports->send("log","{message:\"Error building javascript enviorment adding read to Sensor object.\"}");
return obj;
}
result=v7_set_method(v7, obj, "write", &js_ev3Write);
if(result!=0) {
ports->send("log","{message:\"Error building javascript enviorment adding write to Sensor object.\"}");
return obj;
}
v7_set(v7,mobj,snsr->address,~0,obj);
}
}
closedir (dp);
}
return mobj;
}
enum v7_err js_ev3Log(struct v7 *v7, v7_val_t *res) {
enum v7_err rcode = V7_OK;
v7_val_t arg0 = v7_arg(v7, 0);
char msg[1024];
char buf[1024];
strcpy(msg,(char*)v7_to_cstring(v7,&arg0));
sprintf(buf,"{message:\"%s\"}",msg);
ports->send("log",buf);
return rcode;
}
enum v7_err js_ev3Send(struct v7 *v7, v7_val_t *res) {
enum v7_err rcode = V7_OK;
v7_val_t arg0 = v7_arg(v7, 0);
v7_val_t arg1 = v7_arg(v7, 1);
char c[32];
char m[1024];
strcpy(m,(char*)v7_to_cstring(v7,&arg1));
strcpy(c,(char*)v7_to_cstring(v7,&arg0));
//printf("Send %s = %s\n",c,m);
ports->send(c,m);
return rcode;
}
enum v7_err js_ev3Lib(struct v7 *v7, v7_val_t *res) {
enum v7_err rcode = V7_OK;
v7_val_t arg0 = v7_arg(v7, 0);
char p[1024];
strcpy(p,(char*)v7_to_cstring(v7,&arg0));
char fn[256];
v7_val_t result;
strcat(strcpy(fn,LIB_PATH),p);
rcode=v7_exec_file(v7, fn, &result);
if (rcode != V7_OK) {
char sbuf[256];
sprintf(sbuf,"{message:\"%s in file %s\"}",v7_get_parser_error(v7),p);
ports->send("log",sbuf);
sprintf(sbuf,"Evaluation error in file %s",p);
v7_print_error(stderr, v7, (const char*)sbuf, result);
return rcode;
}
return V7_OK;
}
enum v7_err js_ev3Require(struct v7 *v7, v7_val_t *res) {
enum v7_err rcode = V7_OK;
v7_val_t arg0 = v7_arg(v7, 0);
char p[1024];
strcpy(p,(char*)v7_to_cstring(v7,&arg0));
char fn[256];
v7_val_t result;
char prj[32];
getProject(prj);
strcat(strcat(strcat(strcpy(fn,SRC_PATH),prj),"/"),p);
rcode=v7_exec_file(v7, fn, &result);
if (rcode != V7_OK) {
char sbuf[256];
sprintf(sbuf,"{message:\"%s in file %s\"}",v7_get_parser_error(v7),p);
ports->send("log",sbuf);
sprintf(sbuf,"Evaluation error in file %s",p);
v7_print_error(stderr, v7, (const char*)sbuf, result);
return rcode;
}
return V7_OK;
}
enum v7_err js_ev3On(struct v7 *v7, v7_val_t *res) {
v7_val_t arg0 = v7_arg(v7, 0);
v7_val_t arg1 = v7_arg(v7, 1);
v7_val_t arg2 = v7_arg(v7, 2);
char c[32];
strcpy(c,(char*)v7_to_cstring(v7,&arg0));
char cb[32];
strcpy(cb,(char*)v7_to_cstring(v7,&arg1));
jscblist.push_back(new jscb(string(c),string(cb),arg2));
return V7_OK;
}
v7_val_t mkUtils(struct v7 *v7) {
v7_val_t obj= v7_mk_object(v7);
v7_val_t result=v7_set_method(v7, obj, "log", &js_ev3Log);
if(result!=0) {
ports->send("log","{message:\"Error building javascript enviorment adding log to Msg object.\"}");
return obj;
}
result=v7_set_method(v7, obj, "send", &js_ev3Send);
if(result!=0) {
ports->send("log","{message:\"Error building javascript enviorment adding send to Msg object.\"}");
return obj;
}
result=v7_set_method(v7, obj, "on", &js_ev3On);
if(result!=0) {
ports->send("log","{message:\"Error building javascript enviorment adding on to Msg object.\"}");
return obj;
}
return obj;
}
int jsDispatcher(char *target,char *cmd,char *b) {
enum v7_err rcode = V7_OK;
v7_val_t func,args;
int done=0;
vector<jscb*>::iterator v = jscblist.begin();
while(v!=jscblist.end()) {
jscb *jcb=*v;
if(strcmp(jcb->chnl.c_str(),target)==0) {
done=1;
func = v7_get(v7, jcb->cnxt ,jcb->callback.c_str() , ~0);
args = v7_mk_array(v7);
v7_array_push(v7, args, v7_mk_string(v7,cmd,~0,1));
rcode = v7_apply(v7, func,v7_is_undefined(jcb->cnxt) ? v7_get_global(v7) : jcb->cnxt, args, &exec_result);
if(rcode!=V7_OK) {
char sbuf[256];
sprintf(sbuf,"{message:\"%s\"}",v7_get_parser_error(v7));
ports->send("log",sbuf);
v7_print_error(stderr, v7, "Evaluation error", exec_result);
}
}
v++;
}
return done;
}
int jsControl(char *target,char *cmd,char *b) {
if(strcmp(target,"jscontrol")!=0) return 0; // not to os.
if((strcmp(cmd,"pause")==0) && (script_flag)) {
script_flag=0;
return 1;
}
if((strcmp(cmd,"resume")==0) && (v7!=NULL)) {
script_flag=1;
return 1;
}
if((strcmp(cmd,"stop")==0) && (v7!=NULL)) {
call_epilog();
v7_destroy(v7);
v7=NULL;
script_flag=0;
return 1;
}
return 1;
}
int runscript(char *target,char *cmd,char *b) {
if(strcmp(target,"runscript")!=0) return 0; // not to os.
enum v7_err rcode = V7_OK;
for(auto v=jscblist.begin();v!=jscblist.end();v++) {
delete *v;
}
jscblist.clear();
if(v7!=NULL) {
for(auto dev = jsportlist.begin();dev != jsportlist.end(); dev++) {
delete *dev;
}
jsportlist.clear();
v7_destroy(v7);
v7=NULL;
if(script_flag) {
script_flag=0;
}
}
v7_val_t result;
v7 = v7_create();
v7_val_t mtr=mkMotors(v7);
result=v7_set(v7,v7_get_global(v7),"Motors",~0,mtr);
v7_val_t snsr=mkSensors(v7);
result=v7_set(v7,v7_get_global(v7),"Sensors",~0,snsr);
v7_val_t utils=mkUtils(v7);
result=v7_set(v7,v7_get_global(v7),"Msg",~0,utils);
v7_val_t dev=mkDev(v7);
result=v7_set(v7,v7_get_global(v7),"System",~0,dev);
result=v7_set_method(v7, v7_get_global(v7), "lib", &js_ev3Lib);
result=v7_set_method(v7, v7_get_global(v7), "require", &js_ev3Require);
char fn[128];
strcat(strcpy(fn,SRC_PATH),cmd);
rcode=v7_exec_file(v7, fn, &result);
if (rcode != V7_OK) {
char sbuf[256];
sprintf(sbuf,"{message:\"%s\"}",v7_get_parser_error(v7));
ports->send("log",sbuf);
v7_print_error(stderr, v7, "Evaluation error", result);
v7_destroy(v7);
v7=NULL;
return 1;
}
script_flag=1;
return 1;
}
void call_loop() {
enum v7_err rcode = V7_OK;
v7_val_t func;
func = v7_get(v7, v7_get_global(v7), "loop", ~0);
//puts("Before loop");
rcode = v7_apply(v7, func, v7_mk_undefined(), v7_mk_undefined(), &exec_result);
//puts("After loop");
if (rcode != V7_OK) {
char sbuf[256];
sprintf(sbuf,"{message:\"%s\"}",v7_get_parser_error(v7));
ports->send("log",sbuf);
v7_print_error(stderr, v7, "Evaluation error", exec_result);
script_flag=0;
}
v7_gc(v7,1);
}
void call_epilog() {
enum v7_err rcode = V7_OK;
v7_val_t func;
func = v7_get(v7, v7_get_global(v7), "epilog", ~0);
if(v7_is_undefined(func)==0) {
rcode = v7_apply(v7, func, v7_mk_undefined(), v7_mk_undefined(), &exec_result);
if (rcode != V7_OK) {
char sbuf[256];
sprintf(sbuf,"{message:\"%s\"}",v7_get_parser_error(v7));
ports->send("log",sbuf);
v7_print_error(stderr, v7, "Evaluation error", exec_result);
script_flag=0;
}
}
}
<file_sep>/libws++/server-http.cpp
/*
* libwebsockets-test-server - libwebsockets test implementation
*
* Copyright (C) 2010-2015 <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:
* version 2.1 of the License.
*
* 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.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
#include "server.h"
/*
* This demo server shows how to use libwebsockets for one or more
* websocket protocols in the same server
*
* It defines the following websocket protocols:
*
* dumb-increment-protocol: once the socket is opened, an incrementing
* ascii string is sent down it every 50ms.
* If you send "reset\n" on the websocket, then
* the incrementing number is reset to 0.
*
* lws-mirror-protocol: copies any received packet to every connection also
* using this protocol, including the sender
*/
enum demo_protocols {
/* always first */
PROTOCOL_HTTP = 0,
PROTOCOL_DUMB_INCREMENT,
PROTOCOL_LWS_MIRROR,
/* always last */
DEMO_PROTOCOL_COUNT
};
/*
* We take a strict whitelist approach to stop ../ attacks
*/
struct serveable {
const char *urlpath;
const char *mimetype;
};
/*
* this is just an example of parsing handshake headers, you don't need this
* in your code unless you will filter allowing connections by the header
* content
*/
void
dump_handshake_info(struct lws *wsi)
{
int n = 0;
unsigned int len;
char buf[256];
const unsigned char *c;
do {
c = lws_token_to_string((lws_token_indexes)n);
if (!c) {
n++;
continue;
}
len = lws_hdr_total_length(wsi,(lws_token_indexes)n);
if (!len || len > sizeof(buf) - 1) {
n++;
continue;
}
lws_hdr_copy(wsi, buf, sizeof buf, (lws_token_indexes)n);
buf[sizeof(buf) - 1] = '\0';
fprintf(stderr, " %s = %s\n", (char *)c, buf);
n++;
} while (c);
}
const char * get_mimetype(const char *file)
{
int n = strlen(file);
if (n < 5)
return NULL;
if (!strcmp(&file[n - 4], ".ico"))
return "image/x-icon";
if (!strcmp(&file[n - 4], ".png"))
return "image/png";
if (!strcmp(&file[n - 4], ".gif"))
return "image/gif";
if (!strcmp(&file[n - 3], ".js"))
return "text/javascript";
if (!strcmp(&file[n - 5], ".html"))
return "text/html";
return NULL;
}
/* this protocol server (always the first one) handles HTTP,
*
* Some misc callbacks that aren't associated with a protocol also turn up only
* here on the first protocol server.
*/
int callback_http(struct lws *wsi, enum lws_callback_reasons reason, void *user,
void *in, size_t len)
{
struct per_session_data__http *pss =
(struct per_session_data__http *)user;
static unsigned char buffer[4096];
unsigned long amount, file_len=0;
char leaf_path[1024];
const char *mimetype;
char *other_headers;
unsigned char *end;
struct timeval tv;
unsigned char *p;
char buf[256];
char b64[64];
int n, m;
#ifdef EXTERNAL_POLL
struct lws_pollargs *pa = (struct lws_pollargs *)in;
#endif
switch (reason) {
case LWS_CALLBACK_HTTP:
//dump_handshake_info(wsi);
puts((const char*)in);
/* Check for json "script" */
if (!strcmp((const char *)in, "/files.json")) {
p = buffer + LWS_SEND_BUFFER_PRE_PADDING;
end = p + sizeof(buffer) - LWS_SEND_BUFFER_PRE_PADDING;
if (lws_add_http_header_status(wsi, 200, &p, end))
return 1;
if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_SERVER,
(unsigned char *)"libwebsockets",
13, &p, end))
return 1;
if (lws_add_http_header_by_token(wsi,
WSI_TOKEN_HTTP_CONTENT_TYPE,
(unsigned char *)"application/json",
10, &p, end))
return 1;
if (lws_add_http_header_content_length(wsi,
file_len, &p,
end))
return 1;
if (lws_finalize_http_header(wsi, &p, end))
return 1;
/*
* send the http headers...
* this won't block since it's the first payload sent
* on the connection since it was established
* (too small for partial)
*
* Notice they are sent using LWS_WRITE_HTTP_HEADERS
* which also means you can't send body too in one step,
* this is mandated by changes in HTTP2
*/
n = lws_write(wsi, buffer + LWS_SEND_BUFFER_PRE_PADDING,
p - (buffer + LWS_SEND_BUFFER_PRE_PADDING),
LWS_WRITE_HTTP_HEADERS);
/*
* book us a LWS_CALLBACK_HTTP_WRITEABLE callback
*/
lws_callback_on_writable(wsi);
break;
}
/* dump the individual URI Arg parameters */
n = 0;
while (lws_hdr_copy_fragment(wsi, buf, sizeof(buf),
WSI_TOKEN_HTTP_URI_ARGS, n) > 0) {
lwsl_info("URI Arg %d: %s\n", ++n, buf);
}
if (len < 1) {
lws_return_http_status(wsi,
HTTP_STATUS_BAD_REQUEST, NULL);
goto try_to_reuse;
}
/* if a legal POST URL, let it continue and accept data */
if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
return 0;
/* if not, send a file the easy way */
strcpy(buf, resource_path);
if (strcmp((const char *)in, "/")) {
if (*((const char *)in) != '/')
strcat(buf, "/");
strncat(buf, (const char *)in, sizeof(buf) - strlen(resource_path));
} else /* default file to serve */
strcat(buf, "/index.html");
buf[sizeof(buf) - 1] = '\0';
/* refuse to serve files we don't understand */
mimetype = get_mimetype(buf);
if (!mimetype) {
lwsl_err("Unknown mimetype for %s\n", buf);
lws_return_http_status(wsi,
HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, NULL);
return -1;
}
/* demonstrates how to set a cookie on / */
other_headers = NULL;
n = 0;
if (!strcmp((const char *)in, "/") &&
!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
/* this isn't very unguessable but it'll do for us */
gettimeofday(&tv, NULL);
n = sprintf(b64, "test=LWS_%u_%u_COOKIE;Max-Age=360000",
(unsigned int)tv.tv_sec,
(unsigned int)tv.tv_usec);
p = (unsigned char *)leaf_path;
if (lws_add_http_header_by_name(wsi,
(unsigned char *)"set-cookie:",
(unsigned char *)b64, n, &p,
(unsigned char *)leaf_path + sizeof(leaf_path)))
return 1;
n = (char *)p - leaf_path;
other_headers = leaf_path;
}
n = lws_serve_http_file(wsi, buf, mimetype, other_headers, n);
if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
return -1; /* error or can't reuse connection: close the socket */
/*
* notice that the sending of the file completes asynchronously,
* we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
* it's done
*/
break;
case LWS_CALLBACK_HTTP_BODY:
strncpy(buf, (const char *)in, 20);
buf[20] = '\0';
if (len < 20)
buf[len] = '\0';
lwsl_notice("LWS_CALLBACK_HTTP_BODY: %s... len %d\n",
(const char *)buf, (int)len);
break;
case LWS_CALLBACK_HTTP_BODY_COMPLETION:
lwsl_notice("LWS_CALLBACK_HTTP_BODY_COMPLETION\n");
/* the whole of the sent body arrived, close or reuse the connection */
lws_return_http_status(wsi, HTTP_STATUS_OK, NULL);
goto try_to_reuse;
case LWS_CALLBACK_HTTP_FILE_COMPLETION:
goto try_to_reuse;
case LWS_CALLBACK_HTTP_WRITEABLE:
/*
* we can send more of whatever it is we were sending
*/
do {
/* we'd like the send this much */
n = sizeof(buffer) - LWS_SEND_BUFFER_PRE_PADDING;
/* but if the peer told us he wants less, we can adapt */
m = lws_get_peer_write_allowance(wsi);
/* -1 means not using a protocol that has this info */
if (m == 0)
/* right now, peer can't handle anything */
goto later;
if (m != -1 && m < n)
/* he couldn't handle that much */
n = m;
n = lws_plat_file_read(wsi, pss->fd,
&amount, buffer +
LWS_SEND_BUFFER_PRE_PADDING, n);
/* problem reading, close conn */
if (n < 0)
goto bail;
n = (int)amount;
/* sent it all, close conn */
if (n == 0)
goto flush_bail;
/*
* To support HTTP2, must take care about preamble space
*
* identification of when we send the last payload frame
* is handled by the library itself if you sent a
* content-length header
*/
m = lws_write(wsi, buffer + LWS_SEND_BUFFER_PRE_PADDING,
n, LWS_WRITE_HTTP);
if (m < 0)
/* write failed, close conn */
goto bail;
/*
* http2 won't do this
*/
if (m != n)
/* partial write, adjust */
if (lws_plat_file_seek_cur(wsi, pss->fd, m - n) ==
(unsigned long)-1)
goto bail;
if (m) /* while still active, extend timeout */
lws_set_timeout(wsi,
PENDING_TIMEOUT_HTTP_CONTENT, 5);
/* if we have indigestion, let him clear it
* before eating more */
if (lws_partial_buffered(wsi))
break;
} while (!lws_send_pipe_choked(wsi));
later:
lws_callback_on_writable(wsi);
break;
flush_bail:
/* true if still partial pending */
if (lws_partial_buffered(wsi)) {
lws_callback_on_writable(wsi);
break;
}
lws_plat_file_close(wsi, pss->fd);
goto try_to_reuse;
bail:
lws_plat_file_close(wsi, pss->fd);
return -1;
/*
* callback for confirming to continue with client IP appear in
* protocol 0 callback since no websocket protocol has been agreed
* yet. You can just ignore this if you won't filter on client IP
* since the default uhandled callback return is 0 meaning let the
* connection continue.
*/
case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
/* if we returned non-zero from here, we kill the connection */
break;
/*
* callbacks for managing the external poll() array appear in
* protocol 0 callback
*/
case LWS_CALLBACK_LOCK_POLL:
/*
* lock mutex to protect pollfd state
* called before any other POLL related callback
* if protecting wsi lifecycle change, len == 1
*/
server_lock(len);
break;
case LWS_CALLBACK_UNLOCK_POLL:
/*
* unlock mutex to protect pollfd state when
* called after any other POLL related callback
* if protecting wsi lifecycle change, len == 1
*/
server_unlock(len);
break;
#ifdef EXTERNAL_POLL
case LWS_CALLBACK_ADD_POLL_FD:
if (count_pollfds >= max_poll_elements) {
lwsl_err("LWS_CALLBACK_ADD_POLL_FD: too many sockets to track\n");
return 1;
}
fd_lookup[pa->fd] = count_pollfds;
pollfds[count_pollfds].fd = pa->fd;
pollfds[count_pollfds].events = pa->events;
pollfds[count_pollfds++].revents = 0;
break;
case LWS_CALLBACK_DEL_POLL_FD:
if (!--count_pollfds)
break;
m = fd_lookup[pa->fd];
/* have the last guy take up the vacant slot */
pollfds[m] = pollfds[count_pollfds];
fd_lookup[pollfds[count_pollfds].fd] = m;
break;
case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
pollfds[fd_lookup[pa->fd]].events = pa->events;
break;
#endif
case LWS_CALLBACK_GET_THREAD_ID:
/*
* if you will call "lws_callback_on_writable"
* from a different thread, return the caller thread ID
* here so lws can use this information to work out if it
* should signal the poll() loop to exit and restart early
*/
/* return pthread_getthreadid_np(); */
break;
default:
break;
}
return 0;
/* if we're on HTTP1.1 or 2.0, will keep the idle connection alive */
try_to_reuse:
if (lws_http_transaction_completed(wsi))
return -1;
return 0;
}
| 50ff170af16974fa220efc13533729b635719b83 | [
"JavaScript",
"Makefile",
"C++",
"Markdown"
] | 32 | C++ | drsubs/ev3webapp.js | e17267b51f973ab3db6fb3e48a2279720cc5509f | 987634a3124f8c1656bf3738e8e5b2f7718f6149 |
refs/heads/master | <repo_name>szrharrison/javascript-inheritance-patterns-lab-web-031317<file_sep>/index.js
function Point(x, y) {
this.x = x
this.y = y
}
Point.prototype.toString = function() {
return `(${this.x}, ${this.y})`
}
Point.prototype.constructor = Point
function Shape() {}
Shape.prototype.addToPlane = function(x,y) {
this.position = new Point(x,y)
}
Shape.prototype.move = function(x,y) {
this.position = new Point(x,y)
}
Shape.prototype.constructor = Shape
function Circle(r) {
this.radius = r
}
Circle.prototype = Object.create(Shape.prototype)
Circle.prototype.diameter = function() {
return this.radius * 2
}
Circle.prototype.area = function() {
return Math.PI * this.radius * this.radius
}
Circle.prototype.circumference = function() {
return Math.PI * this.diameter()
}
function Side(l) {
this.length = l
}
function Polygon(sides) {
this.sides = sides
}
Polygon.prototype = Object.create(Shape.prototype)
Polygon.prototype.perimeter = function() {
return this.sides.reduce(function(total, side) {
return total + side.length
}, 0)
}
Polygon.prototype.numberOfSides = function() {
return this.sides.length
}
function Quadrilateral(s1,s2,s3,s4) {
this.side1 = new Side(s1)
this.side2 = new Side(s2)
this.side3 = new Side(s3)
this.side4 = new Side(s4)
Polygon.call(this, [this.side1, this.side2, this.side3, this.side4])
}
Quadrilateral.prototype = Object.create(Polygon.prototype)
Quadrilateral.prototype.constructor = Quadrilateral
function Triangle(s1,s2,s3) {
this.side1 = new Side(s1)
this.side2 = new Side(s2)
this.side3 = new Side(s3)
Polygon.call(this, [this.side1, this.side2, this.side3])
}
Triangle.prototype = Object.create(Polygon.prototype)
Triangle.prototype.constructor = Triangle
function Rectangle(w,h) {
this.width = w
this.height = h
Quadrilateral.call(this, w, h, w, h)
}
Rectangle.prototype = Object.create(Quadrilateral.prototype)
Rectangle.prototype.constructor = Rectangle
Rectangle.prototype.area = function() {
return this.width * this.height
}
function Square(l) {
this.length = l
Rectangle.call(this, l, l)
}
Square.prototype = Object.create(Rectangle.prototype)
Square.prototype.constructor = Square
Square.prototype.listProperties = function() {
let props = []
for (let p in this) {
if( this.hasOwnProperty(p) ) {
props.push(p)
}
}
return props.join(', ')
}
| 819faee116769efa6fe2cd6334654323c3e4ed7d | [
"JavaScript"
] | 1 | JavaScript | szrharrison/javascript-inheritance-patterns-lab-web-031317 | fb495ad6cb8894fc9958e6765b834a448eaa2d88 | cdc4435d6f8c43f3785273c4dcaa904f6294a9a9 |
refs/heads/master | <repo_name>ekaspern/reactSamples<file_sep>/gulpfile.js
var gulp = require('gulp');
var coffee = require('gulp-coffee');
var changed = require('gulp-changed');
var paths;
paths = {
coffee: {
src: '/srcCoffee',
dest: '/src'
}
};
var coffeeCompile, coffeeCompileChanged;
coffeeCompile = function(done) {
var cb;
cb = typeof done === 'function' ? done : function() {};
gulp.src('./srcCoffee/**/*.coffee').pipe(coffee({
bare: true
})).pipe(changed('./srcCoffee')).pipe(gulp.dest('./src')).on('end', function() {
return cb();
});
return null;
};
coffeeCompileChanged = function(file) {
var destPath, sliceStart, srcPath, subPath;
sliceStart = file.path.search(paths.coffee.src) + paths.coffee.src.length;
subPath = file.path.slice(sliceStart);
srcPath = "." + paths.coffee.src + subPath;
destPath = ("." + paths.coffee.dest + subPath).split('/');
destPath.pop();
destPath = destPath.join('/');
return gulp.src(srcPath).pipe(coffee({
bare: true
})).pipe(gulp.dest(destPath)).on('end', function() {
return console.log("compiled: " + subPath);
});
};
gulp.task('coffee-watch', function(done) {
gulp.watch("srcCoffee/**/*.coffee", function(file) {
console.log(file.type + ": " + file.path);
return coffeeCompileChanged(file);
});
return coffeeCompile(done);
});
// gulp.task('default', ['coffee-watch']);
gulp.task('client-compiler', ['coffee-watch']);
// gulp.task('client-compiler', function() {
// return sequence('coffee-watch');
// });
<file_sep>/src/groceryItem.js
var GroceryItem, React, li;
React = require('react');
li = React.DOM.li;
GroceryItem = React.createClass({
displayName: 'GroceryItem',
render: function() {
var product;
product = this.props.product;
return li({
className: 'grocery-item'
}, product);
}
});
module.exports = {
c: GroceryItem,
f: React.createFactory(GroceryItem)
};
<file_sep>/README.md
This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app).
Below you will find some information on how to perform common tasks.<br>
You can find the most recent version of this guide [here](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md).
## Table of Contents
- [Updating to New Releases](#updating-to-new-releases)
- [Sending Feedback](#sending-feedback)
- [Folder Structure](#folder-structure)
- [Available Scripts](#available-scripts)
- [npm start](#npm-start)
- [npm test](#npm-test)
- [npm run build](#npm-run-build)
- [npm run eject](#npm-run-eject)
- [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor)
- [Installing a Dependency](#installing-a-dependency)
- [Importing a Component](#importing-a-component)
- [Adding a Stylesheet](#adding-a-stylesheet)
- [Post-Processing CSS](#post-processing-css)
- [Adding Images and Fonts](#adding-images-and-fonts)
- [Using the `public` Folder](#using-the-public-folder)
- [Adding Bootstrap](#adding-bootstrap)
- [Adding Flow](#adding-flow)
- [Adding Custom Environment Variables](#adding-custom-environment-variables)
- [Can I Use Decorators?](#can-i-use-decorators)
- [Integrating with a Node Backend](#integrating-with-a-node-backend)
- [Proxying API Requests in Development](#proxying-api-requests-in-development)
- [Using HTTPS in Development](#using-https-in-development)
- [Generating Dynamic `<meta>` Tags on the Server](#generating-dynamic-meta-tags-on-the-server)
- [Running Tests](#running-tests)
- [Filename Conventions](#filename-conventions)
- [Command Line Interface](#command-line-interface)
- [Version Control Integration](#version-control-integration)
- [Writing Tests](#writing-tests)
- [Testing Components](#testing-components)
- [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries)
- [Initializing Test Environment](#initializing-test-environment)
- [Focusing and Excluding Tests](#focusing-and-excluding-tests)
- [Coverage Reporting](#coverage-reporting)
- [Continuous Integration](#continuous-integration)
- [Disabling jsdom](#disabling-jsdom)
- [Experimental Snapshot Testing](#experimental-snapshot-testing)
- [Deployment](#deployment)
- [Building for Relative Paths](#building-for-relative-paths)
- [GitHub Pages](#github-pages)
- [Heroku](#heroku)
- [Modulus](#modulus)
- [Netlify](#netlify)
- [Now](#now)
- [Surge](#surge)
- [Something Missing?](#something-missing)
## Updating to New Releases
Create React App is divided into two packages:
* `create-react-app` is a global command-line utility that you use to create new projects.
* `react-scripts` is a development dependency in the generated projects (including this one).
You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`.
When you run `create-react-app`, it always creates the project with the latest version of `react-scripts` so you’ll get all the new features and improvements in newly created apps automatically.
To update an existing project to a new version of `react-scripts`, [open the changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md), find the version you’re currently on (check `package.json` in this folder if you’re not sure), and apply the migration instructions for the newer versions.
In most cases bumping the `react-scripts` version in `package.json` and running `npm install` in this folder should be enough, but it’s good to consult the [changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md) for potential breaking changes.
We commit to keeping the breaking changes minimal so you can upgrade `react-scripts` painlessly.
## Sending Feedback
We are always open to [your feedback](https://github.com/facebookincubator/create-react-app/issues).
## Folder Structure
After creation, your project should look like this:
```
my-app/
README.md
node_modules/
package.json
gulpfile.js
public/
index.html
favicon.ico
scrCoffee/
App.coffee
index.coffee
css/
index.css
App.css
images/
logo.svg
```
***** Building this App using CoffeeScript ***
Install Node.js
Need version 4 or higher
nvm install v4.0.0
https://facebook.github.io/react/docs/installation.html
Once node is installed create a new React.js application and then you can create your app - “hello-world"
npm install -g create-react-app
create-react-app hello-world
npm start
http://localhost:3000/
Install CoffeScript.js
npm install -g coffee-script
Save as a dependency
npm install --save coffee-script
Install Gulp as a task manager
sudo npm install —global gulp
npm install --save-dev gulp-install
npm install --save-dev gulp-coffee gulp-concat gulp-util
npm install --save-dev gulp-watch
npm install --save-dev gulp-changed
npm install --save-dev react browserify reactify vinyl-source-stream
Create gulpfile.js to manage tasks - need to convert CoffeeScript to JS
gulpfile.js:
var gulp = require('gulp');
var coffee = require('gulp-coffee');
var changed = require('gulp-changed');
var paths;
paths = {
coffee: {
src: '/srcCoffee',
dest: '/src'
}
};
var coffeeCompile, coffeeCompileChanged;
coffeeCompile = function(done) {
var cb;
cb = typeof done === 'function' ? done : function() {};
gulp.src('./srcCoffee/**/*.coffee').pipe(coffee({
bare: true
})).pipe(changed('./srcCoffee')).pipe(gulp.dest('./src')).on('end', function() {
return cb();
});
return null;
};
coffeeCompileChanged = function(file) {
var destPath, sliceStart, srcPath, subPath;
sliceStart = file.path.search(paths.coffee.src) + paths.coffee.src.length;
subPath = file.path.slice(sliceStart);
srcPath = "." + paths.coffee.src + subPath;
destPath = ("." + paths.coffee.dest + subPath).split('/');
destPath.pop();
destPath = destPath.join('/');
return gulp.src(srcPath).pipe(coffee({
bare: true
})).pipe(gulp.dest(destPath)).on('end', function() {
return console.log("compiled: " + subPath);
});
};
gulp.task('coffee-watch', function(done) {
gulp.watch("srcCoffee/**/*.coffee", function(file) {
console.log(file.type + ": " + file.path);
return coffeeCompileChanged(file);
});
return coffeeCompile(done);
});
gulp.task('default', ['coffee-watch']);
Now we can run gulp at the command line to convert our CoffeeScript files to JS
gulp
After we run gulp we can start the application
npm start
So we do not have to run gulp each time to compile the coffeescript add the task to the start in the package.json
scripts": {
"start": "npm run client-compiler & react-scripts start",
"client-compiler": "gulp client-compiler",...}
The client-compiler will run the coffe-watch and recompile the coffeescript if it changes.
Now we need to install delorean to use Flux
npm install --save delorean
I use lodash so install it as a dependency not just a dev dependency
npm install —save lodash
npm install —save moment
<file_sep>/src/flux/grocery_store.js
var Flux, _, moment;
Flux = require('delorean').Flux;
_ = require('lodash');
moment = require('moment');
module.exports = Flux.createStore({
actions: {
'set-grocery-stores': 'setGroceryStores',
'get-current-list': 'getCurrentList',
'set-grocery-list': 'setGroceryList'
},
scheme: {
groceryStores: {
"default": []
},
currentList: {
"default": []
},
loading: {
"default": null
}
},
setGroceryStores: function(data) {
return this.set('groceryStores', data);
},
getCurrentList: function(id) {
var groceryStores, list, store;
groceryStores = this.state.groceryStores;
store = _.find(groceryStores, {
id: id
});
list = store.products;
return this.set({
currentList: list
});
},
setGroceryList: function(options) {
var data, index;
index = options.index, data = options.data;
this.state.groceryStores[index].products = data;
return this.set({
groceryStores: this.state.groceryStores
});
}
});
<file_sep>/src/store.js
var GroceryList, React, Store, div, h2, ref;
React = require('react');
GroceryList = require('./groceryList').f;
ref = React.DOM, div = ref.div, h2 = ref.h2;
Store = React.createClass({
displayName: 'Store',
getInitialState: function() {
return {
showList: false
};
},
render: function() {
var id, name, products, showList, store;
store = this.props.store;
id = store.id, name = store.name, products = store.products;
showList = this.state.showList;
console.log("showList", showList);
return div({}, [
h2({
key: id,
className: 'store',
onClick: this.handleClick
}, name), showList ? GroceryList({
key: 'products',
className: 'products-list',
products: products
}) : void 0
]);
},
handleClick: function() {
return this.setState({
showList: true
});
}
});
module.exports = {
c: Store,
f: React.createFactory(Store)
};
<file_sep>/src/App.js
var App, Flux, Groceries, React, div, h2, ref;
React = require('react');
Flux = require('delorean').Flux;
Groceries = require('./groceries').f;
require('../css/App.css');
ref = React.DOM, div = ref.div, h2 = ref.h2;
App = React.createClass({
mixins: [Flux.mixins.storeListener],
watchStores: ['grocery'],
componentWillMount: function() {
var groceryStores;
groceryStores = [
{
id: 1,
name: 'Whole Foods',
products: ['Peanut Butter', 'Eggs', 'Yogurt']
}, {
id: 2,
name: 'Harvest Coop',
products: ['Hummus', 'Ice cream', 'Bread']
}, {
id: 3,
name: 'Trader Joes',
products: ['Potato Chips', 'Trail Mix', 'Seltzer']
}
];
this.trigger('getGroceryStores');
return this.trigger('setGroceryStores', groceryStores);
},
render: function() {
return div({
key: "app",
className: "App"
}, [
div({
key: 'app-header',
className: 'App-header'
}, "Grocery Lists"), Groceries({
key: 'stores'
})
]);
}
});
module.exports = {
c: App,
f: React.createFactory(App)
};
<file_sep>/src/grocery.js
var Grocery, GroceryList, React, div, h2, ref;
React = require('react');
GroceryList = require('./groceryList').f;
ref = React.DOM, div = ref.div, h2 = ref.h2;
Grocery = React.createClass({
displayName: 'Grocery',
getInitialState: function() {
return {
showList: false
};
},
render: function() {
var id, name, products, showList, store;
store = this.props.store;
console.log("store", store);
id = store.id, name = store.name, products = store.products;
showList = this.state.showList;
return div({}, [
h2({
key: id,
className: 'store',
onClick: this.handleClick
}, name), showList ? GroceryList({
key: 'products',
className: 'products-list',
products: products
}) : void 0
]);
},
handleClick: function() {
var handleStoreClick, id, ref1, store;
ref1 = this.props, handleStoreClick = ref1.handleStoreClick, store = ref1.store;
id = store.id;
console.log("id", id);
handleStoreClick(id);
return this.setState({
showList: true
});
}
});
module.exports = {
c: Grocery,
f: React.createFactory(Grocery)
};
<file_sep>/src/stores.js
var React, Store, Stores, div;
React = require('react');
Store = require('./store').f;
div = React.DOM.div;
Stores = React.createClass({
displayName: 'Stores',
getInitialState: function() {
return {
groceryStores: [
{
id: 1,
name: 'Whole Foods',
products: ['Peanut Butter', 'Eggs', 'Yogurt']
}, {
id: 2,
name: 'Harvest Coop',
products: ['Hummus', 'Ice cream', 'Bread']
}, {
id: 3,
name: 'Trader Joes',
products: ['Potato Chips', 'Trail Mix', 'Seltzer']
}
]
};
},
render: function() {
var groceryStores, i, id, len, store, stores;
groceryStores = this.state.groceryStores;
stores = [];
for (i = 0, len = groceryStores.length; i < len; i++) {
store = groceryStores[i];
id = store.id;
console.log("store", store);
stores.push(Store({
key: id,
store: store
}));
}
return div({
key: "list"
}, stores);
}
});
module.exports = {
c: Stores,
f: React.createFactory(Stores)
};
<file_sep>/src/utilities/server_request.js
var Request,
indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
module.exports = Request = (function() {
Request.prototype.defaults = {
url: '',
method: 'GET',
timeout: 105000,
data: {},
headers: null,
success: null,
error: null,
onTimeout: null,
authenticate: true,
responseType: null,
requestName: null,
contentType: null
};
function Request(options) {
var k, ref, state, v;
this.options = options;
state = 'pending';
ref = this.defaults;
for (k in ref) {
v = ref[k];
if (this.options[k] === void 0) {
this.options[k] = this.defaults[k];
}
}
this.authToken = '';
this.start();
}
Request.prototype.done = function(doneCB) {
this.doneCB = doneCB;
return this;
};
Request.prototype.then = function(thenCB) {
this.thenCB = thenCB;
return this;
};
Request.prototype.finished = function(finishedCB) {
this.finishedCB = finishedCB;
return this;
};
Request.prototype.error = function(errorCB) {
this.errorCB = errorCB;
return this;
};
Request.prototype.abort = function() {
var ref;
this.doneCB = null;
this.thenCB = null;
this.finishedCB = null;
this.errorCB = null;
return (ref = this.xmlHttp) != null ? ref.abort() : void 0;
};
Request.prototype.start = function() {
var authenticate, binaryResponse, contentType, data, endpoint, error, headers, k, method, onTimeout, payload, ref, requestName, requestTimer, responseType, success, timeout, url, v;
ref = this.options, method = ref.method, data = ref.data, headers = ref.headers, url = ref.url, timeout = ref.timeout, onTimeout = ref.onTimeout, error = ref.error, success = ref.success, requestName = ref.requestName, authenticate = ref.authenticate, responseType = ref.responseType, contentType = ref.contentType;
endpoint = url + this.makeQueryParam();
binaryResponse = responseType === 'blob';
this.xmlHttp = new XMLHttpRequest();
this.xmlHttp.open(method, endpoint, true);
if (responseType) {
this.xmlHttp.responseType = responseType;
}
if (contentType != null) {
this.xmlHttp.setRequestHeader("Content-type", contentType);
} else {
this.xmlHttp.setRequestHeader("Content-type", "application/json");
}
this.xmlHttp.setRequestHeader("Accept", "application/json, text/javascript, */*; q=0.01");
this.xmlHttp.setRequestHeader("Accept-Language", "en-us, en;");
if (authenticate) {
this.xmlHttp.setRequestHeader("authToken", this.authToken);
}
for (k in headers) {
v = headers[k];
this.xmlHttp.setRequestHeader(k, v);
}
requestTimer = setTimeout((function(_this) {
return function() {
if (typeof _this.finishedCB === "function") {
_this.finishedCB("timeout", _this.xmlHttp);
}
if (typeof _this.errorCB === "function") {
_this.errorCB("timeout", _this.xmlHttp);
}
_this.abort();
return typeof onTimeout === "function" ? onTimeout() : void 0;
};
})(this), timeout);
this.xmlHttp.onreadystatechange = (function(_this) {
return function() {
var alert, e, responseData, status;
if (_this.xmlHttp.readyState === 4) {
clearTimeout(requestTimer);
try {
responseData = binaryResponse ? _this.xmlHttp.response : JSON.parse(_this.xmlHttp.responseText);
} catch (error1) {
e = error1;
responseData = _this.xmlHttp.responseText || null;
}
status = +_this.xmlHttp.status;
if (status > 399 || status === 0) {
if (typeof error === "function") {
error(_this.xmlHttp.status, _this.xmlHttp, responseData);
}
if (typeof _this.errorCB === "function") {
_this.errorCB(_this.xmlHttp.status, _this.xmlHttp, responseData);
}
if (status === 401 || status === 503) {
alert = {
isAlert: true
};
if (_this.xmlHttp.status === 401) {
alert.message = 'Error';
}
if (_this.xmlHttp.status === 503) {
alert.message = 'Error';
}
}
return typeof _this.finishedCB === "function" ? _this.finishedCB() : void 0;
}
}
};
})(this);
payload = (contentType === 'text/plain' ? data : JSON.stringify(data));
if (method === 'PUT' || method === 'POST') {
this.xmlHttp.send(payload);
} else {
this.xmlHttp.send();
}
return this;
};
Request.prototype.makeQueryParam = function() {
var data, divider, i, k, method, ref, rv, url, v;
ref = this.options, data = ref.data, url = ref.url, method = ref.method;
if (method !== 'GET') {
return '';
}
rv = indexOf.call(url, '?') >= 0 ? '' : '?';
i = 0;
for (k in data) {
v = data[k];
if (!(v !== '' && (v != null))) {
continue;
}
rv += i === 0 ? '' : '&';
rv += k + "=" + (encodeURIComponent(v));
i++;
}
divider = rv === '?' ? '' : '&';
rv += divider + "_=" + (new Date().getTime());
return rv;
};
return Request;
})();
<file_sep>/src/shoppingList.js
var GroceryItem, React, ShoppingList, div, ref, ul;
React = require('react');
GroceryItem = require('./groceryItem').f;
ref = React.DOM, div = ref.div, ul = ref.ul;
ShoppingList = React.createClass({
displayName: 'ShoppingList',
getInitialState: function() {
return {
items: ['Peanut Butter', 'Eggs', 'Yogurt']
};
},
render: function() {
var i, item, items, len, list;
items = this.state.items;
list = [];
for (i = 0, len = items.length; i < len; i++) {
item = items[i];
list.push(GroceryItem({
key: item,
product: item
}));
}
return div({
key: "list"
}, ul({
className: 'shopping-list'
}, list));
}
});
module.exports = {
c: ShoppingList,
f: React.createFactory(ShoppingList)
};
<file_sep>/srcOld/shoppingList.js
import React from 'react';
import GroceryItem from './groceryItem.js'
class ShoppingList extends React.Component {
constructor() {
super();
this.state = {
items: ['Peanut Butter', 'Eggs', 'Yogurt'],
};
}
render() {
return (
<div className="shopping-list">
<h1>Shopping List for {this.props.name}</h1>
<ul>
{this.state.items.map(function(item, i){
return <GroceryItem item={item} key={i} />;
})}
</ul>
</div>
);
}
}
export default ShoppingList;<file_sep>/src/index.js
var App, React, ReactDOM, dispatcher;
React = require('react');
ReactDOM = require('react-dom');
App = require('./App').f;
dispatcher = require('./dispatcher');
ReactDOM.render(React.createElement(App), document.getElementById('root'));
| 7e4587fb1f2d888d658152a37fdb7e3578427723 | [
"JavaScript",
"Markdown"
] | 12 | JavaScript | ekaspern/reactSamples | d1469348b56c5c3c92e716f9e3556f5ab2df5aaa | 0b68386cb5f7badcaa9b15f24aa96962c772d71f |
refs/heads/master | <repo_name>Kush28/CosmoAir-1.0<file_sep>/src/FinalSetterGetter.java
/**
*
* @author ProgJazz
*/
public class FinalSetterGetter {
public String depSilk, arrSilk, arrSpice, depSpice, intermediate, totalTime, via, spiceFlightNo, silkFlightNo;
//Final Setter Methods...
public void setSilkFlightNo(String flightNo) {
silkFlightNo= flightNo;
}
public void setSpiceFlightNo(String flightNo) {
spiceFlightNo= flightNo;
}
public void setIntermediate(String inter) {
intermediate= inter;
}
public void setDuration(String time) {
totalTime= time;
}
public void setVia(String via) {
this.via = via;
}
public void setDeptSilk(String depTime) {
this.depSilk = depTime;
}
public void setArrSilk(String arrTime) {
this.arrSilk= arrTime;
}
public void setDeptSpice(String depTime) {
this.depSpice = depTime;
}
public void setArrSpice(String arrTime) {
this.arrSpice= arrTime;
}
//Final Getter Methods...
public String getSilkFlightNo() {
return(silkFlightNo);
}
public String getSpiceFlightNo() {
return(spiceFlightNo);
}
public String getIntermediate() {
return(intermediate);
}
public String getDuration(){
return(totalTime);
}
public String getVia() {
return(via );
}
public String getDeptSilk() {
return(depSilk);
}
public String getArrSilk() {
return(arrSilk);
}
public String getDeptSpice() {
return(depSpice) ;
}
public String getArrSpice() {
return(arrSpice);
}
}
<file_sep>/src/Flight.java
/**
*
* @author ProgJazz
*/
public class Flight {
private String flightNo, source, destination, halt, depTime, arrTime;
boolean days[] = new boolean[8];
int seats;
//Setter Methods...
public void setFlightNo(String flightNo){
this.flightNo = flightNo;
}
public void setSource(String source){
this.source = source;
}
public void setDestination(String dest){
destination = dest;
}
public void setVia(String halt){
this.halt = halt;
}
public void setDepTime(String depTime){
this.depTime = depTime;
}
public void setArrTime(String arrTime){
this.arrTime = arrTime;
}
public void setDays(int day, boolean check) {
days[day] = check;
}
//Getter Methods...
public String getFlightNo(){
return flightNo;
}
public String getSource(){
return source;
}
public String getDestination(){
return destination;
}
public String getVia(){
return this.halt;
}
public String getDepTime(){
return this.depTime;
}
public String getArrTime(){
return this.arrTime;
}
public boolean getFrequency(int i) {
return days[i];
}
public int getCapacity() {
return seats;
}
}
<file_sep>/src/CombinedFlight.java
/**
*
* @author ProgJazz
*/
import java.io.*;
public class CombinedFlight extends FinalSetterGetter {
int flightCount, seats = 0;
BufferedReader br;
FileReader fr;
final int timeDiffSingapore = 150; //Singapore Time Difference 150 Minute...
//Time Difference Calculator and Checking...
public static int timeDifference(int arrHour, int arrMinute, int depHour, int depMinute) {
int diff;
if (depHour < arrHour)
diff = ((depHour + 24) - arrHour) * 60;
else
diff = (depHour - arrHour) * 60;
return (diff + (depMinute - arrMinute));
}
//Modified Constructor...
CombinedFlight(String source, int spiceDay, int silkDay) throws IOException {
int i, j;
SilkAirSchedule silkAir = new SilkAirSchedule();
SpiceJetSchedule spiceJet = new SpiceJetSchedule();
for (i=0;i<spiceJet.spiceSize;i++) {
if (spiceJet.flights[i].getSource().compareTo(source) == 0 && spiceJet.flights[i].getFrequency(spiceDay)) {
for (j=0;j<silkAir.silkSize;j++) {
String silkSource = silkAir.flights[j].getSource();
int depHour = silkAir.getHour(j, 0);
int depMinute = silkAir.getMinute(j, 0);
String spiceDest = spiceJet.flights[i].getDestination();
int arrHour = spiceJet.getHour(i, 1);
int arrMinute = spiceJet.getMinute(i, 1);
if (spiceDest.compareTo(silkSource.substring(0,silkSource.lastIndexOf("(")-1).toUpperCase().trim()) == 0) {
if (silkAir.flights[j].getFrequency(silkDay)) {
int timeDifference = timeDifference(arrHour, arrMinute, depHour, depMinute);
if (timeDifference >= 120 && timeDifference <= 360) {
flightCount++;} } } } } } }
//Sorting Flights according to Flight Durations...
public void sortFlights(int flightDuration[], CombinedFlight flight[]) {
int i, j, k;
CombinedFlight temp;
for (i=0;i<flightCount-1;i++) {
for (j=i+1;j<flightCount;j++) {
if (flightDuration[i] > flightDuration[j]) {
//Swapping Durations...
k = flightDuration[j];
flightDuration[j] = flightDuration[i];
flightDuration[i] = k;
//Swapping Flights...
temp = flight[j];
flight[j] = flight[i];
flight[i] = temp; } } } }
//THE THOR METHOD...GRRR...I AM THOR...THE LEGENDARY GUARDIAN OF ASGUARD...SON OF ODIN...LORD OF THE VIKINGS...
public CombinedFlight[] combine(String source,int spiceDay,int silkDay) throws IOException {
int i, j, totalDuration;
SilkAirSchedule silkAir = new SilkAirSchedule();
SpiceJetSchedule spiceJet = new SpiceJetSchedule();
int duration[] = new int[flightCount];
CombinedFlight flightCombo[] = new CombinedFlight[flightCount];
for(i=0;i<flightCount;i++)
flightCombo[i] = new CombinedFlight(source, spiceDay, silkDay);
int current = 0;
for(i=0;i<spiceJet.spiceSize;i++) {
if(spiceJet.flights[i].getSource().compareTo(source) == 0 && spiceJet.flights[i].getFrequency(spiceDay)) {
for(j=0;j<silkAir.silkSize;j++) {
String silkSource=silkAir.flights[j].getSource();
int depTimeHr = silkAir.getHour(j, 0);
int depTimeMin = silkAir.getMinute(j, 0);
String spiceDest = spiceJet.flights[i].getDestination();
spiceDest = spiceDest.trim();
int arrTimeHr = spiceJet.getHour(i, 1);
int arrTimeMin = spiceJet.getMinute(i, 1);
if(spiceDest.compareTo(silkSource.substring(0,silkSource.lastIndexOf("(") - 1).toUpperCase().trim()) == 0 ) {
if(silkAir.flights[j].getFrequency(silkDay)) {
int time = timeDifference(arrTimeHr, arrTimeMin, depTimeHr, depTimeMin);
if(time >= 120 && time <= 360) {
if (seats < 15) {
flightCombo[current].setDeptSpice(spiceJet.flights[i].getDepTime());
flightCombo[current].setSpiceFlightNo(spiceJet.flights[i].getFlightNo());
flightCombo[current].setArrSpice(spiceJet.flights[i].getArrTime());
flightCombo[current].setIntermediate(spiceDest);
flightCombo[current].setVia(spiceJet.flights[i].getVia());
flightCombo[current].setDeptSilk(timeConverter(silkAir.flights[j].getDepTime()));
flightCombo[current].setSilkFlightNo(silkAir.flights[j].getFlightNo());
flightCombo[current].setArrSilk(timeConverter(silkAir.flights[j].getArrTime()));
totalDuration = timeDifference(spiceJet.getHour(i, 0), spiceJet.getMinute(i, 0), silkAir.getHour(j, 1), silkAir.getMinute(j, 1)) - timeDiffSingapore;
duration[current] = totalDuration;
flightCombo[current].setDuration(Integer.toString(totalDuration / 60) + "Hours " + Integer.toString(totalDuration % 60) + " Minutes");
current++; } } } } } } }
sortFlights(duration, flightCombo);
return flightCombo;
}
//String to Time Converter...
String timeConverter(String time) {
String timeVar;
String hour = time.substring(0, 2);
String minute = time.substring(2, 4);
if (Integer.parseInt(hour) > 12)
timeVar = Integer.parseInt(hour) - 12 + ":" + minute + " PM";
else
timeVar = hour+ ":" + minute + " AM";
if(time.contains("+"))
timeVar += "(+1)";
return timeVar;
}
}<file_sep>/src/ConfirmSlip.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author ProgJazz and <NAME>
*/
import java.io.*;
import java.util.StringTokenizer;
import javax.swing.Icon;
import javax.swing.ImageIcon;
public class ConfirmSlip extends javax.swing.JFrame {
/**
* Creates new form ConfirmSlip
*/
public ConfirmSlip(CustomerDetails obj) {
initComponents();
Icon img=new ImageIcon("Images\\Bigcontentmediamainpix_700x396.jpg");
jLabel27.setIcon(img);
jLabel22.setText(obj.name);
jLabel23.setText(obj.eMail);
jLabel24.setText(obj.pass);
jLabel11.setText(obj.spice);
jLabel12.setText(obj.silk);
jLabel5.setText(obj.source);
jLabel21.setText(obj.sourceTime);
jLabel20.setText(obj.desTime);
jLabel19.setText(String.valueOf(obj.d) + " OCT");
jLabel18.setText(String.valueOf(obj.a) + " OCT");
try {
BufferedReader br = new BufferedReader(new FileReader("Files/PassengerDatabase.csv"));
String line;
while ((line = br.readLine()) != null) {
StringTokenizer str = new StringTokenizer(line, "|");
jLabel26.setText(String.valueOf((Integer.parseInt(str.nextToken()))));
}
}
catch(IOException e) {
System.out.println("File cannot be read...");
}
}
/**
* 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();
jLabel23 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel24 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel25 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel26 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
jLabel15 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
jLabel17 = new javax.swing.JLabel();
jLabel18 = new javax.swing.JLabel();
jLabel19 = new javax.swing.JLabel();
jLabel20 = new javax.swing.JLabel();
jLabel21 = new javax.swing.JLabel();
jLabel22 = new javax.swing.JLabel();
jLabel28 = new javax.swing.JLabel();
jLabel27 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
jLabel1.setFont(new java.awt.Font("Nirmala UI Semilight", 1, 24)); // NOI18N
jLabel1.setForeground(new java.awt.Color(0, 51, 51));
jLabel1.setText("Booking Confirmation");
getContentPane().add(jLabel1);
jLabel1.setBounds(160, 10, 300, 40);
jLabel23.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel23.setText("N");
getContentPane().add(jLabel23);
jLabel23.setBounds(230, 110, 316, 25);
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel2.setForeground(new java.awt.Color(0, 51, 51));
jLabel2.setText("Name:");
getContentPane().add(jLabel2);
jLabel2.setBounds(70, 70, 50, 25);
jLabel24.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel24.setText("N");
getContentPane().add(jLabel24);
jLabel24.setBounds(230, 190, 316, 25);
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel3.setForeground(new java.awt.Color(0, 51, 51));
jLabel3.setText("Email Id:");
getContentPane().add(jLabel3);
jLabel3.setBounds(70, 110, 70, 25);
jLabel25.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel25.setForeground(new java.awt.Color(0, 51, 51));
jLabel25.setText("Number of Passenger:");
getContentPane().add(jLabel25);
jLabel25.setBounds(67, 188, 160, 25);
jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel4.setForeground(new java.awt.Color(0, 51, 51));
jLabel4.setText("Booking Id:");
getContentPane().add(jLabel4);
jLabel4.setBounds(70, 150, 90, 25);
jLabel26.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel26.setText("N");
getContentPane().add(jLabel26);
jLabel26.setBounds(230, 150, 316, 25);
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel5.setText("1");
getContentPane().add(jLabel5);
jLabel5.setBounds(164, 293, 77, 25);
jLabel6.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel6.setForeground(new java.awt.Color(0, 51, 51));
jLabel6.setText("SilkAir:");
getContentPane().add(jLabel6);
jLabel6.setBounds(330, 250, 60, 25);
jLabel7.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel7.setForeground(new java.awt.Color(0, 51, 51));
jLabel7.setText("Destination:");
getContentPane().add(jLabel7);
jLabel7.setBounds(330, 290, 90, 25);
jLabel8.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel8.setText("Singapore");
getContentPane().add(jLabel8);
jLabel8.setBounds(430, 290, 77, 25);
jLabel9.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel9.setForeground(new java.awt.Color(0, 51, 51));
jLabel9.setText("SpiceJet:");
getContentPane().add(jLabel9);
jLabel9.setBounds(67, 250, 70, 25);
jLabel10.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel10.setForeground(new java.awt.Color(0, 51, 51));
jLabel10.setText("Source:");
getContentPane().add(jLabel10);
jLabel10.setBounds(67, 293, 60, 25);
jLabel11.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel11.setText("1");
getContentPane().add(jLabel11);
jLabel11.setBounds(164, 250, 70, 25);
jLabel12.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel12.setText("2");
getContentPane().add(jLabel12);
jLabel12.setBounds(430, 250, 60, 25);
jLabel13.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel13.setForeground(new java.awt.Color(0, 51, 51));
jLabel13.setText("Time:");
getContentPane().add(jLabel13);
jLabel13.setBounds(330, 330, 40, 25);
jLabel14.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel14.setForeground(new java.awt.Color(0, 51, 51));
jLabel14.setText("Dep. Date: ");
getContentPane().add(jLabel14);
jLabel14.setBounds(67, 336, 80, 25);
jLabel15.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel15.setForeground(new java.awt.Color(0, 51, 51));
jLabel15.setText("Arrival Date: ");
getContentPane().add(jLabel15);
jLabel15.setBounds(67, 372, 90, 25);
jLabel16.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel16.setForeground(new java.awt.Color(0, 51, 51));
jLabel16.setText("Time:");
getContentPane().add(jLabel16);
jLabel16.setBounds(329, 372, 40, 25);
jLabel17.setFont(new java.awt.Font("Showcard Gothic", 0, 17)); // NOI18N
jLabel17.setForeground(new java.awt.Color(0, 51, 51));
jLabel17.setText("<NAME>");
getContentPane().add(jLabel17);
jLabel17.setBounds(250, 410, 100, 25);
jLabel18.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel18.setText("1");
getContentPane().add(jLabel18);
jLabel18.setBounds(164, 372, 77, 25);
jLabel19.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel19.setText("1");
getContentPane().add(jLabel19);
jLabel19.setBounds(164, 336, 77, 25);
jLabel20.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel20.setText("2");
getContentPane().add(jLabel20);
jLabel20.setBounds(430, 370, 130, 25);
jLabel21.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel21.setText("2");
getContentPane().add(jLabel21);
jLabel21.setBounds(430, 330, 77, 25);
jLabel22.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel22.setText("N");
getContentPane().add(jLabel22);
jLabel22.setBounds(230, 70, 316, 25);
getContentPane().add(jLabel28);
jLabel28.setBounds(0, 0, 580, 0);
getContentPane().add(jLabel27);
jLabel27.setBounds(0, 0, 580, 440);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel19;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel21;
private javax.swing.JLabel jLabel22;
private javax.swing.JLabel jLabel23;
private javax.swing.JLabel jLabel24;
private javax.swing.JLabel jLabel25;
private javax.swing.JLabel jLabel26;
private javax.swing.JLabel jLabel27;
private javax.swing.JLabel jLabel28;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
// End of variables declaration//GEN-END:variables
}
<file_sep>/src/SilkAirSchedule.java
/**
*
* @author ProgJazz
*/
import java.io.*;
public class SilkAirSchedule {
Flight flights[];
int silkSize;
public SilkAirSchedule() throws IOException {
DataManager data = new DataManager();
flights = data.readSilkAirFile();
silkSize = data.silkSize();
}
public int getHour(int i, int j) {
if(j == 0) {
String depart = flights[i].getDepTime();
int dep = Integer.parseInt(depart.substring(0, 2));
return dep;
}
else {
String arrive = flights[i].getArrTime();
int arr = Integer.parseInt(arrive.substring(0, 2));
return arr;
}
}
public int getMinute(int i, int j) {
if(j == 0) {
String depart = flights[i].getDepTime();
int departure = Integer.parseInt(depart.substring(2, 4));
return departure;
}
else {
String arrive = flights[i].getArrTime();
int arrival = Integer.parseInt(arrive.substring(2, 4));
return arrival;
}
}
}
<file_sep>/src/SpiceJetSchedule.java
/**
*
* @author ProgJazz
*/
import java.util.*;
import java.io.*;
public class SpiceJetSchedule {
Flight flights[];
int spiceSize;
public SpiceJetSchedule() throws IOException {
DataManager fr = new DataManager();
flights = fr.readSpiceJetFile();
spiceSize = fr.spiceSize();
}
public int getHour(int i, int j) {
if(j == 1) {
String arrive = flights[i].getArrTime();
StringTokenizer part = new StringTokenizer(arrive, ":");
String str = part.nextToken();
int arr = Integer.parseInt(str);
if(arrive.contains("PM"))
arr += 12;
return arr;
}
else {
String depart = flights[i].getDepTime();
StringTokenizer part = new StringTokenizer(depart, ":");
String str = part.nextToken();
int dep = Integer.parseInt(str);
if(depart.contains("PM"))
dep += 12;
return dep;
}
}
public int getMinute(int i, int j) {
if(j == 1) {
String arrive = flights[i].getArrTime();
StringTokenizer part = new StringTokenizer(arrive, ": ");
String str = part.nextToken();
str = part.nextToken();
return (Integer.parseInt(str));
}
else {
String depart = flights[i].getDepTime();
StringTokenizer part = new StringTokenizer(depart, ": ");
String str = part.nextToken();
str = part.nextToken();
return (Integer.parseInt(str));
}
}
}
| 1ffbd5bce3d325d46fface7d9a7df7b252933db0 | [
"Java"
] | 6 | Java | Kush28/CosmoAir-1.0 | ea083c49f1f09df531a563854dc8159eb0ea0a65 | 612d2e364accf7d77f466024e8f9976ca0f0d8f4 |
refs/heads/master | <file_sep>function calculate(event) {
var av = document.forms[0];
var av_value = "";
for (i = 0; i < av.length; i++) {
if (av[i].checked) {
av_value = av[i].value;
}
}
var ac = document.forms[1];
var ac_value = "";
for (i = 0; i < ac.length; i++) {
if (ac[i].checked) {
ac_value = ac[i].value;
}
}
var pr = document.forms[2];
var pr_value = "";
for (i = 0; i < pr.length; i++) {
if (pr[i].checked) {
pr_value = pr[i].value;
}
}
var ui = document.forms[3];
var ui_value = "";
for (i = 0; i < ui.length; i++){
if (ui[i].checked) {
ui_value = ui[i].value;
}
}
var s = document.forms[4];
var s_value = "";
for (i = 0; i < s.length; i++){
if (s[i].checked) {
s_value = s[i].value;
}
}
var c = document.forms[5];
var c_value = "";
for (i = 0; i < c.length; i++) {
if (c[i].checked) {
c_value = c[i].value;
}
}
var i = document.forms[6];
var i_value = "";
for (b = 0; b < i.length; b++) {
if (i[b].checked) {
i_value = i[b].value;
}
}
var a = document.forms[7];
var a_value = "";
for (i = 0; i < a.length; i++) {
if (a[i].checked) {
a_value = a[i].value;
}
}
console.log(av_value + ac_value + pr_value + c_value + i_value + a_value);
$.ajax({
url: "/ajax/calculateBase",
type: "post",
data: {
"AV": av_value,
"AC": ac_value,
"PR": pr_value,
"UI": ui_value,
"S": s_value,
"C": c_value,
"I": i_value,
"A": a_value
},
success: function (data) {
console.log(data);
var result = document.getElementById("base_result");
result.innerText = data;
}
})
}
function calculateTime(event) {
var e = document.forms[8];
var e_value = "";
for (i = 0; i < e.length; i++) {
if (e[i].checked) {
e_value = e[i].value;
}
}
var rl = document.forms[9];
var rl_value = "";
for (i = 0; i < rl.length; i++) {
if (rl[i].checked) {
rl_value = rl[i].value;
}
}
var rc = document.forms[10];
var rc_value = "";
for (i = 0; i < rc.length; i++) {
if (rc[i].checked) {
rc_value = rc[i].value;
}
}
console.log(e_value + rl_value + rc_value);
$.ajax({
url: "/ajax/calculateTime",
type: "post",
data: {
"E": e_value,
"RL": rl_value,
"RC": rc_value,
},
success: function (data) {
console.log(data);
var result = document.getElementById("time_result");
result.innerText = data;
}
})
}
function calculateContext(event) {
var mav = document.forms[11];
var mav_value = "";
for (i = 0; i < mav.length; i++) {
if (mav[i].checked) {
mav_value = mav[i].value;
}
}
var mac = document.forms[12];
var mac_value = "";
for (i = 0; i < mac.length; i++) {
if (mac[i].checked) {
mac_value = mac[i].value;
}
}
var mpr = document.forms[13];
var mpr_value = "";
for (i = 0; i < mpr.length; i++) {
if (mpr[i].checked) {
mpr_value = mpr[i].value;
}
}
var mui = document.forms[14];
var mui_value = "";
for (i = 0; i < mui.length; i++) {
if (mui[i].checked) {
mui_value = mui[i].value;
}
}
var ms = document.forms[15];
var ms_value = "";
for (i = 0; i < ms.length; i++) {
if (ms[i].checked) {
ms_value = ms[i].value;
}
}
var mc = document.forms[16];
var mc_value = "";
for (i = 0; i < mc.length; i++) {
if (mc[i].checked) {
mc_value = mc[i].value;
}
}
var mi = document.forms[17];
var mi_value = "";
for (i = 0; i < mi.length; i++) {
if (mi[i].checked) {
mi_value = mi[i].value;
}
}
var ma = document.forms[18];
var ma_value = "";
for (i = 0; i < ma.length; i++) {
if (ma[i].checked) {
ma_value = ma[i].value;
}
}
var cr = document.forms[19];
var cr_value = "";
for (i = 0; i < cr.length; i++) {
if (cr[i].checked) {
cr_value = cr[i].value;
}
}
var ir = document.forms[20];
var ir_value = "";
for (i = 0; i < ir.length; i++) {
if (ir[i].checked) {
ir_value = ir[i].value;
}
}
var ar = document.forms[21];
var ar_value = "";
for (i = 0; i < ar.length; i++) {
if (ar[i].checked) {
ar_value = ar[i].value;
}
}
console.log(mav_value + mac_value + mpr_value + mui_value + ms_value + mc_value + mi_value + ma_value);
$.ajax({
url: "/ajax/calculateContext",
type: "post",
data: {
"MAV": mav_value,
"MAC": mac_value,
"MPR": mpr_value,
"MUI": mui_value,
"MS": ms_value,
"MC": mc_value,
"MI": mi_value,
"MA": ma_value,
"CR": cr_value,
"IR": ir_value,
"AR": ar_value
},
success: function (data) {
console.log(data);
var result = document.getElementById("context_result");
result.innerText = data;
}
});
}
<file_sep>function deleteDesk(event) {
var deskId = event.target.id;
$.ajax({
url: "/ajax/deleteDesk",
type: "post",
data: {
"id": deskId
},
success: function () {
var deskLi = document.getElementById(deskId);
deskLi.remove();
}
});
}
<file_sep>package ru.itis.infosecurity.service;
import org.springframework.stereotype.Service;
import ru.itis.infosecurity.forms.BaseForm;
import ru.itis.infosecurity.forms.ContextForm;
import ru.itis.infosecurity.forms.TimeForm;
import javax.swing.text.MutableAttributeSet;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Map;
import java.util.TreeMap;
@Service
public class CalculationService {
private static Map<String, Double> params = new TreeMap<>();
private static double baseScore;
private static double fImpact;
private static double exploitability;
private static double temporalScore;
private static double environmentalScore;
private static double impact;
public double calculateBaseMetrix(BaseForm form) {
return calculateFunction(getHashMapBase(form));
}
private double calculateFunction(Map<String, Double> params) {
double impactBase = 1 - ((1 - params.get("C")) * (1 - params.get("I")) * (1 - params.get("A")));
exploitability = 8.22 * params.get("AV") * params.get("AC") * params.get("PR")*params.get("UI");
if(params.get("S") == 0) {
impact = 6.42 * impactBase;
} else {
impact = 7.42 * (impactBase - 0.029) - 3.25 * (Math.pow(impactBase - 0.02, 15));
}
if(impact <= 0) {
baseScore = 0;
}else if(params.get("S") == 0) {
baseScore = Math.min((impact + exploitability), 10);
} else {
baseScore = Math.min((1.08 * (impact + exploitability)), 10);
}
return baseScore;
}
public double calculateTimeMetrix(TimeForm timeForm) {
addParamsForTime(timeForm);
temporalScore = baseScore * params.get("E") * params.get("RL") * params.get("RC");
return temporalScore;
}
public double calculateContextMetrix(ContextForm contextForm) {
addParamsForContext(contextForm);
double mImpact;
double mImpactBase = Math.min((1 - (1 - params.get("MC") * params.get("CR")) * (1 - params.get("MI") * params.get("IR")) * (1 - params.get("MA") * params.get("AR"))), 0.915);
double mExploitability = 8.22 * params.get("MAV") * params.get("MAC") * params.get("MPR") * params.get("MUI");
if(params.get("MS") == 0.0) {
mImpact = 6.42 * mImpactBase;
} else {
mImpact = 7.52 * (mImpactBase - 0.029) - 3.25 * (Math.pow(mImpactBase - 0.02, 15));
}
if(mImpact <= 0.0) {
environmentalScore = 0;
} else if(params.get("MS") == 0.0) {
double res = (Math.min((mImpact + mExploitability), 10));
double result = new BigDecimal(res).setScale(1,RoundingMode.UP).doubleValue();
environmentalScore = result * params.get("E") * params.get("RL") * params.get("RC");
} else {
double res = (Math.min((1.08 * (mImpact + mExploitability)), 10));
double result = new BigDecimal(res).setScale(1,RoundingMode.UP).doubleValue();
environmentalScore = result * params.get("E") * params.get("RL") * params.get("RC");
}
return environmentalScore;
}
private Map<String, Double> getHashMapBase(BaseForm form) {
getValues(params, form);
return params;
}
private void getValues(Map<String, Double> params, BaseForm form) {
String AV = form.getAV();
switch (AV) {
case "N":
params.put("AV", 0.85);
break;
case "A":
params.put("AV", 0.62);
break;
case "L":
params.put("AV", 0.55);
break;
case "P":
params.put("AV", 0.2);
break;
}
String AC = form.getAC();
switch (AC) {
case "L":
params.put("AC", 0.77);
break;
case "H":
params.put("AC", 0.44);
break;
}
String S = form.getS();
switch (S) {
case "U":
params.put("S", 0.0);
break;
case "C":
params.put("S", 1.0);
break;
}
String PR = form.getPR();
switch (PR) {
case "N":
params.put("PR", 0.85);
break;
case "L":
if(params.get("S") == 1) {
params.put("PR", 0.68);
} else {
params.put("PR", 0.62);
}
break;
case "H":
if(params.get("S") == 1) {
params.put("PR", 0.5);
} else {
params.put("PR", 0.27);
}
break;
}
String UI = form.getUI();
switch (UI) {
case "N":
params.put("UI", 0.85);
break;
case "R":
params.put("UI", 0.62);
break;
}
String c = form.getC();
switch (c) {
case "N":
params.put("C", 0.0);
break;
case "L":
params.put("C", 0.22);
break;
case "H":
params.put("C", 0.56);
break;
}
String i = form.getI();
switch (i) {
case "N":
params.put("I", 0.0);
break;
case "L":
params.put("I", 0.22);
break;
case "H":
params.put("I", 0.56);
break;
}
String a = form.getA();
switch (a) {
case "N":
params.put("A", 0.0);
break;
case "L":
params.put("A", 0.22);
break;
case "H":
params.put("A", 0.56);
break;
}
}
private void addParamsForTime(TimeForm timeForm) {
String E = timeForm.getE();
switch (E) {
case "X":
params.put("E", 1.0);
break;
case "U":
params.put("E", 0.91);
break;
case "P":
params.put("E", 0.94);
break;
case "F":
params.put("E", 0.97);
break;
case "H":
params.put("E", 1.0);
break;
}
String RL = timeForm.getRL();
switch (RL) {
case "X":
params.put("RL", 1.0);
break;
case "O":
params.put("RL", 0.95);
break;
case "T":
params.put("RL", 0.96);
break;
case "W":
params.put("RL", 0.97);
break;
case "U":
params.put("RL", 1.0);
break;
}
String RC = timeForm.getRC();
switch (RC) {
case "X":
params.put("RC", 1.0);
break;
case "U":
params.put("RC", 0.92);
break;
case "R":
params.put("RC", 0.96);
break;
case "C":
params.put("RC", 1.0);
break;
}
}
private void addParamsForContext(ContextForm contextForm) {
String MAV = contextForm.getMAV();
switch (MAV) {
case "X":
params.put("MAV", params.get("AV"));
break;
case "N":
params.put("MAV", 0.85);
break;
case "A":
params.put("MAV", 0.62);
break;
case "L":
params.put("MAV", 0.55);
break;
case "P":
params.put("MAV", 0.2);
break;
}
String MAC = contextForm.getMAC();
switch (MAC) {
case "X":
params.put("MAC", params.get("AC") );
break;
case "L":
params.put("MAC", 0.77);
break;
case "H":
params.put("MAC", 0.44);
break;
}
String MS = contextForm.getMS();
switch (MS) {
case "X":
params.put("MS", params.get("S"));
break;
case "U":
params.put("MS", 0.0);
break;
case "C":
params.put("MS", 1.0);
}
String MPR = contextForm.getMPR();
switch (MPR) {
case "X":
params.put("MPR", params.get("PR"));
break;
case "N":
params.put("MPR", 0.85);
break;
case "L":
if(params.get("MS") == 1.0) {
params.put("MPR", 0.68);
} else {
params.put("MPR", 0.62);
}
break;
case "H":
if(params.get("MS") == 1.0) {
params.put("MPR", 0.5);
} else {
params.put("MPR", 0.27);
}
break;
}
String MUI = contextForm.getMUI();
switch (MUI) {
case "X":
params.put("MUI", params.get("UI"));
break;
case "N":
params.put("MUI", 0.85);
break;
case "R":
params.put("MUI", 0.62);
break;
}
String MC = contextForm.getMC();
switch (MC) {
case "X":
params.put("MC", params.get("C"));
break;
case "N":
params.put("MC", 0.0);
break;
case "L":
params.put("MC", 0.22);
break;
case "H":
params.put("MC", 0.56);
break;
}
String MI = contextForm.getMI();
switch (MI) {
case "X":
params.put("MI", params.get("I"));
break;
case "N":
params.put("MI", 0.0);
break;
case "L":
params.put("MI", 0.22);
break;
case "H":
params.put("MI", 0.56);
break;
}
String MA = contextForm.getMA();
switch (MA) {
case "X":
params.put("MA", params.get("A"));
break;
case "N":
params.put("MA", 0.0);
break;
case "L":
params.put("MA", 0.22);
break;
case "H":
params.put("MA", 0.56);
break;
}
String CR = contextForm.getCR();
switch (CR) {
case "X":
params.put("CR", 1.0);
break;
case "H":
params.put("CR", 1.5);
break;
case "M":
params.put("CR", 1.0);
break;
case "L":
params.put("CR", 0.5);
break;
}
String IR = contextForm.getIR();
switch (IR) {
case "X":
params.put("IR", 1.0);
break;
case "H":
params.put("IR", 1.5);
break;
case "M":
params.put("IR", 1.0);
break;
case "L":
params.put("IR", 0.5);
break;
}
String AR = contextForm.getAR();
switch (AR) {
case "X":
params.put("AR", 1.0);
break;
case "H":
params.put("AR", 1.5);
break;
case "M":
params.put("AR", 1.0);
break;
case "L":
params.put("AR", 0.5);
break;
}
}
}
<file_sep>document.addEventListener("DOMContentLoaded", function (ev) {
var a = document.body.querySelectorAll("[data-contain-user-tags]");
for (var i = 0; i < a.length; i++) {
a[i].innerHTML = checkForLogin(a[i].innerHTML);
}
});
function addTask(event) {
var id = event.target.id;
var card = document.getElementById("card" + id);
var name = document.getElementById("input" + id);
var date = document.getElementById("date" + id);
var ul = document.getElementById("ul-id" + id);
$.ajax({
url: "/ajax/addTask",
type: "post",
data: {
"id": id,
"name": name.value,
"date": date.value
},
success: function (task) {
var li = document.createElement("li");
var a = document.createElement("a");
var text = document.createElement("em");
a.href = "/tasks/" + task.id;
a.innerHTML = task.name + " ";
li.appendChild(a);
li.appendChild(text);
ul.appendChild(li);
name.value = "";
}
});
var div = document.getElementById("addTaskTo" + id);
hide(div);
}
function commentTask(event) {
var taskId = event.target.id;
var comment = document.getElementById("comment");
var ul = document.getElementById("ul-id" + taskId);
if (comment.value.length > 0) {
$.ajax({
url: "/ajax/addComment",
type: "post",
data: {
"id": taskId,
"comment": comment.value,
},
success: function (data) {
var element = document.createElement("li");
var a = document.createElement("a");
var text = document.createElement("b");
a.href = "/profile";
a.innerHTML = data.author + ": ";
var str = data.commentText;
text.innerHTML = checkForLogin(str);
element.appendChild(a);
element.appendChild(text);
ul.appendChild(element);
comment.value = "";
}
})
} else
alert("Comment can't be empty! Write something in the form")
}
function returnTask(event) {
var id = event.target.id;
$.ajax({
url: "/ajax/returnTask",
type: "post",
data: {
"id": id
},
success: function (id) {
}
})
}
function checkForLogin(str) {
var regexp = /@[A-Za-z-]+/g;
var userCandidates = str.match(regexp);
for (var i = 0; userCandidates != null && i < userCandidates.length; i++) {
$.ajax({
async: false,
url: "/ajax/checkUser",
method: "get",
data: {
"name": userCandidates[i].slice(1)
},
success: function (user) {
str = str.replace("@" + user.login,
"<a href='/profile/" + user.id + "'>@" + user.login + "</a>");
},
error(msg) {
alert(msg);
}
});
}
return str;
}
var hide = function (elem) {
elem.style.display = 'none';
};<file_sep># CVSS V3
<file_sep>package ru.itis.infosecurity.forms;
import lombok.Data;
@Data
public class TimeForm {
private String E;
private String RL;
private String RC;
}
| e128d2fcaa37d0fb97808b46387424c52f7ecad2 | [
"JavaScript",
"Java",
"Markdown"
] | 6 | JavaScript | KonnaKotik/CVSS | 1b8c468c5cea79366d5fe1723edd5bdbb0908209 | 294658d5b23296db5fe7654615241a66803f7efc |
refs/heads/master | <repo_name>natank/mongoose-tutorial<file_sep>/app.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost:27017/tutorial-mongs')
//mongoose.connect('mongodb://nathank:<EMAIL>:59077/tutorial-mng')
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.log("wer'e connected");
}); | 22e1ddb46cce684b6b648e375aaec281cdbe2de9 | [
"JavaScript"
] | 1 | JavaScript | natank/mongoose-tutorial | 20e078b3056b48b783d725d79ed76d598c0131ef | e1562f52a83175788e859127b13ad0b14556bf34 |
refs/heads/master | <file_sep><!--
TEMPLATE INSTRUCTIONS:
Please provide as much information as you have for the resource that you
are adding to the collection. Please replace the sample text for each item
between the lines that start with ":::" in each section.
-->
<!-- RESOURCE NAME ------------------------------------------------------>
# Resource Name
Sample resource name
<!-- RESOURCE DESCRIPTION ----------------------------------------------->
## Resource Description
Sample resource description.
<!-- CREATOR - PERSON(S)- ----------------------------------------------->
## Resource Creator(s)
Sample creator person text
<!-- CREATOR - ORGANIZATION- -------------------------------------------->
## Organization
Sample creator organization text
<!-- RESOURCE - URL- ---------------------------------------------------->
## Online Resource
[sampleURL](sampleURL)
<!-- RESOURCE - AUDIENCE- ----------------------------------------------->
## Target Audience
Sample audience text
<!-- RESOURCE - FORMAT- ------------------------------------------------->
## Online Resource
Sample format description text
<!-- SUBMITTER - NAME- ----------------------------------------------->
## Submitted By
Sample submitter name text
<!-- SUBMITTER - EMAIL ADDRESS- ----------------------------------------------->
## Submitted By
Sample submitter email text
<file_sep>#! /bin/bash
/usr/local/bin/pandoc \
--standalone \
--from markdown \
--toc \
--toc-depth=1 \
--number-sections \
--top-level-division=chapter \
-o ../docs/all-cards.pdf \
--metadata date="`date +%D`" \
../templates/webpageHeader.md ../cards/*.md ../templates/webpageFooter.md<file_sep><!--
TEMPLATE INSTRUCTIONS:
Please provide as much information as you have for the resource that you
are adding to the collection. Please replace the sample text for each item
between the lines that start with ":::" in each section.
-->
<!-- RESOURCE NAME ------------------------------------------------------>
<!-- replace the "Resource Name" with the short name of the resource ---->
# the greatest git training ever {.resourceName}
<!-- RESOURCE DESCRIPTION ----------------------------------------------->
## Resource Description {.resourceDescription}
Sample resource description.
<!-- RESOURCE - KEYWORDS ------------------------------------------------>
<!-- -------------------------------------------------------------------->
## Resource Keywords {.resourceKeywords}
* Keyword 1
* Keyword 2 ...
<!-- CREATOR - PERSON(S)- ----------------------------------------------->
## Resource Creator(s) {.creatorPersons}
* Last name, First name MI
* Last name, First name MI
<!-- CREATOR - ORGANIZATION- -------------------------------------------->
## Organization {.creatorOrganization}
Sample creator organization text
<!-- RESOURCE - URL- ---------------------------------------------------->
## Online Resource {.onlineResource}
[sampleURL](sampleURL)
<!-- RESOURCE - AUDIENCE- ----------------------------------------------->
<!-- Researcher, Librarian, Undergraduate, Graduate, Policy Maker, ect.-->
## Target Audience {.targetAudience}
* Audience 1
* Audience 2 ...
<!-- RESOURCE - FORMAT- ------------------------------------------------->
<!-- -------------------------------------------------------------------->
## Resource Format/Media Type {.resourceFormat}
Sample format description text
<!-- RESOURCE - DISCIPLINE- --------------------------------------------->
<!-- -------------------------------------------------------------------->
## Resource Discipline {.resourceDiscipline}
* Discipline 1
* Discipline 2 ...
<!-- RESOURCE - License- --------------------------------------------->
<!-- -------------------------------------------------------------------->
## Resource License {.resourceLicense}
Sample resource license description
<!-- SUBMITTER - NAME- -------------------------------------------------->
## Submitter Name {.submitterName}
Sample submitter name text
<!-- SUBMITTER - EMAIL ADDRESS- ----------------------------------------->
## Submitter Email {.submitterEmail}
Sample submitter email text
<file_sep>---------------------
| [](http://creativecommons.org/licenses/by/4.0/)
| This work is licensed under a [Creative Commons Attribution 4.0 International License](http://creativecommons.org/licenses/by/4.0/)
<file_sep>---
title: GWLA Research Data Management Task Force - Data Curation Training Materials Registry
author:
- GWLA Research Data Management Task Force
margin-left: 1in
margin-right: 1in
margin-top: 1in
margin-bottom: 1in
documentclass: report
...
This collection of resources has been compiled by the *Greater Western Library Alliance Task Force* as one of the planned project products. <file_sep>#! /bin/bash
/usr/local/bin/pandoc \
--standalone \
--css=page.css \
--from markdown \
--section-divs \
-o ../docs/all-cards.html \
--metadata date="`date +%D`" \
../templates/webpageHeader.md ../cards/*.md ../templates/webpageFooter.md<file_sep># Research Data Management Training Materials
This repository is an aggregation point for a curated collection of *Research Data Management* educational and training materials. Each item in the collection is represented by a "card" that is based on a flavor of [markdown](https://daringfireball.net/projects/markdown/syntax) that is supported by the [Pandoc](https://pandoc.org/MANUAL.html) processor.
The HTML view of the resource collection can be viewed at:
* [http:/GWLA-RDM-TF.github.io/rdm-training-materials/all-cards.html](http:/GWLA-RDM-TF.github.io/rdm-training-materials/all-cards.html)
The PDF representation of the resource collection cat be downloaded from:
* [http:/GWLA-RDM-TF.github.io/rdm-training-materials/all-cards.pdf](http:/GWLA-RDM-TF.github.io/rdm-training-materials/all-cards.pdf)
----------------------
New resources can be added to the card collection by copying the `card-template.md` file in the `templates` folder and creating a new card with your choice of name in the `cards` folder. The selected name should contain no spaces and end with a `.md` extension.
----------------------
If you have [Pandoc](https://pandoc.org/MANUAL.html) installed on your computer and have an operational `bash` shell environment, you can run the scripts in the `scripts` folder to regenerate the compiled HTML and PDF files that represent all of the registered resources.
----------------------
You can provide feedback and suggestions for improvements and fixes through the [issues](https://github.com/GWLA-RDM-TF/rdm-training-materials/issues) section of this repository.
| 50fd1ffd3d237265fc5568b90dde0f939b8705af | [
"Markdown",
"Shell"
] | 7 | Markdown | GWLA-RDM-TF/rdm-training-materials | 9dbf3ce571f183733cdd4f8a0f9a1943427a48d4 | 12c4a0b80b93e7a6d42bd69bb5aa06e86975683f |
refs/heads/master | <repo_name>besetinc/Loto<file_sep>/Loto/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.Threading.Tasks;
using System.Windows.Forms;
namespace Loto
{
public partial class Form1 : Form
{
HashSet<int> izvuceni = new HashSet<int>();
Random rand = new Random();
int klik = 0;
public Form1()
{
InitializeComponent();
}
private int Izvuci(ref HashSet<int> izvuceni)
{
int broj = rand.Next(1, 37);
while (izvuceni.Contains(broj))
{
broj = rand.Next(1, 37);
}
izvuceni.Add(broj);
return broj;
}
private void button1_Click(object sender, EventArgs e)
{
klik++;
switch (klik)
{
case 1:
textBox1.Text = Izvuci(ref izvuceni).ToString();
break;
case 2:
textBox2.Text = Izvuci(ref izvuceni).ToString();
break;
case 3:
textBox3.Text = Izvuci(ref izvuceni).ToString();
break;
case 4:
textBox4.Text = Izvuci(ref izvuceni).ToString();
break;
case 5:
textBox5.Text = Izvuci(ref izvuceni).ToString();
break;
case 6:
textBox6.Text = Izvuci(ref izvuceni).ToString();
break;
}
}
private void button2_Click(object sender, EventArgs e)
{
{
int[] listic = { 5, 7, 12, 26, 29, 33 };
int pogodeni = 0;
for (int i = 0; i < listic.Length; i++)
{
if (izvuceni.Contains(listic[i]))
pogodeni++;
}
textBox8.Text = pogodeni.ToString() + "/6";
}
}
}
}
| cf55701172349222d8f928958be6ef7d435e5d91 | [
"C#"
] | 1 | C# | besetinc/Loto | 76f8e76e4c141e913d6def20e3545263b911dced | 58005fabd89341d9e97b799802c696a49955f9b5 |
refs/heads/main | <repo_name>watheia/cucumber-screenplay-demo<file_sep>/src/main/java/screenplay/tasks/AddItemToCart.java
package screenplay.tasks;
import static net.serenitybdd.screenplay.matchers.WebElementStateMatchers.isCurrentlyEnabled;
import static net.serenitybdd.screenplay.questions.WebElementQuestion.valueOf;
import net.serenitybdd.screenplay.Task;
import net.serenitybdd.screenplay.actions.Click;
import net.serenitybdd.screenplay.actions.Hover;
import net.serenitybdd.screenplay.conditions.Check;
import screenplay.user_interfaces.QuickViewPopup;
import screenplay.user_interfaces.SearchResultsPage;
public class AddItemToCart {
public static Task fromSearchResultsPage() {
return Task.where("Add item to Cart", Hover.over(SearchResultsPage.FIRST_PRODUCT_PRICE),
Check.whether(valueOf(SearchResultsPage.QUICK_VIEW_LINK), isCurrentlyEnabled()).andIfSo(
Hover.over(SearchResultsPage.QUICK_VIEW_LINK)),
Click.on(SearchResultsPage.QUICK_VIEW_LINK), Click.on(QuickViewPopup.SELECT_ITEM_COLOR),
Click.on(QuickViewPopup.ADD_ITEM_TO_CART));
}
}
<file_sep>/src/main/java/screenplay/tasks/LogIn.java
package screenplay.tasks;
import static net.serenitybdd.screenplay.Tasks.instrumented;
import static screenplay.user_interfaces.LoginForm.*;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Task;
import net.serenitybdd.screenplay.actions.Click;
import net.serenitybdd.screenplay.actions.Enter;
import net.thucydides.core.annotations.Step;
import screenplay.abilities.Authenticate;
public class LogIn implements Task {
@Step("Logs in loaded {0}")
public static LogIn withCredentials() {
return instrumented(LogIn.class);
}
@Step
public <T extends Actor> void performAs(T user) {
user.attemptsTo(Enter.theValue(authenticated(user).username()).into(FILL_USERNAME),
Enter.theValue(authenticated(user).password()).into(FILL_PASSWORD), Click.on(SIGN_IN));
}
private Authenticate authenticated(Actor actor) {
return Authenticate.as(actor);
}
}
<file_sep>/serenity.properties
serenity.project.name = serenity-cucumber-bdd-screenplay
serenity.outputDirectory = build/reports/serenity
serenity.requirements.types=theme,capability,feature
<file_sep>/src/main/java/screenplay/tasks/GoToLogin.java
package screenplay.tasks;
import static screenplay.user_interfaces.GlobalHeaderNavigationBar.getLoginScreen;
import net.serenitybdd.screenplay.Task;
import net.serenitybdd.screenplay.actions.Click;
public class GoToLogin {
public static Task called() {
return Task.where("Go To Login screen", Click.on(getLoginScreen()));
}
}
<file_sep>/src/main/java/screenplay/user_interfaces/GlobalMenu.java
package screenplay.user_interfaces;
import net.serenitybdd.core.pages.PageObject;
import net.serenitybdd.screenplay.targets.Target;
public class GlobalMenu extends PageObject {
public static Target CLOTHES = Target.the("Clothes Top Menu Option").locatedBy("#category-3 > a");
public static Target WOMEN = Target.the("Women Menu Option under clothes").locatedBy("#category-5 > a");
}
<file_sep>/src/main/java/screenplay/actions/Refresh.java
package screenplay.actions;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Interaction;
import net.serenitybdd.screenplay.abilities.BrowseTheWeb;
public class Refresh implements Interaction {
public <T extends Actor> void performAs(T actor) {
BrowseTheWeb.as(actor).getDriver().manage().deleteAllCookies();
// BrowseTheWeb.loaded(actor).getDriver().navigate().refresh();
}
public static Refresh theBrowserSession() {
return new Refresh();
}
}
<file_sep>/src/test/java/features/user_account/UserLoginStepDef.java
package features.user_account;
import static net.serenitybdd.screenplay.GivenWhenThen.seeThat;
import static net.serenitybdd.screenplay.actors.OnStage.theActorCalled;
import static net.serenitybdd.screenplay.actors.OnStage.theActorInTheSpotlight;
import static net.serenitybdd.screenplay.matchers.ConsequenceMatchers.displays;
import static org.hamcrest.Matchers.equalTo;
import io.cucumber.datatable.DataTable;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import net.serenitybdd.screenplay.actors.OnStage;
import net.serenitybdd.screenplay.actors.OnlineCast;
import org.junit.Before;
import screenplay.abilities.Authenticate;
import screenplay.questions.UserAccount;
import screenplay.tasks.LogIn;
import screenplay.tasks.Start;
public class UserLoginStepDef {
@Before
public void set_the_stage() {
OnStage.setTheStage(new OnlineCast());
}
@Given("^that (.*) is a registered (?:member|admin)$")
public void user_is_a_registered_member(String actor) {
theActorCalled(actor).wasAbleTo(Start.prepareToSignIn());
}
@When("^(?:he|she|they|Byron) logs in with valid credentials$")
public void user_has_signed_in_with_their_account(DataTable credentials) {
theActorInTheSpotlight().whoCan(Authenticate.with(credentials)).attemptsTo(LogIn.withCredentials());
}
@Then("^(?:he|she|they) should be able to view (?:his|her|their) account profile$")
public void user_should_be_able_to_view_their_account_profile() {
theActorInTheSpotlight().should(seeThat(UserAccount.loaded(), displays("title", equalTo("My account"))));
}
}
<file_sep>/src/main/java/screenplay/user_interfaces/GlobalHeader.java
package screenplay.user_interfaces;
import net.serenitybdd.core.annotations.findby.FindBy;
import net.serenitybdd.core.pages.PageObject;
import net.serenitybdd.core.pages.WebElementFacade;
import net.serenitybdd.screenplay.targets.Target;
public class GlobalHeader extends PageObject {
@FindBy(css = ".btn.btn-default.button-search")
public static WebElementFacade SEARCH_BTN;
public static Target SEARCH_BAR = Target.the("Search bar field")
.locatedBy("#search_widget > form > input.ui-autocomplete-input");
}
<file_sep>/src/main/java/screenplay/tasks/ProceedToCheckOut.java
package screenplay.tasks;
import static net.serenitybdd.screenplay.matchers.WebElementStateMatchers.isCurrentlyEnabled;
import static net.serenitybdd.screenplay.matchers.WebElementStateMatchers.isCurrentlyVisible;
import static net.serenitybdd.screenplay.questions.WebElementQuestion.valueOf;
import net.serenitybdd.screenplay.Task;
import net.serenitybdd.screenplay.actions.Click;
import net.serenitybdd.screenplay.actions.Scroll;
import net.serenitybdd.screenplay.conditions.Check;
import screenplay.user_interfaces.CheckoutSummary;
import screenplay.user_interfaces.QuickViewPopup;
import screenplay.user_interfaces.ShoppingCartSummary;
public class ProceedToCheckOut {
public static Task fromQuickViewPopup() {
return Task.where("Proceed to checkout from cart status popup", Scroll.to(QuickViewPopup.PROCEED_TO_CHECKOUT),
Click.on(QuickViewPopup.PROCEED_TO_CHECKOUT));
}
public static Task fromCartSummaryPopup() {
return Task.where("Proceed to checkout from cart status popup",
Scroll.to(ShoppingCartSummary.PROCEED_TO_CHECKOUT), Click.on(ShoppingCartSummary.PROCEED_TO_CHECKOUT));
}
public static Task fromCheckoutSummary() {
return Task.where("Proceed to checkout from cart status popup", Scroll.to(CheckoutSummary.ADDRESSES_STEP),
Click.on(CheckoutSummary.ADDRESSES_STEP), Click.on(CheckoutSummary.CONTNUE_TO_SHIPPING),
// Click.on(CheckoutSummary.SHIPPING_STEP),
Check.whether(valueOf(CheckoutSummary.SHIPPING_CARRIER), isCurrentlyEnabled()).andIfSo(
Click.on(CheckoutSummary.SHIPPING_CARRIER)),
Click.on(CheckoutSummary.CONTNUE_TO_PAYMENT),
Check.whether(valueOf(CheckoutSummary.PAY_BY_BANK_WIRE), isCurrentlyVisible())
.andIfSo(Click.on(CheckoutSummary.PAY_BY_BANK_WIRE)));
}
}
<file_sep>/src/main/java/screenplay/user_interfaces/LoginForm.java
package screenplay.user_interfaces;
import net.serenitybdd.core.pages.PageObject;
import net.serenitybdd.screenplay.targets.Target;
public class LoginForm extends PageObject {
public static Target FILL_USERNAME = Target.the("Fill user name")
.locatedBy("#login-form > section > div:nth-child(2) > div.col-md-6 > input");
public static Target FILL_PASSWORD = Target.the("Fill password")
.locatedBy("#login-form > section > div:nth-child(3) > div.col-md-6 > div > input");
public static Target SIGN_IN = Target.the("Submit login").locatedBy("#submit-login");
}
<file_sep>/src/main/java/screenplay/questions/UserAccount.java
package screenplay.questions;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Question;
import net.serenitybdd.screenplay.abilities.BrowseTheWeb;
import screenplay.model.UserAccountInformation;
public class UserAccount implements Question<UserAccountInformation> {
@Override
public UserAccountInformation answeredBy(Actor actor) {
String title = BrowseTheWeb.as(actor).getTitle();
return new UserAccountInformation(title);
}
public static UserAccount loaded() {
return new UserAccount();
}
}
<file_sep>/build.gradle
plugins {
id 'java'
id 'groovy'
id 'net.serenitybdd.plugins.gradle'
}
repositories {
mavenLocal()
jcenter()
}
dependencies {
implementation "org.codehaus.groovy:groovy:${groovyVersion}",
"net.serenity-bdd:serenity-core:${serenityVersion}",
"net.serenity-bdd:serenity-screenplay:${serenityVersion}",
"net.serenity-bdd:serenity-screenplay-webdriver:${serenityVersion}",
"net.serenity-bdd:serenity-cucumber5:${serenityCucumberVersion}"
testImplementation "net.serenity-bdd:serenity-junit:${serenityVersion}",
"net.serenity-bdd:serenity-ensure:${serenityVersion}",
"junit:junit:${junitVersion}",
"org.slf4j:slf4j-api:${slf4jVersion}"
}
test {
testLogging.showStandardStreams = true
systemProperties System.getProperties()
ignoreFailures = true
finalizedBy aggregate
}
serenity {
outputDirectory = file('build/reports/serenity')
}
<file_sep>/src/main/java/screenplay/tasks/SearchAnItem.java
package screenplay.tasks;
import static net.serenitybdd.screenplay.Tasks.instrumented;
import static screenplay.user_interfaces.GlobalHeader.SEARCH_BAR;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Task;
import net.serenitybdd.screenplay.actions.Enter;
import org.openqa.selenium.Keys;
public class SearchAnItem implements Task {
private String keyword;
public static SearchAnItem with(String keyword) {
return instrumented(SearchAnItem.class, keyword);
}
@Override
public <T extends Actor> void performAs(T actor) {
actor.attemptsTo(Enter.theValue(keyword).into(SEARCH_BAR).thenHit(Keys.ENTER));
}
public SearchAnItem(String keyword) {
this.keyword = keyword;
}
}
<file_sep>/buildSrc/build.gradle
plugins {
id 'java'
}
repositories {
mavenLocal()
jcenter()
}
dependencies {
implementation 'net.serenity-bdd:serenity-gradle-plugin:2.3.8'
}<file_sep>/src/main/java/screenplay/questions/SearchResultsGrid.java
package screenplay.questions;
import static net.serenitybdd.screenplay.questions.ValueOf.the;
import static screenplay.user_interfaces.SearchResultsPage.SEARCH_RESULTS_GRID;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Question;
import net.serenitybdd.screenplay.annotations.Subject;
import net.serenitybdd.screenplay.questions.Visibility;
@Subject("the 'Search Results' view")
public class SearchResultsGrid implements Question<ElementAvailability> {
@Override
public ElementAvailability answeredBy(Actor actor) {
return ElementAvailability.from(the(Visibility.of(SEARCH_RESULTS_GRID).viewedBy(actor)));
}
}
<file_sep>/src/main/java/screenplay/user_interfaces/ApplicationHomePage.java
package screenplay.user_interfaces;
import net.serenitybdd.core.pages.PageObject;
//@DefaultUrl("http://prestashop:90")
public class ApplicationHomePage extends PageObject {
}
<file_sep>/README.md
# cucumber-screenplay-demo framework
This is a simple example on how one can get Cucumber and Screenplay working together.
## Screenplay implementation
These tests use tasks, actions, abilities, questions and page elements defined in src/main/java/screenplay.
The screenplay package structure is shown below:
````
+ model
Domain model classes
+ abilities
Actor/User can do abilities
+ tasks
Business-level tasks
+ actions
UI interactions
+ user_interfaces
Page Objects and Page Elements
+ questions
Objects used to query the application
````
## Running the Project Using Gradle
This requires webdriver setup. By default the tests run on Chrome, you need to set the latest chromedriver instance on your system path.
Open a command window and run:
./gradle.bat test (For Windows Machines)
./gradlew test (For Linux based and Mac)
If you want to run the tests using firefox, make sure latest geckodriver is available on your system path.
Open a command window and run:
./gradlew test -Dwebdriver.driver=firefox
If you want to run the tests using internet explorer, make sure latest internetexplorerdriver is available on your system path.
Open a command window and run:
./gradlew test -Dwebdriver.driver=iexplorer
If you want to run the tests using Android , make sure Appium installed and run on http://localhost:4723 and provide the exact expected chromedriver as part of it.
Open a command window and run
./gradlew test -Dwebdriver.base.url="http://serenitybddpractice.com" -Dappium.hub="http://localhost:4723/
wd/hub" -Dwebdriver.driver=appium -Dappium.platform=ANDROID -Dappium.platformName=Android -Dappium.automation
Name=uiautomator2 -Dappium.browserName=chrome -Dappium.deviceName="emulator_5554" -Dappium.nativeWebScreensho
t=true -Dappium.androidScreenshotPath='target/screenshots';
These commands run Cucumber features using Cucumber's JUnit runner. The `@RunWith(CucumberWithSerenity.class)` annotation on the `CucumberSerenityBDDSimpleRunner`
class tells JUnit to kick off Cucumber.
## Licensing
This distribution, as a whole, is licensed under the terms of the Apache License, Version 2.0
<file_sep>/src/test/java/features/search/SearchItemsSD.java
package features.search;
import static net.serenitybdd.screenplay.GivenWhenThen.seeThat;
import static net.serenitybdd.screenplay.actors.OnStage.theActorCalled;
import static net.serenitybdd.screenplay.actors.OnStage.theActorInTheSpotlight;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static screenplay.questions.ElementAvailability.Available;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import java.util.List;
import net.serenitybdd.screenplay.actors.OnStage;
import net.serenitybdd.screenplay.actors.OnlineCast;
import org.junit.Before;
import screenplay.questions.SearchResults;
import screenplay.tasks.NavigateMenu;
import screenplay.tasks.SearchAnItem;
import screenplay.tasks.Start;
public class SearchItemsSD {
@Before
public void set_the_stage() {
OnStage.setTheStage(new OnlineCast());
}
@Given("^that (.*) wants to buy (?:Sweater|an item)$")
public void carla_wants_to_buy_T_shirt(String actor) {
theActorCalled(actor).wasAbleTo(Start.readyToSearch());
}
@When("^s?he searches for Sweater using the navigation menu$")
public void she_searches_for_T_shirts_using_the_navigation_menu() {
theActorInTheSpotlight().attemptsTo(NavigateMenu.toBlousesItem());
}
@When("^s?he searches for keyword (.*)$")
public void she_searches_for_keywords_using_the_navigation_menu(List<String> keywords) {
theActorInTheSpotlight().attemptsTo(SearchAnItem.with(keywords.get(0)));
}
@Then("^s?he should see the list of (.*) with prices available for sale$")
public void she_should_see_the_list_of_items_with_prices_available_for_sale(List<String> items) {
theActorInTheSpotlight().should(seeThat(SearchResults.resultsGrid(), is(Available)),
seeThat(SearchResults.checkForTitle(), containsString("product")),
seeThat(SearchResults.price(), is(Available)));
}
}
<file_sep>/src/main/java/utils/ConvertCucumberDataTable.java
package utils;
import io.cucumber.datatable.DataTable;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import utils.exceptions.TableConverterException;
/***
* This is a util class that converts Cucumber Data Table into a flat linked
* hash map.
*
* Example 1: Cucumber Data Table data: * | username | password | * |
* <EMAIL> | password | For the above data table
* the Linked Hash map (flat map object) named credentials looks like below
* credentials map size = 2 credentials map values : in this format "key" ->
* "value" "username" -> "<EMAIL>" "password" ->
* "<PASSWORD>"
*
* Example 2: Cucumber Data Table data: | username | password | |
* <EMAIL> | password | |
* <EMAIL> | password | For the above data table the
* Linked Hash map (flat map object) named credentials looks like below
* credentials map size = 4 credentials map values : in this format "key" ->
* "value" "username[0]" -> "<EMAIL>"
* "password[0]" -> "<PASSWORD>" "username[1]" ->
* "<EMAIL>" "password[1]" -> "<PASSWORD>"
*
* In an ideal project it's better to use plain old java object for each type of
* data specific model. A simple example would be to create a seperate Login
* Model object with userName and Password data fields.
***/
public class ConvertCucumberDataTable {
private final List<List<String>> rows;
private final Map<String, String> flatMap;
private final List<String> headers;
public static Map<String, String> toMap(DataTable dataTable) {
return new ConvertCucumberDataTable(dataTable).convertToMap();
}
private ConvertCucumberDataTable(DataTable dataTable) {
this.rows = dataTable.asLists();
this.headers = this.rows.get(0);
this.flatMap = new LinkedHashMap<>();
}
private Map<String, String> convertToMap() {
if (this.rows.size() < 2) {
throw new TableConverterException("A DataTable should have atleast one header and one data row");
}
if (this.rows.size() == 2) { // in case of only header followed by one single data row
addOnlySingleRowDataToMap();
return Collections.unmodifiableMap(flatMap);
}
addAllDataRowsToMap();
return Collections.unmodifiableMap(flatMap);
}
private void addAllDataRowsToMap() {
Iterator iter = this.rows.iterator();
int rowCnt = 0;
while (iter.hasNext()) {
List<String> row = (List) iter.next();
validRowCheck(row);
addRowDataToMap(rowCnt, row);
rowCnt++;
}
}
private void addOnlySingleRowDataToMap() {
List<String> singleDataRow = this.rows.get(1); // extract the last or second row from data table in case of
// single data row
validRowCheck(singleDataRow);
for (int colCnt = 0; colCnt < headers.size(); colCnt++) {
String key = headers.get(colCnt);
String value = singleDataRow.get(colCnt);
flatMap.put(key, value);
}
}
private void addRowDataToMap(int rowCnt, List<String> row) {
for (int colCnt = 0; colCnt < headers.size(); colCnt++) {
String key = headers.get(colCnt) + "[" + rowCnt + "]";
String value = row.get(colCnt);
flatMap.put(key, value);
}
}
private void validRowCheck(List<String> row) {
if (row.size() != headers.size()) {
throw new TableConverterException("A DataTable record has missing column data");
}
}
}
<file_sep>/src/main/java/screenplay/user_interfaces/QuickViewPopup.java
package screenplay.user_interfaces;
import net.serenitybdd.core.pages.PageObject;
import net.serenitybdd.screenplay.targets.Target;
public class QuickViewPopup extends PageObject {
public static Target SELECT_ITEM_COLOR = Target.the("Select item color")
.locatedBy("#group_2 > li:nth-child(2) > label > input"); // #TODO Make is generic
public static Target ADD_ITEM_TO_CART = Target.the("Add item to cart")
.locatedBy("#add-to-cart-or-refresh > div.product-add-to-cart > div > div.add > button");
public static Target PROCEED_TO_CHECKOUT = Target.the("Proceed to checkout")
.locatedBy("#blockcart-modal > div > div > div.modal-body > div > div.col-md-7 > div > div > a");
}
<file_sep>/src/main/java/screenplay/exceptions/CannotAuthenticateException.java
package screenplay.exceptions;
public class CannotAuthenticateException extends RuntimeException {
public CannotAuthenticateException(String actorName) {
super("The actor " + actorName + " does not have the ability to sign in to website (system under test)");
}
}
<file_sep>/settings.gradle
pluginManagement {
repositories {
jcenter()
mavenCentral()
maven {
url "https://plugins.gradle.org/m2/"
url "https://cdn.watheia.dev/m2/"
}
}
plugins {
id 'net.serenitybdd.plugins.gradle' version '2.3.6'
id 'com.diffplug.gradle.spotless' version '5.7.0'
}
}
rootProject.name = 'cucumber-screenplay-demo'
<file_sep>/gradle.properties
group=dev.watheia
version=0.1.0
org.gradle.caching=true
org.gradle.configureondemand=true
org.gradle.console=auto
org.gradle.daemon=true
org.gradle.daemon.idletimeout=1800000
org.gradle.parallel=true
org.gradle.warning.mode=all
groovyVersion=3.0.5
junitVersion=4.13
slf4jVersion=1.7.30
serenityVersion=2.3.8
serenityCucumberVersion=2.2.6
| 3329de0b0c4b8d6ceded6fd0b47706b27116f5b9 | [
"Markdown",
"Java",
"INI",
"Gradle"
] | 23 | Java | watheia/cucumber-screenplay-demo | 72ad5b2ea36244232346436dcea0bf7422a2faf2 | e9633b8a885d174d44504125c4ba170d2b0f073e |
refs/heads/main | <repo_name>ollayka/my-topics-challenge<file_sep>/src/App.test.js
import React from "react";
import App from "./App";
import { render } from "@testing-library/react";
import "@testing-library/jest-dom/extend-expect";
import data from "./topics.json";
const { topics } = data;
test("the topics data is correct", () => {
expect(topics).toMatchSnapshot;
expect(topics).toHaveLength(30);
});
for (let i = 0; i < topics.length; i += 1) {
test(`topics[${i}] should have properties (label, volume, sentiment, sentimentScore)`, () => {
expect(topics[i]).toHaveProperty("label");
expect(topics[i]).toHaveProperty("volume");
expect(topics[i]).toHaveProperty("sentiment");
expect(topics[i]).toHaveProperty("sentimentScore");
});
}
test("header renders with correct text", () => {
const { getByTestId } = render(<App />);
const headerEl = getByTestId("header");
expect(headerEl.textContent).toBe("My Topics Challenge");
});
<file_sep>/README.md
## MY TOPICS CHALLENGE
### Intro
This project was built with React
### How to run the code
- Clone this repo
- In the project directory, add `npm install` if necessary
- Run this app using the command `npm start`
- Navigate to [http://localhost:3000](http://localhost:3000) to view it in the browser
### How to run the tests
- Run `npm test` to launch the test runner
<file_sep>/src/App.js
import "./App.css";
import data from "./topics.json";
import WordCloud from "./components/WordCloud/WordCloud.jsx";
//access data and randomize the order of its display at the moment of rendering the App component
const { topics } = data;
const topicsRandomized = topics.sort(() => Math.random() - 0.5);
export default function App() {
return (
<div className="App">
<h1 data-testid="header">My Topics Challenge</h1>
<WordCloud topics={topicsRandomized} />
</div>
);
}
<file_sep>/src/components/MetaData/MetaData.jsx
import React from "react";
export default function MetaData({ topic }) {
const { label, volume, sentiment } = topic;
const { positive, neutral, negative } = sentiment;
return (
<div data-testid="metadata">
<div>Information on topic "{label}":</div>
<div>Total Mentions: {volume}</div>
<div>
<p>
Positive Mentions:{" "}
<span style={{ color: "green" }}>{positive ? positive : 0}</span>
</p>
<p>
Neutral Mentions: <span>{neutral ? neutral : 0}</span>
</p>
<p>
Negative Mentions:{" "}
<span style={{ color: "red" }}>{negative ? negative : 0}</span>
</p>
</div>
</div>
);
}
//added validation for topics without mentions assigned to a certain sentiment to display "0"
<file_sep>/src/components/Topic/Topic.jsx
import React from "react";
export default function Topic({ popularityGroups, onClick, item }) {
const { label, sentimentScore, volume } = item;
const fontSizes = [12, 18, 24, 30, 36, 42];
//function to define label's font size basing on the topic's popularity
const setFontSize = (num, arr) => arr.findIndex((el) => el.includes(num));
//function to define label's color basing on the topic's sentiment score
const setFontColor = (num) =>
num > 60 ? "green" : num < 40 ? "red" : "grey";
//style info moved to a separate object for better readability
const styleObj = {
fontSize: fontSizes[setFontSize(volume, popularityGroups)],
color: setFontColor(sentimentScore),
};
return (
<div data-testid="label" style={styleObj} onClick={() => onClick(item)}>
{label}
</div>
);
}
<file_sep>/src/components/WordCloud/WordCloud.jsx
import React, { useState } from "react";
import Topic from "../Topic/Topic";
import MetaData from "../MetaData/MetaData";
import "./WordCloud.css";
export default function WordCloud({ topics }) {
//define if the metadata should be displayed
const [showMetadata, setShowMetadata] = useState(false);
//define info on which topic should be displayed
const [topicSelected, setTopicSelected] = useState({});
//function to split topics into 6 popularity groups (to be displayed in different font sizes)
const setFontGroups = (arr) => {
const volumesArr = arr
.map((item) => item.volume)
.reduce(
(unique, item) => (unique.includes(item) ? unique : [...unique, item]),
[]
)
.sort((a, b) => a - b);
function splitIntoGroups(array, parts) {
let result = [];
for (let i = parts; i > 0; i--) {
result.push(array.splice(0, Math.ceil(array.length / i)));
}
return result;
}
return splitIntoGroups(volumesArr, 6);
};
//assign topics into different popularity groups (arrays)
let popularityGroups = setFontGroups(topics);
//update metadata-related states on mouse click
function onClick(value) {
setShowMetadata(true);
setTopicSelected(value);
}
return (
<div className="content-container">
{/* map through the randomized topics array, display each label as a component, pass down necessary props */}
<div data-testid="wordcloud" className="wordcloud-container">
{topics.map((item, index) => (
<Topic
key={index}
item={item}
popularityGroups={popularityGroups}
onClick={onClick}
/>
))}
</div>
{/* if a label got clicked, show a div with metadata */}
<div className="metadata-container">
{showMetadata && <MetaData topic={topicSelected} />}
</div>
</div>
);
}
| bd7d5ac62bd963c1a9ea23a3106e21096afb1e15 | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | ollayka/my-topics-challenge | f681e7c64cf1f29e8560b914f2fbe126fbe14b07 | c146dcaecacd80a65112cd989402a30ad1949836 |
refs/heads/master | <file_sep># SQLiteExample
An example of how to interact with a database using SQLite and ADO.NET.
I prefer using LinqToSql as opposed to ADO.NET, but this might have value to someone out there.
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SQLite;
namespace SQLiteExample
{
public partial class Form1 : Form
{
SQLiteConnection sqLiteConnection2 = new SQLiteConnection(@"data source=\\mgfs01\home$\CHedberg\My Documents\Visual Studio 2010\Projects\SQLiteExample\TEST.db3");
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Insert_ADONET();
//Insert_LINQ();
}
private void Insert_ADONET()
{
SQLiteTransaction trans;
string SQL = "INSERT INTO TestTable (ID, NAME, DESCRIPTION) VALUES";
SQL += "(@ID, @Name, @Description)";
SQLiteCommand cmd = new SQLiteCommand(SQL);
cmd.Parameters.AddWithValue("@ID", 0);
cmd.Parameters.AddWithValue("@Name", this.textBox1.Text);
cmd.Parameters.AddWithValue("@Description", this.textBox2.Text);
cmd.Connection = sqLiteConnection2;
sqLiteConnection2.Open();
trans = sqLiteConnection2.BeginTransaction();
int retval = 0;
try
{
retval = cmd.ExecuteNonQuery();
if (retval == 1)
MessageBox.Show("Row inserted!");
else
MessageBox.Show("Row NOT inserted.");
}
catch (Exception ex)
{
trans.Rollback();
Console.WriteLine(ex.Message);
}
finally
{
trans.Commit();
cmd.Dispose();
sqLiteConnection2.Close();
}
}
private void Get_ADONET()
{
string SQL = "SELECT * FROM TestTable";
SQLiteCommand cmd = new SQLiteCommand(SQL);
cmd.Connection = sqLiteConnection2;
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
da.Fill(ds);
DataTable dt = ds.Tables[0];
//this.dataGridView1.DataSource = dt;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
cmd.Dispose();
sqLiteConnection2.Close();
}
}
}
}
| a2de289772bb064073917ed89be6764545f8889c | [
"Markdown",
"C#"
] | 2 | Markdown | Chedberg84/SQLiteExampleWithADONET | 5bee95e87f9ad6178ff910df01ec0cabb6de1160 | 1b26fa6420dbd04ea87cfc79ed2ba215856c06e4 |
refs/heads/master | <file_sep>import os
# General Flask app settings
DEBUG = os.environ.get('DEBUG', None)
SECRET_KEY = os.environ.get('SECRET_KEY', None)
COUPON_SAVE_DIR = os.environ.get('COUPON_SAVE_DIR', None)
QUALIFIED_MEDIA_URL = os.environ.get('QUALIFIED_MEDIA_URL', None)
# Twilio API credentials
TWILIO_ACCOUNT_SID = os.environ.get('TWILIO_ACCOUNT_SID', None)
TWILIO_AUTH_TOKEN = os.environ.get('TWILIO_AUTH_TOKEN', None)
TWILIO_NUMBER = os.environ.get('TWILIO_NUMBER', None)
<file_sep>from flask import Flask, request, render_template, redirect, url_for
from .forms import CouponForm
from .utils import generate_barcode_image, combine_images_into_coupon, \
open_image_file_from_url, send_coupon_via_mms
twilio_logo_png_url = 'http://www.twilio.com/packages/company/' + \
'img/logos_downloadable_logobrand.png'
app = Flask(__name__, static_url_path='/static')
app.config.from_pyfile('config.py')
@app.route('/', methods=['GET', 'POST'])
def create_coupon():
form = CouponForm()
if form.validate_on_submit():
serial_number = form.serial_number.data
phone_number = form.phone_number.data
logo_image_url = form.logo_image_url.data
coupon_text = form.coupon_text.data
logo_img = open_image_file_from_url(logo_image_url)
if not logo_img:
logo_img = open_image_file_from_url(twilio_logo_png_url)
if serial_number:
barcode_img = generate_barcode_image(serial_number)
else:
barcode_img = generate_barcode_image()
coupon_url = combine_images_into_coupon(logo_img, barcode_img)
send_coupon_via_mms(coupon_url, phone_number, coupon_text)
return redirect(url_for('coupon_confirmation'))
return render_template('create_coupon.html', form=form)
@app.route('/confirmation/', methods=['GET'])
def coupon_confirmation():
form = CouponForm()
return render_template('confirmation.html', form=form)
<file_sep># Branded MMS Coupon Creator
Flask app that pulls a .png logo and creates a coupon picture. The coupon is
then sent via [Twilio MMS](https://www.twilio.com/mms).
## Deployment
### Heroku
You'll need a [Twilio account](https://www.twilio.com/try-twilio) to send
the coupons via MMS. After signing up you can deploy to Heroku with the button
below.
<a href="https://heroku.com/deploy?template=https://github.com/makaimc/branded-mms-coupons/"><img src="https://www.herokucdn.com/deploy/button.png" alt="Deploy on Heroku"></a>
<file_sep>Flask==0.10.1
Flask-WTF==0.10.2
Jinja2==2.7.3
MarkupSafe==0.23
Pillow==2.5.3
WTForms==2.0.1
Werkzeug==0.9.6
argparse==1.2.1
httplib2==0.9
itsdangerous==0.24
pyBarcode==0.7
requests==2.4.1
six==1.8.0
twilio==3.6.7
wsgiref==0.1.2
gunicorn==19.1.1
| 150e07fd0d807e21567bf23d4357421499447aa9 | [
"Markdown",
"Python",
"Text"
] | 4 | Python | shantelnubia/branded-mms-coupons | 89a27dc213e5f429db0ff265552d3421bba5436a | 4da86a5f70f66f6e0f22d2256895c50c0b14fb5f |
refs/heads/master | <repo_name>besinator/chart_manager<file_sep>/app/models/regular_serie.rb
class RegularSerie < ActiveRecord::Base
attr_accessible :chart_id, :color, :dash_style, :name, :series_type, :regular_serie_datum_attributes
has_many :regular_serie_datum, dependent: :destroy
belongs_to :chart
accepts_nested_attributes_for :regular_serie_datum
end
<file_sep>/app/assets/javascripts/app.js
/**
*= require_self
*= require extjs4/Chart/ux/Highcharts
*= require extjs4/Chart/ux/Highcharts/Serie
*= require extjs4/Chart/ux/Highcharts/LineSerie
*= require extjs4/Chart/ux/Highcharts/SplineSerie
*= require extjs4/Chart/ux/Highcharts/AreaRangeSerie
*= require extjs4/Chart/ux/Highcharts/AreaSerie
*= require extjs4/Chart/ux/Highcharts/AreaSplineRangeSerie
*= require extjs4/Chart/ux/Highcharts/AreaSplineSerie
*= require extjs4/Chart/ux/Highcharts/BarSerie
*= require extjs4/Chart/ux/Highcharts/BoxPlotSerie
*= require extjs4/Chart/ux/Highcharts/BubbleSerie
*= require extjs4/Chart/ux/Highcharts/ColumnRangeSerie
*= require extjs4/Chart/ux/Highcharts/ColumnSerie
*= require extjs4/Chart/ux/Highcharts/ErrorBarSerie
*= require extjs4/Chart/ux/Highcharts/FunnelSerie
*= require extjs4/Chart/ux/Highcharts/GaugeSerie
*= require extjs4/Chart/ux/Highcharts/PieSerie
*= require extjs4/Chart/ux/Highcharts/RangeSerie
*= require extjs4/Chart/ux/Highcharts/ScatterSerie
*= require extjs4/Chart/ux/Highcharts/WaterfallSerie
*= require extjs4/Ext/ux/ColorPickerCombo
*/
//here is storage for combobox options - chart_type
/*
var chart_types_store = Ext.create('Ext.data.Store', {
fields: ['name'],
data: [
{"name": "line"},
{"name": "spline"},
{"name": "step"},
{"name": "area"},
{"name": "bar"},
{"name": "column"},
{"name": "scatter"},
{"name": "funnel"},
]
});
*/
//Instance of application
Ext.application({
//global namespace - chart manager
name: 'CM',
appFolder: '/assets/app',
controllers: ['Charts'],
requires: [
'CM.ChartsConfig'
],
autoCreateViewport: true
});
<file_sep>/app/assets/javascripts/app/view/chart/Form.js
Ext.define('CM.view.chart.Form', {
extend: 'Ext.window.Window',
alias : 'widget.chart_form',
title : 'Add / Edit Chart',
layout: 'fit',
autoShow: true,
combo_chart_types: [
'Line',
'Spline',
'Step',
'Area',
'Bar',
'Column',
'Scatter',
'Funnel',
],
combo_dash_styles: [
'Solid',
'ShortDash',
'ShortDot',
'ShortDashDot',
'ShortDashDotDot',
'Dot',
'Dash',
'LongDash',
'DashDot',
'LongDashDot',
'LongDashDotDot'
],
//same as highcharts default colors
default_colors: [
'#2F7ED8',
'#0D233A',
'#8BBC21',
'#910000',
'#1AADCE',
'#492970',
'#F28F43',
'#77A1E5',
'#C42525',
'#A6C96A'
],
last_tab: 0,
initComponent: function() {
this.items = [{
xtype: 'form',
//title: 'Chart Form',
layout: 'form',
bodyPadding: '5 5 5 5',
width: 350,
//form fields
items: [{
//Base information fieldset and fields
xtype:'fieldset',
title: 'Chart information',
layout: 'anchor',
collapsed: false,
collapsible: true,
defaults: {
anchor: '100%'
},
items: [{
xtype: 'hidden',
name : 'id',
fieldLabel: 'id'
}, {
xtype: 'textfield',
name : 'name',
fieldLabel: 'Name',
}, {
xtype: 'textfield',
name : 'group',
fieldLabel: 'Group'
}, {
xtype: 'combo',
name : 'chart_type',
fieldLabel: 'Type',
displayField: 'name',
store: this.combo_chart_types,
queryMode: 'local',
typeAhead: true
}],
}, {
//More information fieldset and fields
xtype:'fieldset',
title: 'Chart configuration',
layout: 'anchor',
collapsible: true,
collapsed: false,
defaults: {
anchor: '100%'
},
items: [{
xtype: 'textfield',
name : 'chart_config.title',
fieldLabel: 'Title'
}, {
xtype: 'textfield',
name : 'chart_config.subtitle',
fieldLabel: 'Subtitle'
}, {
xtype: 'textfield',
name : 'chart_config.xtitle',
fieldLabel: 'X axis title'
}, {
xtype: 'textfield',
name : 'chart_config.ytitle',
fieldLabel: 'Y axis title'
}],
}, {
//Serie configuration - tabbed panel
xtype:'tabpanel',
plain:true,
activeTab: 0,
defaults:{
bodyPadding: 10
},
items:[{
//tab panel 1 == serie 1
title:'Serie 1',
layout: 'anchor',
defaults: {
anchor: '100%'
},
items:[{
xtype: 'textfield',
name : 'regular_serie_0.name',
fieldLabel: 'serie_name'
}, {
xtype: 'combo',
name : 'regular_serie_0.series_type',
fieldLabel: 'series_type',
displayField: 'name',
store: this.combo_chart_types,
queryMode: 'local',
typeAhead: true
}, {
xtype: 'combo',
name : 'regular_serie_0.dash_style',
fieldLabel: 'dash_style',
store: this.combo_dash_styles,
queryMode: 'local',
typeAhead: true
}, {
xtype: 'colorcbo',
name : 'regular_serie_0.color',
fieldLabel: 'color'
}],
}],
}],
}];
this.buttons = [{
text: 'Add Serie',
handler: this.addRegularSerieTab
}, {
text: 'Save',
action: 'save' //action defined in controller => CreateOrUpdate
}, {
text: 'Cancel',
scope: this,
handler: this.close
}];
this.callParent(arguments);
},
//set field values to default
setFieldsToDefaults: function(series) {
this.down('form').getForm().findField('chart_type').setValue(this.combo_chart_types[0]);
this.down('form').getForm().findField('regular_serie_0.series_type').setValue(this.combo_chart_types[0]);
this.down('form').getForm().findField('regular_serie_0.dash_style').setValue(this.combo_dash_styles[0]);
this.down('form').getForm().findField('regular_serie_0.color').setValue(this.default_colors[0]);
},
//
addRegularSerieTab: function() {
//console.log(this.up('chart_form').down('tabpanel'));
var win;
if(this.up('chart_form'))
{
win = this.up('chart_form');
}
else
{
win = this;
}
var tab_panel = win.down('tabpanel');
win.last_tab++;
//new tab layount
var new_serie_panel = tab_panel.add({
title: 'Serie '+(win.last_tab+1),
layout: 'anchor',
defaults: {
anchor: '100%'
},
items:[{
xtype: 'textfield',
name : 'regular_serie_'+win.last_tab+'.name',
fieldLabel: 'serie_name'
}, {
xtype: 'combo',
name : 'regular_serie_'+win.last_tab+'.series_type',
fieldLabel: 'series_type',
displayField: 'name',
store: win.combo_chart_types,
queryMode: 'local',
typeAhead: true
}, {
xtype: 'combo',
name : 'regular_serie_'+win.last_tab+'.dash_style',
fieldLabel: 'dash_style',
store: win.combo_dash_styles,
queryMode: 'local',
typeAhead: true
}, {
xtype: 'colorcbo',
name : 'regular_serie_'+win.last_tab+'.color',
fieldLabel: 'color'
}],
});
//set serie default values (color should be different from last one - ciculate default_color arr)
win.down('form').getForm().findField('regular_serie_'+win.last_tab+'.series_type').setValue(win.combo_chart_types[0]);
win.down('form').getForm().findField('regular_serie_'+win.last_tab+'.dash_style').setValue(win.combo_dash_styles[0]);
win.down('form').getForm().findField('regular_serie_'+win.last_tab+'.color').setValue(win.default_colors[win.last_tab % win.default_colors.length]);
//set added tab as active
tab_panel.setActiveTab(new_serie_panel);
//tab_panel.doLayout();
},
//function to dynamically add form fields for regular series - based on received data
addRegularSerieFormFields: function(series) {
console.log(this);
//vars for creating structured field names
var serie_property = "regular_serie";
var data_property = "regular_serie_datum";
var i = 0; //tracking series number
//hold field name and label
var field_name = "";
var field_label = "";
//to store last property => for creating right type of field (textbox, hidden, ... )
var last_property = "";
//instance of form field to be added
var temp_field;
//iterate through series and their properties and create fields accordingly (including series data)
for(i = 0; i < series.length; i++)
{
for(var property in series[i]) {
//-------------------------------------------------------------------------
//regular series data
//-------------------------------------------------------------------------
if(property == "regular_serie_datum_attributes") {
continue;
}
//-------------------------------------------------------------------------
//regular series
//-------------------------------------------------------------------------
else {
//dont create form fields for id and chart_id properties
if(property == "id" || property == "chart_id") {
continue;
}
//create form fields for serie properies (include series number - i)
field_name = serie_property+"_"+i+"."+property;
field_label = property;
last_property = property;
//if field_name already exists, dont create field
if(this.down('form').getForm().findField(field_name)) {
continue;
}
}
//create form field according to property type
switch(last_property)
{
//color picker
case "color":
temp_field = Ext.create('Ext.ux.ColorPickerCombo', {
name: field_name,
fieldLabel: field_label
});
this.down('form').add(temp_field);
break;
//series type combobox
case "series_type":
temp_field = Ext.create('Ext.form.field.ComboBox', {
name: field_name,
fieldLabel: field_label,
store: this.combo_chart_types,
queryMode: 'local',
typeAhead: true
});
var added_field = this.down('form').add(temp_field); //add field to form
added_field.setValue(this.combo_chart_types[0]);
break;
//series dash style combobox
case "dash_style":
temp_field = Ext.create('Ext.form.field.ComboBox', {
name: field_name,
fieldLabel: field_label,
store: this.combo_dash_styles,
queryMode: 'local',
typeAhead: true
});
var added_field = this.down('form').add(temp_field); //add field to form
added_field.setValue(this.combo_dash_styles[0]);
break;
//default textfield
default:
temp_field = Ext.create('Ext.form.field.Text', {
name: field_name,
fieldLabel: field_label
});
this.down('form').add(temp_field); //add field to form
}
}
}
}
});
<file_sep>/config/routes.rb
ChartManager::Application.routes.draw do
devise_for :admins
mount RailsAdmin::Engine => '/admin', :as => 'rails_admin'
resources :charts
resources :logins
root to: 'index#index'
# This redirect is a work around for the use of Extjs4 with Rails assets pipeline:
# for "test" and "production" mode images are now retrived this way
match "/resources/themes/*all" => redirect {|env, req|
URI.unescape "/assets/extjs4/resources/themes/#{req.params[:all]}"
}, all: /.*/ unless Rails.env == 'development'
end
<file_sep>/README.md
Rails + ExtJS app for creating charts
<file_sep>/app/models/chart.rb
class Chart < ActiveRecord::Base
attr_accessible :chart_type, :group, :name, :user_id, :chart_config_attributes, :regular_serie_attributes
has_one :chart_config, dependent: :destroy
has_many :regular_serie, dependent: :destroy
belongs_to :user
accepts_nested_attributes_for :chart_config, :regular_serie
end
<file_sep>/db/migrate/20130423161511_create_regular_serie_data.rb
class CreateRegularSerieData < ActiveRecord::Migration
def change
create_table :regular_serie_data do |t|
t.string :x_field
t.float :data_index
t.integer :regular_serie_id
t.timestamps
end
end
end
<file_sep>/app/assets/javascripts/app/model/RegularSerie/Data.js
Ext.define('CM.model.RegularSerie.Data', {
extend : 'Ext.data.Model',
idProperty: 'id',
fields : [
{ name: 'id', type: 'int' },
{ name: 'regular_serie_id', type: 'int' },
{ name: 'x_field', type: 'string' },
{ name: 'data_index', type: 'float' }
],
});
<file_sep>/app/controllers/charts_controller.rb
class ChartsController < ApplicationController
respond_to :json
#-----------------------------------------------------
#get all charts => GET /charts
#-----------------------------------------------------
def index
current_user = User.first
charts = current_user.charts.all
#include in chart respond also chart_config, regular_serie and regular_serie_datum (data) => all nested with chart
respond_with(charts) do |format|
#get all charts as json string
charts_str = charts.to_json(
:include => [
'chart_config',
'regular_serie' => {
:include => ['regular_serie_datum']
}]
)
#response string in specified format
response_str = "{\"success\": true, charts: #{charts_str}}"
format.json { render :json => response_str }
end
end
#-----------------------------------------------------
#create chart => POST /charts
#-----------------------------------------------------
def create
current_user = User.first
p "--------------------------------------------\n\n\n\n\n\n"
p params[:chart]
p "--------------------------------------------\n\n\n\n\n\n"
chart = current_user.charts.new(params[:chart])
chart.save
respond_with(chart) do |format|
#get all charts as json string
chart_str = chart.to_json(
:include => [
'chart_config',
'regular_serie' => {
:include => ['regular_serie_datum']
}]
)
#response string in specified format
response_str = "{\"success\": true, charts: #{chart_str}}"
if chart.valid?
format.json { render :json => response_str }
else
format.json { render json: { success: false, errors: chart.errors } }
end
end
end
#-----------------------------------------------------
#update chart => PUT /charts/<id>
#-----------------------------------------------------
def update
current_user = User.first
chart = current_user.charts.find(params[:id])
chart.update_attributes(params[:chart])
respond_with(chart) do |format|
#get all charts as json string
chart_str = chart.to_json(
:include => [
'chart_config',
'regular_serie' => {
:include => ['regular_serie_datum']
}]
)
#response string in specified format
response_str = "{\"success\": true, charts: #{chart_str}}"
if chart.valid?
format.json { render :json => response_str }
else
format.json { render json: { success: false, errors: chart.errors } }
end
end
end
#-----------------------------------------------------
#delete chart => DELETE /charts/<id>
#-----------------------------------------------------
def destroy
current_user = User.first
chart = current_user.charts.find(params[:id])
chart.destroy
respond_with(chart) do |format|
format.json
end
end
end
<file_sep>/app/assets/javascripts/app/model/RegularSerie/Config.js
Ext.define('CM.model.RegularSerie.Config', {
extend : 'Ext.data.Model',
requires: [
'CM.model.RegularSerie.Data'
],
idProperty: 'id',
fields: [
{ name: 'id', type: 'int' },
{ name: 'chart_id', type: 'int' },
{ name: 'name', type: 'string' },
{ name: 'series_type', type: 'string' },
{ name: 'dash_style', type: 'string' },
{ name: 'color', type: 'string' },
],
hasMany: [{
foreignKey: 'regular_serie_id', /* rule 1.3, 1.5 */
associationKey: 'regular_serie_datum', /* rule 1.4, 1.5 */
name: 'regular_serie_datum_attributes', /* rule 1.6 */
model: 'CM.model.RegularSerie.Data' /* rule 1.7 */
}],
});
<file_sep>/app/models/regular_serie_datum.rb
class RegularSerieDatum < ActiveRecord::Base
attr_accessible :data_index, :regular_serie_id, :x_field
belongs_to :regular_serie
end
<file_sep>/app/models/user.rb
class User < ActiveRecord::Base
attr_accessible :email, :login, :password_digest
has_many :charts, dependent: :destroy
end
<file_sep>/app/assets/javascripts/app/model/ChartConfig.js
Ext.define('CM.model.ChartConfig', {
extend: 'Ext.data.Model',
idProperty: 'id',
fields: [
{ name: 'id', type: 'int' },
{ name: 'chart_id', type: 'int' },
{ name: 'title', type: 'string' },
{ name: 'subtitle', type: 'string' },
{ name: 'xtitle', type: 'string' },
{ name: 'ytitle', type: 'string' },
],
});
<file_sep>/app/assets/javascripts/app/controller/Charts.js
Ext.define('CM.controller.Charts', {
extend: 'Ext.app.Controller',
stores: ['Charts'],
models: ['Chart'],
views: [
'chart.Tree',
'chart.Form'
],
init: function() {
this.control({
'chart_tree': {
itemdblclick: this.editChart,
selectionchange: this.selectionChange
},
'chart_form button[action=save]': {
click: this.createOrUpdateChart
},
'button[action=addChart]': {
click: this.addChart
},
'button[action=editChart]': {
click: this.editChart
},
'button[action=deleteChart]': {
click: this.deleteChart
}
});
},
//-------------------------------------------------------------------------------------
//addChart - open empty form
//-------------------------------------------------------------------------------------
addChart: function() {
var formWin = Ext.widget('chart_form');
formWin.setFieldsToDefaults();
formWin.show();
},
//-------------------------------------------------------------------------------------
//editChart - open form with preset record data
//-------------------------------------------------------------------------------------
editChart: function() {
var record = Ext.getCmp('chart_tree').getSelectedChart(); //get selected record from grid
Ext.apply(record.data,record.getAssociatedData()); //merge record data with all associated data (chart model with assoc models char_config, ...
var formWin = Ext.widget('chart_form'); //get form window
for(var i = 1; i<record.data.regular_serie_attributes.length; i++)
{
formWin.addRegularSerieTab();
}
//formWin.addRegularSerieFormFields(record.data.regular_serie_attributes); //dynamically add fields to according to the number of existing series
//-------------------------------------------------------------------------------------
//populate form field with data
//-------------------------------------------------------------------------------------
for(var property in record.data) {
var formField; //field of form to be written to
var base_property = ""; //first part of formField name (eg chart_config.title)
//-------------------------------------------------------------------------
//regular series
//-------------------------------------------------------------------------
if(property == "regular_serie_attributes") {
base_property = "regular_serie";
//iterate regular_serie_attributes - array of objects
for(var i=0; i<record.data.regular_serie_attributes.length; i++) {
//iterate regular_serie_attributes[i] properties
for(var sub_property in record.data.regular_serie_attributes[i]) {
//find field for current regular_serie_attribute
formField = formWin.down('form').getForm().findField(base_property+"_"+i+"."+sub_property);
//if field is found => write data to field
if(formField) {
formField.setValue(record.data.regular_serie_attributes[i][sub_property]);
}
}
}
}
else {
//-------------------------------------------------------------------------
//chart config
//-------------------------------------------------------------------------
if(property == "chart_config_attributes") {
base_property = "chart_config"; //field name is eg => chart_config.title (title == sub_property)
//iterate chart_config_attributes
for(var sub_property in record.data.chart_config_attributes) {
//find field for chart_config_attribute
formField = formWin.down('form').getForm().findField(base_property+"."+sub_property);
//if field is found => write data to field
if(formField) {
formField.setValue(record.data.chart_config_attributes[sub_property]);
}
}
}
//-------------------------------------------------------------------------
//chart - load record will load only not nested data, so only chart data
//-------------------------------------------------------------------------
else {
formWin.down('form').loadRecord(record);
}
}
}
//-------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------
},
//-------------------------------------------------------------------------------------
//createOrUpdateChart - after save button on form - create/update store and db
//-------------------------------------------------------------------------------------
createOrUpdateChart: function(button) {
var win = button.up('window');
var form = win.down('form');
var store = this.getStore('Charts');
var values = form.getValues();
var val_chart = {}; //object to hold chart values from form
var val_chart_config = {}; //object to hold chart_config values from form
var val_regular_serie = []; //array of objects for regular_serie
var val_regular_serie_data = []; //array of objects for regular_serie_data
//-------------------------------------------------------------------------------------
//populate val_chart .. val_regular_serie_data with corresponding values returned from form
// - they will be used to create corresponding model and pushed to store
//form field name formats => regular_serie_0.series_type, chart_config.ytitle, name
//-------------------------------------------------------------------------------------
for(var property in values) {
//console.log(property + ': ' + values[property]);
var match; //for regex match
//-------------------------------------------------------------------------
//populate regular serie data
//-------------------------------------------------------------------------
if(n = property.indexOf('regular_serie_datum') != -1) {
//console.log(property + ': ' + values[property]);
}
else {
//-------------------------------------------------------------------------
//populate regular series (regular_serie_0.series_type)
//-------------------------------------------------------------------------
if(property.indexOf('regular_serie') != -1) {
//find first occurence of number in string (field name) = regular_serie number
match = property.match(/\d+/);
var serie_num = match[0];
//if regular serie object doesnt exists - create one
if(val_regular_serie.length <= serie_num) {
val_regular_serie[serie_num] = {};
}
//assign property - save only part after dot
val_regular_serie[serie_num][property.substr(property.indexOf('.')+1)] = values[property];
delete values[property]; //delete regular_serie_0.xxx property from values
}
else {
//-------------------------------------------------------------------------
//populate chart config (chart_config.ytitle)
//-------------------------------------------------------------------------
if(property.indexOf('chart_config') != -1) {
//save only last part of property name, aftej the dot"
val_chart_config[property.substr(property.indexOf('.')+1)] = values[property];
delete values[property]; //after assignment remove propery from values
}
//-------------------------------------------------------------------------
//populate chart (eg. name)
//-------------------------------------------------------------------------
else {
//console.log(property + ': ' + values[property]);
val_chart[property] = values[property];
}
}
}
}
//-------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------
//create new model isntance (filled with chart data) - will be added to store
var chart = Ext.create('CM.model.Chart', val_chart);
//assign chart config to chart record
chart.beginEdit();
chart.data.chart_config_attributes = {};
for(var property in val_chart_config) {
chart.data.chart_config_attributes[property] = val_chart_config[property];
}
chart.endEdit();
//assign regular series to chart record - in store writer manually get this data and put to
//server response
chart.beginEdit();
for(var i in val_regular_serie) {
chart.regular_serie_attributes().data.items[i] = {};
chart.regular_serie_attributes().data.items[i].data = {};
for(var property in val_regular_serie[i]) {
chart.regular_serie_attributes().data.items[i].data[property] =
val_regular_serie[i][property];
}
}
chart.endEdit();
//validate chart records
var errors = chart.validate();
//if char record are valid
if (errors.isValid()) {
var chartRecord = form.getRecord();
//if record exists - only update record
if (chartRecord) {
chartRecord.set(val_chart); //update chart
//update chart_config
//if chartRecord.getChartConfig() is not defined (when model has been just created and stored)
//then catch error and assign values manually - manual assign doesnt work for loaded data
//from database => wtf??? => created this workaroud
try {
var chartConfigRecord = chartRecord.getChartConfig();
chartConfigRecord.set(val_chart_config);
for(var i in val_regular_serie)
{
var regularSerieRecord = chartRecord.regular_serie_attributes().data.items[i];
regularSerieRecord.set(val_regular_serie[i]);
}
}
//manually set chart_config - this wont happen, if store is loaded from dbimmediatly
// after chart record creation
catch(err) {
console.log("chart record wasnt saved: "+err);
//assign chart config values manually to record and commit changes to store
chartRecord.beginEdit();
for(var property in val_chart_config) {
//update chart config
chartRecord.data.chart_config_attributes[property] = val_chart_config[property];
}
chartRecord.endEdit();
chartRecord.commit();
}
chartRecord.setDirty(); //set dirty, to be sure the record is saved
//else - create record - add it to store
} else {
store.add(chart);
}
//synchronize store - update/create and close window
store.sync({
success: function() {
//if record was created, then load store from db - fixes issues with not up to date data
if(!chartRecord) {
store.load();
}
//after successfull update/create close form
win.close();
},
failure: function(batch, options) {
//extract server side validation errors
var serverSideValidationErrors = batch.exceptions[0].error;
var errors = new Ext.data.Errors();
for (var field in serverSideValidationErrors) {
var message = serverSideValidationErrors[field].join(", ");
errors.add(undefined, { field: field, message: message });
}
form.getForm().markInvalid(errors);
}
});
//if chart records are not valid
} else {
form.getForm().markInvalid(errors);
}
},
//-------------------------------------------------------------------------------------
//deleteChart - delete record
//-------------------------------------------------------------------------------------
deleteChart: function() {
var record = Ext.getCmp('chart_tree').getSelectedChart();
if (record) {
var store = this.getChartsStore();
store.remove(record);
store.sync();
}
},
//-------------------------------------------------------------------------------------
//selectionChange - enable/disable buttons according to selection
//-------------------------------------------------------------------------------------
selectionChange: function(selectionModel, selections) {
var tree = Ext.getCmp('chart_tree');
if (selections.length > 0) {
tree.enableRecordButtons();
} else {
tree.disableRecordButtons();
}
},
});
| 1907440016b569d02ede7c29cd44f1f6e2e18b7c | [
"JavaScript",
"Ruby",
"Markdown"
] | 14 | Ruby | besinator/chart_manager | e677df712e6a65ef0ae8ffd65f76de60269aa43e | c221e1077b0611a092a59e910f8e097beab49bdf |
refs/heads/master | <file_sep>
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('template.html')
@app.route('/my-link/')
def my_link(player='<NAME>'):
fname = request.args.get('fname')
lname = request.args.get('lname')
player = fname.strip() + " " + lname.strip()
import sys
from recommender import recommend
try:
x = recommend(player)
msg = "<h1>Find Similar NHL players!</h1>"
msg += "<h2> Recommender System For: <b>" + player.title() + "</b></h2>"
msg += "<hr></hr>"
count = 1
for i,j in enumerate(x.recommendations.values):
msg += "<p>" + str(count) + ": " + x.recommendations.index[i] + " " + str(j[0]) + "</p>"
count += 1
return msg
except:
return "<p><b>" + player + "</b> is not in the database... check spelling??"
if __name__ == '__main__':
app.run(debug=True)
<file_sep>from data_parse import DataOrg
from db_connect import hockey_connect
import os
import pandas as pd
class recommend(DataOrg):
def __init__(self, player):
"""Init"""
#Inherit Class to connect to DB
self.conn = hockey_connect(os.environ['smsDBusername'],
os.environ['smsDBpassword'],
'localhost')
#Inherit class that gets data
DataOrg.__init__(self)
#Run the System
self.run(player)
def run(self, player):
""""""
#Redefine data set
df = self.data
#Use pearson correlation method with at least 100 ratings
corrMatrix = df.T.corr(method='pearson')
myRatings = df.loc[player].dropna()
dd = pd.DataFrame(corrMatrix[player])
dd = dd[dd.index != player]
self.recommendations = dd.sort_values(player, ascending=False)[:10]
<file_sep>import pandas as pd
import numpy as np
class DataOrg():
def __init__(self):
""""""
#Get Data and pivot table it
self.data = self.pivot(self.__getData__())
def __getData__(self):
"""Get Data For Recommender System"""
df = self.conn.query("""
SELECT firstname || ' ' || lastname, height, weight, shootcatch,
firstnhl, (lastnhl-firstnhl)+1 AS yearsPlayed, master.pos,
birthcountry, gp, g, a, pts
FROM master
JOIN scoring ON scoring.playerid = master.playerid
WHERE scoring.lgid = 'NHL'
""")
df.columns = ["name", "height", "weight",
"shoot", "firstnhl", "yearsPlayed", "pos",
"country", "gp", "g", "a", "pts"]
df = df[df.pos != 'G']
df['pos'] = [1 if x in ['C', 'C/L', 'C/R', 'F', 'L', 'L/C', 'L/D', 'R'] else 0 for x in df.pos]
df['country'] = pd.Categorical(df.country).codes
df['ratio'] = df.g/df.a
return df
def pivot(self, df):
""""""
data = df.groupby(df.name).agg({'height':['mean'],
'weight':['mean'],
'firstnhl':['mean'],
'yearsPlayed':['mean'],
'gp':['sum'],
'g':['sum'],
'a':['sum'],
'pts':['sum'],
'ratio':['mean'],
'pos':['mean'],
'country':['mean']
})
data = data[data['gp']['sum'] >= 100]
data = data[data['yearsPlayed']['mean'] >= 3]
return data
<file_sep>"""
------------------------
Shyft Technologies Inc.
Shyft - May 2017
------------------------
Module to connect to smsApp databases.
-<NAME>
"""
import psycopg2
import pandas as pd
import numpy as np
import os
class hockey_connect():
"""Class to connect to Shyft Databases"""
def __init__(self, username, password, database="localhost"):
"""Init"""
self.dbServers = {"localhost": 'localhost'}
self.username = username
self.password = <PASSWORD>
self.__getDB__(database)
self.conn = self.__connect__()
def __getDB__(self, database):
"""Gets the server and database to connect to"""
try:
self.server = self.dbServers[database]
self.dbName = "hockey"
self.msg = "Your are connected to " + self.dbName + " on the " + \
database + " server!"
except:
database + " is not a valid database. Your options are " + \
str(self.dbServers.keys())
def __connect__(self):
"""Connect to Shyft database"""
try:
conn = psycopg2.connect(dbname = self.dbName,
user = self.username,
password = <PASSWORD>,
host = self.server
)
print self.msg
return conn
except:
print "I am unable to connect to the database"
def query(self, query):
"""Queries Database
Pass in Query as a String"""
cur = self.conn.cursor()
cur.execute(query)
rows = cur.fetchall()
rows = pd.DataFrame(rows)
return rows
<file_sep>from db_connect import hockey_connect
__all__ = ["hockey_connect"] | 9a4ad668ab86382d0c4b07a4b529e0c349db8716 | [
"Python"
] | 5 | Python | bmburlingame/Recommender | 74c30bb732617e928b714adbf5b621522a2a4681 | 9e08134e978505c8cc1a2429d0fe86ec0720b29d |
refs/heads/master | <repo_name>TayyabChaudhary/Updrive-site<file_sep>/src/Components/Sections/Section4/section4.js
import React from 'react'
import './section4.scss'
export default function section4() {
return (
<div>
<div className="yellow-background">
<h1 className="is-size-1 has-text-centered has-text-weight-medium">
We are ready to take your call 24/7!
</h1>
<h2 className="is-size-1 has-text-centered has-text-weight-bold">Call Now (92)307</h2>
</div>
<footer className="footer">
<div className="container">
<div className="columns">
<div className="column">
<img src="https://livedemo00.template-help.com/wt_prod-27536/images/logo-default-312x75.png"width="200px" />
</div>
<div className="column">
<h1>Services</h1>
<ul>
<li><a href="#!">Adress Pickup</a></li>
<li><a href="#!">Airport Transfer</a></li>
<li><a href="#!">Long-distance Transfer</a></li>
<li><a href="#!">Taxi Tour</a></li>
</ul>
</div>
</div>
</div>
</footer>
</div>
)
}
<file_sep>/src/Components/Sections/Section1/section1.js
import React from 'react';
import jQuery from 'jquery';
import $ from 'jquery';
import './section1.scss'
export default function section1() {
(function ($) { // Begin jQuery
$(function () { // DOM ready
// If a link has a dropdown, add sub menu toggle.
$('nav ul li a:not(:only-child)').click(function (e) {
$(this).siblings('.nav-dropdown').toggle();
// Close one dropdown when selecting another
$('.nav-dropdown').not($(this).siblings()).hide();
e.stopPropagation();
});
// Clicking away from dropdown will remove the dropdown class
$('html').click(function () {
$('.nav-dropdown').hide();
});
// Toggle open and close nav styles on click
$('#nav-toggle').click(function () {
$('nav ul').slideToggle();
});
// Hamburger to X toggle
$('#nav-toggle').on('click', function () {
this.classList.toggle('active');
});
}); // end DOM ready
})(jQuery); // end jQuery\\
$(window).on('load', function () {
$("#cover").fadeOut(8000);
});
return (
<div>
<section className="navigation">
<div className="nav-container">
<div className="brand">
<a href="#!"><img src="https://livedemo00.template-help.com/wt_prod-27536/images/logo-default-312x75.png" /></a>
</div>
<nav>
<div className="nav-mobile"><a id="nav-toggle" href="#!"><span></span></a></div>
<ul className="nav-list">
<li>
<a href="#!" style={{color:"#FDC501"}}>Home</a>
</li>
<li>
<a href="#!">About</a>
</li>
<li>
<a href="#!">Services</a>
<ul className="nav-dropdown">
<li>
<a href="#!">Web Design</a>
</li>
<li>
<a href="#!">Web Development</a>
</li>
<li>
<a href="#!">Graphic Design</a>
</li>
</ul>
</li>
<li>
<a href="#!">Careers</a>
</li>
<li>
<a href="#!">Pages</a>
<ul className="nav-dropdown">
<li>
<a href="#!">Web Design</a>
</li>
<li>
<a href="#!">Web Development</a>
</li>
<li>
<a href="#!">Graphic Design</a>
</li>
</ul>
</li>
<li>
<a href="#!">Contact us</a>
</li>
<li >
<a href="#!" style={{ color: "#FDC501" }}><i className="fa fa-phone"></i><strong>Call Now:</strong><b style={{ color: "rgb(13, 255, 0)" }}> (+92) 1303903</b></a>
</li>
</ul>
</nav>
</div>
</section>
<div id="cover"> <span class="glyphicon glyphicon-refresh w3-spin preloader-Icon"><i class="fa fa-refresh" aria-hidden="true"></i></span>Please Wait Browser IS Loading......!</div>
</div>
)
}
| 21a7d6aa30ae67b8aa9bc0aba99b5b77e1702ac5 | [
"JavaScript"
] | 2 | JavaScript | TayyabChaudhary/Updrive-site | 6d4fc934133a9ba2445da62e2cc4c2be034e6cb5 | cd2f0603b444282e0ed8ad8a25cac3c26dfa38ca |
refs/heads/master | <file_sep>## Import Data if it does not exist in global environment
if (!exists('data', envir = globalenv())) {
#Import Data and convert date column to date class
data <- read.table('household_power_consumption.txt',sep = ";",skip = 1)
data$V1 <- as.Date(data$V1,'%d/%m/%Y')
# Creating 2 dates to include for plotting
date1 <- as.Date("2007/02/01",'%Y/%m/%d')
date2 <- as.Date("2007/02/02",'%Y/%m/%d')
#Subset data using 2 dates and bind 2 datasets to give us data with 2 dates
data1 <- subset(data,V1 == date1)
data2 <- subset(data,V1 == date2)
data <- rbind(data1,data2)
}
#converting power data to numeric and getting rid of NA's for Y-Axis
data2 <- data
data2$V3 <- as.numeric(data2$V3)
data2 <- data2[!is.na(data2$V3),]
## Creating Datetime for x-axis
datetime <- as.POSIXct(paste(data2$V1, data2$V2), format="%Y-%m-%d %H:%M:%S")
# Opening png graphics device and plotting
png(filename = 'plot3.png',width = 480,height = 480)
plot(datetime,data2$V7,xlab = '',ylab = 'Energy sub metering',type = 'l')
lines(datetime,data2$V8,type = 'l',col = 'red')
lines(datetime,data2$V9,type = 'l',col = 'blue')
legend('topright',legend = c('Sub_metering_1','Sub_metering_2','Sub_metering_3'),col = c('black','red','blue'),lty = 1)
dev.off() | 86443ce8b5c5abbd1352a8222d5e6aa9aa4e9e94 | [
"R"
] | 1 | R | pmorgan13/ExData_Plotting1 | c5a3898f04cc29062e107d2144c208aa6065b018 | 1be3b8e5dd90d417a31e269b41984ff740148778 |
refs/heads/master | <repo_name>OlasubomiEfuniyi/game-backend<file_sep>/game-piece.js
const MINIMUM_RADIUS = 100;
const FOOD = 1;
const PLAYER = 2;
const COLORS = ["red", "green", "blue","orange", "yellow", "black", "brown"];
class GamePiece {
constructor(x = 0, y = 0, radius = MINIMUM_RADIUS, type = FOOD, color = "green") {
this._x = x;
this._y = y;
this._radius = radius;
this._type = type;
this._color = color;
this._isAlive = true;
}
set x(x) {
this._x = x;
}
set y(y) {
this._y = y;
}
set radius(radius) {
this._radius = radius;
}
set type(type) {
this._type = type;
}
set color(color) {
this._color = color;
}
get x() {
return this._x;
}
get y() {
return this._y;
}
get radius() {
return this._radius;
}
get type() {
return this._type;
}
get color() {
return this._color;
}
get isAlive() {
return this._isAlive;
}
grow(radiusIncrement) {
if(this._type === PLAYER) {
this._radius += radiusIncrement;
}
}
shrink(radiusDecrement) {
if(this._type === PLAYER) {
if(this._radius - radiusDecrement > MINIMUM_RADIUS) {
this._radius -= radiusDecrement;
} else {
this._radius = MINIMUM_RADIUS;
this.isAlive = false;
}
}
}
}
exports.GamePiece = GamePiece;
exports.FOOD = FOOD;
exports.PLAYER = PLAYER;
exports.MINIMUM_RADIUS = MINIMUM_RADIUS;
exports.COLORS = COLORS;<file_sep>/player-data.js
const { GamePiece, MINIMUM_RADIUS, PLAYER, COLORS } = require("./game-piece");
class PlayerData {
constructor(id, name = "", webSocket) {
this._id = id;
this._name = name;
this._webSocket = webSocket;
this._pieces = [];
}
get id() {
return this._id;
}
get name() {
return this._name;
}
get webSocket() {
return this._webSocket;
}
get pieces() {
return this._pieces;
}
set name(name) {
this._name = name;
}
set webSocket(ws) {
this._webSocket = ws;
}
//This method adds a game piece for a player. A player can have multiple game pieces if they split.
addGamePiece(x, y, radius=MINIMUM_RADIUS) {
let color = undefined;
if(this._pieces.length == 0) { //This is the first game piece, give it a random color
color = COLORS[Math.floor(Math.random() * (COLORS.length - 1))];
} else { //Use the same color as the existing game pieces
color = this._pieces[0].color;
}
this._pieces.push(new GamePiece(x, y, radius, PLAYER, color));
}
}
exports.PlayerData = PlayerData;
<file_sep>/app.js
const WebSocket = require("ws");
const LinkedList = require("./linked-list").LinkedList;
const { GameData } = require("./game-data");
const port = 1024;
//Linked list to keep track of port numbers
const portList = new LinkedList();
//A map from game code to the game's data
const codeToGameData = new Map();
//A web socket for handling game world logistics with all clients
const wss = new WebSocket.Server({port: port}, () => {
console.log(`Server socket listening on port ${port}`);
});
/****************Initialize linked list of port numbers********************/
const minPort = 1025;
const maxPort = 65535;
for(let p = minPort; p <= maxPort; p++) {
portList.addToFront(p);
}
/***************End of port initialization **************************/
//Set a callback to handle a client connecting to the websocket
wss.on('connection', (ws) => {handleConnection(ws);});
/********************************************* Overseer Functions ***********************************************/
//This function handles a successful connection between a client and the server
function handleConnection(ws) {
console.log("client is connected to game server");
ws.on('message', (message) => {handleGameServerMessage(ws, message);});
}
//This function hanles a message from a connected client via their web socket connection
function handleGameServerMessage(ws, message) {
let msg = JSON.parse(message);
console.log("received: %s", message);
switch(msg.type) {
case "CREATE":
createGame(ws);
break;
case "PORT":
getPort(ws, Number.parseInt(msg.gameCode));
break;
default:
let result = {status: "FAILURE", msg: `Invalid command: ${msg.type}`};
ws.send(JSON.stringify(result));
break;
};
}
//This function creates a new game world and returns an
//object containing the relevant info about the game world
function createGame(ws) {
let gameCode = generateGameCode();
let portNumber = null;
if(portList.size != 0) {
portNumber = portList.removeFromFront();
let gameData = new GameData();
gameData.port = portNumber;
gameData.gameCode = gameCode;
//Add the game data to the map
codeToGameData.set(gameCode, gameData);
let webSocketServer = new WebSocket.Server({port: portNumber}, () => {
console.log(`Created web socket server for game world with code ${gameCode} on port ${portNumber}`);
webSocketServer.on('connection', (ws) => {
console.log(`Player connected to game world with game code ${gameCode}`);
ws.on('message', (message) => {handleGameWorldMessage(gameCode, message, ws)});
});
//Return this result to client after the server is created
let result = {status: "SUCCESS", type: "CREATE", gameCode: gameCode};
ws.send(JSON.stringify(result));
});
}
}
//Return the port number associated with the game code provided
function getPort(ws, gc) {
let gameData = codeToGameData.get(gc);
if(gameData !== undefined) {
let portNumber = gameData.port;
let result = {status: "SUCCESS", type: "PORT", port: portNumber};
ws.send(JSON.stringify(result));
} else {
ws.send(JSON.stringify({status: "FAILURE", msg: "Invalid game code"}));
}
}
//This function generates a unique game code
function generateGameCode() {
return Date.now();
}
/**************************************************** Game World Functions *******************************************************/
//This function handles messages sent to game worlds
function handleGameWorldMessage(gc, message, ws) {
let msg = JSON.parse(message);
let result = {};
console.log(`received message: ${message}`);
switch(msg.type) {
//When a player attempts to connect to a game world, assign the player a unique id and return it to them as part of the response
case "CONNECT":
if(codeToGameData.has(gc)) { //There is already game data associated with this game code. This should always be the
//case if the player provides game code for a created game
let gameData = codeToGameData.get(gc);
//You can only connect to a game that is in the waiting state
if(gameData.isGameWaiting()) {
let id = generateUniqueID();
let name = msg.name;
gameData.addPlayer(id, name, ws);
result = {status: "SUCCESS", type: "CONNECT", playerWaitlist: gameData.getPlayerNames(), id: id, gameCode: gc};
codeToGameData.get(gc).notifyPlayers(result);
} else {
result = {status: "FAILURE", msg: "Attempt to connect to a game that is not waiting to be connected to"};
ws.send(JSON.stringify(result));
}
} else {
result = {status: "FAILURE", msg: "Invalid game code provided on CONNECT"}
ws.send(JSON.stringify(result));
}
break;
case "START":
handleStartGame(gc, ws);
break;
default:
result = {status: "FAILURE", msg: `Invalid comamand: ${msg.type}`};
codeToGameData.get(gc).notifyPlayers(result);
break;
};
}
//This function handles a request to start a game given the game code associated with the game world
function handleStartGame(gc, ws) {
let gameData = codeToGameData.get(gc);
if(gameData) {
//Create a game piece for each player
gameData.createGamePieces();
//Create food in the game world
gameData.createFood();
//Signify that the game has started
if(gameData.isGameWaiting()) {
gameData.startGame();
gameData.notifyPlayers({status: "SUCCESS", type: "START", playerData: gameData.playerData, foodData: gameData.foodData, leaderboard: gameData.leaderboard});
} else {
ws.send(JSON.stringify({status: "FAILURE", msg: "Attempt to start a game that is not waiting to be started"}));
}
} else { //Notify the player that they game code they provided is invalid
ws.send(JSON.stringify({status: "FAILURE", msg: "Invalid game code provided on START"}));
}
}
//This function generates a unique player id
function generateUniqueID() {
return Date.now();
}
<file_sep>/game-data.js
const { GamePiece, FOOD, COLORS, MINIMUM_RADIUS } = require("./game-piece");
const { PlayerData } = require("./player-data");
const { LeaderBoard } = require("./leaderboard");
const MAX_X = 5000;
const MAX_Y = 5000;
const NUM_FOOD = 1000;
const FOOD_RADIUS = 10;
// A game can be in one of the following 3 states
const WAITING = "WAITING";
const STARTED = "STARTED";
const ENDED = "ENDED";
class GameData {
constructor() {
this._playerData = new Map(); //A map from player id to information about the player including information about the player's game piece.
this._numPlayers = 0; //The number of players in the game
this._maxX = MAX_X; //The largest x coordinate in the game
this._maxY = MAX_Y; //The largest y coordinate in the game
this._foodData = []; //A list of all the food in the game world.
this._leaderBoard = new LeaderBoard(); //An up to date listing of the players' scores
this._port = -1;
this._gameCode = -1;
this._gameState = WAITING;
}
//Expose a map from a players id to an object containing their id, name and game pieces only.
get playerData() {
let pd = new Map();
this._playerData.forEach((player, id, map) => {
pd.set(id, {id: id, name: player.name, pieces: player.pieces});
});
return pd;
}
get numPlayers() {
return this._numPlayers;
}
get maxX() {
return this._maxX;
}
get maxY() {
return this._maxY;
}
get foodData() {
return this._foodData;
}
get port() {
return this._port;
}
get gameCode() {
return this._gameCode;
}
get leaderboard() {
return this._leaderBoard.board;
}
get gameState() {
return this._gameState;
}
set port(port) {
this._port = port;
}
set gameCode(gc) {
this._gameCode = gc;
}
startGame() {
this._gameState = STARTED;
}
endGame() {
this._gameState = ENDED;
}
isGameWaiting() {
return this._gameState === WAITING;
}
isGameStarted() {
return this._gameState === STARTED;
}
isGameEnded() {
return this._gameState === ENDED;
}
//This method adds a player to the game
addPlayer(id, name, ws) {
if(!this._playerData.has(id)) { //Create a new player with the provided id and name
let playerData = new PlayerData(id, name, ws);
this._playerData.set(id, playerData);
this._numPlayers++;
}
this._leaderBoard.addPlayer(id); //Add the player to the leaderboard
}
//This method returns a list of player names
getPlayerNames() {
let res = [];
this._playerData.forEach((value, key, map) => {
res.push(value.name);
})
return res;
}
//This method sends message to all the players in the game via their web socket
notifyPlayers(message) {
this._playerData.forEach((player, id, map) => {
//Replace maps with objects whose dataType key signify that it is a map and whose
//value key is a 2d array representing all the entries in the map.
player.webSocket.send(JSON.stringify(message, (key, value) => {
if(value instanceof Map) {
return {
dataType: 'Map',
value: Array.from(value.entries()),
};
} else {
return value;
}
}));
})
}
//This method adds food to the game
createFood() {
for(let i = 0; i < NUM_FOOD; i++) {
let x = Math.floor(Math.random() * MAX_X);
let y = Math.floor(Math.random() * MAX_Y);
let foodPiece = new GamePiece(x, y, FOOD_RADIUS, FOOD, COLORS[(Math.floor(Math.random() * (COLORS.length - 1)))]);
this._foodData.push(foodPiece);
}
}
//This method creates game pieces for all players in the game
createGamePieces() {
this._playerData.forEach((player, id, map) => {
let x = Math.floor(Math.random() * MAX_X);
let y = Math.floor(Math.random() * MAX_Y);
player.addGamePiece(x, y, MINIMUM_RADIUS);
});
}
}
exports.GameData = GameData;<file_sep>/linked-list.js
class Node {
constructor(data, next) {
this._data = data;
this._next = next;
}
//Underscores are used to create backing states. Otherwise, a stack overflow will occur.
//The basic idea is that we want the name of the field as we store it to be slightly different from the
//name through which it is accessed or set.
get data() {
return this._data;
}
get next() {
return this._next;
}
set next(next) {
this._next = next;
}
set data(data) {
this._data = data;
}
}
class LinkedList {
constructor() {
this._head = null;
this._size = 0;
}
get size() {
return this._size;
}
set size(s) {
this._size = s;
}
//Add a node to the back of the linked list
addToBack(data) {
if(this._head === null) {
this._head = new Node(data, null);
} else {
let current = this._head;
while(current.next != null) {
current = current.next;
}
current.next = new Node(data, null);
}
this._size++;
}
//Add a node to the front of the linked list
addToFront(data) {
if(this._head === null) {
this._head = new Node(data, null);
} else {
let oldHead = this._head;
this._head = new Node(data, oldHead);
}
this.size++;
}
//Remove a node from the front of the linked list and return its data
removeFromFront() {
if(this._head == null) {
return null;
} else {
let retValue = this._head.data;
this._head = this._head.next;
this._size--;
return retValue;
}
}
//Remove a node from the back of the linked list and return its data
removeFromBack() {
if(this._head == null) {
return null;
} else {
let current = this._head;
let previous = null;
while(current.next !== null) {
previous = current;
current = current.next;
}
if(previous === null) { //We are removing the head
let retValue = this._head.data;
this._head = null;
this._size--;
return retValue;
} else {
let retValue = current.data;
previous.next = null;
this._size--;
return retValue;
}
}
}
}
exports.LinkedList = LinkedList;
<file_sep>/leaderboard.js
class LeaderBoard {
constructor() {
this._board = []; //An array where each entry is an object that contains the id of a player and thier score in descending
//order of their score.
}
get board() {
return this._board;
}
//Add a player to the leaderboard
addPlayer(id) {
let key = id;
this._board.push({id: id, score: 0});
}
//Adjust a players points up or down by points
adjustPoints(id, points) {
let player = undefined;
let playerIndex = -1;
//Find the player with the given id
for(let i = 0; i < this._board.length; i++) {
if(this._board[i].id === id) {
player = this._board[i];
playerIndex = i;
break;
}
}
//Adjust the points and move the player either up or down the leaderboard
if(player !== undefined) {
if(points > 0) { //Move the player up
for(let i = playerIndex - 1; i >= 0; i--) {
if(this._board[i].score < player.score) {
swap(i, playerIndex);
playerIndex = i;
} else {
break;
}
}
} else if(points < 0) { //Move the player down
for(let i = playerIndex + 1; i < this._board.length; i++) {
if(this._board[i].score > player.score) {
swap(i, playerIndex);
playerIndex = i;
} else {
break;
}
}
}
}
}
//This method swaps the values at the provided indices in the leaderboard
swap(i, j) {
let temp = this._board[j];
this._board[j] = this._board[i];
this._board[i] = temp;
}
}
exports.LeaderBoard = LeaderBoard; | 919de3e38c51157ca6c06ab3101a2b1422487dd9 | [
"JavaScript"
] | 6 | JavaScript | OlasubomiEfuniyi/game-backend | 2e679ad4b28ddf503c82d824b44f76150ea19a5d | ba9b02e06a14e177d3e410dcb6149118d4131ba0 |
refs/heads/master | <repo_name>MacAndKaj/SimpleEngine2D<file_sep>/src/include/Buttons/NormalButton.hpp
//
// Created by maciej on 13.08.18.
//
#ifndef ENGINE_NORMALBUTTON_HPP
#define ENGINE_NORMALBUTTON_HPP
//TODO implement
class NormalButton {
};
#endif //ENGINE_NORMALBUTTON_HPP
<file_sep>/tests/utils/mocks/IDectectorsModuleMock.hpp
//
// Created by mkajdak on 30.08.18.
//
#ifndef ENGINE_IDECTECTORSMODULEMOCK_HPP
#define ENGINE_IDECTECTORSMODULEMOCK_HPP
#include <gmock/gmock.h>
#include <Modules/IDetectorsModule.hpp>
namespace eng
{
namespace det
{
class IDetectorsModuleMock : public IDetectorsModule
{
public:
MOCK_CONST_METHOD0(getCollisionDetector,ICollisionDetector&());
MOCK_CONST_METHOD0(getEventDetector,IEventDetector&());
};
}
}
#endif //ENGINE_IDECTECTORSMODULEMOCK_HPP
<file_sep>/tests/utils/mocks/ICollisionDetectorMock.hpp
//
// Created by maciejkajdak on 06.09.18.
//
#ifndef ENGINE_ICOLLISIONDETECTORMOCK_HPP
#define ENGINE_ICOLLISIONDETECTORMOCK_HPP
#include <gmock/gmock.h>
#include <Detectors/ICollisionDetector.hpp>
namespace eng
{
namespace det
{
class ICollisionDetectorMock : public ICollisionDetector
{
public:
MOCK_METHOD2(startMonitoring,void(
std::function<void(sf::Event::EventType)> ¬ifier,
std::shared_ptr<ICollisionDetector> generator));
MOCK_METHOD0(isMonitoring,bool());
MOCK_METHOD0(stopMonitoring,void());
};
}
}
#endif //ENGINE_ICOLLISIONDETECTORMOCK_HPP
<file_sep>/tests/UT/EventDetectorTests.cpp
//
// Created by mkajdak on 30.08.18.
//
#include <gtest/gtest.h>
#include <mocks/IEventGeneratorMock.hpp>
#include <Detectors/EventDetector.hpp>
#include <Engine.hpp>
#include <chrono>
using ::testing::_;
using ::testing::Return;
using namespace testing;
using namespace std::literals::chrono_literals;
namespace eng
{
namespace det
{
class EventDetectorTests : public ::testing::Test
{
public:
EventDetectorTests()
: _engine(new Engine)
, _sut(_engine->getDetectorsModule().getEventDetector())
{
_eventGeneratorMock = std::make_shared<IEventGeneratorMock>();
}
void callback(sf::Event)
{
_callbackApplied = true;
}
void isEventTypeEqualToGainedFocus(sf::Event event)
{
_callbackApplied = event.type == sf::Event::GainedFocus;
}
bool _callbackApplied;
std::shared_ptr<IEventGeneratorMock> _eventGeneratorMock;
std::unique_ptr<Engine> _engine;
std::reference_wrapper<IEventDetector> _sut;
};
TEST_F(EventDetectorTests, EventDetectorTests_ShouldHandleEventAndStartMonitoring_Test)
{
_callbackApplied = false;
std::function<void(sf::Event)> func =
std::bind(&EventDetectorTests::callback,this,std::placeholders::_1);
_eventGeneratorMock->delegateToFake();
_sut.get().startMonitoring(func,_eventGeneratorMock);
ASSERT_TRUE(_sut.get().isMonitoring());
std::this_thread::sleep_for(std::chrono::milliseconds(10));
_sut.get().stopMonitoring();
ASSERT_FALSE(_sut.get().isMonitoring());
ASSERT_TRUE(_callbackApplied);
}
TEST_F(EventDetectorTests, EventDetectorTests_ShouldHandleCloseEvent_Test)
{
_callbackApplied = false;
std::function<void(sf::Event)> func =
std::bind(&EventDetectorTests::isEventTypeEqualToGainedFocus,this,std::placeholders::_1);
_eventGeneratorMock->delegateToFake();
_sut.get().startMonitoring(func,_eventGeneratorMock);
ASSERT_TRUE(_sut.get().isMonitoring());
std::this_thread::sleep_for(std::chrono::nanoseconds(10));
_sut.get().stopMonitoring();
ASSERT_TRUE(_callbackApplied);
}
}
}<file_sep>/src/include/Interface/IElement.hpp
//
// Created by mkajdak on 29.08.18.
//
#ifndef ENGINE_IELEMENT_HPP
#define ENGINE_IELEMENT_HPP
#include <Helpers/ElementProperties.hpp>
#include <SFML/Graphics/Drawable.hpp>
#include <functional>
class LetterButton;
namespace eng
{
class IElement : public sf::Drawable
{
public:
IElement() : _elementProperties(0, 0)
{}
IElement(const IElement &) = delete;
virtual ElementProperties getElementProperties() const = 0;
virtual unsigned int getElementID() const = 0;
protected:
ElementProperties _elementProperties;
};
}
#endif //ENGINE_IELEMENT_HPP
<file_sep>/src/CMakeLists.txt
include_directories(include)
file(GLOB src_files
sources/Animations/*.cpp
sources/Buttons/*.cpp
sources/Detectors/*.cpp
sources/Helpers/*.cpp
sources/Modules/*.cpp
sources/Scenario/*.cpp
sources/Windows/*.cpp
sources/Generators/*.cpp
sources/*.cpp)
add_library(MyLib ${src_files})
find_package(Threads REQUIRED)
add_executable(${EXECUTABLE_NAME} MainWrapper.cpp)
target_link_libraries(${EXECUTABLE_NAME} MyLib pthread)
find_package(SFML 2.5 REQUIRED network audio graphics window system)
if (SFML_FOUND)
include_directories(${SFML_INCLUDE_DIR})
target_link_libraries(${EXECUTABLE_NAME} ${SFML_LIBRARIES} ${SFML_DEPENDENCIES})
endif ()
<file_sep>/src/sources/Detectors/CollisionDetector.cpp
//
// Created by maciej on 26.08.18.
//
#include <Detectors/CollisionDetector.hpp>
namespace eng
{
namespace det
{
CollisionDetector::CollisionDetector()
: _log("CollisionDetector")
{
}
CollisionDetector::~CollisionDetector()
{
}
void CollisionDetector::startMonitoring(std::function<void(sf::Event::EventType)> ¬ifier,
std::shared_ptr<ICollisionDetector> generator)
{
}
void CollisionDetector::stopMonitoring()
{
}
bool CollisionDetector::isMonitoring()
{
return false;
}
} //det
} //eng<file_sep>/tests/utils/mocks/IEngineMock.hpp
//
// Created by mkajdak on 30.08.18.
//
#include <gmock/gmock.h>
#include <Engine.hpp>
namespace eng
{
class IEngineMock : public Engine
{
public:
MOCK_CONST_METHOD0(getDetectorsModule, det::IDetectorsModule & ());
};
}<file_sep>/src/include/Engine.hpp
//
// Created by mkajdak on 28.08.18.
//
#ifndef ENGINE_ENGINE_HPP
#define ENGINE_ENGINE_HPP
#include <Modules/DetectorsModule.hpp>
#include "IEngine.hpp"
namespace eng
{
class Engine : public IEngine
{
public:
~Engine() override;
const det::IDetectorsModule &getDetectorsModule() const override;
//protected:
Engine();
private:
std::unique_ptr<det::IDetectorsModule> _detectorsModule;
Logger _log;
};
} //eng
#endif //ENGINE_ENGINE_HPP
<file_sep>/src/include/Animations/AnimationSprite.hpp
//
// Created by mkajdak on 28.08.18.
//
#ifndef ENGINE_ANIMATIONSPRITE_HPP
#define ENGINE_ANIMATIONSPRITE_HPP
//TODO implement
class AnimationSprite
{
};
#endif //ENGINE_ANIMATIONSPRITE_HPP
<file_sep>/tests/UT/ElementPropertiesTests.cpp
//
// Created by mkajdak on 29.08.18.
//
#include <gtest/gtest.h>
#include <Helpers/ElementProperties.hpp>
using namespace eng;
class ElementPropertiesTests : public ::testing::Test
{
public:
void startService()
{
_sut = std::make_unique<ElementProperties>(0,0);
}
std::unique_ptr<ElementProperties> _sut;
};
TEST_F(ElementPropertiesTests, ElementPropertiesTests_ShouldStoreOnlyCopy_Test)
{
startService();
auto element = (*_sut);
ASSERT_EQ(_sut->getID(),1);
ASSERT_EQ(element.getID(),1);
}
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
project(ENGINE)
set(CMAKE_CXX_STANDARD 14)
set(EXECUTABLE_NAME "PARANOID")
set(CMAKE_BINARY_DIR ${CMAKE_SOURCE_DIR}/build)
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR})
set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR})
set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake_modules")
if (${TARGET} tests)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D_MYSYMBOL")
endif ()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DDEBUG")
add_subdirectory(src)
add_subdirectory(tests)
FILE(COPY Resoures/Pacific_Again.ttf DESTINATION "${CMAKE_BINARY_DIR}")
FILE(COPY Resoures/icon.png DESTINATION "${CMAKE_BINARY_DIR}")
<file_sep>/src/include/Detectors/EventDetector.hpp
//
// Created by maciej on 27.08.18.
//
#ifndef ENGINE_EVENTDETECTOR_HPP
#define ENGINE_EVENTDETECTOR_HPP
#include <Detectors/IEventDetector.hpp>
#include <Logger.hpp>
#include <SFML/Window.hpp>
namespace eng
{
class DetectorsModule;
namespace det
{
class EventDetector : public IEventDetector
{
public:
virtual ~EventDetector();
void startMonitoring(std::function<void(sf::Event)> ¬ifier
, std::shared_ptr<IEventGenerator> generator) override;
void stopMonitoring() override;
void handleEvents( std::shared_ptr<IEventGenerator> generator);
bool isMonitoring() override;
private:
EventDetector();
Logger _log;
std::function<void(sf::Event)> _notifier;
std::vector<std::thread> _detectorThreads;
friend class DetectorsModule;
bool _monitoring;
};
} // det
} // eng
#endif //ENGINE_EVENTDETECTOR_HPP
<file_sep>/src/MainWrapper.cpp
#include <SFML/Graphics/Rect.hpp>
#include <SFML/Graphics.hpp>
#include <random>
#include <functional>
#include <cstdlib>
#include <cmath>
#include <Engine.hpp>
#include <Windows/MainWindow.hpp>
class MainWrapper
{
public:
int execute();
};
int MainWrapper::execute()
{
return 0;
}
int main()
{
eng::Engine engine;
auto window = std::make_unique<MainWindow>(engine);
return window->run();
}<file_sep>/tests/CMakeLists.txt
file(GLOB SRCS UT/*.cpp)
find_package(Threads REQUIRED)
include_directories ("${PROJECT_SOURCE_DIR}/src/include" "utils")
add_executable(tests ${SRCS})
# files are only copied if a target depends on them
#add_custom_target(tests ALL DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/Pacific_Again.ttf")
################################
find_package(SFML 2.5 REQUIRED network audio graphics window system)
if(SFML_FOUND)
include_directories(${SFML_INCLUDE_DIR})
endif()
find_package(GTest REQUIRED)
if (GTEST_FOUND)
include_directories(${GTEST_INCLUDE_DIRS} ${GMOCK_INCLUDE_DIRS})
endif ()
enable_testing()
target_link_libraries(tests gtest gmock gtest_main MyLib pthread ${SFML_LIBRARIES} ${SFML_DEPENDENCIES})
#install(TARGETS tests DESTINATION build)<file_sep>/tests/UT/CollisionDetectorTests.cpp
//
// Created by mkajdak on 30.08.18.
//
<file_sep>/src/sources/Windows/InfoWindow.cpp
//
// Created by mkajdak on 28.08.18.
//
#include "Windows/InfoWindow.hpp"
<file_sep>/tests/UT/MainWindowTests.cpp
//
// Created by mkajdak on 30.08.18.
//
#include <gtest/gtest.h>
#include <Windows/MainWindow.hpp>
#include <mocks/IEngineMock.hpp>
#include <mocks/IDectectorsModuleMock.hpp>
#include <mocks/IEventDetectorMock.hpp>
#include <mocks/ICollisionDetectorMock.hpp>
#include <Buttons/LetterButton.hpp>
using ::testing::_;
using ::testing::Return;
using namespace testing;
class MainWindowTests : public ::testing::Test
{
public:
protected:
virtual void SetUp()
{
_sut = std::make_unique<MainWindow>(_engineMock);
}
MainWindowTests()
{
EXPECT_CALL(_engineMock, getDetectorsModule()).
WillRepeatedly(ReturnRef(_detectorsModuleMock));
EXPECT_CALL(_detectorsModuleMock,getCollisionDetector()).
WillOnce(ReturnRef(_collisionDetectorMock));
EXPECT_CALL(_detectorsModuleMock,getEventDetector()).
WillOnce(ReturnRef(_eventDetectorMock));
}
eng::det::IEventDetectorMock _eventDetectorMock;
eng::det::ICollisionDetectorMock _collisionDetectorMock;
eng::det::IDetectorsModuleMock _detectorsModuleMock;
eng::IEngineMock _engineMock;
std::unique_ptr<MainWindow> _sut;
};
TEST_F(MainWindowTests, MainWindowTests_ShouldCloseWhileExit_Test)
{
}
TEST_F(MainWindowTests, MainWindowTests_ShouldAddCorrectElements_Test)
{
unsigned int nrOfElement = 1;
ASSERT_FALSE(_sut->isElement(nrOfElement));
auto button = std::make_unique<LetterButton>();
auto element = std::unique_ptr<IElement>(button.release()->getAsElement());
std::cout << element->getElementID() << std::endl;
nrOfElement = element->getElementID();
_sut->addItemToDraw(element);
ASSERT_TRUE(_sut->isElement(nrOfElement));
}
<file_sep>/src/sources/Generators/EventGenerator.cpp
//
// Created by maciejkajdak on 06.09.18.
//
#include <Generators/EventGenerator.hpp>
namespace eng
{
namespace det
{
EventGenerator::EventGenerator(sf::Window &window)
: _window(window)
{
}
bool EventGenerator::pollEvent(sf::Event& event)
{
if (not _window.get().isOpen()) return false;
return _window.get().pollEvent(event);
}
}
}<file_sep>/src/sources/Manager.cpp
//
// Created by mkajdak on 29.08.18.
//
#include <Manager.hpp>
<file_sep>/src/include/IManager.hpp
//
// Created by mkajdak on 30.08.18.
//
#ifndef ENGINE_IMANAGER_HPP
#define ENGINE_IMANAGER_HPP
class IManager
{
};
#endif //ENGINE_IMANAGER_HPP
<file_sep>/src/sources/Modules/DetectorsModule.cpp
//
// Created by mkajdak on 28.08.18.
//
#include <Modules/DetectorsModule.hpp>
#include <Detectors/CollisionDetector.hpp>
#include <Detectors/EventDetector.hpp>
namespace eng
{
namespace det
{
DetectorsModule::DetectorsModule()
: _log("DetectorsModule")
, _collisionDetectorPtr(new CollisionDetector)
, _eventDetectorPtr(new EventDetector)
{
}
DetectorsModule::~DetectorsModule()
{
}
ICollisionDetector & DetectorsModule::getCollisionDetector() const
{
return *_collisionDetectorPtr;
}
IEventDetector &DetectorsModule::getEventDetector() const
{
return *_eventDetectorPtr;
}
} // det
} // eng<file_sep>/src/include/Modules/DetectorsModule.hpp
//
// Created by mkajdak on 28.08.18.
//
#ifndef ENGINE_DETECTORSMODULE_HPP
#define ENGINE_DETECTORSMODULE_HPP
#include <Logger.hpp>
#include "IDetectorsModule.hpp"
namespace eng
{
class Engine;
namespace det
{
class CollisionDetector;
class EventDetector;
class DetectorsModule : public IDetectorsModule
{
public:
ICollisionDetector & getCollisionDetector() const override;
IEventDetector &getEventDetector() const override;
~DetectorsModule() override;
protected:
DetectorsModule();
private:
Logger _log;
std::unique_ptr<CollisionDetector> _collisionDetectorPtr;
std::unique_ptr<EventDetector> _eventDetectorPtr;
friend class eng::Engine;
};
} //det
} //eng
#endif //ENGINE_DETECTORSMODULE_HPP
<file_sep>/README.md
# SimpleEngine2D
Trying to create very simple 2D engine fo self-learning.
<file_sep>/tests/utils/mocks/IEventDetectorMock.hpp
//
// Created by mkajdak on 30.08.18.
//
#ifndef ENGINE_IDETECTORMOCK_HPP
#define ENGINE_IDETECTORMOCK_HPP
#include <gmock/gmock.h>
#include <Detectors/IEventDetector.hpp>
namespace eng
{
namespace det
{
class IEventDetectorMock :public IEventDetector
{
public:
MOCK_METHOD2(startMonitoring,void(
std::function<void(sf::Event)> ¬ifier,
std::shared_ptr<IEventGenerator> generator));
MOCK_METHOD0(stopMonitoring,void());
MOCK_METHOD0(isMonitoring,bool());
};
} //det
} //det
#endif //ENGINE_IDETECTORMOCK_HPP
<file_sep>/tests/utils/mocks/IEventGeneratorMock.hpp
//
// Created by maciejkajdak on 06.09.18.
//
#ifndef ENGINE_IEVENTGENERATORMOCK_HPP
#define ENGINE_IEVENTGENERATORMOCK_HPP
#include <gmock/gmock.h>
#include <Generators/IEventGenerator.hpp>
using ::testing::_;
using ::testing::Invoke;
using ::testing::Return;
namespace eng
{
namespace det
{
class IEventGeneratorMock : public IEventGenerator
{
public:
MOCK_METHOD1(pollEvent,bool(sf::Event& event));
void delegateToFake()
{
EXPECT_CALL(*this,pollEvent(_))
.WillOnce(Invoke(this,&IEventGeneratorMock::fakePollEvent))
.WillRepeatedly(Return(true));
}
bool fakePollEvent(sf::Event& event)
{
event.type = sf::Event::GainedFocus;
return true;
}
};
}
}
#endif //ENGINE_IEVENTGENERATORMOCK_HPP
<file_sep>/src/include/Logger.hpp
//
// Created by maciej on 20.08.18.
//
#ifndef ENGINE_LOGGER_HPP
#define ENGINE_LOGGER_HPP
#include <fstream>
#include <memory>
const unsigned int maxBufferSize = 1024;
enum class logging{
logEnd,
warning,
debug
};
class Logger
{
public:
Logger () = delete;
explicit Logger (const std::string &_nameOfLoggerOwner);
virtual ~Logger ();
void setNameOfLoggerOwner (const std::string &nameOfLoggerOwner);
private:
void addToBuffer(const std::string& arg) const{_buffer.append(arg);}
void clearBuffer()const;
mutable std::string _buffer;
std::string _nameOfLoggerOwner;
static std::unique_ptr<std::ofstream> _logFile;
static void initLogFile();
friend const Logger& operator << (const Logger &log, const char* strm);
friend const Logger& operator << (const Logger &log, const logging& strm);
};
#endif //ENGINE_LOGGER_HPP
<file_sep>/src/include/Modules/FPSModule.hpp
//
// Created by mkajdak on 29.08.18.
//
#ifndef ENGINE_FPSMODULE_HPP
#define ENGINE_FPSMODULE_HPP
class FPSModule
{
};
#endif //ENGINE_FPSMODULE_HPP
<file_sep>/src/sources/Buttons/NormalButton.cpp
//
// Created by maciej on 13.08.18.
//
#include <Buttons/NormalButton.hpp>
<file_sep>/src/sources/Logger.cpp
//
//
// Created by maciej on 20.08.18.
#include <Logger.hpp>
#include <ctime>
#if defined(DEBUG)
#include <iostream>
#endif
using namespace std;
unique_ptr<ofstream> Logger::_logFile = unique_ptr<ofstream>(nullptr);
Logger::Logger(const string &_nameOfLoggerOwner) : _nameOfLoggerOwner(_nameOfLoggerOwner)
{
if (not Logger::_logFile) initLogFile();
}
void Logger::initLogFile()
{
auto now = time(nullptr);
auto timeNow = localtime(&now);
string fileName = "logs/";
fileName += to_string(timeNow->tm_year);
fileName += to_string(timeNow->tm_mon);
fileName += to_string(timeNow->tm_mday);
fileName += to_string(timeNow->tm_hour);
fileName += to_string(timeNow->tm_min);
fileName += ".log";
Logger::_logFile = make_unique<ofstream>(fileName);
}
Logger::~Logger()
{
if (_logFile)
{
clearBuffer();
if (_logFile->is_open()) _logFile->close();
}
}
void Logger::clearBuffer()const
{
if (_buffer.empty()) return;
*_logFile << '[' << _nameOfLoggerOwner << "] " << _buffer << '\n';
#if defined(DEBUG)
std::cout << '[' << _nameOfLoggerOwner << "] " << _buffer << std::endl;
#endif
_buffer.clear();
}
void Logger::setNameOfLoggerOwner(const string &nameOfLoggerOwner)
{
_nameOfLoggerOwner = nameOfLoggerOwner;
}
const Logger &operator<<(const Logger &log, const char *strm)
{
std::string tmp{strm};
tmp += ' ';
if (not tmp.empty())
{
log.addToBuffer(strm);
}
return log;
}
const Logger &operator<<(const Logger &log, const logging &strm)
{
if (strm == logging::logEnd)
{
log.clearBuffer();
}
return log;
}<file_sep>/src/include/IEngine.hpp
//
// Created by mkajdak on 30.08.18.
//
#ifndef ENGINE_IENGINE_HPP
#define ENGINE_IENGINE_HPP
#include <Modules/DetectorsModule.hpp>
namespace eng
{
class IEngine
{
public:
virtual ~IEngine() = default;;
virtual const det::IDetectorsModule &getDetectorsModule() const = 0;
};
} //eng
#endif //ENGINE_IENGINE_HPP
<file_sep>/src/include/Windows/MainWindow.hpp
//
// Created by maciej on 16.08.18.
//
#ifndef ENGINE_MAINWINDOW_HPP
#define ENGINE_MAINWINDOW_HPP
#include <map>
#include <SFML/Graphics/RenderWindow.hpp>
#include <Detectors/EventDetector.hpp>
#include <Detectors/CollisionDetector.hpp>
#include <Helpers/ElementProperties.hpp>
#include <Interface/IElement.hpp>
#include <Engine.hpp>
#include <Generators/IEventGenerator.hpp>
using namespace eng;
class MainWindow
{
public:
explicit MainWindow(IEngine &engine);
virtual ~MainWindow()
{};
int run();
void addItemToDraw(std::unique_ptr<IElement> &);
bool isElement(const unsigned int &id) const;
void handleEvent(sf::Event event);
//get
unsigned int getWindowHeight() const;
unsigned int getWindowWidth() const;
const std::string &getWindowTitle() const;
//set
void setWindowHeight(unsigned int windowHeight);
void setWindowWidth(unsigned int windowWidth);
void setWindowTitle(const std::string &windowTitle);
private:
void drawAllElements();
void closeWindow();
void keyPressed(sf::Event &event);
unsigned int _windowHeight;
unsigned int _windowWidth;
sf::Color _defaultWindowColor;
det::IEventDetector &_eventDetector;
det::ICollisionDetector &_collisionDetector;
std::shared_ptr<det::IEventGenerator> _eventGenerator;
std::string _windowTitle;
std::map<unsigned int, std::unique_ptr<IElement>> _allDrawableItems;
Logger _log;
std::unique_ptr<sf::RenderWindow> _handlerWindow;
};
#endif //ENGINE_MAINWINDOW_// HPP
<file_sep>/src/sources/Buttons/LetterButton.cpp
//
// Created by maciej on 12.08.18.
//
#include <Buttons/LetterButton.hpp>
#include <iostream>
LetterButton::LetterButton()
: _log("LetterButton")
, _clicked(false)
, _focused(false)
{
_buttonText.setString("LetterButton");
if (!_font.loadFromFile("Pacific_Again.ttf"))
{
_log << __FUNCTION__ << "Error while loading font!" << logging::logEnd;
}
_buttonText.setFont(_font);
_buttonText.setFillColor(_basicColor);
}
LetterButton::~LetterButton()
{
}
void LetterButton::click()
{
if (_focused)
{
_buttonText.setFillColor(_onClickColor);
_clicked = true;
}
}
void LetterButton::unclick()
{
if (_clicked)
{
if (_callback)
{
_log << __FUNCTION__ << " callback applied." << logging::logEnd;
_callback();
}
_buttonText.setFillColor(_onFocusColor);
_clicked = false;
}
}
bool LetterButton::isClicked()
{
return _clicked;
}
void LetterButton::setFunctionality(std::function<void()> &functionality)
{
_callback = functionality;
}
void LetterButton::draw(sf::RenderTarget &target, sf::RenderStates states) const
{
target.draw(_buttonText, states);
}
void LetterButton::setBasicColor(const sf::Color &basicColor)
{
_basicColor = basicColor;
}
void LetterButton::setOnFocusColor(const sf::Color &onFocusColor)
{
_onFocusColor = onFocusColor;
}
void LetterButton::setOnClickColor(const sf::Color &onClickColor)
{
_onClickColor = onClickColor;
}
void LetterButton::focus()
{
if (not _focused)
{
_buttonText.setFillColor(_onFocusColor);
_focused = true;
}
}
void LetterButton::unfocus()
{
if (_focused)
{
_buttonText.setFillColor(_basicColor);
_focused = false;
}
}
void LetterButton::setButtonText(const std::string &buttonText)
{
_buttonText.setString(buttonText);
_log.setNameOfLoggerOwner("LetterButton(" + buttonText + ')');
}
eng::ElementProperties LetterButton::getElementProperties() const
{
return _elementProperties;
}
unsigned int LetterButton::getElementID() const
{
return _elementProperties.getID();
}
eng::IElement *LetterButton::getAsElement()
{
return this;
}<file_sep>/src/sources/Detectors/EventDetector.cpp
//
// Created by maciej on 27.08.18.
//
#include <Detectors/EventDetector.hpp>
#include <iostream>
#include <future>
namespace eng
{
namespace det
{
EventDetector::EventDetector()
: _log("EventDetector")
, _monitoring(false)
{
}
EventDetector::~EventDetector()
{
stopMonitoring();
}
void EventDetector::startMonitoring(std::function<void(sf::Event)> ¬ifier
, std::shared_ptr<IEventGenerator> generator)
{
_monitoring = true;
_notifier = notifier;
auto thr = std::thread(&EventDetector::handleEvents,this,generator);
_detectorThreads.push_back(std::move(thr));
}
void EventDetector::stopMonitoring()
{
_monitoring = false;
for (auto &item : _detectorThreads)
{
if (item.joinable())item.join();
}
}
void EventDetector::handleEvents( std::shared_ptr<IEventGenerator> generator )
{
_log << __FUNCTION__ << " started for window" << logging::logEnd;
sf::Event event{};
while(_monitoring)
{
if(generator->pollEvent(event))
{
if(_notifier)
_notifier(event);
}
}
_log << __FUNCTION__ << " stopped for window" << logging::logEnd;
}
bool EventDetector::isMonitoring()
{
return _monitoring;
}
} //det
} //eng<file_sep>/tests/UT/LetterButtonTests.cpp
//
// Created by mkajdak on 17.08.18.
//
#include <gtest/gtest.h>
#include <cmath>
#include <Buttons/LetterButton.hpp>
#include <SFML/Window/Mouse.hpp>
#include <Interface/ICallable.hpp>
class LetterButtonTests : public ::testing::Test
{
public:
void startService()
{
this->_sut = std::make_unique<LetterButton>();
}
void callback()
{
_change = true;
}
bool _change{};
std::unique_ptr<LetterButton> _sut;
};
TEST_F(LetterButtonTests, LetterButtonTests_ShouldChangeState_Test)
{
startService();
_sut->focus();
_sut->click();
ASSERT_TRUE(_sut->isClicked());
_sut->unclick();
ASSERT_FALSE(_sut->isClicked());
_sut->unfocus();
_sut->click();
ASSERT_FALSE(_sut->isClicked());
_sut->unclick();
ASSERT_FALSE(_sut->isClicked());
}
TEST_F(LetterButtonTests, LetterButtonTests_ShouldHandleFunctionality_Test)
{
startService();
_change = false;
std::function<void(void)> func = std::bind(&LetterButtonTests::callback, this);
_sut->setFunctionality(func);
_sut->focus();
_sut->click();
_sut->unclick();
ASSERT_TRUE(_change);
}
TEST_F(LetterButtonTests, LetterButtonTests_ShouldNotHandleFunctionality_Test)
{
startService();
_change = false;
std::function<void(void)> func = std::bind(&LetterButtonTests::callback, this);
_sut->setFunctionality(func);
_sut->click();
ASSERT_FALSE(_change);
_sut->unclick();
ASSERT_FALSE(_change);
}
<file_sep>/src/sources/Modules/FPSModule.cpp
//
// Created by mkajdak on 29.08.18.
//
#include <Modules/FPSModule.hpp>
<file_sep>/src/include/Windows/InfoWindow.hpp
//
// Created by mkajdak on 28.08.18.
//
#ifndef ENGINE_INFOWINDOW_HPP
#define ENGINE_INFOWINDOW_HPP
//TODO implement
class InfoWindow
{
};
#endif //ENGINE_INFOWINDOW_HPP
<file_sep>/src/include/Detectors/ICollisionDetector.hpp
//
// Created by maciejkajdak on 06.09.18.
//
#ifndef ENGINE_ICOLLISIONDETECTOR_HPP
#define ENGINE_ICOLLISIONDETECTOR_HPP
#include <SFML/Window.hpp>
#include <functional>
#include <memory>
namespace eng
{
namespace det
{
class ICollisionDetector
{
public:
virtual ~ICollisionDetector(){};
virtual void startMonitoring(std::function<void(sf::Event::EventType)> ¬ifier,
std::shared_ptr<ICollisionDetector> generator) = 0;
virtual void stopMonitoring() = 0;
virtual bool isMonitoring() = 0;
};
} //det
} //eng
#endif //ENGINE_ICOLLISIONDETECTOR_HPP
<file_sep>/src/sources/Windows/MainWindow.cpp
//
// Created by maciej on 16.08.18.
//
#include <SFML/Window/Event.hpp>
#include <Windows/MainWindow.hpp>
#include <Generators/EventGenerator.hpp>
using namespace eng;
MainWindow::MainWindow(IEngine &engine)
: _log("MainWindow")
, _defaultWindowColor(sf::Color::Black)
, _eventDetector(engine.getDetectorsModule().getEventDetector())
, _collisionDetector(engine.getDetectorsModule().getCollisionDetector())
, _windowTitle("MainWindow")
{
auto desktopMode = sf::VideoMode::getDesktopMode();
_windowWidth = desktopMode.width;
_windowHeight = desktopMode.height;
_handlerWindow = std::make_unique<sf::RenderWindow>(
sf::VideoMode(_windowWidth, _windowHeight), _windowTitle);
_eventGenerator = std::make_shared<det::EventGenerator>(std::ref(*_handlerWindow));
}
int MainWindow::run()
{
std::function<void(sf::Event)> func =
std::bind(&MainWindow::handleEvent,this,std::placeholders::_1);
_eventDetector.startMonitoring(func,_eventGenerator);
_handlerWindow->setVisible(true);
while (_handlerWindow->isOpen() and _eventDetector.isMonitoring())
{
_handlerWindow->clear(_defaultWindowColor);
if(not _allDrawableItems.empty()) drawAllElements();
_handlerWindow->display();
}
_eventDetector.stopMonitoring();
return EXIT_SUCCESS;
}
void MainWindow::addItemToDraw(std::unique_ptr<IElement> &item)
{
_log << __FUNCTION__ << " element ID: " <<
std::to_string(item->getElementID()).c_str() << logging::logEnd;
_allDrawableItems.insert(std::make_pair(
item->getElementID(), std::move(item)));
}
void MainWindow::drawAllElements()
{
if (not _allDrawableItems.empty())
{
for (const auto &drawableItem : _allDrawableItems)
{
_handlerWindow->draw(*(drawableItem.second));
}
}
else
{
_log << "Nothing to draw!" << logging::logEnd;
}
}
unsigned int MainWindow::getWindowHeight() const
{
return _windowHeight;
}
void MainWindow::setWindowHeight(unsigned int windowHeight)
{
_windowHeight = windowHeight;
}
unsigned int MainWindow::getWindowWidth() const
{
return _windowWidth;
}
void MainWindow::setWindowWidth(unsigned int windowWidth)
{
_windowWidth = windowWidth;
}
const std::string &MainWindow::getWindowTitle() const
{
return _windowTitle;
}
void MainWindow::setWindowTitle(const std::string &windowTitle)
{
_windowTitle = windowTitle;
}
bool MainWindow::isElement(const unsigned int &id) const
{
if (_allDrawableItems.find(id) != _allDrawableItems.end())
{
return true;
}
else
{
_log << __FUNCTION__ << "element with ID:" << std::to_string(id).c_str() << " not found" << logging::logEnd;
}
return false;
}
void MainWindow::handleEvent(sf::Event event)
{
switch (event.type)
{
case sf::Event::Closed:
closeWindow();
break;
case sf::Event::KeyPressed:
keyPressed(event);
break;
}
}
void MainWindow::closeWindow()
{
_handlerWindow->close();
}
void MainWindow::keyPressed(sf::Event& event)
{
if(event.key.code == sf::Keyboard::Escape) closeWindow();
}
<file_sep>/src/include/Modules/IDetectorsModule.hpp
//
// Created by mkajdak on 30.08.18.
//
#ifndef ENGINE_IDETECTORSMODULE_HPP
#define ENGINE_IDETECTORSMODULE_HPP
#include <Detectors/ICollisionDetector.hpp>
namespace eng
{
namespace det
{
class IEventDetector;
class IDetectorsModule
{
public:
virtual ~IDetectorsModule() {};
virtual ICollisionDetector & getCollisionDetector() const =0;
virtual IEventDetector &getEventDetector() const = 0;
};
}
}
#endif //ENGINE_IDETECTORSMODULE_HPP
<file_sep>/src/include/Generators/IEventGenerator.hpp
//
// Created by maciejkajdak on 06.09.18.
//
#ifndef ENGINE_IEVENTGENERATOR_HPP
#define ENGINE_IEVENTGENERATOR_HPP
#include <SFML/Window/Event.hpp>
namespace eng
{
namespace det
{
class IEventGenerator
{
public:
virtual ~IEventGenerator(){}
virtual bool pollEvent(sf::Event& event) = 0;
};
}
}
#endif //ENGINE_IEVENTGENERATOR_HPP
<file_sep>/src/sources/Animations/Animation.cpp
//
// Created by mkajdak on 28.08.18.
//
#include <Animations/Animation.hpp>
<file_sep>/src/include/Detectors/IEventDetector.hpp
//
// Created by maciej on 27.08.18.
//
#ifndef ENGINE_IDETECTOR_HPP
#define ENGINE_IDETECTOR_HPP
#include <functional>
#include <SFML/Window/Event.hpp>
#include <thread>
#include <Generators/IEventGenerator.hpp>
namespace eng
{
namespace det
{
class IEventDetector
{
public:
virtual void startMonitoring(std::function<void(sf::Event)> ¬ifier
, std::shared_ptr<IEventGenerator> generator) = 0;
virtual void stopMonitoring() = 0;
virtual bool isMonitoring() = 0;
};
} //det
} //eng
#endif //ENGINE_IDETECTOR_HPP
<file_sep>/src/include/Generators/EventGenerator.hpp
//
// Created by maciejkajdak on 06.09.18.
//
#ifndef ENGINE_EVENTGENERATOR_HPP
#define ENGINE_EVENTGENERATOR_HPP
#include <SFML/Window.hpp>
#include "IEventGenerator.hpp"
#include <memory>
namespace eng
{
namespace det
{
class EventGenerator : public IEventGenerator
{
public:
explicit EventGenerator(sf::Window &window);
bool pollEvent(sf::Event& event) override;
std::reference_wrapper<sf::Window> _window;
};
}
}
#endif //ENGINE_EVENTGENERATOR_HPP
<file_sep>/src/include/Manager.hpp
//
// Created by mkajdak on 29.08.18.
//
#ifndef ENGINE_MANAGER_HPP
#define ENGINE_MANAGER_HPP
class Manager
{
};
#endif //ENGINE_MANAGER_HPP
<file_sep>/src/sources/Engine.cpp
//
// Created by mkajdak on 28.08.18.
//
#include <Engine.hpp>
namespace eng
{
Engine::Engine()
: _log("Engine")
, _detectorsModule(new det::DetectorsModule())
{
}
Engine::~Engine()
{
}
const det::IDetectorsModule &Engine::getDetectorsModule() const
{
return *_detectorsModule;
}
}<file_sep>/src/include/Helpers/ElementProperties.hpp
//
// Created by mkajdak on 29.08.18.
//
#ifndef ENGINE_ELEMENTPROPERTIES_HPP
#define ENGINE_ELEMENTPROPERTIES_HPP
#include <SFML/System.hpp>
#include <Logger.hpp>
namespace eng
{
class ElementProperties
{
public:
ElementProperties() = delete;
ElementProperties(unsigned int positionCentralY, unsigned int positionCentralX);
ElementProperties(const ElementProperties& elementProperties);
//set
unsigned int getPositionCentralY() const;
unsigned int getPositionCentralX() const;
const sf::Vector2f &getSize() const;
unsigned int getID() const;
//get
void setPositionCentralY(unsigned int positionCentralY);
void setPositionCentralX(unsigned int positionCentralX);
void setSize(const sf::Vector2f &size);
//relations
bool operator<(const ElementProperties &rhs) const;
private:
unsigned int _positionCentralY;
unsigned int _positionCentralX;
sf::Vector2f _size;
unsigned int _elementID;
Logger _log;
static unsigned int _amountOfRegisteredElements;
};
} //eng
#endif //ENGINE_ELEMENTPROPERTIES_HPP
<file_sep>/src/sources/Helpers/ElementProperties.cpp
//
// Created by mkajdak on 29.08.18.
//
#include <Helpers/ElementProperties.hpp>
namespace eng
{
unsigned int ElementProperties::_amountOfRegisteredElements = 0;
ElementProperties::ElementProperties(unsigned int positionCentralY, unsigned int positionCentralX)
: _log("ElementProperties")
, _positionCentralY(positionCentralY)
, _positionCentralX(positionCentralX)
, _size(0,0)
{
++ElementProperties::_amountOfRegisteredElements;
_elementID = ElementProperties::_amountOfRegisteredElements;
_log << "Creating a new Element with ID: " << std::to_string(_elementID).c_str()
<< logging::logEnd;
}
unsigned int ElementProperties::getPositionCentralY() const
{
return _positionCentralY;
}
void ElementProperties::setPositionCentralY(unsigned int positionCentralY)
{
_positionCentralY = positionCentralY;
}
unsigned int ElementProperties::getPositionCentralX() const
{
return _positionCentralX;
}
void ElementProperties::setPositionCentralX(unsigned int positionCentralX)
{
_positionCentralX = positionCentralX;
}
const sf::Vector2f &ElementProperties::getSize() const
{
return _size;
}
void ElementProperties::setSize(const sf::Vector2f &size)
{
_size = size;
}
ElementProperties::ElementProperties(const ElementProperties &elementProperties)
:_log("ElementProperties")
{
_log << "Copying an element!!!" << logging::logEnd;
_size = elementProperties._size;
_positionCentralX = elementProperties._positionCentralX;
_positionCentralY = elementProperties._positionCentralY;
_elementID = elementProperties.getID();
}
unsigned int ElementProperties::getID() const
{
return _elementID;
}
bool ElementProperties::operator<(const ElementProperties &rhs) const
{
return _elementID < rhs._elementID;
}
}<file_sep>/src/include/Buttons/LetterButton.hpp
//
// Created by maciej on 12.08.18.
//
#ifndef ENGINE_LETTERBUTTON_HPP
#define ENGINE_LETTERBUTTON_HPP
#include <functional>
#include <SFML/Graphics/Drawable.hpp>
#include <SFML/Graphics/Color.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Graphics/Text.hpp>
#include <Interface/IClickable.hpp>
#include <Interface/IElement.hpp>
#include <Logger.hpp>
class ICallable;
class LetterButton
: public eng::IElement, public IClickable
{
public:
LetterButton();
~LetterButton() override;
//IClickable
void click() override;
void unclick() override;
bool isClicked() override;
void focus() override;
void unfocus() override;
//sf::Drawable
void draw(sf::RenderTarget &target, sf::RenderStates states) const override;
//eng::IElement
eng::ElementProperties getElementProperties() const override;
unsigned int getElementID() const override;
eng::IElement *getAsElement();
void setFunctionality(std::function<void()> &func);
void setBasicColor(const sf::Color &basicColor);
void setOnFocusColor(const sf::Color &onFocusColor);
void setOnClickColor(const sf::Color &onClickColor);
void setButtonText(const std::string &buttonText);
private:
Logger _log;
bool _clicked;
bool _focused;
unsigned int _fontSize;
sf::Font _font;
sf::Text _buttonText;
sf::Color _basicColor = sf::Color::Black;
sf::Color _onFocusColor = sf::Color::Blue;
sf::Color _onClickColor = sf::Color::Red;
std::function<void(void)> _callback;
};
#endif //ENGINE_LETTERBUTTON_HPP
<file_sep>/src/include/Animations/Animation.hpp
//
// Created by mkajdak on 28.08.18.
//
#ifndef ENGINE_ANIMATION_HPP
#define ENGINE_ANIMATION_HPP
//TODO implement
class Animation
{
};
#endif //ENGINE_ANIMATION_HPP
<file_sep>/src/include/Detectors/CollisionDetector.hpp
//
// Created by maciej on 26.08.18.
//
#ifndef ENGINE_COLLISIONDETECTOR_HPP
#define ENGINE_COLLISIONDETECTOR_HPP
#include <Detectors/ICollisionDetector.hpp>
#include <Logger.hpp>
#include <functional>
#include <thread>
namespace eng
{
class DetectorsModule;
namespace det
{
class CollisionDetector : public ICollisionDetector
{
public:
~CollisionDetector() override;
void startMonitoring(std::function<void(sf::Event::EventType)> ¬ifier,
std::shared_ptr<ICollisionDetector> generator) override;
void stopMonitoring() override;
bool isMonitoring() override;
private:
CollisionDetector();
Logger _log;
friend class DetectorsModule;
};
} //det
} //eng
#endif //ENGINE_COLLISIONDETECTOR_HPP
<file_sep>/src/include/Interface/ICallable.hpp
//
// Created by maciej on 30.07.18.
//
#ifndef ENGINE_ICALLABLE_HPP
#define ENGINE_ICALLABLE_HPP
class ICallable {
public:
virtual void callback() = 0;
};
#endif //ENGINE_ICALLABLE_HPP
<file_sep>/src/sources/Animations/SpriteReader.cpp
//
// Created by maciej on 29.08.18.
//
#include <Animations/SpriteReader.hpp>
<file_sep>/src/include/Animations/SpriteReader.hpp
//
// Created by maciej on 29.08.18.
//
#ifndef ENGINE_SPRITEREADER_HPP
#define ENGINE_SPRITEREADER_HPP
class SpriteReader
{
};
#endif //ENGINE_SPRITEREADER_HPP
<file_sep>/src/include/Interface/IClickable.hpp
//
// Created by maciej on 30.07.18.
//
#ifndef ENGINE_ICLICKABLE_HPP
#define ENGINE_ICLICKABLE_HPP
#include <SFML/Graphics/Drawable.hpp>
class IClickable {
public:
virtual void click() = 0;
virtual void unclick() = 0;
virtual bool isClicked() = 0;
virtual void focus() = 0;
virtual void unfocus() = 0;
};
#endif //ENGINE_ICLICKABLE_HPP
| 174395c3eefebda3099ae84a80e57735a1b5cb1f | [
"Markdown",
"CMake",
"C++"
] | 55 | C++ | MacAndKaj/SimpleEngine2D | 884b97a5fd595659e1a4f8dd49150e6a2d76839c | c61150688a64ef1059de87ae6f0e678788b602b5 |
refs/heads/master | <repo_name>lharr/gbm_surv_sig<file_sep>/scripts/surv_gene_sig.R
# <NAME> 2017 - GBM Gene Signatures
# scripts/surv_gene_sig.R
#
# Usage:
# Run in command line:
#
# Rscript scripts/surv_gene_sig.R
#
# Output:
# Produces survival curves and analyses for cell TCGA GBM data
# Set Dependencies --------------------------------------------------------
library(survival)
library(gplots)
# Prepare Expression Data -------------------------------------------------
data_file = file.path("data", "data_RNA_Seq_v2_mRNA_median_Zscores.txt")
expression <- read.table(data_file, sep = "\t",
header = T, row.names = 1)[,-1]
# transpose dataset so each patient a row
expression <- data.frame(t(expression))
# just grab genes in signature
expression2 <- data.frame(expression$COL2A1, expression$DDIT4, expression$EGLN3,
expression$FAM162A, expression$KDELR3, expression$LOXL2,
expression$NDRG1, expression$P4HA1, expression$P4HA2,
expression$PFKL, expression$PPP1R3C, expression$STC1,
expression$VEGFA, expression$VLDLR, expression$VIT,
expression$CLYBL, expression$APLN, expression$ANKRD37,
expression$ERO1A)
# normalize expression
expression2 <- data.frame(scale(expression2))
new_row_names <- c()
current_names <- row.names(expression)
for (r in 1:length(current_names)){
name <- current_names[r]
new_row_names = c(new_row_names, paste("TCGA-", substr(name, 6,7), "-",
substr(name, 9, 12), sep = ""))
}
expression2$PATIENT_ID <- new_row_names
# average over those with multiple measurements
expression_ag <- aggregate(.~PATIENT_ID, FUN=mean, data=expression2)
# Prepare Clinical Data ---------------------------------------------------
data_file = file.path("data", "data_bcr_clinical_data_patient.txt")
clinical <- read.table(data_file, header = T,
row.names = 1, sep = "\t")
small_clinical <- data.frame(clinical$PATIENT_ID, clinical$OS_MONTHS,
clinical$OS_STATUS)
small_clinical <- small_clinical[small_clinical$clinical.OS_STATUS != "[Not Available]", ]
# create binary variable if dead or alive
Dead = rep(NA, dim(small_clinical)[1])
for (i in 1:length(small_clinical$clinical.OS_STATUS)){
if (small_clinical$clinical.OS_STATUS[i] == "DECEASED"){
Dead[i] = 1
}
else if (small_clinical$clinical.OS_STATUS[i] == "LIVING"){
Dead[i] = 0
}
}
small_clinical$Dead = Dead
small_clinical$clinical.OS_MONTHS <- as.integer(small_clinical$clinical.OS_MONTHS)
# Merge Data --------------------------------------------------------------
merged_data <- merge(small_clinical, expression_ag, by.x = "clinical.PATIENT_ID",
by.y = "PATIENT_ID")
head(merged_data)
# Survival Analysis -------------------------------------------------------
coxfit <- coxph(Surv(clinical.OS_MONTHS, Dead) ~., data=merged_data[, c(2, 4:23)])
cox.zph(coxfit)
coefs <- as.matrix(coxfit$coefficients)
risk_score <- as.matrix((merged_data[, 5:23] - colMeans(merged_data[, 5:23]))) %*% coefs
merged_data$risk_score <- risk_score
group <- rep(NA, dim(merged_data)[1])
for (i in 1:dim(merged_data)[1]){
if (risk_score[i] > 0){
group[i] = "H"
}
else if (risk_score[i] < 0){
group[i] = "L"
}
}
merged_data$group <- group
my_surv <- survfit(Surv(clinical.OS_MONTHS, Dead) ~ group, data = merged_data)
par(mfrow=c(1,1))
plot(my_surv, conf.int=F, lty = 1, col = c("red", "black"),
xlab = "Months of Overall Survival", ylab = "Percent Survival")
legend("bottomleft", legend=c("H", "L"), col=c("red","black"), lty=1,
horiz=F, bty='n')
png('gene_signature_survival.png', res = 300)
dev.off()
risk_low <- merged_data$risk_score[merged_data$group == 'L']
risk_high <- merged_data$risk_score[merged_data$group == 'H']
mean(risk_low)
mean(risk_high)
t.test(risk_low, risk_high)
survdiff(Surv(clinical.OS_MONTHS, Dead) ~ group, data = merged_data)
get_95_ci <- function(values){
n = length(values)
s = sd(values)
error <- qnorm(.975)*(s/sqrt(n))
ci <- mean(values) + c(-1,1)*error
return(ci)
}
get_95_ci(risk_low)
get_95_ci(risk_high)
coxfit2 <- coxph(Surv(clinical.OS_MONTHS, Dead) ~ group, data=merged_data)
# get hazard ratio
hz <- exp(1)^coxfit2$coefficients
percen_reduct <- (1-hz)*100<file_sep>/README.md
# TCGA Glioblastoma Gene Signature Analysis
## Summary
Provisional 2013 TCGA glioblastoma RNAseq expression data were subjected to survival
signature risk score identification analysis [1, 2]. Expression data were normed and
then averaged for individuals with multiple measurements. After verifying proportionality
of hazards, a Cox proportional hazards model was fit to the 19 signature genes with
overall survival status as the outcome. Risk scores for each participant was determined
using the method by Lu et al [2]. Risk scores were than categorized as Low or
High using 0 as the cutpoint . Differential survival
between the Low and High gene signature risk groups were visualized using
Kaplan-Meier curves and difference between the curves was assessed via the log-rank test.
All gene signature analyses were performed in R.
[1] <NAME>. \& <NAME>. (2004). Partial Cox regression analysis for high-dimensional
microarray gene expression data. Bioinformatics, 20, i208-i215.
doi: 10.1093/bioinformatics/bth900\\
[2] <NAME>., <NAME>, <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>.,
<NAME>., <NAME>, <NAME>., \& <NAME>. (2006). A Gene Expression Signature
Predicts Survival of Patients with Stage I Non-Small Cell Lung Cancer.
PLOS Medicine, https://doi.org/10.1371/journal.pmed.0030467.

## Reproducibility and Data
The data can be downloaded using this link:
http://www.cbioportal.org/study?id=gbm_tcga#summary. Alternatively, to download the data
and reproduce all analyses:
```
bash data/data_files.sh
Rscript scripts/surv_gene_sig.R
```
## Contact
* About the code: <NAME> (<EMAIL>)
* About the project or collaboration: Dr. <NAME> (<EMAIL>)
and <NAME> (<EMAIL>) | 87fe16ddb8f6252db76d072aab66130693e84ab5 | [
"Markdown",
"R"
] | 2 | R | lharr/gbm_surv_sig | de1aa7265736bb7d1d8128b52fa9600cbb5b5921 | e8818383580f393523209fb8e6126352b997c82d |
refs/heads/master | <repo_name>LuGeorgiev/PythonSelfLearning<file_sep>/Fundamentals/Functions/Lecture.py
def find_result(num_str):
sum_odd = 0
sum_even = 0
for char in num_str:
if char == '-':
continue
number = int(char)
if number % 2 == 0:
sum_even += number
else:
sum_odd += number
return sum_odd * sum_even
if __name__ == "__main__":
string_num = input()
result = find_result(string_num)
print(result)
<file_sep>/Fundamentals/ExamPrep/p2-LismonSay.py
numbers_list = list(map(int, input().split()))
data = input()
counter = 0
while not data == "exhausted":
manipulated_num_list = []
data_list = input().split()
command = data_list[0]
if command == 'set':
if len(set(numbers_list)) == len(numbers_list):
print('It is a set')
else:
manipulated_num_list = list(sorted(set(numbers_list), key=numbers_list.index))
elif command == 'filter':
even_or_odd = data_list[1]
if even_or_odd == 'even':
manipulated_num_list = [num for num in numbers_list if num % 2 == 0]
else:
manipulated_num_list = [num for num in numbers_list if num % 2 == 1]
elif command == 'multiply':
number = input(data_list[1])
manipulated_num_list = [num * number for num in numbers_list]
elif command == 'divide':
number = input(data_list[1])
if number == 0:
print('Zero division caught')
else:
manipulated_num_list = list(map(lambda x: x*number, numbers_list))
elif command == 'slice':
left = int(data_list[1])
right = int(data_list[2])
if 0 <= left < len(numbers_list) and 0 <= right < len(numbers_list):
manipulated_num_list = numbers_list[left:right+1]
else:
print('IndexError caught')
elif command == 'sort':
manipulated_num_list = list(sorted(numbers_list))
elif command == 'reverse':
manipulated_num_list = list(reversed(numbers_list))
if len(manipulated_num_list) > 0:
print(manipulated_num_list)
counter += 1
data = input()
print(f'I beat it for: {counter} rounds')
<file_sep>/NakovBook/NestedCylcles/Axe.py
def print_top(num_int, width_int):
front_dashes = ('-' * (num_int * 3))
for i in range (0, num):
back_dashes = ('-' * (width - len(front_dashes) - 2 - i))
mid_dashes = ('-' * i)
print(f'{front_dashes}*{mid_dashes}*{back_dashes}')
def print_handle(num_int, height_int):
front_starts = ('*' * (num_int * 3 + 1))
mid_dashes = ('-' * (num_int - 1))
last_dashes = ('-' * ((num_int * 5) - len(front_starts) - len(mid_dashes) - 1))
for i in range(height_int):
print(f'{front_starts}{mid_dashes}*{last_dashes}')
def print_blade(num_int, height_int):
for i in range(0, height_int):
front_dashes = ('-' * (num_int * 3 - i))
mid_dashes = ('-' * (num_int - 1 + (2 * i)))
last_dashes = ('-' * ((num_int * 5) - len(front_dashes) - len(mid_dashes) - 2))
print(f'{front_dashes}*{mid_dashes}*{last_dashes}')
return len(front_dashes), len(mid_dashes)
num = int(input())
width = num * 5
blade_hand_height = num // 2
print_top(num, width)
print_handle(num, blade_hand_height)
if num > 2:
if num == 3:
dash_qty, starts_qty = print_blade(num, blade_hand_height)
else:
dash_qty, starts_qty = print_blade(num, blade_hand_height - 1)
else:
dash_qty = 7
starts_qty = -1
dashes = ('-' * (dash_qty - 1))
starts = ('*' * (starts_qty + 4))
last_lashes =('-' * (width - dash_qty - starts_qty - 3))
print(f'{dashes}{starts}{last_lashes}')
<file_sep>/NakovBook/SimpleCalculations/VegetableMarket.py
price_vegetables = float(input())
price_fruits = float(input())
kg_vegetables = int(input())
kg_fruits = int(input())
print(str((price_fruits*kg_fruits + price_vegetables*kg_vegetables)/1.94))
<file_sep>/Fundamentals/MagicMethods/Lect_Demo.py
result = 10 + 5
print(result)
a = 9
result = a.__add__(5)
print(result)
print(bin(-11 << 2))<file_sep>/Fundamentals/Dictionaries/Lect_Demo..py
my_list = [1, 2, 2, 4, 6]
#print reverse
print(my_list[::-1])
student = {'user': 'Lubo',
'pass': '<PASSWORD>',
'course': ['C# Fundamentals', 'C# ASP', 'Algorithms']}
for key in student:
print(key)
for kvp in student.items():
print(f'the key is: {kvp[0]}, and values are: {kvp[1]} ')
print(student['pass'])
print(student.get('Pass', 'Sorry mate no such key'))
if 'pass' in student.keys():
print('Here')
else:
print('Not here')
second_part_student = {
'age': 25
}
student.update(second_part_student)
print(student)
<file_sep>/Fundamentals/ObjectsAndClasses/Lect_BankSystem.py
class BankAccount:
def __init__(self, name, bank, balance):
self.name = name
self.bank = bank
self.balance = balance
data_list = input().split(' | ')
accounts_list = []
while data_list[0] != "end":
bank = data_list[0]
name = data_list[1]
balance = float(data_list[2])
bank_account = BankAccount(name, bank, balance)
accounts_list.append(bank_account)
data_list = input().split(' | ')
# - means descending it it is INT
# sort balance descending and bank.name length ascending
for acc in sorted(accounts_list, key=lambda x: (-x.balance, len(x.bank))):
print(f'{acc.name} -> {acc.balance:.2f} ({acc.bank})')
<file_sep>/NakovBook/NestedCylcles/DrawFortress.py
def print_top(line_int):
upper = ('^' * (line_int//2))
lower = ('_' * (line_int*2 - (2*len(upper)+4)))
return f'/{upper}\\{lower}/{upper}\\'
def print_bottom(line_int):
lower = ('_' * (line_int//2))
upper = (' ' * (line_int*2 - (2*len(lower)+4)))
return f'\\{lower}/{upper}\\{lower}/'
def print_last_body(line_int):
line_len = line_int * 2
draw_space = line_int * 2 - 2
tilds = line_int // 2
underline_qty = line_len - 4 - (2 * tilds)
space_qty = (draw_space - underline_qty) // 2
space = (' ' * space_qty)
underline = ('_' * underline_qty)
return f'|{space}{underline}{space}|'
lines = int(input())
if lines <= 4:
lines_in_Body = lines - 2
else:
lines_in_Body = lines - 3
spaces = (' ' * (lines * 2 - 2))
print(print_top(lines))
for r in range(lines_in_Body):
print(f'|{spaces}|')
if lines > 4:
print(print_last_body(lines))
print(print_bottom(lines))
<file_sep>/Fundamentals/OOP/Lect_Animals.py
class Animal:
def __init__(self, name: str, age: int):
self.age = age
self.name = name
class Dog(Animal):
def __init__(self, name, age, number_of_legs: int):
Animal.__init__(self, name, age)
self.number_of_legs = number_of_legs
def make_sound(self):
return 'Bau Bauuuu'
def __str__(self):
return f'Dog: {self.name}, age: {self.age}, number of legs: {self.number_of_legs}'
class Cat(Animal):
def __init__(self, name, age, iq: int):
Animal.__init__(self, name, age)
self.iq = iq
def make_sound(self):
return 'I am very intelligent cat... blah blah'
def __str__(self):
return f'Cat: {self.name}, age: {self.age}, IQ: {self.iq}'
class Snake(Animal):
def __init__(self, name, age, cruelty_coef: int):
Animal.__init__(self, name, age)
self.crulety = cruelty_coef
def make_sound(self):
return 'PSsss I am snake'
def __str__(self):
return f'Snake: {self.name}, age: {self.age}, cruelty: {self.crulety}'
data_list = input().split()
animal_list = []
while not data_list[0].startswith("I'm"):
if data_list[0] == 'talk':
name = data_list[1]
current_animal = list(filter(lambda x: x.name == name, animal_list))[0]
print(current_animal.make_sound())
else:
kind = data_list[0]
name = data_list[1]
age = int(data_list[2])
ability = int(data_list[3])
if kind == 'Dog':
dog = Dog(name, age, ability)
animal_list.append(dog)
elif kind == "Cat":
cat = Cat(name, age, ability)
animal_list.append(cat)
elif kind == 'Snake':
snake = Snake(name, age, ability)
animal_list.append(snake)
data_list = input().split()
dogs_list = filter(lambda x: isinstance(x, Dog), animal_list)
cats_list = filter(lambda x: isinstance(x, Cat), animal_list)
snakes_list = filter(lambda x: isinstance(x, Snake), animal_list)
sorted_animals = dogs_list + cats_list + snakes_list
for animal in sorted_animals:
print(animal)
<file_sep>/Fundamentals/FilesRegex/Lect_MergeFiles.py
with open('odd.txt', 'r') as file:
odd_num = file.readlines()
with open('even.txt', 'r') as file:
even_num = file.readlines()
merged = list(zip(odd_num, even_num))
with open('merged-output.txt', 'a') as file:
for el in merged:
file.write(el[0])
file.write(el[1])
<file_sep>/Fundamentals/Lists/Lect_SmallestNumber.py
nums = list(map(int, input().split(' ')))
#nums.sort()
#print(nums[0])
print(min(nums))
<file_sep>/Fundamentals/Dictionaries/Lect_Key-Key_Val-Val.py
target_key = input()
target_value = input()
lines = int(input())
data_dict = {}
for num in range(0, lines):
tokens_list = input().split(' => ')
key = tokens_list[0]
value_list = tokens_list[1].split(';')
data_dict[key] = value_list
for k, v in data_dict.items():
if target_key in k:
print(f'{k}:')
for el in v:
if target_value in el:
print(f'-{el}')
<file_sep>/Fundamentals/ObjectsAndClasses/Exercise/ClosestTwoPoints.py
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def to_str(self):
return f'X:{self.x}, Y:{self.y} '
class Segment:
def __init__(self, point_1: Point, point_2: Point):
self.point_1 = point_1
self.point_2 = point_2
self.distance = self.calculate_distance()
def calculate_distance(self):
side_a = abs(self.point_1.x - self.point_2.x)
side_b = abs(self.point_1.y - self.point_2.y)
side_c = math.sqrt(side_a ** 2 + side_b ** 2)
return side_c
def to_str(self):
return f'{self.distance:.3f}\n({self.point_1.x}, {self.point_1.y})\n({self.point_2.x}, {self.point_2.y})'
def point_factory(x_int, y_int):
return Point(x_int, y_int)
lines = int(input())
points = []
for line in range(lines):
#x, y = list(map(int, input().split()))
x, y = [int(num) for num in input().split()]
point = point_factory(x, y)
points.append(point)
segments = []
for i in range(len(points)):
for j in range(i + 1, len(points)):
segment = Segment(points[i], points[j])
segments.append(segment)
for segment in sorted(segments, key=lambda z: z.distance):
print(segment.to_str())
break
#for point in points:
# print(point.to_str())<file_sep>/Fundamentals/ObjectsAndClasses/Exercise/PointsDistance.py
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def calculate_distance (point_1: Point, point_2: Point):
side_a = abs(point_1.x - point_2.x)
side_b = abs(point_1.y - point_2.y)
return math.sqrt(side_a ** 2 + side_b ** 2)
def point_factory(x_int, y_int):
return Point(x_int, y_int)
x_1, y_1 = list(map(int, input().split()))
x_2, y_2 = list(map(int, input().split()))
point_1 = point_factory(x_1, y_1)
point_2 = point_factory(x_2, y_2)
distance = calculate_distance(point_1, point_2)
print(f'{distance:.3f}')
<file_sep>/Fundamentals/Lists/Lect_CountOddNumbers.py
nums = list(map(int, input().split(' ')))
odd_num_list = [num for num in nums if num % 2 == 1]
print(len(odd_num_list))
<file_sep>/Fundamentals/Dictionaries/Excercises/Dif-Ref-Advanced.py
data_list = input().split(' -> ')
names_dict = {}
while not data_list[0] == 'end':
name = data_list[0]
tokens = data_list[1].split(', ')
if tokens[0].isdigit():
if name not in names_dict.keys():
names_dict[name] = []
else:
names_dict[name].extend(tokens)
else:
if tokens[0] in names_dict.keys():
if name not in names_dict.keys():
names_dict[name] = []
names_dict[name].extend(names_dict[tokens[0]])
data_list = input().split(' -> ')
<file_sep>/Fundamentals/ObjectsAndClasses/Exercise/Boxes.py
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
@staticmethod
def calc_distance(point_1, point_2):
side_a = point_1.x - point_2.x
side_b = point_1.y - point_2.y
side_c = math.sqrt(side_a ** 2 + side_b ** 2)
return side_c
def to_str(self):
return f'X:{self.x}, Y:{self.y} '
def point_factory(coor):
x_int, y_int = [int(point) for point in coor.split(':')]
return Point(x_int, y_int)
class Box:
def __init__(self, upper_left: Point, upper_right: Point, bottom_left: Point, bottom_right: Point):
self.upper_left = upper_left
self.upper_right = upper_right
self.bottom_left = bottom_left
self.bottom_right = bottom_right
self.height = self.get_height()
self.width = self.get_width()
self.perimeter = self.calc_perimeter()
self.area = self.calc_area()
def get_width(self):
width = Point.calc_distance(self.upper_left, self.upper_right)
return width
def get_height(self):
height = Point.calc_distance(self.upper_left, self.bottom_left)
return height
def calc_perimeter(self):
return self.height * 2 + self.width * 2
def calc_area(self):
return self.height * self.width
def to_str(self):
return f'Box: {self.width:.0f}, {self.height:.0f}\nPerimeter: {self.perimeter:.0f}\nArea: {self.area:.0f}'
def box_factory(u_l, u_r, b_l, b_r):
upper_left = point_factory(u_l)
upper_right = point_factory(u_r)
bottom_left = point_factory(b_l)
bottom_right = point_factory(b_r)
return Box(upper_left, upper_right, bottom_left, bottom_right)
data_list = input().split(' | ')
box_list = []
while data_list[0] != 'end':
box_list.append(box_factory(data_list[0], data_list[1], data_list[2], data_list[3]))
data_list = input().split(' | ')
for box in box_list:
print(box.to_str())<file_sep>/Fundamentals/Dictionaries/Lect_DictRef.py
data_list = input().split(' = ')
names_dict = {}
while data_list[0] != "end":
if data_list[1].isdigit():
names_dict[data_list[0]] = int(data_list[1])
else:
if data_list[1] in names_dict.keys():
names_dict[data_list[0]] = names_dict[data_list[1]]
else:
continue
data_list = input().split(' = ')
for k, v in names_dict.items():
print(f'{k} === {v}')
<file_sep>/Fundamentals/Lists/Lect_MultyplyIntegers.py
def multiply(el, p):
return el * p
if __name__ == "__main__":
data_list = list(map(int, input().split(' ')))
multiplyer = int(input())
a = [multiply(el, multiplyer) for el in data_list]
print(a)
print(*a)
print(' '.join(map(str, a)))
<file_sep>/Fundamentals/ExamPrep/p4-agency.py
from abc import ABC, abstractmethod
class Apartment (ABC):
def __init__(self, id, rooms, baths, square_meters, price):
self.id = id
self.rooms = int(rooms)
self.bath = int(baths),
self.square_meters = int(square_meters)
self.price = float(price)
self.is_take = False
@abstractmethod
def __str__(self):
return (f'{self.rooms} rooms place with {self.bath} bathroom/s.\n{self.square_meters} sq. meters for {self.price} lv.')
class LivingApartment(Apartment):
def __init__(self, id, rooms, baths, square_meters, price):
Apartment.__init__(self, id, rooms, baths, square_meters, price)
def __str__(self):
return Apartment.__str__(self)
class OfficeApartment(Apartment):
def __init__(self, id, rooms, baths, square_meters, price):
Apartment.__init__(self, id, rooms, baths, square_meters, price)
def __str__(self):
return Apartment.__str__(self)
data = input()
apartments_list = []
while not data == "start_selling":
try:
current_app = eval(data)
apartments_list.append(current_app)
except Exception as ex:
print(ex)
data = input()
data_list = input().split()
ids_list = list(map(lambda x: x.id, apartments_list))
while not (data_list[0] == "free" or data_list[0] == "taken"):
command = data_list[0]
id = data_list[1]
if id in ids_list:
current_apartment: Apartment = list(filter(lambda x: x.id == id, apartments_list))[0]
if current_apartment.is_take:
print(f'Apartment with id - {id} is already taken')
elif command == "rent" and isinstance(current_apartment, LivingApartment):
print(f'Apartment with id - {id} is only for selling!')
elif command == "buy" and isinstance(current_apartment, OfficeApartment):
print(f'Apartment with id - {id} is only for renting!')
else:
current_apartment.is_take = True
else:
print(f'Apartment with id - {id} does not exist!')
data_list = input().split()
if data_list[0] == "taken":
taken_apartments_list = list(filter(lambda a: a.is_taken == True, apartments_list))
for apart in sorted(taken_apartments_list, key=lambda a: (a.price, -a.square_meters)):
print(apart)
elif data_list[0] == "free":
taken_apartments_list = list(filter(lambda a: a.is_taken == False, apartments_list))
for apart in sorted(taken_apartments_list, key=lambda a: (-a.price, a.square_meters)):
print(apart)
if len(taken_apartments_list) == 0:
print('No information for this query')
# OfficeApartment("id_nim", 4, 2, 123, 2300)
# LivingApartment("00L", 2, 2, 173, 223000)
# OfficeApartment("i00A", 3, 2, 153, 23050)<file_sep>/Fundamentals/ObjectsAndClasses/Lect_demo.py
class Person:
def __init__(self, name, gender, age):
self.name = name
self.gender = gender
self.age = age
persone_1 = Person('Ivan', 'mail', 67)
persone_2 = Person('Marin', 'other', 37)
persone_3 = Person('Mira', 'female', 6)
print(persone_1.name)
print(persone_3.name)<file_sep>/NakovBook/SimpleCalculations/Money.py
bitcoins = int(input())
china = float(input())
commission = (100-float(input()))/100
bgn = bitcoins * 1168
bgn += china * 0.15 * 1.76
euro = bgn / 1.95
print(round(euro*commission, 2))
<file_sep>/Fundamentals/Lists/Excercises/SumAdjancentEqualNumbers.py
num_list = [1, 1, 2, 3, 3, 4]
index = 0
while index < len(num_list)-1:
if num_list[index] == num_list[index+1]:
cur_sum = num_list[index] + num_list[index+1]
del num_list[index]
num_list[index] = cur_sum
index = -1
index += 1
print(*num_list)
<file_sep>/Fundamentals/FilesRegex/Lect_Demo.py
#r - read, w - write
with open('my-file.txt', 'a') as file:
file.write('added data')
line_data = file.readline()
while line_data != '':
print(line_data, end='')
line_data = file.readline()
<file_sep>/NakovBook/SimpleCalculations/DailyEarnings.py
working_days = int(input())
money_daily = float(input())
used_bgn = float(input())
year_income = working_days * money_daily * 14.5
tolls = year_income * 0.25
print(round(((year_income + tolls) / 365), 2))
<file_sep>/Fundamentals/Dictionaries/Lect_OddOccurencies.py
input_line = input().lower().split(' ')
occ_dict = {}
for word in input_line:
occ_dict[word] = input_line.count(word)
for key, value in occ_dict.items():
if value % 2 == 1:
print(f'{key}', end=' ')
<file_sep>/Fundamentals/Dictionaries/Excercises/Wordrobe.py
n = int(input())
wardrobe_dict = {}
for i in range(n):
data_list = input().split(' -> ')
color = data_list[0]
clothes_list = data_list[1].split(',')
if color not in wardrobe_dict.keys():
wardrobe_dict[color] = []
wardrobe_dict[color].extend(clothes_list)
items_count_dict = {}
for col, cloth_list in wardrobe_dict.items():
items_count_dict[col] = {c: cloth_list.count(c) for c in cloth_list}
tokens = input().split()
target_col = tokens[0]
target_garment = ' '.join(tokens[1:])
for color, kvp in items_count_dict.items():
print(f'{color} clothes: ')
for garment, garment_count in kvp.items():
if target_col == color and target_garment == garment:
print(f'* {garment} - {garment_count} (found)')
else:
print(f'* {garment} - {garment_count}')
<file_sep>/Fundamentals/OOP/Lect_Person.py
class Person:
def __init__(self, name: str, age: int):
self.name = name
self.age = age
@property
def age(self):
return self.__age
@age.setter
def age(self, value):
if value < 0:
raise Exception('Age is invalid')
self.__age = value
@property
def name(self):
return self.__name
@name.setter
def name(self, value):
if len(value) < 3:
raise Exception("name should be more than 3 symbols")
self.__name = value
def __str__(self):
return f'{self.name} {self.age}'
class Child(Person):
def __init__(self, name, age):
Person.__init__(self, name, age)
@property
def age(self):
return self.__age
@age.setter
def age(self, value):
Person.age.fset(self, value)
if value > 15:
raise Exception("Child's age must be less than 15")
self.__age = value
person = Child("lu", -3)
<file_sep>/Fundamentals/FilesRegex/Lect_PrintOddLines.py
with open('my-file.txt', 'r') as file:
row_text = file.readlines()
odd_rows_text = [row_text[index] for index in range(len(row_text)) if index % 2 == 1]
with open('output-odd.txt', 'a') as output:
output.write(''.join(odd_rows_text))<file_sep>/Fundamentals/FilesRegex/Lect_Convert ToHtml.py
with open('html.txt', 'r') as file:
line = file.readline()
title_content = "HTML-Content"
second_part = ''
while line != 'exit':
tag, content = line.split()
if tag == 'title':
title_content = content
else:
opening_tag = f'<{tag}>'
closing_tag = f'</{tag}>'
row = f'{opening_tag}{content}{closing_tag}\n'
second_part += row
line = file.readline()
first_part = f'<!DOCTYPE html>\n<html>\n<head>\n<title>{title_content}</title>\n</head>\n<body>'
closing_part = '</body>\n</html>'
with open('index.html', 'w') as file:
file.write(first_part)
file.write(second_part)
file.write(closing_part)
<file_sep>/NakovBook/ConditionalStatements/Trip.py
budget = float(input())
season = input()
if budget <= 100:
destination = 'Bulgaria'
money_spent = budget * 0.7
info = f'Hotel - {money_spent:.2f}'
if season == 'summer':
money_spent = budget * 0.3
info = f'Camp - {money_spent:.2f}'
elif budget <= 1000:
destination = 'Balkans'
money_spent = budget * 0.8
info = f'Hotel - {money_spent:.2f}'
if season == 'summer':
money_spent = budget * 0.4
info = f'Camp - {money_spent:.2f}'
else:
destination = 'Europe'
money_spent = budget * 0.9
info = f'Hotel - {money_spent:.2f}'
print('Somewhere in ' + destination)
print(info)
<file_sep>/NakovBook/ConditionalStatements/OnTimeForExam.py
def calculate_time(exam_minutes_int, arrival_minutes_int):
time_diff = exam_minutes_int - arrival_minutes_int
if time_diff == 0:
return 0, ''
elif 0 < time_diff <= 30:
return 0, time_span(time_diff)
elif time_diff > 30:
return -1, time_span(time_diff)
else:
return 1, time_span(time_diff)
def time_span(time_diff_int):
hour = abs(int(time_diff_int / 60))
minutes = abs(time_diff_int) - 60 * hour
if time_diff_int == 0:
return ''
elif hour >= 1:
return f'{hour}:{minutes:02} hours'
else:
return f'{minutes} minutes'
exam_hour = int(input())
exam_minute = int(input())
arrival_hour = int(input())
arrival_minute = int(input())
exam_in_minutes = exam_hour * 60 + exam_minute
arrival_in_minutes = arrival_hour * 60 + arrival_minute
is_Late, time_span = calculate_time(exam_in_minutes, arrival_in_minutes)
if is_Late == 0:
if time_span == '':
print('On time')
else:
print(f'On time\n{time_span} before the start')
elif is_Late == -1:
print(f'Early\n{time_span} before the start')
else:
print(f'Late\n{time_span} after the start')
<file_sep>/Fundamentals/OOP/Exercise/Animals.py
from abc import ABC, abstractmethod
class Animal(ABC):
def __init__(self ,name, age, gender):
self.name = name
self.age = age
self.gender = gender
@property
def age(self):
return self.__age
@age.setter
def age(self, value):
if value < 0:
raise Exception('Invalid input')
self.__age = value
@abstractmethod
def produce_sound(self):
pass
def __str__(self):
return f'{self.__class__.__name__}\n{self.name} {self.age} {self.gender}\n{self.produce_sound()}'
class Dog(Animal):
def __init__(self, name, age, gender):
Animal.__init__(self, name, age, gender)
def produce_sound(self):
return 'Bau bau'
class Frog(Animal):
def __init__(self, name, age, gender):
Animal.__init__(self, name, age, gender)
def produce_sound(self):
return 'Kva kva'
class Cat(Animal):
def __init__(self, name, age, gender):
Animal.__init__(self, name, age, gender)
def produce_sound(self):
return 'Miau miau'
class Tomcat(Cat):
def __init__(self, name, age, gender='Male'):
Cat.__init__(self, name, age, gender='Male')
def produce_sound(self):
return 'MIAU MIAU'
class Kitten(Cat):
def __init__(self, name, age, gender='Female'):
Cat.__init__(self, name, age, gender='Female')
def produce_sound(self):
return 'miauuuuu'
animals_list = []
while True:
kind = input()
if kind == 'Beast!':
break
name, age, gender = input().split()
obh_str = f'{kind}("{name}",{int(age)},"{gender}")'
try:
obj = eval(obh_str)
animals_list.append(obj)
except Exception as ex:
print('Invalid input')
for animal in animals_list:
print(animal)
<file_sep>/Fundamentals/LambdaFunc/Lect_Demo.py
students_grades = {
'ivan': [3, 4],
'petar': [5, 3, 5],
'maria': [6, 6, 6, 5],
'gosho000000': [3, 5]
}
sorted_grades = sorted(students_grades, key=lambda kvp: (kvp[0], len(kvp[1])))
print(sorted_grades[::-1])
# Reverse positive numbers
nums = (2, 3, 34, -56, -2, 34, -23)
positive_nums_list = list(filter(lambda x: x >= 0, map(int, nums)))
print(*positive_nums_list[::-1])
<file_sep>/Fundamentals/Lists/Lecture_Demo.py
temps = [20, 30, 78, 45, 19]
print(temps)
temps.append(67)
print(temps[-1])
print('range')
print(temps[1:-1])
for t in temps:
print(t)
for index in range(len(temps)):
print(index)
<file_sep>/Fundamentals/Dictionaries/Excercises/SocialMediaPosts.py
data_list = input().split()
post_dict = {}
while not data_list[0] == "drop":
command = data_list[0]
post_name = data_list[1]
if command == 'post':
post_dict[post_name] = {'likes': 0, 'dislikes': 0, 'comments': None}
elif command == 'like':
if post_name in post_dict.keys():
post_dict[post_name]['like'] += 1
elif command == 'dislike':
if post_name in post_dict.keys():
post_dict[post_name]['dislikes'] += 1
elif command == 'comment':
commentator = data_list[2]
content = ' '.join(data_list[3:])
if post_name in post_dict.keys():
if not post_dict[post_name]['comments']:
post_dict[post_name]['comments'] = []
post_dict[post_name]['comments'].append({commentator: content})
data_list = input().split()
for post_name, metrics in post_dict.items():
print(f'Post: {post_name} | Likes: {metrics["likes"]} | Dislikes: {metrics["dislikes"]}')
print("Comments")
if metrics['comments']:
for comment in metrics['comments']:
for kvp in comment.items():
print(f'* {kvp[0]}: {kvp[1]}')
else:
print("None")
<file_sep>/NakovBook/SimpleCalculations/LearningHall.py
hall_length = float(input())
hall_width = float(input())
rows = hall_length//1.2
cols = (hall_width-1)//0.7
print(int(rows*cols-3))
<file_sep>/NakovBook/SimpleCalculations/ChangeTiles.py
area_side = int(input())
tile_width = float(input())
tile_height = float(input())
bench_width = int(input())
bench_length = int(input())
area_to_cover = area_side*area_side - bench_length*bench_width
tile_area = tile_height*tile_width
tiles_needed = area_to_cover/tile_area
time = tiles_needed*0.2
print(round(tiles_needed, 2))
print(round(time, 2))<file_sep>/Fundamentals/ObjectsAndClasses/Lect_DateTime.py
from datetime import datetime
date = datetime.utcnow()
print(date)<file_sep>/README.md
# PythonSelfLearning
Solving Python tasks
<file_sep>/Fundamentals/Dictionaries/Lect_CountRealNumbers.py
numbers_list = list(map(lambda x: float(x), input().split(' ')))
occ_dic = {num: numbers_list.count(num) for num in numbers_list}
#now is sorted by values, default is by key
for key, value in sorted(occ_dic.items(), key=lambda kvp: kvp[1], reverse=True):
print(f'{key} -> {value} times')
<file_sep>/Fundamentals/ObjectsAndClasses/Lect_Excercise_task.py
class Exercise:
def __init__(self, topic, course, judge_contest_link, problems):
self.topic = topic
self.course_name = course
self.judge_contest_link = judge_contest_link
self.problems_list = problems
exercise_list = []
data_list = input().split(' -> ')
while not data_list[0] == 'go go go':
topic_name = data_list[0]
course_name = data_list[1]
judge_link = data_list[2]
problem_list = data_list[3].split(', ')
exercise = Exercise(topic_name, course_name, judge_link, problem_list)
exercise_list.append(exercise)
data_list = input().split(' -> ')
for exercise in exercise_list:
print(f'Exercises: {exercise.topic}')
print(f'Problems for exercises and homework for the "{exercise.course_name}" course @ SoftUni.')
print(f'Check your solutions here: {exercise.judge_contest_link}')
for index in range(len(exercise.problems_list)):
print(f'{index + 1}. {exercise.problems_list[index]}')
<file_sep>/Fundamentals/Lists/Lect_RotateListOfStrings.py
input_list = list(input().split(' '))
last_element = input_list.pop()
input_list.insert(0, last_element)
print(*input_list)
#print(input_list[-1], end=' ')
#print(*input_list[:-1])
<file_sep>/Fundamentals/OOP/Exercise/BookShop.py
class Book:
def __init__(self, title: str, author :str, price :float):
self.title = title
self.author = author
self.price = price
@property
def author(self):
return self.__author
@author.setter
def author(self, value : str):
if len(value.split()) > 1:
second_name = value.split()[1]
if second_name[0].isdigit():
raise Exception('Author not valid!')
self.__author = value
@property
def title(self):
return self.__title
@title.setter
def title(self, value):
if len(value) < 3:
raise Exception('Title not valid')
self.__title = value
@property
def price(self):
return self.__price
@price.setter
def price(self, value):
if value < 0:
raise Exception('Price not valid')
self.__price = value
def __str__(self):
return f'Type: {self.__class__.__name__}\nTitle: {self.title}\nAuthor: {self.author}\nPrice: {self.price:.2f}'
class GoldenEditionBook(Book):
def __init__(self, title, author, price):
Book.__init__(self, title, author, price)
self.price = price
@property
def price(self):
return self.__price
@price.setter
def price(self, value):
Book.price.fset(self, value)
self.__price = value * 1.3
author = input()
title = input()
price = float(input())
try:
book = Book(title=title, author=author, price=price)
g_book = GoldenEditionBook(title=title, author=author, price=price)
print(book)
print()
print(g_book)
except Exception as ex:
print(ex)
<file_sep>/Fundamentals/Lists/Lect_RemoveNegativeAndReverse.py
nums = list(map(int, input().split(' ')))
positive_nums = list(filter(lambda x: x >= 0, nums))
print(list(reversed(positive_nums)))
| 4c9ea91d02cc7173315f15e863996681ddec3dc1 | [
"Markdown",
"Python"
] | 45 | Python | LuGeorgiev/PythonSelfLearning | db8fcff2c2df8946d6acf2a2e5677eccf2bbe5dc | 5a88f5a82d261d8ee5e9f65849b940d010cbf096 |
refs/heads/main | <repo_name>Mahfujur51/curd<file_sep>/app/Http/Controllers/CustomerController.php
<?php
namespace App\Http\Controllers;
use App\Customer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Intervention\Image\Facades\Image;
class CustomerController extends Controller
{
public function index(){
$customers=Customer::orderBy('id')->paginate(10);
return view('welcome',compact('customers'));
}
public function store(Request $request){
$request->validate([
'name'=>'required|max:50',
'phone'=>'required|max:50',
'email'=>'required|max:50|unique:customers',
'gender'=>'required|max:50',
'image'=>'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$customer=new Customer();
$customer->name=$request->name;
$customer->phone=$request->phone;
$customer->email=$request->email;
$customer->gender=$request->gender;
if ($request->has('status')){
$customer->status=$request->status;
}else{
$customer->status='inactive';
}
if($request->has('image')){
$image = $request->file('image');
$name_gen = hexdec(uniqid()).'.'.$image->getClientOriginalExtension();
Image::make($image)->resize(270,270)->save('customer/'.$name_gen);
$image_url = $name_gen;
}
$customer->image = $image_url;
$customer->save();
return redirect()->back()->with('message', 'Customer Insert Successfully!!');
}
public function update(Request $request,$id){
$request->validate([
'name'=>'required|max:50',
'phone'=>'required|max:50',
'email'=>'required|max:50',
'gender'=>'required|max:50',
'image'=>'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$customer=Customer::findOrFail($id);
$image='customer/'.$customer->image;
$customer->name=$request->name;
$customer->phone=$request->phone;
$customer->email=$request->email;
$customer->gender=$request->gender;
if ($request->has('status')){
$customer->status=$request->status;
}else{
$customer->status='inactive';
}
if($request->has('image')){
unlink($image);
$image = $request->file('image');
$name_gen = hexdec(uniqid()).'.'.$image->getClientOriginalExtension();
Image::make($image)->resize(270,270)->save('customer/'.$name_gen);
$image_url = $name_gen;
$customer->image = $image_url;
}
$customer->update();
return redirect()->back()->with('message', 'Customer Updated Successfully!!');
}
public function delete($id){
$customer=Customer::findOrFail($id);
$image='customer/'.$customer->image;
unlink($image);
$customer->delete();
return redirect()->back()->with('message', 'Customer Deleted Successfully!!');
}
public function inactive($id){
$customer=Customer::findOrFail($id);
$customer->status='inactive';
$customer->save();
return redirect()->back()->with('message', 'Customer Inactive Successfully!!');
}
public function active($id){
$customer=Customer::findOrFail($id);
$customer->status='active';
$customer->save();
return redirect()->back()->with('message', 'Customer Active Successfully!!');
}
}
<file_sep>/routes/web.php
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/','CustomerController@index')->name('index');
Route::get('/delete/{id}','CustomerController@delete')->name('delete');
Route::get('/edit','CustomerController@edit')->name('edit');
Route::post('/store','CustomerController@store')->name('store');
Route::post('/update/{id}','CustomerController@update')->name('update');
Route::get('/inactive/{id}','CustomerController@inactive')->name('inactive');
Route::get('/active/{id}','CustomerController@active')->name('active');
| 79105efb8fbfe57fbb9da3e8d0e79997d1ec9a7b | [
"PHP"
] | 2 | PHP | Mahfujur51/curd | 7364d4de77ac4d003e2815f190d5e5c90a16a360 | bf82e925682b8ffb5e044b4a1f9ef157121bc469 |
refs/heads/master | <file_sep>from keras.layers import Activation, Convolution2D, Dropout, Conv2D
from keras.layers import AveragePooling2D, BatchNormalization
from keras.layers import GlobalAveragePooling2D
from keras.models import Sequential
from keras.layers import Flatten
from keras.models import Model
from keras.layers import Input
from keras.layers import MaxPooling2D
from keras.layers import SeparableConv2D
from keras import layers
from keras.regularizers import l2
from keras.layers import Dense
def final_model(input1, num_classes): # 81%
input_shape = (input1)
model = Sequential()
model.add(Convolution2D(filters=64, kernel_size=(5, 5), padding='same',
name='image_array', input_shape=input_shape))
model.add(BatchNormalization())
model.add(SeparableConv2D(filters=64, kernel_size=(3, 3), padding='same'))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2), padding='same'))
# model.add(Dropout(.25))
model.add(SeparableConv2D(filters=128, kernel_size=(3, 3), padding='same'))
model.add(BatchNormalization())
model.add(SeparableConv2D(filters=128, kernel_size=(3, 3), padding='same'))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2), padding='same'))
# model.add(Dropout(.25))
model.add(SeparableConv2D(filters=256, kernel_size=(3, 3), padding='same'))
model.add(BatchNormalization())
model.add(SeparableConv2D(filters=256, kernel_size=(3, 3), padding='same'))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2), padding='same'))
# model.add(Dropout(.25))
model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax', name='predictions'))
return model
def mini_XCEPTION(input_shape, num_classes, l2_regularization=0.01): # 80%
regularization = l2(l2_regularization)
# base
img_input = Input(input_shape)
x = SeparableConv2D(8, (3, 3), strides=(1, 1), kernel_regularizer=regularization,
use_bias=False)(img_input)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = SeparableConv2D(8, (3, 3), strides=(1, 1), kernel_regularizer=regularization,
use_bias=False)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
# module 1
residual = SeparableConv2D(16, (1, 1), strides=(2, 2),
padding='same', use_bias=False)(x)
residual = BatchNormalization()(residual)
x = SeparableConv2D(16, (3, 3), padding='same',
kernel_regularizer=regularization,
use_bias=False)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = SeparableConv2D(16, (3, 3), padding='same',
kernel_regularizer=regularization,
use_bias=False)(x)
x = BatchNormalization()(x)
x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
x = layers.add([x, residual])
# module 2
residual = SeparableConv2D(32, (1, 1), strides=(2, 2),
padding='same', use_bias=False)(x)
residual = BatchNormalization()(residual)
x = SeparableConv2D(32, (3, 3), padding='same',
kernel_regularizer=regularization,
use_bias=False)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = SeparableConv2D(32, (3, 3), padding='same',
kernel_regularizer=regularization,
use_bias=False)(x)
x = BatchNormalization()(x)
x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
x = layers.add([x, residual])
# module 3
residual = SeparableConv2D(64, (1, 1), strides=(2, 2),
padding='same', use_bias=False)(x)
residual = BatchNormalization()(residual)
x = SeparableConv2D(64, (3, 3), padding='same',
kernel_regularizer=regularization,
use_bias=False)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = SeparableConv2D(64, (3, 3), padding='same',
kernel_regularizer=regularization,
use_bias=False)(x)
x = BatchNormalization()(x)
x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
x = layers.add([x, residual])
# module 4
residual = SeparableConv2D(128, (1, 1), strides=(2, 2),
padding='same', use_bias=False)(x)
residual = BatchNormalization()(residual)
x = SeparableConv2D(128, (3, 3), padding='same',
kernel_regularizer=regularization,
use_bias=False)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = SeparableConv2D(128, (3, 3), padding='same',
kernel_regularizer=regularization,
use_bias=False)(x)
x = BatchNormalization()(x)
x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
x = layers.add([x, residual])
# # module 5
# residual = SeparableConv2D(256, (1, 1), strides=(2, 2),
# padding='same', use_bias=False)(x)
# residual = BatchNormalization()(residual)
#
# x = SeparableConv2D(256, (3, 3), padding='same',
# kernel_regularizer=regularization,
# use_bias=False)(x)
# x = BatchNormalization()(x)
# x = Activation('relu')(x)
# x = SeparableConv2D(256, (3, 3), padding='same',
# kernel_regularizer=regularization,
# use_bias=False)(x)
# x = BatchNormalization()(x)
#
# x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
# x = layers.add([x, residual])
# module 6
x = SeparableConv2D(num_classes, (3, 3),
# kernel_regularizer=regularization,
padding='same')(x)
x = GlobalAveragePooling2D()(x)
output = Activation('softmax', name='predictions')(x)
model = Model(img_input, output)
return model
def oriaga(input_shape, num_classes, l2_regularization=0.01):
regularization = l2(l2_regularization)
# base
img_input = Input(input_shape)
x = Conv2D(8, (3, 3), strides=(1, 1), kernel_regularizer=regularization,
use_bias=False)(img_input)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = Conv2D(8, (3, 3), strides=(1, 1), kernel_regularizer=regularization,
use_bias=False)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
# module 1
residual = Conv2D(16, (1, 1), strides=(2, 2),
padding='same', use_bias=False)(x)
residual = BatchNormalization()(residual)
x = SeparableConv2D(16, (3, 3), padding='same',
kernel_regularizer=regularization,
use_bias=False)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = SeparableConv2D(16, (3, 3), padding='same',
kernel_regularizer=regularization,
use_bias=False)(x)
x = BatchNormalization()(x)
x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
x = layers.add([x, residual])
# module 2
residual = Conv2D(32, (1, 1), strides=(2, 2),
padding='same', use_bias=False)(x)
residual = BatchNormalization()(residual)
x = SeparableConv2D(32, (3, 3), padding='same',
kernel_regularizer=regularization,
use_bias=False)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = SeparableConv2D(32, (3, 3), padding='same',
kernel_regularizer=regularization,
use_bias=False)(x)
x = BatchNormalization()(x)
x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
x = layers.add([x, residual])
# module 3
residual = Conv2D(64, (1, 1), strides=(2, 2),
padding='same', use_bias=False)(x)
residual = BatchNormalization()(residual)
x = SeparableConv2D(64, (3, 3), padding='same',
kernel_regularizer=regularization,
use_bias=False)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = SeparableConv2D(64, (3, 3), padding='same',
kernel_regularizer=regularization,
use_bias=False)(x)
x = BatchNormalization()(x)
x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
x = layers.add([x, residual])
# module 4
residual = Conv2D(128, (1, 1), strides=(2, 2),
padding='same', use_bias=False)(x)
residual = BatchNormalization()(residual)
x = SeparableConv2D(128, (3, 3), padding='same',
kernel_regularizer=regularization,
use_bias=False)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = SeparableConv2D(128, (3, 3), padding='same',
kernel_regularizer=regularization,
use_bias=False)(x)
x = BatchNormalization()(x)
x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
x = layers.add([x, residual])
x = Conv2D(num_classes, (3, 3),
# kernel_regularizer=regularization,
padding='same')(x)
x = GlobalAveragePooling2D()(x)
output = Activation('softmax', name='predictions')(x)
model = Model(img_input, output)
return model
<file_sep>from imutils import face_utils
import numpy as np
import argparse
import dlib
import cv2
import glob
import os
import pathlib
filepath = "Path of the folder which contains the images"
save = "Path of the folder where we want to save the keypoint generated images"
# vaal = os.path.isfile("/Users/deez/dlibs/PrivateTest/0.jpg")
# place all the files for which keys points has to be genrerated in a folder and give the path of the folder in filepath
# for generating images from dataset one can use functions provided in datasets.py file
# for FER images we recommend to create 3 separate directories to store the images, Training, PrivateTest, PublicTest
# for CK+ images one can put all the images in a single folder
files = glob.glob(filepath)
# construct the argument parser and parse the arguments
# initialize dlib's face detector (HOG-based) and then create
# the facial landmark predictor
detector = dlib.get_frontal_face_detector()
# detector = dlib.cnn_face_detection_model_v1('mmod_human_face_detector.dat')
predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')
for img in files:
filename = os.path.basename(img)
image = cv2.imread(img)
raw_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.resize(raw_gray,(48,48))
rects = detector(gray, 1)
for (i, rect) in enumerate(rects):
shape = predictor(gray, rect)
shape = face_utils.shape_to_np(shape)
(x, y, w, h) = face_utils.rect_to_bb(rect)
for (x, y) in shape:
cv2.circle(gray, (x, y), 1, (0, 0, 0), -1)
cv2.imwrite(save + filename,gray)
<file_sep>import sys
import os
import cv2
from keras.models import load_model
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from src.utils.datasets import get_labels
from src.utils.inference import detect_faces
from src.utils.inference import draw_text
from src.utils.inference import draw_bounding_box
from src.utils.inference import apply_offsets
from src.utils.inference import load_detection_model
from src.utils.inference import load_image
from src.utils.preprocessor import preprocess_input
from src.utils.datasets import DataManager
from src.utils.datasets import split_data
from sklearn.metrics import confusion_matrix,accuracy_score
emotion_model_path = 'fc_key.hdf5'
# val = os.path.isfile(emotion_model_path)
emotion_classifier = load_model(emotion_model_path, compile=False)
emotion_target_size = emotion_classifier.input_shape[1:3]
emotion_classifier.summary()
dataset_name = "ferpluskey"
input_shape = (64, 64, 1)
validation_split = .1
data_loader = DataManager(dataset_name, image_size=input_shape[:2])
faces, emotions = data_loader.get_data()
faces = preprocess_input(faces)
num_samples, num_classes = emotions.shape
train_data, val_data = split_data(faces, emotions, validation_split)
train_faces, train_emotions = train_data
val_faces, val_emotions = val_data
labels = ['neutral','happiness','surprise','sadness','anger','disgust','fear','contempt','unknown', 'NF']
pred = emotion_classifier.predict(val_faces)
results = np.zeros_like(pred)
results[np.arange(len(pred)),pred.argmax(1)] = 1
# results = results.argmax(axis=1)
cm = confusion_matrix(val_emotions.argmax(axis=1),results.argmax(axis=1))
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
accuracy = accuracy_score(val_emotions.argmax(axis=1),results.argmax(axis=1))
df_cm = pd.DataFrame(cm, index=labels, columns=labels)
fig = plt.figure(figsize=(15,15))
plt.title('Accuracy :' + str(round(accuracy,2)))
heatmap = sns.heatmap(df_cm, annot=True, fmt=".2f")
heatmap.yaxis.set_ticklabels(heatmap.yaxis.get_ticklabels(), rotation=0, ha='right', fontsize=14)
heatmap.xaxis.set_ticklabels(heatmap.xaxis.get_ticklabels(), rotation=45, ha='right', fontsize=14)
plt.ylabel('Predicted label')
plt.xlabel('True label')
plt.show()
<file_sep>To Train datasets.
1. Clone the repository
2. Create a folder called datasets in the root directory fo the repository
3. To train on FER13 dataset , create folder called fer2013 in the datasets folder and place the files in the folder
4. To train on CK+ dataset, create folder called CKPlus in the datasets folder and place the files
5. Finally run the train_emotion_classifer.py file. (Double check on the paths set in the code)
To see a demo,
1. give the name of the model to load in demo.py file
2. place the image to be tested in images directory
3. run the demo.py file
4. new file called ‘predicted_result’ wil be generate containing the prediction
To generate key-points
1. place all images for which keypoints has to be generated in a folder
2. create a folder where keypoint generated images has to be saved
3. set the path variables in keypointgenerator.py file to the folder where the images are present
4. run the keypointgenerator.py file
Datasets,
CK and CK+: http://www.pitt.edu/~emotion/ck-spread.htm
FER2013: https://www.kaggle.com/c/challenges-in-representation-learning-facial-expression-recognition-challenge/data
FER-plus: https://github.com/Microsoft/FERPlus
We have created one hot encoding for all the ground truth labels in the dataset directory as well, use them if needed
Environment Setup
1. Install miniconda or Anaconda
2. In the command prompt type, conda env create -f environment.yml
3. this will create all the necessary setup related for the project
4. activate the environment by typing conda activate gpu_env in command prompt
5. deactivae the environment by typing conda deactivate
Acknowledgements,
We sincerely thank <NAME> et al., for their codes posted in GitHub at https://github.com/oarriaga/face_classification
<file_sep>import cv2
from keras.models import load_model
import numpy as np
from src.utils.datasets import get_labels
from src.utils.inference import draw_text
from src.utils.inference import draw_bounding_box
from src.utils.inference import apply_offsets
from src.utils.preprocessor import preprocess_input
import dlib
from src.utils.datasets import Base_path
import os
# parameters for loading data and images
image_path = 'test_image.jpg' # path of the image
directory_path = os.path.basename(image_path)
emotion_model_path = Base_path + '/trained_models/model A_ferplus.hdf5'
emotion_labels = get_labels('ferplus')
font = cv2.FONT_HERSHEY_SIMPLEX
# hyper-parameters for bounding boxes shape
emotion_offsets = (40, 40)
# loading models
emotion_classifier = load_model(emotion_model_path, compile=False)
# gender_classifier = load_model(gender_model_path, compile=False)
# getting input model shapes for inference
emotion_target_size = emotion_classifier.input_shape[1:3]
# gender_target_size = gender_classifier.input_shape[1:3]
# loading images
rgb_image = cv2.imread(image_path)
gray_image = cv2.cvtColor(rgb_image,cv2.COLOR_BGR2GRAY)
gray_image = np.squeeze(gray_image)
gray_image = gray_image.astype('uint8')
detector = dlib.get_frontal_face_detector()
faces = detector(gray_image,1)
for face_coordinates in faces:
x1, x2, y1, y2 = apply_offsets(face_coordinates, emotion_offsets)
gray_face = gray_image[y1:y2, x1:x2]
gray_face = cv2.resize(gray_face, (emotion_target_size))
# cv2.imshow('face', gray_face)
gray_face = preprocess_input(gray_face, True)
gray_face = np.expand_dims(gray_face, 0)
gray_face = np.expand_dims(gray_face, -1)
emotion_label_arg = np.argmax(emotion_classifier.predict(gray_face))
emotion_text = emotion_labels[emotion_label_arg]
color = (0, 0, 255)
draw_bounding_box(face_coordinates, rgb_image, color)
draw_text(face_coordinates, rgb_image, emotion_text, color, 0, 0, 1, 1)
cv2.imwrite(directory_path + '/predicted_result.png', rgb_image)
<file_sep>import pandas as pd
import numpy as np
import os
import cv2
from glob import iglob
import glob
# All path information is related to the system environment being used, Modify them as per the needs
Base_path = '/home/deez/Emotion_classification'
class DataManager(object):
"""Class for loading fer2013 emotion classification dataset or
imdb gender classification dataset."""
def __init__(self, dataset_name='imdb',
dataset_path=None, image_size=(48, 48)):
self.dataset_name = dataset_name
self.dataset_path = dataset_path
self.image_size = image_size
if self.dataset_path is not None:
self.dataset_path = dataset_path
elif self.dataset_name == 'fer2013':
self.dataset_path = (Base_path + '/datasets/fer2013/fer2013/fer2013.csv')
elif self.dataset_name == 'fer2013key':
self.dataset_path = (Base_path + '/datasets/fer2013/fer2013key/')
elif self.dataset_name == 'ckplus':
self.dataset_path = (Base_path + '/datasets/ckplus/')
elif self.dataset_name == "ckpluskey":
self.dataset_path = (Base_path +'/datasets/ckplus/ckpluskey/')
elif self.dataset_name == 'ferpluskey':
self.dataset_path = (Base_path + '/datasets/fer2013/fer2013key/')
elif self.dataset_name == 'ferplus':
self.dataset_path = (Base_path + '/datasets/fer2013/fer2013/fer2013.csv')
def get_data(self):
if self.dataset_name == 'fer2013':
ground_truth_data = self._load_fer2013()
elif self.dataset_name == 'fer2013key':
ground_truth_data = self._load_fer2013key()
if self.dataset_name == 'ferplus':
ground_truth_data = self._load_ferplus()
elif self.dataset_name == 'ferpluskey':
ground_truth_data = self._load_ferpluskey()
elif self.dataset_name == 'ckplus':
ground_truth_data = self._load_ckplus()
elif self.dataset_name == 'ckpluskey':
ground_truth_data = self._load_ckpluskey()
return ground_truth_data
def _load_ferplus(self):
data = pd.read_csv(self.dataset_path)
pixels = data['pixels'].tolist()
width, height = 48, 48
faces = []
for pixel_sequence in pixels:
face = [int(pixel) for pixel in pixel_sequence.split(' ')]
face = np.asarray(face).reshape(width, height)
face = cv2.resize(face.astype('uint8'), self.image_size)
faces.append(face.astype('float32'))
faces = np.asarray(faces)
faces = np.expand_dims(faces, -1)
fer_plus_emotions = np.load(Base_path + '/datasets/ferplus/ferpluslabels.npy')
return faces, fer_plus_emotions
def _load_ferpluskey(self):
num_classes = 10
count = 0
y_size, x_size = self.image_size
train_directory = (self.dataset_path + '/Training/*.*')
validation_directory = (self.dataset_path + '/PrivateTest/*.*')
test_directory = (self.dataset_path + '/PublicTest/*.*')
file_list = [f for f in iglob(train_directory, recursive=True) if os.path.isfile(f)]
num_faces = len(file_list) - 1
train_x = np.zeros(shape=(num_faces, y_size, x_size))
train_y = np.zeros(shape=(num_faces, num_classes))
for image_file in file_list:
if image_file.lower().endswith('.jpg'):
filename = os.path.basename(image_file)
idx = int(os.path.splitext(filename)[0])
image_array = cv2.imread(image_file, cv2.IMREAD_GRAYSCALE)
image_array = cv2.resize(image_array, (y_size, x_size))
face = image_array.astype('float32')
train_x[idx] = face
file_list = [f for f in iglob(validation_directory, recursive=True) if os.path.isfile(f)]
num_faces = len(file_list) - 1
val_x = np.zeros(shape=(num_faces, y_size, x_size))
val_y = np.zeros(shape=(num_faces, num_classes))
for image_file in file_list:
if image_file.lower().endswith('.jpg'):
filename = os.path.basename(image_file)
idx = int(os.path.splitext(filename)[0])
image_array = cv2.imread(image_file, cv2.IMREAD_GRAYSCALE)
image_array = cv2.resize(image_array, (y_size, x_size))
face = image_array.astype('float32')
val_x[idx] = face
file_list = [f for f in iglob(test_directory, recursive=True) if os.path.isfile(f)]
num_faces = len(file_list) - 1
test_x = np.zeros(shape=(num_faces, y_size, x_size))
test_y = np.zeros(shape=(num_faces, num_classes))
for image_file in file_list:
if image_file.lower().endswith('.jpg'):
filename = os.path.basename(image_file)
idx = int(os.path.splitext(filename)[0])
image_array = cv2.imread(image_file, cv2.IMREAD_GRAYSCALE)
image_array = cv2.resize(image_array, (y_size, x_size))
face = image_array.astype('float32')
test_x[idx] = face
faces = np.concatenate((train_x, test_x, val_x), axis=0)
faces = np.expand_dims(faces, -1)
fer_plus_emotions = np.load(Base_path + '/datasets/ferplus/ferpluslabels.npy')
return faces, fer_plus_emotions
def _load_ckpluskey(self):
files = glob.glob(self.dataset_path + '*.png')
num_faces = len(files)
y_size, x_size = self.image_size
faces = np.zeros(shape=(num_faces, y_size, x_size))
for file_arg, file_path in enumerate(files):
image_array = cv2.imread(file_path, cv2.IMREAD_GRAYSCALE)
image_array = cv2.resize(image_array, (y_size, x_size))
face = image_array.astype('float32')
faces[file_arg] = face
faces = np.expand_dims(faces, -1)
emotions = np.load((self.dataset_path + '/labels.npy'))
return faces, emotions
def _load_ckplus(self):
num_classes = 8
emotion_file_list = []
emotion_file_name = []
image_file_list = []
count = 0
root_dir = (Base_path + '/datasets/ckplus/***/**/*')
file_list = [f for f in iglob(root_dir, recursive=True) if os.path.isfile(f)]
for file in file_list:
if file.lower().endswith('.txt'):
path, file_name = os.path.split(file)
emotion_file_list.append(file)
emotion_file_name.append(file_name[:-12])
count += 1
i_count = 0
for image_file in file_list:
if image_file.lower().endswith('.png'):
path, image_name = os.path.split(image_file)
image_name_without_extension = os.path.splitext(image_name)[0]
if image_name_without_extension in emotion_file_name:
image_file_list.append(image_file)
i_count += 1
num_faces = len(image_file_list)
y_size, x_size = self.image_size
faces = np.zeros(shape=(num_faces, y_size, x_size))
emotions = np.zeros(shape=(num_faces, num_classes))
for file_arg, file_path in enumerate(image_file_list):
image_array = cv2.imread(file_path, cv2.IMREAD_GRAYSCALE)
image_array = cv2.resize(image_array, (y_size, x_size))
face = image_array.astype('float32')
faces[file_arg] = image_array
for file_arg, file_path in enumerate(emotion_file_list):
with open(file_path, "r") as myfile:
data = myfile.readlines()
label = int(os.path.splitext(data[0])[0])
emotions[file_arg, label] = 1
faces = np.expand_dims(faces, -1)
return faces, emotions
def _load_fer2013(self):
data = pd.read_csv(self.dataset_path)
pixels = data['pixels'].tolist()
width, height = 48, 48
faces = []
for pixel_sequence in pixels:
face = [int(pixel) for pixel in pixel_sequence.split(' ')]
face = np.asarray(face).reshape(width, height)
face = cv2.resize(face.astype('uint8'), self.image_size)
faces.append(face.astype('float32'))
faces = np.asarray(faces)
faces = np.expand_dims(faces, -1)
emotions = pd.get_dummies(data['emotion']).as_matrix()
return faces, emotions
def _load_fer2013key(self):
num_classes = 7
count = 0
y_size, x_size = self.image_size
train_directory = (self.dataset_path + '/Training/*.*')
validation_directory = (self.dataset_path + '/PrivateTest/*.*')
test_directory = (self.dataset_path + '/PublicTest/*.*')
file_list = [f for f in iglob(train_directory, recursive=True) if os.path.isfile(f)]
num_faces = len(file_list) - 1
train_x = np.zeros(shape=(num_faces, y_size, x_size))
train_y = np.zeros(shape=(num_faces, num_classes))
for image_file in file_list:
if image_file.lower().endswith('.jpg'):
filename = os.path.basename(image_file)
idx = int(os.path.splitext(filename)[0])
image_array = cv2.imread(image_file, cv2.IMREAD_GRAYSCALE)
image_array = cv2.resize(image_array, (y_size, x_size))
face = image_array.astype('float32')
train_x[idx] = face
if image_file.lower().endswith('.npy'):
path = os.path.dirname(image_file)
train_y = np.load(path + '/labels.npy')
file_list = [f for f in iglob(validation_directory, recursive=True) if os.path.isfile(f)]
num_faces = len(file_list) - 1
val_x = np.zeros(shape=(num_faces, y_size, x_size))
val_y = np.zeros(shape=(num_faces, num_classes))
for image_file in file_list:
if image_file.lower().endswith('.jpg'):
filename = os.path.basename(image_file)
idx = int(os.path.splitext(filename)[0])
image_array = cv2.imread(image_file, cv2.IMREAD_GRAYSCALE)
image_array = cv2.resize(image_array, (y_size, x_size))
face = image_array.astype('float32')
val_x[idx] = face
if image_file.lower().endswith('.npy'):
path = os.path.dirname(image_file)
val_y = np.load(path + '/labels.npy')
file_list = [f for f in iglob(test_directory, recursive=True) if os.path.isfile(f)]
num_faces = len(file_list) - 1
test_x = np.zeros(shape=(num_faces, y_size, x_size))
test_y = np.zeros(shape=(num_faces, num_classes))
for image_file in file_list:
if image_file.lower().endswith('.jpg'):
filename = os.path.basename(image_file)
idx = int(os.path.splitext(filename)[0])
image_array = cv2.imread(image_file, cv2.IMREAD_GRAYSCALE)
image_array = cv2.resize(image_array, (y_size, x_size))
face = image_array.astype('float32')
test_x[idx] = face
if image_file.lower().endswith('.npy'):
path = os.path.dirname(image_file)
test_y = np.load(path + '/labels.npy')
faces = np.concatenate((train_x, test_x, val_x), axis=0)
faces = np.expand_dims(faces, -1)
emotions = np.concatenate((train_y, val_y, test_y), axis=0)
return faces, emotions
def get_labels(dataset_name):
if dataset_name == 'fer2013' or dataset_name == 'fer2013key':
return {0: 'angry', 1: 'disgust', 2: 'fear', 3: 'happy',
4: 'sad', 5: 'surprise', 6: 'neutral'}
elif dataset_name == 'ckplus' or dataset_name == 'ckpluskey':
return {0: 'neutral', 1: 'anger', 2: 'contempt', 3: 'disgust', 4: 'fear', 5: 'happy', 6: 'sadness', 7: 'surprise'}
elif dataset_name == 'ferplus' or dataset_name == 'ferpluskey':
return {0: 'neutral', 1: 'happiness', 2: 'surprise', 3: 'sadness', 4: 'anger', 5: 'disgust', 6: 'fear',
7: 'contempt', 8:'unknown', 9:'NF'}
else:
raise Exception('Invalid dataset name')
def split_data(x, y, validation_split=.2):
num_samples = len(x)
num_train_samples = int((1 - validation_split)*num_samples)
train_x = x[:num_train_samples]
train_y = y[:num_train_samples]
val_x = x[num_train_samples:]
val_y = y[num_train_samples:]
train_data = (train_x, train_y)
val_data = (val_x, val_y)
return train_data, val_data
| 141bce2c04995b4315b68a8280aafbcf6200b1d0 | [
"Markdown",
"Python"
] | 6 | Python | s785564373/Emotion-Recognition | 1da15d73c87859238a8caa0e39637d2fd0699a42 | b5ef896a64c0841d687a34315bc48828cce5eb98 |
refs/heads/master | <repo_name>daniel9898/Tp_Laboratorio_2<file_sep>/Pereira.Daniel.2D.TP3/EntidadesInstanciables/Instructor.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EntidadesAbstractas;
using System.Xml.Serialization;
namespace EntidadesInstanciables
{
public sealed class Instructor : PersonaGimnasio
{
#region Atributos
private Queue<Gimnasio.EClases> _clasesDelDia;
private static Random _random;
#endregion
#region Constructores
public Instructor(int id, string nombre, string apellido, string dni, ENacionalidad nacionalidad)
: base(id, nombre, apellido, dni, nacionalidad)
{
this._clasesDelDia = new Queue<Gimnasio.EClases>();
this.RandomClases();
this.RandomClases();
}
public Instructor()
{
}
static Instructor()
{
_random = new Random();
}
#endregion
#region Propiedades
[XmlIgnore]
public Queue<Gimnasio.EClases> ListaClases
{
get
{
return this._clasesDelDia;
}
}
#endregion
#region Metodos
///<summary>
///Genera una clase aleatoreamente y se la asigna al objeto instructor actual
///</summary>
private void RandomClases()
{
this._clasesDelDia.Enqueue(((Gimnasio.EClases)_random.Next(0, 4)));
}
/// <summary>
/// retorna una cadena con las clases del dia del objeto instructor
/// </summary>
/// <returns></returns>
protected override string ParticiparEnClase()
{
string retorno = "\n\nCLASES DEL DIA :";
foreach (Gimnasio.EClases alum in this._clasesDelDia)
{
retorno += "\n" + alum.ToString();
}
return retorno;
}
/// <summary>
/// retorna una cadena de texto con todos los datos del objeto instructor
/// </summary>
/// <returns></returns>
protected override string MostrarDatos()
{
return base.MostrarDatos() + ParticiparEnClase();
}
/// <summary>
/// retorna una cadena de texto con todos los datos del objeto instructor
/// </summary>
/// <returns></returns>
public override string ToString()
{
return MostrarDatos();
}
#endregion
#region Sobrecargas
/// <summary>
/// Verifica si un instructor da una determinada clase
/// </summary>
/// <param name="ins"></param>
/// <param name="clases"></param>
/// <returns></returns>
public static bool operator ==(Instructor ins, Gimnasio.EClases clase)
{
bool retorno = false;
foreach (Gimnasio.EClases a in ins._clasesDelDia)
{
if (a == clase)
{
retorno = true;
}
}
return retorno;
}
/// <summary>
/// Verifica si un instructor No da una determinada clase
/// </summary>
/// <param name="ins"></param>
/// <param name="clases"></param>
/// <returns></returns>
public static bool operator !=(Instructor ins, Gimnasio.EClases clases)
{
return !(ins == clases);
}
#endregion
}
}
<file_sep>/Pereira.Daniel.2D.TP3/EntidadesAbstractas/Persona.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Excepciones;
namespace EntidadesAbstractas
{
public class Persona
{
#region Atributos
private string _apellido;
private string _nombre;
private int _dni;
private ENacionalidad _nacionalidad;
#endregion
#region Enumerados
public enum ENacionalidad
{
Argentino,
Extranjero
}
#endregion
#region Propiedades
/// <summary>
/// Valida que el DNI sea correcto y lo setea
/// </summary>
public int DNI
{
get { return this._dni; }
set
{
try
{
int retorno = ValidarDni(this._nacionalidad, value);
if (retorno != -1)// si retorno vale -1 significa que es un dni invalido
this._dni = value;
else
{
throw new DniInvalidoException();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
/// <summary>
/// Valida que el nombre sea correcto y lo setea
/// </summary>
public string Nombre
{
get { return this._nombre; }
set
{
try
{
string retorno = ValidarNombreApellido(value);
if (retorno != null)
this._nombre = value;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
/// <summary>
/// Valida que el Apellido sea correcto y lo setea
/// </summary>
public string Apellido
{
get { return this._apellido; }
set
{
string retorno = ValidarNombreApellido(value);
if (retorno != null)
this._apellido = value;
else
throw new NullReferenceException();
}
}
/// <summary>
/// Valida que la nacionalidad sea la correcto y la setea
/// </summary>
public ENacionalidad Nacionalidad
{
get { return this._nacionalidad; }
set
{
try
{
if (value == ENacionalidad.Argentino || value == ENacionalidad.Extranjero)
this._nacionalidad = value;
else
{
throw new NacionalidadInvalidaException("Nacionalidad Invalida");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
/// <summary>
/// Valida que el dni sea correcto y lo setea
/// </summary>
public string StringToDNI
{
set
{
int retorno = ValidarDni(this._nacionalidad, value);
if (retorno != -1)
this._dni = retorno;
else
{
throw new NacionalidadInvalidaException("La nacionalidad nose condice con el número de DNI");
}
}
}
#endregion
#region Constructores
public Persona(string nombre, string apellido, ENacionalidad nacionalidad)
{
this.Nombre = nombre;
this.Apellido = apellido;
this.Nacionalidad = nacionalidad;
}
public Persona(string nombre, string apellido, int dni, ENacionalidad nacionalidad)
: this(nombre, apellido, nacionalidad)
{
this.DNI = dni;
}
public Persona(string nombre, string apellido, string dni, ENacionalidad nacionalidad)
: this(nombre, apellido, nacionalidad)
{
this.StringToDNI = dni;
}
public Persona()
{
}
#endregion
#region Metodos
/// <summary>
/// Muestra todos los datos de un objeto persona
/// </summary>
/// <returns></returns>
public override string ToString()
{
string retorno = "";
try
{
retorno = "NOMBRE COMPLETO : " + this._apellido.ToString() + "," + this._nombre.ToString() + "\nNACIONALIDAD :" + this._nacionalidad.ToString();
}
catch (NullReferenceException e)
{
Console.WriteLine(e.Message);
}
return retorno;
}
/// <summary>
/// Valida que la nacionalidad cumpla con los parametros del numero de Dni
/// </summary>
/// <param name="nacionalidad"></param>
/// <param name="dato"></param>
/// <returns></returns>
private int ValidarDni(ENacionalidad nacionalidad, int dato)
{
int retorno = -1;
if (nacionalidad == ENacionalidad.Argentino && dato >= 1 && dato < 89999999)
{
retorno = dato;
}
else if (nacionalidad == ENacionalidad.Extranjero && dato > 89999999 && dato < 500000000)
{
retorno = dato;
}
return retorno;
}
/// <summary>
/// Valida que la nacionalidad cumpla con los parametros del numero de Dni
/// </summary>
/// <param name="nacionalidad"></param>
/// <param name="dato"></param>
/// <returns></returns>
private int ValidarDni(ENacionalidad nacionalidad, string dato)
{
int retorno = -1;
int dni;
if (int.TryParse(dato, out dni))
{
retorno = ValidarDni(nacionalidad, dni);
if (retorno != -1)
retorno = dni;
}
return retorno;
}
/// <summary>
/// Valida que sea un nombre o apellido valido,solo letras
/// </summary>
/// <param name="dato"></param>
/// <returns></returns>
private string ValidarNombreApellido(string dato)
{
Regex rgx = new Regex("^[A-Za-z ]+$");
if (rgx.IsMatch(dato))
return dato;
else
return null;
}
#endregion
}
}
<file_sep>/Pereira.Daniel.2D.TP3/EntidadesInstanciables/Gimnasio.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excepciones;
using Archivos;
using System.Xml.Serialization;
namespace EntidadesInstanciables
{
[Serializable]
[XmlInclude(typeof(Alumno))]
[XmlInclude(typeof(Instructor))]
[XmlInclude(typeof(Jornada))]
public class Gimnasio
{
#region Atributos
private List<Alumno> _alumnos;
private List<Instructor> _instructores;
private List<Jornada> _jornada;
#endregion
#region Enumerados
public enum EClases
{
Natacion,
Pilates,
CrossFit,
Yoga
}
#endregion
#region Constructores
public Gimnasio()
{
this._alumnos = new List<Alumno>();
this._instructores = new List<Instructor>();
this._jornada = new List<Jornada>();
}
#endregion
#region Propiedades
public List<Alumno> Alumnos
{
get { return this._alumnos; }
set { this._alumnos = value; }
}
public List<Instructor> Instructores
{
get { return this._instructores; }
set { this._instructores = value; }
}
public List<Jornada> Jornada
{
get { return this._jornada; }
set { this._jornada = value; }
}
/// <summary>
/// indexa la lista de jornada
/// </summary>
/// <param name="indice"></param>
/// <returns></returns>
public Jornada this[int indice]
{
get
{
try
{
return this._jornada[indice];
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine(e.Message);
return null;
}
}
}
#endregion
#region Metodos
/// <summary>
/// Retorna una cadena con todos los datos del gimnasio
/// </summary>
/// <param name="gim"></param>
/// <returns></returns>
private static string MostrarDatos(Gimnasio gim)
{
string retorno = "JORNADA :\n";
for (int i = 0; i < gim._jornada.Count; i++)
{
retorno += gim._jornada[i].ToString();
}
return retorno;
}
/// <summary>
/// Retorna una cadena con todos los datos del gimnasio
/// </summary>
/// <returns></returns>
public override string ToString()
{
return Gimnasio.MostrarDatos(this);
}
/// <summary>
/// Guarda los datos del gimnasio en un archivo con formato xml
/// </summary>
/// <param name="gim"></param>
/// <returns></returns>
public static bool Guardar(Gimnasio gim)
{
Xml<Gimnasio> xml = new Xml<Gimnasio>();
return ((IArchivo<Gimnasio>)xml).Guardar("GIMNASIO.xml", gim);
}
/// <summary>
/// Lee los datos del gimnasio desde un archivo con formato xml
/// </summary>
/// <param name="gim"></param>
/// <returns></returns>
public static bool Leer(Gimnasio gim)
{
Xml<Gimnasio> xml = new Xml<Gimnasio>();
bool retorno = ((IArchivo<Gimnasio>)xml).Leer("GIMNASIO.xml", out gim);
Console.WriteLine(gim.ToString());
return retorno;
}
#endregion
#region Sobrecargas
/// <summary>
/// Verifica si un alumno esta anotado en un gimnasio
/// </summary>
/// <param name="g"></param>
/// <param name="a"></param>
/// <returns></returns>
public static bool operator ==(Gimnasio g, Alumno a)
{
bool retorno = false;
int i;
for (i = 0; i < g._alumnos.Count; i++)
{
if (a == g._alumnos[i])
retorno = true;
}
return retorno;
}
/// <summary>
/// Verifica si un alumno No esta anotado en un gimnasio
/// </summary>
/// <param name="g"></param>
/// <param name="a"></param>
/// <returns></returns>
public static bool operator !=(Gimnasio g, Alumno a)
{
return !(g == a);
}
/// <summary>
/// Verifica si un instructor esta anotado en un gimnasio
/// </summary>
/// <param name="g"></param>
/// <param name="ins"></param>
/// <returns></returns>
public static bool operator ==(Gimnasio g, Instructor ins)
{
bool retorno = false;
for (int i = 0; i < g._instructores.Count; i++)
{
if (ins == g._instructores[i])
retorno = true;
}
return retorno;
}
/// <summary>
/// Verifica si un instructor No esta anotado en un gimnasio
/// </summary>
/// <param name="g"></param>
/// <param name="ins"></param>
/// <returns></returns>
public static bool operator !=(Gimnasio g, Instructor ins)
{
return !(g == ins);
}
/// <summary>
/// Retorna el primer instructor que pueda dar la clase
/// </summary>
/// <param name="g"></param>
/// <param name="clase"></param>
/// <returns></returns>
public static Instructor operator ==(Gimnasio g, Gimnasio.EClases clase)
{
for (int i = 0; i < g._instructores.Count; i++)
{
foreach (Gimnasio.EClases cla in g._instructores[i].ListaClases)
{
if (cla == clase)
return g._instructores[i];
}
}
return null;
}
/// <summary>
/// Retorna el primer instructor que No pueda dar la clase
/// </summary>
/// <param name="g"></param>
/// <param name="clase"></param>
/// <returns></returns>
public static Instructor operator !=(Gimnasio g, Gimnasio.EClases clase)
{
for (int i = 0; i < g._instructores.Count; i++)
{
foreach (Gimnasio.EClases cla in g._instructores[i].ListaClases)
{
if (cla != clase)
return g._instructores[i];
}
}
return null;
}
/// <summary>
/// Agrega un alumno al gimnasio validando que ya no este ingresado
/// </summary>
/// <param name="gim"></param>
/// <param name="a"></param>
/// <returns></returns>
public static Gimnasio operator +(Gimnasio gim, Alumno a)
{
if (gim != a)
gim._alumnos.Add(a);
else
throw new AlumnoRepetidoException();
return gim;
}
/// <summary>
/// Agrega un instructor al gimnasio validando que ya no este ingresado
/// </summary>
/// <param name="gim"></param>
/// <param name="i"></param>
/// <returns></returns>
public static Gimnasio operator +(Gimnasio gim, Instructor i)
{
if (gim != i)
gim._instructores.Add(i);
return gim;
}
/// <summary>
/// Agrega una nueva clase al gimnasio junto con un instructor que pueda darla
/// y los alumnos que esten anotados para esa clase
/// </summary>
/// <param name="gim"></param>
/// <param name="clase"></param>
/// <returns></returns>
public static Gimnasio operator +(Gimnasio gim, Gimnasio.EClases clase)
{
Instructor inst = gim == clase;
try
{
Jornada jor = new Jornada(clase, inst);
gim._jornada.Add(jor);
for (int i = 0; i < gim._alumnos.Count; i++)
{
if (gim._alumnos[i] == clase)
jor += gim._alumnos[i];
}
}
catch (NullReferenceException)//si inst queda en null significa que no hay instructor
{ //para la clase
throw new SinInstructorException();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return gim;
}
#endregion
}
}
<file_sep>/RPP/Pereira.Daniel.2d/Entidades/Gaseosa.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace Entidades
{
[Serializable]
[XmlInclude(typeof(Gaseosa))]
public class Gaseosa : Producto
{
#region Atributos
protected float _litros;
protected static bool DeConsumo;
#endregion
#region Propiedades
/// <summary>
/// al precio final le calcula su 42%
/// </summary>
public override float CalcularCostoDeProduccion
{
get { return base._precio * 0.42f; }
}
/// <summary>
/// inserta o retorna el valor litros de un de una Galletita
/// </summary>
public float litros
{ get; set; }
#endregion
#region Constructores
public Gaseosa(int codigoDeBarra,float precio,EMarcaProducto marca,float litros):base(codigoDeBarra,marca,precio)
{
this._litros = litros;
}
static Gaseosa()
{
Gaseosa.DeConsumo = true;
}
public Gaseosa(Producto p, float litros):base((int)p,p.Marca,p.Precio)
{
this._litros = litros;
}
public Gaseosa()
{
}
#endregion
#region Metodos
/// <summary>
/// retorna una cadena de texto con toda la informacion de una Gaseosa
/// </summary>
/// <returns></returns>
private string MostrarGaseosa()
{
return this + "LITROS : " + this._litros.ToString();
}
/// <summary>
/// muestra todos los datos de una gaseosa
/// </summary>
/// <returns></returns>
public string ToString()
{
return MostrarGaseosa();
}
/// <summary>
/// retorna una cadena especifica
/// </summary>
/// <returns></returns>
public override string Consumir()
{
return "Bebible";
}
#endregion
}
}
<file_sep>/Pereira.Daniel.2D.TP3/Archivos/Texto.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excepciones;
namespace Archivos
{
public class Texto : IArchivo<string>
{
/// <summary>
/// Guarda los datos de tipo string en un archivo con formato texto
/// </summary>
/// <param name="archivo"></param>
/// <param name="datos"></param>
/// <returns></returns>
bool IArchivo<string>.Guardar(string archivo,string datos)
{
bool retorno = true;
try
{
FileStream stream = new FileStream(archivo, FileMode.Append, FileAccess.Write);
StreamWriter escribir = new StreamWriter(stream);
string miCadena = datos;
string[] partes = miCadena.Split(new char[] { '\n' });
foreach (string item in partes)
{
escribir.WriteLine(item);
}
escribir.Close();
}
catch (Exception e)
{
retorno = false;//si entro aca significa que hubo un problema
throw new ArchivosException(e);
}
return retorno;
}
/// <summary>
/// Lee los datos desde un archivo con formato txt
/// </summary>
/// <param name="archivo"></param>
/// <param name="datos"></param>
/// <returns></returns>
bool IArchivo<string>.Leer(string archivo,out string datos)
{
bool retorno = true;
try
{
FileStream stream = new FileStream(archivo, FileMode.Open, FileAccess.Read);
TextReader lector = new StreamReader(stream);
datos = lector.ReadToEnd();
lector.Close();
}
catch (Exception e)
{
retorno = false;//si entro aca significa que hubo un problema
throw new ArchivosException(e);
}
return retorno;
}
}
}
<file_sep>/Pereira.Daniel.2D.TP3/TestUnitario/DniValido.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Excepciones;
using EntidadesInstanciables;
using EntidadesAbstractas;
namespace Utest
{
[TestClass]
public class DniValido
{
[TestMethod]
[ExpectedException(typeof(NacionalidadInvalidaException))]
public void TestDniValido()
{
// se verifica que lanze la excepcion cuando el DNI sea incorrecto dependiendo
//de su nacionalidad
int id = 45;
string nombre ="Daniel";
string apellido = "Pereira";
string dni = "456888";
Alumno.ENacionalidad nacionalidad = Alumno.ENacionalidad.Extranjero;
Gimnasio.EClases claseQueToma = Gimnasio.EClases.Yoga;
Alumno alu1 = new Alumno(id,nombre,apellido,dni,nacionalidad,claseQueToma);
}
}
}
<file_sep>/Pereira.Daniel.2D.TP3/Archivos/Xml.cs
using Excepciones;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace Archivos
{
public class Xml<T> : IArchivo<T>
{
/// <summary>
/// Guarda los datos del tipo T en un archivo con formato Xml
/// </summary>
/// <param name="archivo"></param>
/// <param name="datos"></param>
/// <returns></returns>
bool IArchivo<T>.Guardar(string archivo,T datos)
{
bool retorno = true;
try
{
XmlSerializer xml = new XmlSerializer(typeof(T));
Stream escritor = new FileStream(archivo, FileMode.OpenOrCreate);
xml.Serialize(escritor, datos);
escritor.Close();
}
catch (Exception e)
{
retorno = false;//si entro aca significa que hubo un problema
throw new ArchivosException(e);
}
return retorno;
}
/// <summary>
/// lee los datos de tipo T desde un archivo con formato Xml
/// </summary>
/// <param name="archivo"></param>
/// <param name="datos"></param>
/// <returns></returns>
bool IArchivo<T>.Leer(string archivo,out T datos)
{
bool retorno = true;
try
{
XmlSerializer xml = new XmlSerializer(typeof(T));
FileStream Lector = File.OpenRead(archivo);
T e = (T)xml.Deserialize(Lector);
datos = e;
Lector.Close();
}
catch (Exception ex)
{
retorno = false;//si entro aca significa que hubo un problema
throw new ArchivosException(ex);
}
return retorno;
}
}
}
<file_sep>/RPP/Pereira.Daniel.2d/FormEstante/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.Threading.Tasks;
using System.Windows.Forms;
using Entidades;
using System.IO;
using System.Xml.Serialization;
namespace FormEstante
{
public partial class FormEstante : Form
{
public FormEstante()
{
InitializeComponent();
}
/// <summary>
/// Compara 2 marcas de 2 productos diferentes y retorna un valor entero
/// positivo,negativo o cero dependiendo de si uno es mayor,menor o son iguales
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
private static int OrdenarProductos(Producto a, Producto b)
{
return string.Compare(a.Marca.ToString(), b.Marca.ToString());
}
public Estante est1;
public Estante est2;
/// <summary>
/// Instancia y carga diferentes productos y estantes
/// </summary>
/// <param name="e1"></param>
/// <param name="e2"></param>
private void CargarEstante(out Estante e1,out Estante e2)
{
//DEJE LA CARGA COMENTADA PARA PROBAR LA DESERIALIZACION
//****************************************************
//est1 = new Estante(4);
//est2 = new Estante(3);
//Harina h1 = new Harina(102, 37.5f, Producto.EMarcaProducto.Favorita, Harina.ETipoHarina.CuatroCeros);
//Harina h2 = new Harina(103, 40.25f, Producto.EMarcaProducto.Favorita, Harina.ETipoHarina.Integral);
//Galletita g1 = new Galletita(113, 33.65f, Producto.EMarcaProducto.Pitusas, 250f);
//Galletita g2 = new Galletita(111, 56f, Producto.EMarcaProducto.Diversión, 500f);
//Jugo j1 = new Jugo(112, 25f, Producto.EMarcaProducto.Naranjú, Jugo.ESaborJugo.Pasable);
//Jugo j2 = new Jugo(333, 33f, Producto.EMarcaProducto.Swift, Jugo.ESaborJugo.Asqueroso);
//Gaseosa g = new Gaseosa(j2, 2250f);
//if (!(est1 + h1))
//{
// Console.WriteLine("No se pudo agregar el producto al estante!!!");
//}
//if (!(est1 + g1))
//{
// Console.WriteLine("No se pudo agregar el producto al estante!!!");
//}
//if (!(est1 + g2))
//{
// Console.WriteLine("No se pudo agregar el producto al estante!!!");
//}
//if (!(est1 + g1))
//{
// Console.WriteLine("No se pudo agregar el producto al estante!!!");
//}
//if (!(est1 + j1))
//{
// Console.WriteLine("No se pudo agregar el producto al estante!!!");
//}
//if (!(est2 + h2))
//{
// Console.WriteLine("No se pudo agregar el producto al estante!!!");
//}
//if (!(est2 + j2))
//{
// Console.WriteLine("No se pudo agregar el producto al estante!!!");
//}
//if (!(est2 + g))
//{
// Console.WriteLine("No se pudo agregar el producto al estante!!!");
//}
//if (!(est2 + g1))
//{
// Console.WriteLine("No se pudo agregar el producto al estante!!!");
//}
//e1 = est1;
//e2 = est2;
e1 = Serializador.DeserializarEstante("estante1xml.xml");
e2 = Serializador.DeserializarEstante("estante2xml.xml");
}
/// <summary>
/// Evento que muestra los datos de los estantes y sus productos
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnEjecutar_Click(object sender, EventArgs e)
{
rtxtSalida.Text = "";
Estante est1;
Estante est2;
this.CargarEstante(out est1, out est2);
rtxtSalida.Text += String.Format("Valor total Estante1: {0}", est1.ValorEstanteTotal);
rtxtSalida.Text += String.Format("Valor Estante1 sólo de Galletitas: {0}", est1.GetValorEstante(Producto.ETipoProducto.Galletita));
rtxtSalida.Text += String.Format("Contenido Estante1:\n{0}", Estante.MostrarEstante(est1));
rtxtSalida.Text += "Estante ordenado por Marca....\n";
est1.GetProductos().Sort(FormEstante.OrdenarProductos);
rtxtSalida.Text += Estante.MostrarEstante(est1);
est1 = est1 - Producto.ETipoProducto.Galletita;
rtxtSalida.Text += String.Format("Estante1 sin Galletitas: {0}", Estante.MostrarEstante(est1));
rtxtSalida.Text += String.Format("Contenido Estante2:\n{0}", Estante.MostrarEstante(est2));
est2 -= Producto.ETipoProducto.Todos;
rtxtSalida.Text += String.Format("Contenido Estante2:\n{0}", Estante.MostrarEstante(est2));
}
/// <summary>
/// guarda en un archivo de texto todos los datos de los estantes
/// </summary>
/// <param name="rtxt"></param>
public static void GuardarEstante(string rtxt)
{
FileStream stream = new FileStream("EstantesTxt.txt",FileMode.OpenOrCreate,FileAccess.Write);
StreamWriter escribir = new StreamWriter(stream);
string miCadena = rtxt;
string[] partes=miCadena.Split(new char[] {'\n'});
foreach (string item in partes)
{
escribir.WriteLine(item);
}
escribir.Close();
}
/// <summary>
/// Al cerrar el formulario se gurada en archivo de texto y se
/// serializa o se deserializa dependiendo el caso
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FormEstante_FormClosing(object sender, FormClosingEventArgs e)
{
//guardarmos en un archivo txt
FormEstante.GuardarEstante(rtxtSalida.Text);
//LO DE ABAJA QUEDO COMENTADO PARA PROBAR LA DESERIALIZACION
//guardarmos en un archivo xml
//Serializador.SerializarEstante(est1,"estante1xml.xml");
//Serializador.SerializarEstante(est2,"estante2xml.xml");
}
}
}
<file_sep>/Pereira.Daniel.2D.TP3/EntidadesAbstractas/PersonaGimnasio.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EntidadesAbstractas
{
public abstract class PersonaGimnasio : Persona
{
#region Atributos
private int _identificador;
#endregion
#region Constructores
public PersonaGimnasio(int id, string nombre, string apellido, string dni, ENacionalidad nacionalidad)
: base(nombre, apellido, dni, nacionalidad)
{
if ( id >= 1 && id <= 2000 )//ponemos un limite maximo al id
{
this._identificador = id;
}
else
throw new FormatException();
}
public PersonaGimnasio()
{
}
#endregion
#region Metodos
/// <summary>
/// Determina si dos objetos son del mismo tipo
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
return this.GetType() == obj.GetType();
}
/// <summary>
/// retorna una cadena de texto con todos los datos del objeto Persona Gimnasio
/// </summary>
/// <returns></returns>
protected virtual string MostrarDatos()
{
string retorno = "";
try
{
retorno = base.ToString() + "\n\nCARNET NÚMERO :" + this._identificador;
}
catch (NullReferenceException e)
{
Console.WriteLine(e.Message);
}
return retorno;
}
/// <summary>
/// Retorna una cadena de texto especifica
/// </summary>
/// <returns></returns>
protected abstract string ParticiparEnClase();
#endregion
#region Sobrecargas
/// <summary>
/// determina si dos objetos son iguales comparando sus tipos y sus DNI
/// </summary>
/// <param name="pg1"></param>
/// <param name="pg2"></param>
/// <returns></returns>
public static bool operator ==(PersonaGimnasio pg1, PersonaGimnasio pg2)
{
bool retorno = false;
if (pg1.Equals(pg2) && pg1.DNI == pg2.DNI)
{
retorno = true;
}
return retorno;
}
/// <summary>
/// determina si dos objetos son diferentes comparando sus tipos y sus DNI
/// </summary>
/// <param name="pg1"></param>
/// <param name="pg2"></param>
/// <returns></returns>
public static bool operator !=(PersonaGimnasio pg1, PersonaGimnasio pg2)
{
return !(pg1 == pg2);
}
#endregion
}
}
<file_sep>/RPP/Pereira.Daniel.2d/Entidades/Producto.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.IO;
namespace Entidades
{
public abstract class Producto
{
#region Atributos
protected int _codigoBarra;
protected EMarcaProducto _marca;
protected float _precio;
#endregion
#region Enumerados
public enum EMarcaProducto
{
Favorita,
Pitusas,
Diversión,
Naranjú,
Swift
}
public enum ETipoProducto
{
Jugo,
Harina,
Gaseosa,
Galletita,
Todos
}
#endregion
#region Propiedades
/// <summary>
/// retorna el costo de produccion de un producto especifico
/// </summary>
public abstract float CalcularCostoDeProduccion{get;}
/// <summary>
/// retorna o inserta un tipo valor Emarca
/// </summary>
public EMarcaProducto Marca
{
get { return this._marca; }
set { this._marca = value; }
}
/// <summary>
/// retorna o inserta un precio
/// </summary>
public float Precio
{
get { return this._precio; }
set { this._precio = value; }
}
/// <summary>
/// retorna o inserta un codigo de barra
/// </summary>
public int CodigoDeBarra
{
get { return this._codigoBarra; }
set { this._codigoBarra = value; }
}
#endregion
#region Constructor
public Producto(int codigoDeBarra, EMarcaProducto marca, float precio)
{
this._codigoBarra = codigoDeBarra;
this._marca = marca;
this._precio = precio;
}
public Producto()
{
}
#endregion
#region Metodos
/// <summary>
/// retorna la cadena de texto especificada
/// </summary>
/// <returns></returns>
public virtual string Consumir()
{
return "Parte de una mezcla";
}
/// <summary>
/// compara si 2 objetos son del mismo tipo
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
return (obj.GetType() == this.GetType());
}
/// <summary>
/// retorna una cadena con todos los datos del producto
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
private static string MostrarProducto(Producto p)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("\nMARCA : "+ p._marca.ToString());
sb.AppendLine("CODIGO DE BARRAS : "+ p._codigoBarra.ToString());
sb.AppendLine("PRECIO : " +p._precio.ToString());
return sb.ToString();
}
#endregion
#region Sobrecargas
/// <summary>
/// Sobrecarga del operador explicito (int) que retorna el codigo de barra del producto
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
public static explicit operator int(Producto p)
{
return p._codigoBarra;
}
/// <summary>
/// sobrecarga del operador string que muestra todos los datos de un producto
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
public static implicit operator string(Producto p)
{
return Producto.MostrarProducto(p);
}
/// <summary>
/// Compara 2 productos y devuelve true si son del mismo tipo y compraten la misma marca y patente
/// </summary>
/// <param name="ProdUno"></param>
/// <param name="ProdDos"></param>
/// <returns></returns>
public static bool operator ==(Producto ProdUno, Producto ProdDos)
{
bool retorno=false;
if (!(ProdUno.Equals(ProdDos)) && ((int)ProdUno == (int)ProdDos && ProdUno._marca==ProdDos._marca))
{
retorno = true;
}
else if ((int)ProdUno == (int)ProdDos && ProdUno._marca == ProdDos._marca)
{
retorno = true;
}
return retorno;
}
/// <summary>
/// Compara 2 productos y devuelve False si NO son del mismo tipo,
/// sin son del mismo tipo,retorna false sino coparten marca y patente
/// </summary>
/// <param name="ProdUno"></param>
/// <param name="ProdDos"></param>
/// <returns></returns>
public static bool operator !=(Producto ProdUno, Producto ProdDos)
{
return !(ProdUno == ProdDos);
}
/// <summary>
/// compara si el enumerado marca indicado coincide con el del algun
/// producto ya ingresado en ese caso retorna true.
/// </summary>
/// <param name="ProdUno"></param>
/// <param name="marca"></param>
/// <returns></returns>
public static bool operator ==(Producto ProdUno, EMarcaProducto marca)
{
bool retorno = false;
if (ProdUno._marca == marca)
retorno = true;
return retorno;
}
/// <summary>
/// compara si el enumerado marca indicado coincide con el del algun
/// producto ya ingresado,sino coincide retorna False.
/// </summary>
/// <param name="ProdUno"></param>
/// <param name="marca"></param>
/// <returns></returns>
public static bool operator !=(Producto ProdUno, EMarcaProducto marca)
{
return !(ProdUno == marca);
}
#endregion
}
}
<file_sep>/Pereira.Daniel.2D.TP3/TestUnitario/ValorNoNulo.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Excepciones;
using EntidadesInstanciables;
using EntidadesAbstractas;
namespace Utest
{
[TestClass]
public class ValorNoNulo
{
[TestMethod]
[ExpectedException(typeof(NullReferenceException))]
public void TestNull()
{
// se verifica que lanze la excepcion cuando el apellido sea incorrecto
int id = 45;
string nombre = "Daniel";
string apellido = "Pereira9999";
string dni = "456888";
Alumno.ENacionalidad nacionalidad = Alumno.ENacionalidad.Argentino;
Gimnasio.EClases claseQueToma = Gimnasio.EClases.Yoga;
Alumno alu1 = new Alumno(id, nombre, apellido, dni, nacionalidad, claseQueToma);
}
}
}
<file_sep>/Tp1-Lab II/Tp1-Lab II/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.Threading.Tasks;
using System.Windows.Forms;
namespace Tp1_Lab_II
{
public partial class Calculadora : Form
{
private string _numero1 = "";
private string _numero2 = "";
private double _resultado;
public Calculadora()
{
InitializeComponent();
}
private void txtNumero1_TextChanged(object sender, EventArgs e)
{
_numero1 = txtNumero1.Text;
}
private void txtNumero2_TextChanged(object sender, EventArgs e)
{
_numero2 = txtNumero2.Text;
}
private void txtNumero1_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsNumber(e.KeyChar))
e.Handled = false;
else if (char.IsControl(e.KeyChar))
e.Handled = false;
else if (char.IsSeparator(e.KeyChar))
e.Handled = false;
else
e.Handled = true;
}
private void txtNumero2_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsNumber(e.KeyChar))
e.Handled = false;
else if (char.IsControl(e.KeyChar))
e.Handled = false;
else if (char.IsSeparator(e.KeyChar))
e.Handled = false;
else
e.Handled = true;
}
private void btnLimpiar_Click(object sender, EventArgs e)
{
txtNumero1.Clear();
txtNumero2.Clear();
lblResultado.Text = "00";
cmbOperacion.Text = "";
}
private void btnOperar_Click(object sender, EventArgs e)
{
Numero numeroA = new Numero(_numero1);
Numero numeroB = new Numero(_numero2);
string aux = "0";
string operador = cmbOperacion.Text;
operador = Calculadora2.ValidarOperador(operador);
_resultado = Calculadora2.Operar(numeroA, numeroB, operador);
if (_resultado == 0)
{
_resultado.ToString();
lblResultado.Text = aux + _resultado;
}
else
lblResultado.Text = _resultado.ToString();
}
}
}
<file_sep>/Pereira.Daniel.2D.TP4/Navegador TP-4 - AlumnoV2/Navegador/frmHistorial.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;
using Archivos;
namespace Navegador
{
public partial class frmHistorial : Form
{
public const string ARCHIVO_HISTORIAL = "historico.dat";
public frmHistorial()
{
InitializeComponent();
}
private void frmHistorial_Load(object sender, EventArgs e)
{
List<string> historial;
Texto archivos = new Texto(frmHistorial.ARCHIVO_HISTORIAL);
((IArchivo<string>)archivos).leer(out historial);
foreach (string link in historial)
{//agregamos las cadenas ala lista del listBox
this.lstHistorial.Items.Add(link);
}
}
}
}
<file_sep>/Pereira.Daniel.2D.TP3/Excepciones/AlumnoRepetidoException.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Excepciones
{
public class AlumnoRepetidoException : Exception
{
private string _mensajeBase = "Alumno Repetido";
public string Message
{
get { return this._mensajeBase; }
}
public AlumnoRepetidoException()
: base()
{
}
}
}
<file_sep>/RPP/Pereira.Daniel.2d/Entidades/Galletita.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace Entidades
{
[Serializable]
[XmlInclude(typeof(Galletita))]
public class Galletita : Producto
{
#region Atributos
protected float _peso;
protected static bool DeConsumo;
#endregion
#region Propiedades
/// <summary>
/// al precio final le calcula su 33%
/// </summary>
public override float CalcularCostoDeProduccion
{
get { return base._precio * 0.33f; }
}
/// <summary>
/// inserta o retorna el peso galletita
/// </summary>
public float Peso
{ get; set; }
#endregion
#region Constructores
public Galletita(int codigoDeBarra,float precio,EMarcaProducto marca,float peso):base(codigoDeBarra,marca,precio)
{
this._peso = peso;
}
static Galletita()
{
Galletita.DeConsumo = true;
}
public Galletita()
{
}
#endregion
#region Metodos
/// <summary>
/// retorna una cadena de texto con todos los datos de una galletita
/// especifica
/// </summary>
/// <param name="g"></param>
/// <returns></returns>
private string MostrarGalletita(Galletita g)
{
return this + "PESO :" + g._peso.ToString();
}
/// <summary>
/// muestra todos los datos de la de la galletita en la instancia
/// actual
/// </summary>
/// <returns></returns>
public string ToString()
{
return MostrarGalletita(this);
}
/// <summary>
/// retorna una cadena de texto especifica
/// </summary>
/// <returns></returns>
public override string Consumir()
{
return "Comestible";
}
#endregion
}
}
<file_sep>/Pereira.Daniel.2D.TP4/Navegador TP-4 - AlumnoV2/Hilo/Descargador.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net; // Avisar del espacio de nombre
using System.ComponentModel;
using System.Reflection;
namespace Hilo
{
public class Descargador
{
private string html;
private Uri direccion;
/// <summary>
/// Delegado que recibe metodos que reciban un entero y retornen void
/// </summary>
/// <param name="progreso"></param>
public delegate void EvProgreso(int progreso);
/// <summary>
/// Delegado que recibe metodos que reciban un string y retornen void
/// </summary>
/// <param name="html"></param>
public delegate void EvFinDes(string html);
/// <summary>
/// Evento del tipo delegado EvProgreso que manejara el progreso de la descarga
/// </summary>
public event EvProgreso EvenProg;
/// <summary>
/// Evento del tipo delegado EvFinDes que manejara el fin de la descarga
/// </summary>
public event EvFinDes EvenFinDes;
public Descargador(Uri direccion)
{
this.html = "";
this.direccion = direccion;
}
public void IniciarDescarga()
{
try
{
WebClient cliente = new WebClient();
cliente.DownloadProgressChanged += WebClientDownloadProgressChanged;
cliente.DownloadStringCompleted += WebClientDownloadCompleted;
cliente.DownloadStringAsync(direccion);
}
catch (Exception e)
{
throw e;
}
}
private void WebClientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
EvenProg(e.ProgressPercentage);
}
private void WebClientDownloadCompleted(object sender, DownloadStringCompletedEventArgs e)
{
try
{
html = e.Result;
EvenFinDes(html);
}
catch (TargetInvocationException)
{
}
}
}
}
<file_sep>/RPP/Pereira.Daniel.2d/Entidades/Harina.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.IO;
namespace Entidades
{
[Serializable]
[XmlInclude(typeof(Harina))]
public class Harina : Producto
{
#region Atributos
protected ETipoHarina _tipo;
protected static bool DeConsumo;
#endregion
public enum ETipoHarina
{
Integral,
CuatroCeros
}
#region Propiedades
/// <summary>
/// al precio final le calcula su 60%
/// </summary>
public override float CalcularCostoDeProduccion
{
get { return base._precio * 0.60f; }
}
/// <summary>
/// inserta o retorna un valor de tipo ETipoHarina
/// </summary>
public ETipoHarina Tipo
{ get; set; }
#endregion
#region Constructores
public Harina()
{
}
public Harina(int codigoDeBarra,float precio,EMarcaProducto marca,ETipoHarina tipo):base(codigoDeBarra,marca,precio)
{
this._tipo = tipo;
}
static Harina()
{
Harina.DeConsumo = false;
}
#endregion
#region Metodos
/// <summary>
/// retorna una cadena de texto con toda la informacion de una Harina
/// </summary>
/// <returns></returns>
private string MostrarHarina()
{
return this + "TIPO : " + this._tipo.ToString();
}
/// <summary>
/// muestra todos los datos de una Harina
/// </summary>
/// <returns></returns>
public string ToString()
{
return MostrarHarina();
}
#endregion
}
}
<file_sep>/Tp1-Lab II/Tp1-Lab II/Numero.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tp1_Lab_II
{
class Numero
{
private double _numero;
/// <summary>
/// Inicializa el atributo _numero en cero
/// </summary>
public Numero()
{
this._numero = 0;
}
/// <summary>
/// Valida e inicializa el atributo _numero con el valor que se le pase como
/// parametro
/// </summary>
/// <param name="numero"></param>
public Numero(string numero): this()
{
SetNumero(numero);
}
/// <summary>
/// inicializa el atributo _numero con el valor que se le pasa
/// como parametro
/// </summary>
/// <param name="numero"></param>
public Numero(double numero)
{
this._numero = numero;
}
/// <summary>
/// Valida un string,si lo puede convertir a numero
/// lo retorna
/// </summary>
/// <param name="nro"></param>
/// <returns>0 si no pudo convertir,un double si pudo</returns>
private static double ValidarNumero(string nro)
{
double Num;
double retorno = 0;
bool retor;
retor = double.TryParse(nro, out Num);
if (retor)
retorno = Num;
return retorno;
}
/// <summary>
/// Valida un string,si se pueda convertir a numero
/// lo asigna en el atributo _numero
/// </summary>
/// <param name="numero"></param>
private void SetNumero(string numero)
{
double retorno;
retorno = Numero.ValidarNumero(numero);
if (retorno != 0)
this._numero = retorno;
}
/// <summary>
/// Retorna el valor que tiene en el momento la propiedad _numero
/// </summary>
/// <returns></returns>
public double GetNumero()
{
return this._numero;
}
}
}
<file_sep>/Pereira.Daniel.2D.TP3/Excepciones/ArchivosException.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Excepciones
{
public class ArchivosException : Exception
{
private string _message = "A ocurrido un error con el archivo solicitado";
public ArchivosException(Exception innerException):base(innerException.Message,innerException)
{
}
public string Message
{
get { return this._message +"\n"+ InnerException.Message ; }
}
}
}
<file_sep>/Pereira.Daniel.2D.TP3/Excepciones/NacionalidadInvalidaException.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Excepciones
{
public class NacionalidadInvalidaException : Exception
{
private string _mensajeBase = "La nacionalidad no se condice con el DNI";
public string Message
{
get { return this._mensajeBase; }
}
public NacionalidadInvalidaException()
: base()
{ }
public NacionalidadInvalidaException(string message)
: base(message)
{
this._mensajeBase = message;
}
}
}
<file_sep>/Tp1-Lab II/Tp1-Lab II/Calculadora.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tp1_Lab_II
{
class Calculadora2
{
/// <summary>
/// Toma 2 valores,un operador y calcula la operacion que corresponda
/// </summary>
/// <param name="numero1"></param>
/// <param name="numero2"></param>
/// <param name="operador"></param>
/// <returns></returns>
public static double Operar(Numero numero1, Numero numero2, string operador)
{
double num1 = numero1.GetNumero();
double num2 = numero2.GetNumero();
double retorno = 0;
switch (operador)
{
case "+":
retorno = num1 + num2;
break;
case "-":
retorno = num1 - num2;
break;
case "*":
retorno = num1 * num2;
break;
case "/":
if (num2 != 0)
retorno = num1 / num2;
else
retorno = 00;
break;
}
return retorno;
}
/// <summary>
/// Recibe un string y valida que este comprendido en ciertos parametros
/// </summary>
/// <param name="operador"></param>
/// <returns></returns>
public static string ValidarOperador(string operador)
{
string retorno = "+";
if (operador == "+" || operador == "-" || operador == "*" || operador == "/")
retorno = operador;
return retorno;
}
}
}
<file_sep>/RPP/Pereira.Daniel.2d/Entidades/Jugo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace Entidades
{
[Serializable]
[XmlInclude(typeof(Jugo))]
public class Jugo : Producto
{
#region Atributos
protected ESaborJugo _sabor;
protected static bool DeConsumo;
#endregion
public enum ESaborJugo
{
Pasable,
Asqueroso
}
#region Propiedades
/// <summary>
/// al precio final le calcula su 40%
/// </summary>
public override float CalcularCostoDeProduccion
{
get { return base._precio * 0.40f; }
}
/// <summary>
/// inserta o retorna un valor de tipo EsaborJugo
/// </summary>
public ESaborJugo Sabor
{ get; set; }
#endregion
#region Constructores
public Jugo(int codigoDeBarra,float precio,EMarcaProducto marca,ESaborJugo sabor):base(codigoDeBarra,marca,precio)
{
this._sabor = sabor;
}
static Jugo()
{
Jugo.DeConsumo = true;
}
public Jugo()
{
}
#endregion
#region Metodos
/// <summary>
/// retorna una cadena de texto con toda la informacion de un Jugo
/// </summary>
/// <returns></returns>
private string MostrarJugo()
{
return this + "SABOR : " + this._sabor.ToString();
}
/// <summary>
/// muestra todos los datos de un jugo
/// </summary>
/// <returns></returns>
public string ToString()
{
return MostrarJugo();
}
/// <summary>
/// retorna una cadena de texto especifica
/// </summary>
/// <returns></returns>
public override string Consumir()
{
return "Bebible";
}
#endregion
}
}
<file_sep>/Pereira.Daniel.2D.TP3/EntidadesInstanciables/Jornada.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excepciones;
using Archivos;
namespace EntidadesInstanciables
{
public class Jornada
{
#region Atributos
private List<Alumno> _alumnos;
private Gimnasio.EClases _clases;
private Instructor Instructor;
#endregion
#region Constructores
private Jornada()
{
this._alumnos = new List<Alumno>();
}
public Jornada(Gimnasio.EClases clase, Instructor instructor)
: this()
{
this._clases = clase;
this.VerificarInstructor(instructor);
}
#endregion
#region Propiedades
public List<Alumno> ListaAlumnos
{
get { return this._alumnos; }
set { this._alumnos = value; }
}
public Gimnasio.EClases Clase
{
get { return this._clases; }
set { this._clases = value; }
}
public Instructor InstructorClase
{
get { return this.Instructor; }
set { this.Instructor = value; }
}
#endregion
#region Metodos
/// <summary>
/// Verifica que un Instructor pueda ejercer la clase de una Jornada especifica
/// </summary>
/// <param name="inst"></param>
/// <returns></returns>
private void VerificarInstructor(Instructor inst)
{
foreach (Gimnasio.EClases clas in inst.ListaClases)
{
if (this._clases == clas)
this.Instructor = inst;
}
}
/// <summary>
/// Retorna una cadena de texto con toda la informacion de la jornada
/// </summary>
/// <returns></returns>
public override string ToString()
{
string retorno = "";
retorno += "CLASE DE " + this._clases.ToString() + " POR " + this.Instructor.ToString() + "\n\nALUMNOS :\n";
foreach (Alumno a in this._alumnos)
retorno += a.ToString();
return retorno += "\n<----------------------------------------------------------->\n\n";
}
/// <summary>
/// Guarda los datos en un archivo con formato txt
/// </summary>
/// <param name="jor"></param>
/// <returns></returns>
public static bool Guardar(Jornada jor)
{
Texto archivo = new Texto();
return ((IArchivo<string>)archivo).Guardar("JORNADA.txt", jor.ToString());
}
/// <summary>
/// Lee los datos desde un archivo con formato txt
/// </summary>
/// <returns></returns>
public static bool leer()
{
Texto archivo = new Texto();
string dato = "";
bool retorno = ((IArchivo<string>)archivo).Leer("JORNADA.txt", out dato);
Console.WriteLine(dato);
return retorno;
}
#endregion
#region Sobrecargas
/// <summary>
/// Verifica si un alumno esta en una jornada
/// </summary>
/// <param name="jor"></param>
/// <param name="alum"></param>
/// <returns></returns>
public static bool operator ==(Jornada jor, Alumno alum)
{
bool retorno = false;
for (int i = 0; i < jor._alumnos.Count; i++)
{
if (alum == jor._alumnos[i])
retorno = true;
}
return retorno;
}
/// <summary>
/// Verifica si un alumno No esta en una jornada
/// </summary>
/// <param name="jor"></param>
/// <param name="alum"></param>
/// <returns></returns>
public static bool operator !=(Jornada jor, Alumno alum)
{
return !(jor == alum);
}
/// <summary>
/// Agrega un alumno a la jornada verificando antes que ya no se encuentre en ella,
/// que se halla anotado en la misma clase que realiza la jornada y que su estado sea distinto
/// de deudor
/// </summary>
/// <param name="jor"></param>
/// <param name="alum"></param>
/// <returns></returns>
public static Jornada operator +(Jornada jor, Alumno alum)
{
if (jor != alum && alum.ClaseQueToma == jor._clases && alum.EstadoDeCuenta != Alumno.EEstadoCuenta.Deudor)
jor._alumnos.Add(alum);
return jor;
}
#endregion
}
}
<file_sep>/Pereira.Daniel.2D.TP4/Navegador TP-4 - AlumnoV2/Archivos/Texto.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Archivos
{
public class Texto : IArchivo<string>
{
private string _archivo;
public Texto(string archivo)
{
this._archivo = archivo;
}
bool IArchivo<string>.guardar(string datos)
{
bool retorno = true;
try
{
FileStream stream = new FileStream(_archivo, FileMode.Append, FileAccess.Write);
StreamWriter escribir = new StreamWriter(stream);
escribir.WriteLine(datos);
escribir.Close();
}
catch (Exception)
{
retorno = false;
}
return retorno;
}
bool IArchivo<string>.leer(out List<string> datos)
{
bool retorno = true;
datos = new List<string>();
try
{
FileStream stream = new FileStream(_archivo, FileMode.Open, FileAccess.Read);
TextReader lector = new StreamReader(stream);
string totalTexto = lector.ReadToEnd();
string[] partes = totalTexto.Split(new char[] { '\n' });
foreach (string item in partes)
{
datos.Add(item);
}
lector.Close();
}
catch (Exception)
{
retorno = false;
}
return retorno;
}
}
}
<file_sep>/Pereira.Daniel.2D.TP3/EntidadesInstanciables/Alumno.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EntidadesAbstractas;
namespace EntidadesInstanciables
{
public sealed class Alumno : PersonaGimnasio
{
#region Atributos
private Gimnasio.EClases _claseQueToma;
private EEstadoCuenta _estadoCuenta;
#endregion
#region Enumerados
public enum EEstadoCuenta
{
Ninguno,
AlDia,
MesPrueba,
Deudor
}
#endregion
#region Constructores
public Alumno(int id,string nombre, string apellido, string dni, ENacionalidad nacionalidad,Gimnasio.EClases claseQueToma)
: base(id,nombre, apellido, dni, nacionalidad)
{
this._claseQueToma = claseQueToma;
}
public Alumno(int id,string nombre, string apellido, string dni, ENacionalidad nacionalidad, Gimnasio.EClases claseQueToma, EEstadoCuenta estadoCuenta)
: this(id,nombre, apellido, dni, nacionalidad, claseQueToma)
{
this._estadoCuenta = estadoCuenta;
}
public Alumno()
{ }
#endregion
#region Propiedades
public Gimnasio.EClases ClaseQueToma
{
get { return this._claseQueToma; }
}
public EEstadoCuenta EstadoDeCuenta
{
get { return this._estadoCuenta; }
}
#endregion
#region Sobrecargas
/// <summary>
/// Verifica que el estado de un alumno no sea deudor y que tome una clase especifica
/// </summary>
/// <param name="a"></param>
/// <param name="clase"></param>
/// <returns></returns>
public static bool operator ==(Alumno a, Gimnasio.EClases clase)
{
bool retorno = false;
if (a._estadoCuenta != EEstadoCuenta.Deudor && a._claseQueToma == clase)
retorno = true;
return retorno;
}
/// <summary>
/// comprueba si un alumno no toma una clase especifica
/// </summary>
/// <param name="a"></param>
/// <param name="clase"></param>
/// <returns></returns>
public static bool operator !=(Alumno a, Gimnasio.EClases clase)
{
bool retorno = false;
if (a._claseQueToma != clase)
retorno = true;
return retorno;
}
#endregion
#region Metodos
/// <summary>
/// retorna un string especificando la clase que toma el alumno
/// </summary>
/// <returns></returns>
protected override string ParticiparEnClase()
{
string retorno = "";
try
{
retorno = "\nTOMA CLASES DE " + this._claseQueToma.ToString()+"\n";
}
catch(NullReferenceException e)
{
Console.WriteLine(e.Message);
}
return retorno;
}
/// <summary>
/// retorna un string con todos los datos del alumno
/// </summary>
/// <returns></returns>
protected override string MostrarDatos()
{
string retorno = "";
try
{
retorno = "\n" + base.MostrarDatos() + "\n\nESTADO DE CUENTA :" + this._estadoCuenta.ToString() + ParticiparEnClase();
}
catch (NullReferenceException e)
{
Console.WriteLine(e.Message);
}
return retorno;
}
/// <summary>
/// Retorna una cadena de texto con todos los datos del alumno
/// </summary>
/// <returns></returns>
public override string ToString()
{
return MostrarDatos();
}
#endregion
}
}
<file_sep>/Pereira.Daniel.2D.TP3/TestUnitario/IdValido.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Excepciones;
using EntidadesInstanciables;
using EntidadesAbstractas;
namespace Utest
{
[TestClass]
public class IdValido
{
[TestMethod]
[ExpectedException(typeof(FormatException))]
public void TestID()
{
// se verifica que lanze la excepcion cuando el ID no este entre los
//limites minimo y maximo
int id = 4565; // maximo 2000
string nombre = "Jorge";
string apellido = "Pe";
string dni = "456655";
Alumno.ENacionalidad nacionalidad = Alumno.ENacionalidad.Argentino;
Gimnasio.EClases claseQueToma = Gimnasio.EClases.Yoga;
Alumno alu1 = new Alumno(id, nombre, apellido, dni, nacionalidad, claseQueToma);
}
}
}
<file_sep>/Pereira.Daniel.2D.TP4/Navegador TP-4 - AlumnoV2/Archivos/IArchivo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Archivos
{
public interface IArchivo<T>
{
/// <summary>
/// guarda los datos en un archivo con un formato especifico
/// </summary>
/// <param name="datos"></param>
/// <returns></returns>
bool guardar(T datos);
/// <summary>
/// lee los datos desde un archivo con formato especifico y los retorna en una
/// lista del tipo especificado
/// </summary>
/// <param name="datos"></param>
/// <returns></returns>
bool leer(out List<T> datos);
}
}
<file_sep>/RPP/Pereira.Daniel.2d/Entidades/Serializador.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace Entidades
{
public class Serializador
{
/// <summary>
/// Serializa en un archivo xml los datos del estante pasado por parametro
/// en una ruta especifica
/// </summary>
/// <param name="e"></param>
/// <param name="ruta"></param>
public static void SerializarEstante(Estante e,string ruta)
{
XmlSerializer xml;
xml = new XmlSerializer(typeof(Estante));
Stream archivo = new FileStream(ruta,FileMode.OpenOrCreate);
xml.Serialize(archivo,e);
archivo.Close();
}
/// <summary>
/// Deserializa en un objeto de tipo estante los datos del archivo xml pasado por parametro
/// </summary>
/// <param name="ruta"></param>
public static Estante DeserializarEstante(string ruta)
{
XmlSerializer xml;
xml = new XmlSerializer(typeof(Estante));
FileStream Lector = File.OpenRead(ruta);
Estante e = (Estante)xml.Deserialize(Lector);
Lector.Close();
return e;
}
}
}
<file_sep>/RPP/Pereira.Daniel.2d/Entidades/Estante.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace Entidades
{
[Serializable]
[XmlInclude(typeof(Harina))]
[XmlInclude(typeof(Jugo))]
[XmlInclude(typeof(Galletita))]
[XmlInclude(typeof(Gaseosa))]
public class Estante
{
#region Atributos
protected sbyte _capacidad;
protected List<Producto> _productos;
protected int contador;
#endregion
#region propiedades
/// <summary>
/// retorna la suma de los precios de todos los productos del estante especifico
/// </summary>
public float ValorEstanteTotal
{
get { return GetValorEstante(); }
}
/// <summary>
/// Retorna o inserta un una capacidad al o del estante
/// </summary>
public sbyte Capacidad
{
get { return this._capacidad; }
set { this._capacidad = value; }
}
/// <summary>
/// retorna la lista con todos los productos
/// </summary>
public List<Producto> Productos
{
get { return this._productos; }
set { }
}
#endregion
#region Constructores
private Estante()
{
this._productos = new List<Producto>();
}
public Estante(sbyte capacidad):this()
{
this._capacidad = capacidad;
this.contador = capacidad;
}
#endregion
#region Metodos
/// <summary>
/// retorna la lista con todos los productos
/// </summary>
/// <returns></returns>
public List<Producto> GetProductos()
{
return this._productos;
}
/// <summary>
/// retorna la suma de todos los precios de un estante
/// </summary>
/// <returns></returns>
private float GetValorEstante()
{
float valor=0;
for (int i = 0; i < this._productos.Count; i++)
{
valor += _productos[i].Precio;
}
return valor;
}
/// <summary>
/// retorna la suma de todos los precios de un producto especifico
/// de un estante
/// </summary>
/// <param name="tipo"></param>
/// <returns></returns>
public float GetValorEstante(Producto.ETipoProducto tipo)
{
float valor = 0;
for (int i = 0; i < this._productos.Count; i++)
{
switch (tipo)
{
case Producto.ETipoProducto.Jugo:
if (this._productos[i] is Jugo)
valor += this._productos[i].Precio;
break;
case Producto.ETipoProducto.Harina:
if (this._productos[i] is Harina)
valor += this._productos[i].Precio;
break;
case Producto.ETipoProducto.Gaseosa:
if (this._productos[i] is Gaseosa)
valor += this._productos[i].Precio;
break;
case Producto.ETipoProducto.Galletita:
if (this._productos[i] is Galletita)
valor += this._productos[i].Precio;
break;
default:
GetValorEstante();
break;
}
}
return valor;
}
/// <summary>
/// muestra todos los datos del estante incluidos los de todos
/// sus productos
/// </summary>
/// <param name="e"></param>
/// <returns></returns>
public static string MostrarEstante(Estante e)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("CAPACIDAD : {0}",e._capacidad.ToString());
for (int i = 0; i < e._productos.Count; i++)
{
if(e._productos[i] is Jugo)
sb.AppendLine(((Jugo)e._productos[i]).ToString());
if(e._productos[i] is Harina)
sb.AppendLine(((Harina)e._productos[i]).ToString());
if(e._productos[i] is Gaseosa)
sb.AppendLine(((Gaseosa)e._productos[i]).ToString());
if(e._productos[i] is Galletita)
sb.AppendLine(((Galletita)e._productos[i]).ToString());
}
return sb.ToString();
}
#endregion
#region sobrecargas
/// <summary>
/// compara si un producto ya se encuentra en la lista,en ese caso retorna true.
/// </summary>
/// <param name="e"></param>
/// <param name="prod"></param>
/// <returns></returns>
public static bool operator ==(Estante e, Producto prod)
{
bool retorno=false;
for (int i = 0; i < e._productos.Count; i++)
{
if (e._productos[i] == prod)
retorno = true;
}
return retorno;
}
/// <summary>
/// compara si un producto no se encuentra en la lista,en ese caso retorna false.
/// </summary>
/// <param name="e"></param>
/// <param name="prod"></param>
/// <returns></returns>
public static bool operator !=(Estante e, Producto prod)
{
return !(e == prod);
}
/// <summary>
/// inserta un producto ala lista siempre y cuando la capacidad lo permita
/// y el producto no se encuentre ya ingresado en la lista
/// </summary>
/// <param name="e"></param>
/// <param name="prod"></param>
/// <returns></returns>
public static bool operator +(Estante e, Producto prod)
{
bool retorno = false;
if (e.contador >= 1 && e != prod)
{
e._productos.Add(prod);
e.contador--;
retorno = true;
}
return retorno;
}
/// <summary>
/// Elimina un producto especifico de la lista
/// </summary>
/// <param name="e"></param>
/// <param name="prod"></param>
/// <returns></returns>
public static Estante operator -(Estante e, Producto prod)
{
for (int i = 0; i < e._productos.Count; i++)
{
if (prod is Galletita && e._productos[i] is Galletita)
{
e._productos.Remove(e._productos[i]);
i--;
}
else if (prod is Gaseosa && e._productos[i] is Gaseosa)
{
e._productos.Remove(e._productos[i]);
i--;
}
else if (prod is Jugo && e._productos[i] is Jugo)
{
e._productos.Remove(e._productos[i]);
i--;
}
else if (prod is Harina && e._productos[i] is Harina)
{
e._productos.Remove(e._productos[i]);
i--;
}
}
return e;
}
/// <summary>
/// elimina todos los preoductos de la lista que coincidan con el
/// enumerado
/// </summary>
/// <param name="e"></param>
/// <param name="tipo"></param>
/// <returns></returns>
public static Estante operator -(Estante e, Producto.ETipoProducto tipo)
{
Estante aux = e;
for (int i = 0; i < e._productos.Count; i++)
{
switch (tipo)
{
case Producto.ETipoProducto.Jugo:
if (aux._productos[i] is Jugo)
aux -=aux._productos[i];
break;
case Producto.ETipoProducto.Harina:
if (aux._productos[i] is Harina)
aux -=aux._productos[i];
break;
case Producto.ETipoProducto.Gaseosa:
if (aux._productos[i] is Gaseosa)
aux -=aux._productos[i];
break;
case Producto.ETipoProducto.Galletita:
if (aux._productos[i] is Galletita)
aux -=aux._productos[i];
break;
default:
aux -= Producto.ETipoProducto.Galletita;
aux -= Producto.ETipoProducto.Gaseosa;
aux -= Producto.ETipoProducto.Harina;
aux -= Producto.ETipoProducto.Jugo;
break;
}
}
return aux;
}
#endregion
}
}
| 2cb73d44a73210dc6b88fd589989a9e7f72e1ea1 | [
"C#"
] | 29 | C# | daniel9898/Tp_Laboratorio_2 | 45524645592b8c9e459d09fb97adddbad19e0d77 | 899d98214c41be2d6d010695cd8cab7f17af0907 |
refs/heads/master | <file_sep>import React, {useContext} from 'react';
import {ThemeContext} from '../../App';
import './TaskDisplay.scss';
export default props => {
let {theme} = useContext(ThemeContext);
return (
<div className={`task-display ${theme}`}>
<section className='task'>
<p>{props.task.task}</p>
<svg xmlns="http://www.w3.org/2000/svg" onClick={() => props.deleteFn(props.task.id)} width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="gray" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="delete-icon">
<polyline points="3 6 5 6 21 6"></polyline>
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
<line x1="10" y1="11" x2="10" y2="17"></line><line x1="14" y1="11" x2="14" y2="17"></line>
</svg>
</section>
<div className='task-progress'>
<div className={`progress-option ${props.task.progress === 'Not Started' ? 'active-not-started' : 'not-active'}`} onClick={() => props.progressFn('Not Started', props.task.id)}>Not Started</div>
<div id='in-progress' className={`progress-option ${props.task.progress === 'In Progress' ? 'active-in-progress' : 'not-active'}`} onClick={() => props.progressFn('In Progress', props.task.id)}>In Progress</div>
<div className={`progress-option ${props.task.progress === 'Complete' ? 'active-complete' : 'not-active'}`} onClick={() => props.progressFn('Complete', props.task.id)}>Complete</div>
</div>
</div>
)
}<file_sep>import React, {useState, useEffect, useContext} from 'react';
import {Link} from 'react-router-dom';
import {UserContext} from '../../App';
import mainIcon from '../../assets/todo-list-v2.svg';
import './Header.scss';
export default props => {
let [nameInput, setNameInput] = useState(''),
[edit, setEdit] = useState(false);
let {username, changeUsername} = useContext(UserContext);
useEffect(() => {
if(!username){
setEdit(true);
} else {
setEdit(false);
}
}, [username])
const addUsername = () => {
changeUsername(nameInput)
setEdit(false);
}
return (
<header>
<section className='icon-flex'>
<img src={mainIcon} alt='To Do List' className='app-icon'/>
<p>Doist</p>
</section>
{edit
? (
<section className='username-flex'>
<input className='username-input' value={nameInput} placeholder='Add Username' onChange={e => setNameInput(e.target.value)}/>
<button className='username-btn' onClick={addUsername}>Add</button>
</section>
)
: (
<section className='username-flex'>
<p>Welcome, {username}</p>
<Link to='/settings' className='nav-links'>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="feather feather-settings">
<circle cx="12" cy="12" r="3"></circle>
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path>
</svg>
</Link>
</section>
)}
</header>
)
}<file_sep>import React, {useState, useEffect} from 'react';
import Header from './Components/Header/Header';
import routes from './routes';
import './App.scss';
export const ThemeContext = React.createContext(null);
export const UserContext = React.createContext(null);
function App() {
let [theme, setTheme] = useState(''),
[username, setUsername] = useState('');
useEffect(() => {
getStoredTheme();
getStoredUsername();
}, [])
const getStoredTheme = () => {
let userTheme = localStorage.getItem('theme');
if(!userTheme){
setTheme('light');
localStorage.setItem('theme', 'light');
} else {
setTheme(userTheme);
}
}
const getStoredUsername = () => {
let storedUsername = localStorage.getItem('username');
if(!storedUsername){
setUsername('')
localStorage.setItem('username', '');
} else {
setUsername(storedUsername)
}
}
const toggleTheme = () => {
if(theme === 'light'){
setTheme('dark');
localStorage.setItem('theme', 'dark');
} else if(theme === 'dark') {
setTheme('light');
localStorage.setItem('theme', 'light');
}
}
const changeUsername = (val) => {
setUsername(val);
localStorage.setItem('username', val);
}
return (
<ThemeContext.Provider value={{theme, toggleTheme}}>
<UserContext.Provider value={{username, changeUsername}}>
<div className={`App ${theme ? theme : null}`}>
<Header />
{routes}
</div>
</UserContext.Provider>
</ThemeContext.Provider>
);
}
export default App;<file_sep>import React from 'react';
import {Switch, Route} from 'react-router-dom';
import TaskDashboard from './Components/TaskDashboard/TaskDashboard';
import Settings from './Components/Settings/Settings';
export default (
<Switch>
<Route exact path='/' component={TaskDashboard}/>
<Route path='/settings' component={Settings}/>
</Switch>
)<file_sep># Welcome to Doist
Doist is a simple task management developer portfolio project. On this application, users are able to add a username, create tasks, manage tasks progress, and more. This project features the use of React, React Hooks (including useState, useEffect, and useContext), the React Context API, and Sass/SCSS. This project also features working with localStorage to store user tasks.
[Click here](https://doist-developer-project.netlify.app/#/) to view the live site.
 | 079408fefef1570d69e043634a2a8cf0db2fc796 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | mattcbodily/todo-list-v2 | a2bd78f3ecb05f69584f65a0649f6bc1ba7f7e5e | 7963eee839f3e5df65b0904961d28026613a02b8 |
refs/heads/master | <repo_name>GabrielMotaBLima/Numerical_Analysis<file_sep>/Polynomial Interpolation/Newton's Polynomial Method/README.md
# Newton's Polynomial Method
<file_sep>/Roots of Equations/Fixed-Point Iteration/Fixed-Point_Iteration.java
public class Function {
private double y, x, rho;
public Function(){
}
public Function(double x){
this.x=x;
//this.rho = -(2.0/3.0)*x*x*x + (4.0/3.0)*x*x;
//this.y = 2.0*x*x*x - 4.0*x*x + 3.0*x;
this.rho = Math.cos(x);
this.y = Math.cos(x) - x;
}
public static void main(String args[]) {
double a = 0.0;
double b = 1.0;
double p = 1.0e-8;
int count = 0;
double x=0;
Function Ma = new Function(a);
Function Mb = new Function(b);
System.out.println("#################################################################################");
System.out.println("################################## FIXED-POINT ##################################");
System.out.println("#################################################################################");
while( Math.abs((Ma.y))>p ){
Ma = new Function(a);
b = Ma.rho;
Mb = new Function(b);
if( Math.abs((Mb.y))>p || Math.abs((b-a))>p ){
x = b;
}
a = Mb.rho;
x = a;
count = count + 1 ;
System.out.println("it: "+count+" | a: "+a+" | b: "+b+" | E: "+ (b-a) +" | x: "+x+" | f(a): "+Ma.y+" | f(b): "+Mb.y+" ");
}
System.out.println("Raiz: "+x+" ");
}
}
<file_sep>/Linear Systems/Gauss Elimination Method With Pivoting/README.md
# Gauss Elimination Method With Pivoting
<file_sep>/Linear Systems/Cholesky Method/README.md
# Cholesky Method
<file_sep>/README.md
# Numerical Analysis
This repository is intended for Numerical Algorithms in some programming languages, made by me at college in Numerical Algorithms subject. The algorithms that will split up for now are:
- Linear Systems
- [Gauss Elimination Method](https://github.com/GabrielMotaBLima/Numerical_Analysis/tree/master/Linear%20Systems/Gauss%20Elimination%20Method)
- [Gauss Elimination Method With Pivoting](https://github.com/GabrielMotaBLima/Numerical_Analysis/tree/master/Linear%20Systems/Gauss%20Elimination%20Method%20With%20Pivoting)
- LU Decomposition Method
- [Cholesky Method](https://github.com/GabrielMotaBLima/Numerical_Analysis/tree/master/Linear%20Systems/Cholesky%20Method)
- Conjugate Gradient Method
- Polynomial Interpolation
- [Newton's Polynomial Method](https://github.com/GabrielMotaBLima/Numerical_Analysis/tree/master/Polynomial%20Interpolation/Newton's%20Polynomial%20Method)
- Lagrange's Polynomial Method
- Curves Adjustments
- Least Squares Method
- Numerical Integration
- Newton-Cotes Formulas
- Trapezium Rule
- Simpsons 1/3 Rule
- Simpsons 3/8 Rule
- Quadrature of Gauss-Legendre
- Roots of Equations
- [Bisection Method](https://github.com/GabrielMotaBLima/Numerical_Analysis/tree/master/Roots%20of%20Equations/Bisection%20Method)
- [Regula Falsi Method](https://github.com/GabrielMotaBLima/Numerical_Analysis/tree/master/Roots%20of%20Equations/Regula-Falsi%20Method)
- [Fixed-Point Iteration](https://github.com/GabrielMotaBLima/Numerical_Analysis/tree/master/Roots%20of%20Equations/Fixed-Point%20Iteration)
- [Pegasus Method](https://github.com/GabrielMotaBLima/Numerical_Analysis/tree/master/Roots%20of%20Equations/Pegasus%20Method)
- [Newton-Raphson Method](https://github.com/GabrielMotaBLima/Numerical_Analysis/tree/master/Roots%20of%20Equations/Newton-Raphson%20Method)
- [Illinois Method (extra)](https://github.com/GabrielMotaBLima/Numerical_Analysis/tree/master/Roots%20of%20Equations/Illinois%20Method)
- Ordinary Differential Equations
- Euler Method
- Euler Modified Method
- Runge-Kutta Method
- Runge-Kutta Method (2nd order)
- Dormand-Prince and Fehlberg Method
- Dormand-Prince Modified Method
| 978de9db68fe2c6e1c65edd3ce8e0c6f43fff2f5 | [
"Markdown",
"Java"
] | 5 | Markdown | GabrielMotaBLima/Numerical_Analysis | eb382983e1e39422c464ea32a0987deadc296934 | 6abd1d3e94d1a96a81cedb26ed6ea645b1ad6f79 |
refs/heads/master | <file_sep><?php
namespace app\models;
use Yii;
/**
* This is the model class for table "eventos".
*
* @property int $evento_codigo
* @property int $organizacion_codigo
* @property string $nombre
* @property int $Estado_codigo
* @property int $usuario_registro
* @property int $usuario_modificacion
* @property string $fecha_modificacion
* @property string $fecha_registro
*
* @property Estados $estadoCodigo
* @property Organizacion $organizacionCodigo
* @property IngresoEvento[] $ingresoEventos
* @property Invitados[] $invitados
* @property ItemsEvento[] $itemsEventos
* @property LogAccionesEvento[] $logAccionesEventos
* @property ProgramacionEvento[] $programacionEventos
* @property StaffEvento[] $staffEventos
*/
class Eventos extends \yii\db\ActiveRecord
{
public $cantidad;
public $estado_item;
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'eventos';
}
/**
* @return \yii\db\Connection the database connection used by this AR class.
*/
public static function getDb()
{
return Yii::$app->get('db_invitado');
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['evento_codigo', 'organizacion_codigo', 'nombre', 'Estado_codigo', 'usuario_registro', 'usuario_modificacion', 'fecha_modificacion', 'fecha_registro'], 'required'],
[['evento_codigo', 'organizacion_codigo', 'Estado_codigo', 'usuario_registro', 'usuario_modificacion'], 'integer'],
[['fecha_modificacion', 'fecha_registro'], 'safe'],
[['nombre'], 'string', 'max' => 255],
[['evento_codigo'], 'unique'],
/*[['Estado_codigo'], 'exist', 'skipOnError' => true, 'targetClass' => Estados::className(), 'targetAttribute' => ['Estado_codigo' => 'estado_codigo']],
[['organizacion_codigo'], 'exist', 'skipOnError' => true, 'targetClass' => Organizacion::className(), 'targetAttribute' => ['organizacion_codigo' => 'organizacion_codigo']],*/
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'evento_codigo' => 'Evento Codigo',
'organizacion_codigo' => 'Organizacion Codigo',
'nombre' => 'Nombre',
'Estado_codigo' => 'Estado Codigo',
'usuario_registro' => 'Usuario Registro',
'usuario_modificacion' => 'Usuario Modificacion',
'fecha_modificacion' => 'Fecha Modificacion',
'fecha_registro' => 'Fecha Registro',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getEstadoCodigo()
{
return $this->hasOne(Estados::className(), ['estado_codigo' => 'Estado_codigo']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getOrganizacionCodigo()
{
return $this->hasOne(Organizacion::className(), ['organizacion_codigo' => 'organizacion_codigo']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getIngresoEventos()
{
return $this->hasMany(IngresoEvento::className(), ['evento_codigo' => 'evento_codigo']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getInvitados()
{
return $this->hasMany(Invitados::className(), ['evento_codigo' => 'evento_codigo']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getItemsEventos()
{
return $this->hasMany(ItemsEvento::className(), ['evento_codigo' => 'evento_codigo']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getLogAccionesEventos()
{
return $this->hasMany(LogAccionesEvento::className(), ['evento_codigo' => 'evento_codigo']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getProgramacionEventos()
{
return $this->hasMany(ProgramacionEvento::className(), ['evento_codigo' => 'evento_codigo']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getStaffEventos()
{
return $this->hasMany(StaffEvento::className(), ['evento_codigo' => 'evento_codigo']);
}
}
<file_sep><?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\widgets\SwitchInput;
use kartik\select2\Select2;
use kartik\depdrop\DepDrop;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use kartik\widgets\TimePicker;
use kartik\date\DatePicker;
use yii\grid\GridView;
use yii\bootstrap\Modal;
//$this->registerJsFile('@web/js/eventoScript.js', ['depends' => [yii\web\JqueryAsset::className()]]);
/* @var $this yii\web\View */
/* @var $model app\models\Eventos */
/* @var $form yii\widgets\ActiveForm */
?>
<?php
$js = <<<JS
cargarDatatable();
JS;
$this->registerJs($js);
?>
<?= Html::input('hidden','table_items_data','', $options=['class'=>'form-control', 'id'=>'table_items_data']) ?>
<?= Html::input('hidden','item_url','', $options=['class'=>'form-control item_url', 'id'=>Url::to(['items-evento/get-items-evento','evento' => $model->evento_codigo])]) ?>
<div class="eventos-form">
<?php $form = ActiveForm::begin(['id'=>'eventos']); ?>
<div class="container">
<ul class="nav nav-tabs">
<li class="active"><a data-toggle="tab" href="#datos">Datos y Programación</a></li>
<li><a data-toggle="tab" href="#programacion">Programación</a></li>
<li><a data-toggle="tab" href="#invitados">Invitados</a></li>
<li><a data-toggle="tab" href="#staff">Staff</a></li>
</ul>
<div class="tab-content">
<div id="datos" class="tab-pane fade in active">
<div class="row justify-content-center">
<div class="col-12 col-md-6">
<?= $form->field($model, 'nombre')->textInput(['maxlength' => true])->label('Nombre') ?>
</div>
<div class="col-12 col-md-6">
<?=
$form->field($model, 'Estado_codigo')->widget(SwitchInput::classname([
'name' => 'Estado_codigo',
'pluginOptions' => [
'onText' => 'Si',
'offText' => 'No',
]
]))->label('Estado');
?>
</div>
<div class="col-12 col-md-6">
<label>Sede</label>
<?= Select2::widget([
'name'=>'sede',
'data' => ArrayHelper::map($model_sedes->getSedes(), "Codigo","Descripcion"),
'language' => 'es',
'options' =>[
'placeholder' => 'Seleccione ',
'id'=>'sede'
],
'pluginOptions' => [
'allowClear' => true,
]
]) ?>
</div>
<div class="col-12 col-md-6">
<label>Ubicación</label>
<?=
DepDrop::widget([
'name'=>'ubicacion_sede',
'options' => ['id'=>'ubicacion_sedes'],
'type' => DepDrop::TYPE_SELECT2,
'pluginOptions'=>[
'depends'=>['sede'],
'placeholder' => 'Select...',
'url' => Url::to(['sede-ubicacion/get-ubicacion'])
]
]);
?>
</div>
<div class="col-12" style="text-align:center;margin-top:20px">
<label>ÍTEMS DEL EVENTO</label>
<hr size="2" width="100%" style='margin-top:0px; margin-bottom: 20px;border: 0;border-top: 1px solid #172d44;'>
</div>
<div class="col-12">
<table id="table_items" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>Nombre</th>
<th>Cantidad</th>
<th>Stock</th>
<th>Estado</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<br>
</div>
<div class="col-12 col-md-4">
<label>Item</label>
<?= Select2::widget([
'name'=>'item_codigo',
'data' => ArrayHelper::map($model_itemsCatalogo->getItems(), "Codigo","Descripcion"),
'language' => 'es',
'options' =>[
'placeholder' => 'Seleccione ',
'id'=>'item_codigo'
],
'pluginOptions' => [
'allowClear' => true,
]
])
?>
</div>
<div class="col-12 col-md-4">
<?= $form->field($model, 'cantidad')->textInput() ?>
</div>
<div class="col-12 col-md-2">
<?=
$form->field($model, 'estado_item')->widget(SwitchInput::classname([
'name' => 'estado_item',
'pluginOptions' => [
'onText' => 'Si',
'offText' => 'No',
]
]))->label('Estado');
?>
</div>
<div class="col-12 col-md-2">
<br>
<?= Html::button('Agregar', array('onclick' => 'js:agregarItems()','class' => 'btn btn-primary'));?>
</div>
</div>
</div>
<div id="programacion" class="tab-pane fade">
<div class="row justify-content-center">
<div class="col-12 col-md-3">
<label>Fecha Inicial</label>
<?php
echo DatePicker::widget([
'name'=>'dateini',
'type' => DatePicker::TYPE_COMPONENT_PREPEND,
'removeButton' => false,
'pluginOptions' => [
'autoclose'=>true,
'todayBtn' => true,
'format' => 'dd/mm/yyyy',
],
'options'=>['autocomplete'=>'off']
]);
?>
</div>
<div class="col-12 col-md-3">
<label>Hora Inicio</label>
<?php
echo TimePicker::widget([
'name' => 'timeini',
'addon'=>'<i class="far fa-clock"></i>',
'addonOptions' => [
'asButton' => true,
]
]);
?>
</div>
<div class="col-12 col-md-3">
<label>Fecha Final</label>
<?php
echo DatePicker::widget([
'name'=>'dateini',
'type' => DatePicker::TYPE_COMPONENT_PREPEND,
'removeButton' => false,
'pluginOptions' => [
'autoclose'=>true,
'todayBtn' => true,
'format' => 'dd/mm/yyyy',
],
'options'=>['autocomplete'=>'off']
]);
?>
</div>
<div class="col-12 col-md-3">
<label>Hora Final</label>
<?php
echo TimePicker::widget([
'name' => 'timeini',
'bsVersion'=>'3.x',
'addon'=>'<i class="far fa-clock"></i>',
'addonOptions' => [
'asButton' => true,
]
]);
?>
</div>
</div>
</div>
<div id="invitados" class="tab-pane fade">
Staff
</div>
<div id="staff" class="tab-pane fade">
<h3>Menu 2</h3>
<p>Some content in menu 2.</p>
</div>
</div>
</div>
<!--
<?= $form->field($model, 'evento_codigo')->textInput() ?>
<?= $form->field($model, 'organizacion_codigo')->textInput() ?>
<?= $form->field($model, 'Estado_codigo')->textInput() ?>
<?= $form->field($model, 'usuario_registro')->textInput() ?>
<?= $form->field($model, 'usuario_modificacion')->textInput() ?>
<?= $form->field($model, 'fecha_modificacion')->textInput() ?>
<?= $form->field($model, 'fecha_registro')->textInput() ?>
-->
<br>
<div class="form-group" style="text-align: center">
<?= Html::submitButton('Aceptar', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<file_sep>
var items_obj = [];
function agregarItems(){
var item_codigo = $('#item_codigo').val();
var nombre_item = $( "#item_codigo option:selected" ).text()
var eventos_cantidad = $('#eventos-cantidad').val();
//var eventos_estado_item = $('#eventos-estado_item').is(":checked")
var array_datatable = [];
var estado = ($('#eventos-estado_item').is(":checked") == true)?'1':'0';
var encontrado = false;
items_obj.forEach( function(valor, indice, array) {
if(valor.item_codigo != '' && valor.item_codigo == $('#item_codigo').val()){
encontrado = true;
valor.item_codigo = $('#item_codigo').val();
valor.cantidad= $('#eventos-cantidad').val();
valor.estado_item = estado;
}
});
if(encontrado == false){
item = {
item_codigo : $('#item_codigo').val(),
nombre_item : nombre_item,
eventos_cantidad: $('#eventos-cantidad').val(),
eventos_estado_item : estado,
}
items_obj.push(item);
}
items_obj.forEach( function(valor, indice, array) {
var btn = (valor.item_codigo != '')?'<a class="btn-editar-item" id="btn-'+valor.item_codigo+'"><span class="glyphicon glyphicon-pencil" title="Editar"></span></a>':''
data_datatable = [
valor.nombre_item,
valor.eventos_cantidad,
valor.eventos_cantidad,
valor.eventos_estado_item,
btn
]
//print datatable
array_datatable.push(data_datatable);
});
$('#item_codigo').val('');
$('#eventos-cantidad').val('');
$('#table_items_data').val(JSON.stringify(items_obj));
$(document).ready(function() {
var table = $('#table_items').DataTable();
table.destroy();
$('#table_items').DataTable( {
'responsive': true,
"searching": false,
"lengthChange": false,
"ordering": false,
"lengthMenu": [ 4 ],
data: array_datatable,
columns: [
{ title: "Nombre" },
{ title: "Cantidad" },
{ title: "Stock" },
{ title: "Estado" },
{ title: "" },
]
});
} )
//$('#eventos-estado_item').val('');
}
function cargarDatatable(){
$.post($('.item_url').attr('id'), function( data ) {
data = [data.data];
items_obj = data;
var array_datatable = []
data.forEach( function(valor, indice, array) {
var btn = (valor.item_codigo != '')?'<a class="btn-editar-item" id="btn-'+valor.item_evento_codigo+'"><span class="glyphicon glyphicon-pencil" title="Editar"></span></a>':''
data_datatable = [
valor.nombre,
valor.cantidad,
valor.stock,
valor.estado,
btn
]
array_datatable.push(data_datatable);
});
var table = $('#table_items').DataTable();
table.destroy();
$('#table_items').DataTable( {
'responsive': true,
"searching": false,
"lengthChange": false,
"ordering": false,
"lengthMenu": [ 4 ],
data: array_datatable,
columns: [
{ title: "Nombre" },
{ title: "Cantidad" },
{ title: "Stock" },
{ title: "Estado" },
{ title: "" },
]
});
})
}<file_sep><?php
namespace app\models;
use Yii;
/**
* This is the model class for table "items_evento".
*
* @property int $item_evento_codigo
* @property int $evento_codigo
* @property int $item_codigo
* @property int $cantidad
* @property int $stock
* @property int $activo
* @property int $usuario_registro
* @property int $usuario_modificacion
* @property string $fecha_registro
* @property string $fecha_modificacion
*
* @property Eventos $eventoCodigo
* @property ItemsInvitado[] $itemsInvitados
*/
class ItemsEvento extends \yii\db\ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'items_evento';
}
/**
* @return \yii\db\Connection the database connection used by this AR class.
*/
public static function getDb()
{
return Yii::$app->get('db_invitado');
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['item_evento_codigo', 'evento_codigo', 'item_codigo', 'cantidad', 'stock', 'activo', 'usuario_registro', 'usuario_modificacion', 'fecha_registro', 'fecha_modificacion'], 'required'],
[['item_evento_codigo', 'evento_codigo', 'item_codigo', 'cantidad', 'stock', 'activo', 'usuario_registro', 'usuario_modificacion'], 'integer'],
[['fecha_registro', 'fecha_modificacion'], 'safe'],
[['item_evento_codigo'], 'unique'],
[['evento_codigo'], 'exist', 'skipOnError' => true, 'targetClass' => Eventos::className(), 'targetAttribute' => ['evento_codigo' => 'evento_codigo']],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'item_evento_codigo' => 'Item Evento Codigo',
'evento_codigo' => 'Evento Codigo',
'item_codigo' => 'Item Codigo',
'cantidad' => 'Cantidad',
'stock' => 'Stock',
'activo' => 'Activo',
'usuario_registro' => '<NAME>',
'usuario_modificacion' => '<NAME>',
'fecha_registro' => 'Fecha Registro',
'fecha_modificacion' => 'Fecha Modificacion',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getEventoCodigo()
{
return $this->hasOne(Eventos::className(), ['evento_codigo' => 'evento_codigo']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getItemsInvitados()
{
return $this->hasMany(ItemsInvitado::className(), ['items_evento_codigo' => 'item_evento_codigo']);
}
public function getItemsEvento($id){
$query = Yii::$app->db_invitado->createCommand("SELECT itev.item_evento_codigo,ic.item_codigo,ic.nombre+'|'+ic.marca+'|'+ic.modelo as nombre,ic.estado,itev.cantidad,itev.stock
FROM DB_Invitado.dbo.items_evento itev
left join DB_Invitado.dbo.eventos ev on ev.evento_codigo=itev.evento_codigo
left join DB_Invitado.dbo.items_catalogo ic on ic.item_codigo = itev.item_codigo
where ev.evento_codigo =".$id)->queryAll();
return $query;
}
}
| 4a03b5b85391a06c934177fc821787154bb7ebb6 | [
"JavaScript",
"PHP"
] | 4 | PHP | greinnyc/gi | ca5b3ec35ce789968f56d5477fc4116a3f38155a | 660504488c4e8161f556169401dbdf92851c835e |
refs/heads/master | <file_sep>all:
gcc -c game2.c -g
gcc game2.o -o game2 -l ncurses
rm game2.o
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <curses.h>
#define MSPF (100/60)
#define NORMAL 0
#define BOSS 1
#define BATTLE 2
#define BOSSDEAD 3
#define CLEAR 4
#define STAGEGAMEN 5
#define MAXHP 5
#define BOSSMAXHP 10
#define BEAMSUU 20
#define ENEMYSUU 10
#define ITEMSUU 2
void setting();
void DISPLAY();
void run();
void appearBeam(int a_y,int a_x);
void makeENEMY_BEAM();
void makeBOSS_BEAM();
void moveEnemy_BEAM();
void moveBoss_BEAM();
void moveBeam();
void makeEnemy();
void makeBoss();
void moveEnemy();
void moveBoss();
void hantei();
void bshantei();
void imhantei(int a_y,int a_x);
int atari(int bm_y,int bm_x,int ene_y,int ene_x,int lev,char *form);
void HP(int hp);
void BOSS_HP(int bshp);
void en_attack(int a_y,int a_x,int joutai);
void en_bm_attack(int a_y,int a_x,int joutai);
void bs_attack(int a_y,int a_x,int joutai);
void makeITEM();
void moveITEM();
void score_keisan(int enemyscore);
int kaisuu=0;
int cnt=0,cnt1=0,cnt2=0,cnt3=0,cnt4=0;
int hp = MAXHP;
int GO = 0;
int pattern = 0;
int pat2 = 1;
int field = STAGEGAMEN;
int temphp;
int temp=0;
int message = 0;
int m = 0;
int dam = 0;
int exitbs = 0;
int deathcnt = 0;
int d_x1,d_x2;
int bossidou=0;
int ALLENEMY=0;
int critical = 0;
struct ME{
int joutai;
char me_form[4];
int a_y;
int a_x;
int stage;
int score;
} me[1];
struct Beam{
int beamexsist;//0 or 1:0 is not exsist,1 is exsist.
int beam_y;
int beam_x;
int beam_type;
/* struct Beam *nextp; */
} bn[BEAMSUU];
struct Enemy{
int level;
char *enemy_form;
int enemyexsist;
int enemy_y;
int enemy_x;
int enemy_hp;
int enjoutai;
int enscore;
struct Beam enbm[10];
} en[ENEMYSUU];
struct BOSS_ENEMY{
int blevel;
int bossexsist;
int boss_y;
int boss_x;
int boss_hp;
int bsscore;
struct Beam bsbm[10];
}bs[3];
struct ITEM{
int number;
char item_form[2];
int itemexsist;
int item_y;
int item_x;
}im[ITEMSUU];
int main()
{
//初期化
initscr();
//設定
setting();
//ゲーム実行
DISPLAY();
run();
endwin();
return 0;
}
void setting()
{
noecho();
cbreak();
curs_set(0);
keypad(stdscr,TRUE);
timeout(0);
}
void DISPLAY(){
mvaddstr(0,0,"**************************************");
mvaddstr(1,0,"* * *");
mvaddstr(2,0,"* * *");
mvaddstr(3,0,"* * *");
mvaddstr(4,0,"* * *");
mvaddstr(5,0,"* *************");
mvaddstr(6,0,"* * *");
mvaddstr(7,0,"* * *");
mvaddstr(8,0,"* * *");
mvaddstr(9,0,"* *************");
mvaddstr(10,0,"* * *");
mvaddstr(11,0,"* * *");
mvaddstr(12,0,"* * *");
mvaddstr(13,0,"* * *");
mvaddstr(14,0,"* *************");
mvaddstr(15,0,"* * *");
mvaddstr(16,0,"**************************************");
}
void run()
{
clock_t time1,pre_time;
char ch;
char clearmes[15];
int beamdelay = 0;
int beam = 0;//beamが1のときに画面にビームがあります
/* int beam_x,beam_y; */
int delay,delay_s;
int delay_st = 1;
int kotei_delay1 = 0;
int kotei_delay2 = 0;
int kotei_delay3 = 0;
int wait = 9000;
me[0].joutai = 0;
me[0].a_x = 10;
me[0].a_y = 15;
me[0].stage = 1;
me[0].score = 0;
int enemy = 1;
/* int enemy_x = 9; */
/* int enemy_y = 3; */
int randam = 0;
int reala_x;
int i;
int smes = 0;
int quit = 0;
char stagemes[10];
while((ch = getch()) != 's'){
mvaddstr(7,7,"INVADAR GAME");
mvaddstr(15,18,"q:exit");
if(ch == 'q'){
quit = 1;
break;
}
if(ch == '2'){
ALLENEMY = 31;
me[0].stage = 2;
mvaddstr(10,6,"jump to STAGE2");
}
if(ch == 'c'){
ALLENEMY = 0;
me[0].stage = 1;
mvaddstr(10,6," ");
}
if((delay_s % 27000) == 0){
if(smes == 0){
mvaddstr(8,6,"-PRESS 's' KEY-");
smes = 1;
}else if(smes == 1){
mvaddstr(8,6," ");
smes = 0;
}
}
delay_s++;
}
if(quit == 0){
erase();
DISPLAY();
HP(hp);
score_keisan(0);
pre_time = 0;
while((ch=getch()) != 'q'){
time1 = clock();
switch(ch){
case 'f':
if(me[0].joutai == 0){
if(me[0].a_x > 1){
mvaddch(me[0].a_y,me[0].a_x,' ');
me[0].a_x--;
}
}else if(me[0].joutai == 1){
if(me[0].a_x > 2){
mvaddstr(me[0].a_y,me[0].a_x-1," ");
me[0].a_x--;
}
}
break;
case 'j':
if(me[0].joutai == 0){
if(me[0].a_x < 24){
mvaddch(me[0].a_y,me[0].a_x,' ');
me[0].a_x++;
}
}else if(me[0].joutai == 1){
if(me[0].a_x < 23){
mvaddstr(me[0].a_y,me[0].a_x-1," ");
me[0].a_x++;
}
}
break;
case ' ':
if(bossidou == 0){
appearBeam(me[0].a_y,me[0].a_x);
}
/* if(beam == 0){ */
/* beam_x = a_x; */
/* beam_y = a_y; */
/* beep(); */
/* beam = 1; */
/* } */
break;
}
/* if(beam == 1 && (delay % wait) == 0){ */
/* mvaddch(beam_y,beam_x,' '); */
/* beam_y--; */
/* mvaddch(beam_y,beam_x,'i'); */
/* if(beam_y < 0){ */
/* mvaddch(beam_y,beam_x,' '); */
/* beam = 0; */
/* } */
/* } */
if(field == NORMAL){
if((double)(time1 - pre_time) >= MSPF){
if((delay % wait) == 0){
moveEnemy();
moveEnemy_BEAM();
moveBeam();
if(GO == 0){
hantei();
en_bm_attack(me[0].a_y,me[0].a_x,me[0].joutai);
}
}
}
}else if(field == BATTLE){
if((delay % wait) == 0){
moveBoss();
moveBeam();
moveBoss_BEAM();
if(bossidou == 0){
if(GO == 0){
bshantei();
bs_attack(me[0].a_y,me[0].a_x,me[0].joutai);
}
}
}
if(bossidou == 0){
if((delay % 27000) == 0){
makeBOSS_BEAM();
}
}
}
if(GO == 1){
mvaddstr(8,8,"GAME OVER");
}
if(field == NORMAL){
if((delay % 45000) == 0){
makeEnemy();
}
}else if(field == BOSS){
erase();
DISPLAY();
HP(hp);
score_keisan(0);
makeBoss();
BOSS_HP(bs[0].boss_hp);
field = BATTLE;
}
if(GO == 0){
if(field == NORMAL){
if((delay % wait) == 0){
moveITEM();
srand((unsigned)time(NULL));
randam = rand()%10;
if(randam == 0){
makeITEM();
}
imhantei(me[0].a_y,me[0].a_x);
}
if(message == 1){
kotei_delay1 = delay;
message = 0;
}
if((delay % (kotei_delay1+90000)) == 0){
mvaddstr(11,27," ");
mvaddstr(12,26," ");
}
}
}
if(field == BOSSDEAD){
if((delay % 27000) == 0){
moveBoss();
}
}
if(exitbs == 1){
for(i = 0; i< 2; i++){
im[i].itemexsist = 0;
}
for(i = 0; i< BEAMSUU; i++){
bn[i].beamexsist = 0;
}
for(i = 0; i < ENEMYSUU; i++){
en[i].enemyexsist = 0;
}
kotei_delay1 = delay;
exitbs = 0;
}
if(field == CLEAR){
sprintf(clearmes,"-STAGE%d CLEAR-",me[0].stage-1);
mvaddstr(8,6,clearmes);
if((delay % (kotei_delay1+120000)) == 0){
mvaddstr(8,6," ");
field = STAGEGAMEN;
kotei_delay3 = delay;
}
}
if(field == STAGEGAMEN){
sprintf(stagemes,"-STAGE%d-",me[0].stage);
mvaddstr(8,9,stagemes);
if(((delay+1) % (kotei_delay3+90000)) == 0){
mvaddstr(8,9," ");
field = NORMAL;
}
}
/* if(enemy == 1 && (delay % wait) == 0){ */
/* srand((unsigned)time(NULL)); */
/* randam = rand()%10; */
/* if((randam >= 0)&&(randam < 5)){ */
/* mvaddstr(enemy_y,enemy_x," "); */
/* enemy_x++; */
/* enemy_x--; */
/* } */
/* } */
/* if(beam_y == enemy_y && (beam_x == enemy_x || beam_x == enemy_x+1 || beam_x == enemy_x+2)){ */
/* mvaddstr(enemy_y,enemy_x," "); */
/* beam = 0; */
/* enemy = 0; */
/* mvaddstr(12,3,"HIT!"); */
/* } */
/* if(enemy == 1) mvaddstr(enemy_y,enemy_x,"orz"); */
if(dam == 1){
mvaddstr(me[0].a_y,me[0].a_x-1," ");
dam = 0;
}
switch(me[0].joutai){
case 0:
sprintf(me[0].me_form,"A");
reala_x = me[0].a_x;
break;
case 1:
sprintf(me[0].me_form,"AAA");
reala_x = me[0].a_x-1;
break;
}
mvaddstr(me[0].a_y,reala_x,me[0].me_form);
move(LINES-1,COLS-1);//カーソルが邪魔なので移動
delay++;
pre_time = time1;
}
}
}
void appearBeam(int a_y,int a_x){
if(me[0].joutai == 0){
if(cnt < BEAMSUU){
if(bn[cnt].beamexsist == 0){
bn[cnt].beamexsist = 1;
bn[cnt].beam_y = a_y;
bn[cnt].beam_x = a_x;
}
}
if(bn[0].beamexsist == 0){
if(cnt >= BEAMSUU-1) cnt = 0;
}
cnt++;
}else if(me[0].joutai == 1){
if(cnt < BEAMSUU-2){
if(bn[cnt].beamexsist == 0 && bn[cnt+1].beamexsist == 0 && bn[cnt+2].beamexsist == 0){
bn[cnt].beamexsist = 1;
bn[cnt+1].beamexsist = 1;
bn[cnt+2].beamexsist = 1;
bn[cnt].beam_y = a_y;
bn[cnt+1].beam_y = a_y;
bn[cnt+2].beam_y = a_y;
bn[cnt].beam_x = a_x-1;
bn[cnt+1].beam_x = a_x;
bn[cnt+2].beam_x = a_x+1;
}
}
if(bn[0].beamexsist == 0){
if(cnt >= BEAMSUU-3) cnt = 0;
}
cnt += 3;
}
/* struct Beam *p; */
/* p =(struct Beam *)malloc(sizeof(struct Beam)); */
/* p->beamexsist = 1; */
/* p->beam_y = a_y; */
/* p->beam_x = a_x; */
/* p->nextp = root; */
/* root = p; */
}
void makeENEMY_BEAM(){
int i;
for(i = 0; i < ENEMYSUU; i++){
if(en[i].enemyexsist == 1){
en[i].enbm[cnt4].beamexsist = 1;
en[i].enbm[cnt4].beam_y = en[i].enemy_y;
en[i].enbm[cnt4].beam_x = en[i].enemy_x;
en[i].enbm[cnt4].beam_type = 1;
en[i].enbm[cnt4+1].beamexsist = 1;
en[i].enbm[cnt4+1].beam_y = en[i].enemy_y;
en[i].enbm[cnt4+1].beam_x = en[i].enemy_x;
en[i].enbm[cnt4+1].beam_type = 2;
en[i].enbm[cnt4+2].beamexsist = 1;
en[i].enbm[cnt4+2].beam_y = en[i].enemy_y;
en[i].enbm[cnt4+2].beam_x = en[i].enemy_x;
en[i].enbm[cnt4+2].beam_type = 3;
cnt4++;
}
}
if(cnt4 > 7){
cnt4 = 0;
}
}
void makeBOSS_BEAM(){
bs[0].bsbm[cnt1].beamexsist = 1;
bs[0].bsbm[cnt1].beam_y = bs[0].boss_y+1;
bs[0].bsbm[cnt1].beam_x = bs[0].boss_x+1;
cnt1++;
if(cnt1 >= 10){
cnt1 = 0;
}
}
void moveEnemy_BEAM(){
int i,j;
for(i = 0; i < ENEMYSUU; i++){
for(j = 0; j < 10; j++){
if(en[i].enbm[j].beamexsist == 1){
mvaddch(en[i].enbm[j].beam_y,en[i].enbm[j].beam_x,' ');
switch(en[i].enbm[j].beam_type){
case 1:
en[i].enbm[j].beam_y++;
break;
case 2:
if(en[i].enbm[j].beam_x > 1){
if((en[i].enbm[j].beam_y % 2) == 0){
en[i].enbm[j].beam_x--;
}
}
en[i].enbm[j].beam_y++;
break;
case 3:
if(en[i].enbm[j].beam_x < 24){
if((en[i].enbm[j].beam_y % 2) == 0){
en[i].enbm[j].beam_x++;
}
}
en[i].enbm[j].beam_y++;
break;
}
mvaddch(en[i].enbm[j].beam_y,en[i].enbm[j].beam_x,'V');
if(en[i].enbm[j].beam_y >= me[0].a_y+1){
mvaddch(en[i].enbm[j].beam_y,en[i].enbm[j].beam_x,'*');
en[i].enbm[j].beamexsist = 0;
}
}
}
}
}
void moveBoss_BEAM(){
int i;
for(i = 0; i < 10; i++){
if(bs[0].bsbm[i].beamexsist == 1){
mvaddch(bs[0].bsbm[i].beam_y,bs[0].bsbm[i].beam_x,' ');
bs[0].bsbm[i].beam_y++;
mvaddch(bs[0].bsbm[i].beam_y,bs[0].bsbm[i].beam_x,'V');
if(bs[0].bsbm[i].beam_y >= me[0].a_y+1){
mvaddch(bs[0].bsbm[i].beam_y,bs[0].bsbm[i].beam_x,'*');
bs[0].bsbm[i].beamexsist = 0;
}
}
}
}
void moveBeam(){
int i;
for(i = 0;i < BEAMSUU; i++){
if(bn[i].beamexsist == 1){
mvaddch(bn[i].beam_y,bn[i].beam_x,' ');
bn[i].beam_y--;
mvaddch(bn[i].beam_y,bn[i].beam_x,'i');
if(bn[i].beam_y < 1){
mvaddch(bn[i].beam_y,bn[i].beam_x,'*');
bn[i].beamexsist = 0;
}
}
}
/* struct Beam *p; */
/* for(p = root; p != NULL; p = p->nextp){ */
/* if(p->beamexsist == 1){ */
/* mvaddch(p->beam_y,p->beam_x,' '); */
/* p->beam_y--; */
/* mvaddch(p->beam_y,p->beam_x,'i'); */
/* if(p->beam_y < 0){ */
/* mvaddch(p->beam_y,p->beam_x,' '); */
/* p->beamexsist = 0; */
/* } */
/* } */
/* } */
}
void makeEnemy(){
int randam1;
srand((unsigned)time(NULL));
randam1 = rand()%18;
if(ALLENEMY<21){
en[cnt2].level = 1;
en[cnt2].enemyexsist = 1;
en[cnt2].enemy_y = 1;
en[cnt2].enemy_x = randam1+2;
en[cnt2].enemy_hp = 1;
en[cnt2].enjoutai = 0;
}else if(ALLENEMY >= 21 && ALLENEMY < 30){
en[cnt2].level = 2;
en[cnt2].enemyexsist = 1;
en[cnt2].enemy_y = 1;
en[cnt2].enemy_x = randam1+2;
en[cnt2].enemy_hp = 2;
en[cnt2].enjoutai = 0;
}else if(ALLENEMY >= 30){
if(me[0].stage == 1){
field = BOSS;
}else if(me[0].stage == 2){
if(ALLENEMY >=31 && ALLENEMY < 50){
en[cnt2].level = 3;
en[cnt2].enemyexsist = 1;
en[cnt2].enemy_y = 1;
en[cnt2].enemy_x = randam1+2;
en[cnt2].enemy_hp = 1;
en[cnt2].enjoutai = 0;
}else if(ALLENEMY >= 50){
en[cnt2].level = 4;
en[cnt2].enemyexsist = 1;
en[cnt2].enemy_y = 1;
en[cnt2].enemy_x = randam1+2;
en[cnt2].enemy_hp = 3;
en[cnt2].enjoutai = 0;
}
}
}
if(field == NORMAL){
switch(en[cnt2].level){
case 1:
en[cnt2].enemy_form = (char *)malloc(strlen("orz")+1);
sprintf(en[cnt2].enemy_form,"orz");
en[cnt2].enscore = 10;
break;
case 2:
en[cnt2].enemy_form = (char *)malloc(strlen("69")+1);
sprintf(en[cnt2].enemy_form,"69");
en[cnt2].enscore = 30;
break;
case 3:
en[cnt2].enemy_form = (char *)malloc(strlen("BM")+1);
sprintf(en[cnt2].enemy_form,"BM");
en[cnt2].enscore = 50;
break;
case 4:
en[cnt2].enemy_form = (char *)malloc(strlen("T<o>T")+1);
sprintf(en[cnt2].enemy_form,"T<o>T");
en[cnt2].enscore = 80;
break;
}
mvaddstr(en[cnt2].enemy_y,en[cnt2].enemy_x,en[cnt2].enemy_form);
cnt2++;
}
if(cnt2 > ENEMYSUU-1) cnt2 = 0;
ALLENEMY++;
}
void makeBoss(){
bs[0].blevel = 1;
bs[0].bossexsist = 1;
bs[0].boss_y = 1;
bs[0].boss_x = 10;
bs[0].boss_hp = 10;
bs[0].bsscore = 100;
temphp = bs[0].boss_hp;
mvaddstr(bs[0].boss_y,bs[0].boss_x,"p--q");
mvaddstr(bs[0].boss_y+1,bs[0].boss_x,"B**O");
}
void moveEnemy(){
int i,j;
if(pattern == 1){
pattern--;
pat2 = 1;
}else if(pattern == -1){
pattern++;
pat2 = -1;
}else if(pattern == 0){
if(pat2 == 1){
pattern--;
}else if(pat2 == -1){
pattern++;
}
}
for(i = 0; i < ENEMYSUU; i++){
if(en[i].enemyexsist == 1){
for(j = 0; j < strlen(en[i].enemy_form); j++) mvaddch(en[i].enemy_y,en[i].enemy_x+j,' ');
switch(en[i].level){
case 1:
case 2:
case 4:
en[i].enemy_y++;
en[i].enemy_x += pattern;
break;
case 3:
if(en[i].enemy_y != 4 && en[i].enjoutai == 0){
en[i].enemy_y++;
}else if(en[i].enemy_y == 4 && en[i].enjoutai == 0){
makeENEMY_BEAM();
en[i].enjoutai = 1;
}else if(en[i].enemy_y == 4 && en[i].enjoutai == 1){
en[i].enemy_y--;
}else if(en[i].enemy_y != 4 && en[i].enjoutai == 1){
en[i].enemy_y--;
}
break;
}
mvaddstr(en[i].enemy_y,en[i].enemy_x,en[i].enemy_form);
switch(en[i].level){
case 1:
case 2:
case 4:
if(en[i].enemy_y == me[0].a_y){
en_attack(me[0].a_y,me[0].a_x,me[0].joutai);
for(j = 0; j < strlen(en[i].enemy_form); j++) mvaddch(en[i].enemy_y,en[i].enemy_x+j,' ');
en[i].enemyexsist = 0;
}
break;
case 3:
if(en[i].enemy_y == 0){
en[i].enjoutai = 0;
for(j = 0; j < strlen(en[i].enemy_form); j++) mvaddch(en[i].enemy_y,en[i].enemy_x+j,'*');
en[i].enemyexsist = 0;
}
}
}
}
}
void moveBoss(){
int randam2;
srand((unsigned)time(NULL));
randam2 = rand()%20;
if(bs[0].bossexsist == 1){
if(field == BATTLE){
if(bs[0].boss_y != 6){
bossidou = 1;
if((bs[0].boss_y%2)==1){
mvaddstr(8,6,"-BOSS BATTLE-");
m = 1;
}else{
mvaddstr(8,6," ");
m = 0;
}
mvaddstr(bs[0].boss_y,bs[0].boss_x," ");
mvaddstr(bs[0].boss_y+1,bs[0].boss_x," ");
bs[0].boss_y++;
mvaddstr(bs[0].boss_y,bs[0].boss_x,"p--q");
mvaddstr(bs[0].boss_y+1,bs[0].boss_x,"B**O");
}else{
bossidou = 0;
if(m == 1) mvaddstr(8,6," ");
mvaddstr(bs[0].boss_y,bs[0].boss_x," ");
mvaddstr(bs[0].boss_y+1,bs[0].boss_x," ");
if(bs[0].boss_x <= 1){
bs[0].boss_x++;
}else if(bs[0].boss_x >= 21){
bs[0].boss_x--;
}else{
if(randam2 >= 0 && randam2 < 10){
bs[0].boss_x++;
}else{
bs[0].boss_x--;
}
}
mvaddstr(bs[0].boss_y,bs[0].boss_x,"p--q");
mvaddstr(bs[0].boss_y+1,bs[0].boss_x,"B**O");
m = 0;
}
}else if(field == BOSSDEAD){
deathcnt++;
if(deathcnt == 1){
mvaddstr(bs[0].boss_y,bs[0].boss_x,"p--q");
mvaddstr(bs[0].boss_y+1,bs[0].boss_x,"B**O");
d_x1 = bs[0].boss_x;
d_x2 = bs[0].boss_x+2;
}else if(deathcnt == 5){
mvaddstr(bs[0].boss_y,d_x1," ");
mvaddstr(bs[0].boss_y,d_x2," ");
mvaddstr(bs[0].boss_y+1,d_x1," ");
mvaddstr(bs[0].boss_y+1,d_x2," ");
bs[0].bossexsist = 0;
field = CLEAR;
exitbs = 1;
deathcnt = 0;
}else{
mvaddstr(bs[0].boss_y,d_x1," ");
mvaddstr(bs[0].boss_y,d_x2," ");
mvaddstr(bs[0].boss_y+1,d_x1," ");
mvaddstr(bs[0].boss_y+1,d_x2," ");
d_x1 = d_x1-1;
d_x2 = d_x2+1;
mvaddstr(bs[0].boss_y,d_x1,"p-");
mvaddstr(bs[0].boss_y,d_x2,"-q");
mvaddstr(bs[0].boss_y+1,d_x1,"B*");
mvaddstr(bs[0].boss_y+1,d_x2,"*O");
}
}
}
}
void hantei(){
int i,j,k;
char str[10];
for(i = 0; i < BEAMSUU ; i++){
for(j = 0; j <ENEMYSUU ; j++){
if(bn[i].beamexsist == 1 && en[j].enemyexsist == 1){
if(atari(bn[i].beam_y,bn[i].beam_x,en[j].enemy_y,en[j].enemy_x,en[j].level,en[j].enemy_form) == 1){
en[j].enemy_hp--;
if(critical == 1){
en[j].enemy_hp -= 2;
critical = 0;
}
if(en[j].enemy_hp == 0){
kaisuu++;
sprintf(str,"KILL:%2d",kaisuu);
mvaddstr(10,27," ");
mvaddstr(10,27,str);
score_keisan(en[j].enscore);
for(k = 0; k < strlen(en[j].enemy_form); k++) mvaddch(en[j].enemy_y,en[j].enemy_x+k,' ');
en[j].enemyexsist = 0;
}
mvaddch(bn[i].beam_y,bn[i].beam_x,' ');
bn[i].beamexsist = 0;
}
}
}
}
}
void bshantei(){
int i;
for(i = 0; i < BEAMSUU; i++){
if(bn[i].beamexsist == 1 && bs[0].bossexsist == 1){
if(atari(bn[i].beam_y,bn[i].beam_x,bs[0].boss_y,bs[0].boss_x,bs[0].blevel,NULL) == 1){
temphp--;
BOSS_HP(temphp);
mvaddch(bn[i].beam_y,bn[i].beam_x,' ');
bn[i].beamexsist = 0;
}
}
}
}
void imhantei(int a_y,int a_x){
int i;
for(i = 0; i < ITEMSUU; i++){
if(im[i].itemexsist == 1){
if(im[i].item_y == a_y && im[i].item_x == a_x){
mvaddstr(11,27,"ITEM GET!");
message = 1;
switch(im[i].number){
case 1:
me[0].joutai = 1;
mvaddstr(12,27,"POWER UP!");
break;
case 2:
if(hp < MAXHP){
hp++;
HP(hp);
mvaddstr(12,27,"RECOVRY!");
}else{
mvaddstr(12,26,"ALREADY MAX");
}
break;
}
}
}
}
}
int atari(int bm_y,int bm_x,int ene_y,int ene_x,int lev,char *form){
int i;
if(field == NORMAL){
for(i = 0; i < strlen(form); i++){
if((bm_y == ene_y || bm_y == ene_y-1 ) && (bm_x == ene_x+i)){
if(lev == 4 && i == 2) critical = 1;
return(1);
}
}
return(0);
}else if(field == BATTLE){
if((bm_y == ene_y || bm_y == ene_y+1) && (bm_x == ene_x || bm_x == ene_x+1 || bm_x == ene_x+2 || bm_x == ene_x+3)){
return(1);
}else{
return(0);
}
}else{
return(0);
}
}
void en_attack(int a_y,int a_x,int joutai){
int i,j,k;
for(i = 0; i < ENEMYSUU; i++){
if(en[i].enemyexsist == 1){
for(j = 0; j < strlen(en[i].enemy_form); j++){
for(k = 0; k < strlen(me[0].me_form); k++){
if((en[i].enemy_y == a_y) && (en[i].enemy_x+j == a_x+k)){;
if(joutai == 1){
me[0].joutai = 0;
dam = 1;
}else{
hp--;
HP(hp);
}
}
}
}
}
}
}
void en_bm_attack(int a_y,int a_x, int joutai){
int i,j;
for(i = 0; i < ENEMYSUU; i++){
for(j = 0; j < 10; j++){
if(en[i].enbm[j].beamexsist == 1){
if(joutai == 0){
if(en[i].enbm[j].beam_y == a_y && en[i].enbm[j].beam_x == a_x){
hp--;
HP(hp);
}
}else if(joutai == 1){
if((en[i].enbm[j].beam_y == a_y) && (en[i].enbm[j].beam_x == a_x-1 || en[i].enbm[j].beam_x == a_x || en[i].enbm[j].beam_x == a_x+1)){
me[0].joutai = 0;
dam = 1;
}
}
}
}
}
}
void bs_attack(int a_y,int a_x,int joutai){
int i;
for(i = 0; i < 10; i++){
if(bs[0].bsbm[i].beamexsist == 1){
if(joutai == 0){
if(bs[0].bsbm[i].beam_y == a_y && bs[0].bsbm[i].beam_x == a_x){
hp--;
HP(hp);
}
}else if(joutai == 1){
if((bs[0].bsbm[i].beam_y == a_y) && (bs[0].bsbm[i].beam_x == a_x-1 || bs[0].bsbm[i].beam_x == a_x || bs[0].bsbm[i].beam_x == a_x+1)){
me[0].joutai = 0;
dam = 1;
}
}
}
}
}
void HP(int hp){
int i;
mvaddstr(15,27,"HP:");
for(i = 0; i < MAXHP; i++){
mvaddch(15,30+i,' ');
}
for(i = 0; i < hp; i++){
mvaddch(15,30+i,'|');
}
if(hp == 0){
GO = 1;
}
}
void BOSS_HP(int bshp){
int i;
mvaddstr(1,27,"BOSS:");
for(i = 0; i < bs[0].boss_hp ; i++){
mvaddch(2,27+i,' ');
}
for(i = 0; i < bshp; i++){
mvaddch(2,27+i,'|');
}
if(bshp == 0){
erase();
DISPLAY();
HP(hp);
score_keisan(bs[0].bsscore);
me[0].stage = 2;
field = BOSSDEAD;
kaisuu++;
}
}
void makeITEM(){
int randam3,randam4;
srand((unsigned)time(NULL));
randam3 = rand()%23;
randam4 = rand()%3;
if(cnt3 < ITEMSUU){
switch(randam4){
case 0:
im[cnt3].number = 1;
break;
case 1:
case 2:
im[cnt3].number = 2;
break;
}
im[cnt3].itemexsist = 1;
im[cnt3].item_y = 1;
im[cnt3].item_x = randam3+1;
switch(im[cnt3].number){
case 1:
sprintf(im[cnt3].item_form,"P");
break;
case 2:
sprintf(im[cnt3].item_form,"E");
break;
}
mvaddstr(im[cnt3].item_y,im[cnt3].item_x,im[cnt3].item_form);
if(cnt3 == ITEMSUU-1) cnt3 = 0;
}
cnt3++;
}
void moveITEM(){
int i;
for(i = 0; i < ITEMSUU; i++){
if(im[i].itemexsist == 1){
mvaddch(im[i].item_y,im[i].item_x,' ');
im[i].item_y++;
mvaddstr(im[i].item_y,im[i].item_x,im[i].item_form);
if(im[i].item_y == me[0].a_y+1){
mvaddstr(im[i].item_y,im[i].item_x,"*");
im[i].itemexsist = 0;
}
}
}
}
void score_keisan(int enemyscore){
char str[20];
mvaddstr(6,26," ");
mvaddstr(7,26," ");
me[0].score += enemyscore;
sprintf(str,"%10d",me[0].score);
mvaddstr(6,26,"TOTAL SCORE");
mvaddstr(7,26,str);
}
<file_sep># shooting-game
インベーダゲーム風のシューティングゲーム
#説明
##ゲーム画面

- A:操作キャラ
- HP:体力。敵に当たると減り、0になるとゲームオーバー
- TOTAL SCORE:ゲームのスコア
##操作
- f:左に動く
- j:右に動く
- スペース:たまをうつ
##アイテム
- E:取るとHPが1回復する
- P:取ると自キャラがAAAのように大きくなり攻撃の範囲も大きくなる
| d8c1516a36528a3a543cf1609b3044fe8194f854 | [
"Markdown",
"C",
"Makefile"
] | 3 | Makefile | itsukiss/shooting-game | ab0a29b03cc59c65d020bd1220ed73784098c62f | 7e6834c6319f3118c44c8179d12653d930c9d67e |
refs/heads/master | <file_sep>server.servlet.context-path=/mvc-app
server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/gb_spring_mvc
spring.datasource.username=root
spring.datasource.password=<PASSWORD>
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL8Dialect
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.hibernate.ddl-auto=update
spring.mvc.hiddenmethod.filter.enabled=true
<file_sep>package ru.geekbrains.rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ru.geekbrains.persist.entity.Product;
import ru.geekbrains.service.ProductService;
import java.util.List;
@RestController
@RequestMapping("/api/v1/product")
public class ProductResource {
ProductService productService;
@Autowired
public ProductResource(ProductService productService) {
this.productService = productService;
}
@GetMapping("/all")
public List<Product> getAll() {
return productService.findAll();
}
@GetMapping("/{id}")
public Product getById(@PathVariable long id) {
return productService.findById(id).orElseThrow(HttpNotFoundException::new);
}
@PostMapping
public void createProduct(@RequestBody Product product) {
productService.save(product);
}
@PutMapping
public void updateProduct(@RequestBody Product product) {
productService.save(product);
}
@DeleteMapping("/{id}")
public void deleteProduct(@PathVariable long id) {
productService.delete(id);
}
@ExceptionHandler
public ResponseEntity<HttpNotFoundResponse> httpNotFoundExceptionResponseHandler(HttpNotFoundException e) {
HttpNotFoundResponse httpNotFoundResponse = new HttpNotFoundResponse();
httpNotFoundResponse.setStatus(HttpStatus.NOT_FOUND.value());
httpNotFoundResponse.setMessage("Not found");
httpNotFoundResponse.setTimestamp(System.currentTimeMillis());
return new ResponseEntity<>(httpNotFoundResponse, HttpStatus.NOT_FOUND);
}
}
<file_sep>package ru.geekbrains.rest;
public class HttpNotFoundException extends RuntimeException {
}
<file_sep>package ru.geekbrains.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@RequestMapping("/site")
@Controller
public class SiteController {
@GetMapping("login")
public String login() {
return "login";
}
}
<file_sep>package ru.geekbrains.persist;
import org.hibernate.annotations.Cascade;
import javax.persistence.*;
import java.util.List;
@Entity
@Table(name = "products")
@NamedQueries({
@NamedQuery(name = "Product.findByName", query = "from Product p where p.productName = :name")
})
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "product_name")
private String productName;
@Column
private float cost;
@OneToMany(mappedBy = "product")
@Cascade(org.hibernate.annotations.CascadeType.ALL)
private List<CustomerProducts> customerProducts;
public Product() {}
public Product(String name, float cost) {
productName = name;
this.cost = cost;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public float getCost() {
return cost;
}
public void setCost(float cost) {
this.cost = cost;
}
@Override
public String toString() {
return "Product{" +
"id=" + id +
", productName='" + productName + '\'' +
", cost=" + cost +
", customerProducts=" + customerProducts +
'}';
}
}
<file_sep>package ru.geekbrains.server;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import ru.geekbrains.server.persistance.UserRepository;
@Component
public class BeanPP implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
// В данном методе просто возвращаем бин
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("Создан бин " + beanName);
if (bean instanceof ChatServer) {
((ChatServer) bean).start(7777);
}
return bean;
}
}
<file_sep>package ru.geekbrains.server;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ChatServerApplication {
public static void main(String[] args) {
// ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
ChatServer chatServer = context.getBean(ChatServer.class);
// chatServer.start(7777);
}
}
| 6ebbb8910c12652f1f38b2bb5f2022ef045a85d9 | [
"Java",
"INI"
] | 7 | INI | silver23891/spring | 227fae6e6f75d8e22812ea4654a93bf1ef18d150 | 8aa1716182d2e8fe00bc0a30367c4eee3752475e |
refs/heads/master | <file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entity;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author Jakub
*/
@Entity
@Table(name = "dock")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Dock.findAll", query = "SELECT d FROM Dock d"),
@NamedQuery(name = "Dock.findById", query = "SELECT d FROM Dock d WHERE d.id = :id"),
@NamedQuery(name = "Dock.findByName", query = "SELECT d FROM Dock d WHERE d.name = :name"),
@NamedQuery(name = "Dock.findByType", query = "SELECT d FROM Dock d WHERE d.type = :type"),
@NamedQuery(name = "Dock.findByEfficiency", query = "SELECT d FROM Dock d WHERE d.efficiency = :efficiency")})
public class Dock implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Size(max = 20)
@Column(name = "name")
private String name;
@Column(name = "type")
private Integer type;
@Column(name = "efficiency")
private Integer efficiency;
@OneToMany(mappedBy = "dockId")
private Collection<FinalCommission> finalCommissionCollection;
@JoinColumn(name = "onStation", referencedColumnName = "id")
@ManyToOne(optional = false)
private Station onStation;
public Dock() {
}
public Dock(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public Integer getEfficiency() {
return efficiency;
}
public void setEfficiency(Integer efficiency) {
this.efficiency = efficiency;
}
@XmlTransient
public Collection<FinalCommission> getFinalCommissionCollection() {
return finalCommissionCollection;
}
public void setFinalCommissionCollection(Collection<FinalCommission> finalCommissionCollection) {
this.finalCommissionCollection = finalCommissionCollection;
}
public Station getOnStation() {
return onStation;
}
public void setOnStation(Station onStation) {
this.onStation = onStation;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Dock)) {
return false;
}
Dock other = (Dock) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "Dock[ " + name + " on " + onStation.getName() + " on " + onStation.getOnPlanet().getName() + " ]";
}
}
<file_sep>PersistenceErrorOccured=A persistence error occurred.
Create=Create
View=View
Edit=Edit
Delete=Delete
Close=Close
Cancel=Cancel
Save=Save
SelectOneMessage=Select One...
Home=Home
Maintenance=Maintenance
AppName=EnterpriseApplication1-war
DockCreated=Dock was successfully created.
DockUpdated=Dock was successfully updated.
DockDeleted=Dock was successfully deleted.
CreateDockTitle=Create New Dock
CreateDockSaveLink=Save
CreateDockShowAllLink=Show All Dock Items
CreateDockIndexLink=Index
CreateDockLabel_id=Id:
CreateDockRequiredMessage_id=The Id field is required.
CreateDockTitle_id=Id
CreateDockLabel_name=Name:
CreateDockTitle_name=Name
CreateDockLabel_type=Type:
CreateDockTitle_type=Type
CreateDockLabel_efficiency=Efficiency:
CreateDockTitle_efficiency=Efficiency
CreateDockLabel_onStation=OnStation:
CreateDockRequiredMessage_onStation=The OnStation field is required.
CreateDockTitle_onStation=OnStation
EditDockTitle=Edit Dock
EditDockSaveLink=Save
EditDockViewLink=View
EditDockShowAllLink=Show All Dock Items
EditDockIndexLink=Index
EditDockLabel_id=Id:
EditDockRequiredMessage_id=The Id field is required.
EditDockTitle_id=Id
EditDockLabel_name=Name:
EditDockTitle_name=Name
EditDockLabel_type=Type:
EditDockTitle_type=Type
EditDockLabel_efficiency=Efficiency:
EditDockTitle_efficiency=Efficiency
EditDockLabel_onStation=OnStation:
EditDockRequiredMessage_onStation=The OnStation field is required.
EditDockTitle_onStation=OnStation
ViewDockTitle=View
ViewDockDestroyLink=Destroy
ViewDockEditLink=Edit
ViewDockCreateLink=Create New Dock
ViewDockShowAllLink=Show All Dock Items
ViewDockIndexLink=Index
ViewDockLabel_id=Id:
ViewDockTitle_id=Id
ViewDockLabel_name=Name:
ViewDockTitle_name=Name
ViewDockLabel_type=Type:
ViewDockTitle_type=Type
ViewDockLabel_efficiency=Efficiency:
ViewDockTitle_efficiency=Efficiency
ViewDockLabel_onStation=OnStation:
ViewDockTitle_onStation=OnStation
ListDockTitle=List
ListDockEmpty=(No Dock Items Found)
ListDockDestroyLink=Destroy
ListDockEditLink=Edit
ListDockViewLink=View
ListDockCreateLink=Create New Dock
ListDockIndexLink=Index
ListDockTitle_id=Id
ListDockTitle_name=Name
ListDockTitle_type=Type
ListDockTitle_efficiency=Efficiency
ListDockTitle_onStation=OnStation
FinalCommissionCreated=FinalCommission was successfully created.
FinalCommissionUpdated=FinalCommission was successfully updated.
FinalCommissionDeleted=FinalCommission was successfully deleted.
CreateFinalCommissionTitle=Create New FinalCommission
CreateFinalCommissionSaveLink=Save
CreateFinalCommissionShowAllLink=Show All FinalCommission Items
CreateFinalCommissionIndexLink=Index
CreateFinalCommissionLabel_id=Id:
CreateFinalCommissionRequiredMessage_id=The Id field is required.
CreateFinalCommissionTitle_id=Id
CreateFinalCommissionLabel_dockId=DockId:
CreateFinalCommissionTitle_dockId=DockId
CreateFinalCommissionLabel_adminId=AdminId:
CreateFinalCommissionRequiredMessage_adminId=The AdminId field is required.
CreateFinalCommissionTitle_adminId=AdminId
CreateFinalCommissionLabel_transportId=TransportId:
CreateFinalCommissionRequiredMessage_transportId=The TransportId field is required.
CreateFinalCommissionTitle_transportId=TransportId
CreateFinalCommissionLabel_shipId=ShipId:
CreateFinalCommissionRequiredMessage_shipId=The ShipId field is required.
CreateFinalCommissionTitle_shipId=ShipId
EditFinalCommissionTitle=Edit FinalCommission
EditFinalCommissionSaveLink=Save
EditFinalCommissionViewLink=View
EditFinalCommissionShowAllLink=Show All FinalCommission Items
EditFinalCommissionIndexLink=Index
EditFinalCommissionLabel_id=Id:
EditFinalCommissionRequiredMessage_id=The Id field is required.
EditFinalCommissionTitle_id=Id
EditFinalCommissionLabel_dockId=DockId:
EditFinalCommissionTitle_dockId=DockId
EditFinalCommissionLabel_adminId=AdminId:
EditFinalCommissionRequiredMessage_adminId=The AdminId field is required.
EditFinalCommissionTitle_adminId=AdminId
EditFinalCommissionLabel_transportId=TransportId:
EditFinalCommissionRequiredMessage_transportId=The TransportId field is required.
EditFinalCommissionTitle_transportId=TransportId
EditFinalCommissionLabel_shipId=ShipId:
EditFinalCommissionRequiredMessage_shipId=The ShipId field is required.
EditFinalCommissionTitle_shipId=ShipId
ViewFinalCommissionTitle=View
ViewFinalCommissionDestroyLink=Destroy
ViewFinalCommissionEditLink=Edit
ViewFinalCommissionCreateLink=Create New FinalCommission
ViewFinalCommissionShowAllLink=Show All FinalCommission Items
ViewFinalCommissionIndexLink=Index
ViewFinalCommissionLabel_id=Id:
ViewFinalCommissionTitle_id=Id
ViewFinalCommissionLabel_dockId=DockId:
ViewFinalCommissionTitle_dockId=DockId
ViewFinalCommissionLabel_adminId=AdminId:
ViewFinalCommissionTitle_adminId=AdminId
ViewFinalCommissionLabel_transportId=TransportId:
ViewFinalCommissionTitle_transportId=TransportId
ViewFinalCommissionLabel_shipId=ShipId:
ViewFinalCommissionTitle_shipId=ShipId
ListFinalCommissionTitle=List
ListFinalCommissionEmpty=(No FinalCommission Items Found)
ListFinalCommissionDestroyLink=Destroy
ListFinalCommissionEditLink=Edit
ListFinalCommissionViewLink=View
ListFinalCommissionCreateLink=Create New FinalCommission
ListFinalCommissionIndexLink=Index
ListFinalCommissionTitle_id=Id
ListFinalCommissionTitle_dockId=DockId
ListFinalCommissionTitle_adminId=AdminId
ListFinalCommissionTitle_transportId=TransportId
ListFinalCommissionTitle_shipId=ShipId
PlanetCreated=Planet was successfully created.
PlanetUpdated=Planet was successfully updated.
PlanetDeleted=Planet was successfully deleted.
CreatePlanetTitle=Create New Planet
CreatePlanetSaveLink=Save
CreatePlanetShowAllLink=Show All Planet Items
CreatePlanetIndexLink=Index
CreatePlanetLabel_id=Id:
CreatePlanetRequiredMessage_id=The Id field is required.
CreatePlanetTitle_id=Id
CreatePlanetLabel_name=Name:
CreatePlanetTitle_name=Name
CreatePlanetLabel_stationCount=StationCount:
CreatePlanetTitle_stationCount=StationCount
EditPlanetTitle=Edit Planet
EditPlanetSaveLink=Save
EditPlanetViewLink=View
EditPlanetShowAllLink=Show All Planet Items
EditPlanetIndexLink=Index
EditPlanetLabel_id=Id:
EditPlanetRequiredMessage_id=The Id field is required.
EditPlanetTitle_id=Id
EditPlanetLabel_name=Name:
EditPlanetTitle_name=Name
EditPlanetLabel_stationCount=StationCount:
EditPlanetTitle_stationCount=StationCount
ViewPlanetTitle=View
ViewPlanetDestroyLink=Destroy
ViewPlanetEditLink=Edit
ViewPlanetCreateLink=Create New Planet
ViewPlanetShowAllLink=Show All Planet Items
ViewPlanetIndexLink=Index
ViewPlanetLabel_id=Id:
ViewPlanetTitle_id=Id
ViewPlanetLabel_name=Name:
ViewPlanetTitle_name=Name
ViewPlanetLabel_stationCount=StationCount:
ViewPlanetTitle_stationCount=StationCount
ListPlanetTitle=List
ListPlanetEmpty=(No Planet Items Found)
ListPlanetDestroyLink=Destroy
ListPlanetEditLink=Edit
ListPlanetViewLink=View
ListPlanetCreateLink=Create New Planet
ListPlanetIndexLink=Index
ListPlanetTitle_id=Id
ListPlanetTitle_name=Name
ListPlanetTitle_stationCount=StationCount
ShipCreated=Ship was successfully created.
ShipUpdated=Ship was successfully updated.
ShipDeleted=Ship was successfully deleted.
CreateShipTitle=Create New Ship
CreateShipSaveLink=Save
CreateShipShowAllLink=Show All Ship Items
CreateShipIndexLink=Index
CreateShipLabel_id=Id:
CreateShipRequiredMessage_id=The Id field is required.
CreateShipTitle_id=Id
CreateShipLabel_name=Name:
CreateShipTitle_name=Name
CreateShipLabel_serialNumber=SerialNumber:
CreateShipTitle_serialNumber=SerialNumber
CreateShipLabel_capacity=Capacity:
CreateShipTitle_capacity=Capacity
CreateShipLabel_type=Type:
CreateShipTitle_type=Type
EditShipTitle=Edit Ship
EditShipSaveLink=Save
EditShipViewLink=View
EditShipShowAllLink=Show All Ship Items
EditShipIndexLink=Index
EditShipLabel_id=Id:
EditShipRequiredMessage_id=The Id field is required.
EditShipTitle_id=Id
EditShipLabel_name=Name:
EditShipTitle_name=Name
EditShipLabel_serialNumber=SerialNumber:
EditShipTitle_serialNumber=SerialNumber
EditShipLabel_capacity=Capacity:
EditShipTitle_capacity=Capacity
EditShipLabel_type=Type:
EditShipTitle_type=Type
ViewShipTitle=View
ViewShipDestroyLink=Destroy
ViewShipEditLink=Edit
ViewShipCreateLink=Create New Ship
ViewShipShowAllLink=Show All Ship Items
ViewShipIndexLink=Index
ViewShipLabel_id=Id:
ViewShipTitle_id=Id
ViewShipLabel_name=Name:
ViewShipTitle_name=Name
ViewShipLabel_serialNumber=SerialNumber:
ViewShipTitle_serialNumber=SerialNumber
ViewShipLabel_capacity=Capacity:
ViewShipTitle_capacity=Capacity
ViewShipLabel_type=Type:
ViewShipTitle_type=Type
ListShipTitle=List
ListShipEmpty=(No Ship Items Found)
ListShipDestroyLink=Destroy
ListShipEditLink=Edit
ListShipViewLink=View
ListShipCreateLink=Create New Ship
ListShipIndexLink=Index
ListShipTitle_id=Id
ListShipTitle_name=Name
ListShipTitle_serialNumber=SerialNumber
ListShipTitle_capacity=Capacity
ListShipTitle_type=Type
StationCreated=Station was successfully created.
StationUpdated=Station was successfully updated.
StationDeleted=Station was successfully deleted.
CreateStationTitle=Create New Station
CreateStationSaveLink=Save
CreateStationShowAllLink=Show All Station Items
CreateStationIndexLink=Index
CreateStationLabel_id=Id:
CreateStationRequiredMessage_id=The Id field is required.
CreateStationTitle_id=Id
CreateStationLabel_name=Name:
CreateStationTitle_name=Name
CreateStationLabel_cargoSize=CargoSize:
CreateStationTitle_cargoSize=CargoSize
CreateStationLabel_onPlanet=OnPlanet:
CreateStationTitle_onPlanet=OnPlanet
EditStationTitle=Edit Station
EditStationSaveLink=Save
EditStationViewLink=View
EditStationShowAllLink=Show All Station Items
EditStationIndexLink=Index
EditStationLabel_id=Id:
EditStationRequiredMessage_id=The Id field is required.
EditStationTitle_id=Id
EditStationLabel_name=Name:
EditStationTitle_name=Name
EditStationLabel_cargoSize=CargoSize:
EditStationTitle_cargoSize=CargoSize
EditStationLabel_onPlanet=OnPlanet:
EditStationTitle_onPlanet=OnPlanet
ViewStationTitle=View
ViewStationDestroyLink=Destroy
ViewStationEditLink=Edit
ViewStationCreateLink=Create New Station
ViewStationShowAllLink=Show All Station Items
ViewStationIndexLink=Index
ViewStationLabel_id=Id:
ViewStationTitle_id=Id
ViewStationLabel_name=Name:
ViewStationTitle_name=Name
ViewStationLabel_cargoSize=CargoSize:
ViewStationTitle_cargoSize=CargoSize
ViewStationLabel_onPlanet=OnPlanet:
ViewStationTitle_onPlanet=OnPlanet
ListStationTitle=List
ListStationEmpty=(No Station Items Found)
ListStationDestroyLink=Destroy
ListStationEditLink=Edit
ListStationViewLink=View
ListStationCreateLink=Create New Station
ListStationIndexLink=Index
ListStationTitle_id=Id
ListStationTitle_name=Name
ListStationTitle_cargoSize=CargoSize
ListStationTitle_onPlanet=OnPlanet
TransportCreated=Transport was successfully created.
TransportUpdated=Transport was successfully updated.
TransportDeleted=Transport was successfully deleted.
CreateTransportTitle=Create New Transport
CreateTransportSaveLink=Save
CreateTransportShowAllLink=Show All Transport Items
CreateTransportIndexLink=Index
CreateTransportLabel_id=Id:
CreateTransportRequiredMessage_id=The Id field is required.
CreateTransportTitle_id=Id
CreateTransportLabel_startDate=StartDate:
CreateTransportTitle_startDate=StartDate
CreateTransportLabel_endDate=EndDate:
CreateTransportTitle_endDate=EndDate
CreateTransportLabel_toStation=ToStation:
CreateTransportTitle_toStation=ToStation
CreateTransportLabel_fromPlanet=FromPlanet:
CreateTransportTitle_fromPlanet=FromPlanet
CreateTransportLabel_fromStation=FromStation:
CreateTransportTitle_fromStation=FromStation
CreateTransportLabel_toPlanet=ToPlanet:
CreateTransportTitle_toPlanet=ToPlanet
EditTransportTitle=Edit Transport
EditTransportSaveLink=Save
EditTransportViewLink=View
EditTransportShowAllLink=Show All Transport Items
EditTransportIndexLink=Index
EditTransportLabel_id=Id:
EditTransportRequiredMessage_id=The Id field is required.
EditTransportTitle_id=Id
EditTransportLabel_startDate=StartDate:
EditTransportTitle_startDate=StartDate
EditTransportLabel_endDate=EndDate:
EditTransportTitle_endDate=EndDate
EditTransportLabel_toStation=ToStation:
EditTransportTitle_toStation=ToStation
EditTransportLabel_fromPlanet=FromPlanet:
EditTransportTitle_fromPlanet=FromPlanet
EditTransportLabel_fromStation=FromStation:
EditTransportTitle_fromStation=FromStation
EditTransportLabel_toPlanet=ToPlanet:
EditTransportTitle_toPlanet=ToPlanet
ViewTransportTitle=View
ViewTransportDestroyLink=Destroy
ViewTransportEditLink=Edit
ViewTransportCreateLink=Create New Transport
ViewTransportShowAllLink=Show All Transport Items
ViewTransportIndexLink=Index
ViewTransportLabel_id=Id:
ViewTransportTitle_id=Id
ViewTransportLabel_startDate=StartDate:
ViewTransportTitle_startDate=StartDate
ViewTransportLabel_endDate=EndDate:
ViewTransportTitle_endDate=EndDate
ViewTransportLabel_toStation=ToStation:
ViewTransportTitle_toStation=ToStation
ViewTransportLabel_fromPlanet=FromPlanet:
ViewTransportTitle_fromPlanet=FromPlanet
ViewTransportLabel_fromStation=FromStation:
ViewTransportTitle_fromStation=FromStation
ViewTransportLabel_toPlanet=ToPlanet:
ViewTransportTitle_toPlanet=ToPlanet
ListTransportTitle=List
ListTransportEmpty=(No Transport Items Found)
ListTransportDestroyLink=Destroy
ListTransportEditLink=Edit
ListTransportViewLink=View
ListTransportCreateLink=Create New Transport
ListTransportIndexLink=Index
ListTransportTitle_id=Id
ListTransportTitle_startDate=StartDate
ListTransportTitle_endDate=EndDate
ListTransportTitle_toStation=ToStation
ListTransportTitle_fromPlanet=FromPlanet
ListTransportTitle_fromStation=FromStation
ListTransportTitle_toPlanet=ToPlanet
UserCreated=User was successfully created.
UserUpdated=User was successfully updated.
UserDeleted=User was successfully deleted.
CreateUserTitle=Create New User
CreateUserSaveLink=Save
CreateUserShowAllLink=Show All User Items
CreateUserIndexLink=Index
CreateUserLabel_id=Id:
CreateUserRequiredMessage_id=The Id field is required.
CreateUserTitle_id=Id
CreateUserLabel_name=Name:
CreateUserTitle_name=Name
CreateUserLabel_password=<PASSWORD>:
CreateUserTitle_password=<PASSWORD>
CreateUserLabel_type=Type:
CreateUserTitle_type=Type
EditUserTitle=Edit User
EditUserSaveLink=Save
EditUserViewLink=View
EditUserShowAllLink=Show All User Items
EditUserIndexLink=Index
EditUserLabel_id=Id:
EditUserRequiredMessage_id=The Id field is required.
EditUserTitle_id=Id
EditUserLabel_name=Name:
EditUserTitle_name=Name
EditUserLabel_password=<PASSWORD>:
EditUserTitle_password=<PASSWORD>
EditUserLabel_type=Type:
EditUserTitle_type=Type
ViewUserTitle=View
ViewUserDestroyLink=Destroy
ViewUserEditLink=Edit
ViewUserCreateLink=Create New User
ViewUserShowAllLink=Show All User Items
ViewUserIndexLink=Index
ViewUserLabel_id=Id:
ViewUserTitle_id=Id
ViewUserLabel_name=Name:
ViewUserTitle_name=Name
ViewUserLabel_password=<PASSWORD>:
ViewUserTitle_password=<PASSWORD>
ViewUserLabel_type=Type:
ViewUserTitle_type=Type
ListUserTitle=List
ListUserEmpty=(No User Items Found)
ListUserDestroyLink=Destroy
ListUserEditLink=Edit
ListUserViewLink=View
ListUserCreateLink=Create New User
ListUserIndexLink=Index
ListUserTitle_id=Id
ListUserTitle_name=Name
ListUserTitle_password=<PASSWORD>
ListUserTitle_type=Type
UserCommissionCreated=UserCommission was successfully created.
UserCommissionUpdated=UserCommission was successfully updated.
UserCommissionDeleted=UserCommission was successfully deleted.
CreateUserCommissionTitle=Create New UserCommission
CreateUserCommissionSaveLink=Save
CreateUserCommissionShowAllLink=Show All UserCommission Items
CreateUserCommissionIndexLink=Index
CreateUserCommissionLabel_id=Id:
CreateUserCommissionRequiredMessage_id=The Id field is required.
CreateUserCommissionTitle_id=Id
CreateUserCommissionLabel_userId=UserId:
CreateUserCommissionRequiredMessage_userId=The UserId field is required.
CreateUserCommissionTitle_userId=UserId
CreateUserCommissionLabel_transportId=TransportId:
CreateUserCommissionRequiredMessage_transportId=The TransportId field is required.
CreateUserCommissionTitle_transportId=TransportId
EditUserCommissionTitle=Edit UserCommission
EditUserCommissionSaveLink=Save
EditUserCommissionViewLink=View
EditUserCommissionShowAllLink=Show All UserCommission Items
EditUserCommissionIndexLink=Index
EditUserCommissionLabel_id=Id:
EditUserCommissionRequiredMessage_id=The Id field is required.
EditUserCommissionTitle_id=Id
EditUserCommissionLabel_userId=UserId:
EditUserCommissionRequiredMessage_userId=The UserId field is required.
EditUserCommissionTitle_userId=UserId
EditUserCommissionLabel_transportId=TransportId:
EditUserCommissionRequiredMessage_transportId=The TransportId field is required.
EditUserCommissionTitle_transportId=TransportId
ViewUserCommissionTitle=View
ViewUserCommissionDestroyLink=Destroy
ViewUserCommissionEditLink=Edit
ViewUserCommissionCreateLink=Create New UserCommission
ViewUserCommissionShowAllLink=Show All UserCommission Items
ViewUserCommissionIndexLink=Index
ViewUserCommissionLabel_id=Id:
ViewUserCommissionTitle_id=Id
ViewUserCommissionLabel_userId=UserId:
ViewUserCommissionTitle_userId=UserId
ViewUserCommissionLabel_transportId=TransportId:
ViewUserCommissionTitle_transportId=TransportId
ListUserCommissionTitle=List
ListUserCommissionEmpty=(No UserCommission Items Found)
ListUserCommissionDestroyLink=Destroy
ListUserCommissionEditLink=Edit
ListUserCommissionViewLink=View
ListUserCommissionCreateLink=Create New UserCommission
ListUserCommissionIndexLink=Index
ListUserCommissionTitle_id=Id
ListUserCommissionTitle_userId=UserId
ListUserCommissionTitle_transportId=TransportId
| 33734d36a89f2706aed514d08784493198245f6e | [
"Java",
"INI"
] | 2 | Java | qbassqbass/north-american-octo-wookie | dfc74c6eff888c109d55b60f6689fecb14397aac | 174ba4eab49830230ccb67d0b1edb12a80123c72 |
refs/heads/master | <file_sep>import React, { Component } from 'react';
class Form extends Component {
constructor(props) {
super(props)
this.state = {
art: {},
isLoaded: false,
}
console.log(this.props.user_id)
// console.log(this.props.arts[0])
}
//************************* */
componentDidMount() {
this.getArt()
}
// ${foundUser.id}`
getArt() {
fetch('/users/1/arts/1')
//fetch(`/users/${this.props.user_id}/arts/${this.props.arts[this.state.art]}`)
.then(response => response.json())
.then (jsonedArt => {
this.setState({ art: jsonedArt, isLoaded: true})
// console.log (jsonedArt)
})
// .then(jsonedUser => this.setState({ user: jsonedUser }))
.catch(error => console.error(error))
}
//************************* */
//******************************* */
render() {
//console.log(this.props.update)
return (
<>
<form id={this.props.id} onSubmit={this.props.update}>
<div class="form-group">
<label for="exampleInputTitle">Title </label>
<input
onChange={this.props.change}
name={'title'}
placeholder={'title'}
type={'text'}
defaultValue={this.props.title}
id={'title'}
/>
</div>
<div class="form-group">
<label for="exampleInputImage">Image </label>
<input
onChange={this.props.change}
name={'img'}
placeholder={'img'}
type={'text'}
defaultValue={this.props.img}
id={'img'}
/>
</div>
<div class="form-group">
<label for="exampleInputDescription">Description </label>
<input
onChange={this.props.change}
name={'description'}
placeholder={'description'}
type={'text'}
defaultValue={this.props.description}
id={'description'}
/>
</div>
<div class="form-group">
<label for="exampleInputSize">Size </label>
<input
onChange={this.props.change}
name={'size'}
placeholder={'size'}
type={'text'}
defaultValue={this.props.size}
id={'size'}
/>
</div>
<div class="form-group">
<label for="exampleInputStyle">Style </label>
<input
onChange={this.props.change}
name={'style'}
placeholder={'style'}
type={'text'}
defaultValue={this.props.style}
id={'style'}
/>
</div>
<div class="form-group">
<label for="exampleInputMedium">Medium </label>
<input
onChange={this.props.change}
name={'medium'}
placeholder={'medium'}
type={'text'}
defaultValue={this.props.medium}
id={'medium'}
/>
</div>
<div class="form-group">
<label for="exampleInputMaterial">Material </label>
<input
onChange={this.props.change}
name={'materila'}
placeholder={'materila'}
type={'text'}
defaultValue={this.props.materila}
id={'materila'}
/>
</div>
<input type='submit' value='submite change' onClick={this.props.update}/>
</form>
</>
)
}
}
export default Form<file_sep>import React, { Component } from 'react';
import Arts from './Arts.js'
import Form from './FormUpdateArt.js'
class User extends Component {
constructor(props) {
super(props)
this.state = {
user: {},
isLoaded: false,
}
// this.handleDelete = this.handleDelete.bind(this)
}
componentDidMount() {
this.getUser()
}
getUser() {
fetch('/users/1')
//fetch(`/users/${this.state.user.id}`)
.then(response => response.json())
.then (jsonedUser => {
this.setState({ user: jsonedUser, isLoaded: true})
})
// .then(jsonedUser => this.setState({ user: jsonedUser }))
.catch(error => console.error(error))
}
//******************** */
render() {
console.log(this.state.user.arts)
return (
<>
<h1>Welcome {this.state.user.first_name} {this.state.user.last_name}!</h1>
{this.state.isLoaded === true && <Arts arts= {this.state.user.arts}/> }
<button> create </button>
<div className='box'>
<h3>personal information : </h3>
<h4><span>phone : </span>{this.state.user.phone}</h4>
<h4><span>address : </span>{this.state.user.address}</h4>
</div>
{/* {this.state.isLoaded &&
<Form
update = {this.handleUpdate} change= {this.handleChange}
user_id = {this.state.user.id}
arts = {this.state.user.arts}
title = {this.state.user.arts[0].title}
img = {this.state.user.arts[0].img}
/>
} */}
</>
)
}
}
export default User | ceb0c5d085e24585afd7830d4d00c10d235133c6 | [
"JavaScript"
] | 2 | JavaScript | kasyaro/Art-client | 35c130d6bdba04f9e1ff3b0116773ce66e9251f5 | 56aef02efd7b26a83367a02a99b6912e592522c6 |
refs/heads/master | <repo_name>dlevi309/pop-api-scraper<file_sep>/CHANGELOG.md
# Change Log
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
<a name="0.1.2"></a>
## [0.1.2](https://github.com/popcorn-official/pop-api-scraper/compare/0.1.1...0.1.2) (2018-01-01)
### Bug Fixes
* Deprecate v0.1.1, not published correctly ([474d55a](https://github.com/popcorn-official/pop-api-scraper/commit/474d55a))
<a name="0.1.1"></a>
## [0.1.1](https://github.com/popcorn-official/pop-api-scraper/compare/v0.1.0...v0.1.1) (2018-01-01)
### Bug Fixes
* **Cron:** Fix issue where cronjob does not start on creation ([#5](https://github.com/popcorn-official/pop-api-scraper/issues/5)) ([cdd965e](https://github.com/popcorn-official/pop-api-scraper/commit/cdd965e))
* **PopApiScraper:** Fix issue where status files are empty ([#6](https://github.com/popcorn-official/pop-api-scraper/issues/6)) ([9ac9975](https://github.com/popcorn-official/pop-api-scraper/commit/9ac9975))
<a name="0.1.0"></a>
# 0.1.0 (2017-12-27)
### Features
* **initial-release:** Initial relase for npm registery ([e8deafd](https://github.com/popcorn-official/pop-api-scraper/commit/e8deafd))
<file_sep>/src/providers/index.js
// Export the neseccary modules.
export AbstractProvider from './AbstractProvider'
export IProvider from './IProvider'
| 81fbf982833626fcbb22dbeef97413bfb59ace42 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | dlevi309/pop-api-scraper | 659701a4299a4563c9f0d8b3d199f3aaf086a848 | c28f7c175c6dc8d4a715faccd6763548bb945c2d |
refs/heads/master | <repo_name>shengxihu/HTML-CSS<file_sep>/banner/banner.js
function SlideShow(c) {
var a = document.getElementById("img_cont"),
f = a.getElementsByTagName("img"),
h = document.getElementById("pointer"),
n = h.getElementsByTagName("span"),
d = f.length,
c = c || 3000,
e = lastI = 3,
m;
function breakTime() {
m = setInterval(function () {
e = e + 1 >= d ? e + 1 - d : e + 1;
changeImage();
}, c)
}
function mouseControl() {
clearInterval(m)
}
function changeImage() {
f[lastI].style.display = "none";
n[lastI].className = "";
f[e].style.display = "block";
n[e].className = "on";
lastI = e;
}
f[e].style.display = "block";
a.onmouseover = mouseControl;
a.onmouseout = breakTime;
n[0].onclick=function(){
e=0;
changeImage();
}
n[1].onclick=function(){
e=1;
changeImage();
}
n[2].onclick=function(){
e=2;
changeImage();
}
n[3].onclick=function(){
e=3;
changeImage();
}
}
SlideShow(2000);
| ac91bfd72d24a708fd26a3f201c16765b6510da8 | [
"JavaScript"
] | 1 | JavaScript | shengxihu/HTML-CSS | 171828e9dafa16ed5e087d5dd8f90c0de5739cb1 | e2355fbb79ebf55f4cae4ec6b09cf04eb8c07190 |
refs/heads/master | <file_sep>"use strict"
module.exports= {
computeAverage: function (a,b,c){
return (a+b+c)/3
},
computeFatorial: function(){
},
computeTempCtoF:function(){
},
computeTempFtoC:function (){
}
} | fde7e28b69989a6ab07a6ccaec336c1ee3543fb7 | [
"JavaScript"
] | 1 | JavaScript | matthewm1234/folder | c63e2079bcd14a68207abc08c2cf40e0f5095b8d | b30a80c36cf6f028bb8492b39705ca8bc21a05b2 |
refs/heads/master | <repo_name>smit1712/Lingo<file_sep>/Controllers/LingoController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace Lingo_WebApp.Controllers
{
[ApiController]
[Route("[Controller]")]
public class LingoController : Controller
{
private static readonly string[] _lingoWords = new[]{
"Afijn", "Credo", "Deern", "Duaal", "Echec", "Egard", "Koket", "Ethos", "Fluks", "Frêle"
};
private LingoWord _currentWord { get; set; }
private readonly ILogger<LingoController> _logger;
public LingoController(ILogger<LingoController> logger)
{
_logger = logger;
}
[HttpGet]
public async Task<ActionResult<LingoWord>> Get()
{
Random rn = new Random(Guid.NewGuid().GetHashCode());
if (_currentWord == null)
{
_currentWord = new LingoWord(_lingoWords.ElementAt(rn.Next(0, _lingoWords.Length - 1)));
}
return _currentWord;
}
[HttpPost, ActionName("Guess"), Route("Guess")]
public async Task<ActionResult<Item>> GetGuess(Item word)
{
try
{
_currentWord.Check(word.name);
return new Item { isComplete = true };
}
catch (Exception ex)
{
return new Item { isComplete = false };
}
}
[HttpGet, Route("Reset")]
public async Task<ActionResult<LingoWord>> Reset()
{
Random rn = new Random(Guid.NewGuid().GetHashCode());
_currentWord = new LingoWord(_lingoWords.ElementAt(rn.Next(0, _lingoWords.Length - 1)));
return _currentWord;
}
}
public class Item
{
public bool isComplete { get; set; }
public string name { get; set; }
}
}
<file_sep>/LingoWord.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Lingo_WebApp
{
public class LingoWord
{
public List<LingoLetter> CorrectWord { get; } = new List<LingoLetter>();
public List<LingoLetter> GuessedWord { get; } = new List<LingoLetter>();
public LingoWord(string word)
{
if (word.Length != 5) throw new ArgumentException("This Lingo board only supports 5 letter words");
word = word.ToLowerInvariant();
foreach (char character in word)
{
CorrectWord.Add(new LingoLetter(character));
}
}
public void SetGuessedWord(string word)
{
if (word.Length != 5) throw new ArgumentException("This Lingo board only supports 5 letter words");
GuessedWord.Clear();
word = word.ToLowerInvariant();
foreach (char character in word)
{
GuessedWord.Add(new LingoLetter(character));
}
}
}
public class LingoLetter
{
public Status LetterStatus { get; set; }
public char character { get; set; }
public LingoLetter(char letter)
{
character = letter;
LetterStatus = Status.unknown;
}
}
public enum Status
{
unknown, wrongLocation, Correct
}
public static class extensions
{
public static void Check(this LingoWord lingoWord, string word)
{
if (string.IsNullOrEmpty(word)) return;
word = word.ToLowerInvariant();
try
{
lingoWord.SetGuessedWord(word);
List<char> correctLetters = new List<char>();
foreach (LingoLetter letter in lingoWord.CorrectWord)
{
if (word.Contains(letter.character))
{
correctLetters.Add(letter.character);
}
}
lingoWord.GuessedWord.ForEach(l => l.LetterStatus = Status.unknown);
int i = 0;
foreach (char character in word)
{
if (correctLetters.Contains(character))
{
lingoWord.GuessedWord[i].LetterStatus = Status.wrongLocation;
}
if (character == lingoWord.CorrectWord[i].character)
{
lingoWord.GuessedWord[i].LetterStatus = Status.Correct;
}
i++;
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
}
}
| c73c6325ec5ad33abd8624764d5e0e3e3ca1dbb5 | [
"C#"
] | 2 | C# | smit1712/Lingo | 3bcd5885f18feb179a253f23790e3a199b5b145d | 17637e688408cee93b087fe9542b68be820234b2 |
refs/heads/master | <repo_name>LTESoftware/Saber<file_sep>/PreSaber-Nuevo/src/app/models/advancehasuser.ts
export class Advancehasuser {
constructor(public id: number,
public description: string,
public content: string,
public createdAt: any,
public updatedAt: any,
public EquipMentHasUser: number,
public SectionHasResources: number,
public ResourceHasUser: number){}
}
<file_sep>/PreSaber-Web/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {routing,appRoutingProviders} from "./app.rounting";
import {FormsModule} from "@angular/forms";
import {HttpClientModule} from "@angular/common/http";
import { AppComponent } from './app.component';
import { LoginComponent } from './components/login/login.component';
import { HomeComponent } from './components/home/home.component';
import { RegistroComponent } from './components/registro/registro.component';
import { VerificarCodigoComponent } from './components/verificar-codigo/verificar-codigo.component';
import { HomeAdminComponent } from './components/home-admin/home-admin.component';
import { HomeEstudianteComponent } from './components/home-estudiante/home-estudiante.component';
import { HomeProfesorComponent } from './components/home-profesor/home-profesor.component';
import { CrearContratoComponent } from './components/administrador/crear-contrato/crear-contrato.component';
import { CrearUsuarioComponent } from './components/administrador/crear-usuario/crear-usuario.component';
import { CrearTypoUsuarioComponent } from './components/administrador/crear-typo-usuario/crear-typo-usuario.component';
import { CrearCursoComponent } from './components/administrador/crear-curso/crear-curso.component';
import { CrearSeccionComponent } from './components/administrador/crear-seccion/crear-seccion.component';
import { PerfilUsuarioComponent } from './components/administrador/perfil-usuario/perfil-usuario.component';
@NgModule({
declarations: [
AppComponent,
LoginComponent,
HomeComponent,
RegistroComponent,
VerificarCodigoComponent,
HomeAdminComponent,
HomeEstudianteComponent,
HomeProfesorComponent,
CrearContratoComponent,
CrearUsuarioComponent,
CrearTypoUsuarioComponent,
CrearCursoComponent,
CrearSeccionComponent,
PerfilUsuarioComponent
],
imports: [
BrowserModule,
routing,
FormsModule,
HttpClientModule
],
providers: [
appRoutingProviders
],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/PreSaber-Nuevo/src/app/models/evaluacion/pregunta.ts
export class Pregunta{
constructor(
public id_pregunta: any,
public sesion_id_fk: any,
public contexto: any,
public pregunta: any,
public justificacion: any,
public compentencia_id_fk: any,
public componente_id_fk: any
)
{
}
}
<file_sep>/php-backend/App/componentes/profesor/examen_taller.php
<?php
$app->post('/profesor/listarExamenTaller', function () use ($app) {
$helper = new helper();
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$sql = "select * from evaluacion.examen_taller order by id_examen desc limit 200 ";
$conexion = new conexPG();
$r = $conexion->consultaComplejaAso($sql);
$data = [
'code' => 'LTE-001',
'data' => $r
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/cargarExamenTaller', function () use ($app) {
$helper = new helper();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$parametros = json_decode($json);
$id_examen = (isset($parametros->id_examen)) ? $parametros->id_examen : null;
$sql = "select * from evaluacion.examen_taller et
join evaluacion.base_examen be on et.base_examen_id_fk=be.id_base_examen
join evaluacion.configuracion con on et.id_examen=con.examen_id_fk where et.id_examen='$id_examen';";
$conexion = new conexPG();
$r1 = $conexion->consultaComplejaNorAso($sql);
$sql = "select * from evaluacion.sesion s where s.examen_taller_id_fk = '$id_examen' order by s.id_sesion desc limit 200";
$r = $conexion->consultaComplejaAso($sql);
$data = [
'code' => 'LTE-001',
'data' => [
'data' => $r1,
'sesion' => $r
]
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => ''
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/actualizarTallerExamen', function () use ($app) {
$helper = new helper();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$parametros = json_decode($json);
$id_examen = (isset($parametros->id_examen)) ? $parametros->id_examen : null;
$descripcion_examen = (isset($parametros->descripcion_examen)) ? $parametros->descripcion_examen : null;
$estado_examen = (isset($parametros)) ? $parametros->estado_examen : null;
$fechaActualizacion = date('Y-m-d H:i');
$conexion = new conexPG();
$sql = "UPDATE evaluacion.examen_taller
SET descripcion_examen='$descripcion_examen', fecha_actualizacion_examen='$fechaActualizacion', estado_examen='$estado_examen'
WHERE id_examen='$id_examen'";
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-001'
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => ''
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/crearPregunta', function () use ($app) {
$helper = new helper();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$parametros = json_decode($json);
$sesion_id_fk = (isset($parametros->sesion_id_fk)) ? $parametros->sesion_id_fk : null;
$contexto = htmlspecialchars((isset($parametros->contexto)) ? $parametros->contexto : null, ENT_QUOTES);
$pregunta = htmlspecialchars((isset($parametros->pregunta)) ? $parametros->pregunta : null, ENT_QUOTES);
$justificacion = htmlspecialchars((isset($parametros->justificacion)) ? $parametros->justificacion : null, ENT_QUOTES);
$compentencia_id_fk = (isset($parametros->compentencia_id_fk)) ? $parametros->compentencia_id_fk : null;
$componente_id_fk = (isset($parametros->componente_id_fk)) ? $parametros->componente_id_fk : null;
$conexion = new conexPG();
$sql = "INSERT INTO evaluacion.pregunta(
sesion_id_fk, contexto, pregunta, justificacion, compentencia_id_fk, componente_id_fk)
VALUES ('$sesion_id_fk', '$contexto', '$pregunta', '$justificacion', '$compentencia_id_fk', '$componente_id_fk');";
$conexion->consultaSimple($sql);
$data = [
'code'=>'LTE-001'
];
} else {
$data = [
'code' => 'LTE-013',
'line'=>'140'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/actualizarPregunta', function () use ($app) {
$helper = new helper();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$parametros = json_decode($json);
$id_pregunta = (isset($parametros->id_pregunta)) ? $parametros->id_pregunta : null;
$contexto = htmlspecialchars((isset($parametros->contexto)) ? $parametros->contexto : null, ENT_QUOTES);
$pregunta = htmlspecialchars((isset($parametros->pregunta)) ? $parametros->pregunta : null, ENT_QUOTES);
$justificacion = htmlspecialchars((isset($parametros->justificacion)) ? $parametros->justificacion : null, ENT_QUOTES);
$compentencia_id_fk = (isset($parametros->compentencia_id_fk)) ? $parametros->compentencia_id_fk : null;
$componente_id_fk = (isset($parametros->componente_id_fk)) ? $parametros->componente_id_fk : null;
$conexion = new conexPG();
$sql = "UPDATE evaluacion.pregunta
SET contexto='$contexto', pregunta='$pregunta', justificacion='$justificacion', compentencia_id_fk='$compentencia_id_fk', componente_id_fk='$componente_id_fk'
WHERE id_pregunta='$id_pregunta';";
$conexion->consultaSimple($sql);
$data = [
'code'=>'LTE-007'
];
} else {
$data = [
'code' => 'LTE-013',
'line'=>'140'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});<file_sep>/php-backend/App/componentes/profesor/componente.php
<?php
$app->post('/profesor/crearComponente', function () use ($app) {
$json = $app->request->post('json', null);
$helper = new helper();
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$parametros = json_decode($json);
$fecha_creacion = date('Y-m-d H:i:s');
$fecha_actualizacion = date('Y-m-d H:i:s');
$descripcion = (isset($parametros->descripcion_componente)) ? $parametros->descripcion_componente : null;
$conexion = new conexPG();
$sql = "INSERT INTO evaluacion.componente(
descripcion_componente, fecha_creacion_componente, fecha_actualizacion_componente)
VALUES ('$descripcion', '$fecha_creacion', '$fecha_actualizacion');";
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-001'
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/listarComponente', function () use ($app) {
$helper = new helper();
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$conexion = new conexPG();
$sql = "select c.* from evaluacion.componente c order by c.id_componente desc limit 200 ";
$r=$conexion->consultaComplejaAso($sql);
$data = [
'code' => 'LTE-001',
'data'=>$r
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/actualizarComponente', function () use($app){
$json = $app->request->post('json', null);
$helper = new helper();
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$parametros = json_decode($json);
$fecha_actualizacion = date('Y-m-d H:i:s');
$descripcion = (isset($parametros->descripcion_componente)) ? $parametros->descripcion_componente : null;
$id_componente= (isset($parametros->id_componente)) ? $parametros->id_componente : null;
$conexion = new conexPG();
$sql = "UPDATE evaluacion.componente
SET descripcion_componente='$descripcion', fecha_actualizacion_componente='$fecha_actualizacion'
WHERE id_componente='$id_componente';";
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-001'
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});<file_sep>/PreSaber-Nuevo/src/app/components/administrador/crear-contrato/crear-contrato.component.ts
import {Component, OnInit} from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {ElementsService} from "../../../services/elements.service";
import {ContratoEntidad} from "../../../models/contratoEntidad";
import {Ciudades} from "../../../models/ciudades";
import {CrearContratoService} from "../../../services/crearContrato.service";
import {GLOBAL} from "../../../services/global";
import {User} from "../../../models/user";
import {Ficha} from "../../../models/ficha";
import {Curso} from "../../../models/curso";
import {CursoService} from "../../../services/curso.service";
import {FichaService} from "../../../services/ficha.service";
import {UsuarioService} from "../../../services/usuario.service";
import {Rol} from "../../../models/rol";
@Component({
selector: 'app-crear-contrato',
templateUrl: './crear-contrato.component.html',
styleUrls: ['./crear-contrato.component.css'],
providers: [ElementsService, CrearContratoService, CursoService, FichaService, UsuarioService]
})
export class CrearContratoComponent implements OnInit {
public userIdentity: any;
public objContratoEntidad: ContratoEntidad;
public imagenContrato: Array<File>;
public listCiudades: Array<Ciudades>;
public listContrato: Array<ContratoEntidad>;
public token: string;
public r: any;
public url: any;
public filtro: string;
public objFicha: Ficha;
public objCurso: Curso;
public listCurso: Array<Curso>;
public listFicha: Array<Object>;
public archivoExcel: Array<File>;
public vistaCrearficha: any;
public vistaCargarUsuarios: any;
public filtroFicha: string;
public objUsuario: User;
public listRol: Array<Rol>;
public listUsuariosFicha: Array<User>;
public cantidadUsuariosFicha: any;
public filtroUsuariosFicha: string;
public listUsuarioRegistrados: Array<User>;
position = "top-right";
constructor(private _ElementService: ElementsService, private _contratoService: CrearContratoService,
private _Router: Router, private _Route: ActivatedRoute, private _cursoService: CursoService, private _fichaService: FichaService, private _usuarioService: UsuarioService) {
this.userIdentity = this._ElementService.getUserIdentity();
this.objContratoEntidad = new ContratoEntidad('', '', '', '000',
'', '000', '000', '', null, null);
this.objCurso = new Curso('', '', '', '000', '', '', '');
this.token = localStorage.getItem('token');
this.objFicha = new Ficha('', '', '', '', '', '000',
0, 0, '', '', '');
this.objUsuario = new User(null, 0, '', '', '', '',
'', null, null, null, '', null,
null, null, '1');
this.url = GLOBAL.urlFiles;
this.filtro = '';
this.filtroFicha = '';
this.filtroUsuariosFicha = '';
}
ngOnInit() {
this._ElementService.pi_poValidarUsuario('CrearContratoComponent');
this.cargarCiudades();
$("#loader").hide();
$("#loader1").hide();
$("#loaderCrearFicha").hide();
$("#loaderTablaCurso").hide();
$("#loaderTablaFichas").hide();
$("#btnCargarUsuarios").hide();
$("#cargarImagen").hide();
$("#loaderExcel").hide();
$("#seccionFicha").toggle();
$("#seccionUsuarioFicha").toggle();
$("#loaderTablaUsuariosFicha").hide();
$("#loaderCrearUsuario").hide();
$("#LoaderTablaRegistrados").hide();
$("#btnAsociar").hide();
$("#informacionUsuario").hide();
this.listarContratos();
this.listarRol();
}
openMyModal(event) {
document.querySelector('#' + event).classList.add('md-show');
}
closeMyModal(event) {
((event.target.parentElement.parentElement).parentElement).classList.remove('md-show');
}
cargarImagen($event) {
this.imagenContrato = <Array<File>>$event.target.files;
console.log(this.imagenContrato);
}
cargarCiudades() {
this._contratoService.listarCiudades(this.token).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status = 'success') {
this.listCiudades = respuesta.data;
}
}, error2 => {
}
)
}
crearContrato() {
this._ElementService.pi_poBontonDesabilitar('#btnCrearRegistro');
$("#loader").show();
this._contratoService.crearContrato(this.token, ['imagen'], this.imagenContrato, this.objContratoEntidad).then(
(resultado) => {
this.r = resultado;
this._ElementService.pi_poValidarCodigo(this.r);
if (this.r.status == 'success') {
this._ElementService.pi_poAlertaSuccess('Contrato creado de forma correcta', 'Contrato');
this._ElementService.pi_poBotonHabilitar('#btnCrearRegistro');
this.listarContratos();
this.limpiarCampos();
$("#loader").hide();
} else {
this._ElementService.pi_poAlertaError(this.r.msg, 'Contrato');
this._ElementService.pi_poBotonHabilitar('#btnCrearRegistro');
$("#loader").hide();
}
},
(error) => {
console.log(error);
}
)
}
listarContratos() {
$("#loader1").show();
this._contratoService.listarContrato(this.token).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status = 'success') {
this.listContrato = respuesta.data;
$("#loader1").hide();
} else {
$("#loader1").hide();
}
}, error2 => {
}
)
}
filtrar() {
$("#preLoadertabla").show();
let listContrato1 = new Array<ContratoEntidad>();
let validacion = 1;
for (let i in this.listContrato) {
if (this.listContrato[i].descripcion == this.filtro || this.listContrato[i].descripcion_ciudad == this.filtro) {
listContrato1.push(this.listContrato[i]);
this.listContrato = listContrato1;
$("#preLoadertabla").hide();
validacion = 0;
break;
}
}
if (validacion == 1) {
this._contratoService.filtrarContrato(this.filtro, this.token).subscribe(
respuestaF => {
this._ElementService.pi_poValidarCodigo(respuestaF);
if (respuestaF.status == 'success') {
this.listContrato = respuestaF.data;
$("#preLoadertabla").hide();
} else {
this._ElementService.pi_poAlertaWarning('No se encontraron resultado con el filtro: ' + this.filtro, 'Filtro');
this.listarContratos();
$("#preLoadertabla").hide();
}
}, error => {
}
)
}
}
actualizarContrato() {
this._ElementService.pi_poBontonDesabilitar('#actualizarRegistro');
$('#loader').show();
this._contratoService.actualizarContrato(this.token, ['imagen'], this.imagenContrato, this.objContratoEntidad).then(
(resultado) => {
this.r = resultado;
this._ElementService.pi_poValidarCodigo(this.r);
if (this.r.status == 'success') {
this._ElementService.pi_poAlertaSuccess('Contrato actualizado de forma correcta.', 'Contrato');
this._ElementService.pi_poBotonHabilitar('#actualizarRegistro');
this.listarContratos();
this.limpiarCampos();
$("#loader").hide();
} else {
this._ElementService.pi_poAlertaError(this.r.msg, 'Contrato');
this._ElementService.pi_poBotonHabilitar('#actualizarRegistro');
$("#loader").hide();
}
},
(error) => {
console.log(error);
}
)
}
limpiarCampos() {
this.objContratoEntidad = new ContratoEntidad('', '', '', '000', '',
'000', '000', '', null, null);
}
seleccionarContrato(contrato) {
this._ElementService.pi_poBontonDesabilitar('#btnCrearRegistro');
this.objContratoEntidad = contrato;
this._ElementService.pi_poAlertaWarning('Se selecciono el contrato ' + this.objContratoEntidad.descripcion + ' de la ciudad de ' + this.objContratoEntidad.descripcion_ciudad, 'Seleccion contrato');
this._ElementService.pi_poBotonHabilitar("#actualizarRegistro")
}
//Ficha metodos
cargarFichas(contrato) {
this.limpiarCamposFicha();
this._ElementService.pi_poBontonDesabilitar('#btnActualizarFicha');
this.objContratoEntidad = contrato;
this.listarFichas();
this.objFicha.contrato_entidad_id_fk = this.objContratoEntidad.id;
$("#seccionContrato").toggle('500');
$("#seccionFicha").toggle('1000');
let validacion = localStorage.getItem('variableLoader');
console.log(validacion);
console.log(this.objContratoEntidad.id);
$("#loaderExcel").hide();
if (validacion == null) {
console.log('entro');
$("#loaderExcel").hide();
} else if (validacion == this.objContratoEntidad.id) {
console.log('entro1');
$("#loaderExcel").show();
}
}
volverContrato() {
$("#seccionFicha").toggle('500');
$("#seccionContrato").toggle('1000');
}
listarCursos() {
this.listCurso = new Array<Curso>();
$("#loader1").show();
this._cursoService.listarCurso(this.token).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.listCurso = respuesta.data;
console.log(this.listCurso);
$("#loader1").hide();
}
}, error2 => {
}
)
}
seleccionarCurso(curso) {
this.objCurso = curso;
this.objFicha.curso_id_fk = this.objCurso.id;
this._ElementService.pi_poVentanaAlerta('Cuidado!', 'Se selecciono el curso: ' + this.objCurso.descripcion + '.')
}
limpiarCamposFicha() {
this.objFicha = new Ficha('', '', '', '', '', '000',
0, 0, '', '', '');
}
crearFicha() {
$("#loaderCrearFicha").show();
this._ElementService.pi_poBontonDesabilitar('#btnCrearFicha');
if (this.objFicha.usuarios_maximos > this.objFicha.usuarios_minimos) {
this._fichaService.crearFicha(this.objFicha, this.token).subscribe(
respuesta => {
if (respuesta.status == 'success') {
this._ElementService.pi_poAlertaSuccess(respuesta.msg, 'Ficha');
this.limpiarCamposFicha();
this.listarFichas();
this._ElementService.pi_poBotonHabilitar('#btnCrearFicha');
$("#loaderCrearFicha").hide();
} else {
this._ElementService.pi_poAlertaError(respuesta.msg, 'Ficha');
$("#loaderCrearFicha").hide();
}
}, error2 => {
}
)
} else {
this._ElementService.pi_poVentanaAlerta('Error al crear.', 'Lo sentimos, Usuarios maximos debe ser mayor a usuarios minimos.');
}
}
actualizarFicha() {
$("#loaderCrearFicha").show();
this._ElementService.pi_poBontonDesabilitar('#btnActualizarFicha');
if (this.objFicha.usuarios_maximos > this.objFicha.usuarios_minimos) {
this._fichaService.actualizarFicha(this.objFicha, this.token).subscribe(
respuesta => {
if (respuesta.status == 'success') {
this._ElementService.pi_poAlertaSuccess(respuesta.msg, 'Ficha');
this.limpiarCamposFicha();
this.listarFichas();
this._ElementService.pi_poBotonHabilitar('#btnCrearFicha');
$("#loaderCrearFicha").hide();
} else {
this._ElementService.pi_poAlertaError(respuesta.msg, 'Ficha');
this._ElementService.pi_poBotonHabilitar('#btnActualizarFicha');
$("#loaderCrearFicha").hide();
}
}, error2 => {
}
)
} else {
this._ElementService.pi_poVentanaAlerta('Error al crear.', 'Lo sentimos, Usuarios maximos debe ser mayor a usuarios minimos.');
}
}
listarFichas() {
$("#loaderTablaFichas").show();
this._fichaService.listarFicha(this.objContratoEntidad, this.token).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status = 'success') {
if (respuesta.data != 0) {
this.listFicha = respuesta.data;
} else {
this.listFicha = [];
}
$("#loaderTablaFichas").hide();
} else {
this._ElementService.pi_poAlertaError(respuesta.msg, 'Listado de fichas');
$("#loaderTablaFichas").hide();
}
}, error2 => {
}
)
}
seleccionarFicha(ficha) {
this._ElementService.pi_poBotonHabilitar('#btnActualizarFicha');
this.objCurso.id = ficha.idcurso;
this.objCurso.descripcion = ficha.descripcioncurso;
this.objFicha = ficha;
this.objFicha.curso_id_fk = ficha.idcurso;
this._ElementService.pi_poAlertaWarning('Se selecciono la ficha: ' + this.objFicha.descripcion, 'Seleccion');
this._ElementService.pi_poBontonDesabilitar('#btnCrearFicha');
}
vistaCargarUusario(parametros) {
if (parametros == 1) {
$("#botonesFicha").toggle(100);
$("#btnCargarUsuarios").toggle(100);
$("#cargarImagen").toggle(100);
} else {
$("#botonesFicha").toggle(100);
$("#btnCargarUsuarios").toggle(100);
$("#cargarImagen").toggle(100);
}
}
descargarPlantilla() {
window.open(this.url + '/archivos_estandar/Plantilla_Estudiantes_Ficha_LTE.xlsx');
}
cargarExcel(event) {
this.archivoExcel = <Array<File>>event.target.files;
}
cargarEstudiantes() {
localStorage.setItem('variableLoader', this.objContratoEntidad.id);
$("#loaderExcel").show();
this._ElementService.pi_poBontonDesabilitar('#btnCrearRegistro');
$("#loader").show();
this._fichaService.cargarEstudiantes(this.token, ['excel'], this.archivoExcel, this.objFicha).then(
(resultado) => {
this.r = resultado;
this._ElementService.pi_poValidarCodigo(this.r);
if (this.r.status == 'success') {
localStorage.removeItem('variableLoader');
this.listarFichas();
$("#loaderExcel").hide();
console.log(this.r);
} else {
localStorage.removeItem('variableLoader');
$("#loaderExcel").hide();
console.log(this.r);
}
},
(error) => {
console.log(error);
}
)
}
filtrarFicha() {
$("#loaderTablaFichas").show();
this._fichaService.filtrarFicha(this.filtroFicha, this.token, this.objContratoEntidad).subscribe(
respuestaF => {
this._ElementService.pi_poValidarCodigo(respuestaF);
if (respuestaF.status == 'success') {
this.listFicha = respuestaF.data;
$("#loaderTablaFichas").hide();
} else {
this._ElementService.pi_poAlertaWarning('No se encontraron resultado con el filtro: ' + this.filtro, 'Filtro');
this.listarFichas();
$("#loaderTablaFichas").hide();
}
}, error => {
}
)
}
//Usuarios metodos
volverFicha() {
$("#seccionUsuarioFicha").toggle(200);
$("#seccionFicha").toggle(200);
}
cargarEstudiante(ficha) {
this._ElementService.pi_poBotonHabilitar('#btnCrearUsuario');
this._ElementService.pi_poBontonDesabilitar('#btnActualizarUsuario');
this.objFicha = ficha;
this.listarUsuariosFicha();
$("#seccionFicha").toggle(200);
$("#seccionUsuarioFicha").toggle(200);
}
listarRol() {
this._fichaService.listarRolEstudiante().subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
this.listRol = respuesta.data;
}, error => {
}
)
}
listarUsuariosFicha() {
$("#loaderTablaUsuariosFicha").show();
this._fichaService.listarUsuariosFicha(this.objFicha, this.token).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status = 'success') {
if (respuesta.data != 0) {
this.listUsuariosFicha = respuesta.data;
this.cantidadUsuariosFicha = this.listUsuariosFicha.length;
$("#loaderTablaUsuariosFicha").hide();
} else {
this.listUsuariosFicha = new Array<User>();
$("#loaderTablaUsuariosFicha").hide();
}
} else {
this._ElementService.pi_poVentanaAlerta(respuesta.code, respuesta.msg);
}
}, error2 => {
}
)
}
crearUsuarioFicha() {
this._ElementService.pi_poBontonDesabilitar("#btnCrearUsuario");
$("#loaderCrearUsuario").show();
this._fichaService.crearUsuarioFicha(this.objUsuario, this.token, this.objContratoEntidad.id, this.objFicha.id).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this._ElementService.pi_poAlertaSuccess('Usuario creado de fomra correcta', 'Usuario');
this.limpiarCamposUsuario();
this._ElementService.pi_poBotonHabilitar("#btnCrearUsuario");
this.listarUsuariosFicha();
$("#loaderCrearUsuario").hide();
} else {
this._ElementService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
this._ElementService.pi_poBotonHabilitar("#btnCrearUsuario");
$("#loaderCrearUsuario").hide();
}
}, error2 => {
}
)
}
limpiarCamposUsuario() {
this.objUsuario = new User(null, 0, '', '', '', '',
'', null, null, null, '', null,
null, null, '1');
}
seleccionarUsuario(usuarios) {
this._ElementService.pi_poBontonDesabilitar('#btnCrearUsuario');
this._ElementService.pi_poBotonHabilitar('#btnActualizarUsuario');
this.objUsuario = usuarios;
this._ElementService.pi_poAlertaMensaje("Se selecciono el usuario: " + this.objUsuario.documento + '-' + this.objUsuario.nombre, 'Usuario seleccionado');
}
actualizarUsuario() {
this._ElementService.pi_poBontonDesabilitar('#btnActualizarUsuario');
$('#loaderCrearUsuario').show();
this._usuarioService.actualizarUsuarioAdministrador(this.objUsuario, this.token).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.limpiarCamposUsuario();
this.listarUsuariosFicha();
$('#loaderCrearUsuario').hide();
this._ElementService.pi_poBotonHabilitar('#btnCrearUsuario');
this._ElementService.pi_poBontonDesabilitar('#btnActualizarUsuario');
this._ElementService.pi_poAlertaSuccess(respuesta.msg, 'Usuario');
} else if (respuesta.status == 'error') {
this._ElementService.pi_poBotonHabilitar('#btnActualizarUsuario');
$('#loaderCrearUsuario').hide();
this._ElementService.pi_poAlertaError(respuesta.msg, 'Usuario');
}
}, error2 => {
})
}
filtrarUsuariosFicha() {
$("#loaderTablaUsuariosFicha").show();
let listusuario1 = new Array<User>();
let validacion = 1;
for (let i in this.listUsuariosFicha) {
if (this.listUsuariosFicha[i].documento == this.filtroUsuariosFicha || this.listUsuariosFicha[i].correo == this.filtroUsuariosFicha || this.listUsuariosFicha[i].nombre == this.filtroUsuariosFicha) {
listusuario1.push(this.listUsuariosFicha[i]);
this.listUsuariosFicha = listusuario1;
$("#loaderTablaUsuariosFicha").hide();
validacion = 0;
break;
}
}
if (validacion == 1) {
this._fichaService.filtrarUsuariosFicha(this.filtroUsuariosFicha, this.token, this.objFicha).subscribe(
respuestaF => {
this._ElementService.pi_poValidarCodigo(respuestaF);
if (respuestaF.status == 'success') {
this.listUsuariosFicha = respuestaF.data;
$("#loaderTablaUsuariosFicha").hide();
} else {
this._ElementService.pi_poAlertaWarning('No se encontraron resultado con el filtro: ' + this.filtro, 'Filtro');
this.listarUsuariosFicha();
$("#loaderTablaUsuariosFicha").hide();
}
}, error => {
}
)
}
}
listarUsuarios() {
$("#LoaderTablaRegistrados").show();
this._usuarioService.listarUsuarios(this.token).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.listUsuarioRegistrados = respuesta.data;
$("#LoaderTablaRegistrados").hide();
} else {
this._ElementService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
$("#LoaderTablaRegistrados").hide();
}
}, error2 => {
}
)
}
seleccionarUsuarioRegistrado(usuario) {
if (usuario.rol_descripcion != 'ADMINISTRADOR' && usuario.rol_descripcion != 'administrador') {
this.objUsuario = usuario;
this._ElementService.pi_poAlertaWarning('Se selecciono el usuario ' + this.objUsuario.nombre + ' con documento ' + this.objUsuario.documento, 'USUARIO');
} else {
this._ElementService.pi_poVentanaAlertaWarning('Error', 'Lo sentimos, No se puede seleccionar el usuario con rol ADMINISTRADOR.');
}
}
usuarioExistente(validacion) {
if (validacion == 0) {
$("#seccionDatos").show();
$("#btnActualizarUsuario").show();
$("#btnCrearUsuario").show();
$("#btnAsociar").hide();
$("#informacionUsuario").hide();
} else {
this.listarUsuarios();
$("#seccionDatos").hide();
$("#btnActualizarUsuario").hide();
$("#btnCrearUsuario").hide();
$("#btnAsociar").show();
$("#informacionUsuario").show();
}
}
crearUsuarioExistente() {
this._fichaService.crearUsuarioExistenteFicha(this.objUsuario, this.token, this.objContratoEntidad.id, this.objFicha.id).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.limpiarCamposUsuario();
this.listarUsuariosFicha();
this._ElementService.pi_poAlertaSuccess(respuesta.code, respuesta.msg);
} else {
this._ElementService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
}
}, error2 => {
}
)
}
limpiarCamposUsuarioFicha() {
this.objUsuario = new User(null, 0, '', '', '', '',
'', null, null, null, '', null,
null, null, '1');
}
}
<file_sep>/php-backend/App/componentes/profesor/ficha.php
<?php
$app->post('/profesor/FichasProfesor', function () use ($app) {
$helper = new helper();
$autorizacion = $app->request->post('token', null);
if ($autorizacion != null) {
$validacionToken = $helper->authCheck($autorizacion);
if ($validacionToken == true) {
$conexion = new conexPG();
$usuarioToken = $helper->authCheck($autorizacion, true);
$sql = "select * from seguridad.usuario where id ='$usuarioToken->sub' and estado ='ACTIVO'";
$r = $conexion->consultaComplejaNorAso($sql);
if ($r != 0) {
$sql = "select f.* from presaber.ficha f
join presaber.ficha_usuario fu on f.id=fu.ficha_id_fk
join seguridad.usuario u on fu.usuario_id_fk= u.id where u.id='$usuarioToken->sub'";
$r = $conexion->consultaComplejaAso($sql);
if ($r != 0) {
$data = [
'code' => 'LTE-001',
'data' => $r
];
} else {
$data = [
'code' => 'LTE-000',
'status' => 'error',
'msg' => 'Lo sentimos, notienes fichas asociadas.'
];
}
} else {
$data = [
'code' => 'LTE-013',
'line'=>'33-ficha'
];
}
} else {
$data = [
'code' => 'LTE-013',
'line'=>'39-ficha'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/estudiantesFicha', function () use ($app) {
$helper = new helper();
$autorizacion = $app->request->post('token', null);
if ($autorizacion != null) {
$validacionToken = $helper->authCheck($autorizacion);
if ($validacionToken == true) {
$conexion = new conexPG();
$usuarioToken = $helper->authCheck($autorizacion, true);
$id = $app->request->post('id',null);
$sql = "select usu.* from seguridad.usuario as usu
inner join presaber.ficha_usuario as fiusu on usu.id=fiusu.usuario_id_fk
inner join seguridad.rol as ro on ro.id= usu.rol_id_fk
inner join presaber.ficha as fi on fiusu.ficha_id_fk=fi.id where fi.id='$id' and ro.descripcion='ESTUDIANTE'";
$r = $conexion->consultaComplejaAso($sql);
$data =[
'code'=>'LTE-001',
'data'=>$r
];
} else {
$data = [
'code' => 'LTE-013',
'line'=>'39-ficha'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
echo $helper->checkCode($data);
});<file_sep>/PreSaber-Nuevo/src/app/models/evaluacion/configuracion.ts
export class Configuracion{
constructor(
public id_configuracion: any,
public repetir_bool: any,
public cantidad_intentos: any,
public mesclar_preguntas: any,
public mesclar_respuestas: any,
public contrasena_bool: any,
public contrasena: any,
public examen_id_fk: any
){}
}
<file_sep>/php-backend/App/componentes/profesor/configuracion.php
<?php
$app->post('/profesor/actualizarConfiguracion', function () use ($app) {
$helper = new helper();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$conexion = new conexPG();
$parametros = json_decode($json);
$id_configuracion = (isset($parametros->id_configuracion)) ? $parametros->id_configuracion : null;
$sql = "select * from evaluacion.configuracion where id_configuracion='$id_configuracion'";
$r = $conexion->consultaComplejaNor($sql);
if ($r != 0) {
$id_examen = (isset($parametros->id_examen)) ? $parametros->id_examen : null;
$id_base_examen = (isset($parametros->id_base_examen)) ? $parametros->id_base_examen : null;
$id_configuracion = (isset($parametros->id_configuracion)) ? $parametros->id_configuracion : null;
$repetir_bool = (isset($parametros->repetir_bool)) ? $parametros->repetir_bool : null;
$cantidad_intentos = (isset($parametros->cantidad_intentos)) ? $parametros->cantidad_intentos : null;
$mesclar_preguntas = (isset($parametros->mesclar_preguntas)) ? $parametros->mesclar_preguntas : null;
$mesclar_respuestas = (isset($parametros->mesclar_respuestas)) ? $parametros->mesclar_respuestas : null;
$contrasena_bool = (isset($parametros->contrasena_bool)) ? $parametros->contrasena_bool : null;
$contrasena = (isset($parametros->contrasena)) ? $parametros->contrasena : null;
if ($contrasena != $r['contrasena']) {
$pwd = <PASSWORD>('<PASSWORD>', $contrasena);
$sql = "UPDATE evaluacion.configuracion
SET repetir_bool='$repetir_bool',
cantidad_intentos='$cantidad_intentos',
mesclar_preguntas='$mesclar_preguntas',
mesclar_respuestas='$mesclar_respuestas',
contrasena_bool='$contrasena_bool',
contrasena='$pwd'
WHERE id_configuracion='$id_configuracion';";
$conexion->consultaSimple($sql);
$sql = "UPDATE evaluacion.examen_taller
SET base_examen_id_fk='$id_base_examen'
WHERE id_examen='$id_examen';";
$conexion->consultaSimple($sql);
} else {
$sql = "UPDATE evaluacion.configuracion
SET repetir_bool='$repetir_bool',
cantidad_intentos='$cantidad_intentos',
mesclar_preguntas='$mesclar_preguntas',
mesclar_respuestas='$mesclar_respuestas',
WHERE id_configuracion='$id_configuracion';";
$conexion->consultaSimple($sql);
$sql = "UPDATE evaluacion.examen_taller
SET base_examen_id_fk='$id_base_examen'
WHERE id_examen='$id_examen';";
$conexion->consultaSimple($sql);
}
$data = [
'code'=>'LTE-007'
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => ''
];
}
echo $helper->checkCode($data);
});<file_sep>/PreSaber-Web/src/app/models/rol.ts
export class Rol {
constructor(public id: number,
public descripcion: string,
public state: string,
public fecha_creacion: any,
public fecha_actualizacion: any) {
}
}
<file_sep>/PreSaber-Web/src/app/components/administrador/crear-typo-usuario/crear-typo-usuario.component.ts
import { Component, OnInit } from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {ElementsService} from "../../../services/elements.service";
@Component({
selector: 'app-crear-typo-usuario',
templateUrl: './crear-typo-usuario.component.html',
styleUrls: ['./crear-typo-usuario.component.css']
})
export class CrearTypoUsuarioComponent implements OnInit {
public userIdentity: any;
constructor(private _ElementService: ElementsService,
private _Router: Router, private _Route: ActivatedRoute) {
this.userIdentity = this._ElementService.getUserIdentity();
}
ngOnInit() {
this._ElementService.pi_poValidarUsuario('CrearTypoUsuarioComponent');
}
}
<file_sep>/PreSaber-Web/src/app/services/usuario.service.ts
import {Injectable} from "@angular/core";
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {Observable} from "rxjs/Observable";
import {User} from "../models/user";
import {GLOBAL} from "./global";
@Injectable()
export class UsuarioService {
public url: string;
constructor(public _http: HttpClient) {
this.url = GLOBAL.url;
}
newRegister(user): Observable<any> {
let json = JSON.stringify(user);
//let params = 'json=' + '{"email":"' + user.email + '","password":"' + user.password + '","firstName":"'
//+ user.firstName + '","lastName":"' + user.lastName + '"}';
let params = 'json=' + json;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(this.url + 'crearUsuario', params, {headers: headers});
}
activateAcount(user): Observable<any> {
let params = 'json=' + '{"correo":"' + user.correo + '","codigo_activacion":"' + user.codigo_activacion + '"}';
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(this.url + 'activarCodigo', params, {headers: headers});
}
listarRoles(): Observable<any> {
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(this.url + 'administrador/rolUsuario', {headers: headers});
}
listarUsuarios(token): Observable<any> {
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
let parametros = 'token=' + token;
return this._http.post(this.url + 'administrador/listarUsuario', parametros, {headers: headers});
}
crearUsuarioAdministrador(usuario, token): Observable<any> {
let json = JSON.stringify(usuario);
let params = 'json=' + json + '&token=' + token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(this.url + 'administrador/crearUsuario', params, {headers: headers});
}
actualizarUsuarioAdministrador(usuario, token): Observable<any> {
let json = JSON.stringify(usuario);
let params = 'json=' + json + '&token=' + token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(this.url + 'administrador/actualizarUsuario', params, {headers: headers});
}
editarPerfil(token, params: Array<string>, files: Array<File>, data = null) {
let urlF = this.url + 'actualizarPerfil';
return new Promise((resolve, reject) => {
var formData: any = new FormData();
var xhr = new XMLHttpRequest();
if (files != undefined) {
var name_file_input = params[0];
for (var i = 0; i < files.length; i++) {
formData.append(name_file_input, files[i], files[i].name);
}
}
formData.append('token', token);
if (data != null)
var json = JSON.stringify(data);
formData.append('json', json);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
}
xhr.open("POST", urlF, true);
xhr.send(formData);
});
}
filtrarUsuario(filtro, token): Observable<any> {
let json = '{"filtro":"' + filtro + '"}';
let params = 'json=' + json + '&token=' + token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(this.url + 'administrador/filtroUsuario', params, {headers: headers});
}
}
<file_sep>/PreSaber-Web/src/app/components/administrador/crear-curso/crear-curso.component.ts
import {Component, OnInit} from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {ElementsService} from "../../../services/elements.service";
import {Curso} from "../../../models/curso";
import {CursoService} from "../../../services/curso.service";
import {GLOBAL} from "../../../services/global";
import {ContratoEntidad} from "../../../models/contratoEntidad";
import {Modulo} from "../../../models/modulo";
import {ModuloService} from "../../../services/modulo.service";
import {User} from "../../../models/user";
@Component({
selector: 'app-crear-curso',
templateUrl: './crear-curso.component.html',
styleUrls: ['./crear-curso.component.css'],
providers: [ElementsService, CursoService, ModuloService]
})
export class CrearCursoComponent implements OnInit {
public userIdentity: any;
public objCurso: Curso;
public token: any;
public imagenCurso: Array<File>;
public listCursos: Array<Curso>;
public r: any;
public url: string;
public filtro: string;
public objModulo: Modulo;
public idCurso: string;
public listCurso: Array<Curso>;
public objInformacion: Object;
public filtroModulo: string;
public listModulo: Array<object>;
public imagenModulo: Array<File>;
public listProfesores: Array<Object>;
public objUsuario: User;
public filtroProfesor: String;
constructor(private _ElementService: ElementsService, private _cursoService: CursoService,
private _Router: Router, private _Route: ActivatedRoute, private _ModuleService: ModuloService) {
this.userIdentity = this._ElementService.getUserIdentity();
this.objCurso = new Curso('', '', '', '000', '', '', '');
this.objModulo = new Modulo(0, '', '', '', '', '', null, '000', '', '');
this.objUsuario = new User('', '', '', '', '', '', '', '', '',
'', '', '', '', 'PROFESOR', '');
this.token = localStorage.getItem('token');
this.url = GLOBAL.urlFiles;
this.filtro = '';
this.filtroModulo = '';
this.filtroProfesor = '';
this._ElementService.pi_poBontonDesabilitar('#actualizarRegistro');
}
ngOnInit() {
this._ElementService.pi_poValidarUsuario('CrearCursoComponent');
$("#loader").hide();
$("#loader1").hide();
this.listarCursos();
$("#seccionModulo").toggle();
}
crearCurso() {
this._ElementService.pi_poBontonDesabilitar('#btnCrearRegistro');
$("#loader").show();
this._cursoService.crearCurso(this.token, ['imagen'], this.imagenCurso, this.objCurso).then(
(resultado) => {
this.r = resultado;
this._ElementService.pi_poValidarCodigo(this.r);
if (this.r.status == 'success') {
this.listarCursos();
this._ElementService.pi_poAlertaSuccess('Curso creado de forma correcta');
this._ElementService.pi_poBotonHabilitar('#btnCrearRegistro');
this.limpiarCampos();
$("#loader").hide();
} else {
this._ElementService.pi_poAlertaError(this.r.msg);
this._ElementService.pi_poBotonHabilitar('#btnCrearRegistro');
$("#loader").hide();
}
},
(error) => {
console.log(error);
this._ElementService.pi_poBotonHabilitar('#btnCrearRegistro');
}
)
}
cargarImagen(event) {
this.imagenCurso = <Array<File>>event.target.files;
}
limpiarCampos() {
this.objCurso = new Curso('', '', '', '000', '', '', '');
}
listarCursos() {
$("#loader1").show();
this._cursoService.listarCurso(this.token).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.listCursos = respuesta.data;
$("#loader1").hide();
}
}, error2 => {
}
)
}
filtrar() {
$("#loader1").show();
let lisCurso1 = new Array<Curso>();
let validacion = 1;
for (let i in this.listCursos) {
if (this.listCursos[i].descripcion == this.filtro) {
lisCurso1.push(this.listCursos[i]);
this.listCursos = lisCurso1;
$("#loader1").hide();
validacion = 0;
break;
}
}
if (validacion == 1) {
this._cursoService.filtrarCurso(this.filtro, this.token).subscribe(
respuestaF => {
this._ElementService.pi_poValidarCodigo(respuestaF);
if (respuestaF.status == 'success') {
this.listCursos = respuestaF.data;
$("#loader1").hide();
} else {
this._ElementService.pi_poAlertaWarning('No se encontraron resultado con el filtro: ' + this.filtro);
this.listarCursos();
$("#loader1").hide();
}
}, error => {
}
)
}
}
seleccionarCurso(curso) {
this.objCurso = curso;
this._ElementService.pi_poAlertaWarning('Se selecciono el curso: ' + this.objCurso.descripcion + ' con estado: ' + this.objCurso.estado + '.');
this._ElementService.pi_poBotonHabilitar('#actualizarRegistro');
this._ElementService.pi_poBontonDesabilitar('#btnCrearRegistro');
}
actualizarCurso() {
this._ElementService.pi_poBontonDesabilitar('#actualizarRegistro');
$("#loader").show();
this._cursoService.actualizarCurso(this.token, ['imagen'], this.imagenCurso, this.objCurso).then(
(resultado) => {
this.r = resultado;
this._ElementService.pi_poValidarCodigo(this.r);
if (this.r.status == 'success') {
this.listarCursos();
this._ElementService.pi_poAlertaSuccess('Curso actualizado de forma correcta');
this._ElementService.pi_poBotonHabilitar('#btnCrearRegistro');
this.limpiarCampos();
$("#loader").hide();
} else {
this._ElementService.pi_poAlertaError(this.r.msg);
this._ElementService.pi_poBotonHabilitar('#actualizarRegistro');
$("#loader").hide();
}
},
(error) => {
console.log(error);
this._ElementService.pi_poBotonHabilitar('#actualizarRegistro');
}
)
}
verModulosCurso(curso) {
$("#loaderCrearModulo").hide();
$("#preLoadertablaProfesores").hide();
this._ElementService.pi_poBontonDesabilitar('#btnActualizarModulo');
this.objCurso = curso;
this.objModulo.curso_id_fk = this.objCurso.id;
this.listarModulos();
this.informacionCurso();
$("#seccionCurso").toggle('1000');
$("#seccionModulo").toggle('1000');
}
//Metodos Modulo
listarModulos() {
$("#loaderTablaModulo").show();
this._ModuleService.listarModulo(this.token, this.objCurso).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.listModulo = respuesta.data;
$("#loaderTablaModulo").hide();
}
}, error2 => {
}
)
}
filtrarModulo() {
$("#loaderTablaModulo").show();
let listModulo1 = new Array<object>();
this._ModuleService.filtrarModulo(this.filtroModulo, this.token).subscribe(
respuestaF => {
this._ElementService.pi_poValidarCodigo(respuestaF);
if (respuestaF.status == 'success') {
this.listModulo = respuestaF.data;
$("#loaderTablaModulo").hide();
} else {
this._ElementService.pi_poAlertaWarning('No se encontraron resultado con el filtro: ' + this.filtro);
this.listarModulos();
$("#loaderTablaModulo").hide();
}
}, error => {
}
)
}
filtrarProfesor() {
this._ModuleService.filtrarProfesor(this.filtroProfesor, this.token).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.listProfesores = respuesta.data;
} else {
this.listarProfesores();
this._ElementService.pi_poAlertaError(respuesta.msg);
}
}, error2 => {
}
)
}
informacionCurso() {
$("#loaderTablaCursos").show();
this._ModuleService.informacionCurso(this.objCurso).subscribe(
respuesta => {
this.objInformacion = respuesta.data[0];
this.objCurso = respuesta.data[0];
$("#loaderTablaCursos").hide();
}, error2 => {
}
)
}
cargarImagenModulo(event) {
this.imagenModulo = <Array<File>>event.target.files;
}
crearModulo() {
this._ElementService.pi_poBontonDesabilitar('#btnCrearModulo');
$("#loaderCrearModulo").show();
this._ModuleService.crearModulo(this.token, ['imagen'], this.imagenModulo, this.objModulo).then(
(resultado) => {
this.r = resultado;
this._ElementService.pi_poValidarCodigo(this.r);
if (this.r.status == 'success') {
this.listarModulos();
this._ElementService.pi_poAlertaSuccess('Modulo creado de forma correcta');
this._ElementService.pi_poBotonHabilitar('#btnCrearModulo');
this.limpiarCamposModulo()
$("#loaderCrearModulo").hide();
} else {
this._ElementService.pi_poAlertaError(this.r.msg);
this._ElementService.pi_poBotonHabilitar('#btnCrearModulo');
$("#loaderCrearModulo").hide();
}
},
(error) => {
console.log(error);
this._ElementService.pi_poBotonHabilitar('#btnCrearModulo');
}
)
}
limpiarCamposModulo() {
this.objModulo = new Modulo(0, this.objCurso.id, '', '', '', '', null, '000', '', '');
}
informacionProfesor(modulo) {
this.objUsuario.documento = modulo.documento;
this.objUsuario.nombre = modulo.nombre;
this.objUsuario.apellido = modulo.apellido;
this.objUsuario.correo = modulo.correo
this.objUsuario.id = modulo.id_usuario;
this.objUsuario.imagen = modulo.imagen_usuario;
}
seleccionarModulo(modulo) {
this.informacionProfesor(modulo);
this._ElementService.pi_poBontonDesabilitar('#btnCrearModulo');
this._ElementService.pi_poBotonHabilitar('#btnActualizarModulo');
this.objModulo = modulo;
this.objCurso.id = this.objModulo.curso_id_fk;
this.informacionCurso();
}
actualizarModulo() {
this._ElementService.pi_poBontonDesabilitar('#btnActualizarModulo');
$("#loaderCrearModulo").show();
this._ModuleService.actualizarModulo(this.token, ['imagen'], this.imagenModulo, this.objModulo).then(
(resultado) => {
this.r = resultado;
this._ElementService.pi_poValidarCodigo(this.r);
if (this.r.status == 'success') {
this.listarModulos();
this._ElementService.pi_poAlertaSuccess('Curso actualizado de forma correcta');
this._ElementService.pi_poBotonHabilitar('#btnCrearModulo');
this.limpiarCamposModulo();
$("#loaderCrearModulo").hide();
} else {
this._ElementService.pi_poAlertaError(this.r.msg);
this._ElementService.pi_poBotonHabilitar('#btnActualizarModulo');
$("#loaderCrearModulo").hide();
}
},
(error) => {
console.log(error);
this._ElementService.pi_poBotonHabilitar('#btnActualizarModulo');
}
)
}
regresarCurso() {
$("#seccionModulo").toggle('1000');
$("#seccionCurso").toggle('1000');
}
listarProfesores() {
$("#preLoadertablaProfesores").show();
this._ModuleService.listarProfesores(this.token).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.listProfesores = respuesta.data;
$("#preLoadertablaProfesores").hide();
} else {
$("#preLoadertablaProfesores").hide();
this._ElementService.pi_poAlertaError(respuesta.msg);
}
}, error2 => {
}
)
}
seleccionarProfesor(profesor) {
this.objUsuario = profesor;
this.objModulo.usuario_profesor_id_fk = profesor.id;
this._ElementService.pi_poVentanaAlerta('Cuidado!', 'Se selecciono al profesor: ' + profesor.nombre);
}
}
<file_sep>/PreSaber-Nuevo/src/app/components/administrador/crear-usuario/crear-usuario.component.ts
import {Component, OnInit} from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {ElementsService} from "../../../services/elements.service";
import {User} from "../../../models/user";
import {CrearTypoUsuarioComponent} from "../crear-typo-usuario/crear-typo-usuario.component";
import {UsuarioService} from "../../../services/usuario.service";
import {Rol} from "../../../models/rol";
@Component({
selector: 'app-crear-usuario',
templateUrl: './crear-usuario.component.html',
styleUrls: ['./crear-usuario.component.css'],
providers: [UsuarioService, ElementsService]
})
export class CrearUsuarioComponent implements OnInit {
public userIdentity: any;
public objUsuario: User;
public listRol: Array<Rol>;
public listaUsuarios: Array<User>;
public token: string;
public filtro: string;
position = "top-right";
constructor(private _ElementService: ElementsService,
private _Router: Router, private _Route: ActivatedRoute, private _usuarioService: UsuarioService) {
this.userIdentity = this._ElementService.getUserIdentity();
this.objUsuario = new User(null, 0, '', '', '', '',
'', null, null, null, '', null,
null, null, '1');
this.token = localStorage.getItem('token');
this.filtro = '';
}
ngOnInit() {
this._ElementService.pi_poValidarUsuario('CrearTypoUsuarioComponent');
$("#preLoadertabla").hide()
this.listarRol();
this.listarUsuarios();
$('#loader').hide();
this._ElementService.pi_poBontonDesabilitar("#actualizarRegistro");
}
listarRol() {
this._usuarioService.listarRoles().subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
this.listRol = respuesta.data;
}, error => {
}
)
}
listarUsuarios() {
$("#preLoadertabla").show()
this._usuarioService.listarUsuarios(this.token).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
this.listaUsuarios = respuesta.data;
$("#preLoadertabla").hide()
}, error2 => {
}
)
}
crearUsuario() {
$('#btnCrearRegistro').attr('disabled', 'disabled');
$('#loader').show();
this._usuarioService.crearUsuarioAdministrador(this.objUsuario, this.token).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.listarUsuarios();
$('#loader').hide();
$('#btnCrearRegistro').removeAttr('disabled');
this._ElementService.pi_poAlertaSuccess(respuesta.msg,'Usuario');
} else if (respuesta.status == 'error') {
$('#btnCrearRegistro').removeAttr('disabled');
$('#loader').hide();
this._ElementService.pi_poAlertaError(respuesta.msg,'Usuario');
}
}, error2 => {
}
)
}
actualizarUsuario() {
this._ElementService.pi_poBontonDesabilitar('#actualizarRegistro');
$('#loader').show();
this._usuarioService.actualizarUsuarioAdministrador(this.objUsuario, this.token).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.limpíarCampos();
this.listarUsuarios();
$('#loader').hide();
this._ElementService.pi_poBotonHabilitar('#btnCrearRegistro');
this._ElementService.pi_poBontonDesabilitar('#actualizarRegistro');
this._ElementService.pi_poAlertaSuccess(respuesta.msg,'Usuario');
} else if (respuesta.status == 'error') {
this._ElementService.pi_poBotonHabilitar('#actualizarRegistro');
$('#loader').hide();
this._ElementService.pi_poAlertaError(respuesta.msg,'Usuario');
}
}, error2 => {
})
}
limpíarCampos() {
this.objUsuario = new User(null, 0, '', '', '', '',
'', null, null, null, '', null,
null, null, '1');
}
filtrar() {
$("#preLoadertabla").show();
let listusuario1 = new Array<User>();
let validacion = 1;
for (let i in this.listaUsuarios) {
if (this.listaUsuarios[i].documento == this.filtro || this.listaUsuarios[i].correo == this.filtro || this.listaUsuarios[i].nombre == this.filtro) {
listusuario1.push(this.listaUsuarios[i]);
this.listaUsuarios = listusuario1;
$("#preLoadertabla").hide();
validacion = 0;
break;
}
}
if (validacion == 1) {
this._usuarioService.filtrarUsuario(this.filtro, this.token).subscribe(
respuestaF => {
this._ElementService.pi_poValidarCodigo(respuestaF);
if (respuestaF.status == 'success')
{
this.listaUsuarios = respuestaF.data;
$("#preLoadertabla").hide();
}else
{
this._ElementService.pi_poAlertaWarning('No se encontraron resultado con el filtro: '+this.filtro,'Filtro');
this.listarUsuarios();
$("#preLoadertabla").hide();
}
}, error => {
}
)
}
}
seleccionarUsuario(usuarios) {
this._ElementService.pi_poBontonDesabilitar('#btnCrearRegistro');
this.objUsuario = usuarios;
this._ElementService.pi_poAlertaWarning('Se selecciono el usuario ' + this.objUsuario.nombre + ' con documento ' + this.objUsuario.documento + '.','Seleccion');
this._ElementService.pi_poBotonHabilitar("#actualizarRegistro")
}
}
<file_sep>/php-backend/App/componentes/examen_publico.php
<?php
$app->post('/cargarExamenCompleto', function () use ($app) {
$json = $app->request->post('json', null);
$helper = new helper();
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$arregloExamen = array();
$parametros = json_decode($json);
$id_sesion = (isset($parametros->id_sesion)) ? $parametros->id_sesion : null;
$conexion = new conexPG();
$sql = "select se.*, ex.*,be.descripcion_base_examen,tr.descripcion, cf.* from evaluacion.sesion se
join evaluacion.examen_taller ex on se.examen_taller_id_fk=ex.id_examen
join evaluacion.base_examen be on ex.base_examen_id_fk=be.id_base_examen
join presaber.tipo_recurso tr on ex.tipo_recurso_id_fk=tr.id
join evaluacion.configuracion cf on cf.examen_id_fk = ex.id_examen
where se.id_sesion='$id_sesion';";
$r = $conexion->consultaComplejaNorAso($sql);
$sql = "select pr.*, comcia.id_competencia, comcia.descripcion_competencia,
compo.id_componente,compo.descripcion_componente from evaluacion.pregunta pr
join evaluacion.competencia comcia on pr.compentencia_id_fk=comcia.id_competencia
join evaluacion.componente compo on pr.componente_id_fk=compo.id_componente where pr.sesion_id_fk='$id_sesion'; ";
$r2 = $conexion->consultaComplejaAso($sql);
$arregloPreguntaRespuestas = array();
$cantidadPreguntas = 0;
for ($i = 0; $i < count($r2); $i++) {
$id_pregutna = $r2[$i]['id_pregunta'];
$sql1 = "select rp.* from evaluacion.respuesta rp where rp.pregunta_id_fk='$id_pregutna'; ";
$r3 = $conexion->consultaComplejaAso($sql1);
$arregloRespuesta = array();
for ($nn = 0; $nn<count($r3); $nn++){
array_push($arregloRespuesta,[
'id_respuesta'=>$r3[$nn]['id_respuesta'],
'pregunta_id_fk'=>$r3[$nn]['pregunta_id_fk'],
'tipo_repuesta'=>$r3[$nn]['tipo_repuesta'],
'descripcion_respuesta'=>$r3[$nn]['descripcion_respuesta'],
'correcta_respuesta'=>$r3[$nn]['correcta_respuesta'],
'respuestaSeleccionada'=>'0'
]);
}
array_push($arregloPreguntaRespuestas, [
'contexto' => html_entity_decode($r2[$i]['contexto']),
'pregunta' => html_entity_decode($r2[$i]['pregunta']),
'justificacion' => html_entity_decode($r2[$i]['justificacion']),
'respondio' => '0',
'correcto' => '0',
'puntajePregunta' => '',
'id_competencia' => $r2[$i]['id_competencia'],
'descripcion_competencia' => $r2[$i]['descripcion_competencia'],
'id_componente' => $r2[$i]['id_componente'],
'descripcion_componente' => $r2[$i]['descripcion_componente'],
'cantidad_respuestas' => count($r3),
'respuestas' => $arregloRespuesta
]);
$cantidadPreguntas++;
}
$arregloExamen = [
'descripcion_examen' => $r['descripcion_examen'],
'descripcion_sesion' => $r['descripcion_sesion'],
'id_sesion' => $r['id_sesion'],
'id_examen' => $r['id_examen'],
'descripcion' => $r['descripcion'],
'descripcion_base_examen' => $r['descripcion_base_examen'],
'cantidad_preguntas' => $cantidadPreguntas,
'puntajeGlobal' => '0',
'cantidadBuenas' => '0',
'configuracion' => [
'id_configuracion' => $r['id_configuracion'],
'repetir_bool' => $r['repetir_bool'],
'cantidad_intentos' => $r['cantidad_intentos'],
'mesclar_preguntas' => $r['mesclar_preguntas'],
'mesclar_respuestas' => $r['mesclar_respuestas'],
'contrasena_bool' => $r['contrasena_bool'],
'contrasena' => $r['contrasena'],
'examen_id_fk' => $r['examen_id_fk']
],
'preguntas' => $arregloPreguntaRespuestas
];
$data = [
'code' => 'LTE-001',
'data' => $arregloExamen
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/examen/validarContrasena', function () use ($app) {
$json = $app->request->post('json', null);
$helper = new helper();
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$pass1 = $app->request->post('pass1', null);
$pass2 = $app->request->post('pass2', null);
$pass1 = hash('SHA256', $pass1);
if ($pass1 == $pass2) {
$data = [
'code' => 'LTE-000',
'status' => 'success',
'msg' => 'Comprobacion realizada'
];
} else {
$data = [
'code' => 'LTE-000',
'status' => 'error',
'msg' => 'Comprobacion errónea'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
echo $helper->checkCode($data);
});<file_sep>/PreSaber-Nuevo/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {SharedModule} from './shared/shared.module';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {routing,appRoutingProviders} from "./app.rounting";
import {FormsModule} from "@angular/forms";
import {HttpClientModule} from "@angular/common/http";
import { AppComponent } from './app.component';
import { LoginComponent } from './components/login/login.component';
import { HomeComponent } from './components/home/home.component';
import { RegistroComponent } from './components/registro/registro.component';
import { VerificarCodigoComponent } from './components/verificar-codigo/verificar-codigo.component';
import { HomeAdminComponent } from './components/home-admin/home-admin.component';
import { HomeEstudianteComponent } from './components/home-estudiante/home-estudiante.component';
import { HomeProfesorComponent } from './components/home-profesor/home-profesor.component';
import { CrearContratoComponent } from './components/administrador/crear-contrato/crear-contrato.component';
import { CrearUsuarioComponent } from './components/administrador/crear-usuario/crear-usuario.component';
import { CrearTypoUsuarioComponent } from './components/administrador/crear-typo-usuario/crear-typo-usuario.component';
import { CrearCursoComponent } from './components/administrador/crear-curso/crear-curso.component';
import { CrearSeccionComponent } from './components/administrador/crear-seccion/crear-seccion.component';
import { PerfilUsuarioComponent } from './components/administrador/perfil-usuario/perfil-usuario.component';
import { FichasComponent } from './components/profesor/fichas/fichas.component';
import { CrearRecursoComponent } from './components/profesor/crear-recurso/crear-recurso.component';
import {CKEditorModule} from "ng2-ckeditor";
import {SafeHtmlPipe} from "./services/tanfromarHtml";
import { RecursosComponent } from './components/profesor/recursos/recursos.component';
import { MisEstudiantesComponent } from './components/profesor/mis-estudiantes/mis-estudiantes.component';
import { MisCursosComponent } from './components/profesor/mis-cursos/mis-cursos.component';
import { MisCursosEstudianteComponent } from './components/estudiante/mis-cursos-estudiante/mis-cursos-estudiante.component';
import { FichasCursoComponent } from './components/estudiante/fichas-curso/fichas-curso.component';
import { ClasesAsignaturaComponent } from './components/estudiante/clases-asignatura/clases-asignatura.component';
@NgModule({
declarations: [
AppComponent,
LoginComponent,
HomeComponent,
RegistroComponent,
VerificarCodigoComponent,
HomeAdminComponent,
HomeEstudianteComponent,
HomeProfesorComponent,
CrearContratoComponent,
CrearUsuarioComponent,
CrearTypoUsuarioComponent,
CrearCursoComponent,
CrearSeccionComponent,
PerfilUsuarioComponent,
FichasComponent,
CrearRecursoComponent,
SafeHtmlPipe,
RecursosComponent,
MisEstudiantesComponent,
MisCursosComponent,
MisCursosEstudianteComponent,
FichasCursoComponent,
ClasesAsignaturaComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
SharedModule,
routing,
FormsModule,
HttpClientModule,
CKEditorModule,
],
providers: [appRoutingProviders],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/PreSaber-Nuevo/src/app/models/evaluacion/competencia.ts
export class Competencia{
constructor(
public id_competencia: any,
public descripcion_competencia: any,
public fecha_creacion_competencia: any,
public fecha_actualizacion_competencia: any
)
{}
}
<file_sep>/php-backend/App/componentes/profesor/modulo.php
<?php
$app->post('/profesor/MisCursos',function ()use ($app){
$helper= new helper();
$token = $app->request->post('token',null);
if ($token != null)
{
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true)
{
$usuarioToken = $helper->authCheck($token,true);
$conexion = new conexPG();
$id = $app->request->post('id',null);
$sql ="select mo.*,fi.descripcion as descripcionFicha from presaber.ficha fi join presaber.curso cu on fi.curso_id_fk = cu.id
join presaber.modulo mo on cu.id=mo.curso_id_fk where mo.usuario_profesor_id_fk='$usuarioToken->sub' and fi.id='$id'";
$r = $conexion->consultaComplejaAso($sql);
if($r != 0)
{
$data=[
'code'=>'LTE-001',
'data'=>$r
];
}else{
$data=[
'code'=>'LTE-003'
];
}
}else
{
$data =[
'code'=>'LTE-013'
];
}
}else{
$data=[
'code'=>'LTE-013'
];
}
echo $helper->checkCode($data);
});<file_sep>/php-backend/App/librerias/conexion.php
<?PHP
/*
class conex {
private $host;
private $usuario;
private $contrasena;
private $nombreBD;
private $validacionConexion;
function __construct() {
$this->host = "192.168.0.12";
$this->usuario = "joseluis";
$this->contrasena = "Treseditores2018";
$this->nombreBD = "prueba";
$this->validacionConexion = mysqli_connect($this->host, $this->usuario, $this->contrasena, $this->nombreBD);
}
public function cadenaConexion ()
{
return $this->validacionConexion;
}
public function consultaSimple($sql) {
mysqli_query($this->validacionConexion, $sql);
}
public function consultaCompleja($sql)
{
$consulta= mysqli_query($this->validacionConexion, $sql);
return $consulta;
}
}
*/
use Symfony\Component\Yaml\Yaml;
class conexPG
{
private $validacionConexion;
function __construct()
{
$config = Yaml::parseFile(__DIR__ . './../../Config/config.yml');
$this->validacionConexion = pg_connect('host='.$config['dbal']['pgsql']['host'].' dbname='.$config['dbal']['pgsql']['dbname'].' user='.$config['dbal']['pgsql']['user'].' password='.$config['dbal']['pgsql']['password']) or die('NO HAY CONEXION: ' . pg_last_error());
}
public function getConexion()
{
return $this->validacionConexion;
}
public function consultaComplejaNorAso($sql)
{
$result = pg_query($this->validacionConexion, $sql);
if (pg_num_rows($result)>0)
{
return pg_fetch_assoc($result);
}else
{
return 0;
}
}
public function consultaComplejaNor($sql)
{
$result = pg_query($this->validacionConexion, $sql);
return $result;
}
public function consultaComplejaAso($sql)
{
$result = pg_query($this->validacionConexion, $sql);
if (pg_num_rows($result)>0)
{
while ($row = pg_fetch_assoc($result)) {
$data[] = $row;
}
}else
{
$data=0;
}
return $data;
}
public function consultaSimple($sql)
{
pg_query($this->validacionConexion, $sql);
}
}
<file_sep>/PreSaber-Web/src/app/models/resource.ts
export class Resource {
constructor(public id: number,
public description: string,
public content: string,
public createdAt: any,
public updatedAt: any,
public UserTeacher: number,
public TypeResource: number,
public TypeTeme: number) {
}
}<file_sep>/PreSaber-Nuevo/src/app/services/modulo.service.ts
import {Injectable} from "@angular/core";
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {Observable} from "rxjs/Observable";
import {User} from "../models/user";
import {GLOBAL} from "./global";
@Injectable()
export class ModuloService {
public url: string;
constructor(public _http: HttpClient) {
this.url = GLOBAL.url;
}
crearModulo(token, params: Array<string>, files: Array<File>, data = null) {
let urlF = this.url + 'administrador/crearModulo';
return new Promise((resolve, reject) => {
var formData: any = new FormData();
var xhr = new XMLHttpRequest();
if (files != undefined) {
var name_file_input = params[0];
for (var i = 0; i < files.length; i++) {
formData.append(name_file_input, files[i], files[i].name);
}
}
formData.append('token', token);
if (data != null)
var json = JSON.stringify(data);
formData.append('json', json);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
}
xhr.open("POST", urlF, true);
xhr.send(formData);
});
}
actualizarModulo(token, params: Array<string>, files: Array<File>, data = null) {
let urlF = this.url + 'administrador/actualizarModulo';
return new Promise((resolve, reject) => {
var formData: any = new FormData();
var xhr = new XMLHttpRequest();
if (files != undefined) {
var name_file_input = params[0];
for (var i = 0; i < files.length; i++) {
formData.append(name_file_input, files[i], files[i].name);
}
}
formData.append('token', token);
if (data != null)
var json = JSON.stringify(data);
formData.append('json', json);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
}
xhr.open("POST", urlF, true);
xhr.send(formData);
});
}
informacionCurso(curso): Observable<any>{
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
let json = JSON.stringify(curso);
let parametros = 'json=' + json;
return this._http.post(this.url + 'administrador/informacionCurso', parametros, {headers: headers});
}
listarCurso(token): Observable<any>{
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
let parametros = 'token=' + token;
return this._http.post(this.url + 'administrador/listarCurso', parametros, {headers: headers});
}
listarModulo(token, curso): Observable<any>{
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
let json = JSON.stringify(curso);
let parametros = 'token=' + token+'&json='+json;
return this._http.post(this.url + 'administrador/listarModulo', parametros, {headers: headers});
}
filtrarCurso(filtro,token): Observable<any>{
let json = '{"filtro":"'+filtro+'"}';
let params = 'json=' + json+'&token='+token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(this.url + 'administrador/filtroCurso', params, {headers: headers});
}
filtrarModulo(filtro,token): Observable<any>{
let json = '{"filtro":"'+filtro+'"}';
let params = 'json=' + json+'&token='+token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(this.url + 'administrador/filtroModulo', params, {headers: headers});
}
listarProfesores(token): Observable<any>
{
let params = "token="+token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(this.url+'administrador/listarProfesores',params,{headers: headers});
}
filtrarProfesor(filtro,token): Observable<any>{
let json = '{"filtro":"'+filtro+'"}';
let params = 'json=' + json+'&token='+token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(this.url + 'administrador/filtroProfesor', params, {headers: headers});
}
}
<file_sep>/PreSaber-Web/src/app/services/global.ts
export var GLOBAL = {
url: 'http://localhost/LTE/trunk/php-backend/index.php/',
urlFiles: 'http://localhost/LTE/trunk/php-backend/App/public'
};
<file_sep>/PreSaber-Nuevo/src/app/services/presaber/seccion_recurso.service.ts
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {GLOBAL} from "../global";
import {Injectable} from "@angular/core";
import {Observable} from "rxjs/Observable";
@Injectable()
export class Seccion_recursoService{
public url: any;
constructor(private _http:HttpClient)
{
this.url=GLOBAL.url;
}
crearSesionRecurso(token, params: Array<string>, files: Array<File>, data = null) {
let urlF = this.url + 'profesor/crearSesionRecurso';
return new Promise((resolve, reject) => {
var formData: any = new FormData();
var xhr = new XMLHttpRequest();
if (files != undefined) {
var name_file_input = params[0];
for (var i = 0; i < files.length; i++) {
formData.append(name_file_input, files[i], files[i].name);
}
}
if (token != null)
{
formData.append('token', token);
}
if (data != null)
var json = JSON.stringify(data);
formData.append('json', json);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
}
xhr.open("POST", urlF, true);
xhr.send(formData);
});
}
listarSeccionRecurso(token,objSesionRecurso): Observable<any> {
let json = JSON.stringify(objSesionRecurso);
let params = 'token=' + token+'&json='+json;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(this.url + 'profesor/listarSesionRecurso', params, {headers: headers});
}
actualizarSeccionRecurso(token,objSesionRecurso): Observable<any> {
let json = JSON.stringify(objSesionRecurso);
let params = 'token=' + token+'&json='+json;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(this.url + 'profesor/actualizarSeccionRecurso', params, {headers: headers});
}
actualizarPrioridad(token,sesionRecurso): Observable<any>
{
let params = 'sesionRecurso='+JSON.stringify(sesionRecurso)+'&token='+token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(this.url + 'profesor/actualizarPrioridadSeccionRecurso', params, {headers: headers});
}
}
<file_sep>/php-backend/App/componentes/administrador/ficha.php
<?php
$app->post('/administrador/crearFicha', function () use ($app) {
$json = $app->request->post('json', null);
$helper = new helper();
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$conexion = new conexPG();
$usuarioToken = $helper->authCheck($token, true);
$sql = "select * from seguridad.usuario where id ='$usuarioToken->sub'";
$r = $conexion->consultaComplejaNor($sql);
if (pg_num_rows($r) > 0) {
$usuario = pg_fetch_assoc($r);
$parametros = json_decode($json);
$usuario_administrador_id_fk = $usuario['id'];
$curso_id_fk = (isset($parametros->curso_id_fk)) ? $parametros->curso_id_fk : null;
$contrato_entidad_id_fk = (isset($parametros->contrato_entidad_id_fk)) ? $parametros->contrato_entidad_id_fk : null;
$descripcion = (isset($parametros->descripcion)) ? $parametros->descripcion : null;
$estado = (isset($parametros->estado)) ? $parametros->estado : null;
$usuarios_minimos = (isset($parametros->usuarios_minimos)) ? $parametros->usuarios_minimos : null;
$usuarios_maximos = (isset($parametros->usuarios_maximos)) ? $parametros->usuarios_maximos : null;
$fecha_finalizacion = (isset($parametros->fecha_finalizacion)) ? $parametros->fecha_finalizacion : null;
$fecha_creacion = $fecha_creacion = date('Y-m-d H:i:s');
$conexion = new conexPG();
$sql = "INSERT INTO presaber.ficha(
usuario_administrador_id_fk, curso_id_fk, contrato_entidad_id_fk, descripcion, estado, usuarios_minimos, usuarios_maximos, fecha_finalizacion, fecha_creacion)
VALUES ( '$usuario_administrador_id_fk', '$curso_id_fk', '$contrato_entidad_id_fk', '$descripcion', '$estado', '$usuarios_minimos', '$usuarios_maximos', '$fecha_finalizacion', '$fecha_creacion');";
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-001'
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013',
'line' => '19-ficha'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/administrador/crearUsuarioFicha', function () use ($app) {
$helper = new helper();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$conexion = new conexPG();
$parametros = json_decode($json);
$documento = (isset($parametros->documento)) ? $parametros->documento : null;
$nombre = (isset($parametros->nombre)) ? $parametros->nombre : null;
$apellido = (isset($parametros->apellido)) ? $parametros->apellido : null;
$correo = (isset($parametros->correo)) ? $parametros->correo : null;
$estado = (isset($parametros->estado)) ? $parametros->estado : null;
$idFicha = (isset($parametros->idFicha)) ? $parametros->idFicha : null;
$rol_id_fk = (isset($parametros->rol_id_fk)) ? $parametros->rol_id_fk : null;
$contrato_entidad_id_fk = (isset($parametros->contrato_entidad_id_fk)) ? $parametros->contrato_entidad_id_fk : null;
$fecha_creacion = $fecha_creacion = date('Y-m-d H:i:s');
$sql = "select * from seguridad.usuario where documento = '$documento' or correo='$correo'";
$r = $conexion->consultaComplejaNorAso($sql);
if ($r == 0) {
$contrasena = time() . 21;
$pwd = hash('SHA256', $contrasena);
$usuarioToken = $helper->authCheck($token, true);
$sql = "select * from seguridad.rol where id ='$rol_id_fk'";
$r = $conexion->consultaComplejaNorAso($sql);
$descripcionRol = $r['descripcion'];
$sql = "select count(f.*) as cantidad_registros, f.usuarios_minimos,f.usuarios_maximos
from presaber.ficha f left join presaber.ficha_usuario fu on f.id=fu.ficha_id_fk where f.id ='$idFicha' group by f.id";
$r = $conexion->consultaComplejaNorAso($sql);
if ($r != 0) {
if ($descripcionRol != 'PROFESOR' && $descripcionRol != 'profesor') {
if ($r['cantidad_registros'] < $r['usuarios_maximos']) {
$sql = "select * from presaber.contrato_entidad where id='$contrato_entidad_id_fk'";
$r = $conexion->consultaComplejaNorAso($sql);
$descripcionContratoEntidad = $r['descripcion'];
if ($r != 0) {
$rutaImagen = '/imagenes_estandar/usuario-64x64.png';
$sql = "select id from seguridad.rol WHERE descripcion like 'estudiante' or descripcion like 'ESTUDIANTE'";
$r = $conexion->consultaComplejaNorAso($sql);
$idRol = $r['id'];
$sql = "INSERT INTO seguridad.usuario(
rol_id_fk, documento, nombre, apellido, correo, contrasena, imagen, fecha_creacion,estado)
VALUES ('$idRol', '$documento', '$nombre', '$apellido', '$correo', '$pwd','$rutaImagen', '$fecha_creacion','$estado') returning id;";
$r = $conexion->consultaComplejaNorAso($sql);
$id_usuario = $r['id'];
$sql = "INSERT INTO presaber.ficha_usuario(
usuario_id_fk, ficha_id_fk, usuario_administrador_id_fk, descripcion, estado, fecha_creacion)
VALUES ('$id_usuario','$idFicha', '$usuarioToken->sub', 'Usuario creado por carga de excel', 'ACTIVO', '$fecha_creacion');";
$conexion->consultaSimple($sql);
pi_poEnviaEmail('<EMAIL>', 'Osiris123', 'Los Tres Editores', $correo, 'Datos de inscripcion.',
pi_po_email_CrearUsuariosFicha($nombre, $descripcionContratoEntidad, $fecha_creacion, $correo, $contrasena));
$data = [
'code' => 'LTE-001',
];
} else {
$data = [
'code' => 'LTE-000',
'status' => 'error',
'msg' => 'Lo sentimos, no pudimos encontrar el contrato, por favor recargue la pagina.'
];
}
} else {
$data = [
'code' => 'LTE-000',
'status' => 'error',
'msg' => 'Lo sentimos, esta ficha alcanzo el limite de usuarios.'
];
}
} else {
$rutaImagen = '/imagenes_estandar/usuario-64x64.png';
$sql = "INSERT INTO seguridad.usuario(
rol_id_fk, documento, nombre, apellido, correo, contrasena, imagen, fecha_creacion,estado)
VALUES ('$rol_id_fk', '$documento', '$nombre', '$apellido', '$correo', '$pwd','$rutaImagen', '$fecha_creacion','$estado') returning id;";
$r = $conexion->consultaComplejaNorAso($sql);
$id_usuario = $r['id'];
$sql = "INSERT INTO presaber.ficha_usuario(
usuario_id_fk, ficha_id_fk, usuario_administrador_id_fk, descripcion, estado, fecha_creacion)
VALUES ('$id_usuario','$idFicha', '$usuarioToken->sub', 'Usuario creado manual', 'ACTIVO', '$fecha_creacion');";
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-001',
];
}
} else {
$data = [
'code' => 'LTE-000',
'status' => 'error',
'msg' => 'Lo sentimos esta ficha no esta creada, vuleve a cargar la pagina.'
];
}
} else {
$data = [
'code' => 'LTE-000',
'status' => 'error',
'msg' => 'Lo sentimos, ya se encuentra un usuario registrado con ese correo o con ese documento.'
];
}
} else {
$data = [
'code' => 'LTE-013',
'line' => '82-ficha'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/administrador/crearUsuarioExistente', function () use ($app) {
$helper = new helper();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$conexion = new conexPG();
$parametros = json_decode($json);
$documento = (isset($parametros->documento)) ? $parametros->documento : null;
$nombre = (isset($parametros->nombre)) ? $parametros->nombre : null;
$apellido = (isset($parametros->apellido)) ? $parametros->apellido : null;
$correo = (isset($parametros->correo)) ? $parametros->correo : null;
$estado = (isset($parametros->estado)) ? $parametros->estado : null;
$idFicha = (isset($parametros->idFicha)) ? $parametros->idFicha : null;
$rol_id_fk = (isset($parametros->rol_id_fk)) ? $parametros->rol_id_fk : null;
$contrato_entidad_id_fk = (isset($parametros->contrato_entidad_id_fk)) ? $parametros->contrato_entidad_id_fk : null;
$fecha_creacion = $fecha_creacion = date('Y-m-d H:i:s');
$sql = "select fu.* from presaber.ficha_usuario fu
join seguridad.usuario u on fu.usuario_id_fk=u.id where fu.ficha_id_fk = '$idFicha' and u.documento like '$documento';";
$r = $conexion->consultaComplejaNorAso($sql);
if ($r == 0) {
$contrasena = time() . 21;
$pwd = hash('SHA256', $contrasena);
$usuarioToken = $helper->authCheck($token, true);
$sql = "select * from seguridad.rol where id ='$rol_id_fk'";
$r = $conexion->consultaComplejaNorAso($sql);
$descripcionRol = $r['descripcion'];
$sql = "select count(f.*) as cantidad_registros, f.usuarios_minimos,f.usuarios_maximos
from presaber.ficha f left join presaber.ficha_usuario fu on f.id=fu.ficha_id_fk where f.id ='$idFicha' group by f.id";
$r = $conexion->consultaComplejaNorAso($sql);
if ($r != 0) {
if ($descripcionRol != 'PROFESOR' && $descripcionRol != 'profesor') {
if ($r['cantidad_registros'] < $r['usuarios_maximos']) {
$sql = "select * from presaber.contrato_entidad where id='$contrato_entidad_id_fk'";
$r = $conexion->consultaComplejaNorAso($sql);
$descripcionContratoEntidad = $r['descripcion'];
if ($r != 0) {
$rutaImagen = '/imagenes_estandar/usuario-64x64.png';
$sql = "select id from seguridad.rol WHERE descripcion like 'estudiante' or descripcion like 'ESTUDIANTE'";
$r = $conexion->consultaComplejaNorAso($sql);
$idRol = $r['id'];
$sql = "select * from seguridad.usuario where seguridad.usuario.documento ='$documento'";
$r = $conexion->consultaComplejaNorAso($sql);
$id_usuario = $r['id'];
$sql = "INSERT INTO presaber.ficha_usuario(
usuario_id_fk, ficha_id_fk, usuario_administrador_id_fk, descripcion, estado, fecha_creacion)
VALUES ('$id_usuario','$idFicha', '$usuarioToken->sub', 'Usuario creado por carga de excel', 'ACTIVO', '$fecha_creacion');";
$conexion->consultaSimple($sql);
pi_poEnviaEmail('<EMAIL>', 'Osiris123', 'Los Tres Editores', $correo, 'Datos de inscripcion.',
pi_po_email_CrearUsuariosFicha($nombre, $descripcionContratoEntidad, $fecha_creacion, $correo, $contrasena));
$data = [
'code' => 'LTE-001',
];
} else {
$data = [
'code' => 'LTE-000',
'status' => 'error',
'msg' => 'Lo sentimos, no pudimos encontrar el contrato, por favor recargue la pagina.'
];
}
} else {
$data = [
'code' => 'LTE-000',
'status' => 'error',
'msg' => 'Lo sentimos, esta ficha alcanzo el limite de usuarios.'
];
}
} else {
$rutaImagen = '/imagenes_estandar/usuario-64x64.png';
$sql = "select * from seguridad.usuario where seguridad.usuario.documento ='$documento'";
$r = $conexion->consultaComplejaNorAso($sql);
$id_usuario = $r['id'];
$sql = "INSERT INTO presaber.ficha_usuario(
usuario_id_fk, ficha_id_fk, usuario_administrador_id_fk, descripcion, estado, fecha_creacion)
VALUES ('$id_usuario','$idFicha', '$usuarioToken->sub', 'Usuario creado manual', 'ACTIVO', '$fecha_creacion');";
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-001',
];
}
} else {
$data = [
'code' => 'LTE-000',
'status' => 'error',
'msg' => 'Lo sentimos esta ficha no esta creada, vuleve a cargar la pagina.'
];
}
} else {
$data = [
'code' => 'LTE-000',
'status' => 'error',
'msg' => 'Lo sentimos, ya se encuentra un usuario registrado con ese correo o con ese documento.'
];
}
} else {
$data = [
'code' => 'LTE-013',
'line' => '82-ficha'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/administrador/actualizarFicha', function () use ($app) {
$json = $app->request->post('json', null);
$helper = new helper();
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$conexion = new conexPG();
$usuarioToken = $helper->authCheck($token, true);
$sql = "select * from seguridad.usuario where id ='$usuarioToken->sub'";
$r = $conexion->consultaComplejaNor($sql);
if (pg_num_rows($r) > 0) {
$parametros = json_decode($json);
$id = (isset($parametros->id)) ? $parametros->id : null;
$sql = "select * from presaber.ficha where id= '$id'";
$r = $conexion->consultaComplejaNor($sql);
if (pg_num_rows($r) > 0) {
$curso_id_fk = (isset($parametros->curso_id_fk)) ? $parametros->curso_id_fk : null;
$contrato_entidad_id_fk = (isset($parametros->contrato_entidad_id_fk)) ? $parametros->contrato_entidad_id_fk : null;
$descripcion = (isset($parametros->descripcion)) ? $parametros->descripcion : null;
$estado = (isset($parametros->estado)) ? $parametros->estado : null;
$usuarios_minimos = (isset($parametros->usuarios_minimos)) ? $parametros->usuarios_minimos : null;
$usuarios_maximos = (isset($parametros->usuarios_maximos)) ? $parametros->usuarios_maximos : null;
$fecha_finalizacion = (isset($parametros->fecha_finalizacion)) ? $parametros->fecha_finalizacion : null;
$fecha_actualizacion = $fecha_creacion = date('Y-m-d H:i:s');
$conexion = new conexPG();
$sql = "UPDATE presaber.ficha
SET curso_id_fk='$curso_id_fk', contrato_entidad_id_fk='$contrato_entidad_id_fk', descripcion='$descripcion', estado='$estado', usuarios_minimos='$usuarios_minimos',
usuarios_maximos='$usuarios_maximos', fecha_finalizacion='$fecha_finalizacion', fecha_actualizacion='$fecha_actualizacion'
WHERE id='$id';";
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-001'
];
} else {
$data = [
'cdoe' => 'LTE-002'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013',
'line' => '19-ficha'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/administrador/leerEstudiantesFicha', function () use ($app) {
$helper = new helper();
$token = $app->request->post('token', null);
$json = $app->request->post('json', null);
if ($json != null) {
if ($token != null) {
$excel = (isset($_FILES['excel'])) ? $_FILES['excel'] : null;
if ($excel != null) {
$parametros = json_decode($json);
$curso_id_fk = (isset($parametros->curso_id_fk)) ? $parametros->curso_id_fk : null;
$contrato_entidad_id_fk = (isset($parametros->contrato_entidad_id_fk)) ? $parametros->contrato_entidad_id_fk : null;
$descripcion = (isset($parametros->descripcion)) ? $parametros->descripcion : null;
$usuarios_minimos = (isset($parametros->usuarios_minimos)) ? $parametros->usuarios_minimos : null;
$usuarios_maximos = (isset($parametros->usuarios_maximos)) ? $parametros->usuarios_maximos : null;
$fecha_finalizacion = (isset($parametros->fecha_finalizacion)) ? $parametros->fecha_finalizacion : null;
$usuarioToken = $helper->authCheck($token, true);
$nombreArchivo = pi_poNombreArchivo($excel);
pi_poEliminarArchivo('/excel/fichaUsuarios/' . $nombreArchivo);
pi_poMove('/excel/fichaUsuarios/', $excel);
$excel = \PhpOffice\PhpSpreadsheet\IOFactory::load('App/public/excel/fichaUsuarios/' . $nombreArchivo);
$excel->setActiveSheetIndex(0);
$filas = $excel->getActiveSheet()->getHighestRow();
$fecha_creacion = $fecha_creacion = date('Y-m-d H:i:s');
$fallidos = Array();
$conexion = new conexPG();
$rutaImagen = '/imagenes_estandar/usuario-64x64.png';
$sql = "select * from presaber.contrato_entidad where id='$contrato_entidad_id_fk'";
$r = $conexion->consultaComplejaNorAso($sql);
$descripcionContratoEntidad = $r['descripcion'];
if ($r != 0) {
$sql = "select id from seguridad.rol WHERE descripcion like 'estudiante' or descripcion like 'ESTUDIANTE'";
$r = $conexion->consultaComplejaNorAso($sql);
$idRol = $r['id'];
$contador = 0;
$contadorTotal = 0;
$cantidadFichasCreadas = 1;
$banderaCrearFicha = 0;
$banderaActivo = 0;
for ($i = 2; $i <= $filas; $i++) {
$fecha_creacion = $fecha_creacion = date('Y-m-d H:i:s');
$documento = $excel->getActiveSheet()->getCell('A' . $i)->getValue();
$nombre = $excel->getActiveSheet()->getCell('B' . $i)->getValue();
$apellido = $excel->getActiveSheet()->getCell('C' . $i)->getValue();
$correo = $excel->getActiveSheet()->getCell('D' . $i)->getValue();
if ($documento != '' || $documento != null || $nombre != '' || $nombre != null || $apellido != '' || $apellido != null || $correo != '' || $correo != null) {
$sql = "select * from seguridad.usuario where documento='$documento' or correo ='$correo'";
$r = $conexion->consultaComplejaAso($sql);
if ($r == 0) {
if ($banderaCrearFicha == 0) {
$sql = "INSERT INTO presaber.ficha(
usuario_administrador_id_fk, curso_id_fk, contrato_entidad_id_fk, descripcion,
estado, usuarios_minimos, usuarios_maximos, fecha_finalizacion, fecha_creacion)
VALUES ('$usuarioToken->sub', '$curso_id_fk', '$contrato_entidad_id_fk', '$descripcion', 'INACTIVO',
'$usuarios_minimos','$usuarios_maximos', '$fecha_finalizacion', '$fecha_creacion') RETURNING id;";
$r = $conexion->consultaComplejaNorAso($sql);
$idFicha = $r['id'];
$banderaCrearFicha = 1;
}
$contrasena = time() . '21';
$pwd = hash('SHA256', $contrasena);
$sql = "INSERT INTO seguridad.usuario(
rol_id_fk, documento, nombre, apellido, correo, contrasena, imagen, fecha_creacion, estado)
VALUES ('$idRol', '$documento', '$nombre', '$apellido', '$correo', '$pwd','$rutaImagen', '$fecha_creacion','ACTIVO') returning id;";
$r = $conexion->consultaComplejaNorAso($sql);
$id_usuario = $r['id'];
pi_poEnviaEmail('<EMAIL>', 'Osiris123', 'Los Tres Editores', $correo, 'Datos de inscripcion.',
pi_po_email_CrearUsuariosFicha($nombre, $descripcionContratoEntidad, $fecha_creacion, $correo, $contrasena));
$sql = "INSERT INTO presaber.ficha_usuario(
usuario_id_fk, ficha_id_fk, usuario_administrador_id_fk, descripcion, estado, fecha_creacion)
VALUES ('$id_usuario','$idFicha', '$usuarioToken->sub', 'Usuario creado por carga de excel', 'ACTIVO', '$fecha_creacion');";
$conexion->consultaSimple($sql);
$contador++;
$contadorTotal++;
if ($contador >= $usuarios_minimos && $banderaActivo == 0) {
$banderaActivo = 1;
$sql = "update presaber.ficha set estado='ACTIVO' where id='$idFicha'";
$conexion->consultaSimple($sql);
}
if ($contador >= $usuarios_maximos) {
$sql = "INSERT INTO presaber.ficha(
usuario_administrador_id_fk, curso_id_fk, contrato_entidad_id_fk, descripcion,
estado, usuarios_minimos, usuarios_maximos, fecha_finalizacion, fecha_creacion)
VALUES ('$usuarioToken->sub', '$curso_id_fk', '$contrato_entidad_id_fk', '$descripcion', 'INACTIVO',
'$usuarios_minimos','$usuarios_maximos', '$fecha_finalizacion', '$fecha_creacion') RETURNING id;";
$r = $conexion->consultaComplejaNorAso($sql);
$idFicha = $r['id'];
$contador = 0;
$cantidadFichasCreadas++;
$banderaActivo = 0;
}
} else {
array_push($fallidos, array([
'documento' => $documento,
'nombre' => $nombre,
'apellido' => $apellido,
'correo' => $correo
]));
}
}
}
$data = [
'code' => 'LTE-001',
'data' => [
'usuarioNoRegistrados' => [
'msg' => 'Las siguientes personas no pudieron ser registradas, por el motivo de que ya existe un correo o un documento.',
'data' => $fallidos
],
'resultadoGeneral' => [
'cantidadRegistrados' => $contadorTotal,
'cantidadFichasCreadas' => $cantidadFichasCreadas
]
]
];
} else {
$data = [
'code' => 'LTE-000',
'status' => 'error',
'msg' => 'Este contrato no existe, por favor recargue la pagina.'
];
}
} else {
$data = [
'code' => 'LTE-000',
'status' => 'error',
'msg' => 'Lo sentimos el archivo excel es requerido'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/administrador/listarFichaContrato', function () use ($app) {
$json = $app->request->post('json', null);
$helper = new helper();
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validarUsuarioToken = $helper->authCheck($token);
if ($validarUsuarioToken == true) {
$conexion = new conexPG();
$parametros = json_decode($json);
$id = (isset($parametros->id)) ? $parametros->id : null;
$sql = "select f.*,c.descripcion as descripcioncurso, c.id as idcurso from presaber.ficha f join presaber.curso
c on f.curso_id_fk=c.id where f.contrato_entidad_id_fk = '$id' order by f.id desc limit 200";
$r = $conexion->consultaComplejaAso($sql);
$data = [
'code' => 'LTE-001',
'data' => $r
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/administrador/listarUsuariosFicha', function () use ($app) {
$json = $app->request->post('json', null);
$helper = new helper();
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$conexion = new conexPG();
$usuarioToken = $helper->authCheck($token, true);
$sql = "select * from seguridad.usuario where id='$usuarioToken->sub'";
$r = $conexion->consultaComplejaAso($sql);
if ($r != 0) {
$parametros = json_decode($json);
$id = (isset($parametros->id)) ? $parametros->id : null;
$sql = "select u.*, ro.descripcion as rol_descripcion from presaber.ficha f
join presaber.ficha_usuario fu on f.id=fu.ficha_id_fk
join seguridad.usuario u on fu.usuario_id_fk = u.id
join seguridad.rol ro on u.rol_id_fk= ro.id
where f.id ='$id' order by u.id desc limit 200";
$r = $conexion->consultaComplejaAso($sql);
$data = [
'code' => 'LTE-001',
'data' => $r
];
} else {
$data = [
'code' => 'LTE-013',
'line' => '432-ficha'
];
}
} else {
$data = [
'code' => 'LTE-013',
'line' => '427-ficha'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/administrador/rolUsuarioFicha', function () use ($app) {
$conexion = new conexPG();
$helper = new helper();
$sql = "select * from seguridad.rol where estado = 'ACTIVO' and descripcion like 'ESTUDIANTE'
or descripcion like 'estudiante'
or descripcion like 'profesor'
or descripcion like 'PROFESOR'";
$r = $conexion->consultaComplejaAso($sql);
$data = [
'code' => 'LTE-001',
'data' => $r
];
echo $helper->checkCode($data);
});
$app->post('/administrador/filtrarFicha', function () use ($app) {
$json = $app->request->post('json', null);
$toke = $app->request->post('token', null);
$helper = new helper();
if ($json != null) {
if ($toke != null) {
$validarToke = $helper->authCheck($toke);
if ($validarToke == true) {
$parametros = json_decode($json);
$filtro = (isset($parametros->filtro)) ? $parametros->filtro : null;
$id = (isset($parametros->id)) ? $parametros->id : null;
$sql = "select f.*,c.descripcion as descripcioncurso, c.id as idcurso from presaber.ficha f join presaber.curso
c on f.curso_id_fk=c.id where f.contrato_entidad_id_fk = '$id' and f.id = '$filtro' order by f.id desc limit 200";
$conexion = new conexPG();
$r = $conexion->consultaComplejaAso($sql);
if ($r != 0) {
$data = [
'code' => 'LTE-001',
'data' => $r
];
} else {
$data = [
'code' => 'LTE-003'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-010'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/administrador/filtroUsuarioFicha', function () use ($app) {
$json = $app->request->post('json', null);
$toke = $app->request->post('token', null);
$helper = new helper();
if ($json != null) {
if ($toke != null) {
$validarToke = $helper->authCheck($toke);
if ($validarToke == true) {
$parametros = json_decode($json);
$id = (isset($parametros->id)) ? $parametros->id : null;
$filtro = (isset($parametros->filstro)) ? $parametros->filtro : $parametros->filtro;
$sql = "select u.*, ro.descripcion as rol_descripcion from presaber.ficha f
join presaber.ficha_usuario fu on f.id=fu.ficha_id_fk
join seguridad.usuario u on fu.usuario_id_fk = u.id
join seguridad.rol ro on u.rol_id_fk= ro.id
where f.id ='$id' and u.correo like '%$filtro%' or u.nombre like '%$filtro%' or u.documento like '%$filtro%' order by u.id desc limit 200";
$conexion = new conexPG();
$r = $conexion->consultaComplejaAso($sql);
if ($r != 0) {
$data = [
'code' => 'LTE-001',
'data' => $r
];
} else {
$data = [
'code' => 'LTE-003'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-010'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/administrador/cargarUsuariosFicha', function () use ($app) {
$helper = new helper();
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$excel = (isset($_FILES['excel'])) ? $_FILES['excel'] : null;
if ($excel != null) {
$nombreArchivo = pi_poNombreArchivo($excel);
pi_poEliminarArchivo('/excel/usuariosFicha/' . $nombreArchivo);
pi_poMove('/excel/usuariosFicha/', $excel);
$excel = \PhpOffice\PhpSpreadsheet\IOFactory::load('App/public/excel/usuariosFicha/' . $nombreArchivo);
$excel->setActiveSheetIndex(0);
$filas = $excel->getActiveSheet()->getHighestColumn();
die();
} else {
$data = [
'code' => 'LTE-000',
'status' => 'error',
'msg' => 'Lo sentimos el archivo excel es requerido'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});<file_sep>/PreSaber-Nuevo/src/app/services/evaluacion_services/pregunta.service.ts
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {Injectable} from "@angular/core";
import {Observable} from "rxjs/Observable";
import {GLOBAL} from "../global";
@Injectable()
export class PreguntaService{
public url:string;
constructor(private _Http: HttpClient)
{
this.url = GLOBAL.url;
}
listar(token,objSesion): Observable<any>
{
let json = JSON.stringify(objSesion);
let params = 'token='+token+'&json='+json;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Http.post(this.url + 'profesor/listarPregunta', params, {headers: headers});
}
cargarPregunta(token,idPregunta): Observable<any>
{
let json = '{"id_pregunta":"'+idPregunta+'"}';
let params = 'token='+token+'&json='+json;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Http.post(this.url + 'profesor/cargarPregunta', params, {headers: headers});
}
eliminar(token,idPregunta): Observable<any>
{
let json = '{"id_pregunta":"'+idPregunta+'"}';
let params = 'token='+token+'&json='+json;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Http.post(this.url + 'profesor/eliminarPregunta', params, {headers: headers});
}
}
<file_sep>/php-backend/App/componentes/configuracion/subir_archivo.php
<?php
$app->post('/pi_po/imagenesEditor', function () use ($app) {
$imagen = $_FILES['ImagenEditore'];
$nombre = time().'21';
pi_poMove('/imaganes/editores/',$imagen,$nombre);
$data =[
'link'=>"http://localhost/LTE/trunk/php-backend/App/public/imaganes/editores/".$nombre.'.'.pi_poExtenssion($imagen)
];
echo json_encode($data);
});
$app->post('/pi_po/archivosEditor', function () use ($app) {
$imagen = $_FILES['Archivo'];
$extension = explode('.',pi_poNombreArchivo($imagen));
$nombre = time().'21'.'.'.end($extension);
$rutaCompleta='App/public/archivos/editores/';
move_uploaded_file($imagen["tmp_name"],$rutaCompleta.$nombre);
$data =[
'link'=>"http://localhost/LTE/trunk/php-backend/App/public/archivos/editores/".$nombre
];
echo json_encode($data);
});<file_sep>/php-backend/App/componentes/profesor/respuesta.php
<?php
$app->post('/profesor/crearRespuesta', function () use ($app) {
$helper = new helper();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$parametros = json_decode($json);
$descripcion_respuesta = htmlspecialchars((isset($parametros->descripcion_respuesta)) ? $parametros->descripcion_respuesta : null, ENT_QUOTES);
$correcta_respuesta = (isset($parametros->correcta_respuesta)) ? $parametros->correcta_respuesta : null;
$pregunta_id_fk = (isset($parametros->pregunta_id_fk)) ? $parametros->pregunta_id_fk : null;
$conexion = new conexPG();
$sql = "INSERT INTO evaluacion.respuesta(
pregunta_id_fk, descripcion_respuesta, correcta_respuesta)
VALUES ($pregunta_id_fk, '$descripcion_respuesta', '$correcta_respuesta');";
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-001'
];
} else {
$data = [
'code' => 'LTE-013',
'line' => '140'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/actualizarRespuesta', function () use ($app) {
$helper = new helper();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$parametros = json_decode($json);
$id_respuesta = (isset($parametros->id_respuesta)) ? $parametros->id_respuesta : null;
$descripcion_respuesta = htmlspecialchars((isset($parametros->descripcion_respuesta)) ? $parametros->descripcion_respuesta : null, ENT_QUOTES);
$correcta_respuesta = (isset($parametros->correcta_respuesta)) ? $parametros->correcta_respuesta : null;
$conexion = new conexPG();
$sql = "UPDATE evaluacion.respuesta
SET descripcion_respuesta='$descripcion_respuesta', correcta_respuesta='$correcta_respuesta'
WHERE id_respuesta='$id_respuesta';";
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-007'
];
} else {
$data = [
'code' => 'LTE-013',
'line' => '140'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/eliminarRespuesta', function () use ($app) {
$helper = new helper();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$parametros = json_decode($json);
$id_respuesta = (isset($parametros->id_respuesta)) ? $parametros->id_respuesta : null;
$conexion = new conexPG();
$sql = "DELETE FROM evaluacion.respuesta
WHERE id_respuesta='$id_respuesta';";
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-008'
];
} else {
$data = [
'code' => 'LTE-013',
'line' => '140'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/listarRespuesta', function () use ($app) {
$helper = new helper();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$parametros = json_decode($json);
$id_pregunta = (isset($parametros->id_pregunta)) ? $parametros->id_pregunta : null;
$conexion = new conexPG();
$sql = "select r.* from evaluacion.respuesta r where r.pregunta_id_fk ='$id_pregunta' order by r.id_respuesta desc limit 200;";
$r = $conexion->consultaComplejaAso($sql);
$result = [];
for ($i = 0; $i < count($r); $i++) {
array_push($result, ['id_respuesta' => $r[$i]["id_respuesta"],
'pregunta_id_fk' => $r[$i]["pregunta_id_fk"],
'descripcion_respuesta' => html_entity_decode($r[$i]["descripcion_respuesta"]),
'correcta_respuesta' => $r[$i]["correcta_respuesta"]]);
}
$data = [
'code' => 'LTE-001',
'data' => $result
];
} else {
$data = [
'code' => 'LTE-013',
'line' => '140'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});<file_sep>/otros/sql/19052018.sql
-- Database generated with pgModeler (PostgreSQL Database Modeler).
-- pgModeler version: 0.8.2
-- PostgreSQL version: 9.5
-- Project Site: pgmodeler.com.br
-- Model Author: ---
-- Database creation must be done outside an multicommand file.
-- These commands were put in this file only for convenience.
-- -- object: new_database | type: DATABASE --
-- -- DROP DATABASE IF EXISTS new_database;
-- CREATE DATABASE new_database
-- ;
-- -- ddl-end --
--
-- object: seguridad | type: SCHEMA --
-- DROP SCHEMA IF EXISTS seguridad CASCADE;
CREATE SCHEMA seguridad;
-- ddl-end --
ALTER SCHEMA seguridad OWNER TO postgres;
-- ddl-end --
-- object: presaber | type: SCHEMA --
-- DROP SCHEMA IF EXISTS presaber CASCADE;
CREATE SCHEMA presaber;
-- ddl-end --
ALTER SCHEMA presaber OWNER TO postgres;
-- ddl-end --
-- object: evaluacion | type: SCHEMA --
-- DROP SCHEMA IF EXISTS evaluacion CASCADE;
CREATE SCHEMA evaluacion;
-- ddl-end --
ALTER SCHEMA evaluacion OWNER TO postgres;
-- ddl-end --
-- object: configuracion | type: SCHEMA --
-- DROP SCHEMA IF EXISTS configuracion CASCADE;
CREATE SCHEMA configuracion;
-- ddl-end --
ALTER SCHEMA configuracion OWNER TO postgres;
-- ddl-end --
-- object: evaluacion_cp | type: SCHEMA --
-- DROP SCHEMA IF EXISTS evaluacion_cp CASCADE;
CREATE SCHEMA evaluacion_cp;
-- ddl-end --
ALTER SCHEMA evaluacion_cp OWNER TO postgres;
-- ddl-end --
SET search_path TO pg_catalog,public,seguridad,presaber,evaluacion,configuracion,evaluacion_cp;
-- ddl-end --
-- object: seguridad.usuario | type: TABLE --
-- DROP TABLE IF EXISTS seguridad.usuario CASCADE;
CREATE TABLE seguridad.usuario(
id serial NOT NULL,
rol_id_fk integer,
documento varchar(100),
nombre varchar(100),
apellido varchar(100),
correo varchar(150),
contrasena varchar(100),
codigo_activacion varchar(50),
imagen varchar(100),
estado varchar(10),
ultimo_ingreso timestamp,
fecha_creacion timestamp,
fecha_actualizacion timestamp,
CONSTRAINT pk_user_id PRIMARY KEY (id)
);
-- ddl-end --
ALTER TABLE seguridad.usuario OWNER TO postgres;
-- ddl-end --
-- object: seguridad.rol | type: TABLE --
-- DROP TABLE IF EXISTS seguridad.rol CASCADE;
CREATE TABLE seguridad.rol(
id serial NOT NULL,
descripcion varchar(100),
estado varchar(10),
fecha_creacion timestamp,
fecha_actualizacion timestamp,
CONSTRAINT pk_role_id PRIMARY KEY (id)
);
-- ddl-end --
ALTER TABLE seguridad.rol OWNER TO postgres;
-- ddl-end --
-- object: presaber.curso | type: TABLE --
-- DROP TABLE IF EXISTS presaber.curso CASCADE;
CREATE TABLE presaber.curso(
id serial NOT NULL,
usuario_administrador_id_fk integer,
descripcion varchar(150),
estado varchar(10),
imagen varchar(100),
fecha_creacion timestamp,
fecha_actualizacion timestamp,
CONSTRAINT pk_course PRIMARY KEY (id)
);
-- ddl-end --
ALTER TABLE presaber.curso OWNER TO postgres;
-- ddl-end --
-- object: presaber.ficha | type: TABLE --
-- DROP TABLE IF EXISTS presaber.ficha CASCADE;
CREATE TABLE presaber.ficha(
id serial NOT NULL,
usuario_administrador_id_fk integer,
curso_id_fk integer,
contrato_entidad_id_fk integer,
descripcion varchar(150),
estado varchar(10),
usuarios_minimos integer,
usuarios_maximos integer,
fecha_finalizacion timestamp,
fecha_creacion timestamp,
fecha_actualizacion timestamp,
CONSTRAINT pk_id PRIMARY KEY (id)
);
-- ddl-end --
ALTER TABLE presaber.ficha OWNER TO postgres;
-- ddl-end --
-- object: presaber.ficha_usuario | type: TABLE --
-- DROP TABLE IF EXISTS presaber.ficha_usuario CASCADE;
CREATE TABLE presaber.ficha_usuario(
id serial NOT NULL,
usuario_id_fk integer,
ficha_id_fk integer,
usuario_administrador_id_fk integer,
descripcion varchar(150),
estado varchar(10),
fecha_creacion timestamp,
fecha_actualizacion timestamp,
CONSTRAINT pk_equipment_has_user_id PRIMARY KEY (id)
);
-- ddl-end --
ALTER TABLE presaber.ficha_usuario OWNER TO postgres;
-- ddl-end --
-- object: presaber.modulo | type: TABLE --
-- DROP TABLE IF EXISTS presaber.modulo CASCADE;
CREATE TABLE presaber.modulo(
id serial NOT NULL,
curso_id_fk integer,
usuario_administrador_id_fk integer,
descripcion varchar(150),
prioridad integer,
imagen varchar(100),
estado varchar(10),
fecha_creacion timestamp,
fecha_actualizacion timestamp,
usuario_profesor_id_fk integer,
CONSTRAINT pk_module PRIMARY KEY (id)
);
-- ddl-end --
ALTER TABLE presaber.modulo OWNER TO postgres;
-- ddl-end --
-- object: presaber.recurso | type: TABLE --
-- DROP TABLE IF EXISTS presaber.recurso CASCADE;
CREATE TABLE presaber.recurso(
id serial NOT NULL,
usuario_profesor_id_fk integer,
tipo_recurso_id_fk integer,
descripcion varchar(150),
contenido text,
fecha_creacion timestamp,
fecha_actualizacion timestamp,
estado varchar(10),
CONSTRAINT pk_resource PRIMARY KEY (id)
);
-- ddl-end --
ALTER TABLE presaber.recurso OWNER TO postgres;
-- ddl-end --
-- object: presaber.recurso_usuario | type: TABLE --
-- DROP TABLE IF EXISTS presaber.recurso_usuario CASCADE;
CREATE TABLE presaber.recurso_usuario(
id serial NOT NULL,
ficha_usuario_id_fk integer,
recurso_id_fk integer,
usuario_profesor_id_fk integer,
descripcion varchar(150),
estado varchar(10),
prioridad integer,
imagen varchar(100),
fecha_creacion timestamp,
fecha_actualizacion timestamp,
CONSTRAINT pk_resource_has_user PRIMARY KEY (id)
);
-- ddl-end --
ALTER TABLE presaber.recurso_usuario OWNER TO postgres;
-- ddl-end --
-- object: presaber.seccion | type: TABLE --
-- DROP TABLE IF EXISTS presaber.seccion CASCADE;
CREATE TABLE presaber.seccion(
id serial NOT NULL,
modulo_id_fk integer,
usuario_profesor_id_fk integer,
description varchar(150),
prioridad integer,
imagen varchar(100),
estado varchar(100),
fecha_creacion timestamp,
fecha_actualizacion timestamp,
CONSTRAINT pk_section PRIMARY KEY (id)
);
-- ddl-end --
ALTER TABLE presaber.seccion OWNER TO postgres;
-- ddl-end --
-- object: presaber.seccion_recurso | type: TABLE --
-- DROP TABLE IF EXISTS presaber.seccion_recurso CASCADE;
CREATE TABLE presaber.seccion_recurso(
id serial NOT NULL,
seccion_id_fk integer,
recurso_id_fk integer,
usuario_profesor_id_fk integer,
descripcion varchar(150),
estado varchar(10),
prioridad integer,
imagen varchar(100),
fecha_creacion timestamp,
fecha_actualizacion timestamp,
CONSTRAINT pk_section_has_user PRIMARY KEY (id)
);
-- ddl-end --
ALTER TABLE presaber.seccion_recurso OWNER TO postgres;
-- ddl-end --
-- object: presaber.tipo_recurso | type: TABLE --
-- DROP TABLE IF EXISTS presaber.tipo_recurso CASCADE;
CREATE TABLE presaber.tipo_recurso(
id serial NOT NULL,
descripcion varchar(150),
estado varchar(10),
fecha_creacion timestamp,
fecha_actualizacion timestamp,
CONSTRAINT pk_type_resource PRIMARY KEY (id)
);
-- ddl-end --
ALTER TABLE presaber.tipo_recurso OWNER TO postgres;
-- ddl-end --
-- object: presaber.contrato_entidad | type: TABLE --
-- DROP TABLE IF EXISTS presaber.contrato_entidad CASCADE;
CREATE TABLE presaber.contrato_entidad(
id serial NOT NULL,
usuario_administrador_id_fk integer,
descripcion varchar(250),
ciudad_id_fk integer,
estado varchar(100),
tipo varchar(100),
imagen varchar(100),
fecha_creacion timestamp,
fecha_actualizacion timestamp,
CONSTRAINT pk_entity_contract PRIMARY KEY (id)
);
-- ddl-end --
ALTER TABLE presaber.contrato_entidad OWNER TO postgres;
-- ddl-end --
-- object: evaluacion.examen_taller | type: TABLE --
-- DROP TABLE IF EXISTS evaluacion.examen_taller CASCADE;
CREATE TABLE evaluacion.examen_taller(
id_examen serial NOT NULL,
base_examen_id_fk integer,
descripcion_examen varchar(120),
fecha_creacion_examen timestamp,
fecha_actualizacion_examen timestamp,
estado_examen varchar(50) NOT NULL,
CONSTRAINT pk_examen_aller_id PRIMARY KEY (id_examen)
);
-- ddl-end --
ALTER TABLE evaluacion.examen_taller OWNER TO postgres;
-- ddl-end --
-- object: evaluacion.pregunta | type: TABLE --
-- DROP TABLE IF EXISTS evaluacion.pregunta CASCADE;
CREATE TABLE evaluacion.pregunta(
id_pregunta serial NOT NULL,
sesion_id_fk integer,
contexto text,
pregunta text,
justificacion text,
compentencia_id_fk integer,
componente_id_fk integer,
CONSTRAINT pk_pregunta_id PRIMARY KEY (id_pregunta)
);
-- ddl-end --
ALTER TABLE evaluacion.pregunta OWNER TO postgres;
-- ddl-end --
-- object: evaluacion.respuesta | type: TABLE --
-- DROP TABLE IF EXISTS evaluacion.respuesta CASCADE;
CREATE TABLE evaluacion.respuesta(
id_respuesta serial NOT NULL,
pregunta_id_fk integer,
tipo_repuesta varchar(150),
descripcion_respuesta text,
correcta_respuesta varchar(100),
CONSTRAINT pk_respuesta_id PRIMARY KEY (id_respuesta)
);
-- ddl-end --
ALTER TABLE evaluacion.respuesta OWNER TO postgres;
-- ddl-end --
-- object: evaluacion.sesion | type: TABLE --
-- DROP TABLE IF EXISTS evaluacion.sesion CASCADE;
CREATE TABLE evaluacion.sesion(
id_sesion serial NOT NULL,
examen_taller_id_fk integer,
descripcion_sesion varchar(120),
CONSTRAINT pk_sesion_id PRIMARY KEY (id_sesion)
);
-- ddl-end --
ALTER TABLE evaluacion.sesion OWNER TO postgres;
-- ddl-end --
-- object: evaluacion.base_examen | type: TABLE --
-- DROP TABLE IF EXISTS evaluacion.base_examen CASCADE;
CREATE TABLE evaluacion.base_examen(
id_base_examen serial NOT NULL,
descripcion_base_examen varchar(120),
fecha_creacion_base_examen timestamp,
fecha_actualizacion_base_examen timestamp,
CONSTRAINT base_examen_id_fk PRIMARY KEY (id_base_examen)
);
-- ddl-end --
ALTER TABLE evaluacion.base_examen OWNER TO postgres;
-- ddl-end --
-- object: seguridad.menu | type: TABLE --
-- DROP TABLE IF EXISTS seguridad.menu CASCADE;
CREATE TABLE seguridad.menu(
id serial NOT NULL,
descripcion varchar(120),
CONSTRAINT pk_menu_id PRIMARY KEY (id)
);
-- ddl-end --
ALTER TABLE seguridad.menu OWNER TO postgres;
-- ddl-end --
-- object: seguridad.permiso | type: TABLE --
-- DROP TABLE IF EXISTS seguridad.permiso CASCADE;
CREATE TABLE seguridad.permiso(
id serial NOT NULL,
role_id_fk integer,
menu_id_fk integer,
estado varchar(60),
CONSTRAINT pk_permiso_id PRIMARY KEY (id)
);
-- ddl-end --
ALTER TABLE seguridad.permiso OWNER TO postgres;
-- ddl-end --
-- object: configuracion.pais | type: TABLE --
-- DROP TABLE IF EXISTS configuracion.pais CASCADE;
CREATE TABLE configuracion.pais(
id serial NOT NULL,
descripcion varchar(250),
CONSTRAINT ph_pais_id PRIMARY KEY (id)
);
-- ddl-end --
ALTER TABLE configuracion.pais OWNER TO postgres;
-- ddl-end --
-- object: configuracion.departamento | type: TABLE --
-- DROP TABLE IF EXISTS configuracion.departamento CASCADE;
CREATE TABLE configuracion.departamento(
id serial NOT NULL,
descripcion varchar(250),
pais_id_fk integer,
CONSTRAINT pk_departamento_id PRIMARY KEY (id)
);
-- ddl-end --
ALTER TABLE configuracion.departamento OWNER TO postgres;
-- ddl-end --
-- object: configuracion.ciudad | type: TABLE --
-- DROP TABLE IF EXISTS configuracion.ciudad CASCADE;
CREATE TABLE configuracion.ciudad(
id serial NOT NULL,
descripcion varchar(250),
departamento_id_fk integer,
CONSTRAINT pk_ciudad_id PRIMARY KEY (id)
);
-- ddl-end --
ALTER TABLE configuracion.ciudad OWNER TO postgres;
-- ddl-end --
-- object: evaluacion.configuracion | type: TABLE --
-- DROP TABLE IF EXISTS evaluacion.configuracion CASCADE;
CREATE TABLE evaluacion.configuracion(
id_configuracion serial NOT NULL,
repetir_bool varchar(100),
cantidad_intentos varchar(100),
mesclar_preguntas varchar(100),
mesclar_respuestas varchar(100),
contrasena_bool varchar(100),
contrasena varchar(250),
examen_id_fk integer,
CONSTRAINT pk_configuracion_di PRIMARY KEY (id_configuracion)
);
-- ddl-end --
ALTER TABLE evaluacion.configuracion OWNER TO postgres;
-- ddl-end --
-- object: evaluacion.competencia | type: TABLE --
-- DROP TABLE IF EXISTS evaluacion.competencia CASCADE;
CREATE TABLE evaluacion.competencia(
id_competencia serial NOT NULL,
descripcion_competencia varchar(250),
fecha_creacion_competencia timestamp,
fecha_actualizacion_competencia timestamp,
CONSTRAINT pk_competencia_di PRIMARY KEY (id_competencia)
);
-- ddl-end --
ALTER TABLE evaluacion.competencia OWNER TO postgres;
-- ddl-end --
-- object: evaluacion.componente | type: TABLE --
-- DROP TABLE IF EXISTS evaluacion.componente CASCADE;
CREATE TABLE evaluacion.componente(
id_componente serial NOT NULL,
descripcion_componente varchar(250),
fecha_creacion_componente timestamp,
fecha_actualizacion_componente timestamp,
CONSTRAINT pk_id_componente PRIMARY KEY (id_componente)
);
-- ddl-end --
ALTER TABLE evaluacion.componente OWNER TO postgres;
-- ddl-end --
-- object: usuario_rol_id_fk | type: CONSTRAINT --
-- ALTER TABLE seguridad.usuario DROP CONSTRAINT IF EXISTS usuario_rol_id_fk CASCADE;
ALTER TABLE seguridad.usuario ADD CONSTRAINT usuario_rol_id_fk FOREIGN KEY (rol_id_fk)
REFERENCES seguridad.rol (id) MATCH FULL
ON DELETE RESTRICT ON UPDATE CASCADE;
-- ddl-end --
-- object: curso_usuario_administrador_id_fk | type: CONSTRAINT --
-- ALTER TABLE presaber.curso DROP CONSTRAINT IF EXISTS curso_usuario_administrador_id_fk CASCADE;
ALTER TABLE presaber.curso ADD CONSTRAINT curso_usuario_administrador_id_fk FOREIGN KEY (usuario_administrador_id_fk)
REFERENCES seguridad.usuario (id) MATCH FULL
ON DELETE RESTRICT ON UPDATE CASCADE;
-- ddl-end --
-- object: ficha_usuario_administrador_id_fk | type: CONSTRAINT --
-- ALTER TABLE presaber.ficha DROP CONSTRAINT IF EXISTS ficha_usuario_administrador_id_fk CASCADE;
ALTER TABLE presaber.ficha ADD CONSTRAINT ficha_usuario_administrador_id_fk FOREIGN KEY (usuario_administrador_id_fk)
REFERENCES seguridad.usuario (id) MATCH FULL
ON DELETE RESTRICT ON UPDATE CASCADE;
-- ddl-end --
-- object: ficha_curso_id_fk | type: CONSTRAINT --
-- ALTER TABLE presaber.ficha DROP CONSTRAINT IF EXISTS ficha_curso_id_fk CASCADE;
ALTER TABLE presaber.ficha ADD CONSTRAINT ficha_curso_id_fk FOREIGN KEY (curso_id_fk)
REFERENCES presaber.curso (id) MATCH FULL
ON DELETE RESTRICT ON UPDATE CASCADE;
-- ddl-end --
-- object: ficha_contrato_entidad_fk_id | type: CONSTRAINT --
-- ALTER TABLE presaber.ficha DROP CONSTRAINT IF EXISTS ficha_contrato_entidad_fk_id CASCADE;
ALTER TABLE presaber.ficha ADD CONSTRAINT ficha_contrato_entidad_fk_id FOREIGN KEY (contrato_entidad_id_fk)
REFERENCES presaber.contrato_entidad (id) MATCH FULL
ON DELETE RESTRICT ON UPDATE CASCADE;
-- ddl-end --
-- object: ficha_usuario_ficha_id_fk | type: CONSTRAINT --
-- ALTER TABLE presaber.ficha_usuario DROP CONSTRAINT IF EXISTS ficha_usuario_ficha_id_fk CASCADE;
ALTER TABLE presaber.ficha_usuario ADD CONSTRAINT ficha_usuario_ficha_id_fk FOREIGN KEY (ficha_id_fk)
REFERENCES presaber.ficha (id) MATCH FULL
ON DELETE RESTRICT ON UPDATE CASCADE;
-- ddl-end --
-- object: ficha_usuario_usuario_id_fk | type: CONSTRAINT --
-- ALTER TABLE presaber.ficha_usuario DROP CONSTRAINT IF EXISTS ficha_usuario_usuario_id_fk CASCADE;
ALTER TABLE presaber.ficha_usuario ADD CONSTRAINT ficha_usuario_usuario_id_fk FOREIGN KEY (usuario_id_fk)
REFERENCES seguridad.usuario (id) MATCH FULL
ON DELETE RESTRICT ON UPDATE CASCADE;
-- ddl-end --
-- object: ficha_usuario_usuario_admin_id_fk | type: CONSTRAINT --
-- ALTER TABLE presaber.ficha_usuario DROP CONSTRAINT IF EXISTS ficha_usuario_usuario_admin_id_fk CASCADE;
ALTER TABLE presaber.ficha_usuario ADD CONSTRAINT ficha_usuario_usuario_admin_id_fk FOREIGN KEY (usuario_administrador_id_fk)
REFERENCES seguridad.usuario (id) MATCH FULL
ON DELETE RESTRICT ON UPDATE CASCADE;
-- ddl-end --
-- object: modulo_curso_id_fk | type: CONSTRAINT --
-- ALTER TABLE presaber.modulo DROP CONSTRAINT IF EXISTS modulo_curso_id_fk CASCADE;
ALTER TABLE presaber.modulo ADD CONSTRAINT modulo_curso_id_fk FOREIGN KEY (curso_id_fk)
REFERENCES presaber.curso (id) MATCH FULL
ON DELETE RESTRICT ON UPDATE CASCADE;
-- ddl-end --
-- object: modulo_usuario_administrador_id_fk | type: CONSTRAINT --
-- ALTER TABLE presaber.modulo DROP CONSTRAINT IF EXISTS modulo_usuario_administrador_id_fk CASCADE;
ALTER TABLE presaber.modulo ADD CONSTRAINT modulo_usuario_administrador_id_fk FOREIGN KEY (usuario_administrador_id_fk)
REFERENCES seguridad.usuario (id) MATCH FULL
ON DELETE RESTRICT ON UPDATE CASCADE;
-- ddl-end --
-- object: fk_modulo_usuario_id | type: CONSTRAINT --
-- ALTER TABLE presaber.modulo DROP CONSTRAINT IF EXISTS fk_modulo_usuario_id CASCADE;
ALTER TABLE presaber.modulo ADD CONSTRAINT fk_modulo_usuario_id FOREIGN KEY (usuario_profesor_id_fk)
REFERENCES seguridad.usuario (id) MATCH FULL
ON DELETE RESTRICT ON UPDATE CASCADE;
-- ddl-end --
-- object: recurso_usuario_profesor_id_fk | type: CONSTRAINT --
-- ALTER TABLE presaber.recurso DROP CONSTRAINT IF EXISTS recurso_usuario_profesor_id_fk CASCADE;
ALTER TABLE presaber.recurso ADD CONSTRAINT recurso_usuario_profesor_id_fk FOREIGN KEY (usuario_profesor_id_fk)
REFERENCES seguridad.usuario (id) MATCH FULL
ON DELETE RESTRICT ON UPDATE CASCADE;
-- ddl-end --
-- object: recurso_tipo_recurso_fk | type: CONSTRAINT --
-- ALTER TABLE presaber.recurso DROP CONSTRAINT IF EXISTS recurso_tipo_recurso_fk CASCADE;
ALTER TABLE presaber.recurso ADD CONSTRAINT recurso_tipo_recurso_fk FOREIGN KEY (tipo_recurso_id_fk)
REFERENCES presaber.tipo_recurso (id) MATCH FULL
ON DELETE RESTRICT ON UPDATE CASCADE;
-- ddl-end --
-- object: recurso_usuario_ficha_usuario_fk_id | type: CONSTRAINT --
-- ALTER TABLE presaber.recurso_usuario DROP CONSTRAINT IF EXISTS recurso_usuario_ficha_usuario_fk_id CASCADE;
ALTER TABLE presaber.recurso_usuario ADD CONSTRAINT recurso_usuario_ficha_usuario_fk_id FOREIGN KEY (ficha_usuario_id_fk)
REFERENCES presaber.ficha_usuario (id) MATCH FULL
ON DELETE RESTRICT ON UPDATE CASCADE;
-- ddl-end --
-- object: recurso_usuario_recurso_id_fk | type: CONSTRAINT --
-- ALTER TABLE presaber.recurso_usuario DROP CONSTRAINT IF EXISTS recurso_usuario_recurso_id_fk CASCADE;
ALTER TABLE presaber.recurso_usuario ADD CONSTRAINT recurso_usuario_recurso_id_fk FOREIGN KEY (recurso_id_fk)
REFERENCES presaber.recurso (id) MATCH FULL
ON DELETE RESTRICT ON UPDATE CASCADE;
-- ddl-end --
-- object: recurso_usuario_usuario_profesor_id_fk | type: CONSTRAINT --
-- ALTER TABLE presaber.recurso_usuario DROP CONSTRAINT IF EXISTS recurso_usuario_usuario_profesor_id_fk CASCADE;
ALTER TABLE presaber.recurso_usuario ADD CONSTRAINT recurso_usuario_usuario_profesor_id_fk FOREIGN KEY (usuario_profesor_id_fk)
REFERENCES seguridad.usuario (id) MATCH FULL
ON DELETE RESTRICT ON UPDATE RESTRICT;
-- ddl-end --
-- object: seccion_modulo_id_fk | type: CONSTRAINT --
-- ALTER TABLE presaber.seccion DROP CONSTRAINT IF EXISTS seccion_modulo_id_fk CASCADE;
ALTER TABLE presaber.seccion ADD CONSTRAINT seccion_modulo_id_fk FOREIGN KEY (modulo_id_fk)
REFERENCES presaber.modulo (id) MATCH FULL
ON DELETE RESTRICT ON UPDATE CASCADE;
-- ddl-end --
-- object: seccion_user_profesor_id_fk | type: CONSTRAINT --
-- ALTER TABLE presaber.seccion DROP CONSTRAINT IF EXISTS seccion_user_profesor_id_fk CASCADE;
ALTER TABLE presaber.seccion ADD CONSTRAINT seccion_user_profesor_id_fk FOREIGN KEY (usuario_profesor_id_fk)
REFERENCES seguridad.usuario (id) MATCH FULL
ON DELETE RESTRICT ON UPDATE CASCADE;
-- ddl-end --
-- object: seccion_usuario_seccion_id_fk | type: CONSTRAINT --
-- ALTER TABLE presaber.seccion_recurso DROP CONSTRAINT IF EXISTS seccion_usuario_seccion_id_fk CASCADE;
ALTER TABLE presaber.seccion_recurso ADD CONSTRAINT seccion_usuario_seccion_id_fk FOREIGN KEY (seccion_id_fk)
REFERENCES presaber.seccion (id) MATCH FULL
ON DELETE RESTRICT ON UPDATE CASCADE;
-- ddl-end --
-- object: seccion_usuario_recurso_id_fk | type: CONSTRAINT --
-- ALTER TABLE presaber.seccion_recurso DROP CONSTRAINT IF EXISTS seccion_usuario_recurso_id_fk CASCADE;
ALTER TABLE presaber.seccion_recurso ADD CONSTRAINT seccion_usuario_recurso_id_fk FOREIGN KEY (recurso_id_fk)
REFERENCES presaber.recurso (id) MATCH FULL
ON DELETE RESTRICT ON UPDATE CASCADE;
-- ddl-end --
-- object: seccion_usuario_usuario_profesor_id_fk | type: CONSTRAINT --
-- ALTER TABLE presaber.seccion_recurso DROP CONSTRAINT IF EXISTS seccion_usuario_usuario_profesor_id_fk CASCADE;
ALTER TABLE presaber.seccion_recurso ADD CONSTRAINT seccion_usuario_usuario_profesor_id_fk FOREIGN KEY (usuario_profesor_id_fk)
REFERENCES seguridad.usuario (id) MATCH FULL
ON DELETE RESTRICT ON UPDATE CASCADE;
-- ddl-end --
-- object: contrato_entidad_usuario_administrador_id_fk | type: CONSTRAINT --
-- ALTER TABLE presaber.contrato_entidad DROP CONSTRAINT IF EXISTS contrato_entidad_usuario_administrador_id_fk CASCADE;
ALTER TABLE presaber.contrato_entidad ADD CONSTRAINT contrato_entidad_usuario_administrador_id_fk FOREIGN KEY (usuario_administrador_id_fk)
REFERENCES seguridad.usuario (id) MATCH FULL
ON DELETE RESTRICT ON UPDATE CASCADE;
-- ddl-end --
-- object: fk_contrato_entidad_ciudad_id | type: CONSTRAINT --
-- ALTER TABLE presaber.contrato_entidad DROP CONSTRAINT IF EXISTS fk_contrato_entidad_ciudad_id CASCADE;
ALTER TABLE presaber.contrato_entidad ADD CONSTRAINT fk_contrato_entidad_ciudad_id FOREIGN KEY (ciudad_id_fk)
REFERENCES configuracion.ciudad (id) MATCH FULL
ON DELETE RESTRICT ON UPDATE CASCADE;
-- ddl-end --
-- object: base_examen_id_fk | type: CONSTRAINT --
-- ALTER TABLE evaluacion.examen_taller DROP CONSTRAINT IF EXISTS base_examen_id_fk CASCADE;
ALTER TABLE evaluacion.examen_taller ADD CONSTRAINT base_examen_id_fk FOREIGN KEY (base_examen_id_fk)
REFERENCES evaluacion.base_examen (id_base_examen) MATCH FULL
ON DELETE NO ACTION ON UPDATE NO ACTION;
-- ddl-end --
-- object: fk_sesion_pregunta_fk | type: CONSTRAINT --
-- ALTER TABLE evaluacion.pregunta DROP CONSTRAINT IF EXISTS fk_sesion_pregunta_fk CASCADE;
ALTER TABLE evaluacion.pregunta ADD CONSTRAINT fk_sesion_pregunta_fk FOREIGN KEY (sesion_id_fk)
REFERENCES evaluacion.sesion (id_sesion) MATCH FULL
ON DELETE RESTRICT ON UPDATE CASCADE;
-- ddl-end --
-- object: fk_pregunta_competencia_di | type: CONSTRAINT --
-- ALTER TABLE evaluacion.pregunta DROP CONSTRAINT IF EXISTS fk_pregunta_competencia_di CASCADE;
ALTER TABLE evaluacion.pregunta ADD CONSTRAINT fk_pregunta_competencia_di FOREIGN KEY (compentencia_id_fk)
REFERENCES evaluacion.competencia (id_competencia) MATCH FULL
ON DELETE RESTRICT ON UPDATE CASCADE;
-- ddl-end --
-- object: fk_pregunta_componente_id | type: CONSTRAINT --
-- ALTER TABLE evaluacion.pregunta DROP CONSTRAINT IF EXISTS fk_pregunta_componente_id CASCADE;
ALTER TABLE evaluacion.pregunta ADD CONSTRAINT fk_pregunta_componente_id FOREIGN KEY (componente_id_fk)
REFERENCES evaluacion.componente (id_componente) MATCH FULL
ON DELETE RESTRICT ON UPDATE CASCADE;
-- ddl-end --
-- object: pregunta_id_fk | type: CONSTRAINT --
-- ALTER TABLE evaluacion.respuesta DROP CONSTRAINT IF EXISTS pregunta_id_fk CASCADE;
ALTER TABLE evaluacion.respuesta ADD CONSTRAINT pregunta_id_fk FOREIGN KEY (pregunta_id_fk)
REFERENCES evaluacion.pregunta (id_pregunta) MATCH FULL
ON DELETE NO ACTION ON UPDATE NO ACTION;
-- ddl-end --
-- object: examen_taller_id_fk | type: CONSTRAINT --
-- ALTER TABLE evaluacion.sesion DROP CONSTRAINT IF EXISTS examen_taller_id_fk CASCADE;
ALTER TABLE evaluacion.sesion ADD CONSTRAINT examen_taller_id_fk FOREIGN KEY (examen_taller_id_fk)
REFERENCES evaluacion.examen_taller (id_examen) MATCH FULL
ON DELETE NO ACTION ON UPDATE NO ACTION;
-- ddl-end --
-- object: rol_id_fk | type: CONSTRAINT --
-- ALTER TABLE seguridad.permiso DROP CONSTRAINT IF EXISTS rol_id_fk CASCADE;
ALTER TABLE seguridad.permiso ADD CONSTRAINT rol_id_fk FOREIGN KEY (role_id_fk)
REFERENCES seguridad.rol (id) MATCH FULL
ON DELETE NO ACTION ON UPDATE NO ACTION;
-- ddl-end --
-- object: menu_id_fk | type: CONSTRAINT --
-- ALTER TABLE seguridad.permiso DROP CONSTRAINT IF EXISTS menu_id_fk CASCADE;
ALTER TABLE seguridad.permiso ADD CONSTRAINT menu_id_fk FOREIGN KEY (menu_id_fk)
REFERENCES seguridad.menu (id) MATCH FULL
ON DELETE NO ACTION ON UPDATE NO ACTION;
-- ddl-end --
-- object: fk_departamento_pais_id | type: CONSTRAINT --
-- ALTER TABLE configuracion.departamento DROP CONSTRAINT IF EXISTS fk_departamento_pais_id CASCADE;
ALTER TABLE configuracion.departamento ADD CONSTRAINT fk_departamento_pais_id FOREIGN KEY (pais_id_fk)
REFERENCES configuracion.pais (id) MATCH FULL
ON DELETE RESTRICT ON UPDATE CASCADE;
-- ddl-end --
-- object: fk_ciudad_departamento_id | type: CONSTRAINT --
-- ALTER TABLE configuracion.ciudad DROP CONSTRAINT IF EXISTS fk_ciudad_departamento_id CASCADE;
ALTER TABLE configuracion.ciudad ADD CONSTRAINT fk_ciudad_departamento_id FOREIGN KEY (departamento_id_fk)
REFERENCES configuracion.departamento (id) MATCH FULL
ON DELETE RESTRICT ON UPDATE CASCADE;
-- ddl-end --
-- object: fk_configuracion_examen_taller_id | type: CONSTRAINT --
-- ALTER TABLE evaluacion.configuracion DROP CONSTRAINT IF EXISTS fk_configuracion_examen_taller_id CASCADE;
ALTER TABLE evaluacion.configuracion ADD CONSTRAINT fk_configuracion_examen_taller_id FOREIGN KEY (examen_id_fk)
REFERENCES evaluacion.examen_taller (id_examen) MATCH FULL
ON DELETE RESTRICT ON UPDATE CASCADE;
-- ddl-end --
<file_sep>/PreSaber-Web/src/app/models/typeequipmenthasuser.ts
export class Typeequipmenthasuser {
constructor(public id: number,
public description: string,
public stateType: string,
public createdAt: any,
public updatedAt: any) {
}
}<file_sep>/PreSaber-Nuevo/src/app/models/globalstate.ts
export class Globalstate {
constructor(public id,
public description,
public updateAt) {
}
}
<file_sep>/PreSaber-Nuevo/src/app/components/profesor/mis-cursos/mis-cursos.component.ts
import {Component, OnInit} from '@angular/core';
import {CursoService} from "../../../services/curso.service";
import {ElementsService} from "../../../services/elements.service";
import {Modulo} from "../../../models/modulo";
import {GLOBAL} from "../../../services/global";
import {Router} from "@angular/router";
import {Seccion} from "../../../models/seccion";
import {SesionService} from "../../../services/evaluacion_services/sesion.service";
import {Tiporecurso} from "../../../models/tiporecurso";
import {RecursosService} from "../../../services/recursos.service";
import {Recurso} from "../../../models/evaluacion/recurso";
import {Seccion_recurso} from "../../../models/seccion_recurso";
import {Seccion_recursoService} from "../../../services/presaber/seccion_recurso.service";
@Component({
selector: 'app-mis-cursos',
templateUrl: './mis-cursos.component.html',
styleUrls: ['./mis-cursos.component.scss'],
providers: [CursoService, ElementsService, SesionService, RecursosService, Seccion_recursoService]
})
export class MisCursosComponent implements OnInit {
public token: any;
public objModulo: Modulo;
public listModulo: Array<Object>;
public url: any;
public descripcionFicha: any;
public arregloFicha: any;
public descripcionCurso: string;
public listTipoRecurso: Array<Tiporecurso>;
public objTipoRecurso: Tiporecurso;
//--------------Variables seccion
public objSeccion: Seccion;
public listSesion: Array<Seccion>;
public imagen: Array<File>;
public res: any;
public sesionDescripcion: any;
public listRespuestaCompleta;
public listRecursosArchivo: Array<Object>;
public tipoRecurso: any;
public listRecursos: Array<Object>;
public tipoRecursoCrear: any;
public objRecurso: Recurso;
public objSeccionRecurso: Seccion_recurso;
public listSeccionRecurso: Array<Seccion_recurso>;
constructor(private _CursoService: CursoService,
private _ElementService: ElementsService,
private _Router: Router,
private _RecursoService: RecursosService,
private _SesionService: SesionService,
private _Seccion_recurso: Seccion_recursoService) {
this.token = localStorage.getItem('token');
this.objTipoRecurso = new Tiporecurso(0, '', '', '', '');
this.objModulo = new Modulo(0, '', '', '',
'', '', '', '', '', '','');
this.objSeccion = new Seccion('', '', '', '', '', '', '000', '', '');
this.objRecurso = new Recurso('', '', '', '', '', '', '', '');
this.objSeccionRecurso = new Seccion_recurso('', '', '', '', '', '000', '', '', '', '');
this.url = GLOBAL.urlFiles;
this.descripcionCurso = '';
this.sesionDescripcion = '';
this.tipoRecurso = '';
this.tipoRecursoCrear = null;
}
ngOnInit() {
this._ElementService.pi_poValidarUsuario('MisCursosComponent');
this.listarCursosProfesor();
$("#seccionSesiones").hide();
$("#regresarCurso").hide();
$("#sesionrecursos").hide();
$("#regresarSesion").hide();
$("#tablaTalleresExamenes").hide();
$("#tablaArchivos").hide();
this.arregloFicha = localStorage.getItem('ficha').split('|-|');
this.descripcionFicha = this.arregloFicha[1];
}
listarCursosProfesor() {
let id = localStorage.getItem('ficha').split('|-|');
if (id != null || id.length != 1) {
this._CursoService.misCursos(this.token, id[0]).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.listModulo = respuesta.data;
} else {
this._ElementService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
}
}, error2 => {
}
)
} else {
this._ElementService.pi_poVentanaAlertaWarning('LTE-000', 'Lo sentimos seleccione la ficha para ver los cursos');
this._Router.navigate(['MisFichas']);
}
}
seleccionarCurso(curso) {
if (curso.estado.toLowerCase() == 'activo') {
$("#seccionCurso").toggle(250);
$("#seccionSesiones").toggle(500);
$("#regresarCurso").show();
this.objSeccion.modulo_id_fk = curso.id;
this.descripcionCurso = '-' + curso.descripcion;
this.listarSesionesCurso();
} else {
this._ElementService.pi_poVentanaAlertaWarning('LTE-000', 'Lo sentimos no se puede cargar el curso su estado es INACTIVO');
}
}
listarSesionesCurso() {
this._SesionService.listarSesionCurso(this.token, this.objSeccion).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.listSesion = respuesta.data;
} else {
this.listSesion = [];
this._ElementService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
}
}, error2 => {
}
);
}
cargarImagen($event) {
this.imagen = <Array<File>>$event.target.files;
}
regresarCurso() {
$("#seccionSesiones").toggle(250);
$("#seccionCurso").toggle(500);
$("#regresarCurso").hide();
this.descripcionCurso = '';
}
crearSesionCurso() {
console.log(this.objSeccion);
this._SesionService.crearSesionCurso(this.token, this.objSeccion).subscribe(
(resultado) => {
this._ElementService.pi_poValidarCodigo(resultado);
if (resultado.status == 'success') {
this.listarSesionesCurso();
this.limpiarCamposSesion();
this._ElementService.pi_poAlertaSuccess(resultado.msg, resultado.code);
} else {
this._ElementService.pi_poVentanaAlertaWarning(resultado.code, resultado.msg);
}
},
(error) => {
console.log(error);
}
)
}
cambiarPrioridad(tipo, objSesion) {
var nuevaPrioridad;
if (tipo == 'arriba') {
nuevaPrioridad = objSesion.prioridad - 1;
if (nuevaPrioridad > 0) {
for (var i = 0; i < this.listSesion.length; i++) {
if (this.listSesion[i].prioridad == nuevaPrioridad) {
this.listSesion[i].prioridad = objSesion.prioridad;
}
}
for (var i = 0; i < this.listSesion.length; i++) {
if (this.listSesion[i].id == objSesion.id) {
this.listSesion[i].prioridad = nuevaPrioridad;
}
}
this.listSesion.sort(function (a, b) {
return (a.prioridad - b.prioridad)
})
this.actualizarPrioridad();
} else {
this._ElementService.pi_poAlertaError('Lo sentimos, este item ya alcanzo su maxima prioridad', 'LTE-000');
}
} else if (tipo == 'abajo') {
nuevaPrioridad = (parseInt(objSesion.prioridad) + parseInt('1'));
if (nuevaPrioridad <= this.listSesion.length) {
for (var i = 0; i < this.listSesion.length; i++) {
if (this.listSesion[i].prioridad == nuevaPrioridad) {
this.listSesion[i].prioridad = objSesion.prioridad;
}
}
for (var i = 0; i < this.listSesion.length; i++) {
if (this.listSesion[i].id == objSesion.id) {
this.listSesion[i].prioridad = nuevaPrioridad;
}
}
this.listSesion.sort(function (a, b) {
return (a.prioridad - b.prioridad)
})
this.actualizarPrioridad();
} else {
this._ElementService.pi_poAlertaError('Lo sentimos, este item ya alcanzo su minima prioridad', 'LTE-000');
}
}
}
actualizarPrioridad() {
this._SesionService.actualizarPrioridad(this.token, this.listSesion).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this._ElementService.pi_poAlertaSuccess(respuesta.msg, respuesta.code);
} else {
this._ElementService.pi_poVentanaAlertaWarning(this.res.code, this.res.msg);
}
}, error2 => {
}
)
}
editarSesion(sesion) {
this.objSeccion = sesion;
this._ElementService.pi_poAlertaWarning('Se selecciono la sesion: ' + this.objSeccion.description + ' con prioridad de: ' + this.objSeccion.prioridad, 'LTE-000');
}
actualizarSesionCurso() {
if (this.objSeccion.description == '' || this.objSeccion.estado == '000') {
this._ElementService.pi_poAlertaError('Lo sentimos, la descripcion y el estado son requeridos', 'LTE-000');
} else {
this._SesionService.actualizarSesionCurso(this.token, ['imagen'], this.imagen, this.objSeccion).then(
(resultado) => {
this._ElementService.pi_poValidarCodigo(resultado);
this.res = resultado;
if (this.res.status == 'success') {
this.limpiarCamposSesion();
this.listarSesionesCurso();
this._ElementService.pi_poAlertaSuccess(this.res.msg, this.res.code);
} else {
this._ElementService.pi_poVentanaAlertaWarning(this.res.code, this.res.msg);
}
},
(error) => {
console.log(error);
}
)
}
}
limpiarCamposSesion() {
this.objSeccion = new Seccion('', '', '', '', '', '', '000', '', '');
}
volverSesion() {
$("#regresarCurso").show();
$("#regresarSesion").hide();
$("#sesionrecursos").toggle(200);
$("#seccionSesiones").toggle(500);
this.sesionDescripcion = '';
}
seleccionarSesion(sesion) {
this.cargarTipoRecursos();
$("#regresarCurso").hide();
$("#regresarSesion").show();
$("#seccionSesiones").toggle(200);
$("#sesionrecursos").toggle(500);
this.sesionDescripcion = '-' + sesion.description;
this.objSeccionRecurso.seccion_id_fk = sesion.id;
this.listarSeccionRecurso();
}
cargarRecursos() {
$("#loaderTablaRecursos").show();
let recurso = this.tipoRecurso.split('-');
$("#tablaArchivos").show();
this.objTipoRecurso.id = recurso[0];
this._RecursoService.listarArchivos(this.token, this.objTipoRecurso).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
$("#loaderTablaRecursos").hide();
this.listRecursosArchivo = respuesta.data;
} else {
this.listRecursosArchivo = [];
this._ElementService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
$("#loaderTablaRecursos").hide();
}
}, error2 => {
}
)
}
cargarTipoRecursos() {
$("#loaderTipoRecurso").show();
this._RecursoService.cargarTipos().subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.listTipoRecurso = respuesta.data;
$("#loaderTipoRecurso").hide();
} else {
this._ElementService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
}
}, error2 => {
}
)
}
seleccionRecurso(tipo, obj) {
this.objRecurso = obj;
this.objSeccionRecurso.recurso_id_fk = this.objRecurso.id;
this._ElementService.pi_poAlertaWarning('Se selecciono el recurso con codigo: ' + this.objRecurso.id, 'LTE-000');
}
crearRecursoSesion() {
if (this.objRecurso.id != '') {
this._Seccion_recurso.crearSesionRecurso(this.token, ['imagen'], this.imagen, this.objSeccionRecurso).then(
(resultado) => {
this._ElementService.pi_poValidarCodigo(resultado);
this.res = resultado;
if (this.res.status == 'success') {
this.listarSeccionRecurso();
this.limpiarCamposSeccionRecurso();
this._ElementService.pi_poAlertaSuccess(this.res.msg, this.res.code);
} else {
this._ElementService.pi_poVentanaAlertaWarning(this.res.code, this.res.msg);
}
},
(error) => {
console.log(error);
}
)
} else {
this._ElementService.pi_poVentanaAlertaWarning('LTE-000', 'Lo sentimos, Debes seleccionar el recurso para poder crearlo');
}
}
listarSeccionRecurso() {
this._Seccion_recurso.listarSeccionRecurso(this.token, this.objSeccionRecurso).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.listSeccionRecurso = respuesta.data;
} else {
this.listSeccionRecurso = [];
this._ElementService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
}
}, error2 => {
}
)
}
cambiarPrioridadSeccionRecurso(tipo, objSesionRecurso) {
var nuevaPrioridad;
if (tipo == 'arriba') {
nuevaPrioridad = objSesionRecurso.prioridad - 1;
if (nuevaPrioridad > 0) {
for (var i = 0; i < this.listSeccionRecurso.length; i++) {
if (this.listSeccionRecurso[i].prioridad == nuevaPrioridad) {
this.listSeccionRecurso[i].prioridad = objSesionRecurso.prioridad;
}
}
for (var i = 0; i < this.listSeccionRecurso.length; i++) {
if (this.listSeccionRecurso[i].id == objSesionRecurso.id) {
this.listSeccionRecurso[i].prioridad = nuevaPrioridad;
}
}
this.listSeccionRecurso.sort(function (a, b) {
return (a.prioridad - b.prioridad)
})
this.actualizarPrioridad();
} else {
this._ElementService.pi_poAlertaError('Lo sentimos, este item ya alcanzo su maxima prioridad', 'LTE-000');
}
} else if (tipo == 'abajo') {
nuevaPrioridad = (parseInt(objSesionRecurso.prioridad) + parseInt('1'));
if (nuevaPrioridad <= this.listSeccionRecurso.length) {
for (var i = 0; i < this.listSeccionRecurso.length; i++) {
if (this.listSeccionRecurso[i].prioridad == nuevaPrioridad) {
this.listSeccionRecurso[i].prioridad = objSesionRecurso.prioridad;
}
}
for (var i = 0; i < this.listSeccionRecurso.length; i++) {
if (this.listSeccionRecurso[i].id == objSesionRecurso.id) {
this.listSeccionRecurso[i].prioridad = nuevaPrioridad;
}
}
this.listSeccionRecurso.sort(function (a, b) {
return (a.prioridad - b.prioridad)
})
this.actualizarPrioridad();
} else {
this._ElementService.pi_poAlertaError('Lo sentimos, este item ya alcanzo su minima prioridad', 'LTE-000');
}
}
}
actualizarPrioridadSeccionRecurso() {
this._Seccion_recurso.actualizarPrioridad(this.token, this.listSeccionRecurso).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this._ElementService.pi_poAlertaSuccess(respuesta.msg, respuesta.code);
} else {
this._ElementService.pi_poVentanaAlertaWarning(this.res.code, this.res.msg);
}
}, error2 => {
}
)
}
editarSesionRecurso(sesionRecurso) {
this.objSeccionRecurso.id = sesionRecurso.id;
this.objSeccionRecurso.descripcion = sesionRecurso.descripcion;
this.objSeccionRecurso.estado = sesionRecurso.estado;
this.objSeccionRecurso.recurso_id_fk = sesionRecurso.idrecurso;
this.objRecurso.id = sesionRecurso.idrecurso;
}
actualizarSeccionRecurso() {
if (this.objSeccionRecurso.descripcion == '' || this.objSeccionRecurso.estado == '000') {
this._ElementService.pi_poVentanaAlertaWarning('LTE-000', 'Lo sentimos todos los datos son requeridos');
this._ElementService.pi_poAlertaError('Lo sentimos todos los datos son requeridos', 'LTE-000');
} else {
this.objSeccionRecurso.recurso_id_fk = this.objRecurso.id;
this._Seccion_recurso.actualizarSeccionRecurso(this.token, this.objSeccionRecurso).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.listarSeccionRecurso();
this.limpiarCamposSeccionRecurso();
this._ElementService.pi_poAlertaSuccess(respuesta.msg, respuesta.code);
} else {
this._ElementService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
}
}, error2 => {
}
)
}
}
limpiarCamposSeccionRecurso() {
this.objSeccionRecurso = new Seccion_recurso('', '', '', '', '', '000', '', '', '', '');
}
}
<file_sep>/PreSaber-Web/src/app/services/elements.service.ts
import {Injectable} from "@angular/core";
import {User} from "../models/user";
import {Observable} from "rxjs/Observable";
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {GLOBAL} from "./global";
import {Globalstate} from "../models/globalstate";
import {OnInit} from "@angular/core";
import {Router} from "@angular/router";
declare var alertify: any;
declare var swal: any;
declare var PNotify: any;
@Injectable()
export class ElementsService implements OnInit {
public url: string;
public user: any;
public entity: Array<Globalstate>;
public userIdentity: any;
public home: string;
constructor(public _http: HttpClient, private _Router: Router) {
this.url = GLOBAL.url;
}
ngOnInit() {
}
pi_poAlertaSuccess(mensaje) {
alertify.success(mensaje);
}
pi_poAlertaError(mensaje) {
alertify.error(mensaje);
}
pi_poAlertaWarning(mensaje) {
alertify.warning(mensaje);
}
pi_poAlertaMensaje(mensaje) {
alertify.message(mensaje);
}
pi_poBontonDesabilitar(idBoton) {
$(idBoton).attr('disabled', 'disabled');
}
pi_poBotonHabilitar(idBoton) {
$(idBoton).removeAttr('disabled')
}
pi_poValidarUsuario(nombreVista) {
this.userIdentity = this.getUserIdentity();
let validacion = 0;
if (this.userIdentity != null) {
for (let i in this.userIdentity.permisos) {
if (this.userIdentity.permisos[i].descripcion == nombreVista) {
validacion = 1;
}
}
if (validacion == 1) {
} else {
this.home = this.userIdentity.rol_descripcion;
this._Router.navigate([this.home]);
swal({
title: 'Sin permisos',
text: 'Lo sentimos, no cuentas con los permisos suficientes para ingresar a este modulo',
icon: "success",
button: "Iniciar sesion",
});
}
} else {
this._Router.navigate(['']);
}
}
pi_poValidarCodigo(respuesta) {
switch (respuesta.code) {
case 'LTE-004':
swal({
title: respuesta.code,
text: respuesta.msg,
icon: "success",
button: "Iniciar sesion",
});
localStorage.removeItem('token');
localStorage.removeItem('userIdentity');
break;
case 'LTE-005':
swal({
title: respuesta.code,
text: respuesta.msg,
icon: "success",
button: "Iniciar sesion",
});
localStorage.removeItem('token');
localStorage.removeItem('userIdentity');
break;
case 'LTE-011':
swal({
title: respuesta.code,
text: respuesta.msg,
icon: "success",
button: "Iniciar sesion",
});
localStorage.removeItem('token');
localStorage.removeItem('userIdentity');
break;
case 'LTE-013':
swal({
title: respuesta.code,
text: respuesta.msg,
icon: "success",
button: "Iniciar sesion",
});
localStorage.removeItem('token');
localStorage.removeItem('userIdentity');
break;
case 'LTE-014':
swal({
title: respuesta.code,
text: respuesta.msg,
icon: "success",
button: "Cerrar",
});
break;
default:
}
}
pi_poVentanaAlerta(titulo, mensaje) {
swal({
title: titulo,
text: mensaje,
icon: "success",
button: "Iniciar sesion",
});
}
alerts(tipe, msg) {
let data = '';
if (tipe == 1 || tipe == '1') {
data = '<div class="alert alert-success icons-alert" style="margin-bottom: 0px;">' +
'<button type="button" class="close" data-dismiss="alert" aria-label="Close">' +
'<i class="icofont icofont-close-line-circled"></i>' +
'</button>\n' +
'<p><strong>Bien hecho!</strong> <code>' + msg + '</code></p>' +
'</div>';
} else if (tipe == 2 || tipe == '2') {
data = '<div class="alert alert-warning icons-alert" style="margin-bottom: 0px;">' +
'<button type="button" class="close" data-dismiss="alert" aria-label="Close">' +
'<i class="icofont icofont-close-line-circled"></i>' +
'</button>\n' +
'<p><strong>Cuidado!</strong> <code>' + msg + '</code></p>' +
'</div>';
} else if (tipe == 3 || tipe == '3') {
data = '<div class="alert alert-danger icons-alert" style="margin-bottom: 0px;">' +
'<button type="button" class="close" data-dismiss="alert" aria-label="Close">' +
'<i class="icofont icofont-close-line-circled"></i>' +
'</button>\n' +
'<p><strong>Error!</strong> <code>' + msg + '</code></p>' +
'</div>';
} else {
}
return data;
}
//Traer usuario de local storage
getUserIdentity() {
let usuario = JSON.parse(localStorage.getItem('userIdentity'));
if (usuario != 'undefined') {
this.user = usuario;
} else {
this.user = null;
}
return this.user;
}
}
<file_sep>/php-backend/App/componentes/administrador/modulo.php
<?php
$app->post('/administrador/crearModulo', function () use ($app) {
$helper = new helper();
$conexion = new conexPG();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token');
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$usuarioIdentificado = $helper->authCheck($token, true);
$sql = "select * from seguridad.usuario where id='$usuarioIdentificado->sub'";
$r = $conexion->consultaComplejaAso($sql);
if ($r != 0) {
$params = json_decode($json);
$curso_id_fk = (isset($params->curso_id_fk)) ? $params->curso_id_fk : null;
$usuario_administrador_id_fk = $usuarioIdentificado->sub;
$descripcion = (isset($params->descripcion)) ? $params->descripcion : null;
$usuario_profesor_id_fk = (isset($params->usuario_profesor_id_fk)) ? $params->usuario_profesor_id_fk : null;
$imagen = (isset($_FILES['imagen'])) ? $_FILES['imagen'] : null;
$estado = (isset($params->estado)) ? $params->estado : null;
$fecha_creacion = $fecha_creacion = date('Y-m-d H:i:s');
$sql = "select * from presaber.curso cu join presaber.modulo mo on cu.id=mo.curso_id_fk where cu.id='$curso_id_fk'";
$r = $conexion->consultaComplejaNor($sql);
$prioridad = pg_num_rows($r) + 1;
$validacion = 1;
if ($imagen != null) {
$extension = strtolower(pi_poExtenssion($imagen));
if ($extension == 'png' || $extension == 'gif' || $extension == 'jpg' || $extension == 'jpeg') {
$nombreArchivo = time();
$ruta = '/imagenes/modulo/' . $nombreArchivo . '.' . pi_poExtenssion($imagen);
pi_poMove('/imagenes/modulo', $imagen, $nombreArchivo);
} else {
$validacion = 0;
}
} else {
$ruta = '/imagenes_estandar/letra-m-32x32.png';
}
if ($validacion == 1) {
$sql = "INSERT INTO presaber.modulo(
curso_id_fk, usuario_administrador_id_fk, descripcion, prioridad, imagen, estado, fecha_creacion, usuario_profesor_id_fk)
VALUES ('$curso_id_fk', '$usuario_administrador_id_fk', '$descripcion', '$prioridad', '$ruta', '$estado', '$fecha_creacion', '$usuario_profesor_id_fk');";
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-001'
];
} else {
$data = [
'code' => 'LTE-014'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/administrador/actualizarModulo', function () use ($app) {
$helper = new helper();
$conexion = new conexPG();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token');
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$usuarioToken = $helper->authCheck($token, true);
$sql = "select * from seguridad.usuario where id='$usuarioToken->sub'";
$r = $conexion->consultaComplejaAso($sql);
if ($r != 0) {
$params = json_decode($json);
$id = (isset($params->id)) ? $params->id : null;
$descripcion = (isset($params->descripcion)) ? $params->descripcion : null;
$curso_id_fk = (isset($params->curso_id_fk)) ? $params->curso_id_fk : null;
$usuario_profesor_id_fk = (isset($params->usuario_profesor_id_fk)) ? $params->usuario_profesor_id_fk : null;
$imagen = (isset($_FILES['imagen'])) ? $_FILES['imagen'] : null;
$estado = (isset($params->estado)) ? $params->estado : null;
$fecha_actualizacion = date('Y-m-d H:i:s');
$sql = "select * from presaber.modulo where id='$id'";
$r = $conexion->consultaComplejaNor($sql);
if (pg_num_rows($r) > 0) {
$validacion = 1;
$modulo = pg_fetch_assoc($r);
if ($imagen != null) {
$extension = pi_poExtenssion($imagen);
if ($extension == 'png' || $extension == 'gif' || $extension == 'jpg' || $extension == 'jpeg') {
if ($modulo['imagen'] != '/imagenes_estandar/letra-m-32x32.png') {
pi_poEliminarArchivo($modulo['imagen']);
}
$nombreArchivo = time();
$ruta = '/imagenes/modulo/' . $nombreArchivo . '.' . pi_poExtenssion($imagen);
pi_poMove('/imagenes/modulo', $imagen, $nombreArchivo);
} else {
$validacion = 0;
}
}
if ($validacion == 1) {
if ($imagen != null) {
$sql = "UPDATE presaber.modulo
SET curso_id_fk='$curso_id_fk',descripcion='$descripcion', imagen='$ruta', estado='$estado', fecha_actualizacion='$fecha_actualizacion', usuario_profesor_id_fk='$usuario_profesor_id_fk'
WHERE id='$id';";
} else {
$sql = "UPDATE presaber.modulo
SET curso_id_fk='$curso_id_fk',descripcion='$descripcion',estado='$estado', fecha_actualizacion='$fecha_actualizacion', usuario_profesor_id_fk='$usuario_profesor_id_fk'
WHERE id='$id';";
}
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-001'
];
} else {
$data = [
'code' => 'LTE-014'
];
}
} else {
$data = [
'code' => 'LTE-002'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/administrador/eliminarModulo', function () use ($app) {
$helper = new helper();
$conexion = new conexPG();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token');
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$params = json_decode($json);
$id = (isset($params->id)) ? $params->id : null;
$sql = "DELETE FROM presaber.modulo WHERE id = " . $id . ";";
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-001'
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/administrador/listarModulo', function () use ($app) {
$helper = new helper();
$conexion = new conexPG();
$json = $app->request->post('json', null);
if ($json != null) {
$parametros = json_decode($json);
$id = (isset($parametros->id)) ? $parametros->id : null;
$token = $app->request->post('token');
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$usuarioValidado = $helper->authCheck($token, true);
$sql = "select * from seguridad.usuario where id='$usuarioValidado->sub'";
$r = $conexion->consultaComplejaAso($sql);
if ($r != 0) {
$sql = "select mo.*,cu.descripcion as descripcion_curso, u.id as id_usuario, u.nombre, u.apellido, u.correo, u.documento, u.imagen as imagen_usuario from presaber.modulo mo
join presaber.curso cu on mo.curso_id_fk=cu.id
join seguridad.usuario u on mo.usuario_profesor_id_fk=u.id
join seguridad.rol r on u.rol_id_fk=r.id where cu.id='$id' order by mo.id desc limit 200";
$r = $conexion->consultaComplejaAso($sql);
$data = [
'code' => 'LTE-001',
'data' => $r
];
} else {
$data = [
'code' => 'LTE-013',
'line' => '208-modulo'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data=[
'code'=>'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/administrador/filtroModulo', function () use ($app) {
$json = $app->request->post('json', null);
$toke = $app->request->post('token', null);
$helper = new helper();
if ($json != null) {
if ($toke != null) {
$validarToke = $helper->authCheck($toke);
if ($validarToke == true) {
$parametros = json_decode($json);
$filtro = (isset($parametros->filstro)) ? $parametros->filtro : $parametros->filtro;
$sql = "select mo.*,cu.descripcion as descripcion_curso from presaber.modulo mo join presaber.curso cu on mo.curso_id_fk=cu.id where
mo.descripcion like '%$filtro%'or cu.descripcion like '%$filtro%' order by mo.fecha_creacion DESC limit 200";
$conexion = new conexPG();
$r = $conexion->consultaComplejaAso($sql);
if ($r != 0) {
$data = [
'code' => 'LTE-001',
'data' => $r
];
} else {
$data = [
'code' => 'LTE-003'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-010'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/administrador/filtroProfesor', function () use ($app) {
$json = $app->request->post('json', null);
$toke = $app->request->post('token', null);
$helper = new helper();
if ($json != null) {
if ($toke != null) {
$validarToke = $helper->authCheck($toke);
if ($validarToke == true) {
$parametros = json_decode($json);
$filtro = (isset($parametros->filstro)) ? $parametros->filtro : $parametros->filtro;
$sql = "select u.*, r.descripcion as descripcion_rol from seguridad.usuario u join seguridad.rol r
on u.rol_id_fk=r.id where u.nombre like '%$filtro%' or u.documento like '%$filtro%' and u.estado like 'ACTIVO' and r.descripcion
like 'PROFESOR' or r.descripcion like 'profesor' ";
$conexion = new conexPG();
$r = $conexion->consultaComplejaAso($sql);
if ($r != 0) {
$data = [
'code' => 'LTE-001',
'data' => $r
];
} else {
$data = [
'code' => 'LTE-003'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-010'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/administrador/listarProfesores', function () use ($app) {
$helper = new helper();
$token = $app->request->post('token', null);
if ($token != null) {
$validarToken = $helper->authCheck($token);
if ($validarToken == true) {
$sql = "select u.*, r.descripcion as descripcion_rol from seguridad.usuario u join seguridad.rol r
on u.rol_id_fk=r.id where u.estado like 'ACTIVO' and r.descripcion
like 'PROFESOR' or r.descripcion like 'profesor'";
$conexion = new conexPG();
$r=$conexion->consultaComplejaAso($sql);
if ($r != 0)
{
$data=[
'code'=>'LTE-001',
'data'=>$r
];
}else
{
$data=[
'code'=>'LTE-003'
];
}
} else {
$data = [
'code' => 'LTE-013',
'line' => '284-modulo'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
echo $helper->checkCode($data);
});<file_sep>/PreSaber-Nuevo/src/app/services/evaluacion_services/respuesta.service.ts
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {Injectable} from "@angular/core";
import {Observable} from "rxjs/Observable";
import {GLOBAL} from "../global";
@Injectable()
export class RespuestaService{
public url:string;
constructor(private _Http: HttpClient)
{
this.url = GLOBAL.url;
}
crear(token,objRespuesta): Observable<any>
{
let json = JSON.stringify(objRespuesta);
let params = 'token='+token+'&json='+json;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Http.post(this.url + 'profesor/crearRespuesta', params, {headers: headers});
}
listar(token,objPregunta): Observable<any>
{
let json = JSON.stringify(objPregunta);
let params = 'token='+token+'&json='+json;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Http.post(this.url + 'profesor/listarRespuesta', params, {headers: headers});
}
editar(token,objRespuesta): Observable<any>
{
let json = JSON.stringify(objRespuesta);
let params = 'token='+token+'&json='+json;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Http.post(this.url + 'profesor/actualizarRespuesta', params, {headers: headers});
}
eliminar(token,objRespuesta): Observable<any>
{
let json = JSON.stringify(objRespuesta);
let params = 'token='+token+'&json='+json;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Http.post(this.url + 'profesor/eliminarRespuesta', params, {headers: headers});
}
}
<file_sep>/PreSaber-Nuevo/src/app/components/administrador/perfil-usuario/perfil-usuario.component.ts
import {Component, OnInit} from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {ElementsService} from "../../../services/elements.service";
import {User} from "../../../models/user";
import {UsuarioService} from "../../../services/usuario.service";
import {GLOBAL} from "../../../services/global";
@Component({
selector: 'app-perfil-usuario',
templateUrl: './perfil-usuario.component.html',
styleUrls: ['./perfil-usuario.component.css'],
providers: [ElementsService, UsuarioService]
})
export class PerfilUsuarioComponent implements OnInit {
public userIdentity: any;
public objUsuario: User;
public imagenPerfil: Array<File>;
public token: string;
public url: string;
public status: any;
public r: any;
constructor(private _ElementService: ElementsService,
private _Router: Router, private _Route: ActivatedRoute, private _usuarioService: UsuarioService) {
this.userIdentity = this._ElementService.getUserIdentity();
this.objUsuario = new User(this.userIdentity.sub, null, this.userIdentity.nombre, '', this.userIdentity.apellido, this.userIdentity.correo, '', null, '',
this.userIdentity.imagen, null, null, null, null, null);
this.token = localStorage.getItem('token');
this.url = GLOBAL.urlFiles;
$('#loader').hide();
}
ngOnInit() {
$('#loader').hide();
this._ElementService.pi_poValidarUsuario('PerfilUsuarioComponent');
}
cargarImagen($event) {
this.imagenPerfil = <Array<File>>$event.target.files;
console.log(this.imagenPerfil);
}
editarPerfil() {
$('#loader').show();
this._usuarioService.editarPerfil(this.token, ['imagen'], this.imagenPerfil, this.objUsuario).then(
(resultado) => {
this.r = resultado;
if (this.r.status == 'success') {
$('#loader').hide();
this.userIdentity.nombre = this.r.data.nombre;
this.userIdentity.apellido = this.r.data.apellido;
this.userIdentity.imagen = this.r.data.imagen;
let json = JSON.stringify(this.userIdentity);
localStorage.setItem('userIdentity', json);
$('#alert').html(this._ElementService.alerts(2, this.r.msg));
} else {
$('#loader').hide();
$('#alert').html(this._ElementService.alerts(3, this.r.data.msg));
}
},
(error) => {
console.log(error);
}
)
}
}
<file_sep>/php-backend/App/componentes/profesor/sesion.php
<?php
$app->post('/profesor/listarSesion', function () use ($app) {
$helper = new helper();
$json = $app->request->post('json', null);
if ($json != null) {
$conexion = new conexPG();
$parametros = json_decode($json);
$id_examen = (isset($parametros->id_examen)) ? $parametros->id_examen : null;
$sql = "select s.* from evaluacion.sesion s where s.examen_taller_id_fk ='$id_examen';";
$r = $conexion->consultaComplejaAso($sql);
if ($r != 0) {
$data = [
'code' => 'LTE-001',
'data' => $r
];
} else {
$data = [
'code' => 'LTE-003'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/crearSesion', function () use ($app) {
$helper = new helper();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$parametros = json_decode($json);
$examen_taller_id_fk = (isset($parametros->examen_taller_id_fk)) ? $parametros->examen_taller_id_fk : null;
$descripcion_sesion = (isset($parametros->descripcion_sesion)) ? $parametros->descripcion_sesion : null;
$conexion = new conexPG();
$sql = "INSERT INTO evaluacion.sesion(
examen_taller_id_fk, descripcion_sesion)
VALUES ('$examen_taller_id_fk', '$descripcion_sesion');";
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-001',
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/listarSesionCurso', function () use ($app) {
$helper = new helper();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionUsuarioToken = $helper->authCheck($token);
if ($validacionUsuarioToken == true) {
$usuarioToken = $helper->authCheck($token, true);
$conexion = new conexPG();
$parametros = json_decode($json);
$modulo_id_fk = (isset($parametros->modulo_id_fk)) ? $parametros->modulo_id_fk : null;
$sql = "select se.* from presaber.seccion se where se.usuario_profesor_id_fk ='$usuarioToken->sub' and se.modulo_id_fk='$modulo_id_fk' order by se.prioridad asc";
$r = $conexion->consultaComplejaAso($sql);
if ($r != 0) {
$data = [
'code' => 'LTE-001',
'data' => $r
];
} else {
$data = [
'code' => 'LTE-003'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/crearSesionCurso', function () use ($app) {
$helper = new helper();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionUsuarioToken = $helper->authCheck($token);
if ($validacionUsuarioToken == true) {
$usuarioToken = $helper->authCheck($token, true);
$conexion = new conexPG();
$parametros = json_decode($json);
$imagen = (isset($_FILES['imagen'])) ? $_FILES['imagen'] : null;
$modulo_id_fk = (isset($parametros->modulo_id_fk)) ? $parametros->modulo_id_fk : null;
$description = (isset($parametros->description)) ? $parametros->description : null;
$estado = (isset($parametros->estado)) ? $parametros->estado : null;
$sql = "select se.* from presaber.seccion se where se.usuario_profesor_id_fk ='$usuarioToken->sub' and se.modulo_id_fk='$modulo_id_fk'";
$r = $conexion->consultaComplejaNor($sql);
$prioridad = pg_num_rows($r) + 1;
$nombreArchivo = time() + '21';
//pi_poMove('/imagenes/sesion/', $imagen, $nombreArchivo);
//$ruta = '/imagenes/sesion/' . $nombreArchivo . '.' . pi_poExtenssion($imagen);
$fecha_creacion = date('Y-m-d H:i:s');
$sql = "INSERT INTO presaber.seccion(
modulo_id_fk, usuario_profesor_id_fk, description, prioridad, imagen, estado, fecha_creacion, fecha_actualizacion)
VALUES ('$modulo_id_fk', '$usuarioToken->sub', '$description', '$prioridad','', '$estado', '$fecha_creacion', '$fecha_creacion');";
$conexion->consultaComplejaAso($sql);
$data = [
'code' => 'LTE-001'
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/actualizarPrioridad', function () use ($app) {
$helper = new helper();
$token = $app->request->post('token', null);
if ($token != null) {
$validacionUsuarioToken = $helper->authCheck($token);
if ($validacionUsuarioToken == true) {
$usuarioToken = $helper->authCheck($token, true);
$conexion = new conexPG();
$json = $app->request->post('sesion', null);
$sesiones = json_decode($json,true);
for($i=0; $i<count($sesiones); $i++)
{
$prioridad=$sesiones[$i]['prioridad'];
$id=$sesiones[$i]['id'];
$fecha_actualizacion = date('Y-m-d H:i:s');
$sql = "UPDATE presaber.seccion
SET prioridad='$prioridad',fecha_actualizacion='$fecha_actualizacion'
WHERE id='$id';";
$conexion->consultaSimple($sql);
}
$data =[
'code'=>'LTE-001'
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/actualizarSesionCurso',function()use($app){
$helper = new helper();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$parametros = json_decode($json);
$description = (isset($parametros->description)) ? $parametros->description : null;
$imagen = (isset($_FILES['imagen'])) ? $_FILES['imagen'] : null;
$estado=(isset($parametros->estado)) ? $parametros->estado : null;
$id = (isset($parametros->id)) ? $parametros->id: null;
$conexion = new conexPG();
$sql = "select * from presaber.seccion where id='$id'";
$fecha_actualizacion = date('Y-m-d H:i:s');
$r= $conexion->consultaComplejaNorAso($sql);
if ($r != 0)
{
if ($imagen != null)
{
pi_poEliminarArchivo($r['imagen']);
$nombreArchivo = time() + '21';
pi_poMove('/imagenes/sesion/', $imagen, $nombreArchivo);
$ruta = '/imagenes/sesion/' . $nombreArchivo . '.' . pi_poExtenssion($imagen);
$sql ="UPDATE presaber.seccion
SET description='$description', imagen='$ruta', estado='$estado', fecha_actualizacion='$fecha_actualizacion'
WHERE id='$id';";
$conexion->consultaSimple($sql);
}else
{
$sql ="UPDATE presaber.seccion
SET description='$description', estado='$estado', fecha_actualizacion='$fecha_actualizacion'
WHERE id='$id';";
$conexion->consultaSimple($sql);
}
$data=[
'code'=>'LTE-001'
];
}else
{
$data=[
'code'=>'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
<file_sep>/PreSaber-Nuevo/src/app/models/evaluacion/componente.ts
export class Componente{
constructor(
public id_componente: any,
public descripcion_componente: any,
public fecha_creacion_componente: any,
public fecha_actualizacion_componente: any
){}
}
<file_sep>/php-backend/index.php
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE');
header('Allow: GET, POST, OPTIONS, PUT, DELETE');
$method = $_SERVER['REQUEST_METHOD'];
if ($method == 'OPTIONS') {
die();
}
require_once 'vendor/autoload.php';
$app = new \Slim\Slim();
$yaml = new \Symfony\Component\Yaml\Yaml();
define("SPECIALCONSTANT", true);
//elementos
require 'App/librerias/conexion.php';
require 'App/servicios/jwtAuth.php';
require 'App/servicios/helper.php';
require 'App/librerias/upload.pixel.php';
require 'App/librerias/email/email.pixel.php';
require 'App/librerias/email/plantillas.pixel.php';
require 'vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Spreadsheet.php';
require 'vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx.php';
require 'vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/IReader.php';
require 'App/componentes/configuracion/subir_archivo.php';
//Componentes
require 'App/componentes/usuario.php';
require 'App/componentes/administrador/contrato_entidad.php';
require 'App/componentes/administrador/curso.php';
require 'App/componentes/administrador/usuario.php';
require 'App/componentes/ciudad.php';
require 'App/componentes/administrador/modulo.php';
require 'App/componentes/administrador/ficha.php';
require 'App/componentes/profesor/ficha.php';
require 'App/componentes/profesor/recurso.php';
require 'App/componentes/base_examen.php';
require 'App/componentes/profesor/competencia.php';
require 'App/componentes/profesor/componente.php';
require 'App/componentes/profesor/sesion.php';
require 'App/componentes/profesor/examen_taller.php';
require 'App/componentes/profesor/configuracion.php';
require 'App/componentes/profesor/pregunta.php';
require 'App/componentes/profesor/respuesta.php';
require 'App/componentes/examen_publico.php';
require 'App/componentes/profesor/modulo.php';
require 'App/componentes/profesor/sesion_recurso.php';
require 'App/componentes/estudiante/estudiante.php';
$app->run();<file_sep>/PreSaber-Nuevo/src/app/components/estudiante/mis-cursos-estudiante/mis-cursos-estudiante.component.ts
import {Component, OnInit} from '@angular/core';
import {ElementsService} from "../../../services/elements.service";
import {EstudianteService} from "../../../services/estudiante/estudiante.service";
import {Router} from "@angular/router";
import {Modulo} from "../../../models/modulo";
import {GLOBAL} from "../../../services/global";
import {Curso} from "../../../models/curso";
@Component({
selector: 'app-mis-cursos-estudiante',
templateUrl: './mis-cursos-estudiante.component.html',
styleUrls: ['./mis-cursos-estudiante.component.scss'],
providers: [ElementsService, EstudianteService]
})
export class MisCursosEstudianteComponent implements OnInit {
public token: any;
public ficha: any;
public listCurso: Array<Curso>;
public urlFile: any;
public cursoSeleccionado: string;
constructor(private _ElementService: ElementsService,
private _estudianteService: EstudianteService,
private _router:Router) {
this.token = localStorage.getItem('token');
this.ficha = localStorage.getItem('ficha');
this.urlFile = GLOBAL.urlFiles;
}
ngOnInit() {
this._ElementService.pi_poValidarUsuario('MisCursosEstudianteComponent');
this.cursoSeleccionado = localStorage.getItem('id_curso');
this.cargarCursos();
}
cargarCursos() {
this._estudianteService.listarModulosCurso(this.token, this.ficha).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.listCurso = respuesta.data;
} else {
}
}, error2 => {
}
)
}
seleccionarCurso(curso){
localStorage.setItem('id_curso',curso.id);
this._router.navigate(['estudiante/asignaturasCurso']);
}
}
<file_sep>/PreSaber-Nuevo/src/app/services/ficha.service.ts
import {Injectable} from "@angular/core";
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {Router} from "@angular/router";
import {GLOBAL} from "./global";
import {Observable} from "rxjs/Observable";
@Injectable()
export class FichaService {
public url: string;
constructor(private _http: HttpClient, private _Router: Router) {
this.url = GLOBAL.url;
}
crearFicha(ficha, token): Observable<any> {
let json = JSON.stringify(ficha);
let parametros = "json=" + json + "&token=" + token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(this.url + 'administrador/crearFicha', parametros, {headers: headers});
}
filtrarFicha(filtro, token, contrato): Observable<any> {
contrato.filtro = filtro;
let json = JSON.stringify(contrato);
let params = 'json=' + json + '&token=' + token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(this.url + 'administrador/filtrarFicha', params, {headers: headers});
}
filtrarUsuariosFicha(filtro, token, ficha): Observable<any> {
ficha.filtro = filtro;
let json = JSON.stringify(ficha);
let params = 'json=' + json + '&token=' + token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(this.url + 'administrador/filtroUsuarioFicha', params, {headers: headers});
}
crearUsuarioFicha(usuario, token, contrato_entidad_id_fk, idFicha): Observable<any> {
usuario.contrato_entidad_id_fk = contrato_entidad_id_fk;
usuario.idFicha = idFicha;
let json = JSON.stringify(usuario);
let parametros = "json=" + json + "&token=" + token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(this.url + 'administrador/crearUsuarioFicha', parametros, {headers: headers});
}
crearUsuarioExistenteFicha(usuario, token, contrato_entidad_id_fk, idFicha): Observable<any> {
usuario.contrato_entidad_id_fk = contrato_entidad_id_fk;
usuario.idFicha = idFicha;
let json = JSON.stringify(usuario);
let parametros = "json=" + json + "&token=" + token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(this.url + 'administrador/crearUsuarioExistente', parametros, {headers: headers});
}
actualizarFicha(ficha, token): Observable<any> {
let json = JSON.stringify(ficha);
let parametros = "json=" + json + "&token=" + token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(this.url + 'administrador/actualizarFicha', parametros, {headers: headers});
}
listarFicha(contrato, token): Observable<any> {
let json = JSON.stringify(contrato);
let parametros = "json=" + json + "&token=" + token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(this.url + 'administrador/listarFichaContrato', parametros, {headers: headers});
}
listarUsuariosFicha(ficha, token): Observable<any> {
let json = JSON.stringify(ficha);
let parametros = "json=" + json + "&token=" + token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(this.url + 'administrador/listarUsuariosFicha', parametros, {headers: headers});
}
listarRolEstudiante(): Observable<any> {
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(this.url + 'administrador/rolUsuarioFicha', {headers: headers});
}
cargarEstudiantes(token, params: Array<string>, files: Array<File>, data = null) {
let urlF = this.url + 'administrador/leerEstudiantesFicha';
return new Promise((resolve, reject) => {
var formData: any = new FormData();
var xhr = new XMLHttpRequest();
if (files != undefined) {
var name_file_input = params[0];
for (var i = 0; i < files.length; i++) {
formData.append(name_file_input, files[i], files[i].name);
}
}
formData.append('token', token);
if (data != null)
var json = JSON.stringify(data);
formData.append('json', json);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
}
xhr.open("POST", urlF, true);
xhr.send(formData);
});
}
//------------------------------------------------------------------------------Metodos Profesor -----------------------------------------------------
fichasProfesor(token): Observable<any> {
let parametros = 'token=' + token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(this.url + 'profesor/FichasProfesor', parametros, {headers: headers});
}
cargarEstudianteFicha(token,id): Observable<any> {
let parametros = 'token='+token+'&id='+id;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(this.url + 'profesor/estudiantesFicha', parametros, {headers: headers});
}
}
<file_sep>/PreSaber-Nuevo/src/app/models/ciudades.ts
export class Ciudades {
constructor(public id: number,
public descripcion: string,
public departamento_id_fk: string,
){}
}
<file_sep>/PreSaber-Nuevo/src/app/models/evaluacion/examne_taller.ts
export class Examne_taller{
constructor(
public id_examen: any,
public base_examen_id_fk: any,
public descripcion_examen: any,
public fecha_creacion_examen: any,
public fecha_actualizacion_examen: any,
public estado_examen: any,
public tipo_recurso_id_fk: any
){}
}
<file_sep>/PreSaber-Nuevo/src/app/models/evaluacion/sesion.ts
export class Sesion{
constructor(
public id_sesion: any,
public examen_taller_id_fk: any,
public descripcion_sesion: any
)
{}
}
<file_sep>/php-backend/App/componentes/profesor/competencia.php
<?php
$app->post('/profesor/crearCompetencia', function () use ($app) {
$json = $app->request->post('json', null);
$helper = new helper();
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$parametros = json_decode($json);
$fecha_creacion = date('Y-m-d H:i:s');
$fecha_actualizacion = date('Y-m-d H:i:s');
$descripcion = (isset($parametros->descripcion_competencia)) ? $parametros->descripcion_competencia : null;
$conexion = new conexPG();
$sql = "INSERT INTO evaluacion.competencia(
descripcion_competencia, fecha_creacion_competencia, fecha_actualizacion_competencia)
VALUES ('$descripcion', '$fecha_creacion', '$fecha_actualizacion');";
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-001'
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/listarCompetencias', function () use ($app) {
$helper = new helper();
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$conexion = new conexPG();
$sql = "select c.* from evaluacion.competencia c order by c.id_competencia desc limit 200 ";
$r=$conexion->consultaComplejaAso($sql);
$data = [
'code' => 'LTE-001',
'data'=>$r
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/actualizarCompetencia', function () use($app){
$json = $app->request->post('json', null);
$helper = new helper();
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$parametros = json_decode($json);
$fecha_actualizacion = date('Y-m-d H:i:s');
$descripcion = (isset($parametros->descripcion_competencia)) ? $parametros->descripcion_competencia : null;
$id_competencia= (isset($parametros->id_competencia)) ? $parametros->id_competencia : null;
$conexion = new conexPG();
$sql = "UPDATE evaluacion.competencia
SET descripcion_competencia='$descripcion', fecha_actualizacion_competencia='$fecha_actualizacion'
WHERE id_competencia='$id_competencia';";
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-001'
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});<file_sep>/PreSaber-Nuevo/src/app/models/curso.ts
export class Curso {
constructor(public id: any,
public usuario_administrador_id_fk: any,
public descripcion: string,
public estado: string,
public imagen: any,
public fecha_creacion: any,
public fecha_actualizacion: any) {}
}
<file_sep>/PreSaber-Web/src/app/components/home/home.component.ts
import {Component, OnInit} from '@angular/core';
import {LoginService} from "../../services/login.service";
import {User} from "../../models/user";
import {ActivatedRoute, Router} from "@angular/router";
import {ElementsService} from "../../services/elements.service";
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
providers: [ElementsService, LoginService]
})
export class HomeComponent implements OnInit {
public ObjUser: User;
constructor(private _router: Router,
private _route: ActivatedRoute,
private _loginService: LoginService,
private _ElementService: ElementsService) {
this.ObjUser = new User(null, null, '', '', '', '',
'', null, null, null, '', null,
null, null, null);
this._ElementService.pi_poValidarUsuario('HomeComponent');
}
ngOnInit() {
$('#loader').hide();
}
login() {
$('#btnIngresar').attr('disabled', 'disabled');
$('#loader').show();
this._loginService.login(this.ObjUser).subscribe(
respuesta => {
if (respuesta.status != 'error') {
localStorage.setItem('token', respuesta.data);
this._loginService.login(this.ObjUser, true).subscribe(
respuesta1 => {
localStorage.setItem('userIdentity', JSON.stringify(respuesta1.data));
$('#loader').hide();
if (respuesta1 != null) {
if (respuesta1.data.rol_descripcion == 'ADMINISTRADOR') {
window.location.href = '/ADMINISTRADOR';
} else if (respuesta1.data.rol_descripcion == 'PROFESOR') {
window.location.href = '/PROFESOR';
} else if (respuesta1.data.rol_descripcion == 'ESTUDIANTE') {
window.location.href = '/ESTUDIANTE';
}
}
}, error2 => {
}
);
$('#btnIngresar').removeAttr('disabled', 'disabled');
} else {
$('#loader').hide();
$('#alert').html(this._ElementService.alerts(3, 'Lo sentimos, los datos ingresados son incorrectos'));
$('#btnIngresar').removeAttr('disabled', 'disabled');
}
}, error2 => {
}
);
}
}
<file_sep>/PreSaber-Nuevo/src/app/components/home/home.component.ts
import {Component, OnInit, ViewChild, ElementRef} from '@angular/core';
import {LoginService} from "../../services/login.service";
import {User} from "../../models/user";
import {ActivatedRoute, Router} from "@angular/router";
import {ElementsService} from "../../services/elements.service";
import {animate, AUTO_STYLE, state, style, transition, trigger} from '@angular/animations';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
providers: [ElementsService, LoginService],
animations: [
trigger('mobileMenuTop', [
state('no-block, void',
style({
overflow: 'hidden',
height: '0px',
})
),
state('yes-block',
style({
height: AUTO_STYLE,
})
),
transition('no-block <=> yes-block', [
animate('400ms ease-in-out')
])
])
]
})
export class HomeComponent implements OnInit {
deviceType = 'desktop';
verticalNavType = 'expanded';
verticalEffect = 'shrink';
chatToggle = 'out';
chatInnerToggle = 'off';
innerHeight: string;
isScrolled = false;
isCollapsedMobile = 'no-block';
windowWidth: number;
@ViewChild('searchFriends') search_friends: ElementRef;
public ObjUser: User;
constructor(private _router: Router,
private _route: ActivatedRoute,
private _loginService: LoginService,
private _ElementService: ElementsService) {
const scrollHeight = window.screen.height - 150;
this.innerHeight = scrollHeight + 'px';
this.windowWidth = window.innerWidth;
this.setMenuAttributs(this.windowWidth);
this.ObjUser = new User(null, null, '', '', '', '',
'', null, null, null, '', null,
null, null, null);
this._ElementService.pi_poValidarUsuario('HomeComponent');
}
ngOnInit() {
$('#loader').hide();
}
openMyModal(event) {
document.querySelector('#' + event).classList.add('md-show');
}
closeMyModal(event) {
((event.target.parentElement.parentElement).parentElement).classList.remove('md-show');
}
login() {
$('#btnIngresar').attr('disabled', 'disabled');
$('#loader').show();
this._loginService.login(this.ObjUser).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status != 'error') {
localStorage.setItem('token', respuesta.data);
this._loginService.login(this.ObjUser, true).subscribe(
respuesta1 => {
this._ElementService.pi_poValidarCodigo(respuesta1);
localStorage.setItem('userIdentity', JSON.stringify(respuesta1.data));
$('#loader').hide();
}, error2 => {
}
);
$('#btnIngresar').removeAttr('disabled', 'disabled');
} else {
$('#loader').hide();
$('#alert').html(this._ElementService.alerts(3, 'Lo sentimos, los datos ingresados son incorrectos'));
$('#btnIngresar').removeAttr('disabled', 'disabled');
}
}, error2 => {
}
);
}
onResize(event) {
this.innerHeight = event.target.innerHeight + 'px';
/* menu responsive */
this.windowWidth = event.target.innerWidth;
this.setMenuAttributs(this.windowWidth);
}
setMenuAttributs(windowWidth) {
if (windowWidth >= 768 && windowWidth <= 1024) {
this.deviceType = 'tablet';
this.verticalNavType = 'collapsed';
this.verticalEffect = 'push';
} else if (windowWidth < 768) {
this.deviceType = 'mobile';
this.verticalNavType = 'offcanvas';
this.verticalEffect = 'overlay';
} else {
this.deviceType = 'desktop';
this.verticalNavType = 'expanded';
this.verticalEffect = 'shrink';
}
}
onScroll(event) {
this.isScrolled = false;
}
onMobileMenu() {
this.isCollapsedMobile = this.isCollapsedMobile === 'yes-block' ? 'no-block' : 'yes-block';
}
}
<file_sep>/php-backend/App/componentes/administrador/contrato_entidad.php
<?php
$app->post('/administrador/crearContratoEntidad', function () use ($app) {
$json = $app->request->post('json', null);
$helper = new helper();
if ($json != null) {
$token = $app->request->post('token');
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$userToken = $helper->authCheck($token, true);
$parametros = json_decode($json);
$descripcion = (isset($parametros->descripcion)) ? $parametros->descripcion : null;
$ciudad = (isset($parametros->ciudad_id_fk)) ? $parametros->ciudad_id_fk : null;
$estado = (isset($parametros->estado)) ? $parametros->estado : null;
$tipo = (isset($parametros->tipo)) ? $parametros->tipo : null;
$imagen = (isset($_FILES['imagen'])) ? $_FILES['imagen'] : null;
$rutaImagen = '';
$conexion = new conexPG();
$sql = "select * from seguridad.usuario where id='$userToken->sub'";
$r = $conexion->consultaComplejaNor($sql);
if (pg_num_rows($r) > 0) {
$validacion = 1;
if ($imagen != null) {
$extension = pi_poExtenssion($imagen);
$validacion = 1;
if ($extension == 'png' || $extension == 'gif' || $extension == 'jpg' || $extension == 'jpeg') {
$nombreArchivo = time();
pi_poMove('/imagenes/contrato_entidad', $imagen, $nombreArchivo);
$rutaImagen = '/imagenes/contrato_entidad/' . $nombreArchivo . '.' . $extension;
} else {
$validacion = 2;
}
} else {
$rutaImagen = '/imagenes/contrato_entidad/logo-contrato-45x45.png';
}
if ($validacion == 1) {
$fecha_creacion = date('Y-m-d H:i');
$sql = "INSERT INTO presaber.contrato_entidad(
usuario_administrador_id_fk, descripcion, ciudad_id_fk, estado, tipo, imagen, fecha_creacion)
VALUES ('$userToken->sub', '$descripcion', '$ciudad', '$estado', '$tipo', '$rutaImagen', '$fecha_creacion');";
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-001'
];
} else {
$data = [
'code' => 'LTE-014'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/administrador/actualizarContratoEntidad', function () use ($app) {
$json = $app->request->post('json', null);
$helper = new helper();
if ($json != null) {
$token = $app->request->post('token');
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$userToken = $helper->authCheck($token, true);
$parametros = json_decode($json);
$id = (isset($parametros->id)) ? $parametros->id : null;
$descripcion = (isset($parametros->descripcion)) ? $parametros->descripcion : null;
$ciudad = (isset($parametros->ciudad_id_fk)) ? $parametros->ciudad_id_fk : null;
$estado = (isset($parametros->estado)) ? $parametros->estado : null;
$tipo = (isset($parametros->tipo)) ? $parametros->tipo : null;
$imagen = (isset($_FILES['imagen'])) ? $_FILES['imagen'] : null;
$rutaImagen = '';
$conexion = new conexPG();
$sql = "select * from seguridad.usuario where id='$userToken->sub'";
$r = $conexion->consultaComplejaNor($sql);
if (pg_num_rows($r) > 0) {
$sql = "select * from presaber.contrato_entidad where id='$id'";
$r = $conexion->consultaComplejaNor($sql);
if (pg_num_rows($r) > 0) {
$contrato_entidad = pg_fetch_assoc($r);
if ($imagen != null) {
$extension = pi_poExtenssion($imagen);
$validacion = 1;
if ($extension == 'png' || $extension == 'gif' || $extension == 'jpg' || $extension == 'jpeg') {
if ($contrato_entidad['imagen'] != '/imagenes_estandar/logo-contrato-45x45.png') {
pi_poEliminarArchivo($contrato_entidad['imagen']);
}
$nombreArchivo = time();
pi_poMove('/imagenes/contrato_entidad', $imagen, $nombreArchivo);
$rutaImagen = '/imagenes/contrato_entidad/' . $nombreArchivo . '.' . $extension;
} else {
$validacion = 2;
}
}
$fecha_actualizacion = date('Y-m-d H:i');
if ($imagen != null) {
if ($validacion == 1) {
$sql = "UPDATE presaber.contrato_entidad
SET descripcion='$descripcion', ciudad_id_fk='$ciudad', estado='$estado', tipo='$tipo', imagen='$rutaImagen', fecha_actualizacion='$fecha_actualizacion'
WHERE id='$id';";
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-007'
];
} else {
$data = [
'code' => 'LTE-014'
];
}
} else {
$sql = "UPDATE presaber.contrato_entidad
SET descripcion='$descripcion', ciudad_id_fk='$ciudad', estado='$estado', tipo='$tipo', fecha_actualizacion='$fecha_actualizacion'
WHERE id='$id';";
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-007'
];
}
} else {
$data = [
'code' => 'LTE-002'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/administrador/eliminarContratoEntidad',function ()use ($app){
$helper = new helper();
$json = $app->request->post('json',null);
if ($json != null)
{
$token=$app->request->post('token',null);
if ($token != null)
{
$validacionToken=$helper->authCheck($token);
if ($validacionToken == true)
{
$parametros = json_decode($json);
$id=(isset($parametros->id)) ? $parametros->id : null;
$conexion = new conexPG();
$sql="select * from presaber.contrato_entidad where id='$id' and estado like 'ACTIVO'";
$r=$conexion->consultaComplejaNor($sql);
if (pg_num_rows($r)>0)
{
$sql = "update presaber.contrato_entidad set estado='INACTIVO' where id='$id'";
$conexion->consultaSimple($sql);
$data=[
'code'=>'LTE-008'
];
}else
{
$data = [
'code'=>'LTE-002'
];
}
}else
{
$data=[
'LTE-011'
];
}
}else
{
$data=[
'code'=>'LTE-010'
];
}
}else
{
$data=[
'code'=>'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/administrador/listarContratos', function () use($app){
$helper = new helper();
$token = $app->request->post('token',null);
if ($token != null)
{
$validacionUsuario = $helper->authCheck($token);
if ($validacionUsuario == true)
{
$conexion = new conexPG();
$sql="select ce.*, ci.descripcion as descripcion_ciudad from presaber.contrato_entidad ce join configuracion.ciudad ci on ce.ciudad_id_fk= ci.id order by id desc limit 200";
$r = $conexion->consultaComplejaAso($sql);
if ($r>0)
{
$data = [
'code'=>'LTE-001',
'data'=>$r
];
}else
{
$data = [
'code'=>'LTE-003'
];
}
}else
{
$data=[
'code'=>'LTE-013',
'line'=>'248-contrato-entidad'
];
}
}else
{
$data = [
'code'=>'LTE-013',
'line'=>'255-contrato-entidad'
];
}
echo $helper->checkCode($data);
});
$app->post('/administrador/filtroContrato', function () use($app){
$json = $app->request->post('json',null);
$toke = $app->request->post('token',null);
$helper = new helper();
if ($json != null)
{
if ($toke != null)
{
$validarToke = $helper->authCheck($toke);
if ($validarToke == true)
{
$parametros = json_decode($json);
$filtro = (isset($parametros->filstro)) ? $parametros->filtro : $parametros->filtro;
$sql = "select ce.*, ci.descripcion as descripcion_ciudad from presaber.contrato_entidad ce join configuracion.ciudad ci on ce.ciudad_id_fk= ci.id
where ce.descripcion like '%$filtro%' or ci.descripcion like '%$filtro%' order by fecha_creacion DESC limit 200";
$conexion = new conexPG();
$r = $conexion->consultaComplejaNor($sql);
if (pg_num_rows($r)>0)
{
$data = [
'code'=>'LTE-001',
'data'=>pg_fetch_assoc($r)
];
}else
{
$data=[
'code'=>'LTE-003'
];
}
}else
{
$data = [
'code'=>'LTE-013'
];
}
}else
{
$data = [
'code'=>'LTE-010'
];
}
}else
{
$data = [
'code'=>'LTE-009'
];
}
echo $helper->checkCode($data);
});<file_sep>/PreSaber-Web/src/app/components/home-admin/home-admin.component.ts
import {Component, OnInit} from '@angular/core';
import {ElementsService} from "../../services/elements.service";
import {Router, ActivatedRoute} from "@angular/router";
@Component({
selector: 'app-home-admin',
templateUrl: './home-admin.component.html',
styleUrls: ['./home-admin.component.css'],
providers: [ElementsService]
})
export class HomeAdminComponent implements OnInit {
public userIdentity: any;
constructor(private _ElementService: ElementsService,
private _Router: Router, private _Route: ActivatedRoute) {
this.userIdentity = this._ElementService.getUserIdentity();
}
ngOnInit() {
this._ElementService.pi_poValidarUsuario('HomeAdminComponent');
}
}
<file_sep>/php-backend/App/componentes/profesor/pregunta.php
<?php
$app->post('/profesor/listarPregunta', function () use ($app) {
$json = $app->request->post('json', null);
$helper = new helper();
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$conexion = new conexPG();
$parametros = json_decode($json);
$id_sesion = (isset($parametros->id_sesion)) ? $parametros->id_sesion : null;
$sql = "select * from evaluacion.pregunta pre
join evaluacion.competencia cpcia on pre.compentencia_id_fk=cpcia.id_competencia
join evaluacion.componente cpte on pre.componente_id_fk=cpte.id_componente where pre.sesion_id_fk='$id_sesion'
order by pre.id_pregunta desc;";
$r = $conexion->consultaComplejaAso($sql);
$data = [
'code' => 'LTE-001',
'data' => $r
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/cargarPregunta', function () use ($app){
$json = $app->request->post('json', null);
$helper = new helper();
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$conexion = new conexPG();
$parametros = json_decode($json);
$id_pregunta = (isset($parametros->id_pregunta)) ? $parametros->id_pregunta : null;
$sql = "select p.* from evaluacion.pregunta p where p.id_pregunta='$id_pregunta'";
$r = $conexion->consultaComplejaNorAso($sql);
$data = [
'code' => 'LTE-001',
'data' => [
'id_pregunta'=>$r['id_pregunta'],
'sesion_id_fk'=>$r['sesion_id_fk'],
'contexto'=>html_entity_decode($r['contexto'],ENT_QUOTES),
'pregunta'=>html_entity_decode($r['pregunta'],ENT_QUOTES),
'justificacion'=>html_entity_decode($r['justificacion'],ENT_QUOTES),
'compentencia_id_fk'=>$r['compentencia_id_fk'],
'componente_id_fk'=>$r['componente_id_fk']
]
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/eliminarPregunta', function () use ($app){
$json = $app->request->post('json', null);
$helper = new helper();
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$conexion = new conexPG();
$parametros = json_decode($json);
$id_pregunta = (isset($parametros->id_pregunta)) ? $parametros->id_pregunta : null;
$sql = "DELETE FROM evaluacion.respuesta
WHERE pregunta_id_fk='$id_pregunta';";
$r = $conexion->consultaSimple($sql);
$sql = "delete from evaluacion.pregunta p where p.id_pregunta='$id_pregunta'";
$r = $conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-008'
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});<file_sep>/PreSaber-Web/src/app/models/contratoEntidad.ts
export class ContratoEntidad {
constructor(public id: '',
public usuario_administrador_id_fk: string,
public descripcion: string,
public ciudad_id_fk: any,
public descripcion_ciudad: any,
public estado: string,
public tipo: string,
public imagen: any,
public fecha_creacion: any,
public fecha_actualizacion: number) {}
}
<file_sep>/PreSaber-Web/src/app/services/registro.service.ts
import {Injectable} from "@angular/core";
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {Observable} from "rxjs/Observable";
import {User} from "../models/user";
import {GLOBAL} from "./global";
@Injectable()
export class RegistroService {
public url: string;
constructor(public _http: HttpClient) {
this.url = GLOBAL.url;
}
newRegister(user): Observable<any> {
let json = JSON.stringify(user);
//let params = 'json=' + '{"email":"' + user.email + '","password":"' + user.password + '","firstName":"'
//+ user.firstName + '","lastName":"' + user.lastName + '"}';
let params = 'json=' + json;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(this.url + 'crearUsuario', params, {headers: headers});
}
activateAcount(user): Observable<any> {
let params = 'json=' + '{"correo":"' + user.correo + '","codigo_activacion":"' + user.codigo_activacion + '"}';
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(this.url + 'activarCodigo', params, {headers: headers});
}
}
<file_sep>/PreSaber-Nuevo/src/app/services/elements.service.ts
import {Injectable} from "@angular/core";
import {User} from "../models/user";
import {Observable} from "rxjs/Observable";
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {GLOBAL} from "./global";
import {Globalstate} from "../models/globalstate";
import {ToastData, ToastOptions, ToastyService} from 'ng2-toasty';
import {OnInit} from "@angular/core";
import {Router} from "@angular/router";
import swal from 'sweetalert2';
declare var alertify: any;
declare var PNotify: any;
@Injectable()
export class ElementsService implements OnInit {
public positon: string;
public url: string;
public user: any;
public entity: Array<Globalstate>;
public userIdentity: any;
public home: string;
constructor(public _http: HttpClient, private _Router: Router, private toastyService: ToastyService) {
this.url = GLOBAL.url;
this.positon='top-right';
}
ngOnInit() {
}
pi_poAlertaSuccess(mensaje,titulo) {
this.positon = 'top-right';
const toastOptions: ToastOptions = {
title: titulo,
msg: mensaje,
showClose: true,
timeout: 5000,
theme: 'material'
};
this.toastyService.success(toastOptions);
}
pi_poAlertaError(mensaje,titulo) {
this.positon = 'top-right';
const toastOptions: ToastOptions = {
title: titulo,
msg: mensaje,
showClose: true,
timeout: 5000,
theme: 'material'
};
this.toastyService.error(toastOptions);
}
pi_poAlertaWarning(mensaje,titulo) {
this.positon = 'top-right';
const toastOptions: ToastOptions = {
title: titulo,
msg: mensaje,
showClose: true,
timeout: 5000,
theme: 'material'
};
this.toastyService.warning(toastOptions);
}
pi_poAlertaMensaje(mensaje,titulo) {
this.positon = 'top-right';
const toastOptions: ToastOptions = {
title: titulo,
msg: mensaje,
showClose: true,
timeout: 5000,
theme: 'material'
};
this.toastyService.info(toastOptions);
}
pi_poBontonDesabilitar(idBoton) {
$(idBoton).attr('disabled', 'disabled');
}
pi_poBotonHabilitar(idBoton) {
$(idBoton).removeAttr('disabled')
}
pi_poValidarUsuario(nombreVista) {
this.userIdentity = this.getUserIdentity();
let validacion = 0;
if (this.userIdentity != null) {
for (let i in this.userIdentity.permisos) {
if (this.userIdentity.permisos[i].descripcion == nombreVista) {
validacion = 1;
}
}
if (validacion == 1) {
} else {
this.home = this.userIdentity.rol_descripcion;
this._Router.navigate([this.home]);
swal(
'Cancelled',
'Lo sentimos, no cuentas con los permisos suficientes para ingresar a este modulo',
'error'
);
}
} else {
this._Router.navigate(['']);
}
}
pi_poValidarCodigo(respuesta) {
switch (respuesta.code) {
case 'LTE-004':
swal({
title: respuesta.code,
text: respuesta.msg,
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
confirmButtonText: 'Iniciar sesion',
confirmButtonClass: 'btn btn-success',
});
localStorage.removeItem('token');
localStorage.removeItem('userIdentity');
localStorage.removeItem('ficha');
break;
case 'LTE-005':
swal({
title: respuesta.code,
text: respuesta.msg,
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
confirmButtonText: 'Iniciar sesion',
confirmButtonClass: 'btn btn-success',
});
localStorage.removeItem('token');
localStorage.removeItem('userIdentity');
localStorage.removeItem('ficha');
break;
case 'LTE-011':
swal({
title: respuesta.code,
text: respuesta.msg,
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
confirmButtonText: 'Iniciar sesion',
confirmButtonClass: 'btn btn-success',
});
localStorage.removeItem('token');
localStorage.removeItem('userIdentity');
localStorage.removeItem('ficha');
break;
case 'LTE-013':
swal({
title: respuesta.code,
text: respuesta.msg,
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
confirmButtonText: 'Iniciar sesion',
confirmButtonClass: 'btn btn-success',
});
localStorage.removeItem('token');
localStorage.removeItem('userIdentity');
localStorage.removeItem('ficha');
break;
case 'LTE-014':
swal({
title: respuesta.code,
text: respuesta.msg,
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
confirmButtonText: 'Iniciar sesion',
confirmButtonClass: 'btn btn-success',
});
break;
default:
}
}
pi_poVentanaAlerta(titulo, mensaje) {
swal({
title: titulo,
text: mensaje,
type: 'success'
}).catch(swal.noop);
}
pi_poVentanaAlertaWarning(titulo,mensaje)
{
swal({
title: titulo,
text: mensaje,
type: 'warning'
}).catch(swal.noop);
}
alerts(tipe, msg) {
let data = '';
if (tipe == 1 || tipe == '1') {
data = '<div class="alert alert-success icons-alert" style="margin-bottom: 0px;">' +
'<button type="button" class="close" data-dismiss="alert" aria-label="Close">' +
'<i class="icofont icofont-close-line-circled"></i>' +
'</button>\n' +
'<p><strong>Bien hecho!</strong> <code>' + msg + '</code></p>' +
'</div>';
} else if (tipe == 2 || tipe == '2') {
data = '<div class="alert alert-warning icons-alert" style="margin-bottom: 0px;">' +
'<button type="button" class="close" data-dismiss="alert" aria-label="Close">' +
'<i class="icofont icofont-close-line-circled"></i>' +
'</button>\n' +
'<p><strong>Cuidado!</strong> <code>' + msg + '</code></p>' +
'</div>';
} else if (tipe == 3 || tipe == '3') {
data = '<div class="alert alert-danger icons-alert" style="margin-bottom: 0px;">' +
'<button type="button" class="close" data-dismiss="alert" aria-label="Close">' +
'<i class="icofont icofont-close-line-circled"></i>' +
'</button>\n' +
'<p><strong>Error!</strong> <code>' + msg + '</code></p>' +
'</div>';
} else {
}
return data;
}
//Traer usuario de local storage
getUserIdentity() {
let usuario = JSON.parse(localStorage.getItem('userIdentity'));
if (usuario != 'undefined') {
this.user = usuario;
} else {
this.user = null;
}
return this.user;
}
}
<file_sep>/PreSaber-Nuevo/src/app/models/seccion.ts
export class Seccion {
constructor(public id: any,
public modulo_id_fk: any,
public usuario_profesor_id_fk: any,
public description: any,
public prioridad: any,
public imagen: any,
public estado: any,
public fecha_creacion: any,
public fecha_actualizacion: any) {
}
}
<file_sep>/PreSaber-Web/src/app/components/administrador/crear-seccion/crear-seccion.component.ts
import { Component, OnInit } from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {ElementsService} from "../../../services/elements.service";
@Component({
selector: 'app-crear-seccion',
templateUrl: './crear-seccion.component.html',
styleUrls: ['./crear-seccion.component.css']
})
export class CrearSeccionComponent implements OnInit {
public userIdentity: any;
constructor(private _ElementService: ElementsService,
private _Router: Router, private _Route: ActivatedRoute) {
this.userIdentity = this._ElementService.getUserIdentity();
}
ngOnInit() {
this._ElementService.pi_poValidarUsuario('CrearSeccionComponent');
}
}
<file_sep>/php-backend/App/componentes/estudiante/estudiante.php
<?php
$app->post('/estudiante/MisFichas', function () use ($app) {
$token = $app->request->post('token', null);
$helper = new helper();
$conexion = new conexPG();
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$usuarioToken = $helper->authCheck($token, true);
$sql = "select usu.id as id_usuario,conenti.id as id_contrato,
conenti.imagen as imagen_contrato_entidad,
fiusu.estado as estado_usuario_ficha,
fiusu.fecha_terminacion as fecha_finalizacion_usuario,
fiusu.id as id_usuario_ficha,
ficha.id as id_ficha,
ficha.descripcion as descripcion_ficha_usuario,
ficha.contrato_entidad_id_fk as id_contrato_entidad,
ficha.curso_id_fk as id_curso from seguridad.usuario as usu
inner join presaber.ficha_usuario as fiusu on usu.id=fiusu.usuario_id_fk
inner join presaber.ficha as ficha on fiusu.ficha_id_fk=ficha.id
inner join presaber.contrato_entidad as conenti on ficha.contrato_entidad_id_fk = conenti.id
where usu.id = '$usuarioToken->sub'";
$r = $conexion->consultaComplejaAso($sql);
$data = [
'code' => 'LTE-001',
'data' => $r
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
echo $helper->checkCode($data);
});
$app->post('/estudiante/MisCursos', function () use ($app) {
$token = $app->request->post('token', null);
$helper = new helper();
$conexion = new conexPG();
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$usuarioToken = $helper->authCheck($token, true);
$id = $app->request->post('id', null);
$sql = "select cur.* from seguridad.usuario usu
inner join presaber.ficha_usuario fiusu on usu.id= fiusu.usuario_id_fk
inner join presaber.ficha fi on fi.id=fiusu.ficha_id_fk
inner join presaber.curso cur on fi.curso_id_fk=cur.id
where usu.id ='$usuarioToken->sub' and fi.id = '$id' ";
$r = $conexion->consultaComplejaAso($sql);
$data = [
'code' => 'LTE-001',
'data' => $r
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
echo $helper->checkCode($data);
});
$app->post('/estudiante/MisModulos', function () use ($app) {
$token = $app->request->post('token', null);
$helper = new helper();
$conexion = new conexPG();
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$usuarioToken = $helper->authCheck($token, true);
$ficha = $app->request->post('id', null);
$curso = $app->request->post('id_curso', null);
$sql = "select mo.* from seguridad.usuario usu
inner join presaber.ficha_usuario fiusu on usu.id= fiusu.usuario_id_fk
inner join presaber.ficha fi on fi.id=fiusu.ficha_id_fk
inner join presaber.curso cur on fi.curso_id_fk=cur.id
inner join presaber.modulo mo on mo.curso_id_fk=cur.id
where usu.id = '$usuarioToken->sub' and fi.id = '$ficha' and cur.id='$curso' order BY mo.prioridad ASC";
$r = $conexion->consultaComplejaAso($sql);
$data = [
'code' => 'LTE-001',
'data' => $r
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
echo $helper->checkCode($data);
});
$app->post('/estudiante/misClases', function () use ($app) {
$token = $app->request->post('token', null);
$helper = new helper();
$conexion = new conexPG();
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$usuarioToken = $helper->authCheck($token, true);
$modulo = $app->request->post('id', null);
$sql = "select * from presaber.seccion sec where sec.modulo_id_fk='$modulo' order by sec.prioridad ASC;";
$r = $conexion->consultaComplejaAso($sql);
$data = [
'code' => 'LTE-001',
'data' => $r
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
echo $helper->checkCode($data);
});
$app->post('/estudiante/ActividadesClases', function () use ($app) {
$token = $app->request->post('token', null);
$helper = new helper();
$conexion = new conexPG();
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$usuarioToken = $helper->authCheck($token, true);
$seccion = $app->request->post('id', null);
$sql = "select sere.id as id_sesion_recurso,sere.imagen, sere.prioridad as prioridad_recurso,
sere.descripcion as descripcion_sesion_recurso,
sere.estado as estado_sesion_recurso,
usu.documento,usu.nombre,usu.apellido,
usu.correo, re.id as id_recurso, re.descripcion as descripcion_recurso,
re.contenido as recurso_contenido,
re.estado as estado_recurso, tr.descripcion as tipo_recurso,rr.* from presaber.seccion_recurso sere
inner join presaber.recurso re on sere.recurso_id_fk=re.id
inner join presaber.tipo_recurso tr on re.tipo_recurso_id_fk=tr.id
inner join seguridad.usuario usu on re.usuario_profesor_id_fk = usu.id
left join presaber.resultados_recurso rr on sere.id=rr.seccion_recurso_id_fk_resultado_recurso
where sere.seccion_id_fk = '$seccion' order by sere.prioridad ASC";
$r = $conexion->consultaComplejaAso($sql);
$resultado = array();
if ($r != 0) {
for ($i = 0; $i < count($r); $i++) {
$text1 = $r[$i]['descripcion_recurso'];
$text2 = $r[$i]['recurso_contenido'];
array_push($resultado, [
'id_sesion_recurso' => $r[$i]['id_sesion_recurso'],
'prioridad_recurso' => $r[$i]['prioridad_recurso'],
'descripcion_sesion_recurso' => $r[$i]['descripcion_sesion_recurso'],
'estado_sesion_recurso' => $r[$i]['estado_sesion_recurso'],
'documento' => $r[$i]['documento'],
'nombre' => $r[$i]['nombre'],
'apellido' => $r[$i]['apellido'],
'correo' => $r[$i]['correo'],
'id_recurso' => $r[$i]['id_recurso'],
'descripcion_recurso' => html_entity_decode($text1, ENT_COMPAT),
'recurso_contenido' => json_decode($text2),
'estado_recurso' => $r[$i]['estado_recurso'],
'tipo_recurso' => $r[$i]['tipo_recurso'],
'imagen' => $r[$i]['imagen'],
'id_resultado_recurso'=>$r[$i]['id_resultado_recurso'],
'descripcion_resultado_recurso'=>$r[$i]['descripcion_resultado_recurso'],
'json_resultado_recurso'=>json_decode($r[$i]['json_resultado_recurso']),
'estado_resultado_recurso'=>$r[$i]['estado_resultado_recurso'],
'fecha_creacion_resultado_recurso'=>$r[$i]['fecha_creacion_resultado_recurso'],
'fecha_actualizacion_resultado_recurso'=>$r[$i]['fecha_actualizacion_resultado_recurso'],
'id_usuario_id_fk_resultado_recurso'=>$r[$i]['id_usuario_id_fk_resultado_recurso'],
'seccion_recurso_id_fk_resultado_recurso'=>$r[$i]['seccion_recurso_id_fk_resultado_recurso'],
'descripcion_resultado_recurso_profesor'=>$r[$i]['descripcion_resultado_recurso_profesor']
]);
}
} else {
$resultado = 0;
}
$data = [
'code' => 'LTE-001',
'data' => $resultado
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
echo $helper->checkCode($data);
});
$app->post('/estudiante/nuevaRespuestaArchivo', function () use ($app) {
$token = $app->request->post('token', null);
$helper = new helper();
$conexion = new conexPG();
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$json = $app->request->post('json', null);
$parametros = json_decode($json);
$descripcion_resultado_recurso = (isset($parametros->descripcion_resultado_recurso)) ? $parametros->descripcion_resultado_recurso : null;
$seccion_recurso_id_fk_resultado_recurso = (isset($parametros->seccion_recurso_id_fk_resultado_recurso)) ? $parametros->seccion_recurso_id_fk_resultado_recurso : null;
$archivos = (isset($_FILES['archivo'])) ? $_FILES['archivo'] : null;
$r = pi_poMoveMultiple('/archivos/respuestas/', $archivos);
$r = json_encode($r);
$usuarioToken = $helper->authCheck($token, true);
$modulo = $app->request->post('id', null);
$fecha_creacion = date('Y-m-d H:i');
$sql = "INSERT INTO presaber.resultados_recurso(
descripcion_resultado_recurso, json_resultado_recurso, estado_resultado_recurso,
fecha_creacion_resultado_recurso, fecha_actualizacion_resultado_recurso,
id_usuario_id_fk_resultado_recurso, seccion_recurso_id_fk_resultado_recurso)
VALUES ('$descripcion_resultado_recurso', '$r', 'ACTIVO', '$fecha_creacion', '$fecha_creacion',
'$usuarioToken->sub', '$seccion_recurso_id_fk_resultado_recurso');";
$conexion->consultaComplejaNor($sql);
$data = [
'code' => 'LTE-001'
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
echo $helper->checkCode($data);
});
$app->post('/estudiante/cargarSeccionRecurso', function () use ($app) {
$token = $app->request->post('token', null);
$helper = new helper();
$conexion = new conexPG();
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$usuarioToken = $helper->authCheck($token, true);
$seccion = $app->request->post('id', null);
$sql = "select sere.id as id_sesion_recurso,sere.imagen, sere.prioridad as prioridad_recurso,
sere.descripcion as descripcion_sesion_recurso,
sere.estado as estado_sesion_recurso,
usu.documento,usu.nombre,usu.apellido,
usu.correo, re.id as id_recurso, re.descripcion as descripcion_recurso,
re.contenido as recurso_contenido,
re.estado as estado_recurso, tr.descripcion as tipo_recurso,rr.* from presaber.seccion_recurso sere
inner join presaber.recurso re on sere.recurso_id_fk=re.id
inner join presaber.tipo_recurso tr on re.tipo_recurso_id_fk=tr.id
inner join seguridad.usuario usu on re.usuario_profesor_id_fk = usu.id
left join presaber.resultados_recurso rr on sere.id=rr.seccion_recurso_id_fk_resultado_recurso
where sere.id= '$seccion' order by sere.prioridad ASC";
$r = $conexion->consultaComplejaAso($sql);
$resultado = array();
if ($r != 0) {
for ($i = 0; $i < count($r); $i++) {
$text1 = $r[$i]['descripcion_recurso'];
$text2 = $r[$i]['recurso_contenido'];
array_push($resultado, [
'id_sesion_recurso' => $r[$i]['id_sesion_recurso'],
'prioridad_recurso' => $r[$i]['prioridad_recurso'],
'descripcion_sesion_recurso' => $r[$i]['descripcion_sesion_recurso'],
'estado_sesion_recurso' => $r[$i]['estado_sesion_recurso'],
'documento' => $r[$i]['documento'],
'nombre' => $r[$i]['nombre'],
'apellido' => $r[$i]['apellido'],
'correo' => $r[$i]['correo'],
'id_recurso' => $r[$i]['id_recurso'],
'descripcion_recurso' => html_entity_decode($text1, ENT_COMPAT),
'recurso_contenido' => json_decode($text2),
'estado_recurso' => $r[$i]['estado_recurso'],
'tipo_recurso' => $r[$i]['tipo_recurso'],
'imagen' => $r[$i]['imagen'],
'id_resultado_recurso'=>$r[$i]['id_resultado_recurso'],
'descripcion_resultado_recurso'=>$r[$i]['descripcion_resultado_recurso'],
'json_resultado_recurso'=>json_decode($r[$i]['json_resultado_recurso']),
'estado_resultado_recurso'=>$r[$i]['estado_resultado_recurso'],
'fecha_creacion_resultado_recurso'=>$r[$i]['fecha_creacion_resultado_recurso'],
'fecha_actualizacion_resultado_recurso'=>$r[$i]['fecha_actualizacion_resultado_recurso'],
'id_usuario_id_fk_resultado_recurso'=>$r[$i]['id_usuario_id_fk_resultado_recurso'],
'seccion_recurso_id_fk_resultado_recurso'=>$r[$i]['seccion_recurso_id_fk_resultado_recurso'],
'descripcion_resultado_recurso_profesor'=>$r[$i]['descripcion_resultado_recurso_profesor']
]);
}
} else {
$resultado = 0;
}
$data = [
'code' => 'LTE-001',
'data' => $resultado
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
echo $helper->checkCode($data);
});<file_sep>/PreSaber-Nuevo/src/app/components/home-estudiante/home-estudiante.component.ts
import {Component, OnInit} from '@angular/core';
import {ElementsService} from "../../services/elements.service";
import {EstudianteService} from "../../services/estudiante/estudiante.service";
import {GLOBAL} from "../../services/global";
import {Router} from "@angular/router";
@Component({
selector: 'app-home-estudiante',
templateUrl: './home-estudiante.component.html',
styleUrls: ['./home-estudiante.component.css'],
providers: [ElementsService, EstudianteService]
})
export class HomeEstudianteComponent implements OnInit {
public token: any;
public listFichas = [];
public urlFiles: any;
public fichaSeleccionada: any;
constructor(private _ElementsService: ElementsService,
private _EstudianteService: EstudianteService,
private _Route:Router) {
this.urlFiles = GLOBAL.urlFiles;
}
ngOnInit() {
this._ElementsService.pi_poValidarUsuario('HomeEstudianteComponent');
this.token = localStorage.getItem('token');
this.fichaSeleccionada = localStorage.getItem('ficha');
this.listarFichasUsuario()
}
listarFichasUsuario() {
this._EstudianteService.listarFichasUsuario(this.token).subscribe(
respuesta => {
this._ElementsService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
if (respuesta.data != 0) {
this.listFichas = respuesta.data;
} else {
}
} else {
}
}, error2 => {
}
)
}
seleccionarFicha(fichas){
localStorage.setItem('ficha',fichas.id_ficha);
this._Route.navigate(['estudiante/misCursos']);
}
}
<file_sep>/PreSaber-Nuevo/src/app/services/recursos.service.ts
import {Injectable} from "@angular/core";
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {Observable} from "rxjs/Observable";
import {GLOBAL} from "./global";
@Injectable()
export class RecursosService{
public url: string;
constructor(private _Htttp: HttpClient)
{
this.url = GLOBAL.url;
}
cargarTipos(): Observable<any>{
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Htttp.post(this.url + 'profesor/cargarTipoRecurso',{headers: headers});
}
crearTallerExamen(token,recurso,crearTaller,baseExamen,configuracion,sesion,tipoRecurso): Observable<any>
{
let objCompleto = Object.assign(recurso,crearTaller,baseExamen,configuracion,tipoRecurso,sesion);
console.log(objCompleto);
let json = JSON.stringify(objCompleto);
let parametros = 'token='+token+'&json='+json;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Htttp.post(this.url + 'profesor/crearTalleExamen',parametros,{headers: headers});
}
cargarExamenTaller(token,tipoRecurso): Observable<any>
{
let json = JSON.stringify(tipoRecurso);
let parametros = 'token='+token+'&json='+json;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Htttp.post(this.url + 'profesor/listarExamenesTalleres',parametros,{headers: headers});
}
listarArchivos(token,tipoRecurso): Observable<any>
{
let json = JSON.stringify(tipoRecurso);
let parametros = 'token='+token+'&json='+json;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Htttp.post(this.url + '/profesor/listarArchivos',parametros,{headers: headers});
}
eliminarArchivos(token,recurso,id): Observable<any>
{
let json = JSON.stringify(recurso);
let parametros = 'token='+token+'&json='+json+'&id_archivo='+id;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Htttp.post(this.url + '/profesor/eliminarArchivo',parametros,{headers: headers});
}
editarDescripcionArchivo(token,recurso): Observable<any>
{
let json = JSON.stringify(recurso);
let parametros = 'token='+token+'&json='+json;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Htttp.post(this.url + '/profesor/editarDescripcionArchivo',parametros,{headers: headers});
}
editarEstadoArchivo(token,recurso): Observable<any>
{
let json = JSON.stringify(recurso);
let parametros = 'token='+token+'&json='+json;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Htttp.post(this.url + '/profesor/editarEstadoArchivo',parametros,{headers: headers});
}
contenidoArchivos(token,tipoRecurso,idrecurso): Observable<any>
{
tipoRecurso.id_recurso= idrecurso;
let json = JSON.stringify(tipoRecurso);
let parametros = 'token='+token+'&json='+json;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Htttp.post(this.url + '/profesor/contenidoArchivo',parametros,{headers: headers});
}
nuevoArchivo(token, params: Array<string>, files: Array<File>, data = null) {
let urlF = this.url + 'profesor/nuevoArchivos';
return new Promise((resolve, reject) => {
var formData: any = new FormData();
var xhr = new XMLHttpRequest();
if (files != undefined) {
var name_file_input = params[0];
for (var i = 0; i < files.length; i++) {
formData.append('archivo[]', files[i], files[i].name);
}
}
if (token != null)
{
formData.append('token', token);
}
if (data != null)
var json = JSON.stringify(data);
formData.append('json', json);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
}
xhr.open("POST", urlF, true);
xhr.send(formData);
});
}
crearRescurso(token, params: Array<string>, files: Array<File>, data = null) {
let urlF = this.url + 'profesor/crearRecurso';
return new Promise((resolve, reject) => {
var formData: any = new FormData();
var xhr = new XMLHttpRequest();
if (files != undefined) {
var name_file_input = params[0];
for (var i = 0; i < files.length; i++) {
formData.append('archivo[]', files[i], files[i].name);
}
}
if (token != null)
{
formData.append('token', token);
}
if (data != null)
var json = JSON.stringify(data);
formData.append('json', json);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
}
xhr.open("POST", urlF, true);
xhr.send(formData);
});
}
}
<file_sep>/php-backend/App/componentes/profesor/sesion_recurso.php
<?php
$app->post('/profesor/crearSesionRecurso', function () use ($app) {
$helper = new helper();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionUsuarioToken = $helper->authCheck($token);
if ($validacionUsuarioToken == true) {
$usuarioToken = $helper->authCheck($token, true);
$conexion = new conexPG();
$parametros = json_decode($json);
$seccion_id_fk = (isset($parametros->seccion_id_fk)) ? $parametros->seccion_id_fk : null;
$recurso_id_fk = (isset($parametros->recurso_id_fk)) ? $parametros->recurso_id_fk : null;
$usuario_profesor_id_fk = $usuarioToken->sub;
$descripcion = (isset($parametros->descripcion)) ? $parametros->descripcion : null;
$estado = (isset($parametros->estado)) ? $parametros->estado : null;
$sql = "select se.*,tr.descripcion as tipoRecursoD, re.descripcion as descripRe, re.id as idRe from presaber.seccion_recurso se
join presaber.recurso re on se.recurso_id_fk=re.id
join presaber.tipo_recurso tr on re.tipo_recurso_id_fk=tr.id
where se.usuario_profesor_id_fk ='$usuarioToken->sub' and se.seccion_id_fk='$seccion_id_fk' and se.recurso_id_fk='$recurso_id_fk'";
$r = $conexion->consultaComplejaNorAso($sql);
if ($r == 0) {
$sql = "select se.*,tr.descripcion as tipoRecursoD from presaber.seccion_recurso se
join presaber.recurso re on se.recurso_id_fk=re.id
join presaber.tipo_recurso tr on re.tipo_recurso_id_fk=tr.id
where se.usuario_profesor_id_fk ='$usuarioToken->sub' and se.seccion_id_fk='$seccion_id_fk'";
$r2 = $conexion->consultaComplejaNor($sql);
$sql = "select tr.descripcion from presaber.recurso re join presaber.tipo_recurso tr on re.tipo_recurso_id_fk=tr.id where re.id='$recurso_id_fk'";
$r = $conexion->consultaComplejaNorAso($sql);
$prioridad = pg_num_rows($r2) + 1;
if (strtolower($r['descripcion']) == 'archivo') {
$ruta = '/imagenes_estandar/archivo.png';
} else if (strtolower($r['descripcion']) == 'examen') {
$ruta = '/imagenes_estandar/examen.png';
} else if (strtolower($r['descripcion']) == 'taller') {
$ruta = '/imagenes_estandar/taller.png';
}
$fecha_creacion = date('Y-m-d H:i:s');
$sql = "INSERT INTO presaber.seccion_recurso(
seccion_id_fk, recurso_id_fk, usuario_profesor_id_fk, descripcion,
estado, prioridad, imagen, fecha_creacion, fecha_actualizacion)
VALUES ('$seccion_id_fk', '$recurso_id_fk', '$usuario_profesor_id_fk', '$descripcion',
'$estado', '$prioridad', '$ruta', '$fecha_creacion', '$fecha_creacion');";
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-001'
];
} else {
$data = [
'code' => 'LTE-000',
'status' => 'error',
'msg' => 'Lo sentimos, Ya existe un recurso con codigo: ' . $r['idre']
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/listarSesionRecurso', function () use ($app) {
$helper = new helper();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionUsuarioToken = $helper->authCheck($token);
if ($validacionUsuarioToken == true) {
$usuarioToken = $helper->authCheck($token, true);
$conexion = new conexPG();
$parametros = json_decode($json);
$seccion_id_fk = (isset($parametros->seccion_id_fk)) ? $parametros->seccion_id_fk : null;
$usuario_profesor_id_fk = $usuarioToken->sub;
$sql = "select se.*, tr.descripcion as descripcionRecurso, re.id as idrecurso from presaber.seccion_recurso se join presaber.recurso re on se.recurso_id_fk=re.id
join presaber.tipo_recurso tr on re.tipo_recurso_id_fk=tr.id where se.seccion_id_fk='$seccion_id_fk' and se.usuario_profesor_id_fk ='$usuario_profesor_id_fk' order by se.prioridad asc";
$r = $conexion->consultaComplejaAso($sql);
if ($r != 0) {
$data = [
'code' => 'LTE-001',
'data' => $r
];
} else {
$data = [
'code' => 'LTE-003'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/actualizarPrioridadSeccionRecurso', function () use ($app) {
$helper = new helper();
$token = $app->request->post('token', null);
if ($token != null) {
$validacionUsuarioToken = $helper->authCheck($token);
if ($validacionUsuarioToken == true) {
$usuarioToken = $helper->authCheck($token, true);
$conexion = new conexPG();
$json = $app->request->post('sesionRecurso', null);
$sesionesRecurso = json_decode($json, true);
for ($i = 0; $i < count($sesionesRecurso); $i++) {
$prioridad = $sesionesRecurso[$i]['prioridad'];
$id = $sesionesRecurso[$i]['id'];
$fecha_actualizacion = date('Y-m-d H:i:s');
$sql = "UPDATE presaber.seccion_recurso
SET prioridad='$prioridad',fecha_actualizacion='$fecha_actualizacion'
WHERE id='$id';";
$conexion->consultaSimple($sql);
}
$data = [
'code' => 'LTE-001'
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/actualizarSeccionRecurso', function () use ($app) {
$helper = new helper();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionUsuarioToken = $helper->authCheck($token);
if ($validacionUsuarioToken == true) {
$usuarioToken = $helper->authCheck($token, true);
$conexion = new conexPG();
$parametros = json_decode($json);
$id_seccionRecurso = (isset($parametros->id)) ? $parametros->id : null;
$seccion_id_fk = (isset($parametros->seccion_id_fk)) ? $parametros->seccion_id_fk : null;
$recurso_id_fk = (isset($parametros->recurso_id_fk)) ? $parametros->recurso_id_fk : null;
$descripcion = (isset($parametros->descripcion)) ? $parametros->descripcion : null;
$estado = (isset($parametros->estado)) ? $parametros->estado : null;
$sql = "select se.*,tr.descripcion as tipoRecursoD, re.descripcion as descripRe, re.id as idRe from presaber.seccion_recurso se
join presaber.recurso re on se.recurso_id_fk=re.id
join presaber.tipo_recurso tr on re.tipo_recurso_id_fk=tr.id
where se.usuario_profesor_id_fk ='$usuarioToken->sub' and se.seccion_id_fk='$seccion_id_fk' and se.recurso_id_fk='$recurso_id_fk'";
$r = $conexion->consultaComplejaNorAso($sql);
if ($r['recurso_id_fk'] == $recurso_id_fk)
{
$r =0;
}
if ($r == 0) {
$sql = "select se.* from presaber.seccion_recurso as se where se.id='$id_seccionRecurso'";
$r = $conexion->consultaComplejaAso($sql);
if ($r != 0) {
$sql = "select tr.descripcion from presaber.recurso re join presaber.tipo_recurso tr on re.tipo_recurso_id_fk=tr.id where re.id='$recurso_id_fk'";
$r = $conexion->consultaComplejaNorAso($sql);
if (strtolower($r['descripcion']) == 'archivo') {
$ruta = '/imagenes_estandar/archivo.png';
} else if (strtolower($r['descripcion']) == 'examen') {
$ruta = '/imagenes_estandar/examen.png';
} else if (strtolower($r['descripcion']) == 'taller') {
$ruta = '/imagenes_estandar/taller.png';
}
$fecha_actualizacion = date('Y-m-d H:i:s');
$sql = "UPDATE presaber.seccion_recurso
SET recurso_id_fk='$recurso_id_fk',descripcion='$descripcion', estado='$estado', imagen='$ruta', fecha_actualizacion='$fecha_actualizacion'
WHERE id='$id_seccionRecurso';";
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-007'
];
} else {
$data = [
'code' => 'LTE-003'
];
}
} else {
$data = [
'code' => 'LTE-000',
'status' => 'error',
'msg' => 'Lo sentimos, Ya existe un recurso con codigo: ' . $r['idre']
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});<file_sep>/PreSaber-Nuevo/src/app/components/estudiante/clases-asignatura/clases-asignatura.component.ts
import {Component, OnInit} from '@angular/core';
import {ElementsService} from "../../../services/elements.service";
import {EstudianteService} from "../../../services/estudiante/estudiante.service";
import {Seccion} from "../../../models/seccion";
import {GLOBAL} from "../../../services/global";
import {Resultados_recurso} from "../../../models/resultados_recurso";
import {SesionService} from "../../../services/evaluacion_services/sesion.service";
import {Sesion} from "../../../models/evaluacion/sesion";
import {Examne_taller} from "../../../models/evaluacion/examne_taller";
import {Examen_tallerService} from "../../../services/evaluacion_services/examen_taller.service";
import {htmlDecode} from "js-htmlencode";
@Component({
selector: 'app-clases-asignatura',
templateUrl: './clases-asignatura.component.html',
styleUrls: ['./clases-asignatura.component.scss'],
providers: [ElementsService, EstudianteService, SesionService, Examen_tallerService]
})
export class ClasesAsignaturaComponent implements OnInit {
public token: any;
public asginatura: string;
public extension: string;
public listSeccion: Array<Seccion>;
public asignaturatxt: string;
public listRecursos: Array<Object>;
public url: string;
public seccionActual: any;
position = "top-right";
public objArchivo: any;
public objArchivoEnviado: any;
public objExamenCompleto: any;
public options: Object;
public archivos: Array<File>;
public objSesion: Sesion;
public listSesiones: Array<Sesion>;
public objExamen: Examne_taller;
public objResultado_recurso: Resultados_recurso;
public passwordExamen: string;
public objCabezera: any;
public res: any;
public listCabezera;
public indexCabezera: any;
public listRespuestaCompleta;
constructor(private _ElementService: ElementsService,
private _EstudianteService: EstudianteService,
private _SesionService: SesionService,
private _ExamenTallerService: Examen_tallerService) {
this.token = localStorage.getItem('token');
this.objArchivo = null;
this.objArchivoEnviado = null;
this.objExamen = new Examne_taller('', '', '', '', '', '', '');
this.passwordExamen = '';
this.indexCabezera = 0;
this.options = {
language: 'es',
charCounterCount: true,
// Set the image upload parameter.
imageUploadParam: 'ImagenEditore',
// Set the image upload URL.
imageUploadURL: GLOBAL.url + 'pi_po/imagenesEditor',
// Additional upload params.
imageUploadParams: {id: 'ImagenEditore'},
// Set request type.
imageUploadMethod: 'POST',
// Set max image size to 5MB.
imageMaxSize: 5 * 1024 * 1024,
// Allow to upload PNG and JPG.
imageAllowedTypes: ['jpeg', 'jpg', 'png'],
fileUploadParam: 'Archivo',
fileUploadURL: GLOBAL.url + 'pi_po/archivosEditor',
fileUploadMethod: 'POST',
fileAllowedTypes: ['application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/pdf', 'application/vnd.openxmlformats-officedocument.presentationml.presentation']
}
this.objResultado_recurso = new Resultados_recurso('', 'SIN OBSERVACION', '', '',
'', '',
'', '', '');
this.objSesion = new Sesion('', '', '');
}
ngOnInit() {
this.asginatura = localStorage.getItem('asignatura');
this.asignaturatxt = localStorage.getItem('asignaturatxt');
this.url = GLOBAL.urlFiles;
$("#seccionRecursoClase").hide();
$("#contenedorArchivo").hide();
$("#seccionExamen").hide();
this.cargarSecciones();
$("#loaderTablasSesionExamen").hide();
this.objExamenCompleto = null;
}
cargarSecciones() {
this._EstudianteService.listarClasesModulo(this.token, this.asginatura).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.listSeccion = respuesta.data;
}
}, error2 => {
}
)
}
cargarRecursosClase(seccion) {
this.objArchivoEnviado = null;
this.seccionActual = seccion;
this._ElementService.pi_poBontonDesabilitar('#btnCargarRecurso');
if (seccion.estado == 'ACTIVO') {
this._EstudianteService.listarRecursosClases(this.token, seccion.id).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
if (respuesta.data != 0) {
this.listRecursos = respuesta.data;
this._ElementService.pi_poAlertaSuccess(respuesta.msg, respuesta.code);
$("#seccionClases").toggle(200);
$("#seccionRecursoClase").show(400);
this._ElementService.pi_poBotonHabilitar('#btnCargarRecurso');
} else {
this.listRecursos = null;
this._ElementService.pi_poAlertaWarning('Lo sentimos, no se encontraron actividades en esta clase', 'LTE-000');
this._ElementService.pi_poBotonHabilitar('#btnCargarRecurso');
}
} else {
this._ElementService.pi_poBotonHabilitar('#btnCargarRecurso');
}
}, error2 => {
this._ElementService.pi_poBotonHabilitar('#btnCargarRecurso');
}
)
} else {
this._ElementService.pi_poAlertaError('LTE-000', 'Lo sentimos, el estado de esta clase es INACTIVO');
}
}
regresarClase() {
$("#seccionRecursoClase").hide(500);
$("#seccionClases").toggle(700);
}
cargarSeccionRecurso(sesionRecurso) {
if (sesionRecurso.tipo_recurso.toLowerCase() == 'examen') {
this.objExamen.id_examen = sesionRecurso.recurso_contenido;
this.cargarSesionesExamen();
$("#idModal").attr("style", "display: block; opacity: 1;");
$("#idModal").addClass("basic modal fade in");
} else if (sesionRecurso.tipo_recurso.toLowerCase() == 'archivo') {
this.objArchivo = sesionRecurso;
if (this.objArchivo.id_resultado_recurso != null) {
this.objArchivoEnviado = this.objArchivo;
$('#seccionEnviarRespuesta').hide();
} else {
this.cargarRespuestaEnvio();
}
this.objResultado_recurso.seccion_recurso_id_fk_resultado_recurso = sesionRecurso.id_sesion_recurso;
$("#seccionRecursoClase").hide(500);
$("#contenedorArchivo").toggle(700);
} else if (sesionRecurso.tipo_recurso.toLowerCase() == 'taller') {
} else {
this._ElementService.pi_poVentanaAlertaWarning('LTE-000', 'Lo sentimos, Ha ocurrido un problema por favor contactar al departamento de sistemas');
}
}
descargarArchivo(archivo) {
window.open(GLOBAL.urlFiles + archivo.rute, 'download');
}
regresarRecurso() {
$("#contenedorArchivo").hide(500);
$("#seccionRecursoClase").toggle(700);
this.objArchivoEnviado = null;
}
cargarArchivos($event) {
this.archivos = <Array<File>>$event.target.files;
//this.archivosp.push(this.archivos[0]);
for (var i = 0; i < this.archivos.length; i++) {
let tipo = this.archivos[i].name.split('.');
let extension = tipo.pop().toLowerCase();
if (extension == 'png' || extension == 'jpg' || extension == 'gif') {
this.archivos[i]['tipo'] = 'imagen';
this.archivos[i]['extension'] = extension;
this.archivos[i]['estado'] = 'true';
this.archivos[i]['id'] = i;
} else if (extension == 'xls' || extension == 'xlsx') {
this.archivos[i]['tipo'] = 'excel';
this.archivos[i]['extension'] = extension;
this.archivos[i]['estado'] = 'true';
this.archivos[i]['id'] = i;
} else if (extension == 'docx' || extension == 'docm') {
this.archivos[i]['tipo'] = 'word';
this.archivos[i]['extension'] = extension;
this.archivos[i]['estado'] = 'true';
this.archivos[i]['id'] = i;
} else if (extension == 'pptx' || extension == 'ppt') {
this.archivos[i]['tipo'] = 'powerpoint';
this.archivos[i]['extension'] = extension;
this.archivos[i]['estado'] = 'true';
this.archivos[i]['id'] = i;
} else if (extension == 'pdf') {
this.archivos[i]['tipo'] = 'pdf';
this.archivos[i]['extension'] = extension;
this.archivos[i]['estado'] = 'true';
this.archivos[i]['id'] = i;
} else if (extension == 'txt') {
this.archivos[i]['tipo'] = 'texto';
this.archivos[i]['extension'] = extension;
this.archivos[i]['estado'] = 'true';
this.archivos[i]['id'] = i;
} else if (extension == 'rar') {
this.archivos[i]['tipo'] = 'rar';
this.archivos[i]['extension'] = extension;
this.archivos[i]['estado'] = 'false';
this.archivos[i]['id'] = i;
} else if (extension == 'exe') {
this.archivos[i]['tipo'] = 'exe';
this.archivos[i]['extension'] = extension;
this.archivos[i]['estado'] = 'false';
this.archivos[i]['id'] = i;
} else {
this.archivos[i]['tipo'] = 'desconocido';
this.archivos[i]['extension'] = extension;
this.archivos[i]['estado'] = 'false';
this.archivos[i]['id'] = i;
}
}
}
nuevaRespuestaArchivo() {
if (this.archivos != undefined) {
this._EstudianteService.nuevaRespuestaArchivo(this.token, ['archivos'], this.archivos, this.objResultado_recurso).then(
(resultado) => {
this._ElementService.pi_poValidarCodigo(resultado);
this.res = resultado;
if (this.res.status == 'success') {
this.cargarRespuestaEnvio();
} else {
this._ElementService.pi_poVentanaAlertaWarning(this.res.code, this.res.msg);
}
},
(error) => {
console.log(error);
}
)
} else {
this._ElementService.pi_poAlertaError('Lo sentimos, los archivos son necesario', 'LTE-000');
}
}
cargarRespuestaEnvio() {
this._EstudianteService.cargarSeccionRecurso(this.token, this.objArchivo.id_sesion_recurso).subscribe(
respuesta => {
if (respuesta.status == 'success') {
if (respuesta.data != 0) {
if (respuesta.data[0].id_resultado_recurso != null) {
this.objArchivoEnviado = respuesta.data[0];
this._ElementService.pi_poAlertaSuccess(respuesta.msg, respuesta.code);
$("#seccionEnviarRespuesta").hide();
} else {
$("#seccionEnviarRespuesta").show();
}
} else {
$("#seccionEnviarRespuesta").show();
}
}
}, error2 => {
}
)
}
//#############################################################Cargar Examen####################################################################
cargarSesionesExamen() {
$("#loaderTablasSesionExamen").show();
this._SesionService.listar(this.objExamen).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.listSesiones = respuesta.data;
console.log(this.objExamenCompleto);
$("#loaderTablasSesionExamen").hide();
} else {
$("#loaderTablasSesionExamen").hide();
}
}, error2 => {
$("#loaderTablasSesionExamen").hide();
}
)
}
empezarExamen() {
if (this.objExamenCompleto.configuracion.contrasena_bool !='' || this.objExamenCompleto.configuracion.contrasena_bool =='1' ) {
if (this.passwordExamen.trim() != '') {
this._ExamenTallerService.comprobarContrasenaTaller(this.token, this.passwordExamen, this.objExamenCompleto.configuracion.contrasena).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this._ElementService.pi_poAlertaSuccess(respuesta.msg, respuesta.code);
this.armarExamen();
$("#idModal").attr("style", "display: none; opacity: 0;");
$("#idModal").addClass("basic modal fade");
$("#seccionRecursoClase").hide();
$("#seccionExamen").toggle(500);
} else {
this._ElementService.pi_poAlertaError(respuesta.msg, respuesta.code);
}
}, error2 => {
}
)
} else {
this._ElementService.pi_poAlertaError('Lo sentimos, la contraseña es requerida', 'LTE-000');
}
} else {
this.armarExamen();
$("#idModal").attr("style", "display: none; opacity: 0;");
$("#idModal").addClass("basic modal fade");
$("#seccionRecursoClase").hide();
$("#seccionExamen").toggle(500);
}
}
cargarExamen(sesion) {
$("#loaderTablasSesionExamen").show();
this._ExamenTallerService.cargarExamenTallerCompleto(this.token, sesion).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.objExamenCompleto = respuesta.data;
$("#loaderTablasSesionExamen").hide();
} else {
$("#loaderTablasSesionExamen").hide();
}
}, error2 => {
$("#loaderTablasSesionExamen").hide();
}
)
}
cancelarSeleccionSesion() {
$("#idModal").attr("style", "display: none; opacity: 0;");
$("#idModal").addClass("basic modal fade");
}
///############################## Pintar examen ###################################################
armarExamen() {
this.armarCabezera();
this.alistarRespuestas();
this.pintarContextoPregunta();
$("#previsualizarTallerExamen").show();
$("#contenedorExamen").show();
$("#contenedorArchivo").hide()
}
armarCabezera() {
let cabezeraMetodo = new Array();
if (this.objExamenCompleto['configuracion'].mesclar_preguntas == '1') {
let arregloNumeros = new Array();
for (let i = 0; i <= 1000; i++) {
arregloNumeros.push({'bandera': '0', 'numero': i});
}
var bandera = 0;
var ramdon = Math.floor((Math.random() * this.objExamenCompleto['cantidad_preguntas']) + 0);
var contador = 0;
var validacionEntrada = 0;
while (contador < this.objExamenCompleto['cantidad_preguntas']) {
validacionEntrada = 0;
ramdon = Math.floor((Math.random() * this.objExamenCompleto['cantidad_preguntas']) + 0);
for (let j = 0; j < arregloNumeros.length; j++) {
if (arregloNumeros[j].index == ramdon) {
validacionEntrada = 1;
}
}
bandera = 0;
if (validacionEntrada == 0) {
while (bandera == 0) {
if (arregloNumeros[ramdon]['bandera'] == '0') {
var res=this.objExamenCompleto['preguntas'][ramdon].respondio;
cabezeraMetodo.push({'index': ramdon, 'respondio': res});
arregloNumeros[ramdon]['bandera'] = 1;
bandera = 1;
} else {
ramdon = Math.floor((Math.random() * this.objExamenCompleto['cantidad_preguntas']) + 0);
}
}
contador++;
}
}
} else {
for (var i = 0; i < this.objExamenCompleto['cantidad_preguntas']; i++) {
cabezeraMetodo.push({'index': i, 'respondio': '0'});
}
}
this.listCabezera = cabezeraMetodo;
}
seleccionCabezera(cabezera) {
console.log(cabezera);
this.objCabezera = cabezera;
this.indexCabezera = cabezera.index;
this.alistarRespuestas();
this.pintarContextoPregunta();
}
pintarContextoPregunta() {
$("#contexto").html(this.objExamenCompleto['preguntas'][this.indexCabezera]['contexto']);
$("#pregunta").html(this.objExamenCompleto['preguntas'][this.indexCabezera]['pregunta']);
}
alistarRespuestas() {
let arregloLetras = new Array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'Ñ', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
let arregloLetrasInicializado = new Array();
let arregloRespuestas = new Array();
var aletorioLetra;
var aleatorioPregunta;
var contador = 0;
for (var i = 0; i < arregloLetras.length; i++) {
arregloLetrasInicializado.push({'bandera': '0', 'letra': arregloLetras[i]});
}
if (this.objExamenCompleto['configuracion'].mesclar_respuestas == true || this.objExamenCompleto['configuracion'].mesclar_respuestas == '1') {
//-------------------------------------------------Mesclar respuestas
while (contador < this.objExamenCompleto['preguntas'][this.indexCabezera]['cantidad_respuestas']) {
aletorioLetra = Math.floor((Math.random() * this.objExamenCompleto['preguntas'][this.indexCabezera]['cantidad_respuestas']) + 0);
aleatorioPregunta = Math.floor((Math.random() * this.objExamenCompleto['preguntas'][this.indexCabezera]['cantidad_respuestas']) + 0);
if (arregloRespuestas.length <= 0 || arregloRespuestas.findIndex(index => index === "letra") < 0) {
let validacionEntrada = 0;
for (var n = 0; n < arregloRespuestas.length; n++) {
if (arregloRespuestas[n].id == aleatorioPregunta) {
validacionEntrada = 1;
}
}
if (validacionEntrada == 0) {
var validacion = 0;
while (validacion == 0) {
if (arregloLetrasInicializado[aletorioLetra].bandera == '0') {
arregloRespuestas.push({
'letra': arregloLetrasInicializado[aletorioLetra].letra,
'indexPregunta': this.indexCabezera,
'data': this.objExamenCompleto['preguntas'][this.indexCabezera]['respuestas'][aleatorioPregunta],
'respuesta': htmlDecode(this.objExamenCompleto['preguntas'][this.indexCabezera]['respuestas'][aleatorioPregunta]['descripcion_respuesta']),
'respuestaSeleccionada': this.objExamenCompleto['preguntas'][this.indexCabezera]['respuestas'][aleatorioPregunta]['respuestaSeleccionada'],
'id': aleatorioPregunta
});
arregloLetrasInicializado[aletorioLetra].bandera = '1';
validacion = 1;
} else {
aletorioLetra = Math.floor((Math.random() * this.objExamenCompleto['preguntas'][this.indexCabezera]['cantidad_respuestas']) + 0);
}
}
contador++;
}
}
}
this.listRespuestaCompleta = arregloRespuestas;
console.log(this.listRespuestaCompleta);
} else {
//-------------------------------------------------No mesclar respuestas
for (var i = 0; i < this.objExamenCompleto['preguntas'][this.indexCabezera]['cantidad_respuestas']; i++) {
arregloRespuestas.push({
'letra': arregloLetrasInicializado[i].letra,
'indexPregunta': this.indexCabezera,
'data': this.objExamenCompleto['preguntas'][this.indexCabezera]['respuestas'][i],
'respuesta': htmlDecode(this.objExamenCompleto['preguntas'][this.indexCabezera]['respuestas'][i]['descripcion_respuesta']),
'respuestaSeleccionada':this.objExamenCompleto['preguntas'][this.indexCabezera]['respuestas'][i]['respuestaSeleccionada'],
'id': i
});
this.listRespuestaCompleta = arregloRespuestas;
}
}
}
seleccionarRespuesta(respuesta) {
this.responder(respuesta.indexPregunta,respuesta.id);
respuesta.respuestaSeleccionada=1;
for (var nn = 0; nn<this.listCabezera.length; nn++){
if (this.objCabezera != null)
{
if (this.listCabezera[nn]['index'] == this.objCabezera.index){
this.listCabezera[nn].respondio = 1;
}
}else
{
if (this.listCabezera[nn]['index'] == 0){
this.listCabezera[nn].respondio = 1;
}
}
}
console.log(respuesta);
console.log(this.objExamenCompleto);
}
responder(indexPregunta,idRespuesta){
for (var i = 0; i<this.listRespuestaCompleta.length;i++){
this.listRespuestaCompleta[i].respuestaSeleccionada=0;
}
if (this.objExamenCompleto.preguntas[indexPregunta].respuestas[idRespuesta].respuestaSeleccionada != 1 || this.objExamenCompleto.preguntas[indexPregunta].respuestas[idRespuesta].respuestaSeleccionada != true){
if (this.objExamenCompleto.preguntas[indexPregunta].respuestas[idRespuesta].correcta_respuesta == 1 || this.objExamenCompleto.preguntas[indexPregunta].respuestas[idRespuesta].correcta_respuesta == true){
this.objExamenCompleto.preguntas[indexPregunta].respondio = 1;
this.objExamenCompleto.cantidadBuenas++;
}else{
this.objExamenCompleto.preguntas[indexPregunta].respondio = 1;
var buenas=this.objExamenCompleto.cantidadBuenas;
if (buenas-1>=0){
this.objExamenCompleto.cantidadBuenas--;
}
}
for (var i = 0 ; i<this.objExamenCompleto.preguntas[indexPregunta].respuestas.length; i++){
this.objExamenCompleto.preguntas[indexPregunta].respuestas[i].respuestaSeleccionada=0;
}
this.objExamenCompleto.preguntas[indexPregunta].respuestas[idRespuesta].respuestaSeleccionada = 1;
}
}
}
<file_sep>/PreSaber-Nuevo/src/app/components/profesor/recursos/recursos.component.ts
import {Component, OnInit} from '@angular/core';
import {ElementsService} from "../../../services/elements.service";
import {Tiporecurso} from "../../../models/tiporecurso";
import {RecursosService} from "../../../services/recursos.service";
import {Sesion} from "../../../models/evaluacion/sesion";
import {Examne_taller} from "../../../models/evaluacion/examne_taller";
import {SesionService} from "../../../services/evaluacion_services/sesion.service";
import {Examen_tallerService} from "../../../services/evaluacion_services/examen_taller.service";
import {htmlDecode} from "js-htmlencode";
import {Recurso} from "../../../models/evaluacion/recurso";
import {GLOBAL} from "../../../services/global";
import swal from "sweetalert2";
@Component({
selector: 'app-recursos',
templateUrl: './recursos.component.html',
styleUrls: ['./recursos.component.scss'],
providers: [ElementsService, RecursosService, SesionService, Examen_tallerService]
})
export class RecursosComponent implements OnInit {
public listTipoRecurso: Array<Tiporecurso>;
public listRecursos: Array<Object>;
public objTipoRecurso: Tiporecurso;
public tipoRecurso: any;
public token: any;
public listSesion: Array<Sesion>;
public objSesion: Sesion;
public objExamen: Examne_taller;
public examenCompleto: Object;
public listCabezera;
public indexCabezera: any;
public listRespuestaCompleta;
public listRecursosArchivo: Array<Object>;
public listContenidoArchivo: Array<Object>;
public objRecurso: Recurso;
public res;
public descripcionArchivoNuevo: any;
//Archivo
public archivos: Array<File>;
public descripcionArchivo: any;
public options: Object;
constructor(private _ElemetService: ElementsService,
private _RecursoService: RecursosService,
private _SesionService: SesionService,
private _ExamenTaller: Examen_tallerService) {
this.objTipoRecurso = new Tiporecurso(0, '', '', '', '');
this.objExamen = new Examne_taller('', '', '', '', '', '', '');
this.objRecurso = new Recurso('', '', '', '', '', '', '', '');
this.objSesion = new Sesion('', '', '');
this.tipoRecurso = '';
this.token = localStorage.getItem('token');
this.indexCabezera = 0;
this.descripcionArchivoNuevo = '';
this.options = {
language: 'es',
charCounterCount: true,
// Set the image upload parameter.
imageUploadParam: 'ImagenEditore',
// Set the image upload URL.
imageUploadURL: GLOBAL.url + 'pi_po/imagenesEditor',
// Additional upload params.
imageUploadParams: {id: 'ImagenEditore'},
// Set request type.
imageUploadMethod: 'POST',
// Set max image size to 5MB.
imageMaxSize: 5 * 1024 * 1024,
// Allow to upload PNG and JPG.
imageAllowedTypes: ['jpeg', 'jpg', 'png'],
fileUploadParam: 'Archivo',
fileUploadURL: GLOBAL.url + 'pi_po/archivosEditor',
fileUploadMethod: 'POST',
fileAllowedTypes: ['application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/pdf', 'application/vnd.openxmlformats-officedocument.presentationml.presentation']
}
}
ngOnInit() {
this._ElemetService.pi_poValidarUsuario("RecursosComponent");
this.cargarTipoRecursos();
$("#loaderTablaRecursos").hide();
$("#loaderTablasSesionExamen").hide();
$("#previsualizarTallerExamen").hide();
$("#contenedorExamen").hide();
$("#tablaTalleresExamenes").hide();
$("#selectEditarEstado").hide();
}
cargarTipoRecursos() {
$("#loaderTipoRecurso").show();
this._RecursoService.cargarTipos().subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.listTipoRecurso = respuesta.data;
$("#loaderTipoRecurso").hide();
} else {
this._ElemetService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
}
}, error2 => {
}
)
}
cargarRecursos() {
$("#loaderTablaRecursos").show();
$("#tablaArchivos").hide();
$("#contenedorArchivo").hide()
let recurso = this.tipoRecurso.split('-');
if (recurso[1] == 'EXAMEN' || recurso[1] == 'examen') {
this.objTipoRecurso.id = recurso[0];
this._RecursoService.cargarExamenTaller(this.token, this.objTipoRecurso).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
$("#loaderTablaRecursos").hide();
this.listRecursos = respuesta.data;
$("#tablaTalleresExamenes").show();
} else {
this._ElemetService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
$("#loaderTablaRecursos").hide();
}
}, error2 => {
}
)
} else if (recurso[1] == 'ARCHIVO' || recurso[1] == 'archivo') {
$("#tablaTalleresExamenes").hide();
$("#contenedorExamen").hide();
$("#tablaArchivos").show();
this.objTipoRecurso.id = recurso[0];
this._RecursoService.listarArchivos(this.token, this.objTipoRecurso).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
$("#loaderTablaRecursos").hide();
this.listRecursosArchivo = respuesta.data;
console.log(this.listRecursosArchivo);
} else {
this.listRecursosArchivo = [];
this._ElemetService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
$("#loaderTablaRecursos").hide();
}
}, error2 => {
}
)
} else if (recurso[1] == 'TALLER' || recurso[1] == 'taller') {
$("#contenedorExamen").hide();
$("#tablaArchivos").hide();
$("#contenedorArchivo").hide();
$("#tablaTalleresExamenes").show();
this.objTipoRecurso.id = recurso[0];
this._RecursoService.cargarExamenTaller(this.token, this.objTipoRecurso).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
$("#loaderTablaRecursos").hide();
this.listRecursos = respuesta.data;
$("#tablaTalleresExamenes").show();
} else {
this.listRecursosArchivo = [];
this._ElemetService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
$("#loaderTablaRecursos").hide();
}
}, error2 => {
}
)
}
}
seleccionarExamen(objExamenP) {
this.objExamen = objExamenP;
$("#loaderTablasSesionExamen").show();
this._SesionService.listar(objExamenP).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.listSesion = respuesta.data;
$("#loaderTablasSesionExamen").hide();
} else {
this._ElemetService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
$("#loaderTablasSesionExamen").hide();
}
}, error2 => {
}
)
}
seleccionarSesion(objSesionP) {
this.objSesion = objSesionP;
this._ExamenTaller.cargarExamenTallerCompleto(this.token, this.objSesion).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.examenCompleto = respuesta.data;
this.armarExamen();
} else {
this._ElemetService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
}
}, error2 => {
}
)
}
armarExamen() {
this.armarCabezera();
this.alistarRespuestas();
this.pintarContextoPregunta();
$("#previsualizarTallerExamen").show();
$("#contenedorExamen").show();
$("#contenedorArchivo").hide()
}
armarCabezera() {
let cabezeraMetodo = new Array();
if (this.examenCompleto['configuracion'].mesclar_preguntas == '1') {
let arregloNumeros = new Array();
for (let i = 0; i <= 1000; i++) {
arregloNumeros.push({'bandera': '0', 'numero': i});
}
var bandera = 0;
var ramdon = Math.floor((Math.random() * this.examenCompleto['cantidad_preguntas']) + 0);
var contador = 0;
var validacionEntrada = 0;
while (contador < this.examenCompleto['cantidad_preguntas']) {
validacionEntrada = 0;
ramdon = Math.floor((Math.random() * this.examenCompleto['cantidad_preguntas']) + 0);
for (let j = 0; j < arregloNumeros.length; j++) {
if (arregloNumeros[j].index == ramdon) {
validacionEntrada = 1;
}
}
bandera = 0;
if (validacionEntrada == 0) {
while (bandera == 0) {
if (arregloNumeros[ramdon]['bandera'] == '0') {
cabezeraMetodo.push({'index': ramdon, 'respondio': '0'});
arregloNumeros[ramdon]['bandera'] = 1;
bandera = 1;
} else {
ramdon = Math.floor((Math.random() * this.examenCompleto['cantidad_preguntas']) + 0);
}
}
contador++;
}
}
} else {
for (var i = 0; i < this.examenCompleto['cantidad_preguntas']; i++) {
cabezeraMetodo.push({'index': i, 'respondio': '0'});
}
}
this.listCabezera = cabezeraMetodo;
}
seleccionCabezera(cabezera) {
this.indexCabezera = cabezera.index;
this.alistarRespuestas();
this.pintarContextoPregunta();
}
pintarContextoPregunta() {
$("#contexto").html(this.examenCompleto['preguntas'][this.indexCabezera]['contexto']);
$("#pregunta").html(this.examenCompleto['preguntas'][this.indexCabezera]['pregunta']);
}
alistarRespuestas() {
let arregloLetras = new Array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'Ñ', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
let arregloLetrasInicializado = new Array();
let arregloRespuestas = new Array();
var aletorioLetra;
var aleatorioPregunta;
var contador = 0;
for (var i = 0; i < arregloLetras.length; i++) {
arregloLetrasInicializado.push({'bandera': '0', 'letra': arregloLetras[i]});
}
if (this.examenCompleto['configuracion'].mesclar_respuestas == true || this.examenCompleto['configuracion'].mesclar_respuestas == '1') {
//-------------------------------------------------Mesclar respuestas
while (contador < this.examenCompleto['preguntas'][this.indexCabezera]['cantidad_respuestas']) {
aletorioLetra = Math.floor((Math.random() * this.examenCompleto['preguntas'][this.indexCabezera]['cantidad_respuestas']) + 0);
aleatorioPregunta = Math.floor((Math.random() * this.examenCompleto['preguntas'][this.indexCabezera]['cantidad_respuestas']) + 0);
if (arregloRespuestas.length <= 0 || arregloRespuestas.findIndex(index => index === "letra") < 0) {
let validacionEntrada = 0;
for (var n = 0; n < arregloRespuestas.length; n++) {
if (arregloRespuestas[n].id == aleatorioPregunta) {
validacionEntrada = 1;
}
}
if (validacionEntrada == 0) {
var validacion = 0;
while (validacion == 0) {
if (arregloLetrasInicializado[aletorioLetra].bandera == '0') {
arregloRespuestas.push({
'letra': arregloLetrasInicializado[aletorioLetra].letra,
'indexPregunta': this.indexCabezera,
'data': this.examenCompleto['preguntas'][this.indexCabezera]['respuestas'][aleatorioPregunta],
'respuesta': htmlDecode(this.examenCompleto['preguntas'][this.indexCabezera]['respuestas'][aleatorioPregunta]['descripcion_respuesta']),
'id': aleatorioPregunta
});
arregloLetrasInicializado[aletorioLetra].bandera = '1';
validacion = 1;
} else {
aletorioLetra = Math.floor((Math.random() * this.examenCompleto['preguntas'][this.indexCabezera]['cantidad_respuestas']) + 0);
}
}
contador++;
}
}
}
this.listRespuestaCompleta = arregloRespuestas;
console.log(this.listRespuestaCompleta);
} else {
//-------------------------------------------------No mesclar respuestas
for (var i = 0; i < this.examenCompleto['preguntas'][this.indexCabezera]['cantidad_respuestas']; i++) {
arregloRespuestas.push({
'letra': arregloLetrasInicializado[i].letra,
'indexPregunta': this.indexCabezera,
'data': this.examenCompleto['preguntas'][this.indexCabezera]['respuestas'][i],
'respuesta': htmlDecode(this.examenCompleto['preguntas'][this.indexCabezera]['respuestas'][i]['descripcion_respuesta']),
'id': i
});
this.listRespuestaCompleta = arregloRespuestas;
}
}
}
seleccionArchivo(recurso) {
$("#previsualizarTallerExamen").show();
$("#contenedorExamen").hide();
$("#contenedorArchivo").show();
$("#selectEditarEstado").hide();
this.objRecurso.id = recurso.id;
this.objRecurso.estado = recurso.estado;
this.listarArchivos();
}
listarArchivos() {
this._RecursoService.contenidoArchivos(this.token, this.objTipoRecurso, this.objRecurso.id).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.listContenidoArchivo = respuesta.data;
$("#selectEditarEstado").attr('style', 'none');
}
}, error2 => {
}
)
}
descargarArchivo(archivo) {
window.open(GLOBAL.urlFiles + archivo.rute, 'download');
}
eliminarArchivo(archivo, recurso) {
swal({
title: 'LTE-000',
text: 'Esta seguro que desea eliminar el archivo: ' + archivo.name,
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Si, Eliminar'
}).then((result) => {
if (result.value) {
console.log(archivo.id);
this._RecursoService.eliminarArchivos(this.token, this.objRecurso, archivo.id).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
console.log('entro');
this.listarArchivos();
} else {
this._ElemetService.pi_poVentanaAlertaWarning(respuesta.msg, respuesta.code);
}
}, error2 => {
}
)
}
});
}
cargarArchivos($event) {
this.archivos = <Array<File>>$event.target.files;
//this.archivosp.push(this.archivos[0]);
for (var i = 0; i < this.archivos.length; i++) {
let tipo = this.archivos[i].name.split('.');
let extension = tipo.pop().toLowerCase();
if (extension == 'png' || extension == 'jpg' || extension == 'gif') {
this.archivos[i]['tipo'] = 'imagen';
this.archivos[i]['extension'] = extension;
this.archivos[i]['estado'] = 'true';
this.archivos[i]['id'] = i;
} else if (extension == 'xls' || extension == 'xlsx') {
this.archivos[i]['tipo'] = 'excel';
this.archivos[i]['extension'] = extension;
this.archivos[i]['estado'] = 'true';
this.archivos[i]['id'] = i;
} else if (extension == 'docx' || extension == 'docm') {
this.archivos[i]['tipo'] = 'word';
this.archivos[i]['extension'] = extension;
this.archivos[i]['estado'] = 'true';
this.archivos[i]['id'] = i;
} else if (extension == 'pptx' || extension == 'ppt') {
this.archivos[i]['tipo'] = 'powerpoint';
this.archivos[i]['extension'] = extension;
this.archivos[i]['estado'] = 'true';
this.archivos[i]['id'] = i;
} else if (extension == 'pdf') {
this.archivos[i]['tipo'] = 'pdf';
this.archivos[i]['extension'] = extension;
this.archivos[i]['estado'] = 'true';
this.archivos[i]['id'] = i;
} else if (extension == 'txt') {
this.archivos[i]['tipo'] = 'texto';
this.archivos[i]['extension'] = extension;
this.archivos[i]['estado'] = 'true';
this.archivos[i]['id'] = i;
} else if (extension == 'rar') {
this.archivos[i]['tipo'] = 'rar';
this.archivos[i]['extension'] = extension;
this.archivos[i]['estado'] = 'false';
this.archivos[i]['id'] = i;
} else if (extension == 'exe') {
this.archivos[i]['tipo'] = 'exe';
this.archivos[i]['extension'] = extension;
this.archivos[i]['estado'] = 'false';
this.archivos[i]['id'] = i;
} else {
this.archivos[i]['tipo'] = 'desconocido';
this.archivos[i]['extension'] = extension;
this.archivos[i]['estado'] = 'false';
this.archivos[i]['id'] = i;
}
}
}
nuevosArchivos() {
this._RecursoService.nuevoArchivo(this.token, ['archivo'], this.archivos, this.objRecurso).then(
(resultado) => {
this._ElemetService.pi_poValidarCodigo(resultado);
this.res = resultado;
if (this.res.status == 'success') {
this.listarArchivos();
this.archivos = new Array<File>();
this.descripcionArchivo = '';
this._ElemetService.pi_poAlertaSuccess(this.res.msg, this.res.code);
} else {
this._ElemetService.pi_poVentanaAlertaWarning(this.res.code, this.res.msg);
}
},
(error) => {
console.log(error);
}
)
}
seleccionarDescripcionArchivo(archivoP) {
this.descripcionArchivoNuevo = archivoP.descripcion;
}
editarArchivo() {
if (this.descripcionArchivoNuevo != '') {
this.objRecurso.descripcion = htmlDecode(this.descripcionArchivoNuevo);
this._RecursoService.editarDescripcionArchivo(this.token, this.objRecurso).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.descripcionArchivoNuevo = '';
this.listarArchivos();
this._ElemetService.pi_poAlertaSuccess(respuesta.msg, respuesta.code);
} else {
this._ElemetService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
}
}, error2 => {
}
)
console.log(this.objRecurso.descripcion);
} else {
this._ElemetService.pi_poAlertaError('Lo sentimos, la descripcion es requerida', 'Campo vacio');
}
}
editarEstadoArchivo(archivos) {
$("#estadoArchivo").hide();
$("#selectEditarEstado").show();
}
cambiarEstadoArchivo() {
if (this.objRecurso.estado != '000') {
this._RecursoService.editarEstadoArchivo(this.token, this.objRecurso).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this._ElemetService.pi_poAlertaSuccess(respuesta.msg, respuesta.code);
//this.listRecursosArchivo.estado=this.objRecurso.estado;
this.listarArchivos();
} else {
this._ElemetService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
}
}, error2 => {
}
)
} else {
this._ElemetService.pi_poAlertaError('Lo sentimos, Sleccione una opcion para el estado', 'LTE-000');
}
}
}
<file_sep>/PreSaber-Nuevo/src/app/models/evaluacion/recurso.ts
export class Recurso{
constructor(
public id: any,
public usuario_profesor_id_fk: any,
public tipo_recurso_id_fk: any,
public descripcion: any,
public contenido: any,
public fecha_creacion: any,
public fecha_actualizacion: any,
public estado: any
)
{}
}
<file_sep>/PreSaber-Web/src/app/app.rounting.ts
import {ModuleWithProviders} from "@angular/core";
import {Routes, RouterModule} from "@angular/router";
//componentes
import {LoginComponent} from "./components/login/login.component";
import {HomeComponent} from "./components/home/home.component";
import {RegistroComponent} from "./components/registro/registro.component";
import {VerificarCodigoComponent} from "./components/verificar-codigo/verificar-codigo.component";
//Import Estudiante
import {HomeEstudianteComponent} from "./components/home-estudiante/home-estudiante.component";
//import Porfesor
import {HomeProfesorComponent} from "./components/home-profesor/home-profesor.component";
//Import Administrador
import {HomeAdminComponent} from "./components/home-admin/home-admin.component";
import {CrearContratoComponent} from "./components/administrador/crear-contrato/crear-contrato.component";
import {CrearCursoComponent} from "./components/administrador/crear-curso/crear-curso.component";
import {CrearSeccionComponent} from "./components/administrador/crear-seccion/crear-seccion.component";
import {CrearTypoUsuarioComponent} from "./components/administrador/crear-typo-usuario/crear-typo-usuario.component";
import {CrearUsuarioComponent} from "./components/administrador/crear-usuario/crear-usuario.component";
import {PerfilUsuarioComponent} from "./components/administrador/perfil-usuario/perfil-usuario.component";
const appRoutes: Routes = [
{path: '', component: HomeComponent},
{path: 'login', component: LoginComponent},
{path: 'home', component: HomeComponent},
{path: 'registro', component: RegistroComponent},
{path: 'verificarCodigo', component: VerificarCodigoComponent},
{path: 'ADMINISTRADOR', component: HomeAdminComponent},
{path: 'ESTUDIANTE', component: HomeEstudianteComponent},
{path: 'crearContrato', component: CrearContratoComponent},
{path: 'crearCurso', component: CrearCursoComponent},
{path: 'crearSeccion', component: CrearSeccionComponent},
{path: 'crearTypoUsuario', component: CrearTypoUsuarioComponent},
{path: 'crearUsuario', component: CrearUsuarioComponent},
{path: 'pefilUserAdmin', component: PerfilUsuarioComponent},
{path: 'PROFESOR', component: HomeProfesorComponent},
{path: '**', component: HomeComponent}
];
export const appRoutingProviders: any[] = [];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
<file_sep>/PreSaber-Nuevo/src/app/services/evaluacion_services/competencia.service.ts
import {Injectable} from "@angular/core";
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {GLOBAL} from "../global";
import {Observable} from "rxjs/Observable";
@Injectable()
export class CompetenciaService {
public url: string;
constructor(private _Http: HttpClient) {
this.url = GLOBAL.url;
}
listarCompetencia(token): Observable<any> {
let params = 'token=' + token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Http.post(this.url + 'profesor/listarCompetencias', params, {headers: headers});
}
crear(token,competencia): Observable<any> {
let json = JSON.stringify(competencia)
let params = 'token=' + token+'&json='+json;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Http.post(this.url + 'profesor/crearCompetencia', params, {headers: headers});
}
actualizar(token,competencia): Observable<any> {
let json = JSON.stringify(competencia)
let params = 'token=' + token+'&json='+json;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Http.post(this.url + 'profesor/actualizarCompetencia', params, {headers: headers});
}
}
<file_sep>/php-backend/App/componentes/administrador/curso.php
<?php
$app->post('/administrador/crearCurso', function () use ($app) {
$helper = new helper();
$conexion = new conexPG();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token');
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$params = json_decode($json);
$usuarioIdentificado = $helper->authCheck($token, true);
$usuario_administrador_id_fk = $usuarioIdentificado->sub;
$descripcion = (isset($params->descripcion)) ? $params->descripcion : null;
$estado = (isset($params->estado)) ? $params->estado : null;
$imagen = (isset($_FILES['imagen'])) ? $_FILES['imagen'] : null;
$fecha_creacion = $fecha_creacion = date('Y-m-d H:i:s');
$fecha_actualizacion = date('Y-m-d H:i:s');
$sql = "select * from seguridad.usuario where id ='$usuarioIdentificado->sub'";
$r = $conexion->consultaComplejaNor($sql);
if (pg_num_rows($r) > 0) {
if ($imagen != null) {
$nombreArchivo = time();
$ruta = '/imagenes/curso/' . $nombreArchivo . '.' . pi_poExtenssion($imagen);
pi_poMove('/imagenes/curso', $imagen, $nombreArchivo);
} else {
$ruta = '/imagenes_estandar/curso-45x45.png';
}
$sql = "INSERT INTO presaber.curso(
usuario_administrador_id_fk, descripcion, estado, imagen, fecha_creacion, fecha_actualizacion)
VALUES (" . $usuario_administrador_id_fk . ", '" . $descripcion . "', '" . $estado . "', '" . $ruta . "', '" . $fecha_creacion . "', '" . $fecha_actualizacion . "');";
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-001'
];
} else {
$data = [
'code' => 'LTE-013',
'line' => '43-curso'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/administrador/actualizarCurso', function () use ($app) {
$helper = new helper();
$conexion = new conexPG();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token');
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$usuarioToken= $helper->authCheck($token,true);
$sql ="select * from seguridad.usuario where id='$usuarioToken->sub'";
$r = $conexion->consultaComplejaNor($sql);
if (pg_num_rows($r)>0)
{
$params = json_decode($json);
$id = (isset($params->id)) ? $params->id : null;
$descripcion = (isset($params->descripcion)) ? $params->descripcion : null;
$estado = (isset($params->estado)) ? $params->estado : null;
$imagen = (isset($_FILES['imagen'])) ? $_FILES['imagen'] : null;
$fecha_actualizacion = date('Y-m-d H:i:s');
if ($imagen != null) {
$nombreArchivo = time();
$ruta = '/imagenes/curso/' . $nombreArchivo . '.' . pi_poExtenssion($imagen);
pi_poMove('/imagenes/curso', $imagen, $nombreArchivo);
}
if ($imagen != null) {
$sql = "UPDATE presaber.curso
SET descripcion='$descripcion', estado='$estado', imagen='$ruta', fecha_actualizacion='$fecha_actualizacion'
WHERE id='$id';";
} else {
$sql = "UPDATE presaber.curso
SET descripcion='$descripcion', estado='$estado',fecha_actualizacion='$fecha_actualizacion'
WHERE id='$id';";
}
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-001'
];
}else
{
$data=[
'code'=>'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/administrador/eliminarCurso', function () use ($app) {
$helper = new helper();
$conexion = new conexPG();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token');
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$params = json_decode($json);
$id = (isset($params->id)) ? $params->id : null;
$sql = "DELETE FROM presaber.curso WHERE id = " . $id . ";";
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-001'
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/administrador/listarCurso', function () use ($app) {
$helper = new helper();
$conexion = new conexPG();
$token = $app->request->post('token');
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$sql = "SELECT id, usuario_administrador_id_fk, descripcion, estado, imagen, fecha_creacion, fecha_actualizacion
FROM presaber.curso order by id desc limit 200;";
$r = $conexion->consultaComplejaAso($sql);
$data = [
'code' => 'LTE-001',
'data' => $r
];
} else {
$data = [
'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-010'
];
}
echo $helper->checkCode($data);
});
$app->post('/administrador/filtroCurso', function () use ($app) {
$json = $app->request->post('json', null);
$toke = $app->request->post('token', null);
$helper = new helper();
if ($json != null) {
if ($toke != null) {
$validarToke = $helper->authCheck($toke);
if ($validarToke == true) {
$parametros = json_decode($json);
$filtro = (isset($parametros->filstro)) ? $parametros->filtro : $parametros->filtro;
$sql = "select * from presaber.curso
where descripcion like '%$filtro%' order by fecha_creacion DESC limit 200";
$conexion = new conexPG();
$r = $conexion->consultaComplejaAso($sql);
if ($r!= 0) {
$data = [
'code' => 'LTE-001',
'data' => $r
];
} else {
$data = [
'code' => 'LTE-003'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-010'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/administrador/informacionCurso',function () use ($app){
$json = $app->request->post('json',null);
$helper = new helper();
if ($json != null)
{
$parametros = json_decode($json);
$conexion = new conexPG();
$id = (isset($parametros->id))? $parametros->id : null;
$sql ="select cu.*,usu.nombre,r.descripcion as descripcion_usuario,usu.apellido,usu.correo, count(fic.id) as cantidad
from presaber.curso cu
join seguridad.usuario usu on cu.usuario_administrador_id_fk=usu.id
join seguridad.rol r on usu.rol_id_fk=r.id
left join presaber.ficha fic on cu.id = fic.curso_id_fk
where cu.id = '$id'
GROUP BY cu.id, usu.id, r.id";
$r = $conexion->consultaComplejaAso($sql);
$data =[
'code'=>'LTE-001',
'data'=>$r
];
}else
{
$data =[
'code'=>'LTE-009'
];
}
echo $helper->checkCode($data);
});<file_sep>/PreSaber-Nuevo/src/app/models/evaluacion/base_examen.ts
export class Base_examen{
constructor (
public id_base_examen: any,
public descripcion_base_examen: any,
public fecha_creacion_base_examen: any,
public fecha_actualizacion_base_examen: any
){}
}
<file_sep>/PreSaber-Nuevo/src/app/models/ficha.ts
export class Ficha {
constructor(public id: string,
public usuario_administrador_id_fk: string,
public curso_id_fk: string,
public contrato_entidad_id_fk: string,
public descripcion: string,
public estado: string,
public usuarios_minimos: number,
public usuarios_maximos: number,
public fecha_finalizacion: any,
public fecha_creacion: any,
public fecha_actualizacion: any) {
}
}
<file_sep>/PreSaber-Nuevo/src/app/components/estudiante/fichas-curso/fichas-curso.component.ts
import { Component, OnInit } from '@angular/core';
import {Modulo} from "../../../models/modulo";
import {GLOBAL} from "../../../services/global";
import {EstudianteService} from "../../../services/estudiante/estudiante.service";
import {ElementsService} from "../../../services/elements.service";
@Component({
selector: 'app-fichas-curso',
templateUrl: './fichas-curso.component.html',
styleUrls: ['./fichas-curso.component.scss'],
providers: [ElementsService,EstudianteService]
})
export class FichasCursoComponent implements OnInit {
public token: any;
public ficha: any;
public id_curso: any;
public listModulo: Array<Modulo>;
public urlFile: any;
constructor(private _ElementService: ElementsService,
private _estudianteService: EstudianteService) {
this.token = localStorage.getItem('token');
this.ficha = localStorage.getItem('ficha');
this.id_curso = localStorage.getItem('id_curso');
this.urlFile = GLOBAL.urlFiles;
this.cargarModulos();
}
ngOnInit() {
this._ElementService.pi_poValidarUsuario('MisCursosEstudianteComponent');
}
cargarModulos() {
this._estudianteService.listarModulosFicha(this.token, this.ficha,this.id_curso).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.listModulo = respuesta.data;
} else {
}
}, error2 => {
}
)
}
seleccionarAsignatura(asignatura){
localStorage.setItem('asignatura',asignatura.id);
localStorage.setItem('asignaturatxt',asignatura.descripcion);
}
}
<file_sep>/PreSaber-Nuevo/src/app/components/profesor/fichas/fichas.component.ts
import {Component, OnInit} from '@angular/core';
import {ElementsService} from '../../../services/elements.service';
import {FichaService} from '../../../services/ficha.service';
import {Ficha} from '../../../models/ficha';
import {Router} from "@angular/router";
@Component({
selector: 'app-fichas',
templateUrl: './fichas.component.html',
styleUrls: ['./fichas.component.scss'],
providers: [ElementsService, FichaService]
})
export class FichasComponent implements OnInit {
public token: any;
public objFicha: Ficha;
public listFicha: Array<Ficha>;
position = 'top-right';
constructor(private _ElementService: ElementsService, private _FichaService: FichaService, private _Route: Router) {
this.token = localStorage.getItem('token');
this.objFicha = new Ficha('','','','',
'','',0,0,'','','');
}
ngOnInit() {
this._ElementService.pi_poValidarUsuario('FichasComponent');
this.listarFichasProfesor();
$('#loaderMisFichas').hide();
}
listarFichasProfesor() {
$('#loaderMisFichas').show();
this._FichaService.fichasProfesor(this.token).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.listFicha = respuesta.data;
this._ElementService.pi_poAlertaMensaje('Se cargaron un total de: ' + this.listFicha.length + ' fichas', 'FICHAS');
$('#loaderMisFichas').hide();
} else {
this._ElementService.pi_poAlertaWarning(respuesta.msg, respuesta.code);
$('#loaderMisFichas').hide();
}
}, error2 => {
}
);
}
cargarFicha(Ficha) {
this.objFicha = Ficha;
if (this.objFicha.estado=='ACTIVO')
{
this._Route.navigate(['profesor/misCursos']);
localStorage.setItem('ficha',this.objFicha.id+'|-|'+this.objFicha.descripcion);
this._ElementService.pi_poAlertaSuccess('Se selecciono la ficha: '+this.objFicha.descripcion+' con codigo: LTE-'+this.objFicha.id,'Mis Fichas');
}else
{
localStorage.removeItem('ficha');
this._ElementService.pi_poVentanaAlertaWarning('Error','Lo sentimos, No podemos cargar la ficha su estado es INACTIVO.');
}
}
}
<file_sep>/PreSaber-Nuevo/src/app/models/evaluacion/respuesta.ts
export class Respuesta{
constructor(
public id_respuesta:any,
public pregunta_id_fk: any,
public tipo_repuesta: any,
public descripcion_respuesta: any,
public correcta_respuesta: any
){}
}
<file_sep>/PreSaber-Nuevo/src/app/models/tiporecurso.ts
export class Tiporecurso {
constructor(public id: number,
public descripcion: string,
public estado: string,
public fecha_creacion: any,
public fecha_actualizacion: any) {}
}
<file_sep>/README.md
# Saber
Plataforma educativa.
<file_sep>/PreSaber-Nuevo/src/app/services/evaluacion_services/examen_taller.service.ts
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {Injectable} from "@angular/core";
import {Observable} from "rxjs/Observable";
import {GLOBAL} from "../global";
@Injectable()
export class Examen_tallerService{
public url:string;
constructor(private _Http: HttpClient)
{
this.url = GLOBAL.url;
}
listar(token): Observable<any>
{
let params = 'token='+token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Http.post(this.url + 'profesor/listarExamenTaller', params, {headers: headers});
}
cargarExamenTaller(token,objExamneTaller): Observable<any>
{
let json = JSON.stringify(objExamneTaller);
let params = 'json='+json+'&token='+token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Http.post(this.url + 'profesor/cargarExamenTaller', params, {headers: headers});
}
cargarExamenTallerCompleto(token,objSesion): Observable<any>
{
let json = JSON.stringify(objSesion);
let params = 'json='+json+'&token='+token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Http.post(this.url + 'cargarExamenCompleto', params, {headers: headers});
}
actualizar(token,objExamneTaller): Observable<any>
{
let json = JSON.stringify(objExamneTaller);
let params = 'json='+json+'&token='+token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Http.post(this.url + 'profesor/actualizarTallerExamen', params, {headers: headers});
}
crearPregunta(token,objPregunta): Observable<any>
{
let json = JSON.stringify(objPregunta);
let params = 'json='+json+'&token='+token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Http.post(this.url + 'profesor/crearPregunta', params, {headers: headers});
}
actualizarPregunta(token,objPregunta): Observable<any>
{
let json = JSON.stringify(objPregunta);
let params = 'json='+json+'&token='+token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Http.post(this.url + 'profesor/actualizarPregunta', params, {headers: headers});
}
}
<file_sep>/PreSaber-Nuevo/src/app/app.rounting.ts
import {ModuleWithProviders} from "@angular/core";
import {Routes, RouterModule} from "@angular/router";
//componentes
import {LoginComponent} from "./components/login/login.component";
import {HomeComponent} from "./components/home/home.component";
import {RegistroComponent} from "./components/registro/registro.component";
import {VerificarCodigoComponent} from "./components/verificar-codigo/verificar-codigo.component";
//Import Estudiante
import {HomeEstudianteComponent} from "./components/home-estudiante/home-estudiante.component";
//import Porfesor
import {HomeProfesorComponent} from "./components/home-profesor/home-profesor.component";
import {FichasComponent} from './components/profesor/fichas/fichas.component';
import {CrearRecursoComponent} from "./components/profesor/crear-recurso/crear-recurso.component";
import {RecursosComponent} from "./components/profesor/recursos/recursos.component";
import {MisEstudiantesComponent} from "./components/profesor/mis-estudiantes/mis-estudiantes.component";
import {MisCursosComponent} from "./components/profesor/mis-cursos/mis-cursos.component";
//Import Administrador
import {HomeAdminComponent} from "./components/home-admin/home-admin.component";
import {CrearContratoComponent} from "./components/administrador/crear-contrato/crear-contrato.component";
import {CrearCursoComponent} from "./components/administrador/crear-curso/crear-curso.component";
import {CrearSeccionComponent} from "./components/administrador/crear-seccion/crear-seccion.component";
import {CrearTypoUsuarioComponent} from "./components/administrador/crear-typo-usuario/crear-typo-usuario.component";
import {CrearUsuarioComponent} from "./components/administrador/crear-usuario/crear-usuario.component";
import {PerfilUsuarioComponent} from "./components/administrador/perfil-usuario/perfil-usuario.component";
import {MisCursosEstudianteComponent} from "./components/estudiante/mis-cursos-estudiante/mis-cursos-estudiante.component";
import {FichasCursoComponent} from "./components/estudiante/fichas-curso/fichas-curso.component";
import {ClasesAsignaturaComponent} from "./components/estudiante/clases-asignatura/clases-asignatura.component";
const appRoutes: Routes = [
{path: '', component: HomeComponent},
{path: 'login', component: LoginComponent},
{path: 'home', component: HomeComponent},
{path: 'registro', component: RegistroComponent},
{path: 'verificarCodigo', component: VerificarCodigoComponent},
{path: 'ADMINISTRADOR', component: HomeAdminComponent},
{path: 'ESTUDIANTE', component: HomeEstudianteComponent},
{path: 'crearContrato', component: CrearContratoComponent},
{path: 'crearCurso', component: CrearCursoComponent},
{path: 'crearSeccion', component: CrearSeccionComponent},
{path: 'crearTypoUsuario', component: CrearTypoUsuarioComponent},
{path: 'crearUsuario', component: CrearUsuarioComponent},
{path: 'pefilUserAdmin', component: PerfilUsuarioComponent},
{path: 'PROFESOR', component: HomeProfesorComponent},
{path: 'MisFichas', component: FichasComponent},
{path: 'profesor/crearRecurso', component: CrearRecursoComponent},
{path: 'profesor/misRecursos', component: RecursosComponent},
{path: 'profesor/misCursos',component: MisCursosComponent},
{path: 'profesor/Mis_Estudiantes', component:MisEstudiantesComponent},
{path: 'estudiante/misCursos', component:MisCursosEstudianteComponent},
{path: 'estudiante/asignaturasCurso', component:FichasCursoComponent},
{path: 'estudiante/clasesAsignatura', component:ClasesAsignaturaComponent},
{path: '**', component: HomeComponent}
];
export const appRoutingProviders: any[] = [];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
<file_sep>/php-backend/App/componentes/profesor/recurso.php
<?php
$app->post('/profesor/cargarTipoRecurso', function () use ($app) {
$helper = new helper();
$conexion = new conexPG();
$sql = "select * from presaber.tipo_recurso";
$r = $conexion->consultaComplejaAso($sql);
if ($r != 0) {
$data = [
'code' => 'LTE-001',
'data' => $r
];
} else {
$data = [
'code' => 'LTE-003'
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/crearTalleExamen', function () use ($app) {
$helper = new helper();
$token = $app->request()->post('token', null);
if ($token != null) {
$validacionToke = $helper->authCheck($token);
if ($validacionToke == true) {
$json = $app->request()->post('json', null);
if ($json != null) {
$conexion = new conexPG();
$fecha_creacion = date('Y-m-d H:i:s');
$fecha_actualizacion = date('Y-m-d H:i:s');
$usuarioToken = $helper->authCheck($token, true);
$parametros = json_decode($json);
$usuario_profesor_id_fk = $usuarioToken->sub;
/*
//-------------------------------------------------------------------------------Recurso
$tipo_recurso_id_fk = (isset($parametros->id_base_examen)) ? $parametros->id_base_examen : null;
$descripcionRecurso = (isset($parametros->descripcion_examen)) ? $parametros->descripcion_examen : null;
$estadoRecurso = 'ACTIVO';
$sql = "INSERT INTO presaber.recurso(
usuario_profesor_id_fk,
tipo_recurso_id_fk,
descripcion,
fecha_creacion,
fecha_actualizacion,
estado)
VALUES ('$usuario_profesor_id_fk',
'$tipo_recurso_id_fk',
'$descripcionRecurso',
'$fecha_creacion',
'$fecha_actualizacion',
'$estadoRecurso') returning id;";
$r = $conexion->consultaComplejaNorAso($sql);
$idRecurso = $r['id'];
*/
//---------------------------------------------------------------------------------Crear Taller Examen
$base_examen_id_fk = (isset($parametros->id_base_examen)) ? $parametros->id_base_examen : null;
$descripcion_examen = (isset($parametros->descripcion_examen)) ? $parametros->descripcion_examen : null;
$estado_examen = (isset($parametros->estado_examen)) ? $parametros->estado_examen : null;
$tipo_recurso_id_fk = (isset($parametros->tipo_recurso_id_fk)) ? $parametros->tipo_recurso_id_fk : null;
$sql = "INSERT INTO evaluacion.examen_taller(
base_examen_id_fk,
descripcion_examen,
fecha_creacion_examen,
fecha_actualizacion_examen,
estado_examen,
tipo_recurso_id_fk,
id_profesor_fk_examne_taller)
VALUES ('$base_examen_id_fk',
'$descripcion_examen',
'$fecha_creacion',
'$fecha_actualizacion',
'$estado_examen',
'$tipo_recurso_id_fk',
'$usuario_profesor_id_fk') returning id_examen;";
$r = $conexion->consultaComplejaNorAso($sql);
$idTallerExamen = $r['id_examen'];
//------------------------------------------------------------------------------------Recurso
$estadoRecurso = 'ACTIVO';
$sql = "INSERT INTO presaber.recurso(
usuario_profesor_id_fk,
tipo_recurso_id_fk,
descripcion,
contenido,
fecha_creacion,
fecha_actualizacion,
estado)
VALUES ('$usuario_profesor_id_fk',
'$tipo_recurso_id_fk',
'$descripcion_examen',
'$idTallerExamen',
'$fecha_creacion',
'$fecha_actualizacion',
'$estadoRecurso') returning id;";
$r = $conexion->consultaComplejaNorAso($sql);
//------------------------------------------------------------------------------------Crear Configuracion
$repetir_bool = (isset($parametros->repetir_bool)) ? $parametros->repetir_bool : null;
$cantidad_intentos = (isset($parametros->cantidad_intentos)) ? $parametros->cantidad_intentos : null;
$mesclar_preguntas = (isset($parametros->mesclar_preguntas)) ? $parametros->mesclar_preguntas : null;
$mesclar_respuestas = (isset($parametros->mesclar_respuestas)) ? $parametros->mesclar_respuestas : null;
$contrasena_bool = (isset($parametros->contrasena_bool)) ? $parametros->contrasena_bool : null;
$contrasena = (isset($parametros->contrasena)) ? $parametros->contrasena : null;
$examen_id_fk = $idTallerExamen;
$pwd = <PASSWORD>('<PASSWORD>', $contrasena);
$sql = "INSERT INTO evaluacion.configuracion(
repetir_bool,
cantidad_intentos,
mesclar_preguntas,
mesclar_respuestas,
contrasena_bool,
contrasena,
examen_id_fk)
VALUES ( '$repetir_bool',
'$cantidad_intentos',
'$mesclar_preguntas',
'$mesclar_respuestas',
'$contrasena_bool',
'$pwd',
'$examen_id_fk') returning id_configuracion;";
$r = $conexion->consultaComplejaNorAso($sql);
$idConfiguracion = $r['id_configuracion'];
//-------------------------------------------------------------------------------------Crear sesion
$descripcion_sesion = (isset($parametros->descripcion_sesion)) ? $parametros->descripcion_sesion : null;
$sql = "INSERT INTO evaluacion.sesion(
examen_taller_id_fk, descripcion_sesion)
VALUES ('$idTallerExamen', '$descripcion_sesion') returning id_sesion;";
$r = $conexion->consultaComplejaNorAso($sql);
$idSesion = $r['id_sesion'];
$data = [
'code' => 'LTE-001',
'data' => [
'idSesion' => $idSesion,
'idTallerExamen' => $idTallerExamen,
'idConfiguracion' => $idConfiguracion
]
];
} else {
$data = [
'code' => 'LTE-009'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/crearRecurso', function () use ($app) {
$helper = new helper();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$archivos = array();
$parametros = json_decode($json);
$usuarioIdentificado = $helper->authCheck($token, true);
$usuario_profesor_id_fk = $usuarioIdentificado->sub;
$tipo_recurso_id_fk = (isset($parametros->tipo_recurso_id_fk)) ? $parametros->tipo_recurso_id_fk : null;
$descripcion = htmlspecialchars((isset($parametros->descripcion) ? $parametros->descripcion : null));
$estado = (isset($parametros->estado)) ? $parametros->estado : null;
$archivos = (isset($_FILES['archivo'])) ? $_FILES['archivo'] : null;
$fecha_creacion = date('Y-m-d H:i:s');
$fecha_actualizacion = date('Y-m-d H:i:s');
$r = pi_poMoveMultiple('/archivos/recurso/', $archivos);
$conexion = new conexPG();
$contenido = [
'tipo' => 'Archivo',
'contenido' => $r,
];
$contenidoJson = json_encode($contenido);
$sql = "INSERT INTO presaber.recurso(
usuario_profesor_id_fk, tipo_recurso_id_fk, descripcion, contenido, fecha_creacion, fecha_actualizacion, estado)
VALUES ( '$usuario_profesor_id_fk', '$tipo_recurso_id_fk', '$descripcion', '$contenidoJson', '$fecha_creacion', '$fecha_actualizacion', '$estado');";
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-001'
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/listarExamenesTalleres', function () use ($app) {
$helper = new helper();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$usuarioToken = $helper->authCheck($token, true);
$parametros = json_decode($json);
$id = (isset($parametros->id)) ? $parametros->id : null;
$sql = "select e.*,be.descripcion_base_examen,tr.descripcion as descripcion_tipo_recurso from evaluacion.examen_taller e
join presaber.tipo_recurso tr on e.tipo_recurso_id_fk=tr.id
join seguridad.usuario usu on e.id_profesor_fk_examne_taller=usu.id
join evaluacion.base_examen be on e.base_examen_id_fk=be.id_base_examen
where tr.id ='$id' and usu.id='$usuarioToken->sub'";
$conexion = new conexPG();
$r = $conexion->consultaComplejaAso($sql);
if ($r != 0) {
$data = [
'code' => 'LTE-001',
'data' => $r
];
} else {
$data = [
'code' => 'LTE-003'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/listarArchivos', function () use ($app) {
$helper = new helper();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$usuarioToken = $helper->authCheck($token, true);
$parametros = json_decode($json);
$id = (isset($parametros->id)) ? $parametros->id : null;
$sql = "select re.*,tp.descripcion as descripcion_tipo_recurso, usu.nombre,
usu.apellido, usu.ultimo_ingreso, rol.descripcion as descripcion_rol from presaber.recurso re
join presaber.tipo_recurso tp on re.tipo_recurso_id_fk=tp.id
join seguridad.usuario usu on usu.id= re.usuario_profesor_id_fk
join seguridad.rol rol on rol.id=usu.rol_id_fk
where re.usuario_profesor_id_fk ='$usuarioToken->sub' and re.tipo_recurso_id_fk ='$id'";
$conexion = new conexPG();
$r = $conexion->consultaComplejaAso($sql);
$r2 = array();
for ($i = 0; $i < count($r); $i++) {
$string = $r[$i]['descripcion'];
array_push($r2, [
'id' => $r[$i]['id'],
'usuario_profesor_id_fk' => $r[$i]['usuario_profesor_id_fk'],
'tipo_recurso_id_fk' => $r[$i]['tipo_recurso_id_fk'],
'descripcion' => html_entity_decode($string, ENT_COMPAT),
'contenido' => json_decode($r[$i]['contenido']),
'fecha_creacion' => $r[$i]['fecha_creacion'],
'fecha_actualizacion' => $r[$i]['fecha_actualizacion'],
'estado' => $r[$i]['estado'],
'descripcion_tipo_recurso' => $r[$i]['descripcion_tipo_recurso']
]);
}
if ($r != 0) {
$data = [
'code' => 'LTE-001',
'data' => $r2
];
} else {
$data = [
'code' => 'LTE-003'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/contenidoArchivo', function () use ($app) {
$helper = new helper();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$usuarioToken = $helper->authCheck($token, true);
$parametros = json_decode($json);
$id = (isset($parametros->id)) ? $parametros->id : null;
$id_recurso = (isset($parametros->id_recurso)) ? $parametros->id_recurso : null;
$sql = "select re.*,tp.descripcion as descripcion_tipo_recurso, usu.nombre,
usu.apellido, usu.ultimo_ingreso, rol.descripcion as descripcion_rol from presaber.recurso re
join presaber.tipo_recurso tp on re.tipo_recurso_id_fk=tp.id
join seguridad.usuario usu on usu.id= re.usuario_profesor_id_fk
join seguridad.rol rol on rol.id=usu.rol_id_fk
where re.usuario_profesor_id_fk ='$usuarioToken->sub' and re.tipo_recurso_id_fk ='$id' and re.id ='$id_recurso'";
$conexion = new conexPG();
$r = $conexion->consultaComplejaAso($sql);
$r2 = array();
for ($i = 0; $i < count($r); $i++) {
$string = $r[$i]['descripcion'];
array_push($r2, [
'id' => $r[$i]['id'],
'usuario_profesor_id_fk' => $r[$i]['usuario_profesor_id_fk'],
'tipo_recurso_id_fk' => $r[$i]['tipo_recurso_id_fk'],
'descripcion' => html_entity_decode($string, ENT_COMPAT),
'contenido' => json_decode($r[$i]['contenido']),
'fecha_creacion' => $r[$i]['fecha_creacion'],
'fecha_actualizacion' => $r[$i]['fecha_actualizacion'],
'estado' => $r[$i]['estado'],
'descripcion_tipo_recurso' => $r[$i]['descripcion_tipo_recurso'],
'nombre' => $r[$i]['nombre'],
'apellido' => $r[$i]['apellido'],
'descripcion_rol' => $r[$i]['descripcion_rol'],
'ultimo_ingreso' => $r[$i]['ultimo_ingreso']
]);
}
if ($r != 0) {
$data = [
'code' => 'LTE-001',
'data' => $r2
];
} else {
$data = [
'code' => 'LTE-003'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/eliminarArchivo', function () use ($app) {
$helper = new helper();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$conexion = new conexPG();
$usuarioToken = $helper->authCheck($token, true);
$parametros = json_decode($json);
$id = (isset($parametros->id)) ? $parametros->id : null;
$id_archivo = $app->request->post('id_archivo', null);
$sql = "select * from presaber.recurso where id='$id'";
$r = $conexion->consultaComplejaNorAso($sql);
if ($r != 0) {
$contenido = json_decode($r['contenido'], true);
for ($i = 0; $i < count($contenido['contenido']); $i++) {
if ($contenido['contenido'][$i]['id'] == $id_archivo) {
//pi_poEliminarArchivo($contenido['contenido'][$i]['rute']);
$contenido['contenido'][$i]['estado']='false';
}
}
$nuevo_contenido = json_encode($contenido);
$sql = "update presaber.recurso set contenido='$nuevo_contenido' where id='$id'";
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-001'
];
} else {
$data = [
'code' => 'LTE-003'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/nuevoArchivos', function () use ($app) {
$helper = new helper();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$conexion = new conexPG();
$usuarioToken = $helper->authCheck($token, true);
$parametros = json_decode($json);
$id = (isset($parametros->id)) ? $parametros->id : null;
$id_archivo = $app->request->post('id_archivo', null);
$sql = "select * from presaber.recurso where id='$id'";
$r = $conexion->consultaComplejaNorAso($sql);
$archivos = (isset($_FILES['archivo'])) ? $_FILES['archivo'] : null;
$fecha_actualizacion = date('Y-m-d H:i:s');
$r2 = pi_poMoveMultiple('/archivos/recurso/', $archivos);
if ($r != 0) {
$contenido = json_decode($r['contenido'], true);
for($j = 0; $j < count($r2); $j++)
{
array_push($contenido['contenido'],$r2[$j]);
}
for($j = 0; $j < count($contenido['contenido']); $j++)
{
$contenido['contenido'][$j]['id']=$j;
}
$nuevo_contenido = json_encode($contenido);
$sql = "update presaber.recurso set contenido='$nuevo_contenido', fecha_actualizacion='$fecha_actualizacion' where id='$id'";
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-001'
];
} else {
$data = [
'code' => 'LTE-003'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/editarDescripcionArchivo', function () use ($app) {
$helper = new helper();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$conexion = new conexPG();
$usuarioToken = $helper->authCheck($token, true);
$parametros = json_decode($json);
$id = (isset($parametros->id)) ? $parametros->id : null;
$descripcion = htmlspecialchars((isset($parametros->descripcion)) ? $parametros->descripcion : null);
$sql = "select * from presaber.recurso where id='$id'";
$r = $conexion->consultaComplejaNorAso($sql);
$fecha_actualizacion = date('Y-m-d H:i:s');
if ($r != 0) {
$sql = "update presaber.recurso set descripcion='$descripcion', fecha_actualizacion='$fecha_actualizacion' where id='$id'";
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-001'
];
} else {
$data = [
'code' => 'LTE-003'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/profesor/editarEstadoArchivo', function () use ($app) {
$helper = new helper();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$conexion = new conexPG();
$usuarioToken = $helper->authCheck($token, true);
$parametros = json_decode($json);
$id = (isset($parametros->id)) ? $parametros->id : null;
$estado = (isset($parametros->estado)) ? $parametros->estado : null;
$sql = "select * from presaber.recurso where id='$id'";
$r = $conexion->consultaComplejaNorAso($sql);
$fecha_actualizacion = date('Y-m-d H:i:s');
if ($r != 0) {
$sql = "update presaber.recurso set estado='$estado', fecha_actualizacion='$fecha_actualizacion' where id='$id'";
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-001'
];
} else {
$data = [
'code' => 'LTE-003'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});<file_sep>/PreSaber-Nuevo/src/app/services/evaluacion_services/componente.service.ts
import {Injectable} from "@angular/core";
import {Observable} from "rxjs/Observable";
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {GLOBAL} from "../global";
@Injectable()
export class ComponenteService{
public url: string;
constructor(private _Http: HttpClient)
{
this.url = GLOBAL.url;
}
listarComponente(token): Observable<any>
{
let params = 'token=' + token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Http.post(this.url + 'profesor/listarComponente', params, {headers: headers});
}
crear(token,componente): Observable<any> {
let json = JSON.stringify(componente)
let params = 'token=' + token+'&json='+json;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Http.post(this.url + 'profesor/crearComponente', params, {headers: headers});
}
actualizar(token,componente): Observable<any> {
let json = JSON.stringify(componente)
let params = 'token=' + token+'&json='+json;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Http.post(this.url + 'profesor/actualizarComponente', params, {headers: headers});
}
}
<file_sep>/PreSaber-Nuevo/src/app/components/profesor/crear-recurso/crear-recurso.component.ts
/*
*Apodo: Pixel programer
* Nombre: <NAME>
* correo: <EMAIL>
*/
import {Component, OnInit} from '@angular/core';
import {ElementsService} from "../../../services/elements.service";
import {RecursosService} from "../../../services/recursos.service";
import {Tiporecurso} from "../../../models/tiporecurso";
import {Configuracion} from "../../../models/evaluacion/configuracion";
import {split} from "ts-node";
import {Base_examen} from "../../../models/evaluacion/base_examen";
import {Base_calificacionService} from "../../../services/evaluacion_services/base_calificacion.service";
import {Examne_taller} from "../../../models/evaluacion/examne_taller";
import {GLOBAL} from "../../../services/global";
import {ComponenteService} from "../../../services/evaluacion_services/componente.service";
import {Componente} from "../../../models/evaluacion/componente";
import {Competencia} from "../../../models/evaluacion/competencia";
import {CompetenciaService} from "../../../services/evaluacion_services/competencia.service";
import {Sesion} from "../../../models/evaluacion/sesion";
import {SesionService} from "../../../services/evaluacion_services/sesion.service";
import {Examen_tallerService} from "../../../services/evaluacion_services/examen_taller.service";
import {ConfiguracionService} from "../../../services/evaluacion_services/configuracion.service";
import {Pregunta} from "../../../models/evaluacion/pregunta";
import {PreguntaService} from "../../../services/evaluacion_services/pregunta.service";
import {htmlEncode} from "js-htmlencode";
import {htmlDecode} from "js-htmlencode";
import {Respuesta} from "../../../models/evaluacion/respuesta";
import {RespuestaService} from "../../../services/evaluacion_services/respuesta.service";
import {Sanitizer} from "@angular/core";
import {exists} from "fs";
import {element} from "protractor";
import swal from "sweetalert2";
import {Recurso} from "../../../models/evaluacion/recurso";
@Component({
selector: 'app-crear-recurso',
templateUrl: './crear-recurso.component.html',
styleUrls: ['./crear-recurso.component.scss',
'../../../../../node_modules/froala-editor/css/themes/dark.min.css',
'../../../../../node_modules/froala-editor/css/themes/red.min.css',
'../../../../../node_modules/froala-editor/css/themes/gray.min.css',
'../../../../../node_modules/froala-editor/css/themes/royal.min.css'],
providers: [ElementsService,
RecursosService,
Base_calificacionService,
ComponenteService,
CompetenciaService,
SesionService,
Examen_tallerService,
ConfiguracionService,
PreguntaService,
RespuestaService]
})
export class CrearRecursoComponent implements OnInit {
public token: any;
public listTipoRecurso: Array<Tiporecurso>;
public objTipoRecurso: Tiporecurso;
public tipoRecursoL: string;
public configuracionExamen: Configuracion;
//Datos basicos
public objExamenTaller: Examne_taller;
public listExamenTaller: Array<Examne_taller>;
//Configuracion
public listBaseCalificacion: Array<Base_examen>;
public objBaseCalificacion: Base_examen;
public objSesion: Sesion;
public listSesion: Array<Sesion>;
//pregunta
public contexto: any;
public pregunta: any;
public justificacion: any;
public listComponente: Array<Componente>;
public objComponente: Componente;
public listCompetencia: Array<Competencia>;
public objCompetencia: Competencia
public idSesion: any;
public idExamenTaller: any;
public objPregunta: Pregunta;
public objRespuesta: Respuesta;
public listPregunta: Array<Object>;
public listRespuesta: Array<Respuesta>;
public listRespuestaCompleta;
public respuesta: any;
position = 'top-right';
//Editor
public options: Object;
public res: any;
//Archivo
public archivos: Array<File>;
public descripcionArchivo: any;
public objRecurso: Recurso;
constructor(private _ElemetService: ElementsService,
private _RecursoService: RecursosService,
private _BaseCalificaion: Base_calificacionService,
private _ComponenteService: ComponenteService,
private _CompetenciaService: CompetenciaService,
private _SesionService: SesionService,
private _ExamenTallerService: Examen_tallerService,
private _ConfiguracionService: ConfiguracionService,
private _PreguntaService: PreguntaService,
private _RespuestaService: RespuestaService) {
this.objTipoRecurso = new Tiporecurso(0, '', '', '', '');
this.configuracionExamen = new Configuracion('', false, '',
false, false, false, '', '');
this.objBaseCalificacion = new Base_examen('', '', '', '');
this.objExamenTaller = new Examne_taller('', '', '', '', '', '000','000');
this.objComponente = new Componente('000', '', '', '');
this.objCompetencia = new Competencia('000', '', '', '');
this.objSesion = new Sesion('', '', '');
this.objPregunta = new Pregunta('', '', '', '', '', '000', '000');
this.objRespuesta = new Respuesta('', '', '', '', false);
this.objRecurso = new Recurso('','','000','','','','','000');
this.token = localStorage.getItem('token');
this.contexto = '';
this.pregunta = '';
this.respuesta = '';
this.descripcionArchivo = '';
this.justificacion = '';
this.idSesion = '';
this.idExamenTaller = '';
//Archivo
//Configuracion Editor
this.options = {
language: 'es',
charCounterCount: true,
// Set the image upload parameter.
imageUploadParam: 'ImagenEditore',
// Set the image upload URL.
imageUploadURL: GLOBAL.url + 'pi_po/imagenesEditor',
// Additional upload params.
imageUploadParams: {id: 'ImagenEditore'},
// Set request type.
imageUploadMethod: 'POST',
// Set max image size to 5MB.
imageMaxSize: 5 * 1024 * 1024,
// Allow to upload PNG and JPG.
imageAllowedTypes: ['jpeg', 'jpg', 'png'],
fileUploadParam: 'Archivo',
fileUploadURL: GLOBAL.url + 'pi_po/archivosEditor',
fileUploadMethod: 'POST',
fileAllowedTypes: ['application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/pdf', 'application/vnd.openxmlformats-officedocument.presentationml.presentation']
}
}
ngOnInit() {
this._ElemetService.pi_poValidarUsuario('CrearRecursoComponent');
this.cargarTipoRecursos();
this.tipoRecursoL = '';
$("#seccionExamen").hide();
$("#previsualizarPregunta").hide();
$("#loaderTablaBaseCalificacion").hide();
$("#loaderTablaCompetencias").hide();
$("#loaderTablaComponente").hide();
$("#loaderTipoRecurso").hide();
$("#loaderTablaExamenTaller").hide();
$("#preloaderTablaPreguntas").hide();
$("#seccionArchivo").hide();
this._ElemetService.pi_poBontonDesabilitar("#btnEditarRespuesta");
this._ElemetService.pi_poBontonDesabilitar("#btnActualizarPregunta");
this._ElemetService.pi_poBontonDesabilitar("#btnEliminarRespuesta");
this._ElemetService.pi_poBontonDesabilitar("#btnActualizarCompetencia");
}
cargarTipoRecursos() {
$("#loaderTipoRecurso").show();
this._RecursoService.cargarTipos().subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.listTipoRecurso = respuesta.data;
$("#loaderTipoRecurso").hide();
} else {
this._ElemetService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
}
}, error2 => {
}
)
}
tipoRecurso() {
if (this.tipoRecursoL != '') {
var recurso = this.tipoRecursoL.split('-');
if (recurso[1] == 'EXAMEN' || recurso[1] == 'examen') {
this.limpiarExamen();
this.listarComponente();
this.listarCompetencia();
$("#btnCargarExamen").show();
$("#seccionMesaTrabajo").hide();
$("#btnActualizarExamenTaller").hide();
$("#btnActualizarConfiguracion").hide();
$("#loaderTablaSesion").hide();
$("#seccionArchivo").hide();
this.objExamenTaller.tipo_recurso_id_fk = recurso[0];
this._ElemetService.pi_poBontonDesabilitar("#btnActualizarCompetencia");
this._ElemetService.pi_poBontonDesabilitar("#btnActualizarComponente");
$("#seccionExamen").show();
} else if (recurso[1] == 'TALLER' || recurso[1] == 'taller') {
} else if (recurso[1] == 'ARCHIVO' || recurso[1] == 'archivo') {
this.objRecurso.tipo_recurso_id_fk = recurso[0];
this.limpiarExamen();
$("#seccionExamen").hide();
$("#seccionArchivo").show();
$("#btnCargarExamen").hide();
$("#previsualizarPregunta").hide();
}
}
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++CONFIGURACION+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
listarBaseCalificacion() {
$("#loaderTablaBaseCalificacion").show();
this._BaseCalificaion.listar_base(this.token).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
$("#loaderTablaBaseCalificacion").hide();
this.listBaseCalificacion = respuesta.data;
} else {
$("#loaderTablaBaseCalificacion").hide();
this._ElemetService.pi_poVentanaAlertaWarning('Base_Calificacion ' + respuesta.code, respuesta.msg);
}
}, error2 => {
}
)
}
seleccionarBaseCalificacion(Base_calificacion) {
this.objBaseCalificacion = Base_calificacion;
this._ElemetService.pi_poVentanaAlertaWarning('Base de calificacion', 'Se selecciono la base: ' +
this.objBaseCalificacion.descripcion_base_examen + ' con codigo: ' + this.objBaseCalificacion.id_base_examen);
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++Pregunta+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
limpiarExamen() {
this.configuracionExamen = new Configuracion('', false, '',
false, false, false, '', '');
this.objBaseCalificacion = new Base_examen('', '', '', '');
this.objExamenTaller = new Examne_taller('', '', '', '', '', '000','000');
this.objComponente = new Componente('000', '', '', '');
this.objCompetencia = new Competencia('000', '', '', '');
this.objSesion = new Sesion('', '', '');
this.objPregunta = new Pregunta('', '', '', '', '', '000', '000');
this.objRespuesta = new Respuesta('', '', '', '', false);
this.objTipoRecurso = new Tiporecurso(0, '', '', '', '');
this.listPregunta = [];
this.listRespuesta = [];
this.listSesion = [];
}
listarComponente() {
$("#loaderTablaComponente").show();
this._ComponenteService.listarComponente(this.token).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.listComponente = respuesta.data;
$("#loaderTablaComponente").hide();
} else {
this._ElemetService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
$("#loaderTablaComponente").hide();
}
}, error2 => {
}
)
}
crearComponente() {
this._ElemetService.pi_poBontonDesabilitar("#btnCrearComponente");
this._ComponenteService.crear(this.token, this.objComponente).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.listarComponente();
this.limpiarComponente();
this._ElemetService.pi_poBotonHabilitar("#btnCrearComponente");
this._ElemetService.pi_poAlertaSuccess(respuesta.msg, respuesta.code);
} else {
this._ElemetService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
this._ElemetService.pi_poBotonHabilitar("#btnCrearComponente");
}
}, error2 => {
}
)
}
actualizarComponente() {
this._ElemetService.pi_poBontonDesabilitar("#btnActualizarComponente");
this._ComponenteService.actualizar(this.token, this.objComponente).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.limpiarComponente();
this._ElemetService.pi_poBontonDesabilitar("#btnActualizarComponente");
this._ElemetService.pi_poAlertaSuccess(respuesta.msg, respuesta.code);
} else {
this._ElemetService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
this._ElemetService.pi_poBontonDesabilitar("#btnActualizarComponente");
}
}, error2 => {
}
)
}
seleccionarComponente(componente) {
this.objComponente = componente;
this._ElemetService.pi_poAlertaMensaje('Selecciono el componente: ' + this.objComponente.descripcion_componente, 'Componente');
this._ElemetService.pi_poBotonHabilitar("#btnActualizarComponente")
this._ElemetService.pi_poBontonDesabilitar("#btnCrearComponente");
}
limpiarComponente() {
this.objComponente = new Componente('000', '', '', '');
}
listarCompetencia() {
$("#loaderTablaCompetencias").show();
this._CompetenciaService.listarCompetencia(this.token).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.listCompetencia = respuesta.data;
$("#loaderTablaCompetencias").hide();
} else {
this._ElemetService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
$("#loaderTablaCompetencias").hide();
}
}, error2 => {
}
)
}
crearCompetencia() {
this._ElemetService.pi_poBontonDesabilitar("#btnCrearCompetencia");
this._CompetenciaService.crear(this.token, this.objCompetencia).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.limpiarCompetencias();
this.listarCompetencia();
this._ElemetService.pi_poAlertaSuccess(respuesta.msg, respuesta.code);
this._ElemetService.pi_poBotonHabilitar("#btnCrearCompetencia");
} else {
this._ElemetService.pi_poVentanaAlertaWarning(respuesta.msg, respuesta.code);
this._ElemetService.pi_poBotonHabilitar("#btnCrearCompetencia");
}
}, error2 => {
}
)
}
limpiarCompetencias() {
this.objCompetencia = new Competencia('000', '', '', '');
}
seleccionarCompetencia(competencia) {
this.objCompetencia = competencia;
this._ElemetService.pi_poBontonDesabilitar("#btnCrearCompetencia");
this._ElemetService.pi_poBotonHabilitar("#btnActualizarCompetencia");
this._ElemetService.pi_poAlertaMensaje('Selecciono la competencia: ' + this.objComponente.descripcion_componente, 'Competencia');
}
actualizarCompetencia() {
this._ElemetService.pi_poBontonDesabilitar("#btnActualizarCompetencia");
this._CompetenciaService.actualizar(this.token, this.objCompetencia).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status = 'success') {
this._ElemetService.pi_poAlertaSuccess(respuesta.msg, respuesta.code);
this.limpiarCompetencias();
this._ElemetService.pi_poBotonHabilitar("##btnActualizarCompetencia");
} else {
this._ElemetService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
this._ElemetService.pi_poBotonHabilitar("##btnActualizarCompetencia");
}
}, error2 => {
}
)
}
crearExamen() {
if (this.objExamenTaller.id_examen == '') {
let arregloErrores = Array();
this._ElemetService.pi_poBontonDesabilitar("#btnCrearSesionExamenTaller");
if (this.objExamenTaller.descripcion_examen == '') {
arregloErrores.push({'titulo': 'Campos vacios', 'Mensaje': 'Seccion Configuracion-Datos Basicos-DESCRIPCION'});
}
if (this.objExamenTaller.estado_examen == '000') {
arregloErrores.push({
'titulo': 'Campos vacios',
'Mensaje': 'Seccion Configuracion-DatosBasicos-ESTADO, Debes seleccionar una opcion'
});
}
if (this.configuracionExamen.contrasena_bool == true && this.configuracionExamen.contrasena == '') {
arregloErrores.push({
'titulo': 'Campos vacios',
'Mensaje': 'Seccion Configuracion-Configuracion-Contraseña, No puede estar vacio, Debes seleccionar una opcion'
});
}
if (this.configuracionExamen.repetir_bool == true && this.configuracionExamen.cantidad_intentos == '') {
arregloErrores.push({
'titulo': 'Campos vacios',
'Mensaje': 'Seccion Configuracion-Configuracion-Cantidad de intentos, No puede estar vacio'
});
}
if (this.objBaseCalificacion.id_base_examen == '') {
arregloErrores.push({
'titulo': 'Campos vacios',
'Mensaje': 'Seccion Configuracion-Configuracion-RANGO DE CALIFICACION, No se selecciono el rango de calificacion'
});
}
if (arregloErrores.length <= 0) {
this._RecursoService.crearTallerExamen(this.token, this.objExamenTaller, this.objExamenTaller,
this.objBaseCalificacion, this.configuracionExamen, this.objSesion, this.objTipoRecurso).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.objExamenTaller.id_examen = respuesta.data.idTallerExamen;
this.configuracionExamen.id_configuracion = respuesta.data.idConfiguracion;
this.objSesion = respuesta.data.idSesion;
this.listarSesion();
$("#btnActualizarConfiguracion").show();
$("#btnActualizarExamenTaller").show();
this._ElemetService.pi_poBontonDesabilitar("#btnCrearSesionExamenTaller");
this._ElemetService.pi_poAlertaSuccess('LTE-001', 'Se creo de forma correcta.');
} else {
this._ElemetService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
this._ElemetService.pi_poBontonDesabilitar("#btnCrearSesionExamenTaller");
}
}, error2 => {
}
);
} else {
for (let i of arregloErrores) {
this._ElemetService.pi_poAlertaError(i.Mensaje, i.titulo);
}
}
} else {
this._ElemetService.pi_poBontonDesabilitar("#btnCrearSesionExamenTaller");
this.objSesion.examen_taller_id_fk = this.objExamenTaller.id_examen;
this._SesionService.crear(this.token, this.objSesion).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this._ElemetService.pi_poAlertaSuccess(respuesta.msg, respuesta.code);
this.listarSesion();
this._ElemetService.pi_poBontonDesabilitar("#btnCrearSesionExamenTaller");
}
}, error2 => {
}
)
}
}
listarSesion() {
$("#loaderTablaSesion").show();
this._SesionService.listar(this.objExamenTaller).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.listSesion = respuesta.data;
$("#loaderTablaSesion").hide();
}
}, error2 => {
}
)
}
listarExamenTaller() {
$("#loaderTablaExamenTaller").show();
this._ExamenTallerService.listar(this.token).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.listExamenTaller = respuesta.data;
$("#loaderTablaExamenTaller").hide();
} else {
}
}, error2 => {
}
)
}
seleccionarExamenTaller(examenTaller) {
this.objExamenTaller = examenTaller;
this._ExamenTallerService.cargarExamenTaller(this.token, this.objExamenTaller).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
$("#btnActualizarExamenTaller").show();
$("#btnActualizarConfiguracion").show();
this.listarComponente();
this.listarCompetencia();
this.configuracionExamen = respuesta.data.data;
this.objBaseCalificacion = respuesta.data.data;
this.listSesion = respuesta.data.sesion;
$("#loaderTablaSesion").hide();
$("#seccionExamen").show();
$("#seccionMesaTrabajo").hide();
this._ElemetService.pi_poAlertaSuccess('Se cargo de forma correcta del recurso', 'Recurso');
} else {
this._ElemetService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
}
}, error2 => {
}
)
}
seleccionarSesion(sesion) {
this.objSesion = sesion;
this.listarPreguntas();
$("#seccionMesaTrabajo").show();
this._ElemetService.pi_poAlertaMensaje('Se selecciono la sesion: ' + this.objSesion.descripcion_sesion + '.', 'Sesion');
}
actualizarExamenTaller() {
this._ExamenTallerService.actualizar(this.token, this.objExamenTaller).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this._ElemetService.pi_poAlertaSuccess(respuesta.msg, respuesta.code);
} else {
this._ElemetService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
}
}, error2 => {
}
)
}
actualizarConfiguracion() {
this._ConfiguracionService.actualizar(this.token, this.configuracionExamen, this.objExamenTaller.id_examen, this.objBaseCalificacion.id_base_examen).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this._ElemetService.pi_poAlertaSuccess(respuesta.msg, respuesta.code);
} else {
this._ElemetService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
}
}, error2 => {
}
)
}
crearPregunta() {
this._ElemetService.pi_poBontonDesabilitar("#btnCrearPregunta");
this.objPregunta.contexto = htmlDecode(this.contexto);
this.objPregunta.pregunta = htmlDecode(this.pregunta);
this.objPregunta.justificacion = htmlDecode(this.justificacion);
this.objPregunta.compentencia_id_fk = this.objCompetencia.id_competencia;
this.objPregunta.componente_id_fk = this.objComponente.id_componente;
this.objPregunta.sesion_id_fk = this.objSesion.id_sesion;
this._ExamenTallerService.crearPregunta(this.token, this.objPregunta).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.listarPreguntas();
this.pregunta = '';
this.contexto = '';
this.justificacion = '';
this._ElemetService.pi_poBotonHabilitar("#btnCrearPregunta");
this.limpiarPregunta();
this._ElemetService.pi_poAlertaSuccess(respuesta.msg, respuesta.code);
} else {
this._ElemetService.pi_poBotonHabilitar("#btnCrearPregunta");
this._ElemetService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
}
}, error2 => {
}
)
}
listarPreguntas() {
$("#preloaderTablaPreguntas").show();
this._PreguntaService.listar(this.token, this.objSesion).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
if (respuesta.data != 0) {
this.listPregunta = respuesta.data;
$("#preloaderTablaPreguntas").hide();
} else {
this.listPregunta = [];
$("#preloaderTablaPreguntas").hide();
}
} else {
this._ElemetService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
}
}, error2 => {
}
)
}
cargarPregunta(pregunta) {
this._PreguntaService.cargarPregunta(this.token, pregunta.id_pregunta).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.objPregunta = respuesta.data;
$("#seccionContexto").html(this.objPregunta.contexto);
$("#seccionPreguntas").html(this.objPregunta.pregunta);
this.listarRespuesta();
$("#previsualizarPregunta").show(500);
} else {
this._ElemetService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
}
}, error2 => {
}
)
}
seleccionarPregunta(pregunta) {
this._PreguntaService.cargarPregunta(this.token, pregunta.id_pregunta).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.objPregunta = respuesta.data;
this.contexto = this.objPregunta.contexto;
this.pregunta = this.objPregunta.pregunta;
this.justificacion = this.objPregunta.justificacion;
this.objComponente.id_componente = this.objPregunta.componente_id_fk;
this.objCompetencia.id_competencia = this.objPregunta.compentencia_id_fk;
this._ElemetService.pi_poBotonHabilitar("#btnActualizarPregunta");
this._ElemetService.pi_poBontonDesabilitar("#btnCrearPregunta");
this._ElemetService.pi_poAlertaMensaje('Se selecciono la pregunta con codigo: ' + this.objPregunta.id_pregunta, 'Pregunta');
} else {
this._ElemetService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
}
}, error2 => {
}
)
}
actualizarPregunta() {
this._ElemetService.pi_poBontonDesabilitar("#btnActualizarPregunta");
this.objPregunta.contexto = htmlDecode(this.contexto);
this.objPregunta.pregunta = htmlDecode(this.pregunta);
this.objPregunta.justificacion = htmlDecode(this.justificacion);
this.objPregunta.compentencia_id_fk = this.objCompetencia.id_competencia;
this.objPregunta.componente_id_fk = this.objComponente.id_componente;
this.objPregunta.sesion_id_fk = this.objSesion.id_sesion;
this._ExamenTallerService.actualizarPregunta(this.token, this.objPregunta).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.pregunta = '';
this.contexto = '';
this.justificacion = '';
this._ElemetService.pi_poBontonDesabilitar("#btnActualizarPregunta");
this._ElemetService.pi_poBotonHabilitar("#btnCrearPregunta");
this.limpiarPregunta();
this._ElemetService.pi_poAlertaSuccess(respuesta.msg, respuesta.code);
} else {
this._ElemetService.pi_poBotonHabilitar("#btnActualizarPregunta");
this._ElemetService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
}
}, error2 => {
}
)
}
seleccionarPreguntaRespuesta(pregunta) {
this._PreguntaService.cargarPregunta(this.token, pregunta.id_pregunta).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.objPregunta = respuesta.data;
this.listarRespuesta();
} else {
this._ElemetService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
}
}, error2 => {
}
)
}
limpiarPregunta() {
this.objPregunta = new Pregunta('', '', '', '', '', '000', '000');
}
crearRespuesta() {
this._ElemetService.pi_poBontonDesabilitar("btnCrearRespuesta");
this.objRespuesta.pregunta_id_fk = this.objPregunta.id_pregunta;
this.objRespuesta.descripcion_respuesta = htmlDecode(this.respuesta);
if (this.respuesta != '') {
this._RespuestaService.crear(this.token, this.objRespuesta).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
this.listarRespuesta();
this.respuesta = '';
this.limpiarRespuesta();
this._ElemetService.pi_poAlertaMensaje(respuesta.msg, respuesta.code);
} else {
this._ElemetService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
}
}, error2 => {
}
)
} else {
this._ElemetService.pi_poAlertaError('Lo sentimos, las respuesta es requerida.', 'RESPUESTA');
}
}
listarRespuesta() {
this._RespuestaService.listar(this.token, this.objPregunta).subscribe(
respuesta => {
this._ElemetService.pi_poValidarCodigo(respuesta);
let arregloLetras = new Array('A', 'B', 'C', 'D', 'E', 'F');
let contador = 0;
if (respuesta.status == 'success') {
this.listRespuesta = respuesta.data;
this.alistarRespuestas();
} else {
this._ElemetService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
}
}, error2 => {
}
)
}
alistarRespuestas() {
let arregloLetras = new Array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'Ñ', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
let arregloLetrasInicializado = new Array();
let arregloRespuestas = new Array();
var aletorioLetra;
var aleatorioPregunta;
var contador = 0;
for (var i = 0; i < arregloLetras.length; i++) {
arregloLetrasInicializado.push({'bandera': '0', 'letra': arregloLetras[i]});
}
if (this.configuracionExamen.mesclar_respuestas == true || this.configuracionExamen.mesclar_respuestas == '1') {
//-------------------------------------------------Mesclar respuestas
while (contador < this.listRespuesta.length) {
aletorioLetra = Math.floor((Math.random() * this.listRespuesta.length) + 0);
aleatorioPregunta = Math.floor((Math.random() * this.listRespuesta.length) + 0);
if (arregloRespuestas.length <= 0 || arregloRespuestas.findIndex(index => index === "letra") < 0) {
let validacionEntrada = 0;
for (var n = 0; n < arregloRespuestas.length; n++) {
if (arregloRespuestas[n].id == aleatorioPregunta) {
validacionEntrada = 1;
}
}
if (validacionEntrada == 0) {
var validacion = 0;
while (validacion == 0) {
if (arregloLetrasInicializado[aletorioLetra].bandera == '0') {
arregloRespuestas.push({
'letra': arregloLetrasInicializado[aletorioLetra].letra,
'data': this.listRespuesta[aleatorioPregunta],
'id': aleatorioPregunta
});
arregloLetrasInicializado[aletorioLetra].bandera = '1';
validacion = 1;
} else {
aletorioLetra = Math.floor((Math.random() * this.listRespuesta.length) + 0);
}
}
contador++;
}
}
}
this.listRespuestaCompleta = arregloRespuestas;
} else {
//-------------------------------------------------No mesclar respuestas
for (var i = 0; i < this.listRespuesta.length; i++) {
arregloRespuestas.push({
'letra': arregloLetrasInicializado[i].letra,
'data': this.listRespuesta[i],
'id': i
});
this.listRespuestaCompleta = arregloRespuestas;
}
}
}
seleccionarRespuesta(prespuesta) {
this._ElemetService.pi_poBotonHabilitar("#btnEditarRespuesta");
this._ElemetService.pi_poBotonHabilitar("#btnEliminarRespuesta");
this._ElemetService.pi_poBontonDesabilitar("#btnCrearRespuesta");
this.objRespuesta = prespuesta.data;
this.respuesta = prespuesta.data.descripcion_respuesta;
this._ElemetService.pi_poAlertaMensaje('Se selecciono una respuesta', 'RESPUESTA');
}
editarRespuesta() {
this.objRespuesta.descripcion_respuesta = htmlDecode(this.respuesta);
this._ElemetService.pi_poBontonDesabilitar("#btnEditarRespuesta");
if (this.respuesta != '') {
this._RespuestaService.editar(this.token, this.objRespuesta).subscribe(
respuestaR => {
this._ElemetService.pi_poValidarCodigo(respuestaR);
if (respuestaR.status == 'success') {
this.listarRespuesta();
this._ElemetService.pi_poAlertaMensaje(respuestaR.msg, respuestaR.code);
this._ElemetService.pi_poBontonDesabilitar("#btnEliminarRespuesta");
this._ElemetService.pi_poBontonDesabilitar("#btnEditarRespuesta");
this._ElemetService.pi_poBotonHabilitar("#btnCrearRespuesta");
} else {
}
}, error2 => {
}
);
} else {
this._ElemetService.pi_poAlertaError('Lo sentimos, las respuesta es requerida.', 'RESPUESTA');
}
}
eliminarPregunta(pregunta) {
swal({
title: 'LTE-000',
text: 'Al momento de eliminar la pregunta se eliminaran tan bien las respuesta de la pregunta esta usted seguro?',
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Si, Eliminar'
}).then((result) => {
if (result.value) {
this._PreguntaService.eliminar(this.token, pregunta.id_pregunta).subscribe(
r => {
this._ElemetService.pi_poValidarCodigo(r);
if (r.status == 'success') {
this.listarPreguntas();
$("#previsualizarPregunta").hide(500);
swal(
r.code,
r.msg,
'success'
);
} else {
swal(
r.code,
r.msg,
'error'
);
}
}, error2 => {
}
)
}
});
}
eliminarRespuesta(respuestap) {
this._ElemetService.pi_poBontonDesabilitar("#btnEliminarRespuesta");
this._ElemetService.pi_poBontonDesabilitar("#btnEditarRespuesta");
this._ElemetService.pi_poBotonHabilitar("#btnCrearRespuesta");
swal({
title: 'LTE-000',
text: 'Esta segura que decea eliminar la respuesta',
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Eliminar'
}).then((result) => {
if (result.value) {
this._RespuestaService.eliminar(this.token, this.objRespuesta).subscribe(
r => {
this._ElemetService.pi_poValidarCodigo(r);
if (r.status == 'success') {
this.listarRespuesta();
this._ElemetService.pi_poBontonDesabilitar("#btnEliminarRespuesta");
this._ElemetService.pi_poBontonDesabilitar("#btnEditarRespuesta");
this._ElemetService.pi_poBotonHabilitar("#btnCrearRespuesta");
this.respuesta = '';
swal(
r.code,
r.msg,
'success'
);
} else {
swal(
r.code,
r.msg,
'error'
);
}
}, error2 => {
}
)
}
});
}
limpiarRespuesta() {
this.objRespuesta = new Respuesta('', '', '', '', false);
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++Archivo+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
cargarArchivos($event) {
this.archivos = <Array<File>>$event.target.files;
//this.archivosp.push(this.archivos[0]);
for (var i = 0; i < this.archivos.length; i++) {
let tipo = this.archivos[i].name.split('.');
let extension = tipo.pop().toLowerCase();
if (extension == 'png' || extension == 'jpg' || extension == 'gif') {
this.archivos[i]['tipo'] = 'imagen';
this.archivos[i]['extension'] = extension;
this.archivos[i]['estado'] = 'true';
this.archivos[i]['id']=i;
} else if (extension == 'xls' || extension == 'xlsx') {
this.archivos[i]['tipo'] = 'excel';
this.archivos[i]['extension'] = extension;
this.archivos[i]['estado'] = 'true';
this.archivos[i]['id']=i;
} else if (extension == 'docx' || extension == 'docm') {
this.archivos[i]['tipo'] = 'word';
this.archivos[i]['extension'] = extension;
this.archivos[i]['estado'] = 'true';
this.archivos[i]['id']=i;
} else if (extension == 'pptx' || extension == 'ppt') {
this.archivos[i]['tipo'] = 'powerpoint';
this.archivos[i]['extension'] = extension;
this.archivos[i]['estado'] = 'true';
this.archivos[i]['id']=i;
} else if (extension == 'pdf') {
this.archivos[i]['tipo'] = 'pdf';
this.archivos[i]['extension'] = extension;
this.archivos[i]['estado'] = 'true';
this.archivos[i]['id']=i;
} else if (extension == 'txt') {
this.archivos[i]['tipo'] = 'texto';
this.archivos[i]['extension'] = extension;
this.archivos[i]['estado'] = 'true';
this.archivos[i]['id']=i;
} else if (extension == 'rar') {
this.archivos[i]['tipo'] = 'rar';
this.archivos[i]['extension'] = extension;
this.archivos[i]['estado'] = 'false';
this.archivos[i]['id']=i;
} else if (extension == 'exe') {
this.archivos[i]['tipo'] = 'exe';
this.archivos[i]['extension'] = extension;
this.archivos[i]['estado'] = 'false';
this.archivos[i]['id']=i;
} else {
this.archivos[i]['tipo'] = 'desconocido';
this.archivos[i]['extension'] = extension;
this.archivos[i]['estado'] = 'false';
this.archivos[i]['id']=i;
}
}
}
crearRecursoArchivo()
{
if (this.descripcionArchivo != '')
{
this.objRecurso.descripcion= htmlDecode(this.descripcionArchivo);
this._RecursoService.crearRescurso(this.token, ['archivo'], this.archivos, this.objRecurso).then(
(resultado) => {
this._ElemetService.pi_poValidarCodigo(resultado);
this.res=resultado;
if (this.res.status == 'success')
{
this. archivos = new Array<File>();
this.descripcionArchivo = '';
this._ElemetService.pi_poAlertaSuccess(this.res.msg,this.res.code);
}else
{
this._ElemetService.pi_poVentanaAlertaWarning(this.res.code,this.res.msg);
}
},
(error) => {
console.log(error);
}
)
}else
{
this._ElemetService.pi_poAlertaError('Lo sentimos, la descripcion del recurso es requerida','LTE-000');
}
}
}
<file_sep>/PreSaber-Nuevo/src/app/models/modulo.ts
export class Modulo {
constructor(public id: number,
public curso_id_fk: string,
public usuario_administrador_id_fk: string,
public contrato_entidad_id_fk: string,
public usuario_profesor_id_fk,
public descripcion: string,
public prioridad: string,
public imagen: any,
public estado: any,
public fecha_creacion: any,
public fecha_actualizacion: any) {
}
}
<file_sep>/PreSaber-Web/src/app/components/registro/registro.component.ts
import {Component, OnInit} from '@angular/core';
import {User} from "../../models/user";
import {Router, ActivatedRoute} from "@angular/router";
import {RegistroService} from "../../services/registro.service";
import {ElementsService} from "../../services/elements.service";
@Component({
selector: 'app-registro',
templateUrl: './registro.component.html',
styleUrls: ['./registro.component.css'],
providers: [RegistroService, ElementsService]
})
export class RegistroComponent implements OnInit {
public objUsuario: User;
public validationCode: boolean;
public activateCode: string;
public typeMesage: string;
constructor(private _route: ActivatedRoute, private _router: Router, private _RegistroService: RegistroService,
private _elementService: ElementsService) {
this.objUsuario = new User(null, 3, '', '', '', '',
'', '', '', '', '', '', '',
'', '');
this.validationCode = false;
this.typeMesage = '2';
}
ngOnInit() {
$('#loader').hide();
this.validationCode = false;
}
nuevoRegistro() {
$('#btnResgistrate').attr('disabled', 'disabled');
$('#loader').show();
this._RegistroService.newRegister(this.objUsuario).subscribe(
respuesta => {
if (respuesta.status === 'success') {
$('#loader').hide();
$('#btnResgistrate').removeAttr('disabled');
this.validationCode = true;
} else {
$('#loader').hide();
$('#alert').html(this._elementService.alerts(3, 'Lo sentimos, ya existe un usuario con este correo.'));
}
$('#btnResgistrate').removeAttr('disabled');
}, error2 => {
}
);
}
validateCode() {
$('#btnConfirmarCodigo').attr('disabled', 'disabled');
this._RegistroService.activateAcount(this.objUsuario).subscribe(
respuesta => {
if (respuesta.status === 'success') {
this.typeMesage = '1';
$('#btnConfirmarCodigo').removeAttr('disabled');
this._router.navigate(['login']);
} else if (respuesta.status === 'error') {
this.typeMesage = '3';
$('#btnConfirmarCodigo').removeAttr('disabled');
}
}, error => {
}
);
}
}
<file_sep>/php-backend/App/componentes/administrador/pregunta.php
<?php
$app->post('/administrador/crearPregunta', function () use ($app) {
$helper = new helper();
$conexion = new conexPG();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token');
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$params = json_decode($json);
$usuario_administrador_id_fk = (isset($params->usuario_administrador_id_fk)) ? $params->usuario_administrador_id_fk : null;
$descripcion = (isset($params->descripcion)) ? $params->descripcion : null;
$estado = (isset($params->estado)) ? $params->estado : null;
$imagen = (isset($_FILES['imagen'])) ? $_FILES['imagen'] : null;
$fecha_creacion = $fecha_creacion = date('Y-m-d H:i:s');
$fecha_actualizacion = date('Y-m-d H:i:s');
if ($imagen != null) {
$nombreArchivo = time();
$ruta = '/imagenes/curso/' . $nombreArchivo . '.' . pi_poExtenssion($imagen);
pi_poMove('/imagenes/curso', $imagen, $nombreArchivo);
} else {
$imagen = '/imagenes/curso/default.jpeg';
$nombreArchivo = time();
$ruta = '/imagenes/curso/' . $nombreArchivo . '.' . pi_poExtenssion($imagen);
pi_poMove('/imagenes/curso', $imagen, $nombreArchivo);
}
$sql = "INSERT INTO presaber.curso(
usuario_administrador_id_fk, descripcion, estado, imagen, fecha_creacion, fecha_actualizacion)
VALUES (".$usuario_administrador_id_fk.", '".$descripcion."', '".$estado."', '".$ruta."', '".$fecha_creacion."', '".$fecha_actualizacion."');";
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-001'
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});<file_sep>/PreSaber-Nuevo/src/app/models/equipmenthasuser.ts
export class Equipmenthasuser {
constructor(public id: number,
public description: string,
public createdAt: any,
public updatedAt: any,
public User: number,
public Equipment: number,
public typeEquimentHasUser: number,
public UserAdmin: number,
public state: string) {
}
}<file_sep>/PreSaber-Nuevo/src/app/services/estudiante/estudiante.service.ts
import {Observable} from "rxjs/Observable";
import {HttpClient,HttpHeaders} from "@angular/common/http";
import {GLOBAL} from "../global";
import {Injectable} from "@angular/core";
@Injectable()
export class EstudianteService{
public url: any;
constructor(private _Http: HttpClient){
this.url = GLOBAL.url;
}
listarFichasUsuario(token): Observable<any>{
let parametros = 'token='+token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Http.post(this.url+'estudiante/MisFichas',parametros,{headers:headers})
}
listarModulosCurso(token,id): Observable<any>{
let parametros = 'token='+token+'&id='+id;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Http.post(this.url+'estudiante/MisCursos',parametros,{headers:headers})
}
listarModulosFicha(token,id,id_curso): Observable<any>{
let parametros = 'token='+token+'&id='+id+'&id_curso='+id_curso;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Http.post(this.url+'estudiante/MisModulos',parametros,{headers:headers})
}
listarClasesModulo(token,id): Observable<any>{
let parametros = 'token='+token+'&id='+id;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Http.post(this.url+'estudiante/misClases',parametros,{headers:headers})
}
listarRecursosClases(token,id): Observable<any>{
let parametros = 'token='+token+'&id='+id;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Http.post(this.url+'estudiante/ActividadesClases',parametros,{headers:headers})
}
}
<file_sep>/php-backend/App/componentes/usuario.php
<?php
$app->post('/crearUsuario', function () use ($app) {
$helper = new helper();
$conexion = new conexPG();
$json = $app->request->post('json', null);
if ($json != null) {
$params = json_decode($json);
$nombre = (isset($params->nombre)) ? $params->nombre : null;
$apellido = (isset($params->apellido)) ? $params->apellido : null;
$correo = (isset($params->correo)) ? $params->correo : null;
$contrasena = (isset($params->contrasena)) ? $params->contrasena : null;
$documento = (isset($params->documento)) ? $params->documento : null;
$rutaImagen = '/imagenes_estandar/usuario-64x64.png';
$sql = "select * from seguridad.usuario where correo like '$correo'";
$user = $conexion->consultaComplejaNor($sql);
if (pg_num_rows($user) <= 0) {
$sql = "select * from seguridad.usuario where documento like '$documento'";
$user = $conexion->consultaComplejaNor($sql);
if (pg_num_rows($user) <= 0) {
$codigo = time() . +'21';
pi_poEnviaEmail('<EMAIL>', 'Osiris123', 'Los Tres Editores', $correo, 'Codigo de activacion cuenta LTE',
pi_po_email_Code($nombre, $codigo));
$pwd = <PASSWORD>('<PASSWORD>', $<PASSWORD>);
$fecha_creacion = date('Y-m-d H:i');
$sql ="select id from seguridad.rol WHERE descripcion like 'estudiante' or descripcion like 'ESTUDIANTE'";
$r = $conexion->consultaComplejaNor($sql);
$rol = pg_fetch_assoc($r);
$sql = "INSERT INTO seguridad.usuario(
rol_id_fk, nombre, apellido, correo, contrasena, codigo_activacion, estado,fecha_creacion,imagen,documento)
VALUES ( $rol[id], '" . $nombre . "','" . $apellido . "','" . $correo . "','" . $pwd . "','" . $codigo . "','INACTIVO','" . $fecha_creacion . "','$rutaImagen','$documento');";
$conexion->consultaComplejaNor($sql);
$data = [
'code' => 'LTE-001'
];
} else {
$data = [
'code' => 'LTE-000',
'status' => 'error',
'msg' => 'Lo sentimos ya existe un usuario registrado con este documento'
];
}
} else {
$data = [
'code' => 'LTE-000',
'status' => 'error',
'msg' => 'Lo sentimos ya existe un usuario registrado con este correo'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/activarCodigo', function () use ($app) {
$helper = new helper();
$conexion = new conexPG();
$json = $app->request->post('json', null);
if ($json != null) {
$parametros = json_decode($json);
$correo = (isset($parametros->correo)) ? $parametros->correo : null;
$codigo = (isset($parametros->codigo_activacion)) ? $parametros->codigo_activacion : null;
$sql = "select * from seguridad.usuario where correo like '" . $correo . "' and codigo_activacion like '" . $codigo . "'";
$r = $conexion->consultaComplejaNor($sql);
if (pg_num_rows($r) > 0) {
$usuario = pg_fetch_assoc($r);
if ($usuario['estado'] == 'INACTIVO') {
if ($usuario['codigo_activacion'] == $codigo) {
$sql = "update seguridad.usuario set estado = 'ACTIVO' where id='$usuario[id]'";
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-001',
'data' => $usuario
];
} else {
$data = [
'code' => 'LTE-000',
'msg' => 'El codigo de activacion es incorrecto.'
];
}
} else {
$data = [
'code' => 'LTE-000',
'msg' => 'Lo sentimos, su suenta ya esta activa.'
];
}
} else {
$data = [
'status' => 'error',
'code' => 'LTE-000',
'msg' => 'Lo sentimos codigo de activacion incorrecto'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/login', function () use ($app) {
$json = $app->request->post('json', null);
$helper = new helper();
if ($json != null) {
$parametros = json_decode($json);
$correo = (isset($parametros->correo)) ? $parametros->correo : null;
$contrasena = (isset($parametros->contrasena)) ? $parametros->contrasena : null;
$getHash = (isset($parametros->has)) ? $parametros->has : false;
$conexion = new conexPG();
$pwd = hash('<PASSWORD>56', $contrasena);
$sql = "select * from seguridad.usuario where correo='$correo' and contrasena='$pwd'";
$r = $conexion->consultaComplejaNor($sql);
if (pg_num_rows($r) > 0) {
$usuario = pg_fetch_assoc($r);
if ($usuario['estado'] != 'INACTIVO') {
if ($correo == $usuario['correo'] && $pwd == $usuario['con<PASSWORD>']) {
$jwtAuth = new jwtAuth();
$jwt = $jwtAuth->signIn($usuario, $getHash);
$data = [
'code' => 'LTE-001',
'data' => $jwt
];
} else {
$data = [
'code' => 'LTE-006'
];
}
} else {
$data = [
'code' => 'LTE-022'
];
}
} else {
$data = [
'code' => 'LTE-000',
'status' => 'error',
'msg' => 'Lo sentimos, no se encontraron resultados'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/actualizarPerfil', function () use ($app) {
$helper = new helper();
$json = $app->request->post('json', null);
if ($json != null) {
$toke = $app->request->post('token', null);
if ($toke != null) {
$validacionUsuario = $helper->authCheck($toke);
if ($validacionUsuario == true) {
$parametros = json_decode($json);
$id = (isset($parametros->id)) ? $parametros->id : null;
$nombre = (isset($parametros->nombre)) ? $parametros->nombre : null;
$apellido = (isset($parametros->apellido)) ? $parametros->apellido : null;
$contrasena = (isset($parametros->contrasena)) ? $parametros->contrasena : null;
$fecha_actualizacion = date('Y-m-d H:i');
$imagen = (isset($_FILES['imagen'])) ? $_FILES['imagen'] : null;
$usuarioToken = $helper->authCheck($toke, true);
if ($usuarioToken->sub == $id) {
$conexion = new conexPG();
$sql = "select * from seguridad.usuario where id ='$id'";
$r = $conexion->consultaComplejaNor($sql);
$usuario = pg_fetch_assoc($r);
if (pg_num_rows($r) > 0) {
if ($contrasena != null) {
$pwd = hash('SHA256', $contrasena);
} else {
$pwd = $usuario['contrasena'];
}
$rutaImagen = $usuario['imagen'];
$validacion = 1;
if ($imagen != null) {
$extension = pi_poExtenssion($imagen);
if ($extension == 'png' || $extension == 'gif' || $extension == 'jpg' || $extension == 'jpeg') {
if ($usuario['imagen'] != '/imagenes_estandar/usuario-64x64.png') {
pi_poEliminarArchivo($usuario['imagen']);
}
$nombreArchivo = time();
pi_poMove('/imagenes/perfil/', $imagen, $nombreArchivo);
$rutaImagen = '/imagenes/perfil/' . $nombreArchivo . '.' . pi_poExtenssion($imagen);
} else {
$validacion = 2;
}
}
if ($validacion == 1) {
if ($imagen != null) {
$sql = "UPDATE seguridad.usuario
SET nombre='$nombre', apellido='$apellido', contrasena='$pwd', fecha_actualizacion='$fecha_actualizacion', imagen='$rutaImagen'
WHERE id='$id';";
} else {
$sql = "UPDATE seguridad.usuario
SET nombre='$nombre', apellido='$apellido', contrasena='$pwd', fecha_actualizacion='$fecha_actualizacion'
WHERE id='$id';";
}
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-007',
'data' => [
'nombre' => $nombre,
'apellido' => $apellido,
'fecha_actualizacion' => $fecha_actualizacion,
'imagen' => $rutaImagen
]
];
} else {
$data = [
'code' => 'LTE-014'
];
}
} else {
$data = [
'code' => 'LTE-013',
'line' => '220'
];
}
} else {
$data = [
'code' => 'LTE-013',
'line' => '226'
];
}
} else {
$data = [
'code' => 'LTE-011'
];
}
} else {
$data = [
'code' => 'LTE-010'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
<file_sep>/php-backend/App/componentes/base_examen.php
<?php
$app->post("/listarBase", function () use ($app) {
$token = $app->request()->post('token', null);
$helper = new helper();
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$conexion = new conexPG();
$sql = "select * from evaluacion.base_examen";
$r = $conexion->consultaComplejaAso($sql);
if ($r != 0)
{
$data =[
'code'=>'LTE-001',
'data'=>$r
];
}else
{
$data = [
'code'=>'LTE-003'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-013'
];
}
echo $helper->checkCode($data);
});<file_sep>/PreSaber-Nuevo/src/app/services/curso.service.ts
import {Injectable} from "@angular/core";
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {Observable} from "rxjs/Observable";
import {User} from "../models/user";
import {GLOBAL} from "./global";
@Injectable()
export class CursoService {
public url: string;
constructor(public _http: HttpClient) {
this.url = GLOBAL.url;
}
crearCurso(token, params: Array<string>, files: Array<File>, data = null) {
let urlF = this.url + 'administrador/crearCurso';
return new Promise((resolve, reject) => {
var formData: any = new FormData();
var xhr = new XMLHttpRequest();
if (files != undefined) {
var name_file_input = params[0];
for (var i = 0; i < files.length; i++) {
formData.append(name_file_input, files[i], files[i].name);
}
}
formData.append('token', token);
if (data != null)
var json = JSON.stringify(data);
formData.append('json', json);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
}
xhr.open("POST", urlF, true);
xhr.send(formData);
});
}
actualizarCurso(token, params: Array<string>, files: Array<File>, data = null) {
let urlF = this.url + 'administrador/actualizarCurso';
return new Promise((resolve, reject) => {
var formData: any = new FormData();
var xhr = new XMLHttpRequest();
if (files != undefined) {
var name_file_input = params[0];
for (var i = 0; i < files.length; i++) {
formData.append(name_file_input, files[i], files[i].name);
}
}
formData.append('token', token);
if (data != null)
var json = JSON.stringify(data);
formData.append('json', json);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
}
xhr.open("POST", urlF, true);
xhr.send(formData);
});
}
listarCurso(token): Observable<any> {
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
let parametros = 'token=' + token;
return this._http.post(this.url + 'administrador/listarCurso', parametros, {headers: headers});
}
filtrarCurso(filtro, token): Observable<any> {
let json = '{"filtro":"' + filtro + '"}';
let params = 'json=' + json + '&token=' + token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(this.url + 'administrador/filtroCurso', params, {headers: headers});
}
misCursos(token,id): Observable<any> {
let params = 'token=' + token+'&id='+id;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(this.url + 'profesor/MisCursos', params, {headers: headers});
}
}
<file_sep>/PreSaber-Web/src/app/models/section.ts
export class Section {
constructor(public id: number,
public description: string,
public priority: string,
public image: string,
public state: string,
public createdAt: any,
public updatedAt: any,
public Module: number,
public UserTeacher: number) {
}
}<file_sep>/PreSaber-Nuevo/src/app/services/evaluacion_services/sesion.service.ts
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {Injectable} from "@angular/core";
import {Observable} from "rxjs/Observable";
import {GLOBAL} from "../global";
@Injectable()
export class SesionService{
public url:string;
constructor(private _Http: HttpClient)
{
this.url = GLOBAL.url;
}
listar(objExamen): Observable<any>
{
let json = JSON.stringify(objExamen);
let params = 'json='+json;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Http.post(this.url + 'profesor/listarSesion', params, {headers: headers});
}
crear(token,sesion): Observable<any>
{
let json = JSON.stringify(sesion);
let params = 'json='+json+'&token='+token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Http.post(this.url + 'profesor/crearSesion', params, {headers: headers});
}
listarSesionCurso(token,objSesion): Observable<any>
{
let json = JSON.stringify(objSesion);
let params = 'json='+json+'&token='+token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Http.post(this.url + 'profesor/listarSesionCurso', params, {headers: headers});
}
actualizarPrioridad(token,sesion): Observable<any>
{
let params = 'sesion='+JSON.stringify(sesion)+'&token='+token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Http.post(this.url + 'profesor/actualizarPrioridad', params, {headers: headers});
}
actualizarSesionCurso(token, params: Array<string>, files: Array<File>, data = null) {
let urlF = this.url + 'profesor/actualizarSesionCurso';
return new Promise((resolve, reject) => {
var formData: any = new FormData();
var xhr = new XMLHttpRequest();
if (files != undefined) {
var name_file_input = params[0];
for (var i = 0; i < files.length; i++) {
formData.append(name_file_input, files[i], files[i].name);
}
}
if (token != null)
{
formData.append('token', token);
}
if (data != null)
var json = JSON.stringify(data);
formData.append('json', json);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
}
xhr.open("POST", urlF, true);
xhr.send(formData);
});
}
crearSesionCurso(token,objSesion): Observable<any>
{
let json = JSON.stringify(objSesion);
let params = 'json='+json+'&token='+token;
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._Http.post(this.url + 'profesor/crearSesionCurso', params, {headers: headers});
}
}
<file_sep>/PreSaber-Web/src/app/app.component.ts
import {Component, DoCheck} from '@angular/core';
import {ElementsService} from "./services/elements.service";
import {ActivatedRoute, Router} from "@angular/router";
import {User} from "./models/user";
import {GLOBAL} from "./services/global";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [ElementsService]
})
export class AppComponent implements DoCheck {
public token = null;
public objUsuario: any;
public url: string;
constructor(private _router: ActivatedRoute,
private _route: Router,
private _elements: ElementsService) {
this.url = GLOBAL.urlFiles;
this.objUsuario = this._elements.getUserIdentity();
this._elements.pi_poValidarUsuario('AppComponent');
}
ngDoCheck() {
this.objUsuario = this._elements.getUserIdentity();
}
registro() {
}
cerrarSesion() {
localStorage.removeItem('token');
localStorage.removeItem('userIdentity');
window.location.href = '/';
}
}
<file_sep>/PreSaber-Nuevo/src/app/models/seccion_recurso.ts
export class Seccion_recurso {
constructor(public id: any,
public seccion_id_fk: any,
public recurso_id_fk: any,
public usuario_profesor_id_fk: any,
public descripcion: any,
public estado: any,
public prioridad: any,
public imagen: any,
public fecha_creacion: any,
public fecha_actualizacion: any) {
}
}
<file_sep>/php-backend/App/componentes/administrador/usuario.php
<?php
$app->post('/administrador/crearUsuario', function () use ($app) {
$helper = new helper();
$conexion = new conexPG();
$json = $app->request->post('json', null);
if ($json != null) {
$token = $app->request->post('token', null);
if ($token != null) {
$validacionToken = $helper->authCheck($token);
if ($validacionToken == true) {
$params = json_decode($json);
$nombre = (isset($params->nombre)) ? $params->nombre : null;
$apellido = (isset($params->apellido)) ? $params->apellido : null;
$correo = (isset($params->correo)) ? $params->correo : null;
$id_rol_fk = (isset($params->rol_id_fk)) ? $params->rol_id_fk : null;
$estado = (isset($params->estado)) ? $params->estado : null;
$documento = (isset($params->documento)) ? $params->documento : null;
$sql = "select * from seguridad.usuario where correo like '$correo'";
$user = $conexion->consultaComplejaNor($sql);
$rutaImagen = '/imagenes_estandar/imagen-perfil-128x128.png';
$contrasena = time() . '351';
if (pg_num_rows($user) <= 0) {
$sql = "select * from seguridad.usuario where correo like '$correo'";
$user = $conexion->consultaComplejaNor($sql);
if (pg_num_rows($user) <= 0) {
$codigo = time() . +'21';
pi_poEnviaEmail('<EMAIL>', 'Osiris123', 'Los Tres Editores no-reply', $correo, 'Informacion de cuenta',
pi_po_email_CrearUsuarioAdministrador($correo, $contrasena, $nombre));
$pwd = hash('SHA256', $contrasena);
$fecha_creacion = date('Y-m-d H:i');
$sql = "INSERT INTO seguridad.usuario(
rol_id_fk, nombre, apellido, correo, contrasena,estado,fecha_creacion,imagen,documento)
VALUES ('$id_rol_fk', '" . $nombre . "','" . $apellido . "','" . $correo . "','" . $pwd . "','$estado','" . $fecha_creacion . "','$rutaImagen','$documento');";
$conexion->consultaComplejaNor($sql);
$data = [
'code' => 'LTE-001'
];
} else {
$data = [
'code' => 'LTE-000',
'status' => 'error',
'msg' => 'Lo sentimos, ya existe un usuario en este documento'
];
}
} else {
$data = [
'code' => 'LTE-000',
'status' => 'error',
'msg' => 'Lo sentimos ya existe un usuario registrado con este correo'
];
}
} else {
$data = [
'code' => 'LTE-011'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/administrador/rolUsuario', function () use ($app) {
$conexion = new conexPG();
$helper = new helper();
$sql = "select * from seguridad.rol where estado = 'ACTIVO'";
$r = $conexion->consultaComplejaAso($sql);
$data = [
'code' => 'LTE-001',
'data' => $r
];
echo $helper->checkCode($data);
});
$app->post('/administrador/listarUsuario', function () use ($app) {
$toke = $app->request->post('token', null);
$helper = new helper();
if ($toke != null) {
$validacionUsuario = $helper->authCheck($toke);
if ($validacionUsuario == true) {
$conexion = new conexPG();
$sql = 'select u.*, r.descripcion as rol_descripcion from seguridad.usuario u join seguridad.rol r on u.rol_id_fk=r.id
order by fecha_creacion DESC limit 200';
$r = $conexion->consultaComplejaAso($sql);
$data = [
'code' => 'LTE-001',
'data' => $r
];
} else {
$data = [
'code' => 'LTE-013'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/administrador/actualizarUsuario', function () use ($app) {
$helper = new helper();
$json = $app->request->post('json', null);
if ($json != null) {
$toke = $app->request->post('token', null);
if ($toke != null) {
$validacionUsuario = $helper->authCheck($toke);
if ($validacionUsuario == true) {
$parametros = json_decode($json);
$id = (isset($parametros->id)) ? $parametros->id : null;
$nombre = (isset($parametros->nombre)) ? $parametros->nombre : null;
$apellido = (isset($parametros->apellido)) ? $parametros->apellido : null;
$correo = (isset($parametros->correo)) ? $parametros->correo : null;
$estado = (isset($parametros->estado)) ? $parametros->estado : null;
$documento = (isset($parametros->documento)) ? $parametros->documento : null;
$rol_id_fk = (isset($parametros->rol_id_fk)) ? $parametros->rol_id_fk : null;
$fecha_actualizacion = date('Y-m-d H:i');
$conexion = new conexPG();
$sql = "select * from seguridad.usuario where correo ='$correo'";
$r = $conexion->consultaComplejaNor($sql);
$usuario = pg_fetch_assoc($r);
if ($usuario['id'] == $id) {
$sql = "select * from seguridad.usuario where id ='$id'";
$r = $conexion->consultaComplejaNor($sql);
if (pg_num_rows($r) > 0) {
$sql = "UPDATE seguridad.usuario
SET nombre='$nombre', apellido='$apellido', fecha_actualizacion='$fecha_actualizacion', correo='$correo',
estado='$estado', rol_id_fk='$rol_id_fk', documento='$documento'
WHERE id='$id';";
$conexion->consultaSimple($sql);
$data = [
'code' => 'LTE-007'
];
} else {
$data = [
'code' => 'LTE-013',
'line' => '220'
];
}
} else {
$data = [
'code' => 'LTE-000',
'status' => 'error',
'msg' => 'Lo sentimos ya existe este correo'
];
}
} else {
$data = [
'code' => 'LTE-011'
];
}
} else {
$data = [
'code' => 'LTE-010'
];
}
} else {
$data = [
'code' => 'LTE-009'
];
}
echo $helper->checkCode($data);
});
$app->post('/administrador/filtroUsuario', function () use($app){
$json = $app->request->post('json',null);
$toke = $app->request->post('token',null);
$helper = new helper();
if ($json != null)
{
if ($toke != null)
{
$validarToke = $helper->authCheck($toke);
if ($validarToke == true)
{
$parametros = json_decode($json);
$filtro = (isset($parametros->filstro)) ? $parametros->filtro : $parametros->filtro;
$sql = "select u.*, r.descripcion as rol_descripcion from seguridad.usuario u join seguridad.rol r on u.rol_id_fk=r.id
where correo like '%$filtro%' or documento like '%$filtro%' or nombre like '%$filtro%' order by fecha_creacion DESC limit 200";
$conexion = new conexPG();
$r = $conexion->consultaComplejaAso($sql);
if ($r != 0)
{
$data = [
'code'=>'LTE-001',
'data'=>$r
];
}else
{
$data=[
'code'=>'LTE-003'
];
}
}else
{
$data = [
'code'=>'LTE-013'
];
}
}else
{
$data = [
'code'=>'LTE-010'
];
}
}else
{
$data = [
'code'=>'LTE-009'
];
}
echo $helper->checkCode($data);
});<file_sep>/PreSaber-Nuevo/src/app/components/profesor/mis-estudiantes/mis-estudiantes.component.ts
import {Component, OnInit} from '@angular/core';
import {ElementsService} from "../../../services/elements.service";
import {FichaService} from "../../../services/ficha.service";
@Component({
selector: 'app-mis-estudiantes',
templateUrl: './mis-estudiantes.component.html',
styleUrls: ['./mis-estudiantes.component.scss'],
providers: [ElementsService, FichaService]
})
export class MisEstudiantesComponent implements OnInit {
public descripcionFicha: any;
public fichaSeleccionada: any;
public listEstudiantes = [];
public token: any;
constructor(private _ElementService: ElementsService,
private _FichaService: FichaService) {
this.token = localStorage.getItem('token');
}
ngOnInit() {
this._ElementService.pi_poValidarUsuario('MisEstudiantesComponent');
this.fichaSeleccionada = localStorage.getItem('ficha').split('|-|');
this.descripcionFicha = this.fichaSeleccionada[1];
this.cargarEstudiantesFicha();
$("#loaderTablaUsuario").hide();
}
cargarEstudiantesFicha() {
$("#loaderTablaUsuario").show();
this._FichaService.cargarEstudianteFicha(this.token, this.fichaSeleccionada[0]).subscribe(
respuesta => {
this._ElementService.pi_poValidarCodigo(respuesta);
if (respuesta.status == 'success') {
if (respuesta.data != 0) {
this.listEstudiantes = respuesta.data;
this._ElementService.pi_poAlertaSuccess(respuesta.msg,respuesta.code);
$("#loaderTablaUsuario").hide();
} else {
this.listEstudiantes=[];
this._ElementService.pi_poVentanaAlertaWarning('LTE-000','Lo sentimos, No se encontraron estudiantes');
$("#loaderTablaUsuario").hide();
}
} else {
this._ElementService.pi_poVentanaAlertaWarning(respuesta.code, respuesta.msg);
$("#loaderTablaUsuario").hide();
}
}, error2 => {
}
)
}
}
<file_sep>/PreSaber-Web/src/app/components/home-estudiante/home-estudiante.component.ts
import { Component, OnInit } from '@angular/core';
import {ElementsService} from "../../services/elements.service";
@Component({
selector: 'app-home-estudiante',
templateUrl: './home-estudiante.component.html',
styleUrls: ['./home-estudiante.component.css'],
providers: [ElementsService]
})
export class HomeEstudianteComponent implements OnInit {
constructor(private _ElementsService: ElementsService) { }
ngOnInit() {
this._ElementsService.pi_poValidarUsuario('HomeEstudianteComponent');
}
}
| 4a06e9f658ace3ff8ae4d5d1ce1c6cea8395b368 | [
"Markdown",
"SQL",
"TypeScript",
"PHP"
] | 92 | TypeScript | LTESoftware/Saber | b55bf1a0b659ccf8d391073e42efdda0e926d3fd | 07fd290491ac335b75d2b2aced280457cd5f4610 |
refs/heads/master | <file_sep>#ifndef DPUSHBUTTON_GLOBAL_H
#define DPUSHBUTTON_GLOBAL_H
#include <QtCore/qglobal.h>
#if defined(DPUSHBUTTON_LIBRARY)
# define DPUSHBUTTONSHARED_EXPORT Q_DECL_EXPORT
#else
# define DPUSHBUTTONSHARED_EXPORT Q_DECL_IMPORT
#endif
#endif // DPUSHBUTTON_GLOBAL_H
<file_sep>#include "dpushbutton.h"
#include <QPainter>
DPushButton::DPushButton(QWidget *parent):QPushButton(parent),
m_containText(false),
m_containPixmap(false),
m_isPress(false),
m_size(1),
m_penColor(Qt::black),
m_font(QFont("Arial", 10))
{
}
DPushButton::DPushButton(const QString &text, QWidget *parent):QPushButton(text, parent),
m_text(text),
m_containText(true),
m_containPixmap(false),
m_isPress(false),
m_size(1),
m_penColor(Qt::black),
m_font(QFont("Arial", 10))
{
}
DPushButton::DPushButton(const QPixmap &pixmap, QWidget *parent):QPushButton(parent),
m_pixmap(pixmap),
m_containText(false),
m_containPixmap(true),
m_isPress(false),
m_size(1),
m_penColor(Qt::black),
m_font(QFont("Arial", 10))
{
}
DPushButton::DPushButton(const QPixmap &pixmap, const QString &text, QWidget *parent):QPushButton(text, parent),
m_text(text),
m_pixmap(pixmap),
m_containText(true),
m_containPixmap(true),
m_isPress(false),
m_size(1),
m_penColor(Qt::black),
m_font(QFont("Arial", 10))
{
}
void DPushButton::setPixmapScale(double i)
{
m_size = i;
}
void DPushButton::setPixmap(const QPixmap &pixmap)
{
m_pixmap = pixmap;
m_containPixmap = true;
}
void DPushButton::setTextColor(const QColor &color)
{
m_penColor = color;
}
void DPushButton::setTextFont(const QFont &font)
{
m_font = font;
}
void DPushButton::setText(const QString &text)
{
m_text = text;
m_containText = true;
}
void DPushButton::paintEvent(QPaintEvent* e)
{
if(m_containText && !m_containPixmap)
{
return QPushButton::paintEvent(e);
}
QPixmap spixmap(m_pixmap);
int pw = spixmap.width();
int ph = spixmap.height();
QPixmap pixmap =spixmap.scaled(QSize(pw*m_size, ph*m_size),Qt::KeepAspectRatio);
QFontMetrics fontMetrics(m_font);
int wid = fontMetrics.width(m_text);
int h = fontMetrics.height();
if(m_containText)
{
if(wid > pixmap.width())
{
this->resize(wid + 2, pixmap.height() + h + 2);
}
else
{
this->resize(pixmap.width() + 2, pixmap.height() + h + 2);
}
}
else
{
this->resize(pixmap.width() + 2, pixmap.height() + 2);
}
QPainter painter(this);
painter.setFont(m_font);
if(m_containPixmap)
{
QRect rect((this->width()-pixmap.width())/2, 1, pixmap.width(), pixmap.height());
painter.drawPixmap(rect, pixmap);
}
painter.setPen(m_penColor);
if(m_containText)
{
painter.drawText(QRect((this->width() -wid) /2, pixmap.height() + 2, wid, h), m_text);
}
if(m_isPress)
{
painter.fillRect(this->rect(), QColor(240, 240, 240, 60));
}
}
void DPushButton::mousePressEvent(QMouseEvent* e)
{
if(m_containText && !m_containPixmap)
{
return QPushButton::mousePressEvent(e);
}
m_isPress = true;
repaint();
emit pressed();
}
void DPushButton::mouseReleaseEvent(QMouseEvent* e)
{
if(m_containText && !m_containPixmap)
{
return QPushButton::mouseReleaseEvent(e);
}
m_isPress = false;
repaint();
emit clicked();
emit released();
}
<file_sep>#ifndef DPUSHBUTTON_H
#define DPUSHBUTTON_H
#include "dpushbutton_global.h"
#include <QPushButton>
class DPUSHBUTTONSHARED_EXPORT DPushButton : public QPushButton
{
public:
explicit DPushButton(QWidget* parent = Q_NULLPTR);
explicit DPushButton(const QString &text, QWidget* parent = Q_NULLPTR);
explicit DPushButton(const QPixmap &pixmap, QWidget* parent = Q_NULLPTR);
explicit DPushButton(const QPixmap &pixmap, const QString &text, QWidget* parent = Q_NULLPTR);
void setPixmapScale(double i);
void setPixmap(const QPixmap &pixmap);
void setTextColor(const QColor &color);
void setTextFont(const QFont &font);
void setText(const QString& text);
protected:
void paintEvent(QPaintEvent *event);
void mousePressEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
private:
QString m_text;
QPixmap m_pixmap;
QColor m_penColor;
QFont m_font;
float m_size;
bool m_containText;
bool m_containPixmap;
bool m_isPress;
};
#endif // DPUSHBUTTON_H
<file_sep># 自定义Qt 按钮
## 1、修改日志
| 编号 | 内容 | 时间 |
| :--: | :----------------------------------------------------------: | :-------: |
| 1 | 第一次创建提交。DPushButton继承自QPushButton类,可以以图片的形式显示按钮,也可以以文字的形式显示按钮。 | 2019.7.16 |
| | | |
| | | |
## 2、接口说明
*日期:2019.7.16*
提供接口:
```c++
void setPixmapScale(double i); //设置按钮显示大小相对于图片的比例。
void setPixmap(const QPixmap &pixmap);
void setTextColor(const QColor &color);
void setTextFont(const QFont &font);
void setText(const QString& text);
```
| 5335aec118ea53900cff531f4f34c2bb705bc9cc | [
"Markdown",
"C",
"C++"
] | 4 | C | xiaoduge/DPushButton | 1a54cfc11a3afbea0c597e72852590acaaa1128e | 7c686e761a4af02953422f43b180d8d530587c6a |
refs/heads/master | <file_sep>
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class RequestHeaderDemoServlet
*/
public class RequestHeaderDemoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public RequestHeaderDemoServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
Enumeration e = request.getHeaderNames();
while(e.hasMoreElements()){
out.println(e.nextElement().toString()+"...."+request.getHeader(e.nextElement().toString()));
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
<file_sep>
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class SecondServlet
*/
public class SecondServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public SecondServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
out.println("getParameter Demo");
String uname = request.getParameter("uname");
String ucontact = request.getParameter("ucontact");
String ucourse = request.getParameter("ucourse");
out.println("Student Name: "+uname);
out.println("Student Contact: "+ucontact);
out.println("Student Course: "+ucourse);
out.println("GetParameter values");
String[] values = request.getParameterValues("ucourse");
for(String s:values){
out.println("s");
}
out.println("GetParameterNames Demo");
Enumeration names = request.getParameterNames();
while(names.hasMoreElements()){
out.println((String)names.nextElement());
}
out.println("getParameterMap Demo");
Map<String,String[]> map = request.getParameterMap();
Set s = map.entrySet();
Iterator i = s.iterator();
while(i.hasNext())
{
Map.Entry m1 = (Map.Entry)i.next();
out.println(m1.getKey());
String[] s1 = request.getParameterValues(m1.getKey().toString());
for(String s2:s1){
out.println(s2);
}
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
| 2cbc6638d9ac5ad2fec90c2b782da545ed404a4c | [
"Java"
] | 2 | Java | dmarepalli/Http-Servlet-Demo | c019545f8f61616c1059f5239e7af406fcd494b4 | 049e934917861629a03f517bb8cafb8415bf8a64 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EPMTools.RBSResources.EPMRepository.Entities
{
public class User
{
public string Name { get; set; }
public string LoginName { get; set; }
public string Email { get; set; }
public bool IsActive { get; set; }
public string RBS { get; set; }
public string RBSInternalName { get; set; }
public Guid ID { get; internal set; }
}
}
<file_sep>using EPMTools.RBSResources.EPMRepository;
using EPMTools.RBSResources.EPMRepository.Entities;
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 EPMTools.RBSResources.WindowsApp
{
public partial class RBSTree : Form
{
public static List<User> Users = new List<User>();
public static List<Node> nodes = new List<Node>();
public Utilities pwaUtilities = null;
public bool isConnected = false;
public RBSTree()
{
InitializeComponent();
}
private void AddNodes(IList<Node> nodes, TreeNodeCollection collection)
{
foreach (var node in nodes)
{
TreeNode collnode = new TreeNode();
collnode.Tag = node.ID;
collnode.Text = node.Text;
collnode.Name = node.FullText;
if (node.SubNodes.Count > 0)
AddNodes(node.SubNodes, collnode.Nodes);
collection.Add(collnode);
}
}
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
var node = nodes.Where(n => n.ID == (Guid)e.Node.Tag).SingleOrDefault();
if (node != null)
{
dataGridView1.DataSource = Users.Where(u => u.RBSInternalName == node.Internalname).ToList();
}
}
private void button1_Click(object sender, EventArgs e)
{
treeView1.Nodes.Clear();
Loading loadingWindow = new Loading();
loadingWindow.Show(this);
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += (s, args) =>
{
this.Invoke(new MethodInvoker(() => this.Enabled = false));
try
{
RBSTree.Users = pwaUtilities.GetResources();
RBSTree.nodes = pwaUtilities.GetNodes();
foreach (var item in RBSTree.nodes)
{
item.SubNodes = RBSTree.nodes.Where(n => n.ParentID == item.ID).ToList();
item.Users = RBSTree.Users.Where(u => u.RBSInternalName == item.Internalname).ToList();
}
}
catch (Exception ex)
{
MessageBox.Show($"Error: {ex.Message}", "Error Occured", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
};
bw.RunWorkerCompleted += (s, args) =>
{
loadingWindow.Close();
AddNodes(nodes.Where(n => n.ParentID == Guid.Empty).ToList(), treeView1.Nodes);
this.Invoke(new MethodInvoker(() => { this.Enabled = true; }));
};
bw.Disposed += (s, args) =>
{
};
bw.RunWorkerAsync();
}
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
var user = ((sender as DataGridView).DataSource as List<EPMTools.RBSResources.EPMRepository.Entities.User>).ElementAtOrDefault(e.RowIndex);
if (user != null)
{
Loading loadingWindow = new Loading();
loadingWindow.Show(this);
UserMembership userMembershipWindow = new UserMembership();
var groups = pwaUtilities.GetUserSharepointGroupGroups(user.ID);
userMembershipWindow.dgvUserGroups.DataSource = groups;
var PSGroups = pwaUtilities.GetProjectServerGroups(user.ID);
userMembershipWindow.dgvPSGroups.DataSource = PSGroups;
userMembershipWindow.ShowDialog();
loadingWindow.Close();
}
}
private void btnConnect_Click(object sender, EventArgs e)
{
Loading loadingWindow = new Loading();
loadingWindow.Show(this);
if (!isConnected)
{
pwaUtilities = new Utilities(txtPwaUrl.Text.Trim(), txtUsername.Text.Trim(), txtPassword.Text.Trim(), txtDomain.Text.Trim());
pwaUtilities.Connect();
isConnected = true;
txtDomain.Enabled = txtPassword.Enabled = txtPwaUrl.Enabled = txtUsername.Enabled = false;
}
else
{
pwaUtilities = null;
isConnected = false;
txtDomain.Enabled = txtPassword.Enabled = txtPwaUrl.Enabled = txtUsername.Enabled = true;
}
loadingWindow.Close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EPMTools.RBSResources.EPMRepository.Entities
{
public class Node
{
public Node()
{
SubNodes = new List<Node>();
Users = new List<User>();
}
public Guid ID { get; set; }
public Guid ParentID { get; set; }
public int Level { get; set; }
public string Text { get; set; }
public string FullText { get; set; }
public string Discription { get; set; }
public IList<Node> SubNodes { get; set; }
public IList<User> Users { get; set; }
public string Internalname
{
get
{
return $"Entry_{ID.ToString().Replace("-", "").ToLower()}";
}
}
}
}
<file_sep>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 EPMTools.RBSResources.WindowsApp
{
public partial class UserMembership : Form
{
public UserMembership()
{
InitializeComponent();
}
}
}
<file_sep>using EPMTools.RBSResources.EPMRepository.Entities;
using Microsoft.ProjectServer.Client;
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace EPMTools.RBSResources.EPMRepository
{
public class Utilities
{
private ProjectContext context = null;
private PSI.Services.SecurityService secService = null;
private PSI.Services.ResourceService resService = null;
public Utilities(string pwaUrl, string username, string password, string domain)
{
context = new ProjectContext(pwaUrl);
context.Credentials = new NetworkCredential(username, password, domain);
secService = new PSI.Services.SecurityService(pwaUrl, username, password, domain);
resService = new PSI.Services.ResourceService(pwaUrl, username, password, domain);
}
public List<Entities.User> GetResources()
{
List<Entities.User> users = new List<Entities.User>();
try
{
context.Load(context.EnterpriseResources,
rs => rs.IncludeWithDefaultProperties(r => r.Name, r => r.Email, r => r.IsActive, r => r.User, r => r.User.LoginName, r => r.CustomFields));
context.ExecuteQuery();
foreach (var item in context.EnterpriseResources)
{
if (item != null && !item.ServerObjectIsNull.Value)
{
var user = new Entities.User();
user.Email = item.Email != null ? item.Email : "";
if (item.User != null && item.User.ServerObjectIsNull.HasValue && !item.User.ServerObjectIsNull.Value)
user.LoginName = item.User.LoginName;
user.IsActive = item.IsActive;
user.Name = item.Name != null ? item.Name : "";
user.ID = item.Id;
var cf = item.CustomFields.Where(c => c.Name.ToLower() == "rbs").SingleOrDefault();
if (cf != null)
{
string internalName = ((String[])item.FieldValues.Where(f => f.Key == cf.InternalName).Single().Value)[0];
user.RBSInternalName = internalName;
}
users.Add(user);
}
}
}
catch (Exception ex)
{
}
return users;
}
public List<Node> GetNodes()
{
List<Node> nodes = new List<Node>();
var ltRBS = context.LoadQuery(context.LookupTables
.IncludeWithDefaultProperties(r => r.Name, r => r.Entries,
r => r.Entries.IncludeWithDefaultProperties(e => ((LookupText)e).Parent, e => ((LookupText)e).Parent.Id))
.Where(l => l.Name == "RBS"));
context.ExecuteQuery();
if (ltRBS.Count() > 0)
{
foreach (LookupText item in ltRBS.First().Entries)
{
if (item.Parent.ServerObjectIsNull.HasValue && item.Parent.ServerObjectIsNull.Value)
{
nodes.Add(new Node()
{
ID = item.Id,
ParentID = Guid.Empty,
Discription = item.Description,
Text = item.Value,
FullText = item.FullValue
});
}
else
{
nodes.Add(new Node()
{
ID = item.Id,
ParentID = item.Parent.Id,
Discription = item.Description,
Text = item.Value,
FullText = item.FullValue
});
}
}
}
return nodes;
}
public List<Entities.Group> GetUserSharepointGroupGroups(Guid userID)
{
List<Entities.Group> groups = new List<Entities.Group>();
EnterpriseResource resource = context.EnterpriseResources.GetByGuid(userID);
context.Load(resource, r => r.User, r => r.User.Groups, r => r.User.Groups.IncludeWithDefaultProperties(g => g.LoginName), r => r.Group, r => r.Id);
context.ExecuteQuery();
if(!resource.ServerObjectIsNull.Value)
{
foreach (var item in resource.User.Groups)
{
Entities.Group group = new Entities.Group();
group.ID = item.Id;
group.Name = item.Title;
groups.Add(group);
}
}
return groups;
}
public List<Entities.Group> GetProjectServerGroups(Guid UserID)
{
var resAuth = resService.GetResource(UserID);
List<Guid> groupsIDs = resAuth.GroupMemberships.Select(g => g.WSEC_GRP_UID).ToList();
return secService.GetGroups(groupsIDs);
}
public void Connect()
{
EnterpriseResource res = EnterpriseResource.GetSelf(context);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EPMTools.RBSResources.EPMRepository.Entities
{
public class Group
{
public int ID { get; internal set; }
public string Name { get; internal set; }
public Guid UniqueID { get; internal set; }
}
}
<file_sep># EMPTools-RBSResources
RBSResources is a simple tool I have created to help me tracking resources accross RBS in MS Project Server.
The tool utilizes Project Server CSOM (Client Side Object Model) and PSI (Project Server Interface), and tested on Microsoft Project Server 2013.
## Usage
- Enter PWA link, username, password, and domain for user with admin permission (or permission allow the user to access admin settings)
- Click "Connect/Disconnect" button to initiate project server context
- Click "Get RBS Tree" to fetch RBS and map resources
- Doule-click on resource to get resource's membership
- Project Server Groups
- Sharepoint Groups
## Credits
created by <NAME> [github](//github.com/hdahamsheh), [twitter](//twitter.com/dohmosh)
## License
Released under the [MIT License](http://www.opensource.org/licenses/mit-license.php)
| ac878aae5b15d194c3cff3a5966bc3bacaea520e | [
"Markdown",
"C#"
] | 7 | C# | hdahamsheh/EMPTools-RBSResources | 55f1e1f1781c559010e81150313101ee02ff6b00 | 648886ce41f0778924220e97bda9f9880e1dfe01 |
refs/heads/master | <repo_name>seburban/cheesecake<file_sep>/cfg.php
<?php
$cfg = array(
//'home' => 'http://www.facebook.com/pages/TCS-Sample/123038897767082',
'home' => 'http://www.facebook.com/thecheesecakeshop',
'base' => 'http://fb.seburban.com/cheesecake',
);
$cfg['storebase'] = $cfg['base'].'/store';
$cfg['quizbase'] = $cfg['base'].'/quiz';
$cfg['storevanity'] = 'http://apps.facebook.com/tcsstorelocator/';
$cfg['quizvanity'] = 'http://apps.facebook.com/cheesecakeshopquiz/';
$cfg['promourl'] = 'http://www.cheesecake.com.au/family';
<file_sep>/quiz/index.php
<?php
require '../../facebook-php-sdk/src/facebook.php';
require '../cfg.php';
$facebook = new Facebook(array(
'appId' => '179312528760904',
'secret' => 'a30cf8ff196e915851e75902661c0f37',
'cookie' => true,
));
$session = $facebook->getSession();
?>
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:og="http://opengraphprotocol.org/schema/"
xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>API Sample</title>
<meta property="og:title" content="" />
<meta property="og:type" content="" />
<meta property="og:url" content="" />
<meta property="og:image" content="" />
<meta property="og:site_name" content="" />
<meta property="og:description" content="" />
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/3.2.0/build/cssreset/reset-min.css">
<style>
body { font-family: Verdana, Arial, sans-serif; color:#000;}
h1 { border-bottom: 1px solid #ccc; padding-bottom:5px; line-height:110%; font-weight:bold;font-size:21px; margin:20px 4px 3px 0}
h2 {margin: 10px 4px 3px 0; font-size:18px}
li { list-style: none; margin-bottom:5px}
a {font-size:11px; color:#3B5998; text-decoration:none}
a:hover {text-decoration:underline}
#quiz { position:absolute; min-width:620px; max-width:750px; margin-top:10px }
#quiz .ans:hover {background-color:#C3E5C0;cursor:pointer;}
#quiz .ans {padding: 10px 0; margin:20px 0;}
#quiz .ans span {/*padding-left: 10px*/}
#quiz .ans img { width:50px; height:50px; vertical-align:-55%; padding:0 0 0 10px;}
.content-pane {max-width:760px;}
#quiz .fb { padding:5px 0;}
#quiz .like iframe {display:inline; height:23px; margin-top:5px}
#quiz .title h3 { font-weight:bold; float:left; margin-right:30px; color:#008000; font-size:150%;}
#quiz .img { width:250px; height:187px; float:left; margin-right:10px}
#resimg {border: 1px solid #008000;}
#quiz .desc-inner { display:inline;}
#quiz .desc { min-height:200px}
#quiz .foot li { margin:0 0 0 10px; padding:3px 10px; display:inline; background-color:#d8dfea; color:#3b5998; cursor:pointer; font-size:13px}
#quiz .foot li:hover {background-color: #627aad; color:#fff }
#quiz .foot ul { text-align:center; }
#fb_multi_friend_selector {margin:0}
#fltr {/*width:165px; */height:275px; position:relative;float:right;margin-right:-70px;margin-top:70px}
.cta {margin-top:10px; font-size:13px; font-weight: bold}
.black_overlay{ display: none; position: absolute; left: 35px; top:35px;width: 650px; height: 582px; background-color: black; z-index:1001; -moz-opacity: 0.5; opacity:.50; filter: alpha(opacity=50); }
</style>
</head>
<body>
<div id="fb-root"></div>
<div class="content-pane">
<div style="float:right;margin:-20px 10px 0 0">
<a href="<?php echo($cfg['home']);?>" target="_top"><img src="http://www.cheesecake.com.au/sites/all/themes/tcs/images/TCSLogo.png" width="70px"></a>
<div style="margin:-8px 0 0 10px; text-align:center"><a href="<?php echo($cfg['home']);?>" target="_top">Home</a></div>
</div>
<h1> What's Your Flavour?</h1>
<div id="quiz"></div>
<img src="" id="fltr"/>
</div>
<div id="hresult" style="display:none">
<div class="fb title"><h3 id="title_text"></h3><div class="like" id="likeobj"></div></div>
<div class="fb desc">
<img src="" class="img" id="resimg">
<div class="fb desc-inner" id="desc_text"> </div>
<div class="fb cta"><a href="<?php echo($cfg['promourl']);?>" target="_blank">Click here to receive a $5 Off Voucher from The Cheesecake Shop!</a></div>
</div>
<div class="fb foot">
<ul>
<li id="publish">Publish To My Wall</li>
<li id="again">Play Again</li>
<li id="back">Back to The Cheesecake Shop</li>
</ul>
</div>
</div>
<div class="black_overlay" id="fade"></div>
<script src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId : '<?php echo $facebook->getAppId(); ?>',
session : <?php echo json_encode($session); ?>,
status : true,
cookie : true,
xfbml : true // I have to use FBML, FML
});
FB.Event.subscribe('auth.login', function() {// this is buggy and poorly documented
// window.location.reload();
});
var Home = '<?php echo($cfg['home']);?>';
//var ImgBase = 'http://www.cheesecake.com.au/sites/default/files';
var ImgBase = 'http://www.cheesecake.com.au/fb';
var Question = function(n,o,q){
this.main_canvas = document.createElement('div');
this.question_canvas = document.createElement('div');
this.answer_canvas = document.createElement('ul');
this.name = n
this.options = o;
this.quiz = q;
return this;
};
Question.prototype.toHTML = function(cb){
var that = this;
var answers = that.options;
for (var i=0;i<answers.length;i++){
var li = document.createElement('li');
$(li).click(function(){cb.call(that.quiz,this)});
$(li).addClass('ans');
var option = document.createElement('input');
option.type = 'radio';
$(option).css('display','none');
option.value = answers[i].result;
var label = document.createElement('span');
label.appendChild(document.createTextNode(answers[i].label));
// var img = document.createElement('img');
// img.src = (answers[i].img == null)?'throw_cake.gif':answers[i].img;
li.appendChild(option);
// li.appendChild(img);
li.appendChild(label);
that.answer_canvas.appendChild(li);
}
var question_name = document.createElement('h2');
question_name.appendChild(document.createTextNode(that.name));
that.question_canvas.appendChild(question_name);
that.main_canvas.appendChild(that.question_canvas);
that.main_canvas.appendChild(that.answer_canvas);
return that.main_canvas;
}
var Result = function(n,d,i,l){
this.name = n;
this.description = d;
this.img = i;
this.html = document.getElementById('hresult');
$('#title_text').html(this.name);
$('#desc_text').html(this.description);
$('#resimg').attr('src',this.img);
$('#resimg').attr('alt',l+': '+this.name);
$('#likeobj').html(this.like());
$('#publish').click(this,function(e){
e.data.publish();
});/*
$('#publish-invite').click(function(){
var i = document.createElement('div');
$(i).css({'position':'absolute', 'left':'50px', 'z-index':'1002'});
i.appendChild(document.getElementById('invite'));
document.getElementsByTagName('body')[0].appendChild(i);
$('#invite').css('display','inline');
$('.black_overlay').css('display','block')
});*/
$('#again').click(function(){window.location.reload()});
$('#back').click(function(){parent.location.href=Home});
$(this.html).css("display","inline");
return this;
};
Result.prototype.toHTML = function(){
return this.html;
}
Result.prototype.like = function(){
return '<iframe src="http://www.facebook.com/plugins/like.php?href=<?php echo(urlencode($cfg['home']));?>&layout=standard&show_faces=false&width=450&action=like&font=verdana&colorscheme=light&height=35" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:23px;" allowTransparency="true"></iframe>'; // FB APIs are clumsy
};
Result.prototype.publish = function(){
var msg = "I took The Cheesecake Shop's 'What's Your Flavour?' quiz and it turns out that I'm "+
getPrep(this.name)+" "+this.name+"!\nTake the quiz and receive your $5 voucher "+
"when you Join Mamuska's Family";
try {
FB.ui({
app_id: '<?php echo($facebook->getAppId());?>',
method: 'feed',
message: msg,
link: Home,
picture: this.img,
description: this.description
});
} catch (e) {}
};
var Quiz = function(canvas){
// The quiz canvas
this.canvas = canvas;
// Current question index
this.index;
// Array of user choices
this.user_selection;
// Current question object
this.current_question;
// The result of the users choices
this.user_result;
// List of questions
this.question;
// List of answers for each question, including result mappings
this.answer;
// List of possible results
this.result;
// event handlers change 'this' scope
var that = this;
// Observe changes to quiz state and act appropriately
$(this.canvas).bind('update',function(e,c){
that.clearCanvas(); // that == quiz object
this.appendChild(c); // this == subject of triggered event (DOMNode)
that.show();
});
this.initialise();
return true;
};
Quiz.prototype.handleOptionSelect = function(o){
if (this.index == 0) { // clumsy, but does the job
this.user_selection['cake'].push(o.getElementsByTagName('input')[0].value);
} else {
this.user_selection['flavour'].push(o.getElementsByTagName('input')[0].value);
}
if (this.index < (this.question.length-1)){
this.index++;
this.nextQuestion();
} else {
this.showResult();
}
};
Quiz.prototype.nextQuestion = function(){
$('#fltr').attr('src',this.fltimage[this.index]);
this.current_question = new Question(this.question[this.index],this.answer[this.index],this);
// Quiz state has changed
$(this.canvas).trigger('update',[this.current_question.toHTML(this.handleOptionSelect)]);
};
Quiz.prototype.showResult = function(){
var ai = this.getMax(this.user_selection['cake'],this.result['cake'].length);
var bi = this.getMax(this.user_selection['flavour'],this.result['flavour'].length);
var a = this.result['cake'][ai].types[bi];
var b = this.result['flavour'][bi];
var l = this.result['flavour'][bi].label+' '+this.result['cake'][ai].label
this.user_result = new Result(a.label,b.description,a.img,l);
$('#fltr').css('display','none');
// Quiz state has changed
$(this.canvas).trigger('update',[this.user_result.toHTML()]);
// meh
this.user_result.publish();
};
Quiz.prototype.getMax = function(sel,len){
var t = {}; var y = 0;
for (var i=1;i<=len;i++){ t[i]=0; }
for (i=0;i<len;i++){ t[parseInt(sel[i])]++; }
for (i in t){ y=(t[i]>y)?i:y; }
return(y-1);
}
Quiz.prototype.hide = function(){
$(this.canvas).hide();
$(this.canvas).css("left","500px");
};
Quiz.prototype.show = function(){
$(this.canvas).animate({"left":"0", "opacity":"show"},"fast");
};
Quiz.prototype.clearCanvas = function(){
this.hide();
this.canvas.innerHTML = '';
};
Quiz.prototype.initialise = function(){
this.clearCanvas();
this.index = 0;
this.user_selection = {cake:[],flavour:[]};
this.current_question = null;
this.user_result = null;
this.fltimage = [
'mam_bowl_t.png',
'mam_cake_t.png',
'mam_hands_t.png',
'mam_hands_behind_t.png',
'mam_kiss_t.png'
];
$(this.fltimage).preload();
this.question = [
"Which best describes the inner you?",
"Which best describes what people see in you?",
"What is your perfect outfit?",
"How would you describe your perfect evening?",
"Your dream job is..."
];
this.answer = [
[{result:1, label:'Layers of personality', description:'', img:null},
{result:2, label:'Light and fluffy', description:'', img:null},
{result:3, label:'Soft and sweet', description:'', img:null},
{result:4, label:'Smooth and strong', description:'', img:null},
{result:5, label:'Firm and furious', description:'', img:null} ],
[{result:1, label:'Cool calm and collected', description:'', img:null},
{result:2, label:'Bright and chirpy', description:'', img:null},
{result:3, label:'Loyal and honest', description:'', img:null},
{result:4, label:'A go getter, Non stop', description:'', img:null},
{result:5, label:'Go with the flow', description:'', img:null}],
[{result:1, label:'I don\'t like to stand out, so something casual', description:'', img:null},
{result:2, label:'A nice outfit with soft colours', description:'', img:null},
{result:3, label:'Classic look, I\'m always in trend', description:'', img:null},
{result:4, label:'I like to be right on the fashion edge', description:'', img:null},
{result:5, label:'The first thing I see that is clean', description:'', img:null}],
[{result:1, label:'A DVD, my sofa and pyjamas', description:'', img:null},
{result:2, label:'Partying with friends', description:'', img:null},
{result:3, label:'Dinner by candlelight with my partner', description:'', img:null},
{result:4, label:'Getting that extra work done', description:'', img:null},
{result:5, label:'A BBQ with your besties', description:'', img:null}],
[{result:1, label:'Homemaker', description:'', img:null},
{result:2, label:'Anything outdoors', description:'', img:null},
{result:3, label:'Professional corporate climber', description:'', img:null},
{result:4, label:'Wealthy entrepreneur', description:'', img:null},
{result:5, label:'Independently wealthy thrill seeker', description:'', img:null}]
];
this.result = {};
this.result['cake'] = [
{label:"Torte", types:[
{label:"Profiterole Torte", img:ImgBase+'/r1-1.png'},
{label:"Tropical Torte", img:ImgBase+'/r1-2.png'},
{label:"Double Choc Strawberry Torte", img:ImgBase+'/r1-3.png'},
{label:"Black Forest", img:ImgBase+'/r1-4.png'},
{label:"Enchanted Forest", img:ImgBase+'/r1-5.png'}
]},
{label:"Pavlova", types:[
{label:"Tea Cake", img:ImgBase+'/r2-1.png'},
{label:"Apple Strudel", img:ImgBase+'/r2-2.png'},
{label:"Marble Baked", img:ImgBase+'/r2-3.png'},
{label:"Lemon Meringue", img:ImgBase+'/r2-4.png'},
{label:"Pavlova", img:ImgBase+'/r2-5.png'}
]},
{label:"Continental", types:[
{label:"French Vanilla", img:ImgBase+'/r3-1.png'},
{label:"Passionfruit", img:ImgBase+'/r3-2.png'},
{label:"Choc Chip", img:ImgBase+'/r3-3.png'},
{label:"Tangy Lemon", img:ImgBase+'/r3-4.png'},
{label:"Strawberry", img:ImgBase+'/r3-5.png'}
]},
{label:"Baked", types:[
{label:"American Baked Cheesecake", img:ImgBase+'/r4-1.png'},
{label:"Tropical Glazed", img:ImgBase+'/r4-2.png'},
{label:"Caribbean Dream", img:ImgBase+'/r4-3.png'},
{label:"Lemon Meringue Baked Cheesecake", img:ImgBase+'/r4-4.png'},
{label:"Wildberry Baked Cheesecake", img:ImgBase+'/r4-5.png'}
]},
{label:"Mudcake", types:[
{label:"White Gold Mudcake", img:ImgBase+'/r5-1.png'},
{label:"Fruit Flan", img:ImgBase+'/r5-2.png'},
{label:"Boston Mudcake", img:ImgBase+'/r5-3.png'},
{label:"Caramel Mudcake", img:ImgBase+'/r5-4.png'},
{label:"Strawberry Glazed Cheesecake", img:ImgBase+'/r5-5.png'}
]}
]; //cake
this.result['flavour'] = [ //flavour
{label:'Vanilla', description: "You're a fairly normal individual who is the salt of the earth; you like to know that everything is in its place and you know which place is yours. You're happy with your lot and don't see what so many people make a fuss about, they are just self obsessed or searching for something that simply isn't there as far as you're concerned. Be happy because almost everyone likes you and you're hard to resist at any occasion."},
{label:'Fresh Fruit', description: "You're light, bright sunny and a little bit fruity. You're always up for a good time and you're in everyone's 'lets go party' list. You get along with people and don't have much time for the more dark miserable types. You bring a ray of sunshine to others' lives, and others look to you to bring on the good times."},
{label:'Chocolate', description: "You're dark rich and a little bit dreamy, you have a shiny of edginess about you that makes you intriguing to others, and like chocolate, you have a personality that is hard to resist. Lay back in the comfort that you will always be in style with your excellent taste and people know you as a stylish and seductive individual."},
{label:'Lemon', description: "You're bright light and zingy, you know what you want and just how to go and get it. You aren't afraid of hard work and are capable at almost anything you set your mind to. People know you as having a sharp humor with a serious side when you need it, but you're generally the life of the party - when you see fit!"},
{label:'Berry', description: "You're popular with a hint of spice to your personality. People generally find you agreeable and you're fairly easy going. You don't like a lot of fuss and find your own path in life without too many complications."}
];
$('#hresult').css('display','none');
};
function getPrep(str){
var p = 'a';
if ((typeof str != 'string')||str.length < 1){
return p;
}
var o = str.substr(0,1).toLowerCase();
switch(o){
case 'a': case 'e': case 'i': case 'o': case 'u':
p = 'an'; break;
default:
p = 'a'; break;
}
return p;
}
$.fn.preload = function() {
this.each(function(){
$('<img/>')[0].src = this;
});
}
var q = new Quiz(document.getElementById('quiz'));
q.nextQuestion();
</script>
</body>
</html>
<?php
/*
<div id="invite" style="display:none">
<fb:serverFbml width="620px">
<script type="text/fbml">
<fb:fbml>
<fb:request-form method='POST' invite=true
action='<?php //echo($cfg['quizbase']);?>/done.php'
type='The Cheesecake Shop - What Flavour Are You?'
content='Find Out What Flavour Your Friends Are'>
<fb:multi-friend-selector cols=4
actiontext="Find Out What Flavour Your Friends Are"
/>
</fb:request-form>
</fb:fbml>
</script>
</fb:serverFbml>
</div>
*/
?>
<file_sep>/promo/tab.php
<?php
require '../cfg.php';
?>
<a href="<?php echo($cfg['promourl']);?>" target="_blank"><img src="http://www.cheesecake.com.au/sites/all/themes/tcs/TCS1532v2.jpg" width="522"></a>
<file_sep>/quiz/done.php
<?php
require '../cfg.php';
?>
<style type="text/css">
body {color:#FFF; font-size:11px; text-decoration:none; font-family:verdana,arial}
li:hover {text-decoration:none; background-color: #627aad; color:#fff }
li { margin:0 0 0 10px; padding:3px 10px; display:inline; background-color:#d8dfea; color:#3b5998; cursor:pointer; font-size:13px}
h1 {color:#4f4f4f}
</style>
<div style="width:522px; text-align:center">
<div style="margin:auto"><img src="http://www.cheesecake.com.au/sites/all/themes/tcs/images/TCSLogo.png" style="border:none;text-decoration:none"><br />
<h1>Thank You For Playing</h1>
<ul><li onClick="window.location.href='<?php echo($cfg['quizbase']);?>'">Play Again</li><li onClick="parent.location.href='<?php echo($cfg['home']);?>'">Go Back to The Cheesecake Shop</li></ul></div>
</div>
<file_sep>/quiz/tab.php
<?php
require '../cfg.php';
?>
<style type="text/css">
a:hover {text-decoration:none}
.fbsubmit { background-color:#3B5998;color:#FFF; border:1px solid #3B5998;cursor:pointer}
</style>
<div style="width:522px; text-align:center">
<div style="margin:auto">
<!--form id="quizform" action="<?php //echo($cfg['quizvanity']);?>" method="get"><img src="http://www.cheesecake.com.au/sites/all/themes/tcs/images/TCSLogo.png" style="border:none;text-decoration:none"><br />
<fb:submit form="quizform"><input type=submit value="Take the quiz now" class="fbsubmit" /></fb:submit></form-->
<a href="<?php echo($cfg['quizvanity']); ?>"><img src="http://fb.seburban.com/cheesecake/quiz/tcs-quiz-splash.jpeg" width="518px" height="587px" /></a>
</div>
</div>
<file_sep>/store/index.php
<?php
require '../../facebook-php-sdk/src/facebook.php';
require '../cfg.php';
$address=@$_GET['address'];
$signed_request = @$_GET['signed_request'];
if ($signed_request){
showStoreLocator($address);
} else {
echo '
<style type="text/css">
#bg { background-image:url("'.$cfg['storebase'].'/bg.png?v=8"); background-repeat:no-repeat; height:502px}
#cp {padding:60px 34px; font-family: verdana;}
#btnsubmit { background-color:#3B5998;color:#FFF; border:1px solid #3B5998;cursor:pointer}
.textaddress { width:188px}
</style>
<div id="bg">
<div id="cp">
<!-- Finding your local The Cheesecake Shop bakery is usually a simple matter of following the aroma
of freshly baked cakes and goodies - or you can just enter your postcode below and click search. -->
<form id="storelocatorform" action="'.$cfg['storevanity'].'" method="get"><strong>Enter your suburb or postcode:</strong> <input type="text" name="address" value="" class="textaddress"/> <fb:submit form="storelocatorform"><input type="submit" value="Search" id="btnsubmit" /> </fb:submit> </form>';
echo '</div></div>';
}
function showStoreLocator($address){
global $cfg;
$facebook = new Facebook(array(
'appId' => '179312528760904',
'secret' => 'a30cf8ff196e915851e75902661c0f37',
'cookie' => true
));
$session = $facebook->getSession();
$pageurl = $cfg['pageurl'];
echo '<!doctype html>
<html> <head>
<title>Store Locator | The Cheesecake Shop</title>
<link rel="shortcut icon" href="http://www.cheesecake.com.au/sites/all/themes/tcs/images/tcs-ico.png" type="image/x-icon" />
<link type="text/css" rel="stylesheet" media="all" href="http://www.cheesecake.com.au/sites/default/files/css/css_daf7f19d84a8b5d8e25a979b2864f711.css" />
<link type="text/css" rel="stylesheet" media="print" href="http://www.cheesecake.com.au/sites/default/files/css/css_a75ab5a8734eb67f2db98decc01c2ce2.css" />
<script type="text/javascript" src="http://www.cheesecake.com.au/misc/jquery.js?Q"></script>
<script type="text/javascript" src="http://www.cheesecake.com.au/misc/drupal.js?Q"></script>
<script type="text/javascript" src="http://www.cheesecake.com.au/sites/all/themes/tcs/swap-images.js?Q"></script>
<script type="text/javascript" src="http://www.cheesecake.com.au/sites/all/themes/tcs/script.js?Q"></script>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
jQuery.extend(Drupal.settings, { "basePath": "/cheesecake/store/", "googleanalytics": { "trackOutgoing": 1, "trackMailto": 1, "trackDownload": 1, "trackDownloadExtensions": "7z|aac|avi|csv|doc|exe|flv|gif|gz|jpe?g|js|mp(3|4|e?g)|mov|pdf|phps|png|ppt|rar|sit|tar|torrent|txt|wma|wmv|xls|xml|zip" } });
//--><!]]>
</script>
<style type="text/css">
.fback {text-align:left; background-color:#d8dfea; width:220px;margin:10px 10px 10px 28px; padding:4px; color: #3b5998; cursor:pointer;}
.fback:hover { background-color:#627aad; color:#FFF}
#bg { background-image:url("'.$cfg['storebase'].'/bgmain.png?v=2"); background-repeat:no-repeat; height:650px; width:758px;}
#cp {padding:60px 20px; font-family: verdana; text-align:center}
#btnsubmit { background-color:#3B5998;color:#FFF; border:1px solid #3B5998;cursor:pointer}
body {background-image:none; font-family:verdana,arial; font-size:13px}
#title { font-weight:bold;position:absolute;top:20px;left:320px; color:#FFF}
</style>
</head>
<body>
<div id="title">STORE LOCATOR</div>
<div id="bg">
<div id="fb-root"></div>
<div id="cp">
<div class="fback" onClick="javascript:parent.location.href=\''.$cfg['home'].'\'">< Back to The Cheesecake Shop</div>
<!--Finding your local The Cheesecake Shop bakery is usually a simple matter of following the aroma <br />
of freshly baked cakes and goodies - or you can just enter your postcode or suburb below and click search. <br /> -->
<br />
<form action="#" onsubmit="showAddress(this.address.value); return false">
<strong>Enter your suburb or postcode:</strong> <input type="text" size="40" id="address" name="address" value="'.$address.'" /> <input type="submit" value="Search" id="btnsubmit"/>
</form>
<br />
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=AB<KEY>" type="text/javascript"></script>
<div id="map_canvas" style="border: 4px solid green; position: relative; height: 423px; float: left; width: 560px;margin-left:72px;"> </div> </div>
<!--div class="clear-block">
<div class="meta">
</div>
</div-->
</div>
<script src="http://connect.facebook.net/en_US/all.js" type="text/javascript"></script>
<script type="text/javascript">
$(window).load(function(){
FB.init({ appId : "'.$facebook->getAppId().'", xfbml : true });
var a = document.getElementById("address");
if (a.value != ""){
showAddress(a.value);
}});
</script>
</body>
</html>';
};
?>
| 74e0848c516c68581b796f65972499a48b30446d | [
"PHP"
] | 6 | PHP | seburban/cheesecake | 416ed8dfa8f245933ce72ac483204aaf9418234d | ab2a55660f114633341dd1914a6a0d9506727385 |
refs/heads/master | <repo_name>Aspectize/HackerNews<file_sep>/HackerNews/Services/ClientService.js
Global.ClientService = {
aasService: 'ClientService',
MainData: 'MainData',
aasCommandAttributes: {
DisplayUser: { CanExecuteOnStart: true },
DisplayItem: { CanExecuteOnStart: true },
ActivatePage: { CanExecuteOnStart: true }
},
DisplayUser: function (id) {
var cmd = Aspectize.Host.PrepareCommand();
cmd.Attributes.aasAsynchronousCall = true;
cmd.Attributes.aasShowWaiting = true;
cmd.Attributes.aasDataName = this.MainData;
cmd.Attributes.aasMergeData = true;
cmd.OnComplete = function (result) {
Aspectize.Host.ExecuteCommand(aas.Services.Browser.UIService.SetCurrent('MainData.user', id));
Aspectize.Host.ExecuteCommand(aas.Services.Browser.UIService.ShowView(aas.ViewName.user));
};
cmd.Call('Server/LoadDataService.GetItem', 'user', id);
},
DisplayItem: function (type, id) {
var em = Aspectize.EntityManagerFromContextDataName(this.MainData);
var pages = em.GetAllInstances('page');
var pageTypes = pages.Filter('type == \'' + type + '\' && previous');
var activePage = pageTypes[0];
var cmd = Aspectize.Host.PrepareCommand();
cmd.Attributes.aasAsynchronousCall = true;
cmd.Attributes.aasShowWaiting = true;
cmd.Attributes.aasDataName = this.MainData;
cmd.Attributes.aasMergeData = true;
cmd.OnComplete = function (result) {
var item = em.GetInstance('item', id);
item.SetField('page', activePage.number);
Aspectize.Host.ExecuteCommand(aas.Services.Browser.UIService.SetCurrent('MainData.item', id));
Aspectize.Host.ExecuteCommand(aas.Services.Browser.UIService.ShowView(aas.ViewName.item));
};
cmd.Call('Server/LoadDataService.GetItem', 'item', id);
},
ActivatePage: function (type, number) {
var em = Aspectize.EntityManagerFromContextDataName(this.MainData);
var pages = em.GetAllInstances('page');
var pageTypes = pages.Filter('type == \'' + type + '\' && previous');
var previousPage = (pageTypes.length > 0) ? pageTypes[0] : null;
var viewIsVisible = $('#' + type).is(":visible");
function navigate(page) {
page.SetField('previous', true);
Aspectize.Host.ExecuteCommand(aas.Services.Browser.UIService.ShowView(type));
Aspectize.Host.ExecuteCommand(aas.Services.Browser.UIService.SetCurrent(aas.Path.MainData.page, page.id));
var url = (page.id == 'news-1') ? 'app.ashx' : type + '?page=' + page.number;
Aspectize.Host.ExecuteCommand(aas.Services.Browser.History.PushState(type, aas.Path.MainData.page, page.id, '', url));
}
if (!number) {
if (previousPage) {
var activePage = Aspectize.Host.ExecuteCommand(aas.Services.Browser.UIService.GetCurrent(aas.Path.MainData.page));
if (previousPage.id !== activePage.id || !viewIsVisible) {
navigate(previousPage);
}
return;
}
number = 1;
}
if (previousPage) previousPage.SetField('previous', false);
var page = em.GetInstance('page', { id: type + '-' + (+number) });
if (!page) {
var cmd = Aspectize.Host.PrepareCommand();
cmd.Attributes.aasAsynchronousCall = true;
cmd.Attributes.aasShowWaiting = true;
cmd.Attributes.aasDataName = this.MainData;
cmd.Attributes.aasMergeData = true;
cmd.OnComplete = function (result) {
page = em.GetInstance('page', { id: type + '-' + (+number) });
navigate(page);
};
cmd.Call('Server/LoadDataService.GetItemPage', type, (+number));
} else {
navigate(page);
}
},
SetHtmlComment: function (aasEventArg, content) {
var element = $(aasEventArg.HtmlItem).find('.content');
element.html(content);
},
SetHtmlAbout: function (content) {
var element = $('#user').find('.about');
element.html(content);
},
ActiveMenuBar: function (menuSelector, activeMenuSelector) {
$(menuSelector + ' > ul > li').removeClass('active');
$(menuSelector + ' > ul > li ' + activeMenuSelector).parent().addClass('active');
}
};
<file_sep>/HackerNews/Scripts/_references.js
/// <reference path="S:\Delivery\Aspectize.core\AspectizeIntellisense.js" />
/// <reference path="S:\Delivery\Applications\HackerNews\HackerNews.AllViews.Intellisense.js" />
/// <reference path="S:\Delivery\Applications\HackerNews\HackerNews.Types.Intellisense.js" />
<file_sep>/HackerNews/Services/UrlRewritingService.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Aspectize.Core;
using Aspectize.Web;
using System.Text.RegularExpressions;
namespace HackerNews.Services
{
[Service(Name = "UrlRewritingService")]
public class UrlRewritingService : IURLRewritingService //, IInitializable, ISingleton
{
List<RewriteOrRedirect> IURLRewritingService.GetTranslators()
{
var translators = new List<RewriteOrRedirect>();
var regItemOrUser = new Regex(@"/hackernews/(?<type>item|user)\?(id=)?(?<id>\w{1,10})$", RegexOptions.IgnoreCase);
var regCategory = new Regex(@"/hackernews/(?<type>news|jobs|ask|show)\?page=(?<page>\d{1,10})$", RegexOptions.IgnoreCase);
translators.Add((Uri url, ref bool redirect) =>
{
redirect = false;
var m = regItemOrUser.Match(url.AbsoluteUri);
if (m.Success)
{
var type = m.Groups["type"].Value.ToLower();
var id = m.Groups["id"].Value;
var redirectUrl = string.Format("/HackerNews/app.ashx?@ClientService.DisplayItem&type={0}&id={1}", type, id);
if (type == "user")
{
redirectUrl = string.Format("/HackerNews/app.ashx?@ClientService.DisplayUser&id={0}", id);
}
var returnUrl = regItemOrUser.Replace(url.AbsoluteUri, redirectUrl);
return returnUrl;
}
var mCategory = regCategory.Match(url.AbsoluteUri);
if (mCategory.Success)
{
var type = mCategory.Groups["type"].Value.ToLower();
var page = mCategory.Groups["page"].Value.ToLower();
var pageInt = int.Parse(page);
var redirectUrl = string.Format("/HackerNews/app.ashx?@ClientService.ActivatePage&type={0}&number={1}", type, pageInt - 1);
var returnUrl = regCategory.Replace(url.AbsoluteUri, redirectUrl);
return returnUrl;
}
return null;
});
return translators;
}
}
}
<file_sep>/HackerNews/Configuration/Application.js
var app = newApplication();
app.CanWorkOffline = true;
app.URLRewritingService = "UrlRewritingService";
var ctxData = newContextData();
ctxData.Name = "MainData";
ctxData.NameSpaceList = "HackerNews";
<file_sep>/HackerNews/Services/LoadDataService.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Data;
using Aspectize.Core;
using HackerNews.Roles;
namespace HackerNews
{
public interface ILoadDataService
{
DataSet GetItemPage(string type, int page);
DataSet GetItem(string type, string id);
}
[Service(Name = "LoadDataService")]
public class LoadDataService : ILoadDataService
{
const string rootUrl = "https://hnpwa.com/api/v0/";
const string rootUrlNewApi = "https://api.hnpwa.com/v0/";
DataSet ILoadDataService.GetItemPage(string type, int page)
{
IEntityManager em = EntityManager.FromDataSet(new DataSet());
//var url = rootUrl + $"{type}.json?page={page}";
var url = rootUrlNewApi + $"{type}/{page}.json";
getDataFromHNAPI(url, em, "item", type);
var items = em.GetAllInstances<item>();
items.ForEach(e => e.page = page);
var newPage = em.CreateInstance<page>(new Dictionary<string, object>() { { "id", type + "-" + page }, { "type", type }, { "number", page } });
newPage.last = (items.Count < 30);
em.Data.AcceptChanges();
return em.Data;
}
DataSet ILoadDataService.GetItem(string type, string id)
{
IEntityManager em = EntityManager.FromDataSet(new DataSet());
var url = rootUrlNewApi + $"{type}/{id}.json";
getDataFromHNAPI(url, em, type, type);
return em.Data;
}
private void getDataFromHNAPI(string url, IEntityManager em, string type, string specificType)
{
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
var json = AspectizeHttpClient.Get(url, new Dictionary<string, object>(), new Dictionary<string, string>());
em.CreateInstanceFromJson(type, json);
// Must add a specificType to distinguish news and show type (both have type link) to manage repeater filter
if (specificType == "show")
{
foreach (item item in em.GetAllInstances<item>())
{
item.type = "show";
}
}
em.Data.AcceptChanges();
}
}
}
<file_sep>/README.md
# HackerNews
Aspectize HackerNews PWA
<file_sep>/HackerNews/Schema/HackerNews.Entities.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.ComponentModel;
using Aspectize.Core;
[assembly:AspectizeDALAssemblyAttribute]
namespace HackerNews
{
public static partial class SchemaNames
{
public static partial class Entities
{
public const string item = "item";
public const string user = "user";
public const string page = "page";
}
public static partial class Relations
{
public const string comments = "comments";
}
}
[SchemaNamespace]
public class DomainProvider : INamespace
{
public string Name { get { return GetType().Namespace; } }
public static string DomainName { get { return new DomainProvider().Name; } }
}
namespace Roles
{
public interface Child { }
public interface Parent { }
}
[DataDefinition(MustPersist = false)]
public class item : Entity, IDataWrapper
{
public static partial class Fields
{
public const string id = "id";
public const string title = "title";
public const string points = "points";
public const string user = "user";
public const string time = "time";
public const string timeago = "timeago";
public const string content = "content";
public const string commentscount = "commentscount";
public const string type = "type";
public const string url = "url";
public const string domain = "domain";
public const string deleted = "deleted";
public const string dead = "dead";
public const string level = "level";
public const string page = "page";
}
void IDataWrapper.InitData(DataRow data, string namePrefix)
{
base.InitData(data, null);
}
[Data(IsPrimaryKey = true)]
public string id
{
get { return getValue<string>("id"); }
set { setValue<string>("id", value); }
}
[Data]
public string title
{
get { return getValue<string>("title"); }
set { setValue<string>("title", value); }
}
[Data(IsNullable = true)]
public int? points
{
get { return getValue<int?>("points"); }
set { setValue<int?>("points", value); }
}
[Data(IsNullable = true)]
public string user
{
get { return getValue<string>("user"); }
set { setValue<string>("user", value); }
}
[Data(IsNullable = true)]
public DateTime? time
{
get { return getValue<DateTime?>("time"); }
set { setValue<DateTime?>("time", value); }
}
[Data(PhysicalName = "time_ago")]
public string timeago
{
get { return getValue<string>("timeago"); }
set { setValue<string>("timeago", value); }
}
[Data]
public string content
{
get { return getValue<string>("content"); }
set { setValue<string>("content", value); }
}
[Data(PhysicalName = "comments_count")]
public int commentscount
{
get { return getValue<int>("commentscount"); }
set { setValue<int>("commentscount", value); }
}
[Data]
public string type
{
get { return getValue<string>("type"); }
set { setValue<string>("type", value); }
}
[Data]
public string url
{
get { return getValue<string>("url"); }
set { setValue<string>("url", value); }
}
[Data]
public string domain
{
get { return getValue<string>("domain"); }
set { setValue<string>("domain", value); }
}
[Data(IsNullable = true)]
public bool? deleted
{
get { return getValue<bool?>("deleted"); }
set { setValue<bool?>("deleted", value); }
}
[Data(IsNullable = true)]
public bool? dead
{
get { return getValue<bool?>("dead"); }
set { setValue<bool?>("dead", value); }
}
[Data(IsNullable = true)]
public int? level
{
get { return getValue<int?>("level"); }
set { setValue<int?>("level", value); }
}
[Data]
public int page
{
get { return getValue<int>("page"); }
set { setValue<int>("page", value); }
}
}
[DataDefinition]
public class user : Entity, IDataWrapper
{
public static partial class Fields
{
public const string id = "id";
public const string about = "about";
public const string createdtime = "createdtime";
public const string created = "created";
public const string karma = "karma";
}
void IDataWrapper.InitData(DataRow data, string namePrefix)
{
base.InitData(data, null);
}
[Data(IsPrimaryKey = true)]
public string id
{
get { return getValue<string>("id"); }
set { setValue<string>("id", value); }
}
[Data(IsNullable = true)]
public string about
{
get { return getValue<string>("about"); }
set { setValue<string>("about", value); }
}
[Data(PhysicalName = "created_time")]
public string createdtime
{
get { return getValue<string>("createdtime"); }
set { setValue<string>("createdtime", value); }
}
[Data]
public string created
{
get { return getValue<string>("created"); }
set { setValue<string>("created", value); }
}
[Data]
public int karma
{
get { return getValue<int>("karma"); }
set { setValue<int>("karma", value); }
}
}
[DataDefinition(MustPersist = false)]
public class page : Entity, IDataWrapper
{
public static partial class Fields
{
public const string id = "id";
public const string type = "type";
public const string number = "number";
public const string last = "last";
public const string previous = "previous";
}
void IDataWrapper.InitData(DataRow data, string namePrefix)
{
base.InitData(data, null);
}
[Data(IsPrimaryKey = true)]
public string id
{
get { return getValue<string>("id"); }
set { setValue<string>("id", value); }
}
[Data]
public string type
{
get { return getValue<string>("type"); }
set { setValue<string>("type", value); }
}
[Data]
public int number
{
get { return getValue<int>("number"); }
set { setValue<int>("number", value); }
}
[Data(DefaultValue = false)]
public bool last
{
get { return getValue<bool>("last"); }
set { setValue<bool>("last", value); }
}
[Data(DefaultValue = true)]
public bool previous
{
get { return getValue<bool>("previous"); }
set { setValue<bool>("previous", value); }
}
}
[DataDefinition]
[RelationPersistenceMode(SeparateTable = false)]
public class comments : DataWrapper, IDataWrapper, IRelation
{
void IDataWrapper.InitData(DataRow data, string namePrefix)
{
base.InitData(data, null);
}
[RelationEnd(Type = typeof(item), Role = typeof(Roles.Child), Multiplicity = Multiplicity.ZeroOrMany)]
public IEntity Child;
[RelationEnd(Type = typeof(item), Role = typeof(Roles.Parent), Multiplicity = Multiplicity.One, FkNames = "ItemId")]
public IEntity Parent;
}
}
<file_sep>/HackerNews/Configuration/Views/item.js
var item = Aspectize.CreateView('item', aas.Controls.item, aas.Zones.Home.ZoneInfo, false, aas.Data.MainData.item);
item.OnActivated.BindCommand(aas.Services.Browser.History.PushState(aas.ViewName.item, aas.Path.MainData.item, item.ParentData.id, '', aas.Expression('item/' + item.ParentData.id)));
item.header.commentscount.BindData(item.ParentData.commentscount);
item.header.points.BindData(item.ParentData.points);
item.header.timeago.BindData(item.ParentData.timeago);
item.header.title.BindData(item.ParentData.title);
item.header.user.BindData(item.ParentData.user);
item.header.showArticle.href.BindData(item.ParentData.url);
item.header.showUser.click.BindCommand(aas.Services.Browser.ClientService.DisplayUser(item.ParentData.user));
var commentRoot = item.TreeViewComments.AddNodeBinding('CommentNode', aas.Data.MainData.item.comments_ROLE_Parent.item, false, false, 'time DESC', '!deleted');
commentRoot.AutoExpand.BindData(true);
commentRoot.timeago.BindData(commentRoot.DataSource.timeago);
commentRoot.user.BindData(commentRoot.DataSource.user);
commentRoot.commentscount.BindData(commentRoot.DataSource.commentscount);
commentRoot.displayCommentsCount.BindData(aas.Expression(IIF(commentRoot.DataSource.commentscount, '', 'hidden')));
commentRoot.OnNodeLoad.BindCommand(aas.Services.Browser.ClientService.SetHtmlComment('', "ContextualData:[Current].content"));
var commentChild = commentRoot.AddNodeBinding('CommentNode', commentRoot.ParentData.comments_ROLE_Parent.item, true, true, "time DESC", '!deleted');
commentChild.AutoExpand.BindData(true);
commentChild.timeago.BindData(commentChild.DataSource.timeago);
commentChild.user.BindData(commentChild.DataSource.user);
commentChild.commentscount.BindData(commentChild.DataSource.commentscount);
commentChild.displayCommentsCount.BindData(aas.Expression(IIF(commentChild.DataSource.commentscount, '', 'hidden')));
commentChild.OnNodeLoad.BindCommand(aas.Services.Browser.ClientService.SetHtmlComment('', "ContextualData:[Current].content"));
var user = Aspectize.CreateView('user', aas.Controls.user, aas.Zones.Home.ZoneInfo, false, aas.Data.MainData.user);
user.OnActivated.BindCommand(aas.Services.Browser.History.PushState(aas.ViewName.user, aas.Path.MainData.user, user.ParentData.id, '', aas.Expression('user/id=' + user.ParentData.id)));
user.OnActivated.BindCommand(aas.Services.Browser.ClientService.SetHtmlAbout(user.ParentData.about));
user.userid.BindData(user.ParentData.id);
user.karma.BindData(user.ParentData.karma);
user.timeago.BindData(user.ParentData.createdtime);
| 6c8652f5c21f44a49b5d5239fdc12620e64aa9f0 | [
"JavaScript",
"C#",
"Markdown"
] | 8 | JavaScript | Aspectize/HackerNews | 075f264c94874ff67ce6aa80fd3d0a7010de79ad | cbeb7c77c03446c836b6ae3ca663191286c1aa22 |
refs/heads/master | <file_sep>//
// SwiftResult.swift
// ITunesSearch
//
// Created by <NAME> on 5/14/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
struct SearchResult: Codable {
var title: String
var creator: String
enum CodingKeys: String, CodingKey {
case title = "trackName"
case creator = "artistName"
}
}
struct SearchResults: Codable {
let results: [SearchResult]
}
| 3d0b56613917d00d93886fff992bd70be3ab9265 | [
"Swift"
] | 1 | Swift | OaklandHawk/ios-itunes-search | 9ec8fde0eff66ded4ca4f251790b7fe06d406040 | 324dbf1c3fb0d7f7585b00fd8e5b8cb0c5cde473 |
refs/heads/master | <repo_name>Maher-OUALI/Text-Editor<file_sep>/Text Editor/lib/Finder.py
import pandas as pd
class Finder():
def __init__(self):
directory='C:/Users/Asus/Desktop/GitHub Projects/projets terminés/Text Editor/assets/unigram_freq.csv' #put here the directory of the assets folder
self.unigram_freq=pd.read_csv(open(directory,'r'))
#self.bigram_freq=pd.read_csv(open('C:/Users/Asus/Desktop/GitHub Projects/projets à terminer/Text Editor (à terminer)/assets/bigram_freq.csv','r'))
def startsWith(self,word):
startsWith_word=self.unigram_freq.word.str.startswith(word,na=False)
return(self.unigram_freq[startsWith_word].dropna().head().word.tolist())
def startsWithKnowingBefore(self,word_before,word):
pass
<file_sep>/Text Editor/README.txt
This Text Editor is the first version of an improved editing tool
Improved in a way that it proposes words' completion to make your typing faster than before or to help people having writing difficulties to write correct phrases
the second version will have a programming mode which will make it even easier for the user to quickly change the color of the text only with typing so that he doesn't have to use the mouse
In this first version i only use a unigram frequncy to predict completions but bigram word frequ could be used to give better predictions
Enjoy :)<file_sep>/Text Editor/lib/Menu.py
import tkinter as tk
from tkinter import filedialog as fd
from tkinter import simpledialog as sd
import tkinter.messagebox as mb
import re
from pynput.keyboard import Key, Controller
import sys
sys.path.insert(0,'C:/Users/Asus/Desktop/GitHub Projects/projets terminés/Text Editor/assets')#put here the directory of the assets folder
from Constants import *
class Menu(tk.Menu):
def __init__(self,parent,controller):
"""this function creates the menu for the text editor"""
#create a main menu
tk.Menu.__init__(self,parent)
#store the text widget in a variable to access the frame attributs for future modifications
self.textWidget=controller
#initialise a keyboard controller to handle (undo, redo, cut, paste, copy ...)
self.keyboard=Controller()
#add the file sub-menu
self.filemenu=tk.Menu(self, tearoff=0)
self.filemenu.add_command(label="New File", command=lambda: self.newFile())
self.filemenu.add_command(label="Open...", command=lambda: self.openFile())
self.filemenu.add_separator()
self.filemenu.add_command(label = "Save", command=lambda: self.saveFile())
self.filemenu.add_separator()
self.filemenu.add_command(label="Exit", command =lambda:parent.destroy())
self.add_cascade(label="File", menu=self.filemenu)
#add the Edit sub-menu
self.editmenu=tk.Menu(self, tearoff=0)
self.editmenu.add_command(label="Undo", command=lambda: self.undo())
self.editmenu.add_command(label="Redo", command=lambda: self.redo())
self.editmenu.add_separator()
self.editmenu.add_command(label="Cut", command=lambda: self.cut())
self.editmenu.add_command(label="Copy", command=lambda: self.copy())
self.editmenu.add_command(label="Paste", command=lambda: self.paste())
self.editmenu.add_separator()
self.editmenu.add_command(label="Find", command=lambda: self.find())
self.add_cascade(label="Edit", menu=self.editmenu)
#add the configuration sub-menu
self.configmenu=tk.Menu(self, tearoff=0)
self.autoGuess=tk.StringVar()
self.configmenu.add_checkbutton(label="Enable Guessing Mode", variable=self.autoGuess,onvalue="Enabled",offvalue="Disabled",command=lambda:self.config_autoGuess())
self.programming=tk.StringVar()
self.configmenu.add_checkbutton(label="Enable Programming Mode", variable=self.programming,onvalue="Enabled",offvalue="Disabled",command=lambda:self.config_programming())
self.add_cascade(label="Configuration", menu=self.configmenu)
#add the graphics sub-menu
self.graphicmenu=tk.Menu(self, tearoff=0)
###adding colors' choice (black, red, blue, green ...)
colors=tk.Menu(self.graphicmenu,tearoff=0)
self.color=tk.StringVar()
for element in COLORS:
colors.add_radiobutton(label=element.upper(), background=element.lower(), foreground="white", variable=self.color, value=element, command=lambda:self.color_choice())
self.graphicmenu.add_cascade(label="Color",menu=colors)
###adding fonts' choice (Arial, comic sans ms, verdana ...)
fonts=tk.Menu(self.graphicmenu, tearoff=0)
self.font=tk.StringVar()
for element in FONTS:
fonts.add_radiobutton(label=element, variable=self.font, value=element, command=lambda:self.font_choice())
self.graphicmenu.add_cascade(label="Font",menu=fonts)
###adding fontSizes' choice (Small, medium, Large)
fontSizes=tk.Menu(self.graphicmenu, tearoff=0)
self.fontSize=tk.StringVar()
for element in list(FONT_SIZES.keys()):
fontSizes.add_radiobutton(label=element.upper(), variable=self.fontSize, value=FONT_SIZES[element], command=lambda:self.fontSize_choice())
self.graphicmenu.add_cascade(label="Font Size",menu=fontSizes)
###adding fontStyles' choice ( Bold, Italian)
fontStyles=tk.Menu(self.graphicmenu, tearoff=0)
self.bold=tk.StringVar()
fontStyles.add_checkbutton(label="BOLD", variable=self.bold,onvalue="Enabled",offvalue="Disabled",command=lambda:self.Bold())
self.italian=tk.StringVar()
fontStyles.add_checkbutton(label="ITALIC", variable=self.italian,onvalue="Enabled",offvalue="Disabled",command=lambda:self.Italic())
self.graphicmenu.add_cascade(label="Font Styles", menu=fontStyles)
self.add_cascade(label="Graphics", menu=self.graphicmenu)
#add the help sub-menu
self.helpmenu = tk.Menu(self, tearoff=0)
message = "This is an editor made by <NAME>"
self.helpmenu.add_command(label="About", command = lambda: mb.showinfo("About!",message))
self.add_cascade(label="Help", menu=self.helpmenu)
def newFile(self): #finished
"""this function generates a new file"""
if(not(self.textWidget.lastIsSaved)):
#here before saving launch a dialog file to see if the user want to save the file or not
self.saveFile()
#here we have to destroy the first frame and launch a second one
self.textWidget.pathOfSavedVersion=None
self.textWidget.lastIsSaved=True
self.textWidget.text.delete("1.0","end")
self.textWidget.initializeElements()
def openFile(self): #finished
"""this function opens an existing file chosen by the user"""
if(not(self.textWidget.lastIsSaved)):
#here before saving launch a dialog file to see if the user want to save the file or not
answer = mb.askokcancel("Save or not","Do you want to save this file?")
if answer:
self.saveFile()
#here we have to destroy the first frame and launch a second one
file = fd.askopenfile()
if file is None: # asksaveasfile return `None` if dialog closed with "cancel".
return
self.textWidget.pathOfSavedVersion=file.name
self.textWidget.lastIsSaved=True
text2open=file.read()
file.close()
self.textWidget.text.delete("1.0","end")
self.textWidget.text.insert("end",text2open)
self.textWidget.text.config(font=DEFAULT_FONT, fg=DEFAULT_COLOR)
self.textWidget.font=DEFAULT_FONT
self.textWidget.color=DEFAULT_COLOR
def saveFile(self): #finished
"""this function saves the file edited by the user"""
if(not(self.textWidget.lastIsSaved)):
if(self.textWidget.pathOfSavedVersion == None):
#here launch a file dialog to choose a path and then save it there and update both self.pathOfSavedVersion and self.lastIsSaved
file = fd.asksaveasfile(mode='w', defaultextension=".txt")
if file is None: # asksaveasfile return `None` if dialog closed with "cancel".
return
self.textWidget.pathOfSavedVersion=file.name
self.textWidget.lastIsSaved=True
text2save = str(self.textWidget.text.get("1.0", "end")) # starts from `1.0`, not `0.0`
file.write(text2save)
file.close()
else:
try:
file=open(self.textWidget.pathOfSavedVersion,mode='w')
text2save = str(self.textWidget.text.get("1.0", "end")) # starts from `1.0`, not `0.0`
file.write(text2save)
file.close()
except:
mb.showinfo("Error!!","Original file not found")
self.textWidget.pathOfSavedVersion = None
self.saveFile()
else:
return
def undo(self): #finished
"""this function mimic the undo of the text widget"""
self.keyboard.press(Key.ctrl)
self.keyboard.press("z")
self.keyboard.release(Key.ctrl)
self.keyboard.release("z")
def redo(self): #finished
"""this function mimic the redo of the text widget"""
self.keyboard.press(Key.ctrl)
self.keyboard.press("y")
self.keyboard.release(Key.ctrl)
self.keyboard.release("y")
def cut(self): #finished
"""this function mimic the cut of the text widget"""
self.keyboard.press(Key.ctrl)
self.keyboard.press("x")
self.keyboard.release(Key.ctrl)
self.keyboard.release("x")
def copy(self): #finished
"""this function mimic the copy of the text widget"""
self.keyboard.press(Key.ctrl)
self.keyboard.press("c")
self.keyboard.release(Key.ctrl)
self.keyboard.release("c")
def paste(self): #finished
"""this function mimic the paste of the text widget"""
self.keyboard.press(Key.ctrl)
self.keyboard.press("v")
self.keyboard.release(Key.ctrl)
self.keyboard.release("v")
def find(self): #finished
"""this function gives the user the posibility of finding a word in the text widget"""
#here we simply launch a dialog for the user to type the word that he wants to look for and then we highlight it in all possible positions in the text widget
if(not(self.textWidget.findMethodTag==None)):
self.textWidget.text.tag_delete(self.textWidget.findMethodTag)
word=sd.askstring("Search", "What do you want to search for?")
if word is not None:
#we look for the word in the text file and we highlight all occurennces
self.textWidget.findMethodTag=word
text=self.textWidget.text.get("1.0","end")
listOfOccurrence=[(m.start(),m.end()) for m in re.finditer(word, text)]
for element in listOfOccurrence:
self.textWidget.text.tag_add(word,"1.0+"+str(element[0])+"c","1.0+"+str(element[1])+"c")
self.textWidget.text.tag_config(word,background=TAGS_COLORS[self.textWidget.color])
else:
return
def config_autoGuess(self): #finished
if(self.autoGuess.get() == "Enabled"):
self.textWidget.autoGuess=True
else:
self.textWidget.autoGuess=False
def config_programming(self): #finished
if(self.programming.get() == "Enabled"):
self.textWidget.programming=True
else:
self.textWidget.programming=False
def color_choice(self): #finished
self.textWidget.color=self.color.get()
self.textWidget.text.config(fg=self.textWidget.color)
def font_choice(self): #finished
temp_list=list(self.textWidget.font)
temp_list[0]=self.font.get()
self.textWidget.font=tuple(temp_list)
self.textWidget.text.config(font=self.textWidget.font)
def fontSize_choice(self): #finished
temp_list=list(self.textWidget.font)
temp_list[1]=int(self.fontSize.get())
self.textWidget.font=tuple(temp_list)
self.textWidget.text.config(font=self.textWidget.font)
def Bold(self): #finished
temp_list=list(self.textWidget.font)
if(self.bold.get() == "Enabled"):
if(len(temp_list)==2):
temp_list.append("bold")
else:
if(not("bold" in temp_list[2])):
temp_list[2] += " bold"
else:
if(len(temp_list)==3):
if("bold" in temp_list[2]):
temp_list[2] = temp_list[2].replace("bold","")
self.textWidget.font=tuple(temp_list)
self.textWidget.text.config(font=self.textWidget.font)
def Italic(self): #finished
temp_list=list(self.textWidget.font)
if(self.italian.get() == "Enabled"):
if(len(temp_list)==2):
temp_list.append("italic")
else:
if(not("italic" in temp_list[2])):
temp_list[2] += " italic"
else:
if(len(temp_list)==3):
if("italic" in temp_list[2]):
temp_list[2] = temp_list[2].replace("italic","")
self.textWidget.font=tuple(temp_list)
self.textWidget.text.config(font=self.textWidget.font)
<file_sep>/Text Editor/Text Editor.py
import tkinter as tk
from tkinter import font
from tkinter import ttk
from lib.Menu import Menu
from lib.Finder import Finder
from assets.Constants import *
from time import time
class TextEditor(tk.Frame):
def __init__(self,parent):
"""this function initializes the text editor widget"""
tk.Frame.__init__(self, parent)
#adding the text widget with its verticall scrollbar
self.text = tk.Text(self, wrap="char")
self.scroll = tk.Scrollbar(self, orient="vertical", command=self.text.yview)
self.text.configure(yscrollcommand=self.scroll.set)
self.scroll.pack(side="right", fill="y")
self.text.pack(side="left", fill="both", expand=True)
self.text.bind('<KeyRelease>',lambda e : self.keyPressed(e))
#initialize elements
self.initializeElements()
#add the menu and initialize file saving related variables
self.menu=Menu(parent,self)
parent.config(menu=self.menu)
#initialize configuration variables
self.autoGuess=False
self.programming=False
#initialize a finder which is going to search for completions when autoGuess mode is on
self.finder=Finder()
def initializeElements(self):
"""this function is used to initialize elements such as font, color, usefull lists etc ..."""
#initializing text related attributs(font, foreground color ...)
self.font=DEFAULT_FONT
self.color=DEFAULT_COLOR
self.text.config(font=self.font, fg=self.color)
self.lastWord=''
self.currentWord=''
self.lastIsSaved=True #this variable is used to check if the latest state of the document has been saved (((it's set to true once the user saves a copy and turned to false at any key press)))
self.pathOfSavedVersion=None #this variable holds the path of the file if it's saved at least once in order to save automatically
#initialize the label to be placed near the cursor every time we start typing something
self.labels=tk.Label(self.text)
self.labelsList=list() #it contains a maximum of four sub_labels to show proposed words each time a char key is pressed
self.labelCounter=-1 #label counter is used to know which proposed word to highlight when the user presses on teh right arrow key
#initialize the list of all tags added because of the find method in the menu
self.findMethodTag=None
def keyPressed(self,event):
"""this function deals with keyPresses in the text widget"""
#when a key is pressed we first change the state of the file to not saved
self.lastIsSaved=False
#we remove tag added from find method
if(not(self.findMethodTag==None)):
self.text.tag_delete(self.findMethodTag)
self.findMethodTag=None
if(self.autoGuess):
#then we check which key was pressed to figure out what to do
if(event.char == ' '): #the space bar is pressed
self.spacePressed(event)
elif event.keysym_num > 0 and event.keysym_num < 60000: # a printable key is pressed
#we destroy labels of proposed words and we re-initialize self.labelsList and we hide the label of potential words' completion
self.labelsList=list()
for label in self.labels.pack_slaves():
label.destroy()
self.labels.place_forget()
#average time needed to execute this function is 120ms ~ almost the time needed to execute the finder.startsWith method
self.charPressed(event)
elif event.keysym_num == 65363: #the right arrow key is pressed
self.rightArrowPressed(event)
else:
#we destroy labels of proposed words and we re-initialize self.labelsList and we hide the label of potential words' completion
self.labelsList=list()
for label in self.labels.pack_slaves():
label.destroy()
self.labels.place_forget()
self.labelCounter=-1
else:
pass
def spacePressed(self,event):
"""this function stores the last word after a whitespace so that could be used later using the bi-gram frequency document or put a proposed word chosen by the user"""
if(self.autoGuess):
if(self.labelCounter != -1):#if the label counter is different from -1 meaning that the user has chosen a word to put automatically so we replace the letters typed by the user
self.labelsList[self.labelCounter].config(background='SystemButtonFace')#we remove the highlighting
word_to_remove=self.text.get("1.0",'end-2c').replace('\n',' ').rsplit(' ', 1)[-1].strip()#we extart the typed letters
self.text.delete("end-"+str(len(word_to_remove)+2)+"c","end")#we delete them
self.text.insert("end",self.labelsList[self.labelCounter]["text"]+" ")#we insert the chosen word with a white space
self.labelCounter=-1
#we destroy labels of proposed words and we re-initialize self.labelsList and we hide the label of potential words' completion
self.labelsList=list()
for label in self.labels.pack_slaves():
label.destroy()
self.labels.place_forget()
#we update the last and current word
self.lastWord = self.text.get("1.0",'end-2c').replace('\n',' ').rsplit(' ', 1)[-1].strip()
self.currentWord=''
else:
pass
def charPressed(self,event):
"""this function deals with chars being pressed to show for the user possible words if the auto guess mode is enabled"""
if(self.autoGuess):
self.labelCounter=-1
self.currentWord=self.text.get("1.0",'end-1c').rsplit(' ', 1)[-1].strip()#we update current word in fact current word is the letters typed by the user
_font=font.Font(family=self.font[0], size=self.font[1])#we define a tk.Font tool to use it later to determine the height and width of the text in pixels to know where to place the label of potential words' completion
_defaultFont=font.Font(family=DEFAULT_FONT[0], size=DEFAULT_FONT[1])#this the same tk.Font tool for DEFAULT_FONT (go to Constants.py in the assets folder)
height=_font.metrics("linespace")#determine the height of a row in a text which will be used as a height unit later
default_height=_defaultFont.metrics("linespace")#determine the height of a proposed word
heightUnit=height
cursorPosition=self.text.index("insert").split('.')#determine the position of the typing cursor in the text
#calculating height and width (initial calculations)
for i in range(1,int(cursorPosition[0])):
height +=((_font.measure(self.text.get(str(i)+".0",str(i+1)+".0"))//680)+1)*heightUnit
height +=_font.measure(self.text.get(cursorPosition[0]+".0","end-1c"))//680*heightUnit
width=(_font.measure(self.text.get(cursorPosition[0]+".0","end-1c"))%680)+5 #the +5 is for better visual aspect nothing more
possibleWords=self.finder.startsWith(self.currentWord)
propositionMaxWidth=0
numberOfShowenLabels=0
for i in range(4):
try:
if(_defaultFont.measure(possibleWords[i])>propositionMaxWidth):
propositionMaxWidth=_defaultFont.measure(possibleWords[i])
self.labelsList.append(tk.Label(self.labels, font=DEFAULT_FONT, text=possibleWords[i],background='SystemButtonFace'))
numberOfShowenLabels+=1
self.labelsList[numberOfShowenLabels-1].pack()
except:
pass
#we update the height and width so that the label of potential words' completion doesn't exceed the text widget
width=min(width,WINDOW_WIDTH-25-propositionMaxWidth)
height=min(height,WINDOW_HEIGHT-25-default_height*numberOfShowenLabels)
self.labels.place(x=width, y=height)
else:
pass
def rightArrowPressed(self,event):
"""this function gives the user the possibility to choose a word that was proposed to him so that he types faster"""
if(self.autoGuess):
if(len(self.labelsList) != 0):
self.labelCounter = (self.labelCounter+1)%len(self.labelsList)
self.labelsList[self.labelCounter].config(bg="light blue")
for i in range(len(self.labelsList)):
if(i!=self.labelCounter):
self.labelsList[i].config(background='SystemButtonFace')
else:
pass
if __name__ == "__main__":
root = tk.Tk()
root.geometry(str(WINDOW_WIDTH)+"x"+str(WINDOW_HEIGHT)+"+0+0")
root.resizable(width=False, height=False)
TextEditor(root).pack(side="top", fill="both", expand=True)
root.mainloop()
<file_sep>/Text Editor/assets/Constants.py
COLORS = ["Black","Red","Blue","Green","Yellow","Pink","Violet"]
DEFAULT_FONT = ("Arial",12)
DEFAULT_COLOR = "Black"
FONT_SIZES = {"SMALL":12,"MEDIUM":20,"LARGE":36}
FONTS = ["Verdana","Arial","Comic sans ms","fixedsys"]
WINDOW_WIDTH, WINDOW_HEIGHT = 700, 700
TAGS_COLORS = {"Black":"Yellow","Red":"Yellow","Blue":"Pink","Green":"Yellow","Yellow":"Red","Pink":"Yellow","Violet":"Light Blue"}
| c544ad755a1e6418ddd0f655a92db694de0eeed6 | [
"Python",
"Text"
] | 5 | Python | Maher-OUALI/Text-Editor | 7a17a4edc6352ca690d9900546387761b0f9c946 | 31b55eb69d199e817cebcb28132a7d85c51f06ca |
refs/heads/master | <file_sep>package aUGUST_LEETCODE_CHALLENGE;
import java.util.Scanner;
public class isPowerOfFour {
public static void main(String[] args) {
Scanner s= new Scanner(System.in);
int n = s.nextInt();
System.out.println(isPowerOfFouR(n));
}
private static boolean isPowerOfFouR(int num) {
if(num==1)
{
return true;
}
int count =0;
if((num & (num-1))!=0)
{
return false;
}
while(num>1)
{
num=num>>1;
count++;
}
if(count%2==0)
{
return true;
}
return false;
}
}
<file_sep>package aUGUST_LEETCODE_CHALLENGE;
import java.util.Arrays;
import java.util.Scanner;
public class H_index {
static Scanner s = new Scanner(System.in);
public static void main(String[] args) {
int n = s.nextInt();
int[] arr = new int[n];
int[] a = input(arr);
System.out.println(hIndex(arr));
display(a);
}
public static int hIndex(int[] citations) {
int cit = 0;
Arrays.sort(citations);
for (int i = citations.length - 1; i >= 0; i--) {
cit++;
if (cit > citations[i]) {
cit--;
return cit;
}
if (cit == citations[i]) {
return cit;
}
}
return cit;
}
public static void display(int[] arr) {
for (int a = 0; a < arr.length; a++) {
System.out.println(arr[a]);
}
}
public static int[] input(int[] arr) {
for (int a = 0; a < arr.length; a++) {
arr[a] = s.nextInt();
}
return arr;
}
}
<file_sep>package aUGUST_LEETCODE_CHALLENGE;
import java.util.ArrayList;
public class path_SumIII {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public class solution {
ArrayList<Integer> ar = new ArrayList<Integer>();
int counter = 0;
public void work(TreeNode root, int sum) {
if (root == null) {
return;
}
ar.add(root.val);
work(root.left, sum);
work(root.right, sum);
int temp = 0;
for (int i = ar.size() - 1; i >= 0; i++) {
if (ar.get(i) + temp == sum) {
counter++;
}
}
ar.remove(ar.size() - 1);
return;
}
}
}
<file_sep>package aUGUST_LEETCODE_CHALLENGE;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class pascal_triangle_2 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
System.out.println(getRow(n));
}
public static List<Integer> getRow(int rowIndex) {
List<Integer> l = new ArrayList<Integer>();
for (int i = 0; i <= rowIndex; i++) {
double p = factorial(rowIndex) /( factorial(rowIndex - i) * factorial(i));
System.out.println(p);
p=Math.round(p);
System.out.println(p);
l.add((int) p);
}
return l;
}
private static double factorial(int r) {
if (r == 1 || r == 0) {
return 1;
}
double i = factorial(r - 1);
return i * r;
}
}
| 5c373261da488a9aa4ac1c8e1f04e7fea50c72b4 | [
"Java"
] | 4 | Java | shivanshbhardwaj/leetcode_2020_august_challenge | fc2a3531c110a98e55702f4af9a3d01ee7179079 | b32f36365c6a4d24a9e0777638ee96d39f523da4 |
refs/heads/master | <repo_name>sylijinlei/Rover2<file_sep>/Rover 2.0-android-src/src/com/wificar/external/FSCoder.java
package com.wificar.external;
/*
* FSCoder.java
* Transform
*
* Copyright (c) 2001-2006 Flagstone Software Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Flagstone Software Ltd. nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.io.*;
/**
* FSCoder is a similar to Java stream classes, allowing words and bit fields
* to be read and written from an internal array of bytes. FSCoder supports both
* little-endian and big-endian byte ordering.
*
* The FSCoder class maintains an internal pointer which points to the next bit
* in the internal array where data will be read or written. When calculating an
* offset in bytes to jump to simply multiply the offset by 8 for the correct
* bit position. The class provides accessor methods, getPointer() and
* setPointer() to change the location of the internal pointer.
*
* When writing to an array the size of the array is changed dynamically should
* a write operation cause a buffer overflow. For reads if an overflow results
* then the bits/bytes that overflowed will be set to zero, rather than throwing
* an exception. The eof() method can be used to determine whether the end of
* the buffer has been reached.
*/
public class FSCoder
{
/**
* Identifies that multibyte words are stored in little-endian format with
* the least significant byte in a word stored first.
*/
public static final int LITTLE_ENDIAN = 0;
/**
* Identifies that multibyte words are stored in big-endian format with the
* most significant byte in a word stored first.
*/
public static final int BIG_ENDIAN = 1;
/*
* Methods used to calculate the size of fields when encoded.
*/
/**
* Calculates the minimum number of bits required to encoded an integer
* in a bit field.
*
* @param value the value to be encoded.
*
* @param signed where the value will be encoded as a signed or unsigned
* integer.
*
* @return the number of bits required to encode the value.
*/
static int size(int value, boolean signed)
{
int size = 0, i = 0;
int mask = 0x80000000;
if (signed)
{
value = (value < 0) ? -value : value;
for (i=32; (value & mask) == 0 && i>0; i--)
mask >>>= 1;
size = (i < 32) ? i+1 : i;
}
else
{
for (i=32; (value & mask) == 0 && i>0; i--)
mask >>>= 1;
size = i;
}
return size;
}
/**
* Calculates the minimum number of bits required to encoded an array of
* integer values in a series of bit fields.
*
* @param values the values to be encoded.
*
* @param signed where the values will be encoded as a signed or unsigned
* integers.
*
* @return the minimum number of bits required to encode all the values.
*/
static int size(int[] values, boolean signed)
{
int size = 0;
for (int i=0; i<values.length; i++)
size = Math.max(size, size(values[i], signed));
return size;
}
/**
* Calculates the minimum number of bits required to encoded a floating
* point number as a fixed point number in 8.8 format.
*
* @param value the value to be encoded.
*
* @return the number of bits required to encode the value.
*/
static int fixedShortSize(float aNumber)
{
float floatValue = aNumber * 256.0f;
return size((int)floatValue, true);
}
/**
* Calculates the minimum number of bits required to encoded a series of
* floating point numbers in a fixed point number in 8.8 format.
*
* @param value the values to be encoded.
*
* @return the minimum number of bits required to encode all the values.
*/
static int fixedShortSize(float[] values)
{
int size = 0;
for (int i=0; i<values.length; i++)
size = Math.max(size, fixedShortSize(values[i]));
return size;
}
/**
* Calculates the minimum number of bits required to encoded a floating
* point number as a fixed point number in 16.16 format.
*
* @param value the value to be encoded.
*
* @return the number of bits required to encode the value.
*/
static int fixedSize(float aNumber)
{
float floatValue = aNumber * 65536.0f;
return size((int)floatValue, true);
}
/**
* Calculates the minimum number of bits required to encoded a series of
* floating point numbers in a fixed point number in 16.16 format.
*
* @param value the values to be encoded.
*
* @return the number of bits required to encode the value.
*/
static int fixedSize(float[] values)
{
int size = 0;
for (int i=0; i<values.length; i++)
size = Math.max(size, fixedSize(values[i]));
return size;
}
/**
* Calculates the length of a string when encoded.
*
* @param string the string to be encoded.
*
* @param encoding the format used to encode the string characters.
*
* @param appendNull whether the string should be terminated with a null
* byte.
*
* @return the number of bytes required to encode the string.
*/
static int strlen(String string, String encoding, boolean appendNull)
{
int length = 0;
if (string != null)
{
try
{
length += string.getBytes(encoding).length;
length += appendNull ? 1 : 0;
}
catch (UnsupportedEncodingException e)
{
}
}
return length;
}
/**
* Calculates the length of a string when encoded.
*
* @param string the string to be encoded.
*
* @param appendNull whether the string should be terminated with a null
* byte.
*
* @return the number of bytes required to encode the string.
*/
static int strlen(String string, boolean appendNull)
{
int length = 0;
if (string != null)
{
try
{
length += string.getBytes("UTF8").length;
length += appendNull ? 1 : 0;
}
catch (UnsupportedEncodingException e)
{
}
}
return length;
}
//private FSMovieListener listener = null;
String encoding = "UTF8";
private int byteOrder = LITTLE_ENDIAN;
private byte[] data = null;
private int ptr = 0;
private int end = 0;
/**
* Constructs an FSCoder object containing an array of bytes with the
* specified byte ordering.
*
* @param order the byte-order for words, eitherLITTLE_ENDIAN or BIG_ENDIAN.
* @param size the size of the internal buffer to be created.
*/
public FSCoder(int order, int size)
{
clearContext();
byteOrder = order;
data = new byte[size];
for (int i=0; i<size; i++)
data[i] = 0;
ptr = 0;
end = data.length << 3;
}
/**
* Constructs an FSCoder object containing an array of bytes with the
* specified byte order.
*
* @param order the byte-order for words, either LITTLE_ENDIAN or BIG_ENDIAN.
* @param bytes an array of bytes where the data will be read or written.
*/
public FSCoder(int order, byte[] bytes)
{
clearContext();
byteOrder = order;
data = bytes;
ptr = 0;
end = data.length << 3;
}
/**
* Return the string representation of the character encoding scheme used
* when encoding or decoding strings as a sequence of bytes.
*
* @return the string the name of the encoding schemd for characters.
*/
public String getEncoding()
{
return encoding;
}
/**
* Sets the string representation of the character encoding scheme used
* when encoding or decoding strings as a sequence of bytes.
*
* @return enc, the string the name of the encoding schemd for characters.
*/
public void setEncoding(String enc)
{
encoding = enc;
}
/*
* Methods for accessing the encoded data
*/
/**
* Returns a copy of the array of bytes.
*
* @return a copy of the internal buffer.
*/
public byte[] getData()
{
int length = (ptr + 7) >> 3;
byte[] bytes = new byte[length];
System.arraycopy(data, 0, bytes, 0, length);
return bytes;
}
/**
* Sets the array of bytes used to read or write data to.
*
* @param order the byte-order for words, either FSCoder.LITTLE_ENDIAN or
* FSCoder.BIG_ENDIAN.
*
* @param bytes a byte array that will be used as the internal buffer.
*/
public void setData(int order, byte[] bytes)
{
byteOrder = order;
data = new byte[bytes.length];
System.arraycopy(bytes, 0, data, 0, bytes.length);
ptr = 0;
end = data.length << 3;
}
/**
* Increases the size of the internal buffer. This method is used when
* encoding data to automatically adjust the buffer size to avoid overflows.
*
* @param size the number of bytes to add to the buffer.
*/
public void addCapacity(int size)
{
int length = (end >>> 3) + size;
byte[] bytes = new byte[length];
System.arraycopy(data, 0, bytes, 0, data.length);
data = bytes;
end = data.length << 3;
}
/**
* Return the size of the internal buffer in bytes.
*
* @return the size of the buffer.
*/
public int getCapacity()
{
return end >>> 3;
}
/*
* Methods for adjusting the location from where data is read or written
*/
/**
* Returns the offset, in bits, from the start of the buffer where the next
* value will be read or written.
*
* @return the offset in bits where the next value will be read or written.
*/
public int getPointer()
{
return ptr;
}
/**
* Sets the offset, in bits, from the start of the buffer where the next
* value will be read or written. If the offset falls outside of the bits
* range supported by the buffer then an IllegalArgumentException will
* be thrown.
*
* @param location the offset in bits from the start of the array of bytes.
*/
public void setPointer(int location)
{
if (location < 0 || location > end)
throw new IllegalArgumentException();
ptr = location;
}
/**
* Adds offset, in bits, to the internal pointer to change the location
* where the next value will be read or written. If the adjust causes the
* point to fall outside the bounds of the internal data then the value
* is clamped to either the start of end of the array.
*
* @param offset the offset in bits from the start of the array of bytes.
*/
public void adjustPointer(int offset)
{
ptr += offset;
if (ptr < 0)
ptr = 0;
else if (ptr >= end)
ptr = end;
}
/**
* Moves the internal pointer forward so it is aligned on a byte boundary.
* All word values read and written to the internal buffer must be
* byte-aligned.
*/
public void alignToByte()
{
ptr = (ptr+7) & ~7;
}
/**
* Returns true of the internal pointer is at the end of the buffer.
*
* @return true if the pointer is at the end of the buffer, false otherwise.
*/
public boolean eof()
{
return ptr >= end;
}
/*
* Core methods for readig and writing bits and multibyte words
*/
/**
* Read a bit field from the internal buffer.
*
* If a buffer overflow would occur then the bits which would cause the
* error when read will be set to zero.
*
* @param numberOfBits the number of bits to read.
*
* @param signed a boolean flag indicating whether the value read should
* be sign extended.
*
* @return the value read.
*/
public int readBits(int numberOfBits, boolean signed)
{
int value = 0;
if (numberOfBits < 0 || numberOfBits > 32)
throw new IllegalArgumentException("Number of bits must be in the range 1..32.");
if (numberOfBits == 0)
return 0;
int index = ptr >> 3;
int base = (data.length - index > 4) ? 0 : (4 - (data.length - index))*8;
for (int i=32; i>base; i-=8, index++)
value |= (data[index] & 0x000000FF) << (i-8);
value <<= ptr % 8;
if (signed)
value >>= 32 - numberOfBits;
else
value >>>= 32 - numberOfBits;
ptr += numberOfBits;
if (ptr > (data.length << 3))
ptr = data.length << 3;
return value;
}
/**
* Write a bit value to the internal buffer. The buffer will resize
* automatically if required.
*
* @param value an integer containing the value to be written.
* @param numberOfBits the least significant n bits from the value that
* will be written to the buffer.
*/
public void writeBits(int value, int numberOfBits)
{
if (numberOfBits < 0 || numberOfBits > 32)
throw new IllegalArgumentException("Number of bits must be in the range 1..32.");
if (ptr+32 > end)
addCapacity(data.length/2+4);
int index = ptr >> 3;
value <<= (32 - numberOfBits);
value = value >>> (ptr % 8);
value = value | (data[index] << 24);
for (int i=24; i>=0; i-=8, index++)
data[index] = (byte)(value >>> i);
ptr += numberOfBits;
if (ptr > (data.length << 3))
ptr = data.length << 3;
}
/**
* Read a word from the internal buffer.
*
* If a buffer overflow would occur then the bytes which would cause the
* error when read will be set to zero.
*
* @param numberOfBytes the number of bytes read in the range 1..4.
*
* @param signed a boolean flag indicating whether the value read should be
* sign extended.
*
* @return the value read.
*/
public int readWord(int numberOfBytes, boolean signed)
{
int value = 0;
if (numberOfBytes < 0 || numberOfBytes > 4)
throw new IllegalArgumentException("Number of bytes must be in the range 1..4.");
int index = ptr >> 3;
if (index + numberOfBytes > data.length)
numberOfBytes = data.length - index;
int numberOfBits = numberOfBytes*8;
if (byteOrder == LITTLE_ENDIAN)
{
for (int i=0; i<numberOfBits; i+=8, ptr+=8, index++)
value += (data[index] & 0x000000FF) << i;
}
else
{
for (int i=0; i<numberOfBits; i+=8, ptr+=8, index++)
{
value = value << 8;
value += data[index] & 0x000000FF;
}
}
if (signed)
{
value <<= 32 - numberOfBits;
value >>= 32 - numberOfBits;
}
return value;
}
/**
* Write a word to the internal buffer. The buffer will resize automatically
* if required.
*
* @param value an integer containing the value to be written.
* @param numberOfBytes the least significant n bytes from the value that
* will be written to the buffer.
*/
public void writeWord(int value, int numberOfBytes)
{
if (numberOfBytes < 0 || numberOfBytes > 4)
throw new IllegalArgumentException("Number of bytes must be in the range 1..4.");
int numberOfBits = numberOfBytes*8;
if (ptr+numberOfBits > end)
addCapacity(data.length/2+numberOfBytes);
if (byteOrder == LITTLE_ENDIAN)
{
int index = ptr >>> 3;
for (int i=0; i<numberOfBits; i+=8, ptr+=8, value >>>= 8, index++)
data[index] = (byte)value;
}
else
{
int index = (ptr + numberOfBits - 8) >>> 3;
for (int i=0; i<numberOfBits; i+=8, ptr+=8, value >>>= 8, index--)
data[index] = (byte)value;
}
}
/**
* Reads an array of bytes from the internal buffer. If a read overflow
* would occur while reading the internal buffer then the remaining bytes
* in the array will not be filled. The method returns the number of bytes
* read.
*
* @param bytes the array that will contain the bytes read.
* @return the number of bytes read from the buffer.
*/
public int readBytes(byte[] bytes)
{
int bytesRead = 0;
if (bytes == null || bytes.length == 0)
return bytesRead;
int index = ptr >>> 3;
int numberOfBytes = bytes.length;
if (index + numberOfBytes > data.length)
numberOfBytes = data.length - index;
for (int i=0; i<numberOfBytes; i++, ptr+=8, index++, bytesRead++)
bytes[i] = data[index];
return bytesRead;
}
/**
* Writes an array of bytes from the internal buffer. The internal buffer
* will be resized automatically if required.
*
* @param bytes the array containing the data to be written.
* @return the number of bytes written to the buffer.
*/
public int writeBytes(byte[] bytes)
{
int bytesWritten = 0;
if (ptr+(bytes.length << 3) > end)
addCapacity(data.length/2+bytes.length);
if (bytes == null || bytes.length == 0)
return bytesWritten;
int index = ptr >>> 3;
int numberOfBytes = bytes.length;
for (int i=0; i<numberOfBytes; i++, ptr+=8, index++, bytesWritten++)
data[index] = bytes[i];
return bytesWritten;
}
/*
* Methods to lookahead at the data without reading.
*/
/**
* Read a bit field without adjusting the internal pointer.
*
* @param numberOfBits the number of bits to read.
*
* @param signed a boolean flag indicating whether the value read should
* be sign extended.
*
* @return the value read.
*/
public int scanBits(int numberOfBits, boolean signed)
{
int start = ptr;
int value = readBits(numberOfBits, signed);
ptr = start;
return value;
}
/**
* Read a word without adjusting the internal pointer.
*
* @param numberOfBytes the number of bytes to read.
*
* @param signed a boolean flag indicating whether the value read should
* be sign extended.
*
* @return the value read.
*/
public int scanWord(int numberOfBytes, boolean signed)
{
int start = ptr;
int value = readWord(numberOfBytes, signed);
ptr = start;
return value;
}
/*
* Methods for accessing fixed point (8.8) and (16.16) values.
*/
/**
* Read a fixed point number, in either (8.8) or (16.16) format from a bit
* field.
*
* @param numberOfBits the number of bits the number is encoded in.
* @param fractionSize the number of bits occupied by the fractional
* part of the number. The integer part will be signed extended.
*
* @return the value read as a floating-point number.
*/
public float readFixedBits(int numberOfBits, int fractionSize)
{
float divisor = (float)(1 << fractionSize);
float value = ((float)readBits(numberOfBits, true)) / divisor;
return value;
}
/**
* Write a fixed point number, in either (8.8) or (16.16) format to a bit
* field.
*
* @param value the value to be ecoded.
* @param numberOfBits the number of bits the number is encoded in.
* @param fractionSize the number of bits occupied by the fractional
* part of the number. The integer part will be signed extended.
*/
public void writeFixedBits(float value, int numberOfBits, int fractionSize)
{
float multiplier = (float)(1 << fractionSize);
writeBits((int)(value*multiplier), numberOfBits);
}
/**
* Read a fixed point number, in either (8.8) or (16.16) format from a
* word field, accounting for the byte-ordering used.
*
* @param mantissaSize the number of bits occupied by the integer
* part of the number. This will be signed extended.
* @param fractionSize the number of bits occupied by the fractional
* part of the number.
*
* @return the value read as a floating-point number.
*/
public float readFixedWord(int mantissaSize, int fractionSize)
{
float divisor = (float)(1 << (fractionSize*8));
int fraction = readWord(fractionSize, false);
int mantissa = readWord(mantissaSize, true) << (fractionSize*8);
return (mantissa + fraction) / divisor;
}
/**
* Write a fixed point number, in either (8.8) or (16.16) format to a
* word field, accounting for the byte-ordering used.
*
* @param value the value to be written.
* @param mantissaSize the number of bits occupied by the integer
* part of the number.
* @param fractionSize the number of bits occupied by the fractional
* part of the number.
*/
public void writeFixedWord(float value, int mantissaSize, int fractionSize)
{
float multiplier = (float)(1 << (fractionSize*8));
int fraction = (int)(value*multiplier);
int mantissa = (int)value;
writeWord(fraction, fractionSize);
writeWord(mantissa, mantissaSize);
}
/*
* Methods for reading specific data types
*/
/**
* Read a double-precision floating point number from a sequence of bytes
* using the byte-ordering of the buffer.
*
* @return the value.
*/
public double readDouble()
{
int upperInt = readWord(4, false);
int lowerInt = readWord(4, false);
long longValue = (long)upperInt << 32;
longValue |= (long)lowerInt & 0x00000000FFFFFFFFL;
return Double.longBitsToDouble(longValue);
}
/**
* Write a double-precision floating point number as a sequence of bytes
* using the byte-ordering of the buffer.
*
* @param value the value to be written.
*/
public void writeDouble(double value)
{
long longValue = Double.doubleToLongBits(value);
int lowerInt = (int)longValue;
int upperInt = (int)(longValue >>> 32);
writeWord(upperInt, 4);
writeWord(lowerInt, 4);
}
/**
* Read a string containing the specified number of characters using the
* default character encoding scheme.
*
* @param length the number of characters to read.
*
* @return the string containing the specified number of characters.
*/
public String readString(int length)
{
return readString(length, encoding);
}
/**
* Read a string containing the specified number of characters with the
* given character encoding scheme.
*
* @param length the number of characters to read.
* @return enc, the string the name of the encoding schemd for characters.
*
* @return the string containing the specified number of characters.
*/
public String readString(int length, String enc)
{
if (length == 0)
return "";
String value = null;
byte[] str = new byte[length];
int len = readBytes(str);
try {
value = new String(str, 0, len, enc);
}
catch (java.io.UnsupportedEncodingException e)
{
value = "";
}
return value;
}
/**
* Read a null-terminated string using the default character encoding scheme.
*
* @return the string read from the internal buffer.
*/
public String readString()
{
return readString(encoding);
}
/**
* Read a null-terminated string using the specified character encoding scheme.
*
* @return the string read from the internal buffer.
*/
public String readString(String enc)
{
String value = null;
int start = ptr>>3;
int length = 0;
while (start < data.length && data[start++] != 0) length++;
byte[] str = new byte[length];
int len = readBytes(str);
try {
value = new String(str, 0, len, enc);
}
catch (java.io.UnsupportedEncodingException e)
{
value = "";
}
readWord(1, false);
len++;
return value;
}
/**
* Write a string to the internal buffer using the default character
* encoding scheme.
*
* @param str the string.
*
* @return the number of bytes written.
*/
public int writeString(String str)
{
return writeString(str, encoding);
}
/**
* Write a string to the internal buffer using the specified character
* encoding scheme.
*
* @param str the string.
*
* @return the number of bytes written.
*/
public int writeString(String str, String enc)
{
int bytesWritten = 0;
try
{
bytesWritten = writeBytes(str.getBytes(enc));
}
catch (java.io.UnsupportedEncodingException e)
{
}
return bytesWritten;
}
/*
* Methods for searching the data
*/
/**
* Searches the internal buffer for a bit pattern and advances the pointer
* to the start of the bit field, returning true to signal a successful
* search. If the bit pattern cannot be found then the method returns false
* and the position of the internal pointer is not changed.
*
* The step, in bits, added to the pointer can be specified, allowing the
* number of bits being searched to be independent of the location in the
* internal buffer. This is useful for example when searching for a bit
* field that begins on a byte or word boundary.
*
* @param value an integer containing the bit patter to search for.
* @param numberOfBits least significant n bits in the value to search for.
* @param step the increment in bits to add to the internal pointer as the
* buffer is searched.
*
* @return true if the pattern was found, false otherwise.
*/
public boolean findBits(int value, int numberOfBits, int step)
{
boolean found = false;
int start = ptr;
for (; ptr < end; ptr += step)
{
if (scanBits(numberOfBits, false) == value)
{
found = true;
break;
}
}
if (found == false)
ptr = start;
return found;
}
/**
* Searches the internal buffer for a word and advances the pointer to the
* location where the word was found, returning true to signal a successful
* search. The search will begin on the next byte boundary. If word cannot
* be found then the method returns false and the position of the internal
* pointer is not changed.
*
* Specifying the number of bytes in the search value allows word of either
* 8, 16, 24 or 32 bits to be searched for. Searches for words are performed
* faster than using the findBits() method.
*
* @param value an integer containing the word to search for.
*
* @param numberOfBytes least significant n bytes in the value to search
* for.
*
* @param step the increment in bits to add to the internal pointer as the
* buffer is searched.
*
* @return true if the pattern was found, false otherwise.
*/
public boolean findWord(int value, int numberOfBytes, int step)
{
boolean found = false;
for (; ptr < end; ptr += step)
{
if (scanWord(numberOfBytes, false) == value)
{
found = true;
break;
}
}
return found;
}
/*
* Context variables are used to pass information between objects when
* they are being encoded or decoded. Context variables are primarily
* used within the Transform classes however they are also used when
* performing unit tests on classes.
*/
/**
* TransparentColors is used to pass information to FSCOlor objects when
* they are being encoded or decoded so that the alpha channel will be
* included.
*/
public static final int TransparentColors = 0;
static final int Action = 1;
/**
* Version is used to pass the current version of Flash that an object is
* being encoded or decoded for.
*/
public static final int Version = 2;
static final int Type = 3;
static final int Empty = 4;
static final int Identifier = 5;
static final int NumberOfFillBits = 6;
static final int NumberOfLineBits = 7;
static final int NumberOfAdvanceBits = 8;
static final int NumberOfGlyphBits = 9;
static final int NumberOfShapeBits = 10;
static final int ArrayCountExtended = 11;
static final int WideCodes = 12;
static final int Delta = 13;
static final int CodingError = 14;
static final int TypeInError = 15;
static final int StartOfError = 16;
static final int ExpectedLength = 17;
static final int DecodeActions = 18;
static final int DecodeShapes = 19;
static final int DecodeGlyphs = 20;
int[] context = new int[21];
private void clearContext()
{
for (int i=0; i<context.length; i++)
context[i] = 0;
}
public int getContext(int key)
{
return context[key];
}
public void setContext(int key, int value)
{
context[key] = value;
}
}
<file_sep>/Rover 2.0-android-src/src/com/wificar/component/AudioComponent.java
package com.wificar.component;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import com.wificar.external.ADPCM;
import com.wificar.external.FSCoder;
import com.wificar.util.ByteUtility;
import android.content.Context;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.util.Log;
public class AudioComponent {
private static int[] stepTable = { 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19,
21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97,
107, 118, 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337,
371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166,
1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327,
3660, 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493,
10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, 22385,
24623, 27086, 29794, 32767 };
private static int[] indexAdjust = { -1, -1, -1, -1, 2, 4, 6, 8 };
private int sampleRateInHz = 8000;
// private static final String LOG_TAG = "AudioRecordTest";
// private static String mFileName = null;
private MediaRecorder mRecorder = null;
private MediaPlayer mPlayer = null;
private AudioRecord audioRecord;
private AudioTrack track;
private int bufferSize = 0;
private WifiCar wificar = null;
public AudioComponent(WifiCar wificar) {
this.wificar = wificar;
this.initialPlayer(sampleRateInHz);
// initialRecorder();
}
/*
* private void onRecord(boolean start) { if (start) { startRecording(); }
* else { stopRecording(); } }
*
* private void onPlay(boolean start) { if (start) { startPlaying(); } else
* { stopPlaying(); } }
*
* private void startPlaying() { mPlayer = new MediaPlayer(); try {
* mPlayer.setDataSource(mFileName);
*
* mPlayer.prepare(); mPlayer.start(); } catch (IOException e) {
* Log.e(LOG_TAG, "prepare() failed"); } }
*
* private void stopPlaying() { mPlayer.release(); mPlayer = null; }
*
* private void startRecording() { mRecorder = new MediaRecorder();
* mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
* mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
* mRecorder.setOutputFile(mFileName);
* mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
*
* try { mRecorder.prepare(); } catch (IOException e) { Log.e(LOG_TAG,
* "prepare() failed"); }
*
* mRecorder.start(); }
*
* private void stopRecording() {
*
* mRecorder.stop(); mRecorder.release(); mRecorder = null; }
*/
private boolean isRecording = false;
private Thread recordThread = null;
private Thread sendThread = null;
private ArrayList audioDataList = new ArrayList();
private final Object mutex = new Object();
public void startRecord() {
if(isRecording) return;
synchronized (mutex) {
isRecording = true;
//Log.d("mic", "start recorder");
final int customBufferSize = 640;
recordThread = new Thread(new Runnable() {
public void run() {
//Log.d("mic", "initial recorder");
initialRecorder();
// initialPlayer(8000);
//Log.d("mic", "state:(" + audioRecord.getState() + ")");
if (audioRecord.getState() == audioRecord.STATE_UNINITIALIZED) {
return;
}
audioRecord.startRecording();
int serial = 0;
int index = 0;
int ticktime = 0;
int timestamp = 0;
int sample = 0;
while (isRecording) {
byte[] buffer = new byte[customBufferSize];
int readState = audioRecord.read(buffer, 0,
customBufferSize);
// byte[] audioData = buffer.clone();
if (readState == audioRecord.ERROR) {
//Log.d("mic", "state:(ERROR)");
} else if (readState == audioRecord.ERROR_BAD_VALUE) {
//Log.d("mic", "state:(ERROR_BAD_VALUE)");
} else if (readState == audioRecord.ERROR_INVALID_OPERATION) {
//Log.d("mic", "state:(ERROR_INVALID_OPERATION)");
} else {
//Log.d("mic", "state:(S)");
}
// mPlayer.
// audioRecord.get
// if(audioDataList.size()>=2){
// byte[] adpcmData = ADPCM.compress(audioData,
// audioRecord.getChannelCount(),
// audioRecord., 160);
//Log.d("mic", "state:(" + readState + ")");
// Log.d("mic","("+isRecording+")recorder length:"+customBufferSize+",index:"+index+",sample:"+sample);
// Log.d("mic",ByteUtility.bytesToHex(audioData));
TalkData data = encodeAdpcm(buffer, buffer.length,
sample, index);
data.setSerial(serial);
data.setTicktime(ticktime);
data.setTimestamp(timestamp);
sample = data.getParaSample();
index = data.getParaIndex();
// CommandEncoder.Protocol cmd =
// CommandEncoder.createTalkData(data);
// trackPlayer.write(buffer, 0, buffer.length);
// trackPlayer.flush();
try {
wificar.sendTalkData(data, 0);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//Log.d("mic", "data:" + data.getData().length);
// wificar.sendAudio(audioData);
// Log.d("wild0","send audio record:"+System.currentTimeMillis());
// }
// audioDataList.add(audioData);
ticktime = ticktime + 40;
serial++;
timestamp = (int) (System.currentTimeMillis() / 1000);
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Log.d("mic", "state:(" + audioRecord.getState() + ")stop");
//if (audioRecord != null) {
audioRecord.stop();
audioRecord.release();
audioRecord = null;
//}
// record(out);
}
});
recordThread.setName("Recording Thread");
//android.os.Process
// .setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
recordThread.start();
}
}
/*
* public void record1() { isRecording = true; final int customBufferSize =
* 640; final int maxCustomBufferSize = 4096; initialRecorder();
* Log.d("recordplay","record"); //ByteArrayOutputStream baos = new
* ByteArrayOutputStream(); //baos.
*
*
*
* recordThread = new Thread(new Runnable() { public void run() { ByteBuffer
* bb = ByteBuffer.allocate(maxCustomBufferSize*5);
* audioRecord.startRecording();
*
* int serial=0; int index= 0; int ticktime= 0; int timestamp = 0; int
* sample =0;
*
* int remaind = 0;
*
* //int position = 0; //audioRecord.
*
*
* while(isRecording){ byte[] buffer = new byte[maxCustomBufferSize]; int
* readState = 0;
*
* readState = audioRecord.read(buffer,0, maxCustomBufferSize);
* if(readState==audioRecord.ERROR){
*
* } else if(readState==audioRecord.ERROR_BAD_VALUE){
*
* } else if(readState==audioRecord.ERROR_INVALID_OPERATION){
*
* } else{
*
* }
*
*
* //audioRecord.read(audioBuffer, sizeInBytes)
*
*
* bb.put(buffer); bb.position(readState+remaind ); bb.flip();
*
* Log.d("recordplay","offset:"+bb.position()+"limit:"+bb.limit()+"state:"+
* readState); byte[] partBuffer; while(bb.position()<bb.limit()){
* if((bb.limit()-bb.position())>customBufferSize){ partBuffer = new
* byte[customBufferSize]; ByteBuffer pb = bb.get(partBuffer);
*
* //position = position+customBufferSize;
*
* //Log.d("recordplay","position:"+bb.position()+",limit:"+bb.limit());
* Log.
* d("recordplay","("+isRecording+")remainder:"+bb.remaining()+",position:"
* +bb
* .position()+"recorder length:"+customBufferSize+",index:"+index+",sample:"
* +sample);
*
* TalkData data = encodeAdpcm(partBuffer, partBuffer.length, sample,
* index); data.setSerial(serial); data.setTicktime(ticktime);
* data.setTimestamp(timestamp);
*
*
* try{ //Thread.sleep(40); wificar.sendTalkData(data); } catch(Exception
* e){ e.printStackTrace(); }
*
* sample = data.getParaSample(); index = data.getParaIndex();
*
* ticktime = ticktime+40; serial++; timestamp = (int)
* (System.currentTimeMillis()/1000);
*
* } else if((bb.limit()-bb.position())==customBufferSize){ partBuffer = new
* byte[customBufferSize]; ByteBuffer pb = bb.get(partBuffer);
*
* //position = position+customBufferSize;
*
* //Log.d("recordplay","position:"+bb.position()+",limit:"+bb.limit());
* Log.
* d("recordplay","(Finish)remainder:"+bb.remaining()+",position:"+bb.position
* (
* )+"recorder length:"+customBufferSize+",index:"+index+",sample:"+sample);
*
* TalkData data = encodeAdpcm(partBuffer, partBuffer.length, sample,
* index); data.setSerial(serial); data.setTicktime(ticktime);
* data.setTimestamp(timestamp);
*
*
* try{ //Thread.sleep(40); wificar.sendTalkData(data); } catch(Exception
* e){ e.printStackTrace(); }
*
* sample = data.getParaSample(); index = data.getParaIndex();
*
* ticktime = ticktime+40; serial++; timestamp = (int)
* (System.currentTimeMillis()/1000);
*
* remaind = 0; bb.clear();
*
* Log.d("recordplay","(Finish)remainder:"+bb.remaining()+",position:"+bb.
* position
* ()+"recorder length:"+customBufferSize+",index:"+index+",sample:"+
* sample); break; } else{
* //Log.d("recordplay","remaind position:"+position+",limit:"+bb.limit());
* remaind = (bb.limit()-bb.position()); byte[] temp = new byte[remaind];
*
* bb.get(temp); bb.clear(); //position = 0;
* Log.d("recordplay","remaind position:"
* +bb.position()+",limit:"+bb.limit()); bb.put(temp);
* Log.d("recordplay","remaind position:"
* +bb.position()+",limit:"+bb.limit());
* //Log.d("recordplay","remaind[temp:"
* +remaind+"] position 2:"+bb.position()+",limit:"+bb.limit()); break; }
* System.gc(); } //sample = 0; //index = 0; //if(serial>5){ //break; //}
*
* }
*
* audioRecord.stop(); audioRecord.release();
*
* //record(out); } }); recordThread.start(); }
*/
public int initialRecorder() {
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// out.writeTo(stream);
// out¤ú¤‘¬°ÀÉ®×
/*
* File pcmFile = new File(myDataPath.getAbsolutePath() +
* "/record.pcm"); // Delete any previous recording. if
* (pcmFile.exists()) pcmFile.delete(); // Create the new file. try {
* pcmFile.createNewFile(); } catch (IOException e) { throw new
* IllegalStateException("Failed to create " + pcmFile.toString()); }
*/
// Start record pcm data
//Log.d("wild0", "audio recorder initial");
try {
// Create a DataOuputStream to write the audio data into the saved
// file.
// OutputStream os = new FileOutputStream(pcmFile);
// BufferedOutputStream bos = new BufferedOutputStream(os);
// DataOutputStream dos = new DataOutputStream(bos);
// Create a new AudioRecord object to record the audio.
bufferSize = AudioRecord
.getMinBufferSize(sampleRateInHz,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
//Log.d("recordplay", "record buffer size:" + bufferSize);
audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
sampleRateInHz, AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT, bufferSize);
// byte[] buffer = new byte[bufferSize];
/*
* audioRecord.startRecording(); while (isRecording) { int
* bufferReadResult = audioRecord.read(buffer, 0, bufferSize); for
* (int i = 0; i < bufferReadResult; i++) out.write(buffer[i]); } //
* filler, data size need can %8 = 0
*
* if (out.size() % 8 != 0) { int filler = 0; filler = 8 -
* (out.size() % 8); for (int i = 0; i < filler; i++) {
* out.write(0); } }
*
* // stop record and close the file. audioRecord.stop();
* out.close();
*/
} catch (Exception e) {
e.printStackTrace();
}
return audioRecord.getState();
// stop thread, this method may be not great, we can use the
// "thread.join( )" method
// recordThread.stop();
}
/*
* class RecordButton extends Button { boolean mStartRecording = true;
*
* OnClickListener clicker = new OnClickListener() { public void
* onClick(View v) { onRecord(mStartRecording); if (mStartRecording) {
* setText("Stop recording"); } else { setText("Start recording"); }
* mStartRecording = !mStartRecording; } };
*
* public RecordButton(Context ctx) { super(ctx);
* setText("Start recording"); setOnClickListener(clicker); } }
*
* class PlayButton extends Button { boolean mStartPlaying = true;
*
* OnClickListener clicker = new OnClickListener() { public void
* onClick(View v) { onPlay(mStartPlaying); if (mStartPlaying) {
* setText("Stop playing"); } else { setText("Start playing"); }
* mStartPlaying = !mStartPlaying; } };
*
* public PlayButton(Context ctx) { super(ctx); setText("Start playing");
* setOnClickListener(clicker); } }
*/
// public AudioRecordTest() {
// mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
// mFileName += "/audiorecordtest.3gp";
// }
/*
* @Override public void onPause() { super.onPause(); if (mRecorder != null)
* { mRecorder.release(); mRecorder = null; }
*
* if (mPlayer != null) { mPlayer.release(); mPlayer = null; } }
*/
int audioTrackBufferSize = 0;
AudioTrack trackPlayer = null;
Thread playThread = null;
private boolean isPlaying = false;
public void initialPlayer(int sampleRate) {
//Log.d("audio", "initial audio:" + sampleRate);
/*
* audioTrackBufferSize = AudioTrack.getMinBufferSize(sampleRateInHz,
* AudioFormat.CHANNEL_CONFIGURATION_MONO,
* AudioFormat.ENCODING_PCM_16BIT); trackPlayer = new
* AudioTrack(AudioManager.STREAM_MUSIC, sampleRateInHz,
* AudioFormat.CHANNEL_CONFIGURATION_MONO,
* AudioFormat.ENCODING_PCM_16BIT, audioTrackBufferSize,
* AudioTrack.MODE_STREAM);//
*/
audioTrackBufferSize = android.media.AudioTrack.getMinBufferSize(
sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT);
trackPlayer = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT, audioTrackBufferSize,
AudioTrack.MODE_STREAM);
}
public void play() {
this.initialPlayer(sampleRateInHz);
trackPlayer.play();
isPlaying = true;
// playThread = new Thread() {
// public void run() {
// byte[] buf = new byte[audioTrackBufferSize];
// trackPlayer.play();
// isPlaying = true;
// while (isPlaying) {
// trackPlayer.write(aData.getPCMData(), 0, aData.getPCMData().length);
// trackPlayer.flush();
// Log.d("audio", "playing");
/*
* try { stream.read(buf); byte[] packet = buf.clone(); // bytes_pkg =
* m_out_bytes.clone() ; trackPlayer.write(packet, 0, packet.length); }
* catch (Exception e) { e.printStackTrace(); }
*/
// try {
// Thread.sleep(50);
// } catch (InterruptedException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
// trackPlayer.stop();
// trackPlayer.release();
// }
// };
// playThread.start();
//Log.d("audio", "play audio:" + audioTrackBufferSize);
}
public void stopPlayer() {
isPlaying = false;
if (trackPlayer != null) {
trackPlayer.stop();
trackPlayer.release();
trackPlayer = null;
}
//Log.d("audio", "stop audio");
}
public void stopRecord() {
isRecording = false;
// Log.d("audio", "stop audio");
}
public void writeAudioData(AudioData aData) {
// Log.d("audio","write audio data:"+packet.length);
if (isPlaying) {
trackPlayer.write(aData.getPCMData(), 0, aData.getPCMData().length);
trackPlayer.flush();
}
// Log.d("audio",
// "playing track:"+ByteUtility.convertByteArrayToString(packet));
}
// public void closePlayer() {
// isPlaying = false;
// }
public static byte[] encodePCMToADPCM(byte[] raw, int len, int sample,
int index) {
short[] pcm = ByteUtility.bytesToShorts(raw);
byte[] adpcm = new byte[(len / 4)];
int cur_sample;
int i;
int delta;
int sb;
int code;
// Log.d("wild3", "len:"+len+",pcmlen:"+pcm.length);
len >>= 1;
// int pre_sample = refsample.getValue();
// int index = refindex.getValue();
for (i = 0; i < len; i++) {
cur_sample = pcm[i]; //
// Log.d("wild3", "cur_sample:"+cur_sample);
delta = cur_sample - sample; //
if (delta < 0) {
delta = -delta;
sb = 8; //
} else {
sb = 0;
} //
code = 4 * delta / stepTable[index]; //
if (code > 7)
code = 7; //
delta = (stepTable[index] * code) / 4 + stepTable[index] / 8; //
if (sb > 0)
delta = -delta;
sample += delta; //
if (sample > 32767)
sample = 32767;
else if (sample < -32768)
sample = -32768;
index += indexAdjust[code]; //
if (index < 0)
index = 0; //
else if (index > 88)
index = 88;
if ((i & 0x01) == 0x01)
adpcm[(i >> 1)] |= code | sb;
else
adpcm[(i >> 1)] = (byte) ((code | sb) << 4); //
}
return adpcm;
}
public static TalkData encodeAdpcm(byte[] raw, int len, int sample,
int index) {
// short[] pcm = LibcMisc.get_short_array(raw,0);
short[] pcm = ByteUtility.bytesToShorts(raw);
byte[] adpcm = new byte[(len / 4)];
int cur_sample;
int i;
int delta;
int sb;
int code;
// Log.d("wild3", "len:"+len+",pcmlen:"+pcm.length);
len >>= 1;
// int pre_sample = refsample.getValue();
// int index = refindex.getValue();
for (i = 0; i < len; i++) {
cur_sample = pcm[i]; //
// Log.d("wild3", "cur_sample:"+cur_sample);
delta = cur_sample - sample; //
if (delta < 0) {
delta = -delta;
sb = 8; //
} else {
sb = 0;
} //
code = 4 * delta / stepTable[index]; //
if (code > 7)
code = 7; //
delta = (stepTable[index] * code) / 4 + stepTable[index] / 8; //
if (sb > 0)
delta = -delta;
sample += delta; //
if (sample > 32767)
sample = 32767;
else if (sample < -32768)
sample = -32768;
index += indexAdjust[code]; //
if (index < 0)
index = 0; //
else if (index > 88)
index = 88;
if ((i & 0x01) == 0x01)
adpcm[(i >> 1)] |= code | sb;
else
adpcm[(i >> 1)] = (byte) ((code | sb) << 4); //
}
// Log.d("wild2", "adpcm data size:"+adpcm.length);
// TalkData data = new TalkData(WifiCar.data, sample, index);
TalkData data = new TalkData(adpcm, sample, index);
return data;
// refsample.setValue(pre_sample);
// refindex.setValue(index);
}
public static byte[] decodeADPCMToPCM(byte[] raw, int len, int sample,
int index) {
ByteBuffer bDecoded = ByteBuffer.allocate(len * 4);
int i;
int code;
int sb;
int delta;
// short[] pcm = new short[len * 2];
len <<= 1;
for (i = 0; i < len; i++) {
if ((i & 0x01) != 0)
code = raw[i >> 1] & 0x0f;
else
code = raw[i >> 1] >> 4;
if ((code & 8) != 0)
sb = 1;
else
sb = 0;
code &= 7;
delta = (stepTable[index] * code) / 4 + stepTable[index] / 8;
if (sb != 0)
delta = -delta;
sample += delta;
if (sample > 32767)
sample = 32767;
else if (sample < -32768)
sample = -32768;
// pcm[i] = (short)pre_sample;
bDecoded.put(CommandEncoder.int16ToByteArray(sample));
index += indexAdjust[code];
if (index < 0)
index = 0;
if (index > 88)
index = 88;
}
return bDecoded.array();
}
/*
* public static byte[] decodeAdpcm(byte[] raw, int len, int sample, int
* index) { ByteBuffer bDecoded = ByteBuffer.allocate(len * 4);
*
* int i; int code; int sb; int delta; // short[] pcm = new short[len * 2];
* len <<= 1;
*
* for (i = 0; i < len; i++) { if ((i & 0x01) != 0) code = raw[i >> 1] &
* 0x0f; else code = raw[i >> 1] >> 4; if ((code & 8) != 0) sb = 1; else sb
* = 0; code &= 7;
*
* delta = (stepTable[index] * code) / 4 + stepTable[index] / 8; if (sb !=
* 0) delta = -delta; sample += delta; if (sample > 32767) sample = 32767;
* else if (sample < -32768) sample = -32768; // pcm[i] = (short)pre_sample;
* bDecoded.put(CommandEncoder.int16ToByteArray(sample)); index +=
* indexAdjust[code]; if (index < 0) index = 0; if (index > 88) index = 88;
* }
*
* return bDecoded.array(); }
*/
}<file_sep>/Rover 2.0-android-src/src/com/wificar/util/BlowFish.java
package com.wificar.util;
public class BlowFish {
public int ROUNDCOUNT = 16;
static class Ctx{
static public int S[][] = new int[4][256];
static public int P[] = new int [18];
}
public int F1(int x)
{
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int y;
/*
d=(short)x & 0x00FF;
x >>= 8;
c=(short)x & 0x00FF;
x >>= 8;
b=(short)x & 0x00FF;
x >>=8;
a=(short)x & 0x00FF;
*/
d=((short)x & 0x00FF);
x >>= 8;
c=((short)x & 0x00FF);
x >>= 8;
b=((short)x & 0x00FF);
x >>=8;
a=((short)x & 0x00FF);
y=Ctx.S[0][a]+Ctx.S[1][b];
y=y ^ Ctx.S[2][c];
y=y + Ctx.S[3][d];
return y;
}
public int[] Blowfish_encipher( int xl[],int xr[])
{
int Xl;
int Xr;
int temp;
//short i;
Xl=xl[0];
Xr=xr[0];
int i;
for (i=0; i<ROUNDCOUNT;++i){
Xl=Xl^Ctx.P[i];
Xr=F1(Xl)^Xr;
temp=Xl;
Xl=Xr;
Xr=temp;
}
temp=Xl;
Xl=Xr;
Xr=temp;
Xr=Xr^Ctx.P[ROUNDCOUNT];
Xl=Xl^Ctx.P[ROUNDCOUNT+1];
xl[0] = Xl;
xr[0] = Xr;
return new int[]{Xl, Xr};
//*xl=Xl;
//*xr=Xr;
}
public int[] Blowfish_decipher(int xl[], int xr[])
{
int Xl;
int Xr;
int temp;
Xl=xl[0];
Xr=xr[0];
int i;
for (i=ROUNDCOUNT+1;i>1;--i){
Xl=Xl^Ctx.P[i];
Xr=F1(Xl)^Xr;
temp=Xl;
Xl=Xr;
Xr=temp;
}
temp=Xl;
Xl=Xr;
Xr=temp;
Xr=Xr ^ Ctx.P[1];
Xl=Xl ^ Ctx.P[0];
xl[0] = Xl;
xr[0] = Xr;
return new int[]{Xl, Xr};
//*xl=Xl;
//*xr=Xr;
}
public void InitBlowfish (byte[] key,int key_len)
{
//short error;
//short numread;
int data;
int data1[];
int datar[];
int ks0[]={
0xd1310ba6,0x98dfb5ac,0x2ffd72db,0xd01adfb7,0xb8e1afed,0x6a267e96,
0xba7c9045,0xf12c7f99,0x24a19947,0xb3916cf7,0x0801f2e2,0x858efc16,
0x636920d8,0x71574e69,0xa458fea3,0xf4933d7e,0x0d95748f,0x728eb658,
0x718bcd58,0x82154aee,0x7b54a41d,0xc25a59b5,0x9c30d539,0x2af26013,
0xc5d1b023,0x286085f0,0xca417918,0xb8db38ef,0x8e79dcb0,0x603a180e,
0x6c9e0e8b,0xb01e8a3e,0xd71577c1,0xbd314b27,0x78af2fda,0x55605c60,
0xe65525f3,0xaa55ab94,0x57489862,0x63e81440,0x55ca396a,0x2aab10b6,
0xb4cc5c34,0x1141e8ce,0xa15486af,0x7c72e993,0xb3ee1411,0x636fbc2a,
0x2ba9c55d,0x741831f6,0xce5c3e16,0x9b87931e,0xafd6ba33,0x6c24cf5c,
0x7a325381,0x28958677,0x3b8f4898,0x6b4bb9af,0xc4bfe81b,0x66282193,
0x61d809cc,0xfb21a991,0x487cac60,0x5dec8032,0xef845d5d,0xe98575b1,
0xdc262302,0xeb651b88,0x23893e81,0xd396acc5,0x0f6d6ff3,0x83f44239,
0x2e0b4482,0xa4842004,0x69c8f04a,0x9e1f9b5e,0x21c66842,0xf6e96c9a,
0x670c9c61,0xabd388f0,0x6a51a0d2,0xd8542f68,0x960fa728,0xab5133a3,
0x6eef0b6c,0x137a3be4,0xba3bf050,0x7efb2a98,0xa1f1651d,0x39af0176,
0x66ca593e,0x82430e88,0x8cee8619,0x456f9fb4,0x7d84a5c3,0x3b8b5ebe,
0xe06f75d8,0x85c12073,0x401a449f,0x56c16aa6,0x4ed3aa62,0x363f7706,
0x1bfedf72,0x429b023d,0x37d0d724,0xd00a1248,0xdb0fead3,0x49f1c09b,
0x075372c9,0x80991b7b,0x25d479d8,0xf6e8def7,0xe3fe501a,0xb6794c3b,
0x976ce0bd,0x04c006ba,0xc1a94fb6,0x409f60c4,0x5e5c9ec2,0x196a2463,
0x68fb6faf,0x3e6c53b5,0x1339b2eb,0x3b52ec6f,0x6dfc511f,0x9b30952c,
0xcc814544,0xaf5ebd09,0xbee3d004,0xde334afd,0x660f2807,0x192e4bb3,
0xc0cba857,0x45c8740f,0xd20b5f39,0xb9d3fbdb,0x5579c0bd,0x1a60320a,
0xd6a100c6,0x402c7279,0x679f25fe,0xfb1fa3cc,0x8ea5e9f8,0xdb3222f8,
0x3c7516df,0xfd616b15,0x2f501ec8,0xad0552ab,0x323db5fa,0xfd238760,
0x53317b48,0x3e00df82,0x9e5c57bb,0xca6f8ca0,0x1a87562e,0xdf1769db,
0xd542a8f6,0x287effc3,0xac6732c6,0x8c4f5573,0x695b27b0,0xbbca58c8,
0xe1ffa35d,0xb8f011a0,0x10fa3d98,0xfd2183b8,0x4afcb56c,0x2dd1d35b,
0x9a53e479,0xb6f84565,0xd28e49bc,0x4bfb9790,0xe1ddf2da,0xa4cb7e33,
0x62fb1341,0xcee4c6e8,0xef20cada,0x36774c01,0xd07e9efe,0x2bf11fb4,
0x95dbda4d,0xae909198,0xeaad8e71,0x6b93d5a0,0xd08ed1d0,0xafc725e0,
0x8e3c5b2f,0x8e7594b7,0x8ff6e2fb,0xf2122b64,0x8888b812,0x900df01c,
0x4fad5ea0,0x688fc31c,0xd1cff191,0xb3a8c1ad,0x2f2f2218,0xbe0e1777,
0xea752dfe,0x8b021fa1,0xe5a0cc0f,0xb56f74e8,0x18acf3d6,0xce89e299,
0xb4a84fe0,0xfd13e0b7,0x7cc43b81,0xd2ada8d9,0x165fa266,0x80957705,
0x93cc7314,0x211a1477,0xe6ad2065,0x77b5fa86,0xc75442f5,0xfb9d35cf,
0xebcdaf0c,0x7b3e89a0,0xd6411bd3,0xae1e7e49,0x00250e2d,0x2071b35e,
0x226800bb,0x57b8e0af,0x2464369b,0xf009b91e,0x5563911d,0x56dfa6aa,
0x78c14389,0xd95a537f,0x207d5ba2,0x02e5b9c5,0x83260376,0x6295cfa9,
0x11c81968,0x4e734a41,0xb3472dca,0x7b14a94a,0x1b510052,0x9a532915,
0xd60f573f,0xbc9bc6e4,0x2b60a476,0x81e67400,0x08ba6fb5,0x571be91f,
0xf296ec6b,0x2a0dd915,0xb6636521,0xe7b9f9b6,0xff340528,0xc5855664,
0x53b02d5d,0xa99f8fa1,0x08ba4799,0x6e85076a};
int ks1[]={
0x4b7a70e9,0xb5b32944,0xdb75092e,0xc4192623,0xad6ea6b0,0x49a7df7d,
0x9cee60b8,0x8fedb266,0xecaa8c71,0x699a17ff,0x5664526c,0xc2b19ee1,
0x193602a5,0x75094c29,0xa0591340,0xe4183a3e,0x3f54989a,0x5b429d65,
0x6b8fe4d6,0x99f73fd6,0xa1d29c07,0xefe830f5,0x4d2d38e6,0xf0255dc1,
0x4cdd2086,0x8470eb26,0x6382e9c6,0x021ecc5e,0x09686b3f,0x3ebaefc9,
0x3c971814,0x6b6a70a1,0x687f3584,0x52a0e286,0xb79c5305,0xaa500737,
0x3e07841c,0x7fdeae5c,0x8e7d44ec,0x5716f2b8,0xb03ada37,0xf0500c0d,
0xf01c1f04,0x0200b3ff,0xae0cf51a,0x3cb574b2,0x25837a58,0xdc0921bd,
0xd19113f9,0x7ca92ff6,0x94324773,0x22f54701,0x3ae5e581,0x37c2dadc,
0xc8b57634,0x9af3dda7,0xa9446146,0x0fd0030e,0xecc8c73e,0xa4751e41,
0xe238cd99,0x3bea0e2f,0x3280bba1,0x183eb331,0x4e548b38,0x4f6db908,
0x6f420d03,0xf60a04bf,0x2cb81290,0x24977c79,0x5679b072,0xbcaf89af,
0xde9a771f,0xd9930810,0xb38bae12,0xdccf3f2e,0x5512721f,0x2e6b7124,
0x501adde6,0x9f84cd87,0x7a584718,0x7408da17,0xbc9f9abc,0xe94b7d8c,
0xec7aec3a,0xdb851dfa,0x63094366,0xc464c3d2,0xef1c1847,0x3215d908,
0xdd433b37,0x24c2ba16,0x12a14d43,0x2a65c451,0x50940002,0x133ae4dd,
0x71dff89e,0x10314e55,0x81ac77d6,0x5f11199b,0x043556f1,0xd7a3c76b,
0x3c11183b,0x5924a509,0xf28fe6ed,0x97f1fbfa,0x9ebabf2c,0x1e153c6e,
0x86e34570,0xeae96fb1,0x860e5e0a,0x5a3e2ab3,0x771fe71c,0x4e3d06fa,
0x2965dcb9,0x99e71d0f,0x803e89d6,0x5266c825,0x2e4cc978,0x9c10b36a,
0xc6150eba,0x94e2ea78,0xa5fc3c53,0x1e0a2df4,0xf2f74ea7,0x361d2b3d,
0x1939260f,0x19c27960,0x5223a708,0xf71312b6,0xebadfe6e,0xeac31f66,
0xe3bc4595,0xa67bc883,0xb17f37d1,0x018cff28,0xc332ddef,0xbe6c5aa5,
0x65582185,0x68ab9802,0xeecea50f,0xdb2f953b,0x2aef7dad,0x5b6e2f84,
0x1521b628,0x29076170,0xecdd4775,0x619f1510,0x13cca830,0xeb61bd96,
0x0334fe1e,0xaa0363cf,0xb5735c90,0x4c70a239,0xd59e9e0b,0xcbaade14,
0xeecc86bc,0x60622ca7,0x9cab5cab,0xb2f3846e,0x648b1eaf,0x19bdf0ca,
0xa02369b9,0x655abb50,0x40685a32,0x3c2ab4b3,0x319ee9d5,0xc021b8f7,
0x9b540b19,0x875fa099,0x95f7997e,0x623d7da8,0xf837889a,0x97e32d77,
0x11ed935f,0x16681281,0x0e358829,0xc7e61fd6,0x96dedfa1,0x7858ba99,
0x57f584a5,0x1b227263,0x9b83c3ff,0x1ac24696,0xcdb30aeb,0x532e3054,
0x8fd948e4,0x6dbc3128,0x58ebf2ef,0x34c6ffea,0xfe28ed61,0xee7c3c73,
0x5d4a14d9,0xe864b7e3,0x42105d14,0x203e13e0,0x45eee2b6,0xa3aaabea,
0xdb6c4f15,0xfacb4fd0,0xc742f442,0xef6abbb5,0x654f3b1d,0x41cd2105,
0xd81e799e,0x86854dc7,0xe44b476a,0x3d816250,0xcf62a1f2,0x5b8d2646,
0xfc8883a0,0xc1c7b6a3,0x7f1524c3,0x69cb7492,0x47848a0b,0x5692b285,
0x095bbf00,0xad19489d,0x1462b174,0x23820e00,0x58428d2a,0x0c55f5ea,
0x1dadf43e,0x233f7061,0x3372f092,0x8d937e41,0xd65fecf1,0x6c223bdb,
0x7cde3759,0xcbee7460,0x4085f2a7,0xce77326e,0xa6078084,0x19f8509e,
0xe8efd855,0x61d99735,0xa969a7aa,0xc50c06c2,0x5a04abfc,0x800bcadc,
0x9e447a2e,0xc3453484,0xfdd56705,0x0e1e9ec9,0xdb73dbd3,0x105588cd,
0x675fda79,0xe3674340,0xc5c43465,0x713e38d8,0x3d28f89e,0xf16dff20,
0x153e21e7,0x8fb03d4a,0xe6e39f2b,0xdb83adf7};
int ks2[]={
0xe93d5a68,0x948140f7,0xf64c261c,0x94692934,0x411520f7,0x7602d4f7,
0xbcf46b2e,0xd4a20068,0xd4082471,0x3320f46a,0x43b7d4b7,0x500061af,
0x1e39f62e,0x97244546,0x14214f74,0xbf8b8840,0x4d95fc1d,0x96b591af,
0x70f4ddd3,0x66a02f45,0xbfbc09ec,0x03bd9785,0x7fac6dd0,0x31cb8504,
0x96eb27b3,0x55fa3941,0xda2547e6,0xabca0a9a,0x28507825,0x530429f4,
0x0a2c86da,0xe9b66dfb,0x68dc1462,0xd7486900,0x680ec0a4,0x27a18dee,
0x4f3ffea2,0xe887ad8c,0xb58ce006,0x7af4d6b6,0xaace1e7c,0xd3375fec,
0xce78a399,0x406b2a42,0x20fe9e35,0xd9f385b9,0xee39d7ab,0x3b124e8b,
0x1dc9faf7,0x4b6d1856,0x26a36631,0xeae397b2,0x3a6efa74,0xdd5b4332,
0x6841e7f7,0xca7820fb,0xfb0af54e,0xd8feb397,0x454056ac,0xba489527,
0x55533a3a,0x20838d87,0xfe6ba9b7,0xd096954b,0x55a867bc,0xa1159a58,
0xcca92963,0x99e1db33,0xa62a4a56,0x3f3125f9,0x5ef47e1c,0x9029317c,
0xfdf8e802,0x04272f70,0x80bb155c,0x05282ce3,0x95c11548,0xe4c66d22,
0x48c1133f,0xc70f86dc,0x07f9c9ee,0x41041f0f,0x404779a4,0x5d886e17,
0x325f51eb,0xd59bc0d1,0xf2bcc18f,0x41113564,0x257b7834,0x602a9c60,
0xdff8e8a3,0x1f636c1b,0x0e12b4c2,0x02e1329e,0xaf664fd1,0xcad18115,
0x6b2395e0,0x333e92e1,0x3b240b62,0xeebeb922,0x85b2a20e,0xe6ba0d99,
0xde720c8c,0x2da2f728,0xd0127845,0x95b794fd,0x647d0862,0xe7ccf5f0,
0x5449a36f,0x877d48fa,0xc39dfd27,0xf33e8d1e,0x0a476341,0x992eff74,
0x3a6f6eab,0xf4f8fd37,0xa812dc60,0xa1ebddf8,0x991be14c,0xdb6e6b0d,
0xc67b5510,0x6d672c37,0x2765d43b,0xdcd0e804,0xf1290dc7,0xcc00ffa3,
0xb5390f92,0x690fed0b,0x667b9ffb,0xcedb7d9c,0xa091cf0b,0xd9155ea3,
0xbb132f88,0x515bad24,0x7b9479bf,0x763bd6eb,0x37392eb3,0xcc115979,
0x8026e297,0xf42e312d,0x6842ada7,0xc66a2b3b,0x12754ccc,0x782ef11c,
0x6a124237,0xb79251e7,0x06a1bbe6,0x4bfb6350,0x1a6b1018,0x11caedfa,
0x3d25bdd8,0xe2e1c3c9,0x44421659,0x0a121386,0xd90cec6e,0xd5abea2a,
0x64af674e,0xda86a85f,0xbebfe988,0x64e4c3fe,0x9dbc8057,0xf0f7c086,
0x60787bf8,0x6003604d,0xd1fd8346,0xf6381fb0,0x7745ae04,0xd736fccc,
0x83426b33,0xf01eab71,0xb0804187,0x3c005e5f,0x77a057be,0xbde8ae24,
0x55464299,0xbf582e61,0x4e58f48f,0xf2ddfda2,0xf474ef38,0x8789bdc2,
0x5366f9c3,0xc8b38e74,0xb475f255,0x46fcd9b9,0x7aeb2661,0x8b1ddf84,
0x846a0e79,0x915f958e,0x466e598e,0x20b45770,0x8cd55591,0xc902de4c,
0xb90bace1,0xbb8205d0,0x11a86248,0x7574a99e,0xb77f19b6,0xe0a9dc09,
0x662d09a1,0xc4324633,0xe85a1f02,0x09f0be8c,0x4a99a025,0x1d6efe10,
0x1ab93d1d,0x0ba5a4df,0xa186f20f,0x2868f169,0xdcb7da83,0x573906fe,
0xa1e2ce9b,0x4fcd7f52,0x50115e01,0xa70683fa,0xa002b5c4,0x0de6d027,
0x9af88c27,0x773f8641,0xc3604c06,0x61a806b5,0xf0177a28,0xc0f586e0,
0x006058aa,0x30dc7d62,0x11e69ed7,0x2338ea63,0x53c2dd94,0xc2c21634,
0xbbcbee56,0x90bcb6de,0xebfc7da1,0xce591d76,0x6f05e409,0x4b7c0188,
0x39720a3d,0x7c927c24,0x86e3725f,0x724d9db9,0x1ac15bb4,0xd39eb8fc,
0xed545578,0x08fca5b5,0xd83d7cd3,0x4dad0fc4,0x1e50ef5e,0xb161e6f8,
0xa28514d9,0x6c51133c,0x6fd5c7e7,0x56e14ec4,0x362abfce,0xddc6c837,
0xd79a3234,0x92638212,0x670efa8e,0x406000e0};
int ks3[]={
0x3a39ce37,0xd3faf5cf,0xabc27737,0x5ac52d1b,0x5cb0679e,0x4fa33742,
0xd3822740,0x99bc9bbe,0xd5118e9d,0xbf0f7315,0xd62d1c7e,0xc700c47b,
0xb78c1b6b,0x21a19045,0xb26eb1be,0x6a366eb4,0x5748ab2f,0xbc946e79,
0xc6a376d2,0x6549c2c8,0x530ff8ee,0x468dde7d,0xd5730a1d,0x42d04dc6,
0x2939bbdb,0xa9ba4650,0xac9526e8,0xbe5ee304,0xa1fad5f0,0x6a2d519a,
0x63ef8ce2,0x9a86ee22,0xc089c2b8,0x43242ef6,0xa51e03aa,0x9cf2d0a4,
0x83c061ba,0x9be96a4d,0x8fe51550,0xba645bd6,0x2826a2f9,0xa73a3ae1,
0x4ba99586,0xef5562e9,0xc72fefd3,0xf752f7da,0x3f046f69,0x77fa0a59,
0x80e4a915,0x87b08601,0x9b09e6ad,0x3b3ee593,0xe990fd5a,0x9e34d797,
0x2cf0b7d9,0x022b8b51,0x96d5ac3a,0x017da67d,0xd1cf3ed6,0x7c7d2d28,
0x1f9f25cf,0xadf2b89b,0x5ad6b472,0x5a88f54c,0xe029ac71,0xe019a5e6,
0x47b0acfd,0xed93fa9b,0xe8d3c48d,0x283b57cc,0xf8d56629,0x79132e28,
0x785f0191,0xed756055,0xf7960e44,0xe3d35e8c,0x15056dd4,0x88f46dba,
0x03a16125,0x0564f0bd,0xc3eb9e15,0x3c9057a2,0x97271aec,0xa93a072a,
0x1b3f6d9b,0x1e6321f5,0xf59c66fb,0x26dcf319,0x7533d928,0xb155fdf5,
0x03563482,0x8aba3cbb,0x28517711,0xc20ad9f8,0xabcc5167,0xccad925f,
0x4de81751,0x3830dc8e,0x379d5862,0x9320f991,0xea7a90c2,0xfb3e7bce,
0x5121ce64,0x774fbe32,0xa8b6e37e,0xc3293d46,0x48de5369,0x6413e680,
0xa2ae0810,0xdd6db224,0x69852dfd,0x09072166,0xb39a460a,0x6445c0dd,
0x586cdecf,0x1c20c8ae,0x5bbef7dd,0x1b588d40,0xccd2017f,0x6bb4e3bb,
0xdda26a7e,0x3a59ff45,0x3e350a44,0xbcb4cdd5,0x72eacea8,0xfa6484bb,
0x8d6612ae,0xbf3c6f47,0xd29be463,0x542f5d9e,0xaec2771b,0xf64e6370,
0x740e0d8d,0xe75b1357,0xf8721671,0xaf537d5d,0x4040cb08,0x4eb4e2cc,
0x34d2466a,0x0115af84,0xe1b00428,0x95983a1d,0x06b89fb4,0xce6ea048,
0x6f3f3b82,0x3520ab82,0x011a1d4b,0x277227f8,0x611560b1,0xe7933fdc,
0xbb3a792b,0x344525bd,0xa08839e1,0x51ce794b,0x2f32c9b7,0xa01fbac9,
0xe01cc87e,0xbcc7d1f6,0xcf0111c3,0xa1e8aac7,0x1a908749,0xd44fbd9a,
0xd0dadecb,0xd50ada38,0x0339c32a,0xc6913667,0x8df9317c,0xe0b12b4f,
0xf79e59b7,0x43f5bb3a,0xf2d519ff,0x27d9459c,0xbf97222c,0x15e6fc2a,
0x0f91fc71,0x9b941525,0xfae59361,0xceb69ceb,0xc2a86459,0x12baa8d1,
0xb6c1075e,0xe3056a0c,0x10d25065,0xcb03a442,0xe0ec6e0e,0x1698db3b,
0x4c98a0be,0x3278e964,0x9f1f9532,0xe0d392df,0xd3a0342b,0x8971f21e,
0x1b0a7441,0x4ba3348c,0xc5be7120,0xc37632d8,0xdf359f8d,0x9b992f2e,
0xe60b6f47,0x0fe3f11d,0xe54cda54,0x1edad891,0xce6279cf,0xcd3e7e6f,
0x1618b166,0xfd2c1d05,0x848fd2c5,0xf6fb2299,0xf523f357,0xa6327623,
0x93a83531,0x56cccd02,0xacf08162,0x5a75ebb5,0x6e163697,0x88d273cc,
0xde966292,0x81b949d0,0x4c50901b,0x71c65614,0xe6c6c7bd,0x327a140a,
0x45e1d006,0xc3f27b9a,0xc9aa53fd,0x62a80f00,0xbb25bfe2,0x35bdd2f6,
0x71126905,0xb2040222,0xb6cbcf7c,0xcd769c2b,0x53113ec0,0x1640e3d3,
0x38abbd60,0x2547adf0,0xba38209c,0xf746ce76,0x77afa1c5,0x20756060,
0x85cbfe4e,0x8ae88dd8,0x7aaaf9b0,0x4cf9aa7e,0x1948c25c,0x02fb8a8c,
0x01c36ae4,0xd6ebe1f9,0x90d4f869,0xa65cdea0,0x3f09252d,0xc208e69f,
0xb74e6132,0xce77e25b,0x578fdfe3,0x3ac372e6};
/* Initialize s-boxes without file read. */
//int i;
for (int i=0 ;i<256;i++){
Ctx.S[0][i]=ks0[i];
Ctx.S[1][i]=ks1[i];
Ctx.S[2][i]=ks2[i];
Ctx.S[3][i]=ks3[i];
}
for (int i=0;i<18;i++)
Ctx.P[i]=0;
short j=0;
int k;
for (int i=0;i<ROUNDCOUNT+2;++i){
data=0x00000000;
for(k=0;k<4;++k){
data=(data<<8)|key[j];
j++;
if (j>=key_len)
j=0;
} // for k
Ctx.P[i]=Ctx.P[i]^data;
} //for i
data1=new int[]{0x00000000};
datar=new int[]{0x00000000};
for (int i=0;i<ROUNDCOUNT+2;i+=2){
Blowfish_encipher(data1,datar);
Ctx.P[i]=data1[0];
Ctx.P[i+1]=datar[0];
}
for (int i=0;i<4;++i){
for (j=0;j<256;j+=2){
Blowfish_encipher(data1,datar);
Ctx.S[i][j]=data1[0];
Ctx.S[i][j+1]=datar[0];
}//for j
}//for i
}
}
<file_sep>/Rover 2.0-android-src/src/com/wificar/util/GetThumb.java
package com.wificar.util;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.util.Log;
public class GetThumb {
/**
* 通过文件名 获取视频的缩略图
*
* @param context
* @param cr cr = getContentResolver();
* @param testVideopath 全路径 "/mnt/sdcard/sidamingbu.mp4";
* @return
*/
public static Bitmap getVideoThumbnail(Context context, ContentResolver cr, String testVideopath) {
// final String testVideopath = "/mnt/sdcard/sidamingbu.mp4";
ContentResolver testcr = context.getContentResolver();
String[] projection = { MediaStore.Video.Media.DATA, MediaStore.Video.Media._ID, };
String whereClause = MediaStore.Video.Media.DATA + " = '" + testVideopath + "'";
Cursor cursor = testcr.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection, whereClause,
null, null);
int _id = 0;
String videoPath = "";
if (cursor == null || cursor.getCount() == 0) {
return null;
}
if (cursor.moveToFirst()) {
int _idColumn = cursor.getColumnIndex(MediaStore.Video.Media._ID);
int _dataColumn = cursor.getColumnIndex(MediaStore.Video.Media.DATA);
do {
_id = cursor.getInt(_idColumn);
videoPath = cursor.getString(_dataColumn);
System.out.println(_id + " " + videoPath);
} while (cursor.moveToNext());
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inDither = false;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = MediaStore.Video.Thumbnails.getThumbnail(cr, _id, Images.Thumbnails.MINI_KIND,
options);
return bitmap;
}
/**
* 通过文件名 获相片的缩略图
*
* @param context
* @param cr cr = getContentResolver();
* @param testVideopath 全路径 "/mnt/sdcard/sidamingbu.jpg";
* @return
*/
public static Bitmap getImageThumbnail(Context context, ContentResolver cr, String testImagepath) {
// final String testVideopath = "/mnt/sdcard/sidamingbu.mp4";
ContentResolver testcr = context.getContentResolver();
String[] projection = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID, };
String whereClause = MediaStore.Images.Media.DATA + " = '" + testImagepath + "'";
Log.e("getVideoThumb", "whereClause :" + whereClause);
Cursor cursor = testcr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, whereClause,
null, null);
int _id = 0;
String imagePath = "";
Log.e("getVideoThumb", "cursor :" + cursor);
if (cursor == null || cursor.getCount() == 0) {
return null;
}
if (cursor.moveToFirst()) {
int _idColumn = cursor.getColumnIndex(MediaStore.Images.Media._ID);
int _dataColumn = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
do {
_id = cursor.getInt(_idColumn);
imagePath = cursor.getString(_dataColumn);
System.out.println(_id + " " + imagePath);
} while (cursor.moveToNext());
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inDither = false;
options.inPreferredConfig = Bitmap.Config.RGB_565;
Bitmap bitmap = MediaStore.Images.Thumbnails.getThumbnail(cr, _id, Images.Thumbnails.MINI_KIND,
options);
return bitmap;
}
}
<file_sep>/Rover 2.0-android-src/src/com/wificar/dialog/MusicListDialog.java
package com.wificar.dialog;
import android.app.Dialog;
import android.content.Context;
public class MusicListDialog extends Dialog {
public MusicListDialog(Context context, int theme) {
super(context, theme);
// TODO Auto-generated constructor stub
}
}
<file_sep>/Rover 2.0-android-src/src/com/wificar/VideoGalleryActivity.java
package com.wificar;
import java.io.File;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import com.CAR2.R;
import com.wificar.dialog.DeleteDialog;
import com.wificar.dialog.wifi_not_connect;
import com.wificar.mediaplayer.JNIWificarVideoPlay;
import com.wificar.mediaplayer.MediaPlayerActivity;
import android.content.ContentResolver;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.MediaStore.Video;
import android.provider.MediaStore.Video.Media;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.Gallery.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
public class VideoGalleryActivity extends Activity {
private static final int VIDEO = 2;
private static VideoGalleryActivity mContext = null;
//public static LibVLC mLibVLC;
public static VideoAdapter imageAdapterV;
private PopupWindow mPopupWindow;
private MyGallery myGallery;
private String videoPath;
private int positionV;
private int currenPosition;
public List<String> video_path1;
private List<String> video_path;
private TextView photos_count;
private Button deleButton;
private Button shareButton;
private boolean isShowing = false;
private boolean connectWifi = false;
private File file;
private Dialog dlg;
public static VideoGalleryActivity getInstance() {
// TODO Auto-generated method stub
return mContext;
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
// if (mPopupWindow != null) {
// mPopupWindow.dismiss();
// mPopupWindow = null;
// Log.d("PopWin", "dismiss ok");
// }
Log.i("VideoGalleryActivity", "onPause");
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.i("VideoGalleryActivity", "onStop");
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.e("VideoGalleryActivity", "onDrestroy");
}
// @Override
// public void onBackPressed() {
// // TODO Auto-generated method stub
// if (mPopupWindow != null) {
// mPopupWindow.dismiss();
// mPopupWindow = null;
// Log.d("PopWin", "dismiss ok");
// }
// finish();
// super.onBackPressed();
//
// }
@Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
Log.i("VideoGalleryActivity", "onRestart");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
mContext = this;
setContentView(R.layout.my_gallery);
/* try {
mLibVLC = LibVLC.getInstance();
} catch (LibVlcException e) {
e.printStackTrace();
}*/
connectWifi = note_Intent(mContext);
myGallery = (MyGallery)findViewById(R.id.myGallery);
video_path = getInSDPhotoVideo();
imageAdapterV = new VideoAdapter(mContext , video_path);
//imageAdapterV = new VideoAdapter(mContext , ShareActivity.getInstance().video_path);
Intent intent = getIntent();
videoPath = intent.getStringExtra("videoPath");
currenPosition = intent.getIntExtra("position", 0);
Log.i("VideoGalleryActivity", "the currenPosition :" + currenPosition);
myGallery.setAdapter(imageAdapterV);
myGallery.setSelection(currenPosition);
myGallery.setOnItemSelectedListener(listenerVideo);
}
public static List<String> getInSDPhotoVideo() {
List<String> it_p = new ArrayList<String>();
String path = Environment.getExternalStorageDirectory().toString() + "/CAR 2.0/Videos";
File f = new File(path);
File[] files = f.listFiles();
/**
* 遍历文件,将所有文件存入ArrayList中,这个地方存的还是文件路径
*/
for(File file : files){
if (file.isDirectory()) {
}else {
String fileName = file.getName();
if (fileName.endsWith(".avi")) {
it_p.add(file.getPath());
}
}
}
return it_p;
}
private void loadVideoGallery(int pv){
positionV = pv;
videoPath = video_path1.get(pv).toString();
video_path = getInSDPhotoVideo();
//imageAdapterV = new VideoAdapter(mContext , ShareActivity.getInstance().video_path);
imageAdapterV = new VideoAdapter(mContext , video_path);
myGallery.setAdapter(imageAdapterV);
myGallery.setSelection(pv);
photos_count.setText(positionV+1 + " of " + video_path1.size());
}
//判断是否连接互联网
public boolean note_Intent(Context context) {
ConnectivityManager con = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkinfo = con.getActiveNetworkInfo();
if (networkinfo == null || !networkinfo.isAvailable()) {
// 当前网络不可用
return false;
}
else{
return true;
}
}
public void dismiss() {
Log.d("PopWin", "dismiss");
if (mPopupWindow != null) {
mPopupWindow.dismiss();
mPopupWindow = null;
Log.d("PopWin", "dismiss ok");
}
}
private void showPopWindow(){
dismiss();
isShowing = true;
View foot_popunwindwow = null;
LayoutInflater LayoutInflater = (LayoutInflater) mContext
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
foot_popunwindwow = LayoutInflater
.inflate(R.layout.photo_count, null);
mPopupWindow = new PopupWindow(foot_popunwindwow,
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
mPopupWindow.showAtLocation(findViewById(R.id.layout),
Gravity.TOP , 10, 5);
mPopupWindow.update();
photos_count = (TextView) foot_popunwindwow.findViewById(R.id.photo_counts);
deleButton = (Button) foot_popunwindwow.findViewById(R.id.delete_button);
deleButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
dlg = new DeleteDialog(mContext,R.style.DeleteDialog,2);
WindowManager m = getWindowManager();
Display d = m.getDefaultDisplay(); //为获取屏幕宽、高
// dlg = new DeleteDialog(instance);
// dlg.setTitle(" " );
Window w=dlg.getWindow();
WindowManager.LayoutParams lp =w.getAttributes();
w.setGravity(Gravity.RIGHT | Gravity.TOP);
lp.x=10;
lp.y=70;
lp.height = (int) (d.getHeight() * 0.3); //高度设置为屏幕的0.6 ;
//lp.width = (int) (d.getWidth() * 0.65); // 宽度设置为屏幕的0.95
w.setAttributes(lp);
dlg.show();
}
});
shareButton = (Button) foot_popunwindwow.findViewById(R.id.share_button);
shareButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(connectWifi){
Intent shareIntent =new Intent();
shareIntent.setAction("android.intent.action.SEND");
shareIntent.setType("video/*");
file = new File(videoPath);
ContentValues content = new ContentValues(5);
content.put(Video.VideoColumns.TITLE, "Share");
content.put(MediaStore.Video.VideoColumns.SIZE, file.length());
content.put(Video.VideoColumns.DATE_ADDED,System.currentTimeMillis() / 1000);
content.put(Video.Media.MIME_TYPE, "video/avi");
content.put(MediaStore.Video.Media.DATA, videoPath);
ContentResolver contentResolver = getContentResolver();
Uri base = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
Uri newUri = contentResolver.insert(base, content);
Log.i("ShareActivity", " values:" + content);
Log.i("ShareActivity", " storeLocation:" + newUri);
if(newUri == null){
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
}else{
shareIntent.putExtra(Intent.EXTRA_STREAM, newUri);
}
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(Intent.createChooser(shareIntent, "Share"));
Log.i("startShare", "start start");
/*Dialog dlg = new share_photo_dialog(instance,R.style.ShareDialog ,imagePath);
WindowManager m = getWindowManager();
Display d = m.getDefaultDisplay(); //为获取屏幕宽、高
// dlg = new DeleteDialog(instance);
// dlg.setTitle(" " );
Window w=dlg.getWindow();
WindowManager.LayoutParams lp =w.getAttributes();
w.setGravity(Gravity.CENTER);
//lp.x=10;
//lp.y=70;
// lp.height = (int) (d.getHeight() * 0.5); //高度设置为屏幕的0.6 ;
//lp.width = (int) (d.getWidth() * 0.65); // 宽度设置为屏幕的0.95
w.setAttributes(lp);
dlg.show();*/
}else{
wifi_not_connect.createwificonnectDialog(mContext).show();
}
}
});
}
public OnItemSelectedListener listenerVideo = new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Log.i("VideoGalleryActivity", "the positionV is :" + arg2);
positionV = arg2;
videoPath = video_path1.get(positionV).toString();
if(!isShowing){
showPopWindow();
}
photos_count.setText(positionV+1 + " of " + video_path1.size());
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
Log.i("VideoGalleryActivity", "onNothingSelected :" + arg0);
}
};
public void Delete_video() {
// TODO Auto-generated method stub
file = new File(videoPath);
if(file.exists()){
file.delete();
}
if(positionV == video_path1.size() - 1){
positionV =0;
ShareActivity.getInstance().loadVideo();
loadVideoGallery(positionV);
}else{
ShareActivity.getInstance().loadVideo();
loadVideoGallery(positionV);
}
if (dlg != null && dlg.isShowing())
{
dlg.dismiss();
}
// dlg.dismiss();
}
class VideoAdapter extends BaseAdapter{
/* 类变量声明 */
private Context mContext;
//private ArrayList<Bitmap> videos = new ArrayList<Bitmap>();
LayoutInflater inflater1;
/**
* @param context
* 上下文构造函数
*/
public VideoAdapter(Context context) {
mContext = context;
}
public VideoAdapter(VideoGalleryActivity mContext2,
List<String> path) {
// TODO Auto-generated constructor stub
mContext = mContext2;
video_path1 = path;
inflater1 = LayoutInflater.from(mContext);
}
// 得到图片数量
public int getCount() {
return video_path1.size();
}
// 获取对应位置的对象
public Object getItem(int position) {
return video_path1.get(position);
}
// 获取ID
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
Bitmap bitmap = null;
ImageView imageview = new ImageView(mContext);
View v1 = inflater1.inflate(R.layout.video_play_item, null);
ImageView imgv = (ImageView) v1.findViewById(R.id.imageView_video_play);
ImageView playBtn = (ImageView) v1.findViewById(R.id.video_play_button);
playBtn.setOnClickListener(videoPlayListent);
imgv.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageview.setLayoutParams(new MyGallery.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
// byte[] rgb565Array = mLibVLC.getThumbnail(video_path.get(position).toString(), 320, 240);
byte[] rgb565Array = JNIWificarVideoPlay.getVideoSnapshot(video_path1.get(position).toString());
if((rgb565Array == null) || (rgb565Array.length == 0)){
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.video_snapshot1);
}else{
// Get the thumbnail.
bitmap = rgb565ToBitmap(rgb565Array);
//bitmap = Bitmap.createBitmap(320,240, Config.ARGB_8888);
// bitmap.copyPixelsFromBuffer(ByteBuffer.wrap(rgb565Array));
}
imgv.setImageBitmap(bitmap);
return v1;
}
}
public OnClickListener videoPlayListent = new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("zhang", "the video path : " + videoPath);
Intent intent = new Intent(VideoGalleryActivity.this, MediaPlayerActivity.class);
intent.putExtra("file_name", videoPath);
intent.putExtra("file_position", positionV);
VideoGalleryActivity.this.startActivity(intent);
}
};
private Bitmap rgb565ToBitmap(byte[] data){
//Bitmap bitmap = Bitmap.createBitmap(320,240, Config.ARGB_8888);
Bitmap bitmap = Bitmap.createBitmap(80, 60, Bitmap.Config.RGB_565);
ByteBuffer buffer = ByteBuffer.wrap(data);
bitmap.copyPixelsFromBuffer(buffer);
return bitmap;
}
}
<file_sep>/Rover 2.0-android-src/src/com/wificar/util/MessageUtility.java
package com.wificar.util;
import com.CAR2.R;
import android.content.Context;
public class MessageUtility {
public static String MESSAGE_ENABLE_MIC = "";
public static String MESSAGE_DISABLE_MIC = "";
public static String MESSAGE_ENABLE_GSENSOR = "";
public static String MESSAGE_DISABLE_GSENSOR = "";
public static String MESSAGE_PORT_INPUT_ERROR = "";
public static String MESSAGE_CONNECTION_ERROR = "";
public static String MESSAGE_TAKE_PHOTO_SUCCESSFULLY = "";
public static String MESSAGE_TAKE_PHOTO_FAIL = "";
private static Context ct = null;
public MessageUtility(Context ct){
this.ct = ct;
MESSAGE_DISABLE_MIC = ct.getResources().getString(R.string.mic_disable_label);
MESSAGE_ENABLE_MIC = ct.getResources().getString(R.string.mic_enable_label);
MESSAGE_ENABLE_GSENSOR = ct.getResources().getString(R.string.g_sensor_enable_label);
MESSAGE_DISABLE_GSENSOR = ct.getResources().getString(R.string.g_sensor_disable_label);
MESSAGE_PORT_INPUT_ERROR = ct.getResources().getString(R.string.port_input_error);
MESSAGE_CONNECTION_ERROR = ct.getResources().getString(R.string.connection_error);
MESSAGE_TAKE_PHOTO_SUCCESSFULLY = ct.getResources().getString(R.string.take_photo_successfully);
MESSAGE_TAKE_PHOTO_FAIL = ct.getResources().getString(R.string.take_photo_fail);
}
}
<file_sep>/Rover 2.0-android-src/src/com/wificar/SettingActivity.java
package com.wificar;
import com.CAR2.R;
import com.wificar.component.WifiCar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class SettingActivity extends Activity{
private static SettingActivity instance = null;
public EditText IP ;
public EditText Port;
public TextView device;
public TextView firmware;
public TextView software;
private Button Okbutton;
public int audio_play = WificarActivity.getInstance().audio_play;
@Override
protected void onCreate(Bundle savedInstanceState) {
instance = this;
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.setting_info);
/*if(WificarActivity.getInstance().with >=1200){
setContentView(R.layout.setting_info);
}else if(WificarActivity.getInstance().with <= 800){
setContentView(R.layout.setting_info_normal);
}*/
//setContentView(R.layout.setting_info);
if(audio_play == 1){
WificarActivity.getInstance().setting_play();
}
IP = (EditText) findViewById(R.id.EditText_IP);
Port = (EditText)findViewById(R.id.EditText_PORT);
device = (TextView)findViewById(R.id.TextView_D);
firmware = (TextView)findViewById(R.id.TextView_F);
software = (TextView)findViewById(R.id.TextView_S);
Okbutton = (Button) findViewById(R.id.OkButton);
Okbutton.setOnClickListener(new View.OnClickListener() {
//@Override
public void onClick(View v) {
//Okbutton.setBackgroundColor(0xA254D1);
Okbutton.setBackgroundResource(R.drawable.ok_off);
WificarActivity.getInstance().onResume();
instance.finish();
}
});
String host = WificarActivity.getInstance().getWifiCar().getHost();
IP.setText(host);
IP.setClickable(false);
//Car Port
String port = String.valueOf(WificarActivity.getInstance().getWifiCar().getPort());
Port.setText(port);
IP.setClickable(false);
//Device Connected
String ssid = "";
try{
ssid = WificarActivity.getInstance().getWifiCar().getSSID();
}
catch(Exception e){
e.printStackTrace();
}
Log.i("zhang", "ssid :" + ssid);
Log.i("zhang", "deivce :" + device);
device.setText(ssid);
//Firmware Version
String firmwareVersion = WificarActivity.getInstance().getWifiCar().getFilewareVersion();
if(!firmwareVersion.equals("")){
firmwareVersion = "1.0";
}else if(firmwareVersion.equals("")){
firmwareVersion = " ";
}
Log.i("zhang", "firmwareVersion11 :" +firmwareVersion);
firmware.setText(firmwareVersion);
//Software Version
String version = WifiCar.getVersion(instance);
software.setText(version);
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
this.onBackPressed();
if (this.isFinishing()){
//Insert your finishing code here
Log.d("activity","setting on Pause:finish");
//·µ»ØµÄ¶¯»
//overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
}
}
}
<file_sep>/Rover 2.0-android-src/src/com/wificar/SplashActivity.java
package com.wificar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import com.CAR2.R;
public class SplashActivity extends Activity {
protected static final int MESSAGE_MAIN_PROCEDURE = 0;
private static SplashActivity instance = null;
private Handler handler = null;
private String TAG = "SplashActivity";
public boolean isExit = false;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
finish();
}
public static SplashActivity getInstance(){
return instance;
}
public void exit(){
Log.i(TAG, "SplashActivity is exit!");
finish();
System.exit(0);
//android.os.Process.killProcess(android.os.Process.myPid());
}
@Override
protected void onDestroy() {
super.onDestroy();
System.exit(0);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.splash);
instance = this;
handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_MAIN_PROCEDURE:
Intent intent = new Intent(instance, WificarActivity.class);
instance.startActivityForResult(intent, 1);
break;
default:
break;
}
super.handleMessage(msg);
}
};
}
@Override
protected void onStart() {
super.onStart();
if(isExit){
isExit = false;
finish();
}
Runnable init = new Runnable() {
//@Override
public void run() {
try {
Thread.sleep(2300);
Message messageLoadingSuccess = new Message();
messageLoadingSuccess.what = MESSAGE_MAIN_PROCEDURE;
handler.sendMessage(messageLoadingSuccess);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread initThread = new Thread(init);
initThread.start();
}
}
<file_sep>/Rover 2.0-android-src/src/com/wificar/mediaplayer/MediaPlayerActivity.java
package com.wificar.mediaplayer;
import java.io.File;
import java.nio.ByteBuffer;
import com.CAR2.R;
import com.wificar.VideoGalleryActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.LayoutInflater;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
public class MediaPlayerActivity extends Activity {
private final int UPDATEUI_FOR_STOP = 0x100;
private final int UPDATEUI_CURRENT_TIME = 0x101;
private SurfaceHolder mSurfaceHolder;
private String mVideoFileName = null;
private int mVideoFilePosition = 0;
private LinearLayout mOverlay;
private SurfaceView mWindow = null;
private SurfaceHolder mWindowHolder = null;
private int mWindowWidth = 0;
private int mWindowHeight = 0;
private ImageButton mPreviousSongImgBtn = null;
private ImageButton mPlayImgBtn = null;
private ImageButton mNextSongImgBtn = null;
private View mSpacer;
private SeekBar mSeekBar = null;
private TextView mDurationText = null;
private TextView mCurrentTimeText = null;
private int mDuration = 0;
private int mCurrentTime = 0;
private boolean mIsPlaying = false;
private boolean mIsVideoRender = false;
private boolean mIsAudioRender = false;
private boolean mIsVideoEnd = false;
private boolean mIsAudioEnd = false;
private boolean mIsFileEnd = false;
private boolean mIsVideoSwitch = false;
private boolean mIsStop = true;
private boolean calledbyother=false;
private boolean mShowing=false;
private int mVideoWidth = 0;
private int mVideoHeight = 0;
private LinearLayout mDecor;
private Handler mHandler = null;
float density;
PowerManager.WakeLock mWakeLock = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* Full screen display without the task and status bar */
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.player);
density = this.getResources().getDisplayMetrics().density;
mDecor = (LinearLayout)findViewById(R.id.player_overlay_decor);
LayoutInflater inflater = (LayoutInflater) getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
mOverlay = (LinearLayout)inflater.inflate(R.layout.player_overlay, null);
mWindow = (SurfaceView)findViewById(R.id.window);
mSurfaceHolder = mWindow.getHolder();
mSurfaceHolder.setKeepScreenOn(true);
mSurfaceHolder.setFormat(PixelFormat.RGBX_8888);
mPreviousSongImgBtn = (ImageButton)mOverlay.findViewById(R.id.previous);
mPlayImgBtn = (ImageButton)mOverlay.findViewById(R.id.play);
mNextSongImgBtn = (ImageButton)mOverlay.findViewById(R.id.next);
mSeekBar = (SeekBar)mOverlay.findViewById(R.id.seek_bar);
mDurationText = (TextView)mOverlay.findViewById(R.id.duration_text);
mCurrentTimeText = (TextView)mOverlay.findViewById(R.id.current_time_text);
mSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
JNIWificarVideoPlay.playerSeek(seekBar.getProgress() * 1000);
}
});
mDecor.addView(mOverlay);
mShowing=true;
mSpacer = (View)findViewById(R.id.player_overlay_spacer);
mSpacer.setOnTouchListener(mTouchListener);
if(!(getIntent().getAction() != null&& getIntent().getAction().equals(Intent.ACTION_VIEW ))){
mVideoFileName = getIntent().getExtras().getString("file_name");
mVideoFilePosition = getIntent().getExtras().getInt("file_position");
}
implSurfaceHolderCallback();
playControl();
mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch(msg.what){
case UPDATEUI_FOR_STOP:
Log.e("MediaPlayer", "UPDATEUI_FOR_STOP");
mIsAudioRender = false;
mIsVideoRender = false;
mIsPlaying = false;
mIsStop = true;
mPlayImgBtn.setBackgroundResource(R.drawable.ic_play);
mCurrentTime = 0;
mCurrentTimeText.setText(timeFormat(mCurrentTime));
mSeekBar.setProgress(mCurrentTime);
JNIWificarVideoPlay.playerStop();
/*if(calledbyother)*/ finish();
/*else{
mIsVideoRender = false;
mIsAudioRender = false;
mIsPlaying = false;
mIsVideoEnd = true;
mIsAudioEnd = true;
mIsVideoSwitch = true;
mPlayImgBtn.setBackgroundResource(R.drawable.ic_play);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(mVideoFilePosition < FileListActivity.mFilesNameArray.length - 1){
mVideoFilePosition = mVideoFilePosition + 1;
mVideoFileName = FileListActivity.mFileDirectory +
FileListActivity.mFilesNameArray[mVideoFilePosition];
if(mVideoFileName == null){
return;
}
if(initPlayerStart() < 0){
return;
}
}
mPlayImgBtn.setBackgroundResource(R.drawable.ic_pause);
}*/
break;
case UPDATEUI_CURRENT_TIME:
if(mCurrentTime < 0){
mCurrentTime = 0;
}
mCurrentTimeText.setText(timeFormat(mCurrentTime));
mSeekBar.setProgress(mCurrentTime);
//Log.e("tieme","ctime"+mCurrentTime);
break;
}
super.handleMessage(msg);
}
};
}
@Override
protected void onResume() {
/*
* if the video is playing, keep the screen light always.
*/
if(mWakeLock == null){
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(pm.SCREEN_DIM_WAKE_LOCK, "media player wakelook");
mWakeLock.acquire();
}
super.onResume();
}
@Override
protected void onPause() {
mIsAudioRender = false;
mIsVideoRender = false;
while(!mIsVideoEnd && !mIsAudioEnd)
{
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
JNIWificarVideoPlay.playerStop();
mIsStop = true;
mIsPlaying = false;
/*
* if the activity is background, you should release
* the wake lock, make the screen can enter wake mode,
* it's benefit for power.
*/
if(mWakeLock != null && mWakeLock.isHeld()){
mWakeLock.release();
mWakeLock = null;
}
finish();
super.onPause();
}
@Override
protected void onDestroy() {
mIsAudioRender = false;
mIsVideoRender = false;
mIsPlaying = false;
mIsStop = true;
mIsVideoSwitch = false;
mIsFileEnd = true;
Log.e("MediaPlayer", "onDestroy");
finish();
super.onDestroy();
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
// mIsAudioRender = false;
// mIsVideoRender = false;
// mIsPlaying = false;
// mIsStop = true;
// mIsVideoSwitch = false;
//
// mIsFileEnd = true;
// try {
// Thread.sleep(50);
// } catch (Exception e) {
// // TODO: handle exception
// }
// MediaPlayerActivity.this.finish();
// mIsAudioRender = false;
// mIsVideoRender = false;
//
// while(!mIsVideoEnd && !mIsAudioEnd)
// {
// try {
// Thread.sleep(500);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
//
// JNIWificarVideoPlay.playerStop();
//
// mIsStop = true;
// mIsPlaying = false;
//
// /*
// * if the activity is background, you should release
// * the wake lock, make the screen can enter wake mode,
// * it's benefit for power.
// */
// if(mWakeLock != null && mWakeLock.isHeld()){
// mWakeLock.release();
// mWakeLock = null;
// }
//
// mIsFileEnd = true;
//
// try {
// Thread.sleep(500);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// mIsAudioEnd = true;
// mIsVideoEnd = true;
// if(mIsAudioEnd && mIsVideoEnd){
// Message message = new Message();
// message.what = MediaPlayerActivity.this.UPDATEUI_FOR_STOP;
// mHandler.sendMessage(message);
// }
new playStopListenThread().start();
//// JNIWificarVideoPlay.playerResume();
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// JNIWificarVideoPlay.playerStop();
mIsAudioRender = false;
mIsVideoRender = false;
mIsPlaying = false;
mIsStop = true;
mIsVideoSwitch = false;
mIsFileEnd = true;
Log.e("MediaPlayer", "onBackPressed");
super.onBackPressed();
}
// @Override
// protected void onStop() {
// // TODO Auto-generated method stub
// Log.e("MediaPlayer", "onStop");
// mIsAudioRender = false;
// mIsVideoRender = false;
// mIsPlaying = false;
// mIsStop = true;
// mIsVideoSwitch = false;
//
// mIsFileEnd = true;
// super.onStop();
// }
private OnTouchListener mTouchListener = new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (!mShowing) {
mDecor.addView(mOverlay);
mShowing=true;
} else {
mDecor.removeView(mOverlay);
mShowing=false;
}
}
return false;
}
};
private void implSurfaceHolderCallback(){
mWindowHolder = mWindow.getHolder();
mWindowHolder.addCallback(new Callback(){
public void surfaceCreated(SurfaceHolder holder){
/*Get the playing window size , and adjust the height, make
* the video can fit the whole window, else because of the
* bitmap scale will keep the aspect of the origin video,
* so the playing window bottom has a black bar.Perhaps you
* need to change it according the screen size.
*/
mWindowWidth = mWindow.getWidth();
mWindowHeight = mWindow.getHeight();
if(initPlayerStart() < 0){
return;
}
}
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
public void surfaceDestroyed(SurfaceHolder holder){
mIsVideoSwitch = true;
}
});
}
private void playControl(){
setPlayButtonControl();
setPreviousButtonControl();
setNextButtonControl();
}
private int initPlayerStart(){
mIsVideoRender = false;
mIsAudioRender = false;
mIsPlaying = false;
mIsStop = true;
mIsVideoEnd = false;
mIsAudioEnd = false;
mIsFileEnd = false;
if (getIntent().getAction() != null&& getIntent().getAction().equals(Intent.ACTION_VIEW )) {
/* Started from external application */
//mVideoFileName = getIntent().getData().getPath();
mVideoFileName = getRealPath(getIntent().getData());
/*File f =new File(mVideoFileName);
String fileName=f.getName();
String prefix=fileName.substring(fileName.lastIndexOf(".")+1);
if(!prefix.equals("avi")){
AlertDialog.Builder builder = new Builder(MediaPlayerActivity.this);
builder.setMessage("Sorry!We don't support this video(."+prefix+").");
builder.setTitle("Warning");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
builder.create().show();
return 0;
}*/
mPreviousSongImgBtn.setVisibility(View.INVISIBLE);
mPreviousSongImgBtn.setClickable(false);
mNextSongImgBtn.setVisibility(View.INVISIBLE);
mNextSongImgBtn.setClickable(false);
calledbyother=true;
}
if(JNIWificarVideoPlay.playerInit(mVideoFileName) < 0){
System.out.println("init player failed");
return -1;
}
mVideoWidth = JNIWificarVideoPlay.getVideoWidth();
mVideoHeight = JNIWificarVideoPlay.getVideoHeight();
//Log.e("initPlayerstart","video size width is " + mVideoWidth + " height is " + mVideoHeight);
changeSurfaceSize();
if(JNIWificarVideoPlay.playerStart() < 0){
System.out.println("start player failed");
return -1;
}
mDuration = JNIWificarVideoPlay.getDuration();
mDurationText.setText(timeFormat(mDuration));
mSeekBar.setMax(mDuration);
mIsVideoRender = true;
mIsAudioRender = true;
mIsPlaying = true;
mIsStop = false;
mIsVideoSwitch = false;
new videoRenderThread().start();
new audioRenderThread().start();
new playStopListenThread().start();
new UpdateCurrentTimeThread().start();
return 0;
}
private void setPlayButtonControl(){
mPlayImgBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
mPlayImgBtn.setClickable(false);
switch(v.getId()){
case R.id.play:
/**
* only the file is end, and the buffered video and audio is flush, and
* the player state is at pause, when press the play button we can restart
* the player.
*/
if(mIsFileEnd && mIsAudioEnd && mIsVideoEnd && !mIsPlaying){
mVideoFileName = VideoGalleryActivity.getInstance().video_path1.get(mVideoFilePosition);
if(mVideoFileName == null){
break;
}
if(initPlayerStart() < 0){
break;
}
mPlayImgBtn.setBackgroundResource(R.drawable.ic_pause);
break;
}
/**
* normal playing state, easily pause player
*/
if(mIsPlaying){
JNIWificarVideoPlay.playerPause();
mPlayImgBtn.setBackgroundResource(R.drawable.ic_play);
mIsPlaying = false;
break;
}
/**
* the player is at pause state is that the buffered
* audio or video is not end.
*/
if(!mIsPlaying && ((mIsAudioEnd != true) || (mIsVideoEnd != true))){
JNIWificarVideoPlay.playerResume();
mPlayImgBtn.setBackgroundResource(R.drawable.ic_pause);
mIsPlaying = true;
break;
}
}
mPlayImgBtn.setClickable(true);
}
});
}
private void setPreviousButtonControl(){
mPreviousSongImgBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
mPreviousSongImgBtn.setClickable(false);
switch(v.getId()){
case R.id.previous:
mIsVideoRender = false;
mIsAudioRender = false;
mIsPlaying = false;
mIsVideoEnd = true;
mIsAudioEnd = true;
mIsVideoSwitch = true;
mPlayImgBtn.setBackgroundResource(R.drawable.ic_play);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(mVideoFilePosition > 0){
mVideoFilePosition = mVideoFilePosition -1;
mVideoFileName = VideoGalleryActivity.getInstance().video_path1.get(mVideoFilePosition);
if(mVideoFileName == null){
break;
}
}
else{
mVideoFilePosition = VideoGalleryActivity.getInstance().video_path1.size() - 1;
mVideoFileName = VideoGalleryActivity.getInstance().video_path1.get(mVideoFilePosition);
if(mVideoFileName == null){
break;
}
}
if(initPlayerStart() < 0){
break;
}
mPlayImgBtn.setBackgroundResource(R.drawable.ic_pause);
break;
}
mPreviousSongImgBtn.setClickable(true);
}
});
}
private void setNextButtonControl(){
mNextSongImgBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
mNextSongImgBtn.setClickable(false);
switch(v.getId()){
case R.id.next:
mIsVideoRender = false;
mIsAudioRender = false;
mIsPlaying = false;
mIsVideoEnd = true;
mIsAudioEnd = true;
mIsVideoSwitch = true;
mPlayImgBtn.setBackgroundResource(R.drawable.ic_play);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(mVideoFilePosition < VideoGalleryActivity.getInstance().video_path1.size() - 1){
mVideoFilePosition = mVideoFilePosition + 1;
mVideoFileName = VideoGalleryActivity.getInstance().video_path1.get(mVideoFilePosition);
if(mVideoFileName == null){
break;
}
}
else{
mVideoFilePosition = 0;
mVideoFileName = VideoGalleryActivity.getInstance().video_path1.get(mVideoFilePosition);
if(mVideoFileName == null){
break;
}
}
if(initPlayerStart() < 0){
break;
}
mPlayImgBtn.setBackgroundResource(R.drawable.ic_pause);
break;
}
mNextSongImgBtn.setClickable(true);
}
});
}
private AudioTrack createPlayer(int samplerate, int channels, int format){
AudioTrack audioPlayer = null;
int chls = AudioFormat.CHANNEL_OUT_STEREO;
int fmt = AudioFormat.ENCODING_DEFAULT;
switch(channels){
case 1:
chls = AudioFormat.CHANNEL_OUT_MONO;
break;
case 2:
chls = AudioFormat.CHANNEL_OUT_STEREO;
break;
default:
break;
}
switch(format){
case 0:
fmt = AudioFormat.ENCODING_PCM_8BIT;
break;
case 1:
fmt = AudioFormat.ENCODING_PCM_16BIT;
break;
default:
fmt = AudioFormat.ENCODING_INVALID;
break;
}
if(fmt == AudioFormat.ENCODING_INVALID){
audioPlayer = null;
return audioPlayer;
}
int minBufSize = AudioTrack.getMinBufferSize(samplerate, chls, fmt);
audioPlayer = new AudioTrack(AudioManager.STREAM_MUSIC, samplerate, chls,
fmt, minBufSize, AudioTrack.MODE_STREAM);
return audioPlayer;
}
private Bitmap rgb565ToBitmap(byte[] data){
/**
* Convert rgb565 data to bitmap
*/
Bitmap bitmap = Bitmap.createBitmap(mVideoWidth, mVideoHeight, Bitmap.Config.RGB_565);
ByteBuffer buffer = ByteBuffer.wrap(data);
bitmap.copyPixelsFromBuffer(buffer);
return bitmap;
}
public void showBitMap(Bitmap bm, Canvas canvas){
float scaleWidth = 0;
float scaleHeight = 0;
if(bm == null){
return;
}
// get bitmap's width and height
int width = bm.getWidth();
int height = bm.getHeight();
Bitmap newbm = null;
if((mWindowWidth != width) || (mWindowHeight != height)){
// calculate the scaling factors
if(mWindowWidth>=1024 & density>=1.0){
scaleWidth = ((float)mWindowWidth/(density*1.3f))/((float)width);
scaleHeight = ((float)mWindowHeight/(density*1.3f))/((float)height);
}
else if(density<1.0){
scaleWidth = ((float)mWindowWidth/(density*2.4f))/((float)width);
scaleHeight = ((float)mWindowHeight/(density*2.4f))/((float)height);
}
else if(mWindowWidth<1024 & density>=1.0){
scaleWidth = ((float)mWindowWidth/(density*1.3f))/((float)width);
scaleHeight = ((float)mWindowHeight/(density*1.3f))/((float)height);
}
else{
scaleWidth = ((float)mWindowWidth/(density*1.3f))/((float)width);
scaleHeight = ((float)mWindowHeight/(density*1.3f))/((float)height);
}
//Log.e("showbitmap", "width=" + width + " " + "heigth= "+ height);
//Log.e("showbitmap","mWindowWidth="+mWindowWidth+"mWindowHeight="+mWindowHeight+"density="+density+"surfwid"+mWindow.getWidth());
// create transform matrix
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
//Log.e("showbitmap","scwid="+scaleWidth+"schei="+scaleHeight);
// create the new bitmap based on the old one and transform matrix.
newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
//Log.e("showbitmap","bmpWidth="+width+"bmpHeight="+height+newbm.getWidth()+newbm.getHeight());
bm.recycle();
}else{
newbm = bm;
}
try{
synchronized(mWindowHolder){
canvas = mWindowHolder.lockCanvas();
}
}finally{
if(canvas != null){
canvas.drawARGB(0, 0, 0, 0);
canvas.drawBitmap(newbm, 0, 0, null);
mWindowHolder.unlockCanvasAndPost(canvas);
}
}
newbm.recycle();
}
class videoRenderThread extends Thread{
@Override
public void run() {
Canvas drawCanvas = null;
while(mIsVideoRender){
if(mIsPlaying){
byte[] frame = JNIWificarVideoPlay.videoRender();
if((frame == null) || (frame.length == 0)){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(mIsFileEnd){
mIsVideoEnd = true;
}
continue;
}
Bitmap bm = rgb565ToBitmap(frame);
showBitMap(bm, drawCanvas);
}else{
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
continue;
}
}
mIsVideoEnd = true;
}
}
class audioRenderThread extends Thread{
@Override
public void run() {
byte[] sampleRateArray = new byte[4];
int sampleRate = 0;
byte[] channelsArray = new byte[4];
int channles = 0;
byte[] formatArray = new byte[4];
int format = 0;
AudioTrack audioPlayer = null;
while(mIsAudioRender){
if(mIsPlaying){
byte[] buf = JNIWificarVideoPlay.audioRender(sampleRateArray, sampleRateArray.length,
channelsArray, channelsArray.length,
formatArray, formatArray.length);
if((buf == null) || (buf.length == 0)){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(mIsFileEnd){
mIsAudioEnd = true;
}
continue;
}
if(audioPlayer == null){
sampleRate = byteArray2Int(sampleRateArray);
channles = byteArray2Int(channelsArray);
format = byteArray2Int(formatArray);
audioPlayer = createPlayer(sampleRate, channles, format);
if(audioPlayer != null){
audioPlayer.play();
}else{
continue;
}
}
audioPlayer.write(buf, 0, buf.length);
}else{
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
continue;
}
}
audioPlayer.flush();
audioPlayer.stop();
audioPlayer.release();
audioPlayer = null;
mIsAudioEnd = true;
}
}
class playStopListenThread extends Thread{
@Override
public void run() {
while(true){
if(JNIWificarVideoPlay.playerIsStop() == 0){
if(mIsStop || mIsVideoSwitch){
break;
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
continue;
}else{
mIsFileEnd = true;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(mIsAudioEnd && mIsVideoEnd){
Message message = new Message();
message.what = MediaPlayerActivity.this.UPDATEUI_FOR_STOP;
mHandler.sendMessage(message);
break;
}else{
continue;
}
}
}
}
}
class UpdateCurrentTimeThread extends Thread{
@Override
public void run() {
while(!mIsStop){
if(mIsVideoSwitch){
break;
}
mCurrentTime = JNIWificarVideoPlay.getCurrentTime();
Message message = new Message();
message.what = MediaPlayerActivity.this.UPDATEUI_CURRENT_TIME;
mHandler.sendMessage(message);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private int byteArray2Int(byte[] data){
int value = 0;
value = (data[0] & 0xff) | ((data[1] & 0xff) << 8) |
((data[2] & 0xff) << 16) | ((data[3] & 0xff) << 24);
return value;
}
/**
*
* @param seconds
* @return : format the seconds as, hour:minute:seconds
*/
private String timeFormat(int seconds){
String timeStr = null;
String fmtminute = null;
String fmtsecond = null;
int hour = (int)(seconds / 3600);
int minute = (int)((seconds - hour * 3600) / 60);
int second = seconds - hour * 3600 - minute * 60;
if(minute < 10) fmtminute = "0"+String.valueOf(minute);
else fmtminute = String.valueOf(minute);
if(second < 10 ) fmtsecond = "0"+String.valueOf(second);
else fmtsecond = String.valueOf(second);
timeStr = String.valueOf(hour) + ":" + fmtminute + ":" + fmtsecond;
return timeStr;
}
private void changeSurfaceSize() {
// get screen size
int dw = getWindowManager().getDefaultDisplay().getWidth();
int dh = getWindowManager().getDefaultDisplay().getHeight();
//Log.e("changsurface init","dw="+dw+"dh="+dh+"mVideoWidth"+mVideoWidth+"mVideoHeight"+mVideoHeight);
// calculate aspect ratio
double ar = (double)mVideoWidth / (double)mVideoHeight;
// calculate display aspect ratio
double dar = (double)dw / (double)dh;
dw = (int) (dh * ar);
//Log.e("changsurface","dw="+dw+"dh="+dh+"ar="+ar+"dar="+dar);
mSurfaceHolder.setFixedSize(mVideoWidth, mVideoHeight);
LayoutParams lp = mWindow.getLayoutParams();
lp.width = dw;
lp.height = dh;
mWindowHeight=dh;
mWindowWidth=dw;
//Log.e("changsurface","mWindowWidth="+mWindowWidth+"mWindowHeight="+mWindowHeight);
mWindow.setLayoutParams(lp);
mWindow.invalidate();
}
//获取真正的文件路径
private String getRealPath(Uri fileUrl){
String fileName = null;
Uri filePathUri = fileUrl;
if(fileUrl!= null){
if (fileUrl.getScheme().toString().compareTo("content")==0) //content://开头的uri
{
Cursor cursor = getApplicationContext().getContentResolver().query(fileUrl, null, null, null, null);
if (cursor != null && cursor.moveToFirst())
{
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
fileName = cursor.getString(column_index); //取出文件路径
Log.e("VideoPlayerActivity", "the content to path :" + fileName);
cursor.close();
}
}else if (fileUrl.getScheme().compareTo("file")==0) //file:///开头的uri
{
fileName = filePathUri.toString();
fileName = filePathUri.toString().replace("file://", "");
}
}
Log.e("videoPlayerActivty", "the realPath:" + fileName);
return fileName;
}
}<file_sep>/Rover 2.0-android-src/src/com/wificar/dialog/DeleteDialog.java
package com.wificar.dialog;
import com.wificar.ImageGalleryActivity;
import com.CAR2.R;
import com.wificar.VideoGalleryActivity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
public class DeleteDialog extends Dialog{
private int i;
public DeleteDialog(Context context) {
super(context);
/* Window w=getWindow();
WindowManager.LayoutParams lp =w.getAttributes();
w.setLayout(120, 100);
w.setGravity(Gravity.RIGHT | Gravity.TOP);
lp.x=10;
lp.y=70;
// lp.height = (int) (d.getHeight() * 0.1); //高度设置为屏幕的0.6 ;
//lp.width = (int) (d.getWidth() * 0.65); // 宽度设置为屏幕的0.95
lp.height = 90;
getWindow().setAttributes(lp);*/
}
public DeleteDialog(Context context, int theme ,int inter){
super(context, theme);
// this.context = context;
this.i = inter;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.share_dialog);
Button positiveBtn = (Button) findViewById(R.id.positiveButton);
Button cancelBtn = (Button) findViewById(R.id.cancelButton);
TextView text = (TextView) findViewById(R.id.message);
if(i == 1){
text.setText("DELETE PHOTOS?");
}else if(i == 2){
text.setText("DELETE VIDEOS?");
}
positiveBtn.setOnClickListener(new View.OnClickListener() {
//@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//dismiss();
cancel();
if(i == 1){
ImageGalleryActivity.getInstance().Delete_photo();
}else if(i == 2){
VideoGalleryActivity.getInstance().Delete_video();
}
}
});
cancelBtn.setOnClickListener(new View.OnClickListener() {
//@Override
public void onClick(View v) {
// TODO Auto-generated method stub
dismiss();
}
});
}
}<file_sep>/Rover 2.0-android-src/src/com/wificar/dialog/Connect_Dialog.java
package com.wificar.dialog;
import com.CAR2.R;
import com.wificar.WificarActivity;
import com.wificar.util.VideoUtility;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.ContextThemeWrapper;
import android.widget.EditText;
import android.widget.TextView;
public class Connect_Dialog {
public Connect_Dialog() {
}
public static AlertDialog.Builder createconnectDialog(Context context){
final AlertDialog.Builder connectDialog = new AlertDialog.Builder(new ContextThemeWrapper(context, R.layout.share_dialog));
connectDialog.setTitle("Connection Status ");
connectDialog.setMessage("CAR 2.0 is not connected, press exit to check your Wi-Fi connection or " +
"press Share to share CAR 2.0 photos and videos");
connectDialog .setCancelable(false);
connectDialog .setPositiveButton("Exit",new DialogInterface.OnClickListener() {
//@Override
public void onClick(DialogInterface dialog, int id) {
WificarActivity.getInstance().exit();
dialog.cancel();
//WificarActivity.getInstance().exitProgrames();
}
}).setNegativeButton("Share",new DialogInterface.OnClickListener() {
//@Override
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
WificarActivity.getInstance().share();
}
});
return connectDialog;
}
}<file_sep>/Rover 2.0-android-src/src/com/wificar/surface/DoubleAxisRightControllerSurfaceView.java
package com.wificar.surface;
import java.io.IOException;
import com.CAR2.R;
import com.wificar.WificarActivity;
import com.wificar.component.WifiCar;
import com.wificar.util.ImageUtility;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;
public class DoubleAxisRightControllerSurfaceView extends SurfaceView implements
SurfaceHolder.Callback,ControllerInterface{
private static final int MAX = 10;
private static final String TAG = "DoubleAxisRightControllerSurfaceView";
static DoubleAxisRightControllerSurfaceView instance;
private int rightStartPointX = 20;
private int rightStartPointY = 20;
private int areaBoundWidth = 20;
private int areaBoundHeight = 20;
private int leftStartPointX = 20;
private int leftStartPointY = 20;
private int stickBallPointX = 10;
private int stickBallPointY =100;
private int stickBallPointSmallY =70;
private int stickBallPointLargeY =WificarActivity.dip2px(getContext(), 180);
private int stickBallPointxLargeY =WificarActivity.dip2px(getContext(), 93);
private int stickBallPointxxLargeY =WificarActivity.dip2px(getContext(), 70);
private int stickBallWidth = 40;
private int stickBallHeight = 40;
private int stickBarPointX = 10;
private int stickBarPointY = 0;
private int stickBarPointSmallY = 0;
private int stickBarPointLargeY = 0;
private int stickBarPointxLargeY = 0;
private int stickBarPointxxLargeY = 0;
private int stickBarPointTopY = WificarActivity.dip2px(getContext(), 13);
private int stickBarWidth = 60;
//private int stickBallPointBaseX = 10;
private int stickBallPointBaseY = 100;
private int stickBallPointBaseSmallY = 70;
private int stickBallPointBaseLargeY = 65;
private int stickBallPointBasexLargeY = WificarActivity.dip2px(getContext(), 93);
private int stickBallPointBasexxLargeY = WificarActivity.dip2px(getContext(), 70);
private int stickBallMotionAreaWidth=80;
private int stickBallMotionAreaHeight=230;
private int stickBallMotionAreaHeightSmall=160;
private int stickBallMotionAreaHeightLarge=150;
private int stickBallMotionAreaHeightxLarge=WificarActivity.dip2px(getContext(), 188);
private int stickBallMotionAreaHeightxxLarge=WificarActivity.dip2px(getContext(), 148);
private boolean captureLeftBall = false;
private boolean captureRightBall = false;
private double size = 0.00;
private int width;
private int height;
int maxPointIndex = 2;
int leftIndexId = -1;
int rightIndexId = -1;
SurfaceHolder holder;
private Handler handler = new Handler();
private WifiCar wifiCar = null;
private boolean controlEnable = true;
private final int tStep = 100;
private int iCarSpeedR = 0, iLastSpeedR = 0;
private int iCarSpeedL = 0, iLastSpeedL = 0;
private int stopLeftSignal = 0;
private int stopRightSignal = 0;
private int waitStopState = 0;
Bitmap stickBar = null;
Bitmap stickBall = null;
Bitmap stickUp = null;
Bitmap stickDown = null;
Bitmap stickUpPress = null;
Bitmap stickDownPress = null;
public static DoubleAxisRightControllerSurfaceView getInstance(){
return instance;
}
public void initial() {
size = WificarActivity.getInstance().dimension;
width = WificarActivity.getInstance().with;
height = WificarActivity.getInstance().hight;
holder = this.getHolder();
stickBar = ImageUtility
.createBitmap(getResources(), R.drawable.control_circle_left);
stickBall = ImageUtility
.createBitmap(getResources(), R.drawable.joy_stick);
if(this.size < 5.8){
Log.i("Double", "180X40");
stickBar = stickBar.createScaledBitmap(stickBar, ImageUtility.dip2px(getContext(), 40), ImageUtility.dip2px(getContext(), 180), true);
stickBall = stickBall.createScaledBitmap(stickBall, ImageUtility.dip2px(getContext(), 40), ImageUtility.dip2px(getContext(), 40), true);
}
if(this.size > 5.8){
Log.i("Double", "225X48");
//stickBar = stickBar.createScaledBitmap(stickBar, 48, 225, true);
stickBall = stickBall.createScaledBitmap(stickBall, ImageUtility.dip2px(getContext(), 48), ImageUtility.dip2px(getContext(), 48), true);
stickBar = stickBar.createScaledBitmap(stickBar, ImageUtility.dip2px(getContext(), 48), ImageUtility.dip2px(getContext(), 225), true);
//stickBall = stickBall.createScaledBitmap(stickBall, ImageUtility.dip2px(getContext(), 48), ImageUtility.dip2px(getContext(), 48), true);
}
/*stickUp = ImageUtility.createBitmap(getResources(),
R.drawable.stick_up);
stickDown = ImageUtility.createBitmap(getResources(),
R.drawable.stick_down);
stickUpPress = ImageUtility
.createBitmap(getResources(), R.drawable.stick_up_press);
stickDownPress = ImageUtility.createBitmap(getResources(),
R.drawable.stick_down_press);*/
holder.addCallback(this);
}
public DoubleAxisRightControllerSurfaceView(Context context) {
super(context);
instance = this;
// TODO Auto-generated constructor stub
initial();
}
public DoubleAxisRightControllerSurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
instance = this;
//Log.e("wild0", "new ControllerSurfaceView:1");
initial();
}
//@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
redraw();
}
//@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
holder.setFormat(PixelFormat.TRANSPARENT);
redraw();
handler.postDelayed(rightMovingTask, tStep);
}
//@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
public void setWifiCar(WifiCar wifiCar) {
this.wifiCar = wifiCar;
}
public void setDirection(int right) {
if(WificarActivity.getInstance().isPlayModeEnable){
WificarActivity.getInstance().sendMessage(WificarActivity.MESSAGE_STOP_PLAY);
}
if(right > 0){ //0805当滑动的速度大于2时,给个全速10
right = MAX;
}
if(right < 0 && right > -4){
right = 0;
}
if(right < -4){
right = -MAX;
}
Log.e("wild0", "direction right:" + right);
/*if(this.size < 5.8){
if(right > 0){ //0805当滑动的速度大于2时,给个全速10
right = MAX;
}
if(right < -4){
right = -MAX;
}
}else{
if(this.width <= 800 & this.height <= 480){
if(right > 0){ //0805当滑动的速度大于2时,给个全速10
right = MAX;
}
if(right < -5){
right = -MAX;
}
}else{
}
}*/
iCarSpeedR = right;
}
public synchronized void redraw() {
Canvas canvas = holder.lockCanvas();
if (canvas == null)
return;
Paint paint = new Paint();
paint.setAlpha(255);
// canvas.drawColor(0, Mode.CLEAR);
// clear(canvas);
//Log.e("wificar", "controller");
//clear(canvas);
if (controlEnable) {
canvas.drawBitmap(stickBar, stickBarPointX, stickBarPointY, paint);
if(this.size < 5.8){
if(this.width <= 480 & this.height <= 320){
canvas.drawBitmap(stickBall, stickBallPointX, stickBallPointSmallY, paint);
}else{
if(this.width > 1100){
Log.e(TAG, "controlEnable ----- >1100");
canvas.drawBitmap(stickBall, stickBallPointX, stickBallPointxxLargeY, paint);
}
else {
canvas.drawBitmap(stickBall, stickBallPointX, stickBallPointY, paint);
}
}
}else{
if(this.width <= 800 & this.height <= 480){ //适应分辨率低的Pad
Log.e(TAG, "controlEnable ----- <800");
canvas.drawBitmap(stickBall, stickBallPointX, stickBallPointLargeY, paint);
}else{
Log.e(TAG, "controlEnable ----- >800");
canvas.drawBitmap(stickBall, stickBallPointX, stickBallPointxLargeY, paint);
}
}
}
holder.unlockCanvasAndPost(canvas);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if(!controlEnable){
return true;
}
int pointerIndex = ((event.getAction() & MotionEvent.ACTION_POINTER_ID_MASK) >> MotionEvent.ACTION_POINTER_ID_SHIFT);
int pointerId = event.getPointerId(pointerIndex);
int action = (event.getAction() & MotionEvent.ACTION_MASK);
int pointerCount = event.getPointerCount();
Log.e("touchinfo", "touch right count(" + pointerId + ":" + action + ":" + event.getAction()
+ "):" + pointerCount);
for (int i = 0; i < pointerCount; i++) {
int id = event.getPointerId(i);
Log.e("wild0","id:"+id+",action:"+action);
switch (action) {
case MotionEvent.ACTION_DOWN:
try{
waitStopState = 0;
//if (pointerCount > 0)
//{
Log.e("down","id:"+id);
float x = event.getX(id);
float y = event.getY(id);
int currentSpeed;
if(this.size < 5.8){
if(this.width <= 480 & this.height <= 320){
currentSpeed = (int) (-(y-stickBallPointBaseSmallY)/7);
if((y-stickBarPointSmallY)>stickBallMotionAreaHeightSmall){
y = stickBarPointSmallY+stickBallMotionAreaHeightSmall;
}
}else{
if(this.width > 1100){
currentSpeed = (int) (-(y-200)/12);
if((y-stickBarPointxxLargeY)>stickBallMotionAreaHeightxxLarge){
y = stickBarPointxxLargeY+stickBallMotionAreaHeightxxLarge;
}
}else{
currentSpeed = (int) (-(y-stickBallPointBaseY)/9);
if((y-stickBarPointY)>stickBallMotionAreaHeight){
y = stickBarPointY+stickBallMotionAreaHeight;
}
}
}
}else{
if(this.width <= 800 & this.height <= 480){
currentSpeed = (int) (-(y-stickBallPointBaseY)/6);
if((y-stickBarPointLargeY)>stickBallMotionAreaHeightLarge){ //0805适应Pad的
y = stickBarPointLargeY+stickBallMotionAreaHeightLarge;
}
}else{
currentSpeed = (int) (-(y-180)/9);
if((y-stickBarPointxLargeY)>stickBallMotionAreaHeightxLarge){ //0805适应Pad的
y = stickBarPointxLargeY+stickBallMotionAreaHeightxLarge;
Log.e(TAG, "down ----------->800");
}
}
}
if(y<stickBarPointTopY){
y = stickBarPointTopY;
}
//TODO
if(this.isLocateAtRightStickBallBoundary(x, y)){
captureRightBall = true;
this.stickBallPointY = (int) y - 20; //0805当按下按钮的时候就发送位置的y坐标,让圆形按钮移动到y点坐标处
this.stickBallPointSmallY = (int) y - 20; //0805当按下按钮的时候就发送位置的y坐标,让圆形按钮移动到y点坐标处
this.stickBallPointxLargeY = (int) y -20; //0805当按下按钮的时候就发送位置的y坐标,让圆形按钮移动到y点坐标处
this.stickBallPointxxLargeY = (int) y -20; //0805当按下按钮的时候就发送位置的y坐标,让圆形按钮移动到y点坐标处
this.stickBallPointLargeY = (int) y - 20; //0805当按下按钮的时候就发送位置的y坐标,让圆形按钮移动到y点坐标处
this.setDirection(currentSpeed);
}
//Log.e("wild0", "("+i+")Action down["+x+","+y+"]");
//Log.e("wild0", "touch right count(1):" + x + "," + y);
this.redraw();
}
catch(Exception e){
e.printStackTrace();
}
break;
case MotionEvent.ACTION_UP:
try{
stopLeftSignal = 1;
stopRightSignal = 1;
waitStopState = 1;
Log.e("barnotify", "ACTION_UP("+i+")Action up");
if(pointerCount==2){
waitStopState = 1;
}
else if(pointerCount==1){
WificarActivity.getInstance().getWifiCar().disableMoveFlag();
this.setDirection(0);
this.stickBallPointY = this.stickBallPointBaseY;
this.stickBallPointSmallY = this.stickBallPointBaseSmallY;
this.stickBallPointxLargeY = this.stickBallPointBasexLargeY;
this.stickBallPointxxLargeY = this.stickBallPointBasexxLargeY;
this.stickBallPointLargeY = this.stickBallPointBaseLargeY;
DoubleAxisLeftControllerSurfaceView.getInstance().setDirection(0);
if(this.size < 5.8){
if(this.width <= 480 & this.height <= 320){
DoubleAxisLeftControllerSurfaceView.getInstance().setStickBallPointSmallY(stickBallPointBaseSmallY);
}else{
if(this.width > 1100)
DoubleAxisLeftControllerSurfaceView.getInstance().setStickBallPointxxLargeY(stickBallPointBasexxLargeY);
else{
DoubleAxisLeftControllerSurfaceView.getInstance().setStickBallPointY(stickBallPointBaseY);
}
}
}else{
if(this.width <= 800 & this.height <= 480){
DoubleAxisLeftControllerSurfaceView.getInstance().setStickBallPointLargeY(stickBallPointBaseLargeY);
}else{
DoubleAxisLeftControllerSurfaceView.getInstance().setStickBallPointxLargeY(stickBallPointBasexLargeY);
}
}
DoubleAxisLeftControllerSurfaceView.getInstance().redraw();
captureRightBall = false;
captureLeftBall = false;
}
}
catch(Exception e){
e.printStackTrace();
}
//this.setDirection(0);
//DoubleAxisLeftControllerSurfaceView.getInstance().setDirection(0);
break;
case MotionEvent.ACTION_MOVE:
try{
waitStopState = 0;
id = event.getPointerId(i);
Log.e("rightbar", i+":("+id+")Action move=>"+event.getPointerCount());
float mx = 0;
float my = 0;
if(event.getPointerCount()==1){
mx = event.getX();
my = event.getY();
}
else if(event.getPointerCount()==2){
mx = event.getX(id);
my = event.getY(id);
}
Log.e("rightbar", "("+id+")Action move");
//Log.e("wild0", "("+i+")Action move");
if(this.size < 5.8){
if(this.width <= 480 & this.height <= 320){
if((my-stickBarPointY)>stickBallMotionAreaHeightSmall){
my = stickBarPointY+stickBallMotionAreaHeightSmall;
}
}else{
if(this.width > 1100){
if((my-stickBarPointxxLargeY)>stickBallMotionAreaHeightxxLarge){
my = stickBarPointxxLargeY+stickBallMotionAreaHeightxxLarge;
}
}else{
if((my-stickBarPointY)>stickBallMotionAreaHeight){
my = stickBarPointY+stickBallMotionAreaHeight;
}
}
}
}else{
if(this.width <= 800 & this.height <= 480){
if((my-stickBarPointLargeY)>stickBallMotionAreaHeightLarge){ //0805适应Pad的
my = stickBarPointLargeY+stickBallMotionAreaHeightLarge;
}
}else{
if((my-stickBarPointxLargeY)>stickBallMotionAreaHeightxLarge){ //0805适应Pad的
my = stickBarPointxLargeY+stickBallMotionAreaHeightxLarge;
}
}
}
if(my<stickBarPointTopY){
my = stickBarPointTopY;
}
if(id==0){
//this.stickBallPointY = (int) my;
if(captureRightBall){
int currentRightSpeed ;
Log.i("DoubleRight", "captureRightBall:" + captureRightBall+ "," + "my:" + my);
if(this.size < 5.8){
if(this.width <= 480 & this.height <= 320){
currentRightSpeed = (int) (-(my-stickBallPointBaseSmallY)/7);
this.stickBallPointSmallY = (int) my - 20; //0805减去20是为了在按下的时候,圆形按钮能滑动到按下的位置
}else{
if(this.width > 1100){
currentRightSpeed = (int) (-(my-stickBallPointBasexxLargeY)/12);
this.stickBallPointxxLargeY = (int) my - WificarActivity.dip2px(getContext(), 10); //0805减去20是为了在按下的时候,圆形按钮能滑动到按下的位置
}else{
currentRightSpeed = (int) (-(my-stickBallPointBaseY)/9);
this.stickBallPointY = (int) my - 20; //0805减去20是为了在按下的时候,圆形按钮能滑动到按下的位置
}
}
}else{
if(this.width <= 800 & this.height <= 480){
currentRightSpeed = (int) (-(my-stickBallPointBaseLargeY)/6);
this.stickBallPointLargeY = (int) my - 20; //0805减去20是为了在按下的时候,圆形按钮能滑动到按下的位置
}else{
currentRightSpeed = (int) (-(my-stickBallPointBasexLargeY)/9);
this.stickBallPointxLargeY = (int) my - WificarActivity.dip2px(getContext(), 10); //0805减去20是为了在按下的时候,圆形按钮能滑动到按下的位置
}
}
//TODO
Log.i("DoubleRight", "currentLeftSpeed:" + currentRightSpeed);
this.setDirection(currentRightSpeed);
}
//this.redraw();
}
else if(id==1){
if(captureLeftBall){
int currentLeftSpeed = 0 ;
if(this.size < 5.8){
if(this.width <= 480 & this.height <= 320){
currentLeftSpeed = (int) (-(my-stickBallPointBaseSmallY)/9);
DoubleAxisLeftControllerSurfaceView.getInstance().setStickBallPointSmallY((int)my -20);
}else{
if(this.width > 1100){
currentLeftSpeed = (int) (-(my-stickBallPointBasexxLargeY)/12);
DoubleAxisLeftControllerSurfaceView.getInstance().setStickBallPointxxLargeY((int)my -20);
}else{
currentLeftSpeed = (int) (-(my-stickBallPointBaseY)/9);
DoubleAxisLeftControllerSurfaceView.getInstance().setStickBallPointY((int)my -20);
}
}
}else{
if(this.width <= 800 & this.height <= 480){
currentLeftSpeed = (int) (-(my-stickBallPointBaseLargeY)/6);
DoubleAxisLeftControllerSurfaceView.getInstance().setStickBallPointLargeY((int)my -20);
}else{
currentLeftSpeed = (int) (-(my-stickBallPointBasexLargeY)/9);
DoubleAxisLeftControllerSurfaceView.getInstance().setStickBallPointxLargeY((int)my -20);
}
}
Log.i("DoubleRight", "currentRightSpeed:" + currentLeftSpeed);
DoubleAxisLeftControllerSurfaceView.getInstance().setDirection(currentLeftSpeed);
DoubleAxisLeftControllerSurfaceView.getInstance().redraw();
}
}
}
catch(Exception e){
e.printStackTrace();
Log.e("rightbar", "excep ("+event.getX(0)+")Action move");
}
break;
case MotionEvent.ACTION_POINTER_1_UP:
//if(id==1){
try{
stopLeftSignal = 1;
stopRightSignal = 1;
waitStopState = 1;
float x2 = event.getX(id);
float y2 = event.getY(id);
Log.e("barnotify", "ACTION_POINTER_1_UP("+pointerId+","+id+"):" + x2 + "," + y2);
if(pointerId==id){
//if(this.isLocateAtRightStickBallBoundary(x2)){
if(id==0){
captureRightBall = false;
setDirection(0);
this.stickBallPointY = this.stickBallPointBaseY;
this.stickBallPointSmallY = this.stickBallPointBaseSmallY;
this.stickBallPointxLargeY = this.stickBallPointBasexLargeY;
this.stickBallPointxxLargeY = this.stickBallPointBasexxLargeY;
this.stickBallPointLargeY = this.stickBallPointBaseLargeY;
}
//}
//if(this.isLocateAtLeftStickBallBoundary(x2)){
if(id==1){
captureLeftBall = false;
if(this.size < 5.8){
if(this.width <= 480 & this.height <= 320){
DoubleAxisLeftControllerSurfaceView.getInstance().setStickBallPointSmallY(stickBallPointBaseSmallY);
}else{
if(this.width > 1100)
DoubleAxisLeftControllerSurfaceView.getInstance().setStickBallPointxxLargeY(stickBallPointBasexxLargeY);
else
DoubleAxisLeftControllerSurfaceView.getInstance().setStickBallPointY(stickBallPointBaseY);
}
}else{
if(this.width <= 800 & this.height <= 480){
DoubleAxisLeftControllerSurfaceView.getInstance().setStickBallPointLargeY(stickBallPointBaseLargeY);
}else{
DoubleAxisLeftControllerSurfaceView.getInstance().setStickBallPointxLargeY(stickBallPointBasexLargeY);
}
}
DoubleAxisLeftControllerSurfaceView.getInstance().setDirection(0);
DoubleAxisLeftControllerSurfaceView.getInstance().redraw();
}
//}
}
}
catch(Exception e){
e.printStackTrace();
}
break;
case MotionEvent.ACTION_POINTER_1_DOWN:
try{
waitStopState = 0;
if(id==1){
float x1 = event.getX(id);
float y1 = event.getY(id);
Log.e("wild0", "touch left point down count(1):" + x1 + "," + y1);
if(this.isLocateAtLeftStickBallBoundary(x1, y1)){
int currentLeftSpeed ;
this.captureLeftBall = true;
if(this.size < 5.8){
if(this.width <= 480 & this.height <= 320){
currentLeftSpeed = (int) (-(y1-stickBallPointBaseSmallY)/7);
if((y1-stickBarPointSmallY)>stickBallMotionAreaHeightSmall){
y1 = stickBarPointSmallY+stickBallMotionAreaHeightSmall;
}
if(y1<stickBarPointTopY){
y1 = stickBarPointTopY;
}
DoubleAxisLeftControllerSurfaceView.getInstance().setStickBallPointSmallY((int)y1 -20);
}else{
if(this.width > 1100){
currentLeftSpeed = (int) (-(y1-stickBallPointBaseY)/9);
if((y1-stickBarPointxxLargeY)>stickBallMotionAreaHeightxxLarge){
y1 = stickBarPointxxLargeY+stickBallMotionAreaHeightxxLarge;
}
if(y1<stickBarPointTopY){
y1 = stickBarPointTopY;
}
DoubleAxisLeftControllerSurfaceView.getInstance().setStickBallPointxxLargeY((int)y1 -20);
}else{
currentLeftSpeed = (int) (-(y1-stickBallPointBaseY)/9);
if((y1-stickBarPointY)>stickBallMotionAreaHeight){
y1 = stickBarPointY+stickBallMotionAreaHeight;
}
if(y1<stickBarPointTopY){
y1 = stickBarPointTopY;
}
DoubleAxisLeftControllerSurfaceView.getInstance().setStickBallPointY((int)y1 -20);
}
}
}else{
if(this.width <= 800 & this.height <= 480){
currentLeftSpeed = (int) (-(y1-stickBallPointBaseY)/6);
if((y1-stickBarPointLargeY)>stickBallMotionAreaHeightLarge){ //0805适应Pad的
y1 = stickBarPointLargeY+stickBallMotionAreaHeightLarge;
}
if(y1<stickBarPointTopY){
y1 = stickBarPointTopY;
}
DoubleAxisLeftControllerSurfaceView.getInstance().setStickBallPointLargeY((int)y1 -20);
}else{
currentLeftSpeed = (int) (-(y1-stickBallPointBaseY)/9);
if((y1-stickBarPointxLargeY)>stickBallMotionAreaHeightxLarge){ //0805适应Pad的
y1 = stickBarPointxLargeY+stickBallMotionAreaHeightxLarge;
}
if(y1<stickBarPointTopY){
y1 = stickBarPointTopY;
}
DoubleAxisLeftControllerSurfaceView.getInstance().setStickBallPointxLargeY((int)y1 -WificarActivity.dip2px(getContext(), 10));
}
}
DoubleAxisLeftControllerSurfaceView.getInstance().setDirection(currentLeftSpeed);
DoubleAxisLeftControllerSurfaceView.getInstance().redraw();
}
}
}
catch(Exception e){
e.printStackTrace();
}
break;
default:
break;
}
}
if(stopRightSignal ==1 && waitStopState==0){
//setDirection(0);
stopRightSignal=0;
}
else if(stopLeftSignal ==1 && waitStopState==0){
//DoubleAxisLeftControllerSurfaceView.getInstance().setDirection(0);
stopLeftSignal=0;
}
this.redraw();
DoubleAxisLeftControllerSurfaceView.getInstance().redraw();
return true;
}
public void setStickBallPointY(int y){
//0805在按下左边的时候,传过来的参数做下限制
if(y>stickBallMotionAreaHeight){
y = stickBallMotionAreaHeight;
}
if(y < 0){
y = 0;
}
this.stickBallPointY = y;
}
public void setStickBallPointSmallY(int y){
//0805在按下左边的时候,传过来的参数做下限制
if(y>stickBallMotionAreaHeightSmall){
y = stickBallMotionAreaHeightSmall;
}
if(y < 0){
y = 0;
}
this.stickBallPointSmallY = y;
}
public void setStickBallPointLargeY(int y){
//0805在按下左边的时候,传过来的参数做下限制
if(y> stickBallMotionAreaHeightLarge){
y = stickBallMotionAreaHeightLarge;
}
if(y < 0){
y = 0;
}
this.stickBallPointLargeY = y;
}
public void setStickBallPointxLargeY(int y){
//0805在按下左边的时候,传过来的参数做下限制
if(y> stickBallMotionAreaHeightxLarge){
y = stickBallMotionAreaHeightxLarge;
}
if(y < 0){
y = 0;
}
this.stickBallPointxLargeY = y;
}
public void setStickBallPointxxLargeY(int y){
//0805在按下左边的时候,传过来的参数做下限制
if(y> stickBallMotionAreaHeightxxLarge){
y = stickBallMotionAreaHeightxxLarge;
}
if(y < 0){
y = 0;
}
this.stickBallPointxxLargeY = y;
}
public boolean isLocateAtLeftStickBallBoundary(float x, float y){
int widthPixel = ImageUtility.getWidth(this.getContext());
int leftXL = -(widthPixel-stickBarWidth);
int leftXR = -(widthPixel-stickBarWidth)+stickBarWidth*2;
int edge = stickBallMotionAreaWidth-stickBallWidth;
// Log.i("barnotify", "width:"+widthPixel+", x:"+x+",("+leftXL+","+leftXR+")");
// Log.i("isLocateAtRightStick", "(x,y):"+ "("+x+","+y+")" + "edge:" + edge);
// Log.i("isLocateAtRightStick", "leftXL-edge*4:"+ (leftXL-edge*4));
// Log.i("isLocateAtRightStick", "(leftXR+edge):"+ (leftXR+edge));
// Log.i("isLocateAtRightStick", "stickBallPointY:"+ stickBallPointY + "," + "stickBallHeight:" + stickBallHeight);
// Log.i("isLocateAtRightStick", "(stickBallPointY-edge):"+ (stickBallPointY-edge));
// Log.i("isLocateAtRightStick", "(edge-stickBallPointY):"+ (edge-stickBallPointY));
// Log.i("isLocateAtRightStick", "(stickBallPointY+stickBallHeight+edge):"+ (stickBallPointY+stickBallHeight+edge));
// Log.e("barnotify", "width:"+widthPixel+", x:"+x+",("+leftXL+","+leftXR+")");
if (x > (leftXL-edge*4) && x < (leftXR+edge) && y>-40 && y < 300) {
return true;
} else {
return false;
}
}
public boolean isLocateAtRightStickBallBoundary(float x, float y){
int widthPixel = ImageUtility.getWidth(this.getContext());
//int leftXL = (-widthPixel);
//int leftXR = (-widthPixel+stickBallWidth);
int edge = stickBallMotionAreaWidth-stickBallWidth;
//Log.e("boundary", "x:"+x+",y:"+y);
/*Log.i("isLocateAtRight", "x:" + x +" ," + "y:" + y +"," + "edge:" + edge);
Log.i("isLocateAtRight", "stickBallMotionAreaWidth:" + stickBallMotionAreaWidth + "stickBallWidth:" + stickBallWidth);
Log.i("isLocateAtRight", "(stickBallPointX-edge):" + (stickBallPointX-edge));
Log.i("isLocateAtRight", "(stickBallPointX+stickBallWidth+edge):" + (stickBallPointX+stickBallWidth+edge));
Log.i("isLocateAtRight", "(stickBallPointY-edge):" + (stickBallPointY-edge));
Log.i("isLocateAtRight", "(stickBallPointY+stickBallHeight+edge):" + (stickBallPointY+stickBallHeight*2+edge));*/
//if (x > (stickBallPointX-edge) && x < (stickBallPointX+stickBallWidth+edge) && y>(stickBallPointY-edge-40) && y <(stickBallPointY+stickBallHeight*2+edge+10)) {
if (x > (stickBallPointX-edge) && x < (stickBallPointX+stickBallWidth+edge) && y> 20 && y < WificarActivity.dip2px(getContext(), 224)) {
Log.e("boundary", "r:"+true);
return true;
} else {
return false;
}
}
//@Override
public void disableControl() {
// TODO Auto-generated method stub
controlEnable = false;
this.setVisibility(INVISIBLE);
this.redraw();
}
//@Override
public void enableControl() {
// TODO Auto-generated method stub
controlEnable = true;
this.setVisibility(VISIBLE);
this.redraw();
}
private Runnable rightMovingTask = new Runnable() {
public void run() {
if (controlEnable) {
//if (iLastSpeedL != 0 && iCarSpeedL == 0)
// wifiCar.moveCommand(WifiCar.GO_DIRECTION.Left, iCarSpeedL);
//iLastSpeedL = iCarSpeedL;
if (iCarSpeedR != 0){
Log.e("wild0", "Run r("+controlEnable+"):"+iCarSpeedR);
try {
wifiCar.move(WifiCar.RIGHT_WHEEL, iCarSpeedR);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
iLastSpeedR=iCarSpeedR;
}
if (iCarSpeedR == 0 && iLastSpeedR!=0){
try {
wifiCar.move(WifiCar.RIGHT_WHEEL, iCarSpeedR);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
iLastSpeedR=0;
}
}
handler.postDelayed(this, tStep);
}
};
}
<file_sep>/Rover 2.0-android-src/src/com/wificar/WificarActivity.java
package com.wificar;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Timer;
import java.util.TimerTask;
import com.CAR2.R;
import com.wificar.component.AudioComponent;
import com.wificar.component.CommandEncoder;
import com.wificar.component.WifiCar;
import com.wificar.dialog.Connect_Dialog;
import com.wificar.dialog.Control_share_dialog;
import com.wificar.dialog.DeleteDialog;
import com.wificar.dialog.DisGsensor;
import com.wificar.dialog.Disrecord_play_dialog;
import com.wificar.dialog.Disrecordvideo_dialog;
import com.wificar.dialog.SDcardCheck;
import com.wificar.dialog.VideoSaveDialog;
import com.wificar.dialog.wifi_not_connect;
import com.wificar.mediaplayer.MediaPlayerActivity;
import com.wificar.surface.CamerSettingSurfaceView;
import com.wificar.surface.CameraSurfaceView;
import com.wificar.surface.ControllerInterface;
import com.wificar.surface.DoubleAxisLeftControllerSurfaceView;
import com.wificar.surface.DoubleAxisRightControllerSurfaceView;
import com.wificar.util.AVIGenerator;
import com.wificar.util.BlowFish;
import com.wificar.util.BlowFishEncryptUtil;
import com.wificar.util.ByteUtility;
import com.wificar.util.ImageUtility;
import com.wificar.util.MessageUtility;
import com.wificar.util.TimeUtility;
import com.wificar.util.VideoUtility;
import com.wificar.util.WificarUtility;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Bitmap.Config;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.MediaScannerConnection;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
//import android.util.Log;
import android.text.format.Time;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.GestureDetector.OnDoubleTapListener;
import android.view.GestureDetector.OnGestureListener;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class WificarActivity extends Activity {
/** Called when the activity is first created. */
public double dimension = 0.0;
private PopupWindow mPopupWindow;
private Context mContext;
private boolean bThreadRun = false; //进入设置界面时的处理事情的线程标识
private boolean bPhotoThreadRun = false;
private String IP ;
private String Port;
private String version;
private String firmwareVersion;
private String SSID;
public EditText tIP ;
public EditText tPort;
public TextView tdevice;
public TextView tfirmware;
public TextView tsoftware;
private Button Okbutton;
// 初始化变�??
public static int Screen_width;
public static int Screen_height;
public static float dscale;// dp -- px
public float density;
public double screenSize;
private Dialog dlg ;
private static int videoWidth = 320;
private static int videoHeight = 240;
private static AVIGenerator movUtil = null;
private boolean sensorEnable = false;
private AudioComponent audio = null;
public static WificarActivity instance = null;
private SensorManager mSensorManager;
private Sensor aSensor;
private static boolean videoRecordEnable = false;
private Sensor mfSensor;
private boolean gSensorControlEnable = false;
static {
// System.loadLibrary("avutil");
// System.loadLibrary("avcore");
// System.loadLibrary("avcodec");
// System.loadLibrary("avformat");
// System.loadLibrary("avdevice");
// System.loadLibrary("swscale");
// System.loadLibrary("avfilter");
// System.loadLibrary("ffmpeg");
// System.loadLibrary("ffmpeg-test-jni");
}
// public static native String stringFromJNI();
// private static native void initial(int width, int height, int frameTime);
// public native String videoEncodeExample(String filename);
// private static native void openStream(String filename);
// private static native void writeBytes(byte[] img);
// private static native void closeStream();
private int controllerType = 1;
public final static int SINGLE_CONTROLLER = 0;
public final static int DOUBLE_AXIS_CONTROLLER = 1;
// private ControllerInterface surface = null;
private DoubleAxisLeftControllerSurfaceView leftSurface = null;
private DoubleAxisRightControllerSurfaceView rightSurface = null;
private CameraSurfaceView cameraSurfaceView = null;
private WifiCar wifiCar = null;
private Handler handler = null;
private boolean isLowPower = false;
private int LowPower;
private int level;
private int scale;
private String startSSID;
private String DirectPath;
private ProgressDialog connectionProgressDialog = null;
private ProgressDialog settingProgressDialog;
public final static int MESSAGE_GET_SETTING_INFO = 8701;
protected static final int MESSAGE_MAIN_SETTING = 8700;
protected static final int MESSAGE_TAKE_PHOTO = 8702;
public final static int MESSAGE_WIFISTATE = 8900;
public final static int MESSAGE_SOUND = 8999;
public final static int MESSAGE_SETTING = 9000;
public final static int MESSAGE_CONNECT_TO_CAR = 8901;
public final static int MESSAGE_CONNECT_TO_CAR_SUCCESS = 8902;
public final static int MESSAGE_CONNECT_TO_CAR_FAIL = 8903;
public final static int MESSAGE_DISCONNECTED = 8904;
protected static final int MESSAGE_START_APPLICATION = 8905;
protected static final int MESSAGE_STOP_RECORD = 8910;
public static final int MESSAGE_STOP_PLAY = 8911;
protected static final int MESSAGE_START_RECORD = 8912;
public static final int MESSAGE_START_PLAY = 8913;
public static final int MESSAGE_PLAY_PICTRUE = 8914;
public static final int MESSAGE_PLAY_VIDEO = 8917;
public static final int MESSAGE_STOP_VIDEO = 8918;
protected static final int MESSAGE_START_RECORD_AUDIO = 7000;
protected static final int MESSAGE_STOP_RECORD_AUDIO = 7001;
protected static final int MESSAGAE_BATTERY = 9502;
public static final int MESSAGE_BATTERY_100 = 9001;
public static final int MESSAGE_BATTERY_75 = 9002;
public static final int MESSAGE_BATTERY_50 = 9003;
public static final int MESSAGE_BATTERY_25 = 9004;
public static final int MESSAGE_BATTERY_0 = 9005;
public static final int MESSAGE_BATTERY_UNKNOWN = 9006;
protected static final int MESSAGE_CHECK_TEST= 8915; //检测不足时发的消息
private float[] fAccelerometerValues = null;
private float[] fMagneticFieldValues = null;
private int LR = 0;
private boolean LRshow = false;
public boolean isGsensor = false;
public boolean disGsensor = false;
public boolean isNotExit = false;
private boolean bIsPortait = true;
private boolean orientationLock = false;
private boolean connect_error = false;
private boolean No_Sdcard = false;
private boolean stopVideo = false;
private boolean startVideo = false;
public boolean isconnectwifi = true;
private boolean controlEnable = false;
public boolean succeedConnect = false;
public boolean isPlayModeEnable = false;
// private int iRotation = 0;
private Timer stop_talk = new Timer(true);
private Timer tGMove = null;
private final int iStep = 100;
private int iCarSpeedR = 0;
private int iCarSpeedL = 0;
private int iLastSpeedL = 0;
private int GsensorCountF = 0;
private int GsensorCountB = 0;
private float fBaseDefault = 9999;
private float fBasePitch = fBaseDefault, fBaseRoll = fBaseDefault;
private float stickRadiu = 40;
private float accDefaultX = 9999;
private float accDefaultY = 9999;
private int f = 0;
private int b = 0;
private int cameramove =0 ;
private int setting = 0;
public int audio_play = 0;
public int audio_stop = 0;
private int Volume;
private int isTalk = 0;
private int isZero = 0;
//private boolean bSetting1 = false;
public int flag = 0;
public int sdcheck = 0;
// Used in the back button behavior
private long lastPressTime = 0;
private static final int DOUBLE_PRESS_INTERVAL = 2000;
private static final String TAG = "";
public int with;
public int hight;
// button timer
private Timer checkSound = new Timer(true);
private Timer recTimer = new Timer(true);
private Timer playTimer = new Timer(true);
private Timer replayTimer = new Timer(true);
private Timer checkTimer = new Timer(true);
private Timer checkSDcard = new Timer(true);
private Timer take_pictrue = new Timer(true);
private Timer take_video = new Timer(true);
private Timer stop_take_video = new Timer(true);
private Timer reConnectTimer = new Timer(true);
private Timer timeout2 = null;
private long lastTime;
private long nSDFreeSize;
private long startRecordTimeStamp = 0;
private long recordTimeLength ;
private long recordTimeLength1;
private long replay_start = 0 ;
//private long replay_stop = 0;
private long replay_time;
//private long replay_time1;
private int replay_flag = 0;
private String FileName;
private VideoSaveDialog videoSaveDialog = new VideoSaveDialog();
//存放记录拍照的时间的变量名
public int isplay_pictrue = 0 ;
public int take_pictrue_T = 0;
public int take_pictrue_T1;
public int j = 0;
public long [] record_times;
public int take_flag = 0;
//public int take_p_times = 0;
public long [] time ;
public String take_p;
public int pictrue_play = 0;
public int pictrue_play1;
public int pictrue_pressed = 0;
//public int t = 0;
//存放记录视频动作的变量名
//开始录制的
public int isplay_video = 0;
public int take_video_T = 0;
public int take_video_T1;
public int k = 0;
public long [] record_video_times;
public long [] video_time;
public String take_v;
public int video_play = 0;
public int video_play1;
public int video_record_stop = 0;
//public long press_video_start;
private int video_pressed = 0;
//结束录制的
public int take_video_T_S = 0;
public int take_video_T_S1;
public int s = 0;
public long [] stop_video_times;
public long [] stop_time;
public String stop_take_v;
public int video_play_stop = 0;
public int video_play_stop1;
public String FILENSME = "time_record";
public String FILENAME_V="time_video";
public String FILENAME_S="stop_video";
private String RECORD_TIME = "record_time";
private WifiManager mWifiManager;
private WifiInfo mWifiInfo;
private int wifiRssi;
private int RssiLevel;
private String ssid;
private Bitmap batteryBitmap = null;
public static WificarActivity getInstance() {
return instance;
}
public void sendMessage(int cmd){
Message msg = new Message();
msg.what = cmd;
this.getHandler().sendMessage(msg);
}
public void openVideoStream(String fileName) throws Exception {
//Log.e("record","start recording:" + DirectPath + " ,"+fileName );
//Log.e("record","start recording:" + videoWidth + " " + videoHeight);
wifiCar.startFlim(DirectPath + "/Videos" , fileName, videoWidth, videoHeight);
videoRecordEnable = true;
}
public void closeVideoStream() throws Exception {
// closeStream();
//movUtil.finishAVI();
Log.e("record","stop recording");
wifiCar.stopFlim();
videoRecordEnable = false;
//sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://" + Environment.getExternalStorageDirectory()))); //结束时扫描SDcard
}
public Handler getHandler() {
return handler;
}
public WifiCar getWifiCar() {
return wifiCar;
}
@Override
protected void onStop() {
//if(!isNotExit){
//Log.e("zhang", "Home exit!");
isNotExit = false;
if(!No_Sdcard)
DeleVideo();
deleIndexVideo(); //删除*.index文件
//wifiCar.disconnect();
//wifiCar.setDisconnect();
finish();
System.exit(0);
//exit();
exitProgrames();
//}
super.onStop();
//Log.e("activity","on stop");
}
@Override
protected void onPause() {
super.onPause();
if(!No_Sdcard)
DeleVideo();
deleIndexVideo(); //删除*.index文件
pause();
if(isPlayModeEnable){
try {
wifiCar.stopPlayTrack();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
exitProgrames();
/* if (!isNotExit ) {
Log.d("wild0","disconnect");
//wifiCar.setDisconnect();
exitProgrames();
// SplashActivity.getInstance().exit();
}*/
//Log.e("activity", "on Pause");
}
private BroadcastReceiver spReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String str = intent.getAction();
Log.d("wild0", "In myReceiver, action = " + str);
Log.d("Settings", "Received action: " + str);
if (str.equals("android.intent.action.BATTERY_CHANGED")) {
//获取手机的电量
level = intent.getIntExtra("level", 0);
scale = intent.getIntExtra("scale", 100);
int power = level * 100 / scale;
//Log.e("zhangzhang11" ,"电池电量:" + power + "%");
sendMessage(MESSAGAE_BATTERY);
if(power < 20){
isLowPower = true;
}
if(power > 20){
isLowPower = false;
}
Log.d("wild0", "battery changed...");
} else if(str.equals("android.intent.action.BATTERY_LOW")){
//Log.e("zhang", "低电量提示!");
//int level = intent.getIntExtra("level", 0);
//int scale = intent.getIntExtra("scale", 100);
isLowPower = true;
LowPower = level * 100 / scale;
//Log.e("zhangzhang" ,"低电量时的电池电量:" + (level * 100 / scale) + "%");
}else if (str
.equals("android.intent.action.ACTION_POWER_CONNECTED")) {
//Log.d("wild0", "power connected");
} else if (str
.equals("android.intent.action.ACTION_POWER_DISCONNECTED")) {
//Log.d("wild0", "power disconnected");
} else if (str.equals("WifiManager.WIFI_STATE_CHANGED_ACTION")) {
int wifiState = intent.getIntExtra(
WifiManager.EXTRA_WIFI_STATE,
WifiManager.WIFI_STATE_UNKNOWN);
//sendMessage(MESSAGE_WIFISTATE);
//Log.e("wild0", "wifi state is " + wifiState);
} else if (str.equals("BluetoothAdapter.STATE_ON")) {
//Log.d("wild0", "bluetooth on");
} else if (str.equals("BluetoothAdapter.STATE_TURNING_OFF")) {
//Log.d("wild0", "bluetooth off");
} else if (str.equals("android.intent.action.SCREEN_OFF")) {
// wifiCar.disconnect();
// finish();
// System.exit(0);
}else if (str.equals("android.intent.action.SCREEN_ON")) {
}
}
};
public void exit() {
if(isPlayModeEnable){
try {
wifiCar.stopPlayTrack();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//SplashActivity.getInstance().exit();
finish();
System.exit(0);
}
public void pause(){
if(wifiCar.isConnected()==1){
Log.e("activity","on exit 1");
//wifiCar.stopAudio();
if(isPlayModeEnable){
try {
wifiCar.stopPlayTrack();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
wifiCar.led_offTrack();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
wifiCar.disableIR();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}// 闽超縊
/*try {
boolean result = wifiCar.disableAudio();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}*/// 闽超羘
disableGSensorControl();// 闽超gsensor
if (sensorEnable) {
mSensorManager.unregisterListener(myAccelerometerListener);
mSensorManager.unregisterListener(myMagneticFieldListener);
}
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("activity","on exit");
//wifiCar.setDisconnect();// 闽超硈絬
}
}
@Override
protected void onResume() {
super.onResume();
reload();
/*if( setting == 1 && audio_play == 1){
//play_audio();
setting_play();
}*/
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.intent.action.SCREEN_ON");
intentFilter.addAction("android.intent.action.SCREEN_OFF");
intentFilter.addAction("android.intent.action.BATTERY_LOW");
intentFilter.addAction("android.intent.action.BATTERY_OKAY");
intentFilter.addAction("android.intent.action.BATTERY_CHANGED");
intentFilter.addAction("android.intent.action.ACTION_POWER_CONNECTED");
intentFilter.addAction("android.intent.action.ACTION_POWER_DISCONNECTED");
intentFilter.addAction("WifiManager.WIFI_STATE_CHANGED_ACTION");
intentFilter.addAction("BluetoothAdapter.STATE_TURNING_OFF");
intentFilter.addAction("BluetoothAdapter.STATE_ON");
registerReceiver(spReceiver, intentFilter);
Log.e("activity", "on Resume");
Runnable init = new Runnable() {
// @Override
public void run() {
Log.e("wificar", "connecting .....");
boolean result = wifiCar.setConnect();
// Log.d("wild0", "connecting result:" + result);
wifiCar.updatedChange();
if (result) {
//Message messageConnectSuccess = new Message();
//messageConnectSuccess.what = MESSAGE_CONNECT_TO_CAR_SUCCESS;
//handler.sendMessage(messageConnectSuccess);
Log.e(TAG, "result1:"+result);
} else {
Log.e(TAG, "result2:"+result);
Message messageConnectFail = new Message();
messageConnectFail.what = MESSAGE_CONNECT_TO_CAR_FAIL;
handler.sendMessage(messageConnectFail);
}
}
};
//if (wifiCar.isChange() || !wifiCar.bConnected) {
if ( wifiCar.isConnected()==0) {
//Message messageConnect = new Message();
//messageConnect.what = MESSAGE_CONNECT_TO_CAR;
//handler.sendMessage(messageConnect);
Thread initThread = new Thread(init);
initThread.start();
}
// if(wifiCar==null) return ;
// wifiCar.connect();
ToggleButton gSensorTogglebutton = (ToggleButton) findViewById(R.id.g_sensor_toggle_button);
if (gSensorTogglebutton != null && gSensorTogglebutton.isChecked()) {
enableGSensorControl();
}
}
/*@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.wificar_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.videoPlayer_menu_item:
//isNotExit = true;
//Intent intent = new Intent();
//intent.setClass(instance, FileListActivity.class);
//startActivityForResult(intent, 5);
break;
default:
break;
}
return super.onMenuItemSelected(featureId, item);
}*/
@Override
protected void onDestroy() {
// Log.d("wild0","on Destroy");
super.onDestroy();
Log.d("activity","on destory");
if(!No_Sdcard)
DeleVideo();
deleIndexVideo(); //删除*.index文件
}
// private ViewSwitcher switcher = null;
public void reload(){
this.changeLandscape();
connectionProgressDialog = new ProgressDialog(this);
//connectionProgressDialog.setTitle("タ硈絬");
//connectionProgressDialog.setMessage("硈絬い叫祔...");
// changePortrait();
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
aSensor = mSensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mfSensor = mSensorManager
.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
int o = getResources().getConfiguration().orientation;
//this.changeLandscape();// ッㄏノlandscape
//
// set false when initializing
ToggleButton irTogglebutton = (ToggleButton) findViewById(R.id.light_toggle_button);
ToggleButton micTogglebutton = (ToggleButton) findViewById(R.id.mic_toggle_button);
ToggleButton ledTogglebutton =(ToggleButton) findViewById(R.id.led_toggle_button);
ToggleButton videTogglebutton =(ToggleButton)findViewById(R.id.video_toggle_button);
Button takepictruebutton = (Button) findViewById(R.id.take_picture_button);
irTogglebutton.setChecked(false);
irTogglebutton.setBackgroundResource(R.drawable.ir);
micTogglebutton.setChecked(false);
micTogglebutton.setBackgroundResource(R.drawable.mic);
ledTogglebutton.setChecked(false);
ledTogglebutton.setBackgroundResource(R.drawable.led);
videTogglebutton.setChecked(false);
if(dimension > 5.8){
videTogglebutton.setBackgroundResource(R.drawable.video);
takepictruebutton.setBackgroundResource(R.drawable.camera);
}else {
videTogglebutton.setBackgroundResource(R.drawable.video1);
takepictruebutton.setBackgroundResource(R.drawable.camera1);
}
}
@Override
protected void onStart() {
super.onStart();
Log.d("activity", "WificarActivity:on Start");
}
public void reStartConnect(){ //断电或者信号弱到没有的时候重新连接
Log.e("wificar", "restart connecting .....");
reConnectTimer = new Timer(true);
reConnectTimer.schedule(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
boolean result = wifiCar.setConnect();
Log.e("zhang", "reconnecting result:" + result);
wifiCar.updatedChange();
if (result) {
//Message messageConnectSuccess = new Message();
//messageConnectSuccess.what = MESSAGE_CONNECT_TO_CAR_SUCCESS;
//handler.sendMessage(messageConnectSuccess);
} else {
Message messageConnectFail = new Message();
messageConnectFail.what = MESSAGE_CONNECT_TO_CAR_FAIL;
handler.sendMessage(messageConnectFail);
if(reConnectTimer != null){
reConnectTimer.cancel();
reConnectTimer = null;
}
}
}
}, 6000); //wifi信号断开14s+6s = 20s后重新连接
/**/
}
// public static int dip2px(float dpValue) {
// return (int) (dpValue * dscale + 0.5f);
// }
//
/**
* 根据手机的分辨率从 dp 的单位 转成为 px(像素)
*/
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
instance = this;
Log.d("activity", "WificarActivity:on Create");
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, //取消屏保
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,
WindowManager.LayoutParams. FLAG_FULLSCREEN);
// getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
// WindowManager.LayoutParams.FLAG_FULLSCREEN);
//setContentView(R.layout.double_axis_landscape);
isconnectwifi = note_Intent(instance);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
// 获取屏幕的宽度,高度和密度以及dp / px
// public void getDisplayMetrics() {
// Screen_width = dm.widthPixels;
// Screen_height = dm.heightPixels;
// Log.e(TAG, "Screen_width:"+Screen_width);
// Log.e(TAG, "Screen_height:"+Screen_height);
// scale = activity.getResources().getDisplayMetrics().density;
Log.e(TAG, "Width = " + dm.widthPixels );
Log.e(TAG, "Height = " + dm.heightPixels);
// }
//启动就创建CAR 2.0文件夹
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
DirectPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/CAR 2.0";
File fileP = new File(DirectPath + "/Pictures");
if (!fileP.exists()) {
fileP.mkdirs();
}
File fileV = new File(DirectPath + "/Videos");
if (!fileV.exists()) {
fileV.mkdirs();
}
}
//////////////03.24程序启动后10ms检测SDcard的剩余容量///////////
checkTimer = new Timer(true);
checkTimer.schedule(new SDCardSizeTest(), 10);
//////////////03.24程序启动后每隔1s检测SDcard的剩余容量///////////
/*
* 获取屏幕分辨率
*/
// DisplayMetrics dm = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(dm);
with = dm.widthPixels ;
hight = dm.heightPixels;
density = dm.density;
double bb = Math.sqrt(Math.pow(with, 2)
+ Math.pow(hight, 2));
screenSize = bb / (160 * dm.density);
Log.e("Main", "Width = " + dm.widthPixels );
Log.e("Main", "Height = " + dm.heightPixels);
//自定义禁止G-sensor的对话框
dlg = new DisGsensor(instance,R.style.CustomDialog);
new MessageUtility(instance);
int[] rands = WificarUtility.getRandamNumber();
wifiCar = new WifiCar(this, rands[0], rands[1], rands[2], rands[3]);
try {
//ImageView battery = null;
handler = new Handler() {
public void handleMessage(Message msg) {
ToggleButton recordTogglebutton = (ToggleButton) findViewById(R.id.record_toggle_button);
Button playTogglebutton = (Button) findViewById(R.id.play_toggle_button);
ToggleButton micbutton = (ToggleButton) findViewById(R.id.mic_toggle_button);
ImageView soundImg= (ImageView) findViewById(R.id.no_sound);
final Button takePictureBtn = (Button) findViewById(R.id.take_picture_button);
final ToggleButton videoTogglebutton = (ToggleButton) findViewById(R.id.video_toggle_button);
final Button recordAudioTogglebutton = (Button) findViewById(R.id.talk_button);
switch (msg.what) {
case MESSAGE_MAIN_SETTING:
/*if(isSpeaking()){
micbutton.setChecked(false);
micbutton.setBackgroundResource(R.drawable.mic);
}
if(checkSound != null){
checkSound.cancel();
checkSound = null;
}*/
break;
case MESSAGE_GET_SETTING_INFO:
new Thread (new MyThread()).start();
bThreadRun = true;
break;
case MESSAGE_TAKE_PHOTO:
/*if (cameraSurfaceView != null) {
try {
// takePictureBtn.setBackgroundResource(R.drawable.camera_pressed);
Log.e("take photo", "start take photo");
wifiCar.takePicture(instance);
} catch (Exception e) {
e.printStackTrace();
}
}*/
//new Thread (new MyPhotoThread()).start();
bPhotoThreadRun = true;
handler.postDelayed(TakePhotoTask, 10);
break;
case MESSAGE_SOUND:
AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
Volume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
Log.e("zhang", "currentVolume11 :" + Volume);
if(Volume == 0){
//Log.e("zhang", "soudImg :" + soundImg);
isZero = 1;
soundImg.setVisibility(View.VISIBLE);
micbutton.setBackgroundResource(R.drawable.mic);
micbutton.setChecked(false);
micbutton.setClickable(true);
}
else {
soundImg.setVisibility(View.GONE);
if(audio_play == 0 || isTalk == 1){ //isTalk=1为对讲按钮按下时 ,audio_play = 0为Mic按钮手动按下还原
soundImg.setVisibility(View.VISIBLE);
}
if(audio_play == 1 && isTalk == 0){ // MIC按钮没有手动还原,对讲按钮没有按下
micbutton.setBackgroundResource(R.drawable.mic_pressed);
micbutton.setChecked(true);
micbutton.setClickable(true);
isZero = 0;
}
}
break;
case MESSAGE_WIFISTATE:
/*switch (wifiState) {
case WifiManager.WIFI_STATE_DISABLED:
Toast.makeText(instance , "wifi关闭!",
Toast.LENGTH_LONG).show();
break;
case WifiManager.WIFI_STATE_DISABLING:
break;
case WifiManager.WIFI_STATE_ENABLED:
Toast.makeText(instance , "wifi打开!",
Toast.LENGTH_LONG).show();
break;
case WifiManager.WIFI_STATE_ENABLING:
break;
case WifiManager.WIFI_STATE_UNKNOWN:
break;
} */
break;
case MESSAGE_CONNECT_TO_CAR:
//connectionProgressDialog.show();
break;
case MESSAGE_CONNECT_TO_CAR_SUCCESS:
succeedConnect = true;
//refreshUIListener();
connectionProgressDialog.cancel();
//Toast connectedToast = Toast.makeText(instance,
// "Success to connect", Toast.LENGTH_SHORT);
///connectedToast.show();
//InitWifiInfo();
//启动软件后获取当前连接的SSID
/*try {
startSSID = wifiCar.getSSID();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}*/
checkSDcard = new Timer(true);
checkSDcard.schedule(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
//Log.e("zhangzhang", "检测是否存在SDcard");
wifiCar.isConnected();
if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
//Log.e("zhangzhang", "检测到没有SDcard");
No_Sdcard = true;
}else{
No_Sdcard = false;
//Log.e("zhangzhang", "检测到又有SDcard存在了");
}
if(!No_Sdcard)
deleIndexVideo(); //删除*.index文件
}
}, 100, 1000);
break;
case MESSAGE_CONNECT_TO_CAR_FAIL:
connectionProgressDialog.cancel();
Connect_Dialog.createconnectDialog(instance).show();
//wifi_not_connect.createwificonnectDialog(instance).show();
isNotExit = true;
connect_error = true;
break;
case MESSAGE_STOP_RECORD:
Toast toast = Toast.makeText(instance, R.string.complete_record, Toast.LENGTH_SHORT);
//toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
try {
wifiCar.stopRecordTrack();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
recordTogglebutton.setBackgroundResource(R.drawable.record_path);
//recordTogglebutton.setTextColor(Color.WHITE);
playTogglebutton.setClickable(true);
if (recTimer != null) {
recordTimeLength = System.currentTimeMillis()
- startRecordTimeStamp;
// Log.d("wild0","time length:"+recordTimeLength);
SharedPreferences share_time = getSharedPreferences(RECORD_TIME, 0);// 指定操作的文件名称 // 指定操作的文件名称
SharedPreferences.Editor edit_time = share_time.edit(); // 编辑文件
edit_time.putLong("record", recordTimeLength); // 保存long型
edit_time.commit() ;
recTimer.cancel();
recTimer = null;
}
take_flag = 0;
video_record_stop = 0;
take_pictrue_T = 0;
take_video_T = 0;
take_video_T_S =0 ;
/*
* recordTogglebutton.setBackgroundResource(R.drawable.
* record_path );
* recordTogglebutton.setTextColor(Color.WHITE);
* playTogglebutton.setClickable(true);
*
* recordTimeLength = System.currentTimeMillis()-
* startRecordTimeStamp;
*/
break;
case MESSAGE_STOP_PLAY:
disablePlayMode();
isPlayModeEnable = false;
replay_flag = 0;
isplay_pictrue =0;
j = 0;
k = 0;
s = 0;
break;
case MESSAGE_START_RECORD:
take_flag = 1;
pictrue_play = 0;
video_play = 0;
video_play_stop = 0;
/*SharedPreferences share_time_reocrd = getSharedPreferences(FILENSME, 0);// 指定操作的文件名称
SharedPreferences share_v = getSharedPreferences(FILENAME_V, 0);// 指定操作的文件名称
SharedPreferences.Editor edit_time_reocrd = share_time_reocrd.edit(); // 编辑文件
SharedPreferences.Editor edit_v = share_v.edit(); // 编辑文件
edit_time_reocrd.putInt("pictrue_play", pictrue_play); // 保存int型
edit_v.putInt("video_play", video_play); // 保存int型
edit_v.putInt("video_play_stop", video_play_stop); // 保存int型
edit_time_reocrd.commit() ;
edit_v.commit();*/
try {
wifiCar.startRecordTrack();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
recordTogglebutton.setBackgroundResource(R.drawable.record_path_pressed);
recordTogglebutton.setTextColor(Color.BLACK);
playTogglebutton.setClickable(false);
// Log.d("wild0", "start record");
startRecordTimeStamp = System.currentTimeMillis();
recTimer = new Timer(true);
recTimer.schedule(new RecordTask(), 60000);
break;
case MESSAGE_START_PLAY:
isPlayModeEnable = true;
try {
wifiCar.startPlayTrack();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
playTogglebutton.setBackgroundResource(R.drawable.replay_pressed);
//recordTogglebutton.setClickable(false);
/////////////03.16读取保存的时间///////////////////
//SharedPreferences share1 = getSharedPreferences(FILENSME, MODE_PRIVATE);
//recordTimeLength1 = share1.getLong("record", recordTimeLength);
/////////////03.16读取保存的时间///////////////////
//if(replay_flag ==1){
// replay_time = System.currentTimeMillis() - replay_start;
//}
SharedPreferences share_time_play = getSharedPreferences(RECORD_TIME, 0);// 指定操作的文件名称
recordTimeLength1 = share_time_play.getLong("record", recordTimeLength);
replayTimer = new Timer(true);
replayTimer.schedule(new rePlayTask(), recordTimeLength1);
Log.e("aaaa", "replaystar");
break;
case MESSAGE_BATTERY_UNKNOWN:
//ImageView battery0 = (ImageView)instance.findViewById(R.id.battery_image_view);
//battery0.setBackgroundResource(R.drawable.battery_0);
break;
/*case MESSAGE_BATTERY_0:
ImageView battery0 = (ImageView)instance.findViewById(R.id.battery_image_view);
battery0.setVisibility(View.VISIBLE);
batteryBitmap = BitmapFactory.decodeResource(instance.getResources(), R.drawable.battery_0);
battery0.setImageBitmap(batteryBitmap);
break;
case MESSAGE_BATTERY_25:
ImageView battery25 = (ImageView)instance.findViewById(R.id.battery_image_view);
battery25.setVisibility(View.INVISIBLE);
//batteryBitmap = BitmapFactory.decodeResource(instance.getResources(), R.drawable.battery_0);
//battery25.setImageBitmap(batteryBitmap);
break;*/
/*case MESSAGE_BATTERY_50:
ImageView battery50 = (ImageView)instance.findViewById(R.id.battery_image_view);
batteryBitmap = BitmapFactory.decodeResource(instance.getResources(), R.drawable.battery_50);
battery50.setImageBitmap(batteryBitmap);
break;
case MESSAGE_BATTERY_75:
ImageView battery75 = (ImageView)instance.findViewById(R.id.battery_image_view);
batteryBitmap = BitmapFactory.decodeResource(instance.getResources(), R.drawable.battery_75);
battery75.setImageBitmap(batteryBitmap);
break;
case MESSAGE_BATTERY_100:
Log.d("wild1", "battery:100");
ImageView battery100 = (ImageView)instance.findViewById(R.id.battery_image_view);
batteryBitmap = BitmapFactory.decodeResource(instance.getResources(), R.drawable.battery_100);
battery100.setImageBitmap(batteryBitmap);
//battery100.setBackgroundResource(R.drawable.battery_100);
break;*/
case MESSAGE_START_RECORD_AUDIO:
try {
Log.d("wild1", "record audio");
wifiCar.enableRecordAudio(0);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case MESSAGE_STOP_RECORD_AUDIO:
recordAudioTogglebutton.setBackgroundResource(R.drawable.talk);
try {
wifiCar.disableRecordAudio();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(audio_play == 1){//如果当前已经打开了MIC接收声音,关闭对讲的时候再继续打开MIC
play_audio();
setting_play();
wifiCar.disableMoveFlag();
micbutton.setBackgroundResource(R.drawable.mic_pressed);
micbutton.setChecked(true);
}
if(stop_talk != null){
stop_talk.cancel();
stop_talk = null;
}
break;
case MESSAGE_CHECK_TEST:
try {
closeVideoStream();
Toast toast1 = Toast.makeText(instance,
R.string.wificar_activity_toast_stop_recording,Toast.LENGTH_SHORT);
//toast1.setGravity(Gravity.CENTER, 0, 0);
toast1.show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
checkSDcard();
break;
default:
break;
}
super.handleMessage(msg);
}
};
} catch (Exception e) {
e.printStackTrace();
}
}
public class MyThread implements Runnable{
// 线程的主要工作方法 获取设置界面的信息
public void run() {
while (bThreadRun) {
IP = wifiCar.getHost();
Port = String.valueOf(wifiCar.getPort());
version = wifiCar.getVersion(instance);
firmwareVersion = wifiCar.getFilewareVersion();
if(!firmwareVersion.equals("")){
firmwareVersion ="1.0";
}else if(firmwareVersion.equals("")){
firmwareVersion =" ";
}
//Log.e("zhang", "firmwareVersion11 :" +firmwareVersion);
try {
SSID = wifiCar.getSSID();
Log.e("zhang", "获取到了SSID:" + SSID);
bThreadRun = false;
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
/* public class MyPhotoThread implements Runnable{
public void run() {
while (bPhotoThreadRun) {
if (cameraSurfaceView != null) {
try {
// takePictureBtn.setBackgroundResource(R.drawable.camera_pressed);
wifiCar.takePicture(instance);
} catch (Exception e) {
e.printStackTrace();
}
}
bPhotoThreadRun = false;
}
}
} */
//获取屏幕的尺寸
public static double getDisplayMetrics(Context cx) {
String str = "";
DisplayMetrics dm = new DisplayMetrics();
dm = cx.getApplicationContext().getResources().getDisplayMetrics();
int screenWidth = dm.widthPixels;
int screenHeight = dm.heightPixels;
//float density = dm.density;
double bb = Math.sqrt(Math. pow(screenWidth, 2) + Math.pow(screenHeight, 2));
double screeSize = bb / (160 * dm.density);
Log.e("zhang", "ping mu 尺寸:" + screeSize);
return screeSize;
}
public void lockOrientation() {
orientationLock = true;
// 20111125: Lock Landscape
return;
}
public void releaseOrientation() {
orientationLock = false;
// 20111125: Lock Landscape
// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}
public boolean enableGSensorControl() {
isGsensor = false;
LRshow = true;
this.gSensorControlEnable = true;
LR = 0;
accDefaultX = fBaseDefault;
accDefaultY = fBaseDefault;
mSensorManager.registerListener(myAccelerometerListener, aSensor,
SensorManager.SENSOR_DELAY_UI);
mSensorManager.registerListener(myMagneticFieldListener, mfSensor,
SensorManager.SENSOR_DELAY_UI);
/*
* 当开始G-sensor功能时把accDefaultX 和 accDefaultY 是设置为 fBaseDefault ,是为了在重新打开G-sensor的时候判断,设置初始值
* */
accDefaultX = fBaseDefault;
accDefaultY = fBaseDefault;
return false;
}
public boolean isgSensorModeEnable(){
ToggleButton gSensorTogglebutton = (ToggleButton) findViewById(R.id.g_sensor_toggle_button);
return gSensorTogglebutton.isChecked();
}
public void disablegSensorMode(){
ToggleButton gSensorTogglebutton = (ToggleButton) findViewById(R.id.g_sensor_toggle_button);
gSensorTogglebutton.setBackgroundResource(R.drawable.g);
disableGSensorControl();
}
public boolean isSpeaking(){
ToggleButton speakingbutton = (ToggleButton) findViewById(R.id.mic_toggle_button);
return speakingbutton.isChecked();
}
public boolean istaking(){
Button takePictureBtn = (Button) findViewById(R.id.take_picture_button);
return takePictureBtn.isClickable();
}
public void disablegSpeaking(){
Button speakingbutton = (Button) findViewById(R.id.mic_toggle_button);
speakingbutton.setBackgroundResource(R.drawable.mic);
speakingbutton.setClickable(false);
try {
wifiCar.disableAudio();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void disablePlayMode(){
//if(!isNotExit){
Toast toast = Toast.makeText(instance, R.string.complete_play, Toast.LENGTH_SHORT);
//toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
//}
Button playTogglebutton = (Button) findViewById(R.id.play_toggle_button);
final Button takePictureBtn = (Button) findViewById(R.id.take_picture_button);
final ToggleButton videoTogglebutton = (ToggleButton) findViewById(R.id.video_toggle_button);
isPlayModeEnable =false;
/*if(take_pictrue != null){
take_pictrue.cancel();
take_pictrue = null;
}
if(take_video != null){
take_video.cancel();
take_video = null;
}
if(stop_take_video != null){
stop_take_video.cancel();
stop_take_video = null;
}*/
if (playTimer != null) {
playTimer.cancel();
playTimer = null;
}
if(replayTimer != null){
replayTimer.cancel();
replayTimer = null;
}
/* SharedPreferences share_s1 = getSharedPreferences(FILENAME_S, 0);
video_play_stop1 = share_s1.getInt("video_play_stop", video_play_stop);
if(video_play_stop1 ==1){
if(dimension > 5.8){
videoTogglebutton.setBackgroundResource(R.drawable.video);
}else {
videoTogglebutton.setBackgroundResource(R.drawable.video1);
}
//videoTogglebutton.setBackgroundResource(R.drawable.video);
videoTogglebutton.setChecked(false);
//videoRecordEnable = false;
try {
closeVideoStream();
//Toast.makeText(instance,
//R.string.wificar_activity_toast_stop_recording,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
//takePictureBtn.setBackgroundResource(R.drawable.camera);
//takePictureBtn.setEnabled(true);
//takePictureBtn.setPressed(true);
try {
wifiCar.stopPlayTrack();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
playTogglebutton.setBackgroundResource(R.drawable.play_path);
Log.e("aaa", "zdf");
flag = 0;
j = 0;
k = 0;
s = 0;
}
public void checkSDcard(){
SDcardCheck.creatSDcardCheckDialog(instance).show();
if(checkTimer != null){
checkTimer.cancel();
checkTimer = null;
}
}
public boolean disableGSensorControl() {
gSensorControlEnable = false;
handler.removeCallbacks(gMovingTask);
releaseOrientation();
// Log.d("wild0","g disable");
accDefaultX = fBaseDefault;
accDefaultY = fBaseDefault;
try {
wifiCar.move(WifiCar.LEFT_WHEEL, 0);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
wifiCar.move(WifiCar.RIGHT_WHEEL,0);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mSensorManager.unregisterListener(myAccelerometerListener);
//releaseOrientation();
fBasePitch = fBaseDefault;
fBaseRoll = fBaseDefault;
leftSurface.enableControl();
rightSurface.enableControl();
// show();
/*
* 当结束G-sensor功能时把accDefaultX 和 accDefaultY 是设置为 fBaseDefault ,是为了在重新打开G-sensor的时候判断,设置初始值
* */
accDefaultX = fBaseDefault;
accDefaultY = fBaseDefault;
// }
//}
return true;
}
class GMovingTask extends TimerTask {
public GMovingTask() {/*
* if (fMagneticFieldValues != null &&
* fAccelerometerValues != null) { float[] values =
* new float[3]; float[] R = new float[9]; float[]
* outR = new float[9];
*
* SensorManager.getRotationMatrix(R, null,
* fAccelerometerValues, fMagneticFieldValues);
*
* if (bIsPortait == false)
* SensorManager.remapCoordinateSystem(R,
* SensorManager.AXIS_Y, SensorManager.AXIS_Z,
* outR); else outR = R;
*
* SensorManager.getOrientation(outR, values);
*
* values[0] = (float) Math.toDegrees(values[0]);
* values[1] = (float) Math.toDegrees(values[1]);
* values[2] = (float) Math.toDegrees(values[2]);
*
* fBasePitch = (float) Math.floor(values[1]);
* fBaseRoll = (float) Math.floor(values[2]); }
*/
}
public void run() {
// Get value
if (fMagneticFieldValues != null && fAccelerometerValues != null) {
float[] values = new float[3];
float[] R = new float[9];
float[] outR = new float[9];
SensorManager.getRotationMatrix(R, null, fAccelerometerValues,
fMagneticFieldValues);
if (bIsPortait == false)
SensorManager.remapCoordinateSystem(R,
SensorManager.AXIS_Y, SensorManager.AXIS_Z, outR);
else
outR = R;
SensorManager.getOrientation(outR, values);
values[0] = (float) Math.toDegrees(values[0]);
values[1] = (float) Math.toDegrees(values[1]);
values[2] = (float) Math.toDegrees(values[2]);
float fPitch = (float) Math.floor(values[1]);
float fRoll = (float) Math.floor(values[2]);
Log.d("gsensor", "pitch:" + fPitch + ",roll" + fRoll);
Log.d("gsensor", "fBasePitch:" + fBasePitch);
Log.d("gsensor", "fBaseDefault:" + fBaseDefault);
// Check if base value is exist, if not, save current one as
// default value
// Log.d("wild0","bIsPortait:"+bIsPortait);
// Log.d("wild0","fPitch:"+fPitch);
// Log.d("wild0","fBasePitch:"+fBasePitch);
if ((fBasePitch == fBaseDefault) || (fBaseRoll == fBaseDefault)) {
fBasePitch = fPitch;
// fBasePitch = 0;
fBaseRoll = fRoll;
Log.d("gsensor", "reset============================");
} else {
// Calculate the speed
float fVer = fPitch - fBasePitch;
float fHor = fRoll - fBaseRoll;
// Set the initial angle, if the angle is larger than this,
// it starts moving
int iInitialAngle = 15;
// Re-calculate the vertical angle
if (fVer > (iInitialAngle + stickRadiu))
fVer = (iInitialAngle + stickRadiu);
else if (fVer < -(iInitialAngle + stickRadiu))
fVer = -(iInitialAngle + stickRadiu);
if (fVer < iInitialAngle && fVer > -(iInitialAngle))
fVer = 0;
else if (fVer >= iInitialAngle)
fVer -= iInitialAngle;
else if (fVer <= -(iInitialAngle))
fVer += iInitialAngle;
// Re-calculate the horizontal angle
if (fHor > (iInitialAngle + stickRadiu))
fHor = (iInitialAngle + stickRadiu);
else if (fHor < -(iInitialAngle + stickRadiu))
fHor = -(iInitialAngle + stickRadiu);
if (fHor < iInitialAngle && fHor > -(iInitialAngle))
fHor = 0;
else if (fHor >= iInitialAngle)
fHor -= iInitialAngle;
else if (fHor <= -(iInitialAngle))
fHor += iInitialAngle;
Log.d("gsensor", "fVer:" + fVer);
// Android 2.1: Support 2 orientation //
setDirection(fHor, fVer);
// Android 2.3.1: Support 4 orientation //
/*
* if (iRotation == 2 || iRotation == 3) setDirection(-fHor,
* -fVer); else setDirection(fHor, fVer);
*/
}
}
}
}
public int getControllerType() {
return this.controllerType;
}
public CameraSurfaceView getCameraSurfaceView() {
return this.cameraSurfaceView;
}
public void setControllerType(int controllerType) {
this.controllerType = controllerType;
}
public static boolean isVideoRecord() {
return videoRecordEnable;
}
private void setDirection(float x, float y) {
WindowManager mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
Display mDisplay = mWindowManager.getDefaultDisplay();
if(mDisplay.getOrientation()==0){
double radians = 0;
if (y == 0){
radians = x;
Log.e("zhang", "radians y=0 :" + radians);
}
else if (x == 0){
radians = y;
Log.e("zhang", "radians x=0 :" + radians);
}
else{
radians = Math.atan(Math.abs(y) / Math.abs(x));
Log.e("zhang", "radians else :" + radians);
}
double angle = radians * (180 / Math.PI);
Log.e("gsensor", "angle : " + angle);
// Get speed first
int iSpeed = 0;
iSpeed = (int) Math.ceil(Math.pow(Math.pow(x, 2) + Math.pow(y, 2), 0.5)
/ stickRadiu * 10);
Log.e("zhang", "iSpeed :" + iSpeed);
int iSpeedR = 0, iSpeedL = 0;
Log.e("zhang", "x :" + x + "y : " + y );
// Check dimension
if (x == 0 && y != 0) {//前、后
if (y > 0) {//前
iSpeedL = iSpeed;
iSpeedR = iSpeed;
} else {//后
iSpeedL = -iSpeed;
iSpeedR = -iSpeed;
}
} else if (x != 0 && y == 0) {//左、右
if (x > 0) {//右
//iSpeedL = iSpeed;
//iSpeedR = -iSpeed;
iSpeedL = -iSpeed;
iSpeedR = iSpeed;
} else {//左
//iSpeedL = -iSpeed;
//iSpeedR = iSpeed;
iSpeedL = iSpeed;
iSpeedR = -iSpeed;
}
} else if (x > 0 && y > 0) {
// 1st, right forward
iSpeedL = iSpeed;
// Calculate the speed of right wheel
if (angle >= 67.5)
iSpeedR = iSpeedL;
else if (angle < 22.5)
iSpeedR = -iSpeedL;
else
//iSpeedR = 0;
iSpeedR = iSpeed;
iSpeedL = 0;
}
else if (x < 0 && y > 0) {//倾斜的时候 向左
// 2nd, left forward
iSpeedR = iSpeed;
// Calculate the speed of right wheel
if (angle >= 67.5)
iSpeedL = iSpeedR;
else if (angle < 22.5)
iSpeedL = -iSpeedR;
//iSpeedL = iSpeedR;
else
iSpeedL = 0;
iSpeedR = iSpeed;
//iSpeedR = 0;
//iSpeedL = iSpeed;
} else if (x < 0 && y < 0) {
// 3rd, left backward
iSpeedL = -iSpeed;
// Calculate the speed of right wheel
if (angle >= 67.5)
iSpeedR = iSpeedL;
else if (angle < 22.5)
iSpeedR = -iSpeedL;
else {
//iSpeedL = 0;
//iSpeedR = -iSpeed;
iSpeedL = -iSpeed;
iSpeedR = 0;
}
} else {
Log.e("zhang", "else x and y :" + x + " ,"+ y);
// 4th, right backward
iSpeedR = -iSpeed;
//iSpeedL = -iSpeed;//当向后超过垂直的时候左边也应该向后
// Calculate the speed of right wheel
if (angle >= 67.5)
iSpeedL = iSpeedR;
else if (angle < 22.5)
iSpeedL = -iSpeedR;
else {
//iSpeedR = 0;
//iSpeedL = -iSpeed;
iSpeedL = 0;
iSpeedR = -iSpeed;
}
}
if (iSpeedL > 10)
iSpeedL = 10;
if (iSpeedL < -10)
iSpeedL = -10;
if (iSpeedR > 10)
iSpeedR = 10;
if (iSpeedR < -10)
iSpeedR = -10;
// Log.d("wificar", "R: " + iSpeedR + " , L: " + iSpeedL);
// wifiCar.setContinueSpeed(iSpeedR, iSpeedL);
Log.e("zhang", "the speed isSpeedL is :" + iSpeedL );
Log.e("zhang", "the speed isSpeedR is :" + iSpeedR );
if (iSpeedL == 0 && iCarSpeedL != 0)
try {
wifiCar.move(WifiCar.LEFT_WHEEL, iSpeedL);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (iSpeedR == 0 && iCarSpeedR != 0)
try {
wifiCar.move(WifiCar.RIGHT_WHEEL, iSpeedR);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
iCarSpeedL = iSpeedL;
iCarSpeedR = iSpeedR;
Log.e("zhang", "the speed iCarSpeedL is :" + iCarSpeedL );
Log.e("zhang", "the speed iCarSpeedR is :" + iCarSpeedR );
if (iCarSpeedL != 0)
try {
wifiCar.move(WifiCar.LEFT_WHEEL, iCarSpeedL);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (iCarSpeedR != 0)
try {
wifiCar.move(WifiCar.RIGHT_WHEEL, iCarSpeedR);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// SensorEventListener myAccelerometerListener = null;
// SensorEventListener myMagneticFieldListener = null;
final SensorEventListener myAccelerometerListener = new SensorEventListener() {
// @Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
private int[] convertGravity(float dx, float dy, float gx, float gy, float range, int orientation){
int leftVolecity = 0;
int rightVolecity = 0;
float my = gy-dy;
float mx = gx-dx;
LR ++;
Log.e("zhang", "my :" + my + "," + "mx :" + mx);
if(orientation==1){
if(Math.abs(my)>range && my<-range ){ // 左转
//leftVolecity = (int) Math.ceil(my)*(-1);;
//rightVolecity = (int) Math.ceil(my)*(1);
leftVolecity = (int) Math.ceil(my)*(1);;
rightVolecity = (int) Math.ceil(my)*(-1);
Log.e("acce", "left:"+leftVolecity+","+rightVolecity);
}
else if(Math.abs(my)>range && my>range ){ //右转
//leftVolecity = (int) Math.ceil(my)*(-1);
//rightVolecity = (int) Math.ceil(my)*(1);
leftVolecity = (int) Math.ceil(my)*(1);
rightVolecity = (int) Math.ceil(my)*(-1);
Log.e("acce", "right:"+leftVolecity+","+rightVolecity);
}
else{
}
}
else{
if(Math.abs(my)>range && my<-range ){ //右转
leftVolecity = (int) Math.ceil(my)*(-1);
rightVolecity = (int) Math.ceil(my)*(1);
Log.e("acce11", "right:"+leftVolecity+","+rightVolecity);
}
else if(Math.abs(my)>range && my>range ){ // 左转
//leftVolecity = (int) Math.ceil(my)*(1);
//rightVolecity = (int) Math.ceil(my)*(-1);
leftVolecity = (int) Math.ceil(my)*(-1);
rightVolecity = (int) Math.ceil(my)*(1);
Log.e("acce11", "left:"+leftVolecity+","+rightVolecity);
}
else{
}
}
if(mx<-range){ //前进
//leftVolecity = gx;
leftVolecity = leftVolecity-(int) Math.ceil(mx);
rightVolecity = rightVolecity-(int) Math.ceil(mx);
GsensorCountF ++;
if(GsensorCountF < 40 && gSensorControlEnable){
Log.e("zhang", "Gsensor :" + GsensorCountF);
setDirectionGsensor(leftVolecity, rightVolecity);
Log.e("zhang Forware", " leftVolecity :" + leftVolecity + "," + "rightVolecity :"+ rightVolecity);
}
}
else if(mx>range ){ //后退
leftVolecity = leftVolecity-((int) Math.ceil(mx));
rightVolecity = rightVolecity-((int) Math.ceil(mx));
GsensorCountB ++;
if(GsensorCountB < 40 && gSensorControlEnable){
setDirectionGsensor(leftVolecity, rightVolecity);
Log.e("zhang Back", " leftVolecity :" + leftVolecity + "," + "rightVolecity :"+ rightVolecity);
}
}
if(leftVolecity >= 2){
leftVolecity = 10;
}
if(leftVolecity <= -2){
leftVolecity = -10;
}
if(rightVolecity >= 2){
rightVolecity = 10;
}
if(rightVolecity <= -2){
rightVolecity = -10;
}
Log.e("zhang", " leftVolecity :" + leftVolecity + "," + "rightVolecity :"+ rightVolecity);
return new int[]{leftVolecity, rightVolecity};
}
// @Override
public void onSensorChanged(SensorEvent event) {
fAccelerometerValues = event.values;
if(accDefaultX == fBaseDefault){
accDefaultX = fAccelerometerValues[0];
}
if(accDefaultY == fBaseDefault){
accDefaultY = fAccelerometerValues[1];
}
WindowManager mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
Display mDisplay = mWindowManager.getDefaultDisplay();
Log.e("acce", "getOrientation(): " + mDisplay.getOrientation());
Log.e("acce", "x:"+fAccelerometerValues[0]+",y:"+fAccelerometerValues[1]+",z:"+fAccelerometerValues[2]);
Log.e("acce", "dx:"+accDefaultX+",dy:"+accDefaultY);
int[] iCar = new int[2];
//判断在启动G-sensor的时候角度的情况 是否接近垂直 ,若是则显示图片提示
/*
* 向前接近了垂直
* */
if( mDisplay.getOrientation()==1){
if((fAccelerometerValues[0]< 0.1f && fAccelerometerValues[2] < 9.8f && !isGsensor)
|| (fAccelerometerValues[0]> 7.6f && fAccelerometerValues[2] < 5.8f && !isGsensor )){ //|| ( fAccelerometerValues[1] < -5.5 && fAccelerometerValues[1] < 7.9 && !isGsensor )
//Log.e("zhang", "想前快垂直了");
disGsensor = true;
showDialog();
gSensorControlEnable = false;
mSensorManager.unregisterListener(myAccelerometerListener);
}else {
handler.postDelayed(gMovingTask, 100);
isGsensor = true;
//Log.e("zhangLLLLLLRRRRRRRR", LR + "");
if(LR < 1){
if (leftSurface != null && rightSurface != null && gSensorControlEnable) {
leftSurface.disableControl();
rightSurface.disableControl();
}
}
if( mDisplay.getOrientation()==1){
iCar = convertGravity(accDefaultX, accDefaultY, fAccelerometerValues[0], fAccelerometerValues[1], 1.5f, mDisplay.getOrientation());
iCarSpeedL = iCar[0];
iCarSpeedR = iCar[1];
}
else{
iCar = convertGravity(accDefaultY, accDefaultX, fAccelerometerValues[1], fAccelerometerValues[0], 1.5f, mDisplay.getOrientation());
iCarSpeedL = iCar[0];
iCarSpeedR = iCar[1];
}
Log.e("acce", "cl:"+iCar[0]+",cr:"+iCar[1]);
if(iCarSpeedL != iCarSpeedR){ //向左 、向右
try {
wifiCar.enableMoveFlag();
wifiCar.move(WifiCar.LEFT_WHEEL, iCar[0]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
wifiCar.enableMoveFlag();
wifiCar.move(WifiCar.RIGHT_WHEEL, iCar[1]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(GsensorCountB > 40 || GsensorCountF > 40){
gSensorControlEnable = false;
Log.e("zhang", "zhang zhang zhang:" + GsensorCountF);
if(iCarSpeedL == iCarSpeedR){ //向前 、向后
try {
wifiCar.enableMoveFlag();
wifiCar.move(WifiCar.LEFT_WHEEL, iCar[0]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
wifiCar.enableMoveFlag();
wifiCar.move(WifiCar.RIGHT_WHEEL, iCar[1]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
if(iCarSpeedL == 0 && iCarSpeedR == 0 ){ //停止
GsensorCountB = 0;
GsensorCountF = 0;
//gSensorControlEnable = true;
try {
wifiCar.disableMoveFlag();
wifiCar.move(WifiCar.LEFT_WHEEL, iCarSpeedL);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
wifiCar.disableMoveFlag();
wifiCar.move(WifiCar.RIGHT_WHEEL, iCarSpeedR);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}else if( mDisplay.getOrientation()==0){
if((fAccelerometerValues[1] < 0 && fAccelerometerValues[2] < 9.7 && !isGsensor)
|| (fAccelerometerValues[1]> 7.8f && fAccelerometerValues[2] < 5.5f && !isGsensor )){ //|| ( fAccelerometerValues[1] < -5.5 && fAccelerometerValues[1] < 7.9 && !isGsensor )
Log.e("zhang", "想前快垂直了");
showDialog();
gSensorControlEnable = false;
mSensorManager.unregisterListener(myAccelerometerListener);
}else{
handler.postDelayed(gMovingTask, 100);
isGsensor = true;
Log.e("zhangLLLLLLRRRRRRRR", LR + "");
if(LR < 1){
if (leftSurface != null && rightSurface != null && gSensorControlEnable) {
leftSurface.disableControl();
rightSurface.disableControl();
}
}
if( mDisplay.getOrientation()==1){
iCar = convertGravity(accDefaultX, accDefaultY, fAccelerometerValues[0], fAccelerometerValues[1], 1.5f, mDisplay.getOrientation());
iCarSpeedL = iCar[0];
iCarSpeedR = iCar[1];
}
else{
iCar = convertGravity(accDefaultY, accDefaultX, fAccelerometerValues[1], fAccelerometerValues[0], 1.5f, mDisplay.getOrientation());
iCarSpeedL = iCar[0];
iCarSpeedR = iCar[1];
}
Log.e("acce", "cl:"+iCar[0]+",cr:"+iCar[1]);
if(iCarSpeedL != iCarSpeedR){ //向左 、向右
try {
wifiCar.enableMoveFlag();
wifiCar.move(WifiCar.LEFT_WHEEL, iCar[0]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
wifiCar.enableMoveFlag();
wifiCar.move(WifiCar.RIGHT_WHEEL, iCar[1]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(GsensorCountB > 40 || GsensorCountF > 40){
gSensorControlEnable = false;
Log.e("zhang", "zhang zhang zhang:" + GsensorCountF);
if(iCarSpeedL == iCarSpeedR){ //向前 、向后
try {
wifiCar.enableMoveFlag();
wifiCar.move(WifiCar.LEFT_WHEEL, iCar[0]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
wifiCar.enableMoveFlag();
wifiCar.move(WifiCar.RIGHT_WHEEL, iCar[1]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
if(iCarSpeedL == 0 && iCarSpeedR == 0){ //停止
GsensorCountB = 0;
GsensorCountF = 0;
//gSensorControlEnable = true;
try {
wifiCar.disableMoveFlag();
wifiCar.move(WifiCar.LEFT_WHEEL,iCarSpeedL);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
wifiCar.disableMoveFlag();
wifiCar.move(WifiCar.RIGHT_WHEEL, iCarSpeedR);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
};
final SensorEventListener myMagneticFieldListener = new SensorEventListener() {
// @Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
// @Override
public void onSensorChanged(SensorEvent event) {
fMagneticFieldValues = event.values;
}
};
@Override
public void onConfigurationChanged(Configuration newConfig) {
// Log.d("wificar","onConfigurationChanged:"+orientationLock);
try {
if (orientationLock) {
// return ;
} else if (!this.gSensorControlEnable) {
// Log.d("wificar","onConfigurationChanged:enable");
cameraSurfaceView.destroyDrawingCache();
// surface.destroyDrawingCache();
// 20111126: Lock landscape
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
} catch (Exception e) {
e.printStackTrace();
}
super.onConfigurationChanged(newConfig);
}
private void changeLandscape() {
// Log.d("wificar", "ORIENTATION_LANDSCAPE");
controllerType = WificarUtility.getIntVariable(instance,
WificarUtility.CONTROLLER_TYPE, 1);
// this.controllerType = WificarActivity.SINGLE_CONTROLLER;
Log.d("wild0", "controllerType:" + controllerType);
dimension = getDisplayMetrics(instance);
Log.e("zhangzhang", "屏幕的尺寸:" + dimension);
if(dimension > 5.8){
setContentView(R.layout.double_axis_landscape_large);
}else{
setContentView(R.layout.double_axis_landscape);
}
//Log.d("wild0", "double axis");
leftSurface = (DoubleAxisLeftControllerSurfaceView) findViewById(R.id.stick_double_axis_left_controller_surfaceview);
rightSurface = (DoubleAxisRightControllerSurfaceView) findViewById(R.id.stick_double_axis_right_controller_surfaceview);
leftSurface.setWifiCar(wifiCar);
rightSurface.setWifiCar(wifiCar);
rightSurface.setZOrderOnTop(true);
leftSurface.setZOrderOnTop(true);
cameraSurfaceView = (CameraSurfaceView) findViewById(R.id.car_camera_surfaceview);
wifiCar.setSurfaceView(cameraSurfaceView);
cameraSurfaceView.setZOrderOnTop(false);
refreshUIListener();
bIsPortait = false;
}
private void refreshUIListener() {
Button zoomInBtn = (Button) this.findViewById(R.id.zoom_in_button);
zoomInBtn.setOnClickListener(new View.OnClickListener() {
// @Override
public void onClick(View v) {
if(succeedConnect){
try {
cameraSurfaceView.zoomIn();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int value = (int) cameraSurfaceView.getTargetZoomValue();
TextView valueText = (TextView) findViewById(R.id.screen_ratio_textview);
valueText.setText(String.valueOf(value) + "%");
}
}
});
Button zoomOutBtn = (Button) this.findViewById(R.id.zoom_out_button);
zoomOutBtn.setOnClickListener(new View.OnClickListener() {
// @Override
public void onClick(View v) {
if(succeedConnect){
try {
cameraSurfaceView.zoomOut();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int value = (int) cameraSurfaceView.getTargetZoomValue();
TextView valueText = (TextView) findViewById(R.id.screen_ratio_textview);
valueText.setText(String.valueOf(value) + "%");
}
}
});
// ╃化ㄏノ
/*final Button takePictureBtn = (Button) this.findViewById(R.id.take_picture_button);
takePictureBtn.setOnClickListener(new View.OnClickListener() {
// @Override
public void onClick(View v) {
if(takePictureBtn.isClickable()){
sendMessage(MESSAGE_TAKE_PHOTO);
//bPhotoThreadRun = true;
//handler.postDelayed(TakePhotoTask, 10);
}
}
});*/
final Button takePictureBtn = (Button) this.findViewById(R.id.take_picture_button);
takePictureBtn.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(succeedConnect){
if(event.getAction() == MotionEvent.ACTION_DOWN){
if(dimension > 5.8){
takePictureBtn.setBackgroundResource(R.drawable.camera_pressed);
}else {
takePictureBtn.setBackgroundResource(R.drawable.camera_pressed1);
}
//bPhotoThreadRun = true;
//handler.postDelayed(TakePhotoTask, 10);
/*if(nSDFreeSize < 50 ){
checkSDcard();
}else{*/
if(No_Sdcard){
Toast toast = Toast.makeText(instance,
R.string.record_fail_warning,Toast.LENGTH_SHORT);
toast.show();
}else{
sendMessage(MESSAGE_TAKE_PHOTO);
}
}
else if(event.getAction() == MotionEvent.ACTION_UP){
if(dimension > 5.8){
takePictureBtn.setBackgroundResource(R.drawable.camera);
}else {
takePictureBtn.setBackgroundResource(R.drawable.camera1);
}
//takePictureBtn.setBackgroundResource(R.drawable.camera);
}
}
return false;
}
});
////////////////////////////////led///////////////////////////
final ToggleButton ledTogglebutton = (ToggleButton) findViewById(R.id.led_toggle_button);
ledTogglebutton.setOnClickListener(new View.OnClickListener() {
//@Override
public void onClick(View v) {
// Perform action on clicks
if(succeedConnect){
if (ledTogglebutton.isChecked()) {
try {
//wifiCar.move(WifiCar.LED_ON,0);
wifiCar.led_onTrack();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ledTogglebutton.setBackgroundResource(R.drawable.led_on);
} else {
int mode = Context.MODE_PRIVATE;
SharedPreferences carSharedPreferences = instance
.getSharedPreferences("WIFICAR_PREFS", mode);
try {
//wifiCar.move(WifiCar.LED_OFF,0);
wifiCar.led_offTrack();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ledTogglebutton.setBackgroundResource(R.drawable.led);
}
}
}
});
//////////////////////////////////led///////////////////////////////////
final ImageView soundImg= (ImageView) findViewById(R.id.no_sound);
final ToggleButton micToggleButton = (ToggleButton) this.findViewById(R.id.mic_toggle_button);
{
/*
* initial
*/
int enableMic = WificarUtility.getIntVariable(instance,
WificarUtility.WIFICAR_MIC, 0);
if (enableMic == 1) {
// boolean result = wifiCar.AudioEnable();
boolean result = wifiCar.playAudio();
if (result) {
micToggleButton.setBackgroundResource(R.drawable.mic_pressed);
micToggleButton.setChecked(true);
}
} else {
// boolean result = wifiCar.AudioDisable();
boolean result = false;
try {
result = wifiCar.disableAudio();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (result) {
micToggleButton.setBackgroundResource(R.drawable.mic);
micToggleButton.setChecked(false);
}
}
}
micToggleButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
if(succeedConnect){
if (micToggleButton.isChecked()) {
// boolean result = wifiCar.AudioEnable();
boolean result = wifiCar.playAudio();
if (result) {
/*
* int mode = Activity.MODE_PRIVATE; SharedPreferences
* carSharedPreferences = instance
* .getSharedPreferences("WIFICAR_PREFS", mode);
* SharedPreferences.Editor carEditor =
* carSharedPreferences .edit();
* carEditor.putBoolean(WifiCar.PREF_MIC, true);
* carEditor.commit();
*/
checkSound = new Timer(true);
checkSound.schedule(new SoundCheck(), 100, 300);
setting = 0;
audio_play = 1;
if(isZero == 1){
AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 2 , 0); //tempVolume:音量绝对值
}
WificarUtility.getIntVariable(instance,WificarUtility.WIFICAR_MIC, 1);
micToggleButton.setBackgroundResource(R.drawable.mic_pressed);
}
} else {
// boolean result = wifiCar.AudioDisable();
boolean result = false;
try {
result = wifiCar.disableAudio();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (result) {
/*
* int mode = Activity.MODE_PRIVATE; SharedPreferences
* carSharedPreferences = instance
* .getSharedPreferences("WIFICAR_PREFS", mode);
* SharedPreferences.Editor carEditor =
* carSharedPreferences .edit();
* carEditor.putBoolean(WifiCar.PREF_MIC, false);
* carEditor.commit();
*/
if(checkSound != null){
checkSound.cancel();
checkSound = null;
}
soundImg.setVisibility(View.VISIBLE);
audio_play = 0;
WificarUtility.getIntVariable(instance,
WificarUtility.WIFICAR_MIC, 1);
micToggleButton.setBackgroundResource(R.drawable.mic);
/*Toast.makeText(instance,
MessageUtility.MESSAGE_DISABLE_GSENSOR,
Toast.LENGTH_SHORT);*/
}
// Toast.makeText(HelloFormStuff.this, "Not checked",
// Toast.LENGTH_SHORT).show();
}
}
}
});
final ToggleButton lightTogglebutton = (ToggleButton) findViewById(R.id.light_toggle_button);
{
/*
* initial
*/
/*
* int mode = Activity.MODE_PRIVATE; SharedPreferences
* carSharedPreferences = getSharedPreferences(
* WifiCar.WIFICAR_PREFS, mode); boolean ir = carSharedPreferences
* .getBoolean(WifiCar.PREF_IR, false);
*/
int enableIr = WificarUtility.getIntVariable(instance,
WificarUtility.WIFICAR_IR, 0);
if (enableIr == 1) {
try {
wifiCar.enableIR();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lightTogglebutton.setBackgroundResource(R.drawable.ir_pressed);
lightTogglebutton.setChecked(true);
} else {
try {
wifiCar.disableIR();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lightTogglebutton.setBackgroundResource(R.drawable.ir);
lightTogglebutton.setChecked(false);
}
}
lightTogglebutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
if(succeedConnect){
if (lightTogglebutton.isChecked()) {
WificarUtility.getIntVariable(instance,
WificarUtility.WIFICAR_IR, 1);
try {
wifiCar.led_offTrack();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
ledTogglebutton.setBackgroundResource(R.drawable.led);
ledTogglebutton.setClickable(false);
ledTogglebutton.setChecked(false);
try {
wifiCar.enableIR();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lightTogglebutton.setBackgroundResource(R.drawable.ir_pressed);
// Toast.makeText(HelloFormStuff.this, "Checked",
// Toast.LENGTH_SHORT).show();
} else {
WificarUtility.getIntVariable(instance,
WificarUtility.WIFICAR_IR, 0);
ledTogglebutton.setBackgroundResource(R.drawable.led);
ledTogglebutton.setClickable(true);
ledTogglebutton.setChecked(false);
try {
wifiCar.disableIR();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lightTogglebutton.setBackgroundResource(R.drawable.ir);
// Toast.makeText(HelloFormStuff.this, "Not checked",
// Toast.LENGTH_SHORT).show();
}
}
}
});
final ToggleButton gSensorTogglebutton = (ToggleButton) findViewById(R.id.g_sensor_toggle_button);
gSensorTogglebutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
// Log.d("wild0", "gsensor on");
if(succeedConnect){
if (gSensorTogglebutton.isChecked()) {
// enableGSensorControl();
if(isPlayModeEnable){
disablePlayMode();
}
//hide();
gSensorTogglebutton.setBackgroundResource(R.drawable.g_pressed);
enableGSensorControl();
} else {
gSensorTogglebutton.setBackgroundResource(R.drawable.g);
disableGSensorControl();
}
}
}
});
final Button playTogglebutton = (Button) findViewById(R.id.play_toggle_button);
final ToggleButton recordTogglebutton = (ToggleButton) findViewById(R.id.record_toggle_button);
//final ToggleButton replayTogglebutton = (ToggleButton) findViewById(R.id.replay_toggle_button);
recordTogglebutton.setOnClickListener(new View.OnClickListener() {
// @Override
public void onClick(View v) {
if(succeedConnect){
if (recordTogglebutton.isChecked()) {
if(isPlayModeEnable){
disablePlayMode();
}
if(isLowPower){ //当手机出现电量低的提示的时候,禁止录制
Disrecord_play_dialog.createdisaenableDialog(instance).show();
recordTogglebutton.setChecked(false);
}else{
Message messageStopRecord = new Message();
messageStopRecord.what = WificarActivity.MESSAGE_START_RECORD;
WificarActivity.getInstance().getHandler().sendMessage(messageStopRecord);
}
} else {
Message messageStopRecord = new Message();
messageStopRecord.what = WificarActivity.MESSAGE_STOP_RECORD;
WificarActivity.getInstance().getHandler()
.sendMessage(messageStopRecord);
}
}
}
});
//final Button playTogglebutton = (Button) findViewById(R.id.play_toggle_button);
final GestureDetector detector = new GestureDetector(new OnGestureListener() {
public boolean onSingleTapUp(MotionEvent e) {
//Log.e("aaa", "s");
return false;
}
public void onShowPress(MotionEvent e) {
}
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
return false;
}
public void onLongPress(MotionEvent e) {
}
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
return false;
}
public boolean onDown(MotionEvent e) {
return false;
}
});
detector.setOnDoubleTapListener(new OnDoubleTapListener() {
public boolean onSingleTapConfirmed(MotionEvent e) {
if(isLowPower){ //当手机电量低的时候,禁止播放
Disrecord_play_dialog.createdisaenableDialog(instance).show();
}else{
if(succeedConnect){
if(flag == 0){
//单击单次播放
isPlayModeEnable = true;
//wifiCar.moveCommand(WifiCar.GO_DIRECTION.TrackPlay, 1);
try {
wifiCar.startPlayTrack();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
playTogglebutton.setBackgroundResource(R.drawable.play_path_pressed);
//recordTogglebutton.setClickable(false);
//replayTogglebutton.setClickable(false);
SharedPreferences share_time_play_s = getSharedPreferences(RECORD_TIME, 0);
recordTimeLength1 = share_time_play_s.getLong("record", recordTimeLength);
Log.e("aaa","recordTimeLength: "+ recordTimeLength1);
playTimer = new Timer(true);
playTimer.schedule(new PlayTask(), recordTimeLength1);
if(isgSensorModeEnable()){
disablegSensorMode();
}
Log.e("aaa", "s");
flag =1;
}
else if(flag !=0){
//结束播放,返回初始状态
//wifiCar.moveCommand(WifiCar.GO_DIRECTION.TrackPlay, 0);
try {
wifiCar.stopPlayTrack();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Message messageStopPlay = new Message();
messageStopPlay.what = WificarActivity.MESSAGE_STOP_PLAY;
WificarActivity.getInstance().getHandler()
.sendMessage(messageStopPlay);
Log.e("aaa", "sf");
flag = 0;
//Toast.makeText(instance, R.string.complete_play, Toast.LENGTH_SHORT).show();
}
else if(flag == 2){
//wifiCar.moveCommand(WifiCar.GO_DIRECTION.TrackPlay, 0);
Message messageStopPlay = new Message();
messageStopPlay.what = WificarActivity.MESSAGE_STOP_PLAY;
WificarActivity.getInstance().getHandler()
.sendMessage(messageStopPlay);
Log.e("aaa", "df");
flag = 0;
//Toast.makeText(instance, R.string.complete_play, Toast.LENGTH_SHORT).show();
}
}
}//结束电量检测
//Log.e("aaa", "s");
return false;
}
public boolean onDoubleTapEvent(MotionEvent e) {
return false;
}
public boolean onDoubleTap(MotionEvent e) {
if(isLowPower){ //当手机电量低的时候,禁止播放
Disrecord_play_dialog.createdisaenableDialog(instance).show();
}else{
if(isgSensorModeEnable()){
disablegSensorMode();
}
if(succeedConnect){
if(flag != 2 && flag != 1){
//isPlayModeEnable = true;
Message messageStartRePlay = new Message();
messageStartRePlay.what = WificarActivity.MESSAGE_START_PLAY;
WificarActivity.getInstance().getHandler()
.sendMessage(messageStartRePlay);
Log.e("aaa", "d");
flag = 2;
}
}
}//结束电量检测
return false;
}
});
// Button button = (Button) findViewById(R.id.button);
playTogglebutton.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
return detector.onTouchEvent(event);
}
});
final Button recordAudioTogglebutton = (Button) findViewById(R.id.talk_button);
recordAudioTogglebutton.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(succeedConnect){
if(event.getAction() == MotionEvent.ACTION_DOWN){
//if(succeedConnect){
soundImg.setVisibility(0);
recordAudioTogglebutton.setBackgroundResource(R.drawable.talk_pressed);
instance.sendMessage(MESSAGE_START_RECORD_AUDIO);
isTalk = 1;
if(audio_play == 1){ // audio =1 则为声音已经打开
disablegSpeaking();
micToggleButton.setBackgroundResource(R.drawable.mic);
micToggleButton.setChecked(false);
}
//}
}
else if(event.getAction() == MotionEvent.ACTION_UP){
//recordAudioTogglebutton.setBackgroundResource(R.drawable.talk);
//if(succeedConnect){
isTalk = 0;
stop_talk = new Timer(true);
stop_talk.schedule(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
instance.sendMessage(MESSAGE_STOP_RECORD_AUDIO);
}
}, 600);
if(audio_play == 1){ // audio =1 则为声音已经打开
soundImg.setVisibility(8);
}
}
//}
}
return false;
}
});
///////////////////////////
//在控制时按分享按钮弹出的对话框
final Button share_pressed = (Button) findViewById(R.id.share_toggle_button);
share_pressed.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(succeedConnect){
//Control_share_dialog.createcontrolsharedialog(instance).show();
AlertDialog.Builder builder = new AlertDialog.Builder(WificarActivity.this);
builder.setMessage("The Facebook, Twitter, Tumblr, and YouTube apps must already be installed on your device to share CAR 2.0 photos and videos.\n" +
"Exit the app, go to Settings and access a Wi-Fi network other than CAR 2.0. Open the CAR 2.0 app and select Share.").setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
} ).create().show();
}
}
});
//////////////////////////
////////////////////////////////camera up and down////////////////////////////////////
//camerasettingSurface = (CamerSettingSurfaceView) findViewById(R.id.camera_setting_surfaceview);
final ToggleButton buttoncameraupon = (ToggleButton) findViewById(R.id.camup_button);
final RelativeLayout camerRelativelayout = (RelativeLayout) findViewById(R.id.linearlayoutleftcamera);
final Button cameraStick = (Button) findViewById(R.id.camera_stick);
buttoncameraupon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(succeedConnect){
if(buttoncameraupon.isChecked()){
buttoncameraupon.setBackgroundResource(R.drawable.up_on);
camerRelativelayout.setVisibility(0);
cameraStick.setVisibility(0);
camerRelativelayout.setBackgroundResource(R.drawable.back);
cameraStick.setBackgroundResource(R.drawable.stick_back);
}
else {
buttoncameraupon.setBackgroundResource(R.drawable.up);
camerRelativelayout.setVisibility(4);
}
}
}
});
if(dimension > 5.8){
cameraStick.setOnTouchListener(new View.OnTouchListener() {
int lastX, lastY;
public boolean onTouch(View v, MotionEvent event) {
//TODO Auto-generated method stub
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
controlEnable = true;
lastX = (int) event.getRawX();
lastY = (int) event.getRawY();
int dx1 = (int) event.getRawX() - lastX;
int dy1 = (int) event.getRawY() - lastY;
int left1 = v.getLeft() + dx1;
int top1 = v.getTop() + dy1;
int right1 = v.getRight() + dx1;
int bottom1 = v.getBottom() + dy1;
v.layout(left1, top1, right1, bottom1);
Log.e("camera---", left1 + "," + top1 + "," + right1 + "," + bottom1);
Log.e(TAG, "dx1:"+dx1+","+"dy1:"+dy1);
break;
// case MotionEvent.ACTION_MOVE:
//
// int dx = (int) event.getRawX() - lastX;
// int dy = (int) event.getRawY() - lastY;
//
// int left = v.getLeft() + dx;
// int top = v.getTop() + dy;
// int right = v.getRight() + dx;
// int bottom = v.getBottom() + dy;
//
// Log.e("camera---", left + "," + top + "," + right + "," + bottom);
// Log.e(TAG, "dx:"+dx+","+"dy:"+dy);
//
// if (left < 1) {
// left = 1;
// right = left + v.getWidth();
// }
//
//
//
// if (top < 0) {
// top = 0;
// bottom = top + v.getHeight();
// }
//
// if(with > 850){
// if (right > 28) {
// right = 28;
// left = 1;
// }
// if (bottom > 117) {
// bottom = 117;
// top = 89;
// }
//
// //right forware
// if(bottom < 65){//摄像头向上
// b = 0;
// f ++;
// Log.e("zhangdddd__11111 > 850", " the f is ---: " + f);
// if( f == 1){
// cameramove = 1;
// try {
// wifiCar.enableMoveFlag();
// wifiCar.cameraup();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
//
// }
//
// // right back
// if(bottom > 85 ){//向下
// f = 0;
// b ++;
// Log.e("zhangdddd__11111 > 850", " the b is ---: " + b);
// if(b == 1){
// cameramove = 2;
// try {
// wifiCar.enableMoveFlag();
// wifiCar.cameradown();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
//
// }
// }else{
// if (right > 22) {
// right = 22;
// left = 1;
// }
// if (bottom > 90) {
// bottom = 90;
// top = 69;
// }
//
// //right forware
// if(bottom < 45){
// b = 0;
// f ++;
// Log.e("zhangdddd__11111", " the f is ---: " + f);
// if( f == 1){
// cameramove = 1;
// try {
// wifiCar.enableMoveFlag();
// wifiCar.cameraup();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
//
// }
//
// // right back
// if(bottom > 65 ){
// f = 0;
// b ++;
// Log.e("zhangdddd__11111", " the b is--- : " + b);
// if(b == 1){
// cameramove = 2;
// try {
// wifiCar.enableMoveFlag();
// wifiCar.cameradown();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
//
// }
// }
//
// v.layout(1, top, right, bottom);
//
// lastX = (int) event.getRawX();
// lastY = (int) event.getRawY();
//
// break;
// case MotionEvent.ACTION_UP:
// f = 0;
// b = 0;
// cameramove = 0;
// try {
// wifiCar.disableMoveFlag();
// wifiCar.camerastop();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// if(with > 850){
// v.layout(1, 47, 28, 75);
// }else{
// v.layout(1, 34, 22, 55);
// }
//
// break;
////------------------------------------------------------------------------------
case MotionEvent.ACTION_MOVE:
int dx = (int) event.getRawX() - lastX;
int dy = (int) event.getRawY() - lastY;
int left = v.getLeft() + dx;
int top = v.getTop() + dy;
int right = v.getRight() + dx;
int bottom = v.getBottom() + dy;
Log.e("camera---", left + "," + top + "," + right + "," + bottom);
if (left < dip2px(getInstance(), 1)) {
left = dip2px(getInstance(), 1);
right = left + v.getWidth();
}
if (top < 0) {
top = 0;
bottom = top + v.getHeight();
}
if(with > 850){
if (right > dip2px(getInstance(), 30)) {
right = dip2px(getInstance(), 30);
left = dip2px(getInstance(), 1);
}
if (bottom > dip2px(getInstance(), 118)) {
bottom = dip2px(getInstance(), 118);
top = dip2px(getInstance(), 90);
}
//right forware
if(bottom < dip2px(getInstance(), 55)){
b = 0;
f ++;
Log.e("zhangdddd__11111 > 850", " the f is ---: " + f);
if( f == 1){
cameramove = 1;
try {
wifiCar.enableMoveFlag();
wifiCar.cameraup();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// right back
if(bottom > dip2px(getInstance(), 83) ){
f = 0;
b ++;
Log.e("zhangdddd__11111 > 850", " the b is ---: " + b);
if(b == 1){
cameramove = 2;
try {
wifiCar.enableMoveFlag();
wifiCar.cameradown();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}else{
if (right > dip2px(getInstance(), 30)) {
right = dip2px(getInstance(), 30);
left = dip2px(getInstance(), 1);
}
if (bottom > dip2px(getInstance(), 60)) {
bottom = dip2px(getInstance(), 60);
top = dip2px(getInstance(), 70);
}
//right forware
if(bottom < dip2px(getInstance(), 40)){
b = 0;
f ++;
Log.e("zhangdddd__11111", " the f is ---: " + f);
if( f == 1){
cameramove = 1;
try {
wifiCar.enableMoveFlag();
wifiCar.cameraup();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// right back
if(bottom > dip2px(getInstance(), 40) ){
f = 0;
b ++;
Log.e("zhangdddd__11111", " the b is--- : " + b);
if(b == 1){
cameramove = 2;
try {
wifiCar.enableMoveFlag();
wifiCar.cameradown();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
v.layout(1, top, right, bottom);
lastX = (int) event.getRawX();
lastY = (int) event.getRawY();
break;
case MotionEvent.ACTION_UP:
f = 0;
b = 0;
cameramove = 0;
try {
wifiCar.disableMoveFlag();
wifiCar.camerastop();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(with > 850){
v.layout(dip2px(getInstance(), 0), dip2px(getInstance(), 55), dip2px(getInstance(), 30), dip2px(getInstance(), 83));
}else{
v.layout(1, 34, 22, 55);
}
break;
}
return false;
}
});
}else{
cameraStick.setOnTouchListener(new View.OnTouchListener() {
int lastX, lastY;
public boolean onTouch(View v, MotionEvent event) {
//TODO Auto-generated method stub
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//controlEnable = true;
lastX = (int) event.getRawX();
lastY = (int) event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
int dx = (int) event.getRawX() - lastX;
int dy = (int) event.getRawY() - lastY;
int left = v.getLeft() + dx;
int top = v.getTop() + dy;
int right = v.getRight() + dx;
int bottom = v.getBottom() + dy;
Log.e("camera", left + "," + top + "," + right + "," + bottom);
if (left < 1) {
left = 1;
right = left + v.getWidth();
}
if (top < 0) {
top = 0;
bottom = top + v.getHeight();
}
if(with <= 480 ){
if (right > 29) {
right = 29;
left = 1;
}
if (bottom > 119) {
bottom = 119;
top = 91;
}
//right forware
if(bottom < 67){
b = 0;
f ++;
Log.e("zhangdddd__11111", " the f is : " + f);
if( f == 1){
try {
wifiCar.enableMoveFlag();
wifiCar.cameraup();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// right back
if(bottom > 87 ){
f = 0;
b ++;
Log.e("zhangdddd__11111", " the b is : " + b);
if(b == 1){
try {
wifiCar.enableMoveFlag();
wifiCar.cameradown();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}else{
if(with > 1100){
if (right > dip2px(getInstance(), 29)) {
right = dip2px(getInstance(), 29);
left =dip2px(getInstance(), 1);
}
if (bottom > dip2px(getInstance(), 117)) {
bottom = dip2px(getInstance(), 117);
top = dip2px(getInstance(), 90);
}
//right forware
if(bottom < dip2px(getInstance(), 45)){
b = 0;
f ++;
Log.e("zhangdddd__11111", " the f is : " + f);
if( f == 1){
try {
wifiCar.enableMoveFlag();
wifiCar.cameraup();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// right back
if(bottom > dip2px(getInstance(), 72) ){
f = 0;
b ++;
Log.e("zhangdddd__11111", " the b is : " + b);
if(b == 1){
try {
wifiCar.enableMoveFlag();
wifiCar.cameradown();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}else{
if (right > 43) {
right = 43;
left = 1;
}
if (bottom > 177) {
bottom = 177;
top = 135;
}
//right forware
if(bottom < 100){
b = 0;
f ++;
Log.e("zhangdddd__11111", " the f is : " + f);
if( f == 1){
try {
wifiCar.enableMoveFlag();
wifiCar.cameraup();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// right back
if(bottom > 124 ){
f = 0;
b ++;
Log.e("zhangdddd__11111", " the b is : " + b);
if(b == 1){
try {
wifiCar.enableMoveFlag();
wifiCar.cameradown();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
v.layout(1, top, right, bottom);
lastX = (int) event.getRawX();
lastY = (int) event.getRawY();
break;
case MotionEvent.ACTION_UP:
f = 0;
b = 0;
try {
wifiCar.disableMoveFlag();
wifiCar.camerastop();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(with <= 480){
v.layout(1, 49, 29, 77);
}else{
if(with > 1100){
v.layout(dip2px(getInstance(), 1), dip2px(getInstance(), 45), dip2px(getInstance(), 29), dip2px(getInstance(),72));
}
else
v.layout(1, 70, 43, 112);
}
break;
}
return false;
}
});
}
/////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////Setting 04.09/////////////////////////
final ToggleButton micbutton = (ToggleButton) findViewById(R.id.mic_toggle_button);
final ToggleButton settingbutton = (ToggleButton) findViewById(R.id.setting_button);
settingbutton.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_DOWN){
settingbutton.setBackgroundResource(R.drawable.setting_on);
setDialog();
}else if(event.getAction() == MotionEvent.ACTION_UP){
settingbutton.setBackgroundResource(R.drawable.setting);
}
return false;
}
});
/* settingbutton.setOnClickListener(new View.OnClickListener() {
//@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(succeedConnect){
if(settingbutton.isChecked()){
//sendMessage(MESSAGE_SETTING);
settingbutton.setBackgroundResource(R.drawable.setting_on);
setDialog();
//进入setting时如果声音打开着就继续开着
if(audio_play == 1){
//setting_play();
}
setting = 1;
isNotExit = true;
sendMessage(MESSAGE_MAIN_SETTING);
Intent settingIntent = new Intent(WificarActivity.this, SettingActivity.class);
settingIntent.putExtra("IP", IP);
settingIntent.putExtra("Port", Port);
settingIntent.putExtra("version", version);
settingIntent.putExtra("firmwareVersion", firmwareVersion);
settingIntent.putExtra("SSID", SSID);
//intent.setClass(WificarActivity.this, SettingActivity1.class);
startActivityForResult(settingIntent, 1);
////////////03.16退出时关闭录影//////////////
if(videoRecordEnable){
try {
closeVideoStream();
//Toast.makeText(instance,
// R.string.wificar_activity_toast_stop_recording,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
////////////03.16退出时关闭录影//////////////
}
}
}
});*/
////////////////////////////////Setting 04.09////////////////////////
////////////////////////////////video////////////////////////////////////
final ToggleButton videoTogglebutton = (ToggleButton) findViewById(R.id.video_toggle_button);
videoTogglebutton.setOnClickListener(new View.OnClickListener() {
private Object cameraSurfaceView;
//@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(succeedConnect){
if(videoTogglebutton.isChecked() ){
checkTimer = new Timer(true);
checkTimer.schedule(new SDCardSizeTest(), 50, 500);
if(isLowPower){ //当手机电量低于10%的时候,禁止录制视频
Disrecordvideo_dialog.createdisaenablevideoDialog(instance).show();
videoTogglebutton.setChecked(false);
}else{
if(connect_error){
if(dimension > 5.8){
videoTogglebutton.setBackgroundResource(R.drawable.video_on);
}else {
videoTogglebutton.setBackgroundResource(R.drawable.video_on1);
}
//recordAudioTogglebutton.setEnabled(true);
}else{
recordAudioTogglebutton.setEnabled(false);
recordAudioTogglebutton.setBackgroundResource(R.drawable.talk);
//Date date = new Date(System.currentTimeMillis());
SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");//锟斤拷锟斤拷锟斤拷锟节革拷式
String filename = date.format(System.currentTimeMillis());
FileName = filename +".avi";
//String FileName =String.valueOf(System.currentTimeMillis() +".avi");
if(No_Sdcard){
NoSDcard();
Toast toast = Toast.makeText(instance,
R.string.record_fail_warning,Toast.LENGTH_SHORT);
//toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
recordAudioTogglebutton.setEnabled(true);
}else{
if(nSDFreeSize < 100 ){
//video();
//Log.e("aaa", "nSDFreeSize111111 = " + nSDFreeSize);
sdcheck = 2;
Message sdcardtest = new Message();
sdcardtest.what = WificarActivity.MESSAGE_CHECK_TEST;
WificarActivity.getInstance().getHandler().sendMessage(sdcardtest);
recordAudioTogglebutton.setEnabled(true);
}else{
sdcheck = 1;
startVideo = true;
handler.postDelayed(StartVideoTask, 10);
/*try {
openVideoStream(FileName);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
if(dimension > 5.8 ){
videoTogglebutton.setBackgroundResource(R.drawable.video_on);
}else {
videoTogglebutton.setBackgroundResource(R.drawable.video_on1);
}
if(take_flag == 1){
}
}
}//结束判断是否连接
}//结束判断电量低于10%
}
else {
/*if(connect_error){
if(dimension > 5.8){
videoTogglebutton.setBackgroundResource(R.drawable.video);
}else {
videoTogglebutton.setBackgroundResource(R.drawable.video1);
}
}else{*/
if(checkTimer != null){
checkTimer.cancel();
checkTimer = null;
}
if(dimension > 5.8 ){
videoTogglebutton.setBackgroundResource(R.drawable.video);
}else {
videoTogglebutton.setBackgroundResource(R.drawable.video1);
}
recordAudioTogglebutton.setEnabled(true);
recordAudioTogglebutton.setBackgroundResource(R.drawable.talk);
stopVideo = true;
handler.postDelayed(StopVideoTask, 10);
//videoTogglebutton.setBackgroundResource(R.drawable.video);
}
}
}
//}
});
////////////////////////////////video////////////////////////////////////
}
/*
*
// TODO Auto-generated method stub
if(ConnectSucceed){
if(videoTogglebutton.isChecked() ){
checkTimer = new Timer(true);
checkTimer.schedule(new SDCardSizeTest(), 50, 1000);
if(isLowPower){
Disrecordvideo_dialog.createdisaenablevideoDialog(instance).show();
videoTogglebutton.setChecked(false);
}else{
if(connect_error){
videoTogglebutton.setBackgroundResource(R.drawable.video_on);
}else{
//Date date = new Date(System.currentTimeMillis());
SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");//锟斤拷锟斤拷锟斤拷锟节革拷式
String filename = date.format(System.currentTimeMillis());
FileName = "V" + filename +".avi";
//String FileName =String.valueOf(System.currentTimeMillis() +".avi");
if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
NoSDcard();
Toast.makeText(instance,
R.string.take_video_fail,Toast.LENGTH_SHORT).show();
}else{
if(nSDFreeSize < 50 ){
//video();
//Log.e("aaa", "nSDFreeSize111111 = " + nSDFreeSize);
sdcheck = 2;
Message sdcardtest = new Message();
sdcardtest.what = WificarActivity.MESSAGE_CHECK_TEST;
WificarActivity.getInstance().getHandler().sendMessage(sdcardtest);
}else{
talkBtn.setEnabled(false);
talkBtn.setBackgroundResource(R.drawable.call);
sdcheck = 1;
startVideo = true;
handler.postDelayed(StartVideoTask, 10);
}
videoTogglebutton.setBackgroundResource(R.drawable.video_on);
video_pressed = 1;
if(take_flag == 1){
video_record_stop = 1;
video_play = 1;
take_v = Integer.toString(take_video_T);
// //Log.e("zhang", "take_v :" + take_v);
take_video_T ++;
record_video_times = new long [60];
record_video_times[take_video_T] = System.currentTimeMillis() - startRecordTimeStamp;
////Log.e("zhang", "filename[] :" + record_times[take_video_T]);
SharedPreferences share_v0 = getSharedPreferences(FILENAME_V, 0);
SharedPreferences.Editor edit_v0 = share_v0.edit();
edit_v0.putLong(take_v, record_video_times[take_video_T]);
edit_v0.putInt("record_video", take_video_T);
edit_v0.putInt("video_play", video_play);
////Log.e("zhang", "take_v :" + take_v);
edit_v0.commit();
}
}
}
}
}
else {
if(connect_error){
videoTogglebutton.setBackgroundResource(R.drawable.video);
}else{
talkBtn.setEnabled(true);
talkBtn.setBackgroundResource(R.drawable.call);
videoTogglebutton.setBackgroundResource(R.drawable.video);
if(video_play == 1){
//stop_press_video();
//Log.e("zhang", "take_video_T_S :" + take_video_T_S);
video_play_stop = 1;
stop_take_v = Integer.toString(take_video_T_S);
//Log.e("zhang", "stop_take_v :" + stop_take_v);
take_video_T_S ++;
stop_video_times = new long [60];
stop_video_times[take_video_T_S] = System.currentTimeMillis() - startRecordTimeStamp;
//Log.e("zhang", "stop_video_times :" + stop_video_times[take_video_T_S]);
SharedPreferences share_s0 = getSharedPreferences(FILENAME_S, MODE_PRIVATE);
SharedPreferences.Editor edit_s0 = share_s0.edit();
edit_s0.putLong(stop_take_v, stop_video_times[take_video_T_S]);
edit_s0.putInt("stop_video", take_video_T_S);
edit_s0.putInt("video_play_stop", video_play_stop);
//Log.e("zhang", "stop_take_v :" + stop_take_v);
edit_s0.commit();
video_pressed = 0;
}
videoRecordEnable = false;
stopVideo = true;
handler.postDelayed(StopVideoTask, 10);
}
}
}
*/
public boolean isPortait() {
return this.bIsPortait;
}
@Override
public void onBackPressed() {
String statement = this.getResources().getString(
R.string.click_again_to_exit_the_program);
long pressTime = System.currentTimeMillis();
if (pressTime - lastPressTime <= DOUBLE_PRESS_INTERVAL) {
//结束时扫描SDcard
if(!No_Sdcard)
DeleVideo();
deleIndexVideo(); //删除*.index文件
// this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file:" + DirectPath )));
//sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://" + Environment.getExternalStorageDirectory())));
MediaScannerConnection.scanFile(this, new String[]{Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath() + "/" + DirectPath}, null, null);
pause();
exit();
try {
wifiCar.stopPlayTrack();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
disableGSensorControl();
// wifiCar.disconnect();
// finish();
} else {
Toast toast =Toast.makeText(this, statement, Toast.LENGTH_SHORT);
//toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
lastPressTime = pressTime;
}
public void setDialog() {
//新建自己风格的dialog
final ToggleButton settingbutton = (ToggleButton) findViewById(R.id.setting_button);
final Dialog dialog = new Dialog(instance,R.style.my_dialog);
//绑定布局
dialog.getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,
WindowManager.LayoutParams. FLAG_FULLSCREEN);
dialog.setContentView(R.layout.setting_info);
Okbutton = (Button) dialog.findViewById(R.id.OkButton);
tIP = (EditText) dialog.findViewById(R.id.EditText_IP);
tPort = (EditText) dialog.findViewById(R.id.EditText_PORT);
tdevice = (TextView) dialog.findViewById(R.id.TextView_D);
tfirmware = (TextView) dialog.findViewById(R.id.TextView_F);
tsoftware = (TextView) dialog.findViewById(R.id.TextView_S);
//设置背景、监听
Okbutton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Okbutton.setBackgroundResource(R.drawable.ok_off);
dialog.dismiss();
//settingbutton.setBackgroundResource(R.drawable.setting);
//settingbutton.setChecked(false);
}
});
dialog.show();
tIP.setText(IP);
tIP.setClickable(false);
tPort.setText(Port);
tPort.setClickable(false);
tdevice.setText(SSID);
tfirmware.setText(firmwareVersion);
tsoftware.setText(version);
}
/*
* @Override public void onAttachedToWindow() {
* this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
* super.onAttachedToWindow(); }
*/
/* //播放拍照的动作
class take_pictrue extends TimerTask{
public void run(){
if(isPlayModeEnable){
Message messagePlay = new Message();
messagePlay.what = WificarActivity.MESSAGE_PLAY_PICTRUE;
WificarActivity.getInstance().getHandler()
.sendMessage(messagePlay);
}
isplay_pictrue = 1;
}
}
//播放录制视频的动作
class take_video extends TimerTask{
public void run(){
Message messagePlayvideo = new Message();
messagePlayvideo.what = WificarActivity.MESSAGE_PLAY_VIDEO;
WificarActivity.getInstance().getHandler()
.sendMessage(messagePlayvideo);
isplay_video = 1;
}
}
class stop_take_video extends TimerTask{
public void run(){
Message messagestopvideo = new Message();
messagestopvideo.what = WificarActivity.MESSAGE_STOP_VIDEO;
WificarActivity.getInstance().getHandler()
.sendMessage(messagestopvideo);
}
}*/
class RecordTask extends TimerTask {
public void run() {
recordTimeLength = startRecordTimeStamp
- System.currentTimeMillis();
Message messageStopRecord = new Message();
messageStopRecord.what = instance.MESSAGE_STOP_RECORD;
WificarActivity.getInstance().getHandler()
.sendMessage(messageStopRecord);
/*
* dsad ToggleButton recordTogglebutton =(ToggleButton)
* findViewById(R.id.record_toggle_button); ToggleButton
* playTogglebutton =(ToggleButton)
* findViewById(R.id.play_toggle_button);
* //recordTogglebutton.setSelected(false);dad
* recordTogglebutton.setBackgroundResource(R.drawable.record_path);
* recordTogglebutton.setTextColor(Color.WHITE);
* playTogglebutton.setClickable(true);
*/
}
}
class PlayTask extends TimerTask {
public void run() {
Message messageStopPlay = new Message();
messageStopPlay.what = instance.MESSAGE_STOP_PLAY;
WificarActivity.getInstance().getHandler()
.sendMessage(messageStopPlay);
}
}
class rePlayTask extends TimerTask {
@Override
public void run() {
replay_flag = 1;
replay_start = System.currentTimeMillis();
Message messageStartRePlay = new Message();
messageStartRePlay.what = WificarActivity.MESSAGE_START_PLAY;
WificarActivity.getInstance().getHandler().sendMessage(messageStartRePlay);
j = 0;
k = 0;
s = 0;
Log.e("aaa", "replay");
}
}
long recordStartTime = 0;
long recordTime = 0;
public void setRecordStartTime(){
recordTime = 0;
recordStartTime = System.currentTimeMillis();
}
public void setRecordEndTime(){
recordTime = System.currentTimeMillis() - recordStartTime;
if(recordTime>20000){
recordTime = 20000;
}
recordStartTime = 0;
}
public long getRecordTime(){
return recordTime;
}
public void convertBitmapToJPG(Bitmap bitmap) {
/*
* File rootsd = Environment.getExternalStorageDirectory(); File dcim =
* new File(rootsd.getAbsolutePath() + "/DCIM"); File file = new
* File(dcim.getAbsolutePath(),
* String.valueOf(System.currentTimeMillis())+".jpg");
*
* OutputStream fOut = new FileOutputStream(file);
*
* bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut); fOut.flush();
* fOut.close();
*
* MediaStore.Images.Media.insertImage(getContentResolver(),file.
* getAbsolutePath(),file.getName(),file.getName());
*/
// Insert image to media store
String szUrl = MediaStore.Images.Media.insertImage(
getContentResolver(), bitmap, System.currentTimeMillis()
+ ".jpg", System.currentTimeMillis() + ".jpg");
Log.e("zhahg", "szUrl :" + szUrl);
// Get real path for the inserted image
try {
Uri uri = Uri.parse(szUrl);
String[] proj = { MediaStore.Images.Media.DATA };
Cursor actualimagecursor = managedQuery(uri, proj, null, null, null);
int actual_image_column_index = actualimagecursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
actualimagecursor.moveToFirst();
String img_path = actualimagecursor
.getString(actual_image_column_index);
uri = Uri.parse("file://" + img_path);
Log.e("zhang", "uri :" + uri);
Log.e("zhang", "img_path :" + img_path);
// Scan the file to update media store index
//sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
//结束时扫描SDcard
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file:" + DirectPath )));
//sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://" + Environment.getExternalStorageDirectory())));
Toast pictureOK = Toast.makeText(instance,
MessageUtility.MESSAGE_TAKE_PHOTO_SUCCESSFULLY,
Toast.LENGTH_SHORT);
//pictureOK.setGravity(Gravity.CENTER, 0, 0);
pictureOK.show();
} catch (Exception e) {
Toast pictureFAIL = Toast.makeText(instance,
MessageUtility.MESSAGE_TAKE_PHOTO_FAIL, Toast.LENGTH_SHORT);
//pictureFAIL.setGravity(Gravity.CENTER, 0, 0);
pictureFAIL.show();
e.printStackTrace();
}
}
//////////////////////////////////////////////////////////////////////////
public void saveMyBitmap(String bitName ,Bitmap mBitmap){
// if(No_Sdcard){
// Toast.makeText(instance,
// R.string.record_fail_warning,Toast.LENGTH_SHORT).show();
// }
//else{
String photopath =DirectPath + "/Pictures";
File file = new File(photopath);
if (!file.exists()) {
file.mkdirs();
}
File f = new File(DirectPath + "/Pictures/" + bitName + ".jpg");
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
//DebugMessage.put("在保存图片时出错:"+e.toString());
}
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
try {
fOut.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
String szUrl =DirectPath + "/Pictures/" + bitName + ".jpg" ;
Log.e("zhahg", "szUrl :" + szUrl);
// Get real path for the inserted image
try {
Uri uri = Uri.parse(szUrl);
String img_path = DirectPath + "/Pictures/" + bitName + ".jpg";
uri = Uri.parse("file://" + img_path);
Log.e("zhang", "uri :" + uri);
Log.e("zhang", "img_path :" + img_path);
// Scan the file to update media store index
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
//if(isplay_pictrue !=1){
Toast pictureOK = Toast.makeText(instance,MessageUtility.MESSAGE_TAKE_PHOTO_SUCCESSFULLY,
Toast.LENGTH_SHORT);
//pictureOK.setGravity(Gravity.CENTER, 0, 0);
pictureOK.show();
//}
} catch (Exception e) {
Toast pictureFAIL = Toast.makeText(instance,
MessageUtility.MESSAGE_TAKE_PHOTO_FAIL, Toast.LENGTH_SHORT);
//pictureFAIL.setGravity(Gravity.CENTER, 0, 0);
pictureFAIL.show();
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
//}
}
//////////////////////
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) { //如果用startActivityResult跳转进到另一个Activity,按返回键时调用的地方
super.onActivityResult(requestCode, resultCode, data);
/* 20111126: This part is already done in OnCreate() */
Log.d("wild0", "onActivityResult:controllerType:" + controllerType);
int o = getResources().getConfiguration().orientation;
this.changeLandscape();// ッ琌ノlandscape
/*
* if (o == 1) { this.changePortrait(); } else if (o == 2) {
* this.changeLandscape(); }
*/
final ToggleButton lightTogglebutton = (ToggleButton) findViewById(R.id.light_toggle_button);
{
/*
* initial
*/
/*
* int mode = Activity.MODE_PRIVATE; SharedPreferences
* carSharedPreferences = getSharedPreferences(
* WifiCar.WIFICAR_PREFS, mode); boolean ir = carSharedPreferences
* .getBoolean(WifiCar.PREF_IR, false);
*/
// Log.d("wild0","ir:"+ir);
int enableIr = WificarUtility.getIntVariable(instance,
WificarUtility.WIFICAR_IR, 0);
if (enableIr == 1) {
try {
wifiCar.enableIR();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lightTogglebutton.setBackgroundResource(R.drawable.ir_pressed);
} else {
try {
wifiCar.disableIR();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lightTogglebutton.setBackgroundResource(R.drawable.ir);
}
}
final ToggleButton micToggleButton = (ToggleButton) this.findViewById(R.id.mic_toggle_button);
{
/*
* initial
*/
/*
* int mode = Activity.MODE_PRIVATE; SharedPreferences
* carSharedPreferences = getSharedPreferences(
* WifiCar.WIFICAR_PREFS, mode); boolean audio =
* carSharedPreferences.getBoolean(WifiCar.PREF_MIC, false);
*/
int enableMic = WificarUtility.getIntVariable(instance,
WificarUtility.WIFICAR_MIC, 0);
if (enableMic == 1) {
// boolean result = wifiCar.AudioEnable();
boolean result = wifiCar.playAudio();
// if (result) {
micToggleButton.setBackgroundResource(R.drawable.mic_pressed);
// }
} else {
// boolean result = wifiCar.AudioDisable();
try {
boolean result = wifiCar.disableAudio();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// if (result) {
micToggleButton.setBackgroundResource(R.drawable.mic);
// }
}
}
isNotExit = false;
//bSetting = false;
}
public class SoundCheck extends TimerTask {
//取得当前的音量值
public void run(){
sendMessage(MESSAGE_SOUND);
}
}
////////////////03.24 SDcard Check///////////////
public class SDCardSizeTest extends TimerTask {
//取得SDCard当前的状态
public void run(){
String sDcString = android.os.Environment.getExternalStorageState();
if (sDcString.equals(android.os.Environment.MEDIA_MOUNTED)) {
// 取得sdcard文件路径
File pathFile = android.os.Environment
.getExternalStorageDirectory();
android.os.StatFs statfs = new android.os.StatFs(pathFile.getPath());
// 获取SDCard上BLOCK总数
long nTotalBlocks = statfs.getBlockCount();
// 获取SDCard上每个block的SIZE
long nBlocSize = statfs.getBlockSize();
// 获取可供程序使用的Block的数量
long nAvailaBlock = statfs.getAvailableBlocks();
// 获取剩下的所有Block的数量(包括预留的一般程序无法使用的块)
long nFreeBlock = statfs.getFreeBlocks();
// 计算SDCard 总容量大小MB
long nSDTotalSize = nTotalBlocks * nBlocSize / 1024 / 1024;
// 计算 SDCard 剩余大小MB
nSDFreeSize = nAvailaBlock * nBlocSize / 1024 / 1024;
//Log.e("aaaa", "nSDTotalSize = " + nSDTotalSize);
//Log.e("aaaa", "nSDFreeSize = " + nSDFreeSize);
//Log.e("aaaa", "sdcheck = " + sdcheck);
if(nSDFreeSize < 100 && sdcheck ==1 ){
sdcheck = 0;
//Log.e("aaa", "nSDFreeSize111111 = " + nSDFreeSize);
Message sdcardtest = new Message();
sdcardtest.what = WificarActivity.MESSAGE_CHECK_TEST;
WificarActivity.getInstance().getHandler().sendMessage(sdcardtest);
}
}
}
}
////////////////03.24 SDcard Check///////////////
public void openFile(File f) {
Intent intent = new Intent();
intent.addCategory("android.intent.category.DEFAULT");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
String type = "image/jpeg";
intent.setDataAndType(Uri.fromFile(f), type);
startActivityForResult(intent, 5);
}
///////////////////03.24当按下提示SDcard内存不足的确定按钮后执行下列代码/////////////////
public void video() {
//TODO Auto-generated method stub
ToggleButton videoTogglebutton = (ToggleButton) findViewById(R.id.video_toggle_button);
//videoTogglebutton.setBackgroundResource(R.drawable.video);
if(dimension > 5.8){
videoTogglebutton.setBackgroundResource(R.drawable.video);
}else if(dimension < 5.8){
videoTogglebutton.setBackgroundResource(R.drawable.video1);
}
videoTogglebutton.setChecked(false);
}
public void NoSDcard(){
ToggleButton videoTogglebutton = (ToggleButton) findViewById(R.id.video_toggle_button);
//videoTogglebutton.setBackgroundResource(R.drawable.video);
if(dimension > 5.8){
videoTogglebutton.setBackgroundResource(R.drawable.video);
}else if(dimension < 5.8){
videoTogglebutton.setBackgroundResource(R.drawable.video1);
}
videoTogglebutton.setChecked(false);
}
public void play_audio(){
ToggleButton micTogglebutton = (ToggleButton) findViewById(R.id.mic_toggle_button);
int enableMic = WificarUtility.getIntVariable(instance,
WificarUtility.WIFICAR_MIC, 0);
Log.e("zhang", "enableMic :" + enableMic);
if (enableMic == 1) {
// boolean result = wifiCar.AudioEnable();
boolean result = wifiCar.playAudio();
if (result) {
audio_play = 1;
micTogglebutton.setBackgroundResource(R.drawable.mic_pressed);
micTogglebutton.setChecked(true);
}
} else {
boolean result1 = false;
try {
result1 = wifiCar.disableAudio();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (result1) {
audio_play = 0;
micTogglebutton.setBackgroundResource(R.drawable.mic);
micTogglebutton.setChecked(false);
}
}
}
public void setting_play(){
ToggleButton micTogglebutton = (ToggleButton) findViewById(R.id.mic_toggle_button);
/*int enableMic = WificarUtility.getIntVariable(instance,
WificarUtility.WIFICAR_MIC, 1);
Log.e("zhang111", "enableMic :" + enableMic);
if (enableMic == 1) {*/
// boolean result = wifiCar.AudioEnable();
boolean result = wifiCar.playAudio();
if (result) {
audio_play = 1;
micTogglebutton.setBackgroundResource(R.drawable.mic_pressed);
micTogglebutton.setChecked(true);
//micTogglebutton.setChecked(false);
}
//}
checkSound = new Timer(true);
checkSound.schedule(new SoundCheck(), 100, 300);
AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
Log.e("zhang", "currentVolume :" + currentVolume);
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,currentVolume, 0); //tempVolume:音量绝对值
}
public void share() {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setClass(instance,ShareActivity.class);
startActivity(intent);
WificarActivity.this.finish();
}
public boolean note_Intent(Context context) {
ConnectivityManager con = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkinfo = con.getActiveNetworkInfo();
if (networkinfo == null || !networkinfo.isAvailable()) {
// 当前网络不可用
//Toast.makeText(context.getApplicationContext(), "请先连接Internet!",
//Toast.LENGTH_SHORT).show();
return false;
}
else{
return true;
}
}
//图片加水印
public Bitmap createBitMap(Bitmap src){
/**
* 水印制作方法
*/
Log.e("zhang", "开始了,画图");
Bitmap wmsrc=BitmapFactory.decodeResource(getResources(), R.drawable.watermark);//水印
if(src==null){
return null;
}
int w=src.getWidth();
int h=src.getHeight();
int wmw=wmsrc.getWidth();
int wmh=wmsrc.getHeight();
//create the new bitmap
Bitmap newb=Bitmap.createBitmap(w,h,Config.ARGB_8888);//创建一个底图
Canvas cv=new Canvas(newb);
//将底图画进去
cv.drawBitmap(src, 0, 0,null);//在0,0坐标开始画入src
//讲水印画进去
cv.drawBitmap(wmsrc,w-wmw-5, h-wmh-5, null); //w-wmw-5, h-wmh-7
Log.e("zhang", "w , h : " + (w-wmw-5) + "," + (h-wmh-5));
//保存图片
cv.save(Canvas.FULL_COLOR_LAYER_SAVE_FLAG);
cv.restore();
return newb;
}
//退出软件
public void exitProgrames(){
android.os.Process.killProcess(android.os.Process.myPid());
pause();
exit();
/* if(video_pressed == 1){
try {
closeVideoStream();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
video_pressed = 0 ;
}*/
}
public void showDialog(){
ToggleButton gsensor = (ToggleButton) findViewById(R.id.g_sensor_toggle_button);
// disGsensor = false;
// Dialog dlg = new DisGsensor(instance,R.style.CustomDialog);
// dlg = new DisGsensor(instance,R.style.CustomDialog);
// dlg.requestWindowFeature(Window.FEATURE_NO_TITLE);
WindowManager m = getWindowManager();
Display d = m.getDefaultDisplay(); //为获取屏幕宽、高
// dlg.setTitle(" " );
Window w=dlg.getWindow();
WindowManager.LayoutParams lp =w.getAttributes();
w.setBackgroundDrawableResource(R.color.vifrification); //设置对话框背景为透明
// w.setGravity(Gravity.CENTER);
// lp.x=10;
// lp.y=25;
// lp.height = (int) (d.getHeight() * 0.7); //高度设置为屏幕的0.6 ;
// lp.width = (int) (d.getWidth() * 0.9); // 宽度设置为屏幕的0.95
//lp.alpha = 0.5f; //设置透明度
w.setAttributes(lp);
dlg.show();
//disgsensor.setVisibility(View.VISIBLE);
//ToggleButton gsensor = (ToggleButton) findViewById(R.id.g_sensor_toggle_button);
gsensor.setBackgroundResource(R.drawable.g);
gsensor.setChecked(false);
//leftSurface.enableControl();
//rightSurface.enableControl();
//show();
try {
wifiCar.move(WifiCar.LEFT_WHEEL, 0);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
wifiCar.move(WifiCar.RIGHT_WHEEL, 0);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*//分享到Email
public void sharetogmail(String path ,int i){
File file = new File(path);
Log.e("zhang11", "use the email");
// if(ShareActivity.getInstance().isSystemEmail){
ComponentName comp_gmail = new ComponentName("com.android.email", "com.android.email.activity.MessageCompose");
//ComponentName comp_gmail = new ComponentName("com.htc.android.email", "com.htc.android.email.ComposeActivity");
Intent intent_gmail = new Intent();
//Intent intent_gmail = new Intent(android.content.Intent.ACTION_SEND);
intent_gmail.setAction(Intent.ACTION_SEND);
intent_gmail.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
if(i == 1){
intent_gmail.setType("image/jpeg");
}else if(i == 2){
intent_gmail.setType("video/*");
}
intent_gmail.setComponent(comp_gmail);
startActivity(intent_gmail); //启动程序
//调用系统的邮件系统
// startActivity(Intent.createChooser(intent_gmail, "请选择邮件发送软件"));
}
//分享到facebook
public void sharetofacebook(String path , int i){
File file = new File(path);
ComponentName comp_f = new ComponentName("com.facebook.katana", "com.facebook.katana.ComposerActivity");
Intent intent_f = new Intent();
intent_f.setAction(Intent.ACTION_SEND);
intent_f.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
if(i == 1){
intent_f.setType("image/jpeg");
}else if(i == 2){
intent_f.setType("video/*");
}
intent_f.setComponent(comp_f);
startActivity(intent_f); //启动程序
}
//分享到twitter
public void sharetotwitter(String path ,int i ){
File file = new File(path);
ComponentName comp = new ComponentName("com.twitter.android", "com.twitter.android.PostActivity");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
if(i == 1){
intent.setType("image/jpeg");
}else if(i == 2){
intent.setType("video/*");
}
intent.setComponent(comp);
startActivity(intent); //启动程序
}
//分享到tumblr
public void sharetotumblr(String path ,int i){
File file = new File(path);
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
if(i == 1){
ComponentName comp = new ComponentName("com.tumblr", "com.tumblr.activity.PhotoPostActivity");
intent.setAction(Intent.ACTION_MAIN);
intent.setType("image/jpeg");
intent.setComponent(comp);
}else if(i == 2){
ComponentName comp = new ComponentName("com.tumblr", "com.tumblr.activity.VideoPostActivity");
//intent.setAction(Intent.ACTION_SEND_MULTIPLE);
intent.setAction(Intent.ACTION_SEND);
intent.setType("video/*");
intent.setComponent(comp);
}
startActivity(intent); //启动程序
}
//分享到youtube
public void sharetoyoutube(String path){
File file = new File(path);
ComponentName comp = new ComponentName("com.google.android.apps.uploader", "com.google.android.apps.uploader.clients.youtube.YouTubeSettingsActivity");
Intent intent_y = new Intent();
intent_y.setAction(Intent.ACTION_SEND);
intent_y.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
intent_y.setType("video/*");
intent_y.setComponent(comp);
startActivity(intent_y); //启动程序
//startActivityForResult(intent_y, 1);
}*/
public void setDirectionGsensor(int left , int right) {
if(WificarActivity.getInstance().isPlayModeEnable){
WificarActivity.getInstance().sendMessage(WificarActivity.MESSAGE_STOP_PLAY);
}
Log.d("wild0", "direction left:" + left);
iCarSpeedL = left*10;
iCarSpeedR = right*10;
}
private Runnable gMovingTask = new Runnable() {
public void run() {
if (gSensorControlEnable & iCarSpeedL == iCarSpeedR) {
//Log.e("zhang", "一直运行gMovingTask");
// if (iLastSpeedL != 0 && iCarSpeedL == 0)
// wifiCar.moveCommand(WifiCar.GO_DIRECTION.Left, iCarSpeedL);
// iLastSpeedL = iCarSpeedL;
if ( iCarSpeedL > 0 && iCarSpeedL != 0) {
// Log.d("wild0","FFFF:"+iCarSpeedL);
try {
wifiCar.enableMoveFlag();
wifiCar.g_move(11, iCarSpeedL);
//Log.e("zhang", "向前向前向前:" + iCarSpeedL);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
iLastSpeedL = iCarSpeedL;
}
if ( iCarSpeedL < 0 && iCarSpeedL != 0) {
// Log.d("wild0",
// "Run left("+controlEnable+"):"+iCarSpeedL);
try {
wifiCar.enableMoveFlag();
wifiCar.g_move(12, iCarSpeedL);
//Log.e("zhang", "向后向后向后");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
iLastSpeedL = iCarSpeedL;
}
if ( iCarSpeedL ==0 && iLastSpeedL != 0 ) {
try {
wifiCar.disableMoveFlag();
wifiCar.move(WifiCar.LEFT_WHEEL, iCarSpeedL);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
wifiCar.disableMoveFlag();
wifiCar.move(WifiCar.RIGHT_WHEEL, iCarSpeedR);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
iLastSpeedL = 0;
}
}
handler.postDelayed(this, 100);
}
};
private Runnable TakePhotoTask = new Runnable() {
public void run() {
if (bPhotoThreadRun) {
if (cameraSurfaceView != null) {
try {
// takePictureBtn.setBackgroundResource(R.drawable.camera_pressed);
Log.e("take photo", "start take photo");
wifiCar.takePicture(instance);
} catch (Exception e) {
e.printStackTrace();
}
}
bPhotoThreadRun = false;
}
handler.postDelayed(this, 100);
}
};
private Runnable StartVideoTask = new Runnable() {
public void run() {
if (startVideo) {
try {
openVideoStream(FileName);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startVideo =false;
}
handler.postDelayed(this, 100);
}
};
private Runnable StopVideoTask = new Runnable() {
public void run() {
if (stopVideo) {
stopVideo = false;
startVideo =false;
try {
closeVideoStream();
Toast toast = Toast.makeText(instance,R.string.wificar_activity_toast_stop_recording,Toast.LENGTH_SHORT);
//toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
handler.postDelayed(this, 100);
}
};
private void DeleVideo(){
if(startVideo){
startVideo = false;
String path = ReadSDPath() + "/CAR 2.0";
File f = new File(path);
File[] files = f.listFiles();
/**
* 遍历文件,将所有文件存入ArrayList中,这个地方存的还是文件路径
*/
for(File file : files){
if (file.isDirectory()) {
}else {
String fileName = file.getName();
if(fileName.equals(FileName)){
File dfile = new File(file.getPath());
dfile.delete();
}
}
}
}
}
private void deleIndexVideo(){
String path = ReadSDPath() + "/CAR 2.0";
File f = new File(path);
if(f.exists()){
f.mkdirs();
File[] files = f.listFiles();
/**
* 遍历文件,将所有文件存入ArrayList中,这个地方存的还是文件路径
*/
for(File file : files){
if (file.isDirectory()) {
}else {
String fileName = file.getName();
if (fileName.endsWith(".index")) {
File dfile = new File(file.getPath());
dfile.delete();
String filePath = file.getPath().substring(0,file.getPath().length()-6);
//Log.e("DeleFile", "filePath :" + filePath);
File dfile1 = new File(filePath);
dfile1.delete();
}
}
}
}
}
//获取SD卡的跟路径
public String ReadSDPath(){
boolean SDExit=Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
if(SDExit){
return Environment.getExternalStorageDirectory().toString();
}else{
return null;
}
}
}<file_sep>/Rover 2.0-android-src/src/com/wificar/surface/CamerSettingSurfaceView.java
package com.wificar.surface;
import java.io.IOException;
import com.CAR2.R;
import com.wificar.WificarActivity;
import com.wificar.component.WifiCar;
import com.wificar.surface.CamerSettingSurfaceView;
import com.wificar.util.ImageUtility;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
public class CamerSettingSurfaceView extends SurfaceView implements SurfaceHolder. Callback
{
static CamerSettingSurfaceView instance;
SurfaceHolder holder;
private Handler handler = new Handler();
private Handler handler_camer = new Handler();
//摇杆的X,Y坐标以及摇杆的半径
// public float RSmallRockerCircleX = 0;
// public float RSmallRockerCircleY = 40;
// public float RSmallRockerCircleY_1 = 65;
// public float RSmallRockerCircleY_2 = 32;
public float RSmallRockerCircleX = 0;
public float RSmallRockerCircleY = WificarActivity.dip2px(getContext(), 60);
public float RSmallRockerCircleY_1 = WificarActivity.dip2px(getContext(), 70);
public float RSmallRockerCircleY_2 = WificarActivity.dip2px(getContext(), 40);
private WifiCar wifiCar = null;
Bitmap background = null;
Bitmap stickBall = null;;
private final int tStep = 1;
private boolean controlEnable = false;
private boolean enableRun = false;
private boolean cameraPressed = false;
private int cameramove =0 ;
private int f = 0;
private int b = 0;
//private MySurfaceViewThread mySurfaceViewThread;
//private boolean hasSurface;
public static CamerSettingSurfaceView getInstance(){
return instance;
}
CamerSettingSurfaceView(Context context) {
super(context);
init();
}
public CamerSettingSurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
instance = this;
//Log.d("wild0", "new ControllerSurfaceView:1");
init();
}
private void init() {
//创建一个新的SurfaceHolder, 并分配这个类作为它的回调(callback)
holder = getHolder();
background = ImageUtility.createBitmap(getResources(),
R.drawable.back);
stickBall = ImageUtility.createBitmap(getResources(),
R.drawable.stick_back);
holder.addCallback(this);
}
//@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
Log.e("zhangzhangzhang", "surfavechange");
redraw();
}
//@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
holder.setFormat(PixelFormat.TRANSPARENT);
redraw();
handler.postDelayed(rightMovingTask, tStep);
//handler_camer.postDelayed(camer, tStep);
}
//@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
//@Override
public void setWifiCar(WifiCar wifiCar) {
this.wifiCar = wifiCar;
}
private void clear(Canvas canvas) {
if (canvas != null) {
canvas.drawColor(Color.TRANSPARENT);
}
}
public synchronized void redraw() {
Canvas canvas = holder.lockCanvas();
if (canvas == null)
return;
clear(canvas);
Paint paint = new Paint();
paint.setAlpha(255);
if (controlEnable) {
if(WificarActivity.getInstance().dimension > 5.8){
if(WificarActivity.getInstance().with > 850){
if(RSmallRockerCircleY !=40){
RSmallRockerCircleY=RSmallRockerCircleY -18;
}
canvas.drawBitmap(background, 0, 0, paint);
canvas.drawBitmap(stickBall, WificarActivity.dip2px(getContext(), 50), RSmallRockerCircleY, paint);
Log.e("1212121", "Y :" + RSmallRockerCircleY);
}else{
if(RSmallRockerCircleY_2 !=32){
RSmallRockerCircleY_2=RSmallRockerCircleY_2 -18;
}
canvas.drawBitmap(background, 0, 0, paint);
canvas.drawBitmap(stickBall, 1, RSmallRockerCircleY_2, paint);
Log.e("1212121", "Y :" + RSmallRockerCircleY_2);
}
}else {
if(RSmallRockerCircleY_1 !=65){
RSmallRockerCircleY_1=RSmallRockerCircleY_1 -18;
}
canvas.drawBitmap(background, 0, 0, paint);
canvas.drawBitmap(stickBall, 1, RSmallRockerCircleY_1, paint);
Log.e("1212121", "Y111 :" + RSmallRockerCircleY_1);
}
}
holder.unlockCanvasAndPost(canvas);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if(!controlEnable){
return true;
}
int action = (event.getAction() & MotionEvent.ACTION_MASK);
switch (action) {
case MotionEvent.ACTION_DOWN:
//cameraPressed = true;
//enableRun = true;
Log.e("zhangdddd", " the f is : " + f);
Log.e("zhangddd11", " the b is : " + b);
float x = event.getX();
float y = event.getY();
RSmallRockerCircleX = 0;
RSmallRockerCircleY = y ;
RSmallRockerCircleY_1 = y;
RSmallRockerCircleY_2 = y;
if(y>90){
RSmallRockerCircleY = WificarActivity.dip2px(getContext(), 60);
}
if(y<20){
RSmallRockerCircleY = WificarActivity.dip2px(getContext(), 20);
}
if(y>125){
RSmallRockerCircleY_1 = 125;
}
if(y<20){
RSmallRockerCircleY_1 = 20;
}
if(y>70){
RSmallRockerCircleY_2 = 70;
}
if(y<17){
RSmallRockerCircleY_2 = 17;
}
if (this.isLocateAtCameraForwardBoundary(x, y)) {
Log.e("zhangzhangzhn", "up_up");
WificarActivity.getInstance().getWifiCar().enableMoveFlag();
f ++;
Log.e("zhangdddd__11111", " the f is : " + f);
if( f == 1){
cameramove = 1;
}
} else if (this.isLocateAtCameraBackwardBoundary(x, y)) {
Log.e("zhangzhangzhn", "down_down");
WificarActivity.getInstance().getWifiCar().enableMoveFlag();
b ++;
Log.e("zhangdddd__11111", " the b is : " + b);
if(b == 1){
cameramove = 2;
}
}
else if(this.isLocateAtCamera(x, y)){
b = 0;
f = 0;
cameramove = 0;
Log.e("zhang33333333 ", " the f is : " + f);
Log.e("zhang33333333 ", " the b is : " + b);
}
break;
case MotionEvent.ACTION_UP:
f = 0;
b = 0;
cameramove = 0;
Log.e("zhangupup", " the f is : " + f);
Log.e("zhangupup11", " the b is : " + b);
float ux = event.getX();
float uy = event.getY();
RSmallRockerCircleX = 0;
RSmallRockerCircleY = 40 ;
RSmallRockerCircleY_1 = 65;
RSmallRockerCircleY_2 = 32;
WificarActivity.getInstance().getWifiCar().disableMoveFlag();
break;
case MotionEvent.ACTION_MOVE:
Log.e("zhangmv", " the f is : " + f);
Log.e("zhangmv11", " the b is : " + b);
float mx = event.getX();
float my = event.getY();
RSmallRockerCircleX = 0;
RSmallRockerCircleY = my ;
RSmallRockerCircleY_1 = my ;
RSmallRockerCircleY_2 = my ;
if(my>90){
RSmallRockerCircleY = 90;
}
if(my<20){
RSmallRockerCircleY = 20;
}
if(my>125){
RSmallRockerCircleY_1 = 125;
}
if(my<20){
RSmallRockerCircleY_1 = 20;
}
if(my>70){
RSmallRockerCircleY_2 = 70;
}
if(my<17){
RSmallRockerCircleY_2 = 17;
}
if (this.isLocateAtCameraForwardBoundary(mx, my)) {
f++;
Log.e("zhangdddd__22222", " the f is : " + f);
Log.e("zhangzhangzhn", "moveup_up");
WificarActivity.getInstance().getWifiCar().enableMoveFlag();
if( f == 1 ){
cameramove = 1;
}
} else if (this.isLocateAtCameraBackwardBoundary(mx, my)) {
Log.e("zhangzhangzhn", "movedown_down");
b++;
Log.e("zhangdddd__2222222", " the b is : " + b);
WificarActivity.getInstance().getWifiCar().enableMoveFlag();
if(b == 1){
cameramove = 2;
}
}
else if(this.isLocateAtCamera(mx, my)){
b = 0;
f = 0;
//cameramoveup = 0;
//cameramovedown = 0;
Log.e("zhang2323 ", " the f is : " + f);
Log.e("zhang23232 ", " the b is : " + b);
}
break;
case MotionEvent.ACTION_POINTER_1_UP:
f = 0;
b = 0;
cameramove = 0;
Log.e("zhangup", " the f is : " + f);
Log.e("zhangup11", " the b is : " + b);
float x2 = event.getX();
float y2 = event.getY();
RSmallRockerCircleX = 0;
RSmallRockerCircleY = 40;
RSmallRockerCircleY_1 = 65;
RSmallRockerCircleY_2 = 32;
WificarActivity.getInstance().getWifiCar().disableMoveFlag();
try {
wifiCar.camerastop();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
this.redraw();
return true;
}
private boolean isLocateAtCameraForwardBoundary(float x, float y) {
// TODO Auto-generated method stub
Log.e("aaaa222222222222F", "x , y " + x +" ," + y);
if(x>-10 && x<80 && y < 45 && y > -80) {
return true;
} else {
return false;
}
}
private boolean isLocateAtCameraBackwardBoundary(float x, float y) {
// TODO Auto-generated method stub
Log.e("aaaa222222222222222B", "x , y " + x +" ," + y);
if(x > -50 && x<80 && y>70 && y < 240 ){
return true;
}
else{
return false;
}
}
private boolean isLocateAtCamera(float x, float y) {
// TODO Auto-generated method stub
Log.e("aaaa33333333333", "x , y " + x +" ," + y);
if(x > -50 && x<80 && y>45 && y < 70 ){
return true;
}
else{
return false;
}
}
public static Bitmap createBitmap(Resources res, int srcId) {
Bitmap bitmap = BitmapFactory.decodeResource(res, srcId);
return bitmap;
}
//@Override
public void disableControl() {
// TODO Auto-generated method stub
controlEnable = false;
this.setVisibility(View.INVISIBLE);
Log.e("zhang11", "setting controldisable");
this.redraw();
}
//@Override
public void enableControl() {
// TODO Auto-generated method stub
controlEnable = true;
this.setVisibility(View.VISIBLE);
Log.e("zhang", "setting controlenable");
this.redraw();
}
private Runnable rightMovingTask = new Runnable() {
//@Override
public void run() {
if (controlEnable) {
//if (iLastSpeedL != 0 && iCarSpeedL == 0)
// wifiCar.moveCommand(WifiCar.GO_DIRECTION.Left, iCarSpeedL);
//iLastSpeedL = iCarSpeedL;
if (cameramove== 0){
Log.e("aaaa_sp", "camera stop:" + cameramove);
//wifiCar.canCommand(1);
try {
wifiCar.disableMoveFlag();
wifiCar.camerastop();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (cameramove == 1 && f == 1){
Log.e("aaaa_up", "camera up:" + cameramove);
try {
wifiCar.enableMoveFlag();
wifiCar.cameraup();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (cameramove == 2 && b == 1){
Log.e("aaaa_down", "camera down:" + cameramove);
try {
wifiCar.enableMoveFlag();
wifiCar.cameradown();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
handler.postDelayed(this, tStep);
}
};
/*private Runnable camer = new Runnable(){
public void run() {
// TODO Auto-generated method stub
if(enableRun){
if(cameraPressed){
wifiCar.enableMoveFlag();
}else if(!cameraPressed){
wifiCar.disableMoveFlag();
}
}
handler_camer.postDelayed(camer, 10);
}
};*/
}
<file_sep>/Rover 2.0-android-src/src/com/wificar/util/ImageAdapterPhoto.java
package com.wificar.util;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
public class ImageAdapterPhoto extends BaseAdapter {
/* 类变量声明 */
private Context mContext;
private ArrayList<Bitmap> photos = new ArrayList<Bitmap>();
/**
* @param context
* 上下文构造函数
*/
public ImageAdapterPhoto(Context context) {
mContext = context;
}
// 把图片添加到数组
public void addPhoto(Bitmap photo) {
photos.add(photo);
}
// 得到图片数量
public int getCount() {
return photos.size();
}
// 获取对应位置的对象
public Object getItem(int position) {
return photos.get(position);
}
// 获取ID
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
/* 局部变量声明 */
ImageView imageView;
/* 查看缓存是否有我们需要的内容 */
if (convertView == null) {
imageView = new ImageView(mContext);
} else {
imageView = (ImageView) convertView;
}
/* 图片属性设置 */
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
// 获取图片&装入adapter
imageView.setImageBitmap(photos.get(position));
return imageView;
}
}
<file_sep>/Rover 2.0-android-src/src/com/wificar/dialog/Control_share_dialog.java
package com.wificar.dialog;
import com.CAR2.R;
import com.wificar.WificarActivity;
import com.wificar.util.VideoUtility;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.ContextThemeWrapper;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;
public class Control_share_dialog {
public Control_share_dialog() {
}
public static AlertDialog.Builder createcontrolsharedialog(Context context){
final AlertDialog.Builder shareDialog = new AlertDialog.Builder(new ContextThemeWrapper(context, R.layout.share_dialog));
//shareDialog.setTitle("Info");
shareDialog.setMessage("The Facebook, Twitter, Tumblr, and YouTube apps must already be installed on your device to share CAR 2.0 photos and videos.\n" +
"Exit the app, go to Settings and access a Wi-Fi network other than CAR 2.0. Open the CAR 2.0 app and select Share.");
shareDialog .setCancelable(false);
shareDialog .setPositiveButton("OK",new DialogInterface.OnClickListener() {
//@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
//WificarActivity.getInstance().exit();
}
});
return shareDialog;
}
} | 5d38cf10a79ff373418369e244f83b5b00775acb | [
"Java"
] | 17 | Java | sylijinlei/Rover2 | 01ce4021e55a8e959f1c43cd0eecfa2ee33482ed | 68878537877e78a7a710d02f0f448f85b2e2d8c0 |
refs/heads/master | <file_sep><?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Requests\MassDestroyProductRequest;
use App\Http\Requests\StoreProductRequest;
use App\Http\Requests\UpdateProductRequest;
use App\Product;
class ProductItemsController extends Controller
{
public function index()
{
// abort_unless(\Gate::allows('product_access'), 403);
$products = Product::all();
return view('my_work.index', compact('products'));
}
/**
* $slug is een woord dat opgezocht wordt in de tabel portfolio_items.
* Onder water wordt de volgende query uitgevoerd: select * from portfolio_items where slug = $slug
*/
public function show()
{
// abort_unless(\Gate::allows('product_show'), 403);
return view('my_work.show', compact('product'));
}
}
<file_sep># portfolio-hidde-master🔥🔥🔥
DIST FOLDER NU MEE BEZIG
* usage git:
git add .
git commit -m ""
git push
// git pull voor ophalen
# [Portfolio - <NAME>]
**<NAME>**
_Ik wil mijn portfolio in react maken. Me hoofddoel die is een object je muis volgt en het systeem werk_
\*\*
_Laravel als backend_
_De data moet een dashboard hebben_
## Planning
* week 1: Zoeken naar inspiratie
* Week 2: Zoeken naar inspiratie
* Week 3: Bouwen van de website
* Week 4: Bouwen van de website
* Week 5: Bouwen van de website
* Week 6: Bouwen van de website
* Week 7: content vullen
* Week 9: installation readme.md
* Week 10: Submitted
## Todo:
- [x] Inspiratie zoeken
- [x] Data beheren met laravel
- [x] Data uitlezen Dashboard
- [x] Laravel server stats uitlezen Dashboard design
- [x] scss toevoegen
- [ ] Dashboard uitbreiden/mooier maken
- [ ]
- [ ]
## Status
| Klaar? | portfolio |
| :----: | --------- |
| ✅ | Nope 😞 |
| ⬜️ | Yeesss 😀 |
## Download and Installation
```sh
$ git clone https://gitlab.glu.nl/530643/webportfolio.git
$ cd hidde-portfolio-master
```
## Usage Laravel
```sh
add a new database
composer install
npm install
cp example.env .env
update je .env naar je database naam en je DB_USERNAME= en DB_PASSWORD=
php artisan key:generate
php artisan migrate:refresh
php artisan migrate:refresh --seed
\*for editting sass this command
npm install
npm run watch
```
### Basic Usage
Read the installation
## Copyright and Licens
@<NAME>
```
```
<file_sep><?php
use Illuminate\Database\Seeder;
class BlogSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('blogs')->insert([
[
'title' => 'Blog 1',
'content' => 'Blog 1 content',
'author' => 'Jeffrey',
'active' => '1',
],
[
'title' => 'Blog 2',
'content' => 'Blog 2 content',
'author' => 'John',
'active' => '0',
],
[
'title' => 'Blog 3',
'content' => 'Blog 3 content',
'author' => 'Karel',
'active' => '1',
],
[
'title' => 'Blog 4',
'content' => 'Blog 4 content',
'author' => 'Mies',
'active' => '1',
],
]);
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Blog extends Model
{
// /**
// * Onderstaand moet je toevoegen omdat standaard Mass Protection aan staat
// *
// * @var array
// */
// protected $fillable = [
// 'title',
// 'content',
// 'author',
// ];
/**
* Onderstaand geeft aan dat op geen van alle velden van de blog tabel
* Mass protected is. Voorwaarde is dat $fillable uitgecomment staat.
*
* @var array
*/
protected $guarded = [];
}
<file_sep><?php
namespace App\Http\Requests;
use App\Product;
use Illuminate\Foundation\Http\FormRequest;
class UpdateProductRequest extends FormRequest
{
public function authorize()
{
return \Gate::allows('product_edit');
}
public function rules()
{
return [
'title' => [
'required',
],
'headtitle' => [
'required',
],
'category' => [
'required',
],
'sub_title' => [
'required',
],
'slug' => [
'required',
],
'month' => [
'required',
],
'day' => [
'required',
],
'description' => [
'required',
],
'body' => [
'required',
],
'image' => [
'required',
],
];
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Contact;
use App\Mail\ContactMail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
class ContactController extends Controller
{
public function index()
{
return view('contact.index');
}
/**
* Met store() schrijven we gegevens weg naar de database.
*/
public function store()
{
/**
* Met request()->validate() kun je validatie toepassen op velden die in
* het formulier gedefinieerd staan.
*
* email: Is een verplicht veld, moet minimaal 3 karakters bevatten en maximaal 150 karakters lang
* en moet een valide email adres bevatten
* Content: Is een verplicht veld, moet minimaal 5 karakters bevatten en maximaal 500 karakters lang
*/
request()->validate([
'email' => 'required|min:3|max:150|email',
'content' => 'required|min:5|max:500',
]);
// Prepareren van data voor de contacts tabel
$contactModel = new Contact();
$contactModel->email = request('email');
$contactModel->content = request('content');
// Nu slaan we de geprepareerde data op in de contacts tabel
$contactModel->save();
Mail::to(request('email'))->send(new ContactMail());
// De pagina terug laten redirecten
return redirect()->back();
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Blog;
use Illuminate\Http\Request;
class BlogsController extends Controller
{
public function index(Request $request)
{
$blogs = Blog::where('active', $request->query('active', 1))->get();
return view('blog.index', ['blogs' => $blogs]);
}
public function create()
{
$blog = new Blog();
return view('blog.create', compact('blog'));
}
/**
* Met store() schrijven we gegevens weg naar de database.
*/
public function store()
{
Blog::create($this->getValidateData());
// Na het opslaan wordt de gebruiker weer terug gestuurd naar de url /blog
return redirect('/blog');
}
/**
* Omdat het een veel voorkomende taak is om 1 item op te halen
* van de database, kun je in de show() een argument opgeven dat meteen
* de $blog variabele vult met het Blog object.
*
* Op deze manier hoef je niet steeds find() of findOrFail() aan te roepen!
*/
public function show(Blog $blog)
{
/**
* find(): Als de model een niet bestaande blogId op probeert te halen
* dan krijg je een lelijke error pagina van Laravel. Dit willen we niet
* omdat het rauwe code van de template getoond wordt.
*
* find() werkt alleen op basis van een ID
*/
// $blog = Blog::find($blogId);
/**
* findOrFail(): Als de model een niet bestaande blogId op probeert te halen
* dan wordt er een nette 404 | error pagina getoond
*
* findOrFail() werkt enkel op basis van een ID
*/
// $blog = Blog::findOrFail($blogId);
return view('blog.show', ['blog' => $blog]);
}
public function edit(Blog $blog)
{
return view('blog.edit', ['blog' => $blog]);
}
public function update(Blog $blog)
{
// $data = $this->getValidateData();
// dd($data);
/**
* Het verschil ten opzichte van store() is dat we een bestaande blog willen updaten
* en geen nieuwe blog aan willen maken.
*/
$blog->update($this->getValidateData());
// Na het opslaan wordt de gebruiker weer terug gestuurd naar de url /blog
return redirect('/blog');
}
protected function getValidateData()
{
/**
* Met request()->validate() kun je validatie toepassen op velden die in
* het formulier gedefinieerd staan.
*
* Title: Is een verplicht veld, moet minimaal 5 karakters bevatten en maximaal 200 karakters lang
* Content: Is een verplicht veld, moet minimaal 5 karakters bevatten en maximaal 1000 karakters lang
* Author: Is een verplicht veld, moet minimaal 2 karakters bevatten en maximaal 150 karakters lang
*/
$data = request()->validate([
'title' => 'required|min:5|max:200',
'content' => 'required|min:5|max:1000',
'author' => 'required|min:2|max:150',
'active' => '',
]);
if (isset($data['active']) && $data['active'] == 'on') {
$data['active'] = 1;
} else {
$data['active'] = 0;
}
return $data;
}
}
<file_sep><?php
Route::get('/', function () {
return view('homepage');
});
//contact
Route::get('/contact', 'ContactController@index');
// Dit is een post en onderstaand is nodig om de velden van het formulier op te vangen
Route::post('/contact', 'ContactController@store');
// Route::get('/homepage', 'ProductItemsController@index');
//mijn-werk/projecten
Route::get('/mijn-werk', 'ProductItemsController@index');
Route::get('/mijn-werk/{slug}', 'ProductItemsController@show');
//blog
Route::get('/blog', 'BlogsController@index');
Route::get('/blog/create', 'BlogsController@create');
// Dit is een post en onderstaand is nodig om de velden van het formulier op te vangen
Route::post('/blog', 'BlogsController@store');
Route::get('/blog/{blog}', 'BlogsController@show');
Route::get('/blog/{blog}/edit', 'BlogsController@edit');
Route::put('/blog/{blog}', 'BlogsController@update');
// Route::redirect('/', '/home');
// Route::redirect('/home', '/admin');
Auth::routes(['register' => false]);
Route::group(['prefix' => 'admin', 'as' => 'admin.', 'namespace' => 'Admin', 'middleware' => ['auth']], function () {
Route::get('/', 'HomeController@index')->name('home');
Route::delete('permissions/destroy', 'PermissionsController@massDestroy')->name('permissions.massDestroy');
Route::resource('permissions', 'PermissionsController');
Route::delete('roles/destroy', 'RolesController@massDestroy')->name('roles.massDestroy');
Route::resource('roles', 'RolesController');
Route::delete('users/destroy', 'UsersController@massDestroy')->name('users.massDestroy');
Route::resource('users', 'UsersController');
Route::delete('products/destroy', 'ProductsController@massDestroy')->name('products.massDestroy');
Route::resource('products', 'ProductsController');
});
<file_sep><?php
use Illuminate\Database\Seeder;
class WorkSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('products')->insert([
[
'title' => 'Heemskerk',
'headtitle' => 'Heemskerk app',
'slug' => 'heemskerk',
'description' => 'Dit is een korte beschrijving',
'body' => 'Dit is de body',
'image' => 'img/thumbnail/logo-heemskerk.png',
'day' => '2',
'month' => 'apr',
'category' => 'Het Bureau',
'sub_title' => 'App voor heemskerk',
],
[
'title' => 'em-project',
'headtitle' => 'projectweek p4',
'slug' => 'em_project',
'description' => 'Projectweek in het eerste jaar van glu',
'body' => 'Dit is de body',
'image' => 'img/thumbnail/em_project.PNG',
'day' => '2',
'month' => 'Jun',
'category' => 'project',
'sub_title' => 'projectweek',
],
[
'title' => 'Netflix',
'headtitle' => 'React',
'slug' => 'Netflix',
'description' => 'In periode 6 moest ik een netflix app maken',
'body' => 'Netflix',
'image' => 'img/thumbnail/netflix.PNG',
'day' => '2',
'month' => 'apr',
'category' => 'REACTJS',
'sub_title' => 'Netflix app met Reactjs',
],
[
'title' => 'TicToc',
'headtitle' => 'eigen project',
'slug' => 'own-project',
'description' => 'Eigen project',
'body' => 'Dit is de body',
'image' => 'img/thumbnail/tictoc.PNG',
'day' => '1',
'month' => 'may',
'category' => 'Het Bureau',
'sub_title' => 'App voor heemskerk',
],
]);
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Product extends Model
{
use SoftDeletes;
protected $dates = [
'created_at',
'updated_at',
'deleted_at',
];
protected $fillable = [
'headtitle',
'title',
'category',
'sub_title',
'slug',
'day',
'month',
'description',
'body',
'image',
'created_at',
'updated_at',
'deleted_at',
'description',
];
}
| cd549e38059d53ac8a532308ca78c4e094429682 | [
"Markdown",
"PHP"
] | 10 | PHP | hidde030/laravelhidde | cb5c56a0630c3d706421829fec918ae728fef0de | 087ef68db62452cca413891c10f4364ea054f80d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.