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 | <file_sep>#include <stdio.h>
#include <stdlib.h>
#define TAILLE_CH 256
#define NB_CASES 64
#define NB_CASES_PAR_LIGNE 8
//struct de la partie qui contient le damier (64 cases), le nom des deux joueurs, et une valeur pour savoir quel joueur commence
struct partie
{
int damier[NB_CASES];
char nomJ1 [TAILLE_CH];
char nomJ2 [TAILLE_CH];
int premierJoueurJoue;
};
//Fonction qui retourne la valeur d'une case du damier
int getCase(struct partie *p, int ligne, int colonne)
{
if (ligne <= (NB_CASES_PAR_LIGNE -1) && colonne <= (NB_CASES_PAR_LIGNE -1) && ligne >= 0 && colonne >= 0)
{
int num= (NB_CASES_PAR_LIGNE*ligne) + colonne ; // calcul pour trouver le numero de la case
int val= (*p).damier[num]; // val est la valeur contenu par la case
return val; //retourne la valeur de la case
}
else
{
return -2;
}
}
//Fonction qui permet de modifier la valeur d'une case du damier
void setCase(struct partie *p, int ligne, int colonne, int val)
{
if (ligne <= (NB_CASES_PAR_LIGNE -1) && colonne <= (NB_CASES_PAR_LIGNE -1) && ligne >= 0 && colonne >= 0 && val<= 1 && val >= (-1))
{
int num= (NB_CASES_PAR_LIGNE*ligne) + colonne ; // calcul pour trouver le numero de la case
(*p).damier[num]=val; // affecte la val a la case
}
else
{
printf("ERREUR setCase\n");
}
}
//Fonction qui permet de modifier la valeur de l'attribut premierJoueurJoue du struct partie pour le changement de tour
void changementJoueur(struct partie *p)
{
if ((*p).premierJoueurJoue == 0) //si c'est au tour du J2
(*p).premierJoueurJoue =1; //tour passe au J1
else
(*p).premierJoueurJoue =0;
}
//Fonction qui crée une partie
struct partie* creerPartie ()
{
struct partie *p;
p=malloc(sizeof(struct partie)); // alloue dynamiquement la memoire de la taille d'un struct partie
if (p==NULL)
exit(1);
printf("Entrez le nom du J1: ");
scanf("%s",(*p).nomJ1);
printf("Entrez le nom du J2: ");
scanf("%s",(*p).nomJ2);
(*p).premierJoueurJoue=1; // noir qui commence
int i;
for (i=0;i<NB_CASES;i++) // boucle pour mettre toutes les cases du damier à 0
{
(*p).damier[i]=0;
}
setCase(p,3,3,-1);//place les pions au milieu du champ damier
setCase(p,3,4,1);
setCase(p,4,3,1);
setCase(p,4,4,-1);
return p;
}
//Fonction d'affichage d'une partie
void affichage( struct partie * p)
{
int j;
int ligne =0;
int colonne ;
for (ligne=0;ligne<NB_CASES_PAR_LIGNE;ligne++)
{
printf("*************************************************\n"); // premiere ligne
for (j=0;j<2;j++)
{
printf("* * * * * * * * *\n"); // 2/3lignes
}
for (colonne=0;colonne<NB_CASES_PAR_LIGNE;colonne++) // 4 lignes avec les valeurs
{
if (getCase(p,ligne,colonne)==1)
printf("* N ");
else if (getCase(p,ligne,colonne)==-1)
printf("* B ");
else
printf("* ");
}
printf("*\n");
for (j=0;j<2;j++) // 5/6 lignes
{
printf("* * * * * * * * *\n");
}
}
printf("*************************************************\n");
}
int priseDansDirectionPossible (struct partie *p, int ligne, int colonne, int horizontal, int vertical )
{
int pion;
if ((*p).premierJoueurJoue == 1)
pion = 1;
else
pion = -1;
//pion = -1;
int i = ligne + vertical;
int j = colonne + horizontal;
while (i >= 0 && j >= 0 && i<=NB_CASES_PAR_LIGNE && j<=NB_CASES_PAR_LIGNE)
{
int x = getCase(p,i,j);
if ( x == 0)
{
return 0;
}
else if ( x == pion )
{
return 0;
/*i=i+vertical;
j=j+horizontal;*/
}
else if ( x != pion )
{
i=i+vertical;
j=j+horizontal;
x = getCase(p,i,j);
if ( x == 0)
return 0;
else if ( x == pion )
return 1;
}
}
return 0;
}
int coupValide(struct partie *p, int ligne, int colonne)
{
int horizontal;
int vertical;
int x=getCase(p,ligne,colonne);
int val;
if (x==0) // si c'est une case vide
{
for (horizontal=-1;horizontal<2;horizontal++) // pour le parcours de -1 à 1
{
for (vertical=-1;vertical<2;vertical++) // pour le parcours de -1 à 1
{
if (horizontal!=0 || vertical!=0)
{
val=priseDansDirectionPossible (p,ligne,colonne,horizontal, vertical);
if (val==1)
return 1;
}
}
}
return 0;
}
else
return 0;
}
void mouvementDansDirection(struct partie *p, int ligne, int colonne, int horizontal, int vertical)
{
int x;
int res=priseDansDirectionPossible (p,ligne,colonne,horizontal,vertical );
if (res==1) // si la prise est possible c'est egale à 1
{
if ((*p).premierJoueurJoue==1) // si c'est le premier joueur (pion noir)
{
do
{
setCase(p,ligne,colonne,1);
colonne=colonne+horizontal;
ligne=ligne+vertical;
x=getCase(p,ligne,colonne);
}
while (x!=1);
}
else
{
do
{
setCase(p,ligne,colonne,-1);
colonne=colonne+horizontal;
ligne=ligne+vertical;
x=getCase(p,ligne,colonne);
}
while (x!=-1); // tant que getcase ne rencontre pas une case blanche... il y a la boucle pour manger les pions noirs
}
}
else
{
printf("mouvement pas possible\n");
}// erreur
}
void mouvement(struct partie *p, int ligne, int colonne)
{
int horizontal;
int vertical;
int x;
for (horizontal=-1;horizontal<2;horizontal++) // pour le parcours de -1 à 1
{
for (vertical=-1;vertical<2;vertical++) // pour le parcours de -1 à 1
{
if (horizontal!=0 || vertical!=0)
{
x=priseDansDirectionPossible (p,ligne,colonne,horizontal, vertical);
if (x==1)
mouvementDansDirection(p,ligne,colonne,horizontal,vertical);
}
}
}
}
int joueurPeutJouer(struct partie *p)
{
int ligne;
int colonne;
int x;
for (ligne=0;ligne<NB_CASES_PAR_LIGNE;ligne++)
{
for (colonne=0;colonne<NB_CASES_PAR_LIGNE; colonne++)
{
x=coupValide(p,ligne,colonne);
if (x==1)
{
return 1;
}
}
}
return 0;
}
//DEBUT PARTIE 3
int saisieJoueur(int *ligne,int *colonne)
{
char saisie[20];
printf("Veuillez saisir A pour abondonner , M pour retourner au menu principal , ou une case valide (num de la ligne entre a et h et num de colonne entre 1 et 8) : ");
scanf("%s",saisie);
int carac;
for (carac=0;saisie[carac]!='\0';carac++)//compte le nb de caractere
{
}
if (saisie[0]=='A' && carac ==1)
return -2;
else if (saisie[0]=='M'&& carac==1)
return -1;
else if (carac==2)
{
char i,j;
int l=0;
int c=0;
for (i='a';i<='h';i++)//boucle de 'a' à 'h' pour le premier caratcere
{
if (saisie[0]== i )
{
for (j='1';j<='8';j++)//boucle de '1' à '8' pour le 2eme caracteres
{
if (saisie[1]== j)
{
(*ligne)=l;//passage par adresse
(*colonne)=c;//passage par adresse
return 1;
}
c++;
}
}
l++;
}
}
else
return 0;
return 0;
}
int tourJoueur(struct partie *p)
{
affichage(p);
if ((*p).premierJoueurJoue==1)
printf("A %s de jouer:\n",(*p).nomJ1);
else
printf("A %s de jouer:\n",(*p).nomJ2);
if (joueurPeutJouer(p)==0)
{
changementJoueur(p);
return 0;
}
int ligne=-1;
int colonne=-1;
int saisie;
do
{
saisie=saisieJoueur(&ligne,&colonne);
printf("ligne:%d\n",ligne);
printf("colonne:%d\n",colonne);
}
while ((saisie==0) || (saisie==1 && (coupValide(p,ligne,colonne)==0)));//tant que saisie n'est pas 0 ou tant que les valeurs rentrées correspondent a un coup valide
if (saisie==1)
{
mouvement(p,ligne,colonne);
changementJoueur(p);
}
return saisie;
}
int gagnant(struct partie *p)
{
int p_blanc=0;
int p_noir=0;
int i;
for (i=0;i<NB_CASES;i++)//boucle sur tout le damier pour compter le nb de pion blanc/noir
{
if ((*p).damier[i]==1)
p_noir++;
else if ((*p).damier[i]==-1)
p_blanc++;
}
if (p_noir>p_blanc)
return 1;
else if (p_noir<p_blanc)
return -1;
else
return 0;
}
int FinPartie(struct partie *p)
{
if (joueurPeutJouer(p)==0)//si le joueur courant ne peut pas jouer
{
changementJoueur(p);
if (joueurPeutJouer(p)==0)//si le 2eme joueur aussi ne peut pas jouer donc aucun des 2 peut jouer
return 1;
}
else
return 0;
return 0;
}
int jouerPartie(struct partie *p)
{
int tour_J;
do
{
tour_J=tourJoueur(p);
}
while ((FinPartie(p)==0) && tour_J!=-1 && tour_J!=-2);//tant que la partie n'est pas finie et tant que le joueur rentrer des cases
if (tour_J==-1)
{
printf("Le joueur souhaite acceder au Menu Principal\n");
return 0;
}
else
{
printf("La partie est terminee\n");
return 1;
}
}
int main()
{
struct partie *p ;
p=creerPartie ();
/* PREMIER BLOC POUR TEST FONCTION Finpartie + gagnant
setCase(p,3,3,0);
setCase(p,3,4,0);
setCase(p,4,3,0);
affichage(p);
printf("Aucun des 2 joueurs ne peut jouer donc FinParite=%d\n",FinPartie(p));
setCase(p,3,3,-1);
setCase(p,3,4,1);
setCase(p,4,3,1);
affichage(p);
printf("Les joueurs sont a egalites d'ou gagnant=%d\n",gagnant(p));
printf("Les joueurs peuvent jouer donc FinPartie=%d\n",FinPartie(p));
setCase(p,0,0,1);
affichage(p);
printf("Le joueur 1 gagne d'ou gagnant=%d\n",gagnant(p));
setCase(p,0,1,-1);
setCase(p,0,2,-1);
affichage(p);
printf("Le joueur 2 gagne d'ou gagnant=%d\n",gagnant(p));
*/
/* SECOND BLOC POUR TEST la fonction saisieJoueur
int ligne,colonne,saisieJ;
saisieJ=saisieJoueur(ligne,colonne);
if(saisieJ==-2)
printf("le joueur Abandonne\n");
else if(saisieJ==-1)
printf("le joueur souhaite retourner au Menu Principal\n");
else if(saisieJ==1)
printf("Le joueur a saisi une case Valide\n");
else
printf("le joueur a saisi n'importe quoi\n");*/
/* TROISIEME BLOC POUR TEST la fonction tourJoueur
int tourJ=tourJoueur(p);
if(tourJ==-2)
printf("le joueur Abandonne\n");
else if(tourJ==-1)
printf("le joueur souhaite retourner au Menu Principal\n");
else if(tourJ==0)
printf("Le joueur ne peut pas joueur");
else{
printf("Le joueur a saisi une case Valide\n");
affichage(p);
}*/
// TEST LA FONCTION joueurPartie
int test=jouerPartie(p);
return 0;
}
<file_sep>#include <stdio.h> //Le PROJET
#include <stdlib.h>
//Question 1
#define TAILLE_CH 256 //Nombre de caractere maximal pour un nom
#define NB_CASES 64 // Nombre de case contenu dans un tableau d'entier
#define NB_CASES_PAR_LIGNE 8 // Nombre d'entier par ligne
//Question 2
struct partie
{
int damier[NB_CASES]; //Damier contenant 64 cases d'entier
char nomJ1[TAILLE_CH]; //Premier joueur
char nomJ2[TAILLE_CH]; //2eme joueur
int premierJoueurJoue; //premierJoueurJoue = 1 si 1er joueur joue sinon 0
};
//Question 3
int getCase(struct partie *p, int ligne, int colonne)
{
if ((ligne >= 0 && ligne <= (NB_CASES_PAR_LIGNE-1)) && (colonne >= 0 && colonne <= (NB_CASES_PAR_LIGNE-1)))
return (*p).damier[(NB_CASES_PAR_LIGNE * (ligne))+colonne]; // -1 pour pas aller sur la case d'a coter
else
printf("SAISIE INCORRECT ");
return 2;
}
//Question 4
void setCase(struct partie *p, int ligne, int colonne, int val)
{
if (ligne>=0 && ligne<=NB_CASES_PAR_LIGNE-1 && colonne>=0 && colonne<=NB_CASES_PAR_LIGNE-1 && val>=-1 && val<=1)
(*p).damier[(NB_CASES_PAR_LIGNE * (ligne))+colonne]=val;
else
printf("SAISIE INCORRECT");
}
//Question 5
void changementJoueur(struct partie *p)
{
if((*p).premierJoueurJoue==1)
(*p).premierJoueurJoue=0;
else
(*p).premierJoueurJoue=1;
}
//Question 6
struct partie* creerPartie ()
{
struct partie *p;
p = malloc (sizeof (struct partie));
if ( p == NULL )
{
printf("Allocation impossible ");
exit(1);
}
printf("Joueur 1 = ");
scanf("%s", (*p).nomJ1 ); //Demande le nom du 1er joueur
printf("Joueur 2 = ");
scanf("%s", (*p).nomJ2); //Demande le nom du 2eme joueur
(*p).premierJoueurJoue = 1; // Le premier joueur commence
int i;
for (i=0; i<NB_CASES; i++) //Tout les case sont a 0
(*p).damier[i]=0;
setCase(p,3,3,-1); //Initialise la case(3,3) a 1
setCase(p,3,4,1); //Initialise la case(3,4) a -1
setCase(p,4,3,1); //Initialise la case(4,3) a -1
setCase(p,4,4,-1); //Initialise la case(4,4) a 1
return p;
}
//Question 7
void affichage1(struct partie * p)
{
int i;
printf("\n");
for ( i = 0 ; i < NB_CASES ; i++)
{
if((*p).damier[i]==-1) //Si le contenu = -1, on diminu l'epase pour le "-"
printf(" %d ",(*p).damier[i]);
else
printf(" %d ",(*p).damier[i]);
if((i+1)%NB_CASES_PAR_LIGNE==0)
printf("\n\n");
}
}
void affichage2 (struct partie * p)
{
int i,j=0;
char N ='N';
char B ='B';
char RIEN = ' ';
printf ("\n");
for (i=0; i<NB_CASES_PAR_LIGNE; i++)
printf (" %d ", i);
printf("\n*****************************************************************\n");
printf("* * * * * * * * *\n");
for ( i = 0 ; i < NB_CASES ; i++)
{
if ((*p).damier[i] == (1))
printf ("* \033[31m%c\033[0m ", N);
else if ((*p).damier[i] == -1)
printf ("* \033[34m%c\033[0m ", B);
else if ((*p).damier[i] == 0)
printf ("* %c ",RIEN);
if((i+1)%NB_CASES_PAR_LIGNE==0)
{
printf("* %d\n* * * * * * * * *",j); //Le dernier point du tableau
printf("\n*****************************************************************\n"); // et afficher la ligne
if ( j < 7) //pour ne pas afficher la derniere ligne
{
printf("* * * * * * * * *\n");
j++;
}
}
}
}
//Question 8 PARTIE 2
int priseDansDirectionPossible (struct partie *p, int ligne, int colonne, int horizontal, int vertical )
{
int pion;
if ((*p).premierJoueurJoue == 1)
pion = 1;
else
pion = -1;
//pion = 1;
int i = ligne + vertical ;
int j = colonne + horizontal;
while (i >= 0 && j >= 0)
{
int x = getCase(p,i,j);
if ( x == 0)
{
return 0;
}
else if ( x == pion )
{
i=i+vertical;
j=j+horizontal;
}
else if ( x != pion )
{
i=i+vertical;
j=j+horizontal;
x = getCase(p,i,j);
if ( x == 0)
return 0;
else if ( x == pion )
return 1;
}
}
return 0;
}
//Question 9
int coupValide(struct partie *p, int ligne, int colonne)
{
int pion;
if ((*p).premierJoueurJoue == 1)
pion = 1;
else
pion = -1;
int horizontal;
int vertical;
int x=getCase(p,ligne,colonne);
int val;
if(x==0) // si c'est une case vide
{
for(horizontal=-1; horizontal<=1; horizontal++) // pour le parcours de -1 à 1
{
for(vertical=-1; vertical<=1; vertical++) // pour le parcours de -1 à 1
{
val=priseDansDirectionPossible (p,ligne,colonne,horizontal, vertical);
if(val==pion)
return 1;
}
}
return 0;
}
else
return 0;
}
//Question 10
void mouvementDansDirection(struct partie *p, int ligne, int colonne, int horizontal, int vertical)
{
int x;
int res=priseDansDirectionPossible (p,ligne,colonne,horizontal,vertical );
if(res==1) // si la prise est possible c'est egale à 1
{
if((*p).premierJoueurJoue==1) // si c'est le premier joueur (pion noir)
{
do
{
setCase(p,ligne,colonne,1);
colonne=colonne+horizontal;
ligne=ligne+vertical;
x=getCase(p,ligne,colonne);
}
while(x!=1);
}
else
{
do
{
setCase(p,ligne,colonne,-1);
colonne=colonne+horizontal;
ligne=ligne+vertical;
x=getCase(p,ligne,colonne);
}
while(x!=-1); // tant que getcase ne rencontre pas une case blanche... il y a la boucle pour manger les pions noirs
}
}
else
{
printf("mouvement pas possible\n");
}// erreur
}
//Question 11
void mouvement(struct partie *p, int ligne, int colonne)
{
int horizontal;
int vertical;
int x;
for(horizontal=-1; horizontal<2; horizontal++) // pour le parcours de -1 à 1
{
for(vertical=-1; vertical<2; vertical++) // pour le parcours de -1 à 1
{
x=priseDansDirectionPossible (p,ligne,colonne,horizontal, vertical);
if(x==1)
mouvementDansDirection(p,ligne,colonne,horizontal,vertical);
}
}
}
//Question 12
int joueurPeutJouer(struct partie *p)
{
int ligne,colonne;
int x;
for(ligne=0; ligne<NB_CASES_PAR_LIGNE-1 ; ligne++)
{
for(colonne=0; colonne<NB_CASES_PAR_LIGNE-1; colonne++)
{
x=coupValide(p,ligne,colonne);
if(x==1)
return 1;
}
}
return 0;
}
int main()
{
struct partie *p;
p = creerPartie();
//printf ("Valeur sur la case (0,5) : %d\n", getCase(p,0,5));
//printf ("Valeur sur la case (0,6) : %d\n", getCase(p,0,6));
//printf ("Valeur sur la case (5,3) : %d\n", getCase(p,5,3));
printf("\n");
//setCase(p,0,6,0);
//setCase(p,0,0,1);
//setCase(p,7,7,-1);
/*setCase(p,4,3,1); //Initialise la case(4,3) a 1
setCase(p,4,2,1);
setCase(p,4,5,1);
setCase(p,4,6,1);
setCase(p,4,7,1);
setCase(p,4,1,-1);
setCase(p,4,4,1);*/
setCase(p,2,2,1);// pour mouvementdansdirection ou mouvement
setCase(p,4,5,-1);// pour mouvement
setCase(p,3,5,1);// pour mouvement
affichage2(p);
printf("\n");
mouvement(p,5,5);// pour mouvement
//printf(" %d ",priseDansDirectionPossible(p,4,2,1,0));
//printf(" %d ",priseDansDirectionPossible(p,2,5,-1,1));
//printf(" %d ",priseDansDirectionPossible(p,4,0,1,0));
int x=joueurPeutJouer(p);
printf("\n joueur peut jouer: %d",x);
/*
int x = 0;
while(x == 0) // une boucle infini pour ne pas liberé p
{};
free(p);*/
return 0;
}
<file_sep># othello
Jeu othello en C (2014)

| a4eec157f0b3f781af927217d53d6afa05a7c349 | [
"Markdown",
"C"
] | 3 | C | KDini/othello | 00de897480ad667e20bc11db5c0c6e9003c0c6c7 | b6e67eebf616c4d8f3d38cfc135d00feba2a024b |
refs/heads/master | <file_sep>using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using PruebaAPI_FINAL.Context;
using PruebaAPI_FINAL.Models;
using Microsoft.EntityFrameworkCore;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace PruebaAPI_FINAL.Controllers
{
[Route("api/[controller]")]
public class BooksController : Controller
{
private readonly AppDBContext context;
public BooksController(AppDBContext context)
{
this.context= context;
}
// GET: api/<BooksController>
[HttpGet]
public ActionResult Get()
{
try
{
return Ok(context.Book.ToList());
}
catch(Exception ex)
{
return BadRequest(ex.Message);
}
}
// GET api/<BooksController>/5
[HttpGet("{id}", Name = "GetBook")]
public ActionResult Get(int id)
{
try
{
var gestor = context.Book.FirstOrDefault(g => g.IdBook == id);
return Ok(gestor);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
// POST api/<BooksController>
[HttpPost]
public ActionResult Post([FromBody] GestoresBD libro)
{
try
{
context.Book.Add(libro);
context.SaveChanges();
return CreatedAtRoute("GetBook", new { id = libro.IdBook }, libro);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
// PUT api/<BooksController>/5
[HttpPut("{id}")]
public ActionResult Put(int id, [FromBody] GestoresBD libro)
{
try
{
if (libro.IdBook == id)
{
context.Entry(libro).State = EntityState.Modified;
context.SaveChanges();
return CreatedAtRoute("GetBook", new { id = libro.IdBook }, libro);
}
else
{
return BadRequest();
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
// DELETE api/<BooksController>/5
[HttpDelete("{id}")]
public ActionResult Delete(int id)
{
try
{
var libro = context.Book.FirstOrDefault(g => g.IdBook == id);
if (libro != null)
{
context.Book.Remove(libro);
context.SaveChanges();
return Ok(id);
}
else
{
return BadRequest();
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace PruebaAPI_FINAL.Models
{
public class GestoresBD
{
[Key]
public int IdBook { get; set; }
public string Nombre { get; set; }
}
}
<file_sep>import './App.css';
import React,{useState,useEffect} from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import axios from 'axios'
import {Modal,ModalBody,ModalFooter,ModalHeader} from 'reactstrap'
function ListaCategoria() {
const URL = "https://localhost:44311/api/Books";
const [data,setData]= useState([])
const [modalInsertar, setModalInsertar]=useState(false);
const [modalEditar, setModalEditar]=useState(false);
const [modalEliminar, setModalEliminar]=useState(false);
const [gestorseleccionado, setGestorseleccionado] = useState({
idBook:'',
nombre:''
})
const handleChange=e=>{
const {name,value}=e.target;
setGestorseleccionado({
...gestorseleccionado,
[name]:value
})
console.log(gestorseleccionado);
}
const controlModalInsertar=()=>{
setModalInsertar(!modalInsertar)
}
const controlModalEditar=()=>{
setModalEditar(!modalEditar)
}
const controlModalEliminar=()=>{
setModalEliminar(!modalEliminar)
}
const peticionGet= async()=>{
await axios.get(URL)
.then(response =>{
setData(response.data);
}).catch(error=>{
console.log(error)
});
}
const peticionPost= async()=>{
delete gestorseleccionado.idBook
await axios.post(URL, gestorseleccionado)
.then(response =>{
setData(data.concat(response.data));
controlModalInsertar();
}).catch(error=>{
console.log(error)
});
}
const peticionPut= async()=>{
await axios.put(URL+"/"+gestorseleccionado.idBook, gestorseleccionado)
.then(response =>{
var respuesta = response.data;
var dataAux = data
dataAux.forEach(gestor =>{
if(gestor.idBook===gestorseleccionado.idBook)
{
if(gestor.idBook===gestorseleccionado.idBook)
{
gestor.nombre=respuesta.nombre;
}
}
})
controlModalEditar();
}).catch(error=>{
console.log(error)
});
}
const peticionDelete= async()=>{
await axios.delete(URL+"/"+gestorseleccionado.idBook)
.then(response =>{
setData(data.filter(gestor=> gestor.idBook!==response.data));
controlModalEliminar();
}).catch(error=>{
console.log(error)
});
}
const seleccionarGestor=(gestorr,caso)=>{
setGestorseleccionado(gestorr);
(caso==="Editar")?
controlModalEditar():controlModalEliminar() ;
}
useEffect(()=>{
peticionGet()
},[])
return (
<>
<div className="create">
<br/>
<button onClick={()=>controlModalInsertar()} className=" btn btn-success" style={{marginLeft:"10%"}}>Agregar Categoria</button>
<br/>
<br/>
<center>
<table className="table table-bordered" style={{width:"80%"}}>
<thead>
<tr>
<th> ID</th>
<th> Nombre</th>
<th> Acciones</th>
</tr>
</thead>
<tbody>
{data.map(g=>(
<tr key={g.id}>
<td>{g.idBook}</td>
<td>{g.nombre}</td>
<td>
<button className="btn btn-info" onClick={()=>seleccionarGestor(g,'Editar')}>Editar</button> {""}
<button className="btn btn-danger"onClick={()=>seleccionarGestor(g,'Eliminar')}>Eliminar</button>
</td>
</tr>
))}
</tbody>
</table>
</center>
<br/>
<br/>
<Modal isOpen={modalInsertar}>
<ModalHeader> Agregar Book</ModalHeader>
<ModalBody>
<div className="form-group">
<label>Nombre Book</label>
<br/>
<input type="text" className="form-control" name="nombre" onChange={handleChange}/>
</div>
</ModalBody>
<ModalFooter>
<button className="btn btn-primary" onClick={()=>peticionPost()}>Guardar</button> {""}
<button className="btn btn-danger" onClick={()=>controlModalInsertar()}>Cancelar</button>
</ModalFooter>
</Modal>
<Modal isOpen={modalEditar}>
<ModalHeader> Editar Book</ModalHeader>
<ModalBody>
<div className="form-group">
<label>ID:</label>
<input type="text" className="form-control" readOnly value ={gestorseleccionado && gestorseleccionado.idBook}/>
<label>Nombre Categoria:</label>
<br/>
<input type="text" className="form-control" name="nombre" onChange={handleChange} value ={gestorseleccionado && gestorseleccionado.nombre}/>
</div>
</ModalBody>
<ModalFooter>
<button className="btn btn-primary" onClick={()=>peticionPut()}>Editar</button> {""}
<button className="btn btn-danger" onClick={()=>controlModalEditar()}>Cancelar</button>
</ModalFooter>
</Modal>
<Modal isOpen={modalEliminar}>
<ModalBody>
Estas seguro que desea eliminar el Book {gestorseleccionado && gestorseleccionado.nombre} ?
</ModalBody>
<ModalFooter>
<button className="btn btn-primary"onClick={()=>peticionDelete()} >Si</button> {""}
<button className="btn btn-secondary" onClick={()=>controlModalEliminar()} >No</button>
</ModalFooter>
</Modal>
</div>
</>
);
}
export default ListaCategoria;<file_sep>create database PruebaTecnicaBF
use PruebaTecnicaBF
create table Book(
IdBook int identity primary key,
Nombre varchar(50)
)
select * from Book
insert into Book values ('El juidero')<file_sep>using Microsoft.EntityFrameworkCore;
using PruebaAPI_FINAL.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PruebaAPI_FINAL.Context
{
public class AppDBContext: DbContext
{
public AppDBContext(DbContextOptions<AppDBContext>options):base(options)
{
}
public DbSet<GestoresBD> Book { get; set; }
}
}
| 452b28f4d5c9fb2f019b84e6718e12ce318da14a | [
"JavaScript",
"C#",
"SQL"
] | 5 | C# | Jenrry14/PruebaBooks | 2d42cdd17911de334d6a6acc84b0698e8bde33bb | 58013074505990156ffccfe479e612f2c465843b |
refs/heads/master | <repo_name>douglascaurismo/test-repo-1<file_sep>/php-project/test2.php
<?php
//aaa
//aaabb | f9f2209e3e789c540fc754f523b1232248610b48 | [
"PHP"
] | 1 | PHP | douglascaurismo/test-repo-1 | 1ef618594aebab2af465ff444457161d6f147041 | d0116ea7fdf6fd6a63a934e0264379e980f60a16 |
refs/heads/master | <repo_name>SablinIgor/ejb.homework2<file_sep>/src/main/java/com/sablin/j2ee/model/Category.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.sablin.j2ee.model;
import java.util.Date;
/**
*
* @author Igor
*/
public class Category implements java.io.Serializable{
public Category(Long id, String name, String code, Date creationDate) {
this.id = id;
this.name = name;
this.code = code;
this.creationDate = creationDate;
}
private Long id;
private String name;
private String code;
private Date creationDate;
public Category(){}
/**
* @return the id
*/
public Long getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Long id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the code
*/
public String getCode() {
return code;
}
/**
* @param code the code to set
*/
public void setCode(String code) {
this.code = code;
}
/**
* @return the creationDate
*/
public Date getCreationDate() {
return creationDate;
}
/**
* @param creationDate the creationDate to set
*/
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
}
<file_sep>/README.md
# Курс: Java: технология Enterprise Java Beans 3.0
## Домашняя работа
## Автор: <NAME>
## Описание:
* Точка входа - index.html
* Создана таблица (JSP/Servlet)
* Колонки таблицы:
* Идентификатор
* Код
* Имя
* Дата создания
* Использован метод getCategories
* Servlet: DispatcherServlet
* В таблицу можно добавлять строки
* Из таблицы можно удалять строки
* Для категории отображается карточка категории с дополнительной информацией
* \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
* Добавлен компонент CalculatorBean с сервлетом CalcServlet
* Реализован функционал вычисления арифметических операций для двух переменных
* В базе данных хранится история вычислений
* История вычислений (последние 10 операций) отображается под формой ввода переменных
<file_sep>/src/main/java/com/sablin/j2ee/service/ProductCatalogBean.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.sablin.j2ee.service;
import com.sablin.j2ee.model.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.Singleton;
import javax.sql.DataSource;
/**
*
* @author Igor
*/
@Singleton
public class ProductCatalogBean {
@Resource(lookup="jdbc/MyResource")
private DataSource ds;
List<Category> AllCategories;
@PostConstruct
public void init(){
System.out.println("ProductCatalogBean.init");
AllCategories = new ArrayList();
UpdateCategories();
}
public Category getCategory(Long id){
System.out.println("ProductCatalogBean.getCategory");
Category result = new Category();
final String q = "select id, code, name, creation_date from public.product_category where id=?";
try (Connection c = ds.getConnection();
PreparedStatement ps = createCategoryStatement(c, q, id);
ResultSet r = ps.executeQuery()) {
if (r.next())
{
System.out.println("id: " +r.getLong("id"));
result.setId(r.getLong("id"));
result.setName(r.getString("name"));
result.setCode(r.getString("code"));
result.setCreationDate(r.getDate("creation_date"));
// return new Category(r.getLong("id"), r.getString("name"),r.getString("code"),r.getDate("creation_date"));
// r.getTimestamp()
//
}
}catch(SQLException exc){
exc.printStackTrace();
}
return result;
}
private static PreparedStatement createCategoryStatement( final Connection c,
final String s,
final Long id) throws SQLException{
PreparedStatement ps = c.prepareStatement(s);
ps.setLong(1, id);
return ps;
}
public List<Category> getCategories(){
System.out.println("ProductCatalogBean.getCategories");
return AllCategories;
}
public void UpdateCategories(){
System.out.println("ProductCatalogBean.UpdateCategories");
AllCategories.clear();
System.out.println("Лезем в базу " + new Date().toString() );
try (Connection c = ds.getConnection();
Statement s = c.createStatement();
ResultSet r = s.executeQuery("select id, code, name, creation_date from public.product_category");) {
while (r.next())
{
AllCategories.add(new Category(r.getLong("id"),r.getString("name"),r.getString("code"),r.getDate("creation_date")));
}
}catch(SQLException exc){
exc.printStackTrace();
}
}
// insert into product_category (code, name) values('xxx','YYY')
public void createCategory(final String name, final String code){
System.out.println("ProductCatalogBean.createCategory");
try (Connection c = ds.getConnection();
Statement s = c.createStatement();)
{
s.executeUpdate("insert into product_category (code, name) values('" + code + "','" + name +"')");
UpdateCategories();
}catch(SQLException exc){
exc.printStackTrace();
}
}
public void deleteCategory(final Long id){
System.out.println("ProductCatalogBean.deleteCategory");
try (Connection c = ds.getConnection();
Statement s = c.createStatement();)
{
s.executeUpdate("delete from product_category where id = " + id);
UpdateCategories();
}catch(SQLException exc){
exc.printStackTrace();
}
}
}
<file_sep>/src/main/java/com/sablin/j2ee/service/CalcServlet.java
package com.sablin.j2ee.service;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "CalcServlet", urlPatterns = {"/calculator"})
public class CalcServlet extends HttpServlet {
@Inject
CalculatorBean calc;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String p_v1 = request.getParameter("v1");
String p_v2 = request.getParameter("v2");
String p_operator = request.getParameter("operator");
if (p_v1 == null || p_v2 == null || p_operator == null) {
System.out.println("Go to calc");
request.setAttribute("operations", calc.getListOperations());
getServletContext().getRequestDispatcher("/mycalc.jsp").forward(request, response);
} else {
double v1 = Double.parseDouble(p_v1);
double v2 = Double.parseDouble(p_v2);
double answer = calc.calculate(v1, v2, p_operator);
calc.saveToLog(p_v1, p_v2, p_operator, String.valueOf(answer) );
request.setAttribute("res", answer);
request.setAttribute("last_v1", p_v1);
request.setAttribute("last_v2", p_v2);
request.setAttribute("last_operator", p_operator);
request.setAttribute("operations", calc.getListOperations());
getServletContext().getRequestDispatcher("/mycalc.jsp").forward(request, response);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
}
| 4a3d3faeead6396fe559f55c61dbf7d5e45106c1 | [
"Markdown",
"Java"
] | 4 | Java | SablinIgor/ejb.homework2 | 2b5e2a340ae792bdee7410ad9bbb916db2ff100a | 5777ca582a1d1ae05e3e1f8c2c2dcd6ae8dee46d |
refs/heads/master | <repo_name>lleses/yudilong<file_sep>/src/main/java/com/dl/comm/utils/IdUtil.java
package com.dl.comm.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
/**
* ID工具
*/
public class IdUtil {
/**
* 根据当前时间生成32位ID
*
* @return yyyyMMddHHmmssSSS+ranNum(15)
*/
public static String id32() {
return secId(32);
}
/**
* ID 生成 - 按时间生成,yyyyMMddHHmmssSSS(17位)+(len-17)位随机数字
*
* @param len
* 长度,超过17的填充随机数字
* @return 指定长度的数字字符串
*/
private static String secId(int len) {
StringBuilder id = new StringBuilder();
id.append(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()));
int l = len - 17;
if (l > 0) {
id.append(ranNum(l));
return id.toString();
} else {
return id.substring(0, len);
}
}
/**
* 生成随机数字字符串
*
* @param len
* 字符串长度
* @return
*/
private static String ranNum(int len) {
char[] ncArrs = new char[]{'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
int ncArrsLength = ncArrs.length;
if (len < 1) {
return "";
}
StringBuffer str = new StringBuffer();
for (int i = 0; i < len; i++) {
str.append(ncArrs[new Random().nextInt(ncArrsLength)]);
}
return str.toString();
}
}<file_sep>/src/main/java/com/dl/modules/mode/order/OrderStrategy.java
package com.dl.modules.mode.order;
import com.dl.comm.result.Result;
public interface OrderStrategy {
Result addOrder(OrderDto order);
}<file_sep>/src/main/java/com/dl/comm/config/Constant.java
package com.dl.comm.config;
import com.dl.comm.utils.SpringUtil;
/**
* 常量配置类
*/
public class Constant {
public static final class OSS {
public static final String ENDPOINT = getProperty("oss.endpoint");
public static final String ACCESSKEY = getProperty("oss.accessKey");
public static final String ACCESSKEY_SECRET = getProperty("oss.accesskeysecret");
public static final String BUCKET_NAME = getProperty("oss.bucketname");
public static final String BASEURL = getProperty("oss.baseurl");
}
protected static String getProperty(String name) {
return SpringUtil.getApplicationContext().getEnvironment().getProperty(name);
}
}
<file_sep>/src/test/java/com/dl/modules/demo/LoggerTest.java
package com.dl.modules.demo;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
@Slf4j
public class LoggerTest{
@Test
public void test1() {
log.info("info 11111");
log.debug("debug 1111");
log.error("error 11111");
}
}
<file_sep>/src/main/java/com/dl/modules/demo/dao/CgoodsDao.java
package com.dl.modules.demo.dao;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.dl.modules.demo.entity.CgoodsTemplate;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
@DS("slave")
public interface CgoodsDao extends BaseMapper<CgoodsTemplate> {
List<CgoodsTemplate> getAll();
}
<file_sep>/src/main/java/com/dl/comm/oss/OSSUtil.java
package com.dl.comm.oss;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.dl.comm.config.Constant;
import java.io.File;
/**
* OSS工具类
*/
public class OSSUtil {
/** 过期时间(10年) */
private static final int CACHE_CONTROL_EXPIRE = 10 * 365 * 24 * 60 * 60;
/**
* 文件上传到oss
*
* @param oosPath - oos文件路径
* @param file
*/
public static final void fileUpload(String oosPath, File file) {
OSS ossClient = new OSSClientBuilder().build(Constant.OSS.ENDPOINT, Constant.OSS.ACCESSKEY, Constant.OSS.ACCESSKEY_SECRET);// 创建OSSClient实例
try {
ObjectMetadata meta = new ObjectMetadata();
meta.setCacheControl("public, max-age=" + CACHE_CONTROL_EXPIRE);
ossClient.putObject(Constant.OSS.BUCKET_NAME, oosPath, file);
} finally {
ossClient.shutdown();// 关闭OSSClient
}
}
}
<file_sep>/src/test/java/com/dl/modules/demo/UserTest.java
package com.dl.modules.demo;
import com.dl.ApplicationTest;
import com.dl.modules.demo.dao.UserDao;
import com.dl.modules.demo.entity.Eds2TvUser;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.time.LocalDateTime;
import java.util.List;
public class UserTest extends ApplicationTest {
@Autowired
private UserDao userDao;
@Test
public void add() {
Eds2TvUser user = new Eds2TvUser();
// user.setUserId(1112l);
user.setMobile("1213");
user.setStoreId("11111");
user.setAccessToken("xxx");
user.setMachineCode("ttt");
user.setCreateTime(LocalDateTime.now());
user.setUpdateTime(LocalDateTime.now());
userDao.insert(user);
System.out.println(user);
}
@Test
public void get() {
Eds2TvUser user = userDao.selectById("1149166740237045761");
System.out.println(user);
}
@Test
public void getList() {
PageHelper.startPage(1, 2);
List<Eds2TvUser> list = userDao.getUser();
PageInfo<Eds2TvUser> page = new PageInfo<>(list);
System.out.println(page);
}
}
<file_sep>/src/test/java/com/dl/ApplicationTest.java
package com.dl;
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
* 加入原因:websocket是需要依赖tomcat等容器的启动。所以在测试过程中我们要真正的启动一个tomcat作为容器。
*
* WebAppConfiguration
* 由于是Web项目,Junit需要模拟ServletContext,因此我们需要给我们的测试类加上@WebAppConfiguration。
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
//@WebAppConfiguration
public class ApplicationTest {
private long begin;
@Before
public void before() {
begin = System.currentTimeMillis();
}
@After
public void after() {
long time = System.currentTimeMillis() - begin;
System.out.println("总耗时:" + time + "ms");
}
}
| d09354d2ed719faa55a817c775b872807a92cf60 | [
"Java"
] | 8 | Java | lleses/yudilong | 2e76abc88e2a91edb5ca7917761a4e96bdb95239 | a15c1471617f6619b2d7d7127f45ed2162c7f115 |
refs/heads/master | <file_sep>module.exports = function(dot) {
if (dot.version) {
return
}
dot("dependencies", "version", {
arg: [
"@dot-event/args",
"@dot-event/glob",
"@dot-event/store",
"@dot-event/wait",
],
})
dot("args", "version", {
paths: {
alias: ["_", "p"],
default: [],
},
})
require("./versionProject")(dot)
dot.any("version", version)
}
async function version(prop, arg, dot) {
const paths = await dot.glob(prop, {
absolute: true,
pattern: arg.paths,
})
return Promise.all(
paths.map(
async path =>
await dot.versionProject(prop, {
...arg,
path,
paths,
})
)
)
}
<file_sep># @dot-event/version
dot-event package.json versioning

| b41364afa3079c037ef981edd7ffaa11103ea1f8 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | dot-event/version | f37f6d60361a873553222cdbbeccb166eb8aba94 | 31683ac5679190956f68d068feac32d92a563862 |
refs/heads/master | <repo_name>shirokurostone/shirokurostone-mail-xoauth2<file_sep>/lib/shirokurostone/mail/xoauth2.rb
require "net/imap"
require "net/smtp"
require "base64"
require "shirokurostone/mail/xoauth2/version"
module Net
class IMAP
def authenticate_xoauth2(user, secret)
send_command('AUTHENTICATE', 'XOAUTH2', Base64.strict_encode64("user=#{user}\x01auth=Bearer #{secret}\x01\x01"))
end
end
class SMTP
def auth_xoauth2(user, secret)
check_auth_args(user, secret)
res = critical {
get_response("AUTH XOAUTH2 "+Base64.strict_encode64("user=#{user}\x01auth=Bearer #{secret}\x01\x01"))
}
check_auth_response(res)
res
end
end
end
<file_sep>/lib/shirokurostone/mail/xoauth2/version.rb
module Shirokurostone
module Mail
module Xoauth2
VERSION = "0.1.0"
end
end
end
| 0324d332f97d3b2c3f50083c5a7f98870fee843e | [
"Ruby"
] | 2 | Ruby | shirokurostone/shirokurostone-mail-xoauth2 | ffb67337d35efb2a7ebf8a3a95049002a7c6bfff | e74f02bc828f904854edc0556063829693062157 |
refs/heads/master | <file_sep>import React from "react";
import { render, fireEvent } from "@testing-library/react";
import Card from "./Card";
it('renders without crashing', ()=> {
render(<Card caption={"test"}
src={'http://test'}
currNum={1}
totalNum={3} />)
});
it('matches snapshot', () => {
const { asFragment } = render(<Card caption={"test"}
src={'http://test'}
currNum={1}
totalNum={3} />);
expect(asFragment()).toMatchSnapshot();
}) | 68807d9e8005b5b381a9a55a79d863cbf73dbbfb | [
"JavaScript"
] | 1 | JavaScript | jakejg/react-state-image-carousel | f025d8747c02cc7e7cb2c709e0637b21bbfe966b | 68f61499a1e97d793b3bc0bb78d2b609ee6191d3 |
refs/heads/master | <file_sep>plot1 <- function(location="plot1.png") {
source("read_data.R")
data <- read_data("data\\household_power_consumption.txt")
png(filename=location, width=480, height=480)
hist(data$Global_active_power, main="Global Active Power",
col="red", xlab="Global Active Power (kilowatts)")
invisible(dev.off() )
}
<file_sep># Since I have enough memory available I read all at once
read_data <- function(file_path) {
# define the column types
df <- read.csv(file_path, header=TRUE, sep=";", na.strings = "?")
# datetime for plot 2
df$datetime <- strptime(paste(df$Date, df$Time, sep=" "),
format="%d/%m/%Y %H:%M:%S")
df$Date <- as.Date(df$Date , "%d/%m/%Y")
df$Time <- strptime(df$Time, format="%H:%M:%S")
# Subsetting
df <- subset(df, df$Date == '2007-02-01' | df$Date == '2007-02-02')
df
}<file_sep>plot4 <- function(location="plot4.png") {
source("read_data.R")
data <- read_data("data\\household_power_consumption.txt")
Sys.setlocale(category = "LC_TIME", locale = "C")
png(filename=location, width=480, height=480)
par(mfrow = c(2, 2))
with(data, {
plot(datetime, Global_active_power, type="l", xlab="", ylab="Global Active Power (kilowatts)")
plot(datetime, Voltage, type="l", ylab="Voltage")
plot(data$datetime, data$Sub_metering_1, type="n", xlab="", ylab="Energy sub metering")
lines(data$datetime, data$Sub_metering_1, col="black")
lines(data$datetime, data$Sub_metering_2, col="red")
lines(data$datetime, data$Sub_metering_3, col="blue")
legend("topright", bty = "n", col = c("black", "red", "blue"), lty=1, legend=c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"))
plot(datetime, Global_reactive_power, type="l")
})
invisible(dev.off() )
}<file_sep>plot2 <- function(location="plot2.png") {
source("read_data.R")
data <- read_data("data\\household_power_consumption.txt")
Sys.setlocale(category = "LC_TIME", locale = "C")
png(filename=location, width=480, height=480)
plot(data$datetime, data$Global_active_power, type="l",
xlab="", ylab="Global Active Power (kilowatts)")
invisible(dev.off() )
} | 6d3258398be037ccc4294145a91f46eb80dab99e | [
"R"
] | 4 | R | RogerKaufmann/ExData_Plotting1 | 47e8bdbc85c2b5c9a5720380b3c0388c2ccdacc7 | b53d4fddea65a820a92f23cbcceb2768155943a3 |
refs/heads/master | <repo_name>swethanayani/CodingExcersice<file_sep>/com-ncr-chess/src/main/java/com/ncr/chess/ChessBoard.java
package com.ncr.chess;
public class ChessBoard {
public static int MAX_BOARD_WIDTH = 7;
public static int MAX_BOARD_HEIGHT = 7;
public Pawn[][] pieces;
public ChessBoard() {
pieces = new Pawn[MAX_BOARD_WIDTH][MAX_BOARD_HEIGHT];
}
/**
* Adds piece to the chessboard when positions are legal
*
* @param pawn
* @param xCoordinate
* @param yCoordinate
* @param pieceColor
*/
public void addPiece(Pawn pawn, int xCoordinate, int yCoordinate, PieceColor pieceColor) {
if (isLegalBoardPosition(xCoordinate, yCoordinate) && pieces[xCoordinate][yCoordinate] == null) {
pawn.setXCoordinate(xCoordinate);
pawn.setYCoordinate(yCoordinate);
pieces[xCoordinate][yCoordinate] = pawn;
System.out.println("Inserted piece at x:" + pawn.getXCoordinate() + " and y:" + pawn.getYCoordinate());
} else {
System.out.println("Cannot Inserted piece at x:" + xCoordinate + " and y:" + yCoordinate);
pawn.setXCoordinate(-1);
pawn.setYCoordinate(-1);
}
}
/**
* this method checks if the position is legal as per length of chessboard
* defined
*
* @param xCoordinate
* @param yCoordinate
* @return
*/
public boolean isLegalBoardPosition(int xCoordinate, int yCoordinate) {
if ((xCoordinate >= 0 && xCoordinate < MAX_BOARD_WIDTH)
&& (yCoordinate >= 0 && yCoordinate < MAX_BOARD_HEIGHT)) {
System.out.println("Legal board position to insert piece");
return true;
} else {
System.out.println("Not legal board position to insert piece");
return false;
}
}
}
| 4b592ba570dc02d5509a0fac8c123e7ae9fdd20a | [
"Java"
] | 1 | Java | swethanayani/CodingExcersice | d78a4ff4ee98011d13b00ebcf5c13cff1ff7c147 | 0291262661b9cc53e40298909bf41bda6fd5622d |
refs/heads/master | <repo_name>DurriyaVasi/barcraft<file_sep>/A1.cpp
#include "A1.hpp"
#include "cs488-framework/GlErrorCheck.hpp"
#include <iostream>
#include <imgui/imgui.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <map>
using namespace glm;
using namespace std;
static const size_t DIM = 16;
//----------------------------------------------------------------------------------------
// Constructor
A1::A1()
: current_col( 0 ), gridInfo(DIM), currX(0.0f), currY(0.0f), shiftKeyPressed(false), mousePressed(false), oldY(8)
{
}
//----------------------------------------------------------------------------------------
// Destructor
A1::~A1()
{}
//----------------------------------------------------------------------------------------
/*
* Called once, at program start.
*/
void A1::init()
{
// Set the background colour.
glClearColor( 0.3, 0.5, 0.7, 1.0 );
// Build the shader
m_shader.generateProgramObject();
m_shader.attachVertexShader(
getAssetFilePath( "VertexShader.vs" ).c_str() );
m_shader.attachFragmentShader(
getAssetFilePath( "FragmentShader.fs" ).c_str() );
m_shader.link();
// Set up the uniforms
P_uni = m_shader.getUniformLocation( "P" );
V_uni = m_shader.getUniformLocation( "V" );
M_uni = m_shader.getUniformLocation( "M" );
col_uni = m_shader.getUniformLocation( "colour" );
initGrid();
initCube();
initSquare();
// Set up initial view and projection matrices (need to do this here,
// since it depends on the GLFW window being set up correctly).
view = glm::lookAt(
glm::vec3( 0.0f, float(DIM)*2.0*M_SQRT1_2, float(DIM)*2.0*M_SQRT1_2 ),
glm::vec3( 0.0f, 0.0f, 0.0f ),
glm::vec3( 0.0f, 1.0f, 0.0f ) );
proj = glm::perspective(
glm::radians( 45.0f ),
float( m_framebufferWidth ) / float( m_framebufferHeight ),
1.0f, 1000.0f );
}
void A1::reset()
{
current_col = 0;
gridInfo.reset();
currX = 0;
currY = 0;
oldRotate = mat4(1.0f);
oldY = 8;
}
void A1::initCube()
{
float vertices[] = {
0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f,
1.0f, 0.0f, 0.0f,
1.0f, 1.0f, 0.0f,
0.0f, 0.0f, 1.0f,
0.0f, 1.0f, 1.0f,
1.0f, 0.0f, 1.0f,
1.0f, 1.0f, 1.0f
};
unsigned int indices[] = { // note that we start from 0!
0, 1, 3, // bottom
0, 2, 3, // bottom
2, 6, 3, // side front
3, 7, 6,
1, 5, 3, // side right
3, 5, 7,
0, 2, 6, // side left
0, 4, 6,
0, 1, 5, // side back
0, 4, 5,
4, 6, 7, // top
4, 5, 7
};
// Create the vertex array to record buffer assignments.
glGenVertexArrays( 1, &m_cube_vao );
glBindVertexArray( m_cube_vao );
// Create the cube vertex buffer
glGenBuffers( 1, &m_cube_vbo );
glBindBuffer( GL_ARRAY_BUFFER, m_cube_vbo );
glBufferData( GL_ARRAY_BUFFER, sizeof(vertices),
vertices, GL_STATIC_DRAW );
glGenBuffers( 1, &m_cube_ebo );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, m_cube_ebo );
glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof(indices),
indices, GL_STATIC_DRAW );
// Specify the means of extracting the position values properly.
GLint posAttrib = m_shader.getAttribLocation( "position" );
glEnableVertexAttribArray( posAttrib );
glVertexAttribPointer( posAttrib, 3, GL_FLOAT, GL_FALSE, 0, nullptr );
// Reset state to prevent rogue code from messing with *my*
// stuff!
glBindVertexArray( 0 );
glBindBuffer( GL_ARRAY_BUFFER, 0 );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
CHECK_GL_ERRORS;
};
void A1::initSquare()
{
float vertices[] = {
0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 1.0f
};
unsigned int indices[] = {
0, 1, 3,
0, 2, 3
};
glGenVertexArrays( 1, &m_square_vao);
glBindVertexArray(m_square_vao);
glGenBuffers(1, &m_square_vbo);
glBindBuffer(GL_ARRAY_BUFFER, m_square_vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW );
glGenBuffers(1, &m_square_ebo);
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, m_square_ebo);
glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
GLint posAttrib = m_shader.getAttribLocation("position");
glEnableVertexAttribArray(posAttrib);
glVertexAttribPointer( posAttrib, 3, GL_FLOAT, GL_FALSE, 0, nullptr );
glBindVertexArray(0);
glBindBuffer( GL_ARRAY_BUFFER, 0 );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
CHECK_GL_ERRORS;
};
void A1::initGrid()
{
size_t sz = 3 * 2 * 2 * (DIM+3);
float *verts = new float[ sz ];
size_t ct = 0;
for( int idx = 0; idx < DIM+3; ++idx ) {
verts[ ct ] = -1;
verts[ ct+1 ] = 0;
verts[ ct+2 ] = idx-1;
verts[ ct+3 ] = DIM+1;
verts[ ct+4 ] = 0;
verts[ ct+5 ] = idx-1;
ct += 6;
verts[ ct ] = idx-1;
verts[ ct+1 ] = 0;
verts[ ct+2 ] = -1;
verts[ ct+3 ] = idx-1;
verts[ ct+4 ] = 0;
verts[ ct+5 ] = DIM+1;
ct += 6;
}
// Create the vertex array to record buffer assignments.
glGenVertexArrays( 1, &m_grid_vao );
glBindVertexArray( m_grid_vao );
// Create the cube vertex buffer
glGenBuffers( 1, &m_grid_vbo );
glBindBuffer( GL_ARRAY_BUFFER, m_grid_vbo );
glBufferData( GL_ARRAY_BUFFER, sz*sizeof(float),
verts, GL_STATIC_DRAW );
// Specify the means of extracting the position values properly.
GLint posAttrib = m_shader.getAttribLocation( "position" );
glEnableVertexAttribArray( posAttrib );
glVertexAttribPointer( posAttrib, 3, GL_FLOAT, GL_FALSE, 0, nullptr );
// Reset state to prevent rogue code from messing with *my*
// stuff!
glBindVertexArray( 0 );
glBindBuffer( GL_ARRAY_BUFFER, 0 );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
// OpenGL has the buffer now, there's no need for us to keep a copy.
delete [] verts;
CHECK_GL_ERRORS;
}
//----------------------------------------------------------------------------------------
/*
* Called once per frame, before guiLogic().
*/
void A1::appLogic()
{
// Place per frame, application logic here ...
}
//----------------------------------------------------------------------------------------
/*
* Called once per frame, after appLogic(), but before the draw() method.
*/
void A1::guiLogic()
{
// We already know there's only going to be one window, so for
// simplicity we'll store button states in static local variables.
// If there was ever a possibility of having multiple instances of
// A1 running simultaneously, this would break; you'd want to make
// this into instance fields of A1.
static bool showTestWindow(false);
static bool showDebugWindow(true);
ImGuiWindowFlags windowFlags(ImGuiWindowFlags_AlwaysAutoResize);
float opacity(0.5f);
ImGui::Begin("Debug Window", &showDebugWindow, ImVec2(100,100), opacity, windowFlags);
if( ImGui::Button( "Quit Application" ) ) {
glfwSetWindowShouldClose(m_window, GL_TRUE);
}
if( ImGui::Button( "Reset" ) ) {
reset();
}
// Eventually you'll create multiple colour widgets with
// radio buttons. If you use PushID/PopID to give them all
// unique IDs, then ImGui will be able to keep them separate.
// This is unnecessary with a single colour selector and
// radio button, but I'm leaving it in as an example.
// Prefixing a widget name with "##" keeps it from being
// displayed.
for (int i = 0; i < 8; i++) {
ImGui::PushID( i );
ImGui::ColorEdit3( "##Colour", colours[i] );
ImGui::SameLine();
if( ImGui::RadioButton( "##Col", ¤t_col, i ) ) {
if (gridInfo.getHeight(currX, currY) > 0) {
gridInfo.setColour(currX, currY, current_col);
}
}
ImGui::PopID();
}
/*
// For convenience, you can uncomment this to show ImGui's massive
// demonstration window right in your application. Very handy for
// browsing around to get the widget you want. Then look in
// shared/imgui/imgui_demo.cpp to see how it's done.
if( ImGui::Button( "Test Window" ) ) {
showTestWindow = !showTestWindow;
}
*/
ImGui::Text( "Framerate: %.1f FPS", ImGui::GetIO().Framerate );
ImGui::End();
if( showTestWindow ) {
ImGui::ShowTestWindow( &showTestWindow );
}
}
void A1::drawCubes(mat4 W, mat4 S) {
for (int i = 0; i < DIM; i++) {
for (int j = 0; j < DIM; j++) {
int height = gridInfo.getHeight(i, j);
if (height == 0) {
continue;
}
for (int k = 0; k < height; k++) {
mat4 T = glm::translate(W, vec3(i, k, j));
glUniformMatrix4fv( M_uni, 1, GL_FALSE, value_ptr( S * oldRotate * T) );
int colourIndex = gridInfo.getColour(i, j);
glUniform3f( col_uni, colours[colourIndex][0], colours[colourIndex][1], colours[colourIndex][2] );
glDrawElements( GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0);
}
}
}
}
//----------------------------------------------------------------------------------------
/*
* Called once per frame, after guiLogic().
*/
void A1::draw()
{
// Create a global transformation for the model (centre it).
mat4 W;
mat4 S;
W = glm::translate( W, vec3( -float(DIM)/2.0f, 0, -float(DIM)/2.0f ) );
float scaleAmount = ((float)oldY)/(8.0f);
S = glm::scale(S, vec3(scaleAmount, scaleAmount, scaleAmount));
m_shader.enable();
glEnable( GL_DEPTH_TEST );
glUniformMatrix4fv( P_uni, 1, GL_FALSE, value_ptr( proj ) );
glUniformMatrix4fv( V_uni, 1, GL_FALSE, value_ptr( view ) );
glUniformMatrix4fv( M_uni, 1, GL_FALSE, value_ptr( S * oldRotate * W ) );
// Just draw the grid for now.
glBindVertexArray( m_grid_vao );
glUniform3f( col_uni, 1, 1, 1 );
glDrawArrays( GL_LINES, 0, (3+DIM)*4 );
// Draw the cubes
glBindVertexArray( m_cube_vao );
drawCubes(W, S);
// Highlight the active square.
glDisable( GL_DEPTH_TEST );
glBindVertexArray(m_square_vao);
W = glm::translate( W, vec3(currX, gridInfo.getHeight(currX, currY), currY));
glUniformMatrix4fv( M_uni, 1, GL_FALSE, value_ptr( S * oldRotate * W ) );
glUniform3f( col_uni, 0, 0, 0 );
glDrawElements( GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
m_shader.disable();
// Restore defaults
glBindVertexArray( 0 );
CHECK_GL_ERRORS;
}
//----------------------------------------------------------------------------------------
/*
* Called once, after program is signaled to terminate.
*/
void A1::cleanup()
{}
//----------------------------------------------------------------------------------------
/*
* Event handler. Handles cursor entering the window area events.
*/
bool A1::cursorEnterWindowEvent (
int entered
) {
bool eventHandled(false);
// Fill in with event handling code...
return eventHandled;
}
//----------------------------------------------------------------------------------------
/*
* Event handler. Handles mouse cursor movement events.
*/
bool A1::mouseMoveEvent(double xPos, double yPos)
{
bool eventHandled(false);
if (!ImGui::IsMouseHoveringAnyWindow()) {
// Put some code here to handle rotations. Probably need to
// check whether we're *dragging*, not just moving the mouse.
// Probably need some instance variables to track the current
// rotation amount, and maybe the previous X position (so
// that you can rotate relative to the *change* in X.
if (mousePressed) {
double xDiff = xPos - oldX;
oldRotate = glm::rotate( oldRotate, glm::radians(((float)xDiff)/2), glm::vec3(0.0f, 1.0f, 0.0f)) ;
}
oldX = xPos;
eventHandled = true;
}
return eventHandled;
}
//----------------------------------------------------------------------------------------
/*
* Event handler. Handles mouse button events.
*/
bool A1::mouseButtonInputEvent(int button, int actions, int mods) {
bool eventHandled(false);
if (actions == GLFW_RELEASE && button == GLFW_MOUSE_BUTTON_LEFT) {
mousePressed = false;
eventHandled = true;
}
if (!ImGui::IsMouseHoveringAnyWindow()) {
// The user clicked in the window. If it's the left
// mouse button, initiate a rotation.
if (button == GLFW_MOUSE_BUTTON_LEFT && actions == GLFW_PRESS) {
mousePressed = true;
eventHandled = true;
// oldX = ????
}
}
return eventHandled;
}
//----------------------------------------------------------------------------------------
/*
* Event handler. Handles mouse scroll wheel events.
*/
bool A1::mouseScrollEvent(double xOffSet, double yOffSet) {
bool eventHandled(false);
double max = 16;
double min = 4;
if (yOffSet + oldY > max) {
oldY = max;
}
if (yOffSet + oldY < min) {
oldY = min;
}
else {
oldY = yOffSet + oldY;
}
return eventHandled;
}
//----------------------------------------------------------------------------------------
/*
* Event handler. Handles window resize events.
*/
bool A1::windowResizeEvent(int width, int height) {
bool eventHandled(false);
// Fill in with event handling code...
return eventHandled;
}
//----------------------------------------------------------------------------------------
/*
* Event handler. Handles key input events.
*/
bool A1::keyInputEvent(int key, int action, int mods) {
bool eventHandled(false);
if (action == GLFW_RELEASE && (key == GLFW_KEY_RIGHT_SHIFT || key == GLFW_KEY_LEFT_SHIFT)) {
shiftKeyPressed = false;
eventHandled = true;
}
// Fill in with event handling code...
if( action == GLFW_PRESS ) {
if (key == GLFW_KEY_RIGHT_SHIFT || key == GLFW_KEY_LEFT_SHIFT) {
shiftKeyPressed = true;
eventHandled = true;
}
if (key == GLFW_KEY_UP) {
if (currY == 0) {
eventHandled = true;
}
else {
if (shiftKeyPressed) {
gridInfo.setHeight(currX, currY - (1.0), gridInfo.getHeight(currX, currY));
gridInfo.setColour(currX, currY - (1.0), gridInfo.getColour(currX, currY));
}
currY = currY - (1.0);
eventHandled = true;
}
}
if (key == GLFW_KEY_DOWN) {
if (currY == (DIM - 1)) {
eventHandled = true;
}
else {
if (shiftKeyPressed) {
gridInfo.setHeight(currX, currY + (1.0), gridInfo.getHeight(currX, currY));
gridInfo.setColour(currX, currY + (1.0), gridInfo.getColour(currX, currY));
}
currY = currY + (1.0);
eventHandled = true;
}
}
if (key == GLFW_KEY_LEFT) {
if (currX == 0) {
eventHandled = true;
}
else {
if (shiftKeyPressed) {
gridInfo.setHeight(currX - (1.0), currY, gridInfo.getHeight(currX, currY));
gridInfo.setColour(currX - (1.0), currY, gridInfo.getColour(currX, currY));
}
currX = currX - (1.0);
eventHandled = true;
}
}
if (key == GLFW_KEY_RIGHT) {
if (currX == (DIM - 1)) {
eventHandled = true;
}
else {
if (shiftKeyPressed) {
gridInfo.setHeight(currX + (1.0), currY, gridInfo.getHeight(currX, currY));
gridInfo.setColour(currX + (1.0), currY, gridInfo.getColour(currX, currY));
}
currX = currX + (1.0);
eventHandled = true;
}
}
if (key == GLFW_KEY_SPACE) {
int oldHeight = gridInfo.getHeight(currX, currY);
if (oldHeight == 0) {
gridInfo.setColour(currX, currY, current_col);
}
gridInfo.setHeight(currX, currY, oldHeight + 1);
eventHandled = true;
}
if (key == GLFW_KEY_BACKSPACE) {
int oldHeight = gridInfo.getHeight(currX, currY);
if (oldHeight > 0) {
gridInfo.setHeight(currX, currY, oldHeight - 1);
}
eventHandled = true;
}
if (key == GLFW_KEY_Q) {
glfwSetWindowShouldClose(m_window, GL_TRUE);
eventHandled = true;
}
if (key == GLFW_KEY_R) {
reset();
eventHandled = true;
}
}
return eventHandled;
}
<file_sep>/A1.hpp
#pragma once
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "cs488-framework/CS488Window.hpp"
#include "cs488-framework/OpenGLImport.hpp"
#include "cs488-framework/ShaderProgram.hpp"
#include "grid.hpp"
class A1 : public CS488Window {
public:
A1();
virtual ~A1();
protected:
virtual void init() override;
virtual void appLogic() override;
virtual void guiLogic() override;
virtual void draw() override;
virtual void cleanup() override;
virtual bool cursorEnterWindowEvent(int entered) override;
virtual bool mouseMoveEvent(double xPos, double yPos) override;
virtual bool mouseButtonInputEvent(int button, int actions, int mods) override;
virtual bool mouseScrollEvent(double xOffSet, double yOffSet) override;
virtual bool windowResizeEvent(int width, int height) override;
virtual bool keyInputEvent(int key, int action, int mods) override;
private:
void initGrid();
void initCube();
void drawCubes(glm::mat4 W, glm::mat4 S);
void initSquare();
void reset();
// Fields related to the shader and uniforms.
ShaderProgram m_shader;
GLint P_uni; // Uniform location for Projection matrix.
GLint V_uni; // Uniform location for View matrix.
GLint M_uni; // Uniform location for Model matrix.
GLint col_uni; // Uniform location for cube colour.
// Fields related to grid geometry.
GLuint m_grid_vao; // Vertex Array Object
GLuint m_grid_vbo; // Vertex Buffer Object
GLuint m_cube_vao; // Vertex Array Object
GLuint m_cube_vbo; // Vertex Buffer Object
GLuint m_cube_ebo; // Element Buffer Object
GLuint m_square_vao; // Vertex Array Object
GLuint m_square_vbo; // Vertex Buffer Object
GLuint m_square_ebo; // Element Buffer Object
// Matrices controlling the camera and projection.
glm::mat4 proj;
glm::mat4 view;
int current_col;
Grid gridInfo;
float currX;
float currY;
float colours[8][3] = {
{ 1.0f, 1.0f, 1.0f },
{ 1.0f, 0.0f, 0.0f },
{ 0.0f, 1.0f, 0.0f },
{ 0.0f, 0.0f, 1.0f },
{ 1.0f, 1.0f, 0.0f },
{ 1.0f, 0.0f, 1.0f },
{ 0.0f, 1.0f, 1.0f },
{ 0.5f, 0.5f, 1.0f }
};
bool shiftKeyPressed;
double oldX;
glm::mat4 oldRotate;
double oldY;
bool mousePressed;
};
| 7a88093bcb2c1fe398fe5e6fe404c711e3b2bc41 | [
"C++"
] | 2 | C++ | DurriyaVasi/barcraft | dd80196e8f9c8b4ab55b8e0ef2e14fa36e0acdfd | c4ebbcdb4553a329258e92594f06084ad3c4d3de |
refs/heads/main | <repo_name>stephendengbl/toutiao<file_sep>/heima-leadnews-service/heima-leadnews-behavior/src/main/java/com/heima/behavior/controller/ApReadBehaviorController.java
package com.heima.behavior.controller;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.behavior.dto.ReadBehaviorDto;
import com.heima.common.dto.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.behavior.service.IApReadBehaviorService;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* APP阅读行为表 前端控制器
* </p>
*
* @author mcm
* @since 2021-05-29
*/
@RestController
@RequestMapping("/api/v1/read_behavior")
@Api(tags = "APP阅读行为表接口")
@CrossOrigin
public class ApReadBehaviorController {
@Autowired
private IApReadBehaviorService apReadBehaviorService;
@PostMapping
public ResponseResult saveReadBehavior(@RequestBody ReadBehaviorDto dto) {
return apReadBehaviorService.saveReadBehavior(dto);
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-user/src/main/java/com/heima/user/controller/ApUserController.java
package com.heima.user.controller;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.common.dto.ResponseResult;
import com.heima.user.dto.UserRelationDto;
import com.heima.user.entity.ApUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.user.service.IApUserService;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* APP用户信息表 前端控制器
* </p>
*
* @author mcm
* @since 2021-05-19
*/
@RestController
@RequestMapping("/api/v1/user")
@Api(tags = "APP用户信息表接口")
@CrossOrigin
public class ApUserController {
@Autowired
private IApUserService apUserService;
/**
* 关注和取消关注
*
* @param dto
* @return
*/
@PostMapping("/user_follow")
public ResponseResult follow(@RequestBody UserRelationDto dto) {
return apUserService.follow(dto);
}
/**
* 根据用户id查询用户
* @param id
* @return
*/
@GetMapping("/{id}")
public ResponseResult<ApUser> getUserById(@PathVariable("id") Integer id) {
return ResponseResult.okResult(apUserService.getById(id));
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-search/src/main/java/com/heima/search/entity/ApUserSearch.java
package com.heima.search.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
* APP用户搜索信息表
* </p>
*
* @author mcm
* @since 2021-06-01
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("ap_user_search")
@ApiModel(description="APP用户搜索信息表")
public class ApUserSearch implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@ApiModelProperty(value = "主键")
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 用户ID
*/
@ApiModelProperty(value = "用户ID")
@TableField("entry_id")
private Integer entryId;
/**
* 搜索词
*/
@ApiModelProperty(value = "搜索词")
@TableField("keyword")
private String keyword;
/**
* 当前状态0 无效 1有效
*/
@ApiModelProperty(value = "当前状态0 无效 1有效")
@TableField("status")
private Integer status;
/**
* 创建时间
*/
@ApiModelProperty(value = "创建时间")
@TableField("created_time")
private Date createdTime;
}
<file_sep>/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.heima</groupId>
<artifactId>heima-leadnews</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>heima-leadnews-common</module>
<module>heima-leadnews-service</module>
<module>heima-leadnews-gateway</module>
</modules>
<!-- 继承Spring boot工程 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.8.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
<!-- 项目源码及编译输出的编码 -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- 项目编译JDK版本 -->
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<!-- 依赖包版本管理 -->
<commons.io.version>2.6</commons.io.version>
<mysql.version>5.1.46</mysql.version>
<mybatis.plus.version>3.3.1</mybatis.plus.version>
<jsoup.version>1.10.2</jsoup.version>
<jwt.version>0.9.1</jwt.version>
<fastjson.version>1.2.58</fastjson.version>
<spring.jwt.version>1.0.9.RELEASE</spring.jwt.version>
<spring.cloud.version>Hoxton.SR6</spring.cloud.version>
<curator.version>4.2.0</curator.version>
<hanlp.version>portable-1.3.4</hanlp.version>
<ali.core.version>4.1.1</ali.core.version>
<ali.green.version>3.6.1</ali.green.version>
<reflections.version>0.9.11</reflections.version>
<swagger.version>2.9.2</swagger.version>
<knife4j.version>2.0.2</knife4j.version>
<com.alibaba.cloud>2.1.2.RELEASE</com.alibaba.cloud>
<xxl.job.version>2.2.0</xxl.job.version>
</properties>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<!--内部依赖工程-->
<dependency>
<artifactId>heima-leadnews-common</artifactId>
<groupId>com.heima</groupId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>${reflections.version}</version>
</dependency>
<!--Apache 工具包包-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons.io.version}</version>
</dependency>
<!-- Mysql 数据库 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- jsoup -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>${jsoup.version}</version>
</dependency>
<!-- jwt -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>${jwt.version}</version>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<!-- spring colud -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring.cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--spring cloud alibaba-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${com.alibaba.cloud}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--匹配度工具包-->
<dependency>
<groupId>com.hankcs</groupId>
<artifactId>hanlp</artifactId>
<version>${hanlp.version}</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>${ali.core.version}</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-green</artifactId>
<version>${ali.green.version}</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>${knife4j.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis.plus.version}</version>
</dependency>
<!-- xxl-job -->
<dependency>
<groupId>com.xuxueli</groupId>
<artifactId>xxl-job-core</artifactId>
<version>${xxl.job.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<useDefaultDelimiters>true</useDefaultDelimiters>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/test/resources</directory>
<filtering>true</filtering>
</testResource>
</testResources>
</build>
</project>
<file_sep>/heima-leadnews-common/src/main/java/com/heima/common/aliyun/OSSConfig.java
package com.heima.common.aliyun;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OSSConfig {
@Bean
public OSS ossClient(OSSProperties properties) {
return new OSSClientBuilder().build(properties.getEndpoint(), properties.getAccessKeyId(), properties.getAccessKeySecret());
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-behavior/src/main/java/com/heima/behavior/service/IApLikesBehaviorService.java
package com.heima.behavior.service;
import com.heima.behavior.dto.LikesBehaviorDto;
import com.heima.behavior.entity.ApLikesBehavior;
import com.baomidou.mybatisplus.extension.service.IService;
import com.heima.common.dto.ResponseResult;
/**
* <p>
* APP点赞行为表 服务类
* </p>
*
* @author mcm
* @since 2021-05-29
*/
public interface IApLikesBehaviorService extends IService<ApLikesBehavior> {
ResponseResult saveLikesBehavior(LikesBehaviorDto dto);
ResponseResult getLikesBehavior(LikesBehaviorDto dto);
}
<file_sep>/heima-leadnews-service/heima-leadnews-behavior/src/main/java/com/heima/behavior/service/impl/ApUnlikesBehaviorServiceImpl.java
package com.heima.behavior.service.impl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.behavior.dto.EntryDto;
import com.heima.behavior.dto.UnLikesBehaviorDto;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.entity.ApUnlikesBehavior;
import com.heima.behavior.mapper.ApUnlikesBehaviorMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.behavior.service.IApUnlikesBehaviorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
/**
* <p>
* APP不喜欢行为表 服务实现类
* </p>
*
* @author mcm
* @since 2021-05-29
*/
@Service
public class ApUnlikesBehaviorServiceImpl extends ServiceImpl<ApUnlikesBehaviorMapper, ApUnlikesBehavior> implements IApUnlikesBehaviorService {
@Autowired
private IApBehaviorEntryService entryService;
@Override
public ResponseResult saveUnlikesBehavior(UnLikesBehaviorDto dto) {
// 获取当前的用户
User user = AppThreadLocalUtil.get();
EntryDto entryDto = new EntryDto();
entryDto.setEquipmentId(dto.getEquipmentId());
if (user != null) {
entryDto.setUserId(user.getUserId());
}
ApBehaviorEntry entry = entryService.getEntry(entryDto);
// 构建对象
ApUnlikesBehavior unlikesBehavior = new ApUnlikesBehavior();
unlikesBehavior.setEntryId(entry.getId());
unlikesBehavior.setArticleId(dto.getArticleId());
unlikesBehavior.setType(dto.getType());
unlikesBehavior.setCreatedTime(new Date());
// 判断是否有不喜欢记录
LambdaQueryWrapper<ApUnlikesBehavior> query = new LambdaQueryWrapper<>();
query.eq(ApUnlikesBehavior::getEntryId, entry.getId());
query.eq(ApUnlikesBehavior::getArticleId, dto.getArticleId());
ApUnlikesBehavior apUnlikesBehavior = this.getOne(query);
if (apUnlikesBehavior == null) {
// 新增
this.save(unlikesBehavior);
} else {
if (apUnlikesBehavior.getType() != dto.getType()) {
apUnlikesBehavior.setType(dto.getType());
this.updateById(apUnlikesBehavior);
}
}
return ResponseResult.okResult();
}
@Override
public ResponseResult<ApUnlikesBehavior> getUnlikesBehavior(UnLikesBehaviorDto dto) {
if(dto.getUserId()==null){
User user = AppThreadLocalUtil.get();
dto.setUserId(user.getUserId());
}
EntryDto entryDto = new EntryDto();
entryDto.setEquipmentId(dto.getEquipmentId());
entryDto.setUserId(dto.getUserId());
ApBehaviorEntry entry = entryService.getEntry(entryDto);
LambdaQueryWrapper<ApUnlikesBehavior> query = new LambdaQueryWrapper<>();
query.eq(ApUnlikesBehavior::getEntryId, entry.getId());
query.eq(ApUnlikesBehavior::getArticleId, dto.getArticleId());
ApUnlikesBehavior apUnlikesBehavior = this.getOne(query);
return ResponseResult.okResult(apUnlikesBehavior);
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-behavior/src/main/java/com/heima/behavior/mapper/ApBehaviorEntryMapper.java
package com.heima.behavior.mapper;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* APP行为实体表,一个行为实体可能是用户或者设备,或者其它 Mapper 接口
* </p>
*
* @author mcm
* @since 2021-05-29
*/
public interface ApBehaviorEntryMapper extends BaseMapper<ApBehaviorEntry> {
}
<file_sep>/heima-leadnews-common/src/main/resources/oss.properties
aliyun.oss.accessKeyId=<KEY>
aliyun.oss.accessKeySecret=<KEY>
aliyun.oss.endpoint=https://oss-cn-beijing.aliyuncs.com
aliyun.oss.bucket=myth
aliyun.oss.host=https://myth.oss-cn-beijing.aliyuncs.com
aliyun.oss.scenes=terrorism
<file_sep>/heima-leadnews-service/heima-leadnews-user/src/main/java/com/heima/user/dto/FollowBehaviorDto.java
package com.heima.user.dto;
import lombok.Data;
@Data
public class FollowBehaviorDto {
/**
* 关注id
*/
private Integer followId;
/**
* 设备id
*/
private String equipmentId;
/**
* 用户id
*/
private Integer userId;
/**
* 操作类型 0 关注 1 取消关注
*/
private Integer operation;
}
<file_sep>/heima-leadnews-service/heima-leadnews-article/src/main/java/com/heima/article/mapper/ApArticleMapper.java
package com.heima.article.mapper;
import com.heima.article.entity.ApArticle;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 文章信息表,存储已发布的文章 Mapper 接口
* </p>
*
* @author mcm
* @since 2021-05-25
*/
public interface ApArticleMapper extends BaseMapper<ApArticle> {
}
<file_sep>/heima-leadnews-service/heima-leadnews-search/src/main/java/com/heima/search/entity/ApAssociateWords.java
package com.heima.search.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
* 联想词表
* </p>
*
* @author mcm
* @since 2021-06-01
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("ap_associate_words")
@ApiModel(description="联想词表")
public class ApAssociateWords implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 联想词
*/
@ApiModelProperty(value = "联想词")
@TableField("associate_words")
private String associateWords;
/**
* 创建时间
*/
@ApiModelProperty(value = "创建时间")
@TableField("created_time")
private Date createdTime;
}
<file_sep>/heima-leadnews-service/heima-leadnews-behavior/src/main/java/com/heima/behavior/service/impl/ApReadBehaviorServiceImpl.java
package com.heima.behavior.service.impl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.behavior.dto.EntryDto;
import com.heima.behavior.dto.ReadBehaviorDto;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.entity.ApLikesBehavior;
import com.heima.behavior.entity.ApReadBehavior;
import com.heima.behavior.mapper.ApReadBehaviorMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.behavior.service.IApReadBehaviorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
/**
* <p>
* APP阅读行为表 服务实现类
* </p>
*
* @author mcm
* @since 2021-05-29
*/
@Service
public class ApReadBehaviorServiceImpl extends ServiceImpl<ApReadBehaviorMapper, ApReadBehavior> implements IApReadBehaviorService {
@Autowired
private IApBehaviorEntryService entryService;
@Override
public ResponseResult saveReadBehavior(ReadBehaviorDto dto) {
// 构建ApReadBehavior对象
// 获取实体id
// 获取当前的用户
User user = AppThreadLocalUtil.get();
EntryDto entryDto = new EntryDto();
entryDto.setEquipmentId(dto.getEquipmentId());
if (user != null) {
entryDto.setUserId(user.getUserId());
}
ApBehaviorEntry entry = entryService.getEntry(entryDto);
ApReadBehavior readBehavior = new ApReadBehavior();
readBehavior.setEntryId(entry.getId());
readBehavior.setArticleId(dto.getArticleId());
readBehavior.setCount(1);
readBehavior.setReadDuration(dto.getReadDuration());
readBehavior.setPercentage(dto.getPercentage());
readBehavior.setLoadDuration(dto.getLoadDuration());
readBehavior.setCreatedTime(new Date());
// 判断是否已经有阅读记录
LambdaQueryWrapper<ApReadBehavior> query = new LambdaQueryWrapper<>();
query.eq(ApReadBehavior::getEntryId, entry.getId());
query.eq(ApReadBehavior::getArticleId, dto.getArticleId());
ApReadBehavior apReadBehavior = this.getOne(query);
if (apReadBehavior == null) {
// 保存
this.save(readBehavior);
} else {
apReadBehavior.setLoadDuration(dto.getLoadDuration());
apReadBehavior.setReadDuration(dto.getReadDuration());
apReadBehavior.setPercentage(dto.getPercentage());
// 在高并发的情况下有可能出现数据不一致的问题
// 方案 1 加锁 分布式锁
// 方案 2 原子类
// 方案 3 update ap_read_behavior set count = count+1 where id = #id
apReadBehavior.setCount(apReadBehavior.getCount() + 1);
apReadBehavior.setUpdatedTime(new Date());
// this.updateById(apReadBehavior);
LambdaUpdateWrapper<ApReadBehavior> update = new LambdaUpdateWrapper<>();
// 查询条件
update.eq(ApReadBehavior::getId, apReadBehavior.getId());
// 更新的字段
update.set(ApReadBehavior::getLoadDuration, dto.getLoadDuration());
update.set(ApReadBehavior::getReadDuration, dto.getReadDuration());
update.set(ApReadBehavior::getPercentage, dto.getPercentage());
update.set(ApReadBehavior::getUpdatedTime, new Date());
update.setSql("count = count+1");
this.update(update);
}
return ResponseResult.okResult();
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-article/src/main/java/com/heima/article/dto/ArticleDto.java
package com.heima.article.dto;
import com.heima.article.entity.ApArticle;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = true)
public class ArticleDto extends ApArticle {
/**
* 文章内容
*/
private String content;
}
<file_sep>/heima-leadnews-common/src/main/java/com/heima/common/dto/ResponseResult.java
package com.heima.common.dto;
import com.heima.common.enums.AppHttpCodeEnum;
import lombok.Data;
import java.io.Serializable;
/**
* 通用的结果返回类
* @param <T>
*/
@Data
public class ResponseResult<T> implements Serializable {
/**
* 返回码
*/
private Integer code;
/**
* 错误提示
*/
private String errorMessage;
/**
* 返回数据
*/
private T data;
public ResponseResult() {
this.code = AppHttpCodeEnum.SUCCESS.getCode();
}
public ResponseResult(Integer code, T data) {
this.code = code;
this.data = data;
}
public ResponseResult(Integer code, String msg) {
this.code = code;
this.errorMessage = msg;
}
public static ResponseResult okResult() {
return okResult(null);
}
public static <T> ResponseResult okResult(T data) {
return new ResponseResult(AppHttpCodeEnum.SUCCESS.getCode(), data);
}
public static ResponseResult errorResult(int code, String msg) {
return new ResponseResult(code, msg);
}
public static ResponseResult errorResult(AppHttpCodeEnum enums) {
return new ResponseResult(enums.getCode(), enums.getErrorMessage());
}
public static ResponseResult errorResult(AppHttpCodeEnum enums, String errorMessage) {
return new ResponseResult(enums.getCode(), errorMessage);
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-admin/src/main/java/com/heima/admin/service/impl/AdChannelServiceImpl.java
package com.heima.admin.service.impl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.dto.ChannelDto;
import com.heima.admin.entity.AdChannel;
import com.heima.admin.mapper.AdChannelMapper;
import com.heima.admin.service.IAdChannelService;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
@Service
public class AdChannelServiceImpl extends ServiceImpl<AdChannelMapper, AdChannel> implements IAdChannelService {
@Override
public ResponseResult listByName(ChannelDto dto) {
// 根据名称模糊查询分页列表
// 参数校验
if (dto == null) {
return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
}
// 构建分页条件 参数 1 当前页 2 每页条数
IPage<AdChannel> page = new Page<>(dto.getPage(), dto.getSize());
LambdaQueryWrapper<AdChannel> query = new LambdaQueryWrapper<>();
// 判断name是否为空
if (!StringUtils.isEmpty(dto.getName())) {
// 参数 1 字段 2 值
query.like(AdChannel::getName, dto.getName());
}
IPage<AdChannel> iPage = this.page(page, query);
// 返回通用的分页响应对象
PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), iPage.getTotal(), iPage.getRecords());
return result;
}
@Override
public ResponseResult saveChannel(AdChannel entity) {
// 需求分析
// 1. 判断参数是否有效
if (entity == null || StringUtils.isEmpty(entity.getName())) {
return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
}
// 2. 判断频道名称是否已经存在
// select count(1) from ad_channel where name = #name
LambdaQueryWrapper<AdChannel> query = new LambdaQueryWrapper<>();
query.eq(AdChannel::getName, entity.getName());
int count = this.count(query);
if (count <= 0) {
// 3. 不存在保存频道
this.save(entity);
}
// 返回新增的频道ID
return ResponseResult.okResult(entity.getId());
}
@Override
public ResponseResult deleteChannel(Integer id) {
// 需求
// 1. 根据id查询频道
AdChannel adChannel = this.getById(id);
if (adChannel == null) {
// 频道不存在,提示
return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
}
// 2. 如果频道存在,需要判断状态是否有效
if (adChannel.getStatus()) {
// 3. 如果是有效,提示不能删除
return ResponseResult.errorResult(AppHttpCodeEnum.DATA_CAN_NOT_DELETE);
}
// 4. 无效,可以删除
this.removeById(id);
return ResponseResult.okResult();
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-article/src/main/java/com/heima/article/entity/ApCollection.java
package com.heima.article.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
* APP收藏信息表
* </p>
*
* @author mcm
* @since 2021-05-29
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("ap_collection")
@ApiModel(description="APP收藏信息表")
public class ApCollection implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 实体ID
*/
@ApiModelProperty(value = "实体ID")
@TableField("entry_id")
private Integer entryId;
/**
* 文章ID
*/
@ApiModelProperty(value = "文章ID")
@TableField("article_id")
private Long articleId;
/**
* 创建时间
*/
@ApiModelProperty(value = "创建时间")
@TableField("collection_time")
private Date collectionTime;
}
<file_sep>/heima-leadnews-service/heima-leadnews-behavior/src/main/java/com/heima/behavior/controller/ApUnlikesBehaviorController.java
package com.heima.behavior.controller;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.behavior.dto.UnLikesBehaviorDto;
import com.heima.behavior.entity.ApUnlikesBehavior;
import com.heima.common.dto.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.behavior.service.IApUnlikesBehaviorService;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* APP不喜欢行为表 前端控制器
* </p>
*
* @author mcm
* @since 2021-05-29
*/
@RestController
@RequestMapping("/api/v1/unlikes_behavior")
@Api(tags = "APP不喜欢行为表接口")
@CrossOrigin
public class ApUnlikesBehaviorController{
@Autowired
private IApUnlikesBehaviorService apUnlikesBehaviorService;
@PostMapping
public ResponseResult saveUnlikesBehavior(@RequestBody UnLikesBehaviorDto dto){
return apUnlikesBehaviorService.saveUnlikesBehavior(dto);
}
@PostMapping("getUnLikes")
public ResponseResult<ApUnlikesBehavior> getUnlikesBehavior(@RequestBody UnLikesBehaviorDto dto){
return apUnlikesBehaviorService.getUnlikesBehavior(dto);
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/service/IWmNewsService.java
package com.heima.wemedia.service;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.wemedia.dto.NewsAuthDto;
import com.heima.wemedia.dto.WmNewsDto;
import com.heima.wemedia.dto.WmNewsPageDto;
import com.heima.wemedia.entity.WmNews;
import com.baomidou.mybatisplus.extension.service.IService;
import com.heima.wemedia.vo.WmNewsVo;
import java.util.List;
/**
* <p>
* 自媒体图文内容信息表 服务类
* </p>
*
* @author mcm
* @since 2021-05-22
*/
public interface IWmNewsService extends IService<WmNews> {
ResponseResult listByCondition(WmNewsPageDto dto);
ResponseResult submit(WmNewsDto dto);
ResponseResult deleteById(Integer id);
ResponseResult downOrUp(WmNewsDto dto);
ResponseResult<List<Integer>> getRelease();
PageResponseResult findPageByName(NewsAuthDto dto);
ResponseResult<WmNewsVo> findNewsVoById(Integer id);
}
<file_sep>/heima-leadnews-service/heima-leadnews-admin/src/main/java/com/heima/admin/mapper/AdChannelMapper.java
package com.heima.admin.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.heima.admin.entity.AdChannel;
public interface AdChannelMapper extends BaseMapper<AdChannel> {
}
<file_sep>/heima-leadnews-service/heima-leadnews-comment/src/main/java/com/heima/comment/service/ICommentRepayService.java
package com.heima.comment.service;
import com.heima.comment.dto.CommentRepayDto;
import com.heima.comment.dto.CommentRepayLikeDto;
import com.heima.comment.dto.CommentRepaySaveDto;
import com.heima.common.dto.ResponseResult;
public interface ICommentRepayService {
ResponseResult save(CommentRepaySaveDto dto);
ResponseResult like(CommentRepayLikeDto dto);
ResponseResult load(CommentRepayDto dto);
}
<file_sep>/heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/service/IWmUserService.java
package com.heima.wemedia.service;
import com.heima.common.dto.ResponseResult;
import com.heima.wemedia.dto.WmLoginDto;
import com.heima.wemedia.entity.WmUser;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 自媒体用户信息表 服务类
* </p>
*
* @author mcm
* @since 2021-05-19
*/
public interface IWmUserService extends IService<WmUser> {
ResponseResult<WmUser> saveWmUser(WmUser entity);
ResponseResult login(WmLoginDto dto);
}
<file_sep>/heima-leadnews-service/heima-leadnews-article/src/main/java/com/heima/article/mapper/ApAuthorMapper.java
package com.heima.article.mapper;
import com.heima.article.entity.ApAuthor;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* APP文章作者信息表 Mapper 接口
* </p>
*
* @author mcm
* @since 2021-05-19
*/
public interface ApAuthorMapper extends BaseMapper<ApAuthor> {
}
<file_sep>/heima-leadnews-service/heima-leadnews-search/src/main/java/com/heima/search/dto/EntryDto.java
package com.heima.search.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class EntryDto {
/**
* 设备id
*/
private String equipmentId;
/**
* 用户id
*/
private Integer userId;
}
<file_sep>/heima-leadnews-service/heima-leadnews-admin/src/main/java/com/heima/admin/job/AuditJob.java
package com.heima.admin.job;
import com.heima.admin.feign.WeMediaFeign;
import com.heima.admin.service.IAuditService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
@Service
@Slf4j
public class AuditJob {
@Autowired
private WeMediaFeign weMediaFeign;
@Autowired
private IAuditService auditService;
@XxlJob("autoAuditJob")
public ReturnT<String> auditJobHandler(String param) throws Exception {
// 查询待发布的文章id列表
try {
ResponseResult<List<Integer>> responseResult = weMediaFeign.getRelease();
if (responseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
List<Integer> ids = responseResult.getData();
for (Integer id : ids) {
// 调用审核服务
auditService.auditById(id);
}
}
return ReturnT.SUCCESS;
} catch (Exception e) {
log.error(e.getMessage());
return ReturnT.FAIL;
}
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-article/src/main/java/com/heima/article/dto/ArticleInfoDto.java
package com.heima.article.dto;
import lombok.Data;
@Data
public class ArticleInfoDto {
// 设备ID
String equipmentId;
// 文章ID
Long articleId;
// 作者ID
Integer authorId;
}
<file_sep>/heima-leadnews-service/heima-leadnews-admin/src/main/java/com/heima/admin/service/impl/AdSensitiveServiceImpl.java
package com.heima.admin.service.impl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.admin.dto.SensitiveDto;
import com.heima.admin.entity.AdSensitive;
import com.heima.admin.mapper.AdSensitiveMapper;
import com.heima.admin.service.IAdSensitiveService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.Date;
/**
* <p>
* 敏感词信息表 服务实现类
* </p>
*
* @author mcm
* @since 2021-05-18
*/
@Service
public class AdSensitiveServiceImpl extends ServiceImpl<AdSensitiveMapper, AdSensitive> implements IAdSensitiveService {
@Override
public ResponseResult listByName(SensitiveDto dto) {
// 需求 根据敏感词模糊查询分页结果
// 准备查询对象
LambdaQueryWrapper<AdSensitive> query = new LambdaQueryWrapper<>();
if (!StringUtils.isEmpty(dto.getName())) {
query.like(AdSensitive::getSensitives, dto.getName());
}
// 准备分页请求对象
IPage<AdSensitive> page = new Page<>(dto.getPage(), dto.getSize());
// 调用分页接口
IPage<AdSensitive> iPage = this.page(page, query);
// 构建通用的分页返回响应
PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(),
iPage.getTotal(), iPage.getRecords());
return result;
}
@Override
public ResponseResult saveSensitive(AdSensitive entity) {
// 需求 保存敏感词 先判断数据库中是否已经存在
if (entity == null || StringUtils.isEmpty(entity.getSensitives())) {
return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
}
// 断数据库中是否已经存在
LambdaQueryWrapper<AdSensitive> query = new LambdaQueryWrapper<>();
query.eq(AdSensitive::getSensitives, entity.getSensitives());
AdSensitive sensitive = this.getOne(query);
if (sensitive == null) {
// 添加时间
entity.setCreatedTime(new Date());
// 不存在新增
this.save(entity);
}
return ResponseResult.okResult(entity.getId());
}
@Override
public ResponseResult updateSensitive(AdSensitive entity) {
// 需求 更新敏感词 先判断数据库中是否已经存在
if (entity == null || StringUtils.isEmpty(entity.getSensitives())) {
return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
}
// 断数据库中是否已经存在
LambdaQueryWrapper<AdSensitive> query = new LambdaQueryWrapper<>();
query.eq(AdSensitive::getSensitives, entity.getSensitives());
AdSensitive sensitive = this.getOne(query);
// 如果已经存在,提示 敏感词已存在
if (sensitive != null) {
return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
}
// 更新
this.updateById(entity);
return ResponseResult.okResult();
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-behavior/src/main/java/com/heima/behavior/service/impl/ApFollowBehaviorServiceImpl.java
package com.heima.behavior.service.impl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.behavior.dto.EntryDto;
import com.heima.behavior.dto.FollowBehaviorDto;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.entity.ApFollowBehavior;
import com.heima.behavior.mapper.ApFollowBehaviorMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.behavior.service.IApFollowBehaviorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
/**
* <p>
* APP关注行为表 服务实现类
* </p>
*
* @author mcm
* @since 2021-05-29
*/
@Service
public class ApFollowBehaviorServiceImpl extends ServiceImpl<ApFollowBehaviorMapper, ApFollowBehavior> implements IApFollowBehaviorService {
@Autowired
private IApBehaviorEntryService entryService;
@Override
public void saveBehavior(FollowBehaviorDto followBehaviorDto) {
// 构建ApFollowBehavior 对象
ApFollowBehavior followBehavior = new ApFollowBehavior();
// 查询实体id
EntryDto entryDto = new EntryDto(followBehaviorDto.getEquipmentId(), followBehaviorDto.getUserId());
ApBehaviorEntry entry = entryService.getEntry(entryDto);
followBehavior.setEntryId(entry.getId());
followBehavior.setFollowId(followBehaviorDto.getFollowId());
followBehavior.setOperation(followBehaviorDto.getOperation());
followBehavior.setCreatedTime(new Date());
// 判断是否已经有关注记录
LambdaQueryWrapper<ApFollowBehavior> query = new LambdaQueryWrapper<>();
query.eq(ApFollowBehavior::getEntryId, entry.getId());
query.eq(ApFollowBehavior::getFollowId, followBehaviorDto.getFollowId());
ApFollowBehavior apFollowBehavior = this.getOne(query);
if (apFollowBehavior != null) {
// 判断已有记录的operation 和传递过来的operation 是否一致,不一致才进行更新
if (apFollowBehavior.getOperation() != followBehaviorDto.getOperation()) {
apFollowBehavior.setOperation(followBehaviorDto.getOperation());
this.updateById(apFollowBehavior);
}
} else {
// 保存
this.save(followBehavior);
}
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-admin/src/main/java/com/heima/admin/service/impl/AuthServiceImpl.java
package com.heima.admin.service.impl;
import com.heima.admin.dto.NewsAuthDto;
import com.heima.admin.dto.WmNews;
import com.heima.admin.feign.WeMediaFeign;
import com.heima.admin.service.IAuthService;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class AuthServiceImpl implements IAuthService {
@Autowired
private WeMediaFeign weMediaFeign;
@Override
public ResponseResult list(NewsAuthDto dto) {
// 调用自媒体的远程接口
PageResponseResult result = weMediaFeign.findPageByName(dto);
return result;
}
@Override
public ResponseResult one(Integer id) {
return weMediaFeign.findNewsVoById(id);
}
@Override
public ResponseResult auth(NewsAuthDto dto) {
// 需求分析
ResponseResult<WmNews> wmNewsResponseResult = weMediaFeign.getById(dto.getId());
if (wmNewsResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
WmNews wmNews = wmNewsResponseResult.getData();
// 1. 判断状态 状态为2 审核失败 需要记录审核失败的原因 更新自媒体文章
// 2. 状态为4 人工审核通过 更新自媒体文章
if (dto.getStatus() == 4) {
wmNews.setStatus(4);
}
if (dto.getStatus() == 2) {
wmNews.setStatus(2);
wmNews.setReason(dto.getMsg());
}
weMediaFeign.updateWmNews(wmNews);
}
return ResponseResult.okResult();
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-article/src/main/java/com/heima/article/listener/HotArticleResultListener.java
package com.heima.article.listener;
import com.alibaba.fastjson.JSON;
import com.heima.article.dto.ArticleStreamMessage;
import com.heima.article.service.IHotArticleService;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
@Service
public class HotArticleResultListener {
@Autowired
private IHotArticleService hotArticleService;
@KafkaListener(topics = {"${topic.hotArticleResultTopic}"})
public void handleMsg(ConsumerRecord<String, String> record) {
String value = record.value();
if (!StringUtils.isEmpty(value)) {
// 解析json
ArticleStreamMessage articleStreamMessage = JSON.parseObject(value, ArticleStreamMessage.class);
// 调用热点文章服务,更新数据
hotArticleService.update(articleStreamMessage);
}
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-admin/src/main/java/com/heima/admin/controller/AuthController.java
package com.heima.admin.controller;
import com.heima.admin.dto.NewsAuthDto;
import com.heima.admin.service.IAuthService;
import com.heima.common.dto.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/v1/news_auth")
public class AuthController {
@Autowired
private IAuthService authService;
@PostMapping("/list")
public ResponseResult list(@RequestBody NewsAuthDto dto) {
return authService.list(dto);
}
@GetMapping("/one/{id}")
public ResponseResult one(@PathVariable("id") Integer id) {
return authService.one(id);
}
/**
* 审核通过
*
* @param dto
* @return
*/
@PostMapping("/auth_pass")
public ResponseResult authPass(@RequestBody NewsAuthDto dto) {
return authService.auth(dto);
}
/**
* 审核通过
*
* @param dto
* @return
*/
@PostMapping("/auth_fail")
public ResponseResult authFail(@RequestBody NewsAuthDto dto) {
return authService.auth(dto);
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-search/src/main/java/com/heima/search/feign/BehaviorFeign.java
package com.heima.search.feign;
import com.heima.common.dto.ResponseResult;
import com.heima.search.dto.ApBehaviorEntry;
import com.heima.search.dto.EntryDto;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
@FeignClient("leadnews-behavior")
public interface BehaviorFeign {
@PostMapping("/api/v1/behavior_entry/getEntry")
public ResponseResult<ApBehaviorEntry> getEntry(@RequestBody EntryDto dto);
}
<file_sep>/heima-leadnews-service/heima-leadnews-behavior/src/main/java/com/heima/behavior/dto/UnLikesBehaviorDto.java
package com.heima.behavior.dto;
import lombok.Data;
@Data
public class UnLikesBehaviorDto {
Integer userId;
// 设备ID
String equipmentId;
// 文章ID
Long articleId;
/**
* 不喜欢操作方式
* 0 不喜欢
* 1 取消不喜欢
*/
Integer type;
}
<file_sep>/heima-leadnews-service/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>heima-leadnews</artifactId>
<groupId>com.heima</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>heima-leadnews-service</artifactId>
<packaging>pom</packaging>
<modules>
<module>heima-leadnews-admin</module>
<module>heima-leadnews-user</module>
<module>heima-leadnews-wemedia</module>
<module>heima-leadnews-article</module>
<module>heima-leadnews-behavior</module>
<module>heima-leadnews-comment</module>
<module>heima-leadnews-search</module>
<module>heima-leadnews-alarm</module>
<module>heima-leadnews-behavior-7</module>
<!-- <module>heima-leadnews-behavior-07</module>-->
</modules>
<dependencies>
<dependency>
<groupId>com.heima</groupId>
<artifactId>heima-leadnews-common</artifactId>
</dependency>
<!-- Spring boot starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
<file_sep>/heima-leadnews-service/heima-leadnews-article/src/main/java/com/heima/article/listener/UpDownListener.java
package com.heima.article.listener;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.IApArticleService;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.HashMap;
@Service
public class UpDownListener {
@Autowired
private IApArticleService articleService;
// 添加监听器 指定监听的主题
@KafkaListener(topics = "${topic.upDownTopic}")
public void handleMessage(ConsumerRecord<String, String> record) {
// 分析结果 ,获取到value
String value = record.value();
if (!StringUtils.isEmpty(value)) {
HashMap map = JSON.parseObject(value, HashMap.class);
// 获取文章id
Long id = (Long) map.get("id");
// 获取需要更新的状态
Boolean isDown = (Boolean) map.get("isDown");
// 调用服务接口更新文章状态
LambdaUpdateWrapper<ApArticle> update = new LambdaUpdateWrapper<>();
update.eq(ApArticle::getId, id);
update.set(ApArticle::getIsDown, isDown);
articleService.update(update);
}
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-article/src/main/java/com/heima/article/service/impl/ApArticleServiceImpl.java
package com.heima.article.service.impl;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.dto.*;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.entity.ApAuthor;
import com.heima.article.entity.ApCollection;
import com.heima.article.feign.BehaviorFeign;
import com.heima.article.feign.UserFeign;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.service.IApAuthorService;
import com.heima.article.service.IApCollectionService;
import com.heima.article.vo.HotArticleVo;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p>
* 文章信息表,存储已发布的文章 服务实现类
* </p>
*
* @author mcm
* @since 2021-05-25
*/
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {
// 注入文章内容服务接口
@Autowired
private IApArticleContentService contentService;
@Autowired
private StringRedisTemplate redisTemplate;
@Override
public ResponseResult<Long> saveArticle(ArticleDto dto) {
// 需求分析
// 1. 判断是否有id
if (dto.getId() == null) {
// 2. 没有id,新增文章
ApArticle apArticle = new ApArticle();
BeanUtils.copyProperties(dto, apArticle);
this.save(apArticle);
// 2.1 保存文章内容
ApArticleContent content = new ApArticleContent();
content.setArticleId(apArticle.getId());
content.setContent(dto.getContent());
contentService.save(content);
return ResponseResult.okResult(apArticle.getId());
}
// 3. 有id,修改文章
ApArticle apArticle = new ApArticle();
BeanUtils.copyProperties(dto, apArticle);
this.updateById(apArticle);
// 3.1 修改文章内容
LambdaUpdateWrapper<ApArticleContent> update = new LambdaUpdateWrapper<>();
// 设置查询条件
update.eq(ApArticleContent::getArticleId, dto.getId());
// 设置更新条件
update.set(ApArticleContent::getContent, dto.getContent());
contentService.update(update);
return ResponseResult.okResult(apArticle.getId());
}
/**
* 加载文章列表
*
* @param dto
* @param type 0 是加载最新文章 1 加载更多文章
* @return
*/
@Override
public ResponseResult loadArticle(ArticleHomeDto dto, int type) {
// 需求分析
// 1. 默认查询10篇文章
// 2. 根据频道ID查询
// 3. 根据发布时间倒序排列
// 4. 如果是需要加载更多文章,前端页面获取当前页面发布时间最小的值,查询比这个时间更小的数据
// 5. 如果是要加载最新文章,前端页面获取当前页面发布时间最大的值,查询比这个时间更大的数据
// 6. 过滤已下架或者已删除的文章
if (dto.getSize() == null || dto.getSize() <= 0 || dto.getSize() >= 50) {
dto.setSize(10);
}
IPage<ApArticle> page = new Page<>(1, dto.getSize());
LambdaQueryWrapper<ApArticle> query = new LambdaQueryWrapper<>();
if (dto.getChannelId() != null && dto.getChannelId() != 0) {
query.eq(ApArticle::getChannelId, dto.getChannelId());
}
query.orderByDesc(ApArticle::getPublishTime);
query.eq(ApArticle::getIsDelete, false);
query.eq(ApArticle::getIsDown, false);
if (type == 1) {
// 如果是需要加载更多文章,前端页面获取当前页面发布时间最小的值,查询比这个时间更小的数据
query.lt(ApArticle::getPublishTime, dto.getMinTime());
}
if (type == 0) {
// 如果是要加载最新文章,前端页面获取当前页面发布时间最大的值,查询比这个时间更大的数据
query.gt(ApArticle::getPublishTime, dto.getMaxTime());
}
IPage<ApArticle> iPage = this.page(page, query);
return ResponseResult.okResult(iPage.getRecords());
}
@Override
public ResponseResult load2(ArticleHomeDto dto, Integer type, boolean firstPage) {
// 判断是否是首页,是首页的话从redis中查询数据
if (firstPage) {
int channelId = 0;
if (dto.getChannelId() != null) {
channelId = dto.getChannelId();
}
String redisKey = "hot_article_first_page_" + channelId;
String json = redisTemplate.opsForValue().get(redisKey);
List<HotArticleVo> hotArticleVos = JSON.parseArray(json, HotArticleVo.class);
return ResponseResult.okResult(hotArticleVos);
}
// 否则走数据库查询
return loadArticle(dto, type);
}
@Override
public ResponseResult loadArticleInfo(ArticleInfoDto dto) {
// 1. 根据文章id查询文章
ApArticle apArticle = this.getById(dto.getArticleId());
if (apArticle == null || apArticle.getIsDown() || apArticle.getIsDelete()) {
return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
}
// 2. 查询文章内容
LambdaQueryWrapper<ApArticleContent> query = new LambdaQueryWrapper<>();
query.eq(ApArticleContent::getArticleId, dto.getArticleId());
ApArticleContent apArticleContent = contentService.getOne(query);
// 3. 构建返回对象
Map<String, Object> map = new HashMap<>();
map.put("config", apArticle);
map.put("content", apArticleContent);
return ResponseResult.okResult(map);
}
@Autowired
private BehaviorFeign behaviorFeign;
@Autowired
private IApCollectionService collectionService;
@Override
public ResponseResult collect(CollectionBehaviorDto dto) {
// 保存ApCollection对象
// 获取当前登录的用户
User user = AppThreadLocalUtil.get();
EntryDto entryDto = new EntryDto();
entryDto.setEquipmentId(dto.getEquipmentId());
if (user != null) {
entryDto.setUserId(user.getUserId());
}
// 远程调用行为微服务获取entryId
ResponseResult<ApBehaviorEntry> entryResponseResult = behaviorFeign.getEntry(entryDto);
if (entryResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
ApBehaviorEntry behaviorEntry = entryResponseResult.getData();
if (behaviorEntry != null) {
ApCollection collection = new ApCollection();
collection.setEntryId(behaviorEntry.getId());
collection.setArticleId(dto.getArticleId());
collection.setCollectionTime(new Date());
if (dto.getOperation() == 0) {
// 查询是否有记录
LambdaQueryWrapper<ApCollection> query = new LambdaQueryWrapper<>();
query.eq(ApCollection::getEntryId, behaviorEntry.getId());
query.eq(ApCollection::getArticleId, dto.getArticleId());
ApCollection apCollection = collectionService.getOne(query);
// 保存
if (apCollection == null) {
collectionService.save(collection);
}
} else {
// 删除记录
LambdaQueryWrapper<ApCollection> query = new LambdaQueryWrapper<>();
query.eq(ApCollection::getEntryId, behaviorEntry.getId());
query.eq(ApCollection::getArticleId, dto.getArticleId());
collectionService.remove(query);
}
}
}
// 判断操作是收藏还是取消收藏 收藏 保存 取消 删除记录
return ResponseResult.okResult();
}
@Autowired
private UserFeign userFeign;
@Autowired
private IApAuthorService authorService;
@Override
public ResponseResult loadBehavior(ArticleInfoDto dto) {
boolean isfollow = false;
boolean islike = false;
boolean isunlike = false;
boolean iscollection = false;
User user = AppThreadLocalUtil.get();
// 查询用户的关注记录
if (user != null) {
FollowBehaviorDto followBehaviorDto = new FollowBehaviorDto();
followBehaviorDto.setUserId(user.getUserId());
ApAuthor apAuthor = authorService.getById(dto.getAuthorId());
followBehaviorDto.setFollowId(apAuthor.getUserId());
ResponseResult<ApUserFollow> userFollowResponseResult = userFeign.getFollow(followBehaviorDto);
if (userFollowResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
ApUserFollow apUserFollow = userFollowResponseResult.getData();
if (apUserFollow != null) {
isfollow = true;
}
}
}
// 查询用户的点赞记录
LikesBehaviorDto likesBehaviorDto = new LikesBehaviorDto();
likesBehaviorDto.setArticleId(dto.getArticleId());
if (user != null) {
likesBehaviorDto.setUserId(user.getUserId());
}
likesBehaviorDto.setEquipmentId(dto.getEquipmentId());
ResponseResult<ApLikesBehavior> likesBehaviorResponseResult = behaviorFeign.getLikesBehavior(likesBehaviorDto);
if (likesBehaviorResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
ApLikesBehavior apLikesBehavior = likesBehaviorResponseResult.getData();
if (apLikesBehavior != null && apLikesBehavior.getOperation() == 0) {
islike = true;
}
}
// 查询用户的不喜欢记录
UnLikesBehaviorDto unLikesBehaviorDto = new UnLikesBehaviorDto();
unLikesBehaviorDto.setArticleId(dto.getArticleId());
unLikesBehaviorDto.setEquipmentId(dto.getEquipmentId());
if (user != null) {
unLikesBehaviorDto.setUserId(user.getUserId());
}
ResponseResult<ApUnlikesBehavior> unlikesBehaviorResponseResult = behaviorFeign.getUnlikesBehavior(unLikesBehaviorDto);
if (unlikesBehaviorResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
ApUnlikesBehavior apUnlikesBehavior = unlikesBehaviorResponseResult.getData();
if (apUnlikesBehavior != null && apUnlikesBehavior.getType() == 0) {
isunlike = true;
}
}
// 查询用户的收藏记录
LambdaQueryWrapper<ApCollection> queryWrapper = new LambdaQueryWrapper<>();
EntryDto entryDto = new EntryDto();
entryDto.setEquipmentId(dto.getEquipmentId());
if (user != null) {
entryDto.setUserId(user.getUserId());
}
ResponseResult<ApBehaviorEntry> entryResponseResult = behaviorFeign.getEntry(entryDto);
if (entryResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
ApBehaviorEntry behaviorEntry = entryResponseResult.getData();
queryWrapper.eq(ApCollection::getEntryId, behaviorEntry.getId());
queryWrapper.eq(ApCollection::getArticleId, dto.getArticleId());
ApCollection apCollection = collectionService.getOne(queryWrapper);
if (apCollection != null) {
iscollection = true;
}
}
Map<String, Boolean> map = new HashMap<>();
map.put("isfollow", isfollow);
map.put("islike", islike);
map.put("isunlike", isunlike);
map.put("iscollection", iscollection);
return ResponseResult.okResult(map);
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-admin/src/main/java/com/heima/admin/dto/ChannelDto.java
package com.heima.admin.dto;
import com.heima.common.dto.PageRequestDto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = true)
public class ChannelDto extends PageRequestDto {
/**
* 频道名称
*/
@ApiModelProperty(value = "频道名称")
private String name;
}
<file_sep>/heima-leadnews-service/heima-leadnews-admin/src/main/java/com/heima/admin/service/impl/AuditServiceImpl.java
package com.heima.admin.service.impl;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.dto.ArticleDto;
import com.heima.admin.dto.ContentDto;
import com.heima.admin.dto.WmNews;
import com.heima.admin.dto.WmUser;
import com.heima.admin.entity.AdChannel;
import com.heima.admin.entity.AdSensitive;
import com.heima.admin.entity.ApArticleSearch;
import com.heima.admin.feign.ArticleFeign;
import com.heima.admin.feign.WeMediaFeign;
import com.heima.admin.repository.ArticleRepository;
import com.heima.admin.service.IAdChannelService;
import com.heima.admin.service.IAdSensitiveService;
import com.heima.admin.service.IAuditService;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.SensitiveWordUtil;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.*;
@Service
public class AuditServiceImpl implements IAuditService {
@Autowired
private WeMediaFeign weMediaFeign;
@Autowired
private ArticleFeign articleFeign;
@Autowired
private GreenTextScan textScan;
@Autowired
private GreenImageScan imageScan;
@Override
@GlobalTransactional
public void auditById(Integer id) {
// 1. 根据id查询自媒体文章
// 1.1 远程调用自媒体接口
ResponseResult<WmNews> wmNewsResponseResult = weMediaFeign.getById(id);
if (!wmNewsResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode()) ||
wmNewsResponseResult.getData() == null) {
return;
}
WmNews wmNews = wmNewsResponseResult.getData();
// 2. 判断自媒体文章的状态和发布时间
// 状态 0 草稿 1 提交(待审核) 2 审核失败 3 人工审核 4 人工审核通过 8 审核通过(待发布) 9 已发布
// 状态为4 判断发布时间是否大于当前时间 是-->发布文章 否-->不用处理
// 状态为8 判断发布时间是否大于当前时间 是-->发布文章 否-->不用处理
if (wmNews.getStatus() == 4 || wmNews.getStatus() == 8) {
// 判断发布时间是否大于当前时间
if (wmNews.getPublishTime().getTime() < System.currentTimeMillis()) {
saveArticle(wmNews);
}
}
if (wmNews.getStatus() == 1) {
// 3. 状态为1 需要自动审核
// 3.1 敏感词审核
boolean resultSensitive = checkBySensitive(wmNews);
// 3.2 阿里云文本审核
if (!resultSensitive) {
return;
}
boolean textAliyun = checkText(wmNews);
if (!textAliyun) {
return;
}
// 3.3 阿里云图片审核
boolean imageAliyun = checkImage(wmNews);
if (!imageAliyun) return;
// 3.4 判断发布时间 如果不大于当前时间 直接发布文章 否则修改文章状态为8
if (wmNews.getPublishTime().getTime() >= System.currentTimeMillis()) {
// 修改文章状态为8
wmNews.setStatus(8);
weMediaFeign.updateWmNews(wmNews);
} else {
saveArticle(wmNews);
}
}
}
@Autowired
private IAdChannelService channelService;
/**
* 保存文章
*
* @param wmNews
*/
private void saveArticle(WmNews wmNews) {
// 调用文章服务的远程接口
ArticleDto dto = new ArticleDto();
// 属性赋值
BeanUtils.copyProperties(wmNews, dto);
// 查询作者的id和名称
ResponseResult<WmUser> userResponseResult = weMediaFeign.getUserById(wmNews.getUserId());
if (userResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
WmUser wmUser = userResponseResult.getData();
dto.setAuthorId(wmUser.getApAuthorId());
dto.setAuthorName(wmUser.getName());
}
// 查询channelName
AdChannel adChannel = channelService.getById(wmNews.getChannelId());
if (adChannel != null) {
dto.setChannelName(adChannel.getName());
}
dto.setLayout(wmNews.getType());
dto.setFlag(0);
dto.setCreatedTime(new Date());
// 设置内容
dto.setContent(wmNews.getContent());
ResponseResult<Long> saveArticle = articleFeign.saveArticle(dto);
if (saveArticle.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
Long articleId = saveArticle.getData();
// 模拟异常
// int i = 1 / 0;
// 更新文章id到自媒体文章中
wmNews.setStatus(9);
wmNews.setArticleId(articleId);
weMediaFeign.updateWmNews(wmNews);
// 创建ES索引
ApArticleSearch apArticleSearch = new ApArticleSearch();
apArticleSearch.setId(articleId);
apArticleSearch.setTitle(wmNews.getTitle());
apArticleSearch.setLayout(wmNews.getType());
apArticleSearch.setImages(wmNews.getImages());
apArticleSearch.setPublishTime(wmNews.getPublishTime());
articleRepository.save(apArticleSearch);
}
}
@Autowired
private ArticleRepository articleRepository;
/**
* 图片审核
*
* @param wmNews
* @return
*/
private boolean checkImage(WmNews wmNews) {
Map<String, Object> textAndImageFromContent = getTextAndImageFromContent(wmNews.getContent());
List<String> images = (List<String>) textAndImageFromContent.get("images");
if (images.size() > 0) {
try {
Map map = imageScan.checkUrl(images);
// 获取到阿里云的结果 分析结果
String suggestion = (String) map.get("suggestion");
// pass 通过 block 拒绝 review 需要人工审核
// 针对于这三种结果做不同的操作
// 通过 返回true
if (suggestion.equals("pass")) {
return true;
}
String label = (String) map.get("label");
// block 需要更新自媒体文章状态为 2 审核失败 保存 返回false
if (suggestion.equals("block")) {
wmNews.setStatus(2);
wmNews.setReason("阿里云文本审核失败,标签为: " + label);
weMediaFeign.updateWmNews(wmNews);
return false;
}
// review 需要更新自媒体文章状态为 3 人工审核 保存 返回false
if (suggestion.equals("review")) {
wmNews.setStatus(3);
wmNews.setReason("阿里云文本审核需要人工审核,标签为: " + label);
weMediaFeign.updateWmNews(wmNews);
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
return true;
}
/**
* 阿里云文本审核
*
* @param wmNews
* @return
*/
private boolean checkText(WmNews wmNews) {
// 审核文章的标题和内容 将标题和内容拼接后调用阿里云接口
Map<String, Object> textAndImageFromContent = getTextAndImageFromContent(wmNews.getContent());
String content = wmNews.getTitle() + textAndImageFromContent.get("text");
try {
Map map = textScan.greenTextScan(content);
// 获取到阿里云的结果 分析结果
String suggestion = (String) map.get("suggestion");
// pass 通过 block 拒绝 review 需要人工审核
// 针对于这三种结果做不同的操作
// 通过 返回true
if (suggestion.equals("pass")) {
return true;
}
String label = (String) map.get("label");
// block 需要更新自媒体文章状态为 2 审核失败 保存 返回false
if (suggestion.equals("block")) {
wmNews.setStatus(2);
wmNews.setReason("阿里云文本审核失败,标签为: " + label);
weMediaFeign.updateWmNews(wmNews);
return false;
}
// review 需要更新自媒体文章状态为 3 人工审核 保存 返回false
if (suggestion.equals("review")) {
wmNews.setStatus(3);
wmNews.setReason("阿里云文本审核需要人工审核,标签为: " + label);
weMediaFeign.updateWmNews(wmNews);
return false;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
@Autowired
private IAdSensitiveService sensitiveService;
/**
* 敏感词审核
*
* @param wmNews
* @return
*/
private boolean checkBySensitive(WmNews wmNews) {
// 构建DFA的Map
if (SensitiveWordUtil.dictionaryMap.size() <= 0) {
// 从敏感词表中查询敏感词
LambdaQueryWrapper<AdSensitive> query = new LambdaQueryWrapper<>();
// 指定需要返回的字段 相当于 select sensitives from ad_sensitive
query.select(AdSensitive::getSensitives);
List<String> list = sensitiveService.listObjs(query, x -> (String) x);
// 初始化map
SensitiveWordUtil.initMap(list);
}
// 判断文章的标题和内容是否合法
Map<String, Integer> map = SensitiveWordUtil.matchWords(wmNews.getTitle());
if (map.size() > 0) {
// 跟新自媒体文章状态,记录拒绝原因
wmNews.setStatus(2);
wmNews.setReason("敏感词校验失败");
weMediaFeign.updateWmNews(wmNews);
return false;
}
// 获取内容
Map<String, Object> textAndImageFromContent = getTextAndImageFromContent(wmNews.getContent());
String text = (String) textAndImageFromContent.get("text");
if (!StringUtils.isEmpty(text)) {
Map<String, Integer> contentResult = SensitiveWordUtil.matchWords(text);
if (contentResult.size() > 0) {
wmNews.setStatus(2);
wmNews.setReason("敏感词校验失败");
weMediaFeign.updateWmNews(wmNews);
return false;
}
}
return true;
}
/**
* 提取内容中的文本和图片
*
* @param content
* @return
*/
private Map<String, Object> getTextAndImageFromContent(String content) {
Map<String, Object> map = new HashMap<>();
StringBuilder sb = new StringBuilder();
List<String> images = new ArrayList<>();
// 分析内容,转换成对象集合
List<ContentDto> contentDtos = JSON.parseArray(content, ContentDto.class);
for (ContentDto contentDto : contentDtos) {
if (contentDto.getType().equals("text")) {
// 文本内容
sb.append(contentDto.getValue());
}
if (contentDto.getType().equals("image")) {
// 图片内容
images.add(contentDto.getValue());
}
}
map.put("text", sb.toString());
map.put("images", images);
return map;
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/service/impl/WmNewsMaterialServiceImpl.java
package com.heima.wemedia.service.impl;
import com.heima.wemedia.entity.WmNewsMaterial;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.IWmNewsMaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 自媒体图文引用素材信息表 服务实现类
* </p>
*
* @author mcm
* @since 2021-05-20
*/
@Service
public class WmNewsMaterialServiceImpl extends ServiceImpl<WmNewsMaterialMapper, WmNewsMaterial> implements IWmNewsMaterialService {
}
<file_sep>/heima-leadnews-service/heima-leadnews-behavior/src/main/java/com/heima/behavior/config/InitConfig.java
package com.heima.behavior.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan({"com.heima.common.exception","com.heima.common.config.knife4j"})
public class InitConfig {
}
<file_sep>/heima-leadnews-service/heima-leadnews-article/src/main/java/com/heima/article/service/impl/ApCollectionServiceImpl.java
package com.heima.article.service.impl;
import com.heima.article.entity.ApCollection;
import com.heima.article.mapper.ApCollectionMapper;
import com.heima.article.service.IApCollectionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* APP收藏信息表 服务实现类
* </p>
*
* @author mcm
* @since 2021-05-29
*/
@Service
public class ApCollectionServiceImpl extends ServiceImpl<ApCollectionMapper, ApCollection> implements IApCollectionService {
}
<file_sep>/heima-leadnews-service/heima-leadnews-admin/src/main/java/com/heima/admin/dto/NewsAuthDto.java
package com.heima.admin.dto;
import com.heima.common.dto.PageRequestDto;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = true)
public class NewsAuthDto extends PageRequestDto {
/**
* 标题
*/
private String title;
/**
* 状态
*/
private Integer status;
/**
* id
*/
private Integer id;
/**
* 失败原因
*/
private String msg;
}
<file_sep>/heima-leadnews-service/heima-leadnews-article/src/main/java/com/heima/article/controller/ApArticleController.java
package com.heima.article.controller;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.article.dto.ArticleDto;
import com.heima.article.dto.ArticleHomeDto;
import com.heima.article.dto.ArticleInfoDto;
import com.heima.article.dto.CollectionBehaviorDto;
import com.heima.common.dto.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.service.IApArticleService;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 文章信息表,存储已发布的文章 前端控制器
* </p>
*
* @author mcm
* @since 2021-05-25
*/
@RestController
@RequestMapping("/api/v1/article")
@Api(tags = "文章信息表,存储已发布的文章接口")
@CrossOrigin
public class ApArticleController {
@Autowired
private IApArticleService apArticleService;
/**
* 保存文章
*
* @param dto
* @return
*/
@PostMapping
public ResponseResult<Long> saveArticle(@RequestBody ArticleDto dto) {
return apArticleService.saveArticle(dto);
}
/**
* 加载文章列表
*
* @param dto
* @return
*/
@PostMapping("/load")
public ResponseResult loadArticle(@RequestBody ArticleHomeDto dto) {
return apArticleService.loadArticle(dto, 0);
}
/**
* 上拉获取更多文章
*
* @param dto
* @return
*/
@PostMapping("/loadmore")
public ResponseResult loadMore(@RequestBody ArticleHomeDto dto) {
return apArticleService.loadArticle(dto, 1);
}
@PostMapping("/loadnew")
public ResponseResult loadNew(@RequestBody ArticleHomeDto dto) {
return apArticleService.loadArticle(dto, 0);
}
@PostMapping("/load_article_info")
public ResponseResult loadArticleInfo(@RequestBody ArticleInfoDto dto) {
return apArticleService.loadArticleInfo(dto);
}
@PostMapping("/collection")
public ResponseResult collect(@RequestBody CollectionBehaviorDto dto) {
return apArticleService.collect(dto);
}
@PostMapping("/load_article_behavior")
public ResponseResult loadBehavior(@RequestBody ArticleInfoDto dto) {
return apArticleService.loadBehavior(dto);
}
}
<file_sep>/heima-leadnews-common/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>heima-leadnews</artifactId>
<groupId>com.heima</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>heima-leadnews-common</artifactId>
<packaging>jar</packaging>
<name>heima-leadnews-common</name>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
</dependency>
<!--匹配度工具包-->
<dependency>
<groupId>com.hankcs</groupId>
<artifactId>hanlp</artifactId>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-green</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
<dependency>
<groupId>com.xuxueli</groupId>
<artifactId>xxl-job-core</artifactId>
</dependency>
</dependencies>
</project>
<file_sep>/heima-leadnews-service/heima-leadnews-behavior/src/main/java/com/heima/behavior/service/IApUnlikesBehaviorService.java
package com.heima.behavior.service;
import com.heima.behavior.dto.UnLikesBehaviorDto;
import com.heima.behavior.entity.ApUnlikesBehavior;
import com.baomidou.mybatisplus.extension.service.IService;
import com.heima.common.dto.ResponseResult;
/**
* <p>
* APP不喜欢行为表 服务类
* </p>
*
* @author mcm
* @since 2021-05-29
*/
public interface IApUnlikesBehaviorService extends IService<ApUnlikesBehavior> {
ResponseResult saveUnlikesBehavior(UnLikesBehaviorDto dto);
ResponseResult<ApUnlikesBehavior> getUnlikesBehavior(UnLikesBehaviorDto dto);
}
<file_sep>/heima-leadnews-service/heima-leadnews-user/src/main/java/com/heima/user/feign/ArticleFeign.java
package com.heima.user.feign;
import com.heima.common.dto.ResponseResult;
import com.heima.user.dto.ApAuthor;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
/**
* 文章远程接口
*/
@FeignClient("leadnews-article")
public interface ArticleFeign {
/**
* 保存文章作者
* @param entity
* @return
*/
@PostMapping("/api/v1/author")
public ResponseResult<ApAuthor> saveAuthor(@RequestBody ApAuthor entity);
/**
* 根据id查询作者
* @param id
* @return
*/
@GetMapping("/api/v1/author/{id}")
public ResponseResult<ApAuthor> getAuthorById(@PathVariable("id") Integer id);
}
<file_sep>/heima-leadnews-common/src/main/java/com/heima/common/dto/User.java
package com.heima.common.dto;
import lombok.Data;
@Data
public class User {
/**
* 用户编号
*/
private Integer userId;
}
<file_sep>/heima-leadnews-service/heima-leadnews-user/src/main/java/com/heima/user/entity/ApUserFollow.java
package com.heima.user.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
* APP用户关注信息表
* </p>
*
* @author mcm
* @since 2021-05-27
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("ap_user_follow")
@ApiModel(description="APP用户关注信息表")
public class ApUserFollow implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@ApiModelProperty(value = "主键")
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 用户ID
*/
@ApiModelProperty(value = "用户ID")
@TableField("user_id")
private Integer userId;
/**
* 用户昵称
*/
@ApiModelProperty(value = "用户昵称")
@TableField("user_name")
private String userName;
/**
* 关注作者ID
*/
@ApiModelProperty(value = "关注作者ID")
@TableField("follow_id")
private Integer followId;
/**
* 粉丝昵称
*/
@ApiModelProperty(value = "粉丝昵称")
@TableField("follow_name")
private String followName;
/**
* 关注度
0 偶尔感兴趣
1 一般
2 经常
3 高度
*/
@ApiModelProperty(value = "关注度 0 偶尔感兴趣 1 一般 2 经常 3 高度")
@TableField("level")
private Integer level;
/**
* 是否动态通知
*/
@ApiModelProperty(value = "是否动态通知")
@TableField("is_notice")
private Boolean isNotice;
/**
* 是否屏蔽评论
*/
@ApiModelProperty(value = "是否屏蔽评论")
@TableField("is_shield_comment")
private Boolean isShieldComment;
/**
* 是否可见我动态
*/
@ApiModelProperty(value = "是否可见我动态")
@TableField("is_display")
private Boolean isDisplay;
/**
* 是否屏蔽私信
*/
@ApiModelProperty(value = "是否屏蔽私信")
@TableField("is_shield_letter")
private Boolean isShieldLetter;
/**
* 创建时间
*/
@ApiModelProperty(value = "创建时间")
@TableField("created_time")
private Date createdTime;
}
<file_sep>/heima-leadnews-common/src/main/java/com/heima/common/aliyun/OSSProperties.java
package com.heima.common.aliyun;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Data
@PropertySource("oss.properties")
@ConfigurationProperties(prefix = "aliyun.oss")
@Component
public class OSSProperties {
private String accessKeyId;
private String accessKeySecret;
private String bucket;
private String host;
private String endpoint;
}
<file_sep>/heima-leadnews-service/heima-leadnews-user/src/main/java/com/heima/user/mapper/ApUserFollowMapper.java
package com.heima.user.mapper;
import com.heima.user.entity.ApUserFollow;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* APP用户关注信息表 Mapper 接口
* </p>
*
* @author mcm
* @since 2021-05-27
*/
public interface ApUserFollowMapper extends BaseMapper<ApUserFollow> {
}
<file_sep>/heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/service/impl/WmUserServiceImpl.java
package com.heima.wemedia.service.impl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.wemedia.dto.WmLoginDto;
import com.heima.wemedia.entity.WmUser;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.IWmUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import java.util.HashMap;
/**
* <p>
* 自媒体用户信息表 服务实现类
* </p>
*
* @author mcm
* @since 2021-05-19
*/
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements IWmUserService {
@Override
public ResponseResult<WmUser> saveWmUser(WmUser entity) {
// 需求 保存自媒体用户
if (entity == null || entity.getApUserId() == null) {
return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
}
// 判断自媒体用户是否已经存在
// 根据ap_user_id 查询
LambdaQueryWrapper<WmUser> query = new LambdaQueryWrapper<>();
query.eq(WmUser::getApUserId, entity.getApUserId());
WmUser wmUser = this.getOne(query);
if (wmUser != null) {
return ResponseResult.okResult(wmUser);
}
// 不存在才进行添加
this.save(entity);
return ResponseResult.okResult(entity);
}
@Override
public ResponseResult login(WmLoginDto dto) {
// 判断用户名和密码是否都为空
if (dto == null || StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())) {
return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
}
// 根据用户名查询用户
LambdaQueryWrapper<WmUser> query = new LambdaQueryWrapper<>();
query.eq(WmUser::getName, dto.getName());
WmUser adUser = this.getOne(query);
if (adUser == null) {
return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
}
// 使用传入的明文密码+查询用户的盐生成MD5密文
String pwd = dto.getPassword() + adUser.getSalt();
// 计算md5
String pass = DigestUtils.md5DigestAsHex(pwd.getBytes());
// 使用密文和表中的密码进行对比
if (!pass.equals(adUser.getPassword())) {
return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
}
// 一致 生成token 使用用户id生成token
String token = AppJwtUtil.getToken(adUser.getId().longValue());
// 返回部分用户信息 对敏感信息处理
adUser.setSalt(null);
adUser.setPassword(<PASSWORD>);
adUser.setPhone(null);
// 前端要求的返回信息
HashMap<String, Object> map = new HashMap<>();
map.put("user", adUser);
map.put("token", token);
return ResponseResult.okResult(map);
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-user/src/main/java/com/heima/user/entity/ApUserRealname.java
package com.heima.user.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
* APP实名认证信息表
* </p>
*
* @author mcm
* @since 2021-05-19
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("ap_user_realname")
@ApiModel(description="APP实名认证信息表")
public class ApUserRealname implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@ApiModelProperty(value = "主键")
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 账号ID
*/
@ApiModelProperty(value = "账号ID")
@TableField("user_id")
private Integer userId;
/**
* 用户名称
*/
@ApiModelProperty(value = "用户名称")
@TableField("name")
private String name;
/**
* 身份证号
*/
@ApiModelProperty(value = "身份证号")
@TableField("idno")
private String idno;
/**
* 正面照片
*/
@ApiModelProperty(value = "正面照片")
@TableField("font_image")
private String fontImage;
/**
* 背面照片
*/
@ApiModelProperty(value = "背面照片")
@TableField("back_image")
private String backImage;
/**
* 手持照片
*/
@ApiModelProperty(value = "手持照片")
@TableField("hold_image")
private String holdImage;
/**
* 活体照片
*/
@ApiModelProperty(value = "活体照片")
@TableField("live_image")
private String liveImage;
/**
* 状态
0 创建中
1 待审核
2 审核失败
9 审核通过
*/
@ApiModelProperty(value = "状态 0 创建中 1 待审核 2 审核失败 9 审核通过")
@TableField("status")
private Integer status;
/**
* 拒绝原因
*/
@ApiModelProperty(value = "拒绝原因")
@TableField("reason")
private String reason;
/**
* 创建时间
*/
@ApiModelProperty(value = "创建时间")
@TableField("created_time")
private Date createdTime;
/**
* 提交时间
*/
@ApiModelProperty(value = "提交时间")
@TableField("submited_time")
private Date submitedTime;
/**
* 更新时间
*/
@ApiModelProperty(value = "更新时间")
@TableField("updated_time")
private Date updatedTime;
}
<file_sep>/heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/controller/LoginController.java
package com.heima.wemedia.controller;
import com.heima.common.dto.ResponseResult;
import com.heima.wemedia.dto.WmLoginDto;
import com.heima.wemedia.service.IWmUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/login")
public class LoginController {
@Autowired
private IWmUserService userService;
@PostMapping("/in")
public ResponseResult in(@RequestBody WmLoginDto dto){
return userService.login(dto);
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-article/src/main/java/com/heima/article/dto/ArticleHomeDto.java
package com.heima.article.dto;
import lombok.Data;
import java.util.Date;
@Data
public class ArticleHomeDto {
// 最大时间
Date maxTime;
// 最小时间
Date minTime;
// 分页size
Integer size;
// 频道ID
Integer channelId;
}
<file_sep>/heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/controller/WmNewsMaterialController.java
package com.heima.wemedia.controller;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.common.dto.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.wemedia.service.IWmNewsMaterialService;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 自媒体图文引用素材信息表 前端控制器
* </p>
*
* @author mcm
* @since 2021-05-20
*/
@RestController
@RequestMapping("/api/v1/news_material")
@Api(tags = "自媒体图文引用素材信息表接口")
@CrossOrigin
public class WmNewsMaterialController{
@Autowired
private IWmNewsMaterialService wmNewsMaterialService;
}
<file_sep>/heima-leadnews-service/heima-leadnews-behavior/src/main/java/com/heima/behavior/listener/FollowListener.java
package com.heima.behavior.listener;
import com.alibaba.fastjson.JSON;
import com.heima.behavior.dto.FollowBehaviorDto;
import com.heima.behavior.service.IApFollowBehaviorService;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
@Service
public class FollowListener {
@Autowired
private IApFollowBehaviorService followBehaviorService;
// 指定监听器 指定需要监听的topic主题
@KafkaListener(topics = "${topic.followBehaviorTopic}")
public void handleMsg(ConsumerRecord<String, String> record) {
// 获取到消息
String value = record.value();
if (!StringUtils.isEmpty(value)) {
// Json转换成为对象
FollowBehaviorDto followBehaviorDto = JSON.parseObject(value, FollowBehaviorDto.class);
// 做关注行为的保存
followBehaviorService.saveBehavior(followBehaviorDto);
}
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-article/src/main/java/com/heima/article/service/IHotArticleService.java
package com.heima.article.service;
import com.heima.article.dto.ArticleStreamMessage;
public interface IHotArticleService {
public void compute();
void update(ArticleStreamMessage articleStreamMessage);
}
<file_sep>/heima-leadnews-service/heima-leadnews-article/src/main/java/com/heima/article/listener/HotArticleListener.java
package com.heima.article.listener;
import com.alibaba.fastjson.JSON;
import com.heima.article.dto.ArticleStreamMessage;
import com.heima.article.dto.UpdateArticleMessage;
import org.apache.kafka.common.serialization.Serde;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.kstream.*;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.Input;
import org.springframework.cloud.stream.annotation.Output;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.util.StringUtils;
import java.time.Duration;
@EnableBinding(value = HotArticleListener.HotArticleProcessor.class)
public class HotArticleListener {
// 监听主题和发送结果主题
@StreamListener("hot_article_score_topic")
@SendTo("hot_article_result_topic")
public KStream<String, String> process(KStream<String, String> input) {
// 从流中获取数据,进行转换
// UpdateArticleMessage {"articleId":1397400822379196418,"type":1,"add":1}
// 需要根据文章id统计一段时间内的所有操作 结果 ArticleStreamMessage
KStream<String, String> map = input.map(new KeyValueMapper<String, String, KeyValue<String, String>>() {
@Override
public KeyValue<String, String> apply(String key, String value) {
// 从JSON转换称为对象
UpdateArticleMessage updateArticleMessage = JSON.parseObject(value, UpdateArticleMessage.class);
Long articleId = updateArticleMessage.getArticleId();
return new KeyValue<>(articleId.toString(), value);
}
});
// 根据key来分组
KGroupedStream<String, String> groupByKey = map.groupByKey(Grouped.with(Serdes.String(), Serdes.String()));
// 根据时间窗口来统计
TimeWindowedKStream<String, String> windowedKStream = groupByKey.windowedBy(TimeWindows.of(Duration.ofSeconds(10)));
// 进行聚合的运算
// 运算最开始的结果
Initializer<String> init = new Initializer<String>() {
@Override
public String apply() {
return null;
}
};
// 定义聚合运算
Aggregator<String, String, String> agg = new Aggregator<String, String, String>() {
@Override
public String apply(String key, String value, String aggregate) {
// key --> 分组的key
// value --> 最初传递进来的UpdateArticleMessage {"articleId":1397400822379196418,"type":1,"add":1}
// aggregate --> 上一次聚合的结果
long articleId = Long.parseLong(key);
UpdateArticleMessage updateArticleMessage = JSON.parseObject(value, UpdateArticleMessage.class);
// 构建最终的结果 ArticleStreamMessage
ArticleStreamMessage result = null;
if (StringUtils.isEmpty(aggregate)) {
result = new ArticleStreamMessage();
result.setArticleId(articleId);
result.setView(0);
result.setLike(0);
result.setComment(0);
result.setCollect(0);
switch (updateArticleMessage.getType()) {
case 0:
result.setView(updateArticleMessage.getAdd());
break;
case 1:
result.setLike(updateArticleMessage.getAdd());
break;
case 2:
result.setComment(updateArticleMessage.getAdd());
break;
case 3:
result.setCollect(updateArticleMessage.getAdd());
break;
}
} else {
// 从上一次聚合的结果转换成对象
result = JSON.parseObject(aggregate, ArticleStreamMessage.class);
switch (updateArticleMessage.getType()) {
case 0:
result.setView(result.getView() + updateArticleMessage.getAdd());
break;
case 1:
result.setLike(result.getLike() + updateArticleMessage.getAdd());
break;
case 2:
result.setComment(result.getComment() + updateArticleMessage.getAdd());
break;
case 3:
result.setCollect(result.getCollect() + updateArticleMessage.getAdd());
break;
}
}
return JSON.toJSONString(result);
}
};
KTable<Windowed<String>, String> aggregate = windowedKStream.aggregate(init, agg, Materialized.with(Serdes.String(), Serdes.String()));
KStream<String, String> map1 = aggregate.toStream().map(new KeyValueMapper<Windowed<String>, String, KeyValue<String, String>>() {
@Override
public KeyValue<String, String> apply(Windowed<String> key, String value) {
return new KeyValue<>(key.key(), value);
}
});
return map1;
}
public interface HotArticleProcessor {
@Input("hot_article_score_topic")
KStream<String, String> input();
@Output("hot_article_result_topic")
KStream<String, String> output();
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/controller/WmMaterialController.java
package com.heima.wemedia.controller;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.common.dto.ResponseResult;
import com.heima.wemedia.dto.WmMaterialDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.wemedia.service.IWmMaterialService;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
/**
* <p>
* 自媒体图文素材信息表 前端控制器
* </p>
*
* @author mcm
* @since 2021-05-20
*/
@RestController
@RequestMapping("/api/v1/material")
@Api(tags = "自媒体图文素材信息表接口")
@CrossOrigin
public class WmMaterialController {
@Autowired
private IWmMaterialService wmMaterialService;
/**
* 图片上传
*
* @param file
* @return
*/
@PostMapping("/upload_picture")
public ResponseResult upload(MultipartFile file) {
return wmMaterialService.upload(file);
}
/**
* 加载图片列表
*
* @param dto
* @return
*/
@PostMapping("/list")
public ResponseResult listByCollection(@RequestBody WmMaterialDto dto) {
return wmMaterialService.listByCollection(dto);
}
/**
* 删除图片
*
* @param id
* @return
*/
@DeleteMapping("/{id}")
public ResponseResult deleteById(@PathVariable("id") Integer id) {
return wmMaterialService.deleteById(id);
}
/**
* 收藏图片
*
* @param id
* @return
*/
@PutMapping("/collect/{id}")
public ResponseResult collect(@PathVariable("id") Integer id) {
return wmMaterialService.updateStatus(id, 1);
}
/**
* 取消收藏
*
* @param id
* @return
*/
@PutMapping("/cancel_collect/{id}")
public ResponseResult cancelCollect(@PathVariable("id") Integer id) {
return wmMaterialService.updateStatus(id, 0);
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-user/src/main/java/com/heima/user/filter/UserFilter.java
package com.heima.user.filter;
import com.heima.common.dto.User;
import com.heima.common.util.AppThreadLocalUtil;
import com.heima.common.util.WeMediaThreadLocalUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@Service
public class UserFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
// 需求 从请求头中解析用户id
// 获取请求对象
HttpServletRequest request = (HttpServletRequest) servletRequest;
// 获取请求头
String userId = request.getHeader("userId");
if (!StringUtils.isEmpty(userId) && !userId.equals("0")) {
// 将用户id放入到本地线程中
User user = new User();
user.setUserId(Integer.parseInt(userId));
AppThreadLocalUtil.set(user);
}
// 放行请求
filterChain.doFilter(servletRequest, servletResponse);
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-article/src/main/java/com/heima/article/entity/ApArticleContent.java
package com.heima.article.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
* APP已发布文章内容表
* </p>
*
* @author mcm
* @since 2021-05-25
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("ap_article_content")
@ApiModel(description="APP已发布文章内容表")
public class ApArticleContent implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@ApiModelProperty(value = "主键")
@TableId(value = "id", type = IdType.ASSIGN_ID)
private Long id;
/**
* 文章ID
*/
@ApiModelProperty(value = "文章ID")
@TableField("article_id")
private Long articleId;
/**
* 文章内容
*/
@ApiModelProperty(value = "文章内容")
@TableField("content")
private String content;
}
<file_sep>/heima-leadnews-service/heima-leadnews-admin/src/main/java/com/heima/admin/service/IAuditService.java
package com.heima.admin.service;
public interface IAuditService {
/**
* 根据自媒体文章id审核文章
* @param id
*/
public void auditById(Integer id);
}
<file_sep>/heima-leadnews-service/heima-leadnews-user/src/main/java/com/heima/user/controller/ApUserRealnameController.java
package com.heima.user.controller;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.common.dto.ResponseResult;
import com.heima.user.dto.AuthDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.user.service.IApUserRealnameService;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* APP实名认证信息表 前端控制器
* </p>
*
* @author mcm
* @since 2021-05-19
*/
@RestController
@RequestMapping("/api/v1/auth")
@Api(tags = "APP实名认证信息表接口")
@CrossOrigin
public class ApUserRealnameController {
@Autowired
private IApUserRealnameService apUserRealnameService;
@PostMapping("/list")
public ResponseResult listByStatus(@RequestBody AuthDto dto) {
return apUserRealnameService.listByStatus(dto);
}
@PostMapping("/authPass")
public ResponseResult authPass(@RequestBody AuthDto dto) {
return apUserRealnameService.auth(dto, 1);
}
@PostMapping("/authFail")
public ResponseResult authFail(@RequestBody AuthDto dto) {
return apUserRealnameService.auth(dto, 0);
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-user/src/main/java/com/heima/user/service/IApUserRealnameService.java
package com.heima.user.service;
import com.heima.common.dto.ResponseResult;
import com.heima.user.dto.AuthDto;
import com.heima.user.entity.ApUserRealname;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* APP实名认证信息表 服务类
* </p>
*
* @author mcm
* @since 2021-05-19
*/
public interface IApUserRealnameService extends IService<ApUserRealname> {
ResponseResult listByStatus(AuthDto dto);
ResponseResult auth(AuthDto dto, int type);
}
<file_sep>/README.md
# toutiao
新闻资讯
<file_sep>/heima-leadnews-service/heima-leadnews-search/src/main/java/com/heima/search/controller/ApAssociateWordsController.java
package com.heima.search.controller;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.common.dto.ResponseResult;
import com.heima.search.dto.UserSearchDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.search.service.IApAssociateWordsService;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 联想词表 前端控制器
* </p>
*
* @author mcm
* @since 2021-06-01
*/
@RestController
@RequestMapping("/api/v1/associate")
@Api(tags = "联想词表接口")
@CrossOrigin
public class ApAssociateWordsController {
@Autowired
private IApAssociateWordsService apAssociateWordsService;
@PostMapping("/search")
private ResponseResult load(@RequestBody UserSearchDto dto) {
// return apAssociateWordsService.load(dto);
return apAssociateWordsService.load2(dto);
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-user/src/main/java/com/heima/user/mapper/ApUserMapper.java
package com.heima.user.mapper;
import com.heima.user.entity.ApUser;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* APP用户信息表 Mapper 接口
* </p>
*
* @author mcm
* @since 2021-05-19
*/
public interface ApUserMapper extends BaseMapper<ApUser> {
}
<file_sep>/heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/WeMediaApp.java
package com.heima.wemedia;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WeMediaApp {
public static void main(String[] args) {
SpringApplication.run(WeMediaApp.class, args);
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-user/src/main/java/com/heima/user/service/impl/ApUserFollowServiceImpl.java
package com.heima.user.service.impl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppThreadLocalUtil;
import com.heima.user.dto.ApAuthor;
import com.heima.user.dto.FollowBehaviorDto;
import com.heima.user.dto.UserRelationDto;
import com.heima.user.entity.ApUserFollow;
import com.heima.user.feign.ArticleFeign;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.service.IApUserFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* <p>
* APP用户关注信息表 服务实现类
* </p>
*
* @author mcm
* @since 2021-05-27
*/
@Service
public class ApUserFollowServiceImpl extends ServiceImpl<ApUserFollowMapper, ApUserFollow> implements IApUserFollowService {
@Autowired
private ArticleFeign articleFeign;
@Override
public ResponseResult getFollow(FollowBehaviorDto dto) {
// 根据用户id和关注的id查询
LambdaQueryWrapper<ApUserFollow> query = new LambdaQueryWrapper<>();
query.eq(ApUserFollow::getUserId,dto.getUserId());
query.eq(ApUserFollow::getFollowId,dto.getFollowId());
ApUserFollow apUserFollow = this.getOne(query);
return ResponseResult.okResult(apUserFollow);
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/entity/WmMaterial.java
package com.heima.wemedia.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
* 自媒体图文素材信息表
* </p>
*
* @author mcm
* @since 2021-05-20
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("wm_material")
@ApiModel(description="自媒体图文素材信息表")
public class WmMaterial implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@ApiModelProperty(value = "主键")
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 自媒体用户ID
*/
@ApiModelProperty(value = "自媒体用户ID")
@TableField("user_id")
private Integer userId;
/**
* 图片地址
*/
@ApiModelProperty(value = "图片地址")
@TableField("url")
private String url;
/**
* 素材类型
0 图片
1 视频
*/
@ApiModelProperty(value = "素材类型 0 图片 1 视频")
@TableField("type")
private Integer type;
/**
* 是否收藏
*/
@ApiModelProperty(value = "是否收藏")
@TableField("is_collection")
private Boolean isCollection;
/**
* 创建时间
*/
@ApiModelProperty(value = "创建时间")
@TableField("created_time")
private Date createdTime;
}
<file_sep>/heima-leadnews-common/src/main/java/com/heima/common/aliyun/OSSService.java
package com.heima.common.aliyun;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
@Service
public class OSSService {
@Autowired
private OSSProperties prop;
@Autowired
private OSS ossClient;
// 支持的文件类型
private static final List<String> suffixes = Arrays.
asList("image/png", "image/jpeg", "image/bmp");
/**
* 本地上传
*
* @param file
* @return
*/
public String upload(MultipartFile file) throws Exception {
// 检查文件类型是否支持
String contentType = file.getContentType();
if (!suffixes.contains(contentType)) {
throw new Exception("不支持文件类型");
}
// 检查当前文件是否是图片,使用java提供的ImageIO工具
try {
BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
if (bufferedImage == null) {
throw new Exception("不支持文件类型");
}
// 原文件名
String originalFilename = file.getOriginalFilename();
// 获取文件的后缀
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
// 构造新的文件名,名字不重复
String newFileName = UUID.randomUUID().toString() + suffix;
// 上传文件
InputStream inputStream = file.getInputStream();
PutObjectRequest putObjectRequest = new PutObjectRequest(prop.getBucket(), newFileName, inputStream);
ossClient.putObject(putObjectRequest);
// https://XXX.oss-cn-beijing.aliyuncs.com/XXXXXX.jpg
String url = prop.getHost() + "/" + newFileName;
return url;
} catch (IOException e) {
e.printStackTrace();
throw new Exception("上传文件失败");
}
}
/**
* 删除文件
*
* @param url
* @return
*/
public String deleteFile(String url) {
String objectName = url.replace(prop.getHost() + "/", "");
ossClient.deleteObject(prop.getBucket(), objectName);
return "删除成功";
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-article/src/main/java/com/heima/article/feign/BehaviorFeign.java
package com.heima.article.feign;
import com.heima.article.dto.*;
import com.heima.common.dto.ResponseResult;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
@FeignClient("leadnews-behavior")
public interface BehaviorFeign {
@PostMapping("/api/v1/behavior_entry/getEntry")
public ResponseResult<ApBehaviorEntry> getEntry(@RequestBody EntryDto dto);
@PostMapping("/api/v1/likes_behavior/getLike")
public ResponseResult<ApLikesBehavior> getLikesBehavior(@RequestBody LikesBehaviorDto dto);
@PostMapping("/api/v1/unlikes_behavior/getUnLikes")
public ResponseResult<ApUnlikesBehavior> getUnlikesBehavior(@RequestBody UnLikesBehaviorDto dto);
}
<file_sep>/heima-leadnews-service/heima-leadnews-article/src/main/java/com/heima/article/service/impl/ApArticleContentServiceImpl.java
package com.heima.article.service.impl;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.service.IApArticleContentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* APP已发布文章内容表 服务实现类
* </p>
*
* @author mcm
* @since 2021-05-25
*/
@Service
public class ApArticleContentServiceImpl extends ServiceImpl<ApArticleContentMapper, ApArticleContent> implements IApArticleContentService {
}
<file_sep>/heima-leadnews-service/heima-leadnews-article/src/main/java/com/heima/article/ArticleApp.java
package com.heima.article;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableFeignClients
public class ArticleApp {
public static void main(String[] args) {
SpringApplication.run(ArticleApp.class, args);
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-behavior/src/main/java/com/heima/behavior/controller/ApFollowBehaviorController.java
package com.heima.behavior.controller;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.common.dto.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.behavior.service.IApFollowBehaviorService;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* APP关注行为表 前端控制器
* </p>
*
* @author mcm
* @since 2021-05-29
*/
@RestController
@RequestMapping("/api/v1/follow_behavior")
@Api(tags = "APP关注行为表接口")
@CrossOrigin
public class ApFollowBehaviorController{
@Autowired
private IApFollowBehaviorService apFollowBehaviorService;
}
<file_sep>/heima-leadnews-service/heima-leadnews-article/src/main/java/com/heima/article/controller/ApAuthorController.java
package com.heima.article.controller;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.article.entity.ApAuthor;
import com.heima.common.dto.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.service.IApAuthorService;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* APP文章作者信息表 前端控制器
* </p>
*
* @author mcm
* @since 2021-05-19
*/
@RestController
@RequestMapping("/api/v1/author")
@Api(tags = "APP文章作者信息表接口")
@CrossOrigin
public class ApAuthorController{
@Autowired
private IApAuthorService apAuthorService;
/**
* 保存文章作者
* @param entity
* @return
*/
@PostMapping
public ResponseResult<ApAuthor> saveAuthor(@RequestBody ApAuthor entity){
return apAuthorService.saveAuthor(entity);
}
/**
* 根据id查询作者
* @param id
* @return
*/
@GetMapping("/{id}")
public ResponseResult<ApAuthor> getAuthorById(@PathVariable("id") Integer id){
ApAuthor apAuthor = apAuthorService.getById(id);
return ResponseResult.okResult(apAuthor);
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-behavior/src/main/java/com/heima/behavior/service/impl/ApLikesBehaviorServiceImpl.java
package com.heima.behavior.service.impl;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.behavior.dto.EntryDto;
import com.heima.behavior.dto.LikesBehaviorDto;
import com.heima.behavior.dto.UpdateArticleMessage;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.entity.ApLikesBehavior;
import com.heima.behavior.mapper.ApLikesBehaviorMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.behavior.service.IApLikesBehaviorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import java.util.Date;
/**
* <p>
* APP点赞行为表 服务实现类
* </p>
*
* @author mcm
* @since 2021-05-29
*/
@Service
public class ApLikesBehaviorServiceImpl extends ServiceImpl<ApLikesBehaviorMapper, ApLikesBehavior> implements IApLikesBehaviorService {
@Autowired
private IApBehaviorEntryService entryService;
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
@Value("${topic.hotArticleScoreTopic}")
private String hotArticleScoreTopic;
@Override
public ResponseResult saveLikesBehavior(LikesBehaviorDto dto) {
// 构建ApLikesBehavior对象
ApLikesBehavior likesBehavior = new ApLikesBehavior();
// 获取当前的用户
User user = AppThreadLocalUtil.get();
EntryDto entryDto = new EntryDto();
entryDto.setEquipmentId(dto.getEquipmentId());
if (user != null) {
entryDto.setUserId(user.getUserId());
}
ApBehaviorEntry entry = entryService.getEntry(entryDto);
likesBehavior.setEntryId(entry.getId());
likesBehavior.setArticleId(dto.getArticleId());
likesBehavior.setType(0);
likesBehavior.setOperation(dto.getOperation());
likesBehavior.setCreatedTime(new Date());
// 查询是否已经有点赞的记录
LambdaQueryWrapper<ApLikesBehavior> query = new LambdaQueryWrapper<>();
query.eq(ApLikesBehavior::getEntryId, entry.getId());
query.eq(ApLikesBehavior::getArticleId, dto.getArticleId());
ApLikesBehavior apLikesBehavior = this.getOne(query);
if (apLikesBehavior != null) {
if (apLikesBehavior.getOperation() != dto.getOperation()) {
apLikesBehavior.setOperation(dto.getOperation());
this.updateById(apLikesBehavior);
}
} else {
// 保存
this.save(likesBehavior);
// 发送消息到kafka
UpdateArticleMessage message = new UpdateArticleMessage();
message.setType(1);
message.setArticleId(dto.getArticleId());
message.setAdd(1);
kafkaTemplate.send(hotArticleScoreTopic, JSON.toJSONString(message));
}
return ResponseResult.okResult();
}
@Override
public ResponseResult getLikesBehavior(LikesBehaviorDto dto) {
// 获取当前的用户
if (dto.getUserId() == null) {
User user = AppThreadLocalUtil.get();
dto.setUserId(user.getUserId());
}
EntryDto entryDto = new EntryDto();
entryDto.setEquipmentId(dto.getEquipmentId());
entryDto.setUserId(dto.getUserId());
ApBehaviorEntry entry = entryService.getEntry(entryDto);
// 查询是否已经有点赞的记录
LambdaQueryWrapper<ApLikesBehavior> query = new LambdaQueryWrapper<>();
query.eq(ApLikesBehavior::getEntryId, entry.getId());
query.eq(ApLikesBehavior::getArticleId, dto.getArticleId());
ApLikesBehavior apLikesBehavior = this.getOne(query);
return ResponseResult.okResult(apLikesBehavior);
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/mapper/WmUserMapper.java
package com.heima.wemedia.mapper;
import com.heima.wemedia.entity.WmUser;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 自媒体用户信息表 Mapper 接口
* </p>
*
* @author mcm
* @since 2021-05-19
*/
public interface WmUserMapper extends BaseMapper<WmUser> {
}
<file_sep>/heima-leadnews-common/src/main/java/com/heima/common/util/WeMediaThreadLocalUtil.java
package com.heima.common.util;
import com.heima.common.dto.User;
public class WeMediaThreadLocalUtil {
private static ThreadLocal<User> threadLocal = new ThreadLocal<>();
/**
* 设置本地线程用户
*
* @param user
*/
public static void set(User user) {
threadLocal.set(user);
}
/**
* 获取本地线程用户
* @return
*/
public static User get() {
return threadLocal.get();
}
}
<file_sep>/heima-leadnews-service/heima-leadnews-user/src/main/java/com/heima/user/dto/LoginDto.java
package com.heima.user.dto;
import lombok.Data;
@Data
public class LoginDto {
//设备id
private String equipmentId;
//手机号
private String phone;
//密码
private String password;
}
<file_sep>/heima-leadnews-service/heima-leadnews-admin/src/main/java/com/heima/admin/service/IAdSensitiveService.java
package com.heima.admin.service;
import com.heima.admin.dto.SensitiveDto;
import com.heima.admin.entity.AdSensitive;
import com.baomidou.mybatisplus.extension.service.IService;
import com.heima.common.dto.ResponseResult;
/**
* <p>
* 敏感词信息表 服务类
* </p>
*
* @author mcm
* @since 2021-05-18
*/
public interface IAdSensitiveService extends IService<AdSensitive> {
ResponseResult listByName(SensitiveDto dto);
ResponseResult saveSensitive(AdSensitive entity);
ResponseResult updateSensitive(AdSensitive entity);
}
<file_sep>/heima-leadnews-service/heima-leadnews-article/src/main/java/com/heima/article/feign/UserFeign.java
package com.heima.article.feign;
import com.heima.article.dto.ApUserFollow;
import com.heima.article.dto.FollowBehaviorDto;
import com.heima.article.dto.UserRelationDto;
import com.heima.common.dto.ResponseResult;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
@FeignClient("leadnews-user")
public interface UserFeign {
@PostMapping("/api/v1/user_follow/getFollow")
public ResponseResult<ApUserFollow> getFollow(@RequestBody FollowBehaviorDto dto);
}
<file_sep>/heima-leadnews-service/heima-leadnews-admin/src/main/java/com/heima/admin/mapper/AdUserMapper.java
package com.heima.admin.mapper;
import com.heima.admin.entity.AdUser;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 管理员用户信息表 Mapper 接口
* </p>
*
* @author mcm
* @since 2021-05-18
*/
public interface AdUserMapper extends BaseMapper<AdUser> {
}
<file_sep>/heima-leadnews-service/heima-leadnews-admin/src/main/java/com/heima/admin/dto/ApArticle.java
package com.heima.admin.dto;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.Date;
/**
* <p>
* 文章信息表,存储已发布的文章
* </p>
*
* @author mcm
* @since 2021-05-25
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("ap_article")
@ApiModel(description="文章信息表,存储已发布的文章")
public class ApArticle implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.ASSIGN_ID)
private Long id;
/**
* 标题
*/
@ApiModelProperty(value = "标题")
@TableField("title")
private String title;
/**
* 文章作者的ID
*/
@ApiModelProperty(value = "文章作者的ID")
@TableField("author_id")
private Integer authorId;
/**
* 作者昵称
*/
@ApiModelProperty(value = "作者昵称")
@TableField("author_name")
private String authorName;
/**
* 文章所属频道ID
*/
@ApiModelProperty(value = "文章所属频道ID")
@TableField("channel_id")
private Integer channelId;
/**
* 频道名称
*/
@ApiModelProperty(value = "频道名称")
@TableField("channel_name")
private String channelName;
/**
* 文章布局
0 无图文章
1 单图文章
2 多图文章
*/
@ApiModelProperty(value = "文章布局 0 无图文章 1 单图文章 2 多图文章")
@TableField("layout")
private Integer layout;
/**
* 文章标记
0 普通文章
1 热点文章
2 置顶文章
3 精品文章
4 大V 文章
*/
@ApiModelProperty(value = "文章标记 0 普通文章 1 热点文章 2 置顶文章 3 精品文章 4 大V 文章")
@TableField("flag")
private Integer flag;
/**
* 文章图片
多张逗号分隔
*/
@ApiModelProperty(value = "文章图片 多张逗号分隔")
@TableField("images")
private String images;
/**
* 文章标签最多3个 逗号分隔
*/
@ApiModelProperty(value = "文章标签最多3个 逗号分隔")
@TableField("labels")
private String labels;
/**
* 点赞数量
*/
@ApiModelProperty(value = "点赞数量")
@TableField("likes")
private Integer likes;
/**
* 收藏数量
*/
@ApiModelProperty(value = "收藏数量")
@TableField("collection")
private Integer collection;
/**
* 评论数量
*/
@ApiModelProperty(value = "评论数量")
@TableField("comment")
private Integer comment;
/**
* 阅读数量
*/
@ApiModelProperty(value = "阅读数量")
@TableField("views")
private Integer views;
/**
* 省市
*/
@ApiModelProperty(value = "省市")
@TableField("province_id")
private Integer provinceId;
/**
* 市区
*/
@ApiModelProperty(value = "市区")
@TableField("city_id")
private Integer cityId;
/**
* 区县
*/
@ApiModelProperty(value = "区县")
@TableField("county_id")
private Integer countyId;
/**
* 创建时间
*/
@ApiModelProperty(value = "创建时间")
@TableField("created_time")
private Date createdTime;
/**
* 发布时间
*/
@ApiModelProperty(value = "发布时间")
@TableField("publish_time")
private Date publishTime;
/**
* 同步状态
*/
@ApiModelProperty(value = "同步状态")
@TableField("sync_status")
private Integer syncStatus;
/**
* 来源
*/
@ApiModelProperty(value = "来源")
@TableField("origin")
private Integer origin;
/**
* 是否可评论
*/
@ApiModelProperty(value = "是否可评论")
@TableField("is_comment")
private Boolean isComment;
/**
* 是否可转发
*/
@ApiModelProperty(value = "是否可转发")
@TableField("is_forward")
private Boolean isForward;
/**
* 是否下架
*/
@ApiModelProperty(value = "是否下架")
@TableField("is_down")
private Boolean isDown;
/**
* 是否已删除
*/
@ApiModelProperty(value = "是否已删除")
@TableField("is_delete")
private Boolean isDelete;
}
<file_sep>/heima-leadnews-service/heima-leadnews-behavior/src/main/java/com/heima/behavior/mapper/ApReadBehaviorMapper.java
package com.heima.behavior.mapper;
import com.heima.behavior.entity.ApReadBehavior;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* APP阅读行为表 Mapper 接口
* </p>
*
* @author mcm
* @since 2021-05-29
*/
public interface ApReadBehaviorMapper extends BaseMapper<ApReadBehavior> {
}
| d216695c5dad232b2af9790ff2a8f5c1898259a1 | [
"Markdown",
"Java",
"Maven POM",
"INI"
] | 85 | Java | stephendengbl/toutiao | a924197d6dbb48bc0262966467ff6a267f74fed1 | 93d9eb7f5ade416aae41d2216c63a423e21de45c |
refs/heads/master | <file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Employee;
use App\Company;
class EmployeeController extends Controller
{
public function index()
{
$employees = Employee::with('companies')->latest()->paginate(10);
return view('employee.employee', compact('employees'));
}
public function show($id)
{
$employee = Employee::find($id);
return view('employee.show')->with('employee', $employee);
}
public function create()
{
$employees = Employee::all();
$companies = Company::all();
return view('employee.create', compact('companies'));
}
public function store(Request $request)
{
$this->validate($request,[
'firstname' => 'required',
'lastname' => 'required',
]);
$employee = new Employee;
$employee->firstname = $request->input('firstname');
$employee->lastname = $request->input('lastname');
$employee->email = $request->input('email');
$employee->phone = $request->input('phone');
$employee->company_id = $request->input('company_id');
$employee->save();
return redirect('/employees')->with('success', 'Employee was added');
}
public function edit($id)
{
$employee = Employee::find($id);
$companies = Company::all();
return view('employee.edit', compact('companies', 'employee'));
}
public function update(Request $request, $id)
{
$this->validate($request,[
'firstname' => 'required',
'lastname' => 'required',
]);
$employee = Employee::find($id);
$employee->firstname = $request->input('firstname');
$employee->lastname = $request->input('lastname');
$employee->email = $request->input('email');
$employee->phone = $request->input('phone');
$employee->company_id = $request->input('company_id');
$employee->save();
return redirect('/employees')->with('success', 'Employee was updated');
}
public function destroy($id)
{
$employee = employee::find($id);
$employee->delete();
return redirect('/employees')->with('success', 'Employee was deleted');
}
}
<file_sep><?php
Route::get('/', function () {
return view('index');
});
Auth::routes();
Route::get('/register', function(){
return redirect('/');
});
Route::get('/home', 'HomeController@index')->name('home');
Route::get('/companies', 'CompanyController@index');
Route::get('/companies/create', 'CompanyController@create');
Route::get('/companies/{id}', 'CompanyController@show');
Route::post('/companies/store', 'CompanyController@store');
Route::get('/companies/{id}/edit', 'CompanyController@edit');
Route::delete('/companies/{id}', 'CompanyController@destroy');
Route::put('/companies/{id}', 'CompanyController@update');
Route::get('/employees', 'EmployeeController@index');
Route::get('/employees/create', 'EmployeeController@create');
Route::get('/employees/{id}', 'EmployeeController@show');
Route::post('/employees/store', 'EmployeeController@store');
Route::get('/employees/{id}/edit', 'EmployeeController@edit');
Route::delete('/employees/{id}', 'EmployeeController@destroy');
Route::put('/employees/{id}', 'EmployeeController@update');<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use App\Company;
use App\Employee;
class CompanyController extends Controller
{
public function index()
{
$companies = Company::latest()->paginate(10);
return view('company.company')->with('companies', $companies);
}
public function show($id)
{
$company = Company::find($id);
$employees = $company->employees()->paginate(10);
return view('company.show', compact(['company'],['employees']),);
}
public function create()
{
$companies = Company::all();
return view('company.create')->with('companies', $companies);
}
public function store(Request $request)
{
$this->validate($request,[
'name' => 'required',
]);
$company = new Company;
$company->name = $request->input('name');
$company->email = $request->input('email');
$company->website = $request->input('website');
$path = $request->file('logo')->store('/images');
$company->logo = $path;
$company->save();
return redirect('/companies')->with('success', 'Company was added');
}
public function edit($id)
{
$company = Company::find($id);
return view('company.edit')->with('company', $company);
}
public function update(Request $request, $id)
{
$this->validate($request,[
'name' => 'required',
]);
$company = Company::find($id);
$company->name = $request->input('name');
$company->email = $request->input('email');
$company->website = $request->input('website');
$path = $request->file('logo')->store('logo', 'public');
$company->logo = $path;
$company->save();
return redirect('/companies')->with('success', 'Company was updated');
}
public function destroy($id)
{
$company = Company::find($id);
$company->delete();
return redirect('/companies')->with('success', 'Company was deleted');
}
}
<file_sep><?php
use Illuminate\Support\Str;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use App\Employee;
use App\Company;
class EmployeeSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
factory(Company::class, 5)->create()->each(function ($company) {
factory(Employee::class, 5)->create(['company_id'=>$company->id]);
});
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Company;
class Employee extends Model
{
public function companies()
{
return $this->belongsTo(\App\Company::class, 'company_id');
}
}
| 604f4d642c93492edad5187003727b2aedf0e334 | [
"PHP"
] | 5 | PHP | Ziyod31/TestProject | 8e61578ddc25e2cf445dfaecc0a2be4959f72211 | 5a82ae13463fede0624061a0ff0ebc55e380ede3 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Support.V7.App;
using Android.Util;
using Android.Views;
using Android.Widget;
using SQLite;
namespace FragmentSample
{
public class PlayQuoteFragment : Fragment
{
public int NoteId => Arguments.GetInt("current_note_id", 0);
DatabaseHelper databaseHelper = new DatabaseHelper();
EditText editNote;
EditText editTitle;
public static PlayQuoteFragment NewInstance(int noteId)
{
var bundle = new Bundle();
bundle.PutInt("current_note_id", noteId);
return new PlayQuoteFragment { Arguments = bundle };
}
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your fragment here
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
if (container == null)
{
return null;
}
var view = inflater.Inflate(Resource.Layout.EditNotes, null);
var switcher = (ViewSwitcher)view.FindViewById(Resource.Id.viewSwitcher1);
TextView textTitle = view.FindViewById<TextView>(Resource.Id.txtNote);
TextView textNote = view.FindViewById<TextView>(Resource.Id.txtNoteGlimpse);
Button editButton = view.FindViewById<Button>(Resource.Id.button_edit);
Button deleteButton = view.FindViewById<Button>(Resource.Id.button_delete);
// second view items
EditText editTitle = view.FindViewById<EditText>(Resource.Id.txtNote);
EditText editNote = view.FindViewById<EditText>(Resource.Id.txtNoteGlimpse);
if (editTitle != null)
{
this.editTitle = editTitle;
this.editNote = editNote;
}
Button saveEditButton = view.FindViewById<Button>(Resource.Id.button_edit);
// switch to edit mode
editButton.Click += delegate {
switcher.ShowNext();
var allNotes = databaseHelper.GetAllNotes();
var curNote = allNotes.ElementAt(NoteId);
EditButton_Clicked(curNote);
};
// save edited note
var intent = new Intent(Activity, typeof(MainActivity));
// delete note
deleteButton.Click += delegate
{
var allNotes = databaseHelper.GetAllNotes();
var curNote = allNotes.ElementAt(NoteId);
databaseHelper.DeleteNote(curNote.ID); StartActivity(intent);
};
var NoteList = databaseHelper.GetAllNotes().ToList();
if (NoteList.Count == 0)
return null;
var result = NoteList[NoteId];
textTitle.Text = result.Title;
textNote.Text = result.Content;
return view;
}
//edit note
public void EditButton_Clicked(Note note)
{
var intent = new Intent(Activity, typeof(MainActivity));
note.Title = editTitle.Text;
note.Content = editNote.Text;
databaseHelper.EditNote(note);
StartActivity(intent);
}
}
}<file_sep>using Android.App;
using Android.OS;
using Android.Support.V7.App;
using Android.Runtime;
using Android.Widget;
using Android.Views;
using System.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.AppCenter;
using Microsoft.AppCenter.Analytics;
using Microsoft.AppCenter.Crashes;
using Microsoft.AppCenter.Distribute;
namespace FragmentSample
{
[Activity(Label = "@string/app_name", Theme = "@style/AppTheme" )]
public class MainActivity : AppCompatActivity
{
DatabaseHelper databaseHelper = new DatabaseHelper();
List<string> TitleList = new List<string>(Titles);
List<string> NoteList = new List<string>(Notes);
protected override void OnCreate(Bundle savedInstanceState)
{
//AppCenter.Start("5bdb87e5-6c27-4009-9226-fa2b92e0beb0", typeof(Distribute));
//AppCenter.Start("5bdb87e5-6c27-4009-9226-fa2b92e0beb0", typeof(Analytics), typeof(Crashes));
AppCenter.Start("75171bf8-d9bf-4172-88e1-8e5dbaddbbc6",
typeof(Analytics), typeof(Crashes));
AppCenter.Start("75171bf8-d9bf-4172-88e1-8e5dbaddbbc6", typeof(Analytics), typeof(Crashes));
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);
if (!File.Exists(Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "myNotes2.db3")))
{
databaseHelper.CreateDatabaseWithTable();
}
}
public override bool OnCreateOptionsMenu(IMenu menu)
{
MenuInflater.Inflate(Resource.Menu.menu_main, menu);
return base.OnCreateOptionsMenu(menu);
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
if (item.ItemId == Resource.Id.AddNote)
{
StartActivity(typeof(CreateNotesActivity));
Toast.MakeText(this, "Write your note and press the button again.", ToastLength.Short).Show();
return true;
}
return base.OnOptionsItemSelected(item);
}
public static string[] Titles = { };
public static string[] Notes = { };
}
}<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using SQLite;
namespace FragmentSample
{
public class DatabaseHelper
{
SQLiteConnection db;
string dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "myNotes5.db3");
public DatabaseHelper()
{
db = new SQLiteConnection(dbPath);
CreateDatabaseWithTable();
}
public void CreateDatabaseWithTable()
{
db.CreateTable<Note>();
}
public TableQuery<Note> GetAllNotes()
{
return db.Table<Note>();
}
public void AddNote(string title, string content)
{
Note newNote = new Note();
newNote.Title = title;
newNote.CreationTime = DateTime.Now;
newNote.Content = content;
db.Insert(newNote);
}
public void DeleteNote(int id)
{
db.Delete<Note>(id);
}
public void EditNote(Note note)
{
db.Update(note);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace FragmentSample
{
public class FileHandler
{
public static string GetPath(string filename)
{
var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var filePath = Path.Combine(documentsPath, filename);
return filePath;
}
public static void Write(string path, string content)
{
File.AppendAllText(path, content + System.Environment.NewLine);
}
}
}
| 456dad725c8eaeffd1fd36822918ed3b920083fa | [
"C#"
] | 4 | C# | JasperNoorkoiv/FragmentNotes | 39c29634f684e28633ec983eb2f8b2a1b5aeb81b | 0d0d48bac54fbe32f7d84c8ddfe0f3bb4f96b1b0 |
refs/heads/master | <file_sep>
#ifndef EMSSYSTEM_H_
#define EMSSYSTEM_H_
#include "EMSChannel.h"
#define ACTION 'G'
#define CHANNEL 'C'
#define INTENSITY 'I'
#define TIME 'T'
#define OPTION 'O'
class EMSSystem {
public:
EMSSystem(int channels);
virtual ~EMSSystem();
virtual void addChannelToSystem(EMSChannel *emsChannel);
virtual void doCommand(String *command);
void shutDown();
virtual int check();
static void start();
protected:
virtual void doActionCommand(String *command);
virtual void setOption(String *option);
virtual bool getChannelAndValue(String *option, int *channel, int *value);
virtual int getNextNumberOfSting(String *command, int startIndex);
private:
EMSChannel **emsChannels;
int channelCount;
int size;
bool isInRange(int channel);
};
#endif /* EMSSYSTEM_H_ */
<file_sep>
#include "AD5252.h"
AD5252::AD5252(uint8_t address) {
this->address = address;
}
AD5252::~AD5252() {
// TODO Auto-generated destructor stub
}
//whiper index is 1 or 3
void AD5252::setPosition(uint8_t wiperIndex, uint8_t whiperPosition){
Wire.beginTransmission(poti_manufactur_address);
Wire.write(wiperIndex);
Wire.write(whiperPosition);
Wire.endTransmission(1);
}
void AD5252::setPosition_sync(uint8_t wiperIndex1,uint8_t wiperIndex2, uint8_t whiperPosition){
Wire.beginTransmission(poti_manufactur_address);
Wire.write(wiperIndex1);
Wire.write(wiperIndex2);
Wire.write(whiperPosition);
Wire.endTransmission(1);
}
//whiper is 1 or 3
uint8_t AD5252::getPosition(uint8_t wiperIndex){
Wire.beginTransmission(poti_manufactur_address);
Wire.write(wiperIndex);
Wire.endTransmission();
Wire.requestFrom(poti_manufactur_address, (uint8_t)1);
uint8_t one = Wire.read();
return one;
}
void AD5252::decrement(uint8_t wiperIndex) {
}
void AD5252::increment(uint8_t wiperIndex) {
}
void AD5252::increment(uint8_t wiperIndex, int steps, int stepDelay) {
}
void AD5252::decrement(uint8_t wiperIndex, int steps, int stepDelay) {
}
<file_sep>
// Necessary files ( AD5252.h, EMSSystem.h, EMSChannel.h) and dependencies (Wire.h, Arduino.h)
// TESTING COMMANDS
// For quick testing (e.g., opening the optocoupler ports, etc) you can use these single-char commands (one command = one char).
// The available commands are:
// "1": toggles the channel 1 between open/closed state (when the channel is closed, the potenciometer position is reset to minimum, i.e., 255)
// "2": toggles the channel 1 between open/closed state (when the channel is closed, the potenciometer position is reset to minimum, i.e., 255)
// "q": increases EMS signal on channel 1 by decreasing the digital potenciometer wiper position (i.e., resistance lowers and more EMS is passing)
// -> note that you have full EMS signal when the potentiometer wiper is at 0 (0 is the maximum)
// "a": decreases EMS signal on channel 1 by increasing the digital potenciometer wiper position (i.e., resistance lowers and more EMS is passing)
// -> note that you have no EMS signal when the potentiometer wiper is at 255 (255 is the maximum resistance of the potentiometer)
// "w": increases EMS signal on channel 2 by decreasing the digital potenciometer wiper position (i.e., resistance lowers and more EMS is passing)
// -> note that you have full EMS signal when the potentiometer wiper is at 0 (0 is the maximum)
// "s": decreases EMS signal on channel 2 by increasing the digital potenciometer wiper position (i.e., resistance lowers and more EMS is passing)
// -> note that you have no EMS signal when the potentiometer wiper is at 255 (255 is the maximum resistance of the potentiometer)
// TESTING COMMANDS
#include "Arduino.h"
#include "Wire.h"
#include "AD5252.h"
#include "EMSSystem.h"
#include "EMSChannel.h"
#include "avr/pgmspace.h"
//DEBUG: setup for verbose mode (prints debug messages if DEBUG_ON is 1)
#define DEBUG_ON 1
//USB: allows to send simplified test commands (one char each, refer to https://github.com/PedroLopes/openEMSstim) to the board via USB (by default this is inactive)
#define USB_TEST_COMMANDS_ACTIVE 1
//Initialization of control objects
AD5252 digitalPot(0);
EMSChannel emsChannel1(5, 4, A2, &digitalPot, 1);
EMSChannel emsChannel2(6, 7, A3, &digitalPot, 3);
EMSSystem emsSystem(2);
void setup()
{
Serial.begin(19200);
//Serial.setTimeout(75);
Serial.flush();
//Add the EMS channels and start the control
emsSystem.addChannelToSystem(&emsChannel1);
emsSystem.addChannelToSystem(&emsChannel2);
EMSSystem::start();
Serial.println("EMS System Start");
pinMode(13, OUTPUT);
digitalWrite(13, HIGH);
}
void loop()
{
//Communicate to the EMS-module over USB
if (Serial.available() > 0)
{
if (USB_TEST_COMMANDS_ACTIVE)
{
String message = Serial.readStringUntil('\n');
doCommand(message);
}
Serial.flush();
}
}
void doCommand(String str)
{
char c = str[0];
if (c == '1')
{
if (emsChannel1.isActivated())
{
emsChannel1.deactivate();
Serial.println("Channel 1 DeActivated \t");
}
else
{
emsChannel1.activate();
Serial.println("EMS: Channel 1 active /t");
}
}
else if (c == '2')
{
if (emsChannel2.isActivated())
{
emsChannel2.deactivate();
Serial.println("Channel 2 DeActivated \t");
}
else
{
emsChannel2.activate();
Serial.println("Channel 2 Activated \t");
}
}
else if (c == 'a')
{
digitalPot.setPosition(1, digitalPot.getPosition(1) + 1);
Serial.println( "\tEMS1:" + String(digitalPot.getPosition(1)));
}
else if (c == 'q')
{
digitalPot.setPosition(1, digitalPot.getPosition(1) - 1);
Serial.println("EMS1:"+String(digitalPot.getPosition(1)));
}
else if (c == 's')
{
digitalPot.setPosition(3, digitalPot.getPosition(3) + 1);
Serial.println( "\tEMS1:" + String(digitalPot.getPosition(3)));
}
else if (c == 'w')
{
digitalPot.setPosition(3, digitalPot.getPosition(3) - 1);
Serial.println( "\tEMS2:" + String(digitalPot.getPosition(3)));
}
else if (c == 'f') // Dual Channel Activation + Syncronus Intensity
{
emsChannel1.activate();
emsChannel2.activate();
String temp = ""; // convert string to int
for (int i=str.indexOf('q')+1; i<str.indexOf('e'); i++)
{
temp += (char)str[i];
}
digitalPot.setPosition_sync(1,3, temp.toInt());
Serial.println("EMS1:"+String(digitalPot.getPosition(1))+ "EMS2:"+String(digitalPot.getPosition(3))+"\t");
}
else if(c=='x')
{
emsChannel1.deactivate();
emsChannel2.deactivate();
}
else Serial.println("Error /t");
}
<file_sep>
#include "EMSChannel.h"
//---------- constructor ----------------------------------------------------
EMSChannel::EMSChannel(uint8_t channel_to_Pads, uint8_t channel_to_Pads_2,
uint8_t led_active_pin, AD5252* digitalPoti, uint8_t wiperIndex) {
intensity = 0;
activated = false;
maxIntensity = 215; // Die differnez ist gleich dem max Wert
minIntensity = 55; //
this->channel_to_Pads = channel_to_Pads;
this->channel_to_Pads_2 = channel_to_Pads_2;
this->led_active_pin = led_active_pin;
endTime = 1;
onTimeChannel = 1;
this->digitalPoti = digitalPoti;
this->wiperIndex = wiperIndex;
pinMode(channel_to_Pads, OUTPUT);
pinMode(channel_to_Pads_2, OUTPUT);
pinMode(led_active_pin, OUTPUT);
digitalWrite(channel_to_Pads_2, LOW);
digitalWrite(channel_to_Pads, LOW);
digitalWrite(led_active_pin, LOW);
}
EMSChannel::~EMSChannel() {
}
//---------- public ----------------------------------------------------
/*
* Starts the communication with the digital Poti. Must be called for initialization
*/
void EMSChannel::start() {
Wire.begin();
}
/*
* Schaltet das EMS-Signal auf die Pads.
*/
void EMSChannel::activate() {
digitalWrite(channel_to_Pads, HIGH);
digitalWrite(channel_to_Pads_2, HIGH);
activated = true;
digitalWrite(led_active_pin, HIGH);
}
/*
* Schaltet das EMS-Signal auf den MosFet.
*/
void EMSChannel::deactivate() {
digitalPoti->setPosition(wiperIndex, 255);
delay(50);
digitalWrite(led_active_pin, LOW);
digitalWrite(channel_to_Pads_2, LOW);
digitalWrite(channel_to_Pads, LOW);
activated = false;
endTime = 0;
}
/* EN: Proofs if the channel is active
*/
bool EMSChannel::isActivated() {
return activated;
}
/* Sets the intensity from 0-100
*
*/
void EMSChannel::setIntensity(int intensity) {
this->intensity = int(
((maxIntensity - minIntensity) * intensity) * 0.01f + 0.5f)
+ minIntensity;
if (this->intensity > POTI_STEPS_UP) {
this->intensity = POTI_STEPS_UP;
} else if (this->intensity < POTI_STEPS_DOWN) {
this->intensity = POTI_STEPS_DOWN;
}
int resistorLevel = POTI_STEPS_UP - this->intensity;
digitalPoti->setPosition(wiperIndex, resistorLevel);
}
/* Return the intensity in a range of 0-100
*/
int EMSChannel::getIntensity() {
return intensity;
}
void EMSChannel::setSignalLength(int signalLength) {
onTimeChannel = signalLength;
}
int EMSChannel::getSignalLength() {
return onTimeChannel;
}
void EMSChannel::applySignal() {
endTime = millis() + onTimeChannel;
}
int EMSChannel::check() {
if (endTime && endTime <= millis()) {
deactivate();
return 1;
}
return 0;
}
//maxIntensity in percent
void EMSChannel::setMaxIntensity(int maxIntensity) {
this->maxIntensity = int(POTI_STEPS_UP * maxIntensity * 0.01f + 0.5f);
}
//minIntensity in percent
void EMSChannel::setMinIntensity(int minIntensity) {
this->minIntensity = int(POTI_STEPS_UP * minIntensity * 0.01f + 0.5f);
}
//---------- private ----------------------------------------------------
<file_sep>
#ifndef EMSCHANNEL_H_
#define EMSCHANNEL_H_
#include <Arduino.h>
#include "Wire.h"
#include "AD5252.h"
// Individual for each device must be knew
#define IDENT_PHRASE = "EMS-Service-BLE1"
//The Poti has 256 steps. 0 - 255.
#define POTI_STEPS_UP 255
#define POTI_STEPS_DOWN 0
class EMSChannel {
public:
static void start();
EMSChannel(uint8_t channel_to_Pads, uint8_t channel_to_Pads_2,
uint8_t led_active_pin, AD5252 *digitalPoti, uint8_t wiperIndex);
virtual ~EMSChannel();
virtual void activate();
virtual void deactivate();
virtual bool isActivated();
virtual void setIntensity(int intensity);
virtual int getIntensity();
virtual void setSignalLength(int signalLength);
virtual int getSignalLength();
virtual void applySignal();
virtual void setMaxIntensity(int maxIntensity);
virtual void setMinIntensity(int minIntensity);
virtual int check();
private:
//internal state
bool activated;
int intensity;
unsigned long int endTime;
int onTimeChannel;
int maxIntensity; // Poti Value
int minIntensity; // Poti Value
//Poti control variables
AD5252* digitalPoti;
int wiperIndex;
//Pin connections to Solid State Relays and LED
uint8_t channel_to_Pads;
uint8_t channel_to_Pads_2;
uint8_t led_active_pin;
};
#endif /* EMSCHANNEL_H_ */
<file_sep>
#include <Arduino.h>
#include "Wire.h"
#ifndef AD5252_AD5252_H_
#define AD5252_AD5252_H_
class AD5252 {
public:
AD5252(uint8_t address);
virtual ~AD5252();
void setPosition(uint8_t wiperIndex, uint8_t whiperPosition);
void setPosition_sync(uint8_t wiperIndex1,uint8_t wiperIndex2, uint8_t whiperPosition);
uint8_t getPosition(uint8_t wiperIndex);
void decrement(uint8_t wiperIndex);
void increment(uint8_t wiperIndex);
void increment(uint8_t wiperIndex, int steps, int stepDelay);
void decrement(uint8_t wiperIndex, int steps, int stepDelay);
private:
static const uint8_t poti_manufactur_address = B0101100;
uint8_t address;
};
#endif /* AD5252_AD5252_H_ */
| 1e432d2f4e8e273543d3672fbf0144ff0ea7cce0 | [
"C++"
] | 6 | C++ | RavikiranKattoju/MSTIM | defde61bef01e48bc820ce6898bdef1db21b39e6 | 63cbcc0098af9e6b66b8d0ab6dc13708d9b39f75 |
refs/heads/master | <file_sep>"# PackageMobile"
<file_sep>package com.mhdhussein.aralpackagemanagement.api;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
public class AralClient {
// public static final String BASE_URL = "http://172.16.31.10/"; //temp
public static final String BASE_URL = "http://aralsoft.net/amas/"; //temp
private static Retrofit retrofit = null;
public static Retrofit getClient(){
Gson gson = new GsonBuilder()
.setLenient()
.setPrettyPrinting()
.enableComplexMapKeySerialization()
.generateNonExecutableJson()
.create();
if (retrofit == null){
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
return retrofit;
}
public static ApiService getApiService(){
return getClient().create(ApiService.class);
}
}
<file_sep>package com.mhdhussein.aralpackagemanagement.utils;
import android.content.Context;
import android.content.Intent;
import android.preference.PreferenceManager;
import android.util.Log;
import com.mhdhussein.aralpackagemanagement.ErrorActivity;
import com.mhdhussein.aralpackagemanagement.LoginActivity;
import com.mhdhussein.aralpackagemanagement.MainActivity;
import com.mhdhussein.aralpackagemanagement.api.ApiService;
import com.mhdhussein.aralpackagemanagement.api.AralClient;
import com.mhdhussein.aralpackagemanagement.model.User;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import static com.mhdhussein.aralpackagemanagement.Constants.PREF_KEY_ID;
import static com.mhdhussein.aralpackagemanagement.Constants.PREF_KEY_NAME;
import static com.mhdhussein.aralpackagemanagement.Constants.PREF_KEY_ROLE;
import static com.mhdhussein.aralpackagemanagement.Constants.PREF_KEY_TOKEN;
import static com.mhdhussein.aralpackagemanagement.Constants.PREF_KEY_TOKEN_REFERESH;
public class UserHelper {
private static final String TAG = "LOGIN_ATTEMPT";
public static boolean isLoggedIn(Context context){
String token = PreferenceManager.getDefaultSharedPreferences(context)
.getString(PREF_KEY_TOKEN , "");
return !token.equals("");
}
public static boolean isSupervisor(Context context){
String token = PreferenceManager.getDefaultSharedPreferences(context)
.getString(PREF_KEY_TOKEN , "");
String role = PreferenceManager.getDefaultSharedPreferences(context)
.getString(PREF_KEY_ROLE , "");
return role.equals("Supervisor");
}
public static void setUser(Context context){
String token = PreferenceManager.getDefaultSharedPreferences(context)
.getString(PREF_KEY_TOKEN , "");
ApiService apiService = AralClient.getApiService();
Observable<User> user = apiService.currentUser("Bearer " + token)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread());
user.subscribe(new Observer<User>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(User user) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit().putString(PREF_KEY_ROLE , user.getRole()).apply();
Log.d(TAG , user.getRole());
PreferenceManager.getDefaultSharedPreferences(context)
.edit().putString(PREF_KEY_NAME , user.getName()).apply();
PreferenceManager.getDefaultSharedPreferences(context)
.edit().putInt(PREF_KEY_ID , user.getId()).apply();
if (UserHelper.isSupervisor(context)) {
Intent mainPage = new Intent(context, MainActivity.class);
mainPage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(mainPage);
} else{
Intent errorPage = new Intent(context, ErrorActivity.class);
errorPage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(errorPage);
}
}
@Override
public void onError(Throwable e) {
Log.d(TAG , e.getMessage());
}
@Override
public void onComplete() {
}
});
}
public static void logout(Context context){
PreferenceManager.getDefaultSharedPreferences(context)
.edit().putString(PREF_KEY_ROLE , "").apply();
PreferenceManager.getDefaultSharedPreferences(context)
.edit().putString(PREF_KEY_NAME , "").apply();
PreferenceManager.getDefaultSharedPreferences(context)
.edit().putString(PREF_KEY_ID , "").apply();
PreferenceManager.getDefaultSharedPreferences(context)
.edit().putString(PREF_KEY_TOKEN , "").apply();
PreferenceManager.getDefaultSharedPreferences(context)
.edit().putString(PREF_KEY_TOKEN_REFERESH , "").apply();
}
public static String getToken(Context context){
return "Bearer " + PreferenceManager.getDefaultSharedPreferences(context)
.getString(PREF_KEY_TOKEN , "");
}
public static User getUser(Context context){
String name = PreferenceManager.getDefaultSharedPreferences(context)
.getString(PREF_KEY_NAME , "");
String role = PreferenceManager.getDefaultSharedPreferences(context)
.getString(PREF_KEY_ROLE , "");
int id = PreferenceManager.getDefaultSharedPreferences(context)
.getInt(PREF_KEY_ID , 0);
User user = new User();
user.setName(name);
user.setRole(role);
user.setId(id);
return user;
}
}
<file_sep>package com.mhdhussein.aralpackagemanagement.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class CourierAttendance {
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("courier")
@Expose
private String courier;
@SerializedName("courier_id")
@Expose
private Integer courierId;
@SerializedName("status")
@Expose
private String status;
@SerializedName("supervisor")
@Expose
private String supervisor;
@SerializedName("supervisor_id")
@Expose
private Integer supervisorId;
@SerializedName("time")
@Expose
private String time;
@SerializedName("date")
@Expose
private String date;
@SerializedName("lateTime")
@Expose
private String lateTime;
@SerializedName("lateTimeNumber")
@Expose
private String lateTimeNumber;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCourier() {
return courier;
}
public void setCourier(String courier) {
this.courier = courier;
}
public Integer getCourierId() {
return courierId;
}
public void setCourierId(Integer courierId) {
this.courierId = courierId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getSupervisor() {
return supervisor;
}
public void setSupervisor(String supervisor) {
this.supervisor = supervisor;
}
public Integer getSupervisorId() {
return supervisorId;
}
public void setSupervisorId(Integer supervisorId) {
this.supervisorId = supervisorId;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getLateTime() {
return lateTime;
}
public void setLateTime(String lateTime) {
this.lateTime = lateTime;
}
public String getLateTimeNumber() {
return lateTimeNumber;
}
public void setLateTimeNumber(String lateTimeNumber) {
this.lateTimeNumber = lateTimeNumber;
}
}
<file_sep>package com.mhdhussein.aralpackagemanagement.adapters;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.mhdhussein.aralpackagemanagement.AttendanceActivity;
import com.mhdhussein.aralpackagemanagement.R;
import com.mhdhussein.aralpackagemanagement.ShipmentInsert;
import com.mhdhussein.aralpackagemanagement.api.ApiService;
import com.mhdhussein.aralpackagemanagement.api.AralClient;
import com.mhdhussein.aralpackagemanagement.model.CourierAttendance;
import com.mhdhussein.aralpackagemanagement.utils.UserHelper;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import static com.mhdhussein.aralpackagemanagement.Constants.SHIPMENT_ENTRY_INSERT;
import static com.mhdhussein.aralpackagemanagement.Constants.SHIPMENT_ENTRY_UPDATE;
public class AttendanceAdapter extends RecyclerView.Adapter<AttendanceAdapter.ViewHolder> {
private Context mContext;
private ArrayList<CourierAttendance> courierAttendances = new ArrayList<>();
public AttendanceAdapter(Context mContext, ArrayList<CourierAttendance> courierAttendances) {
this.mContext = mContext;
this.courierAttendances = courierAttendances;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_attendance_card,
viewGroup , false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
viewHolder.courierName.setText(courierAttendances.get(i).getCourier());
viewHolder.courierId.setText("#" + courierAttendances.get(i).getCourierId());
viewHolder.time.setText(courierAttendances.get(i).getTime());
viewHolder.late.setText(courierAttendances.get(i).getLateTime());
viewHolder.courierCard.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ApiService apiService = AralClient.getApiService();
Observable<Integer> isShipmentExists = apiService.isShipmentExists(
UserHelper.getToken(mContext),
courierAttendances.get(i).getCourierId()
)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread());
isShipmentExists.subscribe(new Observer<Integer>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(Integer value) {
if (value >= 1){
Intent insertShipment = new Intent(mContext , ShipmentInsert.class);
insertShipment.putExtra("type" , SHIPMENT_ENTRY_UPDATE);
insertShipment.putExtra("courier_name" , courierAttendances.get(i).getCourier());
insertShipment.putExtra("courier_id" , courierAttendances.get(i).getCourierId());
mContext.startActivity(insertShipment);
}else {
Intent insertShipment = new Intent(mContext , ShipmentInsert.class);
insertShipment.putExtra("type" , SHIPMENT_ENTRY_INSERT);
insertShipment.putExtra("courier_name" , courierAttendances.get(i).getCourier());
insertShipment.putExtra("courier_id" , courierAttendances.get(i).getCourierId());
mContext.startActivity(insertShipment);
}
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
});
}
@Override
public int getItemCount() {
return courierAttendances.size();
}
public void updateList(ArrayList<CourierAttendance> newList){
courierAttendances = new ArrayList<>();
courierAttendances.addAll(newList);
notifyDataSetChanged();
}
class ViewHolder extends RecyclerView.ViewHolder{
@BindView(R.id.courier_name)
TextView courierName;
@BindView(R.id.courier_id)
TextView courierId;
@BindView(R.id.time)
TextView time;
@BindView(R.id.late)
TextView late;
@BindView(R.id.courierCard)
CardView courierCard;
public ViewHolder(@NonNull View itemView) {
super(itemView);
ButterKnife.bind(this , itemView);
}
}
}
<file_sep>package com.mhdhussein.aralpackagemanagement;
import android.content.Intent;
import android.preference.PreferenceManager;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.mhdhussein.aralpackagemanagement.api.AralClient;
import com.mhdhussein.aralpackagemanagement.api.ApiService;
import com.mhdhussein.aralpackagemanagement.model.Token;
import com.mhdhussein.aralpackagemanagement.model.User;
import com.mhdhussein.aralpackagemanagement.utils.UserHelper;
import com.mhdhussein.aralpackagemanagement.widgets.ViewLoadingDotsBounce;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static com.mhdhussein.aralpackagemanagement.Constants.CLIENT_ID;
import static com.mhdhussein.aralpackagemanagement.Constants.CLIENT_SECRET;
import static com.mhdhussein.aralpackagemanagement.Constants.GRANT_TYPE;
import static com.mhdhussein.aralpackagemanagement.Constants.PREF_KEY_TOKEN;
public class LoginActivity extends AppCompatActivity {
private final String TAG = "LOGIN_ATTEMPT";
@BindView(R.id.id_number)
TextInputEditText idNumber;
@BindView(R.id.password)
TextInputEditText password;
@BindView(R.id.sign_in)
Button signIn;
@BindView(R.id.loading)
ViewLoadingDotsBounce loading;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
ApiService apiService = AralClient.getApiService();
signIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (idNumber.getText().toString().length() > 0 &&
password.getText().toString().length() > 0
) {
Scheduler networkThread = Schedulers.newThread();
Observable<Token> attemptLogin = apiService.login(
Integer.valueOf(idNumber.getText().toString()),
password.getText().toString(),
GRANT_TYPE,
CLIENT_SECRET,
CLIENT_ID
)
.subscribeOn(networkThread)
.observeOn(AndroidSchedulers.mainThread());
attemptLogin.subscribe(new Observer<Token>() {
@Override
public void onSubscribe(Disposable d) {
loading.setVisibility(View.VISIBLE);
}
@Override
public void onNext(Token token) {
Log.d(TAG , token.getTokenType());
PreferenceManager.getDefaultSharedPreferences(LoginActivity.this)
.edit().putString(PREF_KEY_TOKEN , token.getAccessToken()).apply();
UserHelper.setUser(LoginActivity.this);
loading.setVisibility(View.GONE);
}
@Override
public void onError(Throwable e) {
Log.d(TAG , e.getMessage());
toastIconError();
loading.setVisibility(View.GONE);
}
@Override
public void onComplete() {
// finish();
}
});
}
}
});
}
private void toastIconError() {
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
//inflate view
View custom_view = getLayoutInflater().inflate(R.layout.toast_icon_text, null);
((TextView) custom_view.findViewById(R.id.message)).setText("ID Number Or Password is Incorrect");
((ImageView) custom_view.findViewById(R.id.icon)).setImageResource(R.drawable.ic_close);
((CardView) custom_view.findViewById(R.id.parent_view)).setCardBackgroundColor(getResources().getColor(R.color.red_600));
toast.setView(custom_view);
toast.show();
}
@Override
protected void onResume() {
super.onResume();
if (UserHelper.isLoggedIn(this)){
finish();
}
}
}
<file_sep>package com.mhdhussein.aralpackagemanagement;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.mhdhussein.aralpackagemanagement.api.ApiService;
import com.mhdhussein.aralpackagemanagement.api.AralClient;
import com.mhdhussein.aralpackagemanagement.model.ShipmentEntryData;
import com.mhdhussein.aralpackagemanagement.utils.UserHelper;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import static com.mhdhussein.aralpackagemanagement.Constants.SHIPMENT_ENTRY_INSERT;
import static com.mhdhussein.aralpackagemanagement.Constants.SHIPMENT_ENTRY_UPDATE;
public class ShipmentInsert extends AppCompatActivity {
private int formType;
private String courierName;
private int courierNumber;
@BindView(R.id.ofd)
TextInputEditText ofd;
@BindView(R.id.package_value)
TextInputEditText packageValue;
@BindView(R.id.credit)
TextInputEditText creditInput;
@BindView(R.id.paidInCredit)
TextInputEditText paidInCredit;
@BindView(R.id.cash)
TextInputEditText cashInput;
@BindView(R.id.paidInCash)
TextInputEditText paidInCash;
@BindView(R.id.deposited)
TextInputEditText deposited;
@BindView(R.id.delivered)
TextInputEditText delivered;
@BindView(R.id.returned)
TextInputEditText returned;
@BindView(R.id.lost)
TextInputEditText lost;
@BindView(R.id.deficit)
TextInputEditText deficit;
@BindView(R.id.fuel)
TextInputEditText fuel;
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.fab_done)
FloatingActionButton doneBtn;
private int shipmentId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shipment_insert);
ButterKnife.bind(this);
formType = getIntent().getIntExtra("type" , 0);
courierName = getIntent().getStringExtra("courier_name");
courierNumber = getIntent().getIntExtra("courier_id" , 0);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(courierName);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
disableIfNew();
doneBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (formType == SHIPMENT_ENTRY_INSERT){
insertInitialData();
}
if (formType == SHIPMENT_ENTRY_UPDATE){
updateData();
}
}
});
if (formType == SHIPMENT_ENTRY_UPDATE)
{
loadShipmentData();
}
}
private void updateData() {
ApiService apiService = AralClient.getApiService();
Observable<ShipmentEntryData> shipmentUpdate = apiService.insertShipmentEnd(
UserHelper.getToken(this),
shipmentId,
courierNumber,
UserHelper.getUser(this).getId(),
Double.valueOf(ofd.getText().toString()),
Double.valueOf(packageValue.getText().toString()),
Double.valueOf(cashInput.getText().toString()),
Double.valueOf(paidInCash.getText().toString()),
Double.valueOf(creditInput.getText().toString()),
Double.valueOf(paidInCredit.getText().toString()),
Double.valueOf(deposited.getText().toString()),
Double.valueOf(returned.getText().toString()),
Double.valueOf(delivered.getText().toString()),
Double.valueOf(deficit.getText().toString()),
Double.valueOf(lost.getText().toString()),
Double.valueOf(fuel.getText().toString())
)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread());
shipmentUpdate.subscribe(new Observer<ShipmentEntryData>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(ShipmentEntryData shipmentEntryData) {
toastIconSuccess("Shipment Data Added Successfully");
onBackPressed();
}
@Override
public void onError(Throwable e) {
Log.d("DATA_ENTRY_UPDATE" , e.getMessage());
toastIconError("Error Updating Data, Please Check your connection");
}
@Override
public void onComplete() {
}
});
}
private void loadShipmentData() {
ApiService apiService = AralClient.getApiService();
Observable<ShipmentEntryData> getShipment = apiService.getShipment(
UserHelper.getToken(this),
courierNumber
)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread());
getShipment.subscribe(new Observer<ShipmentEntryData>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(ShipmentEntryData shipmentEntryData) {
shipmentId = shipmentEntryData.getData().getId();
ofd.setText(shipmentEntryData.getData().getTotalSent());
packageValue.setText(shipmentEntryData.getData().getAmountSent());
cashInput.setText(shipmentEntryData.getData().getTotalCash());
creditInput.setText(shipmentEntryData.getData().getTotalCredit());
deposited.setText(shipmentEntryData.getData().getDeposited());
delivered.setText(shipmentEntryData.getData().getDelivered());
returned.setText(shipmentEntryData.getData().getReturned());
lost.setText(shipmentEntryData.getData().getLost());
deficit.setText(shipmentEntryData.getData().getDeficit());
fuel.setText(shipmentEntryData.getData().getFuel());
paidInCash.setText(shipmentEntryData.getData().getTotalCashPackages());
paidInCredit.setText(shipmentEntryData.getData().getTotalCreditPackages());
Log.d("PACKAGE_COUNT" , "data is " + shipmentEntryData.getData().getTotalCashPackages());
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
private void insertInitialData() {
ApiService apiService = AralClient.getApiService();
Observable<ShipmentEntryData> shipmentInsert = apiService.insertShipment(
UserHelper.getToken(this),
courierNumber,
UserHelper.getUser(this).getId(),
Integer.valueOf(ofd.getText().toString()),
Double.valueOf(packageValue.getText().toString())
)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread());
shipmentInsert.subscribe(new Observer<ShipmentEntryData>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(ShipmentEntryData shipmentEntryData) {
toastIconSuccess("Shipment Data Added Successfully");
onBackPressed();
}
@Override
public void onError(Throwable e) {
toastIconError("Error Inserting Data, Please Check your connection");
}
@Override
public void onComplete() {
}
});
}
public void disableIfNew(){
if (formType == SHIPMENT_ENTRY_INSERT){
cashInput.setEnabled(false);
creditInput.setEnabled(false);
deposited.setEnabled(false);
delivered.setEnabled(false);
returned.setEnabled(false);
lost.setEnabled(false);
deficit.setEnabled(false);
fuel.setEnabled(false);
}
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
private void toastIconError(String message) {
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
//inflate view
View custom_view = getLayoutInflater().inflate(R.layout.toast_icon_text, null);
((TextView) custom_view.findViewById(R.id.message))
.setText(message);
((ImageView) custom_view.findViewById(R.id.icon)).setImageResource(R.drawable.ic_close);
((CardView) custom_view.findViewById(R.id.parent_view)).setCardBackgroundColor(getResources().getColor(R.color.red_600));
toast.setView(custom_view);
toast.show();
}
private void toastIconSuccess(String message) {
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
//inflate view
View custom_view = getLayoutInflater().inflate(R.layout.toast_icon_text, null);
((TextView) custom_view.findViewById(R.id.message))
.setText(message);
((ImageView) custom_view.findViewById(R.id.icon)).setImageResource(R.drawable.ic_check);
((CardView) custom_view.findViewById(R.id.parent_view)).setCardBackgroundColor(getResources().getColor(R.color.green_600));
toast.setView(custom_view);
toast.show();
}
}
<file_sep>package com.mhdhussein.aralpackagemanagement.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Summary {
@SerializedName("ofd")
@Expose
private Integer ofd;
@SerializedName("cod")
@Expose
private Integer cod;
@SerializedName("tfd")
@Expose
private Integer tfd;
@SerializedName("avg")
@Expose
private Double avg;
@SerializedName("deficit")
@Expose
private Integer deficit;
@SerializedName("lost")
@Expose
private Integer lost;
@SerializedName("deposited")
@Expose
private Integer deposited;
public Integer getOfd() {
return ofd;
}
public void setOfd(Integer ofd) {
this.ofd = ofd;
}
public Integer getCod() {
return cod;
}
public void setCod(Integer cod) {
this.cod = cod;
}
public Integer getTfd() {
return tfd;
}
public void setTfd(Integer tfd) {
this.tfd = tfd;
}
public Double getAvg() {
return avg;
}
public void setAvg(Double avg) {
this.avg = avg;
}
public Integer getDeficit() {
return deficit;
}
public void setDeficit(Integer deficit) {
this.deficit = deficit;
}
public Integer getLost() {
return lost;
}
public void setLost(Integer lost) {
this.lost = lost;
}
public Integer getDeposited() {
return deposited;
}
public void setDeposited(Integer deposited) {
this.deposited = deposited;
}
}
<file_sep>package com.mhdhussein.aralpackagemanagement;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.mhdhussein.aralpackagemanagement.adapters.AttendanceAdapter;
import com.mhdhussein.aralpackagemanagement.api.ApiService;
import com.mhdhussein.aralpackagemanagement.api.AralClient;
import com.mhdhussein.aralpackagemanagement.model.CourierAttendance;
import com.mhdhussein.aralpackagemanagement.model.CourierAttendanceData;
import com.mhdhussein.aralpackagemanagement.utils.UserHelper;
import com.mhdhussein.aralpackagemanagement.widgets.ViewLoadingDotsBounce;
import java.util.ArrayList;
import java.util.Objects;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
public class AttendanceActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.no_entries)
TextView noEntries;
@BindView(R.id.recyclerView)
RecyclerView attendanceList;
private static ArrayList<CourierAttendance> attendances;
private static AttendanceAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attendance);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Attentance");
loadData();
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
private void loadData(){
ApiService apiService = AralClient.getApiService();
Observable<CourierAttendanceData> attendance = apiService.getAttendedCourier(
UserHelper.getToken(this),
UserHelper.getUser(this).getId()
)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread());
attendance.subscribe(new Observer<CourierAttendanceData>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(CourierAttendanceData courierAttendanceData) {
AttendanceActivity.attendances = courierAttendanceData.getData();
if (courierAttendanceData.getData().size() > 0) {
noEntries.setVisibility(View.GONE);
attendanceList.setVisibility(View.VISIBLE);
AttendanceActivity.adapter = new AttendanceAdapter(AttendanceActivity.this , courierAttendanceData.getData());
attendanceList.setAdapter(AttendanceActivity.adapter);
attendanceList.setLayoutManager(new LinearLayoutManager(AttendanceActivity.this));
}else {
noEntries.setVisibility(View.VISIBLE);
attendanceList.setVisibility(View.GONE);
}
}
@Override
public void onError(Throwable e) {
Log.d("CourierAttendance" , e.getMessage());
}
@Override
public void onComplete() {
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_menu , menu);
MenuItem menuItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(this);
return true;
}
@Override
public boolean onQueryTextSubmit(String s) {
return false;
}
@Override
public boolean onQueryTextChange(String s) {
String courierNumber = s;
ArrayList<CourierAttendance> newList = new ArrayList<>();
for (CourierAttendance courierAttendance : AttendanceActivity.attendances){
if (String.valueOf(courierAttendance.getCourierId()).contains(courierNumber)){
newList.add(courierAttendance);
}
}
AttendanceActivity.adapter.updateList(newList);
return true;
}
}
| 741793a8511f8176d84f85b6268bc42a654cbe4d | [
"Markdown",
"Java"
] | 9 | Markdown | apdri/PackageMobile | 7196cfef7d92fbae9bc72ae97e7df08b221db61e | 034b260fdc8870a020a9c141b70b8993306bb097 |
refs/heads/master | <file_sep>class Tipo:
def __str__(self):
return "T"
<file_sep>class Expresiones:
pass
<file_sep>class Booleano(Expresion):
pass
<file_sep>class Variable(Expresion):
pass
<file_sep>class Suma(Entero):
"E1 + E2"
pass
<file_sep>class Conjuncion(Booleano):
"E1 /\ E2"
pass
<file_sep>from tipos.Bool import Bool
from tipos.Int import Int
from tipos.Fun import Fun
from tipos.Paren import Paren
from tipos.Var import Var
import sys
class Sustitucion:
def __init__(self, pairs = None):
"pairs = [(a, T1), (b, T2), ... , (z, Tn)]"
if (pairs == None):
self.pairs = []
else:
self.pairs = pairs
def push(self, a, t):
self.pairs.append((a, t))
def pop(self):
return self.pairs.pop()
def contains(self, v):
s = self.find(v)
return s != None
def find(self, v):
s = filter(lambda e: (e[0].symbol == v.symbol), self.pairs)
if (len(s) > 0):
return s.pop()[1]
else:
return None
def size(self):
return len(self.pairs)
def sustituir(self, t):
if (isinstance(t, Fun)):
t.domain = self.sustituir(t.domain)
t.range = self.sustituir(t.range)
return t
elif(isinstance(t, Var)):
e = self.find(t)
if (e != None): return e
elif(isinstance(t, Paren)):
t.t = self.sustituir(t.t)
return t
def all(self):
return self.pairs
def compose(self, s):
new_pairs = map(
lambda e: (e[0], s.sustituir(e[1])),
self.pairs
)
new_pairs.extend(filter(
lambda e: (self.find(e[0]) == None),
s.pairs
))
return Sustitucion(new_pairs)
<file_sep>from Tipo import Tipo
class Fun(Tipo):
"T1 --> T2"
def __init__(self, domain, range):
self.domain = domain
self.range = range
def __str__(self):
return "%s --> %s" % (self.domain, self.range)
<file_sep>from Tipo import Tipo
class Bool(Tipo):
def __str__(self):
return "bool"
<file_sep>class Entero(Expresion):
pass
<file_sep>class MenorQue(Booleano):
"E1 < E2"
pass
<file_sep>from Tipo import Tipo
class Paren(Tipo):
def __init__(self, t):
self.t = t
def __str__(self):
return "(%s)" % self.t
<file_sep>from Tipo import Tipo
class Int(Tipo):
"int"
def __str__(self):
return "int"
<file_sep>class Lambda(Expresion):
"lambda var.E"
pass
<file_sep>from Sustitucion import Sustitucion
from tipos.Bool import Bool
from tipos.Int import Int
from tipos.Fun import Fun
from tipos.Paren import Paren
from tipos.Var import Var
import unittest
import sys
class SustitucionTest(unittest.TestCase):
def setUp(self):
pass
def test_push(self):
s = Sustitucion()
self.assertEqual(s.size(), 0)
s.push(Var('a'), Int())
self.assertEqual(s.size(), 1)
def test_pop(self):
s = Sustitucion()
s.push(1, 2)
self.assertEqual(s.pop(), (1, 2))
def test_size(self):
s = Sustitucion()
self.assertEqual(s.size(), 0)
s.push(1, 2)
self.assertEqual(s.size(), 1)
s.pop()
self.assertEqual(s.size(), 0)
def test_contains(self):
s = Sustitucion()
self.assertFalse(s.contains(Var('x')))
s.push(Var('a'), 1)
self.assertTrue(s.contains(Var('a')))
def test_find(self):
s = Sustitucion()
s.push(Var('a'), Fun(Var('x'), Var('y')))
self.assertEqual(str(s.find(Var('a'))), str(Fun(Var('x'), Var('y'))))
def test_sustituir(self):
s = Sustitucion()
s.push(Var('a'), Fun(Var('b'), Int()))
self.assertEqual(
str(s.sustituir(Fun(Var('a'), Var('b')))),
str(Fun(Fun(Var('b'), Int()), Var('b')))
)
def test_sustituir_vacio(self):
s = Sustitucion()
self.assertEqual(
str(s.sustituir(Fun(Var('a'), Var('b')))),
str(Fun(Var('a'), Var('b')))
)
def test_sustituir_tipo_base(self):
s = Sustitucion()
s.push(Var('a'), Fun(Var('b'), Int()))
self.assertEqual(
str(s.sustituir(Int())),
str(Int())
)
self.assertEqual(
str(s.sustituir(Bool())),
str(Bool())
)
def test_sustituir_paren(self):
s = Sustitucion()
s.push(Var('a'), Fun(Var('b'), Int()))
self.assertEqual(
str(s.sustituir(Paren(Var('a')))),
str(Paren(Fun(Var('b'), Int())))
)
def test_compose(self):
s1 = Sustitucion()
s1.push(Var('a'), Fun(Var('b'), Int()))
s1.push(Var('w'), Fun(Var('c'), Fun(Var('b'), Bool())))
s2 = Sustitucion()
s2.push(Var('b'), Bool())
s2.push(Var('c'), Int())
s2.push(Var('a'), Bool())
s2.push(Var('w'), Int())
s = s1.compose(s2)
a = map(lambda e: (str(e[0]), str(e[1])), s.all())
self.assertEqual(
a,
[
(str(Var('a')), str(Fun(Bool(), Int()))),
(str(Var('w')), str(Fun(Int(), Fun(Bool(), Bool())))),
(str(Var('b')), str(Bool())),
(str(Var('c')), str(Int())),
]
)
suite = unittest.TestLoader().loadTestsFromTestCase(SustitucionTest)
unittest.TextTestRunner(verbosity=2).run(suite)
| 1fc350d573941bb6a0ca2880b1d54cf0a05dcfbd | [
"Python"
] | 15 | Python | jormar/python-type-analizer | 32871188dd1f4c361bc2c8ccca27bc2aa7d016ea | 67f1ece92c9e032eb818cee210bb6cac8d76e630 |
refs/heads/master | <repo_name>ftodoroski/js-advanced-first-class-functions-practice-lab-nyc-web-010620<file_sep>/index.js
// Code your solution in this file!
function logDriverNames(drivers) {
drivers.forEach(function (driver) {
console.log(driver.name);
})
}
function logDriversByHometown(drivers, location) {
drivers.filter(function (driver) {
return driver.hometown === location
}).forEach( function (driver) {
console.log(driver.name);
})
}
function driversByRevenue(drivers) {
const driverMap = drivers.slice()
return driverMap.sort(function (a ,b) { return a.revenue - b.revenue })
}
function driversByName(drivers) {
return drivers.slice().sort(function (a, b) { return a.name.localeCompare(b.name) })
}
function totalRevenue(drivers) {
return drivers.reduce(function (accumulator, driver) { return accumulator + driver.revenue } ,0)
}
function averageRevenue(drivers) {
const revenue = drivers.reduce(function (accumulator, driver) {return accumulator + driver.revenue }, 0)
return revenue / drivers.length
} | 62da5ca162db7cc08a4b825170a222a31de3d22a | [
"JavaScript"
] | 1 | JavaScript | ftodoroski/js-advanced-first-class-functions-practice-lab-nyc-web-010620 | 33c73beb9ee52d3b685e5e7bee7b7b5dbf92d6a7 | f094e6bb688bde0239ead38c337f91b479986ac7 |
refs/heads/master | <file_sep>package pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import junit.framework.Assert;
public class AcessoPages {
static WebDriver driver;
public AcessoPages(WebDriver driver) {
this. driver = driver;
}
public void acessa(){
driver.get("https://www.celulardireto.com.br");
}
public boolean validaHome() {
//WebElement home = driver.findElement(By.linkText("Celular Direto"));
return driver.findElement(By.linkText("Celular Direto")).isDisplayed();
}
public void menuCelular() {
driver.findElement(By.xpath("//a[contains(text(),'Celulares')]")).click();
}
public boolean validaMarca() {
return driver.findElement(By.xpath("//p[contains(.,'Navegue por marcas')]")).isDisplayed();
}
public void menuSamsung() {
driver.findElement(By.xpath("//a[contains(@href,'./celulares/samsung')]")).click();
}
public boolean validaCelular() {
return driver.findElement(By.xpath("//img[@alt='Logo da Samsung']")).isDisplayed();
}
public void opcaoGalaxyJ2P() {
driver.findElement(By.xpath("//p[contains(.,'Samsung Galaxy J2 Prime')]")).click();
}
public boolean validaModelo() {
return driver.findElement(By.xpath("//h1[contains(.,'Galaxy J2 Prime')]")).isDisplayed();
}
public void BtnComprar() {
driver.findElement(By.xpath("//a[contains(@href,'https://m.lojaonline.tim.com.br/celulares/samsung/samsung-galaxy-j2-prime-tim-13829/?utm_source=wooza&utm_medium=celulardireto&utm_campaign=samsung_galaxy_j2_prime')]")).click();
}
}
<file_sep>package pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import junit.framework.Assert;
public class ConsultaPages {
static WebDriver driver;
public ConsultaPages(WebDriver driver) {
this. driver = driver;
}
public void acessa(){
driver.get("https://www.celulardireto.com.br");
}
public boolean validaHome() {
//WebElement home = driver.findElement(By.linkText("Celular Direto"));
return driver.findElement(By.linkText("Celular Direto")).isDisplayed();
}
public void subMenuPlanosBL() {
driver.findElement(By.xpath("//a[contains(text(),'Internet Banda Larga')]")).findElement(By.xpath("//a[contains(text(),'Planos de Banda Larga')]")).click();
}
public boolean validaMenu() {
return driver.findElement(By.xpath("//*[@id=\"post-644\"]/custom-wooza//custom-modal-cep-search/div[2]/div/h1")).isDisplayed();
}
public void preencheCamposPlanosBL() {
WebElement cep = driver.findElement(By.xpath("//*[@id=\"post-644\"]/custom-wooza//custom-modal-cep-search/div[2]/div/div[2]/input[1]"));
cep.sendKeys("22041011");
WebElement numero = driver.findElement(By.xpath("//*[@id=\"post-644\"]/custom-wooza//custom-modal-cep-search/div[2]/div/div[2]/input[2]"));
numero.sendKeys("100");
driver.findElement(By.xpath("//*[@id=\"post-644\"]/custom-wooza//custom-modal-cep-search/div[2]/div/div[2]//div/img")).click();
}
public void opcaoVerTodosClaro() {
driver.findElement(By.xpath("//*[@id=\"post-644\"]/custom-wooza//div/div/custom-carriers/div/div/custom-carriers-box/div/button")).click();
}
}
| 3e0465d9b159cf26e5f44861e0ef378063676965 | [
"Java"
] | 2 | Java | Larissafr/Wooza | fb8a34fc660fe54a6d1a49ce0b835e52927c94ce | 9b818f9907fb5f130fa874ee1ad84ea4d2c2593f |
refs/heads/master | <file_sep>2048_Java
=========
This repository contains the code to the 2048 game built completely in Java.
The game is tried to be built using object oriented principles, with the main entities or objects being
the GameContainer (Main Game board) and Block (Tiles) as the blocks in them. Other classes are either starter
or helper classes. Appropriate methods and instance variables have been given to each of the classes and the naming
is self explanatory, however suggestions are welcome.
System Requirements : Java SE 1.7, Apache Maven
How tu run ?
-------------
Step 1: Clone the project into a directory on your computer (any directory) using :
git clone https://github.com/nkher/2048_Java.git
Step 2: Run the following command
mvn clean package
Step 3:Run the starter class using the following command
mvn exec:java -Dexec.mainClass=nkher.Twenty_Forty_Eight_Java.GameStarter
Enjoy !
For any suggesttions or feedback please reach me at <EMAIL>
<file_sep>package nkher.Twenty_Forty_Eight_Java;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
/* Class that represents a block or a tile in the main game container */
public class Block extends JPanel {
/**
* @author namesh-kher
*/
private static final long serialVersionUID = 8238269760247636958L;
/* Instance variables */
private Graphics graphics;
private Color color;
private boolean occupied;
private String value;
private JLabel jLabel;
private Font font;
/* Default Constructor to initialize a block with no value */
public Block() {
occupied = false;
this.setLayout(new GridBagLayout());
setPreferredSize(getPreferredSize());
setBackground(getDefaultColor());
setVisible(true);
}
/* Constructor to initialize a block with a new value */
public Block(String value) {
occupied = false;
this.setLayout(new GridBagLayout());
setPreferredSize(getPreferredSize());
setBackground(getColorByValue(value));
this.setValue(value); // Setting the value
setVisible(true);
}
/* Getter for dimension */
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}
/* Getter for default color */
public Color getDefaultColor() {
color = Color.yellow;
return color;
}
/* Routine to set the background colors for the tiles depending upn their value */
public Color getColorByValue(String value) {
if(Integer.parseInt(value) == 2) {
color = new Color(30,144,255); // dogger-blue
return color;
}
else if(Integer.parseInt(value) == 4) {
color = new Color(0,206,209); // dark turquoise
return color;
}
else if(Integer.parseInt(value) == 8) {
color = Color.orange;
return color;
}
else if(Integer.parseInt(value) == 16) {
color = new Color(173,255,47); // green yellow
return color;
}
else if(Integer.parseInt(value) == 32) {
color = new Color(218,165,32); // golden rod
return color;
}
else if(Integer.parseInt(value) == 64) {
color = new Color(255,99,71); // tomato red
return color;
}
else if(Integer.parseInt(value) == 128) {
color = new Color(112,128,144); // slate gray
return color;
}
else if(Integer.parseInt(value) == 256) {
color = new Color(240,248,255); // alice blue
return color;
}
else if(Integer.parseInt(value) == 512) {
color = new Color(189,183,107); // dark khaki
return color;
}
else if(Integer.parseInt(value) == 1024) {
color = new Color(240,230,140); // Khaki
return color;
}
else if(Integer.parseInt(value) == 2048) {
color = new Color(240,255,255); // azure
return color;
}
else if(Integer.parseInt(value) == 4096) {
color = new Color(238,232,170); // pale golden rod
return color;
}
else if(Integer.parseInt(value) == 8192) {
color = new Color(123,104,238); // medium slate blue
return color;
}
return null;
}
/* Getter for graphics */
public Graphics getGraphics(Graphics g) {
graphics = (Graphics) g;
graphics.fillRect(230,80,10,10);
return graphics;
}
/* Setter to set the starting value */
public void setstartingValue() {
this.value = "2";
color = new Color(30,144,255);
setBackground(getColorByValue(this.value));
jLabel = new JLabel(this.value);
jLabel.setFont(setFontDetails());
jLabel.setForeground(Color.BLACK);
this.add(jLabel);
}
/* Checks if the block is not empty */
public boolean occupied() {
return occupied == true;
}
/* Setter for Value */
public void setValue(String value) {
this.value = value;
jLabel = new JLabel(this.value);
jLabel.setFont(setFontDetails());
jLabel.setForeground(Color.BLACK);
this.add(jLabel);
}
/* Getter for Value */
public String getValue() {
return this.value;
}
/* Sets the font and returns the same object */
public Font setFontDetails() {
this.font = new Font("Comic Sans MS", 1, 50);
return this.font;
}
}
<file_sep>package nkher.Twenty_Forty_Eight_Java;
/* A data structure used as the return type for the shifting logic method in the game container class */
public class ReturnFields {
private int returnValue;
private boolean isChange;
public ReturnFields() {
this.isChange = false;
this.returnValue = Integer.MAX_VALUE;
}
public int getreturnValue() {
return returnValue;
}
public boolean isChange() {
return isChange == true;
}
public void setisChange(boolean value) {
this.isChange = value;
}
public void setreturnValue(int value) {
this.returnValue = value;
}
}
<file_sep>package nkher.Twenty_Forty_Eight_Java;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ControlBox extends JFrame {
/**
* @author namesh-kher
*/
private static final long serialVersionUID = -2108949871176690655L;
/* Constants */
public static final int controlBoxPositionX = 250;
public static final int controlBoxPositionY = 0;
public static final String gameOverMessage = "Your Game is Over. Click 'New Game' to try again.";
public static final String gameContinueMessage = "Congratulations. You Win ! Do you want to continue ? ";
/* Instance variables */
private JLabel headerL;
private JPanel controlPanel;
private Dimension dimension;
public ControlBox() {
this.controlPanel = new JPanel(new FlowLayout());
//this.setSize(300, 150);
this.setLayout(new GridLayout(3, 1));
this.add(controlPanel);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent wEvent) {
System.exit(0);
}
});
setLocation(controlBoxPositionX, controlBoxPositionX);
setVisible(true);
}
/* Routine called when the game ends without a win */
public void gameOver() {
setDimension(400, 150);
setSize(getDimension());
headerL = new JLabel(gameOverMessage, JLabel.CENTER);
this.add(headerL);
JButton newGameButton = new JButton("New Game");
JButton exitButton = new JButton("Exit");
// Code for New Game Button
newGameButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new GameContainer();
}
});
// Code for New Game Button
exitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
// Adding the buttons
this.controlPanel.add(newGameButton);
this.controlPanel.add(exitButton);
setVisible(true);
}
/* Routine called when the 2048 block is achieved */
public void winTileAchieved() {
setDimension(500, 150);
setSize(getDimension());
this.headerL = new JLabel(gameContinueMessage, JLabel.CENTER);
this.add(headerL);
JButton continueButton = new JButton("Continue");
JButton newGameButton = new JButton("New Game");
JButton exitButton = new JButton("Exit");
// Code for Continue Button
continueButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
dispose();
}
});
// Code for New Game Button
newGameButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new GameContainer();
}
});
// Code for New Game Button
exitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
// Adding the buttons
this.controlPanel.add(continueButton);
this.controlPanel.add(newGameButton);
this.controlPanel.add(exitButton);
setVisible(true);
}
public void setDimension(int x, int y) {
this.dimension = new Dimension(x, y);
}
public Dimension getDimension() {
return this.dimension;
}
}
| d8c75e3d9ed8a39092f7ca9e6d71d4b8d0fec330 | [
"Markdown",
"Java"
] | 4 | Markdown | nkher/2048_Java | b5733b61976739ae3672e58417c43d17aaec5f0a | 511f5feba8d813cf2f2acf2eee5b197f434ca46a |
refs/heads/master | <repo_name>johanna9389/P2<file_sep>/javascript/function.js
//A
function isArmstrong(n){
"use strict"
n = String(n);
if (n.length > 5) {
return;
}
var sum = 0;
for (var i = 0; i < n.length; i++){
sum = sum + Math.pow(parseInt(n[i]), n.length);
}
if (parseInt(n) == sum)
return true;
else
return false;
}
//B
function allArmstrongs(){
var result ='';
result = result + 1;
for (var i = 2; i < 100000; i++){
if(isArmstrong(i)){
result = result + ', '+ i;
}
}
return result;
}
// C
function allSubstrings1(str){
var result = "";
for (var i = 0; i < str.length; i++) {
for (var j = i+1; j < str.length + 1; j++) {
result += str.substring(i,j) + ", ";
}
}
return result.substring(0, result.length-2);
}
// D
function allSubstrings2(str) {
var arr = new Array();
for (var i = 0; i < str.length; i++) {
for (var j = i+1; j < str.length + 1; j++) {
arr.push(str.substring(i,j))
}
}
return arr;
}
// E
function maxWord(str) {
var arr = str.split(" ");
var maxWord = "";
for (var i = 0; i < arr.length; i++) {
tempStr = arr[i];
if (tempStr.length > maxWord.length){
maxWord = tempStr;
}
}
return maxWord;
} | c4c220ff68f8999dd1ea666bad47fd98cb5b8d50 | [
"JavaScript"
] | 1 | JavaScript | johanna9389/P2 | 4498de9fbcb66c164a47d32315aadce458d88370 | bc397b20f5d5b45eabfd63959b2ae746885e92b9 |
refs/heads/master | <repo_name>wwwfwq/vue-cli<file_sep>/src/components/vm.js
import Vue from 'vue';
export var vm = new Vue(); | 2ab5c0dd1ec9dc4cf35c3f81f95212c4cb9ebf82 | [
"JavaScript"
] | 1 | JavaScript | wwwfwq/vue-cli | 1d6b122ef73ee3adc18f92e26f65fd4888f7b476 | ff36188130af85f41e064c7f29d5bce18cbd0b66 |
refs/heads/master | <repo_name>armani2k20/blog<file_sep>/public/js/deleteBlog.js
$(() => {
$("#deleteBlog").click((e) => {
e.preventDefault();
let search = $("#deleteBar").val();
$.ajax({
url: `/admin/${search}`,
method: 'DELETE'
})
.then((data) => {
window.location.href = "/admin";
});
});
});
<file_sep>/controllers/blogController.js
const Blogs = require("../models/blog");
const Comments = require("../models/comment")
class BlogController {
/**
* This method shows all blog posts
* @param req and res
*/
static showBlog(req, res) {
res.render("index", {
blogs: req.session.blogs
});
}
/**
* This method shows one blog posts
* It loops through the req.session.blogs array and prints the blog title and content for each item
* @param req and res
*/
static showOneBlog(req, res) {
let blogs = req.session.blogs;
let blog;
for (let i in blogs) {
if (blogs[i].blogTitle === req.params.title) {
blog = blogs[i];
break;
}
}
res.render("singleblog", {
blog: blog
});
}
/**
* This method adds a comment to a blog post
* @param req and res
*/
static addComment(req, res) {
let blogs = req.session.blogs
for (let i in blogs) {
blogs[i].comments = blogs[i].comments || [];
if (blogs[i].blogTitle === req.body.title) {
const blogComment = new Comments(req.body);
blogs[i].comments.push(blogComment);
}
}
res.redirect("/");
}
}
//Exporting the BlogController class
module.exports = BlogController;<file_sep>/models/comment.js
//Constructing a comment class. In this constructor it checks for the correct object type and
//whether the field actually exists. If anything of these fail in the constructor it throws a custom error.
class Comments {
constructor(obj) {
if (!obj.comment) {
throw new Error("You must include a comment");
} else if (typeof obj.comment != "string") {
throw new Error("comment must be a string");
} else {
this.comment = obj.comment;
}
}
}
//Exporting the Comments class
module.exports = Comments;<file_sep>/routes/adminRoutes.js
//NPM Modules - No relative path as they are in node_modules
const express = require("express");
const router = express.Router();
//These are my own modules that require a relative path to find them.
const adminController = require("../controllers/adminController");
//Calling a functions on router in this case .get(), .post() and .delete(), which are the HTTP verb, and that takes 2 arguments.
//1 is the path (from the url), the 2nd is the function to call
router.get("/admin", adminController.showBlog);
router.post("/admin", adminController.createBlog);
router.delete("/admin/:title", adminController.deleteBlog);
//Exporting the router object
module.exports = router;<file_sep>/README.md
# Blog
## Prerequisites
* Javascript Foundations
* Node.js Foundations
***
## Project Brief
###Objectives
The purpose of this project is to allow users to manage a blog.
* Store blog posts in a session
* Create Blog posts using an admin system
* View Blog posts in a front end and printed out in EJS
* Be able to delete blog posts from the admin system
* App can be deployed to Heroku
* Users can comment on blog posts
***
##Requirements
* As an admin I want to be able to create a blog post
* As an admin I want to be able to delete a blog post
* As a user I want to be able to view blog posts
* As a user I want to be able to comment on blog posts
***
##Usage
To use this application:
1. Visit [Blog](https://blogplatform.herokuapp.com/)
<file_sep>/routes/blogRoutes.js
//NPM Modules - No relative path as they are in node_modules
const express = require("express");
const router = express.Router();
//These are my own modules that require a relative path to find them.
const blogController = require("../controllers/blogController");
//We are calling two functions on router in this case they are both .get(), which is the HTTP verb, and that takes 2 arguments.
//1 is the path (from the url), the 2nd is the function to call
router.get("/", blogController.showBlog);
router.get("/:title", blogController.showOneBlog);
router.post("/", blogController.addComment);
//Exporting the router object
module.exports = router;<file_sep>/public/js/style.js
$(document).ready(function(){
$('.scrollspy').scrollSpy();
});
$(document).ready(function(){
$('.collapsible').collapsible();
});
$(document).ready(function(){
$('.modal').modal();
});
$(document).ready(function(){
$('ul.tabs').tabs();
});
$(document).ready(function() {
$('select').material_select();
});
<file_sep>/models/blog.js
//Constructing a blog class. In this constructor it checks for the correct object type and
//whether the field actually exists. If anything of these fail in the constructor it throws a custom error.
class Blog {
constructor(obj) {
if (!obj.blogTitle) {
throw new Error("You must include blog title");
} else if (typeof obj.blogTitle != "string") {
throw new Error("Blog Title must be a string");
} else {
this.blogTitle = obj.blogTitle;
}
if (!obj.blogContent) {
throw new Error("You must include blog content");
} else if (typeof obj.blogContent != "string") {
throw new Error("Blog Content must be a string");
} else {
this.blogContent = obj.blogContent;
}
}
}
//Exporting the Blog class
module.exports = Blog;<file_sep>/functions.js
class Functions {
createBlog(array1) {
return new Promise(
(resolve) => {
resolve(array1.push({ blogTitle: "Blog3", blogContent: "Blog Content 3" }));
}
)
}
deleteBlog(array2) {
return new Promise(
(resolve) => {
resolve(array2.splice(2, 1));
}
)
}
showOneBlog(aString) {
return new Promise(
(resolve) => {
resolve(aString);
}
)
}
addComment(comments) {
return new Promise(
(resolve) => {
resolve(comments.push({ comment1: "Comment3", comment2: "Comment3" }));
}
)
}
};
module.exports = Functions; | a68dd9a9202b67f5cb98bb25c34e1c7d806e7f1c | [
"JavaScript",
"Markdown"
] | 9 | JavaScript | armani2k20/blog | 71ad3fb5ffcc1ddefd4643d077459a572d4af84c | efb96f2cd6b62e87984e96e2f5b0915f35c459b7 |
refs/heads/master | <file_sep># SoftwareBasico_2020_1
## Author:
<NAME>
## Trabalho de Software Basico 2020.1
## Description:
The current software has the objective to do a conversion of files from utf8 to utf32 and utf32 to utf8.
It'll be made by reading a preexisting file, identify the type (utf8, utf32 big-endian or utf32 little-endian) of the
inputed file and do the convertion .
## Convertions:
UTF8 ----------------------------- UTF32 (little-endian)
UTF32 (little-endian) -------------- UTF8
UTF32 (big-endian) ----------------- UTF8
## Setup:
In the Terminal:
cd [Path]/SoftwareBasico_2020_1 # go to SoftwareBasico_2020_1 folder in your computer
Then place all files to be converted at the folder "toConvert", after that, in the Terminal:
OBS: Already have some files at the folder as example
cd src #go to src folder
gcc -o exec main.c conv_utf.c #crete a executable call exec
## Excution
Inside 'src' folder:
./exec #execute de executable
## Result
After that all done, you must go in the "converted" folder and it should have all converted files
Obs: the converted file have the same name of the original file in the "toConvert" folder
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>
int utf8_32(FILE *arq_entrada, FILE *arq_saida);
int utf32_8(FILE *arq_entrada, FILE *arq_saida);
<file_sep>/**
* Version control:
* Id Day Version Description
* 1 08-04 0.0.1 Question comprehension and base code to develop the functions utf8_32 and utf32_8
* 2 10-04 0.0.2 Minors updates and Headers creation
* 3 11-04 0.1.0 Minors updates and function utf8_32 implemented
* 4 13-04 0.1.1 Minors updates and optmizations, readable code
* 5 14-04 0.2.0 Enum for Errors and add regions
* 6 01-05 0.3.0 Conversion utf8 -> utf32 - OK
* 7 02-05 0.4.0 Conversion utf32 -> utf8 - OK
* 8 10-05 1.0.0 Finalization and README
*/
#include "../headers/conv_utf.h"
#define TRUE 1
#define FALSE 0
/* Global variable*/
unsigned int BigBOOM = 0x0000feff;
#pragma region Private methods declaration
/**
* Identify the size of a character UTF8
*
* Parameters:
* inByte - first byte of an UTF8 character
*
* Return:
* boolean result
*/
int IdentifyCharSize(unsigned char inbyte);
/**
* Parameters:
* inByte - first byte of an UTF8 character
* auxInByte - 3 remains btyes of the UTF8 character
* n - size of bytes of the character (1,2,3,4)
*
* Return:
* the unicode from the character
*/
unsigned int GetUnicodeFromUtf8(unsigned char inByte, unsigned char auxInByte[3], int n);
/**
* Parameters:
* inByte - BOOM byte
*
* Return:
* boolean result
*/
int IsLittle(unsigned int inByte);
/**
* Parameters:
* inByte - character of UTF32 format
* outByte - adress to be fill in with utf8 charcter
* size - size of the outByte output
*
*/
void GetUf8FromUnicode(unsigned int inByte, unsigned char *outByte, int size);
/**
* Parameters:
* outByte - unsigned int to be converted
*
* Return:
* the outByte with inverted edian (if little -> big)
*
*/
unsigned int InvertEdian(unsigned int outByte);
/**
* Parameters:
* inByte - unsigned int in UTF32 format
*
* Return:
* size of the UTF8 character
*
*/
int SetUtf8Size(unsigned int inByte);
/**
* Parameters:
* outByte - array to be reset
*
*/
void ResetOut(unsigned char *outByte);
#pragma endregion
#pragma region Public Methods
int utf32_8(FILE *inFile, FILE *outFile)
{
unsigned int inByte;
unsigned char outByte[4];
unsigned int isLittle;
int tamInOutByte;
fread(&inByte, sizeof(inByte), 1, inFile);
isLittle = IsLittle(inByte);
while (fread(&inByte, sizeof(inByte), 1, inFile))
{
if (isLittle)
{
inByte = InvertEdian(inByte);
}
tamInOutByte = SetUtf8Size(inByte);
GetUf8FromUnicode(inByte, outByte, tamInOutByte);
fwrite(outByte, tamInOutByte + 1, 1, outFile);
}
return 0;
}
int utf8_32(FILE *inFile, FILE *outFile)
{
unsigned char inByte;
unsigned char auxInByte[3];
unsigned int outByte;
int tamInOutByte;
unsigned int little = InvertEdian(BigBOOM);
/* Introduces BOOM Byte in Utf32 File */
fwrite(&little, sizeof(little), 1, outFile);
while (fread(&inByte, sizeof(inByte), 1, inFile))
{
if (tamInOutByte = IdentifyCharSize(inByte))
{
if (!fread(auxInByte, tamInOutByte-1, 1, inFile))
{
perror("Fail to identify size of char ");
exit(1);
}
}
outByte = GetUnicodeFromUtf8(inByte, auxInByte, tamInOutByte);
outByte = InvertEdian(outByte);
fwrite(&outByte, sizeof(outByte), 1, outFile);
}
}
#pragma endregion
#pragma region Private Methods
int IdentifyCharSize(unsigned char inByte)
{
unsigned char aux;
int ret = FALSE;
int loop = TRUE;
while (loop)
{
aux = inByte;
if ((aux >> (8 - loop)) & 0x01)
{
ret++;
loop++;
}
else
{
break;
}
if (loop > 5)
{
perror("Erro to identify given byte");
exit(1);
}
}
return ret;
}
unsigned int GetUnicodeFromUtf8(unsigned char inByte, unsigned char auxInByte[3], int n)
{
unsigned int ret = 0x00;
unsigned int aux;
unsigned char a;
int desloc = 6;
int cont;
ret += ((inByte << (n + 1)) >> (n + 1));
/* if n is positive then is a multiple byte char */
if (n>0)
{
a = inByte << (n+1);
a = a >> (n+1);
ret = a;
for (cont = 0; cont < n-1; cont++)
{
ret = ret << 6;
aux = auxInByte[cont] & 0x3f;
ret = ret + aux;
}
}
return ret;
}
unsigned int InvertEdian(unsigned int outByte)
{
unsigned int ret = 0x00;
unsigned int aux;
int cont, desloc = 8;
for (cont = 0; cont < 4; cont++)
{
aux = outByte;
aux = (aux >> (cont * desloc)) & 0xff;
ret += aux;
if (cont != 3)
{
ret = ret << desloc;
}
}
return ret;
}
int Is8Utf(FILE *inAuxFile) /* main */
{
unsigned int firstChar;
fread(&firstChar, sizeof(firstChar), 1, inAuxFile);
return firstChar != InvertEdian(BigBOOM) && firstChar != BigBOOM;
}
int SetUtf8Size(unsigned int inByte)
{
int ret = 0;
if (inByte > 0x7f)
{
ret += 1;
if (inByte > 0x7ff)
{
ret += 1;
if (inByte > 0xffff)
{
ret += 1;
}
}
}
return ret;
}
void GetUf8FromUnicode(unsigned int inByte, unsigned char *outByte, int size)
{
ResetOut(outByte);
if (size == 1)
{
outByte[1] = 0x80 + (inByte & 0x3f);
outByte[0] = 0xc0 + (inByte >> 6);
}
else if (size == 2)
{
outByte[2] = 0x80 + (inByte & 0x3f);
outByte[1] = 0x80 + ((inByte >> 6) & 0x3f);
outByte[0] = 0xe0 + (inByte >> 12);
}
else if (size == 3)
{
outByte[3] = 0x80 + (inByte & 0x3f);
outByte[2] = 0x80 + ((inByte >> 6) & 0x3f);
outByte[1] = 0x80 + ((inByte >> 12) & 0x3f);
outByte[0] = 0xf0 + (inByte >> 18);
}
else
{
outByte[0] = inByte;
}
}
void ResetOut(unsigned char *outByte)
{
int cont;
for (cont = 0; cont < 4; cont++)
{
outByte[cont] = 0x00;
}
}
int IsLittle(unsigned int inByte)
{
int ret = TRUE;
if (inByte == BigBOOM)
{
ret = FALSE;
}
return ret;
}
#pragma endregion<file_sep>#include "../headers/conv_utf.h"
#define MAXPATHSIZE 512
#pragma region Private methods Declaration
/**
* Method to verify if given file is a 8UTF coded file
*
* Parameters:
* inFile - the input file to be checked
*
* Return:
* boolean result
* if the file is a 8UTF type file return 1
* else 0
*
* */
int Is8Utf(FILE *inAuxFile);
#pragma endregion
int main(void)
{
/* Variables */
DIR* filesToConvert;
struct dirent *inFileName;
char inFilesDir[MAXPATHSIZE], outFilesDir[MAXPATHSIZE];
char inFilePath[MAXPATHSIZE], outFilePath[MAXPATHSIZE];
FILE *inFile, *outFile, *inAuxFile;
/* defines origin of files to be converted and destination for the converted files */
sprintf(inFilesDir, "../%s", "toConvert");
sprintf(outFilesDir, "../%s", "converted");
/* list of all arq's to be converted */
if (!(filesToConvert = opendir(inFilesDir)))
{
perror("Error open directory \"/toConvert\", please read the README.md file");
exit(1);
}
/* loop through the files to be converted */
while ( ( inFileName = readdir(filesToConvert) ))
{
if (strcmp (inFileName->d_name, ".") && strcmp(inFileName->d_name, ".."))
{
/* Define path of input file and out file */
sprintf(inFilePath, "%s/%s" ,inFilesDir,inFileName->d_name);
sprintf(outFilePath, "%s/%s", outFilesDir,inFileName->d_name);
/* Needed to verify BOOM char */
inAuxFile = fopen(inFilePath, "rb");
/* Open respective in and out files */
inFile = fopen(inFilePath, "rb");
outFile = fopen(outFilePath, "wb");
if (Is8Utf(inAuxFile))
{
utf8_32(inFile, outFile);
}
else
{
utf32_8(inFile,outFile);
}
/* Close respective in and out files */
fclose(inFile);
fclose(outFile);
fclose(inAuxFile);
}
}
/* Close directory */
closedir(filesToConvert);
}
| f1a80c7fc3bee5e92aea28c0855702de60a131bb | [
"Markdown",
"C"
] | 4 | Markdown | MatheusRPaixao/SoftwareBasico_2020_1 | d668f5ac225439403b3945c18b8f1a90393712dc | 32fca4cb1bdc02ea96e2742a9632cc110a980660 |
refs/heads/master | <file_sep>export default function on(type, listener, options) {
return function (node, prevListener) {
if (listener !== prevListener) {
if (prevListener) {
node.removeEventListener(type, prevListener, options);
}
if (listener) {
node.addEventListener(type, listener, options);
}
}
return listener;
};
}
<file_sep>(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.SurplusOnMixin = {})));
}(this, (function (exports) { 'use strict';
function on(type, listener, options) {
return function (node, prevListener) {
if (listener !== prevListener) {
if (prevListener) {
node.removeEventListener(type, prevListener, options);
}
if (listener) {
node.addEventListener(type, listener, options);
}
}
return listener;
};
}
exports.default = on;
Object.defineProperty(exports, '__esModule', { value: true });
})));
<file_sep>export default function on<T extends Element, K extends keyof HTMLElementEventMap>(type: K, listener: (this: T, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions) {
return function (node : T, prevListener?: (this: T, ev: HTMLElementEventMap[K]) => any) {
if (listener !== prevListener) {
if (prevListener) {
node.removeEventListener(type, prevListener, options);
}
if (listener) {
node.addEventListener(type, listener, options);
}
}
return listener;
};
}<file_sep># surplus-mixin-on
## Declarative custom event binding for Surplus applications
Most of the time, we can attach event handlers to Surplus nodes by using the `on...={...}` DOM properties:
```javascript
<button onclick={handleClick}>Click me!</button>
```
However, this doesn't work in two cases:
1. If we're trying to attach to a custom event -- `my-custom-event` -- there are no DOM properties for it.
2. If we want to attach multiple handlers for the same event -- the DOM properties can only have one handler.
Surplus-mixin-on is a small `fn={...}` mixin for Surplus applications that addresses both of these.
```javascript
// custom events
<div fn={on('my-custom-event', handleCustomEvent)}></div>
// multiple handlers
<div fn={on('click', handleClick1)}
fn={on('click', handleClick2)}
><div>
```
Under the hood, surplus-mixin-on uses the `addEventListener()` method on the nodes rather than the event handler properties. | d1e6d2f0691660e143d94324f7bfe72ae0d5acb2 | [
"JavaScript",
"TypeScript",
"Markdown"
] | 4 | JavaScript | adamhaile/surplus-mixin-on | dde707f55ba7f3a527ad9cb0538a4263fc53c32d | 9af0709a03409ab2554830de55191dce0254f746 |
refs/heads/master | <file_sep><?php
return [
'class' => 'app\auth\Base',
'username' => 'username',
'password' => '<PASSWORD>',
];
<file_sep><?php
namespace framework\driver\rpc;
class Http
{
// client实例
protected $client;
/*
* 构造函数
*/
public function __construct($config)
{
$this->client = new client\Http($config);
}
/*
* query实例
*/
public function query($name = null, $filters = null, $headers = null)
{
return new query\Http($this->client, $name, $filters, $headers);
}
}<file_sep><?php
define('APP_DEBUG', true);
$xhprof_dir = '/home/qiujin/www/xhprof/';
include "$xhprof_dir/xhprof_lib/utils/xhprof_lib.php";
include "$xhprof_dir/xhprof_lib/utils/xhprof_runs.php";
xhprof_enable(XHPROF_FLAGS_NO_BUILTINS | XHPROF_FLAGS_CPU | XHPROF_FLAGS_MEMORY);
include '../../../framework/app.php';
$app = framework\App::start('Inline', [
'controller_prefix' => 'controller/inline'
//'param_mode' => 2,
]);
framework\core\Hook::add('exit', function() {
$xhprof_data = xhprof_disable();
$xhprof_runs = new XHProfRuns_Default();
$run_id = $xhprof_runs->save_run($xhprof_data, "xhprof_test");
file_put_contents(APP_DIR.'storage/cache/xhprof_test', $run_id);
});
$app->run();
<file_sep><?php
namespace framework\core;
abstract class Facade
{
// 实例
private static $instances;
// 提供者
protected static $provider;
/*
* 魔术方法,执行实例方法
*/
public static function __callStatic($method, $params)
{
return static::make()->$method(...$params);
}
/*
* 清除实例
*/
public static function clear($class = null)
{
if (static::class !== __CLASS__) {
return static::__callStatic('clear', func_get_args());
}
if ($class === null) {
self::$instances = null;
} elseif (isset(self::$instances[$class])) {
unset(self::$instances[$class]);
}
}
/*
* 生成实例
*/
protected static function make()
{
return self::$instances[static::class] ??
self::$instances[static::class] = Container::makeCustomProvider(static::$provider);
}
}
<file_sep><?php
namespace framework\driver\rpc\client;
use framework\util\Arr;
use framework\core\http\Client;
class GrpcHttp
{
// 配置项
protected $config = [
/*
// 服务端点(HTTP)
'endpoint'
// 公共headers(HTTP)
'http_headers'
// HTTP 请求编码
'http_request_encode' => ['gzip' => 'gzencode'],
// HTTP 响应解码
'http_response_decode' => ['gzip' => 'gzdecode'],
// service类名前缀
'service_prefix'
// schema定义文件加载规则
'schema_loader_rules'
*/
// CURL设置(HTTP)
'http_curlopts' => [
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_2_0
],
// 请求参数协议类格式
'http_request_message_format' => '{service}{method}Request',
// 响应结构协议类格式
'http_response_message_format' => '{service}{method}Response',
];
/*
* 构造函数
*/
public function __construct($config)
{
$this->config = $config + $this->config;
}
/*
* 发送请求
*/
public function send($service, $method, $message)
{
if (isset($this->config['service_prefix'])) {
$service = $this->config['service_prefix'].'\\'.$service;
}
$url = $this->config['endpoint'].'/'.strtr($service, '\\', '.').'/'.$method;
$client = Client::post($url);
$data = $this->makeRequestMessage($service, $method, $message)->serializeToString();
if (isset($this->config['http_request_encode'])) {
$encode_name = array_rand($this->config['http_request_encode']);
$encode_function = $this->config['http_request_encode'][$encode_name];
$client->header('grpc-encoding', $encode_name);
$encode = 1;
$data = $encode_function($data);
}
if (isset($this->config['http_response_decode'])) {
$client->header('grpc-accept-encoding', implode(', ', array_keys($this->config['http_response_decode'])));
}
if (isset($this->config['http_headers'])) {
$client->headers($this->config['http_headers']);
}
if (isset($this->config['http_curlopts'])) {
$client->curlopts($this->config['http_curlopts']);
}
$size = strlen($data);
$client->body(pack('C1N1a'.$size, $encode ?? 0, $size, $data));
$response = $client->response();
if (isset($response->headers['grpc-status'])) {
if ($response->headers['grpc-status'] === '0') {
$result = unpack('Cencode/Nsize/a*data', $response->body);
if ($result['size'] != strlen($result['data'])) {
error('Invalid input: size error');
}
if ($result['encode'] == 1) {
if (($decode_name = strtolower($response->headers['grpc-encoding'] ?? null))
&& isset($this->config['http_response_decode'][$decode_name])
) {
$result['data'] = ($this->config['http_response_decode'][$decode_name])($result['data']);
} else {
error("Can't decode: $decode_name response");
}
}
$response_class = strtr($this->config['http_response_message_format'], [
'{service}' => $service,
'{method}' => ucfirst($method)
]);
$response_message = new $response_class;
$response_message->mergeFromString($result['data']);
return $response_message;
}
error("[{$response->headers['grpc-status']}]".$response->headers['grpc-message']);
}
error($client->error);
}
/*
* 生成请求信息实例
*/
protected function makeRequestMessage($service, $method, $message)
{
if (isset($this->config['http_request_message_format'])) {
if (is_array($message)) {
$class = strtr($this->config['http_request_message_format'], [
'{service}' => $service,
'{method}' => ucfirst($method)
]);
$message = new $class;
$message->mergeFromJsonString(json_encode($message));
return $message;
}
} else {
if (is_subclass_of($message, Message::class)) {
return $message;
}
}
throw new \Exception('Invalid params');
}
}
<file_sep><?php
namespace framework\core;
class Event
{
private static $init;
// 事件容器
private static $events;
// 排序计数器
private static $counter = PHP_INT_MAX;
/*
* 初始化
*/
public static function __init()
{
if (self::$init) {
return;
}
self::$init = true;
if ($config = Config::read('event')) {
foreach ($config as $name => $events) {
foreach ($events as $i => $event) {
self::on($name, $event, $i);
}
}
}
}
/*
* 注册事件
*/
public static function on($name, callable $call, $priority = 0)
{
$event = self::$events[$name] ?? self::$events[$name] = new \SplPriorityQueue();
return $event->insert($call, [$priority, self::$counter--]);
}
/*
* 是否注册
*/
public static function has($name)
{
return isset(self::$events[$name]);
}
/*
* 注册事件数量
*/
public static function count($name)
{
return isset(self::$events[$name]) ? self::$events[$name]->count() : 0;
}
/*
* 删除事件
*/
public static function delete($name)
{
if (isset(self::$events[$name])) {
unset(self::$events[$name]);
}
}
/*
* 触发事件
*/
public static function trigger($name, ...$params)
{
if (isset(self::$events[$name])) {
while (self::$events[$name]->valid()) {
//&& (self::$events[$name]->extract())(...$params) !== false
$params = (self::$events[$name]->extract())(...$params) ?? [];
if ($params === false) {
break;
}
}
unset(self::$events[$name]);
}
}
}
Event::__init();
<file_sep><?php
namespace framework\core;
use framework\util\Arr;
class Config
{
private static $init;
//配置值缓存
private static $config;
//文件检查缓存
private static $checked;
//配置文件目录
private static $config_dir;
/*
* 初始化
*/
public static function __init()
{
if (self::$init) {
return;
}
self::$init = true;
if (defined('ENV_FILE')) {
__require(ENV_FILE);
} elseif (file_exists(APP_DIR.'env.php')) {
__require(APP_DIR.'env.php');
}
if (!defined('app\env\APP_DEBUG')) {
define('app\env\APP_DEBUG', false);
}
if (!defined('app\env\STRICT_ERROR_MODE')) {
define('app\env\STRICT_ERROR_MODE', true);
}
if ($config_file = self::env('CONFIG_FILE')) {
self::$config = __require($config_file);
}
self::$config_dir = self::env('CONFIG_DIR');
}
/*
* 获取环境变量值
*/
public static function env($name, $default = null)
{
return defined($const = "app\\env\\$name") ? constant($const) : $default;
}
/*
* 读取配置项值,不缓存值(仅支持顶级配置项)
*/
public static function read($name)
{
if (strpos($name, '.') === false) {
return self::$config[$name] ?? self::loadFile($name);
}
}
/*
* 获取配置项值
*/
public static function get($name, $default = null)
{
$ns = explode('.', $name);
$fn = array_shift($ns);
if (!self::check($fn)) {
return $default;
}
$value = self::$config[$fn];
if ($ns) {
return is_array($value) ? Arr::get($value, $ns, $default) : $default;
}
return $value;
}
/*
* 检查配置项是否已设置
*/
public static function has($name)
{
$ns = explode('.', $name);
$fn = array_shift($ns);
if (!self::check($fn)) {
return false;
}
$value = self::$config[$fn];
if ($ns) {
return is_array($value) ? Arr::has($value, $ns, $default) : false;
}
return true;
}
/*
* 设置配置项值
*/
public static function set($name, $value)
{
$ns = explode('.', $name);
$fn = array_shift($ns);
if ($ns) {
if (!self::check($fn) || !is_array(self::$config[$fn])) {
self::$config[$fn] = [];
}
Arr::set(self::$config[$fn] , $ns, $value);
} else {
self::$config[$fn] = $value;
}
}
/*
* 检查配置是否导入
*/
private static function check($name)
{
if (isset(self::$config[$name])) {
return true;
}
if (!isset(self::$checked[$name])) {
self::$checked[$name] = true;
$config = self::loadFile($name);
if (isset($config)) {
self::$config[$name] = $config;
return true;
}
}
return false;
}
/*
* 从配置目录中读取子配置文件
*/
private static function loadFile($name)
{
if (self::$config_dir && is_php_file($file = self::$config_dir."$name.php") && is_array($config = __require($file))) {
return $config;
}
}
}
Config::__init();
<file_sep><?php
include '../../../framework/app.php';
framework\App::boot();
driver('captcha', 'image')->output();
<file_sep><?php
namespace framework\util;
class Str
{
/*
* 下划线转驼峰
*/
public static function camelCase(string $str, string $s = '_')
{
$ret = '';
foreach(explode($s, $str) as $v){
$ret .= ucfirst($v);
}
return $ret;
}
/*
* 驼峰转下划线
*/
public static function snakeCase(string $str, string $s = '_')
{
$ret = '';
$len = strlen($str);
$str = lcfirst($str);
for ($i = 0; $i < $len; $i++) {
$c = $str[$i];
$l = strtolower($c);
$ret .= $c === $l ? $c : $s.$l;
}
return $ret;
}
/*
* 头部补全
*/
public static function headPad(string $str, string $s)
{
return substr($str, 0, strlen($s)) == $s ? $str : $s.$str;
}
/*
* 尾部补全
*/
public static function lastPad(string $str, string $s)
{
return substr($str, - strlen($s)) == $s ? $str : $str.$s;
}
/*
* 按位置切割成两半
*/
public static function cut(string $str, int $pos)
{
return [substr($str, 0, $pos), substr($str, $pos)];
}
/*
* 格式替换
*/
public static function format(string $str, array $data, string $format = '{%s}')
{
$replace = [];
foreach ($data as $k => $v) {
$replace[sprintf($format, $k)] = $v;
}
return strtr($str, $replace);
}
/*
* 随机串
*/
public static function random(int $length = 32, int $mode = 2)
{
static $strs = [
//[位码, 长度, 字符集]
[1, 10, '1234567890'],
[2, 26, 'abcdefghijklmnopqrstuvwxyz'],
[4, 26, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'],
[8, 28, '!@#$?|{/:;%^&*()-_[]}<>~+=,.']
];
$l = 0;
$str = '';
foreach ($strs as $s) {
if ($mode & $s[0]) {
$l += $s[1];
$str .= $s[2];
}
}
$ret = '';
for ($i = 0; $i < $length; $i++) {
$ret .= $str[mt_rand(0, $l - 1)];
}
return $ret;
}
}
<file_sep><?php
namespace app\hook;
use framework\App;
use framework\core\http\Request;
use framework\core\http\Response;
class RateLimit
{
public static function run()
{
$config = [
//周期秒数
'ttl' => 10,
//请求限制数
'limit' => 100,
//缓存配置
'cache' => 'apc'
];
$ip = Request::ip();
$cache = cache($config['cache']);
$count = $cache->get($ip, 0);
Response::headers([
'X-Rate-Limit-Limit' => $config['limit'],
'X-Rate-Limit-Remaining' => $config['limit']-$count-1,
'X-Rate-Limit-Reset' => $config['ttl']
]);
if ($count >= $config['limit']) {
Response::status(429);
App::exit();
} else{
if ($count) {
$cache->increment($ip);
} else {
$cache->set($ip, 1, $config['ttl']);
}
}
}
}
<file_sep><?php
namespace framework\driver\db\query;
class Union extends QueryChain
{
// UNION ALL
protected $all;
// union表名
protected $union;
// 多联表设置项
protected $table_options = [];
/*
* 初始化
*/
protected function __init($table, $options, $union, $all = true)
{
$this->all = $all;
$this->table = $table;
$this->union = $union;
$this->table_options[$table] = $options;
}
/*
* union表链
*/
public function union($table)
{
$this->options['fields'] = $this->table_options[$this->table]['fields'];
$this->table_options[$this->union] = $this->options;
$this->union = $table;
return $this;
}
/*
* 查询(多条)
*/
public function find()
{
$sql = $params = [];
$this->table_options[$this->union] = $this->options;
foreach ($this->table_options as $table => $options) {
$select = $this->builder::select($table, $options);
$sql[] = "($select[0])";
$params = array_merge($params, $select[1]);
}
$union = $this->all ? ' UNION ALL ' : ' UNION ';
return $this->db->find(implode($union, $sql), $params);
}
}
<file_sep><?php
// 无模式应用示例的bootstrap文件
define('APP_DEBUG', true);
include '../../../framework/app.php';
framework\App::boot();
$that = (new class() {
use Getter;
});
framework\core\Hook::add('exit', function () {
global $ret;
Response::json($ret, false);
});
<file_sep><?php
namespace framework\driver\db;
use framework\util\Arr;
use framework\core\Container;
class Cluster
{
// 现实例
protected $work;
// 读实例
protected $read;
// 写实例
protected $write;
// 配置
protected $config;
// 构造器
protected $builder;
/*
* 构造函数
*/
public function __construct($config)
{
$this->config = $config;
$this->builder = (__NAMESPACE__.'\\'.ucfirst($config['dbtype']))::BUILDER;
}
/*
* 魔术方法,query实例
*/
public function __get($name)
{
return $this->table($name);
}
/*
* query实例
*/
public function table($name)
{
return new query\Query($this, $name);
}
/*
* 读取语句返回全部数据
*/
public function all($sql, $params = null)
{
return $this->selectDatabase(false)->all($sql, $params);
}
/*
* 更新语句返回影响数量
*/
public function exec($sql, $params = null)
{
return $this->selectDatabase(true)->exec($sql, $params);
}
/*
* 读取语句返回结果对象
*/
public function query($sql, $params = null)
{
return $this->selectDatabase(false)->query($sql, $params);
}
/*
* 获取构造器
*/
public function getBuilder()
{
return $this->builder;
}
/*
* 获取数据库实例
*/
public function getDatabase($mode = null)
{
switch ($mode) {
case null:
return $this->work;
case true:
return $this->write ?? $this->read;
case 'read':
case 'write':
return $this->$mode ?? $this->makeDatabase($mode);
}
throw new \Exception("Invalid cluster database mode: $mode");
}
/*
* 魔术方法,调用数据库实例方法
*/
public function __call($method, $params)
{
$m = strtolower($method);
if (in_array($m, ['insertid', 'begintransaction', 'rollback', 'commit', 'transaction'])) {
$is_write = true;
} elseif (in_array($m, ['fields', 'getfields'])) {
$is_write = false;
}
// 其他quote, errno, error, debug, getConnection
return $this->selectDatabase($is_write ?? null)->$method(...$params);
}
/*
* 选择数据库实例
*/
protected function selectDatabase($is_write = null)
{
if (isset($is_write)) {
if ($is_write) {
$db = $this->write ?? $this->makeDatabase('write');
} elseif (!empty($this->config['follow_write']) && $this->write) {
$db = $this->write;
} else {
$db = $this->read ?? $this->makeDatabase('read');
}
return $this->work = $db;
}
return $this->work ?? $this->work = ($this->read ?? $this->write ?? $this->makeDatabase('read'));
}
/*
* 生成数据库实例
*/
protected function makeDatabase($mode)
{
$config = Arr::random($this->config[$mode]);
$config['read'] = $config['write'] = null;
$config['driver'] = $this->config['dbtype'];
return $this->$mode = Container::driver('db', $config + $this->config);
}
}
<file_sep><?php
include '../bootstrap.php';
$ret = $that->db->user->get();<file_sep><?php
namespace framework\driver\rpc\client;
use framework\core\http\Client;
class JsonrpcHttp
{
// 配置项
protected $config/* = [
// 服务端点(HTTP)
'endpoint'
// HTTP请求headers(HTTP)
'http_headers',
// HTTP请求curl设置(HTTP)
'http_curlopts'
]*/;
/*
* 构造函数
*/
public function __construct($config)
{
$this->config = $config;
}
/*
* 发送请求
*/
public function send($data)
{
$client = Client::post($this->config['endpoint']);
if (isset($this->config['http_headers'])) {
$client->headers($this->config['http_headers']);
}
if (isset($this->config['http_curlopts'])) {
$client->curlopts($this->config['http_curlopts']);
}
$client->body($this->config['requset_serialize']($data));
$result = $client->response()->body;
if ($result !== false) {
return $this->config['response_unserialize']($result);
}
if ($error = $client->error) {
error("-32000: Internet error [$error->code]$error->message");
} else {
error('-32603: nvalid JSON-RPC response');
}
}
}<file_sep><?php
return [
/*
'boot' => [
//'app\hook\Bootstrap::run'
//'app\hook\Redirect::run',
'app\hook\RateLimit::run',
'app\hook\VerifyCsrf::run'
],
'start' => [
'framework\core\Auth::run'
],
'request' => [
'app\hook\RequestTrim::run',
],
'response' => [
'app\hook\ResponseHeader::run'
],
'exit' => [
],
'close' => [
],*/
];
<file_sep><?php
// 参考 https://cloud.google.com/apis/design
namespace framework\core\app;
use framework\App;
use framework\util\Str;
use framework\util\Xml;
use framework\core\Config;
use framework\core\Dispatcher;
use framework\core\http\Status;
use framework\core\http\Request;
use framework\core\http\Response;
class Rest extends App
{
protected $config = [
// 调度模式,支持default route组合
'dispatch_mode' => ['default'],
// 控制器namespace
'controller_ns' => 'controller',
// 控制器类名后缀
'controller_suffix' => null,
/* 默认调度的参数模式
* 0 无参数
* 1 顺序参数
* 2 键值参数
*/
'default_dispatch_param_mode' => 1,
// 控制器类namespace深度,0为不确定
'default_dispatch_depth' => 1,
// 默认调度的路径转为驼峰风格
'default_dispatch_to_camel' => 0,
// 默认调度的控制器,为空不限制
'default_dispatch_controllers' => null,
/* 是否启用自定义方法
* https://cloud.google.com/apis/design/custom_methods
*/
'enable_custom_methods' => false,
// 默认调度下允许的HTTP方法
'default_dispatch_http_methods' => ['GET', 'POST', 'PUT', 'DELETE'/*, 'HEAD', 'PATCH', 'OPTIONS'*/],
// 资源调度的参数模式
'resource_dispatch_param_mode' => 0,
// 资源调度默认路由表
'resource_dispatch_routes' => [
'/' => [':GET' => 'index()', ':POST' => 'create()'],
'*' => [':GET' => 'get()', ':PUT' => 'update()', ':DELETE' => 'delete()']
],
// 路由调度的参数模式
'route_dispatch_param_mode' => 1,
// 路由调度的路由表,如果值为字符串则作为配置名引入
'route_dispatch_routes' => null,
// 是否路由动态调用
'route_dispatch_dynamic' => false,
// 设置动作调度路由属性名,为null则不启用动作路由
'action_dispatch_routes_property' => 'routes',
];
// 请求方法
protected $method;
/*
* 调度
*/
protected function dispatch()
{
$path = App::getPathArr();
$this->method = Request::method();
if ($this->config['enable_custom_methods']) {
$v = array_pop($path);
if (strpos($v, ':') !== false) {
list($v, $this->method) = explode(':', $v);
array_push($path, $v);
}
}
foreach ((array) $this->config['dispatch_mode'] as $mode) {
if ($dispatch = $this->{$mode.'Dispatch'}($path)) {
return $this->dispatch = $dispatch;
}
}
}
/*
* 调用
*/
protected function call()
{
return ($this->dispatch['instance'])->{$this->dispatch['action']}(...$this->dispatch['params']);
}
/*
* 错误
*/
protected function error($code = null, $message = null)
{
Response::code($code ?? 500);
Response::json(['error' => compact('code', 'message')]);
}
/*
* 响应
*/
protected function respond($return = null)
{
Response::json($return);
}
/*
* 默认调度
*/
protected function defaultDispatch($path)
{
$count = count($path);
$depth = $this->config['default_dispatch_depth'];
$param_mode = $this->config['default_dispatch_param_mode'];
if (isset($this->dispatch['continue'])) {
$instance = $this->dispatch['instance'];
list($controller, $params) = $this->dispatch['continue'];
if ($params && $param_mode == 0) {
return;
}
} else {
if ($depth > 0) {
if ($count == $depth) {
$controller_array = $path;
} elseif ($count > $depth && $param_mode > 0) {
$controller_array = array_slice($path, 0, $depth);
$params = array_slice($path, $depth);
}
} elseif ($path && $param_mode == 0) {
$controller_array = $path;
}
if (!isset($controller_array)) {
return;
}
if ($this->config['default_dispatch_to_camel']) {
$controller_array[] = Str::camelCase(array_pop($controller_array), $this->config['default_dispatch_to_camel']);
}
$controller = implode('\\', $controller_array);
if (!isset($this->config['default_dispatch_controllers'])) {
$check = true;
} elseif (!in_array($controller, $this->config['default_dispatch_controllers'])) {
return;
}
if (!$class = $this->getControllerClass($controller, isset($check))) {
return;
}
$instance = new $class();
}
$action = $this->method;
if (($this->config['enable_custom_methods'] || in_array($action, $this->config['default_dispatch_http_methods']))
&& is_callable([$instance, $action])) {
if (!isset($params)) {
$params = [];
}
$reflection = new \ReflectionMethod($instance, $action);
if ($param_mode == 1 && !$this->checkMethodParamsNumber($reflection, count($params))) {
return;
}
if ($param_mode == 2) {
if (($params = $this->getMethodKvParams($params)) === false ||
($params = $this->bindMethodKvParams($reflection, $params, true)) === false
) {
return;
}
}
return compact('action', 'controller', 'instance', 'params');
}
if (!isset($this->dispatch['continue'])) {
$this->dispatch = ['continue' => [$controller, $params ?? []], 'instance' => $instance];
}
}
/*
* 资源调度
*/
protected function resourceDispatch($path)
{
if (($depth = $this->config['default_dispatch_depth']) < 1) {
throw new \Exception('If use resource dispatch, must controller_depth > 0');
}
if (isset($this->dispatch['continue'])) {
$instance= $this->dispatch['instance'];
list($controller, $action_path) = $this->dispatch['continue'];
} elseif (count($path) >= $depth) {
if ($this->config['default_dispatch_to_camel']) {
$path[$depth] = Str::camelCase($path[$depth], $this->config['default_dispatch_to_camel']);
}
$controller = implode('\\', array_slice($path, 0, $depth));
if (!isset($this->config['default_dispatch_controllers'])) {
$check = true;
} elseif (!in_array($controller, $this->config['default_dispatch_controllers'])) {
return;
}
if (!$class = $this->getControllerClass($controller, isset($check))) {
return;
}
$action_path = array_slice($path, $depth);
$instance = new $class();
} else {
return;
}
$routes = $this->config['resource_dispatch_routes'];
$param_mode = $this->config['resource_dispatch_param_mode'];
if (($dispatch = Dispatcher::route($action_path, $routes, $param_mode, false, $this->method))
&& is_callable([$instance, $dispatch[0]])
) {
if ($param_mode == 2) {
$dispatch[1] = $this->bindMethodKvParams(new \ReflectionMethod($instance, $dispatch[0]), $dispatch[1]);
}
return [
'controller' => $controller,
'instance' => $instance,
'action' => $dispatch[0],
'params' => $dispatch[1],
];
}
if (!isset($this->dispatch['continue'])) {
$this->dispatch = ['continue' => [$controller, $action_path], 'instance' => $instance];
}
}
/*
* 路由调度
*/
protected function routeDispatch($path)
{
$param_mode = $this->config['route_dispatch_param_mode'];
if (isset($this->dispatch['continue']) && $this->config['action_dispatch_routes_property']) {
$action_route_dispatch = $this->actionRouteDispatch(
$param_mode,
$this->dispatch['instance'],
$this->dispatch['continue'][0],
$this->dispatch['continue'][1]
);
if (isset($action_route_dispatch)) {
return $action_route_dispatch;
}
}
if ($this->config['route_dispatch_routes']) {
$routes = $this->config['route_dispatch_routes'];
if (is_string($routes) && !($routes = Config::read($routes))) {
return;
}
$dynamic = $this->config['route_dispatch_dynamic'];
if ($dispatch = Dispatcher::route($path, $routes, $param_mode, $dynamic, $this->method)) {
$call = explode('::', $dispatch[0]);
$class = $this->getControllerClass($call[0], $dispatch[2]);
$instance = new $class();
if (isset($call[1])) {
if ($dispatch[2]
&& ($call[1][0] === '_' || !is_callable([$instance, $call[1]]))
) {
return;
}
if ($param_mode == 2) {
$dispatch[1] = $this->bindMethodKvParams(new \ReflectionMethod($instance, $call[1]), $dispatch[1]);
}
return [
'controller' => $call[0],
'instance' => $instance,
'action' => $call[1],
'params' => $dispatch[1],
];
} elseif (isset($dispatch[3])) {
if ($this->config['action_dispatch_routes_property']) {
$action_route_dispatch = $this->actionRouteDispatch(
$param_mode, $instance, $call[0], $dispatch[3]
);
if (isset($action_route_dispatch)) {
return $action_route_dispatch;
}
}
$this->dispatch = ['continue' => [$dispatch[0], $dispatch[3]], 'instance' => $instance];
return;
}
throw new \Exception("无效的路由dispatch规则: $call");
}
}
}
/*
* Action 路由调度
*/
protected function actionRouteDispatch($param_mode, $instance, $controller, $path)
{
$property = $this->config['action_dispatch_routes_property'];
if (!isset($instance->$property)) {
return;
}
if ($dispatch = Dispatcher::route(
$path,
$instance->$property,
$param_mode,
$this->config['route_dispatch_dynamic'],
$this->method
)) {
if ($dispatch[2]
&& ($dispatch[0][0] === '_' || !is_callable([$instance, $dispatch[0]]))
) {
return false;
}
if ($param_mode == 2) {
$dispatch[1] = $this->bindMethodKvParams(new \ReflectionMethod($instance, $dispatch[0]), $dispatch[1]);
}
return [
'controller' => $controller,
'instance' => $instance,
'action' => $dispatch[0],
'params' => $dispatch[1],
];
}
return false;
}
/*
* 获取键值参数
*/
protected function getMethodKvParams(array $arr)
{
$len = count($arr);
if ($len % 2 != 0) {
return false;
}
for ($i = 1; $i < $len; $i = $i + 2) {
$params[$arr[$i-1]] = $arr[$i];
}
return $params ?? [];
}
/*
* 设置POST参数
*/
protected function setRequestParam()
{
if ($type = Request::header('Content-Type')) {
switch (strtolower(trim(strtok($type, ';')))) {
case 'application/json':
$_POST = json_decode(Request::body(), true);
return;
case 'application/xml';
$_POST = Xml::decode(Request::body());
return;
}
}
}
/*
* 检查方法参数数
*/
protected function checkMethodParamsNumber($reflection, $number)
{
return $number >= $reflection->getNumberOfRequiredParameters() && $number <= $reflection->getNumberOfParameters();
}
}
<file_sep><?php
namespace framework\util;
use framework\core\Container;
class File
{
/*
* 文件读取
*/
public static function get($file, $check = false)
{
return (!$check || is_file($file)) ? file_get_contents($file) : false;
}
/*
* 文件写入
*/
public static function put($file, $contents, $flags = 0)
{
return self::makeDir(dirname($file)) && file_put_contents($file, $contents, $flags);
}
/*
* 文件移动
*/
public static function move($file, $to, $check = false)
{
return (!$check || is_file($file)) && self::makeDir(dirname($to)) && rename($file, $to);
}
/*
* 文件复制
*/
public static function copy($file, $to, $check = false)
{
return (!$check || is_file($file)) && self::makeDir(dirname($to)) && copy($file, $to);
}
/*
* 文件删除
*/
public static function delete($file, $check = false)
{
return (!$check || is_file($file)) && unlink($file);
}
/*
* 文件扩展名
*/
public static function ext($file)
{
return pathinfo($file, PATHINFO_EXTENSION);
}
/*
* 文件mime
*/
public static function mime($file, $is_buffer = false)
{
$finfo = finfo_open(FILEINFO_MIME);
$mime = $is_buffer ? finfo_buffer($finfo, $file) : finfo_file($finfo, $file);
finfo_close($finfo);
return $mime;
}
/*
* 文件hash
*/
public static function hash($algo, $file, $raw = false)
{
return hash_file($algo, $file, $raw);
}
/*
* 文件上传
*/
public static function upload($file, $to, $is_buffer = false)
{
if (strpos($to, '://')) {
list($scheme, $to) = explode('://', $to, 2);
}
return Container::driver('storage', $scheme ?? null)->put($file, $to, $is_buffer);
}
/*
* 目录文件列表
*/
public static function files($dir, $recursive = false)
{
$ret = [];
$dir = Str::lastPad($dir, '/');
if ($open = opendir($dir)) {
while (($item = readdir($open)) !== false) {
$file = $dir.$item;
if (is_file($file)) {
$ret[] = $file;
} elseif ($recursive && is_dir($file) && $item !== '.' && $item !== '..') {
$ret = array_merge($ret, self::files($file, $recursive));
}
}
closedir($open);
}
return $ret;
}
/*
* 目录是否可写
*/
public static function isWritableDir($dir)
{
return is_dir($dir) && is_writable($dir) && is_executable($dir);
}
/*
* 如目录不存在则创建目录
*/
public static function makeDir($dir, $mode = 0777, $recursive = true)
{
return is_dir($dir) || mkdir($dir, $mode, $recursive);
}
/*
* 移动目录
*/
public static function moveDir($dir, $to)
{
$dir = Str::lastPad($dir, '/');
$to = Str::lastPad($to, '/');
if ($open = opendir($path)) {
while (($item = readdir($open)) !== false) {
if (is_dir($file = $dir.$item)) {
if ($item !== '.' && $item !== '..') {
self::moveDir($file, $to.$item);
}
} else {
self::makeDir($to);
rename($file, $to.$item);
}
}
closedir($open);
}
rmdir($dir);
}
/*
* 删除目录
*/
public static function deleteDir($dir)
{
self::cleanDir($dir);
rmdir($dir);
}
/*
* 清空目录(不删目录本身)
* $fitler 返回true表示删除对应文件
*/
public static function clearDir($dir, callable $fitler = null)
{
$dir = Str::lastPad($dir, '/');
if ($open = opendir($dir)) {
while (($item = readdir($open)) !== false) {
if ($item !== '.' && $item !== '..') {
$file = $dir.$item;
if (is_dir($file)) {
if (self::clearDir($file, $fitler)) {
rmdir($file);
} else {
$empty = false;
}
} else {
if ($fitler === null || $fitler($file) === true) {
unlink($file);
} else {
$empty = false;
}
}
}
}
closedir($open);
}
return $empty ?? true;
}
}
<file_sep><?php
include '../../../framework/app.php';
framework\App::start('Jsonrpc', [
'batch_max_num' => 1000,
])->run();
<file_sep><?php
namespace framework\driver\rpc\client;
/*
* https://grpc.io/docs/quickstart/php.html
*/
use Grpc\ChannelCredentials;
class Grpc
{
// 配置项
protected $config/* = [
// 服务主机(GRPC)
'host'
// 服务端口(GRPC)
'port'
// grpc设置(GRPC)
'grpc_options'
// service类名前缀
'service_prefix'
// schema定义文件加载规则
'schema_loader_rules'
] */;
// client实例
protected $clients;
/*
* 构造函数
*/
public function __construct($config)
{
$this->config = $config;
}
/*
* 发送请求
*/
public function send($service, $method, $message)
{
if (isset($this->config['service_prefix'])) {
$service = $this->config['service_prefix'].'\\'.$service;
}
$client = $this->getClient($service);
if (is_array($message)) {
$json_msg = json_encode($message);
$reflection = new \ReflectionMethod($client, $method);
$parameters = $reflection->getParameters();
$message = $parameters[0]->getClass()->newInstance();
$message->mergeFromJsonString($json_msg);
}
list($reply, $status) = $client->$method($message)->wait();
if ($status->code === 0) {
return $reply->getMessage();
}
error("[$status->code]$status->details");
}
/*
* 获取client实例
*/
protected function getClient($service)
{
if (isset($this->clients[$service])) {
return $this->clients[$service];
}
$class = $service.'Client';
$options = $this->config['grpc_options'] ?? null;
if (!isset($options['credentials'])) {
$options['credentials'] = ChannelCredentials::createInsecure();
}
return $this->clients[$service] = new $class($this->config['host'].':'.($this->config['port'] ?? 50051), $options);
}
}<file_sep><?php
namespace app\controller;
class User
{
use \Getter;
//action路由仅standard rest下有效
protected $routes = [
'*/name' => 'getName($1)',
'*/email' => 'getEmail($1)'
];
public function index()
{
return $this->db->user->find();
}
/*
* 在standard default dispatch下(url path对应控制器和方法)
* 请求 /User/get
*
* 在rest default dispatch下(HTTP get put post delete请求会自动调用url path控制器类下同名方法)
* 请求GET /User
*
* 在jsonroc下(使用body中的json数据dispatch)
* 请求POST / {"method":"User.get"}
*
* 在grpc下
* 请求POST /User/get
*/
public function get($id = 1)
{
return $this->db->user->get($id);
}
public function put($id)
{
return $this->db->user->update(\Request::post(), $id);
}
public function post()
{
return $this->db->user->insert([
'name' => \Request::post('name'),
'email' => \Request::post('email'),
'mobile' => \Request::post('mobile')
]);
}
public function delete($id)
{
return $this->db->user->delete($id);
}
public function getName($id)
{
return $this->db->user->select('name')->get($id);
}
public function getNames(...$ids)
{
return $this->db->user->select('name')->where('id', 'IN', $ids)->find();
}
// standard模式下的的route dispatch可以调用protected方法
protected function getEmail($id)
{
return $this->db->user->select('email')->get($id);
}
}
?><file_sep><?php
namespace framework\driver\logger\formatter;
use framework\util\Str;
use framework\core\http\Request;
class Formatter
{
// 格式
protected $format = '[{date}] [{level}] {message} on {file} {line}';
// 设置项
protected $options = [
'ip_proxy' => false,
'date_format' => 'Y-m-d H:i:s',
];
// 替换变量
protected $replace;
// 替换方法
protected $replace_methods;
/*
* 初始化
*/
public function __construct($format = null, array $options = null)
{
if ($format) {
$this->format = $format;
}
if ($options) {
$this->options = $options + $this->options;
}
if (preg_match_all('/\{(\@?)(\w+)\}/', $this->format, $matchs)) {
foreach (array_unique($matchs[2]) as $i => $v) {
$m = 'get'.Str::camelCase($v);
if ($matchs[1][$i]) {
$this->replace_methods['{@'.$k.'}'] = $m;
} else {
$this->replace['{'.$v.'}'] = method_exists($this, $m) ? $this->$m() : '';
}
}
}
}
/*
* 格式化处理
*/
public function format($level, $message, $context = null)
{
$replace = ['{level}' => $level, '{message}' => $message] + $this->replace;
if ($context) {
foreach ($context as $k => $v) {
$replace['{'.$k.'}'] = $v;
}
}
if ($this->replace_methods) {
foreach ($this->replace_methods as $k => $v) {
$replace[$k] = $this->$v();
}
}
return strtr($this->format, $replace);
}
/*
* 获取请求进程id
*/
public function getPid()
{
return getmypid();
}
/*
* 获取使用内存大小
*/
public function getMemory()
{
return memory_get_usage();
}
/*
* 获取使用内存大小峰值
*/
public function getMemoryPeak()
{
return memory_get_peak_usage();
}
/*
* 获取uuid
*/
public function getUuid()
{
return uniqid();
}
/*
* 获取当前时间戳
*/
public function getTime()
{
return time();
}
/*
* 获取当前日期
*/
public function getDate()
{
return date($this->options['date_format']);
}
/*
* 获取请求url
*/
public function getUrl()
{
return Request::url();
}
/*
* 获取请求路径
*/
public function gePath()
{
return Request::path();
}
/*
* 获取请求referrer
*/
public function getReferrer()
{
return Request::server('HTTP_REFERRER');
}
/*
* 获取请求方法
*/
public function getMethod()
{
return Request::method();
}
/*
* 获取请求ip
*/
public function getIp()
{
return Request::ip($this->options['ip_proxy']);
}
}
<file_sep><?php
namespace framework\core;
use framework\util\Arr;
class Dispatcher
{
/*
* 路由调度
*/
public static function route($path, $rules, $param_mode, $dynamic_dispatch = false, $method = null)
{
if ($route = (new Router($path, $method))->route($rules)) {
return self::dispatch($route['dispatch'], $route['matches'], $param_mode, $dynamic_dispatch);
}
}
/*
* 获取调度信息
*/
public static function dispatch($dispatch, $params, $param_mode = 0, $dynamic_dispatch = false)
{
$is_dynamic = false;
$dispatch = self::parseDispatch($dispatch, $param_names);
if ($dynamic_dispatch && strpos($dispatch, '$') !== false) {
$dispatch = self::dynamicDispatch($dispatch, $params, $is_dynamic);
}
if ($param_mode && $params && $param_names) {
if ($param_mode === 2) {
$params = self::bindKvParams($param_names, $params);
} else {
$params = self::bindLsParams($param_names, $params);
}
}
return [$dispatch, $params, $is_dynamic, $data['next'] ?? null];
}
/*
* 解析
*/
public static function parseDispatch($dispatch, &$param_names = null)
{
if (($lpos = strpos($dispatch, '(')) && ($rpos = strpos($dispatch, ')'))) {
$param_names = substr($dispatch, $lpos + 1, $rpos - $lpos - 1);
return substr($dispatch, 0, $lpos);
}
return $dispatch;
}
/*
* 获取动态调用
*/
public static function dynamicDispatch($dispatch, &$params, &$is_dynamic)
{
return preg_replace_callback('/\$(\d)/', function ($match) use ($dispatch, &$params, &$is_dynamic) {
$i = $match[1] - 1;
if (isset($params[$i])) {
$is_dynamic = true;
return Arr::pull($params, $i);
}
throw new \Exception("Illegal dynamic Dispatch: $dispatch");
}, $dispatch);
}
/*
* 解析kv参数
*/
protected static function bindKvParams($rules, $params)
{
foreach (explode(',', $rules) as $rule) {
list($k, $v) = explode('=', trim($rule));
$k = trim($k);
$v = trim($v);
if ($v[0] === '$') {
$index = substr($v, 1) - 1;
if (isset($params[$index])) {
$ret[$k] = $params[$index];
} else {
$ret[$k] = null;
}
} else {
$ret[$k] = json_decode($v, true);
}
}
return $ret ?? [];
}
/*
* 解析list参数
*/
protected static function bindLsParams($rules, $params)
{
foreach (explode(',', $rules) as $rule) {
$rule = trim($rule);
if ($rule[0] === '$') {
$index = substr($rule, 1) - 1;
if (isset($params[$index])) {
$ret[] = $params[$index];
} else {
$ret[] = null;
}
} else {
$ret[] = json_decode($rule, true);
}
}
return $ret ?? [];
}
}
<file_sep><?php
define('APP_DEBUG', true);
include '../../../framework/app.php';
framework\App::start('Inline', [
'controller_path' => 'controller/inline',
])->run();<file_sep><?php
namespace framework\exception;
class TemplateException extends \Exception {}
<file_sep><?php
namespace app\auth;
use framework\App;
use framework\core\Auth;
use framework\core\http\Session;
use framework\core\http\Response;
class Session extends Auth
{
private $name = 'user';
public function __construct($config)
{
if (isset($config['name'])) {
$this->name = $config['name'];
}
}
protected function check()
{
return Session::has($this->name);
}
protected function user()
{
return Session::get($this->name);
}
protected function faildo()
{
Response::redirect('/user/login');
}
protected function login($params)
{
return Session::set($this->name, $params);
}
protected function logout()
{
return Session::delete($this->name);
}
}
<file_sep><?php
return [
'local' => [
'driver' => 'local',
// 本地文件目录
'dir' => APP_DIR.'storage/',
],
's3' => [
'driver' => 's3',
'bucket' => 'your_bucket',
'region' => 'us-east-1',
'acckey' => 'your_acckey',
'seckey' => 'your_seckey',
],
'oss' => [
'driver' => 'oss',
'bucket' => 'your_bucket',
'endpoint' => 'http://oss-cn-beijing.aliyuncs.com',
'acckey' => 'your_acckey',
'seckey' => 'your_seckey',
],
'qiniu' => [
'driver' => 'qiniu',
'bucket' => 'your_bucket',
'region' => 'z1',
'domain' => 'your_domain',
'acckey' => 'your_acckey',
'seckey' => 'your_seckey',
],
'ftp' => [
'driver' => 'ftp',
'host' => '127.0.0.1',
//'port' => 21,
'username' => 'username',
'password' => '<PASSWORD>',
],
'sftp' => [
'driver' => 'sftp',
'host' => '127.0.0.1',
//'port' => 22,
//'chroot' => '/home/qiujin',
'username' => 'username',
'password' => '<PASSWORD>',
],
'webdav' => [
'driver' => 'webdav',
'endpoint' => 'https://dav.jianguoyun.com/dav',
'username' => 'username',
'password' => '<PASSWORD>',
],
];
<file_sep><?php
return [
// 视图文件目录
'dir' => APP_DIR.'view/',
// (可选配置)视图主题
//'theme' => '';
/* (可选配置)
* 自定义的错误页面文件路径
* 如未设置,默认使用framework\extend\view\Error类方法
*/
'error' => [
//'404' => '/error/404',
//'500' => '/error/500',
],
// (可选配置)视图魔术方法的页面文件路径与默认参数
'methods' => [
//'success' => ['/method/success', 'message' => '操作成功', 'backto' => '/'],
//'failure' => ['/method/failure', 'message' => '操作失败', 'backto' => '/'],
],
/* (可选配置)
* 启用视图模版
* 此配置只要非null,即使是空数组也会启用模版(使用默认设置)
*/
'template' => [
/* (可选配置)
* 模版文件文件目录
* 如未设置,默认使用视图文件目录
*/
'dir' => APP_DIR.'storage/view/',
// (可选配置)模版文件后缀
'ext' => '.htm', //默认值
]
];
<file_sep><?php
namespace framework\driver\logger;
use framework\core\Event;
use framework\core\http\Request;
use framework\core\http\Response;
/*
* Chrome
* https://github.com/qiu-jin/chromelogger
* Firefox
* https://addons.mozilla.org/en-US/firefox/addon/chromelogger
*/
class WebConsole extends Logger
{
// 版本
const VERSION = '4.0.0';
// 日志等级
protected static $loglevel = [
'emergency' => 'error',
'alert' => 'error',
'critical' => 'error',
'error' => 'error',
'warning' => 'warn',
'notice' => 'warn',
'debug' => 'debug',
'info' => 'info',
'table' => 'table',
'group' => 'group',
'groupEnd' => 'groupEnd',
'groupCollapsed' => 'groupCollapsed'
];
// 是否输出日志
protected $flush;
// 日志数据大小限制(防止过大导致HTTP服务器报错)
protected $message_size_limit = 1024 * 3;
/*
* 构造函数
*/
public function __construct($config)
{
if (isset($config['allow_ip_list']) && !in_array(Request::ip(), $config['allow_ip_list'])) {
return;
}
if (isset($config['check_header_accept']) && $config['check_header_accept'] != Request::server('HTTP_ACCEPT_LOGGER_DATA')) {
return;
}
if (isset($config['message_size_limit'])) {
$this->message_size_limit = $config['message_size_limit'];
}
$this->flush = true;
Event::on('exit', [$this, 'flush']);
}
/*
* 写入
*/
public function write($level, $message, $context = null)
{
if ($this->flush) {
$this->logs[] = [$level, $message, $context];
}
}
/*
* 表格
*/
public function table(array $values, $contex = null)
{
$this->write('table', $values, $contex);
}
/*
* 分组
*/
public function group($value)
{
$this->write('group', $value);
}
/*
* 分组折叠
*/
public function groupCollapsed($value = null, $contex = null)
{
$this->write('groupCollapsed', $value, $contex);
}
/*
* 分组结束
*/
public function groupEnd($value)
{
$this->write('groupEnd', $value);
}
/*
* 输出缓冲
*/
public function flush()
{
if ($this->logs) {
if ($this->flush && !headers_sent()) {
foreach ($this->logs as $log) {
$rows[] = [
null,
$log[1],
isset($log[2]['file']) ? $log[2]['file'].' : '.($log[2]['line'] ?? '') : null,
self::$loglevel[$log[0]] ?? ''
];
}
$format = [
'version' => self::VERSION,
'columns' => ['label', 'log', 'backtrace', 'type'],
'rows' => $rows
];
$data = base64_encode(json_encode($format));
if (($size = strlen($data)) > $this->message_size_limit) {
$format['rows'] = [[
"Message size($size) than message_size_limit($this->message_size_limit)", '', 'warn'
]];
$data = base64_encode(json_encode($format));
}
Response::header('X-ChromeLogger-Data', $data);
}
$this->logs = null;
}
}
}
<file_sep><?php
namespace app\hook;
use framework\core\http\Request;
use framework\core\http\Session;
class VerifyCsrf
{
public static function run()
{
if (Request::isPost()) {
$token = Request::post('csrf_token');
if (!$token || $token !== Session::get('csrf_token')) {
return abort(500, '无效请求,Csrf token 验证失败。');
}
}
}
}
<file_sep><?php
namespace app\hook;
class Bootstrap
{
public static function run()
{
date_default_timezone_set('PRC');
}
}
<file_sep><?php
namespace framework\core;
use framework\App;
use framework\util\Arr;
use framework\exception\Exception;
use framework\exception\ErrorException;
class Error
{
/*
* 等级常量
*/
const ERROR = E_USER_ERROR;
const WARNING = E_USER_WARNING;
const NOTICE = E_USER_NOTICE;
// 错误信息
private static $errors;
// 错误信息类型
private static $error_info_types = [
E_ERROR => [Logger::CRITICAL ,'E_ERROR'],
E_WARNING => [Logger::WARNING ,'E_WARNING'],
E_PARSE => [Logger::ALERT ,'E_PARSE'],
E_NOTICE => [Logger::NOTICE ,'E_NOTICE'],
E_CORE_ERROR => [Logger::CRITICAL ,'E_CORE_ERROR'],
E_CORE_WARNING => [Logger::WARNING ,'E_CORE_WARNING'],
E_COMPILE_ERROR => [Logger::ALERT ,'E_COMPILE_ERROR'],
E_COMPILE_WARNING => [Logger::WARNING ,'E_COMPILE_WARNING'],
E_USER_ERROR => [Logger::ERROR ,'E_USER_ERROR'],
E_USER_WARNING => [Logger::WARNING ,'E_USER_WARNING'],
E_USER_NOTICE => [Logger::NOTICE ,'E_USER_NOTICE'],
E_STRICT => [Logger::NOTICE ,'E_STRICT'],
E_RECOVERABLE_ERROR => [Logger::ERROR ,'E_RECOVERABLE_ERROR'],
E_DEPRECATED => [Logger::NOTICE ,'E_DEPRECATED'],
E_USER_DEPRECATED => [Logger::NOTICE ,'E_USER_DEPRECATED'],
];
/*
* 获取信息
*/
public static function get($all = false)
{
return $all ? self::$errors : Arr::last(self::$errors);
}
/*
* 触发错误
*/
public static function trigger($message, $code = self::ERROR, $limit = 1)
{
$file = $line = $trace = null;
$traces = debug_backtrace(0);
if (isset($traces[$limit])) {
$type = $class = $function = '';
extract($traces[$limit]);
$message = "$class$type$function() $message";
if (\app\env\APP_DEBUG) {
$trace = array_slice($traces, $limit);
}
}
list($level, $prefix) = self::getErrorInfo($code);
if ($code === self::ERROR) {
throw new ErrorException("[$prefix] $message", $code, $file, $line, $trace);
}
self::record('error.user', $level, $code, "User Error: [$prefix] $message", $file, $line, $trace);
}
/*
* set_error_handler 错误处理器
*/
public static function errorHandler($code, $message, $file = null, $line = null)
{
if (error_reporting() & $code) {
list($level, $prefix) = self::getErrorInfo($code);
if (Config::env('STRICT_ERROR_MODE', true)) {
throw new \ErrorException("[$prefix] $message", 0, $code, $file, $line);
}
self::record('error.error', $level, $code, "Error: [$prefix] $message", $file, $line, debug_backtrace(0));
if ($code & (E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR)) {
App::exit(3);
self::respond();
}
}
}
/*
* set_exception_handler 异常处理器
*/
public static function exceptionHandler($e)
{
App::exit($e instanceof \ErrorException ? 3 : 4);
self::record(
'error.exception',
Logger::ERROR,
$e->getCode(),
sprintf('Uncaught %s: %s', get_class($e), $e->getMessage()),
$e->getFile(),
$e->getLine(),
\app\env\APP_DEBUG ? ($e instanceof ErrorException ? $e->getUserTrace() : $e->getTrace()) : null
);
self::respond();
}
/*
* register_shutdown_function 致命错误处理器
*/
public static function fatalHandler()
{
if (($error = error_get_last())
&& ($error['type'] & (E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR))
) {
App::exit(5);
list($level, $prefix) = self::getErrorInfo($error['type']);
$message = "Fatal Error: [$prefix] $error[message]";
self::record('error.fatal', $level, $error['type'], $message, $error['file'], $error['line']);
self::respond();
} else {
App::exit(0);
self::record('error.fatal', Logger::NOTICE, 0, 'Unknown exit', null, null);
}
}
/*
* 记录错误
*/
private static function record($name, $level, $code, $message, $file, $line, $trace = null)
{
$context = compact('code', 'file', 'line', 'trace');
self::$errors[] = compact('level', 'message', 'context');
//Event::trigger('app.error', compact('code', 'file', 'line', 'trace'));
Logger::write($level, $message, $context);
}
/*
* 响应错误
*/
private static function respond()
{
App::abort(500, \app\env\APP_DEBUG ? self::$errors : null);
}
/*
* 获取错误分类信息
*/
private static function getErrorInfo($code)
{
return self::$error_info_types[$code] ?? [Logger::ERROR, 'UNKNOEN_ERROR'];
}
}
<file_sep><?php
namespace framework\core;
class Router
{
private static $init;
// 内置正则规则
private static $patterns = [];
// 路径数组
private $path;
// 路径数组count
private $count;
// HTTP方法
private $method;
/*
* 初始化
*/
public static function __init()
{
if (self::$init) {
return;
}
self::$init = true;
if ($config = Config::get('router')) {
if (isset($config['patterns'])) {
self::$patterns = $config['patterns'];
}
}
}
/*
* 设置内置正则规则
*/
public static function pattern($name, $value = null)
{
if (isset($value)) {
self::$patterns[$name] = $value;
} else {
self::$patterns = $name + self::$patterns;
}
}
/*
* 构造函数
*/
public function __construct(array $path, $method = null)
{
$this->path = $path;
$this->count = count($path);
$this->method = $method;
}
/*
* 路由匹配
*/
public function route($rules, $step = 0)
{
if (!$rules) {
return false;
}
// 数组树尾梢为dispatch数据
if (!is_array($rules)) {
if ($this->count != $step) {
return false;
}
return ['dispatch' => $rules];
}
foreach ($rules as $k => $v) {
if (($matches = self::match($k, $step)) !== false
// 递归处理
&& ($route = self::route($v, $matches[1]))
) {
if (empty($route['matches'])) {
$route['matches'] = $matches[0];
} elseif ($matches[0]) {
$route['matches'] = array_merge($matches[0], $route['matches']);
}
if (isset($matches[2])) {
$route['next'] = $matches[2];
}
return $route;
}
}
return false;
}
/*
* 匹配单元
*/
public function match($rule, $step)
{
$ret = [];
// 方法匹配
if ($rule[0] == ':') {
$arr = explode(' ', substr($rule, 1), 2);
$method = strtoupper(trim($arr[0]));
if (strpos($method, '|') === false) {
if ($method != $this->method) {
return false;
}
} elseif (!in_array($this->method, explode('|', $method))) {
return false;
}
if (isset($arr[1])) {
$rule = trim($arr[1]);
} else {
return [$ret, $step];
}
}
// 空匹配
if ($rule == '/') {
return $step == $this->count ? [$ret, $step] : false;
}
foreach (explode('/', $rule) as $v) {
$c = $v[0];
if (isset($this->path[$step])) {
$s = $this->path[$step];
// 可选匹配
if ($c == '?') {
$v = substr($v, 1);
$c = $v[0];
}
} else{
if ($c == '?') {
return [$ret, $step];
} elseif ($c == '~') {
return [$ret, $step, []];
} elseif ($c != ':') {
return false;
}
}
switch ($c) {
// 通配
case '*':
if ($v == '*') {
$ret[] = $s;
break;
}
return false;
// 用户正则匹配
case '(':
if (substr($v, -1) == ')'
&& ($n = substr($v, 1, -1))
&& preg_match("/^$n$/", $s, $m)
) {
if (isset($m[1])) {
$ret = array_merge($ret, array_slice($m, 1));
} else {
$ret[] = $s;
}
break;
}
return false;
// 内置正则匹配
case '[':
if (substr($v, -1) == ']'
&& ($n = substr($v, 1, -1))
&& isset(self::$patterns[$n])
&& preg_match('/^'.self::$patterns[$n].'$/', $s, $m)
) {
if (isset($m[1])) {
$ret = array_merge($ret, array_slice($m, 1));
} else {
$ret[] = $s;
}
break;
}
return false;
// 验证器匹配
case '{':
if (substr($v, -1) == '}'
&& ($n = substr($v, 1, -1))
&& Validator::{$n}($s)
) {
$ret[] = $s;
break;
}
return false;
// 余部匹配
case '~':
if ($v === '~') {
return [$ret, $this->count, array_slice($this->path, $step)];
}
return false;
// 原义匹配
case '!':
if ($s == substr($v, 1)) {
break;
}
return false;
// 默认匹配
default:
if ($s == $v) {
break;
}
return false;
}
$step++;
}
return [$ret, $step];
}
}
Router::__init();
<file_sep><?php
namespace framework\driver\cache;
use framework\core\Event;
abstract class Cache
{
// 默认缓存过期时间,0表示永不过期,数组取区间随机值
protected $ttl = 0;
/*
* 获取
*/
abstract public function get($key, $default);
/*
* 检查
*/
abstract public function has($key);
/*
* 设置
*/
abstract public function set($key, $value, $ttl);
/*
* 删除
*/
abstract public function delete($key);
/*
* 自增
*/
abstract public function increment($key, $value);
/*
* 自减
*/
abstract public function decrement($key, $value);
/*
* 清理
*/
abstract public function clear();
/*
* 构造函数
*/
public function __construct($config)
{
if (isset($config['ttl'])) {
$this->ttl = $config['ttl'];
}
}
/*
* 获取并删除
*/
public function pull($key)
{
$value = $this->get($key);
$this->delete($key);
return $value;
}
/*
* 不存在则设置
*/
public function remember($key, $value, $ttl = null)
{
if (!$this->has($key)) {
$this->set($key, $value, $ttl);
}
return $value;
}
/*
* 获取多个
*/
public function getMultiple(array $keys, $default = null)
{
foreach ($keys as $key) {
$values[$key] = $this->get($key, $default);
}
return $values;
}
/*
* 设置多个
*/
public function setMultiple(array $values, $ttl = null)
{
foreach ($values as $key => $value) {
if (!$this->set($key, $value, $ttl)) {
return false;
}
}
return true;
}
/*
* 删除多个
*/
public function deleteMultiple(array $keys)
{
foreach ($keys as $key) {
if (!$this->delete($key)) {
return false;
}
}
return true;
}
/*
* 获取缓存有效时间
*/
protected function ttl($ttl)
{
return is_array($t = $ttl ?? $this->ttl) ? mt_rand($t[0], $t[1]) : $t;
}
}
<file_sep><?php
return [
'alidayu' => [
'driver' => 'alidayu',
'acckey' => 'your_acckey',
'seckey' => 'your_seckey',
'signname' => '大鱼测试',
'template' => [
'register' => 'service_template_id'
],
],
'aliyun' => [
'driver' => 'aliyun',
'acckey' => 'your_acckey',
'seckey' => 'your_seckey',
'signname' => '短信测试',
'template' => [
'register' => 'service_template_id'
],
],
'baidu' => [
'driver' => 'baidu',
'acckey' => 'your_acckey',
'seckey' => 'your_seckey',
'template' => [
'register' => 'service_template_id'
],
//(可选配置)服务域名
'host' => 'sms.bj.baidubce.com', //默认
//(可选配置)签名有效期(秒)
'expiration'=> 180 //默认
],
'qcloud' => [
'driver' => 'qcloud',
'acckey' => 'your_acckey',
'seckey' => 'your_seckey',
'signname' => '短信测试',
'template' => [
'register' => '验证码:{code},您正在进行身份验证,此短信验证码{time}分钟内有效,请勿转发他人。'
],
],
'yuntongxun' => [
'driver' => 'yuntongxun',
'appkey' => 'your_appkey',
'acckey' => 'your_acckey',
'seckey' => 'your_seckey',
'template' => [
'register' => 'service_template_id'
],
],
];
<file_sep><?php
namespace framework\driver\logger;
use framework\core\Event;
use framework\driver\logger\formatter\Formatter;
class File extends Logger
{
// 日志文件
protected $logfile;
// 日志格式化处理器
protected $formatter;
// 是否实时写入日志
protected $realtime_write;
/*
* 构造函数
*/
public function __construct($config)
{
$this->logfile = $config['logfile'];
if (empty($config['realtime_write'])) {
Event::on('app.exit', [$this, 'flush']);
} else {
$this->realtime_write = true;
}
if (isset($config['formatter'])) {
$f = $config['formatter'];
$class = $f['class'] ?? Formatter::class;
$this->formatter = new $class($f['format'] ?? null, $f['options'] ?? null);
}
}
/*
* 写入
*/
public function write($level, $message, $context = null)
{
if ($this->realtime_write) {
$this->realWrite($level, $message, $context);
} else {
$this->logs[] = [$level, $message, $context];
}
}
/*
* 输出缓冲
*/
public function flush()
{
if ($this->logs) {
foreach ($this->logs as $log) {
$this->realWrite(...$log);
}
$this->logs = null;
}
}
/*
* 实时写入
*/
protected function realWrite($level, $message, $context)
{
$log = $this->formatter ? $this->formatter->format($level, $message, $context) : $message;
error_log($log.PHP_EOL, 3, $this->logfile);
}
}
<file_sep><?php
// 参考 https://cloud.google.com/apis/design
namespace framework\core\app;
use framework\App;
use framework\util\Str;
use framework\core\Config;
use framework\core\Dispatcher;
use framework\core\http\Status;
use framework\core\http\Request;
use framework\core\http\Response;
class Resource extends App
{
protected $config = [
// 控制器namespace
'controller_ns' => 'controller',
// 控制器类名后缀
'controller_suffix' => null,
// 路由调度的路由表,如果值为字符串则作为配置名引入
'resource_dispatch_routes' => null,
// 标准方法路由规则
'default_standard_methods' => [
':GET' => 'list',
':POST' => 'create',
':GET *' => 'get',
':POST *' => 'update',
':DELETE *' => 'delete',
],
// 自定义方法前缀符
'default_custom_method_prefix' => ':',
// 设置动作调度路由属性名,为null则不启用动作路由
'dispatch_method_routes_property' => 'routes',
];
/*
* 调度
*/
protected function dispatch()
{
$path = App::getPathArr();
$http_method = Request::method();
$routes = $this->config['route_dispatch_routes'];
if (is_string($routes)) {
$routes = Config::read($routes);
}
if ($routes) {
$result = (new Router(App::getPathArr(), $http_method))->route($routes);
if ($result) {
$call = $result['dispatch'];
if (is_string($call)) {
if (!isset($result['next'])) {
$call = explode($this->config['class_method_separator'], $call, 2);
if (isset($call[1])) {
$instance = $this->instanceClass($call[0]);
if ($instance && is_callable([$instance, $call[1]])) {
return ['call' => [$instance, $call[1]], 'params' => $result['matches']];
}
}
} else {
$instance = $this->instanceClass($call);
$method_routes = $this->config['default_standard_methods'];
if ($this->config['action_dispatch_routes_property']) {
$property = $this->config['action_dispatch_routes_property'];
if (isset($instance->$property)) {
$method_routes = array_merge($action_routes, $instance->$property);
}
}
if ($action_routes) {
$action_result = (new Router($result['next'], $http_method))->route($action_routes);
if ($action_result) {
}
}
if ($this->config['default_custom_method_prefix']) {
$custom_method = explode($this->config['default_custom_method_prefix'], $route_dispatch[3]);
if (!isset($custom_method[1])) {
return $this->bindBispatchParams($call[0], $instance, $custom_method);
} elseif (!isset($custom_method[1])) {
return $this->bindBispatchParams($call[0], $instance, $custom_method[0], $custom_method[1]);
}
}
}
}
}
}
}
/*
* 调用
*/
protected function call()
{
return ($this->dispatch['instance'])->{$this->dispatch['action']}(...$this->dispatch['params']);
}
/*
* 错误
*/
protected function error($code = null, $message = null)
{
Response::code($code ?? 500);
Response::json(['error' => compact('code', 'message')]);
}
/*
* 响应
*/
protected function respond($return = null)
{
Response::json($return);
}
/*
* 检查方法参数数
*/
protected function checkMethodParamsNumber($reflection, $number)
{
return $number >= $reflection->getNumberOfRequiredParameters() && $number <= $reflection->getNumberOfParameters();
}
}
<file_sep><?php
namespace framework\driver\cache;
use framework\util\Str;
use framework\util\File as UFile;
class File extends Cache
{
// 缓存文件目录
protected $dir;
// 缓存文件扩展名
protected $ext = '.cache.txt';
// 序列化反序列化处理器
protected $serializer = ['serialize', 'unserialize'];
// 使用真实文件名
protected $use_real_name = false;
/*
* 初始化
*/
public function __construct($config)
{
parent::__construct($config);
if (isset($config['ext'])) {
$this->ext = $config['ext'];
}
if (isset($config['serializer'])) {
$this->serializer = $config['serializer'];
}
$this->dir = Str::lastPad($config['dir'], '/');
$this->use_real_name = !empty($config['use_real_name']);
}
/*
* 获取
*/
public function get($key, $default = null)
{
if (is_file($file = $this->filename($key)) && ($fp = fopen($file, 'r'))) {
$expiration = (int) trim(fgets($fp));
if($expiration === '0' || $expiration > time()){
$data = stream_get_contents($fp);
fclose($fp);
return ($this->serializer[1])($data);
} else {
fclose($fp);
}
}
return $default;
}
/*
* 检查
*/
public function has($key)
{
if (is_file($file = $this->filename($key)) && ($fp = fopen($file, 'r'))) {
$expiration = (int) trim(fgets($fp));
fclose($fp);
return $expiration === '0' || $expiration > time();
}
return false;
}
/*
* 设置
*/
public function set($key, $value, $ttl = null)
{
$expiration = ($t = $this->ttl($ttl)) == 0 ? 0 : $t + time();
return (bool) file_put_contents($this->filename($key), $expiration.PHP_EOL.($this->serializer[0])($value), LOCK_EX);
}
/*
* 删除
*/
public function delete($key)
{
return is_file($file = $this->filename($key)) && unlink($file);
}
/*
* 自增
*/
public function increment($key, $value = 1)
{
return $this->set($key, $this->get($key, 0) + $value);
}
/*
* 自减
*/
public function decrement($key, $value = 1)
{
return $this->set($key, $this->get($key, 0) - $value);
}
/*
* 清理
*/
public function clear(callable $fitler = null)
{
$len = strlen($this->ext);
UFile::clearDir($this->dir, function ($file) use ($len) {
return substr($file, - $len) === $this->ext;
});
}
/*
* 垃圾回收
*/
public function gc()
{
$len = strlen($this->ext);
$time = time();
UFile::clearDir($this->dir, function ($file) use ($len, $time) {
if (substr($file, - $len) === $this->ext) {
$fp = fopen($file, 'r');
$expiration = (int) trim(fgets($fp));
fclose($fp);
return $expiration <= $time && $expiration !== 0;
}
});
}
/*
* 获取文件名
*/
protected function filename($key)
{
return $this->dir.($this->use_real_name ? $key : md5($key)).$this->ext;
}
}
<file_sep><?php
namespace framework\core;
use framework\util\Arr;
use framework\core\http\Request;
use framework\exception\TemplateException;
class Template
{
protected static $init;
// 配置
protected static $config = [
// 空标签
'void_tag' => 'void',
// 原生标签
'raw_tag' => 'raw',
// php标签
'php_tag' => 'php',
// 注释标签
'note_tag' => 'note',
// heredoc标签
'heredoc_tag' => 'heredoc',
// 插槽标签
'slot_tag' => 'slot',
// 块标签
'block_tag' => 'block',
// 父标签
'parent_tag' => 'parent',
// 插入标签
'insert_tag' => 'insert',
// 引用标签
'include_tag' => 'include',
// 继承标签
'extends_tag' => 'extends',
// 结构语句前缀符
'struct_attr_prefix' => '@',
// 赋值语句前缀符
'assign_attr_prefix' => '$',
// 双引号语句前缀符
'double_attr_prefix' => '*',
// 参数语句前缀符
'argument_attr_prefix' => ':',
// 文本插入左右边界符号
'text_delimiter_sign' => ['{{', '}}'],
// 文本插入是否自动转义
'auto_escape_text' => true,
// 文本转义符号与反转义符号
'text_escape_sign' => [':', '!'],
// 不输出标识符
'not_echo_text_sign' => '#',
// 是否去除原生HTML注释
'remove_html_note' => false,
// 允许的函数
'allow_php_functions' => false,
// 允许的静态类
'allow_static_classes' => false,
// 允许的容器
'allow_container_providers' => false,
// filter宏
'view_filter_macro' => __CLASS__.'::filterMacro',
// include宏
'view_include_macro' => __CLASS__.'::includeMacro',
// container宏
'view_container_macro' => __CLASS__.'::ContainerMacro',
// check expired宏
'view_check_expired_macro' => __CLASS__.'::checkExpiredMacro',
// 模版读取器
'view_template_reader' => View::class.'::readTemplate',
];
// 魔术变量
protected static $vars = [
'input' => Request::class.'::input',
'query' => Request::class.'::query',
'param' => Request::class.'::param',
'cookie' => Request::class.'::cookie',
'header' => Request::class.'::header',
'server' => Request::class.'::server',
'session' => Request::class.'::session',
];
// 内置函数
protected static $filters = [
// 是否存在
'isset' => 'isset($0)',
// 是否为空
'empty' => 'empty($0)',
// 默认值
'default' => '($0 ?? $1)',
// 转为字符串
'str' => 'strval($0)',
// 字符串拼接
'cat' => '($0.$1)',
// 字符串拼接
'format' => 'sprintf($0, $1, ...)',
// 字符串补全填充
'pad' => 'str_pad($0, $1, ...)',
// 字符串替换
'replace' => 'str_replace($1, $2, $0)',
// 字符串中字符位置
'index' => 'strpos($1, $0)',
// 字符串截取
'substr' => 'substr($0, $1, $2)',
// 字符串截取
'slice' => 'substr($0, $1, $2 > 0 ? $2 - $1 : $2)',
// 字符串重复
'repeat' => 'str_repeat($0, $1)',
// 字符串长度
'length' => 'strlen($0)',
// 字符串大写
'lower' => 'strtolower($0)',
// 字符串小写
'upper' => 'strtoupper($0)',
// 字符串首字母大写
'ucfirst' => 'ucfirst($0)',
// 每个单词的首字母大写
'capitalize' => 'ucwords($0)',
// 字符串剔除两端空白
'trim' => 'trim($0, ...)',
// 文本换行符转换成HTML换行符
'nl2br' => 'nl2br($0)',
// 字符串md5值
'md5' => 'md5($0)',
// 字符串hash值
'hash' => 'hash($1, $0)',
// 正则匹配
'match' => 'preg_match($1, $0, ...)',
// 字符串HTML转义
'escape' => 'htmlentities($0)',
// 字符串HTML反转义
'unescape' => 'html_entity_decode($0)',
// 字符串URL转义
'urlencode' => 'urlencode($0)',
// 字符串URL反转义
'urldecode' => 'urldecode($0)',
// 数组转为JSON
'jsonencode' => 'json_encode($0, JSON_UNESCAPED_UNICODE)',
// JSON转为数组
'jsondenode' => 'json_denode($0, true)',
// 元素是否存在于数组作用
'in' => 'in_array($0, $1, true)',
// 数组长度
'count' => 'count($0)',
// 创建范围数组
'range' => 'range($0, $1)',
// 字符串分割为数组
'split' => 'explode($1, $0)',
// 数组连接成字符串
'join' => 'implode($1, $0)',
// 获取数组keys
'keys' => 'array_keys($0)',
// 获取数组values
'values' => 'array_values($0)',
// 合并数组
'merge' => 'array_merge($0, $1)',
// 最大值
'max' => 'max($0, ...)',
// 最小值
'min' => 'min($0, ...)',
// 转为数字
'num' => '($0+0)',
// 数字绝对值
'abs' => 'abs($0)',
// 数字向上取整
'ceil' => 'ceil($0)',
// 数字向下取整
'floor' => 'floor($0)',
// 数字四舍五入
'round' => 'round($0, ...)',
// 数字随机值
'rand' => 'rand($0, $1)',
// 数字格式化
'number_format' => 'number_format($0)',
// 时间戳
'time' => 'time()',
// 转为时间戳
'to_time' => 'strtotime($0)',
// 时间格式化
'date' => 'date($0, $1)',
// 视图文件是否存在
'view_exists' => View::class.'::exists($0)',
];
/*
* 初始化
*/
public static function __init()
{
if (self::$init) {
return;
}
self::$init = true;
if ($config = Config::get('template')) {
if ($vars = Arr::pull($config, 'vars')) {
self::$vars = $vars + self::$vars;
}
if ($filters = Arr::pull($config, 'filters')) {
self::$filters = $filters + self::$filters;
}
self::$config = $config + self::$config;
}
}
/*
* 编译模版
*/
public static function complie($str, $is_tpl = false)
{
if ($is_tpl) {
$str = self::$config['view_template_reader']($str);
}
$ret = '';
$str = self::removeNote($str);
$str = self::readInsertAndExtends($str, $ck);
self::checkPHPSyntax($str);
// 检查模版更新
if ($ck) {
$ret = self::wrapCode(self::$config['view_check_expired_macro'](array_unique($ck))).PHP_EOL;
}
return $ret.self::readRawNextPHPCode($str);
}
/*
* 检查PHP语法
*/
protected static function checkPHPSyntax($str)
{
$tokens = token_get_all($str);
if (count($tokens) != 1 || $tokens[0][0] != T_INLINE_HTML) {
throw new TemplateException('禁用PHP原生语法');
}
}
/*
* 解析去除模版注释
*/
protected static function removeNote($str)
{
// 去除原生注释
if (self::$config['remove_html_note']) {
$str = preg_replace('/\<\!--[\w\W]*?--\>/', '', $str);
}
// 去除模版注释
$ret = '';
if ($res = self::parseTagWithText($str, self::$config['note_tag'], null, false, true)) {
$pos = 0;
foreach ($res as $v) {
$ret .= substr($str, $pos, $v['pos'][0] - $pos);
$pos = $v['pos'][1];
}
$str = substr($str, $pos);
}
return $ret.$str;
}
/*
* 读取解析extends标签
*/
protected static function readInsertAndExtends($str, &$ck = [])
{
$i = 0;
$blocks = [];
while (true) {
if ($i > 9) {
throw new TemplateException('Extends嵌套不能大于9层,防止死循环');
}
$str = self::readInsert($str, $ck);
if (!preg_match_all(self::tagRegex(self::$config['extends_tag']), $str, $matches, PREG_OFFSET_CAPTURE)) {
break;
}
if (count($matches[0]) > 1) {
throw new TemplateException('extends语句不允许有多条');
}
$str = substr($str, 0, $matches[0][0][1]).substr($str, strlen($matches[0][0][0]));
$name = self::parseSelfEndTagAttrs($matches[0][0][0], 'name');
$ck[] = $name;
// 读取子模版block
if ($res = self::parseTagWithText($str, self::$config['block_tag'], 'name')) {
$blocks += array_column($res, 'text', 'attr');
}
$str = self::removeNote(self::$config['view_template_reader']($name));
$i++;
}
if ($i == 0) {
return $str;
}
// 替换父模版block
if ($res = self::parseTagWithText($str, self::$config['block_tag'], 'name', null)) {
$pos = 0;
$ret = '';
foreach ($res as $v) {
$ret .= substr($str, $pos, $v['pos'][0] - $pos);
$pos = $v['pos'][1];
if (isset($blocks[$v['attr']]) || !isset($v['text'])) {
$ret .= preg_replace_callback("/<".self::$config['parent_tag']."\s*\/>/", function () use ($v) {
return $v['text'];
}, $blocks[$v['attr']]);
} else {
$ret .= $v['text'];
}
}
return $ret.substr($str, $pos);
}
return $str;
}
/*
* 读取解析insert标签
*/
protected static function readInsert($str, &$ck)
{
$i = 0;
while (true) {
if ($i > 9) {
throw new TemplateException('Insert嵌套不能大于9层,防止死循环');
}
if (!$res = self::parseTagWithText($str, self::$config['insert_tag'], 'name', null)) {
break;
}
$pos = 0;
$ret = '';
foreach ($res as $v) {
$ret .= substr($str, $pos, $v['pos'][0] - $pos);
$name = $v['attr'];
if (strpos($name, '.')) {
list($name, $block) = explode('.', $name, 2);
}
$ck[] = $name;
$content = $contents[$name] ??
$contents[$name] = self::removeNote(self::$config['view_template_reader']($name));
if (isset($block)) {
if (!isset($block_contents[$name])) {
$result = self::parseTagWithText($content, self::$config['block_tag'], 'name');
$blocks[$name] = array_column($result, 'text', 'attr');
}
if (!isset($blocks[$name][$block])) {
throw new TemplateException("$name.$block block 不存在");
}
$content = $blocks[$name][$block];
}
$slots = null;
if ($v['text'] && ($sres = self::parseTagWithText($v['text'], self::$config['slot_tag'], 'name'))) {
$spos = 0;
$sret = '';
foreach ($sres as $sv) {
$sret .= substr($content, $spos, $sv['pos'][0] - $spos);
$spos = $sv['pos'][1];
}
$v['text'] = $sret.substr($v['text'], $spos);
$slots = array_column($sres, 'text', 'attr');
}
if ($sres = self::parseTagWithText($content, self::$config['slot_tag'], null, null)) {
$spos = 0;
$sret = '';
foreach ($sres as $sv) {
$sret .= substr($content, $spos, $sv['pos'][0] - $spos);
$spos = $sv['pos'][1];
if (isset($sv['attr']['name'])) {
$sret .= $slots[$sv['attr']['name']] ?? $sv['text'];
} else {
$sret .= $v['text'] ?? $sv['text'];
}
}
$ret .= $sret.substr($content, $spos);
} else {
$ret .= $content;
}
$pos = $v['pos'][1];
}
$str = $ret.substr($str, $pos);
$i++;
}
return $str;
}
/*
* 读取解析原生语句
*/
protected static function readRawNextPHPCode($str)
{
$ret = '';
$end = [];
if ($res = self::parseTagWithText($str, self::$config['raw_tag'], null, false, true)) {
$pos = 0;
foreach ($res as $v) {
$ret .= self::readPHPCodeNextHeredoc(substr($str, $pos, $v['pos'][0] - $pos), $end);
$ret .= $v['text'];
$pos = $v['pos'][1];
}
$str = substr($str, $pos);
}
if ($str) {
$ret .= self::readPHPCodeNextHeredoc($str, $end);
}
if (!$end) {
return $ret;
}
throw new TemplateException('结构语句标签未闭合');
}
/*
* 读取解析php代码
*/
protected static function readPHPCodeNextHeredoc($str, &$end)
{
if (!self::$config['php_tag']) {
return self::readHeredocNextStruct($str, $end);
}
$ret = '';
if ($res = self::parseTagWithText($str, self::$config['php_tag'])) {
$pos = 0;
foreach ($res as $v) {
$ret .= self::readHeredocNextStruct(substr($str, $pos, $v['pos'][0] - $pos), $end);
$ret .= self::wrapCode(PHP_EOL.$v['text'].PHP_EOL);
$pos = $v['pos'][1];
}
$str = substr($str, $pos);
}
if ($str) {
$ret.= self::readHeredocNextStruct($str, $end);
}
return $ret;
}
/*
* 读取解析heredoc
*/
protected static function readHeredocNextStruct($str, &$end)
{
if (!self::$config['heredoc_tag']) {
return self::readStructAndText($str, $end);
}
$ret = '';
if ($res = self::parseTagWithText($str, self::$config['heredoc_tag'])) {
$pos = 0;
foreach ($res as $v) {
$eot = $v['attr']['name'] ?? 'EOT';
$ret .= self::readStructAndText(substr($str, $pos, $v['pos'][0] - $pos), $end);
$ret .= self::wrapCode("print <<<$eot".PHP_EOL.$v['text'].PHP_EOL."$eot;");
$pos = $v['pos'][1];
}
$str = substr($str, $pos);
}
if ($str) {
$ret.= self::readStructAndText($str, $end);
}
return $ret;
}
/*
* 读取解析插值语句
*/
protected static function readStructAndText($str, &$end)
{
$l = preg_quote(self::$config['text_delimiter_sign'][0]);
$r = preg_quote(self::$config['text_delimiter_sign'][1]);
return preg_replace_callback("/$l(.*?)$r/", function ($matches) use ($str) {
$val = $matches[1];
if ($val[0] == self::$config['not_echo_text_sign']) {
// 不输出
return self::wrapCode(self::readValue(substr($val, 1)).';');
} else {
// 是否转义
$escape = self::$config['auto_escape_text'];
if (in_array($val[0], self::$config['text_escape_sign'])) {
$escape = !array_search($val[0], self::$config['text_escape_sign']);
$val = substr($val, 1);
}
$code = self::readValue($val);
return self::wrapCode($escape ? "echo htmlspecialchars($code);" : "echo $code;");
}
}, self::readInclude(self::readStructTag($str, $end)));
}
/*
* 读取解析include标签
*/
protected static function readInclude($str)
{
return preg_replace_callback(self::tagRegex(self::$config['include_tag']), function ($matches) {
$name = self::$config['argument_attr_prefix'].'name';
$attrs = self::parseSelfEndTagAttrs($matches[0]);
if (isset($attrs['name'])) {
$arg = $attrs['name'];
} elseif(isset($attrs[$name])) {
$arg = self::readValue($attrs[$name]);
} else {
throw new TemplateException("标签值为空 $str");
}
return self::wrapCode(self::$config['view_include_macro']($arg, !isset($attrs['name'])));
}, $str);
}
/*
* 读取解析控制结构语句标签
*/
protected static function readStructTag($str, &$end)
{
$v = "\"[^\"]*\"|'[^']*'";
$regex = "/<([\w-]+)\s+[".self::attrPrefixRegex()."][\w-]+(\s*=\s*($v))?($v|[^'\">])*>/";
if (!preg_match_all($regex, $str, $matches, PREG_OFFSET_CAPTURE)) {
return $str;
}
$pos = 0;
$ret = '';
foreach ($matches[0] as $i => $match) {
if ($pos > $match[1]) {
throw new TemplateException("文本读取偏移地址错误");
}
// 读取左侧HTML
$left = substr($str, $pos, $match[1] - $pos);
// 读取空白内容
$blank = self::readLeftBlank($left);
// 拼接左侧内容,如有为闭合语句,尝试闭合处理。
$ret .= $end ? self::completeStructTag($left, $end) : $left;
// 读取解析标签内代码
$attrs = self::readTagStructAttr($match[0]);
if ($attrs['code']) {
// 处理if与elseif else的衔接
if ($attrs['is_else']) {
if (preg_match('/\?>\s*$/', $ret, $res)) {
$ret = substr($ret, 0, -strlen($res[0])).substr(implode(PHP_EOL.$blank, $attrs['code']), 6);
} else {
throw new TemplateException('衔接if else失败');
}
} else {
$ret .= implode(PHP_EOL.$blank, $attrs['code']);
}
}
// 补全空白内容
$ret .= PHP_EOL.$blank;
if ($matches[1][$i][0] != self::$config['void_tag']) {
$ret .= $attrs['html'];
}
// 如果是自闭合标签则自行添加PHP闭合,否则增加未闭合标签语句数据供下步处理。
if ($attrs['count'] > 0) {
if (substr($attrs['html'], -2) === '/>') {
$ret .= str_repeat(PHP_EOL.$blank.self::wrapCode('}'), $attrs['count']);
} else {
$end[] = [
'num' => 0, // HTML闭合标签层数
'tag' => $matches[1][$i][0], // HTML标签名
'count' => $attrs['count'], // 补全的PHP闭合标签数
];
}
}
// 重设文本处理位置
$pos = strlen($match[0]) + $match[1];
}
// 处理最后剩余部分
if ($tmp = substr($str, $pos)) {
$ret.= $end ? self::completeStructTag($tmp, $end) : $tmp;
}
return $ret;
}
/*
* 合并完成模版标签闭合
*/
protected static function completeStructTag($str, &$end, $blank = null)
{
$ret = '';
do {
$i = count($end) - 1;
$tag = $end[$i]['tag'];
if (!preg_match_all("/(<$tag|<\/$tag>)/", $str, $matches, PREG_OFFSET_CAPTURE)) {
// 无匹配则直接返回
return $ret.$str;
}
$pos = 0;
foreach ($matches[0] as $match) {
$tmp = substr($str, $pos, $match[1] - $pos);
$ret .= $tmp;
// 重设读取位置
$pos = strlen($match[0]) + $match[1];
// 新开始标签则计数加一
if ($match[0][1] !== '/') {
$ret .= $match[0];
$end[$i]['num']++;
} else {
// 非最后结束标签则计数减一
if ($end[$i]['num'] > 0) {
$ret .= $match[0];
$end[$i]['num']--;
// 最后结束标签则处理标签闭合
} else {
if ($tag !== self::$config['void_tag']) {
$ret .= $match[0];
}
$left = $blank ?? self::readLeftBlank($tmp);
$ret .= str_repeat(PHP_EOL.$left.self::wrapCode('}'), $end[$i]['count']);
// 处理完成,退出当前,继续下一环。
array_pop($end);
break;
}
}
}
$str = substr($str, $pos);
} while ($i > 0);
return $ret.$str;
}
/*
* 读取解析流程控制语句
*/
protected static function readTagStructAttr($str)
{
// 标签HTML代码
$html = '';
// 标签PHP代码
$code = [];
// 标签内结构语句条数
$count = 0;
$is_else = false;
$regex = "/\s*([".self::attrPrefixRegex()."])([\w-]+)(?:\s*=\s*(\"[^\"]*\"|'[^']*'))?/";
if (preg_match_all($regex, $str, $matches, PREG_OFFSET_CAPTURE)) {
$pos = 0;
foreach ($matches[1] as $i => $match) {
$html .= substr($str, $pos, $matches[0][$i][1] - $pos);
$pref = $matches[1][$i][0];
$name = $matches[2][$i][0];
if ($matches[3][$i]) {
$val = substr($matches[3][$i][0], 1, -1);
} else {
if ($name != 'else' && $pref == self::$config['struct_attr_prefix']) {
throw new TemplateException("标签属性值不能为空");
}
}
//
if ($pref == self::$config['double_attr_prefix']) {
$q = $matches[3][$i][0][0];
$e = self::$config['auto_escape_text'];
$html .= " $name =$q".self::wrapCode($e ? "echo htmlspecialchars(\"$val\");" : "echo \"$val\";").$q;
// 赋值语句
} elseif ($pref == self::$config['assign_attr_prefix']) {
$code[] = self::wrapCode("$$name = ".self::readValue($val).';');
// 流程控制语句
} elseif ($pref == self::$config['struct_attr_prefix']) {
$count++;
if ($name == 'else' || $name == 'elseif') {
$is_else = true;
if ($code) {
throw new TemplateException("单个标签内else或elseif前不允许有其它语句");
}
}
$code[] = self::wrapCode(self::readControlStruct($name, $val ?? null));
} else {
$html .= $matches[0][$i][0];
}
$pos = $matches[0][$i][1] + strlen($matches[0][$i][0]);
}
$html .= substr($str, $pos);
} else {
$html = $str;
}
return compact('html', 'code', 'count', 'is_else');
}
/*
* 读取语句结构
*/
protected static function readControlStruct($name, $val)
{
switch ($name) {
case 'if':
return 'if ('.self::readValue($val).') {';
case 'elseif':
return 'elseif ('.self::readValue($val).') {';
case 'else':
return 'else {';
case 'each':
$arr = explode(' in ', $val, 2);
if (isset($arr[1])) {
$kv = explode(':', trim($arr[0]), 2);
$val = $arr[1];
if (count($kv) == 1) {
$as = '$'.$kv[0];
} else {
if (empty($kv[0])) {
if (self::isVarChars($kv[1])) {
$as = '$'.$kv[1];
}
} elseif (empty($kv[1])) {
if (self::isVarChars($kv[0])) {
$as = '$'.$kv[0].' => $__';
}
} else {
if (self::isVarChars($kv[0]) && self::isVarChars($kv[1])) {
$as = '$'.$kv[0].' => $'.$kv[1];
}
}
}
if (!isset($as)) {
break;
}
} else {
$as = '$key => $val';
}
return 'foreach('.self::readValue($val)." as $as) {";
case 'for':
if (count($arr = explode(';', $attr['code'], 2)) == 2) {
foreach($arr as $v) {
$ret[] = self::readValue($v, $attr['vars']);
}
return 'for ('.implode(';', $ret).') {';
}
break;
case 'while':
return 'while ('.self::readValue($val).') {';
}
throw new TemplateException("非法语句 $name ($val)");
}
/*
* 解析标签属性
*/
protected static function parseSelfEndTagAttrs($str, $name = true, $self_end = true)
{
if ($self_end === true && substr($str, -2) != '/>') {
throw new TemplateException("必须自闭合标签 $str");
}
if ($self_end === false && substr($str, -2) == '/>') {
throw new TemplateException("必须非自闭合标签 $str");
}
$prefix = preg_quote(self::$config['argument_attr_prefix']);
if (preg_match_all('/([\w\-'.$prefix.']+)\s*=\s*(?:"([^"]+)"|\'([^\']+)\')/', $str, $matches)) {
foreach ($matches[1] as $i => $attr) {
$ret[$attr] = $matches[2][$i] ?: $matches[3][$i];
}
if ($name === true || $name === null) {
return $ret;
}
if (isset($ret[$name])) {
return $ret[$name];
}
}
if ($name === null) {
return null;
}
throw new TemplateException("标签值为空 $str");
}
/*
* 解析标签文本
*/
protected static function parseTagWithText($str, $tag, $name = null, $self_end = false, $nesting = false)
{
if (!preg_match_all(self::tagRegex($tag), $str, $matches, PREG_OFFSET_CAPTURE)) {
return false;
}
$pos = 0;
$end_tag = "</$tag>";
foreach ($matches[0] as $i => $match) {
if ($match[1] >= $pos) {
$attr = self::parseSelfEndTagAttrs($match[0], $name, $self_end);
if (substr($match[0], -2) === '/>') {
$ret[] = [
'pos' => [$match[1], $match[1] + strlen($match[0])],
'text' => null,
'attr' => $attr
];
} else {
if (!$pos = stripos($str, $end_tag, $match[1])) {
throw new TemplateException("标签 $tag 未闭合");
}
$start = $match[1] + strlen($match[0]);
$ret[] = [
'pos' => [$match[1], $pos + strlen($end_tag)],
'text' => substr($str, $start, $pos - $start),
'attr' => $attr
];
}
// 允许嵌套
} elseif ($nesting) {
$p = $pos;
$n = count($ret) - 1;
if (!$pos = stripos($str, $end_tag, $ret[$n]['pos'][1])) {
throw new TemplateException("标签 $tag 未闭合");
}
$ret[$n]['pos'][1] = $pos + strlen($end_tag);
$ret[$n]['text'] .= substr($str, $p, $pos - $p);
} else {
throw new TemplateException("标签 $tag 不允许嵌套使用");
}
}
return $ret;
}
/*
* 读取两侧空白符
*/
protected static function readBlank($str)
{
$lpos = $rpos = 0;
$left = $right = $tmp = '';
$len = strlen($str);
for ($i = 0; $i < $len; $i++) {
if (self::isBlankChar($str[$i])) {
$left .= $str[$i];
} else {
$lpos = $i;
break;
}
}
for ($i = $len - 1; $i >= 0; $i--) {
if (self::isBlankChar($str[$i])) {
$right .= $str[$i];
} else {
$rpos = $i;
break;
}
}
return ['left' => $left, 'right' => $right, 'str'=> substr($str, $lpos, $rpos - $lpos + 1)];
}
/*
* 读取左边空白符
*/
protected static function readLeftBlank($str)
{
$ret = '';
for ($i = strlen($str) - 1; $i >= 0; $i--) {
if (self::isBlankChar($str[$i])) {
$ret .= $str[$i];
} else {
return $ret;
}
}
}
/*
* 包装PHP代码
*/
protected static function wrapCode($code)
{
return "<?php $code ?>";
}
/*
* 是否空白字符
*/
protected static function isBlankChar($char)
{
return $char === ' ' || $char === "\t";
}
/*
* 标签正则
*/
protected static function tagRegex($tag)
{
return '/<'.self::$config[$tag.'_tag'].'(?:"[^"]*"|\'[^\']*\'|[^\'">])*>/';
}
/*
* 属性正则前缀
*/
protected static function attrPrefixRegex()
{
return preg_quote(self::$config['assign_attr_prefix'].self::$config['struct_attr_prefix']
.self::$config['double_attr_prefix'].self::$config['argument_attr_prefix']);
}
/*
* 读取语句单元
*/
protected static function readValue($val, $strs = null, $end = null)
{
if ($strs === null) {
extract(self::extractString($val));
}
if (preg_match('/\w\s+\w/', $val)) {
throw new TemplateException("非法空格 $val");
}
// 去空格
$val = preg_replace('/\s+/', '', $val);
$ret = null;
$tmp = null;
$len = strlen($val);
for($i = 0; $i < $len; $i++) {
$c = $val[$i];
if (self::isVarChar($c)) {
$tmp .= $c;
continue;
}
switch ($c) {
// 数组 过滤器
case '.':
$ret = self::readArrayOrFilterValue($ret, $tmp, $val, $len, $i, $strs);
break;
// 括号
case '(':
if (!isset($ret)) {
if (isset($tmp)) {
$ret = self::readFilterValue($tmp, self::readArguments($val, $len, $i, $strs));
} elseif ($pos = self::findEndPos($val, $len, $i, '(', ')')) {
$ret = "(".self::readValue(substr($val, $i + 1, $pos - $i - 1), $strs).")";
$i = $pos;
}
break;
}
throw new TemplateException("非法 $c 语法 $val");
// 数组
case '[':
if ($pos = self::findEndPos($val, $len, $i, '[', ']')) {
if (!isset($ret) && !isset($tmp)) {
$ret = self::readArrayValue(substr($val, $i, $pos + 1), $strs);
} else {
$key = self::readValue(substr($val, $i + 1, $pos - $i - 1), $strs);
if (isset($ret) && !isset($tmp)) {
$ret = $ret."[$key]";
} elseif (!isset($ret) && isset($tmp)) {
$ret = self::readInitValue($ret, $tmp)."[$key]";
} else {
throw new TemplateException("非法 $c 语法 $val");
}
}
$i = $pos;
break;
}
throw new TemplateException("数组结束符号缺失 $val");
// 数组
case '{':
if (!isset($ret) && !isset($tmp) && ($pos = self::findEndPos($val, $len, $i, '{', '}'))) {
$ret = self::readArrayValue(substr($val, $i, $pos + 1), $strs);
$i = $pos;
break;
}
throw new TemplateException("非法 $c 语法 $val");
// 函数 静态方法 容器
case '@':
if (!isset($ret) && !isset($tmp)) {
$ret = self::readFunctionValue($ret, $tmp, $val, $len, $i, $strs);
break;
}
throw new TemplateException("非法 $c 语法 $val");
// 特殊变量
case '$':
if (!isset($ret) && !isset($tmp)) {
if ($ret = self::readSpecialVarValue($val, $len, $i, $strs)) {
break;
}
}
throw new TemplateException("非法 $c 语法 $val");
// 三元表达式
case '?':
$ret = self::readInitValue($ret, $tmp);
$next = substr($val, $i + 1, 1);
if ($next == ':' || $next == '?') {
return "$ret ?$next ".self::readValue(substr($val, $i + 2), $strs);
} else {
return "$ret ? ".self::readValue(substr($val, $i + 1), $strs, ':');
}
throw new TemplateException("非法 $c 语法 $val");
default:
if (in_array($c, ['+', '-', '*', '/', '%']) || in_array($c, ['!', '&', '|', '=', '>', '<'])) {
// 对象操作符
if ($c == '-' && substr($val, $i + 1, 1) == '>') {
$ret = self::readObjectValue($ret, $tmp, $val, $len, $i, $strs);
} else {
$ret = self::readInitValue($ret, $tmp);
return "$ret$c".self::readValue(substr($val, $i + 1), $strs);
}
break;
} elseif ($end === $c) {
return self::readInitValue($ret, $tmp)." $c ".self::readValue(substr($val, $i + 1), $strs);
}
throw new TemplateException("非法 $c 字符 $val");
}
$tmp = null;
}
return self::readInitValue($ret, $tmp);
}
/*
* 变量
*/
protected static function readVarValue($var)
{
return is_numeric($var) || in_array($var, ['true', 'false', 'null']) ? $var : '$'.$var;
}
/*
* 初始值
*/
protected static function readInitValue($ret, $tmp)
{
if (isset($ret) && isset($tmp)) {
throw new TemplateException("无效初始值: $tmp");
}
return isset($tmp) ? self::readVarValue($tmp) : $ret;
}
/*
* 数组
*/
protected static function readArrayValue($val, $strs)
{
// return "json_decode('".self::injectString($val, $strs)."', true)";
$arr = json_decode($ret = self::injectString($val, $strs), true);
if ($arr !== null) {
return var_export($arr, true);
}
throw new TemplateException("无效的数组: $val");
}
/*
* 特殊变量
*/
protected static function readSpecialVarValue($val, $len, &$pos, $strs)
{
$str = substr($val, $pos + 1);
// 临时变量
if (preg_match("/^\d/", $str, $matchs)) {
$pos += 1;
return self::injectString('$'.$matchs[0], $strs);
// 魔术变量
} elseif (preg_match('/^(?:'.implode('|', array_keys(self::$vars)).')/', $str, $matchs)) {
$i = $pos + strlen($matchs[0]) + 1;
$ret = self::$vars[$matchs[0]];
switch ($c = substr($val, $i, 1)) {
case '.':
$res = self::parseLastNameAndPos($val, $i + 1, $len);
$pos = $res['pos'];
if (empty($res['func'])) {
return "$ret('$res[name]')";
}
return self::readFilterValue($res['name'], self::readArguments($val, $len, $pos, $strs, ["$ret()"]));
case '[':
$epos = self::findEndPos($val, $len, $i, '[', ']');
$pos = $epos;
return "$ret(".self::readValue(substr($val, $i + 1, $epos - $i - 1), $strs).")";
default:
if (!self::isVarChar($c)) {
$pos = $i;
return "$ret()";
}
}
}
}
/*
* 小数 数组值 过滤器
*/
protected static function readArrayOrFilterValue($ret, $tmp, $val, $len, &$pos, $strs)
{
if (!isset($ret) && !isset($tmp)) {
throw new TemplateException("空属性");
}
// 小数
if (isset($tmp) && is_numeric($tmp)) {
if (preg_match('/^\d+/', substr($val, $pos + 1), $matches)) {
$pos += strlen($matches[0]);
return "$tmp.$matches[0]";
}
throw new TemplateException("无效小数");
}
$ret = self::readInitValue($ret, $tmp);
$res = self::parseLastNameAndPos($val, $pos + 1, $len);
$pos = $res['pos'];
// 数组值
if (empty($res['func'])) {
return $ret."['".$res['name']."']";
}
// 宏函数
return self::readFilterValue($res['name'], self::readArguments($val, $len, $pos, $strs, $ret ? [$ret] : []));
}
/*
* 过滤器
*/
protected static function readFilterValue($name, $args)
{
if (empty(self::$filters[$name])) {
return self::$config['view_filter_macro']($name, $args);
}
if (is_string(self::$filters[$name])) {
$ret = preg_replace_callback('/\\$(\d+)/', function ($matches) use (&$args) {
if (isset($args[$matches[1]])) {
$val = $args[$matches[1]];
unset($args[$matches[1]]);
return $val;
}
throw new TemplateException("缺少参数");
}, self::$filters[$name]);
return preg_replace_callback('/\,\s*\.\.\.\s*\)\s*$/', function ($matches) use ($args) {
return $args ? ','.implode(',', $args).')' : ')';
}, $ret);
}
if (is_callable(self::$filters[$name])) {
return self::$filters[$name](...$args);
}
throw new TemplateException("无效的filter设置");
}
/*
* 对象
*/
protected static function readObjectValue($ret, $tmp, $val, $len, &$pos, $strs)
{
if (!isset($ret) && !isset($tmp)) {
throw new TemplateException("对象为空");
}
$ret = self::readInitValue($ret, $tmp);
$res = self::parseLastNameAndPos($val, $pos + 2, $len);
$pos = $res['pos'];
if (empty($res['func'])) {
return "$ret->".$res['name'];
}
$args = implode(', ', self::readArguments($val, $len, $pos, $strs));
return "$ret->$res[name]($args)";
}
/*
* 函数 静态方法 容器
*/
protected static function readFunctionValue($ret, $tmp, $val, $len, &$pos, $strs)
{
$arr = [];
$tmp = null;
for ($i = $pos + 1; $i < $len; $i++) {
$c = $val[$i];
if (self::isVarChar($c)) {
$tmp .= $c;
continue;
}
if (!self::isVarChars($tmp)) {
throw new TemplateException("非法名称 $tmp");
}
$arr[] = $tmp;
if ($c == '.') {
$tmp = null;
} elseif ($c == '(') {
$pos = $i;
$args = implode(', ', self::readArguments($val, $len, $pos, $strs));
// 函数
if (count($arr) == 1) {
if (self::$config['allow_php_functions'] === true
|| in_array($tmp, self::$config['allow_php_functions'])
) {
return "$tmp($args)";
}
throw new TemplateException("不支持的内置函数$tmp");
}
// 静态方法
$tmp = [];
while ($v = array_pop($arr)) {
$tmp[] = $v;
$class = implode('\\', $arr);
if (isset(self::$config['allow_static_classes'][$class])) {
$m = array_shift($tmp);
$n = $tmp ? '\\'.implode('\\', array_reverse($tmp)) : '';
return self::$config['allow_static_classes'][$class]."$n::$m($args)";
}
}
throw new TemplateException("未定义的静态类$class");
} else {
$end = true;
break;
}
}
if ($tmp) {
// 容器
if (!isset($end)) {
$arr[] = $tmp;
}
$provider = implode('.', $arr);
if (self::$config['allow_container_providers'] === true
|| in_array($provider, self::$config['allow_container_providers'])
) {
$pos = $i - 1;
return self::$config['view_container_macro']($provider);
}
throw new TemplateException("不支持的容器$provider");
}
throw new TemplateException("解析错误");
}
/*
* 参数
*/
protected static function readArguments($val, $len, &$pos, $strs, $args = [])
{
$epos = self::findEndPos($val, $len, $pos, '(', ')');
if ($tmp = trim(substr($val, $pos + 1, $epos - $pos - 1))) {
foreach (explode(',', $tmp) as $v) {
$args[] = self::readValue(trim($v), $strs);
}
}
$pos = $epos;
return $args;
}
/*
* 解析最后的名字和位置
*/
protected static function parseLastNameAndPos($val, $pos, $len)
{
$ret = null;
for ($i = $pos; $i < $len; $i++) {
$c = $val[$i];
if (!self::isVarChar($c)) {
break;
}
$ret .= $c;
}
if (self::isVarChars($ret)) {
if (substr($val, $i, 1) !== '(') {
return ['name' => $ret, 'pos' => $i - 1];
}
return ['name' => $ret, 'pos' => $i, 'func' => true];
}
throw new TemplateException("非法字符 $ret");
}
/*
* 注入字符串
*/
protected static function injectString($val, $strs)
{
return preg_replace_callback('/\\$(\d)/', function ($matches) use ($strs) {
return $strs[$matches[1]] ?? '';
}, $val);
}
/*
* 提取字符串
*/
protected static function extractString($val)
{
$tmp = '';
$ret = '';
$strs = [];
$quote = null;
$len = strlen($val);
for($i = 0; $i < $len; $i++) {
$c = $val[$i];
if ($c === '"' || $c === "'") {
if ($quote) {
if ($quote === $c) {
if ($val[$i - 1] === '\\') {
$tmp .= $c;
continue;
}
$ret .= '$'.count($strs);
$strs[]= $quote.$tmp.$quote;
$tmp = '';
$quote = null;
} else {
$tmp .= $c;
}
} else {
$quote = $c;
}
} else {
if ($quote) {
$tmp .= $c;
} else {
$ret .= $c;
}
}
}
if (!$quote) {
return ['val' => $ret, 'strs' => $strs];
}
throw new TemplateException("字符串引号未闭合");
}
/*
* 寻找语句结束符位置
*/
protected static function findEndPos($val, $len, $pos, $left, $right)
{
$num = 0;
for($i = $pos + 1; $i < $len; $i++) {
$c = $val[$i];
if ($c === $left) {
$num++;
} elseif ($c === $right) {
if ($num === 0) {
return $i;
}
$num--;
}
}
throw new TemplateException("$val 没有找到结束符 $right");
}
/*
* 是否变量名字符
*/
protected static function isVarChar($char)
{
return preg_match('/\w/', $char);
}
/*
* 是否变量名字符串
*/
protected static function isVarChars($str)
{
if(($len = strlen($str)) > 0 && !in_array($str, ['true', 'false', 'null']) && !is_numeric($str[0])) {
for ($i = 0; $i < $len; $i++) {
if (!self::isVarChar($str[$i])) {
return false;
}
}
return true;
}
return false;
}
/*
* 模版编译宏(依赖框架实现)
*/
protected static function filterMacro($name, $args)
{
return View::class."::callFilter('$name'".($args ? ', '.implode(', ', $args) : '').")";
}
protected static function ContainerMacro($name)
{
return Container::class."::make('$name')";
}
protected static function includeMacro($name, $is_var = false)
{
return 'include '.View::class.'::path('.($is_var ? $name : "'$name'").');';
}
protected static function checkExpiredMacro($names)
{
return 'if ('.View::class."::checkExpired(__FILE__, '".implode("', '", $names)."')) return include __FILE__;";
}
}
Template::__init();
<file_sep><?php
namespace framework\core\http;
use framework\core\Event;
use framework\core\Config;
class Cookie
{
private static $init;
// cookie设置项
private static $options = [
// 有效期
'lifetime' => 0,
// 有效路径
'path' => '',
// 有效域名
'domain' => '',
// 启用安全传输
'secure' => false,
// httponly设置
'httponly' => false
// samesite设置
'samesite' => null
];
/*
* 初始化
*/
public static function __init()
{
if (self::$init) {
return;
}
self::$init = true;
if ($config = Config::read('cookie')) {
self::$options = $config + self::$options;
}
Event::trigger('cookie');
}
/*
* 获取所有
*/
public static function all()
{
return $_COOKIE;
}
/*
* 获取
*/
public static function get($name, $default = null)
{
return $_COOKIE[$name] ?? $default;
}
/*
* 是否存在
*/
public static function has($name)
{
return isset($_COOKIE[$name]);
}
/*
* 设置
*/
public static function set($name, $value, ...$options)
{
$_COOKIE[$name] = $value;
Response::cookie($name, $value, ...$options);
}
/*
* 永久设置
*/
public static function forever($name, $value, ...$options)
{
self::set($name, $value, 315360000, ...$options);
}
/*
* 删除
*/
public static function delete($name, ...$options)
{
if (isset(self::$_COOKIE[$name])) {
unset(self::$_COOKIE[$name]);
Response::cookie($name, null, null, ...$options);
}
}
/*
* 高级设置
*/
public static function setCookie(
$name, $value, $lifetime = null, $path = null, $domain = null, $secure = null, $httponly = null, $samesite = null
) {
if ($value === null) {
$expire = time() - 3600;
} else {
$lft = $lifetime ?? self::$options['lifetime'];
$expire = $lft ? time() + $lft : 0;
}
if (version_compare(PHP_VERSION, '7.3.0', '<')) {
return setcookie($name, $value, $expire,
$path ?? self::$options['path'],
$domain ?? self::$options['domain'],
$secure ?? self::$options['secure'],
$httponly ?? self::$options['httponly']
);
} else {
return setcookie($name, $value, [
'expire' => $expire,
'path' => $path ?? self::$options['path'],
'domain' => $domain ?? self::$options['domain'],
'secure' => $secure ?? self::$options['secure'],
'httponly' => $httponly ?? self::$options['httponly'],
'samesite' => $samesite ?? self::$options['samesite'],
]);
}
}
}
Cookie::__init();
<file_sep><?php
//默认配置文件
return [
'file' => [
'driver' => 'file',
// 默认获得日志的等级
'level' => array('emergency', 'alert', 'critical', 'error', 'warning', 'notice'/*, 'debug', 'info'*/),
// 日志信息格式,如{date} {ip}会自动替换成当前日期和用户IP
'format' => "[{date}] [{ip}] [{level}] {message} in {file}: {line}",
// 日志文件保存路径
'logfile' => APP_DIR.'storage/log/error-'.date('Y-m-d').'.log',
],
'console' => [
'driver' => 'webConsole',
// 默认获得日志的等级
'level' => array('emergency', 'alert', 'critical', 'error', 'warning', 'notice', 'debug', 'info'),
/*
* 由于此驱动日志是通过http header发送,日志过大时会超过nginx apache的限制导致错误
* 超过此值的日志会被丢弃,替换成一个警告 header_limit_size: vlaue
* 用户也可以自己修改nginx apache配置来修改header发送限制
*/
'header_limit_size' => 4000,
/* (可选配置)
* 设置此项后,只有包含ACCEPT_LOGGER_DATA header的请求(并且其值与check_header_accept相同),才发送log数据
* 目前只有我自己修改chromelogge支持 https://github.com/qiu-jin/chromelogger
*/
//check_header_accept => null
// (可选配置)允许接收日志的请求IP
//'allow_ips' => ['127.0.0.1']
],
'email' => [
'driver' => 'email',
// 日志接受者的邮箱
'to' => '<EMAIL>',
// email实例的配置
'email' => 'sendmail',
/*
* 发送间隔时间(秒),防止同一错误重复发送
* 需要cache实例来保存发送状态
*/
'interval'=> 3600, //默认
// (可选配置)cache实例的配置
//'cache' => null,
],
];
<file_sep><?php
return [
'apc' => [
'driver' => 'apc',
// 缓存key前缀,防止冲突。
'prefix' => 'test',
/* (可选配置)
* 是否调用clear方法清除所有缓存
* 为true时清除所有缓存,会影响其它apc缓存实例。
* 为false时,使用迭代器删除有prefix的key的缓存,需要迭代处理缓存较大时可能效率低。
*/
'global_clear' => false //默认值
],
'db' => [
'driver' => 'db',
/* 缓存数据库
* 值为数组时使用数组配置(参考db配置)
* 值为字符串时直接使用db配置中的同名db实例
*/
'db' => 'mysql',
/* 缓存表名
* key char(128) NOT NULL PRIMARY KEY
* value BLOB
* expiration int(11)
*/
'table' => 'cache',
/*(可选配置)
* 设置缓存值的序列化和反序列化处理器
* 在apc memcached redis opcache等驱动有自己内置序列化和反序列化处理,所以不需要此设置
* 如果缓存值没有数组等复合类型只有字符串等,也可以不设置此项
* 除了json serialize等内置序列化和反序列化处理器,也可以安装扩展支持igbinary msgpack等协议
*/
'serializer' => ['jsonencode', 'jsondecode'], //默认为空
/*(可选配置)
* 设置gc处理器触发几率,值为0.0001到1之间
* apc memcached redis等驱动有自己的gc处理,所以不需要此设置
* file opcache等驱动还需要gc_maxlife配置来配合处理gc
*/
//'gc_random' => ''
],
'file' => [
'driver' => 'file',
// 缓存文件保存目录。
'dir' => APP_DIR.'storage/cache/file/',
// (可选配置)缓存最大生存时间,大于此时间的文件会在触发gc后被删除
'gc_maxlife' => 86400 //默认值
],
'memcached' => [
'driver' => 'memcached',
// 服务器地址,多个以逗号分隔
'hosts' => '127.0.0.1',
// (可选配置)服务器端口
'port' => 11211, //默认值
// (可选配置)用户名
// 'username' => '',
// (可选配置)密码
// 'password' => '',
// (可选配置)超时设置
// 'timeout => ''
// (可选配置)options设置
// 'options => ''
],
'opcache' => [
'driver' => 'opcache',
// PHP缓存文件保存目录。
'dir' => APP_DIR.'storage/cache/php/',
// (可选配置)缓存最大生存时间,大于此时间的文件会在触发gc后被删除
'gc_maxlife' => 86400, //默认值
/* (可选配置)
* 为true时将var_export不支持的数据类型过滤处理,如object转为array,resource设为null等
* 为false不做处理,有不支持的数据类型时会产生php错误,请谨慎使用。
*/
'filter_value' => false //默认值
],
'redis' => [
'driver' => 'redis',
// Redis服务器器地址
'host' => '127.0.0.1',
// (可选配置)服务器端口
'port' => 6379, //默认值
// (可选配置)database
//'database' => ''
],
];
<file_sep><?php
namespace framework\driver\cache;
/*
* https://github.com/phpredis/phpredis
*/
class Redis extends Cache
{
// 连接实例
protected $connection;
/*
* 构造函数
*/
public function __construct($config)
{
$this->connection = $this->contect($config);
}
/*
* 连接
*/
protected function contect($config)
{
$connection = new \Redis();
if (!$connection->connect($config['host'], $config['port'] ?? 6379, $config['timeout'] ?? 0)) {
throw new \Exception('Redis connect error');
}
if (isset($config['password'])) {
$connection->auth($config['password']);
}
if (isset($config['database'])) {
$connection->select($config['database']);
}
if (isset($config['options'])) {
foreach ($config['options'] as $k => $v) {
$connection->setOption($k, $v);
}
}
return $connection;
}
/*
* 获取
*/
public function get($key, $default = null)
{
$value = $this->connection->get($key);
return $value === false ? $default : $value;
}
/*
* 检查
*/
public function has($key)
{
return $this->connection->exists($key);
}
/*
* 设置
*/
public function set($key, $value, $ttl = null)
{
if (($t = $ttl ?? $this->ttl) == 0) {
return $this->connection->set($key, $value);
} else {
return $this->connection->set($key, $value, $t);
}
}
/*
* 删除
*/
public function delete($key)
{
return $this->connection->del($key);
}
/*
* 自增
*/
public function increment($key, $value = 1)
{
return $value > 1 ? $this->connection->incrBy($key, $value) : $this->connection->incr($key);
}
/*
* 自减
*/
public function decrement($key, $value = 1)
{
return $value > 1 ? $this->connection->decrBy($key, $value) : $this->connection->decr($key);
}
/*
* 获取多个
*/
public function getMultiple(array $keys, $default = null)
{
$values = $this->connection->mGet($keys);
if ($default !== false) {
foreach ($keys as $k) {
if (!isset($values[$k]) || $values[$k] === false) {
$values[$k] = $default;
}
}
}
return $values;
}
/*
* 设置多个
*/
public function setMultiple(array $values, $ttl = null)
{
if (($t = $this->ttl($ttl)) == 0) {
return $this->connection->mSet($values);
} else {
return $this->connection->mSet($values, $t);
}
}
/*
* 删除多个
*/
public function deleteMultiple(array $keys)
{
return $this->connection->del($keys);
}
/*
* 清理
*/
public function clear()
{
return $this->connection->flushdb();
}
/*
* 获取连接
*/
public function getConnection()
{
return $this->connection;
}
/*
* 关闭连接
*/
public function close()
{
$this->connection->close();
}
/*
* 析构函数
*/
public function __destruct()
{
$this->close();
}
}
<file_sep><?php
namespace framework\driver\email\query;
use framework\util\Str;
use framework\core\View;
class Query
{
// 邮件驱动
protected $email;
// 请求设置值
protected $options;
/*
* 构造函数
*/
public function __construct($email)
{
$this->email = $email;
}
/*
* 收信人
*/
public function to($email, $name = null)
{
$this->options['to'][] = [$email, $name];
return $this;
}
/*
* 抄送
*/
public function cc($email, $name = null)
{
$this->options['cc'][] = [$email, $name];
return $this;
}
/*
* 秘密抄送
*/
public function bcc($email, $name = null)
{
$this->options['bcc'][] = [$email, $name];
return $this;
}
/*
* 发信人
*/
public function from($email, $name = null)
{
$this->options['from'] = [$email, $name];
return $this;
}
/*
* 被回复人
*/
public function replyTo($email, $name = null)
{
$this->options['replyto'] = [$email, $name];
return $this;
}
/*
* 是否html邮件
*/
public function isHtml($bool = true)
{
$this->options['ishtml'] = (bool) $bool;
return $this;
}
/*
* 邮件主题
*/
public function subject($subject, array $vars = null)
{
$this->options['subject'] = $vars ? Str::format($subject, $vars) : $subject;
return $this;
}
/*
* 文本邮件内容
*/
public function text($content, array $vars = null)
{
$this->options['content'] = $vars ? Str::format($content, $vars) : $content;
return $this;
}
/*
* html邮件内容
*/
public function html($content, array $vars = null)
{
$this->options['ishtml'] = true;
return $this->text($content, $vars);
}
/*
* 邮件模版设置
*/
public function template($tpl, array $vars = null)
{
$this->options['ishtml'] = true;
$this->options['content'] = View::render($tpl, $vars);
return $this;
}
/*
* 邮件编码
*/
public function encoding($encoding)
{
$this->options['encoding'] = $encoding;
return $this;
}
/*
* 邮件附件
*/
public function attach($content, $name = null, $is_buffer = false, $mime = null)
{
$this->options['attach'][] = [$content, $name, $is_buffer, $mime];
return $this;
}
/*
* 内联邮件附件
*/
public function inline($content, $name = null, $is_buffer = false, $mime = null)
{
$this->options['attach'][] = [$content, $name, $is_buffer, $mime, true];
return $this;
}
/*
* 邮件额外选项单个设置(部分邮件驱动有效)
*/
public function option($name, $value)
{
$this->options['options'][$name] = $value;
return $this;
}
/*
* 邮件额外选项多个设置(部分邮件驱动有效)
*/
public function options(array $value)
{
$this->options['options'] = isset($this->options['options']) ? $value + $this->options['options'] : $value;
return $this;
}
/*
* 发送邮件
*/
public function send()
{
return $this->email->send(null, null, null, $this->options);
}
}
<file_sep><?php
use framework\App;
use framework\util\Date;
use framework\core\Debug;
use framework\core\Error;
use framework\core\Event;
use framework\core\Getter;
use framework\core\Logger;
use framework\core\Config;
use framework\core\Container;
use framework\core\Validator;
use framework\core\http\Client;
use framework\core\http\Cookie;
use framework\core\http\Session;
use framework\core\http\Request;
use framework\core\http\Response;
/*
* 获取环境设置
*/
function env($name, $default = null)
{
return Config::env($name, $default);
}
/*
* 获取配置设置
*/
function config($name, $default = null)
{
return Config::get($name, $default);
}
/*
* 获取容器实例
*/
function app($name = null)
{
return isset($name) ? Container::make($name) : App::instance();
}
/*
* 获取日志实例
*/
function logger($name = null, $use_null_handler = false)
{
return Logger::channel($name, $use_null_handler);
}
/*
* 获取驱动实例
*/
function driver($type, $name = null)
{
return Container::driver($type, $name);
}
/*
* 获取数据库实例
*/
function db($name = null)
{
return Container::driver('db', $name);
}
/*
* 获取rpc实例
*/
function rpc($name = null)
{
return Container::driver('rpc', $name);
}
/*
* 获取缓存实例
*/
function cache($name = null)
{
return Container::driver('cache', $name);
}
/*
* 发送EMAIL或获取EMAIL实例
*/
function email($param, ...$params)
{
return $params ? Container::driver('email')->send($param, ...$params) : Container::driver('email', $param);
}
/*
* 输出视图页面
*/
function view($tpl, array $vars = null)
{
return Response::view($tpl, $vars);
}
/*
* 获取请求参数
*/
function input($name = null, $default = null)
{
return Request::input($name, $default);
}
/*
* 设置响应内容
*/
function output($name, $type = null)
{
return Response::send($name, $type);
}
/*
* 获取或设置COOKIE
*/
function cookie($name, ...$params)
{
return $params ? Cookie::set($name, ...$params) : Cookie::get($name);
}
/*
* 获取或设置SESSION
*/
function session($name, $value = null)
{
return isset($value) ? Session::set($name, $value) : Session::get($name);
}
/*
* 验证器
*/
function validate($rule, $message = null)
{
return new Validator($rule, $message);
}
/*
* HTTP请求实例
*/
function fetch($method, $url)
{
return new Client($method, $url);
}
function request($method, $url)
{
return new Client($method, $url);
}
/*
* 中断应用
*/
function abort($code = null, $message = null)
{
App::abort($code, $message);
}
/*
* 设置警告
*/
function warn($message, $limit = 1)
{
Error::trigger($message, E_USER_WARNING, $limit + 1);
return false;
}
/*
* 设置错误
*/
function error($message, $limit = 1)
{
Error::trigger($message, E_USER_ERROR, $limit + 1);
return false;
}
/*
* 调试
*/
function dd(...$vars)
{
Response::send(Debug::dump(...$vars));
}
/*
* 调试
*/
function dump(...$vars)
{
Response::send(Debug::dump(...$vars), false);
}
/*
* 类实例化
*/
function instance($class, ...$params)
{
return new $class(...$params);
}
/*
* JSON序列化
*/
function jsonencode($data)
{
return json_encode($data, JSON_UNESCAPED_UNICODE);
}
/*
* JSON反序列化
*/
function jsondecode($data)
{
return json_decode($data, true);
}
/*
* 获取Getter
*/
function getter($providers = null)
{
return new class ($providers) {
use Getter;
public function __construct($providers) {
$this->{Config::get('getter.providers_name', 'providers')} = $providers;
}
};
}
/*
* 检查文件存在
*/
define('OPCACHE_LOADED', extension_loaded('opcache'));
function is_php_file($file)
{
return (OPCACHE_LOADED && opcache_is_script_cached($file)) || is_file($file);
}
/*
* 安全引用文件
*/
function __require($__file)
{
return require $__file;
}
<file_sep><?php
namespace framework\core\http;
use framework\core\Logger;
class Client
{
const EOL = "\r\n";
// cURL句柄
private $ch;
// 调试设置
private $debug = \app\env\APP_DEBUG;
// 错误信息
private $error;
// 请求设置
private $request;
// 响应内容
private $response;
/*
* GET实例
*/
public static function get($url)
{
return new self('GET', $url);
}
/*
* POST实例
*/
public static function post($url)
{
return new self('POST', $url);
}
/*
* 多进程批量请求
*/
public static function batch(array $queries, callable $handler = null, $select_timeout = 0.1)
{
$mh = curl_multi_init();
foreach ($queries as $i => $query) {
$ch = $query->build();
$indices[strval($ch)] = $i;
curl_multi_add_handle($mh, $ch);
}
do{
if (($status = curl_multi_exec($mh, $active)) != CURLM_CALL_MULTI_PERFORM) {
if ($status != CURLM_OK) {
break;
}
while ($done = curl_multi_info_read($mh)) {
$ch = $done['handle'];
$index = $indices[strval($ch)];
$query = $queries[$index];
$query->setResponse(curl_multi_getcontent($ch));
if (isset($handler)) {
$return[$index] = $handler($query, $index);
} else {
$return[$index] = $query;
}
curl_multi_remove_handle($mh, $ch);
if ($active > 0) {
curl_multi_select($mh, $select_timeout);
}
}
}
} while ($active > 0);
curl_multi_close($mh);
return $return ?? null;
}
/*
* 构造函数
*/
public function __construct($method, $url)
{
$this->request = (object) [
'url' => $url,
'method' => $method,
'curlopts' => [CURLOPT_RETURNTRANSFER => true, CURLOPT_CONNECTTIMEOUT => 6, CURLOPT_TIMEOUT => 60]
];
}
/*
* 设置请求query
*/
public function query($query)
{
$this->request->url .= strpos($this->request->url, '?') === false ? '?' : '&';
$this->request->url .= is_array($query) ? http_build_query($query) : $query;
return $this;
}
/*
* 设置请求body
*/
public function body(string $body, $type = null)
{
$this->request->body = $body;
if ($type) {
$this->request->headers['Content-Type'] = $type;
}
return $this;
}
/*
* 设置请求body为数组被json_encode后的字符串
*/
public function json(array $data)
{
return $this->body(json_encode($data, JSON_UNESCAPED_UNICODE), 'application/json; charset=UTF-8');
}
/*
* 设置表单请求数据,数据类型默认为application/x-www-form-urlencoded格式否则为multipart/form-data
*/
public function form(array $data, $multipart = false)
{
if ($multipart) {
$this->request->body = $data;
return $this;
}
return $this->body(http_build_query($data), 'application/x-www-form-urlencoded');
}
/*
* 文件上传
*/
public function file($name, $file, $filename = null, $mimetype = null)
{
if (isset($this->request->body) && !is_array($this->request->body)) {
throw new \Exception("仅允许与multipart类型form方法合用");
}
$this->request->body[$name] = new \CURLFile($file, $mimetype, $filename);
return $this;
}
/*
* 变量内容上传(不能与file混用)
*/
public function buffer($name, $content, $filename = null, $mimetype = null)
{
if (isset($this->request->boundary)) {
$this->request->body = substr($this->request->body, 0, - strlen($this->request->boundary) - 6);
} else {
$this->request->boundary = uniqid();
$this->request->headers['Content-Type'] = 'multipart/form-data; boundary='.$this->request->boundary;
if (isset($this->request->body)) {
if (!is_array($this->request->body)) {
throw new \Exception("仅允许与multipart类型form方法合用");
}
$this->request->body = $this->setMultipartFormData($this->request->body).self::EOL;
} else {
$this->request->body = '';
}
}
$this->request->body .= implode(self::EOL, [
"--{$this->request->boundary}",
'Content-Disposition: form-data; name="'.$name.'"; filename="'.($filename ?? $name).'"',
'Content-Type: '.($mimetype ?? 'application/octet-stream'),
'Content-Transfer-Encoding: binary',
'',
$content,
"--{$this->request->boundary}--",
''
]);
return $this;
}
/*
* 发送一个流,只支持PUT方法,在PUT大文件时使用节约内存
*/
public function stream($fp)
{
$this->request->curlopts[CURLOPT_PUT] = 1;
$this->request->curlopts[CURLOPT_INFILE] = $fp;
$this->request->curlopts[CURLOPT_INFILESIZE] = fstat($fp)['size'];
return $this;
}
/*
* 设置单个header
*/
public function header($name, $value)
{
$this->request->headers[$name] = $value;
return $this;
}
/*
* 设置多个header
*/
public function headers(array $values)
{
$this->request->headers = isset($this->request->headers) ? $values + $this->request->headers : $values;
return $this;
}
/*
* 认证
*/
public function auth($user, $pass = null)
{
$this->request->headers['Authorization'] = 'Basic '.base64_encode(isset($pass) ? "$user:$pass" : $user);
return $this;
}
/*
* 设置ssl
*/
public function ssl($value = null)
{
if ($value) {
$this->request->curlopts[CURLOPT_SSL_VERIFYPEER] = true;
$this->request->curlopts[is_dir($value) ? CURLOPT_CAPATH : CURLOPT_CAINFO] = $value;
} else {
$this->request->curlopts[CURLOPT_SSL_VERIFYPEER] = false;
$this->request->curlopts[CURLOPT_SSL_VERIFYHOST] = false;
}
return $this;
}
/*
* 设置单个cookie
*/
public function cookie($name, $value)
{
$this->request->cookies[$name] = $value;
return $this;
}
/*
* 设置多个cookie
*/
public function cookies(array $values)
{
$this->request->cookies = isset($this->request->cookies) ? $values + $this->request->cookies : $values;
return $this;
}
/*
* 设置底层curl参数
*/
public function curlopt($name, $value)
{
$this->request->curlopts[$name] = $value;
return $this;
}
/*
* 设置底层curl参数
*/
public function curlopts(array $values)
{
$this->request->curlopts = isset($this->request->curlopts) ? $values + $this->request->curlopts : $values;
return $this;
}
/*
* 设置请求超时时间
*/
public function timeout($timeout)
{
$this->request->curlopts[CURLOPT_TIMEOUT] = $timeout;
return $this;
}
/*
* 设置请求连接超时时间
*/
public function connectTimeout($timeout)
{
$this->request->curlopts[CURLOPT_CONNECTTIMEOUT] = $timeout;
return $this;
}
/*
* 设置重定向
*/
public function allowRedirect($max = 1)
{
$this->request->curlopts[CURLOPT_FOLLOWLOCATION] = (bool) $max;
if ($max > 1) {
$this->request->curlopts[CURLOPT_MAXREDIRS] = (int) $max;
}
return $this;
}
/*
* 设置是否获取并解析请求响应的headers数据
*/
public function returnHeader($bool = true)
{
$this->request->curlopts[CURLOPT_HEADER] = (bool) $bool;
return $this;
}
/*
* 设置debug模式
*/
public function debug($debug = true)
{
$this->debug = $debug;
return $this;
}
/*
* 获取请求响应
*/
public function response()
{
if (!$this->response) {
$this->setResponse($this->exec());
}
return $this->response;
}
/*
* 魔术方法,获取request response error信息
*/
public function __get($name)
{
switch ($name) {
case 'request':
return $this->request;
case 'response':
return $this->response();
case 'error':
return $this->error;
}
throw new \Exception("Undefined property: $$name");
}
/*
* 将请求的获得的body数据直接写入到本地文件,在body内容过大时可节约内存
*/
public function saveAs($file)
{
if ($this->response) {
throw new \Exception("不能使用已完成的请求实例");
}
if ($fp = fopen($file, 'w+')) {
$this->request->curlopts[CURLOPT_FILE] = $fp;
$this->setResponse($this->exec());
$return = $this->response->code == 200 && $this->response->body === true;
if ($return) {
fclose($fp);
} else {
rewind($fp);
//$this->response->body = stream_get_contents($fp);
fclose($fp);
if (file_exists($file)) {
unlink($file);
}
}
return $return;
}
return $this->response = false;
}
/*
* 获取Curl信息
*/
public function getCurlInfo($name = null)
{
if (!$this->response) {
$this->setResponse($this->exec());
}
return curl_getinfo($this->ch, $name);
}
/*
* 执行请求
*/
protected function exec()
{
return curl_exec($this->build());
}
/*
* 构建请求数据
*/
protected function build()
{
$ch = curl_init($this->request->url);
if (isset($this->request->method)){
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->request->method);
}
if (isset($this->request->body)){
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->request->body);
}
if (isset($this->request->headers)) {
foreach ($this->request->headers as $name => $value) {
$headers[] = "$name: $value";
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
if (isset($this->request->cookies)) {
curl_setopt($ch, CURLOPT_COOKIE, http_build_query($this->request->cookies, '', ';'));
}
/*
if ($this->debug) {
$this->request->curlopts[CURLOPT_HEADER] = true;
$this->request->curlopts[CURLINFO_HEADER_OUT] = true;
}*/
if (isset($this->request->curlopts)) {
//ksort($$this->request->curlopts);
curl_setopt_array($ch, $this->request->curlopts);
}
return $this->ch = $ch;
}
/*
* 处理请求响应
*/
protected function setResponse($body)
{
$code = curl_getinfo($this->ch, CURLINFO_HTTP_CODE);
if (!($code >= 200 && $code < 300)) {
$this->setError($code);
}
if (!empty($this->request->curlopts[CURLOPT_HEADER])) {
list($headers, $body) = $this->getResponseHeadersFromResult($body);
}
$this->response = new class ($code, $body, $headers ?? null) {
public $code;
public $body;
public $headers;
public function __construct($code, $body, $headers) {
$this->code = $code;
$this->body = $body;
$this->headers = $headers;
}
// 获取响应头
public function header($name, $default = null) {
return $this->headers[$name] ?? $default;
}
// 解码响应内容
public function decode(callable $decoder = null) {
return $decoder ? $decoder($this->body) : json_decode($this->body, true);
}
public function __toString() {
return $this->body;
}
};
}
/*
* 处理错误信息
*/
protected function setError($code)
{
if ($code) {
$message = $code ?? 'Unknown Status';
} else {
$code = curl_errno($this->ch);
$message = curl_error($this->ch);
}
$this->error = new class ($code, $message, $this->request) {
private $request;
public $code;
public $message;
public function __construct($code, $message, $request) {
$this->code = $code;
$this->message = $message;
$this->request = $request;
}
public function __toString() {
return ($this->code ? "[$this->code]$this->message" : 'Unknown HTTP Error')
.": {$this->request->method} {$this->request->url}";
}
};
}
/*
* 设置multipart类型数据
*/
protected function setMultipartFormData($data, $parent = null)
{
$parts = [];
foreach ($data as $k => $v) {
if ($parent) {
$k = $parent."[$k]";
}
if (is_array($v)) {
$parts = array_merge($parts, $this->setMultipartFormData($v, $k));
} else {
$parts[] = "--{$this->request->boundary}";
$parts[] = "Content-Disposition: form-data; name=\"$k\"";
$parts[] = '';
$parts[] = $v;
}
}
return implode(self::EOL, $parts);
}
/*
* 获取响应头
*/
protected function getResponseHeadersFromResult($body)
{
if (is_string($body) && ($size = curl_getinfo($this->ch, CURLINFO_HEADER_SIZE))) {
$new_body = substr($body, $size);
foreach (explode(self::EOL, substr($body, 0, $size)) as $line) {
$kv = explode(':', $line, 2);
if(isset($kv[1])) {
$k = trim($kv[0]);
$v = trim($kv[1]);
if (isset($headers[$k])) {
if (is_array($headers[$k])) {
$headers[$k][] = $v;
} else {
$headers[$k] = [$headers[$k], $v];
}
} else {
$headers[$k] = $v;
}
}
}
}
return [$headers ?? null, $new_body ?? $body];
}
/*
* 日志
*/
protected static function log($log)
{
Logger::channel($this->debug)->debug($log);
}
/*
* 析构方法,关闭curl句柄
*/
public function __destruct()
{
if (is_resource($this->ch)) curl_close($this->ch);
}
}
<file_sep><?php
namespace framework\core;
use framework\App;
class Command
{
private static $init;
// 终端输出样式
private static $styles = [
'bold' => ['1', '22'],
'underscore' => ['4', '24'],
'blink' => ['5', '25'],
'reverse' => ['7', '27'],
'conceal' => ['8', '28'],
'foreground' => [
'black' => ['30', '39'],
'red' => ['31', '39'],
'green' => ['32', '39'],
'yellow' => ['33', '39'],
'blue' => ['34', '39'],
'magenta' => ['35', '39'],
'cyan' => ['36', '39'],
'white' => ['37', '39'],
],
'background' => [
'black' => ['40', '49'],
'red' => ['41', '49'],
'green' => ['42', '49'],
'yellow' => ['43', '49'],
'blue' => ['44', '49'],
'magenta' => ['45', '49'],
'cyan' => ['46', '49'],
'white' => ['47', '49'],
],
];
// 输出样式模版
private static $templates = [
'error' => ['foreground' => 'white', 'background' => 'red'],
'info' => ['foreground' => 'green'],
'comment' => ['foreground' => 'yellow'],
'question' => ['foreground' => 'black', 'background' => 'cyan'],
'highlight' => ['foreground' => 'red'],
'warning' => ['foreground' => 'black', 'background' => 'yellow'],
];
// 应用实例
private $app;
// 进程ID
private $pid;
// 参数
private $arguments;
// 是否为windows系统
private $is_win;
// 是否有stty命令工具
private $has_stty;
// 是否启用readline扩展
private $has_readline;
// 选项值
private $options;
// 进程标题
protected $title;
// 短选项别名
protected $short_option_alias;
/*
* 初始化
*/
public static function __init()
{
if (self::$init) {
return;
}
self::$init = true;
if ($config = Config::read('command')) {
if (isset($config['styles'])) {
self::$styles = $config['styles'] + self::$styles;
}
if (isset($config['templates'])) {
self::$templates = $config['templates'] + self::$templates;
}
}
}
/*
* 构造函数
*/
public function __construct(array $arguments = null)
{
if (isset($this->title)) {
$this->setTitle($this->title);
}
if ($arguments) {
$this->arguments = $arguments;
$this->options = $this->arguments['long_options'] ?? [];
if (isset($this->arguments['short_options'])) {
if ($this->short_option_alias) {
foreach ($this->arguments['short_options'] as $k => $v) {
$option = $this->short_option_alias[$k] ?? null;
if ($option && !isset($this->options[$option])) {
$this->options[$option] = $v;
}
}
}
$this->options += $this->arguments['short_options'];
}
}
}
/*
* 获取进程id
*/
public function pid()
{
return $this->pid ?? $this->pid = getmypid();
}
/*
* 获取参数
*/
public function param(int $index = null, $default = null)
{
return $index === null ? ($this->arguments['params'] ?? null)
: ($this->arguments['params'][$index - 1] ?? $default);
}
/*
* 获取设置值
*/
public function option($name = null, $default = null)
{
return $name === null ? ($this->options ?? null) : ($this->options[$name] ?? $default);
}
/*
* 获取长设置值
*/
public function longOption($name = null, $default = null)
{
return $name === null ? ($this->arguments['long_options'] ?? null)
: ($this->arguments['long_options'][$name] ?? $default);
}
/*
* 获取短设置值
*/
public function shortOption($name = null, $default = null)
{
return $name === null ? ($this->arguments['short_options'] ?? null)
: ($this->arguments['short_options'][$name] ?? $default);
}
/*
* 读输入
*/
public function read($prompt = null)
{
if ($prompt !== null) {
$this->write($prompt);
}
return fgets(STDIN);
}
/*
* 写输出
*/
public function write($text, $style = null)
{
if ($style === true) {
$text = $this->formatTemplate($text);
} elseif (is_array($style)) {
$text = $this->formatStyle($text, $style);
}
fwrite(STDOUT, $text);
}
/*
* 输出单行
*/
public function line($text, $style = null)
{
$this->write($text, $style);
$this->newline();
}
/*
* 错误
*/
public function error($text)
{
$this->line("<error>$text</error>", true);
}
/*
* 警告
*/
public function warning($text)
{
$this->line("<warning>$text</warning>", true);
}
/*
* 信息
*/
public function info($text)
{
$this->line("<info>$text</info>", true);
}
/*
* 注释
*/
public function comment($text)
{
$this->line("<comment>$text</comment>", true);
}
/*
* 高亮
*/
public function highlight($text)
{
$this->line("<highlight>$text</highlight>", true);
}
/*
*
*/
public function question($text)
{
$this->line("<question>$text</question>", true);
}
/*
* 格式化json
*/
public function json($data)
{
$this->line(json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}
/*
* 表格
*/
public function table(array $data, array $head = null)
{
$data = array_values($data);
if ($head) {
array_unshift($data, $head);
} elseif (!isset($data[0][0])) {
array_unshift($data, $head = array_keys($data[0]));
}
foreach ($data as $i => $row) {
$row = array_values($row);
$data[$i] = $row;
foreach ($row as $k => $v) {
$max_width[$k] = max($max_width[$k] ?? 0, mb_strwidth($v));
}
}
$border = '+'.implode('+', array_map(function ($w) {
return str_repeat('-', $w + 2);
}, $max_width)).'+';
foreach ($data as $row) {
$table[] = '| '.implode(' | ', array_map(function ($w, $v){
return $v.str_repeat(' ', $w - mb_strwidth($v));
}, $max_width, $row)).' |';
}
$table[] = $border;
if ($head) {
array_unshift($table, array_shift($table), $border);
}
array_unshift($table, $border);
$this->line(implode(PHP_EOL, $table));
}
/*
* 换行
*/
public function newline($num = 1)
{
$this->write(str_repeat(PHP_EOL, $num));
}
/*
* 问答
*/
public function ask($prompt, array $auto_complete = null)
{
return $this->read($prompt, $auto_complete);
}
/*
* 确认
*/
public function confirm($prompt)
{
return in_array(strtolower($this->read($prompt)), ['y', 'yes'], true);
}
/*
* 选择
*/
public function choice($prompt, array $options, $is_multi_select = false)
{
}
/*
* 进度条
*/
public function progress($total = 100, $plus = '+', $reduce = '-', $format = '[%s%s] %3d%% Complete')
{
return new class ($this->app, compact('total', 'plus', 'reduce', 'format')) {
private $app;
private $step;
private $options;
public function __construct($app, $options) {
$this->app = $app;
$this->options = $options;
}
public function add(int $num = 1) {
$this->step($this->step ? $this->step + $num : $num);
}
public function step(int $step) {
if (isset($this->step)) {
$this->write("\033[1A");
}
$this->step = $step > $this->options['total'] ? $this->options['total'] : $step;
$percent = intval(($this->step / $this->options['total']) * 100);
$this->write(sprintf(
$this->options['format'],
str_repeat($this->options['plus'], $this->step),
str_repeat($this->options['reduce'], $this->options['total'] - $this->step),
$percent
).PHP_EOL);
//$this->app->write("\007");
}
};
}
/*
* 隐藏输入字符(替换为星号*)
*/
public function hidden($prompt)
{
if ($this->hasStty()) {
$this->write($prompt);
$sttyMode = shell_exec('stty -g');
shell_exec('stty -echo');
$value = $this->read();
shell_exec(sprintf('stty %s', $sttyMode));
if (false !== $value) {
$this->newline();
return $value;
}
throw new \RuntimeException('Aborted');
}
throw new \RuntimeException('Unable to hide the response.');
}
/*
* 输入补全
*/
public function anticipate($prompt, array $values)
{
if ($this->hasReadline()) {
readline_completion_function(function ($input, $index) use ($values) {
if ($input === '') {
return $values;
}
return array_filter($values, function ($value) use ($input) {
return stripos($value, $input) === 0 ? $value : false;
});
});
$input = readline($prompt);
readline_completion_function(function () {});
return $input;
}
throw new \RuntimeException('Anticipate method must enable readline.');
}
/*
* 格式化样式
*/
public function formatStyle($text, array $style)
{
foreach ($style as $k => $v) {
if ($k === 'foreground' || $k === 'background') {
if (isset(self::$styles[$k][$v])) {
list($start[], $end[]) = self::$styles[$k][$v];
}
} elseif (isset(self::$styles[$k])) {
if (self::$styles[$k]) {
list($start[], $end[]) = self::$styles[$k];
}
}
}
if (isset($start)) {
return "\033[".implode(';', $start)."m$text\033[".implode(';', $end)."m";
}
return $text;
}
/*
* 格式化模版
*/
protected function formatTemplate($text)
{
$regex = implode('|', array_keys(self::$templates));
if (!preg_match_all("#<(($regex) | /($regex)?)>#isx", $text, $matches, PREG_OFFSET_CAPTURE)) {
return $text;
}
$offset = 0;
$stack = [];
$output = '';
foreach ($matches[0] as $i => $match) {
list($tag, $pos) = $match;
$part = substr($text, $offset, $pos - $offset);
if ($tag[1] !== '/') {
$count = count($stack);
$stack[] = ['tag' => substr($tag, 1, -1), 'text' => ''];
} else {
if (($last = array_pop($stack)) && $last['tag'] === substr($tag, 2, -1)) {
$count = count($stack);
if (isset(self::$templates[$last['tag']])) {
$part = $this->formatStyle($last['text'].$part, self::$templates[$last['tag']]);
} else {
$part = $last['text'].$part;
}
} else {
throw new \Exception('Template output error 模版标签未闭合');
}
}
if ($count === 0) {
$output .= $part;
} else {
$stack[$count - 1]['text'] .= $part;
}
$offset = $pos + strlen($tag);
}
if ($stack) {
throw new \Exception('Template output error 模版标签未闭合');
}
return str_replace('\\<', '<', $output.substr($text, $offset));
}
/*
* 是否为win系统
*/
public function isWin()
{
return $this->is_win ?? $this->is_win = stripos(PHP_OS, 'win') === 0;
}
/*
* 是否安装stty命令工具
*/
public function hasStty()
{
if (isset($this->has_stty)) {
return $this->has_stty;
}
exec('stty 2>&1', $tmp, $code);
return $this->has_stty = $code === 0;
}
/*
* 是否安装readline扩展
*/
public function hasReadline()
{
return $this->has_readline ?? $this->has_readline = extension_loaded('readline');
}
/*
* 设置进程标题
*/
public function setTitle($title)
{
cli_set_process_title($title);
}
}
Command::__init();
<file_sep><?php
return [
'crypt' => 'sodium',
'serializer' => ['jsonencode', 'jsondecode']
];
<file_sep><?php
namespace app\hook;
class ResponseHeader
{
public static function run($response)
{
$response->headers['X-Porwer-By'] = 'PHPEGG';
}
}
<file_sep><?php
return [
'smtp' => [
'driver' => 'smtp',
// (可选配置)发件人信息
'from' => ['<EMAIL>', 'your_name'],
// 服务器地址
'host' => 'ssl://smtp.example.com',
// 服务器端口
'port' => '465',
// 用户名
'username' => 'your_username',
// 用户密码
'password' => '<PASSWORD>',
],
'mailgun' => [
'driver' => 'mailgun',
// 'from' => ['<EMAIL>', 'your_name'],
// mailgun domain配置
'domain' => 'your_domain',
// mailgun Authorization key配置
'acckey' => 'your_acckey',
],
'sendcloud' => [
'driver' => 'sendcloud',
// 'from' => ['<EMAIL>', 'your_name'],
// sendcloud apiUser
'acckey' => 'your_acckey',
// sendcloud apiKey
'seckey' => 'your_seckey'
],
'sendmail' => [
'driver' => 'sendmail',
// 'from' => ['<EMAIL>', 'your_name'],
// (可选配置)sendmail路径
//'sendmail_path'=> null,
]
];<file_sep><?php
namespace framework\driver\cache;
use framework\core\Container;
/*
* key char(128) NOT NULL PRIMARY KEY
* value BLOB
* expiration int(11)
*/
class Db extends Cache
{
// 数据库实例
protected $db;
// 数据表名
protected $table = 'cache';
// 数据表字段名
protected $fields = ['key', 'value', 'expiration'];
// 序列化反序列化处理器
protected $serializer = ['serialize', 'unserialize'];
/*
* 初始化
*/
public function __construct($config)
{
parent::__construct($config);
if (isset($config['table'])) {
$this->table = $config['table'];
}
if (isset($config['fields'])) {
$this->fields = $config['fields'];
}
if (isset($config['serializer'])) {
$this->serializer = $config['serializer'];
}
$this->db = Container::driver('db', $config['db']);
}
/*
* 获取
*/
public function get($key, $default = null)
{
$cache = $this->db->get($this->format(
'SELECT %s FROM %s WHERE %s = ? AND %s > '.time(), $this->fields[1], $this->table, $this->fields[0], $this->fields[2]
), [$key]);
return $cache ? ($this->serializer[1])($cache[0]['value']) : $default;
}
/*
* 检查
*/
public function has($key)
{
return $this->db->query($this->format(
'SELECT %s FROM %s WHERE %s = ? AND %s > '.time(), $this->fields[1], $this->table, $this->fields[0], $this->fields[2]
), [$key])->count() > 0;
}
/*
* 设置
*/
public function set($key, $value, $ttl = null)
{
return (bool) $this->db->exec($this->format(
'REPLACE INTO %s SET %s = ?, %s = ?, %s = ?', $this->table, ...$this->fields
), [
$key, ($this->serializer[0])($value), time() + (($t = $this->ttl($ttl)) == 0 ? $this->gc_maxlife : $t)
]);
}
/*
* 删除
*/
public function delete($key)
{
return (bool) $this->db->exec($this->format('DELETE FROM %s WHERE %s = ?', $this->table, $this->fields[0]), [$key]);
}
/*
* 自增
*/
public function increment($key, $value = 1)
{
return $this->set($key, $this->get($key, 0) + $value);
}
/*
* 自减
*/
public function decrement($key, $value = 1)
{
return $this->set($key, $this->get($key, 0) - $value);
}
/*
* 获取多个
*/
public function getMultiple(array $keys, $default = null)
{
$in = implode(',', array_fill(0, count($keys), '?'));
$reslut = $this->db->find($this->format(
"SELECT %s, %s FROM %s WHERE %s IN ($in) AND %s > ".time(),
$this->fields[0], $this->fields[1], $this->table, $this->fields[0], $this->fields[2]
), $keys);
$caches = array_column($reslut, 'value', 'key');
foreach ($keys as $key) {
$caches[$key] = isset($caches[$key]) ? ($this->serializer[1])($caches[$key]) : $default;
}
return $caches;
}
/*
* 删除多个
*/
public function deleteMultiple(array $keys)
{
$in = implode(',', array_fill(0, count($keys), '?'));
return (bool) $this->db->exec($this->format("DELETE FROM %s WHERE %s IN ($in)", $this->table. $this->fields[0]), $keys);
}
/*
* 清理
*/
public function clear()
{
return (bool) $this->db->exec($this->format('TRUNCATE %s', $this->table));
}
/*
* 垃圾回收
*/
public function gc()
{
$this->db->exec($this->format('DELETE FROM %s WHERE %s < '.time(), $this->table, $this->fields[2]));
}
/*
* sql格式化
*/
protected function format($sql, ...$params)
{
return sprintf($sql, ...array_map(function ($v) {
return ($this->db::Builder)::keywordEscape($v);
}, $params));
}
}
<file_sep><?php
namespace framework\driver\db;
class Mysql extends Pdo
{
// 构造器
const BUILDER = builder\Builder::class;
/*
* 获取dsn
*/
protected function getDsn($config)
{
$dsn = 'mysql:dbname='.$config['dbname'];
if (isset($config['host'])) {
$dsn .= ';host='.$config['host'];
if (isset($config['port'])) {
$dsn .= ';port='.$config['port'];
}
} elseif (isset($config['socket'])) {
$dsn .= ';unix_socket='.$config['socket'];
}
if (isset($config['charset'])) {
$dsn .= ';charset='.$config['charset'];
}
return $dsn;
}
/*
* 获取表字段名
*/
protected function getFields($table)
{
return array_column($this->select("desc `$table`"), 'Field');
}
}
<file_sep><?php
namespace app\auth;
use framework\App;
use framework\core\Auth;
use framework\core\http\Request;
use framework\core\http\Response;
class Jwt extends Auth
{
private $alg = 'HS256';
private $key = '1234567890';
public function __construct($config)
{
$auth = Request::header('Authorization');
if ($auth) {
$pair = explode(' ', $auth);
if (isset($pair[1])) {
$value = explode('.', $pair[1]);
if (count($value) === 3 && hash_hmac($value[0].'.'.$value[1], $this->alg) === $value[2]) {
$this->playload = json_decode(base64_decode($value[1]));
}
}
}
}
protected function check()
{
return isset($this->playload);
}
protected function user()
{
return $this->playload;
}
protected function faildo()
{
Response::status(403);
App::exit();
}
protected function login($params)
{
$header = base64_encode(json_encode(['typ' => 'JWT','alg' => $this->alg]));
$playload = base64_encode(json_encode($params));
$signature = hash_hmac("$header.$playload", $this->alg);
Response::send("$header.$playload.$signature");
}
protected function logout() {}
}
<file_sep><?php
namespace framework\driver\db;
use framework\util\Str;
use framework\core\Logger;
use framework\core\Container;
abstract class Db
{
// SQL纪录
protected $sql;
// 调试模式
protected $debug = \app\env\APP_DEBUG;
// 数据库名
protected $dbname;
// 数据库连接
protected $connection;
// 数据库表字段
protected $fields;
/*
* 读取语句返回一条数据
*/
abstract public function get($sql);
/*
* 读取语句返回全部数据
*/
abstract public function find($sql);
/*
* 更新语句返回影响数量
*/
abstract public function exec($sql);
/*
* 读取语句返回结果对象
*/
abstract public function query($sql);
/*
* 最近插入数据ID
*/
abstract public function insertId();
/*
* 开始事务
*/
abstract public function beginTransaction();
/*
* 回滚事务
*/
abstract public function rollback();
/*
* 提交事务
*/
abstract public function commit();
/*
* 转义字符串
*/
abstract public function quote($str);
/*
* 获取错误代码
*/
abstract public function errno();
/*
* 获取错误信息
*/
abstract public function error();
/*
* 构造函数
*/
public function __construct($config)
{
$this->connection = $this->connect($config);
$this->dbname = $config['dbname'];
if (isset($config['debug'])) {
$this->debug = $config['debug'];
}
}
/*
* 魔术方法,query实例
*/
public function __get($name)
{
return $this->table($name);
}
/*
* query实例
*/
public function table($name)
{
return new query\Query($this, $name);
}
/*
* 执行事务
*/
public function transaction(callable $call)
{
try {
$this->beginTransaction();
($return = $call($this)) === false ? $this->commit() : $this->rollback();
return $return;
} catch (\Throwable $e) {
$this->rollback();
throw $e;
}
}
/*
* 获取表字段
*/
public function fields($table)
{
return $this->fields[$this->dbname][$table] ?? $this->fields[$this->dbname][$table] = $this->getFields($table);
}
/*
* 设置调试模式
*/
public function debug($bool = true)
{
$this->debug = $bool;
}
/*
* 获取数据Builder类
*/
public function getBuilder()
{
return static::BUILDER;
}
/*
* 获取数据库连接
*/
public function getConnection()
{
return $this->connection;
}
/*
* 日志
*/
protected function sqlLog($sql, $params = null)
{
if ($this->debug) {
if ($params) {
if (isset($params[0])) {
$sql = vsprintf(str_replace("?", "'%s'", $sql), $params);
} else {
$sql = Str::format($sql, $params, ':%s');
}
}
//Logger::channel($this->debug)->debug($sql);
}
}
}<file_sep><?php
namespace framework\core\app;
use framework\App;
use framework\core\Getter;
use framework\core\Command;
use framework\core\Dispatcher;
class Cli extends App
{
protected $config = [
// 控制器namespace
'controller_ns' => 'command',
// 控制器类名后缀
'controller_suffix' => null,
// 闭包绑定的类(为true时绑定匿名类)
'closure_bind_class' => true,
// Getter providers(绑定getter匿名类时有效)
'closure_getter_providers' => null,
// 默认调度的控制器,为空不限制
'default_dispatch_controllers' => null,
// 默认调度的控制器别名
'default_dispatch_controller_alias' => null,
// 默认调用的方法,空则调用__invoke
'default_dispatch_method' => null,
];
// 核心错误
protected $core_errors = [
404 => 'Bad Request',
404 => 'Method not found',
500 => 'Internal Server Error',
];
// 控制器实例
protected $instance;
// 自定义方法集合
protected $custom_methods;
/*
* 设置命令行调用
*/
public function command($name, $call = null)
{
if ($call !== null) {
$this->custom_methods['commands'][$name] = $call;
} elseif (is_array($name)) {
if (isset($this->custom_methods['commands'])) {
$this->custom_methods['commands'] = $name + $this->custom_methods['commands'];
} else {
$this->custom_methods['commands'] = $name;
}
} else {
$this->custom_methods['command'] = $name;
}
return $this;
}
/*
* 调度
*/
protected function dispatch()
{
if (!App::IS_CLI) {
throw new \RuntimeException('NOT CLI SAPI');
}
$arguments = $this->parseArguments();
if ($this->custom_methods) {
$call = $this->customDispatch($arguments);
} else {
$call = $this->defaultDispatch($arguments);
}
if ($call) {
return $this->dispatch = [
'call' => $call,
'params' => $arguments['params'] ?? [],
];
}
}
/*
* 调用
*/
protected function call()
{
return $this->dispatch['call'](...$this->dispatch['params']);
}
/*
* 默认调度
*/
protected function defaultDispatch($arguments)
{
if (empty($arguments['params'])) {
return;
}
$controller = strtr(array_shift($arguments['params']), ':', '\\');
if (isset($this->config['default_dispatch_controller_alias'][$controller])) {
$controller = $this->config['default_dispatch_controller_alias'][$controller];
} elseif (!isset($this->config['default_dispatch_controllers'])) {
$check = true;
} elseif (!in_array($controller, $this->config['default_dispatch_controllers'])) {
return;
}
if ($class = $this->getControllerClass($controller, isset($check))) {
return $this->getDispatchCall(new $class($arguments));
}
}
/*
* 自定义调度
*/
protected function customDispatch(&$arguments)
{
if (isset($this->custom_methods['command'])) {
$call = $this->custom_methods['command'];
} else {
if (empty($arguments['params'])) {
return;
}
$name = array_shift($arguments['params']);
if (empty($this->custom_methods['commands'][$name])) {
return;
}
$call = $this->custom_methods['commands'][$name];
}
if ($call instanceof \Closure) {
if ($class = $this->config['closure_bind_class']) {
if ($class === true) {
$instance = new class ($this->config['closure_getter_providers'], $arguments) extends Command {
use Getter;
public function __construct($providers, $arguments) {
$this->{\app\env\GETTER_PROVIDERS_NAME} = $providers;
parent::__construct($arguments);
}
};
} else {
$instance = new $class($arguments);
}
} else {
$instance = new class ($arguments) extends Command {};
}
return \Closure::bind($call, $instance, Command::class);
} elseif (is_string($call)) {
$call = Dispatcher::parseDispatch($call);
if ($this->config['controller_ns']) {
$call = $this->getControllerClass($call);
}
return $this->getDispatchCall(new $call($arguments));
}
}
/*
* 错误
*/
protected function error($code = null, $message = null)
{
$command = $this->instance ?? new Command;
$command->error("[$code]");
$command->highlight(is_array($message) ? var_dump($message, true) : $message);
}
/*
* 响应
*/
protected function respond($return = null)
{
self::exit(2);
//exit((int) $return);
}
/*
* 解析命令行参数
*/
protected function parseArguments()
{
$argv = $_SERVER['argv'];
App::setPath(array_shift($argv));
$count = count($argv);
$last_option = null;
for ($i = 0; $i < $count; $i++) {
if (strpos($argv[$i], '-') !== 0) {
if ($last_option) {
$arguments["$last_option[0]_options"][$last_option[1]] = $argv[$i];
$last_option = null;
} else {
$arguments['params'][] = $argv[$i];
}
} else {
$last_option = null;
if (strpos($argv[$i], '--') === 0) {
if ($option_name = substr($argv[$i], 2)) {
if (strpos($option_name, '=') > 0) {
list($k, $v) = explode('=', $option_name, 2);
$arguments['long_options'][$k] = $v;
} else {
$arguments['long_options'][$option_name] = true;
$last_option = ['long', $option_name];
}
}
} else {
if ($option_name = substr($argv[$i], 1)) {
if (isset($option_name[1])) {
$arguments['short_options'][$option_name[0]] = substr($option_name, 1);
} elseif (isset($option_name[0])) {
$arguments['short_options'][$option_name] = true;
$last_option = ['short', $option_name];
}
}
}
}
}
return $arguments ?? [];
}
/*
* 获取 call
*/
protected function getDispatchCall($call)
{
$this->instance = $call;
return $this->config['default_dispatch_method'] ? [$call, $this->config['default_dispatch_method']] : $call;
}
}
<file_sep><?php
namespace framework\exception;
class Exception extends \Exception
{
protected $data;
protected $class;
public function __construct($message, $class = null, $data = null)
{
$this->data = $data;
$this->class = $class;
$this->message = $message;
}
public static function export($message, $data)
{
return new self($message.var_export($data, true));
}
public function getData()
{
return $this->data;
}
public function getClass()
{
return $this->class ?? __CLASS__;
}
}
<file_sep><?php
namespace app\logic;
class User
{
use \Getter;
public function getNameById($id)
{
return $this->db->user->select('name')->get($id);
}
}
<file_sep><?php
namespace app\env;
// 开启严格错误模式
const STRICT_ERROR_MODE = true;
// 配置文件目录
const CONFIG_DIR = APP_DIR.'config/';
// 单一配置文件,如存在配置目录则忽略
//const CONFIG_FILE = APP_DIR.'config.php';
// composer vendor目录
const VENDOR_DIR = ROOT_DIR.'vendor/';
// 设置Getter providers属性名
const GETTER_PROVIDERS_NAME = 'providers';
<file_sep><?php
namespace framework\driver\db\query;
class Join extends QueryChain
{
// 当前表名
protected $cur;
// 关联设置
protected $join = [];
// 多关联表设置项
protected $table_options = [];
// 支持关联类型
protected static $join_type = ['INNER', 'LEFT', 'RIGHT'];
/*
* 初始化
*/
protected function __init($table, $options, $join, $prefix = true, $type = 'LEFT')
{
if (!in_array($type, self::$join_type)) {
throw new \Exception("Join Type Error: $type");
}
$this->cur = $join;
$this->table = $table;
$this->join[$join] = ['type' => $type];
$options['prefix'] = false;
if (!isset($options['fields'])) {
$options['fields'] = null;
}
$this->options = ['prefix' => $prefix, 'fields' => null];
$this->table_options[$table] = $options;
}
/*
* 设置关联表
*/
public function join($join, $prefix = true, $type = 'LEFT')
{
if (!in_array($type, self::$join_type)) {
throw new \Exception("Join Type Error: $type");
}
$this->table_options[$this->cur] = $this->options;
$this->cur = $join;
$this->options = ['prefix' => $prefix, 'fields' => null];
$this->join[$join] = ['type' => $type];
return $this;
}
/*
* 设置关联表字段关联
*/
public function on($field1, $field2)
{
$this->join[$this->cur]['on'] = array($field1, $field2);
return $this;
}
/*
* 查询(单条)
*/
public function get($id = null, $pk = 'id')
{
if (isset($id)) {
$this->table_options[$this->table]['where'] = [[$pk, '=', $id]];
}
$this->table_options[$this->cur] = $this->options;
return $this->db->get(...$this->build());
}
/*
* 查询(多条)
*/
public function find()
{
$this->table_options[$this->cur] = $this->options;
return $this->db->find(...$this->build());
}
/*
* 生成 sql
*/
protected function build()
{
$limit = 0;
$order = [];
$where = [];
$group = [];
$having = [];
$fields = [];
$params = [];
foreach ($this->table_options as $table => $options) {
foreach ($options as $name => $value) {
switch ($name) {
case 'fields':
if ($value !== [false]) {
$fields = array_merge($fields, $this->buildField($table, $value, $options['prefix']));
}
break;
case 'where':
if ($value) {
$where[] = $this->builder::whereClause($value, $params, $table);
}
break;
case 'group':
$group = [$value, $table];
break;
case 'having':
$having[] = $this->builder::havingClause($value, $params, $table);
break;
case 'order':
foreach ($value as $v) {
$v[] = $table;
$order[] = $v;
}
break;
case 'limit':
$limit = $value;
break;
}
}
}
$sql = 'SELECT '.implode(',', $fields).' FROM '.$this->builder::quoteField($this->table);
foreach ($this->join as $table => $join) {
$sql .= " {$join['type']} JOIN ".$this->builder::quoteField($table).' ON ';
if (isset($join['on'])) {
$sql .= $this->builder::quoteTableField($this->table, $join['on'][0])
. ' = '.$this->builder::quoteTableField($table, $join['on'][1]);
} else {
$sql .= $this->builder::quoteTableField($this->table, 'id')
. ' = '.$this->builder::quoteTableField($table, "{$this->table}_id");
}
}
if ($where) {
$sql .= ' WHERE '.implode(' AND ', $where);
}
if ($group) {
$sql .= $this->builder::groupClause(...$group);
}
if ($having) {
$sql .= ' HAVING '.implode(' AND ', $having);
}
if ($order) {
$sql .= $this->builder::orderClause($order);
}
if ($limit) {
$sql .= $this->builder::limitClause($limit);
}
return [$sql, $params];
}
/*
* 生成 字段sql
*/
protected function buildField($table, $value, $prefix)
{
if ($prefix) {
if ($prefix === true) {
$prefix = $table;
}
if (!$value) {
foreach ($this->db->fields($table) as $field) {
$fields[] = $this->builder::quoteTableField($table, $field).' AS '
. $this->builder::quoteField("{$prefix}_$field");
}
} else {
foreach ($value as $field) {
if (is_array($field)) {
$fields[] = $this->buildFieldItem($field, $table);
} else {
$fields[] = $this->builder::quoteTableField($table, $field).' AS '
. $this->builder::quoteField("{$prefix}_$field");
}
}
}
} else {
if ($value) {
foreach ($value as $field) {
if (is_array($field)) {
$fields[] = $this->buildFieldItem($field, $table);
} else {
$fields[] = $this->builder::quoteTableField($table, $field);
}
}
} else {
$fields[] = $this->builder::quoteField("$table").".*";
}
}
return $fields;
}
/*
* 生成 字段sql单元
*/
protected function buildFieldItem(array $field, $table)
{
$count = count($field);
if ($count === 2) {
return $this->builder::quoteTableField($table, $field[0]).' AS '.$this->builder::quoteField($field[1]);
} elseif ($count === 3){
$field1 = $field[1] === '*' ? '*' : $this->builder::quoteField($field[1]);
return "$field[0](".$this->builder::quoteField($table).".$field1) AS ".$this->builder::quoteField($field[2]);
}
throw new \Exception('Join Field ERROR: '.var_export($field, true));
}
}
<file_sep><?php
namespace app\hook;
use framework\core\http\Request;
use framework\core\http\Response;
class Redirect
{
public static function run()
{
if (!Request::isHttps()) {
Response::redirect('https://'.Request::url(), true);
}
}
}
<file_sep><?php
namespace app\library;
use framework\App;
use framework\core\View;
use framework\core\Loader;
use framework\core\http\Request;
use framework\core\http\Response;
class MyApp extends App
{
protected $config = [
// 控制器namespace
'controller_ns' => 'controller',
];
protected function dispatch()
{
// 从Url Query中获取请求控制器类与方法名
$action = Request::get('a', 'index');
$controller = Request::get('c', 'home');
$class = 'app\\'.$this->config['controller_ns'].'\\'.$controller;
// 检查控制器类与方法是否合法
if (substr($action, 0, 1) !== '_' && Loader::importPrefixClass($class)) {
$controller_instance = new $class;
// 检查控制器方法是否可用
if (is_callable([$controller_instance, $action])) {
return compact('action', 'controller', 'controller_instance');
}
}
return false;
}
protected function call()
{
// 执行控制器方法
return $this->dispatch['controller_instance']->{$this->dispatch['action']}();
}
protected function error($code = 500, $message = null)
{
// 输出视图error页面
Response::send(View::error($code, $message), 'text/html; charset=UTF-8', false);
}
protected function response($return)
{
// 输出视图页面
Response::view('/'.$this->dispatch['controller'].'/'.$this->dispatch['action'], $return);
}
}
<file_sep><?php
namespace framework\core\http;
use framework\App;
use framework\util\File;
use framework\core\View;
use framework\core\Event;
class Response
{
private static $init;
// 响应内容
private static $response;
/*
* 初始化
*/
public static function __init()
{
if (self::$init) {
return;
}
self::$init = true;
self::$response = new \stdClass();
Event::on('app.flush', [__CLASS__, 'flush']);
}
/*
* 设置响应状态码
*/
public static function code($code = 200)
{
self::$response->code = $code;
}
/*
* 设置响应单个header头
*/
public static function header($name, $value)
{
self::$response->headers[$name] = $value;
}
/*
* 设置响应多个header头
*/
public static function headers(array $headers)
{
if (isset(self::$response->headers)) {
self::$response->headers = $headers + self::$response->headers;
} else {
self::$response->headers = $headers;
}
}
/*
* 设置响应cookie
*/
public static function cookie(
$name, $value, $lifetime = null, $path = null, $domain = null, $secure = null, $httponly = null, $samesite = null
) {
self::$response->cookies[$name] = func_get_args();
}
/*
* 设置响应body内容,追加写入
*/
public static function wirte($body)
{
self::$response->body = isset(self::$response->body) ? self::$response->body.$body : $body;
}
/*
* 设置视图响应
*/
public static function view($tpl, $vars = null)
{
self::html(View::render($tpl, $vars));
}
/*
* 设置响应html
*/
public static function html($html)
{
self::send($html, 'text/html; charset=UTF-8');
}
/*
* 设置响应json格式化数据
*/
public static function json($data)
{
self::send(json_encode($data, JSON_UNESCAPED_UNICODE), 'application/json; charset=UTF-8');
}
/*
* 设置文件输出
*/
public static function file($file, $type = null)
{
self::$response->body = null;
self::$response->headers['Content-Length'] = filesize($file);
self::$response->headers['Content-Type'] = $type ?? File::mime($file);
self::flush();
readfile($file);
App::exit();
}
/*
* 设置响应body内容
*/
public static function send($body = null, $type = null)
{
if (isset($body)) {
self::$response->body = $body;
}
if (isset($type)) {
self::$response->headers['Content-Type'] = $type;
}
App::exit();
}
/*
* 设置响应重定向
*/
public static function redirect($url, $permanently = false)
{
self::$response->code = $permanently ? 301 : 302;
self::$response->headers['Location'] = $url;
self::$response->body = null;
App::exit();
}
/*
* 设置文件下载
*/
public static function download($file, $name = null, $is_buffer = false)
{
if (!$is_buffer) {
self::$response->headers['Content-Disposition'] = 'attachment; filename="'.($name ?? basename($file)).'"';
return self::file($file);
} else {
self::$response->headers['Content-Length'] = strlen($file);
self::$response->headers['Content-Disposition'] = 'attachment; filename="'.$name.'"';
return self::send($file, File::mime($file, true) ?: 'application/octet-stream');
}
}
/*
* 输出响应
*/
public static function flush()
{
if (isset(self::$response->code)) {
http_response_code(self::$response->code);
}
if (isset(self::$response->headers)) {
foreach (self::$response->headers as $k => $v) {
header("$k: $v");
}
}
if (isset(self::$response->cookies)) {
foreach (self::$response->cookies as $v) {
Cookie::setCookie(...$v);
}
}
if (isset(self::$response->body)) {
echo self::$response->body;
}
self::$response = null;
}
}
Response::__init();
<file_sep>文档
---
http://www.phpegg.com
简介
----
PHPEGG是一个轻量但功能丰富的PHP框架,支持`Standard` `Rest` `Micro` `Inline` `Jsonrpc` `Grpc`等应用模式,包含`配置` `类加载` `事件` `容器` `路由` `日志` `错误处理`等核心功能,并集成了`数据库` `缓存` `存储 ` `RPC` `邮件` `短信`等多种功能驱动,而且框架耦合度低,模块之间依赖低,框架初始化只加载少量核心PHP文件,用户完全可以根据自己的需求定制一个灵活 高性能 并且功能丰富的应用框架。
应用模式
----
- **Standard** 默认推荐的标准`MVC`应用模式,适用于网页和接口开发。
- **Rest** `RESTful`风格模式,适用于开发`RESTful`风格的`API`接口。
- **Inline** 内联调用控制器文件面向过程代码,快捷高效。
- **Micro** 微框架模式,提供基本接口方法,灵活高效。
- **Jsonrpc** 基于`jsonrpc`协议的无`scheme`RPC应用。
- **Grpc** 基于`grpc`协议的有`scheme`(使用`protobuf`定义)RPC应用。
- **View** 视图驱动`View<->ViewModel<->Model`模式(未完成)。
- **Cli** 命令行模式,用于命令行工具 计划任务 守护进程等(未完成)。
- **自定义应用** 继承`App`基类,实现约定接口方法,自建应用模式类。
- **无模式应用** 不使用任何应用模式,使用原生多入口方式开发应用。
>另外为了实现不同模式应用之间的相互调用,框架在`rpc`驱动中实现了一套`rpc client`来远程调用服务。
核心功能
----
- **Config** 配置处理
- **Loader** 类加载处理
- **Hook** 事件处理
- **Error** 错误处理
- **Logger** 日志处理
- **Router** 路由处理
- **Container** 容器
- **View** 视图
- **Template** 模版
- **Validator** 验证器
- **Auth** 认证处理
HTTP层
----
- **Client** HTTP请求客户端
- **Request** HTTP请求信息
- **Response** HTTP响应处理
- **Cookie & Session**
功能驱动
----
- `db` 数据库
| 驱动 | 描述
| ----|----
|Mysqli | 基于php mysqli扩展,支持一些特有的mysql方法
|Mysql | 基于php pdo_mysql扩展
|Pgsql | 基于php pdo_pgsql扩展(粗略测试)
|Sqlite | 基于php pdo_sqlite扩展(粗略测试)
|Sqlsrv | 在win系统下使用pdo_sqlsrv扩展,类unix系统下使用pdo_odbc扩展(无环境,未测试)
|Oracle | 基于php pdo_oci扩展(无环境,未测试)
|Cluster | 基于Mysqli,支持设置多个数据库服务器,实现读写分离主从分离,原理是根据SQL的SELECT INSERT等语句将请求分配到不同的服务器。(无环境,未测试)
- `cache` 缓存
| 驱动 | 描述
| ----|----
|Apc | 基于php apcu扩展的单机共享内存缓存
|Db | 使用关系数据库缓存数据
|File | 使用文件保存缓存数据
|Memcached | 使用Memcached服务缓存数据
|Opcache | 将缓存数据写入php文件,使用php Opcache来缓存数据
|Redis | 使用Redis服务缓存数据
- `storage` 存储
| 驱动 | 描述
| ----|----
|Local | 本地文件处理简单适配封装
|Ftp | 基于ftp协议,需要php ftp扩展
|Sftp | 基于ssh协议,需要php ssh2扩展
|S3 | 亚马逊s3服务
|Oss | 阿里云oss服务
|Qiniu | 七牛云存储
|Webdav | 基于Webdav协议,兼容多种网盘,如Box OneDrive Pcloud 坚果云
- `logger` 日志
| 驱动 | 描述
| ----|----
|WebConsole | 日志发送到浏览器控制台,支持Firefox,Chrome(需安装[chromelogger](https://github.com/qiu-jin/chromelogger)插件)
|Email | 日志发送到邮件
|File | 日志写入文件
|Queue | 日志发送到队列(坑)
- `rpc` RPC
| 驱动 | 描述
| ----|----
|Jsonrpc | Jsonrpc协议rpc客户端
|Http | rpc调用风格的httpClient封装
|Rest | rpc调用风格的Rest httpClient封装
|Thrift | Thrift rpc客户端
|Grpc | Grpc rpc客户端
- `email` 邮件
| 驱动 | 描述
| ----|----
|Smtp | 基于Smtp协议发送邮件
|Sendmail | 使用php mail函数发送邮件(服务器需已装postfix等邮件服务器并已开放相应端口)
|Mailgun | 使用Mailgun提供的邮件发送服务
|Sendcloud | 使用Sendcloud提供的邮件发送服务
- `sms` 短信
| 驱动 | 描述
| ----|----
|Alidayu | 阿里大于短信服务
|Aliyun | 阿里云短信服务(暂无企业账户,未测试)
|Baidu | 百度云短信服务(暂无企业账户,未测试)
|Qcloud | 腾讯云短信服务
|Yuntongxun | 容联云通讯短信服务
- `captcha` 验证码
| 驱动 | 描述
| ----|----
|Image | 使用gregwar/captcha包
|Recaptcha | google recaptcha
|Geetest | 极验验证
- `geoip` IP定位
| 驱动 | 描述
| ----|----
|Baidu | Baidu地图IP定位接口,优点几乎不限请求,缺点无法定位国外ip
|Ipip | Ipip IP定位,有在线api接口和离线数据库两种使用方式
|Maxmind | Maxmind IP定位,有在线api接口和离线数据库两种使用方式
- `crypt` 加解密
| 驱动 | 描述
| ----|----
|Openssl | 基于php openssl扩展
|Sodium | 基于php libsodium扩展
- `search` 搜索
| 驱动 | 描述
| ----|----
|Elastic | 基于Elastic rest接口 (待完善)
- `data` 非关系数据库
| 驱动 | 描述
| ----|----
|Cassandra | 使用datastax扩展(坑)
|Mongo | 使用MongoDB扩展(待完善)
|Hbase | 使用Thrift Rpc客户端(坑)
- `queue` 队列
| 驱动 | 描述
| ----|----
|Redis | 使用redis list类型实现简单队列(坑)
|Amqp | 基于Amqp协议RabbitMQ服务(坑)
|Beanstalkd | pda/pheanstalk包(坑)
|Kafka | php-rdkafka扩展(坑)
<file_sep><?php
return [
'elastic' => [
'driver' => 'elastic',
'endpoint' => 'http://127.0.0.1'
]
];
<file_sep><?php
namespace framework\core;
abstract class Model implements ArrayAccess
{
protected static $db;
public static function __init()
{
if (self::$init) {
return;
}
self::$init = true;
$config = Config::get('model');
self::$db = Container::driver('db', $config['db'] ?? null);
}
public static function name($table)
{
return new static();
}
public static function __callStatic($method, $params)
{
return (new static())->__call($method, $params);
}
public function __construct($data = null)
{
$this->__invoke($data);
}
public function __invoke($data = null)
{
}
public function __call($method, $params)
{
self::$db->model($this)->$method(...$params);
}
public function __get()
{
}
public function __set()
{
}
public function __isset()
{
}
public function __unset()
{
}
public function offsetExists($offset)
{
}
public function offsetGet($offset)
{
}
public function offsetSet($offset, $value)
{
}
public function offsetUnset($offset)
{
}
public function save($data = null)
{
}
}
Model::__init();
<file_sep><?php
namespace framework\driver\db\result;
class Pdo
{
// 原始query
protected $query;
/*
* 构造函数
*/
public function __construct(\PDOStatement $query)
{
$this->query = $query;
}
/*
* 获取数据条数
*/
public function count()
{
return $this->query->rowCount();
}
/*
* 获取一条数据
*/
public function fetch()
{
return $this->query->fetch(\PDO::FETCH_ASSOC);
}
/*
* 获取一条数据(无字段键)
*/
public function fetchRow()
{
return $this->query->fetch(\PDO::FETCH_NUM);
}
/*
* 获取一条数据(object)
*/
public function fetchObject($class_name = 'stdClass', array $ctor_args = null)
{
return $this->query->fetchObject($class_name, $ctor_args);
}
/*
* 获取所有数据
*/
public function fetchAll()
{
return $this->query->fetchAll(\PDO::FETCH_ASSOC);
}
}<file_sep><?php
namespace framework\core;
use framework\App;
abstract class Auth
{
private static $init;
// 认证实例
private static $auth;
// 用户信息
protected $user;
/*
* 验证用户
*/
abstract protected function auth();
/*
* 用户认证失败后续操作
*/
abstract protected function fallback();
/*
* 登记用户信息
*/
abstract protected function login($user);
/*
* 注销用户信息
*/
abstract protected function logout();
/*
* 初始化
*/
public static function __init()
{
if (self::$init) {
return;
}
self::$init = true;
$config = Config::read('auth');
if (!is_subclass_of($config['class'], __CLASS__)) {
throw new Exception('Illegal auth class');
}
self::$auth = instance($config['class'], $config);
}
/*
* 静态调用
*/
public static function __callStatic($method, $params)
{
return self::$auth->$method(...$params);
}
/*
* 获取用户信息
*/
public static function user()
{
return self::$auth->user ?? self::$auth->user = self::$auth->auth();
}
/*
* 检查用户认证
*/
public static function check()
{
return bool self::user();
}
/*
* 运行认证处理,检查用户是否认证成功,否则失败处理并退出
*/
public static function run()
{
$this->check() || self::$auth->fallback() === true || App::exit();
}
/*
* 设置用户信息
*/
public static function set($user)
{
self::$auth->user = $user;
}
/*
* 注释用户信息
*/
public static function unset()
{
self::$auth->user = null;
}
}
Auth::__init();
<file_sep><?php
namespace app\hook;
class RequestTrim
{
public static function run($request)
{
self::trim($request->get);
self::trim($request->post);
}
private static function trim(&$array)
{
if (is_array($array)) {
foreach ($array as $k => $v) {
$array[$k] = self::trim($v);
}
} else if (is_string($array)) {
$array = trim($array);
}
}
}
<file_sep><?php
namespace framework\exception;
class ViewException extends \Exception {}
<file_sep><?php
namespace framework;
use framework\core\Error;
use framework\core\Event;
use framework\core\Config;
use framework\core\http\Request;
abstract class App
{
// 框架版本号
const FW_VERSION = '1.0.0';
// 是否命令行环境
const IS_CLI = PHP_SAPI === 'cli';
// 内置应用模式
const MODES = ['Standard', 'Resource', 'Micro', 'Cli'/*, 'Inline', 'Jsonrpc', 'Grpc'*/];
// 应用实例
private static $app;
// boot标示,防止重复执行
private static $boot;
/* 标示退出状态
* 0 未标识退出
* 1 用户强制退出,使用exit
* 2 请求完成并退出
* 3 错误退出
* 4 异常退出
* 5 致命错误退出
*/
private static $exit;
// runing标示,防止重复执行
private static $runing;
// 请求路径
private static $path;
// 错误处理器
private static $error_handler;
// 返回值处理器
private static $return_handler;
// 应用配置项
protected $config;
// 应用调度结果
protected $dispatch;
/*
* 应用调度
*/
abstract protected function dispatch();
/*
* 调用应用
*/
abstract protected function call();
/*
* 错误处理
*/
abstract protected function error($code, $message);
/*
* 响应处理
*/
abstract protected function respond($return);
/*
* 构造函数,合并配置项
*/
private function __construct($config)
{
if ($config) {
$this->config = $config + $this->config;
}
}
/*
* 应用环境初始化
*/
public static function boot()
{
if (self::$boot) {
return;
}
self::$boot = true;
class_alias(__CLASS__, 'App');
define('FW_DIR', __DIR__.'/');
if (!defined('APP_DIR')) {
if (self::IS_CLI) {
define('APP_DIR', dirname(realpath($_SERVER['argv'][0]), 2).'/');
} else {
define('APP_DIR', dirname($_SERVER['DOCUMENT_ROOT']).'/');
}
}
require FW_DIR.'common.php';
require FW_DIR.'core/Config.php';
require FW_DIR.'core/Loader.php';
set_error_handler(function(...$e) {
Error::errorHandler(...$e);
});
set_exception_handler(function($e) {
Error::exceptionHandler($e);
});
register_shutdown_function(function() {
try {
if (!isset(self::$exit)) {
Error::fatalHandler();
}
Event::trigger('app.exit');
Event::trigger('app.flush');
if (Event::has('app.close')) {
if (function_exists('fastcgi_finish_request')) {
fastcgi_finish_request();
}
Event::trigger('app.close');
}
} catch (\Throwable $e) {
Error::exceptionHandler($e);
}
});
Event::trigger('app.boot');
}
/*
* 启动应用,应用调度成功返回一个应用实例,否则调用abort终止应用
*/
public static function start($app = 'Standard', $config = 'app')
{
if (self::$app) {
return;
}
if (in_array($app, self::MODES)) {
$app = "framework\core\app\\$app";
} elseif (!is_subclass_of($app, __CLASS__)) {
throw new \RuntimeException("Illegal app class: $app");
}
return self::$app = new $app(is_array($config) ? $config : Config::read($config));
}
/*
* 返回应用实例
*/
public static function instance()
{
return self::$app;
}
/*
* 运行应用
*/
public function run(callable $return_handler = null)
{
if (self::$runing) {
throw new \RuntimeException('App is runing');
}
self::$runing = true;
if (!$this->dispatch()) {
return self::abort(404);
}
$return = $this->call();
self::$exit = 2;
$handler = $return_handler ?? self::$return_handler;
if ($handler === null || $handler($return) === true) {
$this->respond($return);
}
}
/*
* 退出应用
*/
public static function exit(int $status = 1)
{
if ($status === 1) {
if (!isset(self::$exit)) {
self::$exit = 1;
exit;
}
} else {
self::$exit = $status;
}
}
/*
* 是否已退出应用
*/
public static function isExit()
{
return isset(self::$exit);
}
/*
* 异常退出应用
*/
public static function abort(...$params)
{
if (isset(self::$app)) {
if (self::$error_handler === null || self::$error_handler(...$params) === true) {
self::$app->error(...$params);
}
}
self::exit();
}
/*
* 设置应用错误处理器,由abort方法调用
*/
public static function setErrorHandler(callable $handler)
{
self::$error_handler = $handler;
}
/*
* 设置返回值处理器,由run方法调用
*/
public static function setReturnHandler(callable $handler)
{
self::$return_handler = $handler;
}
/*
* 设置路径
*/
public static function setPath($path)
{
self::$path = trim($path, '/');
}
/*
* 获取路径
*/
public static function getPath()
{
return self::$path ?? trim(rawurldecode(Request::path()), '/');
}
/*
* 获取路径数组
*/
public static function getPathArr()
{
return ($path = self::getPath()) ? explode('/', $path) : [];
}
/*
* 获取配置值
*/
public static function getConfig($name = null, $default = null)
{
return $name === null ? self::$app->config : (self::$app->config[$name] ?? $default);
}
/*
* 获取调度信息
*/
public static function getDispatch($name = null, $default = null)
{
return $name === null ? self::$app->dispatch : (self::$app->dispatch[$name] ?? $default);
}
/*
* 获取控制器类名
*/
protected function getControllerClass($controller, $check = false)
{
$class = "app\\{$this->config['controller_ns']}\\$controller";
if (isset($this->config['controller_suffix'])) {
$class .= $this->config['controller_suffix'];
}
if (class_exists($class, false)) {
return $class;
}
$file = APP_DIR.strtr($this->config['controller_ns'], '\\', '/')."/$controller.php";
if (!$check || (preg_match('/^\w+(\\\\\w+)*$/', $controller) && is_php_file($file))) {
__require($file);
return $class;
}
}
/*
* 绑定键值参数
*/
protected function bindMethodKvParams($reflection, $params, $check = false)
{
if ($reflection->getnumberofparameters() > 0) {
foreach ($reflection->getParameters() as $param) {
if (isset($params[$param->name])) {
$new_params[] = $params[$param->name];
} elseif($param->isDefaultValueAvailable()) {
$new_params[] = $param->getdefaultvalue();
} elseif ($check) {
return false;
} else {
break;
}
}
}
return $new_params ?? [];
}
}
App::boot();
<file_sep><?php
namespace framework\core;
use framework\util\Arr;
class Container
{
// Provider类型常量
const T_DRIVER = 1;
const T_MODEL = 2;
const T_SERVICE = 3;
const T_CLASS = 4;
const T_CLOSURE = 5;
protected static $init;
// 容器实例
protected static $instances;
// 容器提供者设置
protected static $providers = [
'db' => [self::T_DRIVER, 1/*是否应用于Getter(0否,1是,2是并允许属性访问驱动), 驱动类型, 默认配置项*/],
'rpc' => [self::T_DRIVER, 2],
'cache' => [self::T_DRIVER, 1],
'email' => [self::T_DRIVER],
'logger' => [self::T_DRIVER],
'service' => [self::T_SERVICE, 1/*是否应用于Getter(0否,大于0的整数为Getter层数), ...基础名称空间 */],
/*
'model' => [self::T_MODEL, 1, ],
'class' => [self::T_CLASS, 0, [类全名, ...类初始化参数(可选)]],
'closure' => [self::T_CLOSURE, 0, 匿名函数(函数执行返回实例)],
*/
];
/*
* 初始化
*/
public static function __init()
{
if (self::$init) {
return;
}
self::$init = true;
if ($config = Config::get('container')) {
if (isset($config['providers'])) {
self::$providers = $config['providers'] + self::$providers;
}
if (!empty($config['exit_event_clean'])) {
Event::on('exit', function() {
Container::clear();
if (class_exists(Facade::class, false)) {
Facade::clear();
}
});
}
}
}
/*
* 生成实例
*/
public static function make($name)
{
if (isset(self::$instances[$name])) {
return self::$instances[$name];
}
$params = explode('.', $name);
if (isset(self::$providers[$params[0]])) {
return self::$instances[$name] = self::makeProvider($params);
}
throw new \Exception("容器提供者不存在: $name");
}
/*
* 获取实例
*/
public static function get($name)
{
return self::$instances[$name] ?? null;
}
/*
* 设置实例
*/
public static function set($name, object $value)
{
self::$instances[$name] = $value;
}
/*
* 清除实例
*/
public static function clear()
{
self::$instances = null;
}
/*
* 设置规则
*/
public static function bind($name, $provider, $params = null)
{
self::$providers[$name] = $value;
}
/*
* 获取规则
*/
public static function getProvider($name)
{
return self::$providers[$name] ?? null;
}
/*
* 设置规则
*/
public static function setProvider($name, array $value)
{
self::$providers[$name] = $value;
}
/*
* 获取驱动实例
*/
public static function driver($type, $name = null)
{
if (isset(self::$providers[$type])) {
$pv = self::$providers[$type];
if (self::$providers[$type][0] !== self::T_DRIVER) {
throw new \Exception("容器非驱动类型: $type");
}
if (is_array($name)) {
return self::makeDriverInstance($pv[2] ?? $type, $name);
}
$key = $name ? "$type.$name" : $type;
return self::$instances[$key] ?? self::$instances[$key] = self::makeDriver($pv[2] ?? $type, $name ?? $pv[3] ?? null);
}
throw new \Exception("容器驱动不存在: $type");
}
/*
* 生成自定义Provider实例
*/
public static function makeCustomProvider($provider)
{
if (is_string($provider)) {
return self::make($provider);
} elseif (is_array($provider)) {
return instance(...$provider);
} elseif ($provider instanceof \Closure) {
return $provider();
}
throw new \Exception("无效的自定义Provider类型");
}
/*
* 生成Provider实例
*/
protected static function makeProvider($params)
{
$c = count($params);
$v = self::$providers[$params[0]];
switch ($v[0]) {
case self::T_DRIVER:
if ($c <= 2) {
return self::makeDriver($v[2] ?? $params[0], $v[3] ?? null);
}
break;
case self::T_SERVICE:
if ($c > 1) {
$params[0] = $v[2] ?? "app\\$params[0]";
return instance(implode('\\', $params));
}
break;
case self::T_CLASS:
if ($c == 1) {
return instance(...$v[2]);
}
break;
case self::T_CLOSURE:
if ($c == 1) {
return $v[2]();
}
break;
default:
throw new \Exception("无效的Provider类型: $v[0]");
}
throw new \Exception('生成Provider实例失败: '.implode('.', $params));
}
/*
* 生成驱动实例
*/
protected static function makeDriver($type, $index = null)
{
if ($index) {
return self::makeDriverInstance($type, Config::get("$type.$index"));
}
$config = Config::get($type);
$index = Arr::headKey($config);
$key = "$type.$index";
return self::$instances[$key] ?? self::$instances[$key] = self::makeDriverInstance($type, $config[$index]);
}
/*
* 生成驱动实例
*/
protected static function makeDriverInstance($type, $config)
{
if (isset($config['class'])) {
$class = $config['class'];
} elseif (isset($config['driver'])) {
$namespace = $config['namespace'] ?? "framework\driver\\$type";
$class = $namespace."\\".ucfirst($config['driver']);
} else {
throw new \Exception($type.'驱动没有设置实例');
}
return new $class($config);
}
}
Container::__init();
<file_sep><?php
namespace framework\driver\cache;
/*
* http://php.net/memcached
*/
class Memcached extends Cache
{
// 连接实例
protected $connection;
/*
* 构造函数
*/
public function __construct($config)
{
$this->connection = $this->contect($config);
}
/*
* 连接
*/
protected function contect($config)
{
$connection = new \Memcached;
if (isset($config['options'])) {
$connection->setOptions($config['options']);
}
if (isset($config['timeout'])) {
$connection->setOption(\Memcached::OPT_CONNECT_TIMEOUT, $config['timeout']);
}
$hosts = is_array($config['hosts']) ? $config['hosts'] : explode(',', $config['hosts']);
$port = $config['port'] ?? 11211;
foreach ($hosts as $i => $host) {
$connection->addServer($host, $port, 1);
}
if (isset($config['username']) && isset($config['password'])) {
$connection->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
$connection->setSaslAuthData($config['username'], $config['password']);
}
return $connection;
}
/*
* 获取
*/
public function get($key, $default = null)
{
if (($ret = $this->connection->get($key)) === false) {
return $default;
}
return $ret ?? $default;
}
/*
* 检查
*/
public function has($key)
{
return (bool) $this->connection->get($key);
}
/*
* 设置
*/
public function set($key, $value, $ttl = null)
{
return $this->connection->set($key, $value, $ttl ?? 0);
}
/*
* 删除
*/
public function delete($key)
{
return $this->connection->delete($key);
}
/*
* 自增
*/
public function increment($key, $value = 1)
{
return $this->connection->increment($key, $value);
}
/*
* 自减
*/
public function decrement($key, $value = 1)
{
return $this->connection->decrement($key, $value);
}
/*
* 获取多个
*/
public function getMultiple(array $keys, $default = null)
{
$values = $this->connection->getMulti($keys);
foreach ($keys as $k) {
if (!isset($values[$k])) {
$values[$k] = $default;
}
}
return $values;
}
/*
* 设置多个
*/
public function setMultiple(array $values, $ttl = null)
{
return $this->connection->setMulti($values, $this->ttl($ttl));
}
/*
* 删除多个
*/
public function deleteMultiple(array $keys)
{
return $this->connection->deleteMulti($keys);
}
/*
* 清理
*/
public function clear()
{
return $this->connection->flush();
}
/*
* 获取连接
*/
public function getConnection()
{
return $this->connection;
}
/*
* 关闭连接
*/
public function close()
{
$this->connection->quit();
}
/*
* 析构函数
*/
public function __destruct()
{
$this->close();
}
}
<file_sep><?php
namespace framework\driver\rpc\query;
/*
* https://github.com/google/protobuf
*/
class Grpc
{
// namespace
protected $ns;
// client实例
protected $client;
/*
* 构造函数
*/
public function __construct($client, $name)
{
$this->client = $client;
if (isset($name)) {
$this->ns[] = $name;
}
}
/*
* 魔术方法,设置namespace
*/
public function __get($name)
{
$this->ns[] = $name;
return $this;
}
/*
* 魔术方法,调用rpc方法
*/
public function __call($method, $params)
{
$response_message = $this->client->send(implode('\\', $this->ns), $method, ...$params);
return empty($params[1]) ? $response_message ? json_decode($response_message->serializeToJsonString(), true);
}
}<file_sep><?php
namespace framework\util;
use DateTime;
use DatePeriod;
use DateInterval;
use DateTimeZone;
use DateTimeImmutable;
use DateTimeInterface;
use framework\core\Config;
class Date extends DateTime
{
use DateBase;
// 周常量
const SUNDAY = 0;
const MONDAY = 1;
const TUESDAY = 2;
const WEDNESDAY = 3;
const THURSDAY = 4;
const FRIDAY = 5;
const SATURDAY = 6;
// MySQL DATETIME 格式
const MYSQL = 'Y-m-d H:i:s';
/*
* DateImmutable
*/
public static function immutable(...$params)
{
return $params ? new DateImmutable(...$params) : DateImmutable::class;
}
/*
* 时间实例
*/
public static function createFromImmutable($date)
{
$datetime = parent::createFromImmutable($date);
return (new self('@'.$datetime->getTimestamp()))->setTimezone($datetime->getTimezone());
}
}
/*
* immutable class
*/
class DateImmutable extends DateTimeImmutable
{
use DateBase;
/*
* 时间实例
*/
public static function createFromMutable($date)
{
$datetime = parent::createFromMutable($date);
return (new self('@'.$datetime->getTimestamp()))->setTimezone($datetime->getTimezone());
}
}
/*
* base class
*/
trait DateBase
{
private static $init;
// 配置
private static $config = [
'timezone' => 'UTC',
];
// datetime简名
private static $datetime_alias = [
'y' => 'year', 'm' => 'month', 'w' => 'week', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second'
];
// datetime格式
private static $datetime_format = [
'year' => 'Y', 'month' => 'n', 'week' => 'w', 'day' => 'j', 'days' => 't', 'hour' => 'G', 'minute' => 'i', 'second' => 's'
];
// datetime interval格式
private static $datetime_interval_format = [
'year' => 'Y', 'month' => 'M', 'week' => 'W', 'day' => 'D', 'hour' => 'H', 'minute' => 'M', 'second' => 'S'
];
/*
* 初始化
*/
public static function __init()
{
if (self::$init) {
return;
}
self::$init = true;
if ($config = Config::read('date')) {
self::$config = $config + self::$config;
}
}
/*
* 时间实例
*/
public static function parse($time, $tz = null)
{
return new self($time, $tz);
}
/*
* 当前时间实例
*/
public static function now($tz = null)
{
return new self('now', $tz);
}
/*
* 当天实例
*/
public static function today($tz = null)
{
return new self('today', $tz);
}
/*
* 时间实例
*/
public static function create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $tz = null)
{
return new self(sprintf('%04s-%02s-%02s %02s:%02s:%02s', $year, $month, $day, $hour, $minute, $second), $tz);
}
/*
* 时间实例
*/
public static function createFromFormat($format, $time, $tz = null)
{
$datetime = parent::createFromFormat($format, $time, $tz = self::makeTimeZone($tz));
return (new self('@'.$datetime->getTimestamp()))->setTimezone($tz);
}
/*
* 时间实例
*/
public static function createFromInterface($date)
{
$datetime = parent::createFromFormat($date);
return (new self('@'.$datetime->getTimestamp()))->setTimezone($datetime->getTimezone());
}
/*
* 构造函数
*/
public function __construct($time, $tz = null)
{
parent::__construct($time, self::makeTimeZone($tz));
}
/*
* 获取时间魔术方法
*/
public function __get($name)
{
return $this->get($name);
}
/*
* 获取时间
*/
public function get($name)
{
if (isset(self::$datetime_format[$name])) {
return parent::format(self::$datetime_format[$name]);
} elseif (isset(self::$datetime_alias[$name])) {
return parent::format(self::$datetime_format[self::$datetime_alias[$name]]);
} else {
switch ($name) {
case 'ts':
case 'timestamp':
return $this->getTimestamp();
case 'tz':
case 'timezone':
return $this->getTimezone();
}
}
throw new \InvalidArgumentException("Undefined datetime property: $$name");
}
/*
* 设置时间魔术方法
*/
public function __set($name, $value)
{
$this->set($name, $value);
}
/*
* 设置时间
*/
public function set($name, $value)
{
if (isset(self::$datetime_format[$name])) {
to:
switch ($name) {
case 'year':
case 'month':
case 'day':
list($year, $month, $day) = explode('-', parent::format('Y-n-j'));
$$name = $value;
return $this->setDate($year, $month, $day);
case 'hour':
case 'minute':
case 'second':
list($hour, $minute, $second) = explode('-', parent::format('G-i-s'));
$$name = $value;
return $this->setTime($hour, $minute, $second);
case 'week':
return $this->setWeek($value);
}
} elseif (isset(self::$datetime_alias[$name])) {
$name = self::$datetime_alias[$name];
goto to;
} else {
switch ($name) {
case 'ts':
case 'timestamp':
return $this->setTimestamp($value);
case 'tz':
case 'timezone':
return $this->setTimezone($value);
}
}
throw new \InvalidArgumentException("Undefined datetime property: $$name");
}
/*
* 设置周
*/
public function setWeek($value)
{
if ($v >= 0 && $v <= 6) {
$diff = parent::format('w') - $v;
if ($diff == 0) {
return $this;
}
$interval = new DateInterval('P'.abs($diff).'D');
return $diff < 0 ? parent::add($interval) : parent::sub($interval);
}
throw new \InvalidArgumentException("Invalid week value: $value");
}
/*
* 设置时间
*/
public function setDateTime($year, $month, $day, $hour, $minute, $second)
{
return $this->setDate($year, $month, $day) ? $this->setTime($hour, $minute, $second) : false;
}
/*
* 设置时区
*/
public function setTimezone($tz)
{
return parent::setTimezone(self::makeTimeZone($tz));
}
/*
* 增加时间
*/
public function add($value, $type = null)
{
return parent::add(self::interval($value, $type));
}
/*
* 减少时间
*/
public function sub($value, $type = null)
{
return parent::sub(self::interval($value, $type));
}
/*
* 魔术方法
*/
public function __call($name, $params)
{
list($method, $type) = Str::cut(strtolower($name), 3);
if (isset(self::$datetime_format[$type])) {
switch ($method) {
case 'get':
return $this->get($type);
case 'set':
return $this->set($type, ...$params);
case 'add':
case 'sub':
return parent::$method(self::buildDateInterval([$type => $params[0] ?? 1]));
}
}
throw new \BadMethodCallException("Undefined datetime method: $name");
}
/*
* 获取时间差
*/
public function diff($time, $absolute = false)
{
return parent::diff(self::makeDateTime($time), $absolute);
}
/*
* 获取时间差(秒)
*/
public function diffTimestamp($time)
{
return $this->getTimestamp() - self::makeDateTime($time)->getTimestamp();
}
/*
* 是否在时间范围内
*/
public function between($start, $end, $eq = true)
{
$ts = $this->getTimestamp();
$start = self::makeDateTime($start)->getTimestamp();
$end = self::makeDateTime($end)->getTimestamp();
return $eq ? ($ts >= $start && $ts <= $end) : ($ts > $start && $ts < $end);
}
/*
* 格式化时间
*/
public function format($format = Date::MYSQL)
{
return parent::format($format);
}
/*
* 格式化时间
*/
public function toArray()
{
return array_combine(self::$datetime_alias, explode('-', parent::format('Y-n-w-j-G-i-s')));
}
/*
* 格式化时间
*/
public function __toString()
{
return $this->format();
}
/*
* 时间周期实例
*/
public static function period($start, $interval = null, $end = null, $options = null)
{
if (!isset($end)) {
return new DatePeriod($start, $interval);
}
$start = self::makeDateTime($start);
$interval = self::makeDateInterval($interval);
if (is_int($end)) {
return new DatePeriod($start, $interval, $end, $options);
}
return new DatePeriod($start, $interval, self::makeDateTime($end), $options);
}
/*
* 时间差实例
*/
public static function interval($value, $type = null)
{
return self::makeDateInterval($type === null ? $value : [$type => $value]);
}
/*
* DateTime实例
*/
private static function makeDateTime($time)
{
return $time instanceof DateTimeInterface ? $time : new self($time);
}
/*
* TimeZone实例
*/
private static function makeTimeZone($tz)
{
if (empty($tz)) {
return new DateTimeZone(self::$config['timezone'] ?? 'UTC');
} else {
return $tz instanceof DateTimeZone ? $tz : new DateTimeZone($tz);
}
}
/*
* DateInterval实例
*/
private static function makeDateInterval($value)
{
if ($value instanceof DateInterval) {
return $value;
}
return is_string($value) ? DateInterval::createFromDateString($value) : self::buildDateInterval($value);
}
/*
* 获取类型时间差
*/
private static function buildDateInterval(array $value)
{
$date = $time = null;
foreach ($value as $k => $v) {
if (isset(self::$datetime_interval_format[$k])) {
//
} elseif (isset(self::$datetime_alias[$k])) {
$k = self::$datetime_alias[$k];
} else {
continue;
}
$i = $v.self::$datetime_interval_format[$k];
switch ($k) {
case 'year':
case 'month':
case 'week':
case 'day':
$date .= $i;
break;
case 'hour':
case 'minute':
case 'second':
$time .= $i;
break;
}
}
return new DateInterval("P$date".(isset($time) ? "T$time" : ''));
}
}
DateBase::__init();
<file_sep><?php
//默认已开启enable_getter配置,开启后可以使用$this调用容器实例
return $this->db->user->find();<file_sep><?php
return [
'closure' => ['auth' => function () {return framework\core\Auth::instance();}]
];
<file_sep><?php
namespace framework\driver\rpc\query;
class Jsonrpc
{
// 请求id
protected $id;
// namespace
protected $ns;
// client实例
protected $client;
// 参数模式
protected $param_mode;
/*
* 构造函数
*/
public function __construct($client, $param_mode, $name, $id)
{
$this->id = $id;
$this->client = $client;
$this->param_mode = $param_mode;
if (isset($name)) {
$this->ns[] = $name;
}
}
/*
* 魔术方法,设置namespace
*/
public function __get($name)
{
$this->ns[] = $name;
return $this;
}
/*
* 魔术方法,调用rpc方法
*/
public function __call($method, $params)
{
$this->ns[] = $method;
return $this->call($this->param_mode ? ($params[0] ?? null) : $params);
}
/*
* 调用
*/
protected function call($params)
{
$data = ['jsonrpc' => '2.0', 'method' => implode('.', $this->ns), 'params' => $params];
if ($this->id === true) {
$data['id'] = uniqid();
} elseif ($this->id !== false) {
$data['id'] = $this->id;
}
$result = $this->client->send($data);
if (array_key_exists('id', $data)) {
if (isset($result['result'])) {
return $result['result'];
} elseif (isset($result['error'])) {
if (is_array($result['error'])) {
error($result['error']['code'].': '.$result['error']['message']);
} else {
error('-32000: '.$result['error']);
}
}
error('-32000: Invalid response');
}
}
}<file_sep><?php
namespace framework\core;
use framework\App;
use framework\util\Str;
class Loader
{
private static $init;
// 映射
private static $class_map = [];
// PSR4
private static $class_psr4 = [];
// 前缀
private static $class_prefix = [
'app' => APP_DIR,
'framework' => FW_DIR
];
/*
* 初始化
*/
public static function __init()
{
if (self::$init) {
return;
}
self::$init = true;
if ($config = Config::read('loader')) {
foreach ($config as $type => $rules) {
self::add($type, $rules);
}
}
// 注册composer
if ($dir = Config::env('VENDOR_DIR')) {
__require($dir.'autoload.php');
}
// 内置autoload优先级最高
spl_autoload_register([__CLASS__, 'autoload'], true, true);
}
/*
* 添加loader规则
*/
public static function add($type, array $rules)
{
switch ($type = strtolower($type)) {
case 'map':
self::$class_map = $rules + self::$class_map;
return;
case 'prefix':
self::$class_prefix = $rules + self::$class_prefix;
return;
case 'psr4':
self::addPsr4($rules);
return;
case 'file':
foreach ($rules as $v) {
__require($v);
}
return;
}
throw new \Exception("Invalid loader type: $type");
}
/*
* 自动加载
*/
private static function autoload($class)
{
if (isset(self::$class_map[$class])) {
__require(self::$class_map[$class]);
} else {
$arr = explode('\\', $class, 2);
if (isset($arr[1])) {
if (isset(self::$class_prefix[$arr[0]])) {
self::import(self::$class_prefix[$arr[0]].strtr($arr[1], '\\', '/'));
} elseif (isset(self::$class_psr4[$arr[0]])) {
self::importPsr4($arr[0], $arr[1]);
}
}
}
}
/*
* 添加PSR-4规则
*/
private static function addPsr4($rules)
{
foreach ($rules as $k => $v) {
$arr = explode('\\', $class, 2);
self::$class_psr4[$arr[0]][$arr[1] ?? ''] = $v;
}
}
/*
* 加载php文件
*/
private static function import($path)
{
if (is_php_file($file = "$path.php")) {
__require($file);
}
}
/*
* 加载PSR-4规则文件
*/
private static function importPsr4($prefix, $path)
{
$i = 0;
$m = strrpos($path, '\\') ?: 0;
foreach (self::$class_psr4[$prefix] as $k => $v) {
$l = strlen($k);
if ($m >= $l && $l >= $i && strncmp($k, $path, $l) === 0) {
$i = $l;
$d = $v;
}
}
if ($i > 0) {
self::import(Str::lastPad($d, '/').strtr(substr($path, $i), '\\', '/'));
}
}
}
Loader::__init();
<file_sep><?php
define('APP_DEBUG', true);
include '../../../framework/app.php';
framework\App::start('Standard', [
'default_dispatch_param_mode' => 1,
])->run();<file_sep><?php
namespace framework\driver\email;
use framework\driver\email\query\Query;
abstract class Email
{
// 配置
protected $config/* = [
// 发信人
'from'
// 抛出响应错误异常
'throw_response_error'
]*/;
/*
* 邮件发送处理
*/
abstract protected function handle($options);
/*
* 构造函数
*/
public function __construct($config)
{
$this->config = $config;
}
/*
* 邮件设置
*/
public function __call($method, $params)
{
return (new Query($this))->$method(...$params);
}
/*
* 简单发送邮件
*/
public function send($to, $subject, $content, array $options = null)
{
if ($to) {
$options['to'] = is_array($to) ? [$to] : [[$to]];
}
if ($subject) {
$options['subject'] = $subject;
}
if ($content) {
$options['content'] = $content;
}
if (!isset($options['from']) && isset($this->config['from'])) {
$options['from'] = $this->config['from'];
}
return $this->handle($options);
}
}
<file_sep><?php
namespace framework\driver\rpc\query;
class Http
{
// namespace
protected $ns;
// client实例
protected $client;
// filter设置
protected $filters;
// headers设置
protected $headers;
/*
* 构造函数
*/
public function __construct($client, $name, $filters, $headers)
{
$this->ns = $name;
$this->client = $client;
$this->filters = $filters;
$this->headers = $headers;
}
/*
* get方法
*/
public function get($data = null)
{
return $this->call('GET', $data);
}
/*
* post方法
*/
public function post($data = null)
{
return $this->call('POST', $data);
}
/*
* 魔术方法,调用rpc方法
*/
public function __call($method, $params)
{
if (in_array($m = strtoupper($method), array('DELETE', 'PUT', 'PATCH', 'OPTIONS'))) {
return $this->call($m, ...$params);
}
throw new \Exception('Call to undefined method '.__CLASS__."::$method");
}
/*
* 调用
*/
protected function call($method, $data = null)
{
return $this->client->send($method, $this->ns, $this->filters, $data, $this->headers);
}
}<file_sep><?php
namespace framework\driver\rpc\client;
use framework\util\Arr;
use framework\util\Str;
use framework\core\http\Client;
class Http
{
// 配置项
protected $config/* = [
// 服务端点
'endpoint'
// 请求公共headers
'http_headers'
// 请求公共curlopts
'http_curlopts'
// 请求内容编码
'requset_encode'
// 响应内容解码
'response_decode'
// 响应结果字段
'response_result_field'
// 抛出响应错误异常
'throw_response_error'
// 错误码定义字段
'response_error_code_field'
// 错误信息定义字段
'response_error_message_field'
]*/;
// 错误码
protected $error_code;
// 错误信息
protected $error_message;
/*
* 构造函数
*/
public function __construct($config)
{
$this->config = $config;
}
/*
* 请求
*/
public function send($method, $path, $filters, $body, $headers)
{
$config = $this->config;
if (isset($config['request_handler'])) {
$request = (object) compact('config', 'method', 'path', 'filters', 'body', 'headers');
$config['request_handler']($request);
extract((array) $request);
}
$url = $config['endpoint'];
if ($path) {
$url = Str::lastPad($url, '/').$path;
}
if ($filters) {
$url .= (strpos($url, '?') === false ? '?' : '&').http_build_query($filters);
}
$client = new Client($method, $url);
if (isset($config['http_headers'])) {
$client->headers($config['http_headers']);
}
if (isset($headers)) {
$client->headers($headers);
}
if (isset($config['http_curlopts'])) {
$client->curlopts($config['http_curlopts']);
}
if ($body) {
if (is_string($body)) {
$client->body($body);
} else {
if (isset($config['request_encode'])) {
$client->body($config['request_encode']($body));
} else {
$client->form($body);
}
}
}
$response = $client->response();
if (isset($config['response_handler'])) {
$result = $config['response_handler']($response);
if ($result !== null) {
return $result;
}
}
if ($response->code >= 200 && $response->code < 300) {
$result = $response->body;
if (isset($config['response_decode'])) {
$result = $config['response_decode']($result);
}
if (empty($config['response_result_field'])) {
return $result;
}
$result = Arr::get($result, $config['response_result_field']);
if (isset($result)) {
return $result;
}
}
$this->error_code = $response->code;
$this->error_message = '';
if (!$this->error_code) {
$this->error_message = $client->error->message;
} else {
if (isset($config['response_error_code_field'])) {
$this->error_code = Arr::get($result, $config['response_error_code_field']);
}
if (isset($config['response_error_message_field'])) {
$this->error_message = Arr::get($result, $config['response_error_message_field']);
}
}
if (empty($config['throw_response_error'])) {
return false;
}
if ($config['throw_response_error'] !== true) {
throw new \Exception("[$this->error_code]".$this->error_message);
}
$class = $config['throw_response_error'];
throw new $class("[$this->error_code]".$this->error_message);
}
}<file_sep><?php
namespace framework\driver\db;
class Pgsql extends Pdo
{
// 构造器
const BUILDER = builder\Pgsql::class;
/*
* 获取dsn
*/
protected function getDsn($config)
{
$dsn = 'pgsql:host='.$config['host'].';dbname='.$config['dbname'];
if (isset($config['port'])) {
$dsn .= ';port='.$config['port'];
}
return $dsn;
}
/*
* 获取表字段名
*/
protected function getFields($table)
{
$fields = $this->select("SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_NAME = '$table'");
return array_column($fields, 'column_name');
}
}<file_sep><?php
include '../../../framework/app.php';
framework\App::start('Grpc', [
'service_schemes' => [
'prefix' => [
'TestGrpc' => '../scheme/grpc/TestGrpc/'
],
'map' => [
'GPBMetadata\User' => '../scheme/grpc/GPBMetadata/User'
]
]
])->run();
<file_sep><?php
namespace app\auth;
use framework\App;
use framework\core\Auth;
use framework\core\http\Cookie;
class SecureCookie extends Auth
{
private $user;
private $name = 'user';
private $crypt;
public function __construct($config)
{
if (isset($config['name'])) {
$this->name = $config['name'];
}
$this->crypt = driver('crypt', $config['crypt']);
$vaule = Cookie::get($this->name);
if ($vaule) {
$user = $this->crypt->decrypt($vaule);
if ($user) {
$this->user = unserialize($user);
}
}
}
protected function check()
{
return isset($this->user);
}
protected function user()
{
return $this->user;
}
protected function faildo()
{
Response::redirect('/user/login');
}
protected function login($params)
{
Cookie::set($this->name, $this->crypt->encrypt(serialize($params)), time() + 864000, null, null, true);
}
protected function logout()
{
Cookie::delete($this->name);
}
}
<file_sep><?php
define('APP_DEBUG', true);
include '../../../framework/app.php';
framework\App::start(app\library\MyApp::class)->run();<file_sep><?php
return [
'mysqli' => [
'driver' => 'mysqli',
// 服务器地址
'host' => '127.0.0.1',
//(可选配置) 服务器 端口
'port' => 3306,
// 数据库用户名
'username' => 'root',
// 数据库密码
'password' => '',
// 数据库名
'dbname' => 'test',
// 数据库字符集
'charset' => 'utf8',
// (可选配置)数据库socket地址
//'socket' => null
],
'mysql' => [
'driver' => 'mysql',
'host' => '127.0.0.1',
//'port' => 3306,
'username' => 'root',
'password' => '',
'dbname' => 'test',
'charset' => 'utf8',
//'socket' => null
],
'sqlite' => [
'driver' => 'sqlite',
'database' => '/home/qiujin/sqlite/test',
'username' => '',
'password' => '',
],
'pgsql' => [
'driver' => 'pgsql',
'host' => '127.0.0.1',
'username' => 'postgres',
'password' => '',
'dbname' => 'test',
'charset' => 'utf8'
],
'cluster' => [
'driver' => 'cluster',
// 读服务器地址
'read' => array_rand([
'127.0.0.2',
'127.0.0.3',
'127.0.0.4',
]),
// 写服务器地址
'write' => '127.0.0.1',
//'port' => 3306,
'username' => 'root',
'password' => '',
'dbname' => 'test',
'charset' => 'utf8'
],
];
<file_sep><?php
namespace framework\core\app;
use framework\App;
use framework\util\Arr;
use framework\util\Str;
use framework\core\Router;
use framework\core\http\Request;
use framework\core\http\Response;
class Micro extends App
{
protected $config = [
// 控制器namespace
'controller_ns' => 'controller',
// 控制器类名后缀
'controller_suffix' => null,
// 类和方法名分隔符
'class_method_separator' => '::',
// 闭包绑定的类(为true时绑定getter匿名类)
'closure_bind_class' => true,
// Getter providers(绑定getter匿名类时有效)
'closure_getter_providers' => null,
// 方法名转驼峰
'default_method_path_to_camel' => false,
// 设置动作调度路由属性名,为null则不启用动作路由
'method_dispatch_routes_property' => null,
];
// 路由规则
protected $routes = [];
// query规则
protected $queries = [];
/*
* 设置路由规则
*/
public function route(...$params)
{
$count = count($params);
if ($count == 1) {
$this->routes = array_merge_recursive($this->routes, $params[0]);
} else {
if ($count == 2) {
$this->routes[$params[0]] = $params[1];
} else {
$call = array_pop($params);
Arr::set($this->routes, $params, $call);
}
}
return $this;
}
/*
* 设置query规则
*/
public function query(...$params)
{
$count = count($params);
if ($count > 1) {
$call = array_pop($params);
if ($count == 2) {
if (is_array($params[0])) {
$query['query'] = $params[0];
} elseif (is_string($params[0])) {
$query['method_query'] = $params[0];
}
} elseif ($count == 3) {
if (is_array($params[1])) {
if (is_string($params[0])) {
$path = $params[0];
$query['query'] = $params[1];
}
} elseif (is_string($params[1])) {
if (is_array($params[0])) {
$query['query'] = $params[0];
$query['method_query'] = $params[1];
} elseif (is_string($params[0])) {
$path = $params[0];
$query['method_query'] = $params[1];
}
}
} elseif ($count == 4) {
if (is_string($params[0]) && is_array($params[1]) && is_string($params[2])) {
$path = $params[0];
$query['query'] = $params[1];
$query['method_query'] = $params[2];
}
}
if (isset($query)) {
$query['call'] = $call;
if (isset($path)) {
if ($path[0] == ':') {
$arr = explode(' ', substr($v, 1), 2);
$query['http_method'] = $arr[0];
if (isset($path[1])) {
$path = trim($path[1]);
}
}
}
$this->queries[$path ?? ''] = $query;
return $this;
}
}
throw new \Exception("无效的query规则");
}
/*
* 调度
*/
protected function dispatch()
{
if ($this->routes) {
if ($dispatch = $this->dispatchRoute()) {
return $this->dispatch = $dispatch;
}
}
if ($this->queries) {
if ($dispatch = $this->dispatchQuery()) {
return $this->dispatch = $dispatch;
}
}
}
protected function dispatchRoute()
{
$http_method = Request::method();
$result = (new Router(App::getPathArr(), $http_method))->route($this->routes);
if ($result) {
$call = $result['dispatch'];
if ($call instanceof \Closure) {
if ($this->config['closure_bind_class']) {
$call = $this->bindClosure($call, $this->config['closure_bind_class']);
}
return ['call' => $call, 'params' => $result['matches']];
} else {
if (!isset($result['next'])) {
if (is_string($call)) {
$call = explode($this->config['class_method_separator'], $call, 2);
if (isset($call[1])) {
$instance = $this->instanceClass($call[0]);
if ($instance && is_callable([$instance, $call[1]])) {
return ['call' => [$instance, $call[1]], 'params' => $result['matches']];
}
}
}
throw new \Exception("无效的route调用方法或闭包");
} else {
if (is_object($call)) {
$instance = $call;
} elseif(is_string($call)) {
$instance = $this->instanceClass($call);
}
if (!isset($instance)) {
throw new \Exception("无效的route调用类或对象");
}
if (!$this->config['method_dispatch_routes_property']) {
if ($method = $this->checkInstanceMethod($instance, $result['next'])) {
return ['call' => [$instance, $method]];
}
return;
}
$property = $this->config['method_dispatch_routes_property'];
if (isset($instance->$property)) {
$method_result = (new Router($result['next'], $http_method))->route($instance->$property);
if ($method_result) {
if (is_callable([$instance, $method_result[0]]) || $method_result[0][0] === '_') {
return ['call' => [$instance, $method_result[0]], 'params' => $method_result[1]];
}
}
}
}
}
}
}
protected function dispatchQuery()
{
$path = App::getPath();
$http_method = Request::method();
if (isset($this->queries[$path])) {
$call = $query['call'];
foreach ($this->queries[$path] as $query) {
if (isset($query['http_method']) && $http_method != $query['http_method']) {
continue;
}
if (isset($query['query'])) {
foreach ($query['query'] as $k => $v) {
if (Request::query($k) != $v) {
continue 2;
}
}
}
if (!isset($query['method_query'])) {
if ($call instanceof \Closure) {
if ($this->config['closure_bind_class']) {
$call = $this->bindClosure($call, $this->config['closure_bind_class']);
}
return ['call' => $call];
} elseif (is_string($call)) {
$call = explode($this->config['class_method_separator'], $call, 2);
if (isset($call[1])) {
$instance = $this->instanceClass($call[0]);
if ($instance && is_callable([$instance, $call[1]])) {
return ['call' => [$instance, $call[1]]];
}
}
}
throw new \Exception("无效的query调用类方法或闭包");
}
$method = Request::query($query['method_query']);
if ($method) {
if (is_object($call)) {
$instance = $call;
} elseif (is_string($call)) {
$instance = $this->instanceClass($class);
}
if (isset($instance)) {
if ($method = $this->checkInstanceMethod($instance, $method)) {
return ['call' => [$instance, $method]];
}
return;
}
throw new \Exception("无效的query调用类或对象");
}
}
}
}
/*
* 调用
*/
protected function call()
{
return $this->dispatch['call'](...($this->dispatch['params'] ?? []));
}
/*
* 错误
*/
protected function error($code = null, $message = null)
{
Response::code($code ?? 500);
Response::json(['error' => compact('code', 'message')]);
}
/*
* 响应
*/
protected function respond($return = null)
{
Response::json($return);
}
/*
* 闭包绑定类
*/
protected function bindClosure($call, $class)
{
if ($class !== true) {
return \Closure::bind($call, new $class, $class);
}
$getter = getter($this->config['closure_getter_providers']);
return \Closure::bind($call, $getter, $getter);
}
/*
* 实例话类
*/
protected function instanceClass($class)
{
if ($this->config['controller_ns']) {
if ($class = $this->getControllerClass($class)) {
return instance($class);
}
} elseif (class_exists($class)) {
return instance($call);
}
}
/*
* 检查实例方法
*/
protected function checkInstanceMethod($instance, $method)
{
if ($this->config['method_path_default_to_camel']) {
$method = Str::camelCase(str_replace('-', '_', $method));
}
if (is_callable([$instance, $method]) && $method[0] !== '_') {
return $method;
}
}
}
<file_sep><?php
namespace framework\core;
use framework\App;
class Validator
{
protected $data;
protected $rule;
protected $error;
protected $message = [
'require' => '{name} require',
'id' => '{name} must be id',
'ip' => '{name} must be ip',
'email' => '{name} must be email',
'mobile' => '{name} must be mobile'
];
public function __construct($rule, array $message = null)
{
if ($rule) {
$this->rule = $rule;
}
if ($message) {
$this->message = $message + $this->message;
}
}
public function check($fall_continue = false)
{
foreach ($this->rule as $name => $rule) {
if (!isset($data[$name])) {
$data[$name] = null;
}
foreach (explode('|', $rule) as $item) {
$params = explode(':', $item);
$method = array_shift($params);
if (!self::{'check'.$method}($data[$name], ...$params)) {
$this->error[$name] = strtr($this->message[$method], ['{name}' => $name]);
if (!$fall_continue) {
return false;
}
break;
}
}
}
return !isset($this->error);
}
public function fallback()
{
App::abort(400, $this->error);
}
public function run($data)
{
$this->check($data) || $this->fallback() === true || App::exit();
}
public function error()
{
return $this->error;
}
public static function validate($value, $rule)
{
}
public static function checkRequire($var)
{
return isset($var);
}
public static function checkId($var)
{
return is_numeric($var) && is_int($var + 0) && $var > 0;
}
public static function checkIp($var)
{
return filter_var($var, FILTER_VALIDATE_IP);
}
public static function checkUrl($var)
{
return filter_var($var, FILTER_VALIDATE_URL);
}
public static function checkEmail($var)
{
return filter_var($var, FILTER_VALIDATE_EMAIL);
}
public static function checkMobile($var)
{
return preg_match('/^1[3456789]\d{9}$/', $var);
}
public static function checkMin($var, $min)
{
return strlen($var) >= $min;
}
public static function checkMax($var, $max)
{
return strlen($var) <= $max;
}
public static function checkBetween($var, $min, $max)
{
$len = strlen($var);
return $len >= $min && $len <= $max;
}
}
<file_sep><?php
return [
'standard'=> [
'driver' => 'http',
'endpoint' => 'http://standard.example.com',
'response_decode' => 'json'
],
'rest'=> [
'driver' => 'rest',
'host' => 'http://rest.example.com',
'response_decode' => 'json'
],
'jsonrpc'=> [
'driver' => 'jsonrpc',
'endpoint' => 'http://jsonrpc.example.com',
//'requset_serialize' => 'msgpack_serialize',
//'response_unserialize' => 'msgpack_unserialize',
],
'grpc' => [
'driver' => 'grpc',
'host' => '127.0.0.1',
'port' => 50051,
'prefix' => 'TestGrpc',
'auto_bind_param' => true,
'service_schemes' => [
'prefix' => [
'TestGrpc' => APP_DIR.'scheme/grpc/TestGrpc/'
],
'map' => [
'GPBMetadata\User' => APP_DIR.'scheme/grpc/GPBMetadata/User'
]
]
],
'thrift' => [
'driver' => 'thrift',
'host' => '127.0.0.1',
'port' => 9090,
'prefix' => 'pingpong_thrift',
'service_schemes' => [
'prefix' => [
'pingpong_thrift' => APP_DIR.'resource/thrift/pingpong_thrift/'
],
'files' => [
APP_DIR.'resource/thrift/pingpong_thrift/Types'
]
]
],
'zhihu'=> [
'driver' => 'rest',
'endpoint' => 'https://www.zhihu.com/api/v4',
'headers' => [
'Authorization:oauth your_key'
],
'response_decode' => 'json',
],
'github'=> [
'driver' => 'rest',
'endpoint' => 'https://api.github.com',
'headers' => [
'Accept: application/vnd.github.v3+json',
'User-Agent: test',
'Authorization: Basic your_key'
],
'curlopt' => [
'timeout' => 10
],
'response_decode' => 'json',
],
];
<file_sep><?php
return [
'cache' => null,
'filters' => [
]
];
<file_sep><?php
namespace framework\core;
use framework\util\File;
use framework\core\http\Response;
use framework\exception\ViewException;
class View
{
private static $init;
// 数据
private static $vars = [];
// 过滤器
private static $filters = [];
// 配置
private static $config = [
// 视图文件扩展名
'ext' => '.php',
// 视图文件目录
'dir' => APP_DIR.'view/',
// 错误页面
'error' => null,
// 模版配置(为空则不启用模版)
'template' => [
// 模版文件扩展名
'ext' => '.html',
// 模版文件目录(为空则默认使用视图文件目录)
'dir' => null,
// 模版引擎类名
'engine' => Template::class,
// 是否强制编译模版
'force_compile' => \app\env\APP_DEBUG,
]
];
/*
* 初始化
*/
public static function __init()
{
if (self::$init) {
return;
}
self::$init = true;
if ($config = Config::get('view')) {
self::$config = array_replace_recursive(self::$config, $config);
}
}
/*
* 设置变量
*/
public static function var($name, $value)
{
self::$vars[$name] = $value;
}
public static function vars(array $values)
{
self::$vars = self::$vars ? $values + self::$vars : $values;
}
/*
* 设置过滤器
*/
public static function filter($name, $value)
{
self::$filters[$name] = $value;
}
public static function filters(array $values)
{
self::$filters = self::$filters ? $values + self::$filters : $values;
}
/*
* 展示页面
*/
public static function display($tpl, array $vars = null)
{
Response::html(self::render($tpl, $vars));
}
/*
* 渲染页面
*/
public static function render($tpl, array $vars = [], $clean = true)
{
ob_start();
if (self::$vars) {
$vars = $vars ? $vars + self::$vars : self::$vars;
}
(static function() {
extract(func_get_arg(0), EXTR_SKIP);
require func_get_arg(1);
}) ($vars, self::path($tpl));
if ($clean) {
//self::clean();
}
return ob_get_clean();
}
/*
* 检查更新视图文件,返回路径
*/
public static function path($tpl, $force_compile = false)
{
$vfile = self::getViewFilePath($tpl);
if (self::$config['template']) {
if (!is_file($tfile = self::getTemplateFilePath($tpl))) {
throw new ViewException("Template file not found: $tfile");
}
if ($force_compile || self::$config['template']['force_compile'] || !is_file($vfile)
|| filemtime($vfile) < filemtime($tfile)
) {
self::complieTo($vfile, file_get_contents($tfile));
}
}
return $vfile;
}
/*
* 错误页面,404 500页面等
*/
public static function error($code, $message = null)
{
if (isset(self::$config['error'][$code])) {
return self::render(self::$config['error'][$code], compact('code', 'message'));
}
return $code == 404 ? self::render404($message) : self::renderError($message);
}
/*
* 读取模版内容
*/
public static function readTemplate($tpl)
{
if (($content = File::get(self::getTemplateFilePath($tpl))) !== false) {
return $content;
}
throw new ViewException("Template file not found: $file");
}
/*
* 检查视图文件是否过期
*/
public static function checkExpired($vfile, ...$tpls)
{
if (self::$config['template']) {
foreach ($tpls as $tpl) {
if (!is_file($tfile = self::getTemplatePath($tpl))) {
throw new ViewException("模版文件: $tfile 不存在");
}
if (filemtime($vfile) < filemtime($tfile)) {
$dir = realpath(self::$config['dir']);
$len = strlen($dir);
if (strncmp($vfile, $dir, $len) === 0) {
$t = substr($vfile, $len + 1, - strlen(self::$config['ext']));
self::complieTo($vfile, self::readTemplate($t));
return true;
}
throw new ViewException("视图文件: $vfile 与视图目录: $dir 不符");
}
}
}
}
/*
* 调用过滤器
*/
public static function callFilter($name, ...$params)
{
if (isset(self::$filters[$name])) {
return self::$filters[$name](...$params);
}
throw new \BadMethodCallException("调用未定义过滤器: $name");
}
/*
* 检查视图文件是否存在
*/
public static function exists($tpl)
{
return self::$config['template'] ?
is_file(self::getTemplateFilePath($tpl)) : is_php_file(self::getViewFilePath($tpl));
}
/*
* 获取视图文件路径
*/
private static function getViewFilePath($tpl)
{
return self::$config['dir'].$tpl.self::$config['ext'];
}
/*
* 获取模版文件路径
*/
private static function getTemplateFilePath($tpl)
{
return (self::$config['template']['dir'] ?? self::$config['dir']).$tpl.self::$config['template']['ext'];
}
/*
* 编译模版并保存到视图文件
*/
private static function complieTo($file, $content)
{
if (File::put($file, self::$config['template']['engine']::complie($content))) {
return OPCACHE_LOADED && opcache_compile_file($file);
}
throw new ViewException("写入视图文件: $file 失败");
}
private static function render404($message)
{
$html = '<h1 style="text-align: center">🙁 404 Page Not Found 🙁</h1>';
if ($message) {
$html .= '<p style="text-align: center">'.$message.'</p>';
}
return $html;
}
private static function renderError($message)
{
$loglevel = [
Logger::EMERGENCY => ['icon'=>'❌', 'class' => 'error', 'title' => 'error'],
Logger::ALERT => ['icon'=>'❌', 'class' => 'error', 'title' => 'error'],
Logger::CRITICAL => ['icon'=>'❌', 'class' => 'error', 'title' => 'error'],
Logger::ERROR => ['icon'=>'❌', 'class' => 'error', 'title' => 'error'],
Logger::WARNING => ['icon'=>'⚠️', 'class' => 'warning', 'title' => 'warning'],
Logger::NOTICE => ['icon'=>'⚠️', 'class' => 'warning', 'title' => 'warning'],
Logger::INFO => ['icon'=>'❕', 'class' => 'info', 'title' => 'info'],
Logger::DEBUG => ['icon'=>'❕', 'class' => 'info', 'title' => 'info']
];
$html = '<h1 style="text-align: center">🙁 500 Internal Server Error 🙁</h1>';
if($message) {
$html .= '<style type="text/css">.table {background: #AAAAAA}tr{ background-color: #EEEEEE;}.error{ background-color: #FFCCCC;}.warning{ background-color: #FFFFCC;}.info{ background-color: #EEEEEE;}</style>';
$html .= '<table table cellpadding="5" cellspacing="1" width="100%" class="table">';
foreach ($message as $line){
$level = $loglevel[$line['level']];
$txt = $line['message'].' in '.($line['context']['file'] ?? '').' on '.($line['context']['line'] ?? '');
$html .= '<tr class="'.$level['class'].'"><td title="'.$level['title'].'">'.$level['icon'].' '.$txt.'</td></tr>';
}
$html .= '</table>';
}
return $html;
}
/*
* 清理
*/
public static function clear()
{
self::$vars = self::$filters = [];
}
}
View::__init();
<file_sep><?php
namespace framework\core\http;
use framework\core\Event;
use framework\core\Config;
class Request
{
private static $init;
// 是否代理请求
private static $proxy;
/*
* 初始化
*/
public static function __init()
{
if (self::$init) {
return;
}
self::$init = true;
self::$proxy = Config::env('HTTP_REQUEST_PROXY');
Event::trigger('request');
}
/*
* 获取GET值
*/
public static function get($name = null, $default = null)
{
return self::query($name, $default);
}
/*
* 获取GET值
*/
public static function query($name = null, $default = null)
{
return $name === null ? $_GET : ($_GET[$name] ?? $default);
}
/*
* 获取POST值
*/
public static function post($name = null, $default = null)
{
return self::param($name, $default);
}
/*
* 获取POST值
*/
public static function param($name = null, $default = null)
{
return $name === null ? $_POST : ($_POST[$name] ?? $default);
}
/*
* 获取REQUEST值
*/
public static function input($name = null, $default = null)
{
return $name === null ? $_REQUEST : ($_REQUEST[$name] ?? $default);
}
/*
* 获取SERVER值
*/
public static function server($name = null, $default = null)
{
return $name === null ? $_SERVER : ($_SERVER[$name] ?? $default);
}
/*
* 获取HEADER值
*/
public static function header($name, $default = null)
{
return $_SERVER['HTTP_'.strtoupper(strtr($name, '-', '_'))] ?? $default;
}
/*
* 获取COOKIE值
*/
public static function cookie($name = null, $default = null)
{
return $name === null ? Cookie::all() : Cookie::get($name, $default);
}
/*
* 获取SESSION值
*/
public static function session($name = null, $default = null)
{
return $name === null ? Session::all() : Session::get($name, $default);
}
/*
* 获取FILES值
*/
public static function file($name = null)
{
return $name === null ? $_FILES : $_FILES[$name] ?? null;
}
/*
* 获取文件上传实例
*/
public static function uploaded($name)
{
if (isset($_FILES[$name])) {
if (is_array($_FILES[$name]['name'])) {
$keys = array_keys($_FILES[$name]);
$count = count($_FILES[$name]['name']);
for ($i = 0; $i < $count; $i++) {
$files[] = new Uploaded(array_combine($keys, array_column($_FILES[$name], $i)));
}
return $files;
} else {
return new Uploaded($_FILES[$name]);
}
}
}
/*
* 获取host
*/
public static function host()
{
return $_SERVER['HTTP_HOST'];
}
/*
* 获取当前uri
*/
public static function uri()
{
return $_SERVER['REQUEST_URI'];
}
/*
* 获取当前url
*/
public static function url()
{
return (self::isHttps() ? 'https' : 'http').'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
}
/*
* 获取请求方法
*/
public static function method()
{
return strtoupper($_SERVER['REQUEST_METHOD']);
}
/*
* 获取ip
*/
public static function ip($proxy = null)
{
if ($proxy ?? self::$proxy) {
return $_SERVER['HTTP_X_FORWARDED_FOR'] ?? null;
}
return $_SERVER['REMOTE_ADDR'] ?? null;
}
/*
* 获取port
*/
public static function port($proxy = null)
{
if ($proxy ?? self::$proxy) {
return $_SERVER['HTTP_X_FORWARDED_PORT'] ?? null;
}
return $_SERVER['REMOTE_PORT'] ?? null;
}
/*
* 获取请求路径
*/
public static function path()
{
return parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
}
/*
* 获取请求body内容
*/
public static function body()
{
return file_get_contents('php://input');
}
/*
* 是否为POST请求
*/
public static function isPost()
{
return self::method() == 'POST';
}
/*
* 是否为Ajax请求
*/
public static function isAjax()
{
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
/*
* 是否为Https请求
*/
public static function isHttps($proxy = null)
{
if ($proxy ?? self::$proxy) {
return isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https';
}
return isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on';
}
}
Request::__init();
<file_sep><?php
namespace framework\driver\cache;
use framework\util\Str;
use framework\util\File;
/*
* 只支持 null bool int float string array 类型(支持serialize object,但unserialize为array)
*/
class Opcache extends Cache
{
// 缓存文件目录
protected $dir;
// 缓存文件扩展名
protected $ext = '.cache.php';
// 使用真实文件名
protected $use_real_name = false;
// 强制处理数据类型安全
protected $force_type_safe = false;
/*
* 初始化
*/
public function __construct($config)
{
parent::__construct($config);
$this->dir = Str::lastPad($config['dir'], '/');
if (isset($config['ext'])) {
$this->ext = $config['ext'];
}
$this->use_real_name = !empty($config['use_real_name']);
if (isset($config['force_type_safe'])) {
$this->force_type_safe = $config['force_type_safe'];
}
}
/*
* 获取
*/
public function get($key, $default = null)
{
if (is_php_file($file = $this->filename($key))) {
$cache = require($file);
if ($expiration === 0 || $expiration > time()) {
return $cache;
}
}
return $default;
}
/*
* 检查
*/
public function has($key)
{
if (is_php_file($file = $this->filename($key))) {
require($file);
return $expiration === 0 || $expiration > time();
}
return false;
}
/*
* 设置
*/
public function set($key, $value, $ttl = null)
{
if ($this->force_type_safe) {
$value = json_decode(json_encode($value), true);
}
$contents = sprintf('<?php $expiration = %d;'.PHP_EOL.'return %s;',
($t = $this->ttl($ttl)) == 0 ? 0 : $t + time(),
var_export($value, true)
);
return file_put_contents($file = $this->filename($key), $contents, LOCK_EX) && opcache_compile_file($file);
}
/*
* 删除
*/
public function delete($key)
{
return is_php_file($file = $this->filename($key)) && opcache_invalidate($file, true) && unlink($file);
}
/*
* 自增
*/
public function increment($key, $value = 1)
{
return $this->set($key, $this->get($key, 0) + $value);
}
/*
* 自减
*/
public function decrement($key, $value = 1)
{
return $this->set($key, $this->get($key, 0) - $value);
}
/*
* 清理
*/
public function clear()
{
$len = strlen($this->ext);
File::clearDir($this->dir, function ($file) use ($len) {
if (substr($file, - $len) === $this->ext) {
opcache_invalidate($file, true);
return true;
}
});
}
/*
* 垃圾回收
*/
public function gc()
{
$len = strlen($this->ext);
$time = time();
File::cleanDir($this->dir, function ($file) use ($len, $time) {
if (substr($file, - $len) === $this->ext) {
require($file);
if ($expiration <= $time && $expiration !== 0) {
opcache_invalidate($file, true);
return true;
}
}
});
}
/*
* 获取文件名
*/
protected function filename($key)
{
return $this->dir.($this->use_real_name ? $key : md5($key)).$this->ext;
}
}
<file_sep><?php
namespace framework\driver\db\query;
class Relate extends QueryChain
{
// with表名
protected $with;
// query实例
protected $query;
// 是否多条
protected $has_many;
// 字段名
protected $field_name;
/*
* 初始化
*/
protected function __init($table, $query, $with, $has_many = false, $alias = null)
{
$this->with = $with;
$this->table = $table;
$this->query = $query;
$this->has_many = $has_many;
$this->field_name = $alias ?? $with;
$this->options = ['where' => [], 'order' => null, 'fields' => null];
}
/*
* 设置关联表字段关联
*/
public function on($related, array $field1 = null, array $field2 = null)
{
$this->options['on'] = [$related, $field1, $field2];
return $this;
}
/*
* 查询(单条)
*/
public function get($id = null, $pk = 'id')
{
if ($data = $this->query->get($id, $pk)) {
$data = [$data];
$this->withSubData($data);
return $data[0];
}
return null;
}
/*
* 查询(多条)
*/
public function find()
{
if ($data = $this->query->find()) {
$this->withSubData($data);
}
return $data;
}
/*
* with表子数据
*/
protected function withSubData(&$data)
{
if (isset($this->options['on'])) {
$on = $this->options['on'];
if (!isset($on[1])) {
$on[1] = ['id', $this->table.'_id'];
}
if (!isset($on[2])) {
$on[2] = ['id', $this->with.'_id'];
}
list($related, $field1, $field2) = $on;
} else {
$related = $this->table.'_'.$this->with;
$field1 = ['id', $this->table.'_id'];
$field2 = ['id', $this->with.'_id'];
}
if ($in_data = array_unique(array_column($data, $field1[0]))) {
$params = [];
$sql = $this->builder::whereItem($params, $field1[1], 'IN', $in_data);
$sql = 'SELECT '.$this->builder::quoteField($field1[1]).', '
. $this->builder::quoteField($field2[1]).' FROM '.$this->builder::quoteField($related)." WHERE $sql";
$related_data = $this->db->find($sql, $params);
if ($related_data) {
foreach ($related_data as $rd) {
$field2_field1_related[$rd[$field2[1]]][] = $rd[$field1[1]];
}
unset($related_data);
$with_data = $this->db->find(...$this->builder::select($this->with, [
'order' => $this->options['order'],
'fields'=> $this->options['fields'],
'where' => array_merge([[$field2[0], 'IN', array_keys($field2_field1_related)]], $this->options['where'])
]));
if ($with_data) {
foreach ($with_data as $wd) {
if (isset($field2_field1_related[$wd[$field2[0]]])) {
foreach ($field2_field1_related[$wd[$field2[0]]] as $item) {
if ($this->has_many) {
$sub_data[$item][] = $wd;
} elseif (!isset($sub_data[$item])) {
$sub_data[$item] = $wd;
}
}
}
}
unset($with_data);
$count = count($data);
for ($i = 0; $i < $count; $i++) {
$index = $data[$i][$field1[0]];
$data[$i][$this->field_name] = $sub_data[$index] ?? [];
}
}
}
}
}
}
<file_sep><?php
namespace framework\core;
trait Getter
{
/*
* 获取实例
*/
public function __get($name)
{
$v = Container::getProvider($name);
if ($v && !empty($v[1])) {
if ($v[0] === Container::T_DRIVER) {
if ($v[1] === 2) {
// DRIVER 属性访问驱动实例
return $this->$name = new class($name) {
private $_n;
public function __construct($name) {
$this->_n = $name;
}
// 魔术方法,获取驱动实例
public function __get($name) {
if ($name[0] != '_') {
return $this->$name = Container::driver($this->_n, $name);
}
throw new \Exception("属性命名不允许以下划线开头: $name");
}
};
}
return $this->$name = Container::driver($name);
} elseif ($v[0] === Container::T_MODEL) {
/*
return $this->$name = new class($name) {
private $_n;
public function __construct($name) {
$this->_n = $name;
}
//
public function __call($method, $params) {
if ($method[0] != '_') {
$this->$method = Container::model($this->_n, $method);
($this->$method)(...$params);
return $this->$method
}
throw new \Exception("方法命名不允许以下划线开头: $method");
}
};
*/
} elseif ($v[0] === Container::T_SERVICE) {
// SERVICE 名称空间链实例
return $this->$name = new class($name, ($int = (int) $v[1]) > 0 ? $int : 1) {
private $_ns;
private $_depth;
public function __construct($ns, $depth) {
$this->_ns = $ns;
$this->_depth = $depth - 1;
}
// 魔术方法,获取空间链实例或容器实例
public function __get($name) {
$this->_ns .= ".$name";
if ($name[0] != '_') {
if ($this->_depth > 0) {
return $this->$name = new self($this->_ns, $this->_depth);
} else {
return $this->$name = Container::make($this->_ns);
}
}
throw new \Exception("属性命名不允许以下划线开头: $this->_ns");
}
};
}
return $this->$name = Container::make($name);
} else {
$config = Config::get('getter');
if (isset($config['providers_name'])) {
$n = $config['providers_name'];
if ($n && isset($this->$n) && isset($this->$n[$name])) {
return $this->$name = Container::makeCustomProvider($this->$n[$name]);
}
}
if (isset($config['common_providers'][$name])) {
return $this->$name = Container::makeCustomProvider($config['common_providers'][$name]);
}
}
throw new \Exception("Undefined property: $$name");
}
}
<file_sep><?php
namespace framework\driver\email;
use framework\core\http\Client;
use framework\driver\email\query\Mime;
class Mailgun extends Email
{
// 配置
protected $config/* = [
'domain' => '',
'apikey' => '',
]*/;
// 服务端点
protected static $endpoint = 'https://api.mailgun.net/v3';
/*
* 处理请求
*/
protected function handle($options)
{
list($addrs, $mime) = Mime::make($options);
$options['options']['to'] = implode(',', $addrs);
$client = Client::post(self::$endpoint.'/'.$this->config['domain'].'/messages.mime')
->auth('api', $this->config['apikey'])
->form($options['options'], true)
->buffer('message', $mime);
$result = $client->response()->decode();
if (isset($result['id'])) {
return true;
}
if (empty($this->config['throw_response_error'])) {
return false;
}
if ($this->config['throw_response_error'] !== true) {
throw new \Exception($result['message'] ?? $client->error);
}
$class = $this->config['throw_response_error'];
throw new $class($result['message'] ?? $client->error);
}
}
<file_sep><?php
namespace framework\driver\logger;
use framework\util\Str;
use framework\util\Arr;
use framework\util\Date;
use framework\core\Event;
use framework\core\Container;
class Email extends Logger
{
// 日志收件人
protected $to;
// 邮件驱动配置
protected $email;
// 缓存驱动配置
protected $cache = [
'driver'=> 'file',
'ext' => '.send_email_log_cache.txt',
'dir' => APP_DIR.'storage/cache/',
];
// 邮件标题模版
protected $title = "[{time}] Error report: {key}";
// 邮件发送间隔时间(秒数)
protected $send_interval = 900;
/*
* 构造函数
*/
public function __construct($config)
{
$this->to = $config['to'];
$this->email = $config['email'];
if (isset($config['cache'])) {
$this->cache = $config['cache'];
}
if (isset($config['send_interval'])) {
$this->send_interval = $config['send_interval'];
}
Event::on('exit', [$this, 'flush']);
}
public function write($level, $message, $context = null)
{
$this->logs[] = [$level, $message, $context];
}
/*
* 输出缓冲
*/
public function flush()
{
if ($this->logs) {
$log = Arr::last($this->logs);
$key = md5($log[0].$log[1].($log[2]['file'] ?? '').($log[2]['line'] ?? ''));
$cache = Container::driver('cache', $this->cache);
if (!$cache->has($key)) {
$cache->set($key, 1, $this->send_interval);
$title = Str::format($this->title, ['key' => $key, 'time' => Date::now()->format()]);
$content = json_encode($this->logs, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
Container::driver('email', $this->email)->send($this->to, $title, $content);
}
$this->logs = null;
}
}
}<file_sep><?php
namespace framework\driver\rpc;
class Httprpc
{
// client实例
protected $client;
/*
* 构造函数
*/
public function __construct($config)
{
$this->client = new client\Http($config);
}
/*
* query实例
*/
public function __get($name)
{
return $this->query($name);
}
/*
* query实例
*/
public function query($name = null, $filters = null, $headers = null, $method = null)
{
return new query\Httprpc($this->client, $name, $filters, $headers, $method);
}
}<file_sep><?php
namespace framework\driver\email;
use framework\util\Arr;
use framework\driver\email\query\Mime;
class Sendmail extends Email
{
/*
* 构造函数
*/
public function __construct($config)
{
parent::__construct($config);
if (isset($config['sendmail_path'])) {
ini_set('sendmail_path', $config['sendmail_path']);
}
}
/*
* 处理请求
*/
protected function handle($options)
{
$subject = Mime::encodeHeader(Arr::pull($options, 'subject'));
list($addrs, $mime) = Mime::make($options);
list($header, $body) = explode(Mime::EOL.Mime::EOL, $mime, 2);
return mail(implode(',', $addrs), $subject, $body, $header);
}
}
<file_sep><?php
namespace framework\driver\db\result;
class Mysqli
{
// 原始query
protected $query;
/*
* 构造函数
*/
public function __construct(\mysqli_result $query)
{
$this->query = $query;
}
/*
* 获取查询到的数据条数
*/
public function count()
{
return $this->query->num_rows;
}
/*
* 获取一条数据
*/
public function fetch()
{
return $this->query->fetch_assoc();
}
/*
* 获取一条数据(无字段键)
*/
public function fetchRow()
{
return $this->query->fetch_row();
}
/*
* 获取一条数据(object)
*/
public function fetchObject($class_name = 'stdClass', array $ctor_args = null)
{
return $this->query->fetch_object($class_name, $ctor_args);
}
/*
* 获取所有数据
*/
public function fetchAll()
{
return $this->query->fetch_all(MYSQLI_ASSOC);
}
/*
* 析构函数
*/
public function __destruct()
{
$this->query->free();
}
}<file_sep><?php
namespace framework\driver\cache;
/*
* http://php.net/apcu
*/
class Apcu extends Cache
{
// 字段前缀
protected $prefix;
/*
* 构造函数
*/
public function __construct($config)
{
parent::__construct($config);
$this->prefix = $config['prefix'];
}
/*
* 获取
*/
public function get($key, $default = null)
{
return apcu_fetch($this->prefix.$key) ?? $default;
}
/*
* 检查
*/
public function has($key)
{
return apcu_exists($this->prefix.$key);
}
/*
* 设置
*/
public function set($key, $value, $ttl = null)
{
return apcu_store($this->prefix.$key, $value, $this->ttl($ttl));
}
/*
* 删除
*/
public function delete($key)
{
return apcu_delete($this->prefix.$key);
}
/*
* 自增
*/
public function increment($key, $value = 1)
{
return apcu_inc($this->prefix.$key, $value);
}
/*
* 自减
*/
public function decrement($key, $value = 1)
{
return apcu_dec($this->prefix.$key, $value);
}
/*
* 清理
*/
public function clear()
{
return apcu_clear_cache();
}
}
<file_sep><?php
namespace framework\driver\db;
abstract class Pdo extends Db
{
/*
* 获取dsn
*/
abstract protected function getDsn($config);
/*
* 获取表字段名
*/
abstract protected function getFields($table);
/*
* 连接数据库
*/
protected function connect($config)
{
$dsn = $this->getDsn($config);
$connection = new \PDO($dsn, $config['username'], $config['password'], $config['options'] ?? null);
if (isset($config['attributes'])) {
foreach ($config['attributes'] as $attribute => $value) {
$connection->setAttribute($attribute, $value);
}
}
return $connection;
}
/*
* 读取语句返回一条数据
*/
public function get($sql, $params = null)
{
return ($params ? $this->prepareExecute($sql, $params) : $this->pdoQuery($sql))->fetch(\PDO::FETCH_ASSOC);
}
/*
* 读取语句返回全部数据
*/
public function find($sql, $params = null)
{
return ($params ? $this->prepareExecute($sql, $params) : $this->pdoQuery($sql))->fetchAll(\PDO::FETCH_ASSOC);
}
/*
* 更新语句返回影响数量
*/
public function exec($sql, $params = null)
{
return $params ? $this->prepareExecute($sql, $params)->rowCount() : $this->execute($sql);
}
/*
* 读取语句返回结果对象
*/
public function query($sql, $params = null)
{
return new result\Pdo($params ? $this->prepareExecute($sql, $params) : $this->pdoQuery($sql));
}
/*
* 最近插入数据id
*/
public function insertId()
{
return $this->connection->lastInsertId();
}
/*
* 转义字符串
*/
public function quote($str)
{
return $this->connection->quote($str);
}
/*
* 开始事务
*/
public function beginTransaction()
{
return $this->connection->beginTransaction();
}
/*
* 回滚事务
*/
public function rollback()
{
return $this->connection->rollBack();
}
/*
* 提交事务
*/
public function commit()
{
return $this->connection->commit();
}
/*
* 获取错误代码
*/
public function errno()
{
return ($this->connection->errorInfo())[1] ?? null;
}
/*
* 获取错误信息
*/
public function error()
{
return ($this->connection->errorInfo())[2] ?? null;
}
/*
* 执行请求
*/
protected function pdoQuery($sql)
{
$this->sqlLog($sql);
if ($query = $this->connection->query($sql)) {
return $query;
}
throw new \Exception($this->exceptionMessage());
}
protected function execute($sql)
{
$this->sqlLog($sql);
if ($result = $this->connection->exec($sql)) {
return $result;
}
throw new \Exception($this->exceptionMessage());
}
/*
* 预处理执行
*/
protected function prepareExecute($sql, $params)
{
$this->sqlLog($sql, $params);
if ($query = $this->connection->prepare($sql)) {
if ($query->execute($params)) {
return $query;
}
}
$error = $this->connection->errorInfo();
if ($error[0] === 'HY093') {
throw new \Exception('DB ERROR: Invalid parameter number');
}
throw new \Exception($this->exceptionMessage($error));
}
/*
* 异常信息
*/
protected function exceptionMessage($error = null)
{
$err = $error ?? $this->connection->errorInfo();
return "DB ERROR: [$err[1]] $err[2]";
}
/*
* 关闭连接
*/
public function close()
{
$this->connection = null;
}
}<file_sep><?php
return [
'mongo' => [
'driver' => 'mongo',
// 服务器uri
'uri' => 'mongodb://127.0.0.1',
// 数据库名
'dbname' => 'test'
],
'hbase' => [
'driver' => 'hbase',
// 服务器地址
'host' => '127.0.0.1',
// 服务器端口
'port' => 9090,
// 服务scheme文件(thrift)
'service_schemes' => [
'prefix' => [
'Hbase' => APP_DIR.'scheme/thrift/Hbase/'
],
'files' => [
APP_DIR.'scheme/thrift/Hbase/Types'
]
]
],
];
<file_sep><?php
namespace framework\driver\db\builder;
class Builder
{
// 左字段引用符
const FIELD_QUOTE_LEFT = '`';
// 右字段引用符
const FIELD_QUOTE_RIGHT = '`';
// where 逻辑符
protected static $where_logic = ['AND', 'OR', 'XOR', 'NOT', 'AND NOT', 'OR NOT', 'XOR NOT'];
// where 关系符
protected static $where_operator = ['=', '!=', '>', '>=', '<', '<=', 'LIKE', 'IN', 'IS', 'BETWEEN'];
/*
* select语句
*/
public static function select($table, array $options)
{
$params = [];
$sql = self::selectFrom($table, $options['fields'] ?? null);
if (isset($options['where'])) {
$sql .= ' WHERE '.self::whereClause($options['where'], $params);
}
if (isset($options['group'])) {
$sql .= self::groupClause($options['group']);
}
if (isset($options['having'])) {
$sql .= ' HAVING '.self::havingClause($options['having'], $params);
}
if (isset($options['order'])) {
$sql .= self::orderClause($options['order']);
}
if (isset($options['limit'])) {
$sql .= static::limitClause($options['limit']);
}
return [$sql, $params];
}
/*
* insert语句
*/
public static function insert($table, $data, $ignore = false)
{
if ($ignore) {
$sql = 'INSERT IGNORE INTO ';
} else {
$sql = 'INSERT INTO ';
}
list($fields, $values, $params) = self::insertData($data);
return [$sql.self::quoteField($table)." ($fields) VALUES ($values)", $params];
}
/*
* update语句
*/
public static function update($table, $data, $options)
{
list($set, $params) = self::setData($data);
$sql = 'UPDATE '.self::quoteField($table)." SET $set";
if (isset($options['where'])) {
$sql .= ' WHERE '.self::whereClause($options['where'], $params);
}
if (isset($options['limit'])) {
$sql .= static::limitClause($options['limit']);
}
return [$sql, $params];
}
/*
* delete语句
*/
public static function delete($table, $options)
{
$params = [];
$sql = 'DELETE FROM '.self::quoteField($table);
if (isset($options['where'])) {
$sql .= ' WHERE '.self::whereClause($options['where'], $params);
}
if (isset($options['limit'])) {
$sql .= static::limitClause($options['limit']);
}
return [$sql, $params];
}
/*
* insert数据
*/
public static function insertData($data)
{
return [
self::quoteField(implode(self::quoteField(','), array_keys($data))),
implode(',', array_fill(0, count($data), '?')),
array_values($data)
];
}
/*
* select from部分
*/
public static function selectFrom($table, array $fields = null)
{
if (!$fields) {
return "SELECT * FROM ".self::quoteField($table);
}
foreach ($fields as $field) {
if (is_array($field)) {
$count = count($field);
if ($count === 2) {
$select[] = self::quoteField($field[0]).' AS '.self::quoteField($field[1]);
} elseif ($count === 3){
$select[] = "$field[0](".($field[1] === '*' ? '*'
: self::quoteField($field[1])).') AS '.self::quoteField($field[2]);
} else {
throw new \Exception('SQL Field ERROR: '.var_export($field, true));
}
} else {
$select[] = self::quoteField($field);
}
}
return 'SELECT '.implode(',', $select).' FROM '.self::quoteField($table);
}
/*
* where语句
*/
public static function whereClause($data, &$params, $prefix = null)
{
$sql = null;
foreach ($data as $k => $v) {
$sql .= self::whereLogicClause($k, isset($sql));
if (isset($v[1]) && in_array($v[1] = strtoupper($v[1]), self::$where_operator, true)) {
$sql .= self::whereItem($prefix, $params, ...$v);
} else {
$sql .= '('.self::whereClause($v, $params, $prefix).')';
}
}
return $sql;
}
/*
* group语句
*/
public static function groupClause($field, $table = null)
{
if (is_array($field)) {
foreach ($field as $v) {
foreach ($this->db->fields($table) as $field) {
$group[] = $table ? self::quoteTableField($table, $field) : self::quoteField($field);
}
}
return 'GROUP BY '.implode(',', $group);
}
return ' GROUP BY '.($table ? self::quoteTableField($table, $field) : self::quoteField($field));
}
/*
* having语句
*/
public static function havingClause($data, &$params, $prefix = null)
{
$sql = null;
foreach ($data as $k => $v) {
$sql .= self::whereLogicClause($k, isset($sql));
$n = count($v) - 2;
if (isset($v[$n]) && in_array($v[$n] = strtoupper($v[$n]), self::$where_operator, true)) {
$sql .= self::havingItem($prefix, $params, $n - 1, $v);
} else {
$sql .= '('.self::havingClause($v, $params, $prefix).')';
}
}
return $sql;
}
/*
* order语句
*/
public static function orderClause($orders)
{
foreach ($orders as $order) {
$field = isset($order[2]) ? self::quoteTableField($order[2], $order[0]) : self::quoteField($order[0]);
$items[] = $order[1] ? "$field DESC" : $field;
}
return ' ORDER BY '.implode(',', $items);
}
/*
* limit语句
*/
public static function limitClause($limit)
{
if (is_array($limit)) {
return sprintf(' LIMIT %d, %d', $limit[0], $limit[1]);
} else {
return sprintf(' LIMIT %d', $limit);
}
}
/*
* 设置数据
*/
public static function setData($data , $glue = ',')
{
$params = $items = [];
foreach ($data as $k => $v) {
$items[] = self::quoteField($k)."=?";
$params[] = $v;
}
return [implode(" $glue ", $items), $params];
}
/*
* where 逻辑语句
*/
public static function whereLogicClause($logic, $and)
{
if (is_integer($logic)) {
if ($and) {
return ' AND ';
}
} else {
if (in_array($logic = strtoupper(strtok($logic, '#')), self::$where_logic, true)) {
return " $logic ";
}
throw new \Exception('SQL WHERE ERROR: '.var_export($logic, true));
}
}
/*
* where 单元
*/
public static function whereItem($prefix, &$params, $field, $exp, $value)
{
return ' '.(isset($prefix) ? self::quoteTableField($prefix, $field)
: self::quoteField($field)).' '.self::whereItemValue($params, $exp, $value);
}
/*
* having 单元
*/
public static function havingItem($prefix, &$params, $num, $values)
{
$sql = $values[$num] == '*' ? '*' : self::quoteField($values[$num]);
if (isset($prefix)) {
$sql = self::quoteField($prefix).".$sql";
}
if ($num == 1) {
$sql = "$values[0]($sql)";
}
return " $sql ".self::whereItemValue($params, $values[$num + 1], $values[$num + 2]);
}
/*
* where 单元值
*/
public static function whereItemValue(&$params, $exp, $value)
{
switch ($exp) {
case 'IN':
if(is_array($value)) {
$params = array_merge($params, $value);
return 'IN ('.implode(',', array_fill(0, count($value), '?')).')';
}
break;
case 'BETWEEN':
if (count($value) === 2) {
$params = array_merge($params, $value);
return 'BETWEEN ? AND ?';
}
break;
case 'IS':
if ($value === NULL) {
return 'IS NULL';
}
break;
default :
$params[] = $value;
return "$exp ?";
}
throw new \Exception("SQL where ERROR: $exp ".var_export($value, true));
}
/*
* 关键词转义
*/
public static function quoteField($field)
{
return static::FIELD_QUOTE_LEFT.$field.static::FIELD_QUOTE_RIGHT;
}
/*
* 关键词组转义
*/
public static function quoteTableField($table, $field)
{
return self::quoteField($table).'.'.self::quoteField($field);
}
}
<file_sep><?php
namespace framework\driver\db\query;
class With extends QueryChain
{
// with表名
protected $with;
// query实例
protected $query;
// 是否多条
protected $has_many;
// 字段名
protected $field_name;
/*
* 初始化
*/
protected function __init($table, $query, $with, $has_many = false, $alias = null)
{
$this->with = $with;
$this->table = $table;
$this->query = $query;
$this->has_many = $has_many;
$this->field_name = $alias ?? $with;
$this->options['where'] = [];
}
/*
* 设置关联表字段关联
*/
public function on($field1, $field2)
{
$this->options['on'] = [$field1, $field2];
return $this;
}
/*
* 查询(单条)
*/
public function get($id = null, $pk = 'id')
{
if ($data = $this->query->get($id, $pk)) {
$data = [$data];
$this->withData(1, $data);
return $data[0];
}
return null;
}
/*
* 查询(多条)
*/
public function find()
{
if ($data = $this->query->find()) {
$count = count($data);
if ($count > 1 && !array_diff(array_keys($this->options), ['on', 'fields', 'where', 'order'])) {
$this->withOptimizeData($count, $data);
} else {
$this->withData($count, $data);
}
}
return $data;
}
/*
* with表数据
*/
protected function withData($count, &$data)
{
$where = $this->options['where'];
list($field1, $field2) = $this->getOnFields();
for ($i = 0; $i < $count; $i++) {
$this->options['where'] = array_merge([[$field2, '=', $data[$i][$field1]]], $where);
$params = $this->builder::select($this->with, $this->options);
if ($this->has_many) {
$data[$i][$this->field_name] = $this->db->find(...$params);
} else {
$data[$i][$this->field_name] = $this->db->get(...$params);
}
}
}
/*
* with表数据(优化查询)
*/
protected function withOptimizeData($count, &$data)
{
list($field1, $field2) = $this->getOnFields();
$cols = array_unique(array_column($data, $field1));
array_unshift($this->options['where'], [$field2, 'IN', $cols]);
if (isset($this->options['fields']) && !in_array($field2, $this->options['fields'])) {
$this->options['fields'][] = $field2;
}
if ($with_data = $this->db->find(...$this->builder::select($this->with, $this->options))) {
if ($this->has_many) {
foreach ($with_data as $wd) {
$sub_data[$wd[$field2]][] = $wd;
}
} else {
foreach ($with_data as $wd) {
if (!isset($sub_data[$wd[$field2]])) {
$sub_data[$wd[$field2]] = $wd;
}
}
}
unset($with_data);
for ($i = 0; $i < $count; $i++) {
$data[$i][$this->field_name] = $sub_data[$data[$i][$field1]] ?? ($this->has_many ? [] : null);
}
}
}
/*
* 获取关联字段
*/
protected function getOnFields()
{
return $this->options['on'] ?? ['id', $this->table.'_id'];
}
}
<file_sep><?php
return [
'image' => [
'driver' => 'image',
// 验证码图片src
'src' => '/captcha.php',
// 提交表单post name,用来验证信息
'name' => 'image-captcha' //默认
],
'recaptcha' => [
'driver' => 'recaptcha',
// 帐号 sitekey
'acckey' => 'your_acckey',
// 帐号 secret key
'seckey' => 'your_seckey',
],
'geetest' => [
'driver' => 'geetest',
// 帐号 captchaid
'acckey' => 'your_acckey',
// 帐号 secret key
'seckey' => 'your_seckey',
// script 脚本访问地址
'script' => 'https://static.geetest.com/static/tools/gt.js' //默认
],
];<file_sep><?php
namespace framework\driver\db\builder;
class Pgsql extends Builder
{
// 左字段引用符
const FIELD_QUOTE_LEFT = '"';
// 右字段引用符
const FIELD_QUOTE_RIGHT = '"';
/*
* limit语句
*/
public static function limitClause($limit)
{
if (is_array($limit)) {
return sprintf(' LIMIT %d OFFSET %d', $limit[0], $limit[1]);
} else {
return sprintf(' LIMIT %d', $limit);
}
}
}<file_sep><?php
namespace framework\driver\rpc;
use framework\util\Arr;
use framework\core\Loader;
class Grpc
{
// client实例
protected $client;
/*
* 构造函数
*/
public function __construct($config)
{
if (isset($config['endpoint'])) {
$this->client = new client\GrpcHttp($config);
} else {
$this->client = new client\Grpc($config);
}
if (isset($config['schema_loader_rules'])) {
foreach ($config['schema_loader_rules'] as $type => $rules) {
Loader::add($type, $rules);
}
}
}
/*
* 魔术方法,query实例
*/
public function __get($name)
{
return $this->query($name);
}
/*
* query实例
*/
public function query($name = null)
{
return new query\Grpc($this->client, $name);
}
}<file_sep><?php
return [
'redis' => [
'driver' => 'redis',
//'serialize' => '',
//'unserialize' => '',
'host' => '127.0.0.1',
//'port' => '',
'database' => 9
],
'beanstalkd' => [
'driver' => 'beanstalkd',
//'serialize' => '',
//'unserialize' => '',
'host' => '127.0.0.1',
//'port' => '',
],
'amqp' => [
'driver' => 'amqp',
//'serialize' => '',
//'unserialize' => '',
'host' => '127.0.0.1',
'port' => '5672',
'vhost' => '/',
'login' => 'guest',
'password' => '<PASSWORD>'
],
'kafka' => [
'driver' => 'kafka',
//'serialize' => '',
//'unserialize' => '',
'hosts' => '127.0.0.1',
'port' => '9092',
],
];
<file_sep><?php
namespace framework\driver\rpc\client;
/*
* 协议格式 json字符串+EOL
*/
class JsonrpcTcp
{
// 换行符
const EOL = "\n";
// 套接字
protected $socket;
// 配置项
protected $config/* = [
// 服务主机(TCP)
'host'
// 服务端口(TCP)
'port'
// 连接超时(TCP)
'tcp_timeout'
// TCP是否保持连接(TCP)
'tcp_keep_alive'
]*/;
/*
* 构造函数
*/
public function __construct($config)
{
$this->config = $config;
}
/*
* 连接
*/
protected function contect()
{
$this->socket = fsockopen($this->config['host'], $this->config['port'], $errno, $errstr, $this->config['tcp_timeout'] ?? null);
if (!is_resource($this->socket)) {
error("-32000: Internet error $errstr[$errno]");
}
}
/*
* 发送请求
*/
public function send($data)
{
if (!is_resource($this->socket)) {
$this->contect();
}
$data = $this->config['requset_serialize']($data).self::EOL;
if (fwrite($this->socket, $data) === strlen($data)) {
$str = '';
$len = strlen(self::EOL);
while (($res = fgets($this->socket)) !== false) {
$str .= $res;
if (substr($res, - $len) === self::EOL) {
if (empty($this->config['tcp_keep_alive'])) {
$this->close();
}
return $this->config['response_unserialize'](substr($str, 0, - $len));
}
}
}
$this->close();
error('-32000: Invalid response');
}
/*
* 关闭连接
*/
public function close()
{
is_resource($this->socket) && fclose($this->socket);
}
/*
* 析构函数
*/
public function __destruct()
{
$this->close();
}
}
<file_sep><?php
namespace framework\driver\rpc;
class Jsonrpc
{
// 客户端实例
protected $client;
// 配置项
protected $config = [
/* 参数模式
* 0:索引数组,所有参数组成的索引数组
* 1:关联数组,取第一个参数的索引数组或基础类型
*/
'param_mode' => 0,
// 请求内容序列化
'requset_serialize' => 'jsonencode',
// 响应内容反序列化
'response_unserialize' => 'jsondecode',
];
/*
* 构造函数
*/
public function __construct($config)
{
$this->config = $config + $this->config;
if (isset($this->config['endpoint'])) {
$this->client = new client\JsonrpcHttp($this->config);
} else {
$this->client = new client\JsonrpcTcp($this->config);
}
}
/*
* 魔术方法,query实例
*/
public function __get($name)
{
return $this->query($name);
}
/*
* query实例
* $id = true 自动生成id, $id = false 不传id
*/
public function query($name = null, $id = true)
{
return new query\Jsonrpc($this->client, $this->config['param_mode'], $name, $id);
}
/*
* 批量请求
*/
public function batch(...$params)
{
foreach ($params as $i => $v) {
$params[$i]['jsonrpc'] = '2.0';
if (!array_key_exists('id', $v) || $v['id'] === true) {
$params[$i]['id'] = uniqid();
}
}
return $this->client->send($params);
}
}
<file_sep><?php
namespace framework\driver\db;
class Mysqli extends Db
{
// 构造器
const BUILDER = builder\Builder::class;
/*
* 连接数据库
*/
protected function connect($config)
{
$connection = new \mysqli(
$config['host'],
$config['username'],
$config['password'],
$config['dbname'],
$config['port'] ?? '3306',
$config['socket'] ?? null
);
if ($connection->connect_error) {
throw new \Exception("Server Connect Error [$connection->connect_errno] $connection->connect_error");
}
if (isset($config['charset'])) {
$connection->set_charset($config['charset']);
}
if (isset($config['options'])) {
foreach ($config['options'] as $option => $value) {
$connection->options($option, $value);
}
}
return $connection;
}
/*
* 读取语句返回一条数据
*/
public function get($sql, $params = null)
{
$query = $params ? $this->prepareExecute($sql, $params, true) : $this->execute($sql);
$return = $query->fetch_assoc();
$query->free();
return $return;
}
/*
* 读取语句返回全部数据
*/
public function find($sql, $params = null)
{
$query = $params ? $this->prepareExecute($sql, $params, true) : $this->execute($sql);
$return = $query->fetch_all(MYSQLI_ASSOC);
$query->free();
return $return;
}
/*
* 更新语句返回影响数量
*/
public function exec($sql, $params = null)
{
$params ? $this->prepareExecute($sql, $params) : $this->execute($sql);
return $this->connection->affected_rows;
}
/*
* 读取语句返回结果对象
*/
public function query($sql, $params = null)
{
return new result\Mysqli($params ? $this->prepareExecute($sql, $params, true) : $this->execute($sql, MYSQLI_USE_RESULT));
}
/*
* 获取最近插入数据的ID
*/
public function insertId()
{
return $this->connection->insert_id;
}
/*
* 转义字符串
*/
public function quote($str)
{
return "'".$this->connection->escape_string($str)."'";
}
/*
* 开始事务
*/
public function beginTransaction()
{
return $this->connection->autocommit(false) && $this->connection->begin_transaction();
}
/*
* 回滚事务
*/
public function rollback()
{
return $this->connection->rollback() && $this->connection->autocommit(true);
}
/*
* 提交事务
*/
public function commit()
{
return $this->connection->commit() && $this->connection->autocommit(true);
}
/*
* 获取错误代码
*/
public function errno()
{
return $this->connection->errno;
}
/*
* 获取错误信息
*/
public function error()
{
return $this->connection->error;
}
/*
* 获取表字段名
*/
public function getFields($table)
{
return array_column($this->find("desc `$table`"), 'Field');
}
/*
* 切换使用数据库
*/
public function useDatabase($dbname, callable $call)
{
$raw_dbname = $this->dbname;
try {
if ($this->connection->select_db($dbname)) {
$this->dbname = $dbname;
return $call($this);
}
} finally {
$this->dbname = $raw_dbname;
$this->connection->select_db($raw_dbname);
}
}
/*
* 执行请求
*/
protected function execute($sql, $mode = MYSQLI_STORE_RESULT)
{
$this->sqlLog($sql);
if ($result = $this->connection->query($sql, $mode)) {
return $result;
}
throw new \Exception($this->exceptionMessage());
}
/*
* 预处理执行
*/
protected function prepareExecute($sql, $params, $return_result = false)
{
$this->sqlLog($sql, $params);
$bind_params = [];
foreach ($params as $k => $v) {
$bind_params[] = &$params[$k];
}
if ($query = $this->connection->prepare($sql)) {
$type = str_pad('', count($bind_params), 's');
array_unshift($bind_params, $type);
$query->bind_param(...$bind_params);
if ($query->execute()) {
if ($return_result) {
$result = $query->get_result();
$query->close();
return $result;
}
$query->close();
return;
}
}
throw new \Exception($this->exceptionMessage());
}
/*
* 异常信息
*/
protected function exceptionMessage()
{
return 'DB ERROR: ['.$this->connection->errno.'] '.$this->connection->error;
}
/*
* 关闭连接
*/
public function close()
{
if (isset($this->connection)) {
$this->connection->close();
$this->connection = null;
}
}
/*
* 析构函数
*/
public function __destruct()
{
$this->close();
}
}
<file_sep><?php
namespace framework\core\http;
use framework\util\Arr;
use framework\util\Str;
use framework\core\Event;
use framework\core\Config;
class Session
{
private static $init;
// 会话启动设置,参考 https://www.php.net/manual/en/function.session-start.php
private static $start_options = [];
/*
* 初始化
*/
public static function __init()
{
if (self::$init) {
return;
}
self::$init = true;
if ($config = Config::read('session')) {
if (isset($config['start_options'])) {
self::$start_options = $config['start_options'];
}
if (isset($config['save_handler'])) {
session_set_save_handler(instance(...$config['save_handler']));
}
if (!empty($config['exit_event_close_write'])) {
Event::on('exit', 'session_write_close');
}
if (!($config['auto_start'] ?? true)) {
return;
}
}
self::start();
}
/*
* 开始
*/
public static function start(array $start_options = null)
{
if (session_status() != PHP_SESSION_ACTIVE) {
session_start($start_options ?? self::$start_options);
Event::trigger('session');
}
}
/*
* 获取所有
*/
public static function all()
{
return $_SESSION;
}
/*
* 获取
*/
public static function get($name, $default = null)
{
return Arr::get($_SESSION, $name, $default);
}
/*
* 获取
*/
public static function has($name)
{
return Arr::has($_SESSION, $name);
}
/*
* 设置
*/
public static function set($name, $value = null)
{
if (is_array($name)) {
if ($value) {
$_SESSION = array_replace_recursive($_SESSION, $name);
} else {
$_SESSION = $name + $_SESSION;
}
} else {
Arr::set($_SESSION, $name, $value);
}
}
/*
* 删除
*/
public static function delete($name)
{
Arr::delete($_SESSION, $name);
}
/*
* 获取并删除
*/
public static function pull($name, $default = null)
{
return Arr::pull($_SESSION, $name, $default);
}
/*
* 清除所有
*/
public static function clean($delete_cookie = false)
{
session_unset();
session_destroy();
if ($delete_cookie) {
Cookie::delete(session_name(), ...array_values(session_get_cookie_params()));
}
}
}
Session::__init();
<file_sep><?php
namespace framework\driver\db\query;
abstract class QueryChain
{
// 实例
protected $db;
// 表名
protected $table;
// 构建器
protected $builder;
// 设置项
protected $options = ['where' => null, 'fields' => null];
/*
* 构造函数
*/
public function __construct($db, ...$params)
{
$this->db = $db;
$this->builder = $db->getBuilder();
$this->__init(...$params);
}
/*
* 联表查询
*/
public function with($table, $has_many = false, $alias = null)
{
return new With($this->db, $this->table, $this, $table, $has_many, $alias);
}
/*
* 联表查询(多条数据)
*/
public function relate($table, $has_many = false, $alias = null)
{
return new Relate($this->db, $this->table, $this, $table, $has_many, $alias);
}
/*
* select字段
*/
public function select(...$fields)
{
$this->options['fields'] = $fields;
return $this;
}
/*
* 查询where条件
*/
public function where(...$where)
{
$count = count($where);
if ($count === 1 && is_array($where[0])) {
if (empty($this->options['where'])) {
$this->options['where'] = $where[0];
} else {
$this->options['where'] = array_merge($this->options['where'], $where[0]);
}
} elseif ($count === 2) {
$this->options['where'][] = [$where[0], '=', $where[1]];
} elseif ($count === 3) {
$this->options['where'][] = $where;
} else {
throw new \Exception("SQL $type ERROR: ".var_export($where, true));
}
return $this;
}
/*
* 查询where条件或
*/
public function whereOr(...$where)
{
$key = 'OR#'.count($this->options['where']);
$count = count($where);
if ($count === 1 && is_array($where[0])) {
$this->options['where'][$key] = $where[0];
} elseif ($count === 2) {
$this->options['where'][$key] = [$where[0], '=', $where[1]];
} elseif ($count === 3) {
$this->options['where'][$key] = $where;
} else {
throw new \Exception("SQL where ERROR: ".var_export($where, true));
}
return $this;
}
/*
* 查询排序
*/
public function order($field, $desc = false)
{
$this->options['order'][] = [$field, $desc];
return $this;
}
/*
* 查询分组
*/
public function group(...$fields)
{
$this->options['group'] = $fields;
return $this;
}
/*
* having条件
*/
public function having(...$having)
{
$count = count($having);
if ($count === 3 || $count === 4) {
$this->options['having'][] = $having;
} elseif ($count === 1 && is_array($having[0])) {
if (empty($this->options['having'])) {
$this->options['having'] = $having[0];
} else {
$this->options['having'] = array_merge($this->options['having'], $having[0]);
}
} else {
throw new \Exception("SQL $type ERROR: ".var_export($having, true));
}
return $this;
}
/*
* 结果限制
*/
public function limit($limit, $offset = null)
{
$this->options['limit'] = isset($offset) ? [$limit, $offset] : $limit;
return $this;
}
/*
* 结果分页
*/
public function page($page, $num)
{
$this->options['limit'] = [($page - 1) * $num, $num];
return $this;
}
}
<file_sep><?php
namespace framework\core;
use Symfony\Component\VarDumper\VarDumper;
class Debug
{
/*
* dump
*/
public static function dump(...$vars)
{
ob_start();
class_exists(VarDumper::class) ? VarDumper::dump(...$vars) : var_dump(...$vars);
return ob_get_clean();
}
}
<file_sep><?php
return [
'baidu' => [
'driver' => 'baidu',
// 申请的 acckey
'acckey' => 'your_acckey'
],
'ipip' => [
'driver' => 'ipip',
// IP数据库文件路径,本地数据库与在线接口二者同一实例只能使用其一
'database' => APP_DIR.'resource/ipdata/17monipdb.dat',
// 申请的在线接口付费账户token
'token' => '<PASSWORD>'
],
'maxmind' => [
'driver' => 'maxmind',
// IP数据库文件路径,
'database' => APP_DIR.'resource/ipdata/GeoLite2-Country.mmdb',
// 申请的在线接口付费账户acckey
'acckey' => 'your_acckey',
// 申请的在线接口付费账户seckey
'seckey' => 'your_seckey',
// (可选配置)接口类型
'apitype' => 'country',
],
];
<file_sep><?php
namespace framework\driver\email;
use framework\core\Logger;
use framework\driver\email\query\Mime;
class Smtp extends Email
{
// log
protected $log;
// 套接字
protected $socket;
// 配置
protected $config/* = [
// 主机
'host' => '127.0.0.1',
// 端口
'port' => 25,
// 加密
'secure' => '',
// 用户名
'username' => '',
// 密码
'password' => '',
// 超时设置
'timeout' => 30,
// 调试模式
'debug' => false,
// 发送后保持链接
'keep_alive' => false,
]*/;
/*
* 连接
*/
protected function connect()
{
$this->socket = fsockopen(
(isset($this->config['scheme']) ? $this->config['scheme'].'://' : '').$this->config['host'],
$this->config['port'] ?? 25,
$errno, $error,
$this->config['timeout'] ?? 30
);
if (!is_resource($this->socket)) {
throw new \Exception("Smtp connect error: [$errno] $error");
}
$this->read();
$this->command('EHLO '.$this->config['host']);
$this->command('AUTH LOGIN');
$this->command(base64_encode($this->config['username']));
return $this->commandCheck(base64_encode($this->config['password']), '235');
}
/*
* 处理请求
*/
protected function handle($options)
{
if (!is_resource($this->socket)) {
if (!$this->connect()) {
return false;
}
}
if (!$this->commandCheck("MAIL FROM: <{$options['from'][0]}>")) {
return false;
}
list($addrs, $mime) = Mime::make($options);
foreach ($addrs as $addr) {
if (!$this->commandCheck("RCPT TO: <$addr>")) {
return false;
}
}
$this->command('DATA');
if (!$this->commandCheck($mime.Mime::EOL.'.')) {
return false;
}
if (!empty($this->config['keep_alive'])) {
$this->close();
}
return true;
}
/*
* 读网络流
*/
protected function read()
{
$str = '';
while ($s = fgets($this->socket, 1024)) {
$str .= $s;
if (substr($s, 3, 1) == ' ') {
break;
}
}
if (!empty($this->config['debug'])) {
$this->log($str);
}
return trim($str);
}
/*
* 执行SMTP命令
*/
protected function command($cmd)
{
fputs($this->socket, $cmd.Mime::EOL);
return $this->read();
}
/*
* 执行命令检查错误
*/
protected function commandCheck($cmd, $check = '250')
{
$result = $this->command($cmd);
if (substr($result, 0, 3) === $check) {
return true;
}
$this->close();
if (empty($this->config['throw_response_error'])) {
return false;
}
if ($this->config['throw_response_error'] !== true) {
throw new \Exception("SMTP Email Exception: [$cmd] $result");
}
$class = $this->config['throw_response_error'];
throw new $class("SMTP Email Exception: [$cmd] $result");
}
/*
* 退出
*/
public function close()
{
if (is_resource($this->socket)) {
$this->command('QUIT');
fclose($this->socket);
}
}
/*
* 日志处理
*/
protected function log($log)
{
//Logger::channel($this->config['debug'])->debug($log);
}
/*
* 析构函数
*/
public function __destruct()
{
$this->close();
}
}<file_sep><?php
namespace framework\driver\db\query;
class SubQuery extends QueryChain
{
// 当前表名
protected $cur;
// 主表设置项
protected $master;
// 多子联表设置项
protected $table_options = [];
// 支持的子表关系式
protected static $sub_exp = ['=', '>', '<', '>=', '<=', '<>', 'ANY', 'IN', 'SOME', 'ALL', 'EXISTS'];
// 支持的子表逻辑
protected static $sub_logic = ['AND', 'OR', 'XOR', 'AND NOT', 'OR NOT', 'NOT'];
/*
* 初始化
*/
protected function __init($table, $options, $sub, $exp, $logic)
{
$this->checkExpLogic($exp, $logic);
$this->cur = $sub;
$this->table = $table;
$this->master = $options;
$this->options = ['exp' => $exp, 'logic' => $logic];
}
/*
* 子表链
*/
public function sub($sub, $exp = 'IN', $logic = 'AND')
{
$this->checkExpLogic($exp, $logic);
$this->table_options[$this->cur] = $this->options;
$this->cur = $sub;
$this->options = ['exp' => $exp, 'logic' => $logic];
return $this;
}
/*
* 设置子表字段关联
*/
public function on($fields1, $fields2 = null)
{
$this->options['on'] = [$fields1, $fields2];
return $this;
}
/*
* 查询(单条)
*/
public function get()
{
$this->table_options[$this->cur] = $this->options;
return $this->db->get(...$this->buildSelect());
}
/*
* 查询(多条)
*/
public function find()
{
$this->table_options[$this->cur] = $this->options;
return $this->db->find(...$this->buildSelect());
}
/*
* 更新数据
*/
public function update($data)
{
list($set, $params) = $this->builder::setData($data);
$sql = "UPDATE ".$this->builder::quoteField($this->table)." SET $set WHERE ".self::buildSubQuery($params);
if (isset($this->master['limit'])) {
$sql .= $this->builder::limitClause($this->master['limit']);
}
return $this->db->exec($sql, $params);
}
/*
* 删除数据
*/
public function delete()
{
$sql = "DELETE FROM ".$this->builder::quoteField($this->table).self::buildSubQuery($params);
if (isset($this->master['limit'])) {
$sql .= $this->builder::limitClause($this->master['limit']);
}
return $this->db->exec($sql, $params);
}
/*
* 生成查询语句sql
*/
protected function buildSelect()
{
$params = [];
$sql = $this->builder::selectFrom($this->table, $this->master['fields'] ?? null).' WHERE ';
$sql .= self::buildSubQuery($params);
if (isset($this->master['group'])) {
$sql .= $this->builder::groupClause($this->master['group']);
}
if (isset($this->master['having'])) {
$sql .= ' HAVING '.$this->builder::havingClause($this->master['having'], $params);
}
if (isset($this->master['order'])) {
$sql .= $this->builder::orderClause($this->master['order']);
}
if (isset($this->master['limit'])) {
$sql .= $this->builder::limitClause($this->master['limit']);
}
return [$sql, $params];
}
/*
* 生成子查询语句sql
*/
protected function buildSubQuery(&$params = [])
{
$sql = '';
if (isset($this->master['where'])) {
$sql = $this->builder::whereClause($this->master['where'], $params);
}
foreach ($this->table_options as $table => $options) {
if ($sql) {
$sql .= " {$options['logic']} ";
}
if (isset($options['on'])) {
if (is_array($options['on'][0])) {
$sql .= '('.$this->builder::quoteField(implode($this->builder::quoteField(','), $options['on'][0])).')';
} else {
$sql .= $this->builder::quoteField($options['on'][0]);
}
$sql .= " {$options['exp']} ";
if (isset($options['on'][1])) {
$options['fields'] = (array) $options['on'][1];
}
} else {
$sql .= $this->builder::quoteField('id')." {$options['exp']} ";
$options['fields'] = [$this->table.'_id'];
}
$sub = $this->builder::select($table, $options);
$sql .= "($sub[0]) ";
$params = array_merge($params, $sub[1]);
}
return $sql;
}
/*
* 检查子查询逻辑关系
*/
protected function checkExpLogic($exp, $logic)
{
if (!in_array($exp, self::$sub_exp)) {
throw new \Exception('SubQuery Exp ERROR: '.var_export($exp, true));
}
if (!in_array($logic, self::$sub_logic)) {
throw new \Exception('SubQuery Logic ERROR: '.var_export($logic, true));
}
}
}
<file_sep><?php
define('APP_DEBUG', true);
include '../../../framework/app.php';
$app = framework\App::start('Micro');
$app->route('user/*', function ($id) {
return $this->db->user->get($id);
});
if (isset($_GET['c']) && isset($_GET['a'])) {
$app->default($_GET['c'], $_GET['a']);
}
$app->run('dd');
<file_sep><?php
namespace app\auth;
use framework\App;
use framework\core\Auth;
use framework\core\http\Request;
use framework\core\http\Response;
class Base extends Auth
{
private $username = 'username';
private $password = '<PASSWORD>';
public function __construct($config)
{
$this->username = $config['username'];
$this->password = $config['<PASSWORD>'];
}
protected function id()
{
return $this->username;
}
protected function user()
{
return ['username' => $this->username];
}
protected function check()
{
return Request::server('PHP_AUTH_USER') === $this->username && Request::server('PHP_AUTH_PW') === $this->password;
}
protected function faildo()
{
Response::status(401);
Response::header('WWW-Authenticate', 'Basic');
App::exit();
}
protected function login() {}
protected function logout() {}
}
<file_sep><?php
namespace framework\driver\email\query;
use framework\util\File;
class Mime
{
// 换行符
const EOL = "\r\n";
/*
* 构建邮件
*/
public static function make($options)
{
$data = ["MIME-Version: 1.0", "Date: ".date("D, j M Y G:i:s O")];
if (isset($options['from'])) {
$data[] = 'From: '.self::makeAddr($options['from']);
}
foreach ($options['to'] as $to) {
$data[] = "To: ".self::makeAddr($to);
$addrs[] = $to[0];
}
if (isset($options['cc'])) {
foreach ($options['cc'] as $cc) {
$data[] = "CC: ".self::makeAddr($cc);
$addrs[] = $cc[0];
}
}
if (isset($options['bcc'])) {
foreach ($options['bcc'] as $bcc) {
$data[] = "BCC: ".self::makeAddr($bcc);
$addrs[] = $bcc[0];
}
}
if (isset($options['replyto'])) {
$data[] = 'Reply-To: '.self::makeAddr($options['replyto']);
}
if (isset($options['subject'])) {
$data[] = "Subject: ".self::encodeHeader($options['subject']);
}
$encoding = $options['encoding'] ?? 'quoted-printable';
$type = empty($options['ishtml']) ? 'text/plain' : 'text/html';
if (isset($options['attach'])) {
$boundary = uniqid();
$data[] = "Content-Type:multipart/mixed;boundary=\"$boundary\"";
$data[] = '';
$data[] = "--$boundary";
$data[] = "Content-Type: $type; charset=utf-8";
$data[] = "Content-Transfer-Encoding: $encoding";
$data[] = '';
$data[] = self::encodeContent($options['content'], $encoding);
$data[] = '';
$data[] = self::makeAttachments($options['attach'], $boundary);
$data[] = '';
} else {
$data[] = "Content-Type: $type; charset=utf-8";
$data[] = "Content-Transfer-Encoding: $encoding";
$data[] = '';
$data[] = self::encodeContent($options['content'], $encoding);
}
return [$addrs, implode(self::EOL, $data)];
}
/*
* 构建地址
*/
public static function makeAddr($addr)
{
return empty($addr[1]) ? "<$addr[0]>" : self::encodeHeader($addr[1])."<$addr[0]>";
}
/*
* 编码头
*/
public static function encodeHeader($str)
{
return '=?utf-8?B?'.base64_encode($str).'?=';
}
/*
* 编码内容
*/
public static function encodeContent($str, $encoding = 'quoted-printable')
{
switch ($encoding)
{
case 'base64':
return chunk_split(base64_encode($str), 76, self::EOL);
case 'quoted-printable':
return quoted_printable_encode($str);
case '7bit':
case '8bit':
$str = str_replace("\r\n", "\n", $str);
$str = str_replace("\r", "\n", $str);
$str = str_replace("\n", self::EOL, $str);
if (substr($str, - strlen(self::EOL)) != self::EOL) {
$str = $str.self::EOL;
}
return $str;
case 'binary':
return $str;
}
throw new \Exception("无效邮件编码: $encoding");
}
/*
* 构建附件
*/
public static function makeAttachments($attachs, $boundary)
{
foreach ($attachs as $attach) {
if ($attach[2]) {
$content = $attach[0];
$name = $attach[1] ?? 'attach';
} else {
$content = file_get_contents($attach[0]);
$name = $attach[1] ?? basename($attach[0]);
}
$encode_name = self::encodeHeader($name);
$mime = $attach[3] ?? File::mime($attach[0], $attach[2]);
$data[] = "--$boundary";
$data[] = "Content-Type: $mime; name=$encode_name";
$data[] = "Content-Transfer-Encoding: base64";
if (isset($attach[4])) {
$data[] = "Content-Id: <$name>";
$data[] = "Content-Disposition: inline; filename=$encode_name";
} else {
$data[] = "Content-Disposition: attachment; filename=$encode_name";
}
$data[] = '';
$data[] = self::encodeContent($content);
$data[] = '';
}
return implode(self::EOL, $data);
}
}
<file_sep><?php
namespace framework\driver\db\query;
class Query extends QueryChain
{
/*
* 初始化
*/
protected function __init($table)
{
$this->table = $table;
}
/*
* 子查询联表查询
*/
public function sub($table, $exp = 'IN', $logic = 'AND')
{
return new SubQuery($this->db, $this->table, $this->options, $table, $exp, $logic);
}
/*
* join联表查询
*/
public function join($table, $prefix = true, $type = 'LEFT')
{
return new Join($this->db, $this->table, $this->options, $table, $prefix, $type);
}
/*
* union联表查询
*/
public function union($table, $all = true)
{
return new Union($this->db, $this->table, $this->options, $table, $all);
}
/*
* 查询(单条)
*/
public function get($id = null, $pk = 'id')
{
if (isset($id)) {
$this->options['where'] = [[$pk, '=', $id]];
}
return $this->db->get(...$this->builder::select($this->table, $this->options));
}
/*
* 查询(多条)
*/
public function find()
{
return $this->db->find(...$this->builder::select($this->table, $this->options));
}
/*
* 查询返回结果对象
*/
public function query()
{
return $this->db->query(...$this->builder::select($this->table, $this->options));
}
/*
* 插入数据
*/
public function insert(array $data, $return_id = false, $ignore = false)
{
$result = $this->db->exec(...$this->builder::insert($this->table, $data, $ignore));
return $return_id ? $this->db->insertId() : $result;
}
/*
* 插入多个
*/
public function insertAll(array $datas, $ignore = false)
{
if ($ignore) {
$sql = 'INSERT IGNORE INTO ';
} else {
$sql = 'INSERT INTO ';
}
list($fields, $values, $params) = $this->builder::insertData(array_shift($datas));
$sql .= $this->builder::quoteField($this->table)." ($fields) VALUES ($values)";
foreach ($datas as $data) {
$sql .= ", ($values)";
$params = array_merge($params, array_values($data));
}
return $this->db->exec($sql, $params);
}
/*
* 替换数据
*/
public function replace(array $data)
{
$set = $this->builder::setData($data);
$sql = 'REPLACE INTO '.$this->builder::quoteField($this->table)." SET $set[0]";
return $this->db->exec($sql, $set[1]);
}
/*
* 更新数据
*/
public function update($data, $id = null, $pk = 'id')
{
if (isset($id)) {
$this->options['where'] = [[$pk, '=', $id]];
}
return $this->db->exec(...$this->builder::update($this->table, $data, $this->options));
}
/*
* 数据自增自减
*/
public function updateAuto($auto, $data = null, $id = null, $pk = 'id')
{
if (isset($id)) {
$this->options['where'] = [[$pk, '=', $id]];
}
foreach ($auto as $key => $val) {
$v = $this->builder::quoteField($key);
$val = (int) $val;
$set[] = $val > 0 ? "$v = $v+$val" : "$v = $v$val";
}
$params = [];
if ($data) {
list($dataset, $params) = $this->builder::setData($data);
$set[] = $dataset;
}
$sql = ' SET '.implode(',', $set).' WHERE '.$this->builder::whereClause($this->options['where'], $params);
if (isset($this->options['limit'])) {
$sql .= $this->limitClause($this->options['limit']);
}
return $this->db->exec('UPDATE '.$this->builder::quoteField($this->table).$sql, $params);
}
/*
* 删除数据
*/
public function delete($id = null, $pk = 'id')
{
if (isset($id)) {
$this->options['where'] = [[$pk, '=', $id]];
}
return $this->db->exec(...$this->builder::delete($this->table, $this->options));
}
}
<file_sep><?php
namespace framework\util;
class Arr
{
/*
* 获取
*/
public static function get(array $array, $name, $default = null)
{
if (!is_array($name)) {
$name = explode('.', $name);
}
foreach ($name as $n) {
if (isset($array[$n])) {
$array = $array[$n];
} else {
return $default;
}
}
return $array;
}
/*
* 设置
*/
public static function set(array &$array, $name, $value)
{
if (!is_array($name)) {
$name = explode('.', $name);
}
foreach ($name as $n) {
if (!isset($array[$n]) || !is_array($array[$n])) {
$array[$n] = [];
}
$array =& $array[$n];
}
$array = $value;
}
/*
* 检查
*/
public static function has(array $array, $name)
{
if (!is_array($name)) {
$name = explode('.', $name);
}
foreach ($name as $n) {
if (isset($array[$n])) {
$array = $array[$n];
} else {
return false;
}
}
return true;
}
/*
* 删除
*/
public static function delete(array &$array, $name)
{
if (!is_array($name)) {
$name = explode('.', $name);
}
$ln = array_pop($name);
foreach ($name as $n) {
if (!isset($array[$n])) {
return;
}
$array =& $array[$n];
}
if (isset($array[$ln])) {
unset($array[$ln]);
}
}
/*
* 获取并删除
*/
public static function pull(array &$array, $name, $default = null)
{
if (!is_array($name)) {
$name = explode('.', $name);
}
$ln = array_pop($name);
foreach ($name as $n) {
if (!isset($array[$n])) {
return;
}
$array =& $array[$n];
}
if (isset($array[$ln])) {
$value = $array[$ln];
unset($array[$ln]);
return $value;
}
return $default;
}
/*
* 随机值
*/
public static function random(array $array)
{
return $array[array_rand($array)];
}
/*
* 首值
*/
public static function head(array $array)
{
if (PHP_VERSION_ID >= 70300) {
return $array[array_key_first($array)];
}
foreach ($array as $value) {
return $value;
}
}
/*
* 首键
*/
public static function headKey(array $array)
{
if (PHP_VERSION_ID >= 70300) {
return array_key_first($array);
} else {
foreach ($array as $key => $value) {
return $key;
}
}
}
/*
* 尾值
*/
public static function last(array $array)
{
if (PHP_VERSION_ID >= 70300) {
return $array[array_key_last($array)];
} else {
return end($array);
}
}
/*
* 尾键
*/
public static function lastKey(array $array)
{
if (PHP_VERSION_ID >= 70300) {
return array_key_last($array);
} else {
end($array);
return key($array);
}
}
/*
* 序号取值
*/
public static function index(array $array, int $index, $default = null)
{
return ($v = array_slice($array, $index, 1)) ? current($v) : $default;
}
/*
* 是否为哈希数组
*/
public static function isAssoc(array $array)
{
return !array_diff_key($array, array_keys($array));
}
/*
* 是否为list数组
*/
public static function isList(array $array)
{
return PHP_VERSION_ID > 80100 ? array_is_list($array) : array_diff_key($array, array_keys($array));
}
/*
* 获取部分键
*/
public static function pick(array $array , array $keys)
{
foreach ($keys as $key) {
if (isset($array[$key])) {
$return[$key] = $array[$key];
}
}
return $return ?? [];
}
/*
* 过滤键
*/
public static function fitlerKeys(array $array , array $keys)
{
foreach ($keys as $key) {
if (isset($array[$key])) {
$return[$key] = $array[$key];
}
}
return $return ?? [];
}
}
<file_sep><?php
namespace framework\core;
use framework\driver\logger\Logger as LoggerDriver;
class Logger
{
/*
* 日志等级
*/
const EMERGENCY = 'emergency';
const ALERT = 'alert';
const CRITICAL = 'critical';
const ERROR = 'error';
const WARNING = 'warning';
const NOTICE = 'notice';
const INFO = 'info';
const DEBUG = 'debug';
private static $init;
// 日志驱动处理器
private static $handlers;
// 空日志处理器
private static $null_handler;
// 分级日志处理器
private static $level_handler;
// 分组日志处理器
private static $group_handlers;
// 分级日志包含的处理器名集合
private static $level_handler_names;
// 分组日志包含的处理器名集合
private static $group_handler_names;
/*
* 初始化
*/
public static function __init()
{
if (self::$init) {
return;
}
self::$init = true;
if ($configs = Config::get('logger')) {
foreach ($configs as $name => $config) {
self::$handlers[$name] = null;
if (isset($config['level'])) {
foreach ((array) $config['level'] as $lv) {
self::$level_handler_names[$lv][] = $name;
}
}
if (isset($config['group'])) {
foreach ((array) $config['group'] as $gp) {
self::$group_handler_names[$gp][] = $name;
}
}
}
}
}
/*
* 写入emergency日志
*/
public static function emergency($message, $context = null)
{
self::write(__FUNCTION__, $message, $context);
}
/*
* 写入alert日志
*/
public static function alert($message, $context = null)
{
self::write(__FUNCTION__, $message, $context);
}
/*
* 写入critical日志
*/
public static function critical($message, $context = null)
{
self::write(__FUNCTION__, $message, $context);
}
/*
* 写入error日志
*/
public static function error($message, $context = null)
{
self::write(__FUNCTION__, $message, $context);
}
/*
* 写入warning日志
*/
public static function warning($message, $context = null)
{
self::write(__FUNCTION__, $message, $context);
}
/*
* 写入notice日志
*/
public static function notice($message, $context = null)
{
self::write(__FUNCTION__, $message, $context);
}
/*
* 写入info日志
*/
public static function info($message, $context = null)
{
self::write(__FUNCTION__, $message, $context);
}
/*
* 写入debug日志
*/
public static function debug($message, $context = null)
{
self::write(__FUNCTION__, $message, $context);
}
/*
* 写入分级日志
*/
public static function write($level, $message, $context = null)
{
if (isset(self::$level_handler_names[$level])) {
foreach (self::$level_handler_names[$level] as $n) {
self::getHandler($n)->write($level, $message, $context);
}
}
}
/*
* 写入分组日志
*/
public static function groupWrite($group, $level, $message, $context = null)
{
$names = is_array($group) ? $group : (self::$group_handler_names[$group] ?? null);
if ($names) {
foreach ($names as $n) {
self::getHandler($n)->write($level, $message, $context);
}
}
}
/*
* 获取实例
*/
public static function get($name = null)
{
return self::getHandler($name ?? key(self::$handlers));
}
/*
* 获取组实例
*/
public static function group($name)
{
return is_array($name) ? self::makeGroupHandler($name) : self::getGroupHandler($name);
}
/*
* 频道实例
*/
public static function channel($name = null, $enable_null_handler = false)
{
if (!isset($name)) {
return self::getLevelHandler();
}
if (array_key_exists($name, self::$handlers)) {
return self::getHandler($name);
}
if (isset(self::$group_handler_names[$name])) {
return self::getGroupHandler($name);
}
if (is_array($name)) {
return self::makeGroupHandler($name, $enable_null_handler);
}
if ($enable_null_handler) {
return self::getNullHandler();
}
}
/*
* 日志实例
*/
private static function getHandler($name, $enable_null_handler = false)
{
if (isset(self::$handlers[$name])) {
return self::$handlers[$name];
} elseif (array_key_exists($name, self::$handlers)) {
return self::$handlers[$name] = Container::driver('logger', $name);
} elseif ($enable_null_handler) {
return self::getNullHandler();
}
throw new \Exception("日志处理器实例不存在: $name");
}
/*
* 空日志实例
*/
private static function getNullHandler()
{
return self::$null_handler ?? self::$null_handler = new class () extends LoggerDriver {
public function write($level, $message, $context = null) {}
};
}
/*
* 分级日志实例
*/
private static function getLevelHandler()
{
return self::$level_handler ?? self::$level_handler = new class () extends LoggerDriver {
public function write($level, $message, $context = null) {
Logger::write($level, $message, $context);
}
};
}
/*
* 分组日志实例
*/
private static function getGroupHandler($name)
{
if (isset(self::$group_handlers[$name])) {
return self::$group_handlers[$name];
} elseif (isset(self::$group_handler_names[$name])) {
return self::$group_handlers[$name] = self::makeGroupHandler(self::$group_handler_names[$name]);
}
throw new \Exception("分组日志实例不存在: $name");
}
/*
* 生成组实例
*/
private static function makeGroupHandler($names, $enable_null_handler = false)
{
return new class ($names, $enable_null_handler) extends LoggerDriver {
private $names;
private $enable_null_handler;
public function __construct($names, $enable_null_handler) {
$this->names = $names;
$this->enable_null_handler = $enable_null_handler;
}
public function write($level, $message, $context = null) {
foreach ($this->names as $n) {
Logger::getHandler($n, $this->enable_null_handler)->write($level, $message, $context);
}
}
};
}
}
Logger::__init();
<file_sep><?php
$example_host = 'example.com';
switch ($_SERVER['HTTP_HOST']) {
case "standard.$example_host":
include 'index_standard.php';
break;
case "rest.$example_host":
include 'index_rest.php';
break;
case "inline.$example_host":
include 'index_inline.php';
break;
case "jsonrpc.$example_host":
include 'index_jsonrpc.php';
break;
case "micro.$example_host":
include 'index_micro.php';
break;
case "grpc.$example_host":
include 'index_grpc.php';
break;
/*case "view.$example_host":
include 'index_view.php';
break;*/
/*case "graphql.$example_host":
include 'index_graphql.php';
break;*/
}
<file_sep><?php
namespace framework\driver\rpc\query;
class Resource
{
// namespace
protected $ns;
// client实例
protected $client;
// http method
protected $method;
// 配置
protected $config = [
// 标准方法
'standard_methods' => [
'get' => 'GET',
'list' => 'GET',
'create' => 'POST',
'update' => 'POST',
'delete' => 'DELETE',
],
// 自定义方法前缀符
'custom_method_prefix' => '/',
];
// filter设置
protected $filters;
// headers设置
protected $headers;
/*
* 构造函数
*/
public function __construct($client, $config, $path, $filters, $headers, $method)
{
$this->ns = explode('/', $path);
$this->client = $client;
$this->config = array_intersect_key($this->config, $config) + $this->config;
$this->filters = $filters;
$this->headers = $headers;
if ($method) {
$m = strtoupper($method);
if (in_array($m, ['GET', 'POST', 'DELETE', 'PUT', 'PATCH', 'OPTIONS'])) {
$this->method = $m;
} else {
throw new \Exception('Call to undefined method '.__CLASS__."::$method");
}
}
}
/*
* 魔术方法,调用rpc方法
*/
public function __call($name, $params)
{
$data = null;
if ($params) {
$i = count($params) - 1;
if (is_array($params[$i]) || is_object($params[$i])) {
$data = array_pop($params);
}
}
foreach ($this->ns as $i => $v) {
if ($v === '*') {
if ($params) {
$this->ns[$i] = urlencode(array_shift($params));
} else {
throw new \Exception('Resource error:'.implode('/', $this->ns));
}
}
}
$n = strtolower($name);
if (isset($this->config['standard_methods'][$n])) {
return $this->call($this->config['standard_methods'][$n], $data);
} else {
return $this->call(isset($data) ? 'POST' : 'GET', $data, $name);
}
}
/*
* 调用
*/
protected function call($method, $data = null, $custom_method = null)
{
$path = implode('/', $this->ns);
if ($custom_method) {
$path .= $this->config['custom_method_prefix'].$custom_method;
}
return $this->client->send($this->method ?? $method, $path, $this->filters, $data, $this->headers);
}
}<file_sep><?php
namespace framework\exception;
class ErrorException extends \ErrorException
{
protected $trace;
public function __construct($message, $severity, $file, $line, $trace)
{
$this->trace = $trace;
parent::__construct($message, 0, $severity, $file, $line);
}
public function getUsertrace()
{
return $this->trace;
}
}
<file_sep><?php
namespace framework\driver\rpc;
class Resource
{
// client实例
protected $client;
// 配置
protected $config;
/*
* 构造函数
*/
public function __construct($config)
{
$this->config = $config;
$this->client = new client\Http($config);
}
/*
* query实例
*/
public function query($name, $filters = null, $headers = null, $method = null)
{
return new query\Resource($this->client, $this->config, $name, $filters, $headers, $method);
}
}<file_sep><?php
namespace framework\driver\rpc\query;
class Httprpc
{
// namespace
protected $ns;
// client实例
protected $client;
// filter设置
protected $filters;
// http method
protected $method;
// headers设置
protected $headers;
/*
* 构造函数
*/
public function __construct($client, $name, $filters, $headers, $method)
{
if ($name) {
$this->ns[] = $name;
}
$this->client = $client;
$this->filters = $filters;
$this->headers = $headers;
if ($method) {
$m = strtoupper($method);
if (in_array($m, ['GET', 'POST', 'DELETE', 'PUT', 'PATCH', 'OPTIONS')]) {
$this->method = $m;
} else {
throw new \Exception('Call to undefined method '.__CLASS__."::$method");
}
}
}
/*
* 魔术方法,设置namespace
*/
public function __get($name)
{
$this->ns[] = $name;
return $this;
}
/*
* 魔术方法,调用rpc方法
*/
public function __call($name, $params)
{
$this->ns[] = $name;
return $this->call($this->method ?? (isset($params[0]) ? 'POST' : 'GET'), ...$params);
}
/*
* 调用
*/
protected function call($method, $data = null)
{
return $this->client->send($method, implode('/', $this->ns), $this->filters, $data, $this->headers);
}
}<file_sep><?php
namespace framework\core\http;
use framework\util\Str;
use framework\util\File;
class Uploaded
{
// 文件信息
private $file;
// 图片实例
private $image;
// 是否验证
private $is_valid;
// 是否成功
private $is_success;
// 错误信息
private static $error = [
UPLOAD_ERR_OK => 'UPLOAD_ERR_OK',
UPLOAD_ERR_INI_SIZE => 'UPLOAD_ERR_INI_SIZE',
UPLOAD_ERR_FORM_SIZE => 'UPLOAD_ERR_FORM_SIZE',
UPLOAD_ERR_PARTIAL => 'UPLOAD_ERR_PARTIAL',
UPLOAD_ERR_NO_FILE => 'UPLOAD_ERR_NO_FILE',
UPLOAD_ERR_NO_TMP_DIR => 'UPLOAD_ERR_NO_TMP_DIR',
UPLOAD_ERR_CANT_WRITE => 'UPLOAD_ERR_CANT_WRITE'
];
/*
* 文件实例,如设置验证规则验证失败返回false
*/
public static function file($name, $check = null)
{
$instance = new self(Request::file($name));
if ($check) {
$instance->check($check);
}
return $instance;
}
/*
* 构造函数
*/
public function __construct(array $file)
{
$this->file = $file;
$this->is_valid =
$this->is_success = isset($file['error']) && $file['error'] === UPLOAD_ERR_OK &&
isset($file['tmp_name']) && is_uploaded_file($file['tmp_name']);
}
/*
* 是否成功
*/
public function isSuccess()
{
return $this->is_success;
}
/*
* 文件名
*/
public function name()
{
return $this->file['name'] ?? null;
}
/*
* 文件大小
*/
public function size()
{
return $this->file['size'] ?? null;
}
/*
* 文件类型
*/
public function type()
{
return $this->file['type'] ?? null;
}
/*
* 文件路径
*/
public function path()
{
return $this->file['tmp_name'] ?? null;
}
/*
* 文件扩展名
*/
public function ext()
{
if (isset($this->file['name'])) {
return $this->file['extension'] ?? $this->file['extension'] = File::ext($this->file['name']);
}
}
/*
* 文件mime
*/
public function mime()
{
if (isset($this->file['tmp_name'])) {
return $this->file['mime_type'] ?? $this->file['mime_type'] = File::mime($this->file['tmp_name']);
}
}
/*
* 保存文件
*/
public function saveTo($dir)
{
$name = $this->randName();
return $this->saveAs(Str::lastPad($dir, '/').$name) ? $name : false;
}
/*
* 保存文件
*/
public function saveAs($path)
{
return $this->is_valid && File::makeDir(dirname($path)) && move_uploaded_file($this->file['tmp_name'], $path);
}
/*
* 上传到储存器
*/
public function uploadTo($dir, $ext = null)
{
$name = $this->randName($ext);
return $this->uploadAs(Str::lastPad($dir, '/').$name) ? $name : false;
}
/*
* 上传到储存器
*/
public function uploadAs($path)
{
return $this->is_valid && File::upload($this->file['tmp_name'], $path);
}
/*
* 检查文件
*/
public function check($check = null)
{
if (!$this->is_success) {
return false;
}
if ($check) {
if ((isset($check['ext']) && !in_array($this->ext(), $check['ext'])) ||
(isset($check['type']) && !in_array($this->type(), $check['type'])) ||
(isset($check['mime']) && !in_array($this->mime(), $check['mime'])) ||
(!empty($check['image']) && !$this->image($check['image']))
) {
return $this->is_valid = false;
}
if (isset($check['size'])) {
$size = $this->size();
if (is_array($check['size'])) {
if ($size < $check['size'][0] || $size > $check['size'][1]) {
return $this->is_valid = false;
}
} elseif ($size > $check['size']) {
return $this->is_valid = false;
}
}
}
return $this->is_valid = true;
}
/*
* 获取错误信息
*/
public function errno()
{
return $this->file['error'] ?? null;
}
public function error()
{
return self::$error[$this->file['error']] ?? null;
}
/*
* 随机名
*/
protected function randName($ext = null)
{
$name = hash_hmac('md5', $this->path(), random_bytes(16));
if (isset($ext)) {
if ($ext === false) {
return $name;
}
return "$name.$ext";
}
return $name.'.'.$this->ext();
}
}
<file_sep><?php
return [
'openssl' => [
'driver' => 'openssl',
// 设置加密key
'key' => 'your_key',
// 设置加密iv
//'iv' => 'your_iv',
// 加密算法
'method' => 'AES-128-CBC' //默认
/*(可选配置)默认为空
* 设置加密值的序列化和反序列化处理器
* 如果缓存值没有数组等复合类型只有字符串等,也可以不设置此项
*/
//'serializer' => ['jsonencode', 'jsondecode']
],
'sodium' => [
'driver' => 'sodium',
// 设置加密key
'key' => 'your_key',
// 设置加密nonce
//'nonce' => 'your_nonce',
//'serializer' => ['jsonencode', 'jsondecode']
]
];<file_sep><?php
namespace framework\core\app;
use framework\App;
use framework\util\Str;
use framework\core\View;
use framework\core\Config;
use framework\core\Dispatcher;
use framework\core\http\Status;
use framework\core\http\Request;
use framework\core\http\Response;
class Standard extends App
{
protected $config = [
// 调度模式,支持default route组合
'dispatch_mode' => ['default'],
// 控制器namespace
'controller_ns' => 'controller',
// 控制器类名后缀
'controller_suffix' => null,
// 是否启用视图
'enable_view' => false,
// 视图模版路径是否转为下划线风格
'template_path_to_snake' => false,
/* 默认调度的参数模式
* 0 无参数
* 1 顺序参数
* 2 键值参数
* 3 数组参数
*/
'default_dispatch_param_mode' => 1,
// 控制器类namespace深度,0为不确定
'default_dispatch_depth' => 1,
// 默认调度的缺省调度
'default_dispatch_index' => null,
// 默认调度的控制器,为空不限制
'default_dispatch_controllers' => null,
// 默认调度的控制器缺省方法
'default_dispatch_default_action' => null,
// 默认调度的路径转为驼峰风格
'default_dispatch_to_camel' => null,
// 路由调度的参数模式
'route_dispatch_param_mode' => 1,
// 路由调度的路由表,如果值为字符串则作为配置名引入
'route_dispatch_routes' => null,
// 是否路由动态调度
'route_dispatch_dynamic' => false,
// 路由调度是否允许访问受保护的方法
'route_dispatch_access_protected' => false,
// 设置动作调度路由属性名,为null则不启用动作路由
'action_dispatch_routes_property' => 'routes',
];
/*
* 调度
*/
protected function dispatch()
{
$path = App::getPathArr();
foreach ((array) $this->config['dispatch_mode'] as $mode) {
if (($dispatch = $this->{$mode.'Dispatch'}($path)) !== null) {
return $this->dispatch = $dispatch;
}
}
}
/*
* 调用
*/
protected function call()
{
return ($this->dispatch['instance'])->{$this->dispatch['action']}(...$this->dispatch['params']);
}
/*
* 错误
*/
protected function error($code = null, $message = null)
{
Response::code($code ?? 500);
if ($this->config['enable_view']) {
Response::html(View::error($code, $message));
} else {
Response::json(['error' => compact('code', 'message')]);
}
}
/*
* 响应
*/
protected function respond($return = [])
{
if ($this->config['enable_view']) {
Response::view($this->getViewPath(), $return);
} else {
Response::json(['result' => $return]);
}
}
/*
* 默认调度
*/
protected function defaultDispatch($path)
{
$count = count($path);
$depth = $this->config['default_dispatch_depth'];
$to_came = $this->config['default_dispatch_to_camel'];
$param_mode = $this->config['default_dispatch_param_mode'];
if (isset($this->dispatch['continue'])) {
$instance = $this->dispatch['instance'];
list($controller, $params) = $this->dispatch['continue'];
if ($params) {
$action = array_shift($params);
if ($params && $param_mode == 0) {
return;
}
if ($to_came) {
$action = Str::camelCase($action, $to_came);
}
$check_params = true;
} elseif ($this->config['default_dispatch_default_action']) {
$action = $this->config['default_dispatch_default_action'];
} else {
return;
}
} else {
if (!$path) {
if (!$this->config['default_dispatch_index']) {
return;
}
$index = $this->config['default_dispatch_index'];
list($controller, $action) = explode('::', Dispatcher::parseDispatch($index));
} else {
if ($depth > 0) {
if ($count >= $depth) {
$allow_action_route = true;
$controller_array = array_slice($path, 0, $depth);
if ($count == $depth) {
if ($this->config['default_dispatch_default_action']) {
$action = $this->config['default_dispatch_default_action'];
$is_default_action = true;
}
} else {
$check_params = true;
if ($count == $depth + 1) {
$action = $path[$depth];
} elseif ($param_mode > 0) {
$action = $path[$depth];
$params = array_slice($path, $depth + 1);
}
}
}
} elseif ($count > 1 && $param_mode == 0) {
$action = array_pop($path);
$controller_array = $path;
}
if (!isset($controller_array) || !isset($action)) {
return;
}
if ($to_came) {
if (!isset($is_default_action)) {
$action = Str::camelCase($action, $to_came);
}
$controller_array[] = Str::camelCase(array_pop($controller_array), $to_came);
}
$controller = implode('\\', $controller_array);
if (!isset($this->config['default_dispatch_controllers'])) {
$check = true;
} elseif (!in_array($controller, $this->config['default_dispatch_controllers'])) {
return;
}
}
if (!$class = $this->getControllerClass($controller, isset($check))) {
return;
}
$instance = new $class();
}
if (is_callable([$instance, $action]) && $action[0] !== '_') {
if (!isset($params)) {
$params = [];
}
if (isset($check_params)) {
$reflection = new \ReflectionMethod($instance, $action);
if ($param_mode == 1 && !$this->checkMethodParamsNumber($reflection, count($params))) {
return;
}
if ($param_mode == 2) {
if (($params = $this->getMethodKvParams($params)) === false ||
($params = $this->bindMethodKvParams($reflection, $params, true)) === false
) {
return;
}
}
}
return compact('action', 'controller', 'instance', 'params');
} elseif (isset($allow_action_route)) {
$this->dispatch = ['continue' => [$controller, array_slice($path, $depth)], 'instance' => $instance];
}
}
/*
* 路由调度
*/
protected function routeDispatch($path)
{
$param_mode = $this->config['route_dispatch_param_mode'];
if (isset($this->dispatch['continue']) && $this->config['action_dispatch_routes_property']) {
$action_route_dispatch = $this->actionRouteDispatch(
$param_mode,
$this->dispatch['instance'],
$this->dispatch['continue'][0],
$this->dispatch['continue'][1]
);
if (isset($action_route_dispatch)) {
return $action_route_dispatch;
}
}
if ($this->config['route_dispatch_routes']) {
$routes = $this->config['route_dispatch_routes'];
if (is_string($routes) && !($routes = Config::read($routes))) {
return;
}
if ($dispatch = Dispatcher::route($path, $routes, $param_mode, $this->config['route_dispatch_dynamic'])) {
$call = explode('::', $dispatch[0]);
$class = $this->getControllerClass($call[0], $dispatch[2]);
$instance = new $class();
if (isset($call[1])) {
if ($dispatch[2]) {
if (!is_callable([$instance, $call[1]]) || $call[1][0] === '_') {
return false;
}
} elseif ($this->config['route_dispatch_access_protected']) {
$reflection = $this->setMethodAccessible($instance, $call[1]);
}
if ($param_mode == 2) {
$dispatch[1] = $this->bindMethodKvParams($reflection ?? new \ReflectionMethod($instance, $call[1]), $dispatch[1]);
}
return [
'controller' => $call[0],
'instance' => $instance,
'action' => $call[1],
'params' => $dispatch[1],
];
} elseif(isset($dispatch[3])) {
if ($this->config['action_dispatch_routes_property']) {
$action_route_dispatch = $this->actionRouteDispatch(
$param_mode,
$instance,
$call[0],
$dispatch[3]
);
if (isset($action_route_dispatch)) {
return $action_route_dispatch;
}
}
$this->dispatch = ['continue' => [$dispatch[0], $dispatch[3]], 'instance' => $instance];
return;
}
throw new \Exception("无效的路由dispatch规则: $call");
}
}
}
/*
* Action 路由调度
*/
protected function actionRouteDispatch($param_mode, $instance, $controller, $path)
{
$property = $this->config['action_dispatch_routes_property'];
if (!isset($instance->$property)) {
return;
}
if ($dispatch = Dispatcher::route(
$path,
$instance->$property,
$param_mode,
$this->config['route_dispatch_dynamic']
)) {
if ($dispatch[2]) {
if (!is_callable([$instance, $dispatch[0]]) || $dispatch[0][0] === '_') {
return false;
}
} elseif ($this->config['route_dispatch_access_protected']) {
$reflection = $this->setMethodAccessible($instance, $dispatch[0]);
}
if ($param_mode == 2) {
$dispatch[1] = $this->bindMethodKvParams($reflection ?? new \ReflectionMethod($instance, $dispatch[0]), $dispatch[1]);
}
return [
'controller' => $controller,
'instance' => $instance,
'action' => $dispatch[0],
'params' => $dispatch[1],
];
}
return false;
}
/*
* 获取视图路径
*/
protected function getViewPath()
{
$path = $this->dispatch['controller'];
if (empty($this->config['template_path_to_snake'])) {
return '/'.strtr($path, '\\', '/').'/'.$this->dispatch['action'];
} else {
$array = explode('\\', $path);
$array[] = Str::snakeCase(array_pop($array));
$array[] = Str::snakeCase($this->dispatch['action']);
return '/'.implode('/', $array);
}
}
/*
* 获取键值参数
*/
protected function getMethodKvParams(array $arr)
{
$len = count($arr);
if ($len % 2 != 0) {
return false;
}
for ($i = 1; $i < $len; $i = $i + 2) {
$params[$arr[$i-1]] = $arr[$i];
}
return $params ?? [];
}
/*
* 设置控制器方法访问权限
*/
protected function setMethodAccessible($instance, $action)
{
if (!is_callable([$instance, $action])) {
$reflection = new \ReflectionMethod($instance, $action);
if ($reflection->isProtected()) {
$reflection->setAccessible(true);
}
return $reflection;
}
}
/*
* 检查方法参数数
*/
protected function checkMethodParamsNumber($reflection, $number)
{
return $number >= $reflection->getNumberOfRequiredParameters() && $number <= $reflection->getNumberOfParameters();
}
}
<file_sep><?php
namespace framework\driver\logger;
abstract class Logger
{
// 日志
protected $logs;
/*
* 写入
*/
public function write($level, $message, $context = null)
{
$this->logs[] = [$level, $message, $context];
}
/*
* 纪录日志
*/
public function log($level, $message, $context = null)
{
$this->write($level, $message, $context);
}
/*
* emergency等级
*/
public function emergency($message, $context = null)
{
$this->write(__FUNCTION__, $message, $context);
}
/*
* alert等级
*/
public function alert($message, $context = null)
{
$this->write(__FUNCTION__, $message, $context);
}
/*
* critical等级
*/
public function critical($message, $context = null)
{
$this->write(__FUNCTION__, $message, $context);
}
/*
* error等级
*/
public function error($message, $context = null)
{
$this->write(__FUNCTION__, $message, $context);
}
/*
* warning等级
*/
public function warning($message, $context = null)
{
$this->write(__FUNCTION__, $message, $context);
}
/*
* notice等级
*/
public function notice($message, $context = null)
{
$this->write(__FUNCTION__, $message, $context);
}
/*
* info等级
*/
public function info($message, $context = null)
{
$this->write(__FUNCTION__, $message, $context);
}
/*
* debug等级
*/
public function debug($message, $context = null)
{
$this->write(__FUNCTION__, $message, $context);
}
/*
* 清理日志
*/
public function clean()
{
$this->logs = null;
}
}
| 30a70ca3ea24ab7c6c599f114d42bdfe445a3420 | [
"Markdown",
"PHP"
] | 134 | PHP | qiu-jin/phpegg | f76350e6ab9884833cf9e24b2def886be4a1061d | 1ca84906456536d99c265ff173f11e64234ae371 |
refs/heads/master | <file_sep>import smtplib
import yaml
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from flask import Blueprint, request, url_for, render_template
from flask_login import current_user
from werkzeug.exceptions import abort
from werkzeug.utils import redirect
from classget import db
from classget.admin.forms import UpdateClassForm
from classget.models import Subject, Review, get_count
from classget.reviews.forms import ReviewForm
reviews = Blueprint('reviews', __name__)
yml = yaml.load(open('classget/configure.yaml'), Loader=yaml.BaseLoader)
@reviews.route("/classinfo/<int:subject_id>", methods=["GET", "POST"])
def classinfo(subject_id):
# PKのIDでその授業の情報を持ってくる
subject = Subject.query.get_or_404(subject_id)
page = request.args.get('page', 1, type=int)
form = ReviewForm()
subject_keyword = subject.keyword.split(' ')
# 授業IDでその授業のレビューを全部持ってくる
reviews = Review.query.filter_by(subject_id=subject_id).order_by(Review.date_posted.desc())
reviews_num = get_count(reviews)
reviews = reviews.paginate(page=page, per_page=5)
# レビューに基づいたおすすめ授業(3つ)
recommended = subject.recommended_by_review()
# レビューフォームを提出したら
if form.validate_on_submit():
# ログインしている場合
if current_user.is_authenticated:
# キーワードをListから一つのStringにする
keywords = ' '.join([str(i) for i in form.keyword.data])
# レビューをデータベースに入れる
review = Review(title=form.title.data, rating=form.rating.data, content=form.content.data,
keyword=keywords, author=current_user, subject_id=subject_id)
db.session.add(review)
db.session.commit()
return redirect(request.referrer)
# ログインしていない場合→ログイン画面へ
else:
return redirect(url_for('users.login'))
return render_template('reviews/classinfo.html', title=subject.name, subject=subject, form=form, reviews=reviews,
enumerate=enumerate, subject_keyword=subject_keyword, get_count=get_count, Review=Review,
recommended=recommended, reviews_num=reviews_num)
@reviews.route("/delete_review/<int:review_id>_<int:subject_id>", methods=["GET"])
def delete_review(review_id, subject_id):
review = Review.query.get_or_404(review_id)
if review.author != current_user:
abort(403)
db.session.delete(review)
db.session.commit()
return redirect(url_for('reviews.classinfo', subject_id=subject_id))
@reviews.route("/report/<int:subject_id>", methods=["GET", "POST"])
def report(subject_id):
subject = Subject.query.get_or_404(subject_id)
form = UpdateClassForm()
if form.validate_on_submit():
# 送信者情報
sender = "<EMAIL>"
sender_password = yml['<PASSWORD>']
# メールサーバーにログイン
s = smtplib.SMTP_SSL('smtp.gmail.com')
s.login(sender, sender_password)
# 宛名
receiver = "<EMAIL>"
# メール送信情報
msg = MIMEMultipart('alternative')
msg['Subject'] = "ユーザーからの授業情報修正の報告"
msg['From'] = sender
msg['To'] = receiver
# メール本文
content = f'''
・開講区分:{form.sort.data}
・学期:{form.term.data}
・曜日時限:{form.time.data}
・授業名:{form.name.data}
・教授名:{form.teacher.data}
・言語:{form.language.data}
・抽選:{form.draw.data}
・キーワード:{form.keyword.data}
'''
part2 = MIMEText(content, 'plain')
msg.attach(part2)
# メール送信、サーバーを閉じる
s.sendmail(sender, receiver, msg.as_string())
s.quit()
return render_template('reviews/report_complete.html')
# ページを開いたら既存の情報がすでに入っている
elif request.method == 'GET':
form.sort.data = subject.sort
form.term.data = subject.term
form.time.data = subject.time
form.name.data = subject.name
form.teacher.data = subject.teacher
form.language.data = subject.language
form.draw.data = subject.draw
form.keyword.data = subject.keyword
return render_template('reviews/report.html', subject=subject, form=form, title='授業情報報告')
<file_sep>from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
import yaml
db = SQLAlchemy()
bcrypt = Bcrypt()
login_manager = LoginManager()
login_manager.login_view = 'users.login'
def create_app():
app = Flask(__name__)
# config
yml = yaml.load(open('classget/configure.yaml'), Loader=yaml.BaseLoader)
app.config['SECRET_KEY'] = yml['secret_key']
app.config['SQLALCHEMY_DATABASE_URI'] = yml['mysql_config']
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# 持ってきたModuleをappに入れる
db.init_app(app)
bcrypt.init_app(app)
login_manager.init_app(app)
# それぞれのBlueprintをappに入れる
from classget.admin.routes import admin
from classget.main.routes import main
from classget.reviews.routes import reviews
from classget.users.routes import users
from classget.errors.handlers import errors
app.register_blueprint(admin)
app.register_blueprint(main)
app.register_blueprint(reviews)
app.register_blueprint(users)
app.register_blueprint(errors)
return app
<file_sep>from flask_wtf import FlaskForm
from flask_login import current_user
from wtforms import StringField, PasswordField, SubmitField, BooleanField, SelectField, TextAreaField, RadioField, \
SelectMultipleField, ValidationError, widgets
from wtforms.validators import DataRequired, Length, EqualTo
from classget.models import User
class MultiCheckboxField(SelectMultipleField):
widget = widgets.ListWidget(prefix_label=False)
option_widget = widgets.CheckboxInput()
class RegistrationForm(FlaskForm):
faculty_choices = [('商学部', '商学部'), ('経済学部', '経済学部'), ('法学部', '法学部'), ('社会学部', '社会学部')]
username = StringField('Username',
validators=[DataRequired(), Length(min=2, max=10)])
iduser = StringField('UserID',
validators=[DataRequired(), Length(min=2, max=50)])
password = PasswordField('<PASSWORD>', validators=[DataRequired()])
confirm_password = PasswordField('<PASSWORD> Password',
validators=[DataRequired(), EqualTo('password')])
faculty = SelectField('Faculty', choices=faculty_choices)
year = SelectField('Year', choices=[(1, 1), (2, 2), (3, 3), (4, 4)])
submit = SubmitField('Sign Up')
def validate_username(self, username):
user = User.query.filter_by(username=username.data).first()
if user:
raise ValidationError('That username is taken, Please choose a different one')
def validate_iduser(self, iduser):
user = User.query.filter_by(iduser=iduser.data).first()
if user:
raise ValidationError('That ID is taken, Please choose a different one')
class LoginForm(FlaskForm):
iduser = StringField('UserID',
validators=[DataRequired(), Length(min=2, max=50)])
password = PasswordField('<PASSWORD>', validators=[DataRequired()])
remember = BooleanField('Remember Me')
submit = SubmitField('Login')
class UpdateAccountForm(FlaskForm):
faculty_choices = [('商学部', '商学部'), ('経済学部', '経済学部'), ('法学部', '法学部'), ('社会学部', '社会学部')]
username = StringField('Username',
validators=[DataRequired(), Length(min=2, max=10)])
current_password = PasswordField('Current Password', validators=[DataRequired()])
new_password = PasswordField('New Password(optional)')
confirm_password = PasswordField('Confirm New Password(optional)',
validators=[EqualTo('new_password')])
faculty = SelectField('Faculty', choices=faculty_choices)
year = SelectField('Year', choices=[(1, 1), (2, 2), (3, 3), (4, 4)])
submit = SubmitField('Update')
def validate_username(self, username):
if username.data != current_user.username:
user = User.query.filter_by(username=username.data).first()
if user:
raise ValidationError('That username is taken, Please choose a different one')
class ReviewForm(FlaskForm):
keyword_choice = [('抽選', '抽選'), ('期末試験', '期末試験'), ('期末レポート', '期末レポート'), ('中間試験', '中間試験'),
('中間レポート', '中間レポート'), ('出席', '出席'), ('課題(毎回)', '課題(毎回)'), ('課題(たまに)', '課題(たまに)'),
('ライブ', 'ライブ'), ('オンデマンド', 'オンデマンド'), ('ライブ・オンデマ併用', 'ライブ・オンデマ併用'), ('対面', '対面'),
('顔出し', '顔出し')]
title = StringField('Title', validators=[DataRequired(), Length(max=30)])
rating = RadioField('Rating', choices=[(0, 'good'), (1, 'soso'), (2, 'bad')])
content = TextAreaField('Content', validators=[DataRequired()])
keyword = MultiCheckboxField('keywords', choices=keyword_choice)
submit = SubmitField('submit')<file_sep>import os
from flask import Blueprint, render_template, session, request, send_from_directory, current_app
from flask_login import current_user
from sqlalchemy import or_
from classget.main.forms import SearchClassForm
from classget.models import Subject, get_count, Review
main = Blueprint('main', __name__)
@main.route("/", methods=["GET", "POST"])
def mainpage():
form = SearchClassForm()
return render_template('main/mainpage.html', form=form)
@main.route("/searchresult", methods=['GET', 'POST'])
def searchresult():
form = SearchClassForm()
result = Subject.query
if form.validate_on_submit():
session['form.sort.data'] = form.sort.data
session['form.term.data'] = form.term.data
session['form.day.data'] = form.day.data
session['form.time.data'] = form.time.data
session['form.draw.data'] = form.draw.data
session['form.title.data'] = form.title.data
session['form.teacher.data'] = form.teacher.data
session['form.keyword.data'] = form.keyword.data
# 所属
if session['form.sort.data']:
result = result.filter(Subject.sort.in_(session['form.sort.data']))
# 開講区分
if session['form.term.data']:
result = result.filter(Subject.term.in_(session['form.term.data']))
# 曜日
if session['form.day.data']:
day = [0, 0, 0, 0, 0, 0]
for i in range(len(session['form.day.data'])):
day[i] = session['form.day.data'][i]
result = result.filter(or_(Subject.time.like(f'%{day[0]}%'), Subject.time.like(f'%{day[1]}%'),
Subject.time.like(f'%{day[2]}%'), Subject.time.like(f'%{day[3]}%'),
Subject.time.like(f'%{day[4]}%'), Subject.time.like(f'%{day[5]}%')))
# 時限
if session['form.time.data']:
time = [0, 0, 0, 0, 0, 0]
for i in range(len(session['form.time.data'])):
time[i] = session['form.time.data'][i]
result = result.filter(or_(Subject.time.like(f'%{time[0]}%'), Subject.time.like(f'%{time[1]}%'),
Subject.time.like(f'%{time[2]}%'), Subject.time.like(f'%{time[3]}%'),
Subject.time.like(f'%{time[4]}%'), Subject.time.like(f'%{time[5]}%')))
# 抽選
if session['form.draw.data']:
result = result.filter(Subject.draw.in_(session['form.draw.data']))
# 授業名
if session['form.title.data']:
result = result.filter(Subject.name.like(f"%{session['form.title.data']}%"))
# 教授名
if session['form.teacher.data']:
result = result.filter(Subject.teacher.like(f"%{session['form.teacher.data']}%"))
# キーワード
if session['form.keyword.data']:
for keyword in session['form.keyword.data']:
result = result.filter(Subject.keyword.notlike(f'%{keyword}%'))
# 検索結果を10個ずつ分けてページを作る
page = request.args.get('page', 1, type=int)
result_num = get_count(result)
result = result.paginate(page=page, per_page=10)
if not result:
result = "検索結果がありません。"
return render_template('main/searchresult.html', title='検索結果', result=result, get_count=get_count, form=form,
Review=Review, result_num=result_num)
@main.route('/about_us')
def aboutus():
return render_template('main/aboutus.html', title='About Us')
@main.route('/ham_menu', methods=['POST'])
def ham_menu():
action = request.form['action']
if action == 'show_menu':
if current_user.is_authenticated:
return render_template('main/show_ham_menu.html')
else:
return render_template('main/nouser_show_ham_menu.html')
elif action == 'close_menu':
return render_template('main/close_ham_menu.html')
else:
pass
@main.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(current_app.root_path, 'static/img/icon'), 'favicon.ico',
mimetype='image/vnd.microsoft.icon')
@main.route('/sw.js')
def sw_js():
return send_from_directory(os.path.join(current_app.root_path, 'static/js'), 'sw.js')
@main.route('/mobile_install')
def mobile_install():
return render_template('main/mobile_install.html')
<file_sep>from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
class UpdateClassForm(FlaskForm):
sort = StringField('・時間割区分', validators=[DataRequired()])
term = StringField('・学期', validators=[DataRequired()])
time = StringField('・曜日と時限', validators=[DataRequired()])
name = StringField('・授業名', validators=[DataRequired()])
teacher = StringField('・教授名', validators=[DataRequired()])
language = StringField('・言語', validators=[DataRequired()])
draw = StringField('・抽選', validators=[DataRequired()])
keyword = StringField('・キーワード', validators=[DataRequired()])
submit = SubmitField('授業情報修正')<file_sep>{% extends "main/layout.html" %}
{% block contents %}
<div class="content">
<h1>あら。何か問題が発生しました。</h1>
<h4>バグ報告で教えていただけたら、なるはやで直してみます。</h4>
</div>
{% endblock contents %}<file_sep>import random
from flask import Blueprint, url_for, render_template, request
from flask_login import current_user, login_user, login_required, logout_user
from sqlalchemy import or_
from werkzeug.utils import redirect
from classget import bcrypt, db
from classget.models import User, Like, get_count, Subject, Review
from classget.users.forms import RegistrationForm, LoginForm, UpdateAccountForm
users = Blueprint('users', __name__)
@users.route("/createaccount", methods=['GET', 'POST'])
def createaccount():
if current_user.is_authenticated:
return redirect(url_for('main.mainpage'))
form = RegistrationForm()
# アカウント作成フォームを提出したら
if form.validate_on_submit():
# パスワードの暗号化
hashed_pw = bcrypt.generate_password_hash(form.password.data).decode('utf-8')
# ユーザー情報をデータベースに入れる
user = User(username=form.username.data, iduser=form.iduser.data, password=<PASSWORD>,
faculty=form.faculty.data, year=form.year.data)
db.session.add(user)
db.session.commit()
# さっき作られたアカウントでログインさせる
user = User.query.filter_by(iduser=form.iduser.data).first()
login_user(user)
# キャラ診断ページに送る
return redirect(url_for('users.typetest'))
return render_template('users/createaccount.html', title='アカウント作成', form=form)
@users.route("/login", methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('main.mainpage'))
form = LoginForm()
login_error = 0
# ログインフォームを提出したら
if form.validate_on_submit():
# 入力したIDでユーザー情報を持ってくる
user = User.query.filter_by(iduser=form.iduser.data).first()
# そのユーザー情報のPWとログインフォームで入力したPWが一致する場合
if user and bcrypt.check_password_hash(user.password, form.password.data):
# ログインさせる
login_user(user, remember=form.remember.data)
# 行こうとしたページがあったらそのページに送る
next_page = request.args.get('next')
return redirect(next_page) if next_page else redirect(url_for('main.mainpage'))
# パスワードが一致しない場合:パスワードエラー
else:
login_error = 1
return render_template('users/login.html', title='ログイン', form=form, login_error=login_error)
@users.route("/updateaccount", methods=['GET', 'POST'])
@login_required
def updateaccount():
form = UpdateAccountForm()
password_error = 0
# アカウント修正フォームを提出した場合
if form.validate_on_submit():
# 入力したPWが現在のPWと一致したら
if bcrypt.check_password_hash(current_user.password, form.current_password.data):
# 修正情報をデータベースに入れる
current_user.username = form.username.data
current_user.faculty = form.faculty.data
current_user.year = form.year.data
db.session.commit()
# パスワードを変更(新しいパスワードを入力した場合)
if form.new_password.data:
current_user.password = bcrypt.generate_password_hash(form.new_password.data).decode('utf-8')
db.session.commit()
# 修正が終わったらマイページに戻る
return redirect(url_for('users.mypage', my_term='春'))
# 入力したPWが現在PWと一致しない場合:パスワードエラー
else:
password_error = 1
# ページを読み取った場合に書いてあるデフォルトユーザー情報
elif request.method == 'GET':
form.username.data = current_user.username
form.faculty.data = current_user.faculty
form.year.data = current_user.year
return render_template('users/updateaccount.html', title='アカウント情報修正', form=form, password_error=password_error)
@users.route("/logout")
def logout():
logout_user()
return redirect(url_for('main.mainpage'))
@users.route("/mypage/<my_term>")
@login_required
def mypage(my_term):
image_file = url_for('static', filename='img/profile_pics/' + current_user.type + '.png')
liked_subject = Like.query.filter_by(user_id=current_user.id)\
.filter(or_(Like.subject_term.like('%{}%'.format(my_term)), Like.subject_term.like('%通年%'))).all()
def timetable(i):
result = []
for l in liked_subject:
for t in l.subject.time.split(','):
if t == i:
result.append([l.subject.id, l.subject.name])
return result
return render_template('users/mypage.html', title='マイページ', image_file=image_file, liked=liked_subject,
timetable=timetable, my_term=my_term, User=User, Review=Review, get_count=get_count)
@users.route("/typetest", methods=['GET', 'POST'])
@login_required
def typetest():
question = ['初対面の人と友達になることができる。', '人助けをすることが多い。', '課題の期限は絶対守るし、遅刻も絶対しない。',
'普段ストレスや不安をあまり感じない性格を持っている。', '芸術や美術は結構好きだ。',
'しばしば新しい冒険についてのアイデアが思い浮かぶ。', '他の人にどう思われるかはあまり気にしない。',
'人との約束のためなら無理もする。', 'みんなで何かを成し遂げることが好きだ。', '面白い話で場を盛り上げることができる。']
# すでにキャラ診断した人は結果ページに送る
if current_user.type != 'none':
return redirect(url_for('users.typeresult'))
if request.method == 'POST':
# formのdataから属性ごとにスコアを集計
kaisou_score = int(request.form['Q1']) + int(request.form['Q10'])
penguin_score = int(request.form['Q2']) + int(request.form['Q9'])
iruka_score = int(request.form['Q3']) + int(request.form['Q8'])
kame_score = int(request.form['Q4']) + int(request.form['Q7'])
taco_score = int(request.form['Q5']) + int(request.form['Q6'])
scores = {'海藻': kaisou_score, 'ペンギン': penguin_score, 'イルカ': iruka_score,
'カメ': kame_score, 'タコ': taco_score}
# 一番高いスコアのキャラを入れる(複数の場合は共同1位のうちランダムで)
max_score = max(scores.items(), key=lambda x: x[1])
list_max = []
for key, value in scores.items():
if value == max_score[1]:
list_max.append(key)
current_user.type = random.choice(list_max)
db.session.commit()
return redirect(url_for('users.typeresult'))
return render_template('users/typetest.html', question=question, title='キャラ診断')
@users.route("/typeresult", methods=['GET'])
@login_required
def typeresult():
recommended_subjects = current_user.recommend_by_likes()
catchphrase = {'海藻': '楽しいこと大好き!いつもノリノリな陽キャ',
'ペンギン': '冷たい氷も溶けちゃう優しさ!協力的なサポーター',
'イルカ': '頼まれたら裏切らない!信頼のメガバンク',
'カメ': '100人乗っても大丈夫!屋久杉のような安定感',
'タコ': '好奇心が止まらない!圧倒的な柔軟性'}
description = {'海藻': ['おしゃべりで周りを楽しませることができる', '誰かと一緒にいることが好き', '自己主張がしっかりできる', '行動的なみんなのリーダータイプ'],
'ペンギン': ['やさしく、思いやりがある', '面倒見がいい', '共感力が高く、人の痛みが良く分かる', '人を疑わない'],
'イルカ': ['計画的に集中して物事に取り組むことができる', '責任感が強い', '誠実で頼られやすい', '時間や期限をきちんと守る'],
'カメ': ['大勢の人の前でもあまり緊張せずにいられる', '環境が変わってもなじみやすい', 'ものごとを根に持たない', 'あまり激しい感情にならない'],
'タコ': ['クリエイティブだとよく言われる', '原宿が好きだったりする', '人とかぶらないものが好き', '異なる解釈が可能な映画や本などに興味がある']}
type_number = get_count(User.query.filter_by(type=current_user.type))
user_number = get_count(User.query)
type_com = get_count(User.query.filter_by(type=current_user.type, faculty='商学部'))
type_eco = get_count(User.query.filter_by(type=current_user.type, faculty='経済学部'))
type_law = get_count(User.query.filter_by(type=current_user.type, faculty='法学部'))
type_soc = get_count(User.query.filter_by(type=current_user.type, faculty='社会学部'))
type_proportion = "{:.1f}".format((type_number/user_number)*100)
com_proportion = "{:.1f}".format((type_com/type_number)*100)
eco_proportion = "{:.1f}".format((type_eco / type_number) * 100)
law_proportion = "{:.1f}".format((type_law / type_number) * 100)
soc_proportion = "{:.1f}".format((type_soc / type_number) * 100)
return render_template('users/typeresult.html', recommended_subjects=recommended_subjects, type_pp=type_proportion,
com_pp=com_proportion, eco_pp=eco_proportion, law_pp=law_proportion, soc_pp=soc_proportion,
catchphrase=catchphrase, get_count=get_count, description=description, title='診断結果')
@users.route('/like', methods=['POST'])
@login_required
def like():
subject_id = request.form['subject_id']
action = request.form['action']
subject = Subject.query.filter_by(id=subject_id).first_or_404()
if action == 'like':
current_user.like_subject(subject)
db.session.commit()
if action == 'unlike':
current_user.unlike_subject(subject)
db.session.commit()
return render_template('users/like_button.html', subject=subject)
<file_sep>$(document).ready(function() {
$(document).on('click', '.user_like_button', function(event) {
event.preventDefault();
var request_id = $(this).attr('id').split('_');
var subject_id = request_id[1];
var action = request_id[0];
req = $.ajax({
url : '/like',
type : 'POST',
data : { subject_id : subject_id, action : action }
});
req.done(function(data) {
$('.like_buttons'+subject_id).html(data);
});
});
});<file_sep>from flask import render_template, url_for, redirect, request
from classget import app, db, bcrypt
from classget.forms import RegistrationForm, LoginForm, UpdateAccountForm, ReviewForm
from classget.models import User, Subject, Review
from flask_login import login_user, current_user, logout_user, login_required
import random
@app.route("/")
def mainpage():
return render_template('mainpage.html')
@app.route("/createaccount", methods=['GET', 'POST'])
def createaccount():
if current_user.is_authenticated:
return redirect(url_for('mainpage'))
form = RegistrationForm()
# アカウント作成フォームを提出したら
if form.validate_on_submit():
# パスワードの暗号化
hashed_pw = bcrypt.generate_password_hash(form.password.data).decode('utf-8')
# ユーザー情報をデータベースに入れる
user = User(username=form.username.data, iduser=form.iduser.data, password=<PASSWORD>,
faculty=form.faculty.data, year=form.year.data)
db.session.add(user)
db.session.commit()
# さっき作られたアカウントでログインさせる
user = User.query.filter_by(iduser=form.iduser.data).first()
login_user(user)
# キャラ診断ページに送る
return redirect(url_for('typetest'))
return render_template('createaccount.html', title='Register', form=form)
@app.route("/login", methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('mainpage'))
form = LoginForm()
login_error = 0
# ログインフォームを提出したら
if form.validate_on_submit():
# 入力したIDでユーザー情報を持ってくる
user = User.query.filter_by(iduser=form.iduser.data).first()
# そのユーザー情報のPWとログインフォームで入力したPWが一致する場合
if user and bcrypt.check_password_hash(user.password, form.password.data):
# ログインさせる
login_user(user, remember=form.remember.data)
# 行こうとしたページがあったらそのページに送る
next_page = request.args.get('next')
return redirect(next_page) if next_page else redirect(url_for('mainpage'))
# パスワードが一致しない場合:パスワードエラー
else:
login_error = 1
return render_template('login.html', title='login', form=form, login_error=login_error)
@app.route("/updateaccount", methods=['GET', 'POST'])
@login_required
def updateaccount():
form = UpdateAccountForm()
password_error = 0
# アカウント修正フォームを提出した場合
if form.validate_on_submit():
# 入力したPWが現在のPWと一致したら
if bcrypt.check_password_hash(current_user.password, form.current_password.data):
# 修正情報をデータベースに入れる
current_user.username = form.username.data
current_user.faculty = form.faculty.data
current_user.year = form.year.data
db.session.commit()
# パスワードを変更(新しいパスワードを入力した場合)
if form.new_password.data:
current_user.password = <PASSWORD>.generate_password_hash(form.new_password.data).decode('utf-8')
db.session.commit()
# 修正が終わったらマイページに戻る
return redirect(url_for('mypage'))
# 入力したPWが現在PWと一致しない場合:パスワードエラー
else:
password_error = 1
# ページを読み取った場合に書いてあるデフォルトユーザー情報
elif request.method == 'GET':
form.username.data = current_user.username
form.faculty.data = current_user.faculty
form.year.data = current_user.year
return render_template('updateaccount.html', title='update account', form=form, password_error=password_error)
@app.route("/logout")
def logout():
logout_user()
return redirect(url_for('mainpage'))
@app.route("/typetest", methods=['GET', 'POST'])
@login_required
def typetest():
question = ['Q01.初対面の人と友達になるのが得意だ。', 'Q02.人助けをしたり、されたりすることが多い。', 'Q03.課題の期限は守るほうだし、遅刻もしない。',
'Q04.普段ストレスや不安をなかなか感じないブッダみたいな性格を持っている。', 'Q05.芸術や美術は結構好きだ。',
'Q06.しばしば新しい冒険についてのアイデアが思い浮かぶ。', 'Q07.他の人にどう思われるかなんて気にしない超マイウェイ。',
'Q08.人との約束のためなら無理もする。', 'Q09.みんなで何かを成し遂げることが好きだ。', 'Q10.面白い話で場を盛り上げることができる。']
# すでにキャラ診断した人は結果ページに送る
if current_user.type != 'none':
return redirect(url_for('typeresult'))
if request.method == 'POST':
# formのdataから属性ごとにスコアを集計
kaisou_score = int(request.form['Q1']) + int(request.form['Q10'])
penguin_score = int(request.form['Q2']) + int(request.form['Q9'])
iruka_score = int(request.form['Q3']) + int(request.form['Q8'])
kame_score = int(request.form['Q4']) + int(request.form['Q7'])
taco_score = int(request.form['Q5']) + int(request.form['Q6'])
scores = {'kaisou': kaisou_score, 'penguin': penguin_score, 'iruka': iruka_score,
'kame': kame_score, 'taco': taco_score}
print(kaisou_score, penguin_score, iruka_score, kame_score, taco_score)
# 一番高いスコアのキャラを入れる(複数の場合は共同1位のうちランダムで)
max_score = max(scores.items(), key=lambda x: x[1])
list_max = []
for key, value in scores.items():
if value == max_score[1]:
list_max.append(key)
current_user.type = random.choice(list_max)
db.session.commit()
return redirect(url_for('typeresult'))
return render_template('typetest.html', question=question)
@app.route("/typeresult", methods=['GET'])
@login_required
def typeresult():
return render_template('typeresult.html')
@app.route("/mypage")
@login_required
def mypage():
for ranker_id in ['12','68','73']:
if ranker_id == current_user.id:
image_file = url_for('static', filename='img/profile_pics/' + ranker_id + '.png')
image_file = url_for('static', filename='img/profile_pics/' + current_user.type + '.png')
return render_template('mypage.html', title='mypage', image_file=image_file)
@app.route("/searchresult")
def searchresult():
subject = Subject.query.all()
return render_template('searchresult.html', title='検索結果', subject=subject)
@app.route("/classinfo/<int:subject_id>", methods=["GET", "POST"])
def classinfo(subject_id):
# PKのIDでその授業の情報を持ってくる
subject = Subject.query.get_or_404(subject_id)
form = ReviewForm()
# 授業IDでその授業のレビューを全部持ってくる
reviews = Review.query.filter_by(subject_id=subject_id).all()
# レビューフォームを提出したら
if form.validate_on_submit():
# ログインしている場合
if current_user.is_authenticated:
# キーワードをListから一つのStringにする
keywords = ' '.join([str(i) for i in form.keyword.data])
# レビューをデータベースに入れる
review = Review(title=form.title.data, rating=form.rating.data, content=form.content.data,
keyword=keywords, author=current_user, subject_id=subject_id)
db.session.add(review)
db.session.commit()
return redirect(url_for('classinfo', subject_id=subject_id))
# ログインしていない場合→ログイン画面へ
else:
return redirect(url_for('login'))
return render_template('classinfo.html', title=subject.name, subject=subject, form=form, reviews=reviews,
enumerate=enumerate)
<file_sep>$(document).ready(function() {
$(document).on('click', '.hamburger-menu', function(event) {
event.preventDefault();
var action = $(this).attr('id');
req = $.ajax({
url : '/ham_menu',
type : 'POST',
data : { action : action }
});
req.done(function(data) {
$('.ham-menu').html(data);
});
});
});<file_sep>from classget import db, login_manager
from datetime import datetime
from flask_login import UserMixin
from sqlalchemy import func
@login_manager.user_loader
def load_user(id):
return User.query.get(int(id))
def get_count(q):
count_q = q.statement.with_only_columns([func.count()]).order_by(None)
count = q.session.execute(count_q).scalar()
return count
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
iduser = db.Column(db.String(45), unique=True, nullable=False)
username = db.Column(db.String(16), unique=True, nullable=False)
password = db.Column(db.String(50), nullable=False)
faculty = db.Column(db.String(10), nullable=False)
year = db.Column(db.Integer, nullable=False)
type = db.Column(db.String(10), nullable=False, default='none')
reviews = db.relationship('Review', backref='author', lazy=True)
liked_data = db.relationship('Likedata', foreign_keys='Likedata.user_id', backref='user', lazy='dynamic')
liked = db.relationship('Like', foreign_keys='Like.user_id', backref='user', lazy='dynamic')
def __repr__(self):
return f"User('{self.username}', '{self.iduser}', '{self.faculty}', '{self.year}', '{self.type}')"
def like_subject(self, subject):
if not self.has_liked_subject(subject):
like = Like(user_id=self.id, subject_id=subject.id, subject_term=subject.term)
db.session.add(like)
if Likedata.query.filter_by(user_id=self.id, subject_id=subject.id).first():
pass
else:
like_data = Likedata(user_id=self.id, subject_id=subject.id, user_type=self.type)
db.session.add(like_data)
if self.type == '海藻':
subject.like_by_kaisou += 1
elif self.type == 'ペンギン':
subject.like_by_penguin += 1
elif self.type == 'イルカ':
subject.like_by_iruka += 1
elif self.type == 'カメ':
subject.like_by_kame += 1
elif self.type == 'タコ':
subject.like_by_taco += 1
else:
pass
def unlike_subject(self, subject):
if self.has_liked_subject(subject):
Like.query.filter_by(
user_id=self.id, subject_id=subject.id, subject_term=subject.term).delete()
def has_liked_subject(self, subject):
return Like.query.filter(
Like.user_id == self.id,
Like.subject_id == subject.id,
Like.subject_term == subject.term).count() > 0
def recommend_by_likes(self):
if self.type == '海藻':
recommended = Subject.query.order_by(Subject.like_by_kaisou.desc()).limit(3).all()
elif self.type == 'ペンギン':
recommended = Subject.query.order_by(Subject.like_by_penguin.desc()).limit(3).all()
elif self.type == 'イルカ':
recommended = Subject.query.order_by(Subject.like_by_iruka.desc()).limit(3).all()
elif self.type == 'カメ':
recommended = Subject.query.order_by(Subject.like_by_kame.desc()).limit(3).all()
elif self.type == 'タコ':
recommended = Subject.query.order_by(Subject.like_by_taco.desc()).limit(3).all()
else:
recommended = []
return recommended
class Subject(db.Model):
id = db.Column(db.Integer, primary_key=True)
sort = db.Column(db.String(20), nullable=False)
term = db.Column(db.String(20), nullable=False)
time = db.Column(db.String(20), nullable=False)
name = db.Column(db.String(60), nullable=False)
teacher = db.Column(db.String(30), nullable=False)
language = db.Column(db.String(20), nullable=False)
draw = db.Column(db.String(10), nullable=False)
keyword = db.Column(db.String(200))
like_by_kaisou = db.Column(db.Integer, nullable=False, default=0)
like_by_penguin = db.Column(db.Integer, nullable=False, default=0)
like_by_iruka = db.Column(db.Integer, nullable=False, default=0)
like_by_kame = db.Column(db.Integer, nullable=False, default=0)
like_by_taco = db.Column(db.Integer, nullable=False, default=0)
likes_data = db.relationship('Likedata', backref='subject', lazy='dynamic')
likes = db.relationship('Like', backref='subject', lazy='dynamic')
def __repr__(self):
return f"Subject('{self.id}', '{self.sort}', '{self.term}', '{self.time}', '{self.name}', '{self.teacher}', " \
f"'{self.language}', '{self.draw}', '{self.keyword}')"
def recommended_by_review(self):
good_reviews = Review.query.filter_by(subject_id=self.id, rating=0).order_by(Review.date_posted.desc()).limit(3).all()
user_ids = []
for review in good_reviews:
user_ids.append(review.user_id)
rec_subjects = [0, 0, 0]
for i, user_id in enumerate(user_ids):
another_rec_review = Review.query.filter(Review.subject_id != self.id).filter_by(user_id=user_id, rating=0).order_by(Review.date_posted.desc()).first()
if another_rec_review:
rec_subject = Subject.query.filter_by(id=another_rec_review.subject_id).first()
rec_subjects[i] = rec_subject
return rec_subjects
def rating_count(self, rating):
return get_count(Review.query.filter_by(subject_id=self.id, rating=rating))
class Review(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(15), nullable=False)
rating = db.Column(db.Integer, nullable=False)
content = db.Column(db.Text, nullable=False)
keyword = db.Column(db.String(200))
date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
subject_id = db.Column(db.Integer, db.ForeignKey('subject.id'), nullable=False)
class Like(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
subject_id = db.Column(db.Integer, db.ForeignKey('subject.id'))
subject_term = db.Column(db.String(10), nullable=False)
class Likedata(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
subject_id = db.Column(db.Integer, db.ForeignKey('subject.id'))
user_type = db.Column(db.String(10), nullable=False)
<file_sep>from flask_login import current_user
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SelectField, SubmitField, BooleanField
from wtforms.validators import DataRequired, Length, EqualTo, ValidationError
from classget.models import User
class RegistrationForm(FlaskForm):
faculty_choices = [('商学部', '商学部'), ('経済学部', '経済学部'), ('法学部', '法学部'), ('社会学部', '社会学部')]
username = StringField('Username',
validators=[DataRequired(), Length(min=1, max=16)])
iduser = StringField('UserID',
validators=[DataRequired(), Length(min=2, max=45)])
password = PasswordField('<PASSWORD>', validators=[DataRequired()])
confirm_password = PasswordField('<PASSWORD>',
validators=[DataRequired(), EqualTo('password')])
faculty = SelectField('Faculty', choices=faculty_choices)
year = SelectField('Year', choices=[(1, 1), (2, 2), (3, 3), (4, 4)])
submit = SubmitField('アカウント作成')
def validate_username(self, username):
user = User.query.filter_by(username=username.data).first()
if user:
raise ValidationError('既に誰かが使用中のユーザー名です')
def validate_iduser(self, iduser):
user = User.query.filter_by(iduser=iduser.data).first()
if user:
raise ValidationError('既に誰かが使用中のIDです')
class LoginForm(FlaskForm):
iduser = StringField('UserID',
validators=[DataRequired(), Length(min=2, max=50)])
password = PasswordField('<PASSWORD>', validators=[DataRequired()])
remember = BooleanField('Remember Me')
submit = SubmitField('ログイン')
class UpdateAccountForm(FlaskForm):
faculty_choices = [('商学部', '商学部'), ('経済学部', '経済学部'), ('法学部', '法学部'), ('社会学部', '社会学部')]
username = StringField('Username',
validators=[DataRequired(), Length(min=2, max=10)])
current_password = PasswordField('Current <PASSWORD>', validators=[DataRequired()])
new_password = PasswordField('<PASSWORD>(optional)')
confirm_password = PasswordField('Confirm New Password(optional)',
validators=[EqualTo('new_password')])
faculty = SelectField('Faculty', choices=faculty_choices)
year = SelectField('Year', choices=[(1, 1), (2, 2), (3, 3), (4, 4)])
submit = SubmitField('アカウント情報修正')
def validate_username(self, username):
if username.data != current_user.username:
user = User.query.filter_by(username=username.data).first()
if user:
raise ValidationError('既に誰かが使用中のユーザー名です')<file_sep>{% extends 'main/layout.html' %}
{% block stylesheet %}
<!-- ここにCSSファイルをリンクする -->
<link rel="stylesheet" href="{{ url_for('static', filename='css/classinfo.css') }}" type="text/css">
{% endblock %}
{% block contents %}
<!-- ここから授業詳細 -->
<div class="warning">*一部の授業は取れる学年に制限があったり、年によって未開講だったりすることがあります。詳細はCELSの公式シラバスを確認してください。</div>
<fieldset class="outer" id="top">
<div class="classinfo">
<div class="box">
<!-- 授業名 -->
<div class="main-info">
<h1 class="name">{{ subject.name }}</h1>
<!-- 学期と曜日・時限 -->
<div class="term-and-time"><h3>{{ subject.term}} {{ subject.time }}</h3></div>
</div>
<!-- お気に入りボタン -->
<div class="like_buttons{{ subject.id }}">
<!-- お気に入り済みの状態 -->
{% if current_user.is_authenticated and current_user.has_liked_subject(subject) %}
<a href="" class="user_like_button" id="unlike_{{ subject.id }}">
<img class="like-button-img" src="{{ url_for('static', filename='img/system/liked.png') }}" width="35px">
</a>
<!-- お気に入りしてない状態 -->
{% elif current_user.is_authenticated %}
<a href="" class="user_like_button" id="like_{{ subject.id }}">
<img class="like-button-img" src="{{ url_for('static', filename='img/system/unliked.png') }}" width="35px">
</a>
<!-- ログインしてない状態(押したらログインページに送る) -->
{% else %}
<a href="{{ url_for('users.login') }}" class="like_button">
<img class="like-button-img" src="{{ url_for('static', filename='img/system/unliked.png') }}" width="35px">
</a>
{% endif %}
</div>
</div>
<!-- 授業情報 -->
<p class="sort">•{{ subject.sort }} <span class="draw">•{{ subject.draw }}</span></p>
<p class="professor-and-language">•教員名:{{ subject.teacher }} 教授 <span class="draw">•言語:{{ subject.language }}</span></p>
<!-- 3段階の顔文字評価の集計 -->
<div class="class-rating">
<img class="face-top" src="{{ url_for('static', filename='img/system/rating_0.png') }}"> {{ subject.rating_count(0) }}
<img class="face-top" src="{{ url_for('static', filename='img/system/rating_1.png') }}"> {{ subject.rating_count(1) }}
<img class="face-top" src="{{ url_for('static', filename='img/system/rating_2.png') }}"> {{ subject.rating_count(2) }}
<span class="liked_number">(お気に入り {{ get_count(subject.likes) }}件)</span>
</div>
<!-- キーワード -->
<div class="keywords">
{% for keyword in subject_keyword %}
<span class="keyword">{{ keyword }}</span>
{% endfor %}
</div>
<!-- 授業情報修正申請ボタン -->
<div class="report">
<a href="{{ url_for('reviews.report', subject_id=subject.id) }}"><button class="report_button">この授業の最新情報報告</button></a>
</div>
<div class="report">
<a href="{{ url_for('main.searchresult') }}"><button class="go_back_button">検索結果に戻る</button></a>
</div>
</div>
<!-- 授業情報修正ボタン(adminアカウントにだけ見える) -->
{% if current_user.is_authenticated and current_user.iduser == 'admin' %}
<a href="{{ url_for('admin.updateclass', subject_id=subject.id) }}"><button class="update_class_button">授業情報修正</button></a>
{% endif %}
</fieldset>
<!-- ここからレビュー一覧 -->
<fieldset class="outer">
<div class="reviews">過去のレビュー<span class="review-num">:{{ reviews_num }}件</span></div>
{% if reviews.items %}
{% for review in reviews.items %}
<fieldset class="inner">
<!-- レビュー作成者 -->
<div class="author">
<!-- 作成者アイコン -->
<img class="user-icon" src="{{ url_for('static', filename='img/profile_pics/{}.png'.format(review.author.type)) }}">
<!-- 作成者のユーザー名 -->
<div class="user-username">{{ review.author.username }}</div>
<!-- 作成者の学部 -->
<div class="user-faculty">{{ review.author.faculty }}</div>
</div>
<!-- レビュー内容 -->
<div class="review-body">
<!-- タイトル -->
<span class="review-title">{{ review.title }}</span>
<!-- 評価 -->
<img class="review_face" src="{{ url_for('static', filename='img/system/rating_{}.png'.format(review.rating)) }}">
<!-- 投稿日付 -->
<div class="uploaded_date">
{{ review.date_posted.strftime('%Y-%m-%d') }}
</div>
<hr>
<!-- 本文 -->
<div class="review-content">{{ review.content }}</div>
<!-- キーワード -->
<div class="review-keywords">
{% if review.keyword %}
{% for keyword in review.keyword.split(" ") %}
<span class="keyword">{{ keyword }}</span>
{% endfor %}
{% endif %}
</div>
<!-- レビュー削除ボタン(ログインしてるユーザー == 投稿者の場合) -->
{% if review.author == current_user %}
<form class="delete-button" action="{{ url_for('reviews.delete_review', review_id=review.id, subject_id=subject.id) }}">
<button class="review-delete" type="submit">このレビューを削除</button>
</form>
{% endif %}
</div>
</fieldset>
{% endfor %}
<!-- レビューがないとき -->
{% else %}
<div>作成されたレビューがありません。</div>
{% endif %}
<!-- ページの表示 -->
<div class="page_nums">
{% for page_num in reviews.iter_pages(left_edge=1, right_edge=1, left_current=1, right_current=2) %}
{% if page_num %}
{% if reviews.page == page_num %}
<a class="current_page_num" href="{{ url_for('reviews.classinfo', subject_id=subject.id, page=page_num) }}">{{ page_num }}</a>
{% else %}
<a class="page_num" href="{{ url_for('reviews.classinfo', subject_id=subject.id, page=page_num) }}">{{ page_num }}</a>
{% endif %}
{% else %}
...
{% endif %}
{% endfor %}
</div>
</fieldset>
<!-- ここからレビュー作成 -->
<fieldset class="outer">
<div class="newreview">
<div class="create-review"><h2>レビュー作成</h2></div><hr>
<form method="POST" action="" class="newreview">
{{ form.hidden_tag() }}
<div class="title-review">
{% if form.title.errors %}
{{ form.title.label(class="label-title") }}
{{ form.title(class="blank-title", placeholder="15字以内") }}
<span class="error_message">タイトルは15字以内で書いてください</span>
{% else %}
{{ form.title.label(class="label-title") }}
{{ form.title(class="blank-title", placeholder="15字以内") }}
{% endif %}
</div>
<div class="rating-review">
{{ form.rating.label(class="label-rating") }}
{% for l, i in enumerate(form.rating) %}
<img class="face-top" src="{{ url_for('static', filename='img/system/rating_{}.png'.format(l)) }}"> {{ i(class="button") }}
{% endfor %}
</div>
<div class="content-review">
{{ form.content.label(class="label-content") }}
{{ form.content(class="blank-content") }}
</div>
<div class="keyword-review">
{{ form.keyword.label(class="label-keyword") }}
<div class="select-keyword">
{{ form.keyword(class="blank-keyword") }}
</div>
</div>
<div class="submit-review">
{{ form.submit }}
</div>
</form>
</div>
</fieldset>
<div class="suggestion">
<p class="suggestion">この授業に<img class="face_heading" src="{{ url_for('static', filename='/img/system/rating_0.png') }}">レビューを書いた人は、
<br>こちらの授業にも<img class="face_heading" src="{{ url_for('static', filename='/img/system/rating_0.png') }}">レビューを書きました<hr class="sug-hr"></p>
<div class="cream-box">
{% for subject in recommended %}
{% if subject %}
<div class="class-sug">
<p class="class_name">{{ subject.name }}</p>
<p class="term_day">
{{ subject.term }} {{ subject.time }}
{% if current_user.is_authenticated and current_user.has_liked_subject(subject) %}
<img class="like_button" src="{{ url_for('static', filename='/img/system/liked.png') }}">
{% else %}
<img class="like_button" src="{{ url_for('static', filename='/img/system/unliked.png') }}">
{% endif %}
</p>
<hr class="sug-line">
<div class="flex-box">
<img class="face" src="{{ url_for('static', filename='/img/system/rating_0.png') }}">
<p class="rating-number">{{ subject.rating_count(0) }}</p>
<img class="face" src="{{ url_for('static', filename='/img/system/rating_1.png') }}">
<p class="rating-number">{{ subject.rating_count(1) }}</p>
<img class="face" src="{{ url_for('static', filename='/img/system/rating_2.png') }}">
<p class="rating-number">{{ subject.rating_count(2) }}</p>
</div>
<p class="favorite">お気に入り{{ get_count(subject.likes) }}件</p>
<a class="link-classinfo" href="{{ url_for('reviews.classinfo', subject_id=subject.id) }}"><p class="link-classinfo">授業詳細へ</p></a>
</div>
{% else %}
<div class="class-sug">
<div class="no-data">まだデータがありません</div>
</div>
{% endif %}
{% endfor %}
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/like_button.js') }}"></script>
{% endblock %}
<file_sep>alembic==1.4.3
bcrypt==3.2.0
cffi==1.14.4
click==7.1.2
dominate==2.6.0
Flask==1.1.2
Flask-Bcrypt==0.7.1
Flask-Login==0.5.0
Flask-MySQLdb==0.2.0
Flask-Script==2.0.6
Flask-SQLAlchemy==2.4.4
Flask-WTF==0.14.3
itsdangerous==1.1.0
Jinja2==2.11.2
Mako==1.1.3
MarkupSafe==1.1.1
mysqlclient==2.0.3
pycparser==2.20
python-dateutil==2.8.1
python-editor==1.0.4
PyYAML==5.3.1
six==1.15.0
SQLAlchemy==1.3.22
visitor==0.1.3
Werkzeug==1.0.1
WTForms==2.3.3
<file_sep>from flask_wtf import FlaskForm
from wtforms import SelectMultipleField, widgets, StringField, SubmitField
class MultiCheckboxField(SelectMultipleField):
widget = widgets.ListWidget(prefix_label=False)
option_widget = widgets.CheckboxInput()
class SearchClassForm(FlaskForm):
syozoku_choices = [('全学共通教育科目', '全学共通教育科目'), ('商学部', '商学部'), ('経済学部', '経済学部'),
('法学部', '法学部'), ('社会学部', '社会学部'), ('国際交流科目', '国際交流科目'), ('教職科目', '教職科目')]
term_choices = [('春夏学期', '春夏学期'), ('春学期', '春学期'), ('夏学期', '夏学期'), ('秋冬学期', '秋冬学期'),
('秋学期', '秋学期'), ('冬学期', '冬学期'), ('通年', '通年')]
day_choices = [('月', '月曜日'), ('火', '火曜日'), ('水', '水曜日'), ('木', '木曜日'), ('金', '金曜日'), ('他', '他')]
time_choices = [('1', '1限'), ('2', '2限'), ('3', '3限'), ('4', '4限'), ('5', '5限'), ('他', '他')]
draw_choices = [('抽選科目', '抽選科目'), ('抽選なし', '抽選なし')]
keyword_choices = [('期末試験', '期末試験'), ('期末レポート', '期末レポート'), ('中間試験', '中間試験'),
('中間レポート', '中間レポート'), ('出席', '出席'), ('課題(毎回)', '課題(毎回)'), ('課題(たまに)', '課題(たまに)'),
('ライブ', 'ライブ'), ('オンデマンド', 'オンデマンド'), ('ライブ・オンデマ併用', 'ライブ・オンデマ併用'), ('対面', '対面'),
('顔出しアリ', '顔出しアリ'), ('顔出しナシ', '顔出しナシ'),('今年度非開講','今年度非開講')]
sort = MultiCheckboxField('時間割所属', choices=syozoku_choices)
term = MultiCheckboxField('開講区分', choices=term_choices)
day = MultiCheckboxField('曜日', choices=day_choices)
time = MultiCheckboxField('時限', choices=time_choices)
draw = MultiCheckboxField('抽選', choices=draw_choices)
title = StringField('授業名')
teacher = StringField('教授名')
keyword = MultiCheckboxField('(避けたい)キーワード', choices=keyword_choices)
submit = SubmitField('この条件で検索')
<file_sep>from flask_wtf import FlaskForm
from wtforms import SelectMultipleField, widgets, StringField, RadioField, TextAreaField, SubmitField
from wtforms.validators import DataRequired, Length, ValidationError
class MultiCheckboxField(SelectMultipleField):
widget = widgets.ListWidget(prefix_label=False)
option_widget = widgets.CheckboxInput()
class ReviewForm(FlaskForm):
keyword_choices = [('期末試験', '期末試験'), ('期末レポート', '期末レポート'), ('中間試験', '中間試験'),
('中間レポート', '中間レポート'), ('出席', '出席'), ('課題(毎回)', '課題(毎回)'), ('課題(たまに)', '課題(たまに)'),
('ライブ', 'ライブ'), ('オンデマンド', 'オンデマンド'), ('ライブ・オンデマ併用', 'ライブ・オンデマ併用'), ('対面', '対面'),
('顔出しアリ', '顔出しアリ'), ('顔出しナシ', '顔出しナシ'),('今年度非開講','今年度非開講')]
title = StringField('タイトル*', validators=[DataRequired(), Length(max=15)])
rating = RadioField('評 価*', choices=[(0, 'good'), (1, 'soso'), (2, 'bad')])
content = TextAreaField('本 文*', validators=[DataRequired()])
keyword = MultiCheckboxField('キーワード', choices=keyword_choices)
submit = SubmitField('投 稿')
def validate_title(self, title):
if len(title.data) > 15:
raise ValidationError('タイトルは15字以内で書いてください')
<file_sep>from flask import Blueprint, url_for, request, render_template
from flask_login import current_user
from werkzeug.utils import redirect
from classget import db
from classget.admin.forms import UpdateClassForm
from classget.models import Subject
admin = Blueprint('admin', __name__)
@admin.route("/updateclass/<int:subject_id>", methods=["GET", "POST"])
def updateclass(subject_id):
# UserIDが「admin」の場合だけ
if current_user.is_authenticated and current_user.iduser == 'admin':
subject = Subject.query.get_or_404(subject_id)
form = UpdateClassForm()
# 修正フォームが提出されたら、DBに適用する
if form.validate_on_submit():
subject.sort = form.sort.data
subject.term = form.term.data
subject.time = form.time.data
subject.name = form.name.data
subject.teacher = form.teacher.data
subject.language = form.language.data
subject.draw = form.draw.data
subject.keyword = form.keyword.data
db.session.commit()
return redirect(url_for('reviews.classinfo', subject_id=subject_id))
# ページを開いたら既存の情報がすでに入っている
elif request.method == 'GET':
form.sort.data = subject.sort
form.term.data = subject.term
form.time.data = subject.time
form.name.data = subject.name
form.teacher.data = subject.teacher
form.language.data = subject.language
form.draw.data = subject.draw
form.keyword.data = subject.keyword
return render_template('admin/update_class.html', subject=subject, form=form)
else:
return 'access denied'
@admin.route("/createclass", methods=["GET", "POST"])
def createclass():
form = UpdateClassForm()
if current_user.is_authenticated and current_user.iduser == 'admin':
if form.validate_on_submit():
new_subject = Subject(sort=form.sort.data, term=form.term.data, time=form.time.data, name=form.name.data,
teacher=form.teacher.data, language=form.language.data, draw=form.draw.data,
keyword=form.keyword.data)
db.session.add(new_subject)
db.session.commit()
return redirect(url_for('reviews.classinfo', subject_id=new_subject.id))
else:
return 'access denied'
return render_template('admin/createclass.html', form=form)
@admin.route("/report.html")
def report_html():
return render_template('report.html')
| 44492e8aceafd88187af453c4080e1ebe1d7abdc | [
"JavaScript",
"Python",
"Text",
"HTML"
] | 17 | Python | diseungie/classget | 7370c1772ba3c5ccdd7a29cd8861dde6a925a80a | f79e3d33e219c97af19769ceef558eee7499b31b |
refs/heads/master | <file_sep>import React from "react";
const validationComponent = props => {
let textLength = null;
if (props.textLength <= 5) {
textLength = <p>Text too short</p>;
} else {
textLength = <p>Text long enough</p>;
}
return <div>{textLength}</div>;
};
export default validationComponent;
| 219d7713ecf76a0e4dd7df6d91a008cdd3640da2 | [
"JavaScript"
] | 1 | JavaScript | anilkumartudu/react-lists-and-conditionals | 01d60bf5743518f368214e4527fab806e48eeb30 | b8e3cd60c094f818c98cfccf0d292582bfbca8f6 |
refs/heads/master | <repo_name>Relykon/Scrabble_Score<file_sep>/ScrabbleScore/Program.cs
// for(i=0; i<word.length; i++)
// {
// char letter = Word[i];
// if(letter == 'a');
// int letterScore = 1;
// return letterScore;
// }
// else
// {
//
// }
| d79cfe815e2b511f603671762e8872985bb451ec | [
"C#"
] | 1 | C# | Relykon/Scrabble_Score | d72ac165ee894b87403563f04df6202fca71b320 | 90b778fed47aaad57a2ac17f4fa547dea38d7cbd |
refs/heads/master | <repo_name>ranjitkshah/PaintHub<file_sep>/src/Components/LoginPage.js
import React from 'react';
import styles from '../CompStyles/loginPage.module.css';
import TwitterIcon from '@material-ui/icons/Twitter';
import FacebookIcon from '@material-ui/icons/Facebook';
import InstagramIcon from '@material-ui/icons/Instagram';
import { TextField, Button } from '@material-ui/core';
import Box from '@material-ui/core/Box';
function LoginPage() {
return (
<div className={styles.centerAlign}>
<div className={styles.formWrapper}>
<form className={styles.loginForm} noValidate autoComplete="off">
<TextField className={styles.inputs} id="login-username" label="Username" />
<TextField className={styles.inputs} id="login-password" label="<PASSWORD>" />
<Button variant="contained" color="primary"><Box pt={.5} pb={.5} pl={2} pr={2}>Login </Box></Button>
</form>
</div>
<div className={styles.socialIcons}>
<TwitterIcon className={styles.icon} style={{ color:'#376BAA' }}/>
<FacebookIcon className={styles.icon} style={{ color:'#376BAA' }}/>
<InstagramIcon className={styles.icon} style={{ color:'#376BAA' }} />
</div>
</div>
)
}
export default LoginPage
<file_sep>/src/Components/LiveSchedule.js
import React from 'react'
import LessonCard from './Utilities/LessonCard'
import styles from '../CompStyles/liveSchedule.module.css';
function LiveSchedule() {
return (
<div className={styles.liveSchedule}>
<div>
<h3>Ongoing</h3>
<div className={styles.liveCards} >
<LessonCard title="social" percentage="40" background="125deg, #FF6200 0%, #FD9346 100%"/>
<LessonCard title="biology" percentage="53" background="125deg, #20C7C3 0%, #58F4EF 100%"/>
</div>
</div>
<div>
<h3>Scheduled live sessions</h3>
<div className={styles.liveCards} >
<LessonCard title="Telugu" percentage="20" background="125deg, #1D976C 0%, #9DD138 100%"/>
<LessonCard title="Hindi" percentage="88" background="125deg, #2375D3 0%, #3BA9FE 100%" />
<LessonCard title="english" percentage="60" background="125deg, #F03748 0%, #F78179 100%"/>
</div>
</div>
</div>
)
}
export default LiveSchedule
<file_sep>/src/Components/Utilities/VideoLecture.js
import React from 'react';
import ReactPlayer from 'react-player';
import { Button } from '@material-ui/core';
import video from "../../mov_bbb.mp4";
import styles from '../../CompStyles/videoLecture.module.css';
function VideoLecture({ url, chapName,desc }) {//kahaan se aara h?
return (
<div class={styles.videoWrapper}>
<div className={styles.video}>
<ReactPlayer height="330px" width="600px" url={url} controls />
</div>
<div>
<h2>{chapName}</h2>
<p>{desc}</p>
<Button variant="contained" color="primary">Next</Button>
</div>
</div>
)
}
export default VideoLecture
<file_sep>/src/Components/QuizPage.js
import React, { useState, useEffect } from 'react';
import { Button } from '@material-ui/core';
import Alert from '@material-ui/lab/Alert';
import Box from '@material-ui/core/Box';
import styles from '../CompStyles/quizPage.module.css';
import QuizQuestion from './Utilities/QuizQuestion'
import MyTimer from './Utilities/MyTimer'
const questions = [
{
id: 1,
question: 'Which statement about Hooks is not true?',
correct_answer: 'C',
answers:
[
{
value: "A",
answer: 'Hooks are 100% backwards-compatible and can be used side by side with classes'
},
{
value: "B",
answer: 'Hooks are still in beta and not available yet'
},
{
value: "C",
answer:
"Hooks are completely opt-in, there's no need to rewrite existing code"
},
{
value: "D",
answer: 'All of the above'
},
],
},
{
id: 2,
question: 'Which of the following is a fruit?',
correct_answer: 'A',
answers:
[
{
value: "A",
answer: 'apple'
},
{
value: "B",
answer: 'carryminati'
},
{
value: "C",
answer:
"pubg"
},
{
value: "D",
answer: 'loki'
},
],
},
{
id: 3,
question: 'What is the real name of Gamerdidi?',
correct_answer: 'A',
answers:
[
{
value: "A",
answer: 'Meghal'
},
{
value: "B",
answer: 'Normienoob'
},
{
value: "C",
answer: 'Loki'
}
],
},
{
id: 4,
question: 'What is the day today?',
correct_answer: 'E',
answers:
[
{
value: "A",
answer: 'tomorrow'
},
{
value: "B",
answer: 'today'
},
{
value: "C",
answer: 'yesterday'
},
{
value: "D",
answer: 'wrong question'
},
{
value: "E",
answer: 'one of sunday to monday'
}
],
},
];
function QuizPage() {
const [submitAnswer, setSubmitAnswer] = useState({});
const [showResult, setShowResult] = useState(false);
const [score, setScore] = useState(0);
const myAns = e => {
setSubmitAnswer((previousState) => ({ ...previousState, [e.target.name]: e.target.value }));
}
const resetAllStates = () => {
setSubmitAnswer({});
setShowResult(false);
setScore(0);
}
const submitQuizHandler = (e) => {
alert('sure?');
setShowResult(true);
checkAnswers(submitAnswer);
}
const renderResultsData = () => {
return (questions.map(question => {
return (
<h3 key={question.id}>
{question.question} - {question.correct_answer}
</h3>
);
}))
};
const checkAnswers = (solution) => {
{
let count = 0;
questions.map(question => {
if (question.correct_answer === solution[question.id.toString()]) {
count++;
setScore(count);
}
})
}
}
if (showResult) {
return (<div className={styles.quizCompleted}>
<h1>You have completed the test!</h1>
<h1>Your score is {score}/{questions.length} </h1>
<h2>Correct Answers are:</h2>
{renderResultsData()}
</div>)
}
else {
return (
<div className={styles.quizPage}>
<section className={styles.testHeader}>
<div className={styles.testInfo}>
<p className={styles.chapName}>Chapter Name</p>
<p className={styles.testName}>Name of the test</p>
</div>
<div className={styles.testTimer}>
<p> <span style={{fontSize:"20px"}}>Time left : </span><span><MyTimer submitQuizHandler={submitQuizHandler} time={10} /></span> </p>
</div>
</section>
<form className={styles.quizQuestionList}>
{
questions.map((props) => {
return <QuizQuestion props={props} myAns={myAns} />
})
}
<Button onClick={submitQuizHandler} className={styles.submitQuizBtn} variant="contained" color="secondary"><Box pt={0.5} pb={.5} pl={3.5} pr={3.5}>Submit</Box></Button>
</form>
</div>
)
}
}
export default QuizPage
<file_sep>/src/Components/LiveStream.js
import React from 'react'
import VideoLecture from '../Components/Utilities/VideoLecture';
function LiveStream() {
return (
<div>
<VideoLecture url="https://www.youtube.com/watch?v=7sDY4m8KNLc" />
</div>
)
}
export default LiveStream
<file_sep>/src/Components/Utilities/NavBar.js
import React from 'react';
import styles from '../../CompStyles/UtilitiesStyle/NavBar.module.css';
import { AppBar, Toolbar, Typography, IconButton, Button, Grid } from '@material-ui/core';
const NavBar = () => {
return (
<div>
<AppBar position="sticky" className={styles.appBar} style={{ padding: 0 }}>
<Toolbar>
<Grid container spacing={24}>
<Grid item lg={9} md={8} xs={8} sm={6}>
<Typography className={styles.heading}>Dummy website name</Typography>
</Grid>
<Grid item lg={3} md={4} xs={4} sm={6}>
<div>
<button className={styles.navBtn}>Login</button>
<button className={styles.navBtn}>Select class</button>
</div>
</Grid>
</Grid>
</Toolbar>
</AppBar>
</div>
)
}
export default NavBar
<file_sep>/src/Components/axiosInstance.js
import axios from 'axios'
const instance= axios.create({baseURL:'http://painthb.herokuapp.com/',timeout:100000});
export default instance;<file_sep>/src/Components/LessonPage.js
import React from 'react'
import styles from '../CompStyles/lessonPage.module.css';
import LessonCard from './Utilities/LessonCard'
function LessonPage() {
return (
<div>
<div style={{ marginTop: "100px" }} className={styles.lessonCards}>
<LessonCard title="Telugu" percentage="20" background="125deg, #1D976C 0%, #9DD138 100%" />
<LessonCard title="Hindi" percentage="3" background="125deg, #2375D3 0%, #3BA9FE 100%" />
<LessonCard title="science" percentage="50" background="125deg, #F03748 0%, #F78179 100%" />
<LessonCard title="biology" percentage="10" background="125deg, #20C7C3 0%, #58F4EF 100%" />
<LessonCard title="english" percentage="60" background="125deg, #A36CFC 0%, #DAACE0 100%" />
<LessonCard title="mathematics" percentage="26" background="125deg, #F791AB 0%, #FCE484 100%" />
<LessonCard title="social" percentage="40" background="125deg, #FF6200 0%, #FD9346 100%" />
<LessonCard title="general" percentage="99" background="125deg, #2375D3 0%, #67D0E8 100%" />
</div>
</div>
)
}
export default LessonPage
<file_sep>/src/App.js
import React from 'react';
import LoginPage from './Components/LoginPage';
import LessonPage from './Components/LessonPage';
import DashBar from './Components/Utilities/DashBar';
import Navbar from './Components/Utilities/NavBar';
import QuizPage from './Components/QuizPage';
import VideoLecturePage from './Components/VideoLecturePage';
import LiveSchedule from './Components/LiveSchedule';
import AssignmentPage from './Components/AssignmentPage';
import LiveStream from './Components/LiveStream';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import APIFetcher from './Components/Utilities/APIFetcher'
function App() {
return (
<div className="App">
<Router>
<Route path='/' component={Navbar} />
<Route path='/' component={DashBar} />
<Route path='/' exact component={LoginPage} />
<Route path='/schedule' exact component={LiveSchedule} />
<Route path='/quiz' exact component={QuizPage} />
<Route path='/assignment' exact component={AssignmentPage} />
<Route path='/video' exact component={VideoLecturePage} />
<Route path='/lesson' exact component={LessonPage} />
{/* <LiveStream /> */}
<APIFetcher></APIFetcher>
</Router>
</div>
);
}
export default App;
<file_sep>/src/Components/AssignmentPage.js
import React, { useState } from 'react'
import LessonCard from '../Components/Utilities/LessonCard';
import styles from '../CompStyles/assignmentCard.module.css';
import AssignmentTimer from './Utilities/AssignmentTimer';
const assignments = [
{
assignmentId: 1,
subject: "Maths",
lastDateToSubmit: "2020-05-25",
},
{
assignmentId: 2,
subject: "Civics",
lastDateToSubmit: "2020-06-20",
},
{
assignmentId: 3,
subject: "Python",
lastDateToSubmit: "2020-05-5",
},
{
assignmentId: 4,
subject: "Kinematics",
lastDateToSubmit: "2020-05-29",
},
]
function AssignmentPage() {
const colorArray = {
success: "122deg, #1D976C 0%, #9DD138 100%",
failure: "131deg, #CB2D3E 0%, #EF473A 100%",
ongoing: "132deg, #2375D3 0%, #3BA9FE 100%"
}
const [success, setSuccess] = useState(false);
const [failure, setFailure] = useState(false);
const [ongoing, setOngoing] = useState(true);
return (
<>
<h1 style={{ margin: "20px 100px" }}>Assignments</h1>
<div className={styles.assignmentCards}>
{
assignments.map((assignment) => {
return <LessonCard style={{ height: '10px' }} title={assignment.subject} percentage="13" background={ongoing ? colorArray['ongoing'] : colorArray['failure']}>
<p className={styles.track}>Time to work!</p>
<AssignmentTimer lastDateToSubmit={assignment.lastDateToSubmit} />
</LessonCard>
})
}
</div>
</>
)
}
export default AssignmentPage
<file_sep>/src/Components/Utilities/Answers.js
import React from 'react'
function Answers({ props, myAns }) {
return (
<div>
{
props.answers.map(answer => {
return (
<div>
<input onClick={myAns} type="radio" name={props.id} id={`${props.id}-${answer.value}`} value={answer.value} />
<label for={`${props.id}-${answer.value}`}> {answer.answer} </label>
</div>
)
})
}
</div>
)
}
export default Answers
<file_sep>/src/Components/Utilities/ProgressBar.js
import React from 'react';
import styled from 'styled-components';
const Track = styled.div`
width: 70%;
height: 20px;
background-color: #bebebe;
border-radius: 4px;
`;
const Thumb = styled.div`
&:after{
content: "${props => props.percentage}%";
position: absolute;
left: 220px;
top: -8px;
color: #fff;
font-weight: bold;
font-size: 22px;
}
position: relative;
width: ${props => props.percentage}%;
height: 100%;
background-color: #fff;
border-radius: 4px;
`;
function ProgressBar(props){
return (
<Track>
<Thumb percentage={props.percentage} />
</Track>
);
}
export default ProgressBar | 5fd479aa0a892d7673765959af5bdead9816b7bd | [
"JavaScript"
] | 12 | JavaScript | ranjitkshah/PaintHub | 2fd64e8373217b7bb9bf9c3291253eff3d2510bb | 8790f547ba8777198ed9e7c44a5d2e2fe5af376c |
refs/heads/main | <file_sep># cnc_analyzer
## 의존성
* python 3.7.10
* tensorflow-gpu 2.4.1
* matplotlib 3.4.2
* pandas 1.2.4
* ipykernel 5.3.4
## 디렉토리 및 파일 구성
* 데이터 원본
- input 폴더
* 데이터 전처리
- data
+ roll : preprocess_smoothing_op10_3.ipynb 롤링(평균이동) 기법 적용
* State-LSTM
- lstm_state_model_train_op10_3_001.py
* Bi-State-LSTM
- bi_lstm_state_model_train_op10_3_001.py
* Bi-State-GRU
- bi_gru_state_model_train_op10_3.py
* 모델 평가
- model_predict.ipynb
* 모델 저장
- model
+ lstm-state
+ bi-lstm-state
+ bi-gru-state
<file_sep>import numpy as np
import pandas as pd
import datetime
import os
import tensorflow as tf
import hn.utile as hnutile
# from keras_self_attention import SeqSelfAttention
# from keras_self_attention import SeqSelfAttention
# 루트 디렉토리
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
# 모델 저장 루트 디렉토리명
MODEL_ROOT_DIR_NAME = 'model'
# 모델 저장 서브 디렉토리명
MODEL_SUB_DIR_NAME = 'bi-gru-state'
# 모델파일 접두사
MODEL_FILE_PREFIX = 'bi-gru-state-model-'
# 학습데이터 루트 디렉토리명
TRAIN_ROOT_DIR_NAME = 'data'
# 학습데이터 서브 디렉토리명
TRAIN_SUB_DIR_NAME = 'roll'
# 학습데이터 파일 접두사
TRAIN_FILR_PREFIX = 'train-01-'
# 학습데이터 경로
CSV_FILE_PATH = os.path.join(ROOT_DIR, TRAIN_ROOT_DIR_NAME, TRAIN_SUB_DIR_NAME, TRAIN_FILR_PREFIX)
# 학습, 예측 데이터 루프백 사이즈
LOOK_BACK = 30
FIT_PATIENCE = 80
def run_trainning(model, fits, x_trains, y_trains, x_vals, y_vals):
'''
'''
custom_hist = hnutile.CustomEarlyStopCallback()
# model = tf.keras.models.load_model(os.path.join(ROOT_DIR, MODEL_ROOT_DIR_NAME, MODEL_SUB_DIR_NAME, '074', 'bi-lstm-state-model-074-068-0.000107-0.000110.h5'))
for i in range(len(x_trains)):
custom_hist.init(os.path.join(ROOT_DIR, MODEL_ROOT_DIR_NAME, MODEL_SUB_DIR_NAME), i, FIT_PATIENCE, MODEL_FILE_PREFIX)
# 모델 저장 폴더 생성
hnutile.MakeDir(os.path.join(ROOT_DIR, MODEL_ROOT_DIR_NAME, MODEL_SUB_DIR_NAME,'%03d'%(i)))
print('File %03dth: Start trainning.'%(i))
for j in range(fits):
custom_hist.set_fit_count(j)
print('Fit %d/%d.'%(j+1, fits))
hist = model.fit(x_trains[i], y_trains[i], epochs=1, batch_size=1, shuffle=False, callbacks=[custom_hist], validation_data=(x_vals[i%10], y_vals[i%10]))
model.reset_states()
# 조기 종료 체크
if custom_hist.early_stop():
break
# Bset model 선정
base_model_name = hnutile.FindBestModel(os.path.join(ROOT_DIR, MODEL_ROOT_DIR_NAME, MODEL_SUB_DIR_NAME, '%03d'%(i)), MODEL_FILE_PREFIX)
if base_model_name != None:
print('File %03dth: The best model to be use is model >> %s.'%(i ,base_model_name))
model = tf.keras.models.load_model(os.path.join(ROOT_DIR, MODEL_ROOT_DIR_NAME, MODEL_SUB_DIR_NAME, '%03d'%(i), base_model_name))
else:
print('File %03dth: Best model does not exist.'%(i))
def create_bi_state_lstm_model(look_back=1):
'''
양방향 상태 전이 LSTM모델 생성
'''
model = tf.keras.Sequential()
for i in range(4):
model.add(tf.keras.layers.Bidirectional(tf.keras.layers.GRU(50, batch_input_shape=(1, look_back, 1), stateful=True, return_sequences=True)))
model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.Bidirectional(tf.keras.layers.GRU(200, stateful=True, return_sequences=False)))
model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
return model
def main():
'''
메인 함수
'''
datas = []
# train-01-001.csv ~ train-01-100.csv 까지 100개의 데이터 사용
for i in range(100):
file_path = "%s%.3d.csv"%(CSV_FILE_PATH, i+1)
datas.append(pd.read_csv(file_path))
print('%s 파일 데이터 추가.'%(file_path))
# 그래프 출력
hnutile.ShowGraph(datas, yaxis='RollLoad')
load_datas = []
for df in datas:
load_datas.append(df['RollLoad'].values[:, None])
# 학습, 검증 데이터 생성
x_trains, y_trains, x_vals, y_vals = hnutile.CreateTrainDatas(datas=load_datas, look_back=LOOK_BACK)
# 모델 생성
model = create_bi_state_lstm_model(LOOK_BACK)
run_trainning(model, 200,x_trains, y_trains, x_vals, y_vals)
print('Exit process.')
if __name__ == '__main__':
main()
<file_sep>
import numpy as np
from tensorflow.python.client import device_lib
import plotly.graph_objects as go
import plotly.io as pio
import tensorflow as tf
import os
import re
def GPU_INFO():
print(device_lib.list_local_devices())
def create_dataset(signal_data, look_back=1):
'''
룩백사이즈로 데이터 생성
dataX 루백사이즈 데이터 array
dataY 루백+1번째 데이터 array(1건)
'''
dataX, dataY = [], []
for i in range(len(signal_data)-look_back):
dataX.append(signal_data[i:(i+look_back), 0])
dataY.append(signal_data[i + look_back, 0])
return np.array(dataX), np.array(dataY)
def CreateTrainDatas(datas, look_back=1):
'''
'''
x_trains = []
y_trains = []
x_vals = []
y_vals = []
for i in range(90):
x_train, y_train = create_dataset(datas[i], look_back)
x_trains.append(x_train)
y_trains.append(y_train)
for i in range(10):
x_val, y_val = create_dataset(datas[i+90], look_back)
x_vals.append(x_val)
y_vals.append(y_val)
# 입력형 변환
for i in range(len(x_trains)):
x_trains[i] = np.reshape(x_trains[i], (x_trains[i].shape[0], x_trains[i].shape[1], 1))
for i in range(len(x_vals)):
x_vals[i] = np.reshape(x_vals[i], (x_vals[i].shape[0], x_vals[i].shape[1], 1))
return x_trains, y_trains, x_vals, y_vals
def ShowGraph(datas, yaxis='Load'):
pio.templates.default = "plotly_dark"
fig = go.Figure(layout=go.Layout(height=600, width=1200))
cnt = 0
for df in datas:
fig = fig.add_trace(go.Scatter(y=df[yaxis], mode='lines', name = yaxis + str(cnt), line=dict(width=1)))
cnt += 1
fig.update_layout(title=yaxis,
xaxis_title='x',
yaxis_title='y')
fig.show()
def FindBestModel(path_dir, file_pre_fix):
regex = re.compile(r'^%s(\d{3})-(\d{3})-(\d.\d{6})-(\d.\d{6}).h5'%(file_pre_fix))
file_list = os.listdir(path_dir)
val_loss_list = []
for i in range(len(file_list)):
name = file_list[i]
matchobj = regex.search(name)
if matchobj != None:
val_loss_list.append(float(matchobj.group(4)))
# print(val_loss_list)
if len(val_loss_list) > 0:
return file_list[val_loss_list.index(min(val_loss_list))]
return None
def MakeDir(path):
'''
'''
if not os.path.exists(path):
os.makedirs(path)
class CustomEarlyStopCallback(tf.keras.callbacks.Callback):
'''
'''
def init(self, model_dir, file_count, patience=10, file_pre_fix=None):
self.loss = []
self.val_loss = []
self.model_dir = model_dir
self.file_count = file_count
self.patience = patience
self.wait = 0
self.best_val = np.Inf
self.file_pre_fix = file_pre_fix
def early_stop(self):
if self.wait >= self.patience:
print('\nFit %05d: early stopping'%(self.file_count))
return True
return False
def set_fit_count(self, fit_count):
self.fit_count = fit_count
def on_epoch_end(self, batch, logs={}):
if len(self.val_loss) > 0:
min_val_loss = min(self.val_loss)
if min_val_loss > logs.get('val_loss'): # 성능개선이 된 경우
# save
filename = os.path.join(
self.model_dir,
'%03d'%(self.file_count),
'%s%03d-%03d-%.6f-%.6f.h5'%(self.file_pre_fix, self.file_count, self.fit_count, logs.get('loss'), logs.get('val_loss'))
)
self.model.save(filename)
self.best_val = logs.get('val_loss')
self.wait = 0
print('Fit %05d: val_loss improved from %.6f to %.6f, saving model to %s'%(self.fit_count, min_val_loss, logs.get('val_loss'), filename))
else: # 성능개선이 없는경우
self.wait +=1
print('Fit %05d: val_loss did not improve from %.6f'%(self.fit_count, min_val_loss))
else: # 학습 처음시작인경우
filename = os.path.join(
self.model_dir,
'%03d'%(self.file_count),
'%s%03d-%03d-%.6f-%.6f.h5'%(self.file_pre_fix, self.file_count, self.fit_count, logs.get('loss'), logs.get('val_loss'))
)
self.model.save(filename)
self.best_val = logs.get('val_loss')
self.wait = 0
print('Fit %05d: val_loss improved from inf to %.6f, saving model to %s'%(self.fit_count, logs.get('val_loss'), filename))
self.loss.append(logs.get('loss'))
self.val_loss.append(logs.get('val_loss')) | aca3f23a85edda680adcb0b1318daca09b5fecdd | [
"Markdown",
"Python"
] | 3 | Markdown | cybang77/cnc_analyzer | 3403ea6b04e745ce45af7f028749756f14b4e9c4 | 6cfbef15d31ee4be7b572047226eec0e4b2d6789 |
refs/heads/master | <repo_name>makl10/wordfinder<file_sep>/README.md
# wordfinder
## Usage
### Running maven and war (not best practice to run the war with -jar but fine for development, also tomcat suspend debug included):
```
mvn clean install && java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n -jar target/wordfinder-0.0.1-SNAPSHOT.war
```
### Set up DB
- Install MySQL for your env
- Run:
```
CREATE DATABASE IF NOT EXISTS `wordfinder`;
USE `wordfinder`;
DROP TABLE IF EXISTS `wordgrid`;
CREATE TABLE `wordgrid`(
`id` int(11) NOT NULL AUTO_INCREMENT,
`character_grid` varchar(3000) DEFAULT NULL,
`name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB auto_increment=1 default charset=latin1;
```<file_sep>/src/main/java/com/klocke/wordfinder/file/WordSearchFileReader.java
package com.klocke.wordfinder.file;
import org.springframework.web.multipart.MultipartFile;
public interface WordSearchFileReader
{
/**
* Read file from local mnachine
* @param fileLocation
path of file on local machine
* @return
* two dimensional char array representing a grid of letters
*/
char[][] readWordSearchFromFile(String fileLocation);
/**
* Read file uploaded via web front
* @param multipartFile
* file uploaded
* @return
* two dimensional char array representing a grid of letters
*/
char[][] readFromInputFile(MultipartFile multipartFile);
}<file_sep>/src/main/java/com/klocke/wordfinder/controllers/SolvePageController.java
package com.klocke.wordfinder.controllers;
import com.klocke.wordfinder.database.data.WordGrid;
import com.klocke.wordfinder.database.service.WordGridService;
import com.klocke.wordfinder.solver.WordSearchSolver;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.annotation.Resource;
import java.util.List;
@Controller
public class SolvePageController
{
@Resource(name = "wordGridService")
private WordGridService wordGridService;
@Resource(name = "wordSearchSolver")
private WordSearchSolver wordSearchSolver;
@RequestMapping(value = "/solve", method = RequestMethod.GET)
public String upload(Model model)
{
List<WordGrid> allGrids = wordGridService.getAllWordGrids();
model.addAttribute("allGrids", allGrids);
return "solvePage";
}
@RequestMapping(value = "/solve", method = RequestMethod.POST)
public String uploadPost(Model model, RedirectAttributes redirectAttributes,
@RequestParam(name = "word") String wordToCheck, @RequestParam(name = "id") int id)
{
WordGrid wordGrid = wordGridService.retriveWordGridById(id);
if(wordGrid != null)
{
boolean contains = wordSearchSolver.solveForWord(wordToCheck, wordGrid.getCharacterGrid());
if(contains){
redirectAttributes.addFlashAttribute("result", "The word: <b>" + wordToCheck + "</b> is in the grid: " + wordGrid.getName());
}else{
redirectAttributes.addFlashAttribute("result", "The word: <b>" + wordToCheck + "</b> is NOT in the grid: " + wordGrid.getName());
}
}
return "redirect:/solve";
}
}
<file_sep>/src/main/java/com/klocke/wordfinder/database/data/WordGrid.java
package com.klocke.wordfinder.database.data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "wordgrid")
public class WordGrid
{
@Id
@Column(name = "id")
private int id;
@Column(name = "character_grid")
private char[][] characterGrid;
@Column(name = "name")
private String name;
public WordGrid(){}
public WordGrid(char[][] characterGrid, String name) {
this.characterGrid = characterGrid;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public char[][] getCharacterGrid() {
return characterGrid;
}
public void setCharacterGrid(char[][] characterGrid) {
this.characterGrid = characterGrid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString()
{
StringBuffer buffer = new StringBuffer();
buffer.append("Name: " + this.name + " \n");
for(int i = 0; i < characterGrid.length; i++)
{
for(int j = 0; j < characterGrid[i].length; j++)
{
buffer.append(characterGrid[i][j]);
}
buffer.append('\n');
}
return buffer.toString();
}
}
<file_sep>/src/main/java/com/klocke/wordfinder/controllers/HomePageController.java
package com.klocke.wordfinder.controllers;
import com.klocke.wordfinder.database.data.WordGrid;
import com.klocke.wordfinder.database.service.WordGridService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import java.util.List;
@Controller
public class HomePageController
{
@Resource(name = "wordGridService")
private WordGridService wordGridService;
@RequestMapping("/home")
public String getHome(Model model) {
System.out.println("GOT HOME");
System.out.println(model);
List<WordGrid> allGrids = wordGridService.getAllWordGrids();
System.out.println(allGrids);
model.addAttribute("allGrids", allGrids);
return "home";
}
}
| c342075ab4038c1ed11ddb5023251003d752d547 | [
"Markdown",
"Java"
] | 5 | Markdown | makl10/wordfinder | 99533f1ea43dbd7f0462b1b979b88b5a7fc86fb4 | 48b8d05beb6f715c30cf916e9b39fe115b4745c0 |
refs/heads/master | <file_sep>import { Component, OnInit } from '@angular/core';
import { Issue } from '../models/issue';
import { User } from '../models/user';
import { IssueService } from '../services/issue.service';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-issue-form',
templateUrl: './issue-form.component.html',
styleUrls: ['./issue-form.component.scss']
})
export class IssueFormComponent implements OnInit {
constructor(
// tslint:disable-next-line: variable-name
private _IssueService: IssueService,
// tslint:disable-next-line: variable-name
private _router: Router,
private actRoute: ActivatedRoute) { }
// Issue model
issueModel = new Issue('' , '', 'default', 'default', 'default', 'Pending', null);
issueId: string;
projectId = null;
// declare arrays :
priorities = ['low', 'high', 'medium'];
categories = ['Bug', 'Incident'];
stats = ['Pending', 'QA', 'Implementation', 'Closed'];
members = [];
successMsg = '';
// Gestion du select priority
// tslint:disable-next-line: member-ordering
priorityHasError = true;
// Gestion du select category
// tslint:disable-next-line: member-ordering
categoryHasError = true;
// Gestion du select status
// tslint:disable-next-line: member-ordering
statusHasError = true;
submitted = false;
ngOnInit() {
this.issueId = this.actRoute.snapshot.paramMap.get('_id');
this.projectId = this.actRoute.snapshot.paramMap.get('projectId');
this._IssueService.getProjectUsers(this.projectId)
.subscribe(
data => {
this.members = data['members'];
},
err => {
console.error(err);
}
);
if (this.issueId != null) {
this._IssueService.getSpecificIssue(this.issueId)
.subscribe((data: Issue) => {
this.issueModel = data;
},
err => {
console.log(err);
}
);
}
}
validatePriority(value) {
if (value === 'default') {
this.priorityHasError = true;
} else {
this.priorityHasError = false;
}
}
validateCategory(value) {
if (value === 'default') {
this.categoryHasError = true;
} else {
this.categoryHasError = false;
}
}
validateStatus(value) {
if (value === 'default') {
this.statusHasError = true;
} else {
this.statusHasError = false;
}
}
public onSubmit() {
if (this.issueId === null) {
delete this.issueModel._id;
this.issueModel.project = this.projectId;
this._IssueService.addIssue(this.issueModel)
.subscribe(
data => {
this.successMsg = 'Issue créee !';
setTimeout(() => {
this.successMsg = '';
}, 3000);
this.ngOnInit();
// this._router.navigate(['/template/home']);
},
error => {
console.error('Erreur : ', error);
}
);
} else {
this._IssueService.updateIssue(this.issueModel)
.subscribe(
data => {
this.successMsg = 'Issue modifiée !';
setTimeout(() => {
this.successMsg = '';
}, 3000);
// this._router.navigate(['/template/home']);
},
error => {
console.error('Erreur : ', error);
}
);
}
}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
import { JwtHelperService } from '@auth0/angular-jwt';
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class LoginService {
private loginUrl = 'http://localhost:4000/login';
helper = new JwtHelperService();
constructor(private http: HttpClient, private router: Router) { }
login(user) {
return this.http.post<any>(this.loginUrl, user)
.pipe(catchError(this.errorHandler));
}
errorHandler(error: HttpErrorResponse) {
return throwError(error);
}
loggedIn() {
return !!localStorage.getItem('token');
}
logout() {
localStorage.removeItem('token');
this.router.navigate(['/']);
}
getToken() {
return localStorage.getItem('token');
}
getTokenSubject() {
return this.helper.decodeToken(localStorage.getItem('token'));
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { LoginService } from '../services/login.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
constructor(private _log: LoginService, private routerLink: Router) { }
loginData = {uname:'', password:''};
errorMsg= '';
ngOnInit() {
}
onSubmit(){
this._log.login(this.loginData)
.subscribe(
data => {
localStorage.setItem('token', data.token);
this.routerLink.navigate(['/template']);
},
error => {
this.errorMsg = error.statusText;
}
);
}
login(){
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { User } from '../models/user';
import { UserService } from '../services/user.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-user-form',
templateUrl: './user-form.component.html',
styleUrls: ['./user-form.component.scss']
})
export class UserFormComponent implements OnInit {
// tslint:disable-next-line: variable-name
constructor(private _userService: UserService, private _router: Router) { }
roles = ['developer', 'architect', 'analyste', 'programmer'];
userModel = new User('', '', '', '', '', '', '', 'default', [], []);
passwordConfirm = true;
submitted = false;
roleHasError = true;
successMsg = '';
// tslint:disable-next-line: member-ordering
errorMsg = '';
validatePassword(pwd, password) {
if (pwd !== password) {
this.passwordConfirm = false;
} else {
this.passwordConfirm = true;
}
}
validateRole(value) {
if (value === 'default') {
this.roleHasError = true;
} else {
this.roleHasError = false;
}
}
onSubmit() {
this.submitted = true;
delete this.userModel._id;
this._userService.addUser(this.userModel)
.subscribe(
data => {
this.successMsg = 'utilisateur créé !';
setTimeout(() => {
this.successMsg = '';
}, 2000);
this._router.navigate(['/login']);
},
error => this.errorMsg = error.statusText
);
}
ngOnInit() {
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Issue } from '../models/issue';
import { Project } from '../models/project';
import { IssueService } from '../services/issue.service';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-issue',
templateUrl: './issue.component.html',
styleUrls: ['./issue.component.scss']
})
export class IssueComponent implements OnInit {
constructor(private issueService: IssueService, private router: Router,
private actRoute: ActivatedRoute ) { }
issues: Issue[];
projectId = null;
admin: boolean;
title: string;
project: Project;
ngOnInit() {
this.projectId = this.actRoute.snapshot.paramMap.get('id');
this.title = this.actRoute.snapshot.paramMap.get('title');
this.issueService.getIssue(this.projectId)
.subscribe((data: Issue[]) => {
this.issues = data;
});
this.issueService.isAdmin(this.projectId)
.subscribe(
(data: boolean) => {
this.admin = data;
},
err => {
console.error(err);
}
);
}
takeIssue(issueId) {
this.issueService.takeIssue(issueId)
.subscribe(
data => {
this.router.navigate(['/template/home']);
},
err => {
console.error(err);
}
);
}
deleteIssue(id) {
this.issueService.deleteIssue(id).subscribe(res => {
console.log('Deleted');
});
window.location.reload();
}
isAdmin(projectId) {
}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class MainService {
constructor(private http: HttpClient) { }
private uri = 'http://localhost:4000/home';
// retourne les projets de l'utilisater courent
getProjects() {
return this.http.get(this.uri + '/')
.pipe(catchError(this.errorHandler));
}
// retourne le nom et le prénom de l'utilisateur courent
getUser() {
return this.http.get(this.uri + '/user')
.pipe(catchError(this.errorHandler));
}
errorHandler(error: HttpErrorResponse) {
return throwError(error);
}
deleteProject(projectId) {
return this.http.delete(this.uri + '/deleteProject/' + projectId)
.pipe(catchError(this.errorHandler));
}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ProfilService {
constructor(private http: HttpClient) { }
private uri = 'http://localhost:4000/profil';
getUser() {
return this.http.get(this.uri + '/')
.pipe(catchError(this.errorHandler));
}
errorHandler(error: HttpErrorResponse) {
return throwError(error);
}
updateUser(user) {
return this.http.put<any>(this.uri + '/update', user)
.pipe(catchError(this.errorHandler));
}
updatePassword(request) {
return this.http.put<any>(this.uri + '/updatePassword', request)
.pipe(catchError(this.errorHandler));
}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class MyissueService {
private uri = 'http://localhost:4000/issue';
constructor(private http: HttpClient) { }
getMyIssues() {
return this.http.get(this.uri + '/getIssues')
.pipe(catchError(this.errorHandler));
}
errorHandler(error: HttpErrorResponse) {
return throwError(error);
}
nextStep(issueId) {
return this.http.get(this.uri + '/next/' + issueId)
.pipe(catchError(this.errorHandler));
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Project } from '../models/project';
import { ProjectService } from '../services/project.service';
import { LoginService } from '../services/login.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-project-form',
templateUrl: './project-form.component.html',
styleUrls: ['./project-form.component.scss']
})
export class ProjectFormComponent implements OnInit {
constructor(private projectService: ProjectService, private loginService: LoginService,
private router: Router) { }
projectModel = new Project('', '', '', '', null, null);
existUser = true;
currentMember = '';
members = [];
users = [];
projects = [];
request = {};
successMsg = '';
ngOnInit() {
this.projectService.addProjet()
.subscribe(
data => {
Object.keys(data).forEach(key => {
if (key === 'users') {
this.users = data[key];
} else {
this.projects = data[key];
}
});
},
err => {
console.log(err.statusText);
}
);
}
addmember(value) {
if (this.users.indexOf(value) === -1 ) {
this.existUser = false;
} else {
this.existUser = true;
this.members.push(value);
this.currentMember = '';
}
}
removemember(value) {
this.members.splice(this.members.indexOf(value), 1);
}
onSubmit() {
this.request = {
title : this.projectModel.title,
description : this.projectModel.description,
admin: this.loginService.getTokenSubject().subject,
members: this.members
};
this.projectService.add(this.request)
.subscribe(
data => {
this.successMsg = 'Projet créé !';
setTimeout(() => {
this.successMsg = '';
}, 3000);
// this.router.navigate(['/template/home']);
},
err => {
console.log(err.statusText);
}
);
}
}
<file_sep>export class Password {
constructor(
public pass: string,
public Newpwd: string,
public Confirmpwd: string
) {}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { MainService } from '../services/main.service';
import { Projects } from '../models/Projects';
import { Project } from '../models/project';
import { Router } from '@angular/router';
@Component({
selector: 'app-main',
templateUrl: './main.component.html',
styleUrls: ['./main.component.scss']
})
export class MainComponent implements OnInit {
constructor(private mainService: MainService, private router: Router) { }
projects: Projects;
adminProject: Project[];
memberProject: Project[];
ngOnInit() {
this.mainService.getProjects()
.subscribe(
(data: Projects) => {
this.projects = data;
this.adminProject = this.projects.admin;
this.memberProject = this.projects.member;
},
err => {
console.log(err);
}
);
}
deleteProject(projectId) {
this.mainService.deleteProject(projectId)
.subscribe(
data => {
window.location.reload();
// this.router.navigate(['/template/home']);
},
err => {
console.error(err);
}
);
}
}
<file_sep>export class Issue {
constructor(
public _id: string,
public description: string,
public priority: string,
public assignedTo: string,
public category: string,
public status: string,
public project: string
) {}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { User } from '../models/user';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class UserService {
_uri = 'http://localhost:4000/user';
constructor(private _http: HttpClient) { }
addUser(user: User) {
return this._http.post<any>(this._uri + '/add', user)
.pipe(catchError(this.errorHandler));
}
errorHandler(error: HttpErrorResponse) {
return throwError(error);
}
getUser() {
return this._http.get(this._uri + '/');
}
setActivation(user: User) {
return this._http.post<any>(this._uri + '/setActivation', user);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { MainService } from '../services/main.service';
import { LoginService } from '../services/login.service';
import { User } from '../models/user';
@Component({
selector: 'app-template',
templateUrl: './template.component.html',
styleUrls: ['./template.component.scss']
})
export class TemplateComponent implements OnInit {
constructor(private routerLink: Router , private mainService: MainService, private loginService: LoginService) { }
user: User;
userName: string;
ngOnInit() {
this.mainService.getUser()
.subscribe(
(data: User) => {
this.user = data;
this.userName = this.user.lname + ' ' + this.user.name;
},
err => {
console.log(err);
}
);
this.routerLink.navigate(['template/home']);
}
logout() {
this.loginService.logout();
}
}
<file_sep>import { TestBed } from '@angular/core/testing';
import { MyissueService } from './myissue.service';
describe('MyissueService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: MyissueService = TestBed.get(MyissueService);
expect(service).toBeTruthy();
});
});
<file_sep>import { Component, OnInit } from '@angular/core';
import { ProjectService } from '../services/project.service';
import { Project } from '../models/project';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-edit-project',
templateUrl: './edit-project.component.html',
styleUrls: ['./edit-project.component.scss']
})
export class EditProjectComponent implements OnInit {
constructor(private router: Router, private projectService: ProjectService,
private actRoute: ActivatedRoute) { }
projectId: string;
project = new Project('', '', '', '', [], []);
existUser = true;
currentMember = '';
members = [];
users = [];
projects = [];
successMsg = '';
request = {
project : null,
members : []
};
ngOnInit() {
this.projectService.addProjet()
.subscribe(
data => {
Object.keys(data).forEach(key => {
if (key === 'users') {
this.users = data[key];
} else {
this.projects = data[key];
}
});
},
err => {
console.log(err.statusText);
}
);
this.projectId = this.actRoute.snapshot.paramMap.get('projectId');
this.projectService.getProject(this.projectId)
.subscribe(
(data: Project) => {
this.project = data;
this.project.members.forEach(element => {
this.members.push(element['email']);
});
},
err => {
console.error(err);
}
);
}
addmember(value) {
if (this.users.indexOf(value) === -1 ) {
this.existUser = false;
} else {
this.existUser = true;
this.members.push(value);
this.currentMember = '';
}
}
removemember(value) {
this.members.splice(this.members.indexOf(value), 1);
}
onSubmit() {
//console.log(this.members);
this.request.project = this.project;
this.request.members = this.members;
this.projectService.updateProject(this.request)
.subscribe(
data => {
this.successMsg = 'Projet modifié !';
setTimeout(() => {
this.successMsg = '';
}, 3000);
// this.router.navigate(['/template/home']);
},
err => {
console.error(err);
});
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { ProfilService } from '../services/profil.service';
import { User } from '../models/user';
import { Password } from '../models/password';
@Component({
selector: 'app-profil',
templateUrl: './profil.component.html',
styleUrls: ['./profil.component.scss']
})
export class ProfilComponent implements OnInit {
constructor(private profilService: ProfilService) { }
user = new User('', '', '', '', '', '', '', '', [], []);
password = new Password('', '', '');
passwordConfirm = false;
errorMsg = '';
successMsg = '';
ngOnInit() {
this.profilService.getUser()
.subscribe(
(data: User) => {
this.user = data;
},
err => {
console.error(err);
}
);
}
onSubmit() {
this.profilService.updateUser(this.user)
.subscribe(
data => {
this.successMsg = 'User updated !';
setTimeout(() => {
this.successMsg = '';
}, 2000);
},
err => {
this.errorMsg = err.statusText;
}
);
}
onSubmitPwd() {
this.profilService.updatePassword(this.password)
.subscribe(
data => {
this.successMsg = 'Password updated !';
setTimeout(() => {
this.successMsg = '';
}, 2000);
},
err => {
this.errorMsg = err.statusText;
}
);
}
validatePassword(pwd, password) {
if (pwd !== password) {
this.passwordConfirm = false;
} else {
this.passwordConfirm = true;
}
}
}
<file_sep>let mongoose = require('mongoose');
let userSchema = mongoose.Schema({
name: {
type: String,
required: true
},
lname: {
type: String,
required: true
},
uname: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
role: {
type: String,
},
projects: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Project"
}],
projectsAdmin: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Project"
}]
});
let User = module.exports = mongoose.model('User', userSchema);<file_sep>export class User {
constructor(
// tslint:disable-next-line: variable-name
public _id: string,
public name: string,
public lname: string,
public uname: string,
public email: string,
public password: string,
public pwd: string,
public role: string,
public projects: object[],
public projectsAdmin: object[]
) {}
}
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { SlimLoadingBarModule } from 'ng2-slim-loading-bar'; // loading bar
/* import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
*/
import { AppRoutingModule, routingComponent } from './app-routing.module';
import { AppComponent } from './app.component';
import { MainComponent } from './main/main.component';
import { IssueComponent } from './issue/issue.component';
import { UserComponent } from './user/user.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { LoginComponent } from './login/login.component';
import { LoginService } from './services/login.service';
import { AuthGuard } from './services/auth.guard';
import { TokenInterceptorService } from './services/token-interceptor.service';
import { ProjectFormComponent } from './project-form/project-form.component';
import { TemplateComponent } from './template/template.component';
import { EditProjectComponent } from './edit-project/edit-project.component';
import { AngularFontAwesomeModule } from 'angular-font-awesome';
// MDB Angular Pro
import { ButtonsModule, WavesModule, CardsModule } from 'angular-bootstrap-md';
import { ProfilComponent } from './profil/profil.component';
@NgModule({
declarations: [
AppComponent,
routingComponent,
MainComponent,
IssueComponent,
UserComponent,
PageNotFoundComponent,
LoginComponent,
ProjectFormComponent,
TemplateComponent,
EditProjectComponent,
ProfilComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
ButtonsModule,
WavesModule,
CardsModule,
HttpClientModule,
SlimLoadingBarModule,
AngularFontAwesomeModule
/* MatAutocompleteModule,
MatFormFieldModule,
MatInputModule, */
],
providers: [LoginService, AuthGuard,
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptorService,
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { TemplateComponent } from './template/template.component';
import { IssueFormComponent } from './issue-form/issue-form.component';
import { UserFormComponent } from './user-form/user-form.component';
import { IssueComponent } from './issue/issue.component';
import { MainComponent } from './main/main.component';
import { UserComponent } from './user/user.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { LoginComponent } from './login/login.component';
import { AuthGuard } from './services/auth.guard';
import { ProjectFormComponent } from './project-form/project-form.component';
import { EditProjectComponent } from './edit-project/edit-project.component';
import { MyIssuesComponent } from './my-issues/my-issues.component';
import { ProfilComponent } from './profil/profil.component';
const routes: Routes = [
{path: '', redirectTo: 'login', pathMatch: 'full'},
{path : 'login', component : LoginComponent},
{path : 'addUser', component : UserFormComponent},
{path : 'template', component : TemplateComponent, canActivate : [AuthGuard],
children: [
{path : 'addProject', component: ProjectFormComponent, canActivate : [AuthGuard]},
{path : 'editProject/:projectId', component: EditProjectComponent, canActivate : [AuthGuard]},
{path : 'issue/:id/:title', component: IssueComponent, canActivate : [AuthGuard]},
{path : 'updateIssue/:_id/:projectId', component: IssueFormComponent, canActivate : [AuthGuard]},
{path : 'addIssue/:projectId', component : IssueFormComponent, canActivate : [AuthGuard]},
{path : 'getIssues', component : MyIssuesComponent, canActivate : [AuthGuard]},
{path : 'profil', component: ProfilComponent, canActivate : [AuthGuard]},
{path : 'user', component : UserComponent, canActivate : [AuthGuard]},
{path : 'home', component : MainComponent, canActivate : [AuthGuard]},
]
},
{path: "**", component : PageNotFoundComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
export const routingComponent = [
UserFormComponent,
IssueFormComponent,
IssueComponent,
MainComponent,
UserComponent,
ProjectFormComponent,
EditProjectComponent,
MyIssuesComponent,
PageNotFoundComponent
];
<file_sep>import { Component, OnInit } from '@angular/core';
import { MyissueService } from '../services/myissue.service';
import { Issue } from '../models/issue';
import { Router } from '@angular/router';
@Component({
selector: 'app-my-issues',
templateUrl: './my-issues.component.html',
styleUrls: ['./my-issues.component.scss']
})
export class MyIssuesComponent implements OnInit {
constructor(private myIssueService: MyissueService, private router: Router) { }
issues;
successMsg = '';
status = ['Pending', 'Implementation', 'QA', 'Closed'];
button: string;
ngOnInit() {
this.myIssueService.getMyIssues()
.subscribe(
(data) => {
this.issues = data;
},
err => {
console.error(err);
}
);
}
nextStep(issueId) {
this.myIssueService.nextStep(issueId)
.subscribe(
data => {
/* this.successMsg = 'Done !';
setTimeout(() => {
this.successMsg = '';
}, 2000); */
this.ngOnInit();
},
err => {
console.error(err);
}
);
}
}
<file_sep>export class Projects {
constructor(
public admin: [],
public member: []
){}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Project } from '../models/project';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ProjectService {
private _uri = 'http://localhost:4000/project';
constructor(private _http: HttpClient) { }
addProjet() {
return this._http.get(this._uri + '/getUsersEmails')
.pipe(catchError(this.errorHandler));
}
errorHandler(error: HttpErrorResponse) {
return throwError(error);
}
add(data) {
return this._http.post(this._uri + '/add', data)
.pipe(catchError(this.errorHandler));
}
getProject(projectId) {
return this._http.get(this._uri + '/getProject/' + projectId)
.pipe(catchError(this.errorHandler));
}
updateProject(request) {
return this._http.put<any>(this._uri + '/update', request)
.pipe(catchError(this.errorHandler));
}
}
<file_sep>// server.js
const express = require('express'),
bodyParser = require('body-parser'),
cors = require('cors'),
mongoose = require('mongoose'),
config = require('./DB');
swaggerJsDoc = require('swagger-jsdoc');
swaggerUi = require('swagger-ui-express');
const issueRoute = require('./routes/issue.route');
const userRoute = require('./routes/user.route');
const loginRoute = require('./routes/login.route');
const projectRoute = require('./routes/project.route');
const mainRoute = require('./routes/home.route');
const profilRoute = require('./routes/profil.route');
mongoose.Promise = global.Promise;
mongoose.connect(config.DB, { useNewUrlParser: true }).then(
() => { console.log('Database is connected') },
err => { console.log('Can not connect to the database' + err) }
);
mongoose.set('useFindAndModify', false);
const app = express();
const port = process.env.PORT || 4000;
const swaggerOptions = {
swaggerDefinition: {
info: {
title: 'Bugs Managment API',
description: "API rest pour le gestion de bugs et d'incidents dans un projet",
servers: ["http://localhost:4000"]
},
},
apis: ['./routes/*.js']
};
const swaggerDocs = swaggerJsDoc(swaggerOptions);
app.use(bodyParser.json());
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs));
app.use(cors());
app.use('/login', loginRoute);
app.use('/issue', issueRoute);
app.use('/user', userRoute);
app.use('/project', projectRoute);
app.use('/home', mainRoute);
app.use('/profil', profilRoute);
app.listen(port, function() {
console.log('Listening on port ' + port);
});<file_sep>// project.route.js
const express = require('express');
//const app = express();
const projectRoutes = express.Router();
const Project = require("../models/Project");
const User = require("../models/User");
const veriftoken = require('./veriftoken')
// Require Issue model in our routes module
/**
* @swagger
* /project/getUsersEmails:
* get:
* tags:
* - Project
* description: Retourne les emails de tous les utilisateurs (susceptible d'appartenir à un projet)
* produces:
* - application/json
* responses:
* 200:
* description: emails des utilisateurs retournés
*/
projectRoutes.route('/getUsersEmails').get(veriftoken.verifyToken, (req, res) => {
let data = {
users: [],
projects: []
}
User.find({}).select("email -_id").then((user) => {
for (element in user) {
data.users.push(user[element].email)
}
Project.find({}).select('title -_id').then((project) => {
for (element in project) {
data.projects.push(project[element].title);
}
res.status(200).json(data)
})
.catch(error => {
console.log('error on projects list')
res.statusMessage = 'error on projects list';
res.status(400).end();
})
})
.catch(error => {
console.log('error on user list')
res.statusMessage = 'error on user list';
res.status(400).end();
})
});
/**
* @swagger
* /project/add:
* post:
* tags:
* - Project
* description: Ajouter un projet
* produces:
* - application/json
* parameters:
* - name: project
* description: projet à ajouter
* in: body
* required: true
* type: object
* responses:
* 200:
* description: Projet ajouté
*/
projectRoutes.route('/add').post(veriftoken.verifyToken, (req, res) => {
let project = {
title: req.body.title,
description: req.body.description,
admin: req.body.admin,
members: []
}
const users = req.body.members;
User.find({ email: users }).select("_id").then(user => {
for (i in user) {
project.members.push((user[i]._id))
}
let projet = new Project(project);
projet.save().then(proj => {
User.find({ _id: proj.members }).then(use => {
for (i in use) {
use[i].projects.push(proj._id);
use[i].save().then().catch(err => {
res.status(500).end
})
}
})
.catch(err => {
res.status(409).end()
})
User.findOne({ _id: project.admin }).then(user => {
user.projectsAdmin.push(proj._id)
user.save().then().catch(err => {
res.status(500).end()
})
})
.catch(err => {
res.status(409).end()
})
res.status(201).json({ "message": "project added !" })
})
.catch(err => {
//console.log(err)
res.statusMessage = "error : project not added"
res.status(400).end()
})
})
.catch(
err => {
res.status(400).send("error with id users")
}
)
})
/**
* @swagger
* /project/getProject/{projectId}:
* get:
* tags:
* - Project
* description: Retourne le projet dont l'id est donné en paramètre
* produces:
* - application/json
* parameters:
* - name: projectId
* description: project id
* in: path
* required: true
* type: string
* responses:
* 200:
* description: Projet retourné
*/
projectRoutes.route('/getProject/:projectId').get(veriftoken.verifyToken, (req, res) => {
const projectId = req.params.projectId;
Project.findOne({ _id: projectId })
.populate('members')
.exec((err, project) => {
if (err) res.status(500).end;
res.status(200).json(project);
});
})
/**
* @swagger
* /project/update:
* put:
* tags:
* - Project
* description: Met à jour un projet
* produces:
* - application/json
* parameters:
* - name: project
* description: projet a mettre à jour
* in: body
* required: true
* type: object
* responses:
* 200:
* description: Projet mis à jour
*/
projectRoutes.route('/update').put(veriftoken.verifyToken, async(req, res) => {
let project = req.body.project;
project.members.length = 0;
for (i in req.body.members) {
mail = req.body.members[i]
use = await User.findOne({ email: mail })
if (use) {
use.projects.push(project._id)
use.save()
}
}
User.find({ email: req.body.members }).select('_id').then(user => {
for (i in user) {
project.members.push((user[i]._id))
}
Project.updateOne({ _id: project._id }, project, async(err) => {
if (err) {
res.statusMessage = 'cannot update project';
res.status(400).end();
}
res.status(200).json({ 'message': 'updated' });
});
})
.catch(err => {
res.statusMessage = 'cannot update project';
res.status(400).end();
})
});
module.exports = projectRoutes;<file_sep>const express = require('express');
const User = require('../models/User');
const Project = require('../models/Project');
const Issue = require('../models/Issue')
const veriftoken = require('./veriftoken');
const mainRoutes = express.Router();
/**
* @swagger
* /home:
* get:
* tags:
* - Home
* description: retourne la liste des project de l'utilisateur courant (projets membre et admin)
* produces:
* - application/json
* responses:
* 200:
* description: success
*/
mainRoutes.route('/').get(veriftoken.verifyToken, (req, res) => {
// Les projets auquels l'utilisateur appartient
//(en tant qu'admin ou bien en tant que membre)
userProjects = {
admin: null,
member: null,
}
User.findOne({ _id: req.userId })
.populate('projects')
.populate('projectsAdmin')
.exec((err, user) => {
if (err) {
res.status(500).end();
}
userProjects.member = user.projects;
userProjects.admin = user.projectsAdmin;
res.json(userProjects)
});
});
/**
* @swagger
* /home/user:
* get:
* tags:
* - Home
* description: retourne la liste des utilisateurs
* produces:
* - application/json
* responses:
* 200:
* description: success
*/
mainRoutes.route('/user').get(veriftoken.verifyToken, (req, res) => {
const id = req.userId;
User.findOne({ _id: id }, (err, user) => {
if (err) res.status(500).end;
res.status(200).json(user);
});
});
/**
* @swagger
* /home/deleteProject/{projectId}:
* delete:
* tags:
* - Home
* description: supprime un projet et toutes les références des issues et utilisateurs à ce projet
* produces:
* - application/json
* parameters:
* - name: projectId
* description: project id
* in: path
* required: true
* type: string
* responses:
* 200:
* description: projet supprimé
*/
mainRoutes.route('/deleteProject/:projectId').delete(veriftoken.verifyToken, (req, res) => {
const projectId = req.params.projectId;
Project.findByIdAndRemove({ _id: projectId }, (err, project) => {
if (err) {
res.statusMessage = "Cannot delete project"
res.status(400).end()
}
Issue.deleteMany({ _id: project.issues }, err => {
if (err) {
res.status(400).json("Cannot delete project")
}
})
User.findOne({ _id: project.admin }, (err, user) => {
if (err) {
res.status(400).json("Cannot delete project")
}
let index = user.projectsAdmin.indexOf(projectId)
if (index !== -1) user.projectsAdmin.splice(index, 1)
user.save(err => {
if (err) {
res.status(400).json("Cannot delete project")
}
})
})
User.find({ _id: project.members }, (err, users) => {
if (err) {
res.status(400).json("Cannot delete project")
}
for (i in users) {
let user = users[i]
let index = user.projects.indexOf(projectId)
if (index !== -1) user.projects.splice(index, 1)
user.save(err => {
if (err) {
res.status(400).json("Cannot delete project")
}
})
}
})
res.status(200).json("Successfully removed")
})
})
// tells if is admin or not
module.exports = mainRoutes;<file_sep>// issue.route.js
const express = require('express');
//const app = express();
const issueRoutes = express.Router();
const veriftoken = require('./veriftoken');
// Require Issue model in our routes module
const Issue = require('../models/Issue');
const Project = require('../models/Project');
const User = require('../models/User');
/**
* @swagger
* /issue/add:
* post:
* tags:
* - Issue
* description: Ajoute une issue
* produces:
* - application/json
* parameters:
* - name: issue
* description: objet json (issue à ajouter)
* in: body
* required: true
* type: object
* responses:
* 201:
* description: Issue ajouté
*/
issueRoutes.route('/add').post(veriftoken.verifyToken, async function(req, res) {
let issue = new Issue(req.body);
let project = await Project.findOne({ _id: issue.project });
project.issues.push(issue._id);
await project.save((err) => {
res.status(500).end;
});
// save the issue
issue.save()
.then(issue => {
res.status(201).json({ 'issue': 'issue in added successfully' });
})
.catch(err => {
res.status(400).send(err);
});
});
/**
* @swagger
* /issue/projectUsers/{projectId}:
* get:
* tags:
* - Issue
* description: Retourne la liste des membres pour un projet donné
* produces:
* - application/json
* parameters:
* - name: projectId
* description: project id
* in: path
* required: true
* type: string
* responses:
* 200:
* description: success
*/
issueRoutes.route('/projectUsers/:projectId').get(veriftoken.verifyToken, async(req, res) => {
const projectId = req.params.projectId;
data = {
members: []
}
function Member(_email, _name, _lname) {
this.email = _email;
this.name = _name,
this.lname = _lname
}
user = await User.findOne({ _id: req.userId })
if (user) {
let m = new Member(user.email, user.name, user.lname);
data.members.push(m);
}
Project.findOne({ _id: projectId })
.populate('members')
.exec((err, project) => {
if (!project) {
console.log("pas de projet")
} else {
if (err) {
res.status(400).json("error with project Users");
}
if (project.members !== []) {
for (i in project.members) {
let m = new Member(project.members[i].email, project.members[i].name, project.members[i].lname);
data.members.push(m);
}
}
res.status(200).json(data);
}
});
});
/**
* @swagger
* /issue/list/{id}:
* get:
* tags:
* - Issue
* description: Retourne les issues d'un projet donné
* produces:
* - application/json
* parameters:
* - name: id
* description: project id
* in: path
* required: true
* type: string
* responses:
* 200:
* description: liste des issues retournée
*/
issueRoutes.route('/list/:id').get(veriftoken.verifyToken, (req, res) => {
const id = req.params.id;
Project.findOne({ _id: id })
.populate('issues')
.exec((err, project) => {
if (err) {
res.status(500).end;
}
const issues = project.issues;
res.status(200).json(issues);
});
});
/**
* @swagger
* /issue/spec/{id}:
* get:
* tags:
* - Issue
* description: Retourne l'issue dont l'id est donné en paramètres
* produces:
* - application/json
* parameters:
* - name: id
* description: Issue id
* in: path
* required: true
* type: string
* responses:
* 200:
* description: Issue returned
*/
issueRoutes.route('/spec/:id').get((req, res) => {
const id = req.params.id;
Issue.findOne({ _id: id }, (err, issue) => {
if (err) {
res.status(401).send('there is a problem')
} else {
res.json(issue);
}
});
});
issueRoutes.route('/edit/:id').get(veriftoken.verifyToken, function(req, res) {
let id = req.params.id;
Issue.findById(id, function(err, issue) {
res.json(issue);
});
});
/**
* @swagger
* /issue/update:
* put:
* tags:
* - Issue
* description: Met à jour une issue (l'id de l'issue a mettre à jour est récuperer directement dans le cors de la requête)
* produces:
* - application/json
* parameters:
* - name: issue
* description: issue à mettre à jour
* in: body
* required: true
* type: object
* responses:
* 201:
* description: Issue mise à jour
*/
issueRoutes.route('/update').put(veriftoken.verifyToken, (req, res) => {
Issue.updateOne({ _id: req.body._id }, req.body, (err) => {
if (err) {
res.status(400).send('not modified !');
}
res.status(201).json({ 'message': 'updated' });
});
});
/**
* @swagger
* /issue/delete/{id}:
* delete:
* tags:
* - Issue
* description: Supprime l'issue avec l'id donné en paramètres
* produces:
* - application/json
* parameters:
* - name: id
* description: Issue id
* in: path
* required: true
* type: string
* responses:
* 200:
* description: Issue supprimée
*/
issueRoutes.route('/delete/:id').delete(veriftoken.verifyToken, function(req, res) {
Issue.findByIdAndRemove({ _id: req.params.id }, function(err, issue) {
if (err) res.json(err);
else res.status(200).json('Successfully removed');
});
});
/**
* @swagger
* /issue/takeIssue/{issueId}:
* get:
* tags:
* - Issue
* description: Prendre la main par l'utilisateur courant sur l'issue dont l'id est donné en paramètres
* produces:
* - application/json
* parameters:
* - name: issueId
* description: Issue id
* in: path
* required: true
* type: string
* responses:
* 200:
* description: Issue en main
*/
issueRoutes.route('/takeIssue/:issueId').get(veriftoken.verifyToken, (req, res) => {
const issueId = req.params.issueId;
const userId = req.userId;
User.findOne({ _id: userId }).then(async user => {
const issue = await Issue.findOne({ _id: issueId });
issue.assignedTo = user.email;
issue.save();
res.status(200).end();
})
.catch(err => {
res.status(400).send("Unable to take the issue")
})
})
/**
* @swagger
* /issue/getIssues:
* get:
* tags:
* - Issue
* description: Retourne les liste des issues dont l'utilisateur courant a la main
* produces:
* - application/json
* responses:
* 200:
* description: Issues retournées
*/
issueRoutes.route('/getIssues').get(veriftoken.verifyToken, async(req, res) => {
user = await User.findOne({ _id: req.userId })
if (!user) {
res.status(400).json("cannot get current user issues")
} else {
Issue.find({ assignedTo: user.email })
.populate('project')
.exec((err, issues) => {
if (err) {
res.status(400).json("cannot get current user issues")
} else {
res.status(200).json(issues)
}
})
}
})
/**
* @swagger
* /issue/isAdmin/{projectId}:
* get:
* tags:
* - Issue
* description: Retourne vrai si l'utilisateur courant est l'admin du projet dont l'id est donné en paramètres, retourne faux sinon
* produces:
* - application/json
* parameters:
* - name: projectId
* description: project id
* in: path
* required: true
* type: string
* responses:
* 200:
* description: Get user by id
*/
issueRoutes.route('/isAdmin/:projectId').get(veriftoken.verifyToken, (req, res) => {
userId = req.userId
projectId = req.params.projectId
Project.findOne({ _id: projectId, admin: userId }, (err, project) => {
if (err) {
res.status(400).json("cannot define if user is admin")
} else {
if (!project) {
res.status(200).json(false)
} else {
res.status(200).json(true)
}
}
})
})
/**
* @swagger
* /issue/next/{issueId}:
* get:
* tags:
* - Issue
* description: Met à jour le status d'une issue dont l'id est donné en paramètres
* produces:
* - application/json
* parameters:
* - name: id
* description: User id
* in: path
* required: true
* type: string
* responses:
* 200:
* description: Status mis à jour
*/
issueRoutes.route('/next/:issueId').get(veriftoken.verifyToken, async(req, res) => {
issueId = req.params.issueId;
status = ['Pending', 'Implementation', 'QA', 'Closed'];
issue = await Issue.findOne({ _id: issueId });
if (!issue) {
res.status(400).json("there is an error")
} else {
index = status.indexOf(issue.status)
index = (index + 1) % 4
issue.status = status[index];
issue.save()
res.status(200).json("status updated")
}
})
module.exports = issueRoutes;<file_sep>import { Component, OnInit } from '@angular/core';
import { User } from '../models/user';
import { UserService } from '../services/user.service';
import { Router } from '@angular/router';
import { HttpErrorResponse } from '@angular/common/http';
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.scss']
})
export class UserComponent implements OnInit {
users: User[];
// tslint:disable-next-line: variable-name
constructor(private _UserService: UserService, private _router: Router) { }
ngOnInit() {
this._UserService.getUser().
subscribe(
(data: User[]) => {
this.users = data;
},
err => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
console.log(err);
this._router.navigate(['/']);
}
}
}
);
}
/* onActive(value) {
console.log(value);
this._UserService.setActivation(value).
subscribe(
data => {
console.log('success', data);
// this._router.navigate(['/']);
},
error => console.error(error)
);
} */
}
<file_sep># Bug managment
### Installation
- Clonez le projet.
- Installation et lancement du front (l'interface):
```bash
cd client
npm install
ng serve
```
- Installation et lancement de l'api:
```bash
cd api
npm install
npm start
```
Documentation avec Swagger:
```bash
http://localhost:4000/api-docs/
```
## développé avec
- Nodejs
- Express.js
- Mongoose
- Mongodb
- Postman
- Swagger
- Angular
## Auteurs
- **<NAME>**
- **<NAME>**
<file_sep>const express = require('express');
const bcrypt = require("bcrypt");
const User = require('../models/User');
const jwt = require('jsonwebtoken');
const loginRoutes = express.Router();
/**
* @swagger
* /login:
* post:
* tags:
* - Login
* description: Authentification d'un utilisateur. Retourne un token si l'utilisateur s'est authentifié
* produces:
* - application/json
* parameters:
* - name: login
* description: User id
* in: body
* required: true
* type: object
* responses:
* 200:
* description: Utilisateur authentifié
*/
loginRoutes.route('/').post(async(req, res) => {
console.log(req)
User.findOne({ uname: req.body.uname }).then(async user => {
if (user == null) {
res.statusMessage = "User name or password not correct";
return res.status(409).end();
}
//console.log(user);
try {
if (await bcrypt.compare(req.body.password, user.password)) {
let payload = { subject: user.id };
let token = jwt.sign(payload, '<KEY>');
res.status(200).send({ token });
} else {
res.statusMessage = 'User name or password not correct';
res.status(409).end();
}
} catch {
res.status(500).send()
}
}, err => console.log(err));
});
module.exports = loginRoutes;<file_sep>const mongoose = require('mongoose');
const Project = require('./Project');
const Schema = mongoose.Schema;
// Define collection and schema for Issues
let Issue = new Schema({
description: {
type: String,
required: true
},
priority: {
type: String,
enum: ["low", "high", "medium"]
},
assignedTo: {
type: String
},
category: {
type: String,
enum: ["Bug", "Incident"]
},
status: {
type: String,
enum: ["Pending", "QA", "Implementation", "Closed"]
},
project: {
type: mongoose.Schema.Types.ObjectId,
ref: "Project"
}
});
module.exports = mongoose.model('Issue', Issue);<file_sep>import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Issue } from '../models/issue';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class IssueService {
private _uri = 'http://localhost:4000/issue';
constructor(private _http: HttpClient) { }
addIssue(issue: Issue) {
return this._http.post<any>(this._uri + '/add', issue)
.pipe(catchError(this.errorHandler));
}
errorHandler(error: HttpErrorResponse) {
return throwError(error);
}
getIssue(projectId) {
return this._http.get(this._uri + '/list/' + projectId)
.pipe(catchError(this.errorHandler));
}
getSpecificIssue(id) {
return this._http.get(this._uri + '/spec/' + id)
.pipe(catchError(this.errorHandler));
}
updateIssue(issue: Issue) {
return this._http.put<any>(this._uri + '/update', issue)
.pipe(catchError(this.errorHandler));
}
getProjectUsers(projectId) {
return this._http.get(this._uri + '/projectUsers/' + projectId)
.pipe(catchError(this.errorHandler));
}
takeIssue(issueId) {
return this._http.get(this._uri + '/takeIssue/' + issueId)
.pipe(catchError(this.errorHandler));
}
isAdmin(projectId) {
return this._http.get(this._uri + '/isAdmin/' + projectId)
.pipe(catchError(this.errorHandler));
}
deleteIssue(id) {
return this._http.delete(`${this._uri}/delete/${id}`);
}
}
<file_sep>export class Project {
constructor(
public _id: string,
public title: string,
public description: string,
public admin: string,
public members: string[],
public issues: string[]
) {}
}
<file_sep>let mongoose = require("mongoose");
// const User = require("./User");
// const Issue = require("./Issue");
let projectSchema = mongoose.Schema({
title: {
type: String
},
description: {
type: String
},
admin: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
members: [{
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}],
issues: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Issue"
}]
});
let Project = module.exports = mongoose.model('Project', projectSchema); | bd0626a1eb90214275bf8ab6a08eb3cfb208a6f6 | [
"JavaScript",
"TypeScript",
"Markdown"
] | 35 | TypeScript | Madjid-Djennane/bug-management | 290dc3c05115885162e9a990dddf537770bbc0a6 | 54bde88dad399ffd44d1c13ddf87d8563bbe88c6 |
refs/heads/main | <repo_name>Marc-cruz/F-tbolClub<file_sep>/FutbolClub/FutboClub.web/Controllers/EntradasController.cs
using FutboClub.web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace FutboClub.web.Controllers
{
public class EntradasController : Controller
{
// GET: Entradas
public ActionResult Index()
{
var entrada1 = new EntradasModel();
entrada1.Id = 1;
entrada1.Descripcion = "VIP";
var entrada2 = new EntradasModel();
entrada2.Id = 2;
entrada2.Descripcion = "Palco";
var entrada3 = new EntradasModel();
entrada3.Id = 3;
entrada3.Descripcion = "Silla";
var entrada4 = new EntradasModel();
entrada4.Id = 4;
entrada4.Descripcion = "Sol";
var listadeentradas = new List<EntradasModel>();
listadeentradas.Add(entrada1);
listadeentradas.Add(entrada2);
listadeentradas.Add(entrada3);
listadeentradas.Add(entrada4);
return View(listadeentradas);
}
}
}<file_sep>/FutbolClub/FutboClub.web/Controllers/TiendaController.cs
using FutboClub.web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace FutboClub.web.Controllers
{
public class TiendaController : Controller
{
// GET: Tienda
public ActionResult Index()
{
var tienda1 = new TiendaModel();
tienda1.Id = 1;
tienda1.Descripcion = "Hombre";
var tienda2 = new TiendaModel();
tienda2.Id = 2;
tienda2.Descripcion = "Mujer";
var tienda3 = new TiendaModel();
tienda3.Id = 3;
tienda3.Descripcion = "Niño";
var tienda4 = new TiendaModel();
tienda4.Id = 4;
tienda4.Descripcion = "Niña";
var listadetienda = new List<TiendaModel>();
listadetienda.Add(tienda1);
listadetienda.Add(tienda2);
listadetienda.Add(tienda3);
listadetienda.Add(tienda4);
return View(listadetienda);
}
}
} | 288f6374729a9995d5c22e773cf1251b0cf54842 | [
"C#"
] | 2 | C# | Marc-cruz/F-tbolClub | 100338faec06e717c84c92d4a212ecd3cd79f1c3 | 1e45734654bdd77e3532bfae1fa560ef8f7b9423 |
refs/heads/master | <repo_name>JasonUiterwijk/PyramidPanic<file_sep>/PyramidPanic/PyramidPanic/GameScenes/StartScene/StartScene.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PyramidPanic.GameScenes.StartScene
{
class StartScene
{
}
}
| 44471e5c4ba8533945881f6d0fb2669e0d95214e | [
"C#"
] | 1 | C# | JasonUiterwijk/PyramidPanic | 010171a5e55044c94ac53f703449683c2bc02f19 | 75483852355187972462dc6b772da3aba31e855b |
refs/heads/main | <repo_name>ThodorisMaximilianosChytis/diseaseAggregator<file_sep>/diseaseAggregatorClasses.cpp
#include <iostream>
// #include <fstream>
// #include <sstream>
#include <cstring>
#include "diseaseAggregatorClasses.h"
using namespace std;
Child::Child(int _pid):pid(_pid){
CreateRPath(_pid);
CreateWPath(_pid);
SIG_INT_Q=0;
numdir=0;
directories=NULL;
}
Child::~Child(){ //directories for each child
if (directories!=NULL){
for (int j=0; j < this->numdir; j++){
delete[] directories[j];
}
delete[] directories;
}
}
//Create paths to fifo
void Child::CreateRPath(int _pid){
strcpy(this->pathr,"./NamedPipes/fifo1.");
char spid[20];
sprintf(spid, "%d",_pid);
strcat(this->pathr,spid);
//cout << pathr << endl;
}
void Child::CreateWPath(int _pid){
strcpy(this->pathw,"./NamedPipes/fifo2.");
char spid[20];
sprintf(spid, "%d",_pid);
strcat(this->pathw,spid);
}
//Assign the correct directories to the children
void Child::AssignDirectories(int _nworkdir,char** _directories,int & _dirleft,int & j){
this->numdir= _nworkdir;
if (_dirleft>0){ //if mod still left incremet numbe rof dirs the child is responsible for
this->numdir++;
_dirleft--;
}
directories = new char*[numdir];
for(int k=0; k < numdir ; k++){
directories[k] = new char[50];
strcpy(this->directories[k],_directories[j]);
j++; //this value comes from outside and to support the directories table
}
}
int Child::Find(char *country){
for(int k=0; k<numdir ; k++){
if (strcmp(country,directories[k])==0){
return k;
}
}
return -1;
}<file_sep>/diseaseAggregatorfuncts.cpp
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <sstream>
#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<signal.h>
#include "diseaseAggregatorfuncts.h"
using namespace std;
//signal handler
void sig_handler_parent(int signo)
{
if (signo == SIGINT || signo == SIGQUIT){
aflag_int_q=1;
write(0,"SIGINT OR SIGQUIT press enter\0",50);
}
if(signo == SIGCHLD){
int status;
write(1,"caught termindated kid\0 ",50);
//change global variable tp dead pid
sigchld_pid = waitpid(-1, &status, WNOHANG); //rtreice passes away kiddo id
cout << sigchld_pid << endl;
}
}
void Read(char * fifopath,int &rfd,int bufferSize,string* message){
char buff[bufferSize];
int n;
//message ends at #
message->assign("");
do{
if ( (n=read(rfd,buff,bufferSize))<0){
cout << "problem" << endl;
exit(1);
}
buff[n]='\0';
message->append(buff);
}while(message->back()!='#');
}
void Write(char * fifopath,int &wfd,int bufferSize,string* message){
char buff[bufferSize];
int n;
//wite #biffersize bytes at a time unti message is sent
if (message->back()!='#')
message->append("#");
int length = message->length();
for(int j=0;1;j++){
strcpy(buff,message->substr(j*bufferSize,bufferSize).c_str());
n=strlen(buff);
if(write(wfd,buff,n) !=n){
//exit(1);
cout << "problem" << endl;
}
length-=bufferSize;
if (length<=0){
break;
}
}
}
//user interface
void UserQueries(Child** CHT,int bufferSize,int numwork,char * argv[],int & SUCCESS,int & FAIL){
string Request,disease,country,date1,date2,record_id;
int error,k,w_s_q;
while(1){
error=0;
//this is a flag for a terminated child. I dont use the global one to catch multiple terminated kids
w_s_q=-1; // /Start the user interface
cout << "____________________________________________________________________________________________________" << endl;
cout << "|Please Choose Between Applications: " << endl;
cout << "----------------------------------------------------------------------------------------------------" << endl;
cout << "|1) /diseaseFrequency virusName date1 date2 [country] " << endl;
cout << "|2) /topk-AgeRanges k country disease date1 date2 " << endl;
cout << "|3) /searchPatientRecord recordID " << endl;
cout << "|4) /numPatientAdmissions disease date1 date2 [country] " << endl;
cout << "|5) /numPatientDischarges disease date1 date2 [country] " << endl;
cout << "|6) /listCountries " << endl;
cout << "|7) /exit " << endl;
cout << "| Note: Dates entered must follow the format dd-mm-yyyy and date1 must be earlier than date2 " << endl;
cout << "____________________________________________________________________________________________________" << endl;
getline(cin,Request); //get choice from user
cout << "You chose: " << Request << endl;
stringstream wordcount(Request);
stringstream srequest(Request);
int count = 0;
string temp;
while(wordcount>>temp) //count number of words given
count++;
string app;
srequest>>app; //get app name
//cout << count << endl;
////Use the num of words given to choose how to call each function (optional arguments)
if (app=="/listCountries"){
if (count!=1){
cout << "Wrong input, try again" << endl;
error=1;
}else
listCountries(CHT,numwork,bufferSize,w_s_q);
}else if(app=="/diseaseFrequency"){
srequest >> disease;
srequest >> date1;
srequest >> date2;
if (count==5){
srequest >> country;
}else if (count==4){
country.assign("");
}else{
cout << "Wrong input, try again" << endl;
error=1;
}
if (error!=1 && DateCompareEarlier(&date2,&date1)==1){
cout << "Error: exit date given earlier than entry date" << endl;
error=1;
}
if(error!=1)
diseaseFrequency(CHT,app,disease,country,date1,date2,bufferSize,numwork,w_s_q);
}else if(app=="/topk-AgeRanges"){
if (count!=6){
cout << "Wrong input, try again" << endl;
error=1;
}
srequest >> k;
if(k>4) k=4;
if (k<1) k=1;
srequest >>country;
srequest >> disease;
srequest >>date1;
srequest >> date2;
if (error!=1 && DateCompareEarlier(&date2,&date1)==1 ){
cout << "Error: exit date given earlier than entry date" << endl;
error=1;
}
if(error!=1)
TopKAgeRanges(CHT,k,disease, country, date1, date2, bufferSize, numwork,w_s_q);
}else if(app=="/searchPatientRecord"){
if(count!=2){
cout << "Wrong input,try again" << endl;
error=1;
}
srequest >> record_id;
if(error!=1)
searchPatientRecord(CHT,record_id,bufferSize,numwork,w_s_q);
}else if(app=="/numPatientAdmissions"){
srequest >> disease;
srequest >> date1;
srequest >> date2;
if (count==5){
srequest >> country;
}else if (count==4){
country.assign("");
}else{
cout << "Wrong input, try again" << endl;
error=1;
}
if (error!=1 && DateCompareEarlier(&date2,&date1)==1){
cout << "Error: exit date given earlier than entry date" << endl;
error=1;
}
if(error!=1)
diseaseFrequency(CHT,app,disease,country,date1,date2,bufferSize,numwork,w_s_q);
}else if(app=="/numPatientDischarges"){
srequest >> disease;
srequest >> date1;
srequest >> date2;
if (DateCompareEarlier(&date2,&date1)==1){
cout << "Error: exit date given earlier than entry date" << endl;
error=1;
}
if (count==5){
srequest >> country;
}else if (count==4){
country.assign("");
}else{
cout << "Wrong input, try again" << endl;
error=1;
}
if(error!=1)
diseaseFrequency(CHT,app,disease,country,date1,date2,bufferSize,numwork,w_s_q);
}else if (app=="/exit"){
exit(CHT,bufferSize,numwork,w_s_q);
break; //exit loop and user interface
}else{
error=1;
}
if(error==1){
SendError(CHT,bufferSize,numwork,w_s_q);
FAIL++;
}else{
SUCCESS++;
}
//here has been a signal //if siganl received during command line reading it is terminated after the completion of query
if(w_s_q>-1){
ReforkChild(CHT, numwork, bufferSize,argv);
}
//Parent has received a sig int or q signal.this signal is receivied during completing a query so complete it to move on
if(aflag_int_q==1){
break;
}
}
}
void SendError(Child** T, int bufferSize, int numwork,int& w_s_q){
string * message = new string("ERROR@");
string Query=*message;
cout << "ERROR" << endl;
for(int i=0; i<numwork; i++){
Write(T[i]->pathw,T[i]->wfd,bufferSize,&Query);
}
for(int i=0; i<numwork; i++){
Read(T[i]->pathr,T[i]->rfd,bufferSize,message);
int length=message->length();
// cout << *message << endl;
//sig int or q from worker code $
if (length>=2 && message->substr(length-2,length)=="$#"){
w_s_q=T[i]->pid;
T[i]->SIG_INT_Q=1;
}
}
delete message;
}
void exit(Child** T,int bufferSize,int numwork,int& w_s_q){
string message;
message.assign("/exit@");
string Query=message;
for(int i=0; i<numwork; i++){
Write(T[i]->pathw,T[i]->wfd,bufferSize,&Query);
}
for(int i=0; i<numwork; i++){
Read(T[i]->pathr,T[i]->rfd,bufferSize,&message);
int length=message.length();
//sig int or q from worker code $
if (length>=2 && message.substr(length-2,length)=="$#"){
w_s_q=T[i]->pid;
T[i]->SIG_INT_Q=1;
}
}
}
void listCountries(Child** T,int numwork,int bufferSize,int& w_s_q){
string message;
message.assign("/listCountries@");
string Query=message;
int length;
for(int i=0;i<numwork;i++){
Write(T[i]->pathw,T[i]->wfd,bufferSize,&Query);
}
for(int i=0;i<numwork;i++){
Read(T[i]->pathr,T[i]->rfd,bufferSize,&message);
length=message.length();
//sig int or q from worker code $
if (length>=2 && message.substr(length-2,length)=="$#"){
T[i]->SIG_INT_Q=1;
w_s_q=T[i]->pid;
}
//print countries and pids
for (int j=0;j < T[i]->numdir;j++){
cout << T[i]->directories[j] << " " << T[i]->pid <<endl;
}
}
}
void searchPatientRecord(Child ** T,string record_id,int bufferSize,int numwork,int& w_s_q){
string* message = new string("/searchPatientRecord");
message->append("@");
message->append(record_id);
message->append("@");
string Query = *message;
for(int i=0; i<numwork; i++){
Write(T[i]->pathw,T[i]->wfd,bufferSize,&Query);
}
for(int i=0; i<numwork; i++){
Read(T[i]->pathr,T[i]->rfd,bufferSize,message);
//cout << *message << endl;
if(*message=="Found#"){
cout << "job done" << endl;
}
int length=message->length();
if (length>=2 && message->substr(length-2,length)=="$#"){
T[i]->SIG_INT_Q=1;
w_s_q=T[i]->pid;
}
}
if(*message!="Found#" || *message!="Found$#"){
cout << "no record with id: " << record_id << endl;
}
//cout << *wholemess << endl;
delete message;
//delete wholemess;
}
void diseaseFrequency(Child ** Table,string app,string virusName,string country,string date1,string date2,int bufferSize,int numwork,int& w_s_q){
int process=-1;
int freq=0;
string* message = new string(app);
string* wholemess = new string();
message->append("@");
message->append(virusName);
message->append("@");
message->append(date1);
message->append("@");
message->append(date2);
message->append("@");
//with country
if (country!=""){
// int dir=-1;
for (int i=0; i<numwork; i++){
if(Table[i]->Find((char *) country.c_str())>-1){
process = i;
break;
}
}
if (process!=-1){
int optimize=1;
message->append(country);
message->append("@");
Write(Table[process]->pathw,Table[process]->wfd,bufferSize,message);
Read(Table[process]->pathr,Table[process]->rfd,bufferSize,message);
int length=message->length();
if (length>=2 && message->substr(length-2,length)=="$#"){
Table[process]->SIG_INT_Q=1;
w_s_q=Table[process]->pid;
optimize=2;
}
if (app=="/diseaseFrequency"){
freq+=stoi(message->substr(0,message->length()-optimize));
}
else{
wholemess->append(message->substr(0,message->length()-optimize));
}
}else
cout << "country not found" << endl;
}else{
//no country given go through all of them
string Query = *message;
for(int i=0; i<numwork; i++){
Write(Table[i]->pathw,Table[i]->wfd,bufferSize,&Query);
}
for(int i=0; i<numwork; i++){
int optimize=1;
Read(Table[i]->pathr,Table[i]->rfd,bufferSize,message);
int length=message->length();
if (length>=2 && message->substr(length-2,length)=="$#"){
Table[i]->SIG_INT_Q=1;
w_s_q=Table[i]->pid;
optimize=2;
}
//count freq
if (app=="/diseaseFrequency"){
freq+=stoi(message->substr(0,message->length()-optimize));
}
///list for numPatient Queries
else
wholemess->append(message->substr(0,message->length()-optimize));
}
}
if (app=="/diseaseFrequency")
cout << "freq is " <<freq << endl;
else
cout << *wholemess << endl;
//cout << "Frequencies are :" << endl;
//HT->PrintdiseaseFrequency(&virusName,&country,&date1,&date2);
delete message;
delete wholemess;
return;
}
void TopKAgeRanges(Child ** Table,int k,string disease,string country,string date1,string date2,int bufferSize,int numwork,int& w_s_q){
int process=-1;
int freq=0;
char numk[2];
string* message = new string("/topk-AgeRanges");
// string* wholemess = new string();
message->append("@");
sprintf(numk,"%d",k);
message->append(numk);
message->append("@");
message->append(country);
message->append("@");
message->append(disease);
message->append("@");
message->append(date1);
message->append("@");
message->append(date2);
message->append("@");
for (int i=0; i<numwork; i++){
if(Table[i]->Find((char *) country.c_str())>-1){
process = i;
break;
}
}
if (process!=-1){
Write(Table[process]->pathw,Table[process]->wfd,bufferSize,message);
Read(Table[process]->pathr,Table[process]->rfd,bufferSize,message);
int length=message->length();
if (length>=2 && message->substr(length-2,length)=="$#"){
Table[process]->SIG_INT_Q=1;
w_s_q=Table[process]->pid;
}
cout << *message << endl;
}else
cout << "country not found" << endl;
delete message;
}
//create log file
void ACreateLogfile(int SUCCESS,int FAIL,string * &text){
char pid[50];
char logfile[100];
int logfilefd;
strcpy(logfile,"./logfiles/Aggregatorlogfile.");
sprintf(pid,"%d",getpid());
strcat(logfile,pid);
// cout << logfile << endl;
if((logfilefd=open(logfile,O_WRONLY | O_CREAT | O_APPEND,0666))<0){
cout << "ERROR opening logfile" << endl;
exit(1);
}
text->append("TOTAL ");
text->append(to_string(SUCCESS+FAIL));
text->append("\n");
text->append("SUCCESS ");
text->append(to_string(SUCCESS));
text->append("\n");
text->append("FAIL ");
text->append(to_string(FAIL));
text->append("\n");
int n=text->length();
if(write(logfilefd,text->c_str(),n) !=n){
exit(1);
cout << "problem" << endl;
}
}
void ReforkChild(Child** CHT, int numwork,int bufferSize,char** argv){
cout << "a little patience" << endl;
int pid;
int status;
for(int i=0;i<numwork;i++){
if(CHT[i]->SIG_INT_Q==1){
if(waitpid(CHT[i]->pid,&status,0)<0){
cout << "waitpid problem" << endl;
}
// cout<<"nai edw ftanw ola komple" << endl;
//wait for the children that received and int q signal to terminate the refork
if( (pid = fork()) == -1){
exit(1);
}
if(pid!=0){
Child * nC=new Child(pid);
if(mkfifo(nC->pathr,0666) < 0){
exit(1);
}
if(mkfifo(nC->pathw,0666) < 0){
exit(1);
}
nC->numdir=CHT[i]->numdir;
nC->directories=CHT[i]->directories;
CHT[i]->directories=NULL; //trick so that the directories are not erased but juts moved
if( (nC->wfd = open(nC->pathw,O_WRONLY)) < 0 ){
cout << "problem parent wfile" << endl;
exit(1);
}
if( (nC->rfd = open(nC->pathr,O_RDONLY)) < 0 ){
cout << "problem parent rfile" << endl;
exit(1);
}
//send drectories
char buff[bufferSize];
int n;
string send;
send.assign("");
for(int j=0; j<nC->numdir; j++){
send.append(nC->directories[j]);
send.append("@");
}
Write(nC->pathw,nC->wfd,bufferSize,&send);
delete CHT[i];
CHT[i]=nC;
}else{
sleep(1); //have some patience to refork and open fifos
strcpy(argv[0],"$"); //sign for worker to understand that he is reforked
// cout << argv[0] << endl;
// cout << getpid() << endl;
if(execv("./diseaseAggregatorWorker",argv)==-1){
cout << "Error exec the worker executable" << endl;
}
}
}
}
}<file_sep>/create_infiles.sh
#!/bin/bash
CreateRandomDate() {
local day=$((RANDOM%30+1))
local month=$((RANDOM%12+1))
local year=$((RANDOM%1020+1000))
if (( $month==2 && $day>28 )); then #february problem
if (( $year%4==0 )); then
day=29
else
day=28
fi
fi
rdate=$(date -d "$year-$month-$day" '+%d-%m-%Y') #generate random date and transform into correct format
echo "$rdate"
}
CreateRandomRecords(){
local EnterOrExit
# local first_name="$(cat /dev/urandom | tr -dc 'A-Z' | head -c $((RANDOM%10+3)) )"
# local last_name="$(cat /dev/urandom | tr -dc 'A-Z' | head -c $((RANDOM%10+3)) )"
local first_name=${first_names[$((RANDOM%${#first_names[@]}))]}
local last_name=${last_names[ $((RANDOM%${#first_names[@]})) ]}
local Age="$((RANDOM%121+1))"
local disease="$(echo -n "$(shuf -n 1 $3)")"
local p=2
local flag=-1
for ((j=1; j<=$2; j++)); do
if ((flag==1)); then
p=6
fi
if (( $((RANDOM%10)) < $p )); then #write ENTER OR EXIT changing propabilities
EnterOrExit="EXIT"
flag=0
else
EnterOrExit="ENTER"
flag=1
fi
records+=("$1 $EnterOrExit $first_name $last_name $disease $Age")
done
# for l in "${records[@]}";
# do
# echo "$l"
# done
# echo -n "$1 " >> $recordfilepath #write id
}
scriptName=$0
# echo $scriptName
diseasesFile=$1
countriesFile=$2
input_dir=$3
numFilesPerDirectory=$4
numRecordsPerFile=$5
if ! [[ $numFilesPerDirectory =~ ^[0-9]+$ ]]; then
echo "wrong number input for numFilesPerDirectory"
exit 1
fi
if ! [[ $numRecordsPerFile =~ ^[0-9]+$ ]]; then
echo "wrong number input for numRecordsPerFile"
exit 1
fi
if [ ! -f ./$diseasesFile ]; then
echo "$diseasesFile not found"
exit 1
fi
if [ ! -f ./$countriesFile ]; then
echo "$countriesFile not found"
exit 1
fi
#create input_dir
mkdir -p ./$input_dir
#read from countriesFile
recordid=0
declare -a first_names
declare -a last_names
first_names+=(<NAME>)
last_names+=(<NAME>)
while read p; do
declare -a indeces #set arrays
declare -a records
#create a folder fow each country
mkdir -p ./$input_dir/$p
rm -f ./$input_dir/$p/* #overwrite
for ((c=1; c<=$numFilesPerDirectory; c++)); do
while : ; do
rdate=$(CreateRandomDate)
if [ ! -f ./$input_dir/$p/$rdate ]; then
break
fi
done
touch ./$input_dir/$p/$rdate # create a file with random name
odd=2
for ((i=1; i<=numRecordsPerFile/2; i++)); do
let recordid+=1
CreateRandomRecords $recordid $odd "./$diseasesFile"
done
if ((numRecordsPerFile%2==1)) ; then
let recordid+=1
odd=1
CreateRandomRecords $recordid $odd "./$diseasesFile"
fi
done
# for l in "${!records[@]}";
# do
# echo $l
# # echo "${records[$l]}"
# done
indeces=( $(shuf -e "${!records[@]}") ) #create shuffled array of the recrod array indeces
index=0
for datefile in ./$input_dir/$p/* ; do
# echo $datefile
for ((i=1; i<=numRecordsPerFile; i++)); do
# echo $index
# echo ${records[indeces[index]]} # echo ${records[index]}
echo ${records[indeces[index]]} >> $datefile #insert random record from same directory in the file
index=$((index+1))
done
done
unset records #delete arrays
unset indeces
done<$countriesFile
echo "File creation complete"
<file_sep>/diseaseAggregatorWorker.cpp
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "diseaseAggregatorWorkerfuncts.h"
// global flag to handle the sig int and sig quit signal
volatile sig_atomic_t wflag_int_q=0;
// int wflag_int_q=0;
volatile sig_atomic_t flag_usr1=0;
int main(int argc,char ** argv){
//set up sigaction struct and link handlers
struct sigaction action;
action.sa_handler=sig_handler_worker;
action.sa_flags = SA_RESTART;
sigemptyset (&action.sa_mask);
sigaction(SIGINT,&action,NULL);
sigaction(SIGQUIT,&action,NULL);
sigaction(SIGUSR1,&action,NULL);
//nBflah shows if the worker is reforked or not
int nBflag=0;
// cout << "getpid is " << getpid() << endl;
//$ as argv means reforked
if(strcmp(argv[0],"$")==0){
nBflag=1;
}
char input_dir[100];
int numWorkers;
int bufferSize;
if (argc!=7){
cout << "Input error" << endl;
exit(1);
}else{
// for(int i=0;i<7;i++){
// cout << argv[i] << endl;
// }
for(int i=1;i<=5;i+=2){
if(strcmp(argv[i],"-i")==0){
strcpy(input_dir,argv[i+1]);
}else if(strcmp(argv[i],"-b")==0){
bufferSize = atoi(argv[i+1]);
}else if(strcmp(argv[i],"-w")==0){
numWorkers = atoi(argv[i+1]);
}else {
cout << "Input error" << endl;
}
}
if(bufferSize<1) exit(1);
if(numWorkers<1) exit(1);
// cout << "number of workers is: " << numWorkers << endl;
// cout << "bufferSize is: " <<bufferSize << endl;
// cout << "input_dir is: " << input_dir << endl;
}
cout << "child process, pid is : " << getpid() << endl;
cout << "parent is : " << getppid() << endl;
//create fifofile paths
char temp[100];
char path1[50];
char path2[50];
int readfd;
int writefd;
strcpy(path1,"./NamedPipes/fifo1.");
strcpy(path2,"./NamedPipes/fifo2.");
sprintf(temp, "%d", getpid());
// cout << temp << endl;
strcat(path1 ,temp);
strcat(path2 ,temp);
// cout << path1 << endl;
// cout << path2 << endl;
// // cout << "fifo files open" << endl;
if( (readfd = open(path2,O_RDONLY)) < 0 ){
cout << "problem worker rfile" << endl;
exit(1);
}
if( (writefd = open(path1,O_WRONLY)) < 0 ){
cout << "problem worker wfile" << endl;
exit(1);
}
//read the directories worker is responsible for
string* message = new string();
Read(path2,readfd,bufferSize,message);
// cout << *message << endl;
//decode message from aggregator @ means end of word # means end of message
int pos=0;
SSList * dirs = new SSList();
for(int j=0;j<message->length();j++){
if (message->at(j)=='@'){
dirs->Insert(message->substr(pos,j-pos));
pos = j+1;
}
}
// dirs->Print();
//Create and fill data structures for each worker
LList * Records = new LList();
Hashtable * ChildHT = new Hashtable(3,4);
SSLNode* tempN=dirs->SSLHead;
while (tempN!=NULL){
DIR *dp;
struct dirent * e;
//List of date file names
SSList* files = new SSList();
int filecount = 0;
strcpy(temp,input_dir);
strcat(temp,"/");
strcat(temp,tempN->data->c_str());
dp = opendir(temp);
if (dp==NULL){
cout << "problem" << endl;
exit(1);
}
while ( (e=readdir(dp)) != NULL){
if (e->d_type == DT_REG){
filecount++;
files->Insert(e->d_name);
}
}
rewinddir(dp);
closedir(dp);
//files->Print();
//cout << "--------------" << endl;
//Sort datefiles to be in correct chronological order for insertion
files->Sort(1);
//files->Print();
InsertChildFileRecords(Records, ChildHT, tempN, files,temp);
//Message of summary statistics for each file of the same directory
message->assign(*tempN->data);
message->append("\n");
SSLNode* idate=files->SSLHead;
while(idate!=NULL){
message->append(*idate->data);
message->append("\n");
//cout << "ola kala" << endl;
ChildHT->SummaryStatistics(idate->data,message);
idate = idate->Next;
}
//summary statistics ready send only if worker origianl and not reborn
if(nBflag!=1){
Write(path1,writefd,bufferSize,message);
}
delete files;
tempN= tempN->Next;
}
//start interface to parent
int SUCCESS=0;
int FAIL=0;
if (wflag_int_q==0){
QueriesAnswer(Records,ChildHT,dirs,path1,path2,writefd,readfd,bufferSize,SUCCESS,FAIL,input_dir);
}
//if child terminated violentrly create logfile
if (wflag_int_q==1){
CreateLogfile(dirs,SUCCESS,FAIL);
}
// Records->Print();
delete dirs;
delete message;
delete Records;
delete ChildHT;
//close and delete fifo files
close(readfd);
close(writefd);
if(unlink(path1) < 0){
cout << "problem" << endl;
exit(1);
}
if(unlink(path2) < 0){
cout << "problem" << endl;
exit(1);
}
}<file_sep>/diseaseAggregatorClasses.h
#include <iostream>
using namespace std;
class Child{
public:
int pid;
char pathr[100];
char pathw[100];
int rfd;
int wfd;
char** directories;
int numdir;
int SIG_INT_Q;
~Child(void);
Child(int);
void CreateRPath(int);
void CreateWPath(int);
void AssignDirectories(int,char ** ,int &, int &);
int Find(char *);
};<file_sep>/Makefile
all: diseaseAggregator diseaseAggregatorWorker
objects1=diseaseAggregator.o diseaseAggregatorDS.o diseaseAggregatorfuncts.o diseaseAggregatorClasses.o
objects2=diseaseAggregatorWorker.o diseaseAggregatorDS.o diseaseAggregatorWorkerfuncts.o
diseaseAggregator: $(objects1)
g++ -std=c++11 -o diseaseAggregator $(objects1)
diseaseAggregatorDS.o: diseaseAggregatorDS.cpp
g++ -std=c++11 -c diseaseAggregatorDS.cpp
diseaseAggregatorfuncts.o: diseaseAggregatorfuncts.cpp
g++ -std=c++11 -c diseaseAggregatorfuncts.cpp
diseaseAggregatorClasses.o: diseaseAggregatorClasses.cpp
g++ -std=c++11 -c diseaseAggregatorClasses.cpp
diseaseAggregator.o: diseaseAggregator.cpp
g++ -std=c++11 -c diseaseAggregator.cpp
diseaseAggregatorWorker :$(objects2)
g++ -std=c++11 -o diseaseAggregatorWorker $(objects2)
diseaseAggregatorWorkerfuncts.o :diseaseAggregatorWorkerfuncts.cpp
g++ -std=c++11 -c diseaseAggregatorWorkerfuncts.cpp
diseaseAggregatorWorker.o :diseaseAggregatorWorker.cpp
g++ -std=c++11 -c diseaseAggregatorWorker.cpp
clean :
rm diseaseAggregator $(objects1)
rm diseaseAggregatorWorker diseaseAggregatorWorker.o diseaseAggregatorWorkerfuncts.o #diseaseAggregatorDS.h.gch diseaseAggregatorClasses.h.gch
rm ./logfiles/* ./NamedPipes/*<file_sep>/diseaseAggregatorfuncts.h
#include "diseaseAggregatorDS.h"
#include "diseaseAggregatorClasses.h"
extern volatile sig_atomic_t aflag_int_q;
extern volatile sig_atomic_t sigchld_pid;
void sig_handler_parent(int signo);
void Write(char *,int &,int ,string* );
void Read(char * ,int &,int ,string* );
void SendError(Child**,int ,int ,int&);
// void ReConstructNewWorker();
void diseaseFrequency(Child **,string,string,string,string,string,int,int,int&);
void searchPatientRecord(Child **,string ,int,int,int&);
void listCountries(Child**,int,int,int&);
void UserQueries(Child**,int,int,char **,int&,int&);
void exit(Child**,int,int,int&);
void TopKAgeRanges(Child **,int,string,string,string,string,int,int,int&);
void ACreateLogfile(int,int,string *&);
void ReforkChild(Child**, int ,int ,char**);
// void diseaseFrequency(Hashtable *,string,string,string,string);
// void TopKCountries(Hashtable*,int,string,string,string);
// void TopKDisease(Hashtable*,int,string,string,string);
// void numCurrentPatients(Hashtable*,string);
// void exit(LList*,Hashtable*,Hashtable*);<file_sep>/diseaseAggregatorDS.h
#include<string>
using namespace std;
class SSLNode{
public:
string * data;
SSLNode* Next;
SSLNode(string);
~SSLNode(void);
void Print(void);
};
//template <class dataType>
class SSList{
public:
SSLNode* SSLHead;
SSList();
~SSList();
void Insert(string);
//LList* Remove();
SSLNode* Search(string);
void Print();
void Sort(int);
};
int DateCompareEarlier(string*,string*);
///////////////////////////////////////////////////////////////
class MaxHeapNode{
private:
int count;
string* str;
MaxHeapNode* left;
MaxHeapNode* right;
public:
MaxHeapNode(string,int);
~MaxHeapNode();
MaxHeapNode* getleft();
MaxHeapNode* getright();
string* getstr();
int getcount();
void setstr(string*);
void setcount(int);
void Incount(void);
void setleft(MaxHeapNode*);
void setright(MaxHeapNode*);
};
class QNode{
private:
QNode * next;
MaxHeapNode * data;
public:
QNode(MaxHeapNode*);
~QNode();
QNode * getnext();
void setnext(QNode*);
MaxHeapNode * getdata(void);
void setdata(MaxHeapNode*);
};
class Queue {
private:
QNode * front;
QNode * back;
public:
Queue();
~Queue();
void enQ(MaxHeapNode*);
void deQ(void);
int QEmpty(void);
void Destroy();
QNode * getfront();
QNode * getback();
};
class MaxHeap{
private:
MaxHeapNode* Root;
Queue * Q;
string* key;
int count;
public:
MaxHeap(string);
~MaxHeap();
void Insert(MaxHeapNode*);
MaxHeapNode* getMax();
string* getkey();
MaxHeapNode* Search(MaxHeapNode*,string);
void Destroy(MaxHeapNode*);
void Heapify(MaxHeapNode*);
void ShiftUP(MaxHeapNode*);
void Preorder(MaxHeapNode*);
void RemoveRoot();
void RemoveRootHelper(MaxHeapNode*,MaxHeapNode*,Queue*);
};
/////////////////////////////////////////////////////////////////////
class LLNode{
private:
string* Record_id;
string* Entry;
string* Exit;
string* Fname;
string* Lname;
string* Disease;
string* Country;
int Age;
LLNode* Next;
public:
LLNode(string,string,string,string,string,string,string,int);
~LLNode(void);
void Print(void);
string* getid(void);
string* getFname(void);
string* getLname(void);
string* getDisease(void);
string* getCountry(void);
string* getEntry(void);
string* getExit(void);
//string* getDate(void);
int getAge(void);
void setAge(int);
void setFname(string);
void setLname(string);
void setDisease(string);
void setCountry(string);
void setExit(string);
void setEntry(string);
LLNode* getNext(void);
void setNext(LLNode*);
};
//template <class dataType>
class LList{
private:
LLNode* LLHead;
public:
LList();
~LList();
void Insert(string,string,string,string,string,string,string,int);
LLNode* Search(string);
LLNode* SearchDate(string);
LLNode* getLLHead();
void Print();
};
class RBTreeNode{
private:
RBTreeNode* left;
RBTreeNode* right;
RBTreeNode* parent;
int color; //////0=RED 1=BLACK
LLNode * Record;
string* Date;
public:
RBTreeNode(LLNode*);
~RBTreeNode();
void setleft(RBTreeNode *);
void setright(RBTreeNode *);
void setColor(int);
void setparent(RBTreeNode*);
RBTreeNode * getleft(void);
RBTreeNode * getright(void);
RBTreeNode * getparent(void);
LLNode* getRecord(void);
string* getDate(void);
int getColor(void);
void InorderPrinter();
void PostorderPrinter();
void PreorderPrinter();
int DateCompareEarlier(RBTreeNode*,RBTreeNode*);
};
class RBTree{
private:
RBTreeNode * Root;
int Nodecount;
public:
RBTree();
~RBTree();
RBTreeNode * getRoot(void);
void setRoot(RBTreeNode*);
void LRot(RBTreeNode*&);
void RRot(RBTreeNode*&);
void Inorder(RBTreeNode*);
void Postorder(RBTreeNode*);
void Preorder(RBTreeNode*);
RBTreeNode* BSTInsert(RBTreeNode* , RBTreeNode*&);
void FixRBInsert(RBTreeNode *&);
void Insert(LLNode*);
void Destroy(RBTreeNode*);
int BetweenDatesCount(RBTreeNode*, string*, string*,string*,int);
void SummaryStatistics(RBTreeNode* ,string*,int *&);
void CountforTopk(RBTreeNode*,string*,string*,string*,int* &);
};
class BEntry{
private:
string* Key;
RBTree* RBHead;
public:
BEntry();
~BEntry();
void Insert(LLNode*,string);
string* getkey();
int BetweenDatesCount(string* ,string*,string*,int);
void SummaryStatistics(string*,int *&);
void CountforTopk(string*, string*, string*,int *&);
};
class Bucket{
private:
int B_Size;
int count;
BEntry** Content;
Bucket * Next;
public:
Bucket(int);
~Bucket(void);
int Insert(LLNode*,string);
Bucket * getNext();
void setNext(Bucket*);
void PrintBetweenDatesCount(string*,string*);
int diseaseFrequency(string *,string *, string*, string*,string*);
void TopK(MaxHeap*,string*,string*,int);
void SummaryStatistics(string *,string*&);
void TopKAgeRanges(int,string*,string*,string*,string*,string* &); //topK function used for both topk applications
};
class Hashtable{
private:
int HTSize;
Bucket** HTHead;
int count;
int B_Size;///// Isws kalutera edw
public:
Hashtable(int ,int);
~Hashtable();
int getHTSize(void);
Bucket* getHTNode(void);
int Hashfunction(string);
void Insert(string,LLNode*);
void getDisease();
void PrintBetweenDatesCount(string*,string*);
int diseaseFrequency(string*,string*,string*,string*);
void TopK(int,string*,string*,string*,int);
void SummaryStatistics(string *date,string*&);
void numPatientAorD(string*,string*, string *, string*,string *&,SSList * ,string* ); //Acess the architecture-wise deeper structures to print the case count
void TopKAgeRanges(int,string*,string*,string*,string*,string*&); //topk
};
/////////////////////////////////////////////////////////////
<file_sep>/README.txt
README
K24: System Programming Project2
<NAME>
1115201700197
This project successfully tackles the task of interporcessing communication between a given number of workers and, signal handling for all parties. Furthermore, through a user interface it provides some applications-queries for the user to choose from. The programming language used is C++.
Components:
1) source : diseaseAggregator.cpp diseaseAggregatorfuncts.cpp diseaseAggregatorClasses.cpp diseaseAggregatorDS.cp diseaseAggregatorWorker.cpp diseaseAggregatorWorkerfuncts.cpp
2) header : diseaseAggregatorClasses.h diseaseAggregatorfuncts.h diseaseAggregatorDS.h diseaseAggregatorWorkerfuncts.h
3) makefile : Makefile #compiles two programms diseaseAggregator and diseaseAggregatorWorker. The 1st calls the second via execv
4) diseasesFile,CountriesFileEU.
5)bash script: create_infiles.sh #creates the directories and recrods needen for the programma
6)logfiles: directory where aggregator and worker logfiles are stored
7)NamedPipes: directory where the the fifo files for ipc are stored
Important Notes:
-The dates entered follow the format dd/mm/yyyy and date1 < date2.
-Parent keeps information about children in an array of pointers to Child Classes
-strings and string::append is used for IPC the protocol is:
@:end of word
#:end of message
$:sigint or sigquit has been sent.
-No slow worker impacts the communication because first the message is transmitted to the corrrect process,processes (write) while they already proceeed acccomplishing the job
Then the message from each process is read.
-if buffersize smaller than message then #buffersize bytes are sent multiple times until message is complete
-Workers are on the toes for new messages through while loop. as soon as they are sent one, they start working. Parent send messages only to specific worker if needed.
-signals: i)If sigint or sigquit is sent to worker before entering the IPC loop only one child is forked before entering the loop
ii)if they are sent after entering the sigint sigquit then they are considered working and will be terminated smoothly only after completing a given job(multiple workers can be sigintorquited the Refork() will occur for them after completing the next given task.)
iii)if sigint or sigquit is sent to parent before IPC loop then it exits right away.
iv)if they are sent during IPC loop then task will be completed first.
v)sigusr1 is sent from worker to parent. if the parent is waiting for input, the addition of the new file will be arranged after the completion of the next query sent
-The Data structures used by each worker are from first project
Compilation:
#pwd is ThodorisMaxmilianosChytis-Project2
-bash file:
./create_infiles.sh diseasesFile countriesFileEU input_dir 10 10
-diseaseAggregator:
make
./diseaseAggregator -b 1 -w 4 -i input_dir
make clean
<file_sep>/diseaseAggregatorWorkerfuncts.h
#include "diseaseAggregatorDS.h"
#include "diseaseAggregatorClasses.h"
extern volatile sig_atomic_t wflag_int_q;
extern volatile sig_atomic_t flag_usr1;
// extern int wflag_int_q;
void LoadNewFile(Hashtable*,LList*,SSList*,char*);
void QueriesAnswer(LList* ,Hashtable *,SSList *,char * ,char*,int &,int &,int,int&,int&,char*);
void CreateLogfile(SSList*,int ,int );
void InsertChildFileRecords(LList*, Hashtable *, SSLNode* ,SSList* ,char*);
void sig_handler_worker(int signo);
void Write(char *,int &,int ,string* );
void Read(char * ,int &,int ,string* );
<file_sep>/diseaseAggregator.cpp
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <sstream>
#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<signal.h>
//#include "diseaseAggregatorClasses.h"
// #include "diseaseAggregatorDS.h"
#include "diseaseAggregatorfuncts.h"
using namespace std;
//global flags to deal with sig int, quit and chld signals
volatile sig_atomic_t aflag_int_q=0;
volatile sig_atomic_t sigchld_pid=-1;
int main(int argc, char **argv){
//initialize siactions struct
struct sigaction action;
action.sa_handler=sig_handler_parent;
action.sa_flags = SA_RESTART;
sigemptyset (&action.sa_mask);
//link handlers
sigaction(SIGINT,&action,NULL);
sigaction(SIGQUIT,&action,NULL);
sigaction(SIGCHLD,&action,NULL);
//printf("\ncan't catch SIGINT\n");
char input_dir[50];
int numWorkers;
int bufferSize;
if (argc!=7){
cout << "Input error" << endl;
exit(1);
}else{
int i;
for(i=1;i<=5;i+=2){
if(strcmp(argv[i],"-i")==0){
strcpy(input_dir,argv[i+1]);
}else if(strcmp(argv[i],"-b")==0){
bufferSize = atoi(argv[i+1]);
}else if(strcmp(argv[i],"-w")==0){
numWorkers = atoi(argv[i+1]);
}else exit(1);
}
if(bufferSize<1) exit(1);
if(numWorkers<1) exit(1);
cout << "number of workers is: " << numWorkers << endl;
cout << "bufferSize is: " <<bufferSize << endl;
cout << "input_dir is: " << input_dir << endl;
}
//Create directories table
DIR *dp;
struct dirent * e;
int dircount = 0; //by default two directories . and ..
dp = opendir(input_dir);
if (dp==NULL){
cout << "problem" << endl;
exit(1);
}
while ( (e=readdir(dp)) != NULL){
if (e->d_type == DT_DIR && strcmp(e->d_name,".")!=0 && strcmp(e->d_name,"..")!=0){
dircount++;
}
}
rewinddir(dp);
char ** directories = new char*[dircount];
int i=0;
//while(1);
while ( (e=readdir(dp)) != NULL){
if (e->d_type == DT_DIR && strcmp(e->d_name,".")!=0 && strcmp(e->d_name,"..")!=0){
directories[i]= new char[50];
strcpy(directories[i],e->d_name);
// cout << directories[i] << endl;
i++;
}
}
rewinddir(dp);
closedir(dp);
cout << input_dir << " has "<< dircount << " directories" <<endl;
int nworkdir = (dircount/numWorkers);
int dirleft = (dircount%numWorkers);
cout << nworkdir << "||" << dirleft << endl;
if (numWorkers>dircount){ //no need for more workers than directories
numWorkers = dircount;
}
int pid;
int stat;
int j=0; //direcotireis index
Child ** CHT = new Child*[numWorkers];
for(int i=0; i<numWorkers;i++){
if( (pid = fork()) == -1){ //fork children
exit(1);
}
if ( pid==0 ){ //child breaks free
break;
}
CHT[i] = new Child(pid); //store data about each child
CHT[i]->AssignDirectories(nworkdir,directories,dirleft,j);
//create fifo files
if(mkfifo(CHT[i]->pathr,0666) < 0){
exit(1);
}
if(mkfifo(CHT[i]->pathw,0666) < 0){
exit(1);
}
}
//if parent
if (pid != 0){
string * message = new string();
for (int i=0; i<numWorkers ; i++){
//open fifo files
if( (CHT[i]->wfd = open(CHT[i]->pathw,O_WRONLY)) < 0 ){
cout << "problem parent rfile" << endl;
//cout << i << endl;
exit(1);
}
if( (CHT[i]->rfd = open(CHT[i]->pathr,O_RDONLY)) < 0 ){
cout << "problem parent rfile" << endl;
exit(1);
}
//send direcotires to each child
char buff[bufferSize];
int n;
message->assign("");
for(int j=0; j<CHT[i]->numdir+1; j++){
if (j!=CHT[i]->numdir){ //isws den xreiazetai
message->append(CHT[i]->directories[j]);
message->append("@");
}
}
Write(CHT[i]->pathw,CHT[i]->wfd,bufferSize,message);
//receive summary statistics
for(int j=0; j<CHT[i]->numdir; j++){
Read(CHT[i]->pathr,CHT[i]->rfd,bufferSize,message);
cout << *message << endl;
}
}
//sigchld is the value off the pid of passed child i can only catch one signal before the interface for terminated children //sleep(30);
if(sigchld_pid>0){
for(int i=0;i<numWorkers;i++){
if(CHT[i]->pid==sigchld_pid){
CHT[i]->SIG_INT_Q=1;
ReforkChild(CHT, numWorkers, bufferSize,argv);
break;
}
}
sigchld_pid=-1;
}
///call interface
int SUCCESS=0;
int FAIL=0;
if(aflag_int_q==0){
UserQueries(CHT,bufferSize,numWorkers,argv,SUCCESS,FAIL);
}
//parent received sig int or quit
if(aflag_int_q==1){
message->assign("");
for(int i=0;i<numWorkers;i++){
for(int j=0;j<CHT[i]->numdir;j++){
message->append(CHT[i]->directories[j]);
message->append("\n");
}
//kill children
if(kill(CHT[i]->pid,SIGKILL)==-1){
cout << "error" << endl;
}
}
//create the logfile
ACreateLogfile(SUCCESS,FAIL,message);
}
cout << "parent process waiting, pid is : " << getpid() << endl;
for(int i=0; i<numWorkers;i++){
wait(&stat);
close(CHT[i]->wfd);
close(CHT[i]->rfd);
}
cout << "parent waited for children exit status is : "<< WEXITSTATUS(stat) << endl;
delete message;
// // delete the names of the paths to the fifo files
for (int i=0; i<numWorkers; i++){
delete CHT[i];
}
delete[] CHT;
for(int i=0; i<dircount; i++){
delete[] directories[i];
}
delete[] directories;
}else{ //worker
sleep(2); //the fifo files must be opened.
//run the different code
if(execv("./diseaseAggregatorWorker",argv)==-1){
cout << "Error exec the worker executable" << endl;
}
}
}
<file_sep>/diseaseAggregatorWorkerfuncts.cpp
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <sstream>
#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<signal.h>
#include "diseaseAggregatorWorkerfuncts.h"
using namespace std;
// sig int and quit handler change value of global flag
void sig_handler_worker(int signo){
if (signo == SIGINT || signo == SIGQUIT){
wflag_int_q=1;
}
if (signo == SIGUSR1){
flag_usr1=1;
}
}
void Read(char * fifopath,int &rfd,int bufferSize,string* message){
char buff[bufferSize];
int n;
//end of message receivred is #
message->assign("");
do{
if ( (n=read(rfd,buff,bufferSize))<0){
cout << "problem" << endl;
//close(rfd);
break;
}
buff[n]='\0';
message->append(buff);
}while(message->back()!='#');
}
void Write(char * fifopath,int &wfd,int bufferSize,string* message){
//send only #buffersize bytes as long ass needed to complete the message
char buff[bufferSize];
int n;
if (message->back()!='#')
message->append("#");
int length = message->length();
for(int j=0;1;j++){
strcpy(buff,message->substr(j*bufferSize,bufferSize).c_str());
n=strlen(buff);
if(write(wfd,buff,n) !=n){
//exit(1);
cout << "wproblem" << endl;
}
length-=bufferSize;
if (length<=0){
break;
}
}
}
void InsertChildFileRecords(LList* Records,Hashtable * ChildHT,SSLNode* dirnode,SSList* files,char* path){
//for a country directory read throught its files' content
SSLNode * iter = files->SSLHead;
while (iter!=NULL){
char filepath[100];
ifstream infile;
strcpy(filepath,path);
strcat(filepath, "/");
strcat(filepath, iter->data->c_str());
infile.open(filepath);
if(infile.fail()) exit(1);
string record_id,Move,Fname,Lname,Disease,Date,Age;
LList * holdexits = new LList();
while(infile>>record_id){ //import the data from the file
bool insert = true;;
LLNode* found = Records->Search(record_id);
infile >> Move;
infile >> Fname;
infile >> Lname;
infile >> Disease;
infile >> Age;
if (stoi(Age)<=0 || stoi(Age)>120){
cout << "Wrong age" << endl;
insert = false;
}else if(found!=NULL){ //list insert in increasing date order, so :
if (Move=="ENTER"){ //the one found is chonologiacally before so same rid double Enter, error
insert=false;
//found->Print();
// cout << "date is" << *(iter->data) << endl;
//cout << "this record already exists" << endl;
}
}else{ //not found
if (Move=="EXIT"){ //no enter beforehand so keep it in a list beacuse there might be an enter on the same date further down the file
insert=false;
holdexits->Insert(record_id,Fname,Lname,Disease,*(dirnode->data),"--",*(iter->data),stoi(Age));
//cout << " possible wrong chonologiacall exit" << endl;
}
}
//cout << "Insert record: Record_id "<< record_id <<"||"<<Fname << "||" <<Lname<< "||" << Disease << "||" << *(tempN->data) << "||" << *(iter->data)<< "||" << Move << "||" <<Age << endl;
if(insert==true){
if (Move=="ENTER"){
Records->Insert(record_id,Fname,Lname,Disease,*(dirnode->data),*(iter->data),"--",stoi(Age));
ChildHT->Insert(Disease,Records->getLLHead());
}else if(Move=="EXIT"){
found->setExit(*(iter->data));
}
}else{
//cout << "ERROR" << endl;
}
}
LLNode * find;
LLNode *i=holdexits->getLLHead(); //chekarw gia ta exits tou idiou arxeio hmeromhnias
while(i!=NULL){
// cout << "problem is here obviously" << endl;
find=Records->Search( *(i->getid()) ); //brhke enter prin ara to bazw
if(find!=NULL){
// find->Print();
find->setExit(*(i->getExit()) );
find=NULL;
}
i=i->getNext();
}
delete holdexits;
iter = iter->Next;
infile.close();
}
}
void QueriesAnswer(LList* Records,Hashtable* HT,SSList * Countries,char * fifopathw,char * fifopathr,int &wfd,int &rfd,int bufferSize,int& SUCCESS,int& FAIL,char* input_dir){
string Request,disease,country,date1,date2;
int k;
int exit=0;
// write()
//communication interface to parent
while(exit==0){
string* message = new string();
Read(fifopathr,rfd,bufferSize,message);
// cout << *message << endl;
if (*message=="ERROR@#"){
FAIL++;
}else if(*message!="/exit@#"){
SUCCESS++;
}
//Decode the message
int count = 0;
int pos=0;
int length=message->length();
string ** vars = new string*[6];
for(int j=0;j<6;j++){
vars[j]=new string();
}
for(int j=0;j<length;j++){
if(message->at(j)=='@'){
if(++count>6) break;
//cout << count-1 << endl;
// if(message[0])
vars[count-1]->assign(message->substr(pos,j-pos));
//*vars[j]=message->substr(pos,j-pos);
//cout << *vars[count-1] << endl;
//break;
pos = j+1;
}
}
if(count>6) {
//;
cout << "Wrong input, try again" << endl;
}
if(*vars[0]=="/listCountries"){
//success
message->assign("K");
}else if(*vars[0]=="/diseaseFrequency"){
if (count==4){
vars[4]->assign("");
}else if(count!=5){
cout << "Wrong input, try again" << endl;
//continue;
}
char num[20];
//cout << HT->diseaseFrequency(vars[1],vars[4],vars[2],vars[3]) << endl;
sprintf(num,"%d",HT->diseaseFrequency(vars[1],vars[4],vars[2],vars[3])); // disease,country,date1,date2
//cout << num << endl;
message->assign("");
message->append(num);
// cout << *message << endl;
// disease,country,date1,date2
}else if(*vars[0]=="/topk-AgeRanges"){
HT->TopKAgeRanges(stoi(*vars[1]),vars[3],vars[4],vars[5],vars[2],message);
// TopKAgeRanges(int k,string* disease,string* date1,string* date2,string* country,string* &message) //topk
// cout << *message << endl;
//TopKDisease(diseasehashtable,k,country,date1,date2);
}else if(*vars[0]=="/searchPatientRecord"){
// if (count!=2){
// cout << "Wrong input,try again" << endl;
// continue;
// }
//Print the information
LLNode * node;
if ((node = Records->Search(*vars[1]))!=NULL){
node->Print();
message->assign("Found");
}
}else if(*vars[0]=="/numPatientAdmissions"){
if (count==4){
vars[4]->assign("");
}else if(count!=5){
cout << "Wrong input ,try again" << endl;
}
string EnorEx;
//Count for admissions
EnorEx.assign("Entry");
HT->numPatientAorD(vars[1],vars[2],vars[3],vars[4],message,Countries,&EnorEx); // disease,country,date1,date2
}else if(*vars[0]=="/numPatientDischarges"){
if (count==4){
vars[4]->assign("");
}else if(count!=5){
cout << "Wrong input ,try again" << endl;
}
string EnorEx;
//Count for discharges
EnorEx.assign("Exit");
HT->numPatientAorD(vars[1],vars[2],vars[3],vars[4],message,Countries,&EnorEx); // disease,date1,date2,country,...
}else if (*vars[0]=="/exit"){
//exit loop
exit=1;
//exit loop and user interface
}else if (*vars[0]=="ERROR"){
message->assign(*vars[0]);
}
//flag $ gia na steilei to paidi ston gonea plhroforia oti termatizei wste na mhn to sumperilabei sto epomeno erwthma o goneas
if(wflag_int_q==1) //apo thn stigmh pou einai sto read h sygkekrimenh diergasia kanw aparadoxh oti hdh ummetexei sto erwthma
message->append("$");
//cout << *message << endl;
Write(fifopathw,wfd,bufferSize,message);
for (int j=0;j<6;j++){
//cout << *vars[j] << endl;
delete vars[j];
}
delete[] vars;
delete message;
if(wflag_int_q==1){ //apo thn stigmh pou einai sto read syscall h sygkekrimenh diergasia kanw aparadoxh oti hdh summetexei sto erwthma
break; //opote prwta tha oloklhrwsei meta tha termatisei
}
if(flag_usr1==1){
LoadNewFile(HT,Records,Countries,input_dir);
}
}
}
void CreateLogfile(SSList* dirs,int SUCCESS,int FAIL){ //create the log file with the wanted information
char pid[50];
char logfile[50];
int logfilefd;
strcpy(logfile,"./logfiles/logfile.");
sprintf(pid,"%d",getpid());
strcat(logfile,pid);
// cout << logfile << endl;
if((logfilefd=open(logfile,O_WRONLY | O_CREAT | O_APPEND,0666))<0){
cout << "ERROR opening logfile" << endl;
exit(1);
}
string text="";
SSLNode * tempN = dirs->SSLHead;
while(tempN!=NULL){
text.append(*(tempN->data));
text.append("\n");
tempN=tempN->Next;
}
text.append("TOTAL ");
text.append(to_string(SUCCESS+FAIL));
text.append("\n");
text.append("SUCCESS ");
text.append(to_string(SUCCESS));
text.append("\n");
text.append("FAIL ");
text.append(to_string(FAIL));
text.append("\n");
int n=text.length();
if(write(logfilefd,text.c_str(),n) !=n){
exit(1);
cout << "problem" << endl;
}
}
void LoadNewFile(Hashtable* ChildHT,LList * Records,SSList *dirs,char * input_dir){
char temp[100];
string* message=new string("");
SSLNode * tempN= dirs->SSLHead;
while (tempN!=NULL){
DIR *dp;
struct dirent * e;
//List of date file names
SSList* files = new SSList();
int filecount = 0;
strcpy(temp,input_dir);
strcat(temp,"/");
strcat(temp,tempN->data->c_str());
dp = opendir(temp);
if (dp==NULL){
cout << "problem" << endl;
exit(1);
}
while ( (e=readdir(dp)) != NULL){
if (e->d_type == DT_REG){
if(flag_usr1==1 && Records->SearchDate(e->d_name)!=NULL){
continue; //if file found continue to next file
}
filecount++;
files->Insert(e->d_name);
}
}
rewinddir(dp);
closedir(dp);
//files->Print();
//cout << "--------------" << endl;
//Sort datefiles to be in correct chronological order for insertion
files->Sort(1);
//files->Print();
InsertChildFileRecords(Records, ChildHT, tempN, files,temp);
if (files->SSLHead!=NULL){
message->assign(*tempN->data);
message->append("\n");
}
SSLNode* idate=files->SSLHead;
while(idate!=NULL){
message->append(*idate->data);
message->append("\n");
//cout << "ola kala" << endl;
ChildHT->SummaryStatistics(idate->data,message);
idate = idate->Next;
}
cout << *message << endl; //if reload its ok. just print summary statistics from worker
//summary statistics ready send only if worker origianl and not reborn
delete files;
tempN= tempN->Next;
}
flag_usr1=0;
delete message;
}
<file_sep>/diseaseAggregatorDS.cpp
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include "diseaseAggregatorDS.h"
using namespace std;
int DateCompareEarlier(string* date1,string* date2){ //1 -> date1 is earlier || 2->date2 os earlier
if(*date1=="--") //-- is always larger
return 2;
else if(*date2=="--")
return 1;
//sum of dd-mm-yyyy , giving the correct weights
unsigned int sum1= atoi(date1->substr(0,2).c_str())*1 + atoi(date1->substr(3.2).c_str())*31 + atoi(date1->substr(6.4).c_str())*31*12;
unsigned int sum2= atoi(date2->substr(0,2).c_str())*1 + atoi(date2->substr(3.2).c_str())*31 + atoi(date2->substr(6.4).c_str())*31*12;
if (sum1<sum2)
return 1;
else if(sum2<sum1)
return 2;
else
return 0;
}
void SSLNode::Print(void){
cout << *data << endl;
}
SSLNode::SSLNode(string _data){
//cout << "Listnode constructor" << endl;
data = new string(_data);
Next = NULL;
};
SSLNode::~SSLNode(void){
//cout << "deleting LLNode" << endl;
delete data;
}
///////////////////////////////////////////////LList//////////////////////////////////////////////////////////////////////
void SSList::Print(void){
SSLNode * temp = SSLHead;
while (temp!=NULL){
temp->Print(); //print listnode
temp=temp->Next;
}
}
void SSList::Insert(string _data){
SSLNode* newNode= new SSLNode(_data); //listonde memory allocation
newNode->Next = SSLHead; //and list insertion
SSLHead = newNode;
}
SSLNode * SSList::Search(string _data){ //search for a node with specific id . return that node or NULL
SSLNode * temp = SSLHead;
while(temp!=NULL){
if (*(temp->data) == _data){
return temp;
}
temp=temp->Next;
}
return NULL;
}
SSList::SSList(void):SSLHead(NULL){
//cout << "calling LList constructor" << endl;
}
void SSList::Sort(int mode){
if (SSLHead==NULL)
return;
SSLNode * iter = SSLHead;
SSLNode * min = SSLHead;
string * temp ;
while (iter!=NULL){
SSLNode * i =iter->Next;
while(i!=NULL){
if (DateCompareEarlier(i->data,iter->data)==mode){
temp = i->data;
i->data = iter->data;
iter->data = temp;
}
i = i->Next;
}
iter = iter->Next;
}
}
SSList::~SSList(void){ //list constructor
//cout << "deleting List" << endl;
SSLNode* temp;
while (SSLHead!=NULL){
temp=SSLHead;
SSLHead=SSLHead->Next;
delete temp; //call listonode destructor and free listnode
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
LLNode* LLNode::getNext(){
return Next;
}
string* LLNode::getid(){
return Record_id;
}
string * LLNode::getDisease(){
return Disease;
}
string* LLNode::getEntry(){
return Entry;
}
string* LLNode::getExit(){
return Exit;
}
string* LLNode::getCountry(){
return Country;
}
int LLNode::getAge(){
return Age;
}
void LLNode::setExit(string _Exit){
*Exit=_Exit;
}
void LLNode::Print(void){
cout << endl;
cout << "------------------" << endl;
cout << *Record_id << endl;
cout << *Fname << endl;
cout << *Lname << endl;
cout << *Disease << endl;
cout << *Country << endl;
cout << *Entry << endl;
cout << *Exit << endl;
cout << Age << endl;
cout << "------------------" << endl;
}
void LLNode::setNext(LLNode* _Node){
Next=_Node;
}
LLNode::LLNode(string _record_id,string _Fname, string _Lname, string _Disease, string _Country, string _Entry, string _Exit, int _Age):Age(_Age){
//cout << "Listnode constructor" << endl;
Record_id = new string(_record_id);
Fname = new string(_Fname);
Lname = new string(_Lname);
Disease = new string(_Disease); //Listonode Constructor and memory allocation for record strings
Country = new string(_Country);
Entry = new string(_Entry);
Exit = new string(_Exit);
Next = NULL;
};
LLNode::~LLNode(void){
//cout << "deleting LLNode" << endl;
delete Record_id;
delete Fname;
delete Lname; //Listonode destructor and memory free for record strings
delete Disease;
delete Country;
delete Entry;
delete Exit;
}
///////////////////////////////////////////////LList//////////////////////////////////////////////////////////////////////
LLNode* LList::getLLHead(){
return LLHead;
}
void LList::Print(void){
LLNode * temp = LLHead;
while (temp!=NULL){
temp->Print(); //print listnode
temp=temp->getNext();
}
}
void LList::Insert(string _record_id,string _Fname, string _Lname, string _Disease, string _Country, string _Entry, string _Exit,int _Age){
LLNode* newNode= new LLNode(_record_id,_Fname,_Lname,_Disease,_Country,_Entry,_Exit,_Age); //listonde memory allocation
newNode->setNext(LLHead); //and list insertion
LLHead = newNode;
}
LLNode * LList::Search(string id){ //search for a node with specific id . return that node or NULL
LLNode * temp = LLHead;
while(temp!=NULL){
if (*(temp->getid())==id){
return temp;
}
temp=temp->getNext();
}
return NULL;
}
LLNode * LList::SearchDate(string date){ //search for a node with specific id . return that node or NULL
LLNode * temp = LLHead;
while(temp!=NULL){
if (*(temp->getEntry())==date || *(temp->getExit())==date ){
return temp;
}
temp=temp->getNext();
}
return NULL;
}
LList::LList(void):LLHead(NULL){
//cout << "calling LList constructor" << endl;
}
LList::~LList(void){ //list constructor
//cout << "deleting List" << endl;
LLNode* temp;
while (LLHead!=NULL){
temp=LLHead;
LLHead=LLHead->getNext();
delete temp; //call listonode destructor and free listnode
}
}
/////////////////////////////////////////////////////////////RBTreeNode/////////////////////////////////////////////////////////
RBTreeNode::RBTreeNode(LLNode* _Record):left(NULL),right(NULL),parent(NULL),color(0),Date(NULL),Record(_Record){
Date=_Record->getEntry(); //use date in record
//cout << "TreeNode constructed and Initilized succesfully" << endl; //Treenode constructor
}
RBTreeNode::~RBTreeNode(){
//cout << "treenode destroyed" << endl; //treenode destructor
}
void RBTreeNode::setleft(RBTreeNode * _left){
left = _left;
}
void RBTreeNode::setright(RBTreeNode * _right){
right = _right;
}
void RBTreeNode::setparent(RBTreeNode* _parent){
parent = _parent;
}
void RBTreeNode::setColor(int _color){ //0==red 1==black
color = _color;
}
RBTreeNode * RBTreeNode::getright(void){
return right;
}
RBTreeNode * RBTreeNode::getleft(void){
return left;
}
RBTreeNode * RBTreeNode::getparent(void){
return parent;
}
int RBTreeNode::getColor(void){
return color;
}
string* RBTreeNode::getDate(){
return Date;
}
LLNode* RBTreeNode::getRecord(){ //the record is in the list I just return the pointer to it
return Record;
}
//////////////////////////////////////////////////////////RBTree/////////////////////////////////////////////////////////////////////
RBTree::RBTree():Root(NULL),Nodecount(0){ //Rbtree constructor //Nodecount=number n of nodes
//cout << "tree has been created" << endl;
}
RBTree::~RBTree(){ //Rbtree destructor
Destroy(Root); //use helper function to destroy(delete) the tree
//cout << "tree hass been destoyed" << endl;
}
RBTreeNode * RBTree::getRoot(void){
return Root;
}
void RBTree::setRoot(RBTreeNode* _Root){
Root=_Root;
}
//Different traversals to print the tree data
void RBTree::Inorder(RBTreeNode* Root){
if (Root==NULL) return;
Inorder(Root->getleft());
cout << *Root->getDate() << endl;
Inorder(Root->getright());
}
void RBTree::Postorder(RBTreeNode* Root){
if (Root==NULL) return;
Postorder(Root->getleft());
Postorder(Root->getright());
cout << *Root->getDate() << endl;
}
void RBTree::Preorder(RBTreeNode* Root){
if (Root==NULL) return;
cout << *Root->getDate() << endl;
Preorder(Root->getleft());
Preorder(Root->getright());
}
RBTreeNode * RBTree::BSTInsert(RBTreeNode *root, RBTreeNode *&newNode){ //Recursive Binary search Tree insert
if (root==NULL)
return newNode;
if (DateCompareEarlier(newNode->getDate(),root->getDate())==1){ //go left to insert if the date of new node is smaller than the date of the saved one
root->setleft(BSTInsert(root->getleft(), newNode));
root->getleft()->setparent(root);
}else if (DateCompareEarlier(newNode->getDate(),root->getDate())==2 || DateCompareEarlier(newNode->getDate(),root->getDate())==0){ //go right to insert if the date of the new node
root->setright(BSTInsert(root->getright(),newNode)); //is larger or the same as the date of the saved one
root->getright()->setparent(root);
}
return root;
}
void RBTree::LRot( RBTreeNode * &STRootNode){ //STRootNode = subtreerootnode
///Perform a left rotation on the BSTree to preserve BST attributes
RBTreeNode * tbSTRootNode = STRootNode->getright();
STRootNode->setright(tbSTRootNode->getleft()); //the left child of the to be root node is now right child of the one that was root
if(STRootNode->getright() != NULL)
STRootNode->getright()->setparent(STRootNode);
tbSTRootNode->setparent(STRootNode->getparent()); //the parent of root is now parent of to be root
if (STRootNode->getparent() == NULL)
Root = tbSTRootNode; //root was RBTree Root so set RBTree Root to the to be root
else if(STRootNode == STRootNode-> getparent()->getleft()) //else attach correctly to parent root
STRootNode->getparent()->setleft(tbSTRootNode);
else
STRootNode->getparent()->setright(tbSTRootNode);
tbSTRootNode->setleft(STRootNode); //connect the nodes to complete the rotation
STRootNode->setparent(tbSTRootNode);
}
void RBTree::RRot( RBTreeNode * &STRootNode){
//Perform a right rotation ont the BSTree to preserve BST attributes
RBTreeNode * tbSTRootNode = STRootNode->getleft();
STRootNode->setleft(tbSTRootNode->getright()); ////the right child of the to be root node is now left child of the one that was root
if(STRootNode->getleft() != NULL)
STRootNode->getleft()->setparent(STRootNode);
tbSTRootNode->setparent(STRootNode->getparent()); //the parent of root is now parent of to be root
if (STRootNode->getparent() == NULL)
Root = tbSTRootNode; //root was RBTree Root so set RBTree Root to the to be root
else if(STRootNode == STRootNode-> getparent()->getleft())
STRootNode->getparent()->setleft(tbSTRootNode); //else attach correctly to parent root
else
STRootNode->getparent()->setright(tbSTRootNode);
tbSTRootNode->setright(STRootNode); //connect the nodes to complete the rotation
STRootNode->setparent(tbSTRootNode);
}
void RBTree::FixRBInsert(RBTreeNode *&newNode){ //RED=0 BLACK=1 //A function to detect and fix the RBTree violations that occured after BSTreee insertion
RBTreeNode *parent = NULL;
RBTreeNode *grandparent = NULL;
while (newNode != Root && newNode->getColor() == 0 && newNode->getparent()->getColor() == 0) {
parent = newNode->getparent();
grandparent = parent->getparent();
if (parent == grandparent->getleft()) { //1)parent's uncle is also red -> so recolor
RBTreeNode *uncle = grandparent->getright();
if (uncle!=NULL && uncle->getColor()== 0) {
uncle->setColor(1);
parent->setColor(1);
grandparent->setColor(0);
newNode = grandparent;
} else {
if (newNode == parent->getright()) { //i)parent is right of parent -> LRot
LRot(parent);
newNode = parent;
parent = newNode->getparent();
}
RRot(grandparent); //ii)parent is left of parent ->RRot
int temp=parent->getColor();
parent->setColor(grandparent->getColor());
grandparent->setColor(temp);
newNode = parent;
}
} else { //2)parent's parent is right of parent's grandparent
RBTreeNode *uncle = grandparent->getleft();
if(uncle!=NULL && uncle->getColor() == 0) { //i)parent's uncle is also red -> recolor
uncle->setColor(1);
parent->setColor(1);
grandparent->setColor(0);
newNode = grandparent;
}else { //ii) parent is left of parent's parent -> RRot
if (newNode == parent->getleft()) {
RRot(parent);
newNode = parent;
parent = newNode->getparent();
}
LRot(grandparent); //iii)parent is right of parent's parent -> LRot
int temp = parent->getColor();
parent->setColor(grandparent->getColor());
grandparent->setColor(temp);
newNode = parent;
}
}
}
Root->setColor(1);
}
void RBTree::Insert(LLNode* record){ //Insert into RBTRee
RBTreeNode * nRBTNode = new RBTreeNode(record); //treenode allocation
Root = BSTInsert(Root,nRBTNode); //BSTinsert
Nodecount++;
//Preorder(Root);
FixRBInsert(nRBTNode); //Fix the Insertion to preserve RBTree attributes
//Preorder(Root);
//Inorder(Root);
}
void RBTree::Destroy(RBTreeNode * Node){ //Postorder Recursive Destroy the RBTree
if(Node != NULL){
Destroy(Node->getleft());
Destroy(Node->getright());
delete Node;
}
}
//Recursive count for statistcs for topk query
void RBTree::CountforTopk(RBTreeNode* _Root,string* date1,string* date2,string* searchfor,int* & agestats){
if (_Root==NULL){
return;
}
int Age = _Root->getRecord()->getAge();
// cout << *_Root->getRecord()->getCountry() << endl;
if(*searchfor==*_Root->getRecord()->getCountry() && DateCompareEarlier(_Root->getDate(),date1)!=1 && DateCompareEarlier(_Root->getDate(),date2)!=2){
if (Age>60){
agestats[3]++;
}else if(Age>40){
agestats[2]++;
}else if(Age>20){
agestats[1]++;
}else{
agestats[0]++;
}
}
if (_Root->getleft()!=NULL && DateCompareEarlier(_Root->getDate(),date1)!=1){ //
CountforTopk(_Root->getleft(),date1,date2,searchfor,agestats); //go left.recusrion babyyy
}
if (_Root->getright()!=NULL && DateCompareEarlier(_Root->getDate(),date2)!=2){ //
CountforTopk(_Root->getright(),date1,date2,searchfor,agestats); //go left.recusrion babyyy
}
return;
}
//Count for summary statistics recursively
void RBTree::SummaryStatistics(RBTreeNode* _Root,string* date,int* & agestats){
if (_Root==NULL){
return;
}
int Age = _Root->getRecord()->getAge();
if(*date==*_Root->getRecord()->getEntry()){
if (Age>60){
agestats[3]++;
}else if(Age>40){
agestats[2]++;
}else if(Age>20){
agestats[1]++;
}else{
agestats[0]++;
}
}
if (_Root->getleft()!=NULL && DateCompareEarlier(date,_Root->getRecord()->getEntry())!=2){ //
SummaryStatistics(_Root->getleft(),date,agestats); //go left.recusrion babyyy
}
if (_Root->getright()!=NULL && DateCompareEarlier(date,_Root->getRecord()->getEntry())!=1){ //
SummaryStatistics(_Root->getright(),date,agestats); //go right.recusrion babyyy
}
return;
}
int RBTree::BetweenDatesCount(RBTreeNode* _Root, string* date1,string* date2,string * searchfor,int type){
int count=0;
if(_Root==NULL) //Base condition
return 0;
//type 3-4 for discharges
if (type==4 && *searchfor==*_Root->getRecord()->getCountry()){
if(DateCompareEarlier(_Root->getRecord()->getExit(),date1)!=1 && DateCompareEarlier(_Root->getRecord()->getExit(),date2)!=2){
count++; //only count those nodes where the nodes's exit date e[date1,date2]
}
}
if (type==3){
if(DateCompareEarlier(_Root->getRecord()->getExit(),date1)!=1 && DateCompareEarlier(_Root->getRecord()->getExit(),date2)!=2){
count ++;
//////only count those nodes where the nodes's exit date e[date1,date2]
}
}
if (type==2 && *searchfor==*_Root->getRecord()->getCountry()){
if(DateCompareEarlier(_Root->getDate(),date1)!=1 && DateCompareEarlier(_Root->getDate(),date2)!=2){
count++; //only count those nodes where the nodes's entry date e[date1,date2]
}
}
if (type==1){
if(DateCompareEarlier(_Root->getDate(),date1)!=1 && DateCompareEarlier(_Root->getDate(),date2)!=2){
count ++;
//////only count those nodes where the nodes's entry date e[date1,date2]
}
}
if(_Root->getleft()!=NULL ){
if(DateCompareEarlier(_Root->getDate(),date1)!=1 || type==3 ||type==4){
count+=BetweenDatesCount(_Root->getleft(),date1,date2,searchfor,type); //go left.recusrion babyyy
}
} //_Root->getRecord()->Print(); ///which counts people still being nursed
if(_Root->getright()!=NULL){
//go right. recursion babyy
if(DateCompareEarlier(_Root->getDate(),date2)!=2 || type==3 || type==4){
count+=BetweenDatesCount(_Root->getright(),date1,date2,searchfor,type); //go left.recusrion babyyy
}
}
//cout << "Counting inside the tree " << count << endl;
return count;
}
////////////////////////////////////////////////BEntry///////////////////////////////////////////////////////////////
void BEntry::Insert(LLNode* record,string key){ //Insert into the bucket Entry
if (RBHead==NULL){
Key = new string(key);
RBHead = new RBTree();
}
RBHead->Insert(record);
}
string* BEntry::getkey(void){
return Key;
}
BEntry::BEntry():Key(NULL),RBHead(NULL){
//cout << "BucketEntry Constructor" << endl;
}
void BEntry::SummaryStatistics(string* date,int * &agestats){
RBHead->SummaryStatistics(RBHead->getRoot(),date,agestats);
}
int BEntry::BetweenDatesCount(string* date1,string* date2,string* searchfor,int type){ //call the counter function with the demanded type
return RBHead->BetweenDatesCount(RBHead->getRoot(),date1,date2,searchfor,type);
}
void BEntry::CountforTopk(string* date1, string* date2, string* country,int *&agestats){
RBHead->CountforTopk(RBHead->getRoot(),date1,date2,country,agestats);
}
BEntry::~BEntry(){
//cout << "BucketEntry Destructor" << endl;
if (Key!=NULL) delete Key;
if (RBHead!=NULL) delete RBHead;
}
//////////////////////////////////////////////////////////////////Bucket//////////////////////////////////////////////////
Bucket * Bucket::getNext(void){
return Next;
}
void Bucket::setNext(Bucket * _Next){
Next = _Next;
}
Bucket::Bucket(int Bsize):B_Size(Bsize), count(0),Next(NULL){ //Bucket constructor
//cout << "bucket constructorand Bsize is" << B_Size << endl;
Content = new BEntry*[B_Size]; //array of pointers to bucketentries
for (int i=0;i<=B_Size-1;i++){
Content[i]= new BEntry(); //fill the array with BEntrypointers
}
}
Bucket::~Bucket(void){ //Bucket entry constructor
//cout << "bucket destructor" << endl;
for (int i=0 ; i<=B_Size-1 ; i++ ){
delete Content[i]; //delte Bentries
}
delete[] Content;
}
int Bucket::Insert(LLNode * record,string key){ //Insert into the bucket
int i;
for (i=0 ; i<=B_Size-1 ; i++){
if (Content[i]->getkey()==NULL || *(Content[i]->getkey())==key){
Content[i]->Insert(record,key);
return 1;
}
}
return 0;
}
void Bucket::SummaryStatistics(string * date,string*& message){
int i;
char num[12];
int * agestats = new int[4];
int k;
//cout << *date << endl;
for(k=0;k<=B_Size-1;k++){
if (Content[k]->getkey()!=NULL){
for(i=0;i<4;i++){
agestats[i]=0;
}
//cout << *Content[k]->getkey() << endl;
Content[k]->SummaryStatistics(date,agestats);
if (agestats[0]+agestats[1]+agestats[2]+agestats[3]>0){
string pattern[4]={"Age range 0-20 years: ","Age range 21-40 years: ","Age range 41-60 years: ","Age range 61+ years: "};
message->append(*Content[k]->getkey());
message->append("\n");
for(int i=0;i<4;i++){
// char* num;
message->append(pattern[i]);
sprintf(num, "%d",agestats[i]);
message->append(num);
message->append(" cases\n");
}
message->append("\n");
}
//
}
}
delete[] agestats;
//cout << k << endl;
}
int Bucket::diseaseFrequency(string * virusName,string * country, string* date1, string* date2,string * EnorEx){
//initialization for different betweendate couns calls
int sWOcountry,sWcountry;
if(*EnorEx=="Entry"){
sWOcountry=1;
sWcountry=2;
}else if(*EnorEx=="Exit"){
sWcountry=4;
sWOcountry=3;
}
//cout << *EnorEx << endl;
int count=-1;
for(int i=0;i<=B_Size-1;i++){
if (Content[i]->getkey()!=NULL){
if (*(Content[i]->getkey()) == *virusName){
if (*country==""){
// cout << "exw mpei edw pou shmainei oti xwris xwra metraw gia " << *virusName << endl;
count= Content[i]->BetweenDatesCount(date1,date2,country,sWOcountry);
}
else{
// cout << "exw mpei edw pou shmainei oti me xwra " << *country <<" metraw gia " << *virusName << endl;
count= Content[i]->BetweenDatesCount(date1,date2,country,sWcountry);
}
break;
}
}
}
if (count==-1){
// cout << *virusName << " not found frequency is 0" << endl;
return 0;
}
return count;
}
void Bucket::TopKAgeRanges(int k,string* disease,string* date1,string* date2,string* country,string* & message){ //topK function used for both topk applications
int * agestats = new int[4];
int sum=-1;
for(int i=0;i<4;i++){
agestats[i]=0;
}
for (int i=0;i<=B_Size-1;i++){
if (Content[i]->getkey()!=NULL){
//Count age statistics
if (*(Content[i]->getkey()) == *disease){
sum=0;
Content[i]->CountforTopk(date1,date2,country,agestats);
sum=agestats[0]+agestats[1]+agestats[2]+agestats[3];
if (sum>0){
break;
}
}
}
}
if(sum==-1){
cout << *disease << "not found" << endl;
}
else{
float AgestatsPercent[4];
int AgestatsPercentIndex[4];
string pattern[4] = { "0-20: ","21-40: " ,"41-60: ","60+: " };
if(sum>0){
//create percentage array
for(int i=0;i<4;i++){ //mexi k ama thelw all ok
AgestatsPercent[i] =100* (float)agestats[i]/sum ;
AgestatsPercentIndex[i] = i;
}
//sort array and swap indeces accordigly
float tempf;
int tempi;
int maxpos;
string temps;
for(int i=0;i<4;i++){
maxpos=i;
for(int j=i+1;j<4;j++){
if (AgestatsPercent[maxpos]<AgestatsPercent[j]){
maxpos=j;
}
}
tempi=AgestatsPercentIndex[maxpos];
AgestatsPercentIndex[maxpos]=AgestatsPercentIndex[i];
AgestatsPercentIndex[i]=tempi;
tempf=AgestatsPercent[maxpos];
AgestatsPercent[maxpos]=AgestatsPercent[i];
AgestatsPercent[i]=tempf;
}
}
char perc[20];
//create message using the indeces table
for(int i=0;i<k;i++){
if(sum==0){
message->append(pattern[i]);
message->append("0");
}else{
// cout << AgestatsPercentIndex[i] << endl;
message->append(pattern[AgestatsPercentIndex[i]]);
sprintf(perc,"%.2f",AgestatsPercent[i]);
message->append(perc);
}
message->append("%\n");
}
}
delete[] agestats;
}
//////////////////////////////////////////////////////Hashtable/////////////////////////////////////////////////////////////
void Hashtable::SummaryStatistics(string *date,string*& message){
int i;
for (i=0;i<=HTSize-1;i++){
Bucket * temp = HTHead[i];
while(temp!=NULL){
temp->SummaryStatistics(date,message);
temp = temp->getNext();
}
}
}
void Hashtable::numPatientAorD(string* disease,string* date1, string * date2, string* country,string *& message,SSList * Countries,string* EnorEx){ //Acess the architecture-wise deeper structures to print the case count
char count[10];
int index;
index = Hashfunction(*disease);
Bucket * temp = HTHead [index];
message->assign("");
while(temp!=NULL){
if (*country!=""){
//temp->diseaseFrequency(virusName,country,date1,date2,EnorEx);
message->append(*country);
message->append(" ");
sprintf(count,"%d",temp->diseaseFrequency(disease,country,date1,date2,EnorEx));
message->append(count);
message->append("\n");
}else{
SSLNode * iter;
iter = Countries->SSLHead;
while (iter!= NULL){
message->append(*(iter->data));
message->append(" ");
sprintf(count,"%d",temp->diseaseFrequency(disease,iter->data,date1,date2,EnorEx));
message->append(count);
message->append("\n");
iter=iter->Next;
}
}
temp = temp->getNext();
}
// cout << *message << endl;
}
int Hashtable::diseaseFrequency(string * virusName,string* country,string* date1,string* date2){ //Acess structures to print frequency of a specific virus between dates [ for a country]
//cout <<*virusName<<*country<<*date1<<*date2 << endl;
int index;
int count=0;
string EnorEx="Entry";
index = Hashfunction(*virusName);
Bucket * temp = HTHead [index];
while (temp!=NULL){
count=temp->diseaseFrequency(virusName,country,date1,date2,&EnorEx);
temp = temp->getNext();
if (count!=0){
break;
}
}
return count;
}
void Hashtable::TopKAgeRanges(int k,string* disease,string* date1,string* date2,string* country,string* &message){ //topk
message->assign("");
int index = Hashfunction(*disease);
Bucket * temp = HTHead [index];
while (temp!=NULL){
temp->TopKAgeRanges(k,disease,date1,date2,country,message);
temp = temp->getNext();
if(*message!=""){
break;
}
}
}
int Hashtable::Hashfunction(string key){ //hashfunction to get index of the hashtable for key
int a=HTSize+1;
int hash=0;
for(int i=0 ; i<=key.size(); i++){
hash = (a*hash + (unsigned int) key[i])% HTSize; //each character of string works into a creating a sum thas is moded(%)
}
int hashcode = (hash % HTSize);
return hashcode;
}
void Hashtable::Insert(string key,LLNode * record){ //Insert a record pointer into hash......treenode
int index = Hashfunction(key);
if(HTHead[index]==NULL)
HTHead[index] = new Bucket(B_Size);
//cout <<" key is " << key << " hashcode is " <<index << endl;
Bucket* temp = HTHead[index];
while(temp->Insert(record,key)==0){ //only insert if key not found in some bucket
if (temp->getNext()==NULL){
temp->setNext(new Bucket(B_Size));
}
temp=temp->getNext();
}
count++;
}
Hashtable::Hashtable(int _HTSize, int BSize):HTSize(_HTSize),B_Size(BSize){
//cout << "construct hashtable" << endl;
HTHead = new Bucket*[HTSize];
for (int i=0;i<=HTSize-1;i++){
HTHead[i]=NULL; //inistialize with null. Only gets an address a record is to be inserted
}
}
Hashtable::~Hashtable(){ //Hashtable destructor
//cout << "destroy hashtable" << endl;
for (int i=0;i<=HTSize-1;i++){
Bucket * temp;
while (HTHead[i]!=NULL){
temp=HTHead[i];
HTHead[i]=HTHead[i]->getNext();
delete temp;
}
}
delete[] HTHead;
}
| 018ecd609833602fefcc8864fc3fca798d069595 | [
"Makefile",
"Text",
"C",
"C++",
"Shell"
] | 13 | C++ | ThodorisMaximilianosChytis/diseaseAggregator | 19e9df7c534d7b10cc4b7c6e1529052ef49e5f00 | e39650cfdefa69e74296119d3f7b731c53a6d528 |
refs/heads/main | <file_sep>import os
from ._script import Script
class Wire:
def __init__(self, point0, point1, radius):
self.x0, self.y0, self.z0 = point0
self.x1, self.y1, self.z1 = point1
self.radius = radius
@property
def length(self):
return (self.x1 - self.x0) ** 2 \
+ (self.y1 - self.y0) ** 2 \
+ (self.z1 - self.z0) ** 2
class Geometry:
def __init__(self, wires):
self.wires = wires
def get_coordinates(self):
coords = []
for wire in self.wires():
coords.append([
(wire.x0, wire.y0, wire.z0),
(wire.x1, wire.y1, wire.z1)
])
def export_geometry(self, path_to_geometry_folder, name):
with open(f'{path_to_geometry_folder}\{name}.txt', 'w+') as file:
file.write(f'{len(self.wires)} {self.wires[0].radius}\n')
for wire in self.wires:
file.write(f'{wire.x0} {wire.y0} {wire.z0} {wire.x1} {wire.y1} {wire.z1}\n')
print(f'{name}.txt successfully added')
def create_cst_project(self, name, path_to_geometry_folder,
path_to_CST_DE, path_to_CST_project):
self.export_geometry(path_to_geometry_folder, name)
script = Script(name=name, route_geometry=path_to_geometry_folder, route_cst=path_to_CST_project)
path_to_script = os.path.abspath('script.bas'); print(f'"{path_to_CST_DE}" -m "{path_to_script}"')
stream = os.popen(f'"{path_to_CST_DE}" -m "{path_to_script}"')
# script.remove_script()
return stream.read()
<file_sep>[tool.poetry]
name = "cst_geometry"
version = "0.1.5"
description = "Package for modeling in CST Microwave studio using python"
authors = ["konstantgr <<EMAIL>>"]
license = "MIT"
readme = "README.rst"
repository = "https://github.com/konstantgr/cst_geometry_manager"
[tool.poetry.dependencies]
python = "^3.7"
[tool.poetry.dev-dependencies]
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
<file_sep>CST geometry manager
====================
It's a package that allows you to model geometries contain wires and
then export it into CST Microwave Studio 2021 project using python.
Features
--------
- One file format for all wire geometries
- Сreate a CST project directly from a script or notebook.
- Convenient data structure for creating your own unique complex
geometries from wires
Install
=======
For simple installation use pip:
::
pip install cst-geometry
Usage
-----
During using scripts or notebooks for creating projects all the CST Microwave studio windows must be closed
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Wire
------------------
``Wire`` objects serves to create ``Geometry`` objects. Wire object initialized using start point of wire ``point0``, finish point of wire ``point1`` and its radius ``radius``. As needed after initializing you can use ``length`` property. ``point0`` and ``point1`` are vectors of cartesian coordinates.
.. code:: python
from cst_geometry import Wire
x0 = 0; y0 = 0; z0 = 0
x1 = 1; y1 = 1; z1 = 1
radius = 0.5
wire = Wire(
point0 = (x0, y0, z0),
point1 = (x1, y1, z1),
radius = radius
)
print(wire.length) # Returns length of wire
Geometry
------------------
``Geometry`` object allows to easily export geometry to CST Microwave Studio or just export .txt file with geometry parameters. For initializing ``Geometry`` object you should pass a list of ``Wire`` objects. ``create_cst_project`` is a method for creating a .cst project with geometry model. ``export_geometry`` is a method for exporting geometry as .txt file.
.. code:: python
from cst_geometry import Wire, Geometry
def create_wires_by_rule():
wires = []
# ...
# Your code for creating Wire objects
# ...
wires.append(wire)
return wires
wires = create_wires_by_rule()
geometry = geometry(wires)
To create your own geometry use ``Wire`` and ``Geometry`` classes.
.. code:: python
import numpy as np
from cst_geometry import Wire, Geometry
def get_circular_geometry(radius, lengths_of_wires, wire_radius=1e-3, delta_angle=0):
number_of_wires = len(lengths_of_wires)
angles = np.linspace(0, 2 * np.pi, number_of_wires, endpoint=False) + delta_angle
wires = []
for i, length in enumerate(lengths_of_wires):
phi = angles[i]
wire = Wire(
point0=(radius * np.cos(phi), radius * np.sin(phi), -length / 2),
point1=(radius * np.cos(phi), radius * np.sin(phi), length / 2),
radius=wire_radius
)
wires.append(wire)
return Geometry(wires)
Examples
--------
.. code:: python
from cst_geometry import simple_geometries
# Path to CST DESIGN ENVIRONMENT.exe
path_to_CST_DE = r"Absolute\Path\To\CST DESIGN ENVIRONMENT.exe"
# Route to folder with .txt geometries and CST projects
route_to_folder = r"Absolute\Path\To\FOLDER"
def circular_geometry_equal_wires(length, number_of_wires, radius):
lengths = [length for i in range(number_of_wires)]
circular_geometry = simple_geometries.get_circular_geometry(
radius=radius, lengths_of_wires=lengths, wire_radius=1e-3, delta_angle=0
)
return circular_geometry
# During using scripts or notebooks for creating projects
# all the CST Microwave studio windows must be closed !!!
# Creating an array of 18 vertical aligned wires with length 2
# on of imaginary cylinder with radius 4
circular_geometry = circular_geometry_equal_wires(2, 18, 4)
output = circular_geometry.create_cst_project(
name="circular_geometry",
path_to_CST_DE=path_to_CST_DE,
path_to_geometry_folder=route_to_folder,
path_to_CST_project=route_to_folder
)
This code creates simple geometry contain 18 wires equally distributed on
imaginary cylinder. Then ``create_cst_project`` method creates project.
To start using scripts firstly need to change ``path_to_CST_DE``
variable. CST project create in cst\_project folder.
.. image:: examples/CST_example.gif
Several examples with CST projects are located in ``examples/`` folder.
<file_sep>import numpy as np
from cst_geometry import Wire, Geometry
def get_circular_geometry(radius, lengths_of_wires, wire_radius=1e-3, delta_angle=0):
number_of_wires = len(lengths_of_wires)
angles = np.linspace(0, 2 * np.pi, number_of_wires, endpoint=False) + delta_angle
wires = []
for i, length in enumerate(lengths_of_wires):
phi = angles[i]
wire = Wire(
point0=(radius * np.cos(phi), radius * np.sin(phi), -length / 2),
point1=(radius * np.cos(phi), radius * np.sin(phi), length / 2),
radius=wire_radius
)
wires.append(wire)
return Geometry(wires)
def get_cubic_grid_geometry(tau, lengths_of_wires, wire_radius=1e-3):
"""
length_of_wires: np.array([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])
is a 4x3 array, left bottom corner is (0,0) point
"""
number_of_wires_y, number_of_wires_x = lengths_of_wires.shape
wires = []
for i in range(number_of_wires_y):
for j in range(number_of_wires_x):
x = tau * j
y = tau * i
wire = Wire(
point0=(x, y, -lengths_of_wires[i][j] / 2),
point1=(x, y, lengths_of_wires[i][j] / 2),
radius=wire_radius
)
wires.append(wire)
return Geometry(wires)
def get_shortened_taper_geometry(radius_inner, radius_outer, number_of_wires,
taper_height, wire_radius=1e-3,
delta_angle=0):
angles = np.linspace(0, 2 * np.pi, number_of_wires, endpoint=False) + delta_angle
wires = []
for i in range(number_of_wires):
phi = angles[i]
wire = Wire(
point0=(radius_outer * np.cos(phi), radius_outer * np.sin(phi), 0),
point1=(radius_inner * np.cos(phi), radius_inner * np.sin(phi), taper_height),
radius=wire_radius
)
wires.append(wire)
return Geometry(wires)
<file_sep>import os
_script_source = '''Sub Main()
geometry_file = "{}"
Dim studio As Object
'Starts CST MICROWAVE STUDIO
Set studio = CreateObject("CSTStudio.Application")
Dim proj As Object
Set proj = studio.Active3D
Dim Text As String, textline As String, posLat As Integer, posLong As Integer
Dim t As String
Dim route As String, Output As String
Component.New "Geometry"
Dim tau As Double
Dim i,j,l As Integer
Dim x0(1000) As Double
Dim y0(1000) As Double
Dim z0(1000) As Double
Dim x1(1000) As Double
Dim y1(1000) As Double
Dim z1(1000) As Double
Dim row() As String
Open geometry_file For Input As #1
Do Until EOF(1)
Line Input #1, textline
row = Split(textline)
If (UBound(row) - LBound(row) + 1) = 2 Then
number_of_wires = CInt(row(0))
radius_of_wire = CDbl(row(1)) * 100
Else
x0(i) = CDbl(row(0))
y0(i) = CDbl(row(1))
z0(i) = CDbl(row(2))
x1(i) = CDbl(row(3))
y1(i) = CDbl(row(4))
z1(i) = CDbl(row(5))
i += 1
End If
Loop
Close #1
StoreDoubleParameter "r", radius_of_wire
SetParameterDescription ( "r", "wire radius" )
StoreDoubleParameter "N", number_of_wires
SetParameterDescription ( "N", "Number of wires" )
t = ""
For i=0 To number_of_wires - 1
t = t & "With Wire" & vbCrLf
t = t & ".Reset" & vbCrLf
t = t & ".Name ""c" & CStr(i) & """" & vbCrLf
t = t & ".Folder ""Geometry""" & vbCrLf
t = t & ".Type ""BondWire""" & vbCrLf
t = t & ".Material ""PEC""" & vbCrLf
t = t & ".Radius ""r""" & vbCrLf
t = t & ".Point1 " & CStr(x0(i)) & ", " & CStr(y0(i)) & ", " & CStr(z0(i)) & ", ""False""" & vbCrLf
t = t & ".Point2 " & CStr(x1(i)) & ", " & CStr(y1(i)) & ", " & CStr(z1(i)) & ", ""False""" & vbCrLf
t = t & ".BondWireType ""Spline""" & vbCrLf
t = t & ".Alpha ""75""" & vbCrLf
t = t & ".Beta ""35""" & vbCrLf
t = t & ".RelativeCenterPosition ""0.5""" & vbCrLf
t = t & ".SolidWireModel ""True""" & vbCrLf
t = t & ".Termination ""Natural""" & vbCrLf
t = t & ".add" & vbCrLf
t = t & "End With" & vbCrLf
Next
AddToHistory("make geometry", t)
AddToHistory("make planewave", "With PlaneWave" & vbCrLf & _
".Reset" & vbCrLf & _
".Normal ""-1"", ""0"", ""0""" & vbCrLf & _
".EVector ""0"", ""0"", ""1""" & vbCrLf & _
".Polarization ""Linear""" & vbCrLf & _
".ReferenceFrequency ""0""" & vbCrLf & _
".PhaseDifference ""-90.0""" & vbCrLf & _
".CircularDirection ""Left""" & vbCrLf & _
".AxialRatio ""0.0""" & vbCrLf & _
".SetUserDecouplingPlane ""False""" & vbCrLf & _
".Store" & vbCrLf & _
"End With")
AddToHistory("make monitors", "With Monitor" & vbCrLf & _
".Reset" & vbCrLf & _
".Domain ""Frequency""" & vbCrLf & _
".FieldType ""Farfield""" & vbCrLf & _
".ExportFarfieldSource ""False""" & vbCrLf & _
".UseSubvolume ""False""" & vbCrLf & _
".Coordinates ""Structure""" & vbCrLf & _
".SetSubvolume ""-30.25"", ""30.25"", ""-70.5"", ""70.5"", ""-30.25"", ""30.25""" & vbCrLf & _
".SetSubvolumeOffset ""10"", ""10"", ""10"", ""10"", ""10"", ""10""" & vbCrLf & _
".SetSubvolumeInflateWithOffset ""False""" & vbCrLf & _
".SetSubvolumeOffsetType ""FractionOfWavelength""" & vbCrLf & _
".EnableNearfieldCalculation ""True""" & vbCrLf & _
".CreateUsingLinearSamples ""5"", ""7"", ""20""" & vbCrLf & _
"End With")
AddToHistory("make probe","With Probe" & vbCrLf & _
".Reset" & vbCrLf & _
".ID 0" & vbCrLf & _
".AutoLabel 1" & vbCrLf & _
".Field ""RCS""" & vbCrLf & _
".Orientation ""All""" & vbCrLf & _
".SetPosition1 ""-10""" & vbCrLf & _
".SetPosition2 ""0.0""" & vbCrLf & _
".SetPosition3 ""0.0""" & vbCrLf & _
".SetCoordinateSystemType ""Cartesian""" & vbCrLf & _
".Create" & vbCrLf & _
"End With")
Dim sCommand As String
'@ define units
sCommand = ""
sCommand = sCommand + "With Units " + vbLf
sCommand = sCommand + ".Geometry ""mm""" + vbLf
sCommand = sCommand + ".Frequency ""GHz""" + vbLf
sCommand = sCommand + ".Time ""ns""" + vbLf
sCommand = sCommand + "End With"
AddToHistory "define units", sCommand
AddToHistory("Set frequency Solver", "ChangeSolverType ""HF Frequency Domain""")
proj.SaveAs "{}", True
proj.Quit
Set studio = Nothing
End Sub'''
class Script:
def __init__(self, name, route_geometry, route_cst):
self.create_script(name, route_geometry, route_cst)
@staticmethod
def create_script(name, route_geometry, route_cst):
path_to_geometry = os.path.abspath(f"{route_geometry}\{name}.txt")
path_to_cst_file = os.path.abspath(f"{route_cst}\{name}.cst")
source = _script_source.format(path_to_geometry, path_to_cst_file)
with open(os.path.abspath('script.bas'), 'w+') as f:
for line in source.split('\n'):
f.write(f'{line}\n')
print(f'script added at {os.path.abspath("script.bas")}')
@staticmethod
def remove_script():
os.remove(os.path.abspath('script.bas')); print(f'script removed from {os.path.abspath("script.bas")}')
print(f'script removed from {os.path.abspath("script.bas")}')
<file_sep>from cst_geometry.geometry import Wire, Geometry
from cst_geometry import simple_geometries
__all__ = ["Wire", "Geometry", 'simple_geometries']
<file_sep>from cst_geometry import Wire, Geometry
from cst_geometry import simple_geometries
path_to_CST_DE = r"ABSOLUTE\\PATH\\TO\\CST DESIGN ENVIRONMENT.exe"
route_to_folder = r"ABSOLUTE\\PATH\\TO\\FOLDER"
def circular_geometry_equal_wires(length, number_of_wires, radius):
lengths = [length for i in range(number_of_wires)]
circular_geometry = simple_geometries.get_circular_geometry(
radius=radius, lengths_of_wires=lengths, wire_radius=1e-3, delta_angle=0
)
return circular_geometry
def main():
circular_geometry = circular_geometry_equal_wires(2, 18, 4)
output = circular_geometry.create_cst_project(
name="circular_geometry",
path_to_CST_DE=path_to_CST_DE,
path_to_geometry_folder=route_to_folder,
path_to_CST_project=route_to_folder
)
print(output)
if __name__ == '__main__':
main()
| 557a9b0a7063178700458933ea5eebb7f2a48032 | [
"TOML",
"Python",
"reStructuredText"
] | 7 | Python | konstantgr/cst_geometry_manager | 6ff204c2cae7249d4d64b8a9e59bc873d782a1a2 | 021ea7ef3477d7ff30a963ffdd31f534a0d94ad3 |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
"""
pip install pymupdf
"""
import os
import fitz
pdf_dir=[]
pdfPath = './pdf'
imagePath = './image'
def get_file():
docunames = os.listdir(pdfPath)
for docuname in docunames:
if os.path.splitext(docuname)[1] == '.pdf':# all pdf file in pdf folder
pdf_dir.append(docuname)
def conver_img():
for pdf in pdf_dir:
doc = fitz.open(pdfPath+'/'+pdf)
pdf_name = os.path.splitext(pdf)[0]
for pg in range(doc.pageCount):
page = doc[pg]
rotate = int(0)
# scale factor of each side
zoom_x = 2.0
zoom_y = 2.0
trans = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate)
pm = page.getPixmap(matrix=trans, alpha=False)
pm.writePNG(imagePath+'/'+pdf_name+'_%s.png' % pg)
if __name__ == '__main__':
get_file()
if not os.path.exists(imagePath):# is image folder exist
os.makedirs(imagePath) # create folder if not exist
conver_img() | 4db71104c768010801acb5566b7cc40b8656cae9 | [
"Python"
] | 1 | Python | PWN0N/pdf2img | 571501b8f43be73d586914f54453b04f6aeb6097 | 509df095a9f6c7285a37723fcb8d34b75ea96f1b |
refs/heads/main | <repo_name>codesuperr/bot<file_sep>/main.py
#importer le module discord.py
import discord
from discord import *
from discord.utils import get
# ajouter un composant de discord.py
from discord.ext import commands
#cree le bot
bot = commands.Bot(command_prefix="!")
warnings = {}
#detecter quand le bot est pret("allume")
@bot.event
async def on_ready():
print("bot prêt")
await bot.change_presence(status=discord.Status.idle, activity=discord.Game("Je suis un bot"))
#detecter l'emoji python
@bot.event
async def on_raw_reaction_add(payload):
emoji = payload.emoji.name
canal = payload.channel_id
message = payload.message_id
python_role = get(bot.get_guild(payload.guild_id).roles, name="python")
membre = bot.get_guild(payload.guild_id).get_member(payload.user_id)
print(membre)
print(message)
if canal == 835161008829366322 and message == 835196970515431445 and emoji == "python":
print("Grade ajouté !")
await membre.add_roles(python_role)
await membre.send("Tu obtiens le grade python !")
@bot.event
async def on_raw_reaction_add(payload):
emoji = payload.emoji.name # recupere l'emoji
canal = payload.channel_id # recupere le numero du canal
message = payload.message_id # recupere le numero du message
print(message)
id = payload.user_id
guild = payload.guild_id
python_role = get(bot.get_guild(payload.guild_id).roles, name="python")
membre = await bot.get_guild(payload.guild_id).fetch_member(payload.user_id)
# verifier si l'emoji qu'on a ajoutée est "python"
if canal == 835161008829366322 and message == 835196970515431445 and emoji == "python":
await membre.add_roles(python_role)
await membre.send("Tu obtiens le grade python !")
@bot.event
async def on_raw_reaction_remove(payload):
emoji = payload.emoji.name # recupere l'emoji
canal = payload.channel_id # recupere le numero du canal
message = payload.message_id # recupere le numero du message
id = payload.user_id
guild = payload.guild_id
python_role = get(bot.get_guild(payload.guild_id).roles, name="python")
membre = await bot.get_guild(payload.guild_id).fetch_member(payload.user_id)
# verifier si l'emoji qu'on a ajoutée est "python"
if canal == 835161008829366322 and message == 835196970515431445 and emoji == "python":
await membre.remove_roles(python_role)
await membre.send("Tu as perdu le grade python !")
#cree la command !regles
@bot.command()
async def regles(ctx):
await ctx.send("Les regles sont :\n\tI - pas d'insultes\n\tII - pas de double compte\n\tIII - pas de spam")
#cree la command !bienvenu
@bot.command()
async def bienvenu(ctx, nouveau_membre : discord.Member):
#recupere le pseudo
pseudo = nouveau_membre.mention
await ctx.send(f"Bienvenu à {pseudo} sur le serveur TestBotServer! N'esite pas a faire la commande '!regles'")
@bot.command()
@commands.has_role("president ultime")
async def warning(ctx, membre: discord.Member):
pseudo = membre.mention
id = membre.id
# si la personne n'a pas de warning
if id not in warnings:
warnings[id] = 0
print("Le membre n'a aucun avertissement")
warnings[id] += 1
await membre.send(f"vous avez eu un avertissement.\nvous avez eu {warnings[id]} avertssement / 3")
print("ajoute l'avertissement", warnings[id], "/3")
# verifier le nombre d'avertissements
if warnings[id] == 3:
# remet à les warnings
warnings[id] = 0
# message
await membre.send("Vous avez été éjécté du serveur ! trop d'avertissements !")
# ejecter la personne
await membre.kick()
@bot.command()
@commands.has_role("president ultime")
async def betises(ctx, nouveau_membre : discord.Member):
#recupere le pseudo
pseudo = nouveau_membre.mention
await ctx.send(f"tu fais des betises {pseudo} sur le serveur TestBotServer! fait !regles pour afficher les regles")
#verifier l'erreur
@bienvenu.error
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send("vous devez obligatoirement entrer !bienvenu <@pseudo>")
@warning.error
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send("vous devez obligatoirement entrer !warning <@pseudo>")
#donner le jeton pour qu'il se connecte
jeton = "ODM0Nzk1NjcwMDQ0NjcyMDQx.YIGGDQ.XmgAOXIp8jLN4-pCyJhdTNTomQQY"
#phrase
print("lancement du bot...")
#connecter au seveur
bot.run(jeton)
| eaf181ee2a9fad991dddcc83b30d2b0ed92b0b45 | [
"Python"
] | 1 | Python | codesuperr/bot | 571b307383ce35110a752e326ee29ba764f5f130 | 36072a89b3ba2ec51bfd1c3dc58e1669f331a7bd |
refs/heads/master | <file_sep>
[https://www.eff.org/deeplinks/2016/07/new-wordlists-random-passphrases](https://www.eff.org/deeplinks/2016/07/new-wordlists-random-passphrases)
Example passwords
36
MacawGradientUnwittingGoryWishDandy)
22
SwabCrimsonStonyBonus#
56
ZippingZitSubdivideCitricFragranceErgonomicPectinRarity,
54
OutlastLavishDauntingHarmonyHemlockFlammableSulkDucky)
37
DryCaucasianBlatancyAnticsHalvedOgle*
30
MaraudingBasinNeatnessVeteran%
<file_sep>#!/usr/bin/env python3
import secrets
from os import path
rng = secrets.SystemRandom()
S_CHARS = '`~!@#$%^&*()-_+=+?/><,'
def rollDice(dieQty=5):
min = 1
max = 6
num =''
for x in range(dieQty):
n = str(rng.randrange(min, max))
num = num + n
return num
if __name__ == '__main__':
curdir = path.dirname(path.abspath(__file__))
word_dict = {}
with open(curdir + '/eff_large_wordlist.txt','r') as words_list:
for line in words_list:
line = line.split("\t")
word_dict[line[0]] = line[1].strip()
# Number of passwords to generate
for x in range(6):
passw = ''
sCharPresent = False
#this determines the word length
for x in range(rng.randrange(4,10)):
num = rollDice()
rand1 = rng.random()
rand2 = rng.random()
if not sCharPresent:
if rand2 < rand1:
sCharPresent = True
passw = passw + rng.choice(S_CHARS)
passw = passw + word_dict[str(num)].title()
passw = passw + rng.choice(S_CHARS)
print (len(passw))
print (passw)
| c77d1d204137541abe9051ac2010ac02b3d381fc | [
"Markdown",
"Python"
] | 2 | Markdown | Sebohe/password-generator | 2972d39d77f01154194918798ed29411d443be85 | 312a25d3a7c7112f8122bdac2c49043101f58f1f |
refs/heads/master | <repo_name>mfamilia/docker-passenger-app<file_sep>/scripts/build-image.sh
#!/bin/sh
docker build --tag=manuelgfx/docker-passenger-app:latest .
<file_sep>/README.md
== README
Build Image and Tag
docker build --tag=manuelgfx/docker-komo:latest .
<file_sep>/Dockerfile
FROM phusion/passenger-ruby22:0.9.18
USER root
ENV APP_HOME /home/app/
# Set correct environment variables.
ENV HOME $APP_HOME
RUN apt-get update && apt-get install unzip
# install Serf
ADD https://dl.bintray.com/mitchellh/serf/0.6.4_linux_amd64.zip /tmp/serf.zip
RUN unzip /tmp/serf.zip -d /usr/local/bin/
RUN rm /tmp/serf.zip
# add configuration files and handlers for Serf
COPY serf-config /etc/serf
RUN mkdir -p /etc/service/serf/
COPY scripts/serf.run /etc/service/serf/run
RUN chmod 755 /etc/service/serf/run
# Use baseimage-docker's init process.
CMD ["/sbin/my_init"]
# Expose Nginx HTTP service
EXPOSE 80 443 7946 7373
# Start Nginx / Passenger
RUN rm -f /etc/service/nginx/down
# Remove the default site
RUN rm /etc/nginx/sites-enabled/default
ADD configs/rails-env.conf /etc/nginx/main.d/rails-env.conf
ADD configs/postgres-env.conf /etc/nginx/main.d/postgres-env.conf
# Facilitates access when utilizing home mount
RUN usermod -u 1000 -g 50 app
RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
| 5e1f2b5ed773d07163c7c04eb6877719a44f2e84 | [
"Markdown",
"Dockerfile",
"Shell"
] | 3 | Shell | mfamilia/docker-passenger-app | 5f213d85109bd3c217546fd7848234fb644a359e | a438eabcfc012c82e6f626a27ec6fdca6a5120a9 |
refs/heads/master | <file_sep>package com.uzpeng.sign.util;
/**
* @author serverliu on 2018/4/3.
*/
public class SessionStoreKey {
public static final String KEY_AUTH = "AUTH";
public static final String KEY_VERIFY_CODE = "VERIFY_CODE";
}
<file_sep>package com.uzpeng.sign.interceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author serverliu on 2018/4/13.
*/
@Component
public class CrossSiteInterceptor implements HandlerInterceptor{
private static final Logger logger = LoggerFactory.getLogger(CrossSiteInterceptor.class);
@Autowired
private Environment environment;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
logger.info("Method is "+request.getMethod()+" add cross site header!");
response.setHeader("Access-Control-Allow-Origin", environment.getProperty("cross-site.origin"));
response.setHeader("Access-Control-Allow-Methods","POST, PUT, GET, DELETE, OPTIONS");
response.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, authorization," +
"withCredentials, Content-Type, Accept");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Credentials","true");
if(request.getMethod().equals("OPTIONS")){
response.setStatus(200);
return false;
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
<file_sep>package com.uzpeng.sign.web.dto;
/**
* @author uzpeng on 2018/4/17.
*/
public class UpdateTeacherDTO {
}
<file_sep>package com.uzpeng.sign.bo;
import java.util.List;
/**
* @author uzpeng on 2018/4/17.
*/
public class SignRecordTimeListBO {
private List<SignRecordTimeBO> list;
public List<SignRecordTimeBO> getList() {
return list;
}
public void setList(List<SignRecordTimeBO> list) {
this.list = list;
}
}
<file_sep>package com.uzpeng.sign.net;
import com.uzpeng.sign.config.StatusConfig;
import com.uzpeng.sign.bo.SignHttpLinkBO;
import com.uzpeng.sign.net.dto.SignDTO;
import com.uzpeng.sign.util.SerializeUtil;
import com.uzpeng.sign.util.UserMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.security.core.token.Sha512DigestUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
/**
* @author uzpeng on 2018/4/19.
*/
@Component
public class SignWebSocketHandler extends TextWebSocketHandler{
@Autowired
private Environment environment;
private static final Logger logger = LoggerFactory.getLogger(SignWebSocketHandler.class);
private static final Integer DEFAULT_REFRESH_TIME = 15000;
private Timer timer = new Timer();
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
String payload = message.getPayload();
logger.info("handleTextMessage:"+payload);
if(!payload.equals("ACK")){
SignDTO signDTO = SerializeUtil.fromJson(payload, SignDTO.class);
if (signDTO.getStart().equals(StatusConfig.SIGN_START_FLAG)) {
timer = new Timer();
SendSignLinkTask sendSignLinkTask = new SendSignLinkTask(session, signDTO);
logger.info("start construct-sign-link task .....");
timer.schedule(sendSignLinkTask, 0, DEFAULT_REFRESH_TIME);
} else {
logger.info("cancel construct-sign-link task, close websocket session ");
session.close();
}
}
}
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
logger.info("afterConnectionEstablished");
super.afterConnectionEstablished(session);
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
logger.info("afterConnectionClosed");
timer.cancel();
UserMap.removeToken(UserMap.getSignId(session.getId()));
UserMap.removeSignId(session.getId());
super.afterConnectionClosed(session, status);
}
private void constructSignLink(WebSocketSession session, SignDTO signDTO) throws Exception{
String randomStr = UUID.randomUUID().toString();
String sourceStr = randomStr+signDTO.getSignId()+signDTO.getCourseId();
String token = new String(Base64.getEncoder().encode(Sha512DigestUtils.sha(sourceStr)), "utf-8");
String encodedToken = URLEncoder.encode(token,"utf8");
String url = environment.getProperty("link.host") + "/v1/student/sign?token="+encodedToken;
logger.info("token is "+token+", url:"+url);
SignHttpLinkBO signHttpLinkBO = new SignHttpLinkBO();
signHttpLinkBO.setLink(url);
UserMap.putToken(signDTO.getSignId(), token);
UserMap.putSignId(session.getId(), signDTO.getSignId());
session.sendMessage(new TextMessage(SerializeUtil.toJson(signHttpLinkBO, SignHttpLinkBO.class)));
}
private class SendSignLinkTask extends TimerTask{
private WebSocketSession session;
private SignDTO signDTO;
private SendSignLinkTask(WebSocketSession session, SignDTO signDTO) {
this.signDTO = signDTO;
this.session = session;
}
@Override
public void run(){
try {
constructSignLink(session, signDTO);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
<file_sep>package com.uzpeng.sign.service;
import com.uzpeng.sign.config.EmailConfig;
import com.uzpeng.sign.dao.UserDAO;
import com.uzpeng.sign.domain.RoleDO;
import com.uzpeng.sign.domain.UserDO;
import com.uzpeng.sign.util.ObjectTranslateUtil;
import com.uzpeng.sign.util.ThreadPool;
import com.uzpeng.sign.web.dto.LoginDTO;
import com.uzpeng.sign.web.dto.RegisterDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @author serverliu on 2018/3/29.
*/
@Service
public class UserService {
@Autowired
private UserDAO userDAO;
@Autowired
private EmailConfig emailConfig;
public void registerNewUser(RegisterDTO registerDTO){
userDAO.insertUser(ObjectTranslateUtil.registerDTOToUserDO(registerDTO));
}
public Integer loginCheck(LoginDTO loginDTO){
return userDAO.checkUserAndPassword(loginDTO.getUsername(), loginDTO.getPassword());
}
public boolean checkEmailAddress(String email){
return userDAO.checkEmailValid(email);
}
public void sendVerifyCodeByEmail(String email, String code){
System.out.println("email:"+email+",verify code:"+code);
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setText(code);
simpleMailMessage.setTo(email);
simpleMailMessage.setFrom(emailConfig.getFrom());
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setPort(Integer.parseInt(emailConfig.getPort()));
mailSender.setHost(emailConfig.getHost());
mailSender.setUsername(emailConfig.getUserName());
mailSender.setPassword(emailConfig.getPassword());
//todo
ThreadPool.run(()-> mailSender.send(simpleMailMessage));
}
public RoleDO getRole(int id){
return userDAO.getRole(id);
}
public UserDO getUserInfo(String id){
return userDAO.getUserInfo(Integer.parseInt(id));
}
public void updatePassword(Integer id, String newPassword){
userDAO.updatePassword(id , newPassword);
}
public UserDO getUserByOpenId(String openId, String oldPassword){
return userDAO.getUserByOpenId(openId, oldPassword);
}
}
<file_sep>package com.uzpeng.sign.bo;
/**
* @author uzpeng on 2018/4/19.
*/
public class SignWebSocketLinkBO {
private String websocketLink;
public String getLink() {
return websocketLink;
}
public void setLink(String link) {
this.websocketLink = link;
}
}
<file_sep>## 介绍
使用spring+spring mvc+mybatis搭建的签到管理系统及其管理系统的服务端。
<file_sep>package com.uzpeng.sign.web.dto;
/**
* @author serverliu on 2018/4/11.
*/
public class StudentDTO {
private String courseId;
private String name;
private String classInfo;
private String num;
public String getCourseId() {
return courseId;
}
public void setCourseId(String courseId) {
this.courseId = courseId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassInfo() {
return classInfo;
}
public void setClassInfo(String classInfo) {
this.classInfo = classInfo;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
}
<file_sep>package com.uzpeng.sign.bo;
import java.util.List;
/**
* @author serverliu on 2018/4/12.
*/
public class CourseListBO {
private List<CourseBO> currentCourseList;
private List<CourseBO> historyCourseList;
public List<CourseBO> getHistoryCourseList() {
return historyCourseList;
}
public void setHistoryCourseList(List<CourseBO> historyCourseList) {
this.historyCourseList = historyCourseList;
}
public List<CourseBO> getCurrentCourseList() {
return currentCourseList;
}
public void setCurrentCourseList(List<CourseBO> currentCourseList) {
this.currentCourseList = currentCourseList;
}
}
<file_sep>package com.uzpeng.sign.domain;
import java.time.LocalDateTime;
/**
* @author uzpeng on 2018/4/17.
*/
public class SignDO {
private Integer id;
private LocalDateTime create_time;
private Integer course_time_id;
private Integer course_id;
private Integer week;
private Integer state;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCourseId() {
return course_id;
}
public void setCourseId(Integer courseId) {
this.course_id = courseId;
}
public LocalDateTime getCreateTime() {
return create_time;
}
public void setCreateTime(LocalDateTime createTime) {
this.create_time = createTime;
}
public Integer getCourseTimeId() {
return course_time_id;
}
public void setCourseTimeId(Integer courseTimeId) {
this.course_time_id = courseTimeId;
}
public Integer getWeek() {
return week;
}
public void setWeek(Integer week) {
this.week = week;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
}
<file_sep>package com.uzpeng.sign.domain;
import java.time.LocalDateTime;
/**
* @author serverliu on 2018/4/10.
*/
public class SemesterDO {
private Integer id;
private Integer teacher_id;
private String name;
private LocalDateTime start_time;
private LocalDateTime end_time;
public Integer getTeacherId() {
return teacher_id;
}
public void setTeacherId(Integer teacher_id) {
this.teacher_id = teacher_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public LocalDateTime getStartTime() {
return start_time;
}
public void setStartTime(LocalDateTime start_time) {
this.start_time = start_time;
}
public LocalDateTime getEndTime() {
return end_time;
}
public void setEndTime(LocalDateTime end_time) {
this.end_time = end_time;
}
}
<file_sep>package com.uzpeng.sign.service;
import com.uzpeng.sign.dao.TeacherDAO;
import com.uzpeng.sign.domain.TeacherDO;
import com.uzpeng.sign.util.ObjectTranslateUtil;
import com.uzpeng.sign.web.dto.TeacherDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author serverliu on 2018/4/10.
*/
@Service
public class TeacherService {
@Autowired
private TeacherDAO teacherDAO;
public void addTeacher(TeacherDTO teacherDTO){
teacherDAO.addTeacher(ObjectTranslateUtil.teacherDTOToTeacherDO(teacherDTO));
}
public void updateTeacher(TeacherDO teacherDO){
}
}
<file_sep>package com.uzpeng.sign.domain;
/**
* @author serverliu on 2018/4/10.
*/
public class TeacherDO {
private Integer id;
private String name;
private Integer card_num;
private String tel_number;
private String office_hour;
private String office_loc;
private String note;
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 getCardNum() {
return card_num;
}
public void setCardNum(Integer cardNum) {
this.card_num = cardNum;
}
public String getTelNumber() {
return tel_number;
}
public void setTelNumber(String telNumber) {
this.tel_number = telNumber;
}
public String getOfficeHour() {
return office_hour;
}
public void setOfficeHour(String officeHour) {
this.office_hour = officeHour;
}
public String getOfficeLoc() {
return office_loc;
}
public void setOfficeLoc(String officeLoc) {
this.office_loc = officeLoc;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
<file_sep>package com.uzpeng.sign.util;
import com.uzpeng.sign.config.StatusConfig;
import com.uzpeng.sign.domain.SignRecordDO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* @author serverliu on 2018/4/10.
*/
public class StatisticsTool {
private static final Logger logger = LoggerFactory.getLogger(StatisticsTool.class);
private static final double MIN_VALUE=0.01;
public static void pickAbnormalPoint(CopyOnWriteArrayList<SignRecordDO> records){
List<Double> longitude = new ArrayList<>();
List<Double> latitude = new ArrayList<>();
for (SignRecordDO c :
records) {
longitude.add(c.getLongitude());
latitude.add(c.getLatitude());
}
double longitudeMean = getMean(longitude);
double longitudeSD = getSD(longitude, longitudeMean);
double latitudeMean = getMean(latitude);
double latitudeSD = getSD(latitude, latitudeMean);
logger.debug("longitudeMean: "+longitudeMean+",longitudeSD: "+longitudeSD+" latitudeMean:"+latitudeMean+
",latitudeSD"+latitudeSD);
int size = records.size();
ArrayList<Double> probabilities = new ArrayList<>();
for (SignRecordDO record : records) {
double x = getNormalDistributionProbabilityDestiny(record.getLongitude(), longitudeMean, longitudeSD);
double y = getNormalDistributionProbabilityDestiny(record.getLatitude(), latitudeMean, latitudeSD);
logger.debug("x: "+x+",y: "+y);
probabilities.add(x * y);
}
for (int i = 0; i < records.size(); i++) {
SignRecordDO record = records.get(i);
double probability = probabilities.get(i);
int result = probability > MIN_VALUE ? StatusConfig.RECORD_SUCCESS : StatusConfig.RECORD_FAILED;
logger.debug("probability: "+probability+",signId is "+record.getId()+" result:"+result);
record.setState(result);
}
}
private static double getMean(List<Double> data){
CopyOnWriteArrayList<Double> safeData = new CopyOnWriteArrayList<>();
safeData.addAll(data);
double result = 0;
for (Double d : safeData) {
result += d;
}
return result / data.size();
}
private static double getSD(List<Double> data){
return getSD(data, getMean(data));
}
private static double getSD(List<Double> data, double mean){
CopyOnWriteArrayList<Double> safeData = new CopyOnWriteArrayList<>();
safeData.addAll(data);
int size = data.size();
double result = 0;
for (Double d : safeData) {
result += Math.pow((d - mean), 2);
}
return Math.sqrt(result / size);
}
private static double getNormalDistributionProbabilityDestiny(double data, double mean, double sd){
double base = 1 / (Math.sqrt(2 * Math.PI * sd));
double exponent = - ((Math.pow((data - mean), 2)) / (2 * Math.pow(sd, 2)));
return Math.pow(base, exponent);
}
}
<file_sep>package com.uzpeng.sign.web;
import com.uzpeng.sign.config.StatusConfig;
import com.uzpeng.sign.bo.CourseBO;
import com.uzpeng.sign.bo.CourseListBO;
import com.uzpeng.sign.bo.CourseTimeListBO;
import com.uzpeng.sign.domain.UserDO;
import com.uzpeng.sign.service.CourseService;
import com.uzpeng.sign.support.SessionAttribute;
import com.uzpeng.sign.util.*;
import com.uzpeng.sign.web.dto.CourseDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.URLDecoder;
/**
* @author serverliu on 2018/4/11.
*/
@Controller
public class CourseController {
@Autowired
private CourseService courseService;
@Autowired
private Environment env;
@RequestMapping(value = "/v1/course", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
@ResponseBody
public String addCourse(HttpServletRequest request, HttpSession session, HttpServletResponse response){
try {
SessionAttribute auth = (SessionAttribute) session.getAttribute(SessionStoreKey.KEY_AUTH);
UserDO role = UserMap.getUser((String)auth.getObj());
if(role != null && role.getRole().equals(Role.TEACHER)) {
BufferedReader reader = request.getReader();
String json = SerializeUtil.readStringFromReader(reader);
CourseDTO courseDTO = SerializeUtil.fromJson(json, CourseDTO.class);
courseDTO.setTeacherId(role.getRoleId());
courseService.addCourse(courseDTO);
return CommonResponseHandler.handleResponse(StatusConfig.SUCCESS,
env.getProperty("status.success"), env.getProperty("link.host"));
} else {
return CommonResponseHandler.handleNoAuthentication(response);
}
} catch (IOException e) {
e.printStackTrace();
return CommonResponseHandler.handleException(response);
}
}
@RequestMapping(value = "/v1/course", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
@ResponseBody
public String getCourse(HttpServletRequest request, HttpSession session, HttpServletResponse response){
try {
SessionAttribute auth = (SessionAttribute) session.getAttribute(SessionStoreKey.KEY_AUTH);
UserDO role = UserMap.getUser((String)auth.getObj());
if(role != null && role.getRole().equals(Role.TEACHER)) {
String courseName = request.getParameter("name");
if(courseName != null){
String decodeCourseName = URLDecoder.decode(courseName, "utf-8");
CourseListBO courseListBO = courseService.getCourseByName(decodeCourseName);
return CommonResponseHandler.handleResponse(courseListBO, CourseListBO.class);
}else {
BufferedReader reader = request.getReader();
CourseListBO courseListBO = courseService.getCourse(role.getRoleId());
return CommonResponseHandler.handleResponse(courseListBO, CourseListBO.class);
}
} else {
return CommonResponseHandler.handleNoAuthentication(response);
}
} catch (IOException e) {
e.printStackTrace();
return CommonResponseHandler.handleException(response);
}
}
@RequestMapping(value = "/v1/course/{id}", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
@ResponseBody
public String getCourseById(@PathVariable("id")String id, HttpServletRequest request, HttpSession session,
HttpServletResponse response){
try {
SessionAttribute auth = (SessionAttribute) session.getAttribute(SessionStoreKey.KEY_AUTH);
UserDO role = UserMap.getUser((String)auth.getObj());
if(role != null && role.getRole().equals(Role.TEACHER)) {
BufferedReader reader = request.getReader();
Integer courseId = Integer.parseInt(id);
CourseBO courseBO = courseService.getCourseById(courseId);
return CommonResponseHandler.handleResponse(courseBO, CourseBO.class);
} else {
return CommonResponseHandler.handleNoAuthentication(response);
}
} catch (IOException e) {
e.printStackTrace();
return CommonResponseHandler.handleException(response);
}
}
@RequestMapping(value = "/v1/course/{id}", method = RequestMethod.DELETE, produces = "application/json;charset=utf-8")
@ResponseBody
public String deleteCourseById(@PathVariable("id")String id, HttpServletRequest request, HttpSession session,
HttpServletResponse response){
try {
SessionAttribute auth = (SessionAttribute) session.getAttribute(SessionStoreKey.KEY_AUTH);
UserDO role = UserMap.getUser((String)auth.getObj());
if(role != null && role.getRole().equals(Role.TEACHER)) {
courseService.deleteCourseById(Integer.parseInt(id));
return CommonResponseHandler.handleResponse(StatusConfig.SUCCESS,
env.getProperty("status.success"), env.getProperty("link.login"));
} else {
return CommonResponseHandler.handleNoAuthentication(response);
}
} catch (Exception e) {
e.printStackTrace();
return CommonResponseHandler.handleException(response);
}
}
@RequestMapping(value = "/v1/course/{id}", method = RequestMethod.PUT, produces = "application/json;charset=utf-8")
@ResponseBody
public String updateCourseById(@PathVariable("id")String id, HttpServletRequest request, HttpSession session,
HttpServletResponse response){
try {
SessionAttribute auth = (SessionAttribute) session.getAttribute(SessionStoreKey.KEY_AUTH);
UserDO role = UserMap.getUser((String)auth.getObj());
if(role != null && role.getRole().equals(Role.TEACHER)) {
BufferedReader reader = request.getReader();
String json = SerializeUtil.readStringFromReader(reader);
CourseDTO courseDTO = SerializeUtil.fromJson(json, CourseDTO.class);
courseDTO.setCourseId(id);
courseDTO.setTeacherId(role.getRoleId());
courseService.updateCourse(courseDTO);
return CommonResponseHandler.handleResponse(StatusConfig.SUCCESS,
env.getProperty("status.success"), env.getProperty("link.doc"));
} else {
return CommonResponseHandler.handleNoAuthentication(response);
}
} catch (Exception e) {
e.printStackTrace();
response.setStatus(500);
return CommonResponseHandler.handleException(response);
}
}
@RequestMapping(value = "/v1/course/{id}/time", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
@ResponseBody
public String getCourseTimeById(@PathVariable("id")String id, HttpServletRequest request, HttpSession session,
HttpServletResponse response){
try {
SessionAttribute auth = (SessionAttribute) session.getAttribute(SessionStoreKey.KEY_AUTH);
UserDO role = UserMap.getUser((String)auth.getObj());
if(role != null && role.getRole().equals(Role.TEACHER)) {
Integer courseId = Integer.parseInt(id);
CourseTimeListBO courseTimeListBO = courseService.getCourTimeById(courseId);
return CommonResponseHandler.handleResponse(courseTimeListBO, CourseTimeListBO.class);
} else {
return CommonResponseHandler.handleNoAuthentication(response);
}
} catch (Exception e) {
e.printStackTrace();
return CommonResponseHandler.handleException(response);
}
}
}
<file_sep>package com.uzpeng.sign.service;
import com.uzpeng.sign.bo.CourseBO;
import com.uzpeng.sign.bo.CourseListBO;
import com.uzpeng.sign.bo.CourseTimeBO;
import com.uzpeng.sign.bo.CourseTimeListBO;
import com.uzpeng.sign.dao.CourseDAO;
import com.uzpeng.sign.dao.CourseTimeDAO;
import com.uzpeng.sign.dao.SignDAO;
import com.uzpeng.sign.domain.CourseTimeDO;
import com.uzpeng.sign.util.ObjectTranslateUtil;
import com.uzpeng.sign.web.dto.CourseDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
* @author serverliu on 2018/4/11.
*/
@Service
public class CourseService {
@Autowired
private CourseDAO courseDAO;
@Autowired
private CourseTimeDAO courseTimeDAO;
@Autowired
private SignDAO signDAO;
public void addCourse(CourseDTO courseDTO){
int courseId = courseDAO.addCourse(ObjectTranslateUtil.courseDTOToCourseDO(courseDTO));
courseTimeDAO.addCourseTimeList(ObjectTranslateUtil.courseDTOToCourseTimeDO(courseDTO, courseId));
}
public CourseListBO getCourse(Integer teacherId){
return courseDAO.getCourseList(teacherId);
}
public CourseBO getCourseById(Integer courseId){
return courseDAO.getCourseById(courseId);
}
public CourseListBO getCourseByName(String name){
return courseDAO.getCourseByName(name);
}
public void deleteCourseById(Integer id){
courseDAO.deleteCourseById(id);
}
public void updateCourse(CourseDTO courseDTO){
Integer courseId = Integer.parseInt(courseDTO.getCourseId());
List<CourseTimeDO> courseTimeDOs = ObjectTranslateUtil.courseDTOToCourseTimeDO(courseDTO, courseId);
boolean isExistSignRecord = signDAO.checkIsExistRecordByCourseId(courseId);
if(isExistSignRecord){
courseTimeDAO.updateCourseTimeList(courseId);
} else {
courseTimeDAO.deleteCourseTime(courseId);
}
courseTimeDAO.addCourseTimeList(courseTimeDOs);
courseDAO.updateCourse(courseDTO);
}
public CourseTimeListBO getCourTimeById(Integer courseId){
CourseBO courseBO = courseDAO.getCourseById(courseId);
List<CourseTimeDO> courseTimeDOs = courseTimeDAO.getCourseTimeByCourseId(courseId);
List<CourseTimeBO> courseTimeBOs = new ArrayList<>();
for (CourseTimeDO courseTimeDO :
courseTimeDOs) {
courseTimeBOs.add(ObjectTranslateUtil.courseTimeDOToCourseTimeBO(courseTimeDO));
}
CourseTimeListBO courseTimeListBO = new CourseTimeListBO();
courseTimeListBO.setList(courseTimeBOs);
courseTimeListBO.setStartWeek(courseBO.getStartWeek());
courseTimeListBO.setEndWeek(courseBO.getEndWeek());
return courseTimeListBO;
}
}
| 83412b709c3d86077185904d69d128466ee436d4 | [
"Markdown",
"Java"
] | 17 | Java | UZPENG/Sign-Server | e2340a9a22b245739d4f8e9deae15847da81afe5 | c7ef6e667a0c41b04cdca6f4c270038b33c174e8 |
refs/heads/master | <repo_name>zhouqiang-cl/chaos-mesh<file_sep>/ui/src/components/NewExperiment/constants.ts
import { Experiment } from './types'
import * as Yup from 'yup'
export const defaultExperimentSchema: Experiment = {
name: '',
namespace: 'default',
scope: {
namespace_selectors: ['default'],
label_selectors: [],
annotation_selectors: [],
phase_selectors: ['all'],
mode: 'one',
value: '',
},
target: {
kind: 'PodChaos',
pod_chaos: {
action: '',
container_name: '',
},
network_chaos: {
action: '',
bandwidth: {
buffer: 0,
limit: 0,
minburst: 0,
peakrate: 0,
rate: '',
},
corrupt: {
correlation: '',
corrupt: '',
},
delay: {
correlation: '',
jitter: '',
latency: '',
},
duplicate: {
correlation: '',
duplicate: '',
},
loss: {
correlation: '',
loss: '',
},
},
},
scheduler: {
cron: '',
duration: '',
},
}
export const validationSchema = Yup.object().shape({
name: Yup.string().required(),
})
<file_sep>/MAINTAINERS.md
# Maintainers
This file lists the initial committers, and hence the maintainers of the Chaos Mesh project.
In short, maintainers are people who are in charge of the maintenance of the Chaos Mesh project. This includes everything from day-to-day tasks such as issue triage to completing epics. Maintainers should be the first point of contact for security issues or other critical issues that require privacy not offered by the issue tracker.
The maintainers of Chaos Mesh, along with their email and focus area, are listed below:
Name | Email | Focus
----|---|---
[<NAME>](https://github.com/siddontang) | [<EMAIL>](mailto:<EMAIL>) | Project Lead
[<NAME>](https://github.com/zhouqiang-cl) | [<EMAIL>](mailto:<EMAIL>) | Project Lead
[CWen](https://github.com/cwen0) | [<EMAIL>](mailto:<EMAIL>) | Operator, Dashboard
[YangKeao](https://github.com/YangKeao) | [<EMAIL>](mailto:<EMAIL>) | Operator, Dashboard
[Yisaer](https://github.com/Yisaer) | [<EMAIL>](mailto:<EMAIL>) | Operator
<file_sep>/ui/src/components/NewExperiment/types.ts
import { FormikContextType } from 'formik'
export interface ExperimentBasic {
name: string
namespace: string
}
export interface ExperimentScope {
namespace_selectors: string[]
label_selectors: object | string[]
annotation_selectors: object | string[]
phase_selectors: string[]
mode: string
value: string
}
export interface ExperimentTargetPod {
action: string
container_name?: string
}
export interface ExperimentTargetNetworkBandwidth {
buffer: number
limit: number
minburst: number
peakrate: number
rate: string
}
export interface ExperimentTargetNetworkCorrupt {
correlation: string
corrupt: string
}
export interface ExperimentTargetNetworkDelay {
latency: string
correlation: string
jitter: string
}
export interface ExperimentTargetNetworkDuplicate {
correlation: string
duplicate: string
}
export interface ExperimentTargetNetworkLoss {
correlation: string
loss: string
}
export interface ExperimentTargetNetwork {
action: string
bandwidth: ExperimentTargetNetworkBandwidth
corrupt: ExperimentTargetNetworkCorrupt
delay: ExperimentTargetNetworkDelay
duplicate: ExperimentTargetNetworkDuplicate
loss: ExperimentTargetNetworkLoss
}
export interface ExperimentTarget {
kind: string
pod_chaos: ExperimentTargetPod
network_chaos: ExperimentTargetNetwork
io_chaos?: any
kernel_chaos?: any
time_chaos?: any
stress_chaos?: any
}
export interface ExperimentSchedule {
cron: string
duration: string
}
export interface Experiment extends ExperimentBasic {
scope: ExperimentScope
target: ExperimentTarget
scheduler: ExperimentSchedule
}
export interface StepperState {
activeStep: number
}
export enum StepperType {
NEXT = 'NEXT',
BACK = 'BACK',
JUMP = 'JUMP',
RESET = 'RESET',
}
export type StepperAction = {
type: StepperType
payload?: number
}
type StepperDispatch = (action: StepperAction) => void
export interface StepperContextProps {
state: StepperState
dispatch: StepperDispatch
}
export type FormikCtx = FormikContextType<Experiment>
export type StepperFormTargetProps = FormikCtx & {
handleActionChange: (e: React.ChangeEvent<any>) => void
}
<file_sep>/ui/src/lib/utils.ts
export function upperFirst(s: string) {
if (!s) return ''
return s.charAt(0).toUpperCase() + s.slice(1)
}
export function joinObjKVs(obj: { [key: string]: string[] }, separator: string) {
return Object.entries(obj).reduce(
(acc: string[], [key, val]) => acc.concat(val.map((d) => `${key}${separator}${d}`)),
[]
)
}
<file_sep>/ui/src/components/FormField/index.ts
export { default as SelectField } from './SelectField'
export { default as TextField } from './TextField'
| 91816d1ef000b9f76cf81cd3a5d10f1ced59e7ac | [
"Markdown",
"TypeScript"
] | 5 | TypeScript | zhouqiang-cl/chaos-mesh | 9cc9c66790b7b180dbbf1d6736bf401983cbacff | 16df9c28f935b80e34632404ced52ecaeebac9e9 |
refs/heads/master | <repo_name>skywalker1578/Spaceship-Game<file_sep>/README.md
# Spaceship-Game
<file_sep>/spacegame.py
'''
소스코드는 '박쌤과 함께 다양한 예제로 배우는 완전 쉬운 파이썬 3'책의 예제 부분을 일부 참고했습니다
http://www.atio.co.kr/bbs/download.php?bo_table=sub0301&wr_id=32&no=0
'''
import random
import time
import pygame
pygame.init()
fpsClock = pygame.time.Clock()
pygame.display.set_caption('Avoid Asteroids')
asteroidtimer = 10
asteroids = [[20, 0, 0]]
screen_width = 1280
screen_heigth = 720
screen = pygame.display.set_mode((screen_width, screen_heigth))
spaceshipimg = pygame.image.load('./img/spaceship.png')
asteroid0 = pygame.image.load('./img/asteroid00.png')
asteroid1 = pygame.image.load('./img/asteroid01.png')
asteroid2 = pygame.image.load('./img/asteroid02.png')
asteroidimgs = (asteroid0,asteroid1,asteroid2)
gameover = pygame.image.load('./img/gameover.jpg')
background = pygame.image.load('./img/background.jpg')
getbackground = pygame.image.load('./img/getbackground.jpg')
backgroundmusic = pygame.mixer.Sound('./audio/backgroundmusic.wav')
boomsound = pygame.mixer.Sound('./audio/boom.wav')
def text(arg, x, y, size):
font = pygame.font.Font(None, size)
text = font.render('Score: ' + str(arg).zfill(6), True, (0,0,0))
textRect = text.get_rect()
textRect.centerx = x
textRect.centery = y
screen.blit(text, textRect)
def high(arg, x, y, size):
font = pygame.font.Font(None, size)
text = font.render('High: ' + str(arg).zfill(6), True, (0,0,0))
textRect = text.get_rect()
textRect.centerx = x
textRect.centery = y
screen.blit(text, textRect)
def music(x, y, size):
font = pygame.font.Font(None, size)
text = font.render('>> TheFatRat - Unity'.zfill(6), True, (0,0,0))
textRect = text.get_rect()
textRect.centerx = x
textRect.centery = y
screen.blit(text, textRect)
def gethighscore(size, color):
font = pygame.font.Font(None, size)
text = font.render('HighScore!!!'.zfill(6), True, color)
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery
screen.blit(text, textRect)
def gameoverscreen():
high(highscore, 1125, 50, 60)
text(score, 1115, 110, 60)
while 1:
score = 0
FPS = 60
try:
with open('./highscore.txt', 'r') as f:
pass
except:
with open('./highscore.txt', 'w') as f:
f.write('0')
finally:
try:
with open('./highscore.txt', 'r') as f:
highscore = int(f.readline())
except:
with open('./highscore.txt', 'w') as f:
f.write('0')
finally:
with open('./highscore.txt', 'r') as f:
highscore = int(f.readline())
backgroundmusic.play()
background1_y = 0
background2_y = -screen_heigth
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
exit(0)
background1_y += 1
background2_y += 1
if background1_y == screen_heigth:
background1_y = -screen_heigth
if background2_y == screen_heigth:
background2_y = -screen_heigth
screen.blit(background, (0, background1_y))
screen.blit(background, (0, background2_y))
music(1218, 5, 18)
text(score, 780, 20, 30)
high(highscore, 500, 20, 30)
position = pygame.mouse.get_pos()
spaceshippos = (position[0], position[1])
screen.blit(spaceshipimg, spaceshippos)
spaceshiprect = pygame.Rect(spaceshipimg.get_rect())
spaceshiprect.left = spaceshippos[0]
spaceshiprect.top = spaceshippos[1]
asteroidtimer -= 40
if asteroidtimer <= 0:
asteroids.append([random.randint(5, 1275), 0, random.randint(0, 2)])
asteroidtimer = random.randint(50, 200)
index = 0
for stone in asteroids:
stone[1] += 20
if stone[1] > 720:
asteroids.pop(index)
score += 1
stonerect = pygame.Rect(asteroidimgs[stone[2]].get_rect())
stonerect.left = stone[0]
stonerect.top = stone[1]
if stonerect.colliderect(spaceshiprect):
backgroundmusic.stop()
boomsound.play()
asteroids.pop(index)
run = False
screen.blit(asteroidimgs[stone[2]], (stone[0], stone[1]))
index += 1
fpsClock.tick(FPS)
pygame.display.flip()
sleep = 1.4
hightof = False
with open('./highscore.txt', 'r') as f:
line = f.readline()
if int(line) < score:
highscore = score
with open('./highscore.txt', 'w') as f:
f.write(str(score))
hightof = True
screen.blit(gameover, (0, 0))
gameoverscreen()
if hightof:
screen.blit(getbackground, (0, screen.get_rect().centery-150))
gethighscore(300, (255,0,0))
sleep = 2.5
pygame.display.flip()
asteroids.clear()
key_event = pygame.key.get_pressed()
time.sleep(sleep)
boomsound.stop()
| 82feac4718c7dd47c949713dc0114305e7890b85 | [
"Markdown",
"Python"
] | 2 | Markdown | skywalker1578/Spaceship-Game | 04290ee51938db8a40d24c72711594d4c8410aaa | e9d55487a1575c03c25a3bdf70905f2e5607444f |
refs/heads/master | <repo_name>Allison-Northrop/standalone-exercises<file_sep>/grocery_store/lib/aisle.rb
AISLE = []
module StockManager
class Aisle
attr_reader :catagory :products_in_aisle
def initialize(category)
@category = category.upcase
@products_in_aisle = []
end
def self.all
return AISLE
end
def self.find(aisle_name)
AISLE.each do |aisle|
if aisle.category == aisle_name
return aisle
end
end
end
end
end
<file_sep>/grocery_store/lib/product.rb
PRODUCTS = []
module StockManager
class Product
attr_accessor :name, :unit_size, :market_price, :discount_price, :description
def initialize(name, unit_size, market_price, discount_price, description)
@name = name.upcase.to_s
@unit_size = unit_size.to_s
@market_price = market_price.to_f
@discount_price = discount_price.to_f
@description = description.to_f
end
def self.all
return PRODUCTS
# all_products = []
# PRODUCTS.each do |product|
# puts product.name
# # name = product[0].to_s
# # unit_size = product[1].to_s
# # market_price = product[2].to_f
# # discount_price = product[3].to_f
# # description = product[4].to_s
# # a_product = StockManager::Product.new(name, unit_size, market_price, discount_price, description)
# # all_products << a_product
# end
# # return all_products
end
def self.find(product_name)
all_products = StockManager::Product.all
all_products.each do |product|
if product.name == product_name.upcase
print product
return product
end
end
end
def discounted?
#contains logic if it's discounted
end
end
end
a = StockManager::Product.new("Alfalfa", "9 pounds", 1.90, 1, "kind of like hay")
# puts a.name
# puts a.unit_size
# puts a.market_price
# puts a.description
b = StockManager::Product.new("Rice", "1 pound", 3.00, 2, "it's great in sushi")
# puts b.market_price
#
c = StockManager::Product.new("bread", "9 pounds", 9.0, 33, "it's bread!")
# puts b.market_price + a.market_price
#
# puts a.discount_price
# puts b.discount_price
# puts a.discount_price + b.discount_price
PRODUCTS << a
PRODUCTS << b
PRODUCTS << c
# puts StockManager::Product.all
StockManager::Product.find("rice")
<file_sep>/grocery_store/specs/product_spec.rb
require_relative 'spec_helper'
describe "product class" do
it "should create an instance of product" do
new_product = StockManager::Product.new("Alfalfa", "9 pounds", 1.90, 1, "kind of like hay")
new_product.must_be_instance_of Object
end
end
| edbe7f25ba8b18d51f6739e6fae2ff871e7e57d5 | [
"Ruby"
] | 3 | Ruby | Allison-Northrop/standalone-exercises | 8dc48225a7a2003096ebdc9d507f4f929614e02a | 00927faffd91ccacb4cb8cf03d86b3de361e22ed |
refs/heads/master | <file_sep>print("Hello World)
print("Do you like cats?") | 688b83e70d9259765456cb0a192fe4a6a3cd10b4 | [
"Python"
] | 1 | Python | rebeccauranga/rainy-day-git | aa176e0c822c60f8f03e6c5729b8c2f576371e9d | 051638d596c37df7b60af613e6453316fe19363a |
refs/heads/master | <file_sep>// abstract class for data structures
#ifndef STRUCTURE_H
#define STRUCTURE_H
class Structure {
public:
virtual void draw(const Cairo::RefPtr<Cairo::Context> & cr)=0;
};
#endif // STRUCTURE_H
<file_sep>#include "visualize.h"
#include "array.h"
#include <cairomm/context.h>
#include <iostream>
const int Array::field_w = 50;
const int Array::field_h = 20;
const int Array::init_size = 10;
Array::Array() {
x = 50;
y = 50;
size = init_size;
array = new int[size];
n = 0;
horizontal = true;
}
Array::Array(int size) {
x = 50;
y = 50;
this->size = size;
array = new int[size];
n = 0;
horizontal = true;
}
Array::~Array() {
}
void Array::draw(const Cairo::RefPtr<Cairo::Context> & cr) {
// set up variables to increment while printing
int x_pos = x;
int y_pos = y;
int * coord;
int x_increment;
int y_increment;
if (horizontal) {
x_increment = field_w;
y_increment = 0;
} else {
x_increment = 0;
y_increment = field_h;
}
// print array pointing to the array
// make sure they did not insert too many items
Pango::FontDescription font;
font.set_family("Monospace");
font.set_weight(Pango::WEIGHT_BOLD);
Glib::RefPtr<Pango::Layout> layout;
int text_w, text_h;
int i;
char * str = new char[10];
for (int i = 0; i < n && i < size; i++) {
// print the elements
//*coord += *increment
sprintf(str, "%d", array[i]);
// print the background of the element
cr->set_source_rgb(1.0, 1.0, 1.0);
cr->rectangle(x_pos, y_pos, field_w, field_h);
cr->fill();
// print the outside of the element
cr->set_source_rgb(0.0, 0.0, 0.0);
cr->set_line_width(2.0);
cr->rectangle(x_pos, y_pos, field_w, field_h);
cr->stroke();
// print the value of the element
layout = create_pango_layout(str);
layout->set_font_description(font);
layout->get_pixel_size(text_w, text_h);
cr->move_to(x_pos + (field_w - text_w) / 2, y + (field_h - text_h) / 2);
layout->show_in_cairo_context(cr);
// increment to the next element
x_pos += x_increment;
y_pos += y_increment;
}
for (i = n; i < size; i++) {
// print blank elemetns
//*coord += *increment
// print the background of the element
cr->set_source_rgb(0.5, 0.5, 0.5);
cr->rectangle(x_pos, y_pos, field_w, field_h);
cr->fill();
// print the outside of the element
cr->set_source_rgb(0.0, 0.0, 0.0);
cr->set_line_width(2.0);
cr->rectangle(x_pos, y_pos, field_w, field_h);
cr->stroke();
// print the value of the element
layout = create_pango_layout("");
layout->set_font_description(font);
layout->get_pixel_size(text_w, text_h);
cr->move_to(x_pos + (field_w - text_w) / 2, y + (field_h - text_h) / 2);
layout->show_in_cairo_context(cr);
// increment to the next element
x_pos += x_increment;
y_pos += y_increment;
}
}
<file_sep>#include "visualize.h"
#include "dlist.h"
#include <cairomm/context.h>
#include <iostream>
#define ARROW_OFFSET 10
DList::DList() {
tail = NULL;
}
DList::~DList() {
}
void DList::arrange_nodes() {
DListNode * n = dynamic_cast <DListNode *> (head);
int xTmp = list_x;
int yTmp = list_y;
while (n != NULL) {
// check that if the node has neighbors that they point to n correctly
if ((!n->next || !n->next->prev || n->next->prev == n) && ((!n->prev && n == dynamic_cast <DListNode *> (head)) || (n->prev && (!n->prev->next || n->prev->next == n)))) {
xTmp += ListNode::padding;
n->x = xTmp;
n->y = yTmp;
n = n->next;
}
}
tail_x = xTmp + ListNode::padding;
}
void DList::draw_connected(const Cairo::RefPtr<Cairo::Context> & cr) {
DListNode * n = dynamic_cast <DListNode *> (head);
while (n != NULL) {
// check that if the node has neighbors that they point to n correctly
if ((!n->next || !n->next->prev || n->next->prev == n) && ((!n->prev && n == dynamic_cast <DListNode *> (head)) || (n->prev && (!n->prev->next || n->prev->next == n)))) {
// print the body of the node
n->draw(cr);
n->printed = true;
draw_arrows(cr, n);
n = n->next;
}
}
}
void DList::draw_disconnected(const Cairo::RefPtr<Cairo::Context> & cr) {
int xTmp = out_x;
int yTmp = out_y;
for (int i = 0; i < currentNodes; i++) {
if(!nodes[i]->printed) {
nodes[i]->y = yTmp;
nodes[i]->x = xTmp;
nodes[i]->draw(cr);
draw_arrows(cr, dynamic_cast <DListNode *> (nodes[i]));
xTmp += 2 * ListNode::padding;
}
}
}
void DList::draw_arrows(const Cairo::RefPtr<Cairo::Context> & cr, DListNode * node) {
// add the previous arrow
if (node->prev != NULL) {
draw_arrow_helper(cr, node->x + ARROW_OFFSET, node->y + (5 * ListNode::field_h) / 2, node->prev->x + ARROW_OFFSET + ListNode::field_w, node->prev->y + (5 * ListNode::field_h) / 2);
} else {
std::cout << "test" << std::endl;
draw_null_arrow(cr, node->x + ARROW_OFFSET, node->y + (5 * ListNode::field_h) / 2, false);
}
// add the next arrow
if (node->next != NULL) {
draw_arrow_helper(cr, node->x + ListNode::field_w - ARROW_OFFSET, node->y + (3 * ListNode::field_h) / 2, node->next->x - ARROW_OFFSET, node->next->y + (3 * ListNode::field_h) / 2);
} else {
draw_null_arrow(cr, node->x + ListNode::field_w - ARROW_OFFSET, node->y + (3 * ListNode::field_h) / 2, true);
}
}
DListNode::DListNode(List * dlist, int data) : ListNode(dlist, data) {
this->prev = NULL;
this->numFields = 3;
}
void DList::draw_labels(const Cairo::RefPtr<Cairo::Context> & cr) {
draw_label_helper(cr, head, "head", list_x, list_y, RIGHT);
draw_label_helper(cr, tail, "tail", tail_x, list_y, LEFT);
}
DListNode::~DListNode() {
}
<file_sep>all: visualize
visualize: visualize.o main.o list.o dlist.o array.o
g++ -g -o visualize visualize.o main.o list.o dlist.o array.o `pkg-config --cflags --libs gtkmm-3.0` -pthread -std=c++11
visualize.o: visualize.cpp visualize.h
g++ -g -c visualize.cpp `pkg-config --cflags --libs gtkmm-3.0`
main.o: main.cpp
g++ -g -c main.cpp `pkg-config --cflags --libs gtkmm-3.0` -pthread -std=c++11
list.o: list.cpp list.h
g++ -g -c list.cpp `pkg-config --cflags --libs gtkmm-3.0`
dlist.o: dlist.cpp dlist.h
g++ -g -c dlist.cpp `pkg-config --cflags --libs gtkmm-3.0`
array.o: array.cpp array.h
g++ -g -c array.cpp `pkg-config --cflags --libs gtkmm-3.0`
clean:
rm *.o visualize
<file_sep>#ifndef VISUALIZE_H
#define VISUALIZE_H
#include <gtkmm/drawingarea.h>
#include "list.h"
#include "dlist.h"
#include "array.h"
class Visualize : public Gtk::DrawingArea {
public:
Visualize();
~Visualize();
void run();
protected:
virtual bool on_draw(const Cairo::RefPtr<Cairo::Context> & cr);
virtual void update();
};
/*
class ListNode;
class List : Gtk::Widget{
public:
List();
~List();
virtual void draw(const Cairo::RefPtr<Cairo::Context> & cr);
void newNode(ListNode * node);
void removeFromArray(ListNode * node);
private:
virtual void draw_arrow(const Cairo::RefPtr<Cairo::Context> & cr, int start_x, int start_y, int end_x, int end_y);
virtual void draw_null_arrow(const Cairo::RefPtr<Cairo::Context> & cr, int start_x, int start_y);
public:
ListNode * head;
private:
int list_x;
int list_y;
int out_x;
int out_y;
ListNode ** nodes;
int currentNodes;
static const int nodes_size;
};
class ListNode : public Gtk::Widget {
friend class List;
public:
ListNode();
ListNode(List * list);
ListNode(List * list, int x, int y);
~ListNode();
virtual void draw(const Cairo::RefPtr<Cairo::Context> & cr);
virtual void draw_text(const Cairo::RefPtr<Cairo::Context> & cr, int x, int y);
virtual void draw_node(const Cairo::RefPtr<Cairo::Context> & cr, int x, int y);
public:
ListNode * next;
private:
static const int field_w;
static const int field_h;
static const int padding;
List * list;
bool printed;
int x;
int y;
};
*/
#endif
<file_sep>
#ifndef DLIST_H
#define DLIST_H
#include <gtkmm/drawingarea.h>
#include "list.h"
class DListNode;
class DList : public List {
friend class List;
public:
DList();
~DList();
// virtual void draw(const Cairo::RefPtr<Cairo::Context> & cr);
private:
virtual void arrange_nodes();
virtual void draw_arrows(const Cairo::RefPtr<Cairo::Context> & cr, DListNode * node);
virtual void draw_connected(const Cairo::RefPtr<Cairo::Context> & cr);
virtual void draw_disconnected(const Cairo::RefPtr<Cairo::Context> & cr);
virtual void draw_labels(const Cairo::RefPtr<Cairo::Context> & cr);
public:
ListNode * tail;
private:
int tail_x;
int tail_y;
};
class DListNode : public ListNode {
friend class DList;
public :
DListNode(List * dlist, int data);
~DListNode();
public:
DListNode * next;
DListNode * prev;
};
#endif // DLIST_H
<file_sep>
#include "visualize.h"
#include <cairomm/context.h>
#include <iostream>
const int List::nodes_size = 100;
List::List() {
list_x = 50;
list_y = 50;
out_x = list_x;
out_y = list_y + 100;
head = NULL;
nodes = new ListNode*[nodes_size];
currentNodes = 0;
}
List::~List() {
}
void List::newNode(ListNode * node) {
nodes[currentNodes++] = node;
}
void List::removeFromArray(ListNode * node) {
for (int i = 0; i < currentNodes; i++) {
if (nodes[i] == node) {
for (int j = i; j < currentNodes - 1; j++) {
nodes[j] = nodes[j + 1];
}
break;
}
}
currentNodes--;
}
void List::draw(const Cairo::RefPtr<Cairo::Context> & cr) {
// update the positions of the list
arrange_nodes();
// mark the array as unprinted
for (int i = 0; i < currentNodes; i++) {
nodes[i]->printed = false;
}
// print the head of the list
draw_labels(cr);
// print the nodes in the list
draw_connected(cr);
// print nodes disconnected from the list
draw_disconnected(cr);
}
// place the nodes that are part of the list in a single
// horizontal line
void List::arrange_nodes() {
ListNode * n = head;
int xTmp = list_x;
int yTmp = list_y;
while (n != NULL) {
xTmp += ListNode::padding;
n->x = xTmp;
n->y = yTmp;
n = n->next;
}
}
// draw the arrows from a specific node
void List::draw_arrows(const Cairo::RefPtr<Cairo::Context> & cr, ListNode * node) {
std::cout << "other test" << std::endl;
if (node->next != NULL) {
draw_arrow_helper(cr, node->x + ListNode::field_w - 10, node->y + (3 * ListNode::field_h) / 2, node->next->x - 10, node->next->y + ListNode::field_h);
} else {
draw_null_arrow(cr, node->x + ListNode::field_w - 10, node->y + (3 * ListNode::field_h) / 2, true);
}
}
void List::draw_arrow_helper(const Cairo::RefPtr<Cairo::Context> & cr, int start_x, int start_y, int end_x, int end_y) {
double m = (end_y - start_y) / (double ) (end_x - start_x);
double theta = atan(m);
int hyp = 5;
double angle;
if (end_x > start_x) {
angle = 5.0 * 3.14159 / 6.0;
} else {
angle = 3.14159 / 6.0;
}
cr->set_line_width(2.0);
// arrow body
cr->move_to(start_x, start_y);
cr->line_to(end_x, end_y);
// arrow head
cr->line_to(end_x + hyp * cos(theta + angle), end_y + hyp * sin(theta + angle));
cr->line_to(end_x + hyp * cos(theta - angle), end_y + hyp * sin(theta - angle));
cr->line_to(end_x, end_y);
cr->stroke();
}
void List::draw_null_arrow(const Cairo::RefPtr<Cairo::Context> & cr, int start_x, int start_y, bool right) {
int dir = right ? 1 : -1;
// draw the body of the arrow
cr->set_line_width(2.0);
cr->move_to(start_x, start_y);
cr->line_to(start_x + (35 * dir), start_y);
cr->line_to(start_x + (35 * dir), start_y + 10);
cr->stroke();
// draw the horizontal lines
cr->move_to(start_x + (25 * dir), start_y + 10);
cr->line_to(start_x + (45 * dir), start_y + 10);
cr->stroke();
cr->move_to(start_x + (30 * dir), start_y + 15);
cr->line_to(start_x + (40 * dir), start_y + 15);
cr->stroke();
cr->move_to(start_x + (34 * dir), start_y + 20);
cr->line_to(start_x + (36 * dir), start_y + 20);
cr->stroke();
}
// draw labels and connect them to the structure with arrows
void List::draw_labels(const Cairo::RefPtr<Cairo::Context> & cr) {
draw_label_helper(cr, head, "head", list_x, list_y, RIGHT);
}
void List::draw_label_helper(const Cairo::RefPtr<Cairo::Context> & cr, ListNode * label, const char * text, int x, int y, LabelArrowPos arrowPos) {
cr->set_source_rgb(0.0, 0.0, 0.0);
Pango::FontDescription font;
font.set_family("Monospace");
font.set_weight(Pango::WEIGHT_BOLD);
Glib::RefPtr<Pango::Layout> layout = create_pango_layout(text);
layout->set_font_description(font);
int text_w, text_h;
layout->get_pixel_size(text_w, text_h);
cr->move_to(x, y);
layout->show_in_cairo_context(cr);
if (label != NULL) {
if (arrowPos == RIGHT) {
draw_arrow_helper(cr, x + text_w + 10, y + text_h / 2, label->x - 10, label->y + ListNode::field_h);
} else {
draw_arrow_helper(cr, x - 10, y + text_h / 2, label->x + ListNode::field_w + 10, label->y + ListNode::field_h);
}
} else {
if (arrowPos == RIGHT) {
draw_null_arrow(cr, x + text_w + 10, y + text_h / 2, true);
} else {
draw_null_arrow(cr, x - 10, y + text_h / 2, false);
}
}
}
// draw nodes which are fully attached to the list
void List::draw_connected(const Cairo::RefPtr<Cairo::Context> & cr) {
ListNode * n = head;
while (n != NULL) {
n->draw(cr);
n->printed = true;
draw_arrows(cr, n);
n = n->next;
}
}
// draw nodes which may point to the list but are no fully attached to it
void List::draw_disconnected(const Cairo::RefPtr<Cairo::Context> & cr) {
int xTmp = out_x;
int yTmp = out_y;
for (int i = 0; i < currentNodes; i++) {
if (!nodes[i]->printed) {
nodes[i]->y = yTmp;
nodes[i]->x = xTmp;
nodes[i]->draw(cr);
draw_arrows(cr, nodes[i]);
xTmp += 2 * ListNode::padding;
}
}
}
const int ListNode::field_w = 50;
const int ListNode::field_h = 20;
const int ListNode::padding = 100;
ListNode::ListNode() {
}
ListNode::ListNode(List * list) {
this->next = NULL;
this->printed = false;
this->list = list;
list->newNode(this);
}
ListNode::ListNode(List * list, int data) {
this->data = data;
this->next = NULL;
this->printed = false;
this->list = list;
list->newNode(this);
this->numFields = 2;
}
ListNode::~ListNode() {
list->removeFromArray(this);
}
void ListNode::draw(const Cairo::RefPtr<Cairo::Context> & cr) {
cr->set_source_rgb(1.0, 1.0, 1.0);
draw_node(cr, x, y);
cr->set_source_rgb(0.0, 0.0, 0.0);
draw_text(cr, x, y);
}
void ListNode::draw_text(const Cairo::RefPtr<Cairo::Context> & cr, int x, int y) {
char * str = new char[10];
sprintf(str, "%d", data);
Pango::FontDescription font;
font.set_family("Monospace");
font.set_weight(Pango::WEIGHT_BOLD);
Glib::RefPtr<Pango::Layout> layout = create_pango_layout(str);
layout->set_font_description(font);
int text_w, text_h;
layout->get_pixel_size(text_w, text_h);
cr->move_to(x + (field_w - text_w) / 2, y + (field_h - text_h) / 2);
layout->show_in_cairo_context(cr);
}
void ListNode::draw_node(const Cairo::RefPtr<Cairo::Context> & cr, int x, int y) {
cr->rectangle(x, y, field_w, field_h * numFields);
cr->fill();
cr->set_source_rgb(0.0, 0.0, 0.0);
cr->set_line_width(2.0);
for (int i = 0; i < numFields; i++) {
cr->rectangle(x, y + (i * field_h), field_w, field_h);
cr->stroke();
}
}
<file_sep>
#ifndef LIST_H
#define LIST_H
#include <gtkmm/drawingarea.h>
#include "structure.h"
class ListNode;
/*
* A list which automatically tracks created nodes
*/
class List : Gtk::Widget, public Structure {
friend class DList;
public:
enum LabelArrowPos {
TOP,
BOTTOM,
RIGHT,
LEFT
};
public:
List();
~List();
virtual void draw(const Cairo::RefPtr<Cairo::Context> & cr);
void newNode(ListNode * node);
void removeFromArray(ListNode * node);
private:
virtual void arrange_nodes();
virtual void draw_arrows(const Cairo::RefPtr<Cairo::Context> & cr, ListNode * node);
virtual void draw_arrow_helper(const Cairo::RefPtr<Cairo::Context> & cr, int start_x, int start_y, int end_x, int end_y);
virtual void draw_null_arrow(const Cairo::RefPtr<Cairo::Context> & cr, int start_x, int start_y, bool right);
virtual void draw_connected(const Cairo::RefPtr<Cairo::Context> & cr);
virtual void draw_disconnected(const Cairo::RefPtr<Cairo::Context> & cr);
virtual void draw_labels(const Cairo::RefPtr<Cairo::Context> & cr);
virtual void draw_label_helper(const Cairo::RefPtr<Cairo::Context> & cr, ListNode * label, const char * text, int x, int y, LabelArrowPos labelPos);
public:
ListNode * head;
private:
int list_x;
int list_y;
int out_x;
int out_y;
ListNode ** nodes;
int currentNodes;
static const int nodes_size;
};
class ListNode : public Gtk::Widget {
friend class List;
public:
ListNode();
ListNode(List * list);
ListNode(List * list, int data);
ListNode(List * list, int x, int y);
~ListNode();
virtual void draw(const Cairo::RefPtr<Cairo::Context> & cr);
virtual void draw_text(const Cairo::RefPtr<Cairo::Context> & cr, int x, int y);
virtual void draw_node(const Cairo::RefPtr<Cairo::Context> & cr, int x, int y);
public:
ListNode * next;
int data;
bool printed;
int x;
int y;
static const int padding;
protected:
int numFields;
static const int field_w;
static const int field_h;
List * list;
};
#endif
<file_sep>#include "visualize.h"
#include <gtkmm/application.h>
#include <gtkmm/window.h>
#include <thread>
#include <iostream>
void start(Visualize * v) {
v->run();
std::cout << "exiting" << std::endl;
return;
}
int main(int argc, char ** argv) {
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "test");
Gtk::Window win;
win.set_title("Visualize");
Visualize v;
win.add(v);
v.show();
std::thread t1(start, &v);
int res = app->run(win);
t1.join();
return res;
}
<file_sep>#ifndef ARRAY_H
#define ARRAY_H
#include <gtkmm/drawingarea.h>
#include "structure.h"
class Array : Gtk::Widget, public Structure {
public:
Array();
Array(int size);
~Array();
virtual void draw(const Cairo::RefPtr<Cairo::Context> & cr);
public:
int * array;
int size;
int n;
private:
bool horizontal;
int x;
int y;
static const int field_w;
static const int field_h;
static const int init_size;
};
#endif // ARRAY_H
<file_sep>#include "visualize.h"
#include "structure.h"
#include <cairomm/context.h>
#include <stdio.h>
#include <iostream>
//List * list = new List();
Structure * s = NULL;
Visualize::Visualize() {
}
Visualize::~Visualize() {
}
void Visualize::run() {
/*
s = new Array();
Array * a = dynamic_cast <Array *> (s);
update();
a->array[a->n++] = 5;
update();
a->array[a->n++] = 7;
update();
a->array[a->n++] = 12;
update();
*/
/*
s = new List();
List * list = dynamic_cast <List *> (s);
ListNode * node = new ListNode(list, 0);
ListNode * node1 = new ListNode(list, 1);
ListNode * node2 = new ListNode(list, 2);
ListNode * node3 = new ListNode(list, 3);
ListNode * node4 = new ListNode(list, 4);
list->head = node;
node->next = node1;
node1->next = node2;
node2->next = node3;
update();
delete node4;
update();
ListNode * node5 = new ListNode(list, 5);
update();
node5->next = node2;
update();
node1->next = node5;
update();
node->next = node5;
update();
node1->next = NULL;
update();
delete node1;
update();
*/
s = new DList();
DList * list = dynamic_cast <DList *> (s);
DListNode * node = new DListNode(list, 0);
list->head = node;
update();
list->tail = node;
update();
DListNode * node1 = new DListNode(list, 1);
DListNode * node2 = new DListNode(list, 2);
DListNode * node3 = new DListNode(list, 3);
node->next = node1;
node1->prev = node;
list->tail = node1;
update();
node1->next = node2;
node2->prev = node1;
list->tail = node2;
update();
node2->next = node3;
node3->prev = node2;
list->tail = node3;
update();
node1->next = node3;
node3->prev = node1;
update();
/*
delete node4;
update();
DListNode * node5 = new DListNode(list, 5);
update();
node5->next = node2;
update();
node1->next = node5;
update();
node->next = node5;
update();
node1->next = NULL;
update();
delete node1;
update();
*/
}
void Visualize::update() {
this->queue_draw();
std::cout << "blocking" << std::endl;
getchar();
}
bool Visualize::on_draw(const Cairo::RefPtr<Cairo::Context> & cr) {
Gtk::Allocation allocation = get_allocation();
const int width = allocation.get_width();
const int height = allocation.get_height();
if (s != NULL) {
s->draw(cr);
}
}
| 93479869cbcf6063cfedbd1786ba01dcf0430c73 | [
"Makefile",
"C++"
] | 11 | C++ | BPHays/visualize-structures | a6b212c2dcdbfd606e3ee3f5524f2ab4887bb826 | a565c50199f7b7b23586eb9afbf29969c89dc152 |
refs/heads/master | <file_sep>#!/bin/sh
#
# Copyright 1994, 1998, 1999 <NAME>, Moorhead, Minnesota USA
# Copyright 2002, 2003 Slackware Linux, Inc, Concord, CA
# Copyright 2007, 2008, 2011, 2013, 2018, 2020 <NAME>, Sebeka, Minnesota, USA
# All rights reserved.
#
# Tweaked for Salix OS by <NAME> <vlahavas~at~gmail~dot~com>
# Tweaked for Salix OS by <NAME> <thenktor~at~gmx.de>
# 2011-03-27: Replaced some Slackware strings by Salix. Added hibernation hint
# to ask_append()
# 2010-03-01: Added a check if there is a bootable OS on Windows partition
# 2010-01-06: Fixed kernel arch: 's/ARCHTYPE=i386/ARCHTYPE=x86/'
# 2010-01-05: Changed label to "Linux" again, fixed expert install bug
# 2009-09-17: Changed label to "Salix"
# 2009-08-11: Added "auto" commandline option
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
#
TMP=/var/log/setup/tmp
CONSOLETYPE=standard
unset UTFVT
# Set the OS root directory (called T_PX for some unknown reason).
# If an argument is given to this script and it is a directory, it
# is taken to be the root directory. First though, we check for a
# directory named $T_PX, and that gets the first priority.
if [ ! -d "$T_PX" ]; then
if [ ! "$1" = "" ]; then
if [ -d "$1" ]; then
T_PX="$1"
fi
else
# Are we on the installer image?
if [ -r /usr/lib/setup/SeTpartitions ]; then
T_PX=/mnt
# Or, are we on a running system?
elif [ -r /etc/slackware-version ]; then
T_PX=/
# One more installer-likely thing:
elif [ -r /usr/lib/setup/setup ]; then
T_PX=/mnt
else
# We will have to assume we're on an installed and running system.
T_PX=/
fi
fi
fi
# Load locales with respect to $T_PX. Otherwise they won't work when
# launched from the installer using setup.liloconfig
export TEXTDOMAIN="liloconfig"
export TEXTDOMAINDIR="$T_PX/usr/share/locale"
. gettext.sh
# Most of the time LILO is not used on UEFI machines (in fact, it is useless
# unless the machine is running in legacy BIOS mode). So, we'll detect if
# this is a machine running UEFI and suggest skipping LILO installation.
# We'll still allow it if the user wants it, though. It won't hurt anything,
# and might be useful for booting in Legacy BIOS mode later.
if [ -d /sys/firmware/efi ]; then
dialog --visit-items --title "`gettext "UEFI FIRMWARE DETECTED"`" \
--backtitle "`gettext "LILO (Linux Loader) installation"`" \
--menu \
"`gettext "Since LILO (the traditional Linux Loader) does not work with machines \
running UEFI firmware (except in Legacy BIOS mode), you probably do not \
need to install it. Instead, you'll need ELILO, which is a version of \
LILO designed to work with EFI/UEFI systems."`" \
12 80 2 \
"skip" "`gettext "Skip installing LILO and proceed to ELILO installation"`" \
"install" "`gettext "Install LILO anyway"`" 2> $TMP/reply
if [ $? = 1 -o $? = 255 ]; then
exit
fi
REPLY="$(cat $TMP/reply)"
rm -f $TMP/reply
if [ "$REPLY" = "skip" ]; then
exit
fi
fi
# If os-prober is available, we will use it to filter out unbootable
# FAT/NTFS partitions. If it is not availble, we'll use /bin/true
# instead to avoid filtering.
if which os-prober > /dev/null ; then
OSPROBER=os-prober
else
OSPROBER=true
fi
# Determine LILO documentation directory:
LILODOCDIR="$(ls -d $T_PX/usr/doc/lilo-* 2> /dev/null | tail -n 1)"
if [ ! -d "$LILODOCDIR" ]; then
LILODOCDIR="/usr/doc/lilo/"
fi
# If there's no boot_message.txt, start the header for one now:
if [ ! -r $T_PX/boot/boot_message.txt ]; then
cat << EOF > $T_PX/boot/boot_message.txt
Welcome to the LILO Boot Loader!
Please enter the name of the partition you would like to boot
at the prompt below. The choices are:
EOF
fi
# The default install location may be set here:
DEFAULT=" --default-item MBR "
# This is a different 'probe' than the function below.
PROBE() {
if [ -x /sbin/probe ]; then
/sbin/probe -c
else # use fdisk directly:
fdisk -l 2> /dev/null | sed -e "s/Linux filesystem/Linux/g"
fi
}
# Function to ask if the Salix logo boot screen should be used.
ask_boot_splash() {
dialog --title "`gettext "OPTIONAL SALIX LOGO BOOT SCREEN"`" \
--yesno \
"`gettext "Would you like to use a boot screen with the Salix logo \
against a black background? If you answer no here, the standard \
LILO menu will be used.
"`" 7 80 2> $TMP/reply
RETVAL=$?
return $RETVAL
}
boot_bmp() {
cat << EO_BMP
# Boot BMP Image.
# Bitmap in BMP format: 640x480x8
bitmap = /boot/salix.bmp
# Menu colors (foreground, background, shadow, highlighted
# foreground, highlighted background, highlighted shadow):
bmp-colors = 12,0,10,0,9,9
# Location of the option table: location x, location y, number of
# columns, lines per column (max 15), "spill" (this is how many
# entries must be in the first column before the next begins to
# be used. We don't specify it here, as there's just one column.
bmp-table = 5,6,1,16
# Timer location x, timer location y, foreground color,
# background color, shadow color.
bmp-timer = 70,6,14,0
EO_BMP
}
# Menu to check if we want to use VESA framebuffer support:
use_framebuffer() {
if cat /proc/devices | grep "29 fb" 1> /dev/null ; then
dialog --visit-items --title "`gettext "CONFIGURE LILO TO USE FRAME BUFFER CONSOLE?"`" \
--default-item 1024x768x256 \
--menu "`gettext "Looking at /proc/devices, it seems your kernel has support for \
the Linux frame buffer console. If we enable this in /etc/lilo.conf, it \
will allow more rows and columns of text on the screen and give you a cool \
penguin logo at boot time. However, the frame buffer text console is \
slower than a standard text console. In addition, not every video card \
or monitor supports all of these video modes. Would you like to use the \
frame buffer console, or the standard Linux console?"`" 0 0 0 \
"standard" "`gettext "Use the standard Linux console (the safe choice)"`" \
"640x480x64k" "`gettext "Frame buffer console, 640x480x64k"`" \
"800x600x64k" "`gettext "Frame buffer console, 800x600x64k"`" \
"1024x768x64k" "`gettext "Frame buffer console, 1024x768x64k"`" \
"1280x1024x64k" "`gettext "Frame buffer console, 1280x1024x64k"`" \
"1600x1200x64k" "`gettext "Frame buffer console, 1600x1200x64k"`" \
2> $TMP/reply
if [ $? = 1 -o $? = 255 ]; then
exit
fi
# Frame buffer modes above 1024x768 look terrible except
# on LCD panels, and 32 bit color is slow. Since we don't
# even need to run a framebuffer console to run framebuffer
# X anymore, these modes aren't of much real use.
# "1280x1024x256" "Frame buffer console, 1280x1024x256" \
# "1600x1200x256" "Frame buffer console, 1600x1200x256" \
# "1280x1024x32k" "Frame buffer console, 1280x1024x32k" \
# "1600x1200x32k" "Frame buffer console, 1600x1200x32k" \
# "1280x1024x64k" "Frame buffer console, 1280x1024x64k" \
# "1600x1200x64k" "Frame buffer console, 1600x1200x64k" \
# "640x480x16m" "Frame buffer console, 640x480x16.8m" \
# "800x600x16m" "Frame buffer console, 800x600x16.8m" \
# "1024x768x16m" "Frame buffer console, 1024x768x16.8m" \
# "1280x1024x16m" "Frame buffer console, 1280x1024x16.8m" \
# "1600x1200x16m" "Frame buffer console, 1600x1200x16.8m"
CONSOLETYPE="$(cat $TMP/reply)"
if [ "$CONSOLETYPE" = "1600x1200x16m" ]; then
CONSOLENUM=799
elif [ "$CONSOLETYPE" = "1600x1200x64k" ]; then
CONSOLENUM=798
elif [ "$CONSOLETYPE" = "1600x1200x32k" ]; then
CONSOLENUM=797
elif [ "$CONSOLETYPE" = "1600x1200x256" ]; then
CONSOLENUM=796
elif [ "$CONSOLETYPE" = "1280x1024x16m" ]; then
CONSOLENUM=795
elif [ "$CONSOLETYPE" = "1280x1024x64k" ]; then
CONSOLENUM=794
elif [ "$CONSOLETYPE" = "1280x1024x32k" ]; then
CONSOLENUM=793
elif [ "$CONSOLETYPE" = "1280x1024x256" ]; then
CONSOLENUM=775
elif [ "$CONSOLETYPE" = "1024x768x16m" ]; then
CONSOLENUM=792
elif [ "$CONSOLETYPE" = "1024x768x64k" ]; then
CONSOLENUM=791
elif [ "$CONSOLETYPE" = "1024x768x32k" ]; then
CONSOLENUM=790
elif [ "$CONSOLETYPE" = "1024x768x256" ]; then
CONSOLENUM=773
elif [ "$CONSOLETYPE" = "800x600x16m" ]; then
CONSOLENUM=789
elif [ "$CONSOLETYPE" = "800x600x64k" ]; then
CONSOLENUM=788
elif [ "$CONSOLETYPE" = "800x600x32k" ]; then
CONSOLENUM=787
elif [ "$CONSOLETYPE" = "800x600x256" ]; then
CONSOLENUM=771
elif [ "$CONSOLETYPE" = "640x480x16m" ]; then
CONSOLENUM=786
elif [ "$CONSOLETYPE" = "640x480x64k" ]; then
CONSOLENUM=785
elif [ "$CONSOLETYPE" = "640x480x32k" ]; then
CONSOLENUM=784
elif [ "$CONSOLETYPE" = "640x480x256" ]; then
CONSOLENUM=769
fi
fi
}
# A function to ask for append= parameters.
ask_append() {
dialog --title "`gettext "OPTIONAL LILO append=\"<kernel parameters>\" LINE"`" --inputbox \
"`gettext "Some systems might require extra parameters to be passed to the kernel. \
If you needed to pass parameters to the kernel when you booted the Salix \
bootdisk, you'll probably want to enter the same ones here. Most \
systems won't require any extra parameters. If you want to use \
hibernation, please add a resume option for your swap partition. For \
example: 'resume=/dev/sda3' if your swap partition is /dev/sda3. If you \
don't need any, just hit ENTER to continue."`" 14 80 2> $TMP/reply
RETVAL=$?
return $RETVAL
}
# This function scans for bootable partitions (making some assumptions along
# the way which may or may not be correct, but usually work), and sets up
# LILO in either the superblock, or the MBR.
simplelilo()
{
use_framebuffer;
ask_append;
if [ $? = 1 -o $? = 255 ]; then
APPEND="quiet "
fi
APPEND="quiet $(cat $TMP/reply)"
UTFVT="vt.default_utf8=1"
if PROBE -l | grep 'OS/2 Boot Manager' 1> /dev/null 2> /dev/null ; then
dialog --title "`gettext "OS/2 BOOT MANAGER FOUND"`" --yesno \
"`gettext "Your system appears to have Boot Manager, a boot menu system provided \
with OS/2 and Partition Magic. If you like, we can install a very simple \
LILO boot block at the start of your Linux partition. Then, you can \
add the partition to the Boot Manager menu, and you'll be able to use \
Boot Manager to boot Linux. Would you like to install LILO in a Boot \
Manager compatible way?"`" 11 80
FLAG=$?
if [ ! $FLAG = 0 -a ! $FLAG = 1 ]; then
exit 1
fi
if [ $FLAG = 0 ]; then # yes, use BM
if [ -r $T_PX/etc/lilo.conf ]; then
mv $T_PX/etc/lilo.conf $T_PX/etc/lilo.conf.orig
fi
cat << EOF > $T_PX/etc/lilo.conf
# LILO configuration file
# generated by 'liloconfig'
#
# Start LILO global section
#
EOF
if [ ! "$APPEND" = "" -o ! "$UTFVT" = "" ]; then
echo "# Append any additional kernel parameters:" >> $T_PX/etc/lilo.conf
echo "append=\"$APPEND $UTFVT\"" >> $T_PX/etc/lilo.conf
fi
cat << EOF >> $T_PX/etc/lilo.conf
boot = $ROOT_DEVICE
#delay = 5
compact
EOF
if [ "$CONSOLETYPE" = "standard" ]; then
cat << EOF >> $T_PX/etc/lilo.conf
vga = normal
EOF
else
cat << EOF >> $T_PX/etc/lilo.conf
# VESA framebuffer at $CONSOLETYPE
vga = $CONSOLENUM
EOF
fi
cat << EOF >> $T_PX/etc/lilo.conf
# End LILO global section
# Linux root partition section
image = $KERNEL
root = $ROOT_DEVICE
label = Salix
read-only
# End root Linux partition section
EOF
installcolor;
return
fi # Use Boot Manager
fi # Boot Manager detected
# If we got here, we either don't have boot manager or don't want to use it
dialog --visit-items --title "`eval_gettext "SELECT LILO DESTINATION"`" $DEFAULT --menu \
"`gettext "LILO can be installed to a variety of places:
1. The superblock of your root Linux partition. (which could \
be made the bootable partition with Windows or Linux fdisk, or \
booted with a program like OS/2 Boot Manager)
2. A formatted floppy disk.
3. The Master Boot Record of your first hard drive.
Options 1 and 2 are the safest, but option 1 does require a little \
extra work later (setting the partition bootable with fdisk). \
Which option would you like?"`" \
20 80 3 \
"Root" "`gettext "Install to superblock (not for use with XFS)"`" \
"Floppy" "`gettext "Install to a formatted floppy in /dev/fd0 (A:)"`" \
"MBR" "`gettext "Install to Master Boot Record"`" \
2> $TMP/reply
if [ $? = 1 -o $? = 255 ]; then
exit
fi
TG="$(cat $TMP/reply)"
rm -r $TMP/reply
dialog --infobox "\n`gettext "Scanning partitions and generating /etc/lilo.conf..."`" 0 0
sleep 1
if [ "$TG" = "MBR" ]; then
MBR_TARGET=/dev/sda
echo $MBR_TARGET > $TMP/LILOMBR
cat /proc/partitions | while read LINE ; do
MAJOR="$(echo $LINE | cut -f 1 -d ' ')"
MINOR="$(echo $LINE | cut -f 2 -d ' ')"
if [ ! "$MINOR" = "0" -a ! "$MINOR" = "64" ]; then # ignore whole devices to weed out CD drives
if [ "$MAJOR" = "3" ]; then
MBR_TARGET=/dev/hda
echo $MBR_TARGET > $TMP/LILOMBR
elif [ "$MAJOR" = "22" -a ! "$MBR_TARGET" = "/dev/hda" ]; then
MBR_TARGET=/dev/hdc
echo $MBR_TARGET > $TMP/LILOMBR
elif [ "$MAJOR" = "33" -a ! "$MBR_TARGET" = "/dev/hda" -a ! "$MBR_TARGET" = "/dev/hdc" ]; then
MBR_TARGET=/dev/hde
echo $MBR_TARGET > $TMP/LILOMBR
elif [ "$MAJOR" = "34" -a ! "$MBR_TARGET" = "/dev/hda" -a ! "$MBR_TARGET" = "/dev/hdc" -a ! "$MBR_TARGET" = "/dev/hde" ]; then
MBR_TARGET=/dev/hdg
echo $MBR_TARGET > $TMP/LILOMBR
elif [ "$MAJOR" = "259" -a ! "$MBR_TARGET" = "/dev/hda" -a ! "$MBR_TARGET" = "/dev/hdc" -a ! "$MBR_TARGET" = "/dev/hde" -a ! "$MBR_TARGET" = "/dev/hdg" ]; then
if [ "$(echo $LINE | cut -f 4 -d ' ' | cut -b 1-4)" = "nvme" ]; then
MBR_TARGET="/dev/$(echo $LINE | cut -f 4 -d ' ' | cut -f 1 -d p)"
echo $MBR_TARGET > $TMP/LILOMBR
fi
fi
if dmidecode 2> /dev/null | grep -q QEMU 2> /dev/null ; then
if [ -r /dev/vda ]; then
MBR_TARGET=/dev/vda
echo $MBR_TARGET > $TMP/LILOMBR
fi
fi
fi
done
LILO_TARGET=$(cat $TMP/LILOMBR)
elif [ "$TG" = "Root" ]; then
LILO_TARGET=$(echo $ROOT_DEVICE)
elif [ "$TG" = "Floppy" ]; then
LILO_TARGET="/dev/fd0"
fi
cat << EOF > $T_PX/etc/lilo.conf
# LILO configuration file
# generated by 'liloconfig'
#
# Start LILO global section
EOF
#if [ ! "$APPEND" = "" -o ! "$UTFVT" = "" ]; then
echo "# Append any additional kernel parameters:" >> $T_PX/etc/lilo.conf
echo "append=\"$APPEND $UTFVT\"" >> $T_PX/etc/lilo.conf
echo >> $T_PX/etc/lilo.conf
#fi
if echo $LILO_TARGET | grep -q vda 2>/dev/null ; then
echo "disk = /dev/vda bios=0x80 max-partitions=7" >> $T_PX/etc/lilo.conf
fi
cat << EOF >> $T_PX/etc/lilo.conf
boot = $LILO_TARGET
# This option loads the kernel and initrd much faster:
compact
# Boot BMP Image.
# Bitmap in BMP format: 640x480x8
bitmap = /boot/salix.bmp
# Menu colors (foreground, background, shadow, highlighted
# foreground, highlighted background, highlighted shadow):
bmp-colors = 12,0,10,0,9,9
# Location of the option table: location x, location y, number of
# columns, lines per column (max 15), "spill" (this is how many
# entries must be in the first column before the next begins to
# be used. We don't specify it here, as there's just one column.
bmp-table = 5,6,1,16
# Timer location x, timer location y, foreground color,
# background color, shadow color.
bmp-timer = 70,6,14,0
# Standard menu.
# Or, you can comment out the bitmap menu above and
# use a boot message with the standard menu:
#message = /boot/boot_message.txt
# Wait until the timeout to boot (if commented out, boot the
# first entry immediately):
prompt
# Timeout before the first entry boots.
# This is given in tenths of a second, so 600 for every minute:
timeout = 50
# Override dangerous defaults that rewrite the partition table:
change-rules
reset
EOF
if [ "$CONSOLETYPE" = "standard" ]; then
cat << EOF >> $T_PX/etc/lilo.conf
# Normal VGA console
vga = normal
# VESA framebuffer console @ 1024x768x64k
# vga=791
# VESA framebuffer console @ 1024x768x32k
# vga=790
# VESA framebuffer console @ 1024x768x256
# vga=773
# VESA framebuffer console @ 800x600x64k
# vga=788
# VESA framebuffer console @ 800x600x32k
# vga=787
# VESA framebuffer console @ 800x600x256
# vga=771
# VESA framebuffer console @ 640x480x64k
# vga=785
# VESA framebuffer console @ 640x480x32k
# vga=784
# VESA framebuffer console @ 640x480x256
# vga=769
EOF
else
cat << EOF >> $T_PX/etc/lilo.conf
# VESA framebuffer console @ $CONSOLETYPE
vga = $CONSOLENUM
# Normal VGA console
# vga = normal
# VESA framebuffer console @ 1024x768x64k
# vga=791
# VESA framebuffer console @ 1024x768x32k
# vga=790
# VESA framebuffer console @ 1024x768x256
# vga=773
# VESA framebuffer console @ 800x600x64k
# vga=788
# VESA framebuffer console @ 800x600x32k
# vga=787
# VESA framebuffer console @ 800x600x256
# vga=771
# VESA framebuffer console @ 640x480x64k
# vga=785
# VESA framebuffer console @ 640x480x32k
# vga=784
# VESA framebuffer console @ 640x480x256
# vga=769
EOF
fi
cat << EOF >> $T_PX/etc/lilo.conf
# End LILO global section
EOF
# OK, now let's look for Windows partitions:
# If we have os-prober, use the Windows partition list from that:
if which os-prober > /dev/null ; then
DOSP="$(os-prober 2> /dev/null | grep :Windows: | cut -f 1 -d :)"
else # use PROBE output:
DOSP="$(PROBE -l | grep "DOS
Win
W95
FAT12
FAT16
HPFS" | grep -v "Ext'd" | grep -v "Extend" | sort )"
DOSP="$(echo $DOSP | cut -f 1 -d ' ')"
fi
if [ ! "$DOSP" = "" ]; then
TABLE="$(echo $DOSP | cut -b1-8)"
cat << EOF >> $T_PX/etc/lilo.conf
# Windows bootable partition config begins
other = $DOSP
label = Windows
table = $TABLE
# Windows bootable partition config ends
EOF
echo "Windows - (Windows FAT/NTFS partition)" >> $T_PX/boot/boot_message.txt
fi
# Next, we search for Linux partitions:
LNXP="$(PROBE -l | grep "Linux$")"
LNXP="$(echo $LNXP | cut -f 1 -d ' ' | sort)"
if [ ! "$LNXP" = "" ]; then
cat << EOF >> $T_PX/etc/lilo.conf
# Linux bootable partition config begins
image = $KERNEL
root = $ROOT_DEVICE
label = Salix
read-only
# Linux bootable partition config ends
EOF
echo "Linux - (Linux partition)" >> $T_PX/boot/boot_message.txt
fi
# DEAD CODE, BUT IN CASE OS/2 MAKES A COMEBACK!
# # OK, hopefully we can remember how to deal with OS/2 :^)
# OS2P="$(PROBE -l | grep "HPFS")"
# OS2P="$(echo $OS2P | cut -f 1 -d ' ' | sort)"
# if [ ! "$OS2P" = "" ]; then
# TABLE="$(echo $OS2P | cut -b1-8)"
# if [ "$TABLE" = "/dev/hda" ]; then
# cat << EOF >> $T_PX/etc/lilo.conf
## OS/2 bootable partition config begins
#other = $OS2P
# label = OS2
# table = $TABLE
## OS/2 bootable partition config ends
#EOF
# else
# cat << EOF >> $T_PX/etc/lilo.conf
## OS/2 bootable partition config begins
#other = $OS2P
# label = OS2
# table = $TABLE
# loader = /boot/os2_d.b
## map-drive = 0x80
## to = 0x81
## map-drive = 0x81
## to = 0x80
## OS/2 bootable partition config ends
#EOF
# echo "OS2 - OS/2 Warp (HPFS partition)" >> $T_PX/boot/boot_message.txt
# fi
# fi
echo >> $T_PX/boot/boot_message.txt
# Done, now we must install lilo:
installcolor;
}
checkp_text()
{
if [ ! -r $1 ]; then
ArG1="$1"
echo
eval_gettext "I can't find a device named \$ArG1 !"
unset ArG1
echo
echo
gettext "Are you sure you want to use this device name "
echo -n "[y]es, [n]o? "
read use_device;
if [ ! "$use_device" = "y" ]; then
return 1;
fi
return 0;
fi
}
checkp_dialog()
{
if [ ! -r $1 ]; then
ArG1=$1
dialog --title "`gettext "DEVICE FILE NOT FOUND"`" --yesno "`eval_gettext "I can't find a \
device named \"\\\$ArG1\". Are you sure you want to use this device \
name?"`" 7 80
unset ArG1
return $?;
fi
}
installcolor()
{
dialog --infobox "`gettext "Installing the Linux Loader..."`" 5 40
if [ "$T_PX" = "/" ]; then
lilo 1> /dev/null 2> /etc/lilo-error.$$
SUCCESS=$?
else
lilo -r $T_PX -m /boot/map -C /etc/lilo.conf 1> /dev/null 2> /etc/lilo-error.$$
SUCCESS=$?
fi
if [ ! "$SUCCESS" = "0" ]; then # edit file to try lba32 mode:
cat $T_PX/etc/lilo.conf | while read line ; do
echo $line
if [ "$line" = "# Start LILO global section" ] ; then
echo "lba32 # Allow booting past 1024th cylinder with a recent BIOS"
fi
done > $T_PX/etc/lilo.conf.lba32
mv $T_PX/etc/lilo.conf.lba32 $T_PX/etc/lilo.conf
if [ "$T_PX" = "/" ]; then
lilo 1> /dev/null 2> /etc/lilo-error.$$
SUCCESS=$?
else
lilo -r $T_PX -m /boot/map -C /etc/lilo.conf 1> /dev/null 2> /etc/lilo-error.$$
SUCCESS=$?
fi
fi
sleep 1
if [ ! "$SUCCESS" = "0" ]; then # some LILO error occured
echo >> /etc/lilo-error.$$
eval_gettext "Sorry, but the attempt to install LILO has returned an error, so LILO \
has not been correctly installed. You'll have to use a bootdisk \
to start your \
machine instead. It should still be possible to get LILO working by \
editing the /etc/lilo.conf and reinstalling LILO manually. See the \
LILO man page and documentation in \$LILODOCDIR for more help. \
The error message may be seen above." >> /etc/lilo-error.$$
dialog --msgbox "$(cat /etc/lilo-error.$$)" 0 0
fi
}
installtext()
{
echo "Installing the Linux Loader..."
if [ "$T_PX" = "/" ]; then
lilo
SUCCESS=$?
else
lilo -r $T_PX -m /boot/map -C /etc/lilo.conf
SUCCESS=$?
fi
if [ ! "$SUCCESS" = "0" ]; then # try lba32 mode:
cat $T_PX/etc/lilo.conf | while read line ; do
echo $line
if [ "$line" = "# Start LILO global section" ] ; then
echo "lba32 # Allow booting past 1024th cylinder with a recent BIOS"
fi
done > $T_PX/etc/lilo.conf.lba32
mv $T_PX/etc/lilo.conf.lba32 $T_PX/etc/lilo.conf
if [ "$T_PX" = "/" ]; then
lilo 1> /dev/null 2> /dev/null
SUCCESS=$?
else
lilo -r $T_PX -m /boot/map -C /etc/lilo.conf 1> /dev/null 2> /dev/null
SUCCESS=$?
fi
fi
sleep 1
if [ ! "$SUCCESS" = "0" ]; then # some LILO error occured
echo
eval_gettext "LILO INSTALL ERROR # \$SUCCESS
Sorry, but the attempt to install LILO has returned an error, so LILO \
has not been correctly installed. You'll have to use a bootdisk to \
start your machine instead. It should still be possible to get LILO \
working by editing the /etc/lilo.conf and reinstalling LILO manually. \
See the LILO man page and documentation in \$LILODOCDIR for more \
help."
echo
echo
fi
}
# 'probe()' borrowed from LILO QuickInst.
probe()
{
[ ! -z "$(dd if=$1 bs=1 count=1 2>/dev/null | tr '\0' x)" ]
return
}
# Figure out if we're installing from the hard drive
if [ -r $TMP/SeTT_PX ]; then
T_PX="$(cat $TMP/SeTT_PX)"
else
if [ "$T_PX" = "" -a ! "$1" = "" ]; then
T_PX=$1
else
T_PX=/
fi
fi
HDR="no" # this means the header section of /etc/lilo.conf has not yet
# been configured
LNX="no" # this means no Linux partition has been defined as bootable
# through LILO. Both of these must change to "yes" before LILO will
# install from this script.
# Determine the root partition (such as /dev/hda2)
ROOT_DEVICE=$2
if [ "$ROOT_DEVICE" = "" ]; then
if [ -r $TMP/SeTrootdev ]; then
ROOT_DEVICE="$(cat $TMP/SeTrootdev)"
else
ROOT_DEVICE="$(mount | cut -f 1 -d " " | sed -n "1 p")"
fi
fi
# Figure out where the kernel is:
ARCHTYPE=x86
if [ -r $T_PX/vmlinuz ]; then
KERNEL=/vmlinuz
elif [ -r $T_PX/boot/vmlinuz ]; then
KERNEL=/boot/vmlinuz
elif [ -r $T_PX/usr/src/linux/arch/$ARCHTYPE/boot/bzImage ]; then
KERNEL=/usr/src/linux/arch/$ARCHTYPE/boot/bzImage
elif [ -r $T_PX/usr/src/linux/arch/$ARCHTYPE/boot/zImage ]; then
KERNEL=/usr/src/linux/arch/$ARCHTYPE/boot/zImage
else
exit 99 # no kernel? guess you couldn't read. bye bye.
fi
# OK, now let's see if we should automate things:
if [ "$3" == "auto" ]; then
simplelilo
exit
fi
dialog --title "`gettext "INSTALL LILO"`" \
--menu "`gettext "LILO (Linux Loader) is a generic \
boot loader. There's a simple installation which tries to automatically \
set up LILO to boot Linux (also Windows if found). For \
more advanced users, the expert option offers more control over the \
installation process. Since LILO does not work in all cases (and can \
damage partitions if incorrectly installed), there's the third (safe) \
option, which is to skip installing LILO for now. You can always install \
it later with the 'liloconfig' command. Which option would you like?"`" \
18 80 3 \
"simple" "`gettext "Try to install LILO automatically"`" \
"expert" "`gettext "Use expert lilo.conf setup menu"`" \
"skip" "`gettext "Do not install LILO"`" 2> $TMP/reply
if [ $? = 1 -o $? = 255 ]; then
exit
fi
REPLY="$(cat $TMP/reply)"
rm -f $TMP/reply
if [ "$REPLY" = "skip" ]; then
exit
elif [ "$REPLY" = "simple" ]; then
# Do simple LILO setup
simplelilo
exit
fi
# drop through to last option: (use the expert menus)
while [ 0 ]; do
dialog --visit-items --title "`gettext "EXPERT LILO INSTALLATION"`" --menu \
"`gettext "This menu directs the creation of the LILO config file, lilo.conf. \
To install, you make a new LILO configuration file by creating a new header \
and then adding one or more bootable partitions to the file. Once you've done \
this, you can select the install option. Alternately, if you already have an \
/etc/lilo.conf, you may reinstall using that. If you make a mistake, you can \
always start over by choosing 'Begin'. \
Which option would you like?"`" 21 80 8 \
"Begin" "`gettext "Start LILO configuration with a new LILO header"`" \
"Linux" "`gettext "Add a Linux partition to the LILO config"`" \
"Windows" "`gettext "Add a Windows FAT or NTFS partition to the LILO config"`" \
"Install" "`gettext "Install LILO"`" \
"Recycle" "`gettext "Reinstall LILO using the existing lilo.conf"`" \
"Skip" "`gettext "Skip LILO installation and exit this menu"`" \
"View" "`gettext "View your current /etc/lilo.conf"`" \
"Help" "`gettext "Read the Linux Loader HELP file"`" 2> $TMP/reply
if [ $? = 1 -o $? = 255 ]; then
REPLY="Skip"
else
REPLY="$(cat $TMP/reply)"
fi
rm -r $TMP/reply
if [ "$REPLY" = "Begin" ]; then
ask_append;
if [ $? = 1 -o $? = 255 ]; then
APPEND="quiet "
HDR="no"
continue;
else
APPEND="quiet $(cat $TMP/reply)"
fi
UTFVT="vt.default_utf8=1"
use_framebuffer;
dialog --visit-items --title "`eval_gettext "SELECT LILO TARGET LOCATION"`" $DEFAULT --menu "`gettext "LILO can be installed \
to a variety of places: \
the superblock of your root Linux partition (which could then be made the \
bootable partition with fdisk), a formatted floppy disk, \
or the master boot record of your first hard drive. If you're using \
a boot system such as Boot Manager, you should use the \"Root\" \
selection. Please pick a target location:"`" 15 80 3 \
"Root" "`gettext "Install to superblock (not for use with XFS)"`" \
"Floppy" "`gettext "Use a formatted floppy disk in the boot drive"`" \
"MBR" "`gettext "Use the Master Boot Record (possibly unsafe)"`" \
2> $TMP/reply
if [ $? = 1 -o $? = 255 ]; then
HDR="no"
continue;
else
LNX="no"
TG="$(cat $TMP/reply)"
fi
rm -r $TMP/reply
if [ "$TG" = "MBR" ]; then
MBR_TARGET=/dev/sda
echo $MBR_TARGET > $TMP/LILOMBR
cat /proc/partitions | while read LINE ; do
MAJOR="$(echo $LINE | cut -f 1 -d ' ')"
MINOR="$(echo $LINE | cut -f 2 -d ' ')"
if [ ! "$MINOR" = "0" -a ! "$MINOR" = "64" ]; then # ignore whole devices to weed out CD drives
if [ "$MAJOR" = "3" ]; then
MBR_TARGET=/dev/hda
echo $MBR_TARGET > $TMP/LILOMBR
elif [ "$MAJOR" = "22" -a ! "$MBR_TARGET" = "/dev/hda" ]; then
MBR_TARGET=/dev/hdc
echo $MBR_TARGET > $TMP/LILOMBR
elif [ "$MAJOR" = "33" -a ! "$MBR_TARGET" = "/dev/hda" -a ! "$MBR_TARGET" = "/dev/hdc" ]; then
MBR_TARGET=/dev/hde
echo $MBR_TARGET > $TMP/LILOMBR
elif [ "$MAJOR" = "34" -a ! "$MBR_TARGET" = "/dev/hda" -a ! "$MBR_TARGET" = "/dev/hdc" -a ! "$MBR_TARGET" = "/dev/hde" ]; then
MBR_TARGET=/dev/hdg
echo $MBR_TARGET > $TMP/LILOMBR
fi
if dmidecode 2> /dev/null | grep -q QEMU 2> /dev/null ; then
if [ -r /dev/vda ]; then
MBR_TARGET=/dev/vda
echo $MBR_TARGET > $TMP/LILOMBR
fi
fi
fi
done
LILO_TARGET=$(cat $TMP/LILOMBR)
dialog --title "`gettext "CONFIRM LOCATION TO INSTALL LILO"`" --inputbox \
"`gettext "The auto-detected location to install the LILO boot block is shown below. \
If you need to make any changes, you can make them below. Otherwise, hit \
ENTER to accept the target location shown."`" 11 80 $LILO_TARGET 2> $TMP/reply
if [ $? = 0 ]; then
LILO_TARGET="$(cat $TMP/reply)"
fi
rm -f $TMP/reply
elif [ "$TG" = "Root" ]; then
LILO_TARGET=`echo $ROOT_DEVICE`
elif [ "$TG" = "Floppy" ]; then
LILO_TARGET="/dev/fd0"
else
HDR="no"
continue;
fi
dialog --visit-items --title "`gettext "CHOOSE LILO TIMEOUT"`" --menu "`gettext "At boot time, how long would \
you like LILO to wait for you to select an operating system? If you \
let LILO time out, it will boot the first OS in the configuration file by \
default."`" 13 80 4 \
"None" "`gettext "Don't wait at all - boot straight into the first OS"`" \
"5" "`gettext "5 seconds"`" \
"30" "`gettext "30 seconds"`" \
"Forever" "`gettext "Present a prompt and wait until a choice is made"`" 2> $TMP/reply
if [ $? = 1 -o $? = 255 ]; then
HDR="no"
continue;
else
TIMEOUT="$(cat $TMP/reply)"
fi
rm -r $TMP/reply
if [ "$TIMEOUT" = "None" ]; then
PROMPT="#prompt"
TIMEOUT="#timeout = 5"
elif [ "$TIMEOUT" = "5" ]; then
PROMPT="prompt"
TIMEOUT="timeout = 50"
elif [ "$TIMEOUT" = "30" ]; then
PROMPT="prompt"
TIMEOUT="timeout = 300"
elif [ "$TIMEOUT" = "Forever" ]; then
PROMPT="prompt"
TIMEOUT="#timeout = 300"
else
HDR="no"
continue;
fi
cat << EOF > $TMP/lilo.conf
# LILO configuration file
# generated by 'liloconfig'
#
# Start LILO global section
boot = $LILO_TARGET
# This option loads the kernel and initrd much faster:
compact
EOF
# Boot splash
if [ "$PROMPT" = "prompt" ]; then
if ask_boot_splash ; then
boot_bmp >> $TMP/lilo.conf
cat << EOF >> $TMP/lilo.conf
# Standard menu.
# Or, you can comment out the bitmap menu above and
# use a boot message with the standard menu:
#message = /boot/boot_message.txt
EOF
fi
else
cat << EOF >> $TMP/lilo.conf
# Standard menu.
message = /boot/boot_message.txt
EOF
fi
#if [ ! "$APPEND" = "" -o ! "$UTFVT" = "" ]; then
echo "# Append any additional kernel parameters:" >> $TMP/lilo.conf
echo "append=\"$APPEND $UTFVT\"" >> $TMP/lilo.conf
#fi
if echo $LILO_TARGET | grep -q vda 2>/dev/null ; then
echo "disk = /dev/vda bios=0x80 max-partitions=7" >> $TMP/lilo.conf
fi
cat << EOF >> $TMP/lilo.conf
$PROMPT
$TIMEOUT
EOF
if [ "$CONSOLETYPE" = "standard" ]; then
cat << EOF >> $TMP/lilo.conf
# Normal VGA console
vga = normal
# VESA framebuffer console @ 1024x768x64k
# vga=791
# VESA framebuffer console @ 1024x768x32k
# vga=790
# VESA framebuffer console @ 1024x768x256
# vga=773
# VESA framebuffer console @ 800x600x64k
# vga=788
# VESA framebuffer console @ 800x600x32k
# vga=787
# VESA framebuffer console @ 800x600x256
# vga=771
# VESA framebuffer console @ 640x480x64k
# vga=785
# VESA framebuffer console @ 640x480x32k
# vga=784
# VESA framebuffer console @ 640x480x256
# vga=769
EOF
else
cat << EOF >> $TMP/lilo.conf
# VESA framebuffer console @ $CONSOLETYPE
vga = $CONSOLENUM
# Normal VGA console
# vga = normal
# VESA framebuffer console @ 1024x768x64k
# vga=791
# VESA framebuffer console @ 1024x768x32k
# vga=790
# VESA framebuffer console @ 1024x768x256
# vga=773
# VESA framebuffer console @ 800x600x64k
# vga=788
# VESA framebuffer console @ 800x600x32k
# vga=787
# VESA framebuffer console @ 800x600x256
# vga=771
# VESA framebuffer console @ 640x480x64k
# vga=785
# VESA framebuffer console @ 640x480x32k
# vga=784
# VESA framebuffer console @ 640x480x256
# vga=769
EOF
fi
cat << EOF >> $TMP/lilo.conf
# ramdisk = 0 # paranoia setting
# End LILO global section
EOF
HDR="yes"
elif [ "$REPLY" = "Linux" ]; then
dialog --infobox "\n`eval_gettext "Scanning for Linux partitions..."`" 0 0
sleep 1
if [ "$HDR" = "yes" ]; then
if [ "$ROOT_DEVICE" != "" ]; then
DEFROOT="--default-item $ROOT_DEVICE"
fi
echo -n 'dialog --visit-items --title "' > $TMP/tmpmsg
eval_gettext "SELECT LINUX PARTITION \$DEFROOT" >> $TMP/tmpmsg
echo -n '" --menu "' >> $TMP/tmpmsg
gettext "Which Linux partition would you like LILO to boot?" >> $TMP/tmpmsg
echo "\n\\" >> $TMP/tmpmsg
echo "\n\\" >> $TMP/tmpmsg
echo -n ' Partition Start End Sectors ID" ' >> $TMP/tmpmsg
echo -n ' 22 80 13 ' >> $TMP/tmpmsg
LANG=C PROBE -l 2> /dev/null | grep "Linux$" | sort | while read STR; do
STR1="$(echo -n "$STR" | cut -f 1 -d ' ')"
STR2="$(echo -n "$STR" | cut -f 2- -d ' ')"
echo "\"$STR1\" \"$STR2\" \\" >> $TMP/tmpmsg
done
echo "2> $TMP/reply" >> $TMP/tmpmsg
. $TMP/tmpmsg
if [ $? = 1 -o $? = 255 ]; then
rm $TMP/tmpmsg
continue
fi
rm $TMP/tmpmsg
LINUX_PART="$(cat $TMP/reply)"
checkp_dialog $LINUX_PART
if [ ! $? = 0 ]; then
continue;
fi
dialog --title "`eval_gettext "SELECT PARTITION NAME FOR \\\$LINUX_PART"`" --inputbox \
"`gettext "Now you must select a short, unique name for this partition. \
You'll use this name if you specify a partition to boot at the \
LILO prompt. 'Linux' might not be a bad choice. THIS MUST BE A \
SINGLE WORD."`" 11 80 2> $TMP/reply
if [ $? = 1 -o $? = 255 ]; then
continue
fi
LABEL="$(cat $TMP/reply)"
cat << EOF >> $TMP/lilo.conf
# Linux bootable partition config begins
image = $KERNEL
root = $LINUX_PART
label = $LABEL
read-only # Partitions should be mounted read-only for checking
# Linux bootable partition config ends
EOF
else
dialog --title "CAN'T ADD LINUX PARTITION" --msgbox "You can't add \
partitions unless you start over with a new LILO header." 6 80
continue
fi
LNX="yes"
# MORE OS/2 DEAD CODE... DOESN'T HURT.
# THIS ITEM HAS LONG BEEN REMOVED FROM THE MENU...
elif [ "$REPLY" = "OS/2" ]; then
if [ "$HDR" = "yes" ]; then
gettext "These are possibly OS/2 partitions. They will be treated \
as such if you install them using this menu." > $TMP/tmpmsg
echo "\n\\" >> $TMP/tmpmsg
echo "\n\\" >> $TMP/tmpmsg
echo " Device Boot Start End Blocks Id System" >> $TMP/tmpmsg
PROBE -l | grep DOS | sort >> $TMP/tmpmsg
PROBE -l | grep HPFS | sort >> $TMP/tmpmsg
echo >> $TMP/tmpmsg
gettext "Which one would you like LILO to boot?" >> $TMP/tmpmsg
echo >> $TMP/tmpmsg
dialog --title "`gettext "SELECT OS/2 PARTITION"`" --no-collapse --inputbox \
"$(cat $TMP/tmpmsg)" 20 80 2> $TMP/reply
if [ $? = 1 -o $? = 255 ]; then
rm $TMP/tmpmsg
continue
fi
rm $TMP/tmpmsg
OS_2_PART="$(cat $TMP/reply)"
checkp_dialog $OS_2_PART
if [ ! $? = 0 ]; then
continue;
fi
dialog --title "`gettext "SELECT PARTITION NAME"`" --inputbox \
"`gettext "Now you must select a short, unique name for this partition. \
You'll use this name if you specify a partition to boot at the \
LILO prompt. 'OS/2' might not be a bad choice. THIS MUST BE A \
SINGLE WORD."`" 11 80 2> $TMP/reply
if [ $? = 1 -o $? = 255 ]; then
continue
fi
LABEL="$(cat $TMP/reply)"
TABLE="$(echo $OS_2_PART | cut -b1-8)"
if [ "$(echo $TABLE | cut -b6-8)" = "hda" ]; then
cat << EOF >> $TMP/lilo.conf
# OS/2 bootable partition config begins
other = $OS_2_PART
label = $LABEL
table = $TABLE
# OS/2 bootable partition config ends
EOF
else
cat << EOF >> $TMP/lilo.conf
# OS/2 bootable partition config begins
other = $OS_2_PART
label = $LABEL
table = $TABLE
loader = /boot/os2_d.b
# map-drive = 0x80
# to = 0x81
# map-drive = 0x81
# to = 0x80
# OS/2 bootable partition config ends
EOF
fi
else
dialog --title "`gettext "CAN'T ADD OS/2 PARTITION"`" --msgbox "`gettext "You can't add \
partitions unless you start over with a new LILO header."`" 6 80
continue
fi
LNX="yes"
elif [ "$REPLY" = "Windows" ]; then
dialog --infobox "\n`eval_gettext "Scanning for Windows partitions..."`" 0 0
sleep 1
if [ "$HDR" = "yes" ]; then
gettext "These are possibly Windows or DOS partitions. They will be treated
as such if you install them using this menu." > $TMP/tmpmsg
echo >> $TMP/tmpmsg
echo >> $TMP/tmpmsg
echo " Device Boot Start End Blocks Id System" >> $TMP/tmpmsg
PROBE -l | grep "DOS
Win
W95
FAT12
FAT16
HPFS" | grep -v "Ext'd" | grep -v "Extend" | sort | grep "$($OSPROBER 2> /dev/null | grep :Windows: | cut -f 1 -d :)" >> $TMP/tmpmsg
echo >> $TMP/tmpmsg
gettext "Which one would you like LILO to boot?" >> $TMP/tmpmsg
echo >> $TMP/tmpmsg
dialog --title "`gettext "SELECT WINDOWS PARTITION"`" --no-collapse --inputbox \
"$(cat $TMP/tmpmsg)" 20 80 2> $TMP/reply
if [ $? = 1 -o $? = 255 ]; then
rm $TMP/tmpmsg
continue
fi
rm $TMP/tmpmsg
DOSPART="$(cat $TMP/reply)"
checkp_dialog $DOSPART
if [ ! $? = 0 ]; then
continue;
fi
dialog --title "`gettext "SELECT PARTITION NAME"`" --inputbox \
"`gettext "Now you must select a short, unique name for this partition. \
You'll use this name if you specify a partition to boot at the \
LILO prompt. 'Windows' might not be a bad choice. THIS MUST BE A \
SINGLE WORD."`" 11 80 2> $TMP/reply
if [ $? = 1 -o $? = 255 ]; then
continue
fi
LABEL="$(cat $TMP/reply)"
unset USE_LOADER
TABLE="$(echo $DOSPART | cut -b1-8)"
if [ "$(echo $TABLE | cut -b6-8)" = "hda" ]; then
USE_LOADER="no"
fi
if [ "$(echo $TABLE | cut -b6-8)" = "sda" ]; then
if probe /dev/hda; then
USE_LOADER="yes"
else
USE_LOADER="no"
fi
fi
if [ "$USE_LOADER" = "no" ]; then
cat << EOF >> $TMP/lilo.conf
# Windows bootable partition config begins
other = $DOSPART
label = $LABEL
table = $TABLE
# Windows bootable partition config ends
EOF
else
cat << EOF >> $TMP/lilo.conf
# Windows bootable partition config begins
other = $DOSPART
label = $LABEL
# map-drive = 0x80
# to = 0x81
# map-drive = 0x81
# to = 0x80
table = $TABLE
# Windows bootable partition config ends
EOF
fi
else
dialog --title "`gettext "CAN'T ADD WINDOWS PARTITION"`" --msgbox "`gettext "You can't add \
partitions unless you start over with a new LILO header."`" 6 80
continue
fi
LNX="yes"
elif [ "$REPLY" = "Install" -o "$REPLY" = "Recycle" ]; then
if [ "$REPLY" = "Recycle" -a -r $T_PX/etc/lilo.conf ]; then
LNX="yes"
fi
if [ "$LNX" = "no" ]; then
dialog --title "`gettext "CAN'T INSTALL LILO"`" --msgbox "`gettext "LILO could not be \
installed. If you have not created a LILO configuration file by defining \
a new header and adding at least one bootable partition to it, you must do \
so before installing LILO. If you were attempting to use an existing LILO \
configuration file, it could not be found. Try making a new one."`" 9 80
continue
else
if [ "$REPLY" = "Install" ]; then
if [ -r $TMP/lilo.conf ]; then
if [ -r $T_PX/etc/lilo.conf ]; then
mv $T_PX/etc/lilo.conf $T_PX/etc/lilo.conf.bak
fi
cp $TMP/lilo.conf $T_PX/etc/lilo.conf
chmod 644 $T_PX/etc/lilo.conf
fi
fi
installcolor;
fi
rm -f $TMP/tmpmsg $TMP/reply
break
elif [ "$REPLY" = "Skip" ]; then
rm -f $TMP/tmpmsg $TMP/reply
break
elif [ "$REPLY" = "View" ]; then
if [ -r $TMP/lilo.conf ]; then
dialog --title "`gettext "YOUR NEW /etc/lilo.conf"`" --textbox "$TMP/lilo.conf" 22 80
else
if [ -r $T_PX/etc/lilo.conf ]; then
dialog --title "`gettext "YOUR OLD /etc/lilo.conf"`" --textbox "$T_PX/etc/lilo.conf" 22 80
elif [ "$T_PX" = "/" -a -r /etc/lilo.conf ]; then
dialog --title "`gettext "YOUR OLD /etc/lilo.conf"`" --textbox "/etc/lilo.conf" 22 80
else
dialog --title "`gettext "NO CONFIG FILE FOUND"`" --msgbox "`gettext "Sorry, but you don't \
have a LILO configuration file that can be viewed."`" 6 80
fi
fi
elif [ "$REPLY" = "Help" ]; then
# to internationalize text.lilohelp - <NAME>
if [ -f /usr/lib/config/display.lilohelp ]; then
/usr/lib/config/display.lilohelp
else
$T_PX/var/log/setup/display.lilohelp
fi
# dialog --title "LILO INSTALLATION HELP" --textbox "$T_PX/var/log/setup/text.lilohelp" 22 80
fi
done
| 864481782811c87c7182e3dad2158c211af43988 | [
"Shell"
] | 1 | Shell | gapan/liloconfig | 0e48efd5a8098eac7057c23355a1a88252cc53ed | cc58725411135e5daa27d7dc489f8e8a05269984 |
refs/heads/master | <repo_name>yarec/php-cmdb<file_sep>/src/db/RestHelper.php
<?php
namespace cm\db{
class RestHelper {
private static $_ins = null;
public static function ins($ins=null){
if($ins){
self::$_ins = $ins;
}
if(!self::$_ins && class_exists('\db\RestHelperIns')){
self::$_ins = new \db\RestHelperIns();
}
return self::$_ins;
}
public static function get_rest_xwh_tags_list(){
return self::ins()->get_rest_xwh_tags_list();
}
public static function get_rest_join_tags_list(){
return self::ins()->get_rest_join_tags_list();
}
public static function rest_extra_data($item){
return self::ins()->rest_extra_data($item);
}
public static function get_tags_by_oid($uid, $ids, $name){
return self::ins()->get_tags_by_oid($uid, $ids, $name);
}
public static function get_tag_by_name($uid, $name, $type){
return self::ins()->get_tag_by_name($uid, $name, $type);
}
public static function del_tag_by_name($uid, $id, $name){
return self::ins()->del_tag_by_name($uid, $id, $name);
}
public static function save_tag_items($uid, $tag_id, $id, $name){
return self::ins()->save_tag_items($uid, $tag_id, $id, $name);
}
public static function isAdmin(){
return self::ins()->isAdmin();
}
public static function isAdminRest(){
return self::ins()->isAdminRest();
}
public static function user_tbl(){
return self::ins()->user_tbl();
}
public static function data(){
return self::ins()->data();
}
public static function uid(){
return self::ins()->uid();
}
public static function get($k, $def=''){
return self::ins()->get($k, $def);
}
public static function gets(){
return self::ins()->gets();
}
public static function select_add(){
return self::ins()->select_add();
}
public static function join_add(){
return self::ins()->join_add();
}
public static function offset(){
return self::ins()->offset();
}
public static function pagesize(){
return self::ins()->pagesize();
}
}
}
<file_sep>/src/db/Rest.php
<?php
namespace cm\db{
use cm\db;
use cm\db\RestHelper;
class Rest {
private static $tbl_desc = [];
/**
* id=10
* id{<}=15
*/
public static function whereStr($where, $name){
$ret='';
foreach($where as $k=>$v){
$pattern='/(.*)\{(.*)\}/i';
$str=preg_match($pattern, $k, $matchs);
$kk_op = '=';
if($matchs){
$kk = $matchs[1];
$kk_op = $matchs[2];
}else{
$kk = $k;
}
if($col_type=db::valid_table_col($name, $kk)){
if($col_type==2){
$ret.=" and t1.$kk{$kk_op}'$v'";
}else{
$ret.=" and t1.$kk{$kk_op}$v";
}
}else{
#info("column [$k] not exist for table '$name'");
}
// info("[$name] [$kk] [$col_type] $ret");
}
return $ret;
}
public static function getSqlFrom($name, $join_add, $uid, $where_str, $order){
// Tags
$has_tags = isset($_GET['tags'])?1:0;
$is_adm_rest = isset($_GET['isar'])?1:0;
$rest_xwh_tags_list = RestHelper::get_rest_xwh_tags_list();
if($rest_xwh_tags_list && in_array($name, $rest_xwh_tags_list)){
$has_tags = 0;
}
$wh_uid = RestHelper::isAdmin() && $is_adm_rest ? "1=1" : "t1.uid=$uid";
if($has_tags){
$tags = get('tags');
if($tags && is_array($tags) && count($tags)==1 && !$tags[0]){
$tags = '';
}
$where_tags = '';
$in = 'not in';
if($tags){
if(is_string($tags)){
$tags = [$tags];
}
$tags_implode = implode("','", $tags);
$where_tags = "and `name` in ('$tags_implode')";
$in = 'in';
$sql_from = " from $name t1
join tag_items t on t1.id=t.`oid`
$join_add
where $wh_uid and t._st=1 and t.tagid $in
(select id from tags where type='$name' $where_tags )
$order";
}else{
$sql_from = " from $name t1
$join_add
where $wh_uid and t1.id not in
(select oid from tag_items where type='$name')
$order";
}
}else{
//$where_uid = "1=1";
$where_uid = $wh_uid;
if(RestHelper::isAdmin()){
//$where_uid = "t1.uid=$uid";
if($name == RestHelper::user_tbl()){
$where_uid = "t1.id=$uid";
}
}
$sql_from = "from $name t1 $join_add where $where_uid $where_str $order";
}
return $sql_from;
}
public static function getSql($name) {
$uid = RestHelper::uid();
// Sort
$sort = get('sort', '_intm');
$asc = get('asc', -1);
if(!db::valid_table_col($name, $sort)){
$sort = '_intm';
}
$asc = $asc>0?'asc':'desc';
$order = " order by t1.$sort $asc";
// Where
$get_data = RestHelper::gets();
$get_data = un_select_keys(['sort', 'asc'], $get_data);
$st = RestHelper::get('_st', 1);
$where = dissoc($get_data, ['token', '_st']);
if($st!='all'){
$where['_st'] = $st;
}
$where_str = self::whereStr($where, $name);
// search
$search = RestHelper::get('search', '');
$search_key = RestHelper::get('search-key', '');
if($search && $search_key){
$where_str .= " and $search_key like '%$search%'";
}
// Join
$select_add = RestHelper::select_add();
$join_add = RestHelper::join_add();
// Sql
$sql_from = self::getSqlFrom($name, $join_add, $uid, $where_str, $order);
$sql = "select t1.* $select_add $sql_from";
$sql_cnt = "select count(*) cnt $sql_from";
$offset = RestHelper::offset();
$pagesize = RestHelper::pagesize();
$sql .= " limit $offset,$pagesize";
// info("---GET---: $name $sql");
// info("---GET---: $name $sql_cnt");
return [$sql, $sql_cnt];
}
public static function getResName($name){
$res_id_key = RestHelper::get('res_id_key', '');
if($res_id_key){
$res_id = RestHelper::get($res_id_key);
$name .= '_' . $res_id;
}
return $name;
}
/*
$rows = rest::getList($tblname, ['join_cols'=> [
'bom_hot_part_opt' => [
'on' => 'pid',
'jkeys' => [
'id' => 'opt_id',
]
],
'bom_hot_part_opt_ext' =>[
'on' => ['opt_id' => 'pid'],
'jtype' => '1-n',
'jkey' => 'option',
]
]]);
$rows = rest::getList('task_list', ['join_cols'=>[
'task_item' => [
'on' => 'list_id',
'jtype'=> '1-n-o',
'jkey' => 'items'
]
]]);
*/
public static function getList($name, $opts=[]){
$uid = RestHelper::uid();
list($sql, $sql_cnt) = self::getSql($name);
$rows = db::query($sql);
$count = (int)db::queryOne($sql_cnt);
$join_tags_list = RestHelper::get_rest_join_tags_list();
if($join_tags_list && in_array($name, $join_tags_list)){
$ids = getKeyValues($rows, 'id');
$tags = RestHelper::get_tags_by_oid($uid, $ids, $name);
info("get tags ok: $uid $name " . json_encode($ids));
foreach($rows as $k=>$row){
// $rows[$k]['tags'] = tag::getTagsByOid($uid, $row['id'], $name);
if(isset($tags[$row['id']])){
$tag_item = $tags[$row['id']];
$rows[$k]['tags'] = getKeyValues($tag_item, 'name');
}
}
info('set tags ok');
}
if(isset($opts['join_cols'])){
foreach ($opts['join_cols'] as $jtbl => $jopt) {
$jtype = getArg($jopt, 'jtype', '1-1');
$jkeys = getArg($jopt, 'jkeys', []);
$jwhe = getArg($jopt, 'jwhe', []);
if(is_string($jopt['on'])){
$lon = 'id';
$ron = $jopt['on'];
}else if(is_array($jopt['on'])){
$on_keys = array_keys($jopt['on']);
$lon = $on_keys[0];
$ron = $jopt['on'][$lon];
}
// info("------jopt: $jtype $lon $ron ");
$ids = getKeyValues($rows, $lon);
$jwhe[$ron] = $ids;
$jrows = \db::all($jtbl, [
'AND' => $jwhe,
]);
foreach ($jrows as $key => $jrow) {
// info($jrow);
foreach($rows as $k=>&$row){
if(isset($row[$lon]) && isset($jrow[$ron]) && $row[$lon] == $jrow[$ron]){
if($jtype == '1-1'){
foreach ($jkeys as $jkey => $jaskey) {
$row[$jaskey] = $jrow[$jkey];
}
}
$jkey = isset($jopt['jkey']) ? $jopt['jkey'] : $jtbl;
if($jtype == '1-n'){
$row[$jkey][] = $jrow[$jkey];
}
if($jtype == '1-n-o'){
$row[$jkey][] = $jrow;
}
if($jtype == '1-1-o'){
$row[$jkey] = $jrow;
}
}
}
}
}
}
$res_name = self::getResName($name);
return ['data'=>$rows, 'res-name'=>$res_name, 'count'=>$count];
}
public static function renderList($name){
ret(self::getList($name));
}
public static function getItem($name, $id){
$uid = RestHelper::uid();
info("---GET---: $name/$id");
$res_name = "$name-$id";
if($name=='colls'){
$item = db::row( $name, ["$name.id"=>$id],
[ "$name.id", "$name.title", "$name.from_url", "$name._intm", "$name._uptm", "posts.content"],
['[>]posts' => ['uuid'=>'uuid']]
);
}else{
if($name=='feeds'){
$type = RestHelper::get('type');
$rid = RestHelper::get('rid');
$item = db::row($name, ['AND' => [ 'uid'=>$uid, 'rid'=>$id, 'type'=>$type ]]);
if(!$item){
$item = [ 'rid' => $id, 'type' => $type, 'excerpt' => '', 'title' => '', ];
}
$res_name = "{$res_name}-$type-$id";
}else{
$item = db::row($name, ['id'=>$id]);
}
}
if($extra_data = RestHelper::rest_extra_data()){
$item = array_merge($item, $extra_data);
}
return ['data'=>$item, 'res-name'=>$res_name, 'count'=>1];
}
public static function renderItem($name, $id){
ret(self::getItem($name, $id));
}
public static function postData($name){
$data = db::tbl_data($name, RestHelper::data());
$uid = RestHelper::uid();
$tags = [];
if($name=='tags'){
$tags = RestHelper::get_tag_by_name($uid, $data['name'], $data['type']);
}
if($tags && $name=='tags'){
$data = $tags[0];
}else{
info("---POST---: $name ".json_encode($data));
unset($data['token']);
$data['_intm'] = date('Y-m-d H:i:s');
if(!isset($data['uid'])){
$data['uid'] = $uid;
}
$data = db::tbl_data($name, $data);
// \vld::test($name, $data);
$data = db::save($name, $data);
}
return $data;
}
public static function renderPostData($name){
$data = self::postData($name);
ret($data);
}
public static function putData($name, $id){
if($id==0 || $id=='' || trim($id)==''){
info(" PUT ID IS EMPTY !!!");
ret();
}
$uid = RestHelper::uid();
$data = RestHelper::data();
#$data = \db::tbl_data($name, \ctx::data());
unset($data['token']);
unset($data['uniqid']);
self::checkOwner($name, $id, $uid);
if(isset($data['inc'])){
$field = $data['inc'];
unset($data['inc']);
db::exec("UPDATE $name SET $field = $field + 1 WHERE id=$id");
}
if(isset($data['dec'])){
$field = $data['dec'];
unset($data['dec']);
db::exec("UPDATE $name SET $field = $field - 1 WHERE id=$id");
}
if(isset($data['tags'])){
// info("up tags");
RestHelper::del_tag_by_name($uid, $id, $name);
$tags = $data['tags'];
foreach($tags as $tag_name){
$tag = RestHelper::get_tag_by_name($uid, $tag_name, $name);
// info($tag);
if ($tag) {
$tag_id = $tag[0]['id'];
RestHelper::save_tag_items($uid, $tag_id, $id, $name);
}
#info("tags: $name $id ". $tag_name);
}
}
//Fixme: should not exec when inc or dec
info("---PUT---: $name/$id ".json_encode($data));
$data = db::tbl_data($name, RestHelper::data());
$data['id'] = $id;
db::save($name, $data);
return $data;
}
public static function renderPutData($name, $id){
$data = self::putData($name, $id);
ret($data);
}
public static function delete($req, $name, $id){
$uid = RestHelper::uid();
self::checkOwner($name, $id, $uid);
db::save($name,['_st'=>0, 'id'=>$id]);
ret([]);
}
public static function checkOwner($name, $id, $uid){
//$item = \db::row($name, ['id'=>$id]);
$where = [
'AND' => ['id'=>$id],
'LIMIT' => 1,
];
$rows = db::obj()->select($name, '*', $where);
if($rows){
$item = $rows[0];
}else{
$item = null;
}
if($item){
if(array_key_exists('uid', $item)){
$db_uid = $item['uid'];
if($name==RestHelper::user_tbl()){
$db_uid = $item['id'];
}
if($db_uid!=$uid && (!RestHelper::isAdmin() || !RestHelper::isAdminRest())){
ret(311, 'owner error');
}
}else if(!RestHelper::isAdmin()){
ret(311, 'owner error');
}
}else{
ret(312, 'not found error');
}
}
}
}
<file_sep>/src/db/RestHelperIF.php
<?php
namespace cm\db{
interface RestHelperIF
{
public function get_rest_xwh_tags_list();
public function get_rest_join_tags_list();
public function rest_extra_data($item);
public function get_tags_by_oid($uid, $ids, $name);
public function get_tag_by_name($uid, $name, $type);
public function del_tag_by_name($uid, $id, $name);
public function save_tag_items($uid, $tag_id, $id, $name);
public function isAdmin();
public function isAdminRest();
public function user_tbl();
public function data();
public function uid();
public function get($k, $def);
public function gets();
public function select_add();
public function join_add();
public function offset();
public function pagesize();
}
}
<file_sep>/src/db.php
<?php
namespace cm;
use Medoo\Medoo;
// function startWith($str, $s){
// return strpos($str, $s) === 0;
// }
// function is_string_column($type){
// if(startWith(strtolower($type), 'char')
// || startWith(strtolower($type), 'varchar')
// || startWith(strtolower($type), 'datetime')){
// return 2;
// }else{
// return 1;
// }
// }
// cm\db::init([
// 'database_type' => 'mysql',
// 'database_name' => 'myapp_dev',
// 'server' => 'mysql',
// 'username' => 'root',
// 'password' => '<PASSWORD>',
// 'charset' => 'utf8',
// ]);
if (!function_exists('fixfn')) {
function fixfn ($fnlist){
foreach($fnlist as $fname){
if (!function_exists($fname)) {
eval("function $fname(){}");
}
}
}
}
if (!class_exists('cfg')) {
class cfg {
public static function get_db_cfg(){
return array(
'database_type' => 'mysql',
'database_name' => 'myapp_dev',
'server' => 'mysql',
'username' => 'root',
'password' => '<PASSWORD>',
'charset' => 'utf8',
);
}
}
}
$fnlist = array(
'debug',
);
fixfn($fnlist);
class db {
private static $_db_list;
private static $_db_default;
private static $_db;
private static $_dbc;
private static $_ins;
private static $tbl_desc = [];
public static function init($cfg, $withUse=true) {
self::init_db($cfg, $withUse);
}
public static function new_db($cfg){
return new Medoo($cfg);
}
public static function get_db_cfg($cfg='use_db') {
if(is_string($cfg)){
$cfg = \cfg::get_db_cfg($cfg);
}
$cfg['database_name'] = env('DB_NAME', $cfg['database_name']);
$cfg['server'] = env('DB_HOST', $cfg['server']);
$cfg['username'] = env('DB_USER', $cfg['username']);
$cfg['password'] = env('DB_PASS', $cfg['password']);
return $cfg;
}
/**
* @param $cfg
* @param bool $withUse
*
* \db::init_db('use_db1');
*
* or
*
* $db_cfg = \cfg::get_db_cfg('use_db1');
* \db::init_db($db_cfg);
*
*/
public static function init_db($cfg, $withUse=true) {
self::$_dbc = self::get_db_cfg($cfg);
$dbname = self::$_dbc['database_name'];
self::$_db_list[$dbname] = self::new_db(self::$_dbc);
if($withUse){
self::use_db($dbname);
}
}
public static function use_db($dbname) {
self::$_db = self::$_db_list[$dbname];
}
public static function use_default_db() {
self::$_db = self::$_db_default;
}
public static function dbc() {
return self::$_dbc;
}
public static function obj() {
if(!self::$_db){
self::$_dbc = self::get_db_cfg();
self::$_db = self::$_db_default = self::new_db(self::$_dbc);
}
return self::$_db;
}
public static function db_type(){
if(!self::$_dbc){
self::obj();
}
return self::$_dbc['database_type'];
}
public static function desc_sql($tbl_name){
if(self::db_type()=='mysql'){
return "desc $tbl_name";
}else if(self::db_type()=='pgsql'){
return "SELECT COLUMN_NAME, DATA_TYPE FROM information_schema.COLUMNS WHERE TABLE_NAME = '$tbl_name'";
} else return '';
}
public static function table_cols($name){
$tbl_desc = self::$tbl_desc;
if(!isset($tbl_desc[$name])){
$sql = self::desc_sql($name);
if($sql){
$tbl_desc[$name] = self::query($sql);
self::$tbl_desc = $tbl_desc;
debug("---------------- cache not found : $name");
}else{
debug("empty desc_sql for: $name");
}
}
if(!isset($tbl_desc[$name])){
return array();
}else{
return self::$tbl_desc[$name];
}
}
public static function col_array($name){
$fn = function($v) use($name){
return $name.'.'.$v;
};
return getKeyValues(self::table_cols($name), 'Field', $fn);
}
public static function valid_table_col($name, $col){
$table_cols = self::table_cols($name);
foreach($table_cols as $tbl_col){
if($tbl_col['Field']==$col){
$type = $tbl_col['Type'];
return is_string_column($tbl_col['Type']);
}
}
return false;
}
public static function tbl_data($name, $data){
$table_cols = self::table_cols($name);
$ret = [];
foreach($table_cols as $tbl_col){
$col_name = $tbl_col['Field'];
if(isset($data[$col_name])){
$ret[$col_name] = $data[$col_name];
}
}
return $ret;
}
public static function test(){
$sql = "select * from tags limit 10";
$rows = self::obj()->query($sql)->fetchAll(\PDO::FETCH_ASSOC);
var_dump($rows);
}
public static function has_st($name, $cond){
$st_col_name = '_st';
return isset($cond[$st_col_name]) || isset($cond[$name.'.'.$st_col_name]);
}
public static function getWhere($name, $where){
// $name = preg_replace('/\(.*\)/', '', "`$name`");
// debug(" getWhere : $name");
$st_col_name = '_st';
if(!self::valid_table_col($name, $st_col_name)){
return $where;
}
$st_col_name = $name.'._st';
if (is_array($where))
{
$where_keys = array_keys($where);
$where_AND = preg_grep("/^AND\s*#?$/i", $where_keys);
$where_OR = preg_grep("/^OR\s*#?$/i", $where_keys);
$single_condition = array_diff_key($where, array_flip(
explode(' ', 'AND OR GROUP ORDER HAVING LIMIT LIKE MATCH')
));
$cond = [];
if ($single_condition != array()) {
$cond = $single_condition;
if(!self::has_st($name, $cond)){
$where[$st_col_name]=1;
$where = ['AND' => $where];
}
}
if (!empty($where_AND)) {
$value = array_values($where_AND);
$cond = $where[$value[0]];
if(!self::has_st($name, $cond)){
$where[$value[0]][$st_col_name]=1;
}
}
if (!empty($where_OR)) {
$value = array_values($where_OR);
$cond = $where[$value[0]];
if(!self::has_st($name, $cond)){
$where[$value[0]][$st_col_name]=1;
}
}
if(!isset($where['AND']) && !self::has_st($name, $cond)){
$where['AND'][$st_col_name]=1;
}
}
return $where;
}
public static function all_sql($name, $where=[], $cols='*', $join=null){
$map = [];
if($join){
$sql= self::obj()->selectContext($name, $map, $join, $cols, $where);
}else{
$sql= self::obj()->selectContext($name, $map, $cols, $where);
}
return $sql;
}
// $user_fields = array_merge(
// db::col_array('user'),
// ['users_bind.username','users_bind.avatar','users_bind.nickname']
// );
// $user_join = ['[>]users_bind'=>['id'=>'uid']];
//
// $where = [];
// if($keyword){
// $where = ['user.nickname[~]'=>$keyword];
// }
//
// ctx::count(db::count('user', $where));
// $whe = [
// 'AND'=> $where,
// 'ORDER'=>['user.id'=>'DESC'],
// 'LIMIT'=>ctx::limit()
// ];
// $data = [
// 'users'=>db::all('user', $whe , $user_fields, $user_join),
// 'pageinfo' => ctx::pageinfo(),
// 'tpl'=>'/admin/user_list'
// ];
public static function all($name, $where=[], $cols='*', $join=null){
$where = self::getWhere($name, $where);
if($join){
$rows = self::obj()->select($name, $join, $cols, $where);
}else{
$rows = self::obj()->select($name, $cols, $where);
}
return $rows;
}
public static function count($name, $where=['_st'=>1]){
$where = self::getWhere($name, $where);
return self::obj()->count($name, $where);
}
public static function row_sql($name, $where=[], $cols='*', $join=''){
return self::row($name, $where, $cols, $join, true);
}
public static function row($name, $where=[], $cols='*', $join='', $sql_only=null){
$where = self::getWhere($name, $where);
if(!isset($where['LIMIT'])){
$where['LIMIT'] = 1;
}
if($join){
if($sql_only) return self::obj()->selectContext($name, $join, $cols, $where);
$rows = self::obj()->select($name, $join, $cols, $where);
}else{
if($sql_only) return self::obj()->selectContext($name, $cols, $where);
$rows = self::obj()->select($name, $cols, $where);
}
if($rows){
return $rows[0];
}else{
return null;
}
}
public static function one($name, $where=[], $cols='*', $join=''){
$row = self::row($name, $where, $cols, $join);
$var = '';
if($row){
$keys = array_keys($row);
$var = $row[$keys[0]];
}
return $var;
}
public static function parseUk($name, $uk, $data){
$data_has_uk = true;
if(is_array($uk)){
foreach($uk as $item){
if(!isset($data[$item])){
$data_has_uk = false;
}else{
$whe[$item] = $data[$item];
}
}
}
else {
if (!isset($data[$uk])) {
$data_has_uk = false;
}else{
$whe = [$uk => $data[$uk]];
}
}
$isInsert = false;
if($data_has_uk){
if(!self::obj()->has($name, ['AND' => $whe])){
$isInsert = true;
}
}else{
$isInsert = true;
}
return [$whe, $isInsert];
}
public static function save($name, $data, $uk='id'){
list($whe, $isInsert) = self::parseUk($name, $uk, $data);
// info("isInsert: $isInsert, $name $uk ". json_encode($data));
if($isInsert){
debug("insert $name : ".json_encode($data) );
self::obj()->insert($name, $data);
$data['id'] = self::obj()->id();
}else{
debug("update $name " . json_encode($whe));
self::obj()->update($name, $data, ['AND' => $whe]);
}
return $data;
}
public static function update($name, $data, $where){
self::obj()->update($name, $data, $where);
}
public static function exec($sql){
return self::obj()->query($sql);
}
public static function query($sql){
return self::obj()->query($sql)->fetchAll(\PDO::FETCH_ASSOC);
}
public static function queryRow($sql){
$rows = self::query($sql);
if($rows){
return $rows[0];
}else{
return null;
}
}
public static function queryOne($sql){
$row = self::queryRow($sql);
return self::oneVal($row);
}
public static function oneVal($row){
$var = '';
if($row){
$keys = array_keys($row);
$var = $row[$keys[0]];
}
return $var;
}
/**
* 根据id批量更新
* 调用示例:
* $IDs = array_flip($IDs);
* foreach($IDs as &$id){
* $id = array(
* 'priority' => $id++
* );
* }
* updateBatch($IDs)
* $someModel->updateBatch(array(
* 9 => array(
* 'values' => 1,
* 'sort' => 1
* ),
* 10 => array(
* 'values' => 11,
* 'sort' => 2
* ),
* ));
* @param string $where
* @param array $data 键名为主键id,键值为各个字段的值
* @return boolean|boolean|number
*/
public static function updateBatch($name, $data){
$table = $name;
if(!is_array($data) || empty($table))return FALSE;
$sql = "UPDATE `$table` SET";
foreach($data as $id => $row){
foreach($row as $key=>$val){
$toDB[$key][] = "WHEN $id THEN $val";
}
}
foreach($toDB as $key=>$val){
$sql .= ' `'.trim($key, '`').'`=CASE id '.join(' ', $val).' END,';
}
$sql = trim($sql, ',');
$sql .= ' WHERE id IN('.join(',', array_keys($data)).')';
return self::query($sql);
}
}
| 638c7cc78eef003c94c0c9bcaf3e62c36553fb63 | [
"PHP"
] | 4 | PHP | yarec/php-cmdb | 7b224b98a29bd560a8751222ef58b4875ded57a0 | acb545fc176f459a84c60fe28b66447b4a28d577 |
refs/heads/master | <repo_name>309316777/eightwords<file_sep>/include/calendar_type.h
#ifndef __CALENDAR_TYPE_H__
#define __CALENDAR_TYPE_H__
#include <map>
#include <string>
struct CalendarKey
{
int year; // 英文年
int month; // 英文月
int day; // 英文日
};
inline bool operator<(const CalendarKey &lhs, const CalendarKey &rhs)
{
if (lhs.year < rhs.year)
return true;
if (lhs.year > rhs.year)
return false;
if (lhs.month < rhs.month)
return true;
if (lhs.month > rhs.month)
return false;
if (lhs.day < rhs.day)
return true;
if (lhs.day > rhs.day)
return false;
return true;
}
inline bool operator==(const CalendarKey &lhs, const CalendarKey &rhs)
{
return lhs.year == rhs.year && lhs.month == rhs.month && lhs.day == rhs.day;
}
struct CalendarDay
{
std::string chinaYear; // 中文年
std::string chinaMonth; // 中文月
std::string chinaDay; // 中文日
};
// 英中日历对照
typedef std::map<CalendarKey, CalendarDay> CalendarDayList;
#endif
<file_sep>/include/face_converter.h
#ifndef __FACE_CONVERTER_H__
#define __FACE_CONVERTER_H__
#include <iconv.h>
#include <string>
enum face
{
face_utf8 = 0,
face_gb2312,
face_big5,
face_gbk
};
class Convertor
{
public:
static std::string face_to_string(face f);
Convertor(face in_face, face out_face);
~Convertor();
std::string convert(const std::string &src);
private:
iconv_t _iconv = nullptr;
};
#endif
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 2.8.4)
project(eightwords)
message(STATUS "Current system ${CMAKE_SYSTEM_NAME}")
add_definitions(-std=c++11)
include_directories(
"./include"
)
file(GLOB src "./src/*.cpp")
add_executable(eightwords ${src})
find_package(Boost 1.54 REQUIRED program_options)
if (APPLE)
message(STATUS "Apple needs linking libiconv")
set(ICONVLIB "iconv")
endif(APPLE)
target_link_libraries(eightwords sqlite3 ${ICONVLIB} ${Boost_LIBRARIES})
<file_sep>/README.md
# 八字排盘源代码
## 用途
将英文年、月、日、时进行八字排盘。例入:输入1990-10-10 7时(程序默认参数)将输出:“庚午 丙戌 戊申 丙辰”
## 编译
### 库需求
#### Boost
解析命令行参数使用
#### iconv
字符集转换使用
#### sqlite3
从sqlite3数据库中查询农历日期
### 编译指令
```
mkdir build
cd build && cmake ..
make
```
## 使用说明
编译出来的工具为命令行工具,使用-h或--help将显示以下命令行信息
```
-h [ --help ] 显示帮助
-y [ --year ] arg (=1990) 年
-m [ --month ] arg (=10) 月
-d [ --day ] arg (=10) 日
-H [ --hour ] arg (=7) 小时
-s [ --sqlite3 ] arg Sqlite3数据库文件名称
```
需要通过--sqlite3,-s参数将日历数据库文件路径传给程序,日历数据库文件名称为calendar.db,保存在工程目录的data目录下
例如,执行如下命令将会把1980年2月10日3点出生的八字排盘
```
build/eightwords -s ./data/calendar.db -y 1980 -m 2 -d 10 -H 3
```
命令结果为
```
庚申 戊寅 癸丑 甲寅
```
<file_sep>/src/main.cpp
#include <iostream>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
#include "calendar.h"
#include "eightwords.h"
class Arguments
{
public:
Arguments(int argc, const char *argv[])
{
m_options.add_options() // all options
("help,h", "显示帮助") // --help, -h
("year,y", po::value(&year)->default_value(1990), "年") // --year, -y
("month,m", po::value(&month)->default_value(10), "月") // --month, -m
("day,d", po::value(&day)->default_value(10), "日") // --day, d
("hour,H", po::value(&hour)->default_value(7), "小时") // --hour, -h
("sqlite3,s", po::value(&sqlite3File), "Sqlite3数据库文件名称") // --sqlite3, -s
;
po::variables_map vars;
po::store(po::parse_command_line(argc, argv, m_options), vars);
po::notify(vars);
if (vars.count("help") > 0)
{
help = true;
}
}
void showHelp()
{
std::cout << m_options << std::endl;
}
public:
bool help = false;
int year;
int month;
int day;
int hour;
std::string sqlite3File;
private:
po::options_description m_options;
};
int main(int argc, const char *argv[])
{
try
{
// 解析参数
Arguments args(argc, argv);
if (args.help)
{
args.showHelp();
return 0;
}
// 校验参数
if (args.year < 1920 || args.year > 2019)
{
throw std::runtime_error("无效的年(1920-2019)");
}
if (args.month < 1 || args.month > 12)
{
throw std::runtime_error("无效的月(1-12)");
}
if (args.day < 1 || args.day > 31)
{
throw std::runtime_error("无效的日(1-31)");
}
if (args.hour < 1 || args.hour > 24)
{
throw std::runtime_error("无效的小时(1-24)");
}
if (args.sqlite3File.empty())
{
throw std::runtime_error("请指定Sqlite3本地数据库文件");
}
// 转换中文日期
Calendar calendar(args.sqlite3File);
CalendarDay chinaDay = calendar.queryChinaDay(args.year, args.month, args.day);
// 查询时辰
Table8x2 table;
CNStringList result = table.analyze(chinaDay.chinaYear, chinaDay.chinaMonth, chinaDay.chinaDay, args.hour);
// 输出八字
for (const CNString &str : result)
{
for (const CNChar &ch : str)
{
std::cout << ch;
}
std::cout << " ";
}
std::cout << std::endl;
}
catch (std::exception &except)
{
std::cerr << "错误: " << except.what() << std::endl;
}
return 0;
}
| 0f3939b677e47cc83026ed5ace003b0c9c7de154 | [
"Markdown",
"CMake",
"C++"
] | 5 | C++ | 309316777/eightwords | 086b70505f77f170999dd43a61c1442b2042a3a9 | 018f3fcb7b7da1a4753fd5ac8879c6a3316247a3 |
refs/heads/master | <repo_name>Richard-Choooou/image-compress<file_sep>/src/static/js/compress.js
import AddEvents from './events'
import store from '../../store'
const path = window.require('path')
const Https = window.require('https')
const imagemin = window.imagemin
const imageminMozJpeg = window.imageminMozJpeg
const imageminPngquant = window.imageminPngquant
const imageminGifsicle = window.imageminGifsicle
const fsExtra = window.fsExtra
const electron = window.require('electron')
const { shell } = electron.remote
let userConfig = store.getState()
store.subscribe(() => {
userConfig = store.getState()
})
class Compress {
constructor(files, options) {
this.startTime = Date.now()
this.savePath = path.resolve(userConfig.saveFilesDir, userConfig.isCreateNewDir ? this.startTime + '' : '')
this.isOnline = userConfig.compressMode === 'online'
this.files = files
this.uploadList = new Map()
if (this.isOnline) {
this.onlineCompress()
} else {
this.offlineCompress()
}
}
getUploadList() {
return this.uploadList
}
onlineCompress() {
this.uploadList = this.files.reduce((last, file) => {
let uploadPromise = this.uploadFileToServer(file)
uploadPromise.then((xhrResponse => {
return this.downloadToLocal(xhrResponse, uploadPromise, file)
}))
last.set(uploadPromise, {})
return last
}, new Map())
Promise.all(this.uploadList.keys()).then(data => {
this.openCompressSuccessNotification()
console.log('全部压缩完成')
}).catch(e => {
console.log(e)
}).finally(data => {
this.dispatchEvent('allDone')
})
}
uploadFileToServer(file) {
const xhrPromise = new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open("POST", "https://tinypng.com/web/shrink")
const setState = (obj) => {
obj = Object.assign({
name: file.name,
state: 'upload',
progress: 0,
isDone: false
}, this.uploadList.get(xhrPromise), obj)
this.uploadList.set(xhrPromise, obj)
this.dispatchEvent('stateChange', obj)
}
xhr.upload.onprogress = (e) => {
if (e.type === "progress") {
let progress = (e.loaded / e.total * 100).toFixed(0)
let state = {}
if (progress < 100) {
state = {
progress,
state: 'uploading'
}
} else {
state = {
progress,
state: 'compressing'
}
}
setState(state)
}
}
xhr.onabort = (e) => {
console.log('onabort', arguments)
setState({
progress: 0,
state: 'cancel'
})
reject(e)
}
xhr.onerror = function (e) {
console.error('onerror', arguments)
setState({
state: 'error'
})
reject(e)
}
xhr.onload = function (event) {
if (event.target.status === 201) {
setState({
state: 'compressed'
})
resolve(JSON.parse(event.target.responseText))
} else {
reject(event.target)
}
}
xhr.send(file)
})
return xhrPromise
}
downloadToLocal(ServerData, xhrPromise, file) {
const setState = (state) => {
state = Object.assign({
progress: 100,
isDone: false,
state: 'downloading',
name: file.name
}, state)
this.uploadList.set(xhrPromise, state)
this.dispatchEvent('stateChange', state)
}
return new Promise((resolve, reject) => {
Https.get(ServerData.output.url, (res, req) => {
res.setEncoding('binary')
if (res.statusCode === 200) {
let imgData = ''
res.on('data', (d) => {
imgData += d
setState({
state: 'downloading',
})
console.log('正在下载中')
});
res.on('end', () => {
fsExtra.outputFile(path.resolve(this.savePath, file.name), imgData, 'binary', e => {
if (e) {
console.error(e)
setState({
state: 'error',
})
} else {
console.log('保存成功')
}
})
setState({
isDone: true,
state: 'downloaded',
})
resolve('下载完成')
})
}
}).on('error', (e) => {
console.error(e);
setState({
isDone: true,
state: 'error',
})
reject('下载失败')
})
})
}
async offlineCompress() {
await imagemin(this.files.map(file => file.path), this.savePath, {
use: [
imageminGifsicle({
optimizationLevel: Math.floor(userConfig.compressLevel / 3)
}),
imageminPngquant({
quality: 100 - userConfig.compressLevel * 10
}),
imageminMozJpeg({
quality: 100 - userConfig.compressLevel * 10
})
]
})
this.openCompressSuccessNotification()
}
openCompressSuccessNotification() {
new Notification('压缩完成', {
body: '点击打开'
}).onclick = () => {
shell.openItem(this.savePath)
}
}
}
AddEvents(Compress)
export default Compress<file_sep>/public/renderer.js
global.imagemin = require('imagemin')
// global.imageminJpegtran = require('imagemin-jpegtran')
global.imageminPngquant = require('imagemin-pngquant')
global.imageminGifsicle = require('imagemin-gifsicle')
global.imageminMozJpeg = require('imagemin-mozjpeg')
global.fsExtra = require('fs-extra')<file_sep>/src/store/actions.js
import TYPES from './action_types'
function setUserConfigToStorage(config) {
localStorage.setItem('userConfig', JSON.stringify(config))
}
export default {
[TYPES.SET_SAVE_FILE_DIR](state, value) {
state.saveFilesDir = value
setUserConfigToStorage(state)
return state
},
[TYPES.SET_CREATE_NEW_DIR_STATE](state, value) {
state.isCreateNewDir = value
setUserConfigToStorage(state)
return state
},
[TYPES.SET_COMPRESS_MODE](state, value) {
state.compressMode = value
setUserConfigToStorage(state)
return state
},
[TYPES.SET_COMPRESS_LEVEL](state, value) {
state.compressLevel = value
setUserConfigToStorage(state)
return state
}
}<file_sep>/README.md
# 跨平台客户端压缩工具
基于electron以及react开发,欢迎fork
# 使用到的工具
在线压缩:[https://tinypng.com/](https://tinypng.com/) 的压缩api
离线压缩:[https://www.npmjs.com/package/imagemin](https://www.npmjs.com/package/imagemin)
# 使用的框架(库)
* react
* redux
* ant-design
* imagemin
* react-dropzone
# 预览

# 开发
运行
> npm run start
进行开发,如果app中是空白页面,则需要在console中输入,window.location.reload()刷新页面。
# 打包
运行
>npm run package
# 禁止用于商业目的
该项目仅用于学习交流,禁止用于商业开发<file_sep>/src/components/dir_manager/dir_manager.js
import './style.scss'
import React, { Component } from 'react'
import Checkbox from 'antd/lib/checkbox'
import 'antd/lib/checkbox/style/css'
import { connect } from 'react-redux'
const electron = window.require('electron')
const { dialog, shell } = electron.remote
class DirManager extends Component {
openChooseDir() {
dialog.showOpenDialog({
title: '请选择一个文件夹',
defaultPath: this.props.saveFilesDir,
properties: ['openDirectory', 'createDirectory']
}, dirs => {
if (!dirs) return
this.props.setSaveFileDir(dirs[0])
})
}
openChoosedDir() {
shell.openItem(this.props.saveFilesDir)
}
isCreateNewDirChange(e) {
this.props.setCreateNewDirState(e.target.checked)
}
render() {
return (
<div className="dir-manager-container">
<div className="dir-tool">
<p className="dir-path">{this.props.saveFilesDir}</p>
<button className="btn" onClick={(e) => this.openChooseDir(e)}>选择</button>
<button className="btn" onClick={(e) => this.openChoosedDir(e)}>打开目录</button>
</div>
<Checkbox onChange={(e) => this.isCreateNewDirChange(e)} checked={this.props.isCreateNewDir}>是否创建独立文件夹存放图片</Checkbox>
</div>
)
}
}
export default connect(state => {
return {
saveFilesDir: state.saveFilesDir,
isCreateNewDir: state.isCreateNewDir
}
}, dispatch => {
return {
setSaveFileDir(path) {
const action = {
type: 'SET_SAVE_FILE_DIR',
value: path
}
dispatch(action)
},
setCreateNewDirState(state) {
const action = {
type: 'SET_CREATE_NEW_DIR_STATE',
value: state
}
dispatch(action)
}
}
})(DirManager)<file_sep>/src/App.js
import React, { Component } from 'react'
import Dropzone from 'react-dropzone'
import DirManager from './components/dir_manager/dir_manager'
import Compress from './static/js/compress'
import Progress from 'antd/lib/progress'
import Slider from 'antd/lib/slider'
import Switch from 'antd/lib/switch'
import Tooltip from 'antd/lib/tooltip'
import Icon from 'antd/lib/icon'
import 'antd/lib/progress/style/css'
import 'antd/lib/slider/style/css'
import 'antd/lib/switch/style/css'
import 'antd/lib/icon/style/css'
import 'antd/lib/tooltip/style/css'
import './App.scss'
import { connect } from 'react-redux'
const electron = window.require('electron')
const { shell } = electron.remote
const uploadIcon = require('./static/images/upload.svg')
class App extends Component {
constructor(props) {
super(props)
this.state = {
uploadList: new Map()
}
window.addEventListener('online', () => {
this.props.setCompressMode('online')
})
window.addEventListener('offline', () => {
this.props.setCompressMode('offline')
})
this.fileFilter = {
online: /^image\/(png|jpg|jpeg)$/,
offline: /^image\/(png|jpg|jpeg|gif)$/
}
}
onDrop(acceptedFiles) {
this.setState({
uploadList: new Map()
})
this.imageFiles = acceptedFiles.filter(
file => this.props.compressMode === 'online' ? this.fileFilter.online.test(file.type) : this.fileFilter.offline.test(file.type)
).filter(
file => this.props.compressMode === 'offline' ? true : file.size < 1024 * 1024 * 5
)
const compressInstance = new Compress(this.imageFiles)
compressInstance.on('stateChange', data => {
// console.log(data)
this.setState({
uploadList: compressInstance.getUploadList()
})
})
}
onCompressModeChange(checked) {
if (!window.navigator.onLine) return
this.props.setCompressMode(checked ? 'online' : 'offline')
}
onCompressLevelChange(value) {
// console.log(value)
this.props.setCompressLevel(value)
}
goToGitHub() {
shell.openExternal('https://github.com/Richard-Choooou/image-compress')
}
render() {
const areaStyle = {
margin: '0 auto',
width: '440px',
height: '200px',
border: '2px #000 dashed',
borderRadius: '8px'
}
const getProgressList = function(uploadList) {
const checkState = data => {
if(data.state === 'error') {
return 'exception'
} else if(data.isDone) {
return 'success'
} else {
return 'active'
}
}
return [...uploadList.values()].map((value, index) => {
return (
<div className="progress-item" key={index}>
<p>文件名:{value.name}</p>
{value.state === 'uploading'?<p>状态:上传中</p>:''}
{value.state === 'cancel'?<p>状态:已取消</p>:''}
{value.state === 'error'?<p>状态:网络错误</p>:''}
{value.state === 'compressing'?<p>状态:压缩中</p>:''}
{value.state === 'compressed'?<p>状态:压缩完成</p>:''}
{value.state === 'downloading'?<p>状态:下载中</p>:''}
{value.state === 'downloaded'?<p>状态:已完成</p>:''}
<Progress percent={+value.progress} status={checkState(value)}></Progress>
</div>
)
})
}
return (
<div className="App">
<img onClick={this.goToGitHub} width="120" height="120" src="https://github.blog/wp-content/uploads/2008/12/forkme_right_gray_6d6d6d.png?resize=149%2C149" className="attachment-full size-full" alt="Fork me on GitHub" data-recalc-dims="1" />
<div className="container">
<Dropzone onDrop={(e) => this.onDrop(e)} className="drag-area" style={areaStyle}>
<img src={uploadIcon} alt="upload"></img>
<p>将图片拖至此处进行压缩</p>
{this.props.compressMode === 'online' && <div><p>正在使用在线压缩引擎</p><p>一次不能超过20张,且大小不能超过5mb</p></div>}
{this.props.compressMode === 'offline' && <div><p>正在使用离线压缩引擎</p><p>支持gif格式文件压缩</p></div>}
</Dropzone>
<DirManager></DirManager>
<div className="compress-level">
<Switch className="left" size="small" checkedChildren="online" unCheckedChildren="offline" checked={this.props.compressMode === 'online'} defaultChecked onChange={e => this.onCompressModeChange(e)} />
<div className="right">
<span>
压缩等级
<Tooltip title="压缩等级越高,图片质量越差,建议等级4">
<Icon style={{margin: '0 5px'}} type="question-circle" />
</Tooltip>
:</span>
<Slider disabled={this.props.compressMode === 'online'} onChange={e => this.onCompressLevelChange(e)} className="compress-level-slider" defaultValue={3} value={this.props.compressLevel} dots={true} step={1} min={1} max={10} />
</div>
</div>
<div className="progress-container">
{getProgressList(this.state.uploadList)}
</div>
</div>
</div>
);
}
}
export default connect(state => {
return {
compressMode: state.compressMode,
compressLevel: state.compressLevel
}
}, dispatch => {
return {
setCompressMode(mode) {
const action = {
type: 'SET_COMPRESS_MODE',
value: mode
}
dispatch(action)
},
setCompressLevel(level) {
const action = {
type: 'SET_COMPRESS_LEVEL',
value: level
}
dispatch(action)
}
}
})(App)
<file_sep>/src/store/reducer.js
import actions from './actions'
const electron = window.require('electron')
const { app } = electron.remote
const DOCUMENTS_PATH = app.getPath('documents')
/**
* init user config
*/
if (!localStorage.getItem('userConfig')) {
localStorage.setItem('userConfig', JSON.stringify({}))
}
const userConfig = JSON.parse(localStorage.getItem('userConfig'))
const defaultState = Object.assign({}, {
saveFilesDir: DOCUMENTS_PATH,
isCreateNewDir: true,
compressMode: 'online',
compressLevel: 4
}, userConfig)
export default (state = defaultState, action) => {
return actions[action.type] ? actions[action.type](JSON.parse(JSON.stringify(state)), action.value) : state
}<file_sep>/src/store/action_types.js
export default {
'SET_SAVE_FILE_DIR': 'SET_SAVE_FILE_DIR', // 设置存储文件的地址
'SET_CREATE_NEW_DIR_STATE': 'SET_CREATE_NEW_DIR_STATE', // 设置每次压缩是否建立新的文件夹
'SET_COMPRESS_MODE': 'SET_COMPRESS_MODE', // 设置压缩模式(线上|离线)
'SET_COMPRESS_LEVEL': 'SET_COMPRESS_LEVEL' // 设置压缩等级
} | db8e62a929fadc0bfd404da93e7f8d2a20ee3646 | [
"JavaScript",
"Markdown"
] | 8 | JavaScript | Richard-Choooou/image-compress | ec6bd9c36bf34cfddf54c08b9b5b85c8630b5d7e | d8deb6c92faffe2c27bf06eef4b94ee548e847de |
refs/heads/main | <file_sep>name = input('What is your name? \n')
allowedUsers = ['Seyi','Mike','Love']
allowedPassword = ['<PASSWORD>','<PASSWORD>','<PASSWORD>']
if(name in allowedUsers):
password = input('Your password? \n')
userId = allowedUsers.index(name)
while True:
if(password == allowedPassword[userId]):
import datetime
x = datetime.datetime.now()
print(x)
print('Welcome %s' % name)
print('These are the available options:')
print('1. Withdrawal')
print('2. Cash Deposit')
print('3. Complaint')
selectedOption = int(input('Please select an option:'))
if(selectedOption == 1):
print('You selected %s' % selectedOption)
input('How much would you like to withdraw? \n')
print('Take your cash')
elif(selectedOption ==2):
print('You selected %s' % selectedOption)
currentBalance = input('How much would you like to deposit? \n')
print('Your current balance is $ %s' % currentBalance)
elif(selectedOption == 3):
print('You selected %s' % selectedOption)
input('What issue will you like to report? \n')
print('Thank you for contacting us')
else:
print('Invalid Option selected, please try again')
else:
print('Password Incorrect, please try again')
break
else:
print('Name not found, please try again')
| cb742798c174e073cea383c266c6a809e89e944f | [
"Python"
] | 1 | Python | georgia-adam/MockATM | 7c9696949b7000d2dbdbb8f85db44ba63e8ceeed | 5ecd3ab973f0e48716eb6de147cce7f2417c82ed |
refs/heads/master | <file_sep>package com.yj.consumer.config;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
/**
* Create with IDEA
* User: Jason
* Date: 2018/5/26
* Time: 14:40
*/
//@Configuration
public class RestTemplateConfig {
// @Bean
// @LoadBalanced
// public RestTemplate restTemplate(ClientHttpRequestFactory factory){
// return new RestTemplate(factory);
// }
//
// @Bean
// public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
// SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
// factory.setConnectTimeout(15000);
// factory.setReadTimeout(5000);
//
// return factory;
// }
}
<file_sep>package com.yj.consumer;
import com.yj.core.CoreAutoConfiguration;
import com.yj.swagger.EnableSwagger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* Create with IDEA
* User: Jason
* Date: 2018/5/26
* Time: 14:13
*/
@SpringBootApplication(scanBasePackages = {"com.yj.amqp","com.yj.consumer"})
@EnableDiscoveryClient
@EnableSwagger
public class ConsumerApplication {
public static void main(String[] args){
SpringApplication.run(ConsumerApplication.class,args);
}
}
<file_sep>package com.yj.data.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import java.util.ArrayList;
import java.util.List;
/**
* 从配置文件信息加载datasource配置项
* Create with IDEA
* User: Jason
* Date: 2018/6/7
* Time: 20:59
*/
@Configuration
@ConfigurationProperties(prefix = "mybatis.datasource")
@PropertySource(ignoreResourceNotFound = true,value = {"classpath:mybatis/mybatis.yml"})
public class DataSourceConfiguration {
private static Logger logger = LoggerFactory.getLogger(DataSourceAutoConfiguration.class);
private String mapperLocations;
private String typeAliasesPackage;
private String configLocation;
private List<DruidDataSource> cluster = new ArrayList<>();
@Bean
@ConfigurationProperties(prefix = "mybatis.datasource.master")
public DruidDataSource writeDataSource(){
return new DruidDataSource();
}
public String getMapperLocations() {
return mapperLocations;
}
public void setMapperLocations(String mapperLocations) {
this.mapperLocations = mapperLocations;
}
public String getTypeAliasesPackage() {
return typeAliasesPackage;
}
public void setTypeAliasesPackage(String typeAliasesPackage) {
this.typeAliasesPackage = typeAliasesPackage;
}
public String getConfigLocation() {
return configLocation;
}
public void setConfigLocation(String configLocation) {
this.configLocation = configLocation;
}
public List<DruidDataSource> getCluster() {
return cluster;
}
public void setCluster(List<DruidDataSource> cluster) {
this.cluster = cluster;
}
}
<file_sep>package com.yj.zuul.routeLocator;
import com.yj.zuul.RouteLocatorContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.RefreshableRouteLocator;
import org.springframework.cloud.netflix.zuul.filters.SimpleRouteLocator;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.util.StringUtils;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 继承默认路由定位并实现路由刷新接口RefreshableRouteLocator
* 主要重写定位路由信息即重写locateRoute()
* Create with IDEA
* User: Jason
* Date: 2018/6/2
* Time: 10:44
*/
public class DynamicRouteLocator extends SimpleRouteLocator implements RefreshableRouteLocator {
public final static Logger logger = LoggerFactory.getLogger(DynamicRouteLocator.class);
private ZuulProperties properties;
public DynamicRouteLocator(String servletPath, ZuulProperties properties) {
super(servletPath, properties);
this.properties = properties;
}
/**
* 父类已经提供了刷新接口
*/
@Override
public void refresh() {
doRefresh();
}
/**
* 刷新[间隔一段时间自动刷新]一次即调用一次refresh就会调用locateRoutes()方法,重新加载路由信息
* @return
*/
@Override
protected Map<String, ZuulProperties.ZuulRoute> locateRoutes() {
LinkedHashMap<String,ZuulProperties.ZuulRoute> routesMap = new LinkedHashMap<>();
// 从application.properties中加载路由信息
routesMap.putAll(super.locateRoutes());
// 从db中加载路由信息
routesMap.putAll(RouteLocatorContext.getRoutes());
//
// 优化配置
LinkedHashMap<String,ZuulProperties.ZuulRoute> values = new LinkedHashMap<>();
for (Map.Entry<String,ZuulProperties.ZuulRoute> entry:routesMap.entrySet()){
String path = entry.getKey();
if(!path.startsWith("/")){
path = "/" + path;
}
if(StringUtils.hasText(this.properties.getPrefix())){
path = this.properties.getPrefix() + path;
if(!path.startsWith("/")){
path = "/" + path;
}
}
values.put(path,entry.getValue());
}
return values;
}
}
<file_sep># ribbon-demoted
Spring cloud 相关组件
<file_sep>package com.yj.amqp.config;
import com.github.rholder.retry.StopStrategies;
import com.github.rholder.retry.WaitStrategies;
import com.google.common.base.Predicates;
import com.yj.amqp.sender.RabbitSender;
import com.yj.amqp.util.MQConstants;
import com.yj.amqp.util.RabbitMetaMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import com.github.rholder.retry.Retryer;
import com.github.rholder.retry.RetryerBuilder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
/**
* Create with IDEA
* User: Jason
* Date: 2018/6/11
* Time: 18:14
*/
@Configuration
public class RabbitTemplateConfig {
private static final Logger logger = LoggerFactory.getLogger(RabbitTemplateConfig.class);
private static Boolean SUCESS_SEND = false;
@Autowired
RabbitSender rabbitSender;
@Autowired
private RedisTemplate<String,Object> redisTemplate;
@Bean
public RabbitTemplate customRabbitTemplate(ConnectionFactory connectionFactory){
RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
rabbitTemplate.setMessageConverter(jackson2JsonMessageConverter());
// mandatory 必须设置为true,RetureCallback才会调用
/*
如果exchange根据自身类型和消息routeKey无法找到一个符合条件的queue,那么会调用basic.return方法将消息返还给生产者。false:出现上述情形broker会直接将消息扔掉
* */
rabbitTemplate.setMandatory(true);
// 消息发送到RabbitMQ交换器后接收ACK回调
rabbitTemplate.setConfirmCallback((correlationData,ack,cause) ->{
logger.debug("confirm回调,ack={} correlationData ={} cause={}",ack,correlationData,cause);
String cacheKey = correlationData.getId();
RabbitMetaMessage metaMessage = (RabbitMetaMessage) redisTemplate.opsForHash().get(MQConstants.MQ_PRODUCER_RETRY_KEY,cacheKey);
// 只要消息能投入正确的交换器中,并持久化就会返回ack
if(ack){
logger.info("消息已正确投递到队列,correlationData:{}",correlationData);
// 消息已经正确投递到队列,清除重发缓存
redisTemplate.opsForHash().delete(MQConstants.MQ_PRODUCER_RETRY_KEY,cacheKey);
SUCESS_SEND = true;
}else {
// 无Exchange,以及网络中断的其它异常;重发消息
logger.error("消息投递到交换机失败,重发消息。ack:{};correlationData:{}; cause:{}",ack,correlationData,cause);
// 重发消息
reSendMsg(cacheKey,metaMessage);
}
});
// 消息发送到RabbitMQ交换器,但无相应Queue时触发此回调:重发消息
rabbitTemplate.setReturnCallback((msg,replyCode,replyText,exchange,routingKey) ->{
String cacheKey = msg.getMessageProperties().getMessageId();
logger.error("消息投递至交换机失败,没有找到任何匹配的队列!message id:{},replyCode{},replyText:{},"
+ "exchange:{},routingKey{}", cacheKey, replyCode, replyText, exchange, routingKey);
RabbitMetaMessage rabbitMetaMessage = (RabbitMetaMessage)redisTemplate.opsForHash().get(MQConstants.MQ_PRODUCER_RETRY_KEY,cacheKey);
//重发消息
reSendMsg(cacheKey,rabbitMetaMessage);
});
return rabbitTemplate;
}
public void reSendMsg(String msgId,RabbitMetaMessage rabbitMetaMessage){
/**
* 内部类
*/
class ReSendThread implements Callable{
String msgId;
RabbitMetaMessage rabbitMetaMessage;
public ReSendThread(String msgId,RabbitMetaMessage rabbitMetaMessage){
this.msgId = msgId;
this.rabbitMetaMessage = rabbitMetaMessage;
}
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
@Override
public Boolean call() throws Exception {
// 如果发送成功,重发结束
if(SUCESS_SEND){
return true;
}
logger.info("ReSendThread"+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
// 重发消息
rabbitSender.sendMessage(this.rabbitMetaMessage,this.msgId);
return true;
}
}
// 重发机制
Retryer<Boolean> retryer = RetryerBuilder
.<Boolean>newBuilder()
.retryIfException() // 设置异常重试源
.retryIfRuntimeException() // 设置异常重试源
.retryIfResult(Predicates.equalTo(false))
.withWaitStrategy(WaitStrategies.exponentialWait(MQConstants.MUTIPLIER_TIME,
MQConstants.MAX_RETRY_TIME, TimeUnit.SECONDS))
.withStopStrategy(StopStrategies.neverStop())
.build();
ReSendThread reSendThread = new ReSendThread(msgId,rabbitMetaMessage);
try {
retryer.call(reSendThread);
logger.info("ReSendThread"+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
if(!SUCESS_SEND){
rabbitSender.sendMsgToDeadQueue((String)rabbitMetaMessage.getPayload());
}
}catch (Exception ex){
logger.error("重发消息异常");
}
}
@Bean
public Jackson2JsonMessageConverter jackson2JsonMessageConverter(){
Jackson2JsonMessageConverter jsonMessageConverter = new Jackson2JsonMessageConverter();
return jsonMessageConverter;
}
}
<file_sep>package com.yj.core;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariableDefault;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* 请求都通过zuul进来,因此我们可以在zuul里面给请求打标签,基于用户,IP或其他看你的需求,然后将标签信息放入ThreadLocal中,然后在Ribbon Rule中从ThreadLocal拿出来使用就可以了
* 然而,拿不到ThreadLocal。原因是有hystrix这个东西,回忆下hystrix的原理,为了做到故障隔离,hystrix启用了自己的线程,不在同一个线程ThreadLocal失效
* 标签传到HystrixRequestVariableDefault这里的,如果项目中没有使用Hystrix就用不了了,这个时候需要做一个判断在restTemple里面做个判断,没有hystrix就直接threadlocal取
* Create with IDEA
* User: Jason
* Date: 2018/5/24
* Time: 21:13
*/
public class CoreHeaderInterceptor extends HandlerInterceptorAdapter {
private static final Logger logger = LoggerFactory.getLogger(CoreHeaderInterceptor.class);
public static final String HEADER_LABEL = "x-label";
public static final String HEADER_LABLE_SPLIT = ",";
public static final HystrixRequestVariableDefault<List<String>> lable = new HystrixRequestVariableDefault<>();
/**
* 添加标签
* @param labels
*/
public static void initHystrixRequestContext(String labels){
logger.info("labels: "+labels);
if(!HystrixRequestContext.isCurrentThreadInitialized()){
HystrixRequestContext.initializeContext();
}
if(!StringUtils.isEmpty(labels)){
CoreHeaderInterceptor.lable.set(Arrays.asList(labels.split(CoreHeaderInterceptor.HEADER_LABLE_SPLIT)));;
}else {
CoreHeaderInterceptor.lable.set(Collections.emptyList());
}
}
public static void shutdownHystrixRequestContext(){
if(HystrixRequestContext.isCurrentThreadInitialized()){
HystrixRequestContext.getContextForCurrentThread().shutdown();
}
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception{
CoreHeaderInterceptor.initHystrixRequestContext(request.getHeader(CoreHeaderInterceptor.HEADER_LABEL));
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception{
CoreHeaderInterceptor.shutdownHystrixRequestContext();
}
}
<file_sep>package com.yj.zuul.service;
import com.yj.zuul.RouteLocatorContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.RoutesRefreshedEvent;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
/**
* 通过事件来更新路由定位信息
* Create with IDEA
* User: Jason
* Date: 2018/6/2
* Time: 15:16
*/
@Service
public class RefreshRouteService {
@Autowired
ApplicationEventPublisher publisher;
@Autowired
RouteLocator routeLocator;
public void refreshRoute(){
// 清理自定义路由上下文,使之从DB重新加载路由信息
RouteLocatorContext.clearContext();
RoutesRefreshedEvent routesRefreshedEvent = new RoutesRefreshedEvent(routeLocator);
publisher.publishEvent(routesRefreshedEvent);
}
}
<file_sep>package com.yj.amqp.util;
/**
* Create with IDEA
* User: Jason
* Date: 2018/6/11
* Time: 19:34
*/
public class MQConstants {
/**
* 业务交换机名称
*/
public static final String BUSINESS_EXCHANGE = "business.exchange";
/**
* 业务队列名称
*/
public static final String BUSINESS_QUEUE = "business.queue";
/**
* 业务Key
*/
public static final String BUSINESS_KEY = "business.key";
public static final String MQ_PRODUCER_RETRY_KEY = "mq.producer.retry.key";
public static final String MQ_CONSUMER_RETRY_COUNT_KEY = "mq.consumer.retry.count.key";
/**死信队列配置*/
public static final String DLX_EXCHANGE = "dlx.exchange";
public static final String DLX_QUEUE = "dlx.queue";
public static final String DLX_ROUTING_KEY = "dlx.routing.key";
/**发送端重试乘数(ms)*/
public static final int MUTIPLIER_TIME = 500;
/** 发送端最大重试时时间(s)*/
public static final int MAX_RETRY_TIME = 10;
/** 消费端最大重试次数 */
public static final int MAX_CONSUMER_COUNT = 5;
/** 递增时的基本常量 */
public static final int BASE_NUM = 2;
/** 空的字符串 */
public static final String BLANK_STR = "";
}
<file_sep>package com.yj.data;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
/**
* Create with IDEA
* User: Jason
* Date: 2018/6/7
* Time: 21:09
*/
@Aspect
@Component
public class DynamicDataSourceAspect {
}
<file_sep>package com.yj.zuul;
import com.netflix.discovery.converters.Auto;
import com.yj.zuul.routeLocator.DynamicRouteLocator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
/**
* 配置自定义路由定位器
* Create with IDEA
* User: Jason
* Date: 2018/6/2
* Time: 11:32
*/
@Configuration
public class RouteLocatorConfiguration {
@Autowired
private ZuulProperties zuulProperties;
@Autowired
private ServerProperties server;
@Autowired
private JdbcTemplate jdbcTemplate;
@Bean
public DynamicRouteLocator routeLocator(){
DynamicRouteLocator routeLocator = new DynamicRouteLocator(this.server.getServletPath(),this.zuulProperties);
RouteLocatorContext.setJdbcTemplate(jdbcTemplate);
return routeLocator;
}
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>ribbon-demoted-core</artifactId>
<properties>
<swagger.version>2.6.1</swagger.version>
<druid.version>1.0.26</druid.version>
</properties>
<parent>
<groupId>com.yj</groupId>
<artifactId>ribbon-demoted</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix-core</artifactId>
<version>1.3.4.RELEASE</version>
</dependency>
<!--Swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<!--<dependency>-->
<!--<groupId>org.springframework</groupId>-->
<!--<artifactId>spring-beans</artifactId>-->
<!--</dependency>-->
</dependencies>
</project> | 5ff05c0d508607a35919e65a9c593a676efe545b | [
"Markdown",
"Java",
"Maven POM"
] | 12 | Java | jason163/ribbon-demoted | 0dc87050bcb09f601c3f9b0d0ac950bdf67c557a | ef3ed9e11027f6c966ee8ac148a1cc5d26d468b6 |
refs/heads/main | <file_sep>#include<stdlib.h>
#include<math.h>
#include<time.h>
#include<windows.h>
#include<string.h>
#include<GL/glut.h>
int flag = 0, flagw = 1;
void move_key(int key, int x, int y) //movement (u,d,l,r)
{
switch (key)
{
case GLUT_KEY_LEFT:flag = 1;
break;
case GLUT_KEY_RIGHT:flag = 2;
break;
case GLUT_KEY_UP:flag = 3;
break;
case GLUT_KEY_DOWN:flag = 4;
break;
}
}
void keyboard(unsigned char key, int x, int y)//flagw is used to indicate windows. flagw++ is for next window.
{
if (key==32)flagw++; //scan Space bar, flagw is for window
else if (key==113||key==81) flag = 10; //scan for Q
else if (key==76 || key==108) flag = 9; //for scanning L/l
}//void keyboard is for recognizing the keys for next level or Quit.
void output1(int x, int y, char *string)//display texts on widn
{
int len, i;
glRasterPos2f(x, y);
len = (int)strlen(string);
for (i = 0; i < len; i++)
{
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, string[i]);// 24-point proportional spaced Times Roman font.
}
}
void output(int x, int y, char *string)
{
int len, i;
glRasterPos2f(x, y);
len = (int)strlen(string);
for (i = 0; i < len; i++)
{
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, string[i]);//A 18-point proportional spaced Helvetica font
}
}
void display()//display mode
{
int i, j;
glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT);//--double buffer window --rgb color--bitmap to select a window with depth buffer
glLoadIdentity();
glColor3f(1.0, 1.0, 1.0);
if (flagw==1)
{
output1(-2, 4, "go_Korona_Go_Game");
output1(-1, -5, "Submitted By:");
output(4, -7, "4SO18CS128");
output(6, -8, "4SO18CS105");
output(1, -7, "Akanksha");
output(1, -8, "<NAME>");
output1(-3, -0, ".....use SPACE BAR to continue.....");
}
else if (flagw==2)
{
output1(-2, 4, "...INSTRUCTION...");
output(-3, -0, "use up ARROW KEYS to move your character forward");
output(-3, -1, "use down ARROW KEYS to move your character backward");
output(-3, -2, "use left ARROW KEYS to move your character left");
output(-3, -3, "use right ARROW KEYS to move your character right");
output(-3, -4, "to cross the road");
output1(-3, -7, ".....use SPACE BAR to continue.....");
}
glFlush();
glutPostRedisplay();
glutSwapBuffers();
}
void myReshape(int w, int h)//sets the reshape callback for the current window.
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-10.0, 10.0, -10.0, 10.0, -10.0, 10.0);
glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);//used to initialize glut library
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);//--double buffer window --rgb color--bitmap to select a window with depth buffer
glutInitWindowSize(800, 800);//set window size
glutInitWindowPosition(100,0);
glutCreateWindow("go_Korona_Go_Game");
glutReshapeFunc(myReshape);//sets the reshape callback for the current window.
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);//sets the keyboard callback for the current window.
glutSpecialFunc(move_key);//for keys like backspace and all which uses ascii
glClearColor(0.0, 0.0, 0.0, 0.0);//values in alpha used to clear buffers[0-1]
glutMainLoop();//enters the glut event processing loop
return 0;
}
<file_sep>#include <stdlib.h>
#include <GL/glut.h>
#include<math.h>
#include <stdio.h>
#include <string.h>
#include<iostream>
using namespace std;
#include<windows.h>
#include<mmsystem.h>
float m=-12,n=100,mm=-12,nn=100,o=0,xpos=0,ypos=0,xxpos=0,yypos=0,yy1pos=0,xxxpos=0,yyypos=17,yyy1pos=55,xxxxpos=0,yyyypos=0,mask=48,vax=0,touch=0;
int countt=0;
void init(){
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0,200,0,200,-200,200);
glMatrixMode(GL_MODELVIEW);
}
void myReshape(int w, int h)//sets the reshape callback for the current window.
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-10.0, 10.0, -10.0, 10.0, -10.0, 10.0);
glMatrixMode(GL_MODELVIEW);
}
void output1(float x, float y, char *string)//display texts on widn
{
int len, i;
glRasterPos2f(x, y);
len = (int)strlen(string);
for (i = 0; i < len; i++)
{
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, string[i]);// 24-point proportional spaced Times Roman font.
}
}
void output(int x, int y, char *string)
{
int len, i;
glRasterPos2f(x, y);
len = (int)strlen(string);
for (i = 0; i < len; i++)
{
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, string[i]);
//A 18-point proportional spaced Helvetica font
}
}
void quit(unsigned char key,int x,int y)
{
if(key=='q'||key=='Q')
exit(0);
}
void example(){
glColor3f (1.0, 1.0, 1.0); // Set line segment color to green.
int c=countt;
int t=15;
while (c> 0) {
int d = c % 10;
int e=d+48;
glRasterPos2f(t, 190);
t-=0.5;
char msg6=(char)e;
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24,msg6);
c = c / 10;
}
}
void example1(){
glColor3f (1.0, 1.0, 1.0); // Set line segment color to green.
int c=countt;
int t=1;
while (c> 0) {
int d = c % 10;
int e=d+48;
glRasterPos2f(t, 0);
t-=0.5;
char msg6=(char)e;
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24,msg6);
c = c / 10;
}
}
void textt(){
glColor3f (1, 1, 1.0);
glRasterPos2f(0, 190);
char msg4[] = "SCORE :";
for (int i = 0; i < strlen(msg4); i++)
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, msg4[i]);
glRasterPos2f(20, 190);
char msg2[] = "MASK :";
for (int i = 0; i < strlen(msg2); i++)
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, msg2[i]);
glRasterPos2f(35, 190);
char msg6=(char)mask;
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24,msg6);
}
void gameoverdisplay()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Color and Depth Buffers
glLoadIdentity();
glColor3f(1,0,0);
output1(-1.3, 2, "GAME OVER :(");
glColor3f(1,0,1);
output1(-1.5, -2, "PRESS Q TO QUIT");
example1();
glRasterPos2f(-1.5, 0);
char msg4[] = "SCORE :";
for (int i = 0; i < strlen(msg4); i++)
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, msg4[i]);
glColor3f(1,1,1);
glutKeyboardFunc(quit);
glutSwapBuffers();
glutPostRedisplay();
}
void gameoverwindow()
{
glutInitWindowSize(1500, 700);
glutInitWindowPosition(0, 0);
glutCreateWindow("GAME OVER");
glutReshapeFunc(myReshape);
glutDisplayFunc(gameoverdisplay);
}
void winingdisplay()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Color and Depth Buffers
glLoadIdentity();
glColor3f(1,0,0);
output1(-1.1, 3, "BRAVO!!!!");
glColor3f(0,1,0);
output1(-2, 1, "YOU WON THE GAME :)");
glColor3f(1,1,1);
output1(-2.5, -3, "THANKYOU FOR PLAYING");
example1();
glRasterPos2f(-1.5, 0);
char msg4[] = "SCORE :";
for (int i = 0; i < strlen(msg4); i++)
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, msg4[i]);
glutKeyboardFunc(quit);
glutSwapBuffers();
glutPostRedisplay();
}
void winningwindow()
{
glutInitWindowSize(1500, 700);
glutInitWindowPosition(0, 0);
glutCreateWindow("YOU WON THE GAME!");
glutReshapeFunc(myReshape);
glutDisplayFunc(winingdisplay);
}
void comove2()
{
if(xpos<200 && xpos>-210 )
{
xpos-=0.5;
if(xpos==-(180-mm) && nn>95 && nn<110 ){
if(mask==49 || vax==2){
mask=48;
}
else
{
gameoverwindow();
glutDestroyWindow(3);
}
}
if(xpos<-200)
xpos=15;
}
if(xxxpos<200 && xxxpos>-160 )
{
xxxpos-=0.5;
if(xxxpos==-(180-mm) && nn<50 && nn>40 ){
if(mask==49 || vax==2){
mask=48;
}
else
{
gameoverwindow();
glutDestroyWindow(3);
}
}
if(xxxpos<-150)
xxxpos=0;
}
if(yypos<200 && yypos>-220)
{
yypos-=0.5;
if(yypos==-(180-nn) && mm==53){
if(mask==49 || vax==2){
mask=48;
std::cout<<"one more chance"<<yypos<<"\n";
}
else
{gameoverwindow();
glutDestroyWindow(3);}
}
else if(yypos==-(180-nn) && mm==158 ){
if(mask==49|| vax==2 ){
mask=48;
std::cout<<"one more chance"<<yypos<<"\n";
}
else
{gameoverwindow();
glutDestroyWindow(3);}
}
if(yypos<-210)
yypos=0;
}
glutPostRedisplay();
}
void ObjectKeys2(int key, int xx, int yy)
{
switch (key)
{
case GLUT_KEY_LEFT:
{
if(mm>15 && nn>-1 && nn<10)
mm-=5;
else if(mm>15 && mm<130 && nn>40 && nn<50)
mm-=5;
else if(mm>55 && mm<125 && nn>180 && nn<190)
mm-=5;
else if(mm>115 && mm<160 && nn>156 && nn<180)
mm-=5;
else if(mm>-10 && nn<110 && nn>90)
mm-=5;
//else if(mm<-9 && nn<110 && nn>90 )
//glutDestroyWindow(3);if(m>30 && m<35 && n>90){
if(mm>100 && mm<107 && nn<100 && nn>30){
mask=49;
std::cout<<"MASK "<<mask<<"\n";}
if(mm>94 && mm<100 && nn>160 ){
countt+=1;
std::cout<<"TABLET "<<countt<<"\n";
}
if( mm>113 && mm<120 && nn<30){
countt+=1;
std::cout<<"TABLET "<<countt<<"\n";
}
break;
}
case GLUT_KEY_RIGHT:
if(mm<170 && nn<110 && nn>90)
mm+=5;
else if(mm>-10 && mm<115 && nn>170 && nn<190)
mm+=5;
else if(mm>100 && mm<155 && nn>156 && nn<180)
mm+=5;
else if(mm>-10 && mm<115 && nn>35 && nn<50)
mm+=5;
else if(mm>-10 && mm<155 && nn>-1 && nn<20)
mm+=5;
if(mm>100 && mm<107 && nn<100 && nn>30){
mask=49;
std::cout<<"MASK "<<mask<<"\n";}
if(mm>94 && mm<100 && nn>160 ){
countt+=1;
std::cout<<"TABLET "<<countt<<"\n";
}
if( mm>113 && mm<120 && nn<30){
countt+=1;
std::cout<<"TABLET "<<countt<<"\n";
}
if(mm>170 && nn<110 && nn>90){
if(vax==2 && countt>=4)
{glutDestroyWindow(3);
winningwindow();
}
else
std::cout<<"GET VACCINATED\n";}
break;
case GLUT_KEY_UP:
if(mm>50 && mm<60 && nn<185)
nn+=5;
else if(mm>115 && mm<120 && nn<185)
nn+=5;
else if(mm>155 && mm<160 && nn<170)
nn+=5;
else if (mm>12 && mm<30 && nn<40 )
nn+=5;
if( mm>100 && mm<120 && nn<127 && nn>120){
vax=2;
std::cout<<"VACCINE DOSE "<<vax<<"\n";}
if( mm>140 && mm<160 && nn>130 && nn<140){
countt+=1;
std::cout<<"TABLET "<<countt<<"\n";
}
break;
case GLUT_KEY_DOWN:
if(mm>50 && mm<60 && nn>0)
nn-=5;
else if(mm>115 && mm<125 && nn>45)
nn-=5;
else if(mm>155 && mm<160 && nn>0)
nn-=5;
else if (mm>12 && mm<30 && nn<50 && nn>0)
nn-=5;
if( mm>100 && mm<120 && nn<127 && nn>120){
vax=2;
std::cout<<"VACCINE DOSE "<<vax<<"\n";}
if( mm>140 && mm<160 && nn>130 && nn<140){
countt+=1;
std::cout<<"TABLET "<<countt<<"\n";
}
break;
default:
break;
}
}
void lane1(){
glColor3f(1,1,1);
glRectf(20,20,33,27);
}
void draw_pixel(GLint cx, GLint cy)
{
glBegin(GL_POINTS);
glVertex2i(cx,cy);
glEnd();
}
void plotpixels(GLint h,GLint k, GLint x,GLint y)
{
draw_pixel(x+h,y+k);
draw_pixel(-x+h,y+k);
draw_pixel(x+h,-y+k);
draw_pixel(-x+h,-y+k);
draw_pixel(y+h,x+k);
draw_pixel(-y+h,x+k);
draw_pixel(y+h,-x+k);
draw_pixel(-y+h,-x+k);
}
void draw_circle(GLint h, GLint k, GLint r)
{
GLint d=1-r, x=0, y=r;
while(y>x)
{
plotpixels(h,k,x,y);
if(d<0) d+=2*x+3;
else
{
d+=2*(x-y)+5;
--y;
}
++x;
}
plotpixels(h,k,x,y);
}
void draw_object()
{
//tree
int l;
for(l=0;l<=40;l++)
{
glColor3f(0.0,0.5,0.0);
draw_circle(40,280,l);
draw_circle(90,280,l);
draw_circle(150,280,l);
draw_circle(210,280,l);
draw_circle(65,340,l);
draw_circle(115,340,l);
draw_circle(175,340,l);
}
for(l=0;l<=55;l++)
{
glColor3f(0.0,0.5,0.0);
draw_circle(115,360,l);
}
glColor3f(0.9,0.2,0.0);
glBegin(GL_POLYGON);
glVertex2f(100,135);
glVertex2f(100,285);
glVertex2f(140,285);
glVertex2f(140,135);
glEnd();
}
void hse1()
{
//window border
glColor3f(0.35,0.0,0.0);
glBegin(GL_POLYGON);
glVertex2f(595,205);
glVertex2f(595,285);
glVertex2f(675,285);
glVertex2f(675,205);
glEnd();
glBegin(GL_POLYGON);
glVertex2f(825,205);
glVertex2f(825,285);
glVertex2f(905,285);
glVertex2f(905,205);
glEnd();
glBegin(GL_POLYGON);
glVertex2f(845,205);
glVertex2f(845,285);
glVertex2f(850,285);
glVertex2f(850,205);
glEnd();
//door
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex2f(800,100);
glVertex2f(800,220);
glVertex2f(700,220);
glVertex2f(700,100);
glEnd();
glColor3f(0.35,0.0,0.0);
glBegin(GL_POLYGON);
glVertex2f(760,120);
glVertex2f(760,200);
glVertex2f(700,220);
glVertex2f(700,100);
glEnd();
//window
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex2f(600,210);
glVertex2f(600,280);
glVertex2f(670,280);
glVertex2f(670,210);
glEnd();
glBegin(GL_POLYGON);
glVertex2f(830,210);
glVertex2f(830,280);
glVertex2f(900,280);
glVertex2f(900,210);
glEnd();
glColor3f(0.35,0.0,0.0);
glBegin(GL_POLYGON);
glVertex2f(620,210);
glVertex2f(620,280);
glVertex2f(625,280);
glVertex2f(625,210);
glEnd();
glBegin(GL_POLYGON);
glVertex2f(650,210);
glVertex2f(650,280);
glVertex2f(655,280);
glVertex2f(655,210);
glEnd();
glColor3f(0.35,0.0,0.0);
glBegin(GL_POLYGON);
glVertex2f(850,205);
glVertex2f(850,285);
glVertex2f(855,285);
glVertex2f(855,205);
glEnd();
glBegin(GL_POLYGON);
glVertex2f(880,205);
glVertex2f(880,285);
glVertex2f(885,285);
glVertex2f(885,205);
glEnd();
//roof
glColor3f(0.35,0.0,0.0);
glBegin(GL_POLYGON);
glVertex2f(540,330);
glVertex2f(540,350);
glVertex2f(960,350);
glVertex2f(960,330);
glEnd();
//home
glColor3f(.555, .724, .930);
glBegin(GL_POLYGON);
glVertex2f(550,100);
glVertex2f(550,330);
glVertex2f(950,330);
glVertex2f(950,100);
glVertex2f(850,100);
glVertex2f(850,250);
glVertex2f(650,250);
glVertex2f(650,100);
glEnd();
}
void hse2(){
//House_Window1
glBegin(GL_POLYGON);
glColor3f(0.38, 0.21, 0.26);
glVertex2i(295, 75);
glVertex2i(295, 90);
glVertex2i(310, 90);
glVertex2i(310, 75);
glEnd();
//House_Window2
glBegin(GL_POLYGON);
glColor3f(0.38, 0.21, 0.26);
glVertex2i(312, 75);
glVertex2i(312, 90);
glVertex2i(327, 90);
glVertex2i(327, 75);
glEnd();
//House_Window3
glBegin(GL_POLYGON);
glColor3f(0.38, 0.21, 0.26);
glVertex2i(355, 75);
glVertex2i(355, 90);
glVertex2i(370, 90);
glVertex2i(370, 75);
glEnd();
//HouseRoof
glBegin(GL_POLYGON);
glColor3f(.990, 0.0, 0.0);
glVertex2i(285, 105);
glVertex2i(285, 130);
glVertex2i(380, 115);
glVertex2i(380, 105);
glEnd();
//Housetop
glBegin(GL_POLYGON);
glColor3f(.555, 1.0, 1.0);
glVertex2i(290, 70);
glVertex2i(290, 104);
glVertex2i(375, 104);
glVertex2i(375, 70);
glEnd();
//House_Small_Door
glBegin(GL_POLYGON);
glColor3f(0.11, 0.23, 0.36);
glVertex2i(260, 70);
glVertex2i(260, 80);
glVertex2i(285, 80);
glVertex2i(285, 70);
glEnd();
//House_
glBegin(GL_POLYGON);
glColor3f(0.38, 0.41, 0.36);
glVertex2i(330, 70);
glVertex2i(330, 100);
glVertex2i(350, 100);
glVertex2i(350, 70);
glEnd();
//House_Small_Roof
glBegin(GL_POLYGON);
glColor3f(1.0, 0.0, 0.0);
glVertex2i(250, 90);
glVertex2i(257, 104);
glVertex2i(290, 104);
glVertex2i(290, 90);
glEnd();
//House_Small_Fence
glBegin(GL_POLYGON);
glColor3f(.555, .724, .930);
glVertex2i(255, 70);
glVertex2i(255, 90);
glVertex2i(290, 90);
glVertex2i(290, 70);
glEnd();
}
void extra(){
glBegin(GL_POLYGON);
glVertex2f(20, 0.0);
glVertex2f(20.0, 20.0);
glVertex2f(45.0, 20.0);
glVertex2f(45.0, 0.0);
glEnd();
}
void draw_tree1()
{
//1st tree
glColor3f(0.1f, 0.0f, 0.0f);
glBegin(GL_POLYGON);
glVertex2f(-30.0, 5.0);
glVertex2f(-25.0, 5.0);
glVertex2f(-25.0, 10.0);
glVertex2f(-30.0, 10.0);
glEnd();
glColor3f(0.0f, 0.5f, 0.0f);
glBegin(GL_POLYGON);
glVertex2f(-17.5, 10.0);
glVertex2f(-22.5, 15.0);
glVertex2f(-32.5, 15.0);
glVertex2f(-37.5, 10.0);
glEnd();
glColor3f(0.0f, 0.5f, 0.0f);
glBegin(GL_POLYGON);
glVertex2f(-20.0, 15.0);
glVertex2f(-25.0, 20.0);
glVertex2f(-30.0, 20.0);
glVertex2f(-35.0, 15.0);
glEnd();
glColor3f(0.0f, 0.5f, 0.0f);
glBegin(GL_POLYGON);
glVertex2f(-22.5, 20.0);
glVertex2f(-27.5, 25.0);
glVertex2f(-32.5, 20.0);
glEnd();
}
void draw_tree3()
{
//1st tree
glColor3f(0.4f, 0.0f, 0.0f);
glBegin(GL_POLYGON);
glVertex2f(-30.0, 5.0);
glVertex2f(-25.0, 5.0);
glVertex2f(-25.0, 10.0);
glVertex2f(-30.0, 10.0);
glEnd();
glColor3f(0.0f, 0.2f, 0.0f);
glBegin(GL_POLYGON);
glVertex2f(-17.5, 10.0);
glVertex2f(-22.5, 15.0);
glVertex2f(-32.5, 15.0);
glVertex2f(-37.5, 10.0);
glEnd();
glColor3f(0.0f, 0.2f, 0.0f);
glBegin(GL_POLYGON);
glVertex2f(-20.0, 15.0);
glVertex2f(-25.0, 20.0);
glVertex2f(-30.0, 20.0);
glVertex2f(-35.0, 15.0);
glEnd();
glColor3f(0.0f, 0.2f, 0.0f);
glBegin(GL_POLYGON);
glVertex2f(-22.5, 20.0);
glVertex2f(-27.5, 25.0);
glVertex2f(-32.5, 20.0);
glEnd();
}
void draw_tree2(){
//2nd tree
glColor3f(0.1f, 0.0f, 0.0f);
glBegin(GL_POLYGON);
glVertex2f(30.0, 5.0);
glVertex2f(25.0, 5.0);
glVertex2f(25.0, 10.0);
glVertex2f(30.0, 10.0);
glEnd();
glColor3f(0.0f, 0.5f, 0.0f);
glBegin(GL_POLYGON);
glVertex2f(17.5, 10.0);
glVertex2f(22.5, 15.0);
glVertex2f(32.5, 15.0);
glVertex2f(37.5, 10.0);
glEnd();
glColor3f(0.0f, 0.5f, 0.0f);
glBegin(GL_POLYGON);
glVertex2f(20.0, 15.0);
glVertex2f(25.0, 20.0);
glVertex2f(30.0, 20.0);
glVertex2f(35.0, 15.0);
glEnd();
glColor3f(0.0f, 0.5f, 0.0f);
glBegin(GL_POLYGON);
glVertex2f(22.5, 20.0);
glVertex2f(27.5, 25.0);
glVertex2f(32.5, 20.0);
glEnd();
}
void building1(){
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 1.0);
glVertex3f(28, -7, 0);
glVertex3f(28, 7, 0);
glVertex3f(32, 7, 0);
glVertex3f(32, -7, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 1.0);
glVertex3f(28, 10, 0);
glVertex3f(28, 20, 0);
glVertex3f(32, 20, 0);
glVertex3f(32, 10, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 1.0);
glVertex3f(38, -2, 0);
glVertex3f(38, 5, 0);
glVertex3f(42, 5, 0);
glVertex3f(42, -2, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0, 0.0, 0.0);
glVertex3f(25, -7, 0);
glVertex3f(25, 30, 0);
glVertex3f(35, 30, 0);
glVertex3f(35, 10, 0);
glVertex3f(45, 10, 0);
glVertex3f(45, -7, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 0.0);
glVertex3f(30, 40, 0);
glVertex3f(25, 30, 0);
glVertex3f(35, 30, 0);
glEnd();
}
void building2(){
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 1.0);
glVertex3f(-35, 6, 0);
glVertex3f(-32, 6, 0);
glVertex3f(-32, -7, 0);
glVertex3f(-35, -7, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 1.0);
glVertex3f(-30, 6, 0);
glVertex3f(-26, 6, 0);
glVertex3f(-26, 10, 0);
glVertex3f(-30, 10, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.7, 0, 0.7);
glVertex3f(-40, -7, 0);
glVertex3f(-25, -7, 0);
glVertex3f(-25, 15, 0);
glVertex3f(-40, 15, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,5, 0.0);
glVertex3f(-38, 23, 0);
glVertex3f(-27, 23, 0);
glVertex3f(-25, 15, 0);
glVertex3f(-40, 15, 0);
glEnd();
glBegin(GL_LINES);
glColor3f(0.0, 0.0, 0.0);
glVertex3f(-30, 8, 0);
glVertex3f(-26, 8, 0);
glEnd();
glBegin(GL_LINES);
glColor3f(0.0, 0.0, 0.0);
glVertex3f(-28, 6, 0);
glVertex3f(-28, 10, 0);
glEnd();
}
void building3()
{
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 1.0);
glVertex3f(-5, -7, 0);
glVertex3f(5, -7, 0);
glVertex3f(5, 15, 0);
glVertex3f(-5, 15, 0);
glEnd();
glBegin(GL_LINES);
glColor3f(0.0, 0.0, 0.0);
glVertex3f(15, 15, 0);
glVertex3f(-15, 15, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 1.0);
glVertex3f(-14, 0, 0);
glVertex3f(-6, 0, 0);
glVertex3f(-6, 8, 0);
glVertex3f(-14, 8, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 1.0);
glVertex3f(-14, 16, 0);
glVertex3f(-6, 16, 0);
glVertex3f(-6, 24, 0);
glVertex3f(-14, 24, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 1.0);
glVertex3f(-5, 16, 0);
glVertex3f(5, 16, 0);
glVertex3f(5, 24, 0);
glVertex3f(-5, 24, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 1.0);
glVertex3f(6, 0, 0);
glVertex3f(14, 0, 0);
glVertex3f(14, 8, 0);
glVertex3f(6, 8, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 1.0);
glVertex3f(6, 24, 0);
glVertex3f(14, 24, 0);
glVertex3f(14, 16, 0);
glVertex3f(6, 16, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 1.0);
glVertex3f(-35, 6, 0);
glVertex3f(-32, 6, 0);
glVertex3f(-32, -7, 0);
glVertex3f(-35, -7, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 1.0);
glVertex3f(-30, 6, 0);
glVertex3f(-26, 6, 0);
glVertex3f(-26, 10, 0);
glVertex3f(-30, 10, 0);
glEnd();
glBegin(GL_LINES);
glColor3f(0.0, 0.0, 0.0);
glVertex3f(-30, 8, 0);
glVertex3f(-26, 8, 0);
glEnd();
glBegin(GL_LINES);
glColor3f(0.0, 0.0, 0.0);
glVertex3f(-28, 6, 0);
glVertex3f(-28, 10, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0, 0.6, 1.0);
glVertex3f(-15, -7, 0);
glVertex3f(15, -7, 0);
glVertex3f(15, 30, 0);
glVertex3f(-15, 30, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.6, 1.5, 1.0);
glVertex3f(-13, 42, 0);
glVertex3f(13, 42, 0);
glVertex3f(15, 30, 0);
glVertex3f(-15, 30, 0);
glEnd();
}
void house(){
glBegin(GL_POLYGON);
glColor3f(0.0, 0.0, 0.0);
glVertex2f(10,120);
glVertex2f(10,125);
glVertex2f(20,125);
glVertex2f(20,120);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0, 0.0, 0.0);
glVertex2f(14,100);
glVertex2f(14,110);
glVertex2f(16,110);
glVertex2f(16,100);
glEnd();
glBegin(GL_POLYGON);
glColor3f(.990, 0.0, 0.0);
glVertex2f(10,100);
glVertex2f(10,120);
glVertex2f(20,120);
glVertex2f(20,100);
glEnd();
}
void tree(){
glColor3f(.1,0.2,0.1);
glBegin(GL_TRIANGLES);
glColor3f(.1,0.5,0.1);
glVertex2f(30.5,140);
glVertex2f(28,110);
glVertex2f(33,110);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0, 0.0, 0.0);
glVertex2f(30,100);
glVertex2f(30,120);
glVertex2f(31,120);
glVertex2f(31,100);
glEnd();
}
void tree1(){
glColor3f(0.1,0.2,0.1);
glBegin(GL_TRIANGLES);
glColor3f(.1,0.5,0.1);
glVertex2f(30.5,140);
glVertex2f(28,110);
glVertex2f(33,110);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0, 0.0, 0.0);
glVertex2f(30,100);
glVertex2f(30,120);
glVertex2f(31,120);
glVertex2f(31,100);
glEnd();
}
void tree2(){
glBegin(GL_TRIANGLES);
glColor3f(0,0.4,0);
glVertex2f(30.5,140);
glVertex2f(28,110);
glVertex2f(33,110);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3, 0.0, 0.0);
glVertex2f(30,100);
glVertex2f(30,120);
glVertex2f(31,120);
glVertex2f(31,100);
glEnd();
}
void road()
{
glBegin(GL_POLYGON);
glColor3f(1.0,1.0,1.0);
glVertex2f(20,80);
glVertex2f(20,85);
glVertex2f(30,85);
glVertex2f(30,80);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,1.0,1.0);
glVertex2f(50,80);
glVertex2f(50,85);
glVertex2f(60,85);
glVertex2f(60,80);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,1.0,1.0);
glVertex2f(80,80);
glVertex2f(80,85);
glVertex2f(90,85);
glVertex2f(90,80);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,1.0,1.0);
glVertex2f(110,80);
glVertex2f(110,85);
glVertex2f(120,85);
glVertex2f(120,80);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,1.0,1.0);
glVertex2f(140,80);
glVertex2f(140,85);
glVertex2f(150,85);
glVertex2f(150,80);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(0,70);
glVertex2f(0,100);
glVertex2f(50,100);
glVertex2f(50,70);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(50,70);
glVertex2f(50,100);
glVertex2f(70,100);
glVertex2f(70,70);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(70,70);
glVertex2f(70,100);
glVertex2f(103,100);
glVertex2f(103,70);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(103,70);
glVertex2f(103,100);
glVertex2f(120,100);
glVertex2f(120,70);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(120,70);
glVertex2f(120,100);
glVertex2f(135,100);
glVertex2f(135,70);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(135,70);
glVertex2f(135,100);
glVertex2f(150,100);
glVertex2f(150,70);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(150,70);
glVertex2f(150,100);
glVertex2f(170,100);
glVertex2f(170,70);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(50,50);
glVertex2f(50,70);
glVertex2f(70,70);
glVertex2f(70,50);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(103,50);
glVertex2f(103,70);
glVertex2f(120,70);
glVertex2f(120,50);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(50,100);
glVertex2f(50,130);
glVertex2f(70,130);
glVertex2f(70,100);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(103,100);
glVertex2f(103,130);
glVertex2f(120,130);
glVertex2f(120,100);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(120,120);
glVertex2f(120,135);
glVertex2f(150,135);
glVertex2f(150,120);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(135,100);
glVertex2f(135,120);
glVertex2f(150,120);
glVertex2f(150,100);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(50,130);
glVertex2f(50,450);
glVertex2f(120,150);
glVertex2f(120,130);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(50,30);
glVertex2f(50,50);
glVertex2f(120,50);
glVertex2f(120,30);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(20,30);
glVertex2f(20,50);
glVertex2f(50,50);
glVertex2f(50,30);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(135,20);
glVertex2f(135,70);
glVertex2f(150,70);
glVertex2f(150,20);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(20,5);
glVertex2f(20,30);
glVertex2f(40,30);
glVertex2f(40,5);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(40,5);
glVertex2f(40,20);
glVertex2f(150,20);
glVertex2f(150,5);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,0.9,0.0);
glVertex2f(20,0);
glVertex2f(20,5);
glVertex2f(30,5);
glVertex2f(30,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(.7,0.7,0.7);
glVertex2f(30,0);
glVertex2f(30,5);
glVertex2f(40,5);
glVertex2f(40,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,0.9,0.0);
glVertex2f(40,0);
glVertex2f(40,5);
glVertex2f(50,5);
glVertex2f(50,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(.7,0.7,0.7);
glVertex2f(50,0);
glVertex2f(50,5);
glVertex2f(60,5);
glVertex2f(60,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,0.9,0.0);
glVertex2f(60,0);
glVertex2f(60,5);
glVertex2f(70,5);
glVertex2f(70,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(.7,0.7,0.7);
glVertex2f(70,0);
glVertex2f(70,5);
glVertex2f(80,5);
glVertex2f(80,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,0.9,0.0);
glVertex2f(80,0);
glVertex2f(80,5);
glVertex2f(90,5);
glVertex2f(90,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(.7,0.7,0.7);
glVertex2f(90,0);
glVertex2f(90,5);
glVertex2f(100,5);
glVertex2f(100,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,0.9,0.0);
glVertex2f(100,0);
glVertex2f(100,5);
glVertex2f(110,5);
glVertex2f(110,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(.7,0.7,0.7);
glVertex2f(110,0);
glVertex2f(110,5);
glVertex2f(120,5);
glVertex2f(120,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,0.9,0.0);
glVertex2f(120,0);
glVertex2f(120,5);
glVertex2f(130,5);
glVertex2f(130,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(.7,0.7,0.7);
glVertex2f(130,0);
glVertex2f(130,5);
glVertex2f(140,5);
glVertex2f(140,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,0.9,0.0);
glVertex2f(140,0);
glVertex2f(140,5);
glVertex2f(150,5);
glVertex2f(150,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(.7,0.7,0.7);
glVertex2f(150,0);
glVertex2f(150,5);
glVertex2f(160,5);
glVertex2f(160,0);
glEnd();
tree();
house();
}
void road1()
{
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(0,70);
glVertex2f(0,100);
glVertex2f(50,100);
glVertex2f(50,70);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(50,70);
glVertex2f(50,100);
glVertex2f(70,100);
glVertex2f(70,70);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(70,70);
glVertex2f(70,100);
glVertex2f(103,100);
glVertex2f(103,70);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(103,70);
glVertex2f(103,100);
glVertex2f(120,100);
glVertex2f(120,70);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(120,70);
glVertex2f(120,100);
glVertex2f(135,100);
glVertex2f(135,70);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(135,70);
glVertex2f(135,100);
glVertex2f(150,100);
glVertex2f(150,70);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(150,70);
glVertex2f(150,100);
glVertex2f(170,100);
glVertex2f(170,70);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(50,50);
glVertex2f(50,70);
glVertex2f(70,70);
glVertex2f(70,50);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(103,50);
glVertex2f(103,70);
glVertex2f(120,70);
glVertex2f(120,50);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(50,100);
glVertex2f(50,130);
glVertex2f(70,130);
glVertex2f(70,100);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(103,100);
glVertex2f(103,130);
glVertex2f(120,130);
glVertex2f(120,100);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(120,120);
glVertex2f(120,135);
glVertex2f(150,135);
glVertex2f(150,120);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(135,100);
glVertex2f(135,120);
glVertex2f(150,120);
glVertex2f(150,100);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(50,130);
glVertex2f(50,450);
glVertex2f(120,150);
glVertex2f(120,130);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(50,30);
glVertex2f(50,50);
glVertex2f(120,50);
glVertex2f(120,30);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(20,30);
glVertex2f(20,50);
glVertex2f(50,50);
glVertex2f(50,30);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(135,20);
glVertex2f(135,70);
glVertex2f(150,70);
glVertex2f(150,20);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(20,5);
glVertex2f(20,30);
glVertex2f(40,30);
glVertex2f(40,5);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(40,5);
glVertex2f(40,20);
glVertex2f(150,20);
glVertex2f(150,5);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(20,0);
glVertex2f(20,5);
glVertex2f(30,5);
glVertex2f(30,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(30,0);
glVertex2f(30,5);
glVertex2f(40,5);
glVertex2f(40,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(40,0);
glVertex2f(40,5);
glVertex2f(50,5);
glVertex2f(50,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(50,0);
glVertex2f(50,5);
glVertex2f(60,5);
glVertex2f(60,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(60,0);
glVertex2f(60,5);
glVertex2f(70,5);
glVertex2f(70,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(70,0);
glVertex2f(70,5);
glVertex2f(80,5);
glVertex2f(80,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(80,0);
glVertex2f(80,5);
glVertex2f(90,5);
glVertex2f(90,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(90,0);
glVertex2f(90,5);
glVertex2f(100,5);
glVertex2f(100,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(100,0);
glVertex2f(100,5);
glVertex2f(110,5);
glVertex2f(110,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(110,0);
glVertex2f(110,5);
glVertex2f(120,5);
glVertex2f(120,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(120,0);
glVertex2f(120,5);
glVertex2f(130,5);
glVertex2f(130,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(130,0);
glVertex2f(130,5);
glVertex2f(140,5);
glVertex2f(140,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(140,0);
glVertex2f(140,5);
glVertex2f(150,5);
glVertex2f(150,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.3,0.3,0.3);
glVertex2f(150,0);
glVertex2f(150,5);
glVertex2f(160,5);
glVertex2f(160,0);
glEnd();
}
void cir(int x,int y)
{
float th;
glBegin(GL_LINES);
for(int i=0;i<360;i++)
{
th=i*3.142/180;
glVertex2f(x+10*cos(th),y+10*sin(th));
}
glEnd();
}
void poly()
{
glBegin(GL_POLYGON);
glVertex2f(20,190);
glVertex2f(20,170);
glVertex2f(60,170);
glVertex2f(60,190);
glEnd();
glPushMatrix();
cir(20,180);
glPopMatrix();
glPushMatrix();
cir(60,180);
glPopMatrix();
}
void circfun(float x,float y)
{
float th;
glBegin(GL_POLYGON);
for(int i=0;i<360;i++)
{
th=i*3.142/180;
glVertex2f(x+2*cos(th),y+2*sin(th));
}
glEnd();
}
void circ(){
glColor3f (1, 0.0, 0.0);
circfun(-20,-7);
circfun(-20,1);
circfun(-19,8);
circfun(-16,14);
circfun(-10,18);
circfun(-3,21);
circfun(4,21);
circfun(10,19);
circfun(15,15);
circfun(15,-15);
circfun(10,-19);
circfun(4,-21);
circfun(-3,-21);
circfun(-10,-18);
circfun(-16,-14);
circfun(19,-8);
circfun(20,7);
circfun(20,-1);
}
float f=0.0;
void solidcircle(float x,float y,float z){
f +=0.1;
glColor3f(1.0,0,0);
glTranslatef(x,y,z);
glRotatef(f,0,0,1);
glutSolidSphere(6,50,50);
glColor3f(0,0,0);
glutWireSphere(5.99,100,100);
glScalef(0.3,0.3,0);
circ();
}
void MAN()
{
glBegin (GL_POLYGON);//HAIR
glColor3f (0.5, 0.4, 0.3);
glVertex2f (24,53);
glVertex2f (23,55);
glVertex2i (26,55);
glVertex2i (26,56.5);
glVertex2i (31,53);
glEnd();
glColor3f (0.0, 0.0, 0.0);
glRecti (25.7, 50, 26.5, 51.5);//eye1
glRecti (29.5, 50, 30.5, 51.5);//eye2
glBegin (GL_TRIANGLES);//NOSE
glColor3f (0.0, 0.0, 0.0);
glVertex2f (27.5,49);
glVertex2f (27,47);
glVertex2i (28,47);
glEnd();
glBegin (GL_TRIANGLES);//MOUTH
glColor3f (1.0, 0.0, 0.5);
glVertex2i (25.5,46);
glVertex2f (27.5,44);
glVertex2f (29.5,46);
glEnd();
glBegin (GL_QUADS);
glColor3f (0.60, 0.0, 0.);
glVertex2i (24,20);//body
glVertex2i (22,40);
glVertex2i (33,40);
glVertex2i (31,20);
glColor3f (0.0,0.0,0.4);
glVertex2i (25,20);//legs
glVertex2i (20,3);
glVertex2i (25,3);
glVertex2i (27,20);
glVertex2f (30,20);
glVertex2i (34,3);
glVertex2i (29,3);
glVertex2i (28,20);
glColor3f (0.60, 0.0, 0.);
glVertex2f (22,40);//arms
glVertex2f (22.5,38);
glVertex2i (20,23);
glVertex2i (18,25);
glVertex2f (33,40);
glVertex2f (32.5,38);
glVertex2i (38,25);
glVertex2i (36,23);
glEnd();
glColor3f (0.85, 0.95, 0);
glRecti (26, 40, 29, 43);
glBegin (GL_POLYGON);//FACE
glColor3f (0.85, 0.95, 0);
glVertex2f (26,43);
glVertex2f (24,45);
glVertex2i (24,53);
glVertex2i (31,53);
glVertex2i (31,45);
glVertex2i (29,43);
glEnd();
glBegin (GL_TRIANGLES);//SHOE1
glColor3f (1.0, 1.0, 1.0);
glVertex2i (25,3);
glVertex2f (18,1);
glVertex2f (20,3);
glEnd();
glBegin (GL_TRIANGLES);//SHOE2
glColor3f (1.0, 1.0, 1.0);
glVertex2i (29,3);
glVertex2f (37,1);
glVertex2f (34,3);
glEnd();
glBegin (GL_POLYGON);//WRIST1
glColor3f (0.85, 0.95, 0);
glVertex2f (18,25);
glVertex2f (16,25.5);
glVertex2f (17.5,24.5);
glVertex2f (17,23.5);
glVertex2f (18.5,21.5);
glVertex2f (20,23);
glEnd();
glBegin (GL_POLYGON);//WRIST2
glVertex2f (38,25);
glVertex2f (36,23);
glVertex2f (37,21.5);
glVertex2f (39.5,23.5);
glEnd();
glFlush ( ); // Process all OpenGL routines as quickly as possible.
}
float th=0.0;
void vaccine(){
th+=1.0;
glPushMatrix();
glTranslatef(100,100,0);
//glRotatef(th,0,1,0);
glScalef(1,4,0);
glutSolidCube(20);
glPopMatrix();
glPushMatrix();
glTranslatef(100,55,0);
//lRotatef(th,0,1,0);
glScalef(1,4,0);
glutSolidCube(5.0);
glPopMatrix();
glPushMatrix();
glTranslatef(100,45,0);
//glRotatef(th,0,1,0);
glScalef(3.5,0.5,0);
glutSolidCube(5.0);
glPopMatrix();
glPushMatrix();
glTranslatef(100,145,0);
glColor3f(0.5,0.0,0);
//glRotatef(th,0,0,0);
glScalef(0.25,2,0);
glutSolidCube(5.0);
glPopMatrix();
glPushMatrix();
glColor3f(1,0,0);
glTranslatef(100,110,0);
glRotatef(th,1,0,0);
glScalef(3,10,0);
glutSolidCube(5);
glPopMatrix();
}
float k=0;
void tablet(){
k+=0.5;
glPushMatrix();
glColor3f(0,0,1);
glTranslatef(100,100,-25);
glScalef(1.5,1,0);
glutSolidCube(50);
glPopMatrix();
glPushMatrix();
glColor3f(1,1,0);
glTranslatef(135,100,0);
glRotatef(k,0,1,0);
glutSolidSphere(25,20,20);
glPopMatrix();
glPushMatrix();
glTranslatef(65,100,0);
glRotatef(k,0,1,0);
glutSolidSphere(25,20,20);
glPopMatrix();
}
void background2display(){
glClearColor(0.0,0.0,0.0,1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
example();
textt();
glPushMatrix();
glTranslatef(15,105,0);
glScalef(0.3,0.5,0);
hse2();
glPopMatrix();
glPushMatrix();
glTranslatef(147,16,0);
glScalef(0.1,0.2,0);
draw_object();
glPopMatrix();
glPushMatrix();
glTranslatef(42,25,0);
glScalef(0.1,0.1,0);
draw_object();
glPopMatrix();
glPushMatrix();
glTranslatef(xpos,ypos,0);
solidcircle(200,120,0);
glPopMatrix();
glPushMatrix();
glTranslatef(xxxpos,yyy1pos,0);
solidcircle(180,0,0);
glPopMatrix();
glPushMatrix();
glTranslatef(xxpos,yypos,0);
solidcircle(75,220,0);
glPopMatrix();
glPushMatrix();
glTranslatef(xxpos,yypos,0);
solidcircle(180,220,0);
glPopMatrix();
glPushMatrix();
glTranslatef(mm,nn,o);
glScalef(0.8,0.60,0);
MAN();
glPopMatrix();
glPushMatrix();
glTranslatef(42,25,0);
glColor3f(0.3,0.3,0.3);
extra();
glPopMatrix();
glPushMatrix();
glTranslatef(40,5,0);
glScalef(1,3,0);
draw_tree1();
glPopMatrix();
glColor3f (0.0,0.3,0.0);
glRectf(50,25,168.7,44);
glColor3f (0.5, 0.5, 0);
glRectf(0,70,62.5,98);
glColor3f (0.0,0.3,0.0);
glRectf(0,0,25,20);
glPushMatrix();
glTranslatef(30,130,0);
glScalef(1,2,0);
draw_tree3();
glPopMatrix();
glPushMatrix();
glTranslatef(40,130,0);
glScalef(1,2,0);
draw_tree3();
glPopMatrix();
glPushMatrix();
glTranslatef(50,130,0);
glScalef(1,2,0);
draw_tree3();
glPopMatrix();
glPushMatrix();
glTranslatef(60,130,0);
glScalef(1,2,0);
draw_tree3();
glPopMatrix();
glPushMatrix();
glTranslatef(60,40,0);
glScalef(1,1,1.0);
glColor3f(0,0.0,1);
tree2();
glPopMatrix();
glPushMatrix();
glTranslatef(62,-30,0);
glScalef(1,1,1.0);
glColor3f(0,0.0,1);
tree2();
glPopMatrix();
glPushMatrix();
glTranslatef(70,-30,0);
glScalef(1,1,1.0);
glColor3f(0,0.0,1);
tree2();
glPopMatrix();
glPushMatrix();
glTranslatef(78,-30,0);
glScalef(1,1,1.0);
glColor3f(0,0.0,1);
tree2();
glPopMatrix();
glPushMatrix();
glTranslatef(85,-30,0);
glScalef(1,1,1.0);
glColor3f(0,0.0,1);
tree2();
glPopMatrix();
glPushMatrix();
glTranslatef(92,-30,0);
glScalef(1,1,1.0);
glColor3f(0,0.0,1);
tree2();
glPopMatrix();
glPushMatrix();
if( mm>100 && mm<120 && nn<145 && nn>120){
glColor3f (1, 0, 0);
glRasterPos2f(0, 182);
char msg4[] = "You Are Vaccinated..!!";
for (int i = 0; i < strlen(msg4); i++)
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, msg4[i]);
glTranslatef(5450,5200,0);}
else
glTranslatef(110,120,0);
glScalef(0.3,0.4,1.0);
glColor3f(0,0.0,1);
vaccine();
glPopMatrix();
glPushMatrix();
if(mm>100 && mm<107 && nn<100 && nn>30){
glTranslatef(5450,5200,0);}
else
glTranslatef(115,-35,0);
glScalef(0.2,0.5,0);
glColor3f(0,0.4,1);
poly();
glPopMatrix();
glPushMatrix();
glScalef(0.07,0.07,0);
if( mm>140 && mm<160 && nn>130 && nn<140){
glTranslatef(5450,5200,0);}
else
glTranslatef(2450,2200,0);
glColor3f(0,0.0,1);
tablet();
glPopMatrix();
glPushMatrix();
glScalef(0.07,0.07,0);
if(mm>94 && mm<100 && nn>160 ){
glTranslatef(5450,5200,0);}
else
glTranslatef(1600,2600,0);
glColor3f(0,0.0,1);
tablet();
glPopMatrix();
glPushMatrix();
glScalef(0.07,0.07,0);
if( mm>113 && mm<120 && nn<30){
glTranslatef(5450,5200,0);
}
glTranslatef(1900,50,0);
glColor3f(0,0.0,1);
tablet();
glPopMatrix();
glPushMatrix();
glScalef(0.05,0.07,0);
glTranslatef(290,1900,0);
hse1();
glPopMatrix();
glPushMatrix();
glScalef(0.03,0.06,0);
glTranslatef(4580,2235,0);
hse1();
glPopMatrix();
int x=-12;
while(x<200)
{
glPushMatrix();
glTranslatef(x,92,0);
lane1();
x+=35;
glPopMatrix();
}
glPushMatrix();
glScalef(1.25,1.4,0);
road1();
glPopMatrix();
glutSwapBuffers();
glutPostRedisplay();
}
void background2window(){
glutInitWindowSize(1500, 700);
glutInitWindowPosition(0, 0);
glutCreateWindow("CORONA GAME");
init();
glClearColor(0, 0, 0, 0);
glutDisplayFunc(background2display);
glutIdleFunc(comove2);
glutSpecialFunc(ObjectKeys2);
glEnable(GL_DEPTH_TEST);
glutMainLoop();
}
void comove1()
{
if(xpos<200 && xpos>-210 )
{
xpos-=0.5;
if(xpos==-(180-m) && ypos==(n-100) ){
if(mask==49||vax==1){
mask=48;
vax-=0.5;
if(vax==0){
gameoverwindow();
glutDestroyWindow(2);
}
}
else
{gameoverwindow();
glutDestroyWindow(2);}
}
if(xpos<-200)
xpos=15;
}
if(xxxpos<200 && xxxpos>-210 )
{
xxxpos-=0.5;
if(xxxpos==-(180-m) && yyypos==n+17){
if(mask==49||vax==1){
mask=48;
vax-=0.5;
if(vax==0){
gameoverwindow();
glutDestroyWindow(2);
}
}
else
{gameoverwindow();
glutDestroyWindow(2);}
}
if(xxxpos<-160)
xxxpos=0;
}
if(yypos<200 && yypos>-220)
{
yypos-=0.5;
if(yypos==-(180-n) && m==53){
if(mask==49 || vax==1){
mask=48;
vax-=0.5;
if(vax==0){
gameoverwindow();
glutDestroyWindow(2);
}
}
else
{gameoverwindow();
glutDestroyWindow(2);}
}
else if(yypos==-(180-n) && m==118 ){
if(mask==49||vax==1){
mask=48;
vax-=0.5;
if(vax==0){
gameoverwindow();
glutDestroyWindow(2);
}
}
else
{gameoverwindow();
glutDestroyWindow(2);}
}
if(yypos<-210)
yypos=0;
}
glutPostRedisplay();
}
void ObjectKeys(int key, int xx, int yy)
{
switch (key)
{
case GLUT_KEY_LEFT:
{
if(m>15 && n>-1 && n<10)
m-=5;
else if(m>15 && m<130 && n>40 && n<50)
m-=5;
else if(m>55 && m<125 && n>180 && n<190)
m-=5;
else if(m>115 && m<160 && n>156 && n<180)
m-=5;
else if(m>-10 && n<110 && n>90)
m-=5;
if(m<-12 && n<110 && n>90)
exit(0);
if(m>30 && m<35 && n>90){
countt+=1;
std::cout<<"TABLET "<<countt<<"\n";
}
if(m>95 && m<100 && n>90){
countt+=1;
std::cout<<"TABLET "<<countt<<"\n";}
if(m>30 && m<35 && n<100 && n>20){
mask=49;
std::cout<<"MASK "<<mask<<"\n";}
break;
}
case GLUT_KEY_RIGHT:
if(m>30 && m<35 && n>90){
countt+=1;
std::cout<<"TABLET "<<countt<<"\n";}
if(m>95 && m<100 && n>90){
countt+=1;
std::cout<<"TABLET "<<countt<<"\n";}
if(m<180 && n<110 && n>90)
m+=5;
else if(m>-10 && m<115 && n>170 && n<190)
m+=5;
else if(m>100 && m<155 && n>156 && n<180)
m+=5;
else if(m>-10 && m<115 && n>35 && n<50)
m+=5;
else if(m>-10 && m<155 && n>-1 && n<20)
m+=5;
if(m>30 && m<35 && n<100 && n>20){
mask=49;
std::cout<<"MASK "<<mask<<"\n";}
if(m>180 && n<110 && n>90){
if(vax==1 && countt>=2)
{glutDestroyWindow(2);
background2window();
}
else
std::cout<<"GET VACCINATED\n";
}
break;
case GLUT_KEY_UP:
if(m>50 && m<60 && n<185)
n+=5;
else if(m>115 && m<120 && n<185)
n+=5;
else if(m>155 && m<160 && n<170)
n+=5;
else if (m>12 && m<30 && n<40 )
n+=5;
if( n>120 && n<130 && m>115 && m<125){
countt+=1;
std::cout<<"TABLET "<<countt<<"\n";}
if( m>155 && m<160 && n<80 && n>70){
vax=1;
std::cout<<"VACCINE DOSE "<<vax<<"\n";}
break;
case GLUT_KEY_DOWN:
if(m>50 && m<60 && n>0)
n-=5;
else if(m>115 && m<125 && n>40)
n-=5;
else if(m>155 && m<160 && n>0)
n-=5;
else if (m>12 && m<30 && n<50 && n>0)
n-=5;
if( n>120 && n<130 && m>115 && m<125){
countt+=1;
std::cout<<"TABLET "<<countt<<"\n";}
if( m>155 && m<160 && n<80 && n>70){
vax=1;
std::cout<<"VACCINE DOSE "<<vax<<"\n";}
break;
default:
break;
}
}
void display() {
glColor3f (0.3, 0.5, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
example();
textt();
glPushMatrix();
glTranslatef(xpos,ypos,0);
solidcircle(200,120,0);
glPopMatrix();
glPushMatrix();
glTranslatef(xxxpos,yyypos,0);
solidcircle(180,0,0);
glPopMatrix();
glPushMatrix();
glTranslatef(xxpos,yypos,0);
solidcircle(75,220,0);
glPopMatrix();
glPushMatrix();
glTranslatef(xxpos,yypos,0);
solidcircle(140,220,0);
glPopMatrix();
glPushMatrix();
glTranslatef(0,ypos,0);
//solidcircle(75,420,0);
glPopMatrix();
glPushMatrix();
glTranslatef(m,n,o);
glScalef(0.8,0.60,0);
MAN();
glPopMatrix();
glPushMatrix();
glTranslatef(42,25,0);
glColor3f(0.0,0.0,0.0);
extra();
glPopMatrix();
glColor3f (0.5, 0.95, 0);
glRectf(50,25,168.7,44);
glColor3f (0.5, 0.95, 0);
glRectf(0,70,62.5,98);
glColor3f (0.5, 0.95, 0);
glRectf(87.5,70,128.9,76);
glColor3f (0.5, 0.95, 0);
glRectf(87.5,130,128.9,146);
glColor3f (0.5, 0.95, 0);
glRectf(0,0,25,20);
glPushMatrix();
glTranslatef(60,40,0);
glScalef(1,1,1.0);
glColor3f(0,0.0,1);
tree1();
glPopMatrix();
glPushMatrix();
glTranslatef(60,-25,0);
glScalef(1,1,1.0);
glColor3f(0,0.0,1);
tree1();
glPopMatrix();
glPushMatrix();
if( m>155 && m<160 && n<80 && n>15){
glColor3f (0, 0, 0);
glRasterPos2f(0, 182);
char msg4[] = "First Dose Taken..!!";
for (int i = 0; i < strlen(msg4); i++)
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, msg4[i]);
glTranslatef(5000,8400,0);
}
else
glTranslatef(148,25,0);
glScalef(0.3,0.4,1.0);
glColor3f(0,0.0,1);
vaccine();
glPopMatrix();
glPushMatrix();
if(m>30 && m<35 && n<100 && n>20){
glTranslatef(5000,8400,0);}
else
glTranslatef(50,-35,0);
glScalef(0.2,0.5,0);
glColor3f(0,0.4,1);
poly();
glPopMatrix();
glPushMatrix();
glScalef(0.07,0.07,0);
if(m>30 && m<35 && n>90){
glTranslatef(5000,8400,0);
}
else
glTranslatef(700,1400,0);
glColor3f(0,0.0,1);
tablet();
glPopMatrix();
glPushMatrix();
glScalef(0.07,0.07,0);
if( n>120 && n<130 && m>115 && m<125){
glTranslatef(5000,8400,0);
}
else
glTranslatef(1900,2100,0);
glColor3f(0,0.0,1);
tablet();
glPopMatrix();
glPushMatrix();
glScalef(0.07,0.07,0);
if(m>95 && m<100 && n>90){
glTranslatef(5000,8400,0);
}
else
glTranslatef(1700,1400,0);
glColor3f(0,0.0,1);
tablet();
glPopMatrix();
glPushMatrix();
glScalef(0.7,1,0.5);
glTranslatef(18,25,0);
building3();
glPopMatrix();
glPushMatrix();
glScalef(0.7,0.5,0.5);
glTranslatef(180,160,0);
building2();
glPopMatrix();
glPushMatrix();
glScalef(0.7,0.5,0.5);
glTranslatef(197,160,0);
building2();
glPopMatrix();
glPushMatrix();
glScalef(0.7,0.5,0.5);
glTranslatef(202,297.5,0);
building2();
glPopMatrix();
glPushMatrix();
glScalef(0.9,0.7,0.5);
glTranslatef(80,215,0);
building1();
glPopMatrix();
glPushMatrix();
glTranslatef(187,133,0);
glScalef(1,1.4,0);
draw_tree1();
glPopMatrix();
glPushMatrix();
glTranslatef(187,33,0);
glScalef(1,2,0);
draw_tree1();
glPopMatrix();
glPushMatrix();
glScalef(1.25,1.4,0);
road();
glPopMatrix();
glutSwapBuffers();
glutPostRedisplay();
}
void background1window(){
glutInitWindowSize(1500, 700);
glutInitWindowPosition(0, 0);
glutCreateWindow("CORONA GAME");
init();
glClearColor(0, 0.5, 0.7, 0);
glutDisplayFunc(display);
glutIdleFunc(comove1);
glutSpecialFunc(ObjectKeys);
glEnable(GL_DEPTH_TEST);
glutMainLoop();
}
int flag = 0, flagw = 1;
void keyboard(unsigned char key, int x, int y)//flagw is used to indicate windows. flagw++ is for next window.
{
if (key==32)flagw++; //scan Space bar, flagw is for window
else if (key==113||key==81) flag = 10; //scan for Q
else if (key==76 || key==108) flag = 9; //for scanning L/l
}//void keyboard is for recognizing the keys for next level or Quit.
void display1()//display mode
{
int i, j;
glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT);//--double buffer window --rgb color--bitmap to select a window with depth buffer
glLoadIdentity();
glColor3f(1.0, 1.0, 1.0);
if (flagw==1)
{
output1(-2, 4, "go_Korona_Go_Game");
output1(-1, -5, "Submitted By:");
output(4, -7, "4SO18CS128");
output(6, -8, "4SO18CS105");
output(1, -7, "Akanksha");
output(1, -8, "<NAME>");
output1(-3, -0, ".....use SPACE BAR to continue.....");
}
else if (flagw==2)
{
output1(-4, 4, "...INSTRUCTION TO PLAY THE GAME...");
output(-5, -0, "Use ARROW KEYS to move your character FORWARD,BACKWARD,LFFT AND RIGHT.");
output(-5, -1, "Continues FAST MOVEMENT can help the character to protect from corona virus.");
output(-5, -2, "Collecting the MASK will add an extra life eventually preventing from corona virus.");
output(-5, -3, "Collecting the 1st VACCINE along with MINIMUM 2 PILLS to advance to second background.");
output(-5, -4, "Collecting the 2nd VACCINE along with MINIMUM 2 PILLS to WIN the game.");
output(-5, -5, "Collect EXTRA PILLS to score MAXIMUM POINTS.");
output1(-3, -7, ".....use SPACE BAR to continue.....");
}
else if (flagw==3)
{
background1window();
}
glutPostRedisplay();
glutSwapBuffers();
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);//used to initialize glut library
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);//--double buffer window --rgb color--bitmap to select a window with depth buffer
glutInitWindowSize(1500, 800);//set window size
glutInitWindowPosition(0,0);
glutCreateWindow("go_Korona_Go_Game");
glutReshapeFunc(myReshape);//sets the reshape callback for the current window.
glutDisplayFunc(display1);
glutKeyboardFunc(keyboard);//sets the keyboard callback for the current window.
glClearColor(0.0, 0.0, 0.0, 0.0);//values in alpha used to clear buffers[0-1]
glutMainLoop();//enters the glut event processing loop
return 0;
}
<file_sep># go_Korona_Go
“go_Korona_Go_Game” is an user interactive game, where the player is trying
to consume vaccine, tablets and were mask thus protecting himself from this
deadly corona virus which is the current pandemic of whole world. The player
controls the movement of the character using the arrow keys of keyboard. The
main objective is to create awareness among the people that getting vaccinated is
utmost important to protect themselves. The game gets over when the
character(man) hits the corona virus without any medication treatment.
# Background1
<img height=400 width=900 src="https://github.com/AkankshaGaonkar/go_Korona_Go/blob/main/Screenshot%20(269).png" />
# Background2
<img height=400 width=900 src="https://github.com/AkankshaGaonkar/go_Korona_Go/blob/main/Screenshot%20(270).png"/>
<file_sep>#define GL_SILENCE_DEPRECATION
#include <gl/glut.h>
#include <math.h>
float m=-12,n=100,o=0;
void init(){
glClearColor(0, 0.5, 0.7, 0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0,200,0,200,-200,200);
glMatrixMode(GL_MODELVIEW);
}
void ObjectKeys(int key, int xx, int yy)
{
switch (key)
{
case GLUT_KEY_LEFT:
{
m-=5;
break;
}
case GLUT_KEY_RIGHT:
m+=5;
break;
case GLUT_KEY_UP:
n+=5;
break;
case GLUT_KEY_DOWN:
n-=5;
break;
case GLUT_KEY_RIGHT && GLUT_KEY_UP:
break;
}
}
void draw_tree1()
{
//1st tree
glColor3f(0.1f, 0.0f, 0.0f);
glBegin(GL_POLYGON);
glVertex2f(-30.0, 5.0);
glVertex2f(-25.0, 5.0);
glVertex2f(-25.0, 10.0);
glVertex2f(-30.0, 10.0);
glEnd();
glColor3f(0.0f, 0.5f, 0.0f);
glBegin(GL_POLYGON);
glVertex2f(-17.5, 10.0);
glVertex2f(-22.5, 15.0);
glVertex2f(-32.5, 15.0);
glVertex2f(-37.5, 10.0);
glEnd();
glColor3f(0.0f, 0.5f, 0.0f);
glBegin(GL_POLYGON);
glVertex2f(-20.0, 15.0);
glVertex2f(-25.0, 20.0);
glVertex2f(-30.0, 20.0);
glVertex2f(-35.0, 15.0);
glEnd();
glColor3f(0.0f, 0.5f, 0.0f);
glBegin(GL_POLYGON);
glVertex2f(-22.5, 20.0);
glVertex2f(-27.5, 25.0);
glVertex2f(-32.5, 20.0);
glEnd();
}
void draw_tree2(){
//2nd tree
glColor3f(0.1f, 0.0f, 0.0f);
glBegin(GL_POLYGON);
glVertex2f(30.0, 5.0);
glVertex2f(25.0, 5.0);
glVertex2f(25.0, 10.0);
glVertex2f(30.0, 10.0);
glEnd();
glColor3f(0.0f, 0.5f, 0.0f);
glBegin(GL_POLYGON);
glVertex2f(17.5, 10.0);
glVertex2f(22.5, 15.0);
glVertex2f(32.5, 15.0);
glVertex2f(37.5, 10.0);
glEnd();
glColor3f(0.0f, 0.5f, 0.0f);
glBegin(GL_POLYGON);
glVertex2f(20.0, 15.0);
glVertex2f(25.0, 20.0);
glVertex2f(30.0, 20.0);
glVertex2f(35.0, 15.0);
glEnd();
glColor3f(0.0f, 0.5f, 0.0f);
glBegin(GL_POLYGON);
glVertex2f(22.5, 20.0);
glVertex2f(27.5, 25.0);
glVertex2f(32.5, 20.0);
glEnd();
}
void building1(){
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 1.0);
glVertex3f(28, -7, 0);
glVertex3f(28, 7, 0);
glVertex3f(32, 7, 0);
glVertex3f(32, -7, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 1.0);
glVertex3f(28, 10, 0);
glVertex3f(28, 20, 0);
glVertex3f(32, 20, 0);
glVertex3f(32, 10, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 1.0);
glVertex3f(38, -2, 0);
glVertex3f(38, 5, 0);
glVertex3f(42, 5, 0);
glVertex3f(42, -2, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0, 0.0, 0.0);
glVertex3f(25, -7, 0);
glVertex3f(25, 30, 0);
glVertex3f(35, 30, 0);
glVertex3f(35, 10, 0);
glVertex3f(45, 10, 0);
glVertex3f(45, -7, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 0.0);
glVertex3f(30, 40, 0);
glVertex3f(25, 30, 0);
glVertex3f(35, 30, 0);
glEnd();
}
void building2(){
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 1.0);
glVertex3f(-35, 6, 0);
glVertex3f(-32, 6, 0);
glVertex3f(-32, -7, 0);
glVertex3f(-35, -7, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 1.0);
glVertex3f(-30, 6, 0);
glVertex3f(-26, 6, 0);
glVertex3f(-26, 10, 0);
glVertex3f(-30, 10, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.7, 0, 0.7);
glVertex3f(-40, -7, 0);
glVertex3f(-25, -7, 0);
glVertex3f(-25, 15, 0);
glVertex3f(-40, 15, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,5, 0.0);
glVertex3f(-38, 23, 0);
glVertex3f(-27, 23, 0);
glVertex3f(-25, 15, 0);
glVertex3f(-40, 15, 0);
glEnd();
glBegin(GL_LINES);
glColor3f(0.0, 0.0, 0.0);
glVertex3f(-30, 8, 0);
glVertex3f(-26, 8, 0);
glEnd();
glBegin(GL_LINES);
glColor3f(0.0, 0.0, 0.0);
glVertex3f(-28, 6, 0);
glVertex3f(-28, 10, 0);
glEnd();
}
void building3()
{
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 1.0);
glVertex3f(-5, -7, 0);
glVertex3f(5, -7, 0);
glVertex3f(5, 15, 0);
glVertex3f(-5, 15, 0);
glEnd();
glBegin(GL_LINES);
glColor3f(0.0, 0.0, 0.0);
glVertex3f(15, 15, 0);
glVertex3f(-15, 15, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 1.0);
glVertex3f(-14, 0, 0);
glVertex3f(-6, 0, 0);
glVertex3f(-6, 8, 0);
glVertex3f(-14, 8, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 1.0);
glVertex3f(-14, 16, 0);
glVertex3f(-6, 16, 0);
glVertex3f(-6, 24, 0);
glVertex3f(-14, 24, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 1.0);
glVertex3f(-5, 16, 0);
glVertex3f(5, 16, 0);
glVertex3f(5, 24, 0);
glVertex3f(-5, 24, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 1.0);
glVertex3f(6, 0, 0);
glVertex3f(14, 0, 0);
glVertex3f(14, 8, 0);
glVertex3f(6, 8, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 1.0);
glVertex3f(6, 24, 0);
glVertex3f(14, 24, 0);
glVertex3f(14, 16, 0);
glVertex3f(6, 16, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 1.0);
glVertex3f(-35, 6, 0);
glVertex3f(-32, 6, 0);
glVertex3f(-32, -7, 0);
glVertex3f(-35, -7, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0, 1.0, 1.0);
glVertex3f(-30, 6, 0);
glVertex3f(-26, 6, 0);
glVertex3f(-26, 10, 0);
glVertex3f(-30, 10, 0);
glEnd();
glBegin(GL_LINES);
glColor3f(0.0, 0.0, 0.0);
glVertex3f(-30, 8, 0);
glVertex3f(-26, 8, 0);
glEnd();
glBegin(GL_LINES);
glColor3f(0.0, 0.0, 0.0);
glVertex3f(-28, 6, 0);
glVertex3f(-28, 10, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0, 0.6, 1.0);
glVertex3f(-15, -7, 0);
glVertex3f(15, -7, 0);
glVertex3f(15, 30, 0);
glVertex3f(-15, 30, 0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.6, 1.5, 1.0);
glVertex3f(-13, 42, 0);
glVertex3f(13, 42, 0);
glVertex3f(15, 30, 0);
glVertex3f(-15, 30, 0);
glEnd();
}
void house(){
glBegin(GL_POLYGON);
glColor3f(0.0, 0.0, 0.0);
glVertex2f(10,120);
glVertex2f(10,125);
glVertex2f(20,125);
glVertex2f(20,120);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0, 0.0, 0.0);
glVertex2f(14,100);
glVertex2f(14,110);
glVertex2f(16,110);
glVertex2f(16,100);
glEnd();
glBegin(GL_POLYGON);
glColor3f(.990, 0.0, 0.0);
glVertex2f(10,100);
glVertex2f(10,120);
glVertex2f(20,120);
glVertex2f(20,100);
glEnd();
}
void tree(){
glColor3f(.1,0.2,0.1);
glBegin(GL_TRIANGLES);
glColor3f(.1,0.5,0.1);
glVertex2f(30.5,140);
glVertex2f(28,110);
glVertex2f(33,110);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0, 0.0, 0.0);
glVertex2f(30,100);
glVertex2f(30,120);
glVertex2f(31,120);
glVertex2f(31,100);
glEnd();
}
void tree1(){
glColor3f(0.1,0.2,0.1);
glBegin(GL_TRIANGLES);
glColor3f(.1,0.5,0.1);
glVertex2f(30.5,140);
glVertex2f(28,110);
glVertex2f(33,110);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0, 0.0, 0.0);
glVertex2f(30,100);
glVertex2f(30,120);
glVertex2f(31,120);
glVertex2f(31,100);
glEnd();
}
void lanes(){
glBegin(GL_POLYGON); //lanes
glColor3f(1.0,0.9,0.0);
glVertex2f(20,0);
glVertex2f(20,5);
glVertex2f(30,5);
glVertex2f(30,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(.7,0.7,0.7);
glVertex2f(30,0);
glVertex2f(30,5);
glVertex2f(40,5);
glVertex2f(40,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,0.9,0.0);
glVertex2f(40,0);
glVertex2f(40,5);
glVertex2f(50,5);
glVertex2f(50,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(.7,0.7,0.7);
glVertex2f(50,0);
glVertex2f(50,5);
glVertex2f(60,5);
glVertex2f(60,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,0.9,0.0);
glVertex2f(60,0);
glVertex2f(60,5);
glVertex2f(70,5);
glVertex2f(70,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(.7,0.7,0.7);
glVertex2f(70,0);
glVertex2f(70,5);
glVertex2f(80,5);
glVertex2f(80,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,0.9,0.0);
glVertex2f(80,0);
glVertex2f(80,5);
glVertex2f(90,5);
glVertex2f(90,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(.7,0.7,0.7);
glVertex2f(90,0);
glVertex2f(90,5);
glVertex2f(100,5);
glVertex2f(100,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,0.9,0.0);
glVertex2f(100,0);
glVertex2f(100,5);
glVertex2f(110,5);
glVertex2f(110,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(.7,0.7,0.7);
glVertex2f(110,0);
glVertex2f(110,5);
glVertex2f(120,5);
glVertex2f(120,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,0.9,0.0);
glVertex2f(120,0);
glVertex2f(120,5);
glVertex2f(130,5);
glVertex2f(130,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(.7,0.7,0.7);
glVertex2f(130,0);
glVertex2f(130,5);
glVertex2f(140,5);
glVertex2f(140,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,0.9,0.0);
glVertex2f(140,0);
glVertex2f(140,5);
glVertex2f(150,5);
glVertex2f(150,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(.7,0.7,0.7);
glVertex2f(150,0);
glVertex2f(150,5);
glVertex2f(160,5);
glVertex2f(160,0);
glEnd();
glBegin(GL_POLYGON); //lanes
glColor3f(1.0,1.0,1.0);
glVertex2f(40,39);
glVertex2f(40,43);
glVertex2f(50,43);
glVertex2f(50,39);
glEnd();
glBegin(GL_POLYGON); //lanes
glColor3f(1.0,1.0,1.0);
glVertex2f(70,39);
glVertex2f(70,43);
glVertex2f(80,43);
glVertex2f(80,39);
glEnd();
glBegin(GL_POLYGON); //lanes
glColor3f(1.0,1.0,1.0);
glVertex2f(100,39);
glVertex2f(100,43);
glVertex2f(110,43);
glVertex2f(110,39);
glEnd();
glBegin(GL_POLYGON); //lanes
glColor3f(1.0,1.0,1.0);
glVertex2f(58,55);
glVertex2f(58,68);
glVertex2f(60,68);
glVertex2f(60,55);
glEnd();
glBegin(GL_POLYGON); //lanes
glColor3f(1.0,1.0,1.0);
glVertex2f(58,35);
glVertex2f(58,48);
glVertex2f(60,48);
glVertex2f(60,35);
glEnd();
}
void road()
{
glBegin(GL_POLYGON);
glColor3f(1.0,1.0,1.0);
glVertex2f(20,80);
glVertex2f(20,85);
glVertex2f(30,85);
glVertex2f(30,80);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,1.0,1.0);
glVertex2f(50,80);
glVertex2f(50,85);
glVertex2f(60,85);
glVertex2f(60,80);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,1.0,1.0);
glVertex2f(80,80);
glVertex2f(80,85);
glVertex2f(90,85);
glVertex2f(90,80);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,1.0,1.0);
glVertex2f(110,80);
glVertex2f(110,85);
glVertex2f(120,85);
glVertex2f(120,80);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,1.0,1.0);
glVertex2f(140,80);
glVertex2f(140,85);
glVertex2f(150,85);
glVertex2f(150,80);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(0,70);
glVertex2f(0,100);
glVertex2f(50,100);
glVertex2f(50,70);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(50,70);
glVertex2f(50,100);
glVertex2f(70,100);
glVertex2f(70,70);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(70,70);
glVertex2f(70,100);
glVertex2f(103,100);
glVertex2f(103,70);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(103,70);
glVertex2f(103,100);
glVertex2f(120,100);
glVertex2f(120,70);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(120,70);
glVertex2f(120,100);
glVertex2f(135,100);
glVertex2f(135,70);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(135,70);
glVertex2f(135,100);
glVertex2f(150,100);
glVertex2f(150,70);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(150,70);
glVertex2f(150,100);
glVertex2f(170,100);
glVertex2f(170,70);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(50,50);
glVertex2f(50,70);
glVertex2f(70,70);
glVertex2f(70,50);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(103,50);
glVertex2f(103,70);
glVertex2f(120,70);
glVertex2f(120,50);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(50,100);
glVertex2f(50,130);
glVertex2f(70,130);
glVertex2f(70,100);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(103,100);
glVertex2f(103,130);
glVertex2f(120,130);
glVertex2f(120,100);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(120,120);
glVertex2f(120,135);
glVertex2f(150,135);
glVertex2f(150,120);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(135,100);
glVertex2f(135,120);
glVertex2f(150,120);
glVertex2f(150,100);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(50,130);
glVertex2f(50,450);
glVertex2f(120,150);
glVertex2f(120,130);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(50,30);
glVertex2f(50,50);
glVertex2f(120,50);
glVertex2f(120,30);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(20,30);
glVertex2f(20,50);
glVertex2f(50,50);
glVertex2f(50,30);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(135,20);
glVertex2f(135,70);
glVertex2f(150,70);
glVertex2f(150,20);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(20,5);
glVertex2f(20,30);
glVertex2f(40,30);
glVertex2f(40,5);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex2f(40,5);
glVertex2f(40,20);
glVertex2f(150,20);
glVertex2f(150,5);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,0.9,0.0);
glVertex2f(20,0);
glVertex2f(20,5);
glVertex2f(30,5);
glVertex2f(30,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(.7,0.7,0.7);
glVertex2f(30,0);
glVertex2f(30,5);
glVertex2f(40,5);
glVertex2f(40,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,0.9,0.0);
glVertex2f(40,0);
glVertex2f(40,5);
glVertex2f(50,5);
glVertex2f(50,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(.7,0.7,0.7);
glVertex2f(50,0);
glVertex2f(50,5);
glVertex2f(60,5);
glVertex2f(60,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,0.9,0.0);
glVertex2f(60,0);
glVertex2f(60,5);
glVertex2f(70,5);
glVertex2f(70,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(.7,0.7,0.7);
glVertex2f(70,0);
glVertex2f(70,5);
glVertex2f(80,5);
glVertex2f(80,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,0.9,0.0);
glVertex2f(80,0);
glVertex2f(80,5);
glVertex2f(90,5);
glVertex2f(90,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(.7,0.7,0.7);
glVertex2f(90,0);
glVertex2f(90,5);
glVertex2f(100,5);
glVertex2f(100,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,0.9,0.0);
glVertex2f(100,0);
glVertex2f(100,5);
glVertex2f(110,5);
glVertex2f(110,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(.7,0.7,0.7);
glVertex2f(110,0);
glVertex2f(110,5);
glVertex2f(120,5);
glVertex2f(120,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,0.9,0.0);
glVertex2f(120,0);
glVertex2f(120,5);
glVertex2f(130,5);
glVertex2f(130,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(.7,0.7,0.7);
glVertex2f(130,0);
glVertex2f(130,5);
glVertex2f(140,5);
glVertex2f(140,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1.0,0.9,0.0);
glVertex2f(140,0);
glVertex2f(140,5);
glVertex2f(150,5);
glVertex2f(150,0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(.7,0.7,0.7);
glVertex2f(150,0);
glVertex2f(150,5);
glVertex2f(160,5);
glVertex2f(160,0);
glEnd();
tree();
house();
}
void cir(int x,int y)
{
float th;
glBegin(GL_LINES);
for(int i=0;i<360;i++)
{
th=i*3.142/180;
glVertex2f(x+10*cos(th),y+10*sin(th));
}
glEnd();
}
void poly()
{
glBegin(GL_POLYGON);
glVertex2f(20,190);
glVertex2f(20,170);
glVertex2f(60,170);
glVertex2f(60,190);
glEnd();
glPushMatrix();
cir(20,180);
glPopMatrix();
glPushMatrix();
cir(60,180);
glPopMatrix();
}
void circfun(float x,float y)
{
float th;
glBegin(GL_POLYGON);
for(int i=0;i<360;i++)
{
th=i*3.142/180;
glVertex2f(x+2*cos(th),y+2*sin(th));
}
glEnd();
}
void circ(){
glColor3f (1, 0.0, 0.0);
circfun(-20,-7);
circfun(-20,1);
circfun(-19,8);
circfun(-16,14);
circfun(-10,18);
circfun(-3,21);
circfun(4,21);
circfun(10,19);
circfun(15,15);
circfun(15,-15);
circfun(10,-19);
circfun(4,-21);
circfun(-3,-21);
circfun(-10,-18);
circfun(-16,-14);
circfun(19,-8);
circfun(20,7);
circfun(20,-1);
}
float f=0.0;
void solidcircle(int x,int y,int z){
f +=0.1;
glColor3f(1.0,0,0);
glTranslatef(x,y,z);
glRotatef(f,0,0,1);
glutSolidSphere(6,50,50);
glColor3f(0,0,0);
glutWireSphere(5.99,100,100);
glScalef(0.3,0.3,0);
circ();
}
void MAN()
{
glBegin (GL_POLYGON);//HAIR
glColor3f (0.5, 0.4, 0.3);
glVertex2f (24,53);
glVertex2f (23,55);
glVertex2i (26,55);
glVertex2i (26,56.5);
glVertex2i (31,53);
glEnd();
glColor3f (0.0, 0.0, 0.0);
glRecti (25.7, 50, 26.5, 51.5);//eye1
glRecti (29.5, 50, 30.5, 51.5);//eye2
glBegin (GL_TRIANGLES);//NOSE
glColor3f (0.0, 0.0, 0.0);
glVertex2f (27.5,49);
glVertex2f (27,47);
glVertex2i (28,47);
glEnd();
glBegin (GL_TRIANGLES);//MOUTH
glColor3f (1.0, 0.0, 0.5);
glVertex2i (25.5,46);
glVertex2f (27.5,44);
glVertex2f (29.5,46);
glEnd();
glBegin (GL_QUADS);
glColor3f (0.60, 0.0, 0.);
glVertex2i (24,20);//body
glVertex2i (22,40);
glVertex2i (33,40);
glVertex2i (31,20);
glColor3f (0.0,0.0,0.4);
glVertex2i (25,20);//legs
glVertex2i (20,3);
glVertex2i (25,3);
glVertex2i (27,20);
glVertex2f (30,20);
glVertex2i (34,3);
glVertex2i (29,3);
glVertex2i (28,20);
glColor3f (0.60, 0.0, 0.);
glVertex2f (22,40);//arms
glVertex2f (22.5,38);
glVertex2i (20,23);
glVertex2i (18,25);
glVertex2f (33,40);
glVertex2f (32.5,38);
glVertex2i (38,25);
glVertex2i (36,23);
glEnd();
glColor3f (0.85, 0.95, 0);
glRecti (26, 40, 29, 43);
glBegin (GL_POLYGON);//FACE
glColor3f (0.85, 0.95, 0);
glVertex2f (26,43);
glVertex2f (24,45);
glVertex2i (24,53);
glVertex2i (31,53);
glVertex2i (31,45);
glVertex2i (29,43);
glEnd();
glBegin (GL_TRIANGLES);//SHOE1
glColor3f (1.0, 1.0, 1.0);
glVertex2i (25,3);
glVertex2f (18,1);
glVertex2f (20,3);
glEnd();
glBegin (GL_TRIANGLES);//SHOE2
glColor3f (1.0, 1.0, 1.0);
glVertex2i (29,3);
glVertex2f (37,1);
glVertex2f (34,3);
glEnd();
glBegin (GL_POLYGON);//WRIST1
glColor3f (0.85, 0.95, 0);
glVertex2f (18,25);
glVertex2f (16,25.5);
glVertex2f (17.5,24.5);
glVertex2f (17,23.5);
glVertex2f (18.5,21.5);
glVertex2f (20,23);
glEnd();
glBegin (GL_POLYGON);//WRIST2
glVertex2f (38,25);
glVertex2f (36,23);
glVertex2f (37,21.5);
glVertex2f (39.5,23.5);
glEnd();
glFlush ( ); // Process all OpenGL routines as quickly as possible.
}
float th=0.0;
void vaccine(){
th+=1.0;
glPushMatrix();
glTranslatef(100,100,0);
//glRotatef(th,0,1,0);
glScalef(1,4,0);
glutSolidCube(20);
glPopMatrix();
glPushMatrix();
glTranslatef(100,55,0);
//lRotatef(th,0,1,0);
glScalef(1,4,0);
glutSolidCube(5.0);
glPopMatrix();
glPushMatrix();
glTranslatef(100,45,0);
//glRotatef(th,0,1,0);
glScalef(3.5,0.5,0);
glutSolidCube(5.0);
glPopMatrix();
glPushMatrix();
glTranslatef(100,145,0);
glColor3f(0.5,0.0,0);
//glRotatef(th,0,0,0);
glScalef(0.25,2,0);
glutSolidCube(5.0);
glPopMatrix();
glPushMatrix();
glColor3f(1,0,0);
glTranslatef(100,110,0);
glRotatef(th,1,0,0);
glScalef(3,10,0);
glutSolidCube(5);
glPopMatrix();
}
float k=0;
void tablet(){
k+=0.5;
glPushMatrix();
glColor3f(0,0,1);
glTranslatef(100,100,-25);
glScalef(1.5,1,0);
glutSolidCube(50);
glPopMatrix();
glPushMatrix();
glColor3f(1,1,0);
glTranslatef(135,100,0);
glRotatef(k,0,1,0);
glutSolidSphere(25,20,20);
glPopMatrix();
glPushMatrix();
glTranslatef(65,100,0);
glRotatef(k,0,1,0);
glutSolidSphere(25,20,20);
glPopMatrix();
}
void display() {
glColor3f (0.3, 0.5, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glPushMatrix();
glTranslatef(m,n,o);
glScalef(0.8,0.60,0);
MAN();
glPopMatrix();
glColor3f (0.5, 0.95, 0);
glRectf(50,25,168.7,44);
glColor3f (0.5, 0.95, 0);
glRectf(0,70,62.5,98);
glColor3f (0.5, 0.95, 0);
glRectf(87.5,70,128.9,76);
glColor3f (0.5, 0.95, 0);
glRectf(87.5,130,128.9,146);
glColor3f (0.5, 0.95, 0);
glRectf(0,0,25,20);
glPushMatrix();
glTranslatef(60,40,0);
glScalef(1,1,1.0);
glColor3f(0,0.0,1);
tree1();
glPopMatrix();
glPushMatrix();
glTranslatef(60,-25,0);
glScalef(1,1,1.0);
glColor3f(0,0.0,1);
tree1();
glPopMatrix();
glPushMatrix();
glTranslatef(148,25,0);
glScalef(0.3,0.4,1.0);
glColor3f(0,0.0,1);
vaccine();
glPopMatrix();
glPushMatrix();
glTranslatef(50,-35,0);
glScalef(0.2,0.5,0);
glColor3f(0,0.4,1);
poly();
glPopMatrix();
glPushMatrix();
solidcircle(180,120,0);
glPopMatrix();
glPushMatrix();
solidcircle(75,180,0);
glPopMatrix();
glPushMatrix();
solidcircle(120,17,0);
glPopMatrix();
glPushMatrix();
glScalef(0.07,0.07,0);
glTranslatef(700,1400,0);
glColor3f(0,0.0,1);
tablet();
glPopMatrix();
glPushMatrix();
glScalef(0.07,0.07,0);
glTranslatef(1900,2100,0);
glColor3f(0,0.0,1);
tablet();
glPopMatrix();
glPushMatrix();
glScalef(0.07,0.07,0);
glTranslatef(1700,1400,0);
glColor3f(0,0.0,1);
tablet();
glPopMatrix();
glPushMatrix();
glScalef(0.7,1,0.5);
glTranslatef(18,25,0);
building3();
glPopMatrix();
glPushMatrix();
glScalef(0.7,0.5,0.5);
glTranslatef(180,160,0);
building2();
glPopMatrix();
glPushMatrix();
glScalef(0.7,0.5,0.5);
glTranslatef(197,160,0);
building2();
glPopMatrix();
glPushMatrix();
glScalef(0.7,0.5,0.5);
glTranslatef(202,297.5,0);
building2();
glPopMatrix();
glPushMatrix();
glScalef(0.9,0.7,0.5);
glTranslatef(80,215,0);
building1();
glPopMatrix();
glPushMatrix();
glTranslatef(187,133,0);
glScalef(1,1.4,0);
draw_tree1();
glPopMatrix();
glPushMatrix();
glTranslatef(187,33,0);
glScalef(1,2,0);
draw_tree1();
glPopMatrix();
glPushMatrix();
glScalef(1.25,1.4,0);
road();
glPopMatrix();
glutSwapBuffers();
glutPostRedisplay();
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(1500, 700);
glutInitWindowPosition(0, 0);
glutCreateWindow("CORONA GAME");
init();
glutDisplayFunc(display);
glutSpecialFunc(ObjectKeys);
glEnable(GL_DEPTH_TEST);
glutMainLoop();
return 0;
}
| fb9e29fdfcd831251cd0a0ed54e6482a20a7f162 | [
"Markdown",
"C++"
] | 4 | C++ | AkankshaGaonkar/go_Korona_Go | 3175fc52e5e11a6628ef26d3715cb6132b87f8d6 | 7cef1fa13273ec6c5edd5efddfb71bd8fd52e5bc |
refs/heads/master | <file_sep># Interactive-Form
An interactive form made from html5 and css3
#### Live Demo: https://created-by-varun.github.io/Interactive-Form/
#### Preview:

<file_sep>// Nah.... not today | af206df08b433eae6d276c1da9df1076474187bc | [
"Markdown",
"JavaScript"
] | 2 | Markdown | created-by-varun/Interactive-Form | 9ca7ae2c8919d280e29e4664372c74cbf540c633 | 89a0f567b8739c915973854016d8d2f2a704d190 |
refs/heads/master | <repo_name>POO-2020/tarea-01a-el-hospital-XimenaV26<file_sep>/OneDrive/Documentos/Hotel/fecha.js
export default class Fecha {
/**
*
* @param {number} dia valor 1..31
* @param {number} mes valor 1..12
* @param {number} año Año de la fecha de nacimiento
*/
constructor(dia, mes, año) {
this.fecha = new Date(año, mes - 1, dia);
this.diaSemana = ["Domingo", "Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sabado"];
this.diaMes = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"];
this.fecha3 = new Date;
}
getFormatoCorto() {
let date = this.fecha.getDate();
let month = this.fecha.getMonth() + 1;
let year = this.fecha.getFullYear();
return`${date}/${month}/${year}`;
}
}<file_sep>/OneDrive/Documentos/Hospital/main.js
import Nombre from "./nombre.js"
import Paciente from "./paciente.js"
import Tiempo from "./tiempo.js"
import Doctor from "./doctor.js"
import Fecha from "./fecha.js"
import Cita from "./cita.js"
import Hospital from "./hospital.js"
class Main{
constructor(){
this.hospital = new Hospital("Pu<NAME>", "Av. De la Paz");
}
testCita(){
let perfil = new Cita(new Fecha(25, 11, 2020), new Tiempo(4, 33, "PM"), new Nombre("Alfonso", "Ramirez", "peralta"),new Nombre("juan", "perez", "gonzales"));
console.log(perfil.getPerfil())
}
agregarDoctor(){
let doc = new Doctor(45678, "Cirujano", "<NAME>", 3145673);
let doc2 = new Doctor(4563, "Oculista", "<NAME>", 312456312);
this.hospital.registrarDoctor(doc);
this.hospital.registrarDoctor(doc2);
this.hospital.listarDoctor();
}
agregarCita(){
let cita1 = new Cita(new Fecha(26, 4, 2020), new Tiempo(10, 20, "AM"), new Nombre("Ximena", "Velasco", "Godinez"),new Nombre("Rosa", "Flores", "Bivian"));
this.hospital.registrarCita(cita1);
this.hospital.listarCita();
}
}
let app = new Main();
app.testCita();
app.agregarDoctor();
app.agregarCita();
<file_sep>/OneDrive/Documentos/Hotel/reservacion.js
import Fecha from "./fecha.js"
import Huesped from "./huesped.js"
export default class Reservacion{
/**
*
* @param {number} numeroHabitacion El número que identifica a la habiltación, por ejemplo: 1256 ó 2345.
* @param {Fecha} fechaLlegada La fecha de llegada de los huéspedes
* @param {number} noches Número de noches reservadas
* @param {Huesped} huspedes Las personas que estarán hospedadas en esta habitación
*/
constructor(numeroHabitacion, fechaLlegada, noches, huspedes){
this.numeroHabitacion = numeroHabitacion;
this.fechaLlegada = fechaLlegada;
this.noches = noches;
this.huespedes = new Array();
}
getFechaFormatoCorto(){
return(this.fechaLlegada.getFormatoCorto());
}
addHuesped(huesped){
this.huespedes.push(huesped);
}
getNumeroHuspedes(){
this.huespedes.forEach((huesped, i) => {console.log(`${i} ${huesped.getDescription()}`)});
}
print(){
return(`Habitacion : ${this.numeroHabitacion}
Fecha de llegada: ${this.getFechaFormatoCorto()}
${this.noches} noches reservadas
${this.huespedes}`)
}
}
<file_sep>/OneDrive/Documentos/Hospital/cita.js
import Fecha from "./fecha.js"
import Tiempo from "./tiempo.js"
import Doctor from "./doctor.js"
import Paciente from "./paciente.js"
import Nombre from "./nombre.js"
export default class Cita{
/**
*
* @param {Fecha} fecha Fecha de la cita
* @param {Tiempo} hora Hora de la cita
* @param {Doctor} doctor Nombre del Doctor
* @param {Paciente} paciente Nombre del paciente
*/
constructor(fecha,hora, doctor,paciente){
this.fecha = fecha;
this.hora = hora;
this.doctor = doctor;
this.paciente = paciente;
}
getPerfil(){
return(`${this.fecha.getFecha3()}, ${this.hora.getFormato24()}, Dr. ${this.doctor.nombre}, ${this.paciente.getNombreCompleto()}`);
}
}
/**let perfil = new Cita(new Fecha(25, 11, 2000), new Tiempo(4, 3, "PM"), new Nombre("Alfonso", "Ramirez", "peralta"),new Nombre("juan", "perez", "gonzales"))
console.log(perfil.getPerfil())**/<file_sep>/OneDrive/Documentos/Hospital/nombre.js
export default class Nombre{
/**
*
* @param {string} nombre Nombres
* @param {string} apellidoPaterno Apellido paterno
* @param {string} ApellidoMaterno Apellido materno
*/
constructor(nombre, apellidoPaterno, ApellidoMaterno){
this.nombre = nombre;
this.apellidoPaterno = apellidoPaterno;
this.ApellidoMaterno = ApellidoMaterno;
}
getNombreCompleto(){
return(`${this.nombre} ${this.apellidoPaterno} ${this.ApellidoMaterno} `);
}
getApellidoNombre(){
return(`${this.apellidoPaterno} ${this.ApellidoMaterno} ${this.nombre}`)
}
getIniciales(){
return(`${this.nombre[0]} ${this.apellidoPaterno[0]} ${this.ApellidoMaterno[0]}`);
}
}
/**let paciente1 = new Nombre("Ximena", "Velasco", "Godinez");
console.log(paciente1.getNombreCompleto());
console.log(paciente1.getApellidoNombre());
console.log(paciente1.getIniciales());**/
<file_sep>/OneDrive/Documentos/Hotel/huesped.js
export default class Huesped{
/**
*
* @param {string} nombre
* @param {string} genero
*/
constructor(nombre, genero){
this.nombre = nombre;
this.genero = genero;
}
getDescription(){
return(`${this.nombre} genero: ${this.genero}`)
}
}
| 86ccd66df8dee52ae120a3ec2eec8e8ae505e6d8 | [
"JavaScript"
] | 6 | JavaScript | POO-2020/tarea-01a-el-hospital-XimenaV26 | c448f6d0c277168493b61f9f7e6664943ed06ac0 | 6a8ac1d624c17530c59097a869a922652c6aa195 |
refs/heads/master | <repo_name>innayan/dsl_idea<file_sep>/.teamcity/patches/templates/Absolute-ProjectToBreak_SubprojectToBreak_Template2344.kts
package patches.templates
import jetbrains.buildServer.configs.kotlin.v2018_2.*
import jetbrains.buildServer.configs.kotlin.v2018_2.Template
import jetbrains.buildServer.configs.kotlin.v2018_2.buildSteps.script
import jetbrains.buildServer.configs.kotlin.v2018_2.ui.*
/*
This patch script was generated by TeamCity on settings change in UI.
To apply the patch, create a template with absolute id = 'ProjectToBreak_SubprojectToBreak_Template2344'
in the project with absolute id = 'ProjectToBreak', and delete the patch script.
*/
create(AbsoluteId("ProjectToBreak"), Template({
id = AbsoluteId("ProjectToBreak_SubprojectToBreak_Template2344")
name = "template1"
steps {
script {
id = "RUNNER_14"
scriptContent = "echo template"
}
}
}))
<file_sep>/.teamcity/patches/templates/ProjectToBreak1_SubprojectToBreakTemplate2344.kts
package patches.templates
import jetbrains.buildServer.configs.kotlin.v2018_2.*
import jetbrains.buildServer.configs.kotlin.v2018_2.Template
import jetbrains.buildServer.configs.kotlin.v2018_2.buildSteps.script
import jetbrains.buildServer.configs.kotlin.v2018_2.ui.*
/*
This patch script was generated by TeamCity on settings change in UI.
To apply the patch, create a template with id = 'ProjectToBreak1_SubprojectToBreakTemplate2344'
in the project with id = 'ProjectToBreak1', and delete the patch script.
*/
create(RelativeId("ProjectToBreak1"), Template({
id("ProjectToBreak1_SubprojectToBreakTemplate2344")
name = "template1"
steps {
script {
id = "RUNNER_14"
scriptContent = "echo template"
}
}
}))
<file_sep>/.teamcity/patches/projects/Absolute-ProjectToBreak.kts
package patches.projects
import jetbrains.buildServer.configs.kotlin.v2018_2.*
import jetbrains.buildServer.configs.kotlin.v2018_2.Project
import jetbrains.buildServer.configs.kotlin.v2018_2.ui.*
/*
This patch script was generated by TeamCity on settings change in UI.
To apply the patch, create a project with absolute id = 'ProjectToBreak'
in the root project, and delete the patch script.
*/
create(DslContext.projectId, Project({
id = AbsoluteId("ProjectToBreak")
name = "Project to break"
}))
<file_sep>/.teamcity/patches/projects/ProjectToBreak1.kts
package patches.projects
import jetbrains.buildServer.configs.kotlin.v2018_2.*
import jetbrains.buildServer.configs.kotlin.v2018_2.Project
import jetbrains.buildServer.configs.kotlin.v2018_2.ui.*
/*
This patch script was generated by TeamCity on settings change in UI.
To apply the patch, create a project with id = 'ProjectToBreak1'
in the root project, and delete the patch script.
*/
create(DslContext.projectId, Project({
id("ProjectToBreak1")
name = "Project to break1"
}))
<file_sep>/.teamcity/settings.kts
import jetbrains.buildServer.configs.kotlin.v2018_2.*
import jetbrains.buildServer.configs.kotlin.v2018_2.ideaDuplicates
import jetbrains.buildServer.configs.kotlin.v2018_2.ideaInspections
import jetbrains.buildServer.configs.kotlin.v2018_2.ideaRunner
import jetbrains.buildServer.configs.kotlin.v2018_2.vcs.SvnVcsRoot
/*
The settings script is an entry point for defining a TeamCity
project hierarchy. The script should contain a single call to the
project() function with a Project instance or an init function as
an argument.
VcsRoots, BuildTypes, Templates, and subprojects can be
registered inside the project using the vcsRoot(), buildType(),
template(), and subProject() methods respectively.
To debug settings scripts in command-line, run the
mvnDebug org.jetbrains.teamcity:teamcity-configs-maven-plugin:generate
command and attach your debugger to the port 8000.
To debug in IntelliJ Idea, open the 'Maven Projects' tool window (View
-> Tool Windows -> Maven Projects), find the generate task node
(Plugins -> teamcity-configs -> teamcity-configs:generate), the
'Debug' option is available in the context menu for the task.
*/
version = "2019.1"
project {
vcsRoot(svn)
buildType(IdeaTest)
features {
feature {
id = "PROJECT_EXT_5"
type = "CloudImage"
param("key-pair-name", "iy1")
param("use-spot-instances", "false")
param("security-group-ids", "sg-22baaa56,")
param("profileId", "vmw-2")
param("agent_pool_id", "-2")
param("ebs-optimized", "false")
param("instance-type", "t2.micro")
param("amazon-id", "i-02ef2c854675c4fa1")
param("source-id", "i-02ef2c854675c4fa1")
}
feature {
id = "vmw-2"
type = "CloudProfile"
param("profileServerUrl", "")
param("secure:access-id", "credentialsJSON:<KEY>")
param("system.cloud.profile_id", "vmw-2")
param("total-work-time", "")
param("description", "")
param("cloud-code", "amazon")
param("endpoint-url", "ec2.eu-west-1.amazonaws.com")
param("enabled", "false")
param("max-running-instances", "3")
param("agentPushPreset", "")
param("profileId", "vmw-2")
param("name", "dddd")
param("next-hour", "")
param("secure:secret-key", "credentialsJSON:deb973b9-d3d7-4dac-a20a-f5a938124b38")
param("terminate-idle-time", "30")
param("not-checked", "")
}
}
}
object IdeaTest : BuildType({
name = "IDEA_test"
params {
param("system.path.macro.MAVEN.REPOSITORY", ".m2")
param("env.JDK_16", """C:\Java_16""")
}
vcs {
root(svn)
}
steps {
ideaRunner {
pathToProject = ""
jdk {
name = "1.6"
path = "%env.JDK_16%"
patterns("jre/lib/*.jar", "jre/lib/ext/jfxrt.jar")
extAnnotationPatterns("%teamcity.tool.idea%/lib/jdkAnnotations.jar")
}
jdk {
name = "1.8"
path = "%env.JDK_18%"
patterns("jre/lib/*.jar", "jre/lib/ext/jfxrt.jar")
extAnnotationPatterns("%teamcity.tool.idea%/lib/jdkAnnotations.jar")
}
pathvars {
variable("MAVEN_REPOSITORY", "%system.path.macro.MAVEN.REPOSITORY%")
}
jvmArgs = "-Xmx256m"
}
ideaDuplicates {
executionMode = BuildStep.ExecutionMode.RUN_ON_FAILURE
pathToProject = ""
jdk {
name = "1.6"
path = "%env.JDK_16%"
patterns("jre/lib/*.jar", "jre/lib/ext/jfxrt.jar")
extAnnotationPatterns("%teamcity.tool.idea%/lib/jdkAnnotations.jar")
}
jdk {
name = "1.8"
path = "%env.JDK_18%"
patterns("jre/lib/*.jar", "jre/lib/ext/jfxrt.jar")
extAnnotationPatterns("%teamcity.tool.idea%/lib/jdkAnnotations.jar")
}
pathvars {
variable("MAVEN_REPOSITORY", "%system.path.macro.MAVEN.REPOSITORY%")
}
jvmArgs = "-Xmx1G -XX:ReservedCodeCacheSize=240m"
targetJdkHome = "%env.JDK_18%"
lowerBound = 10
discardCost = 0
distinguishMethods = true
distinguishTypes = true
distinguishLiterals = true
extractSubexpressions = true
}
ideaInspections {
executionMode = BuildStep.ExecutionMode.RUN_ON_FAILURE
pathToProject = ""
jdk {
name = "1.6"
path = "%env.JDK_16%"
patterns("jre/lib/*.jar", "jre/lib/ext/jfxrt.jar")
extAnnotationPatterns("%teamcity.tool.idea%/lib/jdkAnnotations.jar")
}
jdk {
name = "1.8"
path = "%env.JDK_18%"
patterns("jre/lib/*.jar", "jre/lib/ext/jfxrt.jar")
extAnnotationPatterns("%teamcity.tool.idea%/lib/jdkAnnotations.jar")
}
pathvars {
variable("MAVEN_REPOSITORY", "%system.path.macro.MAVEN.REPOSITORY%")
}
jvmArgs = "-Xmx512m -XX:ReservedCodeCacheSize=240m"
targetJdkHome = "%env.JDK_18%"
}
}
})
object svn : SvnVcsRoot({
name = "http://UNIT-1413.Labs.IntelliJ.Net/svn/idea/"
url = "http://UNIT-1413.Labs.IntelliJ.Net/svn/idea/"
userName = "admin1"
password = "<PASSWORD>"
})
| cbfc75d8cdae71ddb7b6842c333cfc09a233c6d7 | [
"Kotlin"
] | 5 | Kotlin | innayan/dsl_idea | 0a5a4e01eaa0cf1da2c935dbabb6b08063f2bdcf | bec4846a648ed6aaa6b71461eefb4a03d3f67d51 |
refs/heads/master | <repo_name>EladVaknin/Algorithmic---problem-1-2<file_sep>/MinMax/MaxMax.java
package MinMax;
import java.util.ArrayList;
import java.util.Stack;
public class MaxMax {
/**
* Find the minimum and the maximum elements in array
* Complexity: O(n) - 3/2(n-1) comparisons
* @return number of comparisons
*/
public static int maxMaxM1(int[] arr) {
if(arr.length == 1) {
System.out.println("Max1 = " + arr[0] + " , Max2 = " + arr[0] + " , Comparisons = " + 0);
return 0;
}
int comparisons = 0;
int max1 = arr[0];
int max2 = arr[1];
comparisons++;
if(arr[0] < arr[1]) {
max1 = arr[1];
max2 = arr[0];
}
for (int i = 2; i < arr.length-1; i+=2) {
comparisons++;
if(arr[i] > arr[i+1]) {
comparisons+=2;
if(arr[i] > max1) {
if(arr[i+1] > max1) {
max1 = arr[i];
max2 = arr[i+1];
}
else {
max2 = max1;
max1 = arr[i];
}
}
else if(arr[i] > max2) {
max2= arr[i];
}
}
else {
comparisons+=2;
if(arr[i+1] > max1) {
if(arr[i] > max1) {
max1 = arr[i+1];
max2 = arr[i];
}
else {
max2 = max1;
max1 = arr[i+1];
}
}
else if(arr[i+1] > max2) {
max2= arr[i+1];
}
}
}
comparisons++;
if(arr[arr.length-1] > max1) {
max2 = max1;
max1 = arr[arr.length-1];
}
else {
comparisons++;
if(arr[arr.length-1] > max2){
max2 = arr[arr.length-1];
}
}
System.out.println("Max1 = " + max1 + " , Max2 = " + max2 + " , Comparisons = " + comparisons);
return comparisons;
}
/**
* Find the 2 maximum elements in array - Recursive
* Complexity: O(n) - (n + log n) comparisons
* @return number of comparisons
*/
public static int maxMaxM2Recursive(int[] arr) {
int[] comparisons = new int[1];
comparisons[0] = 0;
Node[] nodes = new Node[arr.length];
for (int i = 0; i < arr.length; i++) {
nodes[i] = new Node(arr[i]);
}
Node max1 = maxMaxM2Recursive(nodes,0,nodes.length-1,comparisons);
int max2 = max1.getStack().pop();
while(!max1.getStack().isEmpty()) {
int x = max1.getStack().pop();
comparisons[0]++;
if(max2 < x) max2 = x;
}
System.out.println("Max1 = " + max1.getData() + " , Max2 = " + max2 + " , Comparisons = " + comparisons[0]);
return comparisons[0];
}
private static Node maxMaxM2Recursive(Node[] nodes, int low, int high,int[] comparisons) {
if(high == low) return nodes[low];
int mid = (low + high)/2;
Node maxL = maxMaxM2Recursive(nodes,low,mid,comparisons);
Node maxR = maxMaxM2Recursive(nodes,mid+1,high,comparisons);
comparisons[0]++;
if(maxL.getData() > maxR.getData()) {
maxL.getStack().push(maxR.getData());
return maxL;
}
else {
maxR.getStack().push(maxL.getData());
return maxR;
}
}
/**
* Find the 2 maximum elements in array - Inductive
* Complexity: O(n) - (n + log n) comparisons
* @return number of comparisons
*/
public static int maxMaxM2Induction(int[] arr) {
int comparisons = 0;
ArrayList<Node> list = new ArrayList<Node>();
for (int i = 0; i < arr.length; i++) {
list.add(new Node(arr[i]));
}
int i = 0;
while(list.size() > 1) {
Node x = list.get(i);
Node y = list.get(i+1);
comparisons++;
if(x.getData() > y.getData()) {
x.getStack().add(y.getData());
list.remove(i+1);
}
else {
y.getStack().add(x.getData());
list.remove(i);
}
i++;
if(i == list.size() || i == list.size()-1) i = 0;
}
int max1 = list.get(0).getData();
Stack<Integer> st = list.get(0).getStack();
int max2 = st.pop();
while(!st.isEmpty()) {
int x = st.pop();
comparisons++;
if(x > max2) {
max2 = x;
}
}
System.out.println("Max1 = " + max1 + " , Max2 = " + max2 + " , Comparisons = " + comparisons);
return comparisons;
}
/**
* @param method
* @param checks
* @param max_size
* Prints the average number of comparisons of given method
*/
public static void getAverageofMethod(int method,int checks,int max_size) {
int[] arr;
double sum = 0;
for (int i = 0; i < checks; i++) {
arr = new int[(int)(Math.random()*max_size+10)];
for (int j = 0; j < arr.length; j++) {
arr[j] = (int)(Math.random()*max_size*10+1);
}
if(method == 1) sum += (double)maxMaxM1(arr)/arr.length;
if(method == 2) sum += (double)maxMaxM2Recursive(arr)/arr.length;
if(method == 3) sum += (double)maxMaxM2Induction(arr)/arr.length;
}
System.out.println("avarage: " + sum/checks);
}
/**
* @param method
* @param checks
* @param max_size
* Prints the average time of given method
*/
public static void getAvarageTimeofMethod(int method,int checks,int max_size) {
int[] arr;
long sum = 0;
for (int i = 0; i < checks; i++) {
arr = new int[max_size];
for (int j = 0; j < arr.length; j++) {
arr[j] = (int)(Math.random()*max_size*10+1);
}
long start = System.currentTimeMillis();
if(method == 1) maxMaxM1(arr);
if(method == 2) maxMaxM2Recursive(arr);
if(method == 3) maxMaxM2Induction(arr);
long end = System.currentTimeMillis();
sum += (end - start);
}
System.out.println("avarage: " + (double)sum/checks + " ms");
}
}
<file_sep>/TestQuestions/Polindrom.java
package TestQuestions;
//import java.util.*;
//// A Java solution for longest palindrome
public class Polindrom {
//
// // Function to print a subString str[low..high]
// static void printSubStr(String str, int low, int high)
// {
// for (int i = low; i <= high; ++i)
// System.out.print(str.charAt(i));
// }
//
// // This function prints the
//// longest palindrome subString
//// It also returns the length
//// of the longest palindrome
// static int longestPalSubstr(String str)
// {
// // get length of input String
// int n = str.length();
//
// // All subStrings of length 1
// // are palindromes
// int maxLength = 1, start = 0;
//
// // Nested loop to mark start and end index
// for (int i = 0; i < str.length(); i++) {
// for (int j = i; j < str.length(); j++) {
// int flag = 1;
//
// // Check palindrome
// for (int k = 0; k < (j - i + 1) / 2; k++)
// if (str.charAt(i + k) != str.charAt(j - k))
// flag = 0;
//
// // Palindrome
// if (flag!=0 && (j - i + 1) > maxLength) {
// start = i;
// maxLength = j - i + 1;
// }
// }
// }
//
// System.out.print("Longest palindrome subString is: ");
// printSubStr(str, start, start + maxLength - 1);
//
// // return length of LPS
// return maxLength;
// }
//
// // Driver Code
// public static void main(String[] args)
// {
// String str = "alfalfa";
// System.out.print("\nLength is: "
// + longestPalSubstr(str));
// }
// }
// test question - polindrom - read a string from the end to the start and this is a same original string
public static String lps(String s) {
if (s.length() == 0) {
return "nothing to see";
}
String s2 = transpos(s);
return lcs(s, s2);
}
private static String transpos(String s) {
int n = s.length();
String s2 = "";
for (int i = n - 1; i >= 0; i--) {
s2 += s.charAt(i);
}
return s2;
}
public static String lcs(String s1, String s2) {
int n = s1.length();
int m = s2.length();
int[][] mat = new int[n + 1][m + 1];
for (int i = 1; i < n + 1; i++) {
for (int j = 1; j < m + 1; j++) {
if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
mat[i][j] = 1 + mat[i - 1][j - 1];
} else {
mat[i][j] = Math.max(mat[i - 1][j], mat[i][j - 1]);
}
}
}
String ans = "";
int i = n;
int j = m;
while (mat[i][j] != 0) {
if (mat[i - 1][j] == mat[i][j - 1]) {
ans = s1.charAt(i - 1) + ans;
i--;
j--;
} else if (mat[i - 1][j] >= mat[i][j - 1]) {
i--;
} else {
j--;
}
}
return ans;
}
}<file_sep>/ParkingProblem/ParkingProblem.java
package ParkingProblem;
public class ParkingProblem {
public static final int x = 0, v = 1;
/**
* parking problem with array (cycle array)
* Complexity: O(n)
*/
public static int parkingProblem(int[] arr) {
int count = 0;
int start = (int)(Math.random()*arr.length);
arr[start] = v;
boolean finnish = false;
while(!finnish){
count++;
if(arr[(start+count)%arr.length] == v) {
arr[(start+count)%arr.length] = x;
if(arr[start%arr.length] == x) finnish = true;
}
}
return count;
}
/**
* parking problem with double cycle linked list
* Complexity: O(n^2)
*/
public static int parkingProblem(DoubleCycleLinkedList list) {
if(list.getHead() == null) return 0;
int count = 0;
NodeDouble n = list.getHead();
n.setData(v);
n = n.getNext();
boolean finnish = false;
while(!finnish){
count = 1;
while(n.getData() != v) {
count++;
n = n.getNext();
}
n.setData(x);
int steps = count;
while(steps > 0) {
steps--;
n = n.getPrev();
}
if(n.getData() == x) finnish = true;
n = n.getNext();
}
return count;
}
/**
* parking problem with linear part and cycle part - double linked list
* Complexity: O(n^2)
*/
public static int parkingProblemWithLinearPart(DoubleLinkedList list) {
if(list == null || list.getHead() == null) return 0;
if(list.getHead().getNext() == null) return 1;
NodeDouble n = list.getHead(), m = list.getHead();
int steps = 0;
while(m == n) { // check weather there is a cycle and count the linear part
steps++;
for(int i = 0; i < steps; i++)
if(m!=null) m = m.getNext();
for(int i = steps; i > 0; i--)
if(m!=null) m = m.getPrev();
}
if(m == null) return steps;
while(m != n) n = n.getNext();
while(m != n) { // count the length of cycle
m = m.getNext();
steps++;
}
return steps;
}
/**
* parking problem with linear part and cycle part - not double list
* Complexity: O(n)
*/
public static int parkingProblemWithLinearPart(LinkedList list) {
if(list == null || list.getHead() == null) return 0;
if(list.getHead().getNext() == null) return 1;
Node n = list.getHead().getNext(), m = list.getHead().getNext().getNext();
while(m != null && m != n) { // check weather there is a cycle
m = m.getNext();
if(m != null) m = m.getNext();
n = n.getNext();
}
if(m == null) return sizeOfList(list);
int count = 0;
m = list.getHead();
while(m != n) { // count the length of linear part
m = m.getNext();
n = n.getNext();
count++;
}
m = m.getNext();
count++;
while(m != n) { // count the length of cycle
m = m.getNext();
count++;
}
return count;
}
private static int sizeOfList(LinkedList list) {
int count = 0;
Node n = list.getHead();
while(n != null) {
n = n.getNext();
count++;
}
return count;
}
}
<file_sep>/Airplan/MinPrice.java
package MiniPrice;
import java.awt.Point;
class Node {
int x, y, price, numOfPaths;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
}
public class MinPrice {
public static int minPriceSimple (Node[][] mat) { // to return the price.
int n = mat.length, m = mat[0].length; //
mat[0][0].price = 0; // start condions
for (int i = 1; i < n; i++) {
mat[i][0].price = mat[i - 1][0].price + mat[i - 1][0].y;
} // the function
for (int i = 1; i < m; i++) {
mat[0][i].price = mat[0][i - 1].price + mat[0][i - 1].x;
} // init the amodot
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
mat[i][j].price = Math.min(mat[i - 1][j].price + mat[i - 1][j].y, mat[i][j - 1].price + mat[i][j - 1].x);
}
}
return mat [n-1][m-1].price;
}
// if i want to retuen the path i will use this code and i will return the path
// return path(mat);
//}
//
// private static String path(Node[][] mat) {
// int i = mat.length-1, j = mat[0].length-1; // init
// String ans = "";
// while(i != 0 && j != 0) { // the condion to come back
// if(mat[i-1][j].price + mat[i-1][j].y < mat[i][j-1].price + mat[i][j-1].x) { // from where i comiong
// ans = "1" + ans;
// i--;
// }
// else {
// ans = "0" + ans;
// j--;
// }
// }
// while(i != 0) {
// ans = "1" + ans;
// i--;
// }
// while(j != 0) {
// ans = "0" + ans;
// j--;
// }
// return ans;
// }
// to return the way if p1 ,p2 on the ways or the return the way
public static String minPrice(Node[][] mat) { // to return the way
int n = mat.length, m = mat[0].length; //
mat[0][0].price = 0; // start condions
mat[0][0].numOfPaths = 1;
for (int i = 1; i < n; i++) {
mat[i][0].price = mat[i-1][0].price + mat[i-1][0].y; mat[i][0].numOfPaths = 1;} // the function
for (int i = 1; i < m; i++) {
mat[0][i].price = mat[0][i-1].price + mat[0][i-1].x; mat[0][i].numOfPaths = 1;} // init the amodot
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
int fromDown = mat[i-1][j].price + mat[i-1][j].y;
int fromLeft = mat[i][j-1].price + mat[i][j-1].x;
mat[i][j].price = Math.min(fromDown,fromLeft);
if(fromDown < fromLeft) {mat[i][j].numOfPaths = mat[i-1][j].numOfPaths;}
else if(fromDown > fromLeft) {mat[i][j].numOfPaths = mat[i][j-1].numOfPaths;}
else mat[i][j].numOfPaths = mat[i-1][j].numOfPaths + mat[i][j-1].numOfPaths;
}
}
return path(mat);
}
private static String path(Node[][] mat) {
int i = mat.length-1, j = mat[0].length-1; // init
String ans = "";
while(i != 0 && j != 0) { // the condion to come back
if(mat[i-1][j].price + mat[i-1][j].y < mat[i][j-1].price + mat[i][j-1].x) { // from where i comiong
ans = "1" + ans;
i--;
}
else {
ans = "0" + ans;
j--;
}
}
while(i != 0) {
ans = "1" + ans;
i--;
}
while(j != 0) {
ans = "0" + ans;
j--;
}
return ans;
}
// test q - if the points is on the short way.
public static int minPriceBetween(Node[][] mat, Point p1, Point p2) {
int n = p2.y - p1.y + 1, m = p2.x - p1.x + 1; //the lenght of the matrix is the difference between the lines.
mat[p1.y][p1.x].price = 0;
for (int i = p1.y + 1; i < p1.y + n; i++) {
mat[i][p1.x].price = mat[i-1][p1.x].price + mat[i-1][p1.x].y;}
for (int i = p1.x + 1; i < p1.x + m; i++) {
mat[p1.y][i].price = mat[p1.y][i-1].price + mat[p1.y][i-1].x;}
for (int i = p1.y + 1; i < p1.y + n; i++) {
for (int j = p1.x + 1; j < p1.x + m; j++) {
mat[i][j].price = Math.min(mat[i-1][j].price + mat[i-1][j].y, mat[i][j-1].price + mat[i][j-1].x);
}
}
return mat[p2.y][p2.x].price;
}
// the main fucnion
public static boolean isOnMinPath(Node[][] mat, Point p1, Point p2) {
if(p2.x <= p1.x && p2.y <= p1.y) { // that say p2 is the firs point
Point t = p1; //swap
p1 = p2;
p2 = t;
}
if(p1.x <= p2.x && p1.y <= p2.y) {
int allPrice = minPriceBetween(mat, new Point(0,0), new Point(mat.length-1,mat[0].length-1)); // thats the pach
int toP1 = minPriceBetween(mat, new Point(0,0), p1); // from (0,0) to p1
int p1toP2 = minPriceBetween(mat, p1, p2); // from p1 to p2
int p2to = minPriceBetween(mat, p2, new Point(mat.length-1,mat[0].length-1)); // from p2 to the end
if(allPrice == toP1 + p1toP2 + p2to) return true; // if the pach = to the way between (0,0) to p1 + p1 to p2 + p2 to the end
else return false;
}
else return false;
}
public static void main(String[] args) {
Node[][] mat = {
{new Node(1,5),new Node(4,1),new Node(0,6)},
{new Node(4,7),new Node(2,5),new Node(0,3)},
{new Node(1,0),new Node(2,0),new Node(0,0)}};
System.out.println(isOnMinPath(mat,new Point(1,1),new Point(1,2)));
}
}
<file_sep>/Donuts/DonutsProblem.java
package Donuts;
public class DonutsProblem {
private static final int time = 2;
/**
* returns the total time for the daunts
* Complexity: O(1)
*/
public static int getTime(int numOfDonuts,int capacity) {
if(capacity >= numOfDonuts) return time;
if((time*numOfDonuts)%capacity == 0) return (time*numOfDonuts)/capacity;
return (time*numOfDonuts)/capacity + 1;
}
}
<file_sep>/Pizza/cutPizza.java
package Pizza;
public class cutPizza {
public static int cutPizza(double x) {
if (x ==(int) x) return (int)x + 1;
else return (int)x + 2;
}
}
<file_sep>/LCS/LCS.java
package LCS;
public class LCS {
public static String lcs(String s1, String s2) {
// build matrix
int n = s1.length();
int m = s2.length();
int[][] f = new int[n+1][m+1]; // incloud 0 place in the string
//init the matrix
for (int i = 0; i < n+1; i++) {f[i][0] = 0;}
for (int j = 0; j < m+1; j++) {f[0][j] = 0;}
for (int i = 1; i < n+1; i++) {
for (int j = 1; j < m+1; j++) {
if(s1.charAt(i-1) == s2.charAt(j-1)) f[i][j] = 1 + f[i-1][j-1]; // if we have a mach
else f[i][j] = Math.max(f[i][j-1], f[i-1][j]);
}
}
// build String ans - and i start from the end
int i = n, j = m;
String ans = "";
// f[i][j] = the lenght of the string that i found
while(f[i][j] != 0) {
if(s1.charAt(i-1) == s2.charAt(j-1)) { // i have a mach
ans = s1.charAt(i-1) + ans;
i--; j--;
}
else {
if(f[i][j-1] > f[i-1][j]) j--;
else i--;
}
}
return ans;
}
/// coplexy - O (nm) to build the matrix and O(n+m) for the build the and.
// O(nm) - that the final coplexy
public static void main(String[] args)
{
System.out.println(lcs("abcde", "eafddbac"));
}
}
| 95066170efb7fae8113a42aa165e67c89ce45d47 | [
"Java"
] | 7 | Java | EladVaknin/Algorithmic---problem-1-2 | 462a75b1dfda29e7c376f10a0181c8287fb13627 | d18613b25c97962281b32232003cbd7c52ac2f1f |
refs/heads/master | <file_sep>package com.example.csc250_multiscreenandroid;
public class MySingleton
{
//static String name = ("MIKE");
//static int counter = 0;
static int fac = 0;
static int S_root = 0;
}
<file_sep>package com.example.csc250_multiscreenandroid;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import java.text.DecimalFormat;
import static java.lang.Math.sqrt;
public class Screen3 extends AppCompatActivity
{
private TextView S_RootTV;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen3);
int sqr = MySingleton.S_root;
double answer = sqrt(sqr);
// TextView nameTV = this.findViewById(R.id.nameTV);
this.S_RootTV = this.findViewById(R.id.S_RootTV);
DecimalFormat df = new DecimalFormat("###.##");
this.S_RootTV.setText(df.format(answer) + ".");
}
} | 3a74684ea164eca5f5a5fea3cc1c97838e5f599f | [
"Java"
] | 2 | Java | linusagwu/CSC250_MultiscreenAndroid | 9e7f8008b667e29367f4159b34690fc0ce5c30d2 | 957a26c6353a04de8e7e0239314707aa10531aa5 |
refs/heads/master | <file_sep>import { Injectable } from '@angular/core';
// import { auth } from 'firebase/app';
// import { AngularFireAuth } from "@angular/fire/auth";
@Injectable({
providedIn: 'root'
})
export class LocalsaveService {
usuario:any
constructor() {}
set_localStorage(correo:string){
this.usuario=correo;
return localStorage.setItem("nombre",this.usuario);
}
get_localStorage(){
return localStorage.getItem('nombre');
}
logoutUser(){
return localStorage.removeItem('nombre');
}
set_registro(nombre:string,correo:string,pass:any,repass:any){
localStorage.setItem("usuario",nombre);
localStorage.setItem("pass",pass);
localStorage.setItem("repass",repass);
return localStorage.setItem("nombre",correo);
}
}
<file_sep>import { RouterModule, Routes } from '@angular/router';
import {LoginComponent} from "./login/login.component";
import {RegistroComponent} from "./registro/registro.component";
import {PrincipalComponent} from "./principal/principal.component";
import {BuscarComponent} from "./buscar/buscar.component";
import {DetalleComponent} from "./detalle/detalle.component";
const APP_ROUTES: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'registro', component: RegistroComponent },
{ path: 'principal', component: PrincipalComponent },
{ path: 'buscar', component: BuscarComponent },
{ path: 'detalle/:id', component: DetalleComponent },
{ path: '**', pathMatch: 'full', redirectTo: 'login' }
];
export const APP_ROUTING = RouterModule.forRoot(APP_ROUTES, {useHash:true});
<file_sep>import { Component, OnInit } from '@angular/core';
import {LocalsaveService} from "../services/localsave.service";
@Component({
selector: 'app-registro',
templateUrl: './registro.component.html',
styleUrls: ['./registro.component.css']
})
export class RegistroComponent implements OnInit {
constructor(public local:LocalsaveService) {
}
registro(nombre:string,correo:string,pass:any,repass:any){
this.local.set_registro(nombre,correo,pass,repass);
}
ngOnInit() {
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import {PokemonService} from "../services/pokemon.service";
import {ActivatedRoute} from "@angular/router";
@Component({
selector: 'app-detalle',
templateUrl: './detalle.component.html',
styleUrls: ['./detalle.component.css']
})
export class DetalleComponent implements OnInit {
pokemon:any;
evolucion:any;
cadenaEvolutiva:any[]=[];
imgEv:any;
imagenEvol:any;
constructor(private route:ActivatedRoute,private pokeapi:PokemonService) {
this.route.params.subscribe(url => {
// trae elpokemon
this.pokeapi.obtenerListadoPokemon(url.id).subscribe((data:any)=> {
this.pokemon=data;
// obtiene la evolucion
this.pokeapi.obtenerEvolucionPokemon(url.id).subscribe((evol:any)=>{
this.evolucion=evol.evolution_chain.url;
// trae la cadena de evolucion
this.pokeapi.obtenerCadenaEvolucion(evol.evolution_chain.url).subscribe((cadena:any)=>{
this.cadenaEvolutiva=cadena.chain.evolves_to;
this.imgEv=this.cadenaEvolutiva[0].species.name;
// trae la imagen de la evolucion
this.pokeapi.obtenerListadoPokemon(this.imgEv).subscribe((dataimg:any)=>{
this.imagenEvol=dataimg;
});
});
});
});
});
}
ngOnInit() {
}
}
<file_sep>import { Component} from '@angular/core';
import {LocalsaveService} from "../services/localsave.service";
@Component({
selector: 'app-navegacion',
templateUrl: './navegacion.component.html',
styleUrls: ['./navegacion.component.css']
})
export class NavegacionComponent {
correo:string;
constructor(public local:LocalsaveService) {
this.correo= this.local.get_localStorage();
}
cerrarSesion(){
this.local.logoutUser();
}
}
<file_sep>import { Component } from '@angular/core';
import {PokemonService} from "../services/pokemon.service";
import {Router} from "@angular/router";
@Component({
selector: 'app-principal',
templateUrl: './principal.component.html',
styleUrls: ['./principal.component.css']
})
export class PrincipalComponent {
listapokemon:any[]=[];
monstruos:any[]=[];
constructor(private pokeapi:PokemonService, private router: Router) {
this.pokeapi.obtenerListado().subscribe((data:any) =>{
this.listapokemon=data;
for(let i=0;i<this.listapokemon.length;i++){
this.pokeapi.obtenerListadoPokemon(this.listapokemon[i].name).subscribe((data:any)=>{
this.monstruos[i]=data;
});
}
});
}
verPokemon(pokemon:any){
console.log(pokemon);
this.router.navigate(['/detalle',pokemon]);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import {PokemonService} from "../services/pokemon.service";
import {Router} from "@angular/router";
@Component({
selector: 'app-buscar',
templateUrl: './buscar.component.html',
styleUrls: ['./buscar.component.css']
})
export class BuscarComponent implements OnInit {
pokemon:any;
constructor(private pokeapi:PokemonService,private router:Router) { }
ngOnInit() {
}
buscar(termino:any){
console.log(termino);
this.pokeapi.obtenerListadoPokemon(termino).subscribe((data:any)=> {
this.pokemon=data;
console.log(this.pokemon);
});
}
verPokemon(pokemon:any){
console.log(pokemon);
this.router.navigate(['/detalle',pokemon]);
}
}
<file_sep>import { Injectable } from '@angular/core';
import {HttpClient} from "@angular/common/http";
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class PokemonService {
constructor(private http:HttpClient) {
console.log("servicio listo");
}
pokemones:any[]=[];
obtenerListado(){
return this.http.get('https://pokeapi.co/api/v2/pokemon/?limit=50&offset=0').pipe( map((data:any) =>{
return data['results'];
}));
}
obtenerListadoPokemon(pokemon:any){
return this.http.get(`https://pokeapi.co/api/v2/pokemon/${pokemon}`).pipe(map((data:any)=>{
return data;
}));
}
obtenerEvolucionPokemon(id:any){
return this.http.get(`https://pokeapi.co/api/v2/pokemon-species/${id}`).pipe(map((data:any)=>{
return data;
}));
}
obtenerCadenaEvolucion(data:any){
return this.http.get(data).pipe(map((cadena:any)=>{
return cadena;
}));
}
}
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
//rutas
import {APP_ROUTING} from "./app.routes";
//servicios
import {HttpClientModule} from "@angular/common/http";
import { AppComponent } from './app.component';
import { RegistroComponent } from './registro/registro.component';
import { PrincipalComponent } from './principal/principal.component';
import { DetalleComponent } from './detalle/detalle.component';
import { NavegacionComponent } from './navegacion/navegacion.component';
import { LoginComponent } from './login/login.component';
import { BuscarComponent } from './buscar/buscar.component';
@NgModule({
declarations: [
AppComponent,
RegistroComponent,
PrincipalComponent,
DetalleComponent,
NavegacionComponent,
LoginComponent,
BuscarComponent
],
imports: [
BrowserModule,
HttpClientModule,
APP_ROUTING
],
providers: [
],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import { Component } from '@angular/core';
import {LocalsaveService} from "../services/localsave.service";
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent {
constructor(public local:LocalsaveService) {
}
usuario(data:string){
this.local.set_localStorage(data);
}
}
| 82cd265bf5045c4cf5fbd6402ad824c9d80073bc | [
"TypeScript"
] | 10 | TypeScript | ediman3d/pokemon | 6fa3e78cc70698d6947c4a82a1f43ff51d1fc378 | 9ca790e609e6f81d847920e59c71f6a45caf56ef |
refs/heads/master | <file_sep>import {
createStore,
applyMiddleware,
compose
} from 'redux';
import { throttle } from 'lodash';
import thunk from 'redux-thunk';
import { routerMiddleware } from 'react-router-redux';
import { Router, Route, browserHistory } from 'react-router';
import rootReducer from './reducer';
declare var window: any;
declare var process: any;
export function loadState() {
try {
const serializedState = localStorage.getItem('state');
if (serializedState === null) {
return undefined;
}
return JSON.parse(serializedState);
} catch(err) { return undefined; }
}
export function saveState(state) {
try {
const serializedState = JSON.stringify(state);
localStorage.setItem('state', serializedState);
} catch (err) {
debugger;
}
}
const persistentState = loadState();
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore<any>(rootReducer, persistentState, composeEnhancers(applyMiddleware(thunk, routerMiddleware(browserHistory)) ));
store.subscribe(throttle( () => {
saveState( store.getState() );
}, 1000) );
export default store;<file_sep>export interface Newsletter {
newsletter_subscription_status: 'init' | 'pending' | 'success' | 'error';
email_address: string;
popup_dismissed: boolean;
}
export interface State {
newsletter: Newsletter;
}<file_sep>declare var require: {
<T>(path: string): T;
(paths: string[], callback: (...modules: any[]) => void): void;
ensure: (paths: string[], callback: (require: <T>(path: string) => T) => void) => void;
};
require('file?name=[name].[ext]!./index.html');
import boot from './core/boot';
boot();<file_sep>var webpack = require('webpack');
var CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
target: 'web',
entry: process.env.NODE_ENV === 'development' ? [
'webpack-dev-server/client?http://localhost:8080',
'webpack/hot/only-dev-server',
'./src/client/index.ts',
'./src/client/stylesheets/main.scss',
'./src/client/stylesheets/new-age.less'
] : ['./src/client/index.ts', './src/client/stylesheets/main.scss', './src/client/stylesheets/new-age.less'],
output: {
path: __dirname + '/build/public',
publicPath: process.env.NODE_ENV === 'development' ? 'http://localhost:8080/' : '',
filename: "lumi.js",
},
// Enable sourcemaps for debugging webpack's output.
devtool: process.env.NODE_ENV === 'development' ? "source-map" : null,
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: ["", ".webpack.js", ".web.js", ".ts", ".tsx", ".js", "svg", "ttf", "eot", "woff2"]
},
module: {
loaders: [
// All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'.
{
test: /\.tsx?$/,
loader: "react-hot!ts-loader"
},
{ test: /\.css$/, exclude: /\.useable\.css$/, loader: "style-loader!css-loader" },
{ test: /\.scss$/, loader: "style-loader!css-loader!sass-loader" },
//{ test: /\.(woff2?|ttf|eot|svg)$/, loader: 'url?limit=10000' },
{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=10000&minetype=application/font-woff" },
{ test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader" },
{ test: /\.less$/, loader: 'style-loader!css-loader!less-loader' }
],
preLoaders: process.env.NODE_ENV === 'development' ? [
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{
test: /\.js$/,
loader: "source-map-loader"
}
] : []
},
devServer: {
contentBase: 'build/public',
port: 8080,
hot: true,
historyApiFallback: {
index: 'index.html'
},
proxy: {
'/api/v0/*': {
target: process.env.PROXY_SERVER ? process.env.PROXY_SERVER : 'http://localhost:3000',
secure: false
}
}
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new CopyWebpackPlugin([
{ from: 'img', to: 'img' }
]),
new webpack.DefinePlugin({
'process.env':{
'NODE_ENV': JSON.stringify( process.env.NODE_ENV ),
'VERSION': JSON.stringify( process.env.VERSION )
}
}),
]
};<file_sep># Lumi.education SPA - Client & Server
This is the Single-Page-Application that runs on http://Lumi.education/<file_sep>import { State as Newsletter } from '../modules/newsletter/newsletter_types';
export interface State extends
Newsletter {}<file_sep>import * as _debug from 'debug';
import server from '../core/server';
import boot_api from '../api';
import * as cluster from 'cluster';
import * as os from 'os';
declare var process: any;
const debug = _debug('boot');
const express_debug = _debug('boot:express');
export default function () {
if (process.env.NODE_ENV == 'development') { boot(); }
else {
const numCPUs = os.cpus().length;
if (cluster.isMaster) {
console.log('Master ' + process.pid + ' is running');
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (deadWorker, code, signal) => {
console.log(`worker ${deadWorker.process.pid} died`);
const worker = cluster.fork();
console.log(`new worker ${worker.process.pid} born.`);
});
} else {
boot();
console.log(`Worker ${process.pid} started`);
}
}
}
function boot() {
debug('starting boot-sequence');
boot_api(server);
const http_server = server.listen(process.env.PORT || 80, function () {
express_debug('express-server successfully booted: ' + process.env.PORT || 80);
});
debug('finished boot-sequence');
}
<file_sep>import * as express from 'express';
import * as bodyParser from 'body-parser';
import * as cookieParser from 'cookie-parser';
const server: express.Application = express();
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({
extended: true
}));
server.use(cookieParser());
export default server;<file_sep>export const NEWSLETTER_SUBSCRIBE_REQUEST = 'NEWSLETTER_SUBSCRIBE_REQUEST';
export const NEWSLETTER_SUBSCRIBE_SUCCESS = 'NEWSLETTER_SUBSCRIBE_SUCCESS';
export const NEWSLETTER_SUBSCRIBE_ERROR = 'NEWSLETTER_SUBSCRIBE_ERROR';
export const NEWSLETTER_SET_EMAIL = 'NEWSLETTER_SET_EMAIL';
export const NEWSLETTER_RESET = 'NEWSLETTER_RESET';
export const NEWSLETTER_POPUP_DISMISS = 'NEWSLETTER_POPUP_DISMISS';<file_sep>import* as debug from 'debug';
var log = debug('boot');
log('loading boot-files');
import boot from './core/boot';
boot();<file_sep>import {
assign
} from 'lodash';
import {
Newsletter
} from './newsletter_types';
import {
NEWSLETTER_SUBSCRIBE_REQUEST,
NEWSLETTER_SUBSCRIBE_ERROR,
NEWSLETTER_SUBSCRIBE_SUCCESS,
NEWSLETTER_SET_EMAIL,
NEWSLETTER_RESET,
NEWSLETTER_POPUP_DISMISS
} from './newsletter_constants';
const initialState: Newsletter = {
email_address: '',
newsletter_subscription_status: 'init',
popup_dismissed: false
};
export default function (state: Newsletter = initialState, action): Newsletter {
switch (action.type) {
case NEWSLETTER_RESET:
return assign({}, state, {
email_address: '',
newsletter_subscription_status: 'init'
});
case NEWSLETTER_SET_EMAIL:
return assign({}, state, { email_address: action.payload.email_address });
case NEWSLETTER_SUBSCRIBE_REQUEST:
return assign({}, state, {
newsletter_subscription_status: 'pending'
});
case NEWSLETTER_SUBSCRIBE_SUCCESS:
return assign({}, state, {
newsletter_subscription_status: 'success',
popup_dismissed: true
});
case NEWSLETTER_SUBSCRIBE_ERROR:
return assign({}, state, {
newsletter_subscription_status: 'error'
});
case NEWSLETTER_POPUP_DISMISS:
return assign({}, state, { popup_dismissed: true });
default:
return state;
}
}<file_sep>import * as express from 'express';
import boot_v0 from './v0';
import * as path from 'path';
export default function boot(server: express.Application) {
server.use(express.static(__dirname + '/../public'));
boot_v0(server);
server.get('*', function(req, res){
res.sendfile(path.resolve('build/public/index.html') );
});
}<file_sep>import * as request from 'superagent';
export function newsletter_subscribe(email_address: string, merge_fields: Object) {
return request('post', '/api/v0/newsletter')
.send({
email_address,
merge_fields
});
}
<file_sep>import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';
import newsletter from '../modules/newsletter/newsletter_reducer';
const rootReducer = combineReducers({
routing: routerReducer,
newsletter
});
export default rootReducer;<file_sep>import * as express from 'express';
import * as request from 'superagent';
import { assign } from 'lodash';
import * as _debug from 'debug';
const debug = _debug('api:newsletter');
export default function boot(server: express.Application) {
server.post('/api/v0/newsletter', (req: express.Request, res: express.Response, next: express.NextFunction) => {
debug('email subscription requested', req.body);
request
.post( process.env.NEWSLETTER_API )
.auth('anykey', process.env.NEWSLETTER_API_KEY )
.send({
'email_address': req.body.email_address,
'merge_fields': req.body.merge_fields,
'status':'pending'
})
.end((err, response) => {
if (err) {
debug('email error', req.body.email_address);
res.status(400).end();
}
else {
debug('email subscribed', req.body.email_address);
res.status(200).end();
}
} );
});
}<file_sep>import {
NEWSLETTER_SUBSCRIBE_REQUEST,
NEWSLETTER_SUBSCRIBE_SUCCESS,
NEWSLETTER_SUBSCRIBE_ERROR,
NEWSLETTER_SET_EMAIL,
NEWSLETTER_RESET,
NEWSLETTER_POPUP_DISMISS
} from './newsletter_constants';
import * as API from './newsletter_api';
export function newsletter_subscribe(email_address: string, merge_fields: Object) {
return dispatch => {
dispatch({
type: NEWSLETTER_SUBSCRIBE_REQUEST,
payload: { email_address, merge_fields }
});
API.newsletter_subscribe(email_address, merge_fields)
.then(res => {
switch (res.status) {
case 200:
dispatch({
type: NEWSLETTER_SUBSCRIBE_SUCCESS,
payload: { email_address, merge_fields }
});
break;
default:
case 400:
dispatch({
type: NEWSLETTER_SUBSCRIBE_ERROR,
payload: {
error: 400,
email_address,
merge_fields
}
})
break;
}
})
.catch(err => {
dispatch({
type: NEWSLETTER_SUBSCRIBE_ERROR,
payload: {
error: 400,
email_address,
merge_fields
}
})
})
}
}
export function newsletter_set_email(email_address: string) {
return {
type: NEWSLETTER_SET_EMAIL,
payload: { email_address }
};
}
export function newsletter_reset() {
return {
type: NEWSLETTER_RESET
};
}
export function newsletter_popup_dismiss() {
return {
type: NEWSLETTER_POPUP_DISMISS
};
}<file_sep>import * as express from 'express';
import boot_newsletter from './newsletter';
export default function boot(server: express.Application) {
boot_newsletter(server);
} | 44ee54ca612356b16bcf2341ed070375d16ffbe1 | [
"JavaScript",
"TypeScript",
"Markdown"
] | 17 | TypeScript | JPSchellenberg/Lumi.education | 00e8a14ed789476c4920736bed66bbd0cd6c7025 | 468d09f90beacee0f2cd9c730515ad28d4d77f51 |
refs/heads/master | <file_sep>const functions = require('firebase-functions');
const admin = require("firebase-admin");
//const core = require("firebase/app");
const express = require('express');
const cors = require('cors');
const tripApp = express();
const userApp = express();
// Automatically allow cross-origin requests
tripApp.use(cors({ origin: true }));
userApp.use(cors({ origin: true }));
// Admin initialization
admin.initializeApp(functions.config().firebase);
// Link DB
var db = admin.firestore();
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
const genId = async () =>{
let date = new Date();
let ts = date.getTime();
ts = ts.toString();
return ts;
}
tripApp.get('/', (req,res)=>{
let tripRef = db.collection('trip');
let query = tripRef.get()
.then(snapshot=>{
if(snapshot.empty){
console.log("No matching docs");
return res.status(404).json({
message: 'Not Found',
data: []
});
}
let retSet = [];
snapshot.forEach(doc=>{
let t = doc.data();
t.id = doc.id;
retSet.push(t);
})
return res.status(200).json({
message: "Trip collection retrieved",
data: retSet,
})
}).catch(err=>{console.log(err)});
})
tripApp.post('/', (req, res) =>{
let tripObj = JSON.parse(req.body.data)
let newTrip = {
startDate: tripObj.startDate || "",
duration: tripObj.duration || "",
owner: tripObj.owner || "",
shared: tripObj.shared || [],
routes: tripObj.routes || [],
city: tripObj.city || null,
description: tripObj.description || "",
name: tripObj.name || "",
};
genId().then(ts => {
newTrip.id = ts;
db.collection('trip').doc(ts).set(newTrip);
let userRef = db.collection('user').doc(newTrip.owner);
console.log(newTrip.owner)
userRef.get().then(function(doc) {
console.log("doc is ", doc.exists)
if(doc.exists){
console.log("user exist!")
userRef.update( {trip: [...doc.data().trip, ts] })
}
return null;
}).catch(err=>console.log(err));
// console.log(req.body.shared);
// console.log(typeof req.body.shared);
// let sr = [];
// if(req.body.shared && (typeof req.body.shared) !=='String') sr = req.body.shared;
// else if(req.body.shared) sr = JSON.parse(req.body.shared);
// // let sr = req.body.shared ? JSON.parse(req.body.shared): [];
// sr = sr.map(String);
// let newTrip = {
// startdate: req.body.startdate || "",
// duration: req.body.duration || "",
// owner: req.body.owner || "",
// shared: sr,
// routes: req.body.routes || [],
// location: req.body.location || "",
// description: req.body.description || "",
// name: req.body.name || "",
// city: req.body.city || "",
// };
// genId().then(ts =>{
// db.collection('trip').doc(ts).set(newTrip);
// return ts;
// }).then((ts1)=>{
// if(newTrip.shared && newTrip.shared.length > 0){
// let ns = newTrip.shared;
// ns.push(newTrip.owner);
// ns.forEach((t)=>{
// let refUser = db.collection('user').doc(t.toString());
// refUser.get().then(doc=>{
// let tripnew = doc.data().trip;
// if(tripnew.indexOf(ts1) === -1){
// tripnew.push(ts1);
// }
// refUser.update({
// trip: tripnew,
// });
// return null;
// }).catch(err=>console.log(err));
// });
// }
// return ts1;
// }).then((ts2)=>{
// console.log("trip added with id ", ts2);
return res.status(201).json({
message: 'trip added',
data: newTrip,
id: ts,
});
}).catch(err=>{
console.log(err);
})
})
tripApp.get('/:id', (req,res)=>{
let retTrip = db.collection('trip').doc(req.params.id);
let getDoc = retTrip.get()
.then(doc=>{
if (!doc.exists){
return res.status(404).json({
message: 'Trip not found',
data: [],
})
} else {
return res.status(200).json({
message: 'Trip retrieved',
data: doc.data(),
});
}
})
})
tripApp.put('/:id', (req,res)=>{
let refTrip = db.collection('trip').doc(req.params.id);
let tripId = req.params.id;
let getDoc = refTrip.get()
.then(doc=>{
if (!doc.exists){
return res.status(404).json({
message: 'Trip not found',
data: [],
})
} else {
let updatedTrip = JSON.parse(req.body.data)
let updateTrip = refTrip.update(updatedTrip);
return res.status(200).json({
message: 'Trip updated',
data: updateTrip,
})
}
})
});
tripApp.delete('/:id', (req,res)=>{
let refTrip = db.collection('trip').doc(req.params.id);
let tripId = req.params.id;
refTrip.get().then(doc=>{
if(!doc.exists){
return res.status(404).json({
message: 'Trip not found',
data: [],
});
}
let userToDel = doc.data().shared;
let ownerToDel = doc.data().owner;
userToDel.push(ownerToDel);
console.log(userToDel);
return userToDel;
})
.then(userToDel =>{
console.log("UsertoDel: ", userToDel);
userToDel.forEach(u=>{
let refUser = db.collection('user').doc(u.toString());
refUser.get().then(doc1=>{
console.log("Doc1: ", doc1.data());
if(!doc1.exists) return null;
let trips = doc1.data().trip;
console.log("oldtrips: ", typeof trips);
console.log('tripid: ', typeof tripId);
let idx = trips.indexOf(tripId);
if(idx!==-1) trips.splice(idx, 1);
idx = trips.indexOf(Number(tripId));
if(idx!==-1) trips.splice(idx, 1);
console.log("newtrips: ", trips);
console.log('newuser: ',refUser);
refUser.update({
trip: trips,
});
return null;
}).catch(err=>console.log(err));
});
return null;
}).then(()=>{
refTrip.delete();
console.log("Trip Deleted ", tripId);
return res.status(200).json({
message: 'Trip deleted',
data: []
});
}).catch(err=>console.log(err));
})
tripApp.get('/shared/:id', (req, res) => {
let userId = req.params.id;
db.collection("trip")
.get()
.then(function(querySnapshot) {
let trips = []
querySnapshot.forEach(function(doc) {
trip = doc.data();
if(trip.shared.includes(userId)){
trips.push(trip)
}
});
return res.status(200).json({
message: "Successfully get shared",
data: trips
})
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});
})
//UserApp
userApp.post('/', (req, res) =>{
let nt = req.body.trip? JSON.parse(req.body.trip) : [];
nt = nt.map(String);
let newUser = {
email: req.body.email || "",
name: req.body.name || "",
trip: nt,
}
genId().then(ts =>{
db.collection('user').doc(newUser.email).set(newUser);
return newUser.email;
}).then((ts1)=>{
if(newUser.trip && newUser.trip.length > 0){
newUser.trip.forEach((t)=>{
let refTrip = db.collection('trip').doc(t.toString());
refTrip.get().then(doc=>{
let shared1 = doc.data().shared;
if(shared1.indexOf(ts1) === -1){
shared1.push(ts1);
}
refTrip.update({
shared: shared1,
});
return null;
}).catch(err=>console.log(err));
});
}
return ts1;
}).then((ts2)=>{
console.log("User added with id ", ts2);
return res.status(201).json({
message: 'User added',
data: newUser,
});
}).catch(err=>console.log(err));
})
userApp.get('/:id', (req, res)=>{
let refUser = db.collection('user').doc(req.params.id);
let getDoc = refUser.get()
.then(doc=>{
if (!doc.exists){
return res.status(404).json({
message: 'User not found',
data: [],
})
} else {
return res.status(200).json({
message: 'User retrieved',
data: doc.data(),
});
}
}).catch(err=>{
console.log(err);
return res.status(500).send({message: 'Server error', data: err});
});
});
userApp.get('/gettrip/:id', (req,res)=>{
let refUser = db.collection('user').doc(req.params.id);
let retData= [];
refUser.get().then(doc=>{
if (!doc.exists){
return res.status(404).json({
message: 'User not found',
data: [],
})
}
return doc.data().trip;
}).then((trips)=>{
let results = [];
trips.forEach(t=>{
let refTrip = db.collection('trip').doc(t.toString());
results.push(refTrip.get());
// refTrip.get().then(doc1=>{
// if(!doc1.exists) return null;
// retData.push(doc1.data());
// results.push(doc1.data());
// console.log(retData);
// return null;
// }).catch(err=>console.log(err));
})
return Promise.all(results);
}).then(results=>{
let reData = []
for(let r of results){
if(r.exists) {
console.log(r.data());
reData.push(r.data());
}
}
return reData;
}).then((reData)=>{
return res.status(200).json({
message: 'Get trips by user',
data: reData,
})
}).catch(err=>console.log(err));
})
userApp.put('/:id', (req,res)=>{
let refUser = db.collection('user').doc(req.params.id);
let userId = req.params.id;
let getDoc = refUser.get()
.then(doc=>{
if (!doc.exists){
return res.status(404).json({
message: 'User not found',
data: [],
})
} else {
let prevTrip = doc.data().trip;
let newTrip = req.body.trip? JSON.parse(req.body.trip):[];
newTrip = newTrip.map(String);
let newUserProfile = req.body;
if(newUserProfile.trip) newUserProfile.trip = JSON.parse(newUserProfile.trip);
newUserProfile.trip = newUserProfile.trip.map(String);
console.log(prevTrip);
console.log(newTrip);
let tripToDel = [];
let tripToAdd = [];
if(newTrip) {
tripToDel = prevTrip.filter(x => !newTrip.includes(x));
tripToAdd = newTrip.filter(x => !prevTrip.includes(x));
}
console.log(tripToDel);
console.log(tripToAdd);
refUser.update(newUserProfile).then(()=>{
tripToDel.forEach((t)=>{
let refTrip = db.collection('trip').doc(t.toString());
refTrip.get().then(doc1=>{
if(!doc1.exists) return null;
let shared = doc1.data().shared;
let idx = shared.indexOf(userId);
if(idx!==-1) shared.splice(idx, 1);
let owner = doc1.data().owner;
if(Number(owner) === Number(userId)) owner = 'undefined';
refTrip.update({
shared: shared,
owner: owner,
});
return null;
}).catch(err=>console.log(err));
});
return null;
})
.then(()=>{
tripToAdd.forEach((t)=>{
let refTrip = db.collection('trip').doc(t.toString());
refTrip.get().then(doc1=>{
if(!doc1.exists) return null;
let shared = doc1.data().shared;
let idx = shared.indexOf(userId);
if(idx===-1) shared.push(userId);
refTrip.update({
shared: shared,
});
return null;
}).catch(err=>console.log(err));
});
return null;
})
.then(()=>{
return res.status(400).json({
message: 'User Updated',
data: [],
})
})
.catch(err=>console.log(err));
return null;
}
}).catch(err=>console.log(err));
})
userApp.delete('/:id', (req,res)=>{
let refUser = db.collection('user').doc(req.params.id);
let userId = req.params.id;
refUser.get().then(doc=>{
if(!doc.exists){
return res.status(404).json({
message: 'User not found',
data: [],
});
}
let tripToDel = doc.data().trip;
console.log('TripToDel');
console.log(tripToDel);
console.log(typeof tripToDel);
return tripToDel;
})
.then((tripToDel)=>{
console.log(tripToDel);
tripToDel.forEach((t)=>{
let refTrip = db.collection('trip').doc(t.toString());
refTrip.get().then(doc1=>{
if(!doc1.exists) return null;
let shared = doc1.data().shared;
let idx = shared.indexOf(userId);
if(idx!==-1) shared.splice(idx, 1);
let owner = doc1.data().owner;
if(Number(owner) === Number(userId)) owner = 'undefined';
refTrip.update({
shared: shared,
owner: owner,
});
return null;
}).catch(err=>console.log(err));
});
return null;
}).then(()=>{
refUser.delete();
return res.status(200).json({
message: 'Deleted',
data: []
})
}).catch(err=>console.log(err));
})
userApp.get("/", (req, res) => {
db.collection("user")
.get()
.then(function(querySnapshot) {
let users = []
querySnapshot.forEach(function(doc) {
user = doc.data();
console.log(user.name)
users.push({
name: user.name,
email: user.email
})
});
return res.status(200).json({
message: "Successfully get",
data: users
})
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});
})
//Export functions
exports.trip = functions.https.onRequest(tripApp);
exports.user = functions.https.onRequest(userApp);
<file_sep>module.exports = {
apiKey: "AIzaSyA6GoLwhUzLcRguPqu8S2KLROMg67w4eT0",
authDomain: "cs498rk-239014.firebaseapp.com",
databaseURL: "https://cs498rk-239014.firebaseio.com",
projectId: "cs498rk-239014",
storageBucket: "cs498rk-239014.appspot.com",
messagingSenderId: "1053708047986"
}; | a8e18f669a8cd08c96db070c531e496e1b326d4f | [
"JavaScript"
] | 2 | JavaScript | zengfh/cs498rk-backend | 841c596408e94b068eccbab5014ffe601611a610 | fddfd747bcbd1fd5477c00e867a1c5292791f20f |
refs/heads/master | <repo_name>LielVaknin/OOP-Project-Pokemon-Game<file_sep>/src/Gui/loginPanel.java
package Gui;
import gameClient.Arena;
import gameClient.GamePlay;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* This class displays the login window of the game.
*
* @authors Liel.Vaknin & Renana.Levy.
*/
public class loginPanel extends JPanel implements ActionListener {
private JFrame loginFrame;
private JLabel ID, level;
private JTextField IDText, levelText;
private JButton loginButton;
private Arena arena;
private Image background;
private int w;
private int h;
/**
* Constructor.
*/
public loginPanel(){
loginFrame = new JFrame();
loginFrame.setTitle("Catch Them All");
ImageIcon image = new ImageIcon("./resources/Pokemon.png");
loginFrame.setIconImage(image.getImage());
loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
loginFrame.setExtendedState(Frame.MAXIMIZED_BOTH);
background = new ImageIcon("./resources/LoginBackground.jpg").getImage();
this.setLayout(null);
ID = new JLabel("ID");
this.add(ID);
IDText = new JTextField(10);
this.add(IDText);
level = new JLabel("level");
this.add(level);
levelText = new JTextField(10);
this.add(levelText);
loginButton = new JButton("Login");
this.add(loginButton);
loginFrame.add(this);
loginFrame.setVisible(true);
loginButton.addActionListener(this);
}
/**
* Displays on the window the TextFields of the Login.
* Overrides paintComponent method.
*
* @param g
*/
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
w = this.getWidth();
h = this.getHeight();
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(background, 0,0, w, h, null);
setID();
setLevel();
setLoginButton();
}
/**
* Displays on the window TextFields for userID.
*/
private void setID(){
ID.setBounds((w/2)-155, (h/2)-35, 90, 35);
ID.setForeground((new Color(255, 255, 255, 255)));
ID.setFont(new Font("Verdana", Font.ITALIC, 20));
IDText.setBounds((w/2)-100, (h/2)-35, 260, 34);
}
/**
* Displays on the window TextFields for choosing level.
*/
private void setLevel() {
level.setBounds((w/2)-170, (h/2)+20, 90, 35);
level.setForeground((new Color(255, 255, 255, 255)));
level.setFont(new Font("Verdana", Font.ITALIC, 20));
levelText.setBounds((w/2)-100, (h/2)+20, 260, 34);
}
/**
* Displays the Login button on the window.
*/
private void setLoginButton(){
loginButton.setBounds((w/2)-20, (h/2)+80, 100, 30);
loginButton.setForeground((new Color(0, 0, 0, 255)));
loginButton.setFont(new Font("Verdana", Font.ITALIC, 18));
}
/**
* Launches the game after pressing the Login button.
* Overrides actionPerformed method from actionListener.
*
* @param e
*/
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == loginButton){
int gameLevel = Integer.parseInt(levelText.getText());
arena = new Arena(gameLevel);
long user = Integer.parseInt(IDText.getText());
arena.gatGame().login(user);
loginFrame.dispose();
Frame frame = new Frame(arena);
GamePlay game = new GamePlay(arena, frame);
Thread gamePlay = new Thread(game);
gamePlay.start();
}
}
}
<file_sep>/README.md
# Catch Them All
## Decription
### Authors : <NAME> & <NAME>
This project consists of two parts.
The first one implements algorithms for developing a data structure type of a directed weighted graph.
The second one uses this graph we created in order to develop pokemons game.
---
## Api
In this package there are 5 classes which each class implements a given interface.
* NodeData class implements the node_data interface.
It represents the set of operations applicable on a node in a directed weighted graph.
This class implements the methods:
set & get methods, toString method and equals method.
* GeoLocation class implements the geo_location interface.
It represents a geo location <x,y,z>, aka Point3D.
This class implements the methods:
getters for x, y and z and a method which calculates the distance between 2 geo locations.
* EdgeData class implements the edge_data interface.
It represents the set of operations applicable on a directional edge in a directed weighted graph.
This class implements the methods:
set & get methods and equals method.
* DWGraph_DS class implements the directed_weighted_graph interface.
It represents a directed weighted graph.
This class implements the methods:
set & get methods, methods for adding / removing nodes and edges to / from the graph,
a method for connecting an edge with weight w between a given src node to a given dest node, toString method and equals method.
* DWGraph_Algo class implements the dw_graph_algorithms interface.
It represents a Directed Weighted Graph Theory algorithms.
The class includes a set of operations applicable on the graph g -
initialization of graph g with a given graph, a getGraph method, a deep copy method,
a method which uses the [DFS algorithm](https://en.wikipedia.org/wiki/Depth-first_search) for the implementation of method which checks
if the graph is strongly connected or not, finding the shortest path in the graph between a given source and destination and a method for finding its length - using [Dijkstra's algorithm](https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm),
a method which saves this graph to a given file name and a method which loads a graph to this graph algorithm (using JSON format and gson library).
## Tests
This ptoject includes 2 JUNIT tests :
- DWGraph_DSTest - for testing class DWGraph_DS algorithms.
- DWGraph_AlgoTest - for testing class DWGraph_Algo algorithms.
### An example of a directed weighted graph:

## Pokemons game
There are 2 packages and 9 classes in this part.
### GameClient package
This package contains all classes which implements the logic of the game:
* Arena class represents the arena of the game and manages the logic of the game in it.
* CL_Agent class represents an agent in the game.
* CL_Pokemon class represents a pokemon in the game.
* jsonToObject class receives data from the server (jar file) on which the game is performed and loads the information from it which based on strings represented as JSON.
* GamePlay class manages the processes of the game.
* Ex2 contains the "main" method which runs the whole project.
### Gui package
This package contains all classes which implements the Graphical User Interface (Gui) of the game.
* Frame class extends JFrame which displays the gamePanel.
* gamePanel class extends JPanel and displays the game arena window.
* loginPanel class extends JPanel implements ActionListener. Displays the login window of the game.
### How the game works?
We implemented a simple logic game in which there are agents and pokemons.
Each pokemon has different value and the role of the agents is to catch as many pokemons as
possible in order to increase their own value.
Our algorithm determines the start position of each agent before starting the game and also directs each one along the graph during the game.
The algorithm finds the nearest pokemon for each agent and moves the agent to there - according to [Dijkstra's algorithm](https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm).
The more Pokemons are caught, the higher score in the game!<br />
There are 0-23 levels and each one has a different amount of agents, pokemons and limited time.
When Pokemon caught, a new one appears in the game arena.
## Installation
For installing the game please follow the instructions below:
* Clone this repository.
* To start playing the game run Ex2.
* Insert your ID & Chooce level.
* Press Login and let's "catch them all!"
### An example of running level 11 of the game :
*Inserting ID and level here :*

*After pressing Login the game starts :*

### *Have fun!*
*For more information go to the project's [wiki pages](https://github.com/LielVaknin/ex2/wiki)*
<file_sep>/src/gameClient/Ex2.java
package gameClient;
import Gui.Frame;
import Gui.loginPanel;
/**
* This class contains the "main" method which runs the whole project.
*
* @authors Liel.Vaknin & Renana.Levy.
*/
public class Ex2 {
public static void main(String[] args){
if(args.length == 0){
loginPanel p = new loginPanel();
}
else {
Arena catchThemAll = new Arena(Integer.parseInt(args[1]));
Frame f = new Frame(catchThemAll);
catchThemAll.gatGame().login(Integer.parseInt(args[0]));
GamePlay game = new GamePlay(catchThemAll, f);
Thread gamePlay = new Thread(game);
gamePlay.start();
}
}
}
<file_sep>/tests/api/DWGraph_AlgoTest.java
package api;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
* Test for DWGraph_Algo class.
*/
class DWGraph_AlgoTest {
directed_weighted_graph g_Test = new DWGraph_DS();
dw_graph_algorithms ga_Test = new DWGraph_Algo();
node_data n0 = new NodeData();
node_data n1 = new NodeData();
node_data n2 = new NodeData();
node_data n3 = new NodeData();
node_data n4 = new NodeData();
/**
* Builts a graph with 5 nodes and 9 edges.
*/
@BeforeEach
public void buildingGraph(){
g_Test.addNode(n0);
g_Test.addNode(n1);
g_Test.addNode(n2);
g_Test.addNode(n3);
g_Test.addNode(n4);
g_Test.connect(0, 1, 6);
g_Test.connect(0, 2, 9);
g_Test.connect(1, 2, 2);
g_Test.connect(1, 3, 7);
g_Test.connect(1, 4, 5);
g_Test.connect(2, 0, 3);
g_Test.connect(2, 3, 1);
g_Test.connect(3, 4, 1);
g_Test.connect(4, 1, 3);
ga_Test.init(g_Test);
assertEquals(5, g_Test.nodeSize());
assertEquals(9, g_Test.edgeSize());
assertEquals(14, g_Test.getMC());
}
/**
* Test for copy method.
*/
@Test
void copy() {
directed_weighted_graph ga_copy = ga_Test.copy();
// System.out.println(g_Test.toString());
// System.out.println(ga_copy.toString());
assertEquals(g_Test, ga_copy);
assertEquals(14, g_Test.getMC());
g_Test.removeNode(1);
// System.out.println(g_Test.toString());
// System.out.println(ga_copy.toString());
assertNotEquals(g_Test, ga_copy);
assertNotEquals(g_Test.getMC(), ga_copy.getMC());
directed_weighted_graph ga_copy2 = ga_Test.copy();
assertEquals(g_Test, ga_copy2);
assertEquals(8, ga_copy2.getMC());
}
/**
* Test for isConnected method.
*/
@Test
void isConnected() {
assertTrue(ga_Test.isConnected()); //The graph is connected.
g_Test.removeEdge(2, 0);
System.out.println(g_Test);
assertFalse(ga_Test.isConnected()); //The graph isn't connected.
node_data n2 = new NodeData(2);
g_Test.addNode(n2);
g_Test.connect(2, 0, 3);
g_Test.removeEdge(4 ,1);
g_Test.removeEdge(0 ,1);
assertFalse(ga_Test.isConnected()); //The graph isn't connected.
ga_Test.init(null);
assertTrue(ga_Test.isConnected()); //The graph is null.
g_Test= new DWGraph_DS();
ga_Test.init(g_Test);
assertTrue(ga_Test.isConnected()); //The graph is empty.
node_data n0 = new NodeData(0);
g_Test.addNode(n0);
assertTrue(ga_Test.isConnected()); //A graph with 1 node.
node_data n1 = new NodeData(1);
g_Test.addNode(n1);
assertFalse(ga_Test.isConnected()); //A graph with 2 nodes that not connected.
g_Test.connect(1, 0, 5.62);
assertFalse(ga_Test.isConnected()); //A graph with 2 nodes that connected at one direction.
g_Test.connect(0, 1, 5.62);
assertTrue(ga_Test.isConnected()); //A graph with 2 nodes that connected.
}
/**
* Test for shortestPathDist and shortestPath methods.
*/
@Test
void shortestPath() {
assertEquals(5, ga_Test.shortestPathDist(1, 0)); //Path between 2 node that in the graph and connected.
assertEquals(3, ga_Test.shortestPath(1, 0).size());
assertEquals(10, ga_Test.shortestPathDist(0, 4)); //Path between 2 node that in the graph and connected.
assertEquals(5, ga_Test.shortestPath(0, 4).size());
assertEquals(3, ga_Test.shortestPathDist(1, 3)); //Path between 2 node that in the graph and connected.
assertEquals(3, ga_Test.shortestPath(1, 3).size());
assertNotNull(g_Test.removeEdge(2, 0));
assertEquals(-1, ga_Test.shortestPathDist(3, 0)); //Path between 2 node that in the graph and not connected.
assertNull(ga_Test.shortestPath(3, 0));
assertEquals(-1, ga_Test.shortestPathDist(4, 7)); //Path between node in the graph to node that not in the graph.
assertNull(ga_Test.shortestPath(4, 7));
assertEquals(-1, ga_Test.shortestPathDist(8, 1)); //Path between node that not in the graph to node in the graph.
assertNull(ga_Test.shortestPath(8, 1));
assertEquals(-1, ga_Test.shortestPathDist(13, 11)); //Path between 2 node that not in the graph.
assertNull(ga_Test.shortestPath(13, 11));
assertEquals(0, ga_Test.shortestPathDist(3, 3)); //Path between node in the graph to himself.
assertEquals(1, ga_Test.shortestPath(3, 3).size());
assertEquals(-1, ga_Test.shortestPathDist(10, 10)); //Path between node that not in the graph to himself.
assertNull(ga_Test.shortestPath(10, 10));
}
/**
* Test for save and load methods.
*/
@Test
void file() {
assertTrue(ga_Test.save("test1.txt")); //Save graph to file.
assertTrue(ga_Test.load("test1.txt")); //Loading graph from a file found.
assertFalse(ga_Test.load("test2.txt")); //Loading graph from a file that not found.
assertFalse(ga_Test.load("")); //Loading graph from nothing file.
assertFalse(ga_Test.save("")); //Save graph to nothing file.
}
}<file_sep>/src/Gui/gamePanel.java
package Gui;
import api.*;
import gameClient.*;
import gameClient.util.*;
import javax.swing.*;
import java.awt.*;
import java.util.Iterator;
import java.util.List;
/**
* This class uses for drawing the window of the game on the frame.
*
* @authors Liel.Vaknin & Renana.Levy.
*/
public class gamePanel extends JPanel {
private static final int WP = 100;
private JLabel level;
private JLabel time;
private JLabel score;
private JLabel moves;
private int w;
private int h;
private Image background;
private Arena arena;
private gameClient.util.Range2Range _w2f;
/**
* Constructor
*
* @param arena represents the game arena.
*/
public gamePanel(Arena arena) {
super();
this.setLayout(null);
background = new ImageIcon("./resources/GameBackground.png").getImage();
level = new JLabel("level: "+arena.getLevel());
this.add(level);
time = new JLabel("time: "+(arena.gatGame().timeToEnd()/1000));
this.add(time);
int grade = jsonToObject.score(arena.gatGame().toString());
score = new JLabel("score: "+grade);
this.add(score);
int moving = jsonToObject.moves(arena.gatGame().toString());
moves = new JLabel("moves: "+moving);
this.add(moves);
this.arena = arena;
}
/**
* Updates the window which displays game arena.
*
* @param score represents the score on the game.
*/
protected void update(int score){
// int grade = jsonToObject.score(arena.gatGame().toString());
this.score.setText("score: "+score);
this.repaint();
}
/**
* Updates the frame relative to the screen size.
*/
private void updateFrame() {
Range rx = new Range(30,w-30);
Range ry = new Range(h-30,60);
Range2D frame = new Range2D(rx,ry);
directed_weighted_graph g = arena.getGraphAlgo().getGraph();
_w2f = Arena.w2f(g,frame);
}
/**
* Draws on the window.
* Overrides paintComponent method.
*
* @param g
*/
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
w = this.getWidth();
h = this.getHeight();
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(background, 0,0, w, h, null);
updateFrame();
g.setColor(Color.BLACK);
drawGraph(g);
drawPokemons(g);
drawAgents(g);
Info();
}
/**
* Draws the graph on the window.
*
* @param g
*/
private void drawGraph(Graphics g) {
directed_weighted_graph graph = arena.getGraphAlgo().getGraph();
Iterator<node_data> it1 = graph.getV().iterator();
while(it1.hasNext()) {
node_data n = it1.next();
drawNode(n,5,g);
Iterator<edge_data> it2 = graph.getE(n.getKey()).iterator();
while(it2.hasNext()) {
edge_data e = it2.next();
drawEdge(e, g);
}
}
}
/**
* Draws a node on the window.
*
* @param n represents the given node needed to be drawn on the window.
* @param r represents a given range between the geo location of a given node and the location of the node in the drawing.
* @param g
*/
private void drawNode(node_data n, int r, Graphics g) {
geo_location pos = n.getLocation();
geo_location fp = this._w2f.world2frame(pos);
g.fillOval((int)fp.x()-r, (int)fp.y()-r-2, 2*r+3, 2*r+3);
g.drawString(""+n.getKey(), (int)fp.x()-r+1, (int)fp.y()-2*r);
}
/**
* Draws an edge on the window.
*
* @param e represents the given edge needed to be drawn on the window.
* @param g
*/
private void drawEdge(edge_data e, Graphics g) {
directed_weighted_graph gg = arena.getGraphAlgo().getGraph();
geo_location s = gg.getNode(e.getSrc()).getLocation();
geo_location d = gg.getNode(e.getDest()).getLocation();
geo_location s0 = this._w2f.world2frame(s);
geo_location d0 = this._w2f.world2frame(d);
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(new BasicStroke(2));
g.drawLine((int)s0.x(), (int)s0.y(), (int)d0.x(), (int)d0.y());
// g.drawString(""+n.getKey(), fp.ix(), fp.iy()-4*r);
}
/**
* Draws all the pokemons on the window.
*
* @param g
*/
private void drawPokemons(Graphics g) {
List<CL_Pokemon> pokemons = arena.getPokemons();
if(pokemons!=null) {
Iterator<CL_Pokemon> it = pokemons.iterator();
while(it.hasNext()) {
CL_Pokemon pok = it.next();
geo_location c = pok.getPos();
int r = 10;
g.setColor(new Color(246, 243, 243, 255));
if(pok.getType() < 0) {
g.setColor(Color.red);
}
if(c!=null) {
geo_location ge = this._w2f.world2frame(c);
ImageIcon poky = new ImageIcon("./resources/Pokemon.png");
g.drawImage(poky.getImage(), (int)ge.x()-r-5, (int)ge.y()-r-5, 3*r, 3*r, null);
// g.fillOval((int)ge.x()-r, (int)ge.y()-r, 2*r, 2*r);
g.drawString(""+pok.getValue(), (int)ge.x()-r+1, (int)ge.y()-r-3);
}
}
}
}
/**
* Draws all the agents on the window.
*
* @param g
*/
private void drawAgents(Graphics g) {
List<CL_Agent> agents = arena.getAgents();
g.setColor(Color.DARK_GRAY);
int i = 0;
while(agents != null && i < agents.size()) {
geo_location c = agents.get(i).getPos();
int r=8;
i++;
if(c!=null) {
geo_location ge = this._w2f.world2frame(c);
ImageIcon poky = new ImageIcon("./resources/Agent.png");
g.drawImage(poky.getImage(), (int)ge.x()-2*r, (int)ge.y()-4*r, 5*r, 6*r, null);
// g.fillOval((int)ge.x()-r, (int)ge.y()-r, 2*r, 2*r);
// g.drawString(""+agents.get(i).getValue(), (int)ge.x(), (int)ge.y()-2*r);
}
}
}
/**
* Draws information about the game on the window - level, time to end, score and moves.
*/
private void Info(){
level.setText("level: "+arena.getLevel());
level.setFont(new Font(Font.SERIF, Font.PLAIN, 20));
level.setBounds(w-3*WP, 2, 200, 50);
time.setText("time: "+(arena.gatGame().timeToEnd()/1000));
time.setFont(new Font(Font.SERIF, Font.PLAIN, 20));
time.setBounds(w-2*WP, 2, 200, 50);
// int grade = jsonToObject.score(arena.gatGame().toString());
score.setFont(new Font(Font.SERIF, Font.PLAIN, 20));
score.setBounds(WP-5, 2, 200, 50);
int moving = jsonToObject.moves(arena.gatGame().toString());
moves.setText("moves: "+moving);
moves.setFont(new Font(Font.SERIF, Font.PLAIN, 20));
moves.setBounds(2*WP, 2, 200, 50);
}
}
<file_sep>/src/api/EdgeData.java
package api;
import java.util.Objects;
/**
* This class represents the set of operations applicable on a
* directional edge (src,dest) in a directed weighted graph.
*
* @authors Liel.Vaknin & Renana.Levy.
*/
public class EdgeData implements edge_data{
private int src;
private int dest;
private double edgeWeight;
private String edgeInfo;
private int edgeTag;
/**
* Constructor
*
* @param src represents the new src.
* @param dest represents the new dest.
* @param edgeWeight represents the new edgeWeight.
*/
public EdgeData(int src,int dest, double edgeWeight){
this.src = src;
this.dest = dest;
this.edgeWeight = edgeWeight;
}
/**
* Copy constructor - Performs a deep copy of a given edge.
*
* @param e represents the given edge.
*/
public EdgeData(edge_data e){
this.src = e.getSrc();
this.dest = e.getDest();
this.edgeWeight = e.getWeight();
this.edgeInfo = e.getInfo();
this.edgeTag = e.getTag();
}
/**
* Returns the key of the source node of this edge.
*
* @return src.
*/
@Override
public int getSrc(){
return this.src;
}
/**
* Returns the key of the destination node of this edge.
*
* @return dest.
*/
@Override
public int getDest(){
return this.dest;
}
/**
* Returns the weight of this edge (positive value).
*
* @return edgeWeight.
*/
@Override
public double getWeight(){
return this.edgeWeight;
}
/**
* Returns the remark (meta data) associated with this edge.
*
* @return edgeInfo.
*/
@Override
public String getInfo(){
return this.edgeInfo;
}
/**
* Allows changing the remark (meta data) associated with this edge.
*
* @param s represents the given edgeInfo.
*/
@Override
public void setInfo(String s){
this.edgeInfo = s;
}
/**
* Returns temporal data which can be used by algorithms.
*
* @return edgeTag.
*/
@Override
public int getTag(){
return this.edgeTag;
}
/**
* Allows setting the "tag" value for temporal marking an edge - common
* practice for marking by algorithms.
*
* @param t represents the new value of the edgeTag.
*/
@Override
public void setTag(int t){
this.edgeTag = t;
}
/**
* Equals method.
*
* @param o represents a given object.
* @return true if this object and a given object are equals, false if not.
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EdgeData edgeData = (EdgeData) o;
return src == edgeData.src && dest == edgeData.dest && Double.compare(edgeData.edgeWeight, edgeWeight) == 0 && edgeTag == edgeData.edgeTag && Objects.equals(edgeInfo, edgeData.edgeInfo);
}
/**
* HashCode method.
*
* @return
*/
@Override
public int hashCode() {
return Objects.hash(src, dest, edgeWeight, edgeInfo, edgeTag);
}
}<file_sep>/tests/api/DWGraph_DSTest.java
package api;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
* Test for DWGraph_DS class.
*/
class DWGraph_DSTest {
directed_weighted_graph g_Test = new DWGraph_DS();
node_data n0 = new NodeData();
node_data n1 = new NodeData();
node_data n2 = new NodeData();
node_data n3 = new NodeData();
node_data n4 = new NodeData();
/**
* Builts a graph with 5 nodes and 9 edges.
*/
@BeforeEach
public void buildingGraph(){
g_Test.addNode(n0);
g_Test.addNode(n1);
g_Test.addNode(n2);
g_Test.addNode(n3);
g_Test.addNode(n4);
g_Test.connect(0, 1, 6);
g_Test.connect(0, 2, 9);
g_Test.connect(1, 2, 2);
g_Test.connect(1, 3, 7);
g_Test.connect(1, 4, 5);
g_Test.connect(2, 0, 3);
g_Test.connect(2, 3, 1);
g_Test.connect(3, 4, 1);
g_Test.connect(4, 1, 3);
assertEquals(5, g_Test.nodeSize());
assertEquals(9, g_Test.edgeSize());
assertEquals(14, g_Test.getMC());
}
/**
* Test for getNode and addNode methods.
*/
@Test
public void nodes() {
assertNull(g_Test.getNode(12)); //A node that isn't in the graph.
assertNotNull(g_Test.getNode(4)); //A node that is in the graph.
node_data n5 = new NodeData();
g_Test.addNode(n5); //Add node to the graph.
assertEquals(6, g_Test.nodeSize());
assertEquals(15, g_Test.getMC());
g_Test.addNode(n5); //Add node which there is in the graph.
assertEquals(6, g_Test.nodeSize());
assertEquals(15, g_Test.getMC());
}
/**
* Test for connect and getEdge methods.
*/
@Test
public void edges() {
assertNotNull( g_Test.getEdge(1, 4));
g_Test.connect(1, 4, 10); //Connect 2 nodes that connected.
g_Test.connect(2, 4, 0); //Connect 2 nodes that didn't connected.
assertNotNull( g_Test.getEdge(2, 4));
g_Test.connect(4, 12, 3); //Connect 2 nodes- the first is in the graph and the second not.
assertNull( g_Test.getEdge(4, 12));
g_Test.connect(9, 3, 5); //Connect 2 nodes- the first isn't in the graph and the second their.
assertNull( g_Test.getEdge(9, 3));
g_Test.connect(12, 13, 3); //Connect 2 nodes that aren't in the graph.
assertNull(g_Test.getEdge(12, 13));
g_Test.connect(3, 3, 7); //Connect node that is in the graph to himself.
assertNull(g_Test.getEdge(3, 3));
g_Test.connect(17, 17, 1); //Connect node that isn't in the graph to himself.
assertNull(g_Test.getEdge(17, 17));
assertEquals(10, g_Test.edgeSize());
assertEquals(15, g_Test.getMC());
}
/**
* Test for getV method.
*/
@Test
public void getV() {
int length= g_Test.getV().size();
assertEquals(5, length);
directed_weighted_graph g_Test1 = new DWGraph_DS();
int length1= g_Test1.getV().size();
assertEquals(0, length1);
}
/**
* Test for getE method.
*/
@Test
void getE() {
int length1= g_Test.getE(1).size();
assertEquals(3, length1);
node_data n5 = new NodeData();
g_Test.addNode(n5);
assertNull(g_Test.getE(5));
assertNull(g_Test.getE(10));
}
/**
* Test for removeNode method.
*/
@Test
void removeNode() {
node_data n= g_Test.removeNode(1); //Remove a node that is in the graph.
assertEquals(1, n.getKey());
assertEquals(4, g_Test.edgeSize());
assertEquals(4, g_Test.nodeSize());
n= g_Test.removeNode(8); //Remove a node that isn't in the graph.
assertNull(n);
assertEquals(4, g_Test.edgeSize());
assertEquals(4, g_Test.nodeSize());
assertEquals(17, g_Test.getMC());
}
/**
* Test for removeEdge method.
*/
@Test
public void removeEdge() {
g_Test.removeEdge(0, 1); //Remove a edge that is in the graph.
g_Test.removeEdge(1, 0); //Remove a edge that isn't in the graph.
g_Test.removeEdge(4, 11); //Remove a edge between node that is in the graph to node that not.
g_Test.removeEdge(7, 2); //Remove a edge between node that isn't in the graph to node that their.
g_Test.removeEdge(17, 13); //Remove a edge between 2 nodes that aren't in the graph.
g_Test.removeEdge(2, 2); //Remove a edge between node that is in the graph to himself.
g_Test.removeEdge(8, 8); //Remove a edge between node that isn't in the graph to himself.
assertEquals(5, g_Test.nodeSize());
assertEquals(8, g_Test.edgeSize());
assertEquals(15, g_Test.getMC());
}
}<file_sep>/src/gameClient/CL_Agent.java
package gameClient;
import api.*;
/**
* This class represents an agent in the game.
*
* @authors Liel.Vaknin & Renana.Levy.
*/
public class CL_Agent {
private int id;
private double value;
private int src;
private int dest;
private double speed;
private geo_location pos;
/**
* Constructor.
*
* @param id
* @param value
* @param src
* @param dest
* @param speed
* @param pos
*/
public CL_Agent(int id, double value, int src, int dest, double speed, geo_location pos){
this.id = id;
this.value = value;
this.src = src;
this.dest = dest;
this.speed = speed;
this.pos = pos;
}
/**
* Returns the id of this agent.
*
* @return id.
*/
public int getId() {
return id;
}
/**
* Returns the value of this agent.
*
* @return value.
*/
public double getValue() {
return value;
}
/**
* Returns the key of the source node which this agent is currently stands on.
*
* @return src.
*/
public int getSrc() {
return src;
}
/**
* Allows to set the key of the source node which this agent is currently stands on.
*
* @param src represents the given key of the source node.
*/
public void setSrc(int src) {
this.src = src;
}
/**
* Returns the key of the destination node which this agent is about to reach.
*
* @return dest.
*/
public int getDest() {
return dest;
}
/**
* Allows to set the key of the destination node which this agent is about to reach.
*
* @param dest represents the given key of the destination node.
*/
public void setDest(int dest) {
this.dest = dest;
}
/**
* Returns the speed of this agent.
*
* @return speed.
*/
public double getSpeed() {
return speed;
}
/**
* Returns geo location <x,y,z>, aka Point3D, of this agent.
*
* @return pos.
*/
public geo_location getPos() {
return pos;
}
/**
* Allows to set the geo location <x,y,z>, aka Point3D, of this agent.
*
* @param pos represents the given geo location.
*/
public void setPos(geo_location pos) {
this.pos = pos;
}
}
<file_sep>/src/gameClient/jsonToObject.java
package gameClient;
import api.*;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.List;
/**
* This class receives data from the server (jar file) on which the game is performed
* and loads the information from it which based on strings represented as JSON.
*
* @authors Liel.Vaknin & Renana.Levy.
*/
public final class jsonToObject {
/**
* Loads the information from the given JSON String which represents a directed weighted graph,
* to the given new empty graph.
*
* @param json represents a JSON String which contains all the information about the game's graph.
* @param graph represents a new empty graph which built according all the information of the given JSON String.
*/
public static void loadGraph(String json, directed_weighted_graph graph) {
Gson gson = new Gson();
JsonObject jGraph = gson.fromJson(json, JsonObject.class);
JsonArray nodes = jGraph.get("Nodes").getAsJsonArray();
for (int i = 0; i < nodes.size(); i++) {
int id = nodes.get(i).getAsJsonObject().get("id").getAsInt();
String pos = nodes.get(i).getAsJsonObject().get("pos").getAsString();
geo_location location = new GeoLocation(pos);
node_data node = new NodeData(id);
node.setLocation(location);
graph.addNode(node);
}
JsonArray edges = jGraph.get("Edges").getAsJsonArray();
for (int i = 0; i < edges.size(); i++) {
int src = edges.get(i).getAsJsonObject().get("src").getAsInt();
int dest = edges.get(i).getAsJsonObject().get("dest").getAsInt();
double weight = edges.get(i).getAsJsonObject().get("w").getAsDouble();
graph.connect(src, dest, weight);
}
}
/**
* Loads the information from the given JSON String which represents a list of agents,
* to a new empty list of agents and returns the list.
*
* @param json represents a JSON String which contains all the information about the game's list of agents.
* @return List<CL_Agent>.
*/
public static List<CL_Agent> loadAgents(String json) {
List<CL_Agent> l = new ArrayList<>();
Gson gson = new Gson();
JsonObject jsonAgents = gson.fromJson(json, JsonObject.class);
JsonArray arrayAgents = jsonAgents.get("Agents").getAsJsonArray();
for(int i=0;i<arrayAgents.size();i++) {
JsonObject agent= arrayAgents.get(i).getAsJsonObject().get("Agent").getAsJsonObject();
int id = agent.get("id").getAsInt();
int value = agent.get("value").getAsInt();
int src = agent.get("src").getAsInt();
int dest = agent.get("dest").getAsInt();
Double speed = agent.get("speed").getAsDouble();
geo_location pos = new GeoLocation(agent.get("pos").getAsString());
CL_Agent a = new CL_Agent(id, value, src, dest, speed, pos);
l.add(a);
}
return l;
}
/**
* Loads the information from the given JSON String which represents a list of pokemons,
* to a new empty list of pokemons and returns the list.
*
* @param json represents a JSON String which contains all the information about the game's list of pokemons.
* @param graph represents the graph's game.
* @return List<CL_Pokemon>.
*/
public static List<CL_Pokemon> loadPokemon(String json, directed_weighted_graph graph) {
List<CL_Pokemon> l = new ArrayList<>();
Gson gson = new Gson();
JsonObject jsonPokemons = gson.fromJson(json, JsonObject.class);
JsonArray arrayPokemons = jsonPokemons.get("Pokemons").getAsJsonArray();
for(int i=0;i<arrayPokemons.size();i++) {
JsonObject agent= arrayPokemons.get(i).getAsJsonObject().get("Pokemon").getAsJsonObject();
int value = agent.get("value").getAsInt();
int type = agent.get("type").getAsInt();
geo_location pos = new GeoLocation(agent.get("pos").getAsString());
CL_Pokemon p = new CL_Pokemon(value, type, pos, graph);
l.add(p);
}
return l;
}
/**
* Loads from the given JSON String the number of agents in the game.
*
* @param jsonGame represents a JSON String which contains the information about the game.
* @return number of agents in the game.
*/
public static int numOfAgentsByLevel(String jsonGame){
Gson gson = new Gson();
JsonObject jGame = gson.fromJson(jsonGame, JsonObject.class);
int numOfAgentsInTheGame = jGame.get("GameServer").getAsJsonObject().get("agents").getAsInt();
return numOfAgentsInTheGame;
}
/**
* Loads from the given JSON String the score in the game.
*
* @param jsonGame represents a JSON String which contains the information about the game.
* @return score in the game.
*/
public static int score(String jsonGame){
Gson gson = new Gson();
JsonObject jGame = gson.fromJson(jsonGame, JsonObject.class);
int grade = jGame.get("GameServer").getAsJsonObject().get("grade").getAsInt();
return grade;
}
/**
* Loads from the given JSON String the number of moves in the game.
*
* @param jsonGame jsonGame represents a JSON String which contains the information about the game.
* @return number of moves in the game.
*/
public static int moves(String jsonGame){
Gson gson = new Gson();
JsonObject jGame = gson.fromJson(jsonGame, JsonObject.class);
int moves = jGame.get("GameServer").getAsJsonObject().get("moves").getAsInt();
return moves;
}
}
| 527fef30495cc53198185295e01b7e5b8659e166 | [
"Markdown",
"Java"
] | 9 | Java | LielVaknin/OOP-Project-Pokemon-Game | 7ba9645bffb16cc3e74b853eaa256aa8c9a7e176 | ec1db58154fe00d465ec9a2a94fcc5b134afb5d7 |
refs/heads/main | <file_sep>from crawler_util.crawler_with_parsel import CrawlerParsel
import unittest
class ToutiaoIOCrawler:
@staticmethod
async def fetch():
posts = await CrawlerParsel.fetch(
__url__='https://toutiao.io/posts/hot/7',
__post_item_xpath__='//div[@class="post"]//h3[@class="title"]/a',
__post_url_func__=lambda url: 'https://toutiao.io' + url
)
return posts
class ToutiaoIOCrawlerTester(unittest.TestCase):
def test_fetch(self):
CrawlerParsel.test_fetch(ToutiaoIOCrawler)
<file_sep>from crawler_util.crawler_with_parsel import CrawlerParsel
import unittest
class NineTwoEZCrawler:
@staticmethod
async def fetch():
return await CrawlerParsel.fetch(
__url__='https://www.92ez.com/',
__post_item_xpath__='//div[@class="post-main"]/h1[@class="post-title"]'
)
class NineTwoEZCrawlerTester(unittest.TestCase):
def test_fetch(self):
CrawlerParsel.test_fetch(NineTwoEZCrawler)
<file_sep>from crawler_util.crawler_with_parsel import CrawlerParsel
import unittest
class TonyBaiCrawler:
@staticmethod
async def fetch():
return await CrawlerParsel.fetch(
__url__='https://tonybai.com/articles/',
__post_item_xpath__='//div[@class="post-content"]//ul/li/a'
)
class TonyBaiCrawlerTester(unittest.TestCase):
def test_fetch(self):
CrawlerParsel.test_fetch(TonyBaiCrawler)
<file_sep>from crawler_util.crawler_with_parsel import CrawlerParsel
import unittest
class RobertTalbertCrawler:
@staticmethod
async def fetch():
posts = await CrawlerParsel.fetch(
__url__='http://rtalbert.org/',
__post_item_xpath__='//article/header[@class="post-header"]/h2/a',
__post_url_func__=lambda url: 'http://rtalbert.org' + url
)
return posts
class RobertTalbertCrawlerTester(unittest.TestCase):
def test_fetch(self):
CrawlerParsel.test_fetch(RobertTalbertCrawler)
<file_sep>from crawler_util.crawler_with_parsel import CrawlerParsel
import unittest
class MrMetroCrawler:
@staticmethod
async def fetch():
posts = await CrawlerParsel.fetch(
__url__='http://miccall.tech/',
__post_item_xpath__='//section[@class="link_box special"]',
__post_title_xpath__='//a//h2/text()',
__post_url_func__=lambda url: 'http://miccall.tech' + url
)
return posts
class MrMetroCrawlerTester(unittest.TestCase):
def test_fetch(self):
CrawlerParsel.test_fetch(MrMetroCrawler)
<file_sep># Blog Subscriber
博客订阅工具
<file_sep>from crawler_util.crawler_with_parsel import CrawlerParsel
import unittest
class ICoderTechCrawler:
@staticmethod
async def fetch():
posts = await CrawlerParsel.fetch(
__url__='https://icoder.tech/',
__post_item_xpath__='//article//header[@class="article-header"]//a[@class="article-title"]',
__post_url_func__=lambda url: 'https://icoder.tech' + url
)
return posts
class ICoderTechCrawlerTester(unittest.TestCase):
def test_fetch(self):
CrawlerParsel.test_fetch(ICoderTechCrawler)
<file_sep>from crawler_util.crawler_with_parsel import CrawlerParsel
import unittest
class WmdpdCrawler:
@staticmethod
async def fetch():
posts = await CrawlerParsel.fetch(
__url__='https://wmdpd.com/',
__post_item_xpath__='//h2[@class="c-post-card__title"]/a',
__post_url_func__=lambda url: 'https://wmdpd.com' + url
)
return posts
class WmdpdCrawlerTester(unittest.TestCase):
def test_fetch(self):
CrawlerParsel.test_fetch(WmdpdCrawler)
<file_sep>import sys
import logging
import json
import redis
import asyncio
import os
from monitor_util.monitor_util import MonitorUtil
from telethon.sync import TelegramClient
from telethon import functions
from sites.program_think_crawler import ProgramThinkCrawler
from sites.coolshell_crawler import CoolShellCrawler
from sites.cybartist_crawler import CybartistCrawler
from sites.nine_two_ez_crawler import NineTwoEZCrawler
from sites.mr_metro_crawler import MrMetroCrawler
from sites.yakoazz_crawler import YakoazzCrawler
from sites.crazyacking_crawler import CrazyackingCrawler
from sites.ackerman_crawler import AckermanCrawler
from sites.yinwang_crawler import YinwangCrawler
from sites.freebuf_crawler import FreeBufCrawler
from sites.wmdpd_crawler import WmdpdCrawler
from sites.icoder_tech_crawler import ICoderTechCrawler
from sites.t00ls_crawler import T00lsCrawler
from sites.linux_cn_crawler import LinuxCnTechCrawler, LinuxCnTalkCrawler, LinuxCnNewsCrawler, LinuxCnShareCrawler
from sites.oschina_crawler import OSChinaIndustryCrawler, OSChinaBlogCrawler
from sites.toutiao_io_crawler import ToutiaoIOCrawler
from sites.mark_karpov_crawler import MarkKarpovCrawler
from sites.tony_bai_crawler import TonyBaiCrawler
from sites.robert_talbert_crawler import RobertTalbertCrawler
from sites.gkogan_co_crawler import GkoganCoCrawler
from sites.mysql_taobao_org_monthly_crawler import MysqlTaobaoOrgMonthlyCrawler
from sites.george_stocker_crawler import GeorgeStockerCrawler
from sites.samcurry_net_crawler import SamCurryNetCrawler
from sites.ismdeep_crawler import IsmdeepCrawler
work_dir = None
redis_config = None
REDIS_KEY_NAME = 'blogger_posts'
api_id = None
api_hash = None
channel_share_link = None
pool = None
client = None
channel = None
async def is_saved(__url__):
conn = redis.Redis(connection_pool=pool)
return conn.hexists(REDIS_KEY_NAME, __url__)
async def push_to_redis(__url__, __title__):
conn = redis.Redis(connection_pool=pool)
conn.hset(REDIS_KEY_NAME, __url__, __title__)
logging.info('Pushed => %s' % __url__)
def init_logging():
logging.basicConfig(
filename=work_dir + '/product.log',
level=logging.INFO,
format='%(asctime)s %(filename)s[%(levelname)s][line:%(lineno)d] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
console = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s %(filename)s[%(levelname)s][line:%(lineno)d] %(message)s')
console.setFormatter(formatter)
logging.getLogger("").addHandler(console)
async def func(__blogger_tag__, __crawler__):
posts = await __crawler__.fetch()
if len(posts) > 0:
await MonitorUtil.update_status('博客订阅.{}'.format(__blogger_tag__), 'true')
for post in posts[::-1]:
if not await is_saved(post['url']):
await client(functions.messages.SendMessageRequest(
peer=channel,
message='%s\n%s\n%s' % (__blogger_tag__, post['title'], post['url']),
no_webpage=False
))
await push_to_redis(post['url'], post['title'])
logging.info('Sent to channel => {%s, %s}' % (post['url'], post['title']))
await MonitorUtil.update_status('博客订阅.func', 'true')
def main():
loop = asyncio.get_event_loop()
tasks = [
func('#coolshell', CoolShellCrawler),
func('#编程随想', ProgramThinkCrawler),
func('#cybartist', CybartistCrawler),
func('#92ez', NineTwoEZCrawler),
func('#mr_metro', MrMetroCrawler),
func('#yakoazz', YakoazzCrawler),
func('#crazyacking', CrazyackingCrawler),
func('#ackerman', AckermanCrawler),
func('#王垠', YinwangCrawler),
# func('#freebuf', FreeBufCrawler),
func('#完美的胖达', WmdpdCrawler),
func('#司徒公子', ICoderTechCrawler),
func('#T00ls', T00lsCrawler),
# func('#Linux中国 #技术', LinuxCnTechCrawler),
func('#Linux中国 #新闻', LinuxCnNewsCrawler),
# func('#Linux中国 #分享', LinuxCnShareCrawler),
# func('#Linux中国 #观点', LinuxCnTalkCrawler),
# func('#开源中国 #综合资讯', OSChinaIndustryCrawler),
# func('#开源中国 #博客', OSChinaBlogCrawler),
# func('#开发者头条', ToutiaoIOCrawler),
func('#Mark_Karpov', MarkKarpovCrawler),
func('#Tony_Bai', TonyBaiCrawler),
func('#Robert_Talbert', RobertTalbertCrawler),
func('#gkogan', GkoganCoCrawler),
func('#数据库内核月报', MysqlTaobaoOrgMonthlyCrawler),
func('#GeorgeStocker', GeorgeStockerCrawler),
func('#SamCurry', SamCurryNetCrawler),
func('#ismdeep', IsmdeepCrawler),
]
loop.run_until_complete(asyncio.wait(tasks))
client.disconnect()
loop.close()
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Usage: python3 blogger-subscriber.py {work_dir}')
exit(0)
# 1. Fetch Working Directory
work_dir = sys.argv[1]
os.chdir(work_dir)
# 2. Initialize logging Configuration
init_logging()
# 3. Get Redis Configuration
redis_config = json.load(open(work_dir + '/redis.json', 'r'))
pool = redis.ConnectionPool(host=redis_config['host'], port=redis_config['port'])
try:
redis.Redis(connection_pool=pool).ping()
except Exception as e:
print(e)
exit(-1)
# 4. Load Monitor Config
monitor_json = json.load(open(work_dir + '/monitor.json', 'r'))
monitor = MonitorUtil()
monitor.set_url(monitor_json['url'])
monitor.set_token(monitor_json['token'])
# Set Telegram Bot
telegram_bot_config = json.load(open(work_dir + '/telegram_bot.json', 'r'))
api_id = telegram_bot_config['api_id']
api_hash = telegram_bot_config['api_hash']
channel_share_link = telegram_bot_config['channel_share_link']
# 4. client connect
# client2 = TelegramClient('anon', api_id, api_hash)
# client2.start()
# client2.disconnect()
client = TelegramClient('anon', api_id, api_hash)
client.connect()
channel = client.get_entity(channel_share_link)
# 4. Start main()
main()
<file_sep>import requests
import logging
class MonitorUtil(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
orig = super(MonitorUtil, cls)
cls._instance = orig.__new__(cls)
return cls._instance
def set_url(self, __url__):
self.url = __url__
def set_token(self, __token__):
self.token = __token__
@staticmethod
async def update_status(key_name, value):
monitor = MonitorUtil()
req = requests.post(
url=monitor.url,
data={
'token': monitor.token,
'key': key_name,
'value': value
}
)
logging.info(req.text)
<file_sep>from crawler_util.crawler_with_parsel import CrawlerParsel
import unittest
class YinwangCrawler:
@staticmethod
async def fetch():
posts = await CrawlerParsel.fetch(
__url__='http://www.yinwang.org/',
__post_item_xpath__='//li[@class="list-group-item title"]',
__post_url_func__=lambda url: 'http://www.yinwang.org' + url
)
return posts
class YinwangCrawlerTester(unittest.TestCase):
def test_fetch(self):
CrawlerParsel.test_fetch(YinwangCrawler)
<file_sep>from crawler_util.crawler_with_parsel import CrawlerParsel
import unittest
class MysqlTaobaoOrgMonthlyCrawler:
@staticmethod
async def fetch():
month_list = await CrawlerParsel.fetch(
__url__='http://mysql.taobao.org/monthly/',
__post_item_xpath__='//ul[@class="posts"]/li/h3/a',
__post_url_func__=lambda url: 'http://mysql.taobao.org' + url,
__post_title_func__=lambda title: title.encode('raw_unicode_escape').decode('utf-8', errors='ignore')
)
posts = []
for month in month_list:
month_posts = await CrawlerParsel.fetch(
__url__=month['url'],
__post_item_xpath__='//ul[@class="posts"]/li/h3/a',
__post_url_func__=lambda url: 'http://mysql.taobao.org' + url,
__post_title_func__=lambda title: title.encode('raw_unicode_escape').decode('utf-8', errors='ignore')
)
[posts.append(post) for post in month_posts]
return posts
class MysqlTaobaoOrgMonthlyCrawlerTester(unittest.TestCase):
def test_fetch(self):
CrawlerParsel.test_fetch(MysqlTaobaoOrgMonthlyCrawler)
<file_sep>from crawler_util.crawler_with_parsel import CrawlerParsel
import unittest
class AckermanCrawler:
@staticmethod
async def fetch():
return await CrawlerParsel.fetch(
__url__='https://www.cnblogs.com/-Ackerman/',
__post_item_xpath__='//div[@class="postTitle"]',
__post_title_xpath__='//a/span/text()'
)
class AckermanCrawlerTester(unittest.TestCase):
def test_fetch(self):
CrawlerParsel.test_fetch(AckermanCrawler)
<file_sep>from crawler_util.crawler_with_parsel import CrawlerParsel
import unittest
class T00lsCrawler:
@staticmethod
async def fetch():
posts = await CrawlerParsel.fetch(
__url__='https://www.t00ls.net/tech.html',
__post_item_xpath__='//div[@class="articles_content"]//div[@class="item_content"]/h4/a',
__post_url_func__=lambda url: 'https://www.t00ls.net/' + url
)
return posts
class T00lsCrawlerTester(unittest.TestCase):
def test_fetch(self):
CrawlerParsel.test_fetch(T00lsCrawler)
<file_sep>from crawler_util.crawler_with_parsel import CrawlerParsel
import unittest
import asyncio
class OSChinaIndustryCrawler:
@staticmethod
async def fetch():
return await CrawlerParsel.fetch(
__url__='https://www.oschina.net/news/widgets/_news_index_generic_list',
__post_item_xpath__='//div[@class="item news-item"]//h3[@class="header"]/a'
)
class OSChinaBlogCrawler:
@staticmethod
async def fetch():
return await CrawlerParsel.fetch(
__url__='https://www.oschina.net/blog/widgets/_blog_index_recommend_list?classification=0',
__post_item_xpath__='//div[@class="item blog-item"]//a[@class="header"]',
)
class OSChinaCrawlerTester(unittest.TestCase):
def test_industry_fetch(self):
CrawlerParsel.test_fetch(OSChinaIndustryCrawler)
def test_blog_fetch(self):
CrawlerParsel.test_fetch(OSChinaBlogCrawler)
<file_sep>from crawler_util.crawler_with_parsel import CrawlerParsel, http_get_text
import unittest
import json
import time
import requests
from lxml import etree
class WeiboHotTopicCrawler:
@staticmethod
async def fetch():
url = "https://s.weibo.com/top/summary?cate=realtimehot"
headers = {
'Host': 's.weibo.com',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'zh-CN,zh;q=0.9',
'Connection': 'keep-alive',
'Referer': 'https://weibo.com/',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36'
}
r = requests.get(url, headers=headers)
if r.status_code != 200:
return []
html_xpath = etree.HTML(r.text)
data = html_xpath.xpath('//*[@id="pl_top_realtimehot"]/table/tbody/tr/td[2]')
posts = []
for tr in (data):
title = tr.xpath('./a/text()')
url = tr.xpath('./a/@href')
if len(title) <= 0 or len(url) <= 0:
continue
title = title[0]
url = "https://s.weibo.com{}".format(url[0])
posts.append({
'title': title,
'url': url
})
return posts
class WeiboHotTopicCrawlerTester(unittest.TestCase):
def test_fetch(self):
CrawlerParsel.test_fetch(WeiboHotTopicCrawler)
<file_sep>import requests
from parsel import Selector
import asyncio
import os
user_agent = 'Mozilla/5.0 ' \
'(Macintosh; Intel Mac OS X 10_15_7) ' \
'AppleWebKit/537.36 (KHTML, like Gecko) ' \
'Chrome/85.0.4183.121 Safari/537.36'
async def http_get_text(__url__):
try:
return requests.get(url=__url__, headers={'User-Agent': user_agent}).text
except Exception as e:
print(e)
pass
try:
return os.popen("curl {}".format(__url__)).read()
except:
pass
return ""
class CrawlerParsel:
@staticmethod
async def fetch(__url__, __post_item_xpath__,
__post_url_xpath__='//a/@href',
__post_title_xpath__='//a/text()',
__post_url_func__=None,
__post_title_func__=None
):
posts = []
selector = Selector(await http_get_text(__url__))
posts_raw = selector.xpath(__post_item_xpath__).extract()
for post_raw in posts_raw:
post_selector = Selector(post_raw)
post_url = post_selector.xpath(__post_url_xpath__).extract()[0]
post_title = post_selector.xpath(__post_title_xpath__).extract()[0].strip()
if __post_url_func__ is not None:
post_url = __post_url_func__(post_url)
if __post_title_func__ is not None:
post_title = __post_title_func__(post_title)
posts.append({
'url': post_url,
'title': post_title
})
return posts
@staticmethod
def test_fetch(__crawler_class__):
posts = asyncio.run(__crawler_class__.fetch())
[print(post) for post in posts]
<file_sep>from crawler_util.crawler_with_parsel import CrawlerParsel
import unittest
class GkoganCoCrawler:
@staticmethod
async def fetch():
posts = await CrawlerParsel.fetch(
__url__='https://www.gkogan.co/blog/',
__post_item_xpath__='//ul[@class="post-list"]/li/a',
__post_url_func__=lambda post_url: 'https://www.gkogan.co' + post_url
)
return posts
class GkoganCoCrawlerTester(unittest.TestCase):
def test_fetch(self):
CrawlerParsel.test_fetch(GkoganCoCrawler)<file_sep>from crawler_util.crawler_with_parsel import CrawlerParsel
import unittest
async def linux_cn_common_fetch(__url__):
return await CrawlerParsel.fetch(
__url__=__url__,
__post_item_xpath__='//span[@class="title"]/a',
__post_title_xpath__='//a/span/text()'
)
class LinuxCnTechCrawler:
@staticmethod
async def fetch():
return await linux_cn_common_fetch('https://linux.cn/tech/')
class LinuxCnNewsCrawler:
@staticmethod
async def fetch():
return await linux_cn_common_fetch('https://linux.cn/news/')
class LinuxCnTalkCrawler:
@staticmethod
async def fetch():
return await linux_cn_common_fetch('https://linux.cn/talk/')
class LinuxCnShareCrawler:
@staticmethod
async def fetch():
return await linux_cn_common_fetch('https://linux.cn/share/')
class LinuxCnCrawlerTester(unittest.TestCase):
def test_news_fetch(self):
CrawlerParsel.test_fetch(LinuxCnNewsCrawler)
def test_tech_fetch(self):
CrawlerParsel.test_fetch(LinuxCnTechCrawler)
def test_talk_fetch(self):
CrawlerParsel.test_fetch(LinuxCnTalkCrawler)
def test_share_fetch(self):
CrawlerParsel.test_fetch(LinuxCnShareCrawler)
<file_sep>from crawler_util.crawler_with_parsel import CrawlerParsel
import unittest
class SamCurryNetCrawler:
@staticmethod
async def fetch():
return await CrawlerParsel.fetch(
__url__='https://samcurry.net/blog/',
__post_item_xpath__='//article//header[@class="entry-header"]//h2[@class="entry-title"]/a'
)
class SamCurryNetCrawlerTester(unittest.TestCase):
def test_fetch(self):
CrawlerParsel.test_fetch(SamCurryNetCrawler)
<file_sep>from crawler_util.crawler_with_parsel import CrawlerParsel
import unittest
class IsmdeepCrawler:
@staticmethod
async def fetch():
return await CrawlerParsel.fetch(
__url__='https://ismdeep.com/archives/',
__post_item_xpath__='//article//a',
__post_url_func__=lambda url: 'https://ismdeep.com' + url
)
class IsmdeepCrawlerTester(unittest.TestCase):
def test_fetch(self):
CrawlerParsel.test_fetch(IsmdeepCrawler)
<file_sep>from crawler_util.crawler_with_parsel import CrawlerParsel
import unittest
class ProgramThinkCrawler:
@staticmethod
async def fetch():
return await CrawlerParsel.fetch(
__url__='https://program-think.blogspot.com/',
__post_item_xpath__='//div[@class="blog-posts hfeed"]//h1[@class="post-title entry-title"]/a'
)
class ProgramThinkCrawlerTester(unittest.TestCase):
def test_fetch(self):
CrawlerParsel.test_fetch(ProgramThinkCrawler)
<file_sep>from crawler_util.crawler_with_parsel import CrawlerParsel
import unittest
class CoolShellCrawler:
@staticmethod
async def fetch():
return await CrawlerParsel.fetch(
__url__='https://coolshell.cn/',
__post_item_xpath__='//h2[@class="entry-title"]/a',
)
class CoolShellCrawlerTester(unittest.TestCase):
def test_fetch(self):
CrawlerParsel.test_fetch(CoolShellCrawler)
<file_sep>from crawler_util.crawler_with_parsel import CrawlerParsel
import unittest
class FreeBufCrawler:
@staticmethod
async def fetch():
posts = await CrawlerParsel.fetch(
__url__='https://www.freebuf.com/',
__post_item_xpath__='//div[@class="article-item"]//div[@class="title-view"]/div[@class="title-left"]/a[1]',
__post_url_xpath__='//a/@href',
__post_title_xpath__='//a/span/text()',
__post_url_func__=lambda url: 'https://www.freebuf.com' + url
)
return posts
class FreeBufCrawlerTester(unittest.TestCase):
def test_fetch(self):
CrawlerParsel.test_fetch(FreeBufCrawler)
<file_sep>from crawler_util.crawler_with_parsel import CrawlerParsel
from parsel import Selector
import unittest
class CrazyackingCrawler:
@staticmethod
async def fetch():
posts = await CrawlerParsel.fetch(
__url__='https://www.cnblogs.com/crazyacking/',
__post_item_xpath__='//div[@class="postTitle"]/a',
__post_title_xpath__='//a/span',
__post_title_func__=lambda __title__: Selector(__title__).xpath('//span/text()').extract()[-1].strip()
)
return posts
class CrazyackingCrawlerTester(unittest.TestCase):
def test_fetch(self):
CrawlerParsel.test_fetch(CrazyackingCrawler)
<file_sep>parsel~=1.6.0
requests~=2.24.0
redis~=3.5.3
Telethon~=1.16.4<file_sep>from crawler_util.crawler_with_parsel import CrawlerParsel
import unittest
class GeorgeStockerCrawler:
@staticmethod
async def fetch():
return await CrawlerParsel.fetch(
__url__='https://georgestocker.com/',
__post_item_xpath__='//section[@class="widget widget_recent_entries"]//ul//li//a'
)
class GeorgeStockerCrawlerTester(unittest.TestCase):
def test_fetch(self):
CrawlerParsel.test_fetch(GeorgeStockerCrawler)
<file_sep>from crawler_util.crawler_with_parsel import CrawlerParsel
import unittest
class MarkKarpovCrawler:
@staticmethod
async def fetch():
posts = await CrawlerParsel.fetch(
__url__='https://markkarpov.com/posts.html',
__post_item_xpath__='//table[@class="table table-striped mt-3"]/tr//a',
__post_url_func__=lambda url: 'https://markkarpov.com' + url if url[0] == '/' else url
)
return posts
class MarkKarpovCrawlerTester(unittest.TestCase):
def test_fetch(self):
CrawlerParsel.test_fetch(MarkKarpovCrawler) | 16123d8dbebc79463f15aebdb021e762f5f72ade | [
"Markdown",
"Python",
"Text"
] | 28 | Python | ismdeep/blog-subscriber | 6264dfc7a60aa9e990b6f72b01a4635777828e32 | 8ba4bae5007ba96f11f7cf0e798811441887087a |
refs/heads/master | <file_sep># Recipes-By-Ingredients-Android-Application
Android Application I produced with a team of five.
<file_sep>package com.example.hungdo.myrecipe.Dish.Content;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import com.example.hungdo.myrecipe.Dish.APIs.ExpandedView;
import com.example.hungdo.myrecipe.R;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.facebook.share.ShareApi;
import com.facebook.share.model.SharePhoto;
import com.facebook.share.model.SharePhotoContent;
import com.twitter.sdk.android.Twitter;
import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.Result;
import com.twitter.sdk.android.core.TwitterAuthConfig;
import com.twitter.sdk.android.core.TwitterException;
import com.twitter.sdk.android.core.TwitterSession;
import com.twitter.sdk.android.core.identity.TwitterLoginButton;
import io.fabric.sdk.android.Fabric;
public class About extends Activity {
private CallbackManager callbackManager;
private LoginButton loginButton;
private TwitterLoginButton twitterLoginButton;
// Note: Your consumer key and secret should be obfuscated in your source code before shipping.
private static final String TWITTER_KEY = "O<KEY>";
private static final String TWITTER_SECRET = "KRLVrLwu87GxFwDehe<KEY>";
//This class handles the app description, facebook API, and Twitter API
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
Fabric.with(this, new Twitter(authConfig));
getFbKeyHash("org.code2care.fbloginwithandroidsdk");
setContentView(R.layout.activity_about);
loginButton = (LoginButton) findViewById(R.id.fb_login_button);
LoginManager.getInstance().logInWithPublishPermissions(
this,
Arrays.asList("publish_actions"));
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
System.out.println("About Login Successful!");
System.out.println("Logged in user Details : ");
System.out.println("--------------------------");
System.out.println("User ID : " + loginResult.getAccessToken().getUserId());
System.out.println("Authentication Token : " + loginResult.getAccessToken().getToken());
Toast.makeText(About.this, "Login Successful!", Toast.LENGTH_LONG).show();
shareAppToFacebook();
}
@Override
public void onCancel() {
Toast.makeText(About.this, "Login cancelled by user!", Toast.LENGTH_LONG).show();
System.out.println("About Login failed!!");
}
@Override
public void onError(FacebookException e) {
Toast.makeText(About.this, "Login unsuccessful!", Toast.LENGTH_LONG).show();
System.out.println("About Login failed!!");
}
});
twitterLoginButton = (TwitterLoginButton) findViewById(R.id.twitter_login_button);
twitterLoginButton.setCallback(new Callback<TwitterSession>() {
@Override
public void success(Result<TwitterSession> result) {
TwitterSession session = result.data;
String msg = "@" + session.getUserName() + " logged in! (#" + session.getUserId() + ")";
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
@Override
public void failure(TwitterException exception) {
Log.d("TwitterKit", "Login with Twitter failure", exception);
}
});
}
//Shares the application to facebook
private void shareAppToFacebook() {
Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.logo1);
SharePhoto photo = new SharePhoto.Builder()
.setBitmap(image)
.setCaption("Check out this cool new app!")
.build();
SharePhotoContent content = new SharePhotoContent.Builder()
.addPhoto(photo)
.build();
ShareApi.share(content, null);
}
//Retrieve the facebook required hashkey
public void getFbKeyHash(String packageName) {
try {
PackageInfo info = getPackageManager().getPackageInfo(
packageName,
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("YourKeyHash :", Base64.encodeToString(md.digest(), Base64.DEFAULT));
System.out.println("YourKeyHash: " + Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
@Override
protected void onActivityResult(int reqCode, int resCode, Intent i) {
super.onActivityResult(reqCode, resCode, i);
callbackManager.onActivityResult(reqCode, resCode, i);
twitterLoginButton.onActivityResult(reqCode, resCode, i);
}
}
<file_sep>package com.example.hungdo.myrecipe.Dish.InitialLaunch;
/**
* Created by sahithi on 10/13/2015.
* A simple license Agreement dialouge activity which starts as soon as the splash screen activity is done.
* Displays only one time after the user has agreed to the agreement. If the user agrees to the license agreement
* he can proceed with the application, otherwise if the user cancels it the application closes.
*/
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.preference.PreferenceManager;
import com.example.hungdo.myrecipe.R;
public class LicenseAgreement {
private String License = "eula_";
private Activity mActivity;
public LicenseAgreement(Activity context) {
mActivity = context;
}
private PackageInfo getPackageInfo() {
PackageInfo pi = null;
try {
pi = mActivity.getPackageManager().getPackageInfo(mActivity.getPackageName(), PackageManager.GET_ACTIVITIES);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return pi;
}
public void show() {
PackageInfo versionInfo = getPackageInfo();
// the license Key changes every time you increment the version number in the AndroidManifest.xml
final String LicenseKey = License + versionInfo.versionCode;
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mActivity);
boolean hasBeenShown = prefs.getBoolean(LicenseKey, false);
if (hasBeenShown == false) {
// Show the license agreement
String title = "Terms and Agreements" + " v" + versionInfo.versionName;
//Includes the updates as well so users know what changed.
String message = mActivity.getString(R.string.updates) + "\n\n" + mActivity.getString(R.string.Terms);
AlertDialog.Builder builder = new AlertDialog.Builder(mActivity)
.setTitle(title)
.setMessage(message)
.setPositiveButton("Accept", new Dialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// Mark this version as read.
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(LicenseKey, true);
editor.commit();
dialogInterface.dismiss();
}
})
.setNegativeButton("Decline", new Dialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Close the activity as they have declined the agreement
mActivity.finish();
}
})
.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
// Close the activity as they have declined the agreement
mActivity.finish();
}
});
builder.create().show();
}
}
}
<file_sep>
package com.example.hungdo.myrecipe.Dish.Content;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.view.Menu;
import android.view.MenuItem;
import com.example.hungdo.myrecipe.Dish.MainActivity;
import com.example.hungdo.myrecipe.R;
/**
* Created by Jay on 10/6/2015.
*/
public class Preferences extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new MyPreferenceFragment())
.commit();
}
public static class MyPreferenceFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
// Resets all settings1 to default
Preference resetPref = findPreference("reset_default");
resetPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getActivity().getBaseContext());
SharedPreferences.Editor editor = pref.edit();
editor.clear();
editor.commit();
// Refreshes activity
Intent intent = getActivity().getIntent();
getActivity().finish();
startActivity(intent);
return false;
}
});
Preference locationPref = findPreference("location_settings");
locationPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
return false;
}
});
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.action_about:
Intent aIntent = new Intent(this, About.class);
startActivity(aIntent);
return true;
case R.id.action_home:
Intent hIntent = new Intent(this, MainActivity.class);
startActivity(hIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
<file_sep>package com.example.hungdo.myrecipe.Dish.Adapters;
/**
* Created by HungDo on 12/5/2015.
*/
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.example.hungdo.myrecipe.Dish.Volley.AppController;
import com.example.hungdo.myrecipe.Dish.SQLite.RecipeData;
import com.example.hungdo.myrecipe.R;
//Custom List Adapter for the Favorites List View
public class CustomFavAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<RecipeData> receipDataItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomFavAdapter(Activity activity, List<RecipeData> receipDataItems) {
this.activity = activity;
this.receipDataItems = receipDataItems;
}
@Override
public int getCount() {
return receipDataItems.size();
}
@Override
public Object getItem(int location) {
return receipDataItems.get(location);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_row_fav, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);
//Title
TextView title = (TextView) convertView.findViewById(R.id.favtitle);
title.setTypeface(null, Typeface.BOLD);
//Publisher
TextView publisher = (TextView) convertView.findViewById(R.id.favpublisher);
//Get the recipe position
RecipeData recipe = receipDataItems.get(position);
//Set title
title.setText(recipe.getTitle());
//Load thumbnails
thumbNail.setImageUrl(recipe.getThumbnail(), imageLoader);
//Set publisher
publisher.setText("By:" + recipe.getPublisher());
return convertView;
}
}<file_sep>package com.example.hungdo.myrecipe.Dish;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import com.example.hungdo.myrecipe.Dish.Content.About;
import com.example.hungdo.myrecipe.Dish.Content.Favorites;
import com.example.hungdo.myrecipe.Dish.Content.Preferences;
import com.example.hungdo.myrecipe.Dish.Content.IngredientBank;
import com.example.hungdo.myrecipe.Dish.APIs.Nutrition;
import com.example.hungdo.myrecipe.Dish.Content.GoogleMaps.MapsActivity;
import com.example.hungdo.myrecipe.Dish.InitialLaunch.LicenseAgreement;
import com.example.hungdo.myrecipe.R;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new LicenseAgreement(this).show();
final ImageButton mapButton = (ImageButton) findViewById(R.id.FindStore);
final ImageButton getRecipe = (ImageButton) findViewById(R.id.getRecipe);
final ImageButton preferences = (ImageButton) findViewById(R.id.Preferences);
final ImageButton nutrition = (ImageButton) findViewById(R.id.Nutrition);
final ImageButton favourites = (ImageButton) findViewById(R.id.Favorites);
//Go to Google Maps
mapButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MapsActivity.class);
startActivity(intent);
}
});
//Go to find recipe
getRecipe.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, IngredientBank.class);
startActivity(intent);
}
});
//Go to preferences
preferences.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Preferences.class);
startActivity(intent);
}
});
//Go the nutrition search
nutrition.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Nutrition.class);
startActivity(intent);
}
});
//Go to favorites
favourites.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Favorites.class);
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_about) {
Intent aIntent = new Intent(this, About.class);
startActivity(aIntent);
return true;
}
switch (item.getItemId()) {
case R.id.action_about:
Intent aIntent = new Intent(this, About.class);
startActivity(aIntent);
return true;
case R.id.action_home:
Intent hIntent = new Intent(this, MainActivity.class);
startActivity(hIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
<file_sep>package com.example.hungdo.myrecipe.Dish.SQLite;
/**
* Created by HungDo on 11/24/15.
*/
public class RecipeData {
//private variables
int id;
String title;
String publisher;
String thumbnail;
// Empty constructor
public RecipeData() {
}
// constructor
public RecipeData(int id, String title, String publisher, String thumbnail) {
this.id = id;
this.title = title;
this.publisher = publisher;
this.thumbnail = thumbnail;
}
// constructor
public RecipeData(String title, String publisher, String thumbnail) {
this.title = title;
this.publisher = publisher;
this.thumbnail = thumbnail;
}
// getting ID
public int getID() {
return this.id;
}
// setting id
public void setID(int id) {
this.id = id;
}
// getting title
public String getTitle() {
return this.title;
}
// setting title
public void setTitle(String title) {
this.title = title;
}
// getting phone number
public String getPublisher() {
return this.publisher;
}
// setting phone number
public void setPublisher(String pub) {
this.publisher = pub;
}
public String getThumbnail() {
return this.thumbnail;
}
// setting title
public void setThumbnail(String tn) {
this.thumbnail = tn;
}
}
<file_sep>package com.example.hungdo.myrecipe.Dish.Adapters;
/**
* Created by HungDo on 12/3/2015.
*/
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.example.hungdo.myrecipe.Dish.APIs.RecipeObj;
import com.example.hungdo.myrecipe.R;
import java.util.List;
//Custom List Adapter for the Nutrition List View
public class CustomNutritionAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<RecipeObj> recipeItems;
public CustomNutritionAdapter(Activity activity, List<RecipeObj> recipeItems) {
this.activity = activity;
this.recipeItems = recipeItems;
}
@Override
public int getCount() {
return recipeItems.size();
}
@Override
public Object getItem(int location) {
return recipeItems.get(location);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_row_nutrition, null);
TextView item = (TextView) convertView.findViewById(R.id.item);
TextView brand = (TextView) convertView.findViewById(R.id.brand);
TextView calories = (TextView) convertView.findViewById(R.id.calories);
TextView fat = (TextView) convertView.findViewById(R.id.fat);
// getting nutrition data for the row
RecipeObj r = recipeItems.get(position);
// Item name
item.setText(r.getItemName());
// Brand Name
brand.setText("Brand: " + r.getBrandName());
// Calories
calories.setText("Calories: " + r.getCalories());
// Total Fat
fat.setText("Total Fat: " + r.getTotalFat());
return convertView;
}
}
<file_sep>package com.example.hungdo.myrecipe.Dish.APIs;
import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.hungdo.myrecipe.Dish.Adapters.CustomNutritionAdapter;
import com.example.hungdo.myrecipe.Dish.Volley.AppController;
import com.example.hungdo.myrecipe.Dish.Content.About;
import com.example.hungdo.myrecipe.Dish.MainActivity;
import com.example.hungdo.myrecipe.R;
import java.util.ArrayList;
import java.util.List;
public class NutritionRequest extends AppCompatActivity {
// Log tag
private static final String TAG = NutritionRequest.class.getSimpleName();
// Recipes json url
private ProgressDialog pDialog;
private final List<RecipeObj> NutritionRequest = new ArrayList<RecipeObj>();
private ListView listView;
private CustomNutritionAdapter adapter;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nutrition);
//Create Listview + Adapter
listView = (ListView) findViewById(R.id.list);
adapter = new CustomNutritionAdapter(this, NutritionRequest);
listView.setAdapter(adapter);
//JSON request to the Nutritionix API
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Method.GET, URL(), null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray arrProducts = response.getJSONArray("hits");
for (int i = 0; i < arrProducts.length(); i++) {
JSONObject productItem = (JSONObject) arrProducts.get(i);
JSONObject nutrition = productItem.getJSONObject("fields");
RecipeObj recipeObj = new RecipeObj();
recipeObj.setItemName(nutrition.getString("item_name"));
recipeObj.setBrandName(nutrition.getString("brand_name"));
recipeObj.setCalories(nutrition.getString("nf_calories"));
recipeObj.setTotalFat(nutrition.getString("nf_total_fat"));
NutritionRequest.add(recipeObj);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
//Add to the singleton requestQ
AppController.getInstance().addToRequestQueue(jsObjRequest);
}
@Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
//Tie all the necessary strings together and return the full url
public String URL() {
Intent intent = getIntent();
String message = intent.getStringExtra(Nutrition.EXTRA_MESSAGE);
return "https://api.nutritionix.com/v1_1/search/" + message + "?fields=item_name%2Citem_id%2Cbrand_name%2Cnf_calories%2Cnf_total_fat&appId=cb52127f&appKey=f8fdea6d4dfa6bed20322b038b965eda";
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
//Action Bar
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.action_about:
Intent aIntent = new Intent(this, About.class);
startActivity(aIntent);
return true;
case R.id.action_home:
Intent hIntent = new Intent(this, MainActivity.class);
startActivity(hIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
| e5e19279dad86eb4717b33b7e5d13fafdca71488 | [
"Markdown",
"Java"
] | 9 | Markdown | IamHungDo/Recipes-By-Ingredients-Android-Application | 0f417710d5543d08fe1506256460b7c0f2f84477 | 0f514b25110fc1829ac21f6e0856548945fec641 |
refs/heads/master | <file_sep>#include <iostream>
#include <cstdlib>
#include <bitset>
#include <string>
#include <vector>
#include <stack>
#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <ctime>
#ifndef PROBLEM_H
#define PROBLEM_H
#include "Node.h"
#include "Problem.h"
class Problem
{
public:
Problem(int sOfV, int K, int CC, const vector<char>& V, const vector<string>& str, const vector<vector<int> >& MatCos);
//~Problem();
Node* startNode() {return startnode;};
Node* goalNode(){return goalnode;};
const vector<string>& stringVector() const {return strings;};
const vector<int> characIndex() const {return charIndex;};
const int firstEst(); // gives trivial upper bound of initial input
const int pathCost(const Node& node1, const Node& node2) const; // returns edge cost for node1->node2 {adjacent nodes}
const int firstHst(const Node& node) const; // heuristic function, takes in current state indices
const int DPhst(const Node& node) const;
const vector<Node*> successors(Node* node); // returns nodes in sorted order of decreasing f(n)
void printSoln(vector<Node*> pathInReverse); // given path in reverse, start node missing
int getCost(char a, char b) const; // returns the matching cost for 2 characters
void printProblemDetails(); // prints all input data
private:
Node* startnode;
Node* goalnode;
int sizeOfVocab;
vector<char> vocab; // vector of characters in vocabulary
int noOfStrings; // number of strings
vector<string> strings; // vector of strings
vector<vector<int> > MC; // matching cost matrix
int CC; // conversion cost
vector<int> charIndex; // position of character in Vocab and MC
vector<int> strLengths; // lengths of strings
int maxStrLength; // length of longest string
vector<int> minAlphabetMC; // min matching cost for each alphabet and - {>0}
vector<vector<vector<vector<int> > > > DPsolvedMatrix; // DPsolve stored in DPsolvedMatrix[i][j] and [j][i]
const int matchingCost(const string& s1, const string& s2); // computes only matching cost (excludes CC), assumes sizes are the same
vector<vector<int> > DPsolve(const string& s1, const string& s2); // DP for every state
};
#endif<file_sep>#include <iostream>
#include <cstdlib>
#include <bitset>
#include <string>
#include <vector>
#include <stack>
#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <ctime>
#include <set>
#include <string>
#ifndef MAGICLOCALSEARCH_CPP
#define MAGICLOCALSEARCH_CPP
#include "Problem.h"
clock_t start;
void Problem::magicLocalSearch(int time)
{
int minDash = 0;
for (int i = 0; i<noOfStrings ; i++)
minDash += maxStrLength - strLengths[i];
int minDashCost = minDash*CC;
// initialization
int bestCostYet = firstEst();
vector<string> bestStateYet(noOfStrings);
for (int i = 0 ; i<noOfStrings ; i++)
{
bestStateYet[i] = strings[i];
for (int j = 0 ; j<maxStrLength-strings[i].length() ; j++)
bestStateYet[i] += '-';
}
for (int loopCount = 0 ; loopCount<5; loopCount++)
{
if (loopCount%1 == 0 and loopCount>0) cout << "loop count : " <<loopCount << endl;
vector<bool> stringPlaced(noOfStrings,false);
vector<int> stringPermutation(noOfStrings);
int j = 0;
while (j<noOfStrings) // look for a better way
{
int temp = rand() % noOfStrings;
if (stringPlaced[temp]==false)
{
stringPlaced[temp] = true;
stringPermutation[j] = temp;
j++;
}
}
vector<string> cur(noOfStrings);
for (int i = 0 ; i<noOfStrings ; i++)
cur[i] = strings[stringPermutation[i]];
// for (int i = 0 ; i<noOfStrings ; i++)
// cout << cur[i] << endl;
magic(cur, stringPermutation, 0, noOfStrings, 40 + min(60,loopCount*20));
int curCost = allMatchingCost(cur)+ minDashCost + (cur[0].length()-maxStrLength)*CC*noOfStrings;
if (curCost < bestCostYet)
{
vector<string> final(noOfStrings);
for (int i = 0 ; i<noOfStrings ; i++)
final[stringPermutation[i]] = cur[i];
bestStateYet = final;
bestCostYet = curCost;
cout << "Best cost yet : " << bestCostYet << " (" << bestStateYet[0].length() << ")" <<endl;
}
}
cout << endl;
for (int i = 0 ; i<noOfStrings ; i++)
cout << bestStateYet[i] << endl;
cout << bestCostYet << endl;
}
#endif
<file_sep>#include <iostream>
#include <fstream>
#include <cstdlib>
#include <time.h>
#include <vector>
using namespace std;
int alphabetsize= 4;
int numseq = 3;
int cc = 1;
int maxlength = 13;
int minlength = 13;
int maxcost = 3;
float _time = 10.0;
vector< vector<int> > mc;
int main(int argc , char** argv) { //generates a file of name argv[1]
fstream writer; //Create a writer.
writer.open(argv[1] , fstream::out);
writer << _time << "\n";
writer << alphabetsize << "\n";
//Write alphabets
for(int i = 'A' ; ((i<= (int)'Z') && ((i-'A')< alphabetsize-1 ) ); ++i) {
writer << (char)i << ", ";
}
if( alphabetsize > 26) {
for(int i = 'a' ; ((i<= (int)'z') && ((i-'a')< alphabetsize-26-1 )); ++i) {
writer << (char)i << ", ";
}
}
if(alphabetsize<=26)
writer << (char)('A' + alphabetsize-1);
else
writer << (char)('a' + alphabetsize-26-1);
writer << "\n";
writer << numseq << "\n";
//Writer Sequences;
srand(time(NULL));
for(int i=0; i<numseq; ++i) {
int length = minlength ; // + rand()%(maxlength-minlength)
if (alphabetsize>26) {
for(int i=0; i<length; ++i) {
int offset = rand()%(2*alphabetsize);
if( offset<= alphabetsize/2 ) {
char c = 'A' + offset;
writer << c;
} else {
char c = 'a' + offset-26;
writer << c;
}
}
} else {
for(int i=0; i<length; ++i) {
int offset = rand()%alphabetsize;
char c = 'A' + offset;
writer << c;
}
}
writer << "\n";
}
writer << cc << "\n";
//Write cost matrix.
//prepare vector of costs.
mc.resize(alphabetsize+1);
for(int i=0; i<mc.size(); i++) {
mc[i].resize(alphabetsize+1);
}
//Give values
// for(int r = 0; r<= alphabetsize; ++r) {
// for(int c=r; c<=alphabetsize; ++c) {
// mc[r][c] = (r==c)?(0):( 1 + rand()%(maxcost) );
// mc[c][r] = mc[r][c];
// }
// }
// Print out the matrix;
vector<vector<int> > myMC = {{0,3,3,3,1},{3,0,3,3,1},{3,3,0,3,1},{3,3,3,0,1},{1,1,1,1,0}};
mc = myMC;
for(int r=0; r<alphabetsize+1; ++r) {
for(int c= 0 ; c<alphabetsize+1; ++c) {
writer << mc[r][c] << " ";
}
writer << "\n";
}
mc.resize(0);
writer << "#\n";
writer.close();
return 0;
}<file_sep>#include <iostream>
#include <cstdlib>
#include <bitset>
#include <string>
#include <vector>
#include <stack>
#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <ctime>
#include <set>
#ifndef PROBLEM_H
#define PROBLEM_H
struct compare;
typedef std::multiset<vector<int> >::iterator sIt;
class Problem
{
public:
Problem(int sOfV, int K, int CC, const vector<char>& V, const vector<string>& str, const vector<vector<int> >& MatCos);
//~Problem();
const vector<string>& stringVector() const {return strings;};
const vector<int> characIndex() const {return charIndex;};
const int firstEst(); // gives trivial upper bound of initial input
//const int DPhst(const Node& node) const;
const int getCost(char a, char b) const; // returns the matching cost for 2 characters
//vector<string> hillClimb(vector<string>& vs, int l); // climbs hill for given input
void printProblemDetails(); // prints all input data
//void localSearch(int time); // in minutes, typically should run till t = time
void magicLocalSearch(int time);
void magic(vector<string>& vs, const vector<int>& orderArray, int start, int end, int loopCount);
private:
int sizeOfVocab;
vector<char> vocab; // vector of characters in vocabulary
int noOfStrings; // number of strings
vector<string> strings; // vector of strings
vector<vector<int> > MC; // matching cost matrix
int CC; // conversion cost
vector<int> charIndex; // position of character in Vocab and MC
vector<int> strLengths; // lengths of strings
int maxStrLength; // length of longest string
// vector<vector<vector<vector<int> > > > DPsolvedMatrix; // DPsolve stored in DPsolvedMatrix[i][j], i<j
vector<vector<pair<string,string> > > DPfinalString; // stores best soln from start state from DP
const int matchingCost(const string& s1, const string& s2); // computes only matching cost (excludes CC), assumes sizes are the same
pair<string,string> DPsolve(const string& s1, const string& s2); // final DP solution stored in DPfinalString
vector<string> randomStateGenerator(int size); // generates a random state of maxL <= size <= sum of lengths
// hill climbing helpers
const int columnCost(const vector<string>& vs , int i , int j, int col); // hillClimb helper, gives MC of jth alphabet of ith string with others of column col
const int columnCost(const vector<string>& vs , int i , int j, int col , int start, int end);
const int allMatchingCost(const vector<string>& vs);
const int allMatchingCost(const vector<string>& vs, int start, int finish);
friend struct compare;
static vector<vector<vector<int> > > dashCostMatrix;
static multiset<vector<int>, compare > dashSet;
void initialiseHillClimb(vector<string>& vs, int l, int start, int end);
sIt returnDashSetItr(vector<int> ijk);
void performSwap(vector<string>&vs, int l, int i, int j, int k, bool& leftSwap);
// magic helpers
void fitNewString(vector<string>& vs, const vector<int>& orderArray , int start, int end, int maxLength, int loopCount);
vector<string> informedRandomState(vector<string>& vs, const vector<int>& orderArray, int start, int end, int maxLength);
void blockAlign(vector<string>& cur, const vector<int>& orderArray, int start, int end, int length);
int magicHillClimb(vector<string>& vs, int start, int end);
};
#endif<file_sep>#include <iostream>
#include <cstdlib>
#include <bitset>
#include <string>
#include <vector>
#include <stack>
#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <ctime>
#ifndef PROBLEM_CPP
#define PROBLEM_CPP
#include "Problem.h"
using namespace std;
Problem::Problem(int sOfV, int Ks, int CCo, const vector<char>& V, const vector<string>& str, const vector<vector<int> >& MatCos)
{
charIndex = vector<int>(256,-1); //256 for each ASCII, initialised to -1 {error detection}
minAlphabetMC = vector<int>(sOfV+1);
sizeOfVocab = sOfV;
noOfStrings = Ks;
CC = CCo;
vocab = V;
strings = str;
MC = MatCos;
maxStrLength = 0;
DPsolvedMatrix = vector<vector<vector<vector<int> > > >(noOfStrings,vector<vector<vector<int> > >(noOfStrings, vector<vector<int> >()));
// char Index initialization
for (int i = 0 ; i <sizeOfVocab ; i++)
charIndex[(int)vocab[i]] = i;
charIndex[(int)('-')] = sizeOfVocab; // !
// strLengths and maxStrLength initialization
strLengths = vector<int>(noOfStrings);
for (int i = 0 ; i<noOfStrings ; i++)
{
strLengths[i] = strings[i].length();
if (strLengths[i]>maxStrLength)
maxStrLength = strLengths[i];
}
// minAlphabetMC initialization
for (int i = 0 ; i<=sizeOfVocab; i++) // <= because dash in the end
{
int curmin;
if (i!=sizeOfVocab) curmin = MC[i][i+1];
else curmin = MC[i][i-1];
for (int j = 0 ; j<=sizeOfVocab ; j++)
{
if (j!=i)
if (MC[i][j] < curmin) curmin = MC[i][j];
}
minAlphabetMC[i] = curmin;
}
//hillClimb(vector<string>{"-agcgcg--a--cg-tt-ag-ttagccagta-cg-cag-atatc","agt--tggca-ttacg-accca-tag-tta-c--atgcggg---","--attt-gcca-aattttgaccaga--ac-gat-catg-ca--a"},44);
/*
for (int i = 0 ; i<noOfStrings-1 ; i++)
for (int j = i+1 ; j<noOfStrings ; j++)
DPsolvedMatrix[i][j] = DPsolve(strings[i],strings[j]);
// startnode and goalnode initialization */
}
/*
const int Problem::DPhst(const Node& node) const
{
int dashes = 0; // for CC cost, total min number of dashes to be introduced
int maxLenRem = 0; // longest remaining string length
int h = 0; // heuristic value
for (int i = 0 ; i<noOfStrings ; i++)
if (strLengths[i]-node.stateIndices()[i] > maxLenRem)
maxLenRem = strLengths[i]-node.stateIndices()[i];
for (int i = 0 ; i<noOfStrings ; i++)
dashes += maxLenRem - (strLengths[i]-node.stateIndices()[i]);
h += CC*dashes;
for (int i = 0 ; i<noOfStrings-1 ; i++)
for (int j = i+1 ; j<noOfStrings ; j++)
h += DPsolvedMatrix[i][j][node.stateIndices()[i]][node.stateIndices()[j]];
return h;
} */
const int Problem::getCost(char a, char b) const
{
return MC[charIndex[(int)a]][charIndex[(int)b]];
}
const int Problem::firstEst() // try doing it heuristically
{
vector<string> tempStrings = strings;
int firstEstimate = 0;
for (int i=0; i<noOfStrings; i++) // substitute for k by no of strings
{
if (strings[i].length() < maxStrLength) // substitute for vec by vector of strings
{
int noOfDashes = maxStrLength - strings[i].length();
firstEstimate += CC * noOfDashes;
for (int j=0; j<noOfDashes ; j++)
tempStrings[i] += "-" ;
}
}
for (int i=0; i<noOfStrings-1; i++)
{
for (int j=i+1; j<noOfStrings; j++)
{
for (int k=0; k<maxStrLength; k++)
{
firstEstimate += getCost(tempStrings[i][k],tempStrings[j][k]);
//strings[i][k] and strings[j][k] matrix lookup
}
}
}
return firstEstimate;
}
vector<vector<int> > Problem::DPsolve(const string& s1, const string& s2) // [i][j] has (best soln - CC cost)
{
vector<vector<int> > nodeCost(s1.length()+1 , vector<int>(s2.length()+1)); // initially includes cost of dashes, remove before returning
vector<vector<int> > nodeDashes(s1.length()+1 , vector<int>(s2.length()+1)); // no of dashes in optimal solution, need to remove cost in the end
int CCeff = 0;
int x = s1.length(); // -------> y
int y = s2.length(); // |
nodeCost[x][y] = 0;
nodeDashes[x][y] = 0;
x--;
while (x>=0)
{
nodeDashes[x][y] = nodeDashes[x+1][y] + 1;
nodeCost[x][y] = nodeCost[x+1][y] + MC[charIndex[(int)s1[x]]][sizeOfVocab] + CCeff; // matching with dash
x--;
}
x = s1.length(); y--;
while (y>=0)
{
nodeDashes[x][y] = nodeDashes[x][y+1] + 1;
nodeCost[x][y] = nodeCost[x][y+1] + MC[charIndex[(int)s2[y]]][sizeOfVocab] + CCeff; // matching with dash
y--;
}
y = s2.length()-1 ; x--; // x = s1.length() - 1
while (x>=0)
{
while (y>=0)
{
int botNbr = nodeCost[x+1][y] + CCeff + MC[sizeOfVocab][charIndex[(int)s1[x]]]; //edge costs
int diagNbr = nodeCost[x+1][y+1] + MC[charIndex[(int)s2[y]]][charIndex[(int)s1[x]]];
int rightNbr = nodeCost[x][y+1] + CCeff + MC[sizeOfVocab][charIndex[(int)s2[y]]];
int minNgb = min(botNbr,min(diagNbr , rightNbr));
if (minNgb == botNbr)
{
nodeDashes[x][y] = nodeDashes[x+1][y] + 1;
nodeCost[x][y] = botNbr;
}
else if (minNgb == diagNbr)
{
nodeDashes[x][y] = nodeDashes[x+1][y+1];
nodeCost[x][y] = diagNbr;
}
else // == rightNbr
{
nodeDashes[x][y] = nodeDashes[x][y+1] + 1;
nodeCost[x][y] = rightNbr;
}
y--;
}
x--;
y = s2.length()-1;
}
for (int i = 0 ; i<s1.length()+1 ; i++)
for (int j = 0 ; j <s2.length()+1 ; j++)
nodeCost[i][j] -= CCeff*nodeDashes[i][j];
return nodeCost;
}
void Problem::printProblemDetails()
{
cout << "=========================== \n" ;
cout << "CC : " << CC << "\n";
cout << "noOfStrings : " << noOfStrings << "\n";
cout << "size of vocab : " << sizeOfVocab << "\n";
cout << "vocab : {";
for (vector<char>::iterator it = vocab.begin() ; it!=vocab.end() ; it++ )
cout << " " << *it << "(" << charIndex[(int)(*it)] << ")" << " " ;
cout << "} \n" ;
cout << "strings : ";
for (int i = 0 ; i<noOfStrings ; i++ )
cout << strings[i] << "[" << strLengths[i] << "]" << " " ;
cout << "\n";
cout << "MC matrix \n--------------------------- \n" ;
for (vector<vector<int> >::iterator it = MC.begin() ; it!=MC.end() ; it++ )
{
for (vector<int>::iterator itr = it->begin() ; itr!= it->end() ; itr++ )
cout << *itr << " ";
cout << "\n";
}
cout << "MC matrix \n--------------------------- \n" ;
cout << "min Alphabet wise MC : ";
for (vector<int>::iterator it = minAlphabetMC.begin() ; it!=minAlphabetMC.end() ; it++)
cout << *it << " ";
cout << "\n";
cout << "=========================== \n" ;
//cout << matchingCost(strings[0],strings[1]) << " " << matchingCost(strings[2],strings[1]) << " " << matchingCost(strings[0],strings[2]) <<endl;
}
const int Problem::matchingCost(const string& s1, const string& s2) //assumes lengths are same
{
int sum = 0;
for (int i = 0 ; i<s1.length() ; i++)
sum += MC[charIndex[(int)(s1.at(i))]][charIndex[(int)(s2.at(i))]];
return sum;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
vector<string> Problem::randomStateGenerator(int size)
{
vector<string> state(noOfStrings,string(size,'&')); // initialised strings with &
for (int i = 0 ; i<noOfStrings ; i++)
{
vector<bool> dashAt(size,false); // stores if dash has been introduced
int j = 0;
while (j<(size-strLengths[i])) // introduced dashes
{
int cur = rand() % size;
if (dashAt[cur]==false)
{
dashAt[cur] = true;
state[i][cur] = '-';
j++;
}
}
int k = 0; int l = 0;
while (k<strLengths[i])
{
if (state[i][l]=='&')
{
state[i][l] = strings[i][k];
k++;
}
l++;
}
}
// for (int i = 0 ; i<noOfStrings ; i++)
// cout << state[i] <<endl;
return state;
}
const int Problem::columnCost(const vector<string>& vs , int i , int j, int col)
{
int cost = 0;
for (int p = 0 ; p<noOfStrings ; p++)
if (p!=i)
cost += MC[charIndex[(int)vs[i][j]]][charIndex[(int)vs[p][col]]];
return cost;
}
const int Problem::allMatchingCost(const vector<string>& vs)
{
int cost = 0;
for (int i = 0 ; i<noOfStrings-1 ; i++)
for (int j = i+1 ; j<noOfStrings ; j++)
cost += matchingCost(vs[i],vs[j]);
return cost;
}
vector<string> Problem::hillClimb(vector<string> vs, int l) // all strings built up to length l
{
/* STRATEGY
* -------------------------------------------------
* Scan all dashes and see if moving left or right
* improves the cost at every step
* If it does, move to neighbour, else terminate */
vector<int> bestNgb(3); // store coordinates and whether left(0) or right(1) neighbour is best
int bestChangeYet; // the more negative, the better
int loopCount = 0; // book-keeping
int zeroCount = 0; // if plateau, then for cutoff
// cout << "Initial matching cost : " << allMatchingCost(vs) << endl;
// primitive now, initialise positions of dashes to look up in constant time
// modify only updated dashes, use a priority queue
while (true)
{
loopCount++;
bestChangeYet = 1; // if doesn't change, then stays positive
for (int i = 0 ; i<noOfStrings ; i++)
for (int j = 0 ; j<l ; j++)
if (vs[i][j] == '-')
{
if (j>0 and vs[i][j-1]!='-')
{
int curCost = columnCost(vs,i,j,j) + columnCost(vs,i,j-1,j-1);
int finCost = columnCost(vs,i,j,j-1) + columnCost(vs,i,j-1,j);
if (finCost - curCost < bestChangeYet)
{
bestChangeYet = finCost - curCost;
bestNgb[0] = i ; bestNgb[1] = j ; bestNgb[2] = 0;
}
}
if (j<l-1 and vs[i][j+1]!='-')
{
int curCost = columnCost(vs,i,j,j) + columnCost(vs,i,j+1,j+1);
int finCost = columnCost(vs,i,j,j+1) + columnCost(vs,i,j+1,j);
if (finCost - curCost < bestChangeYet)
{
bestChangeYet = finCost - curCost;
bestNgb[0] = i ; bestNgb[1] = j ; bestNgb[2] = 1;
}
}
}
if (bestChangeYet > 0 or zeroCount==200) break;
// for plateau
if (bestChangeYet == 0)
{
vector<vector<int> > zeroStateIndices; //[i][j][k] of all zero cost dash movements (k for left or right)
for (int i = 0 ; i<noOfStrings ; i++)
for (int j = 0 ; j<l ; j++)
if (vs[i][j] == '-')
{
if (j>0 and vs[i][j-1]!='-')
{
int curCost = columnCost(vs,i,j,j) + columnCost(vs,i,j-1,j-1);
int finCost = columnCost(vs,i,j,j-1) + columnCost(vs,i,j-1,j);
if (finCost == curCost) // zero state index
zeroStateIndices.push_back(vector<int>{i,j,0});
}
if (j<l-1 and vs[i][j+1]!='-')
{
int curCost = columnCost(vs,i,j,j) + columnCost(vs,i,j+1,j+1);
int finCost = columnCost(vs,i,j,j+1) + columnCost(vs,i,j+1,j);
if (finCost == curCost) // zero state index
zeroStateIndices.push_back(vector<int>{i,j,1});
}
}
zeroCount++;
int decide = rand() % zeroStateIndices.size();
bestNgb = zeroStateIndices[decide];
}
///// ^ for plateau
else zeroCount = 0; // implies crossed plateau
char temp = vs[bestNgb[0]][bestNgb[1]];
// swapping
if (bestNgb[2]==0)
{
vs[bestNgb[0]][bestNgb[1]] = vs[bestNgb[0]][bestNgb[1]-1];
vs[bestNgb[0]][bestNgb[1]-1] = temp;
}
else
{
vs[bestNgb[0]][bestNgb[1]] = vs[bestNgb[0]][bestNgb[1]+1];
vs[bestNgb[0]][bestNgb[1]+1] = temp;
}
// checking if column of dashes align
// bool check1 = true;
//bool check2 = true;
/*for (int q = 0 ; q<l ; q++)
if (vs[0][q]=='-')
{
for (int m = 1 ; m < noOfStrings ; m++)
{
if(vs[m][q]!='-')
{
check1 = false;
break;
}
}
if (check1 == true)
{for (int i = 0 ; i<noOfStrings ; i++)
cout << vs[i] << "\n";
check1=false;
cout<<" found you!!"<<endl;
break;
}
}
*/
}
//cout << loopCount << endl;
//for (int i = 0 ; i<noOfStrings ; i++)
// cout << vs[i] << "\n";
//cout << "Final matching cost : " << allMatchingCost(vs) << endl;
//cout << "Loop cout : " << loopCount << endl;
return vs;
}
void Problem::localSearch(int time)
{
int minDash = 0;
for (int i = 0; i<noOfStrings ; i++)
minDash += maxStrLength - strLengths[i];
int minDashCost = minDash*CC;
int bestCostYet = firstEst();
vector<string> bestStateYet;
for (int loopCount = 0 ; loopCount<100000; loopCount++)
{if (loopCount%500 == 0) {cout << loopCount <<endl;}
int decide = rand()%100;
if (decide < 30)
{
int size = (rand()%(((12*maxStrLength)/10)-maxStrLength))+maxStrLength;
vector<string> cur = randomStateGenerator(size);
// cout << "reset start cost: " << allMatchingCost(cur)+ minDashCost + (size-maxStrLength)*CC*noOfStrings << endl;
cur = hillClimb(cur,size);
int curCost = allMatchingCost(cur)+ minDashCost + (size-maxStrLength)*CC*noOfStrings;
if (curCost < bestCostYet)
{
bestStateYet = cur;
bestCostYet = curCost;
cout << "Best cost yet : " << bestCostYet << endl;
}
}
else if (decide < 80)
{
int size = (rand()%(((15*maxStrLength)/10)-(12*maxStrLength)/10))+((12*maxStrLength)/10);
vector<string> cur = randomStateGenerator(size);
// cout << "reset start cost: " << allMatchingCost(cur)+ minDashCost + (size-maxStrLength)*CC*noOfStrings << endl;
cur = hillClimb(cur,size);
int curCost = allMatchingCost(cur) + minDashCost + (size-maxStrLength)*CC*noOfStrings;
if (curCost < bestCostYet)
{
bestStateYet = cur;
bestCostYet = curCost;
cout << "Best cost yet : " << bestCostYet << endl;
}
}
else
{
int size = (rand()%(((17*maxStrLength)/10)-(15*maxStrLength)/10))+((15*maxStrLength)/10);
vector<string> cur = randomStateGenerator(size);
// cout << "reset start cost: " << allMatchingCost(cur)+ minDashCost + (size-maxStrLength)*CC*noOfStrings << endl;
cur = hillClimb(cur,size);
int curCost = allMatchingCost(cur) + minDashCost + (size-maxStrLength)*CC*noOfStrings;
if (curCost < bestCostYet)
{
bestStateYet = cur;
bestCostYet = curCost;
cout << "Best cost yet : " << bestCostYet << endl;
}
}
}
for (int i = 0 ; i<noOfStrings ; i++)
cout << bestStateYet[i] << endl;
cout << bestCostYet << endl;
}
#endif
<file_sep>#!/bin/bash
i=0
g++ -std=c++11 main.cpp -o hey
g++ -std=c++11 inputgenerator.cpp -o inputwali
while ( (($i < 30)) ); do
g++ -std=c++11 inputgenerator.cpp -o inputwali
./inputwali inputwala.txt
./hey < inputwala.txt
i=$[$i +1]
done<file_sep>#include <iostream>
#include <cstdlib>
#include <bitset>
#include <string>
#include <vector>
#include <stack>
#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <ctime>
#ifndef NODE_H
#define NODE_H
class Problem;
class Node
{
public:
Node(int noOfStrings, int sizeOfVocab, const Problem& p); // start Node constructor
Node(Node* par, vector<int> stateIndices, const Problem& p, int noOfStrings); // successor constructor
Node(const Node& rhs); // copy constructor for storing path (ONLY!)
Node(const vector<int> endStateIndices); // goal Node constructor
//~Node();
bool operator==(const Node& rhs) const; // only checks state indices
bool operator<(const Node& rhs) const;
Node* getParent(){return parent;}
const int path_cost() const {return pathcost;};
const int h() const {return hst;};
const vector<int>& stateIndices() const {return stIndices;};
const vector<vector<int> >& remainingChar() const {return remChar;};
const int counter(){return count;};
void incrementCounter(){count++;};
void printNodeDetails();
static int nodeCount ;
static int visitCount ;
private:
Node* parent;
int count;
int pathcost;
int hst; // heuristic
vector<int> stIndices; // k indices, ith string has been processed till index stIndices[i]
vector<vector<int> > remChar; // alphabet count in remaining strings
};
#endif<file_sep>#include <iostream>
#include <cstdlib>
#include <bitset>
#include <string>
#include <vector>
#include <stack>
#include <stdio.h>
using namespace std;
int main()
{
bitset<5> a = bitset<5>(13);
bitset<5> b = bitset<5>(12);
cout <<a <<endl;
cout << b <<endl;
bitset<5> c = a^b;
cout << c <<endl;
}<file_sep>#include <iostream>
#include <cstdlib>
#include <bitset>
#include <string>
#include <vector>
#include <stack>
#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <ctime>
#include <set>
#include <string>
#ifndef MAGIC_CPP
#define MAGIC_CPP
#include "Problem.h"
// do size for informedRandomState
// correct final order
// make it time bound
void Problem::blockAlign(vector<string>& cur, const vector<int>& orderArray, int start, int end, int length)
{
// need to align cur[end-1] with previous
int bestChangeYet;
int bestIndex;
int swapWithIndex;
while (true)
{
bestChangeYet = 0;
for (int i = 0 ; i<length ; i++)
if (cur[end-1][i] == '-')
{
int l = i; // move left
int r = i; // move right
while (l>=0 and cur[end-1][l] == '-') l--;
while (r<length and cur[end-1][r] == '-') r++;
if (l>=0)
{
int curCost = columnCost(cur,end-1,i,i,start,end) + columnCost(cur,end-1,l,l,start,end);
int finCost = columnCost(cur,end-1,i,l,start,end) + columnCost(cur,end-1,l,i,start,end);
if (finCost - curCost < bestChangeYet)
{
bestChangeYet = finCost - curCost;
bestIndex = i;
swapWithIndex = l;
}
}
if (r<length)
{
int curCost = columnCost(cur,end-1,i,i,start,end) + columnCost(cur,end-1,r,r,start,end);
int finCost = columnCost(cur,end-1,i,r,start,end) + columnCost(cur,end-1,r,i,start,end);
if (finCost - curCost < bestChangeYet)
{
bestChangeYet = finCost - curCost;
bestIndex = i;
swapWithIndex = r;
}
}
}
if (bestChangeYet >= 0) break;
else
{
char temp = cur[end-1][bestIndex];
cur[end-1][bestIndex] = cur[end-1][swapWithIndex];
cur[end-1][swapWithIndex] = temp;
}
}
}
vector<string> Problem::informedRandomState(vector<string>& cur, const vector<int>& orderArray, int start, int end, int maxLength)
{
// start with cur such that start...end-2 has same length
// cur[end-1] may have different length
// need to determine new size randomly
// for start...end-2 only introduce columns of dashes
int size; // determine a better one!!!!!
if ((((13*maxLength)/10)-maxLength) != 0 )
{size = (rand()%(((13*maxLength)/10)-maxLength))+maxLength;}
else
{size = (rand()%2 + maxLength);}
vector<string> state(noOfStrings,string(size,'&')); // initialised strings with &
vector<bool> dashAt(size,false); // stores if dash has been introduced
int j = 0;
while (j<(size-cur[start].length())) // introduced dashes for start...end-2 (column of dashes)
{
int temp = rand() % size;
if (dashAt[temp]==false)
{
dashAt[temp] = true;
for (int i = start; i<end-1 ; i++)
state[i][temp] = '-';
j++;
}
}
dashAt = vector<bool>(size,false);
j = 0;
while (j<(size-cur[end-1].length())) // introduced dashes for end-1
{
int temp = rand() % size;
if (dashAt[temp]==false)
{
dashAt[temp] = true;
state[end-1][temp] = '-';
j++;
}
}
for (int i = start ; i<end ; i++)
{
int k = 0; int l = 0;
while (k<cur[i].length())
{
if (state[i][l]=='&')
{
state[i][l] = cur[i][k];
k++;
}
l++;
}
}
// for (int i = 0 ; i<noOfStrings ; i++)
// cout << state[i] <<endl;
return state;
}
void Problem::fitNewString(vector<string>& vs, const vector<int>& orderArray , int start, int end, int maxLength, int loopCount)
{
// increase length, with upper bound
// can be proportional to end-start
// must be built to maxLength at least
int bestCostYet;
int minDashCost;
vector<string> bestStateYet;
for (int i = start; i<end ; i++)
minDashCost += (maxLength-vs[i].length())*CC;
// initialization
// cout << "========================" << endl;
// cout << "fitting " << end-start << "th string" << endl;
// for (int i = start ; i<end ; i++)
// cout << vs[i] << endl;
// cout << "========================" << endl << endl;
vector<string> cur = informedRandomState(vs,orderArray,start,end,maxLength); // inserts columns for (start,end-1) and randomizes dashes for string to be fit
// doesn't copy strings after end!
// cout << "=======================" << endl;
// cout << "randomised state" << endl;
// for (int i = start ; i<end ; i++)
// cout << cur[i] << endl;
// cout << "========================" << endl;
blockAlign(cur,orderArray,start,end,cur[start].length());
// cout << " block align done" << endl;
// for (int i = start ; i<end ; i++)
// cout << cur[i] << endl;
// cout << "====================" << endl << endl;
int finalLength = magicHillClimb(cur , start, end); // does a hill climb on cur, eliminates dashes and returns final length of strings
// cout << "hill climb done" << endl;
// for (int i = start ; i<end ; i++)
// cout << cur[i] << endl;
bestCostYet = allMatchingCost(cur, start, end) + minDashCost + (finalLength-maxLength)*CC*(end-start);
bestStateYet = cur;
for (int i = 0 ; i<loopCount ; i++)
{
vector<string> temp = informedRandomState(vs,orderArray,start,end,maxLength); // inserts columns for (start,end-1) and randomizes dashes for string to be fit
blockAlign(temp, orderArray,start,end, temp[start].length());
int finLength = magicHillClimb(temp , start, end); // does a hill climb on cur, eliminates dashes and returns final length of strings
int tempCost = allMatchingCost(temp, start, end) + minDashCost + (finLength-maxLength)*CC*(end-start);
if ( tempCost < bestCostYet)
{
bestCostYet = tempCost;
bestStateYet = temp;
}
}
for (int i = start; i<end ; i++)
vs[i] = bestStateYet[i];
}
void Problem::magic(vector<string>& vs, const vector<int>& orderArray , int start, int end, int loopCount)
{
// INVARIANT 1 :: at the end of the function, all the processed strings have the same lengths
if (end == start+2) // base case
{
int a = orderArray[start];
int b = orderArray[start+1];
pair<string,string> temp;
if (a<b) // caught this bug luckily!
{
temp = DPfinalString[a][b];
vs[start] = temp.first;
vs[start+1] = temp.second;
}
else
{
temp = DPfinalString[b][a];
vs[start] = temp.second;
vs[start+1] = temp.first;
}
// INVARIANT 1 HOLDS
cout << "performed magic on : " << (end-start) << " strings" << endl;
// for (int i = start ; i<end ; i++)
// cout << vs[i] << endl;
return;
}
else
{
magic(vs,orderArray,start,end-1,loopCount);
int maxLength = max(vs[end-1].length(),vs[end-2].length());
fitNewString(vs, orderArray, start, end, maxLength, loopCount); // all lengths are same now
cout << "performed magic on : " << (end-start) << " strings" << endl;
// for (int i = start ; i<end ; i++)
// cout << vs[i] << endl;
return;
}
}
#endif<file_sep>#include <iostream>
#include <cstdlib>
#include <bitset>
#include <string>
#include <vector>
#include <stack>
#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <ctime>
using namespace std;
// what if first est is soln?
#include "Node.h"
#include "Problem.h"
#include "Problem.cpp"
#include "Node.cpp"
void DFSbb(Problem& p) // DFS branch & bound implementation //!! duplicate checking??
{
/* initialise f(n) using rudimentary calculation
* work with a stack, insert in order of decreasing f(n) = g(n) + h(n)
* in loop while !empty, pop and delete only after second count
* remember shortest path yet
* if f(n) > f(n_curmin), pop & delete
* if StringMapProblem.goalTest(Node) then update shortest path and f(n)
* insert StringMapProblem.successors(Node) into stack in proper order */
int bestCostYet = p.firstEst();
vector<Node*>* bestPathYet = new vector<Node*>; //stores in reverse order, last node first {doesn't store first node} {separate storage}
stack<Node*> theStack;
theStack.push(p.startNode());
while (!theStack.empty())
{
Node* current = theStack.top();
current->incrementCounter(); // nodes have initial counter 0
if (current->counter() == 2) // seen twice, delete
{
theStack.pop();
delete current;
}
else if (*current == *p.goalNode()) // pop, update bestCostYet and bestPathYet
{
theStack.pop();
if (current->path_cost() < bestCostYet)
{
bestCostYet = current->path_cost();
//cout << "Best yet : " << bestCostYet <<endl;
for (vector<Node*>::iterator it = bestPathYet->begin() ; it != bestPathYet->end() ; it++) //cleaning up previous solution
delete *it;
bestPathYet->resize(0);
Node* temp = current;
while (!(*temp == *p.startNode()))
{
bestPathYet->push_back(new Node(*temp));
temp = temp->getParent();
}
}
delete current;
}
else //(current->counter() == 1) // insert kids if f(n) doesn't exceed bestCostYet
{
if (current->path_cost() + current->h() >= bestCostYet) // what if initial bestCostYet is best bestCostYet?
{
theStack.pop();
delete current;
}
else // push successors into stack, set parents to current
{
vector<Node*> temp = p.successors(current); // ASSERT: decreasing order of f(n)
for (vector<Node*>::iterator it = temp.begin() ; it != temp.end() ; it++)
{
theStack.push(*it);
//(*it)->parent = current;
}
}
}
}
// cout << "Nodes gen : " << Node::nodeCount <<endl;
// cout << bestCostYet << endl;
p.printSoln(*bestPathYet); // prints optimal solution
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int Node::nodeCount=0;
int main()
{
//std::bitset<4>(10);
//------------------------------- INPUT -------------------------------//
double timeInMin;
int sizeOfVocab, noOfStrings, CC;
scanf("%lf",&timeInMin);
scanf("%i",&sizeOfVocab);
vector<char> vocab;
string temp;
getline(cin,temp); //to read endline
getline(cin,temp);
for (string::iterator it = temp.begin() ; it!=temp.end() ; it++)
{
if ((char)(*it)!=',' and (char)(*it)!=' ')
vocab.push_back((char)(*it));
}
scanf("%i",&noOfStrings);
vector<string> strings;
getline(cin,temp); //to read endline
for (int i = 0 ; i<noOfStrings ; i++)
{
getline(cin,temp);
strings.push_back(temp);
}
scanf("%i",&CC);
vector<vector<int> > MC(sizeOfVocab+1 , vector<int>(sizeOfVocab+1));
for (int i = 0 ; i<sizeOfVocab+1 ; i++)
{
for (int j = 0 ; j<sizeOfVocab+1 ; j++)
{
int tem;
scanf("%i", &tem);
MC[i][j] = tem;
}
}
char end;
scanf("%c",&end); //reads endline char
scanf("%c",&end);
//-------------------------------------------------------------------------------//
clock_t start;
double diff;
start = clock();
// if (end == '#')
Problem* current = new Problem(sizeOfVocab,noOfStrings,CC,vocab,strings,MC);
//cout << "First est : " << current->firstEst() <<endl;
DFSbb(*current);
//diff = ( std::clock() - start ) / (double)CLOCKS_PER_SEC;
//cout<<"time taken: "<< diff <<" sec\n" <<"\n";
}<file_sep>#include <iostream>
#include <cstdlib>
#include <bitset>
#include <string>
#include <vector>
#include <stack>
#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <ctime>
#include <set>
#ifndef PROBENGINE_H
#define PROBENGINE_H
// it's the part that can make or break out Suboptimal Search
// it's the part that can learn
// it's our, very own. Probability Engine.
// macha de
class probEngine
{
public:
probEngine(const vector<int>& strLengths); // decide what else you need for input
const int nextSize(); // the prob distribution of this changes with time
void update(int length, int cost, int noOfLoops, ...?); // we throw new info after every iteration
void penalize(int initialLength, int finalLength, ...?); // if column of dashes from initial length, reduce it's probability
private:
vector<int> strLengths; // stores length of strings
};
// you could take initial info such as CC, cost matrix to create an initial prob distribution and modify it accordingly
// length also depends on how different lengths of strings are, i.e. if all are similar or very different. soch le.
// try to get a mathematically sound model
// only output is nextSize()
// add whatever you see fit
<file_sep>#include <iostream>
#include <cstdlib>
#include <bitset>
#include <string>
#include <vector>
#include <stack>
#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <ctime>
#include <set>
using namespace std;
// what if first est is soln?
#include "Problem.h"
#include "Problem.cpp"
#include "magic.cpp"
#include "magicHillClimb.cpp"
#include "magicLocalSearch.cpp"
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
vector<vector<vector<int> > > Problem::dashCostMatrix;
multiset<vector<int>, compare > Problem::dashSet;
int main()
{
//std::bitset<4>(10);
srand (time(0)); // something for randomness
//------------------------------- INPUT -------------------------------//
double timeInMin;
int sizeOfVocab, noOfStrings, CC;
scanf("%lf",&timeInMin);
scanf("%i",&sizeOfVocab);
vector<char> vocab;
string temp;
getline(cin,temp); //to read endline
getline(cin,temp);
for (string::iterator it = temp.begin() ; it!=temp.end() ; it++)
{
if ((char)(*it)!=',' and (char)(*it)!=' ')
vocab.push_back((char)(*it));
}
scanf("%i",&noOfStrings);
vector<string> strings;
getline(cin,temp); //to read endline
for (int i = 0 ; i<noOfStrings ; i++)
{
getline(cin,temp);
strings.push_back(temp);
}
scanf("%i",&CC);
vector<vector<int> > MC(sizeOfVocab+1 , vector<int>(sizeOfVocab+1));
for (int i = 0 ; i<sizeOfVocab+1 ; i++)
{
for (int j = 0 ; j<sizeOfVocab+1 ; j++)
{
int tem;
scanf("%i", &tem);
MC[i][j] = tem;
}
}
char end;
scanf("%c",&end); //reads endline char
scanf("%c",&end);
//-------------------------------------------------------------------------------//
clock_t start;
double diff;
start = clock();
// if (end == '#')
Problem* current = new Problem(sizeOfVocab,noOfStrings,CC,vocab,strings,MC);
cout << "First est : " << current->firstEst() <<endl;
current->magicLocalSearch(5);
diff = ( std::clock() - start ) / (double)CLOCKS_PER_SEC;
cout<<"time taken: "<< diff <<" sec\n" <<"\n";
}<file_sep>#include <iostream>
#include <cstdlib>
#include <bitset>
#include <string>
#include <vector>
#include <stack>
#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <ctime>
#include <set>
#include <string>
#ifndef MAGICHILLCLIMB_CPP
#define MAGICHILLCLIMB_CPP
#include "Problem.h"
int Problem::magicHillClimb(vector<string>& vs, int start, int end)
{
vector<int> best(3); // store coordinates and whether left(0) or right(1) neighbour is best
int bestChangeYet; // the more negative, the better
int loopCount = 0; // book-keeping
int zeroCount = 0; // if plateau, then for cutoff (initally 100)
int l = vs[start].length();
dashCostMatrix = vector<vector<vector<int> > >(noOfStrings , vector<vector<int> >(l, vector<int>(2,numeric_limits<int>::max())));
initialiseHillClimb(vs,l,start,end);
// for (int i = 0 ; i<noOfStrings ; i++)
// cout << vs[i] << endl;
//
// for (int i = 0 ; i<noOfStrings ; i++)
// {
// for (int j = 0 ; j<l ; j++)
// cout << setw(1) << "(" << dashCostMatrix[i][j][0] <<","<< dashCostMatrix[i][j][1] << ") " ;
//
// cout <<endl;
// }
// cout << "----------" << endl;
// for (set<vector<int> >::iterator it = dashSet.begin() ; it!=dashSet.end() ; it++)
// cout << (*it)[0]<<","<<(*it)[1]<<","<<(*it)[2] <<" ";
while (true)
{
loopCount++;
bestChangeYet = 1; // if doesn't change, then stays positive
best = *(dashSet.begin());
int curBestCost = dashCostMatrix[best[0]][best[1]][best[2]];
if (curBestCost > 0 or zeroCount==25) break;
// for plateau
if (curBestCost == 0)
{
vector<vector<int> > zeroStateIndices; //[i][j][k] of all zero cost dash movements (k for left or right)
//for all the zero wale neighbours
for (sIt it = dashSet.begin() ; it!= dashSet.end() ; it++) //iterator syntax
{
if (dashCostMatrix[(*it)[0]][(*it)[1]][(*it)[2]] == 0)
zeroStateIndices.push_back(*it);
else break;
}
zeroCount++;
int decide = rand() % zeroStateIndices.size();
best = zeroStateIndices[decide];
}
///// ^ for plateau /////
else zeroCount = 0; // implies crossed plateau
bool leftSwap = true; // to check what swapping has been done
performSwap(vs,l,best[0],best[1],best[2],leftSwap);
//////////////////////////////// updating dash costs in log(Nk) time {hopefully} ///////////////////////
int effX; // effective X component {3rd out of potentially 4 columns}
if (leftSwap == true) effX = best[1]; // | | |i| |
else effX = best[1]+1; // | |i| | | --> |.| |effX|.| { . => may or may not exist}
if (effX > 1)
for (int i = start ; i < end ; i++)
if (vs[i][effX-2] == '-')
{
vector<int> item = {i, effX-2 , 1};
set<vector<int> >::iterator it = returnDashSetItr(item);
if (it != dashSet.end()) // if doesn't exist, dashCostMatrix has infinite value, so goes down tree quickly
{
dashSet.erase(it);
int finCost = columnCost(vs, i, effX-2, effX-1, start, end) + columnCost(vs, i, effX-1, effX-2, start, end);
int curCost = columnCost(vs, i, effX-2, effX-2, start, end) + columnCost(vs, i, effX-1, effX-1, start, end);
dashCostMatrix[i][effX-2][1] = finCost - curCost;
item = {i, effX-2 , 1};
dashSet.insert(item);
}
}
if (effX < (l-1)) // 4th column exists
for (int i = start ; i < end ; i++)
if (vs[i][effX+1] == '-')
{
vector<int> item = {i, effX+1 , 0};
set<vector<int> >::iterator it = returnDashSetItr(item);
if (it != dashSet.end())
{
dashSet.erase(it);
int finCost = columnCost(vs, i, effX+1, effX, start, end) + columnCost(vs, i, effX, effX+1, start, end);
int curCost = columnCost(vs, i, effX, effX, start, end) + columnCost(vs, i, effX+1, effX+1, start, end);
dashCostMatrix[i][effX+1][0] = finCost - curCost;
item = {i, effX+1 , 0};
dashSet.insert(item);
}
}
// for both effX and effX-1 , need to update left and right move cost
for (int i = start ; i < end ; i++)
for (int j = effX-1 ; j<=effX ; j++)
if (vs[i][j] == '-')
{
if (!(j==effX and effX==(l-1)))
{
vector<int> right = {i,j,1};
set<vector<int> >::iterator itr = returnDashSetItr(right);
if (itr != dashSet.end())
{
dashSet.erase(itr);
int curRightCost = columnCost(vs, i, j, j, start, end) + columnCost(vs, i, j+1, j+1, start, end);
int finRightCost = columnCost(vs, i ,j, j+1, start, end) + columnCost(vs, i, j+1, j, start, end);
dashCostMatrix[i][j][1] = finRightCost - curRightCost ;
right = {i,j,1} ;
dashSet.insert(right);
}
}
if (!(j==effX-1 and j==0))
{
vector<int> left = {i,j,0};
set<vector<int> >::iterator itl = returnDashSetItr(left);
if (itl != dashSet.end())
{
dashSet.erase(itl);
int curLeftCost = columnCost(vs, i, j, j, start, end) + columnCost(vs, i, j-1, j-1, start, end);
int finLeftCost = columnCost(vs, i ,j, j-1, start, end) + columnCost(vs, i, j-1, j, start, end);
dashCostMatrix[i][j][0] = finLeftCost - curLeftCost ;
left = {i,j,0} ;
dashSet.insert(left) ;
}
}
}
////////////////////////////////// ^ updated dashes //////////////////////
}
// checking if column of dashes align, remove if they do
bool check1 = true;
vector<bool> isColumnOfDashes(l,false);
int colOfDashes = 0;
for (int q = 0 ; q<l ; q++)
if (vs[start][q]=='-')
{
check1 = true;
for (int m = start+1 ; m < end ; m++)
{
if(vs[m][q]!='-')
{
check1 = false;
break;
}
}
if (check1 == true)
{
// for (int i = 0 ; i<noOfStrings ; i++)
// cout << vs[i] << "\n";
// check1=false;
// cout<<" found you!! "<< l << endl;
// break;
isColumnOfDashes[q] = true;
colOfDashes ++ ;
}
}
if (colOfDashes!=0)
{
vector<string> dashRemovedStringVector(noOfStrings);
// for (int i = start ; i<end ; i++)
// cout << vs[i] << endl;
// cout << endl;
for (int i = 0 ; i<l ; i++)
if (!isColumnOfDashes[i])
for (int j = start ; j<end ; j++)
dashRemovedStringVector[j].push_back(vs[j][i]);
for (int i = start ; i<end ; i++)
vs[i] = dashRemovedStringVector[i];
// cout << "deleted you : " << vs[start].length() << endl;
//
// for (int i = start ; i<end ; i++)
// cout << vs[i] << endl;
// cout << endl;
}
dashSet.clear(); // make ready for next iteration
return vs[start].length();
}
#endif
<file_sep>#include <iostream>
#include <cstdlib>
#include <bitset>
#include <string>
#include <vector>
#include <stack>
#include <stdio.h>
#include <algorithm>
#include <cmath>
using namespace std;
// what if first est is soln?
class Problem;
class Node
{
public:
Node(int noOfStrings, int sizeOfVocab, const Problem& p); // start Node constructor
Node(Node* par, vector<int> stateIndices, const Problem& p, int noOfStrings); // successor constructor
Node(const Node& rhs); // copy constructor for storing path (ONLY!)
Node(const vector<int> endStateIndices); // goal Node constructor
~Node();
bool operator==(const Node& rhs); // only checks state indices
bool operator<(const Node& rhs);
Node* getParent(){return parent;}
const int path_cost() const {return pathcost;};
const int h() const {return hst;};
const vector<int>& stateIndices() const {return stIndices;};
const vector<vector<int> >& remainingChar() const {return remChar;};
const int counter(){return count;};
void incrementCounter(){count++;};
void printNodeDetails();
static int nodeCount ;
private:
Node* parent;
int count;
int pathcost;
int hst; // heuristic
vector<int> stIndices; // k indices, ith string has been processed till index stIndices[i]
vector<vector<int> > remChar; // alphabet count in remaining strings
};
class Problem
{
public:
Problem(int sOfV, int K, int CC, const vector<char>& V, const vector<string>& str, const vector<vector<int> >& MatCos);
//~Problem();
Node* startNode() {return startnode;};
Node* goalNode(){return goalnode;};
const vector<string>& stringVector() const {return strings;};
const vector<int> characIndex() const {return charIndex;};
const int firstEst(); // gives trivial upper bound of initial input
const int pathCost(const Node& node1, const Node& node2) const; // returns edge cost for node1->node2 {adjacent nodes}
const int firstHst(const Node& node) const; // heuristic function, takes in current state indices
const vector<Node*> successors(Node* node); // returns nodes in sorted order of decreasing f(n)
void printSoln(vector<Node*> pathInReverse); // given path in reverse, start node missing
int getCost(char a, char b) const; // returns the matching cost for 2 characters
void printProblemDetails(); // prints all input data
private:
Node* startnode;
Node* goalnode;
int sizeOfVocab;
vector<char> vocab; // vector of characters in vocabulary
int noOfStrings; // number of strings
vector<string> strings; // vector of strings
vector<vector<int> > MC; // matching cost matrix
int CC; // conversion cost
vector<int> charIndex; // position of character in Vocab and MC
vector<int> strLengths; // lengths of strings
int maxStrLength; // length of longest string
vector<int> minAlphabetMC; // min matching cost for each alphabet and - {>0}
const int matchingCost(const string& s1, const string& s2); // computes only matching cost (excludes CC), assumes sizes are the same
};
Node::Node(int noOfStrings, int sizeOfVocab, const Problem& p)
{
stIndices = vector<int>(noOfStrings,0);
count = 0;
pathcost = 0;
remChar = vector<vector<int> >(noOfStrings, vector<int>(sizeOfVocab));
for (int i = 0 ; i<noOfStrings ; i++)
{
string curr = p.stringVector()[i];
int l = curr.length();
for (int j = 0 ; j<l ; j++)
remChar[i][p.characIndex()[(int)curr[j]]]++;
}
nodeCount=1;
hst = p.firstHst(*this);
//printNodeDetails();
}
Node::Node(Node* par, vector<int> stateIndices, const Problem& p, int noOfStrings)
{
stIndices = stateIndices;
count = 0;
parent = par;
remChar = par->remainingChar();
for (int i=0 ; i<noOfStrings ; i++)
if (stIndices[i] - par->stateIndices()[i] == 1)
remChar[i][p.characIndex()[(int)p.stringVector()[i][stateIndices[i]-1]]]--;
pathcost = par->path_cost() + p.pathCost(*par,*this);
hst = p.firstHst(*this);
//printNodeDetails();
nodeCount++;
// if (nodeCount%100 == 0)
// cout << "Node count : " << nodeCount <<endl;
}
Node::Node(const Node& rhs)
{
pathcost = rhs.pathcost;
stIndices = rhs.stIndices;
count = 0;
hst = rhs.hst;
}
Node::Node(const vector<int> endStateIndices)
{
stIndices = endStateIndices;
}
void Node::printNodeDetails()
{
cout << "=========================== \n" ;
cout << "State indices : ";
for (vector<int>::iterator it = stIndices.begin() ; it!= stIndices.end() ; it++)
cout << *it << " ";
cout << "\n";
cout << "Path cost till Node : " << pathcost << endl;
cout << "Heuristic value : " << hst <<endl;
cout << "Rem char count : { ";
for (vector<vector<int> >::iterator it = remChar.begin() ; it!=remChar.end() ; it++)
{
cout << "( ";
for (vector<int>::iterator itr = it->begin(); itr!= it->end() ; itr++)
cout << *itr << " ";
cout << ") ";
}
cout << "} \n";
cout << "=========================== \n" ;
}
Node::~Node()
{nodeCount--;}
bool Node::operator==(const Node& rhs)
{
int len = stIndices.size();
for (int i = 0 ; i<len ; i++)
{
if (stIndices[i]!=rhs.stateIndices()[i])
return false;
}
return true;
}
bool Node::operator<(const Node& rhs)
{
return hst+pathcost < rhs.h() + rhs.path_cost();
}
Problem::Problem(int sOfV, int Ks, int CCo, const vector<char>& V, const vector<string>& str, const vector<vector<int> >& MatCos)
{
charIndex = vector<int>(256,-1); //256 for each ASCII, initialised to -1 {error detection}
minAlphabetMC = vector<int>(sOfV+1);
sizeOfVocab = sOfV;
noOfStrings = Ks;
CC = CCo;
vocab = V;
strings = str;
MC = MatCos;
maxStrLength = 0;
// char Index initialization
for (int i = 0 ; i <sizeOfVocab ; i++)
charIndex[(int)vocab[i]] = i;
charIndex[(int)('-')] = sizeOfVocab; // !
// strLengths and maxStrLength initialization
strLengths = vector<int>(noOfStrings);
for (int i = 0 ; i<noOfStrings ; i++)
{
strLengths[i] = strings[i].length();
if (strLengths[i]>maxStrLength)
maxStrLength = strLengths[i];
}
// minAlphabetMC initialization
for (int i = 0 ; i<=sizeOfVocab; i++) // <= because dash in the end
{
int curmin;
if (i!=sizeOfVocab) curmin = MC[i][i+1];
else curmin = MC[i][i-1];
for (int j = 0 ; j<=sizeOfVocab ; j++)
{
if (j!=i)
if (MC[i][j] < curmin) curmin = MC[i][j];
}
minAlphabetMC[i] = curmin;
}
// startnode and goalnode initialization
startnode = new Node(noOfStrings,sOfV,*this);
goalnode = new Node(strLengths);
}
const int Problem::pathCost(const Node& node1, const Node& node2) const
{
vector<int> tempStateIndex1 = node1.stateIndices();
vector<int> tempStateIndex2 = node2.stateIndices();
int pc = 0;
string changes = "";
for (int i=0; i<noOfStrings ;i++)
{
if (tempStateIndex2[i]-tempStateIndex1[i]==1)
{
changes +=strings[i][tempStateIndex1[i]]; //replace strings[i]
}
else
{
changes +="-";
pc += CC;
}
}
for (int i=0; i<noOfStrings-1; i++)
for (int j=i+1; j<noOfStrings; j++)
{
pc+= getCost(changes[i],changes[j]);
}
return pc;
}
const int Problem::firstHst(const Node& node) const // heurisitic
{
/* FIRST STRATEGY for heurisitic
* ---------------------------------------------------------------------------------------
* find the longest remaining string length
* at the very least, all other strings must be built up to that length
* calculate the corresponding number of dashes to be introduced
* now consider strings two at a time ( k C 2), find the diff in lengths
* we can assume that MC=0 for diagonal elements
* reduce common aphabets {4G in s1, 3G in s2 --> 1G in s1}
* take max(summation(min each apha for s1),summation(min each alpha for s2)
* ---------------------------------------------------------------------------------------*/
int dashes = 0; // for CC cost, total min number of dashes to be introduced
int maxLenRem = 0; // longest remaining string length
int h = 0; // heuristic value
for (int i = 0 ; i<noOfStrings ; i++)
if (strLengths[i]-node.stateIndices()[i] > maxLenRem)
maxLenRem = strLengths[i]-node.stateIndices()[i];
for (int i = 0 ; i<noOfStrings ; i++)
dashes += maxLenRem - (strLengths[i]-node.stateIndices()[i]);
h += CC*dashes;
for (int i = 0 ; i<noOfStrings-1 ; i++)
for (int j = i+1 ; j<noOfStrings ; j++) // state of indices (maxLenRem = 13)
if (!((strLengths[i]-node.stateIndices()[i] == 0) && (strLengths[j]-node.stateIndices()[j] == 0)))
{ // ----------------------------------
vector<int> remCharS1 = node.remainingChar()[i]; // { 1 , 5 , 4 } ->10
vector<int> remCharS2 = node.remainingChar()[j]; // { 1 , 3 , 7 } ->11
int sum1 = 0;
int sum2 = 0;
// { A , B , C , - }
remCharS1.push_back(maxLenRem - (strLengths[i]-node.stateIndices()[i])); // { 1 , 5 , 4 , 3 }
remCharS2.push_back(maxLenRem - (strLengths[j]-node.stateIndices()[j])); // { 1 , 3 , 7 , 2 }
for (int m = 0 ; m<sizeOfVocab+1 ; m++)
{ // reduced
if (remCharS1[m] > remCharS2[m]) // { 0 , 2 , 0 , 1 }
sum1 += (remCharS1[m] - remCharS2[m])*minAlphabetMC[m]; // { 0 , 0 , 3 , 0 }
else
sum2 += (remCharS2[m] - remCharS1[m])*minAlphabetMC[m];
}
h += max(sum1,sum2);
}
return h;
}
int Problem::getCost(char a, char b) const
{
return MC[charIndex[(int)a]][charIndex[(int)b]];
}
const int Problem::firstEst() // try doing it heuristically
{
vector<string> tempStrings = strings;
int firstEstimate = 0;
for (int i=0; i<noOfStrings; i++) // substitute for k by no of strings
{
if (strings[i].length() < maxStrLength) // substitute for vec by vector of strings
{
int noOfDashes = maxStrLength - strings[i].length();
firstEstimate += CC * noOfDashes;
for (int j=0; j<noOfDashes ; j++)
tempStrings[i] += "-" ;
}
}
for (int i=0; i<noOfStrings-1; i++)
{
for (int j=i+1; j<noOfStrings; j++)
{
for (int k=0; k<maxStrLength; k++)
{
firstEstimate += getCost(tempStrings[i][k],tempStrings[j][k]);
//strings[i][k] and strings[j][k] matrix lookup
}
}
}
return firstEstimate;
}
const vector<Node*> Problem::successors(Node* node)
{
vector<int> tempStateIndex = node->stateIndices();
int remStrings = 0 ;
vector<int> nonBounded;
vector<Node*> nodeSuccessors;
for (int j=0; j<noOfStrings; j++)
{
if (tempStateIndex[j] < strLengths[j])
{
remStrings++;
nonBounded.push_back(j);
}
}
for (int j=1; j<pow(2,remStrings); j++)
{
bitset<16> stateUpdater = bitset<16>(j);
for (int k=0; k<remStrings; k++)
{
tempStateIndex[nonBounded[k]]+= stateUpdater[k];
}
Node *tempNode = new Node(node, tempStateIndex, *this, noOfStrings);
nodeSuccessors.push_back(tempNode);
tempStateIndex = node->stateIndices();
}
sort(nodeSuccessors.begin() , nodeSuccessors.end());
reverse(nodeSuccessors.begin() , nodeSuccessors.end());
return nodeSuccessors;
}
void Problem::printSoln(vector<Node*> pathInReverse)
{
vector<int> initialIndex(noOfStrings,0);
vector<string> newstrings(noOfStrings,"");
//reverse(pathInReverse.begin(),pathInReverse.end());
int size=pathInReverse.size();
Node* temp;
for (int i=0;i<size/2;i++)
{
temp = pathInReverse[i];
pathInReverse[i] = pathInReverse[size-i-1];
pathInReverse[size-i-1] = temp;
}
for (int i=0 ; i<pathInReverse.size(); i++)
{
vector<int> finalIndex = pathInReverse[i]->stateIndices();
for (int j=0; j< noOfStrings; j++)
{
if (finalIndex[j] - initialIndex[j] == 1)
newstrings[j] += strings[j][initialIndex[j]];
else
newstrings[j] += "-";
}
initialIndex = finalIndex;
}
for (int i = 0 ; i<noOfStrings ; i++)
cout << newstrings[i] << endl;
}
void Problem::printProblemDetails()
{
cout << "=========================== \n" ;
cout << "CC : " << CC << "\n";
cout << "noOfStrings : " << noOfStrings << "\n";
cout << "size of vocab : " << sizeOfVocab << "\n";
cout << "vocab : {";
for (vector<char>::iterator it = vocab.begin() ; it!=vocab.end() ; it++ )
cout << " " << *it << "(" << charIndex[(int)(*it)] << ")" << " " ;
cout << "} \n" ;
cout << "strings : ";
for (int i = 0 ; i<noOfStrings ; i++ )
cout << strings[i] << "[" << strLengths[i] << "]" << " " ;
cout << "\n";
cout << "MC matrix \n--------------------------- \n" ;
for (vector<vector<int> >::iterator it = MC.begin() ; it!=MC.end() ; it++ )
{
for (vector<int>::iterator itr = it->begin() ; itr!= it->end() ; itr++ )
cout << *itr << " ";
cout << "\n";
}
cout << "MC matrix \n--------------------------- \n" ;
cout << "min Alphabet wise MC : ";
for (vector<int>::iterator it = minAlphabetMC.begin() ; it!=minAlphabetMC.end() ; it++)
cout << *it << " ";
cout << "\n";
cout << "=========================== \n" ;
//cout << matchingCost(strings[0],strings[1]) << " " << matchingCost(strings[2],strings[1]) << " " << matchingCost(strings[0],strings[2]) <<endl;
}
const int Problem::matchingCost(const string& s1, const string& s2) //assumes lengths are same
{
int sum = 0;
for (int i = 0 ; i<s1.length() ; i++)
sum += MC[charIndex[(int)(s1.at(i))]][charIndex[(int)(s2.at(i))]];
return sum;
}
void DFSbb(Problem& p) // DFS branch & bound implementation //!! duplicate checking??
{
/* initialise f(n) using rudimentary calculation
* work with a stack, insert in order of decreasing f(n) = g(n) + h(n)
* in loop while !empty, pop and delete only after second count
* remember shortest path yet
* if f(n) > f(n_curmin), pop & delete
* if StringMapProblem.goalTest(Node) then update shortest path and f(n)
* insert StringMapProblem.successors(Node) into stack in proper order */
int bestCostYet = p.firstEst();
vector<Node*>* bestPathYet = new vector<Node*>; //stores in reverse order, last node first {doesn't store first node} {separate storage}
stack<Node*> theStack;
theStack.push(p.startNode());
while (!theStack.empty())
{
Node* current = theStack.top();
current->incrementCounter(); // nodes have initial counter 0
if (current->counter() == 2) // seen twice, delete
{
theStack.pop();
delete current;
}
else if (*current == *p.goalNode()) // pop, update bestCostYet and bestPathYet
{
theStack.pop();
if (current->path_cost() < bestCostYet)
{
bestCostYet = current->path_cost();
cout << "Best yet : " << bestCostYet <<endl;
for (vector<Node*>::iterator it = bestPathYet->begin() ; it != bestPathYet->end() ; it++) //cleaning up previous solution
delete *it;
bestPathYet->resize(0);
Node* temp = current;
while (!(*temp == *p.startNode()))
{
bestPathYet->push_back(new Node(*temp));
temp = temp->getParent();
}
}
delete current;
}
else //(current->counter() == 1) // insert kids if f(n) doesn't exceed bestCostYet
{
if (current->path_cost() + current->h() >= bestCostYet) // what if initial bestCostYet is best bestCostYet?
{
theStack.pop();
delete current;
}
else // push successors into stack, set parents to current
{
vector<Node*> temp = p.successors(current); // ASSERT: decreasing order of f(n)
for (vector<Node*>::iterator it = temp.begin() ; it != temp.end() ; it++)
{
theStack.push(*it);
//(*it)->parent = current;
}
}
}
}
cout << bestCostYet << endl;
p.printSoln(*bestPathYet); // prints optimal solution
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int Node::nodeCount=0;
int main()
{
//std::bitset<4>(10);
//------------------------------- INPUT -------------------------------//
double timeInMin;
int sizeOfVocab, noOfStrings, CC;
scanf("%lf",&timeInMin);
scanf("%i",&sizeOfVocab);
vector<char> vocab;
string temp;
getline(cin,temp); //to read endline
getline(cin,temp);
for (string::iterator it = temp.begin() ; it!=temp.end() ; it++)
{
if ((char)(*it)!=',' and (char)(*it)!=' ')
vocab.push_back((char)(*it));
}
scanf("%i",&noOfStrings);
vector<string> strings;
getline(cin,temp); //to read endline
for (int i = 0 ; i<noOfStrings ; i++)
{
getline(cin,temp);
strings.push_back(temp);
}
scanf("%i",&CC);
vector<vector<int> > MC(sizeOfVocab+1 , vector<int>(sizeOfVocab+1));
for (int i = 0 ; i<sizeOfVocab+1 ; i++)
{
for (int j = 0 ; j<sizeOfVocab+1 ; j++)
{
int tem;
scanf("%i", &tem);
MC[i][j] = tem;
}
}
char end;
scanf("%c",&end); //reads endline char
scanf("%c",&end);
//-------------------------------------------------------------------------------//
// if (end == '#')
Problem* current = new Problem(sizeOfVocab,noOfStrings,CC,vocab,strings,MC);
//cout << "First est : " << current->firstEst() <<endl;
DFSbb(*current);
/*
vector<char> vocab = {'A','T'};
vector<string> strings = {"ATAA","TAT","TTTTTT"};
vector<vector<int> > MC = {{0,2,1},{2,0,1},{1,1,0}};
Problem* current = new Problem(2,3,3,vocab,strings,MC);
// Node(vector<int> stateIndices, int cost, const Problem& p); // successor constructor
//cout << current->firstEst() <<endl;
//Node* n1 = new Node(vector<int>{0,0,1},0,*current);
//Node* n2 = new Node(vector<int>{1,0,1},0,*current);
//Node* n3 = new Node(vector<int>{1,1,1},0,*current);
//vector<Node*> path = {n1,n2,n3,n4,n5,n6,n7,n8,n9};
//for (int i = 0 ; i<8 ; i++)
// cout << current->pathCost(*path[i],*path[i+1]) << " ";
vector<Node*> temp = current->successors(current->startNode());
for ( int i = 0 ; i<temp.size() ; i++)
temp[i]->printNodeDetails();
cout <<endl;*/
}
<file_sep>#include <iostream>
#include <cstdlib>
#include <bitset>
#include <string>
#include <vector>
#include <stack>
#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <ctime>
#ifndef NODE_CPP
#define NODE_CPP
#include "Node.h"
#include "Problem.h"
Node::Node(int noOfStrings, int sizeOfVocab, const Problem& p)
{
stIndices = vector<int>(noOfStrings,0);
count = 0;
pathcost = 0;
remChar = vector<vector<int> >(noOfStrings, vector<int>(sizeOfVocab));
for (int i = 0 ; i<noOfStrings ; i++)
{
string curr = p.stringVector()[i];
int l = curr.length();
//for (int j = 0 ; j<l ; j++)
// remChar[i][p.characIndex()[(int)curr[j]]]++;
}
nodeCount = 1;
hst = p.DPhst(*this);
//printNodeDetails();
}
Node::Node(Node* par, vector<int> stateIndices, const Problem& p, int noOfStrings)
{
stIndices = stateIndices;
count = 0;
parent = par;
//remChar = par->remainingChar();
//for (int i=0 ; i<noOfStrings ; i++)
// if (stIndices[i] - par->stateIndices()[i] == 1)
// remChar[i][p.characIndex()[(int)p.stringVector()[i][stateIndices[i]-1]]]--;
pathcost = par->path_cost() + p.pathCost(*par,*this);
hst = p.DPhst(*this);
//printNodeDetails();
nodeCount++;
// if (nodeCount>0 and nodeCount%5000 == 0)
// cout << "Node count : " << nodeCount <<endl;
}
Node::Node(const Node& rhs)
{
pathcost = rhs.pathcost;
stIndices = rhs.stIndices;
count = 0;
hst = rhs.hst;
}
Node::Node(const vector<int> endStateIndices)
{
stIndices = endStateIndices;
}
void Node::printNodeDetails()
{
cout << "=========================== \n" ;
cout << "State indices : ";
for (vector<int>::iterator it = stIndices.begin() ; it!= stIndices.end() ; it++)
cout << *it << " ";
cout << "\n";
cout << "Path cost till Node : " << pathcost << endl;
cout << "Heuristic value : " << hst <<endl;
cout << "Rem char count : { ";
for (vector<vector<int> >::iterator it = remChar.begin() ; it!=remChar.end() ; it++)
{
cout << "( ";
for (vector<int>::iterator itr = it->begin(); itr!= it->end() ; itr++)
cout << *itr << " ";
cout << ") ";
}
cout << "} \n";
cout << "=========================== \n" ;
}
//Node::~Node()
// {nodeCount--;}
bool Node::operator==(const Node& rhs) const
{
int len = stIndices.size();
for (int i = 0 ; i<len ; i++)
{
if (stIndices[i]!=rhs.stateIndices()[i])
return false;
}
return true;
}
bool Node::operator<(const Node& rhs) const
{
return hst+pathcost < rhs.h() + rhs.path_cost();
}
#endif<file_sep>#include <iostream>
#include <cstdlib>
#include <bitset>
#include <string>
#include <vector>
#include <stack>
#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <ctime>
#include <iomanip>
#ifndef PROBLEM_CPP
#define PROBLEM_CPP
#include "Node.h"
#include "Node.cpp"
#include "Problem.h"
using namespace std;
Problem::Problem(int sOfV, int Ks, int CCo, const vector<char>& V, const vector<string>& str, const vector<vector<int> >& MatCos)
{
charIndex = vector<int>(256,-1); //256 for each ASCII, initialised to -1 {error detection}
minAlphabetMC = vector<int>(sOfV+1);
sizeOfVocab = sOfV;
noOfStrings = Ks;
CC = CCo;
vocab = V;
strings = str;
MC = MatCos;
maxStrLength = 0;
DPsolvedMatrix = vector<vector<vector<vector<int> > > >(noOfStrings,vector<vector<vector<int> > >(noOfStrings, vector<vector<int> >()));
// char Index initialization
for (int i = 0 ; i <sizeOfVocab ; i++)
charIndex[(int)vocab[i]] = i;
charIndex[(int)('-')] = sizeOfVocab; // !
// strLengths and maxStrLength initialization
strLengths = vector<int>(noOfStrings);
for (int i = 0 ; i<noOfStrings ; i++)
{
strLengths[i] = strings[i].length();
if (strLengths[i]>maxStrLength)
maxStrLength = strLengths[i];
}
// minAlphabetMC initialization
for (int i = 0 ; i<=sizeOfVocab; i++) // <= because dash in the end
{
int curmin;
if (i!=sizeOfVocab) curmin = MC[i][i+1];
else curmin = MC[i][i-1];
for (int j = 0 ; j<=sizeOfVocab ; j++)
{
if (j!=i)
if (MC[i][j] < curmin) curmin = MC[i][j];
}
minAlphabetMC[i] = curmin;
}
for (int i = 0 ; i<noOfStrings-1 ; i++)
for (int j = i+1 ; j<noOfStrings ; j++)
DPsolvedMatrix[i][j] = DPsolve(strings[i],strings[j]);
// startnode and goalnode initialization
startnode = new Node(noOfStrings,sOfV,*this);
goalnode = new Node(strLengths);
// vector<vector<int> > lol = DPsolve(strings[0], strings[1]);
// for (int i = 0 ; i<strLengths[0]+1 ; i++)
// {
// for (int j = 0 ; j<strLengths[1]+1 ; j++)
// cout << setw(4) << lol[i][j] << " ";
// cout << endl;
// }
}
const int Problem::pathCost(const Node& node1, const Node& node2) const
{
vector<int> tempStateIndex1 = node1.stateIndices();
vector<int> tempStateIndex2 = node2.stateIndices();
int pc = 0;
string changes = "";
for (int i=0; i<noOfStrings ;i++)
{
if (tempStateIndex2[i]-tempStateIndex1[i]==1)
{
changes +=strings[i][tempStateIndex1[i]]; //replace strings[i]
}
else
{
changes +="-";
pc += CC;
}
}
for (int i=0; i<noOfStrings-1; i++)
for (int j=i+1; j<noOfStrings; j++)
{
pc+= getCost(changes[i],changes[j]);
}
return pc;
}
const int Problem::firstHst(const Node& node) const // heurisitic
{//return 0;
/* FIRST STRATEGY for heurisitic
* ---------------------------------------------------------------------------------------
* find the longest remaining string length
* at the very least, all other strings must be built up to that length
* calculate the corresponding number of dashes to be introduced
* now consider strings two at a time ( k C 2), find the diff in lengths
* we can assume that MC=0 for diagonal elements
* reduce common aphabets {4G in s1, 3G in s2 --> 1G in s1}
* take max(summation(min each apha for s1),summation(min each alpha for s2)
* ---------------------------------------------------------------------------------------*/
int dashes = 0; // for CC cost, total min number of dashes to be introduced
int maxLenRem = 0; // longest remaining string length
int h = 0; // heuristic value
for (int i = 0 ; i<noOfStrings ; i++)
if (strLengths[i]-node.stateIndices()[i] > maxLenRem)
maxLenRem = strLengths[i]-node.stateIndices()[i];
for (int i = 0 ; i<noOfStrings ; i++)
dashes += maxLenRem - (strLengths[i]-node.stateIndices()[i]);
h += CC*dashes;
for (int i = 0 ; i<noOfStrings-1 ; i++)
for (int j = i+1 ; j<noOfStrings ; j++) // state of indices (maxLenRem = 13)
if (!((strLengths[i]-node.stateIndices()[i] == 0) && (strLengths[j]-node.stateIndices()[j] == 0)))
{ // ----------------------------------
vector<int> remCharS1 = node.remainingChar()[i]; // { 1 , 5 , 4 } ->10
vector<int> remCharS2 = node.remainingChar()[j]; // { 1 , 3 , 7 } ->11
int sum1 = 0;
int sum2 = 0;
// { A , B , C , - }
remCharS1.push_back(maxLenRem - (strLengths[i]-node.stateIndices()[i])); // { 1 , 5 , 4 , 3 }
remCharS2.push_back(maxLenRem - (strLengths[j]-node.stateIndices()[j])); // { 1 , 3 , 7 , 2 }
for (int m = 0 ; m<sizeOfVocab+1 ; m++)
{ // reduced
if (remCharS1[m] > remCharS2[m]) // { 0 , 2 , 0 , 1 }
sum1 += (remCharS1[m] - remCharS2[m])*minAlphabetMC[m]; // { 0 , 0 , 3 , 0 }
else
sum2 += (remCharS2[m] - remCharS1[m])*minAlphabetMC[m];
}
h += max(sum1,sum2);
}
return h;
}
const int Problem::DPhst(const Node& node) const
{
int dashes = 0; // for CC cost, total min number of dashes to be introduced
int maxLenRem = 0; // longest remaining string length
int h = 0; // heuristic value
for (int i = 0 ; i<noOfStrings ; i++)
if (strLengths[i]-node.stateIndices()[i] > maxLenRem)
maxLenRem = strLengths[i]-node.stateIndices()[i];
for (int i = 0 ; i<noOfStrings ; i++)
dashes += maxLenRem - (strLengths[i]-node.stateIndices()[i]);
h += CC*dashes;
for (int i = 0 ; i<noOfStrings-1 ; i++)
for (int j = i+1 ; j<noOfStrings ; j++)
h += DPsolvedMatrix[i][j][node.stateIndices()[i]][node.stateIndices()[j]];
return h;
}
int Problem::getCost(char a, char b) const
{
return MC[charIndex[(int)a]][charIndex[(int)b]];
}
const int Problem::firstEst() // try doing it heuristically
{
vector<string> tempStrings = strings;
int firstEstimate = 0;
for (int i=0; i<noOfStrings; i++) // substitute for k by no of strings
{
if (strings[i].length() < maxStrLength) // substitute for vec by vector of strings
{
int noOfDashes = maxStrLength - strings[i].length();
firstEstimate += CC * noOfDashes;
for (int j=0; j<noOfDashes ; j++)
tempStrings[i] += "-" ;
}
}
for (int i=0; i<noOfStrings-1; i++)
{
for (int j=i+1; j<noOfStrings; j++)
{
for (int k=0; k<maxStrLength; k++)
{
firstEstimate += getCost(tempStrings[i][k],tempStrings[j][k]);
//strings[i][k] and strings[j][k] matrix lookup
}
}
}
return firstEstimate;
}
const vector<Node*> Problem::successors(Node* node)
{
vector<int> tempStateIndex = node->stateIndices();
int remStrings = 0 ;
vector<int> nonBounded;
vector<Node*> nodeSuccessors;
for (int j=0; j<noOfStrings; j++)
{
if (tempStateIndex[j] < strLengths[j])
{
remStrings++;
nonBounded.push_back(j);
}
}
for (int j=1; j<pow(2,remStrings); j++)
{
bitset<64> stateUpdater = bitset<64>(j);
for (int k=0; k<remStrings; k++)
{
tempStateIndex[nonBounded[k]]+= stateUpdater[k];
}
Node *tempNode = new Node(node, tempStateIndex, *this, noOfStrings);
nodeSuccessors.push_back(tempNode);
tempStateIndex = node->stateIndices();
}
sort(nodeSuccessors.begin() , nodeSuccessors.end(), [](Node* a, Node* b){return a->path_cost() + a->h() > b->path_cost() + b->h();}); // for decreasing order
/*
for (int i = 0 ; i<nodeSuccessors.size()-1 ; i++)
{
int tem = nodeSuccessors[i]->h();
cout << "Node h(n) : " << tem << endl;
}
cout << "xxxxxxxxxxxxxxxxxxx" <<endl; */
return nodeSuccessors;
}
void Problem::printSoln(vector<Node*> pathInReverse)
{
vector<int> initialIndex(noOfStrings,0);
vector<string> newstrings(noOfStrings,"");
//reverse(pathInReverse.begin(),pathInReverse.end());
int size=pathInReverse.size();
if (size==0) // first estimate is actual solution
{
for (int i = 0 ; i<noOfStrings ; i++)
{
for (int j = 0 ; j<strLengths[i] ; j++)
newstrings[i] += strings[i][j];
for (int j = 0 ; j<maxStrLength-strLengths[i] ; j++)
newstrings[i] += '-';
}
}
else
{
Node* temp;
for (int i=0;i<size/2;i++)
{
temp = pathInReverse[i];
pathInReverse[i] = pathInReverse[size-i-1];
pathInReverse[size-i-1] = temp;
}
for (int i=0 ; i<pathInReverse.size(); i++)
{
vector<int> finalIndex = pathInReverse[i]->stateIndices();
for (int j=0; j< noOfStrings; j++)
{
if (finalIndex[j] - initialIndex[j] == 1)
newstrings[j] += strings[j][initialIndex[j]];
else
newstrings[j] += "-";
}
initialIndex = finalIndex;
}
}
for (int i = 0 ; i<noOfStrings ; i++)
cout << newstrings[i] << endl;
}
vector<vector<int> > Problem::DPsolve(const string& s1, const string& s2) // [i][j] has (best soln - CC cost)
{
vector<vector<int> > nodeCost(s1.length()+1 , vector<int>(s2.length()+1)); // initially includes cost of dashes, remove before returning
vector<vector<int> > nodeDashes(s1.length()+1 , vector<int>(s2.length()+1)); // no of dashes in optimal solution, need to remove cost in the end
int CCeff = 0;
int x = s1.length(); // -------> y
int y = s2.length(); // |
nodeCost[x][y] = 0;
nodeDashes[x][y] = 0;
x--;
while (x>=0)
{
nodeDashes[x][y] = nodeDashes[x+1][y] + 1;
nodeCost[x][y] = nodeCost[x+1][y] + MC[charIndex[(int)s1[x]]][sizeOfVocab] + CCeff; // matching with dash
x--;
}
x = s1.length(); y--;
while (y>=0)
{
nodeDashes[x][y] = nodeDashes[x][y+1] + 1;
nodeCost[x][y] = nodeCost[x][y+1] + MC[charIndex[(int)s2[y]]][sizeOfVocab] + CCeff; // matching with dash
y--;
}
y = s2.length()-1 ; x--; // x = s1.length() - 1
while (x>=0)
{
while (y>=0)
{
int botNbr = nodeCost[x+1][y] + CCeff + MC[sizeOfVocab][charIndex[(int)s1[x]]]; //edge costs
int diagNbr = nodeCost[x+1][y+1] + MC[charIndex[(int)s2[y]]][charIndex[(int)s1[x]]];
int rightNbr = nodeCost[x][y+1] + CCeff + MC[sizeOfVocab][charIndex[(int)s2[y]]];
int minNgb = min(botNbr,min(diagNbr , rightNbr));
if (minNgb == botNbr)
{
nodeDashes[x][y] = nodeDashes[x+1][y] + 1;
nodeCost[x][y] = botNbr;
}
else if (minNgb == diagNbr)
{
nodeDashes[x][y] = nodeDashes[x+1][y+1];
nodeCost[x][y] = diagNbr;
}
else // == rightNbr
{
nodeDashes[x][y] = nodeDashes[x][y+1] + 1;
nodeCost[x][y] = rightNbr;
}
y--;
}
x--;
y = s2.length()-1;
}
for (int i = 0 ; i<s1.length()+1 ; i++)
for (int j = 0 ; j <s2.length()+1 ; j++)
nodeCost[i][j] -= CCeff*nodeDashes[i][j];
return nodeCost;
}
void Problem::printProblemDetails()
{
cout << "=========================== \n" ;
cout << "CC : " << CC << "\n";
cout << "noOfStrings : " << noOfStrings << "\n";
cout << "size of vocab : " << sizeOfVocab << "\n";
cout << "vocab : {";
for (vector<char>::iterator it = vocab.begin() ; it!=vocab.end() ; it++ )
cout << " " << *it << "(" << charIndex[(int)(*it)] << ")" << " " ;
cout << "} \n" ;
cout << "strings : ";
for (int i = 0 ; i<noOfStrings ; i++ )
cout << strings[i] << "[" << strLengths[i] << "]" << " " ;
cout << "\n";
cout << "MC matrix \n--------------------------- \n" ;
for (vector<vector<int> >::iterator it = MC.begin() ; it!=MC.end() ; it++ )
{
for (vector<int>::iterator itr = it->begin() ; itr!= it->end() ; itr++ )
cout << *itr << " ";
cout << "\n";
}
cout << "MC matrix \n--------------------------- \n" ;
cout << "min Alphabet wise MC : ";
for (vector<int>::iterator it = minAlphabetMC.begin() ; it!=minAlphabetMC.end() ; it++)
cout << *it << " ";
cout << "\n";
cout << "=========================== \n" ;
//cout << matchingCost(strings[0],strings[1]) << " " << matchingCost(strings[2],strings[1]) << " " << matchingCost(strings[0],strings[2]) <<endl;
}
const int Problem::matchingCost(const string& s1, const string& s2) //assumes lengths are same
{
int sum = 0;
for (int i = 0 ; i<s1.length() ; i++)
sum += MC[charIndex[(int)(s1.at(i))]][charIndex[(int)(s2.at(i))]];
return sum;
}
#endif
<file_sep>#include <iostream>
#include <cstdlib>
#include <bitset>
#include <string>
#include <vector>
#include <stack>
#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <ctime>
#include <set>
#include <limits>
#include <iomanip>
#ifndef PROBLEM_CPP
#define PROBLEM_CPP
#include "Problem.h"
using namespace std;
// need to fix if initial state is best state
Problem::Problem(int sOfV, int Ks, int CCo, const vector<char>& V, const vector<string>& str, const vector<vector<int> >& MatCos)
{
charIndex = vector<int>(256,-1); //256 for each ASCII, initialised to -1 {error detection}
sizeOfVocab = sOfV;
noOfStrings = Ks;
CC = CCo;
vocab = V;
strings = str;
MC = MatCos;
maxStrLength = 0;
DPsolvedMatrix = vector<vector<vector<vector<int> > > >(noOfStrings,vector<vector<vector<int> > >(noOfStrings, vector<vector<int> >()));
// char Index initialization
for (int i = 0 ; i <sizeOfVocab ; i++)
charIndex[(int)vocab[i]] = i;
charIndex[(int)('-')] = sizeOfVocab; // !
// strLengths and maxStrLength initialization
strLengths = vector<int>(noOfStrings);
for (int i = 0 ; i<noOfStrings ; i++)
{
strLengths[i] = strings[i].length();
if (strLengths[i]>maxStrLength)
maxStrLength = strLengths[i];
}
// hillClimb(vector<string>{"caagtagtcc","g-ata-accg","-cccgat-ta"},10);
/*
for (int i = 0 ; i<noOfStrings-1 ; i++)
for (int j = i+1 ; j<noOfStrings ; j++)
DPsolvedMatrix[i][j] = DPsolve(strings[i],strings[j]);
// startnode and goalnode initialization */
}
/*
const int Problem::DPhst(const Node& node) const
{
int dashes = 0; // for CC cost, total min number of dashes to be introduced
int maxLenRem = 0; // longest remaining string length
int h = 0; // heuristic value
for (int i = 0 ; i<noOfStrings ; i++)
if (strLengths[i]-node.stateIndices()[i] > maxLenRem)
maxLenRem = strLengths[i]-node.stateIndices()[i];
for (int i = 0 ; i<noOfStrings ; i++)
dashes += maxLenRem - (strLengths[i]-node.stateIndices()[i]);
h += CC*dashes;
for (int i = 0 ; i<noOfStrings-1 ; i++)
for (int j = i+1 ; j<noOfStrings ; j++)
h += DPsolvedMatrix[i][j][node.stateIndices()[i]][node.stateIndices()[j]];
return h;
} */
const int Problem::getCost(char a, char b) const
{
return MC[charIndex[(int)a]][charIndex[(int)b]];
}
const int Problem::firstEst()
{
vector<string> tempStrings = strings;
int firstEstimate = 0;
for (int i=0; i<noOfStrings; i++) // substitute for k by no of strings
{
if (strings[i].length() < maxStrLength) // substitute for vec by vector of strings
{
int noOfDashes = maxStrLength - strings[i].length();
firstEstimate += CC * noOfDashes;
for (int j=0; j<noOfDashes ; j++)
tempStrings[i] += "-" ;
}
}
for (int i=0; i<noOfStrings-1; i++)
{
for (int j=i+1; j<noOfStrings; j++)
{
for (int k=0; k<maxStrLength; k++)
{
firstEstimate += getCost(tempStrings[i][k],tempStrings[j][k]);
//strings[i][k] and strings[j][k] matrix lookup
}
}
}
return firstEstimate;
}
/*
vector<vector<int> > Problem::DPsolve(const string& s1, const string& s2) // [i][j] has (best soln - CC cost)
{
vector<vector<int> > nodeCost(s1.length()+1 , vector<int>(s2.length()+1)); // initially includes cost of dashes, remove before returning
vector<vector<int> > nodeDashes(s1.length()+1 , vector<int>(s2.length()+1)); // no of dashes in optimal solution, need to remove cost in the end
int CCeff = 0;
int x = s1.length(); // -------> y
int y = s2.length(); // |
nodeCost[x][y] = 0;
nodeDashes[x][y] = 0;
x--;
while (x>=0)
{
nodeDashes[x][y] = nodeDashes[x+1][y] + 1;
nodeCost[x][y] = nodeCost[x+1][y] + MC[charIndex[(int)s1[x]]][sizeOfVocab] + CCeff; // matching with dash
x--;
}
x = s1.length(); y--;
while (y>=0)
{
nodeDashes[x][y] = nodeDashes[x][y+1] + 1;
nodeCost[x][y] = nodeCost[x][y+1] + MC[charIndex[(int)s2[y]]][sizeOfVocab] + CCeff; // matching with dash
y--;
}
y = s2.length()-1 ; x--; // x = s1.length() - 1
while (x>=0)
{
while (y>=0)
{
int botNbr = nodeCost[x+1][y] + CCeff + MC[sizeOfVocab][charIndex[(int)s1[x]]]; //edge costs
int diagNbr = nodeCost[x+1][y+1] + MC[charIndex[(int)s2[y]]][charIndex[(int)s1[x]]];
int rightNbr = nodeCost[x][y+1] + CCeff + MC[sizeOfVocab][charIndex[(int)s2[y]]];
int minNgb = min(botNbr,min(diagNbr , rightNbr));
if (minNgb == botNbr)
{
nodeDashes[x][y] = nodeDashes[x+1][y] + 1;
nodeCost[x][y] = botNbr;
}
else if (minNgb == diagNbr)
{
nodeDashes[x][y] = nodeDashes[x+1][y+1];
nodeCost[x][y] = diagNbr;
}
else // == rightNbr
{
nodeDashes[x][y] = nodeDashes[x][y+1] + 1;
nodeCost[x][y] = rightNbr;
}
y--;
}
x--;
y = s2.length()-1;
}
for (int i = 0 ; i<s1.length()+1 ; i++)
for (int j = 0 ; j <s2.length()+1 ; j++)
nodeCost[i][j] -= CCeff*nodeDashes[i][j];
return nodeCost;
}
*/
void Problem::printProblemDetails()
{
cout << "=========================== \n" ;
cout << "CC : " << CC << "\n";
cout << "noOfStrings : " << noOfStrings << "\n";
cout << "size of vocab : " << sizeOfVocab << "\n";
cout << "vocab : {";
for (vector<char>::iterator it = vocab.begin() ; it!=vocab.end() ; it++ )
cout << " " << *it << "(" << charIndex[(int)(*it)] << ")" << " " ;
cout << "} \n" ;
cout << "strings : ";
for (int i = 0 ; i<noOfStrings ; i++ )
cout << strings[i] << "[" << strLengths[i] << "]" << " " ;
cout << "\n";
cout << "MC matrix \n--------------------------- \n" ;
for (vector<vector<int> >::iterator it = MC.begin() ; it!=MC.end() ; it++ )
{
for (vector<int>::iterator itr = it->begin() ; itr!= it->end() ; itr++ )
cout << *itr << " ";
cout << "\n";
}
cout << "MC matrix \n--------------------------- \n" ;
cout << "\n";
cout << "=========================== \n" ;
//cout << matchingCost(strings[0],strings[1]) << " " << matchingCost(strings[2],strings[1]) << " " << matchingCost(strings[0],strings[2]) <<endl;
}
const int Problem::matchingCost(const string& s1, const string& s2) //assumes lengths are same
{
int sum = 0;
for (int i = 0 ; i<s1.length() ; i++)
sum += MC[charIndex[(int)(s1.at(i))]][charIndex[(int)(s2.at(i))]];
return sum;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
vector<string> Problem::randomStateGenerator(int size)
{
vector<string> state(noOfStrings,string(size,'&')); // initialised strings with &
for (int i = 0 ; i<noOfStrings ; i++)
{
vector<bool> dashAt(size,false); // stores if dash has been introduced
int j = 0;
while (j<(size-strLengths[i])) // introduced dashes
{
int cur = rand() % size;
if (dashAt[cur]==false)
{
dashAt[cur] = true;
state[i][cur] = '-';
j++;
}
}
int k = 0; int l = 0;
while (k<strLengths[i])
{
if (state[i][l]=='&')
{
state[i][l] = strings[i][k];
k++;
}
l++;
}
}
// for (int i = 0 ; i<noOfStrings ; i++)
// cout << state[i] <<endl;
return state;
}
///////////////// HILL CLIMB HELPERS ////////////////
const int Problem::columnCost(const vector<string>& vs , int i , int j, int col, int start, int end)
{
int cost = 0;
for (int p = start ; p<end+1 ; p++)
if (p!=i)
cost += MC[charIndex[(int)vs[i][j]]][charIndex[(int)vs[p][col]]];
return cost;
}
const int Problem::allMatchingCost(const vector<string>& vs)
{
int cost = 0;
for (int i = 0 ; i<noOfStrings-1 ; i++)
for (int j = i+1 ; j<noOfStrings ; j++)
cost += matchingCost(vs[i],vs[j]);
return cost;
}
struct compare
{
bool operator() (const vector<int>& lhs, const vector<int>&rhs)
{
return (Problem::dashCostMatrix[lhs[0]][lhs[1]][lhs[2]] < Problem::dashCostMatrix[rhs[0]][rhs[1]][rhs[2]]);
}
};
//////////////////////////////////////////////////////////////
void Problem::initialiseHillClimb(vector<string>& vs, int l, int start, int end)
{
for (int i = start ; i<end+1 ; i++)
for (int j = 0 ; j<l ; j++)
if (vs[i][j] == '-')
{
// for left swap {if not possible, then is infty becasue of initialisation}
if (!(j==0 or vs[i][j-1]=='-'))
{
int curCost = columnCost(vs,i,j,j,start,end) + columnCost(vs,i,j-1,j-1,start,end);
int finCost = columnCost(vs,i,j,j-1,start,end) + columnCost(vs,i,j-1,j,start,end);
dashCostMatrix[i][j][0] = finCost - curCost; //cout << dashCostMatrix[i][j][0] <<endl;
vector<int> cur = {i,j,0};
dashSet.insert(cur);
}
// for right swap {if not possible, then is infty becasue of initialisation}
if (!(j==l-1 or vs[i][j+1]=='-'))
{
int curCost = columnCost(vs,i,j,j,start,end) + columnCost(vs,i,j+1,j+1,start,end);
int finCost = columnCost(vs,i,j,j+1,start,end) + columnCost(vs,i,j+1,j,start,end);
dashCostMatrix[i][j][1] = finCost - curCost; //cout << dashCostMatrix[i][j][1] << endl;
vector<int> cur = {i,j,1};
dashSet.insert(cur);
}
}
}
sIt Problem::returnDashSetItr(vector<int> ijk) // see typedef for sIt, returns iterator of vec ijk if found, else returns dashSet.end()
{
pair<sIt,sIt> ret = dashSet.equal_range(ijk);
for (sIt it = ret.first ; it != ret.second ; it++)
{
if (((*it)[0]==ijk[0]) and ((*it)[1]==ijk[1]) and ((*it)[2]==ijk[2]))
return it;
}
return dashSet.end();
}
void Problem::performSwap(vector<string>& vs, int l, int i, int j, int k, bool& leftSwap)
// k=0 for left, k=1 for right
{
char temp = vs[i][j];
int maxInt = numeric_limits<int>::max();
// remove from dashSet for that index
sIt itl = returnDashSetItr(vector<int>{i,j,0});
sIt itr = returnDashSetItr(vector<int>{i,j,1});
if (itl != dashSet.end()) dashSet.erase(itl);
if (itr != dashSet.end()) dashSet.erase(itr);
if (k==0) // swap with left
{
vs[i][j] = vs[i][j-1]; // take care of edge cases. remove left/right or add left/right
vs[i][j-1] = temp; // just add to dashSet with inf, hillClimb recomputes values
dashCostMatrix[i][j][0] = maxInt ; dashCostMatrix[i][j][1] = maxInt; // alphabet at place now, must have infty {INVARIANT}
dashSet.insert(vector<int>{i,j-1,1}) ; // has right ngbr for sure if left swap, currently has
if (j!=l-1 and vs[i][j+1]=='-') dashSet.insert(vector<int>{i,j+1,0}); // if right ngbr before swapping is dash, if exists
if (j!=1 and vs[i][j-2]=='-') // if left ngbr after swapping is dash, if exists
{
sIt it = returnDashSetItr(vector<int>{i,j-2,1}); // definitely had right ngbr
dashSet.erase(it); // doesn't now, so remove from set
dashCostMatrix[i][j-2][1] = maxInt;
}
if (j-1 == 0 or vs[i][j-2]=='-') dashCostMatrix[i][j-1][0] = maxInt; // if does not have left non-dash ngbr
else dashSet.insert(vector<int>{i,j-1,0}) ;
}
else // swap with right
{
leftSwap = false;
vs[i][j] = vs[i][j+1]; // take care of edge cases. remove left/right or add left/right
vs[i][j+1] = temp; // just add to dashSet with inf, hillClimb recomputes values
dashCostMatrix[i][j][0] = maxInt ; dashCostMatrix[i][j][1] = maxInt; // alphabet at place now, must have infty {INVARIANT}
dashSet.insert(vector<int>{i,j+1,0}) ; // has left ngbr for sure if right swap
if (j!=0 and vs[i][j-1]=='-') dashSet.insert(vector<int>{i,j-1,1}); // if left ngbr before swapping is dash, if exists {its dash cost is still infty}
if (j!=l-2 and vs[i][j+2]=='-') // if right ngbr after swapping is dash, if exists
{
sIt it = returnDashSetItr(vector<int>{i,j+2,0}); // definitely had left ngbr
dashSet.erase(it);
dashCostMatrix[i][j+2][0] = maxInt;
}
if (j+1 == l-1 or vs[i][j+2]=='-') dashCostMatrix[i][j+1][1] = maxInt; // if does not have right non-dash ngbr
else dashSet.insert(vector<int>{i,j+1,1}) ;
}
}
//vector<string> Problem::hillClimb(vector<string> vs, int l) // all strings built up to length l
//{
/* STRATEGY
* -------------------------------------------------
* Scan all dashes and see if moving left or right
* improves the cost at every step
* If it does, move to neighbour, else terminate */
// implementation using set
// initialise with all elements of set, if dash on left, set to infinity in dash cost matrix
// in while loop, pop best element, see if left or right swap
// swap, make changes to neighboring dashes (add/remove neighbours) --- also remove i,j from dashSet and insert i,j+/-1
// if neighbouring dash is introduced, set dash move cost -> +infinity
// recompute values for potentially four columns
// INVARIANT :: dashSet has only those ngbrs which are possible, i.e. if a--, then right ngbr for left dash not in dashSet. also dash cost for right ngbr is infty
// INVARIANT :: all dashCostMatrix elements other than dashes have value infty, those with dash may or may not
/*
vector<int> best(3); // store coordinates and whether left(0) or right(1) neighbour is best
int bestChangeYet; // the more negative, the better
int loopCount = 0; // book-keeping
int zeroCount = 0; // if plateau, then for cutoff (initally 100)
dashCostMatrix = vector<vector<vector<int> > >(noOfStrings , vector<vector<int> >(l, vector<int>(2,numeric_limits<int>::max())));
initialiseHillClimb(vs,l);
// for (int i = 0 ; i<noOfStrings ; i++)
// cout << vs[i] << endl;
//
// for (int i = 0 ; i<noOfStrings ; i++)
// {
// for (int j = 0 ; j<l ; j++)
// cout << setw(1) << "(" << dashCostMatrix[i][j][0] <<","<< dashCostMatrix[i][j][1] << ") " ;
//
// cout <<endl;
// }
// cout << "----------" << endl;
// for (set<vector<int> >::iterator it = dashSet.begin() ; it!=dashSet.end() ; it++)
// cout << (*it)[0]<<","<<(*it)[1]<<","<<(*it)[2] <<" ";
while (true)
{
loopCount++;
bestChangeYet = 1; // if doesn't change, then stays positive
best = *(dashSet.begin());
int curBestCost = dashCostMatrix[best[0]][best[1]][best[2]];
if (curBestCost > 0 or zeroCount==25) break;
// for plateau
if (curBestCost == 0)
{
vector<vector<int> > zeroStateIndices; //[i][j][k] of all zero cost dash movements (k for left or right)
//for all the zero wale neighbours
for (sIt it = dashSet.begin() ; it!= dashSet.end() ; it++) //iterator syntax
{
if (dashCostMatrix[(*it)[0]][(*it)[1]][(*it)[2]] == 0)
zeroStateIndices.push_back(*it);
else break;
}
zeroCount++;
int decide = rand() % zeroStateIndices.size();
best = zeroStateIndices[decide];
}
///// ^ for plateau /////
else zeroCount = 0; // implies crossed plateau
bool leftSwap = true; // to check what swapping has been done
performSwap(vs,l,best[0],best[1],best[2],leftSwap);
//////////////////////////////// updating dash costs in log(Nk) time {hopefully} ///////////////////////
int effX; // effective X component {3rd out of potentially 4 columns}
if (leftSwap == true) effX = best[1]; // | | |i| |
else effX = best[1]+1; // | |i| | | --> |.| |effX|.| { . => may or may not exist}
if (effX > 1)
for (int i = 0 ; i < noOfStrings ; i++)
if (vs[i][effX-2] == '-')
{
vector<int> item = {i, effX-2 , 1};
set<vector<int> >::iterator it = returnDashSetItr(item);
if (it != dashSet.end()) // if doesn't exist, dashCostMatrix has infinite value, so goes down tree quickly
{
dashSet.erase(it);
int finCost = columnCost(vs, i, effX-2, effX-1) + columnCost(vs, i, effX-1, effX-2);
int curCost = columnCost(vs, i, effX-2, effX-2) + columnCost(vs, i, effX-1, effX-1);
dashCostMatrix[i][effX-2][1] = finCost - curCost;
item = {i, effX-2 , 1};
dashSet.insert(item);
}
}
if (effX < (l-1)) // 4th column exists
for (int i = 0 ; i < noOfStrings ; i++)
if (vs[i][effX+1] == '-')
{
vector<int> item = {i, effX+1 , 0};
set<vector<int> >::iterator it = returnDashSetItr(item);
if (it != dashSet.end())
{
dashSet.erase(it);
int finCost = columnCost(vs, i, effX+1, effX) + columnCost(vs, i, effX, effX+1);
int curCost = columnCost(vs, i, effX, effX) + columnCost(vs, i, effX+1, effX+1);
dashCostMatrix[i][effX+1][0] = finCost - curCost;
item = {i, effX+1 , 0};
dashSet.insert(item);
}
}
// for both effX and effX-1 , need to update lef and right move cost
for (int i = 0 ; i < noOfStrings ; i++)
for (int j = effX-1 ; j<=effX ; j++)
if (vs[i][j] == '-')
{
if (!(j==effX and effX==(l-1)))
{
vector<int> right = {i,j,1};
set<vector<int> >::iterator itr = returnDashSetItr(right);
if (itr != dashSet.end())
{
dashSet.erase(itr);
int curRightCost = columnCost(vs, i, j, j) + columnCost(vs, i, j+1, j+1);
int finRightCost = columnCost(vs, i ,j, j+1) + columnCost(vs, i, j+1, j);
dashCostMatrix[i][j][1] = finRightCost - curRightCost ;
right = {i,j,1} ;
dashSet.insert(right);
}
}
if (!(j==effX-1 and j==0))
{
vector<int> left = {i,j,0};
set<vector<int> >::iterator itl = returnDashSetItr(left);
if (itl != dashSet.end())
{
dashSet.erase(itl);
int curLeftCost = columnCost(vs, i, j, j) + columnCost(vs, i, j-1, j-1);
int finLeftCost = columnCost(vs, i ,j, j-1) + columnCost(vs, i, j-1, j);
dashCostMatrix[i][j][0] = finLeftCost - curLeftCost ;
left = {i,j,0} ;
dashSet.insert(left) ;
}
}
}
////////////////////////////////// ^ updated dashes //////////////////////
// checking if column of dashes align
// bool check1 = true;
//bool check2 = true;
for (int q = 0 ; q<l ; q++)
if (vs[0][q]=='-')
{
for (int m = 1 ; m < noOfStrings ; m++)
{
if(vs[m][q]!='-')
{
check1 = false;
break;
}
}
if (check1 == true)
{for (int i = 0 ; i<noOfStrings ; i++)
cout << vs[i] << "\n";
check1=false;
cout<<" found you!!"<<endl;
break;
}
}
*/
/* }
//cout << loopCount << endl;
//for (int i = 0 ; i<noOfStrings ; i++)
// cout << vs[i] << "\n";
//cout << "Final matching cost : " << allMatchingCost(vs) << endl;
//cout << "Loop cout : " << loopCount << endl;
dashSet.clear(); // make ready for next iteration
return vs;
}
*/
void Problem::localSearch(int time)
{
int minDash = 0;
for (int i = 0; i<noOfStrings ; i++)
minDash += maxStrLength - strLengths[i];
int minDashCost = minDash*CC;
int bestCostYet = firstEst();
vector<string> bestStateYet = {"first ","is","best","pls","get","lost"};
for (int loopCount = 0 ; loopCount<1000; loopCount++)
{if (loopCount%500 == 0 and loopCount>0) cout << "loop count : " <<loopCount << endl;
int decide = rand()%100;
if (decide < 30)
{
int size = (rand()%(((12*maxStrLength)/10)-maxStrLength))+maxStrLength;
vector<string> cur = randomStateGenerator(size);
// cout << "reset start cost: " << allMatchingCost(cur)+ minDashCost + (size-maxStrLength)*CC*noOfStrings << endl;
recurHillClimb(cur,size,0,noOfStrings-1);
int curCost = allMatchingCost(cur)+ minDashCost + (size-maxStrLength)*CC*noOfStrings;
if (curCost < bestCostYet)
{
bestStateYet = cur;
bestCostYet = curCost;
cout << "Best cost yet : " << bestCostYet << " (" << bestStateYet[0].length() << ")" <<endl;
}
}
else if (decide < 80)
{
int size = (rand()%(((15*maxStrLength)/10)-(12*maxStrLength)/10))+((12*maxStrLength)/10);
vector<string> cur = randomStateGenerator(size);
// cout << "reset start cost: " << allMatchingCost(cur)+ minDashCost + (size-maxStrLength)*CC*noOfStrings << endl;
recurHillClimb(cur,size,0,noOfStrings-1);
int curCost = allMatchingCost(cur) + minDashCost + (size-maxStrLength)*CC*noOfStrings;
if (curCost < bestCostYet)
{
bestStateYet = cur;
bestCostYet = curCost;
cout << "Best cost yet : " << bestCostYet << " (" << bestStateYet[0].length() << ")" <<endl;
}
}
else
{
int size = (rand()%(((17*maxStrLength)/10)-(15*maxStrLength)/10))+((15*maxStrLength)/10);
vector<string> cur = randomStateGenerator(size);
// cout << "reset start cost: " << allMatchingCost(cur)+ minDashCost + (size-maxStrLength)*CC*noOfStrings << endl;
recurHillClimb(cur,size,0,noOfStrings-1);
int curCost = allMatchingCost(cur) + minDashCost + (size-maxStrLength)*CC*noOfStrings;
if (curCost < bestCostYet)
{
bestStateYet = cur;
bestCostYet = curCost;
cout << "Best cost yet : " << bestCostYet << " (" << bestStateYet[0].length() << ")" <<endl;
}
}
}
for (int i = 0 ; i<noOfStrings ; i++)
cout << bestStateYet[i] << endl;
cout << bestCostYet << endl;
}
#endif
| 373a3118c19f05410e5b809d25de15eb94bb7a2c | [
"C++",
"Shell"
] | 17 | C++ | kchhhk/ApnaKaam | a9afa6ddf78c28c4aa38810d5be6c7913c1ddba8 | f0783272301123bba6ce2730bd1d6330460d4f26 |
refs/heads/master | <repo_name>kshitiz1798/myfirst<file_sep>/reverse.c
/*reverse of number*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i,rem,rev=0;
printf("enter a number: ");
scanf("%d",&i);
while(i>0)
{
rem=i%10;/*gets the one's place digit number*/
i=i/10;/*remove the one's place digit number*/
rev=rev*10+rem;/* suppose enter number is 654
0*10+4=4
4*10+5=45
45*10+6=456 */
}
printf("%d",rev);
return 0;
}
<file_sep>/factorial.c
/*code to find factorial of a number*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num,i,fact=1;/*declare them as integer type*/
printf("enter the num: ");
scanf("%d",&num);
for(i=1;i<=num;i++)/*run the loop from 1 to the number we entered,so that it keeps on muliplying*/
{
fact=(fact*i);/*multiply i till the number is reached*/
}
printf("%d",fact);
return 0;
}
<file_sep>/prime.c
/*for printing prime numbers below 200*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num,i,j;
for(i=200;i>=1;i--)/*for starting the numerator from 200 and end at 1*/
{
for(j=2;j<i;j++)/*for starting the denominator from 2 to a number less than numerator*/
{
if(i%j==0)
{
break;/*if remainder is 0 the loop breaks and start again,if not the it move forward*/
}
}
if(i==j)/*if the number is not divisible by any number smaller than the number itself then it is a prime number*/
{
printf("%d\n",i);
}
}
return 0;
}
<file_sep>/area perimeter using pointer.c
#include <stdio.h>
#include<stdlib.h>
void area(int,float *);
void perimeter(int,float *);
int main()
{
int r;
float a,p;
printf("enter the radius: ");
scanf("%d",&r);
area(r,&a);
printf("area=%f",a);
perimeter(r,&p);
printf("perimeter=%f",p);
return 0;
}
void area(int r,float *a)
{
*a=3.14*r*r;
return a;
}
void perimeter(int r,float *p)
{
*p=2*3.14*r;
return p;
}
<file_sep>/student details using struct.c
#include <stdio.h>
#include <stdlib.h>
struct detail
{
char name[10][100];
int marks[100];
};
int main()
{
struct detail k;
int n,i,j,temp;
char x;
printf("enter the number of students: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\nenter student name %d: ",i);
scanf("%s",&k.name[i]);
printf("\nenter the marks of student %d: ",i);
scanf("%d",&k.marks[i]);
}
for(i=1;i<=n;i++)
{
printf("name: %s\n",k.name[i]);
printf("marks: %d\n\n",k.marks[i]);
}
for(i=1;i<n;i++)
{
for(j=i+1;j<=n;j++)
{
while(k.marks[i]>k.marks[j])
{
temp=k.marks[i];
k.marks[i]=k.marks[j];
k.marks[j]=temp;
}
}
}
printf("heighest marks is of %d ",k.marks[i]);
return 0;
}
<file_sep>/matrix multiplication & addition.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[100][100],b[100][100],mult[100][100],add[100][100],r1,c1,r2,c2,i,j,k;
printf("enter row and column for 1st matrix: \n");
scanf("%d%d",&r1,&c1);
printf("enter row and column for 2nd matrix: \n");
scanf("%d%d",&r2,&c2);
while(c1!=r2)
{
printf("column of first is not equal to row of second\n");
printf("enter row and column for 1st matrix: \n");
scanf("%d%d",&r1,&c1);
printf("enter row and column for 2nd matrix: \n");
scanf("%d%d",&r2,&c2);
}
printf("enter the elements in first matrix\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("a%d%d=",i+1,j+1);
scanf("%d",&a[i][j]);
}
}
printf("enter the elements in second matrix\n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
printf("b%d%d=",i+1,j+1);
scanf("%d",&b[i][j]);
}
}
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
mult[i][j]=0;
add[i][j]=0;
}
}
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
for(k=0;k<c1;k++)
{
mult[i][j]=mult[i][j]+(a[i][k]*b[k][j]);
}
}
}
printf("multiplication\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
printf("%d ",mult[i][j]);
}
printf("\n");
}
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
add[i][j]=a[i][j]+b[i][j];
}
}
printf("addition\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("%d ",add[i][j]);
}
printf("\n");
}
return 0;
}
<file_sep>/sorting of characters.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i,j;
char temp,str[100];
printf("enter the string: ");
gets(str);
printf("unsorted array: \n");
puts(str);
for(i=0;i<str[i];i++)
{
for(j=i+1;j<str[j];j++)
{
while(str[i]>str[j])
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
}
}
}
printf("\nsorted array: \n");
printf("%s",str);
return 0;
}
<file_sep>/calculator using pointer.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[100],i,*p[100],sum=0,mult=1,n;
printf("enter the count of numbers to add and multiply: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("enter the number %d:",i);
scanf("%d",&a[i]);
}
for(i=1;i<=n;i++)
{
p[i]=&a[i];
}
for(i=1;i<=n;i++)
{
sum=sum + *p[i];
mult=mult * *p[i];
}
printf("sum=%d:\n",sum);
printf("multiplication=%d:\n\n\n",mult);
printf("enter two number to subtract and divide: ");
int k1,k2,sub,div,*l1,*l2;
scanf("%d%d",&k1,&k2);
l1=&k1;
l2=&k2;
if(*l1 < *l2)
{
printf("k1 should be greater than k2;");
}
else if(*l1 > *l2)
{
sub = *l1 - *l2;
div = *l1 / *l2;
printf("subtraction=%d\n",sub);
printf("division=%d",div);
}
else{printf("0");}
return 0;
}
<file_sep>/pascalpyramid.c
/*code for pascal pyramid*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int row,trow,space,chars;
printf("enter the number of row: ");
scanf("%d",&trow);
for(row=0;row<=trow;row++)/*loop for pyramid formation for entered number of rows*/
{
for(space=trow-row;space>=1;space--)/*loop for entering space, from maximum space possible to 1*/
{
printf(" ");
}
int pchar=1;
int num=row;
int den=1;
for(chars=0;chars<=row;chars++)/*for printing the numerical value*/
{
printf("%d ",pchar);/*1 will be printed*/
pchar=pchar*num;/*number will now be multiplied to numerator, which is initially the value of row*/
pchar=pchar/den;/*number will be divided to denominator which is initially 1*/
/*pchar is changed to a different number by multiplication and division*/
num--;/*then after multiplication numerator will be decreased by 1*/
den++;/*after division denominator will be incremented by 1*/
/*numerator and denominator will be changed*/
}
printf("\n");
}
return 0;
}
<file_sep>/creatiing and display linked list.c
#include <stdio.h>
#include <stdlib.h>
typedef struct node /*structure to create linked list*/
{
int data;
struct node * next;
}node;
void display(node * head); /*function to display linklist*/
node * linklist(int n); /*function to create linked list*/
int main()
{
int n=0;
node * HEAD=NULL;
printf("enter the number of nodes: ");
scanf("%d",&n);
HEAD=linklist(n);
display(HEAD);
return 0;
}
node * linklist(n)
{
int i=0;
node * head=NULL;
node * last=NULL;
node * first=NULL;
for(i=0;i<n;i++)
{
last=(node*)malloc(sizeof(node)); /*create a node*/
printf("\n enter the data for node %d: ",i+1);
scanf("%d",&(last->data));
last->next=NULL;
if(head==NULL) /*if list is empty, temp is the first node*/
{
head=last;
}
else
{
first=head;
while(first->next!=NULL)
{
first=first->next;
}
while(first->next==NULL)
{
first->next=last;
}
}
}
return head;
}
void display(node * head)
{
node * first=head;
while(first!=NULL)
{
printf("%d->",first->data);
first=first->next;
}
int p=1,key;
printf("\nenter the digit you want to find: ");
scanf("%d",&key);
while(first!=NULL)
{
if(key==first->data)
{
printf("found %d at position %d",key,p);
break;
}
else
{
first=first->next;
}
p++;
}
}
<file_sep>/online exam.c
#include <stdio.h>
#include <stdlib.h>
struct exam
{
char que[200];
char opt1[200];
char opt2[200];
char opt3[200];
char opt4[200];
char ans[200];
char fans[200];
};
int main()
{
struct exam arr_exam[3];
printf("Enter the questions, their options and the correct answers manually");
int i,total=1,score=0;
for(i=0;i<3;i++)
{
printf("\n\nenter que %d : ",i+1);
gets(arr_exam[i].que);
printf("opt1-->");
gets(arr_exam[i].opt1);
printf("opt2-->");
gets(&arr_exam[i].opt2);
printf("opt3-->");
gets(&arr_exam[i].opt3);
printf("opt4-->");
gets(&arr_exam[i].opt4);
printf("correct answer-->");
gets(&arr_exam[i].ans);
}
printf("\n\n\n***ONLINE EXAM***\n\n");
for(i=0;i<3;i++)
{
printf("\n\nQuestion %d : %s.",i+1,arr_exam[i].que);
printf("\nopt1-->%s",arr_exam[i].opt1);
printf("\nopt2-->%s",arr_exam[i].opt2);
printf("\nopt3-->%s",arr_exam[i].opt3);
printf("\nopt4-->%s",arr_exam[i].opt4);
printf("\nEnter your answer : ");
gets(arr_exam[i].fans);
}
for(i=0;i<3;i++)
{
total=4*(i+1);
}
for(i=0;i<3;i++)
{
if(strcmp(arr_exam[i].fans , arr_exam[i].ans)==0)
{
score=score+4;
}
else
{
score=score-1;
}
}
printf("\n\n\nYour total score is : %d/%d",score,total);
return 0;
}
<file_sep>/maximum number and its position in array.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i,j,a[100],n,max,p=1;
printf("enter the number of elements in an array: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter element %d: ",i+1);
scanf("%d",&a[i]);
}
max=a[0];
for(i=1;i<n;i++)
{
if(max<a[i])
{
max=a[i];
}
}
for(i=0;i<n;i++)
{
if(a[i]==max)
{
printf("maximun value is %d at position %d",a[i],p);
break;
}
p++;
}
return 0;
}
<file_sep>/final create and display of linklist using pointers.c
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
void display();
void create();
struct node *start;
int main()
{
start=NULL;
create();
display();
return 0;
}
void create()
{
int n,i;
printf("enter the count of elements to be entered: ");
scanf("%d",&n);
struct node *new,*temp;
for(i=1;i<=n;i++)
{
if(start==NULL)
{
new=(struct node *)malloc(sizeof(struct node));
scanf("%d",&new->data);
new->next=NULL;
start=new;
temp=start;
}
else
{
new=(struct node *)malloc(sizeof(struct node));
scanf("%d",&new->data);
new->next=NULL;
temp->next=new;
temp=new;
}
}
}
void display()
{
struct node *temp;
temp=start;
while(temp!=NULL)
{
printf("%d->",temp->data);
temp=temp->next;
}
}
<file_sep>/display file using file handling.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
char ans[100];
FILE *fp;
char ch;
fp=fopen("exam.txt","r");
if(fp==NULL)
{
printf("file not present");
exit(1);
}
while(1)
{
ch=fgetc(fp);
if(fp==EOF)
{
printf("file is empty");
exit(2);
}
else
{
printf("%s",*fp);
break;
}
}
printf("\n\n\nEnter your answers: \n");
for(i=0;i<3;i++)
{
printf("ans %d : ",i+1);
scanf("%s",&ans);
}
return 0;
}
<file_sep>/create display and find a number in linked list.c
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
void create();
void display();
void find();
struct node *start;
int main()
{
start=NULL;
create();
display();
find();
return 0;
}
void create()
{
int i,n;
printf("enter the count of digits to be entered: ");
scanf("%d",&n);
struct node *new,*temp;
for(i=1;i<=n;i++)
{
if(start==NULL)
{
new=(struct node *)malloc(sizeof(struct node));
scanf("%d",&new->data);
new->next=NULL;
start=new;
temp=start;
}
else
{
new=(struct node*)malloc(sizeof(struct node));
scanf("%d",&new->data);
new->next=NULL;
temp->next=new;
temp=new;
}
}
}
void display()
{
struct node *temp;
temp=start;
while(temp!=NULL)
{
printf("%d->",temp->data);
temp=temp->next;
}
}
void find()
{
struct node *temp;
temp=start;
int f;
printf("\nenter a number to find: ");
scanf("%d",&f);
while(temp!=NULL)
{
if(f==temp->data)
{
printf("%d is present",f);
break;
}
else
{
printf("not found");
temp=temp->next;
break;
}
}
}
<file_sep>/string comparision.c
/*string comparision*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
char name[20][100],temp[20];
int i,j,n;
printf("enter the number of students: ");
scanf("%d",&n);
if(n > 100)/*if number of names is greater than 100 then it will end the code*/
{
exit(0);
}
for(i=0;i<n;i++)/*loop for getting the number of input as mentioned above*/
{
printf("enter the name of student %d: ",i+1);
scanf("%s",&name[i]);
}
for(i=0;i<n;i++)/*loop for comparing the two names*/
{
for(j=0;j<n;j++)
{
if(strcmp(name[j],name[j+1])>0)/*compare two names, if j>j+1 it will return 1, hence condition satisfied
if j<j+1 it will return 0,hence condition not satisfied*/
{
strcpy(temp,name[j]); /*swapping*/
strcpy(name[j],name[j+1]);
strcpy(name[j+1],temp);
}
}
}
printf("names in sorted order:\n");
for(i=0;i<n;i++)/*loop for printing the sorted names*/
{
printf("%s\n",name[i]);
}
return 0;
}
<file_sep>/leapyear.c
/*to find the entered year is leap year or not*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int year;
printf("enter year: ");
scanf("%d",&year);
if(year%400==0)
{
printf("leap year");
}
else if(year%100==0)
{
printf("not a leap year");
}
else if(year%4==0)
{
printf("leap year");
}
else{printf("not a leap year");}
return 0;
}
<file_sep>/pyramid.c
/*pyramid formation*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int row,trow,space,star;
printf("enter the number of row: ");
scanf("%d",&trow);
for(row=1;row<trow;row++)/*row starts from 1 and end at the number of entered rows*/
{
for(space=trow-row;space>=1;space--)/*space starts from twice the number of total row -1, and end at 1*/
{
printf(" ");
}
for(star=1;star<=(2*row)-1;star++)/*stars will start printing from 1 and will end at twice the total row -1*/
{
printf("*");
}
printf("\n");
}
for(row<trow-1;row>=1;row--)/*this loop will start from a number less than the number entered for total row */
{
for(space=trow-row;space>=1;space--)
{
printf(" ");
}
for(star=1;star<=(2*row)-1;star++)
{
printf("*");
}
printf("\n");
}
return 0;
}
<file_sep>/student details using struct 1.c
#include <stdio.h>
#include <stdlib.h>
struct detail
{
char name[20];
int marks;
};
int main()
{
int i,n,j;
struct detail arr_detail[100];
printf("enter the number of students: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\nenter student name %d: ",i);
scanf("%s",&arr_detail[i].name);
printf("\nenter the marks of student %d: ",i);
scanf("%d",&arr_detail[i].marks);
}
printf("name\tmarks\n\n");
for(i=1;i<=n;i++)
{
printf("%s\t%d\n",arr_detail[i].name,arr_detail[i].marks);
}
return 0;
}
<file_sep>/create display find delete insertion reverse in linked list.c
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
void create();
void display();
void find();
void delete();
void insert();
void reverse();
struct node *start;
int main()
{
start=NULL;
create();
display();
find();
delete();
display();
insert();
display();
reverse();
display();
return 0;
}
void create()
{
int n,i;
printf("enter the number of elements: ");
scanf("%d",&n);
struct node *new,*temp;
for(i=1;i<=n;i++)
{
printf("enter the value %d: ",i);
if(start==NULL)
{
new=(struct node *)malloc(sizeof(struct node));
scanf("%d",&new->data);
new->next=NULL;
start=new;
temp=start;
}
else
{
new=(struct node *)malloc(sizeof(struct node));
scanf("%d",&new->data);
new->next=NULL;
temp->next=new;
temp=new;
}
}
}
void display()
{
struct node *temp;
temp=start;
while(temp!=NULL)
{
printf("%d->",temp->data);
temp=temp->next;
}
}
void find()
{
int f,key,p=1;
printf("\n\nenter the element to find: ");
scanf("%d",&f);
struct node *temp;
temp=start;
while(temp!=NULL)
{
if(temp->data==f)
{
printf("%d is present at location %d",f,p);
break;
}
else
{
temp=temp->next;
}
p++;
}
}
void delete()
{
int d;
printf("\n\nenter the value to be deleted: ");
scanf("%d",&d);
struct node *temp1,*temp2;
if(start!=NULL)
{
if(start->data==d)
{
temp1=start;
start=start->next;
free(temp1);
printf("node is deleted\n");
}
else
{
temp1=start;
temp2=start->next;
while(temp2!=NULL)
{
if(temp2->data==d)
{
temp1->next=temp2->next;
free(temp2);
printf("node is deleted\n");
break;
}
else
{
temp1=temp2;
temp2=temp2->next;
}
}
}
}
else
{
printf("linked list is empty");
}
}
void insert()
{
int i,p;
struct node *temp1,*temp2,*newnode;
newnode=(struct node *)malloc(sizeof(struct node));
printf("\n\nenter the value to be inserted: ");
scanf("%d",&newnode->data);
printf("enter the location for insertion: ");
scanf("%d",&p);
if(start==NULL)
{
start=newnode;
printf("node inserted");
}
else
{
if(start->data==p)
{
newnode->next=start;
start=newnode;
printf("node inserted\n");
}
else
{
temp1=start;
temp2=start->next;
while(temp2!=NULL)
{
if(temp2->data==p)
{
temp1->next=newnode;
newnode->next=temp2;
printf("node is inserted\n");
break;
}
else
{
temp1=temp2;
temp2=temp2->next;
}
}
}
}
}
void reverse()
{
printf("\n\nreverse linked list: ");
struct node *temp1,*temp2;
if(start!=NULL)
{
temp1=start;
temp2=temp1->next;
start=NULL;
while(temp2!=NULL)
{
temp1->next=start;
start=temp1;
temp1=temp2;
temp2=temp2->next;
}
temp1->next=start;
start=temp1;
}
else
{
printf("list is empty");
}
}
| cb2afef95d6cbc1dc7faf21098782af7fe2e8677 | [
"C"
] | 20 | C | kshitiz1798/myfirst | 2a357335e4f79ff3f0e29e55d847a611f2b3fbd9 | b0714ebcc6678ba7cf35e3811e966ea2aa9b031e |
refs/heads/master | <repo_name>andrwjrdn/unit-4-game<file_sep>/assets/javascript/game.js
$(document).ready(function() {
var valueMatch = "";
var ameValue = "";
var carnValue ="";
var celValue = "";
var quartzValue = "";
var ameButton;
var carnButton;
var quartzButton;
var score;
var wins=0;
var loss=0;
/*
================================
START/RESTART
================================
*/
function initialize() {
valueMatch=Math.floor(Math.random()*101)+19;
score=0;
var crystal=[$(".amethyst"), $(".carnelian"), $(".celestite"), $(".quartz")];
var button=[ameButton, carnButton, celValue, quartzValue];
/*
================================
CRYSTAL VALUES
================================
*/
for (var i=0; i<crystal.length; i++) {
button[i]=crystal[i].attr("data-chicken", Math.floor(Math.random()*12)+2);
};
/*
================================
HTML
================================
*/
$("#valueMatch").html(valueMatch);
$("#wins").html(wins);
$("#loss").html(loss);
$("#score").html(score);
}
initialize();
/*
================================
CLICK FUNCTION
================================
*/
$(".crystal").on("click", function(){
score += parseInt($(this).attr("data-chicken"));
$("#score").html(score);
if(score == valueMatch) {
wins++;
initialize();
}
else if (score > valueMatch) {
loss++;
initialize();
}
});
}); | 332324d4ebf9f89b2a79dfbe44c7b56943e33df9 | [
"JavaScript"
] | 1 | JavaScript | andrwjrdn/unit-4-game | 1a5c305af5e0abf5a0b3a09886b8571040dd3eba | 8a95f75881a7a7103518101f717f9c95dfb95484 |
refs/heads/main | <repo_name>Noghss/faixas-API<file_sep>/src/main/webapp/scripts/main.js
$(document).ready(function () {
$("#header").load("./components/header/header.html");
debugger;
switch (window.location.hash) {
case "#pedidos":
$("#content").load("../pages/pedidos/pedidos.html");
break;
case "#faixas":
$("#content").load("../pages/faixas/faixas.html");
break;
case "#clientes":
$("#content").load("../pages/clientes/clientes.html");
break;
case "#dashboard":
$("#content").load("../pages/dashboard/dashboard.html");
break;
default:
$("#content").load("../pages/dashboard/dashboard.html");
break;
}
});
<file_sep>/src/main/webapp/pages/dashboard/dashboard.js
function initDashboard() {
$("#title").text("Dashboard");
}
<file_sep>/src/main/webapp/components/header/header.js
function dashboard() {
$("#content").load("../pages/dashboard/dashboard.html");
}
function pedidos() {
$("#content").load("../pages/pedidos/pedidos.html");
}
function faixas() {
$("#content").load("../pages/faixas/faixas.html");
}
function clientes() {
$("#content").load("../pages/clientes/clientes.html");
}
<file_sep>/src/main/java/com/faixas/pedido/Pedido.java
/**
*
*/
package com.faixas.pedido;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import com.faixas.cliente.Cliente;
/**
* @author camil
*
*/
@Entity // This tells Hibernate to make a table out of this classS
public class Pedido {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private Date data;
private Date previsaoEntrega;
private Double valorServico;
private Double valorSinal;
private Date data_inicioProd;
private Date dataFimProd;
private Date dataRealEntrega;
private String status;
private Integer cliente;
/**
* @return the id
*/
public Integer getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return the data
*/
public Date getData() {
return data;
}
/**
* @param data the data to set
*/
public void setData(Date data) {
this.data = data;
}
/**
* @return the previsaoEntrega
*/
public Date getPrevisaoEntrega() {
return previsaoEntrega;
}
/**
* @param previsaoEntrega the previsaoEntrega to set
*/
public void setPrevisaoEntrega(Date previsaoEntrega) {
this.previsaoEntrega = previsaoEntrega;
}
/**
* @return the valorServico
*/
public Double getValorServico() {
return valorServico;
}
/**
* @param valorServico the valorServico to set
*/
public void setValorServico(Double valorServico) {
this.valorServico = valorServico;
}
/**
* @return the valorSinal
*/
public Double getValorSinal() {
return valorSinal;
}
/**
* @param valorSinal the valorSinal to set
*/
public void setValorSinal(Double valorSinal) {
this.valorSinal = valorSinal;
}
/**
* @return the data_inicioProd
*/
public Date getData_inicioProd() {
return data_inicioProd;
}
/**
* @param data_inicioProd the data_inicioProd to set
*/
public void setData_inicioProd(Date data_inicioProd) {
this.data_inicioProd = data_inicioProd;
}
/**
* @return the dataFimProd
*/
public Date getDataFimProd() {
return dataFimProd;
}
/**
* @param dataFimProd the dataFimProd to set
*/
public void setDataFimProd(Date dataFimProd) {
this.dataFimProd = dataFimProd;
}
/**
* @return the dataRealEntrega
*/
public Date getDataRealEntrega() {
return dataRealEntrega;
}
/**
* @param dataRealEntrega the dataRealEntrega to set
*/
public void setDataRealEntrega(Date dataRealEntrega) {
this.dataRealEntrega = dataRealEntrega;
}
/**
* @return the status
*/
public String getStatus() {
return status;
}
/**
* @param status the status to set
*/
public void setStatus(String status) {
this.status = status;
}
/**
* @return the cliente
*/
public Integer getCliente() {
return cliente;
}
/**
* @param cliente the cliente to set
*/
public void setCliente(Integer cliente) {
this.cliente = cliente;
}
@Override
public String toString() {
return "Pedido [getId()=" + getId() + ", getData()=" + getData() + ", getPrevisaoEntrega()="
+ getPrevisaoEntrega() + ", getValorServico()=" + getValorServico() + ", getValorSinal()="
+ getValorSinal() + ", getData_inicioProd()=" + getData_inicioProd() + ", getDataFimProd()="
+ getDataFimProd() + ", getDataRealEntrega()=" + getDataRealEntrega() + ", getStatus()=" + getStatus()
+ ", getCliente()=" + getCliente() + "]";
}
}
<file_sep>/src/main/java/com/faixas/pedido/PedidoController.java
/**
*
*/
package com.faixas.pedido;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller // This means that this class is a Controller
@RequestMapping(path = "/pedido") // This means URL's start with /demo (after Application path)
public class PedidoController {
@Autowired // This means to get the bean called userRepository
// Which is auto-generated by Spring, we will use it to handle the data
private PedidoRepository pedidoRepository;
@PostMapping(path = "/add") // Map ONLY POST Requests
public @ResponseBody String addNewPedido(Pedido pedido) {
// @ResponseBody means the returned String is the response, not a view name
// @RequestParam means it is a parameter from the GET or POST request
try {
pedidoRepository.save(pedido);
return "Pedido Adicionado com Sucesso!";
} catch (Exception e) {
return e.getMessage();
}
}
@DeleteMapping(path = "/delete")
public @ResponseBody String deletePedido(Integer id) {
Pedido pedido = pedidoRepository.findById(id).get();
try {
pedidoRepository.delete(pedido);
return "Pedido Deletado com Sucesso!";
} catch (Exception e) {
return e.getMessage();
}
}
@GetMapping(path = "/all")
public @ResponseBody Iterable<Pedido> getAllPedidos() {
// This returns a JSON or XML with the users
return pedidoRepository.findAll();
}
}<file_sep>/README.md
# Faixas
Faixas contém o sistema de uma loja de banners completo, Backend e Frontend.
O backend foi escrito em Java, ultilizando o Spring Boot como framework e o MySQL como banco de dados.
O Frontend foi escrito em Javascript puro, e convertido para JQuery posteriormente para fins de aprendizado.
# Subindo a Aplicação:
Será necessário instalar:
* Eclipse IDE for Enterprise Java Developers 4.0 ou superior.
* MySQL Worchbench 8.0 ou superior.
Vamos aos passos:
* Clone esse projeto no seu Eclipse IDE for Enterprise Java Developers.
* Dentro da pasta database deve conter um Dump.sql, ultilize este arquivo para importar o seu banco de dados dentro do MySQL Workbench.
* Rode um Maven Update Project para baixar as dependências.
* Start a aplicação como Java Application.
O Tomcat deve liberar a porta padrão para seu projeto, acesse pot http://localhost:8080
Ele irá apontar para o index.html que está dentro de src\main\webapp.
<file_sep>/database/Dump20210508.sql
-- MySQL dump 10.13 Distrib 8.0.22, for Win64 (x86_64)
--
-- Host: localhost Database: faixas
-- ------------------------------------------------------
-- Server version 8.0.22
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!50503 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `cliente`
--
DROP TABLE IF EXISTS `cliente`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `cliente` (
`id` int NOT NULL AUTO_INCREMENT,
`nome` varchar(100) NOT NULL,
`cpf` varchar(15) NOT NULL,
`rua` varchar(100) NOT NULL,
`numero` int NOT NULL,
`complemento` varchar(30) DEFAULT NULL,
`bairro` varchar(100) NOT NULL,
`cep` varchar(15) NOT NULL,
`cidade` varchar(100) NOT NULL,
`telefone` varchar(30) NOT NULL,
`email` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=56 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `cliente`
--
LOCK TABLES `cliente` WRITE;
/*!40000 ALTER TABLE `cliente` DISABLE KEYS */;
INSERT INTO `cliente` VALUES (1,'<NAME>','11322266603','Av dos Curios',501,'Bloco 18 Ap 403','Pontal','38055100','Uberaba','99460013','<EMAIL>');
/*!40000 ALTER TABLE `cliente` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `faixa`
--
DROP TABLE IF EXISTS `faixa`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `faixa` (
`id` int NOT NULL AUTO_INCREMENT,
`altura` decimal(6,2) NOT NULL,
`largura` decimal(6,2) NOT NULL,
`texto` varchar(200) NOT NULL,
`cor_faixa` varchar(50) NOT NULL,
`cor_texto` varchar(50) NOT NULL,
`valor_faixa` decimal(9,2) NOT NULL,
`pedido` int DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=39 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `faixa`
--
LOCK TABLES `faixa` WRITE;
/*!40000 ALTER TABLE `faixa` DISABLE KEYS */;
INSERT INTO `faixa` VALUES (1,50.00,150.00,'Arthur é chato','green','black',60.00,1);
/*!40000 ALTER TABLE `faixa` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `hibernate_sequence`
--
DROP TABLE IF EXISTS `hibernate_sequence`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `hibernate_sequence` (
`next_val` bigint DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `hibernate_sequence`
--
LOCK TABLES `hibernate_sequence` WRITE;
/*!40000 ALTER TABLE `hibernate_sequence` DISABLE KEYS */;
INSERT INTO `hibernate_sequence` VALUES (56);
/*!40000 ALTER TABLE `hibernate_sequence` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `pedido`
--
DROP TABLE IF EXISTS `pedido`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `pedido` (
`id` int NOT NULL AUTO_INCREMENT,
`data` datetime NOT NULL,
`previsao_entrega` datetime DEFAULT NULL,
`valor_servico` decimal(9,2) NOT NULL,
`valor_sinal` decimal(9,2) NOT NULL,
`data_inicio_prod` datetime DEFAULT NULL,
`data_fim_prod` datetime DEFAULT NULL,
`data_real_entrega` datetime DEFAULT NULL,
`status` char(2) DEFAULT NULL,
`cliente` int DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=40 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `pedido`
--
LOCK TABLES `pedido` WRITE;
/*!40000 ALTER TABLE `pedido` DISABLE KEYS */;
INSERT INTO `pedido` VALUES (1,'2020-11-21 15:00:00','2020-11-27 15:00:00',100.00,50.00,'2020-11-22 15:00:00','2020-11-27 15:00:00','2020-11-28 15:00:00','F',1);
/*!40000 ALTER TABLE `pedido` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping events for database 'faixas'
--
--
-- Dumping routines for database 'faixas'
--
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2021-05-08 17:03:21
<file_sep>/src/main/webapp/pages/clientes/clientes.js
function addClientes() {
$.ajax({
url: "/cliente/add",
type: "POST",
data: {
nome: "Camila",
cpf: "12345678910",
rua: "<NAME>",
numero: 001,
complemento: "Apto 001",
bairro: "Pontal",
cep: "38055100",
cidade: "Uberaba",
telefone: "12345678910",
email: "<EMAIL>",
},
}).done(function (addClientesResponse) {
// TODO: Porque salvar um seletor dentro de uma variável?
var toaster = $(".toast");
toaster.find(".toast-body").text(addClientesResponse);
toaster.toast("show");
initClientes();
});
}
function deleteCliente(id) {
$.ajax({
url: "/cliente/delete",
type: "DELETE",
data: {
id: id,
},
}).done(function (deleteClienteResponse) {
var toaster = $(".toast");
toaster.find(".toast-body").text(deleteClienteResponse);
toaster.toast("show");
initClientes();
});
}
function initClientes() {
$("#title").text("Clientes");
// Busca a lista de clientes
$.ajax({
url: "/cliente/all",
}).done(function (clientes) {
let tabelaclientesHTML =
"" +
"<tr>" +
"<th scope='col'>ID</th>" +
"<th> Nome </th>" +
"<th> CPF </th>" +
"<th> Rua </th>" +
"<th> Número </th>" +
"<th> Complemento </th>" +
"<th> Bairro </th>" +
"<th> Cep </th>" +
"<th> Cidade </th>" +
"<th> Telefone </th>" +
"<th> Email </th>" +
"<th> </th>" +
"</tr>";
for (let idxClientes = 0; idxClientes < clientes.length; idxClientes++) {
// prettier-ignore
tabelaclientesHTML +=
"" +
"<tr>" +
"<th scope='row'> " +
clientes[idxClientes].id +
" </th>" +
"<td> " +
clientes[idxClientes].nome +
" </td>" +
"<td> " +
clientes[idxClientes].cpf +
" </td>" +
"<td> " +
clientes[idxClientes].rua +
" </td>" +
"<td> " +
clientes[idxClientes].numero +
" </td>" +
"<td> " +
clientes[idxClientes].complemento +
" </td>" +
"<td> " +
clientes[idxClientes].bairro+
" </td>" +
"<td> " +
clientes[idxClientes].cep+
" </td>" +
"<td> " +
clientes[idxClientes].cidade+
" </td>" +
"<td> " +
clientes[idxClientes].telefone+
" </td>" +
"<td> " +
clientes[idxClientes].email+
" </td>" +
"<td> " +
"<button onclick='deleteCliente(" + clientes[idxClientes].id + ")'>" +
"<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='currentColor' class='bi bi-trash' viewBox='0 0 16 16'>" +
"<path d='M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0V6z'/>" +
"<path fill-rule='evenodd' d='M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1v1zM4.118 4 4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4H4.118zM2.5 3V2h11v1h-11z'/>" +
"</svg>" +
"</button>" +
" </td>" +
"</tr>";
}
$("#tabela-clientes").html(tabelaclientesHTML);
});
}
| 9dc0794cd14f170359894a9b5e14fa5eb850a67e | [
"JavaScript",
"Java",
"Markdown",
"SQL"
] | 8 | JavaScript | Noghss/faixas-API | 8f9a7ad53a1d98327c1276b9891a28fe49a91d9a | e4500b5bf9a574307f58ca0e0c087df36f9d86f4 |
refs/heads/master | <file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UACompatiible" content="ie=edge">
<title>Document</title>
</head>
<body>
<?php
foreach ($siswa->show($_GET['id']) as $key) {
$id = $data['id'];
$nis = $data['nis'];
$nama = $data['nama'];
$alamat = $data['alamat'];
}
?>
<fieldset>
<legend>edit data siswa</legend>
<form action="/siswa/proses.php?aksi=update" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>">
<table>
<tr>
<th>Nomor Induk Siswa</th>
<td>input type="number" name="id" value="<?php echo $nis; ?>" readonly></td>
</tr>
<tr>
<th>Nama Siswa</th>
<td>input type="text" name="nama" value="<?php echo $nama; ?>" readonly></td>
</tr>
<tr>
<th>alamat</th>
<td><textarea name="alamat" cols="40" readonly><?php echo $alamat; ?></textarea></td>
</tr>
</table>
</form>
</fieldset>
</boddy>
</html>
<file_sep><?php
include '../database.php';
$biodata = new biodata();
$aksi = $_GET['aksi'];
if (isset($_POST['save'])) {
$id = $_POST['id'];
$nama = $_POST['nama'];
$alamat = $_POST['alamat'];
$jenis_kelamin = $_POST['jenkel'];
$umur = $_POST['umur'];
$aksi = $_POST['aksi'];
}
if ($aksi == "tambah") {
$biodata->create(
$no,
$nama,
$alamat,
$jenis_kelamin,
$agama,
$tgl_lahir,
$umur,
$aksi
);
header("location:index.php");
} elseif ($aksi == "update") {
$biodata->update(
$no,
$nama,
$alamat,
$jenis_kelamin,
$agama,
$tgl_lahir,
$umur,
$aksi
);
header("location:index.php");
} elseif ($aksi == "delete") {
$biodata->delete($_GET['id']);
header("location:index.php");
}
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Latihan CRUD - Edit Data</title>
</head>
<body>
<?php
include '../database.php';
$biodata = new biodata();
foreach ($biodata > edit($_GET['id']) as $data) {
$id = $data['id'];
$nis = $data['nis'];
$nama = $data['nama'];
$alamat = $data['alamat'];
}
?>
<fieldset>
<legend>Edit Data biodata</legend>
<form action="proses.php?aksi=update" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>">
<table>
<tr>
<th>Nomor biodata</th>
<td><input type="number" name="no" value="<?php echo $nis; ?>" required></td>
</tr>
<tr>
<th>Nama</th>
<td><input type="text" name="nama" value="<?php echo $nama; ?>" required></td>
</tr>
<tr>
<th>Alamat</th>
<td><textarea name="alamat" required><?php echo $alamat; ?></textarea></td>
</tr>
<tr>
<th>Jenis_Kelamin</th>
<td><input type="date" name="jenkel" required><?php echo $jenkel; ?></in></td>
</tr>
<tr>
<th>Agama</th>
<td><textarea name="agama" required><?php echo $agama; ?></textarea></td>
</tr>
<tr>
<th>tgl_lahir</th>
<td><textarea name="tgl_lahir" required><?php echo $tgl_lahir; ?></textarea></td>
</tr>
<tr>
<th>umur</th>
<td><textarea name="umur" required><?php echo $alamat; ?></textarea></td>
</tr>
<tr>
<th><input type="submit" name="save" value="Simpan"></th>
</tr>
</table>
</form>
</fieldset>
</body>
</html>
<file_sep><?php
class biodata extends Database
{
//Menampilkan Semua Data
public function index()
{
$databiodata = mysqli_query($this->koneksi, "select * from siswa");
//var_dump($datasiswa);
return $datasiswa;
}
//Menambah Data
public function create($nis, $nama, $alamat)
{
mysqli_query(
this - koneksi,
"insert into biodata value (null, 'no','nama','alamat','agama','jenkel','tgl_lahir','umur')"
);
}
// Menampilkan Data Berdasarkan ID
public function show($id)
{
$databiodata = mysqli_query($this->koneksi, "select * from biodata id='$id'");
return $datasbiodata;
}
//mengupdate data berdasarkan id
public function update($id, $nis, $nama, $alamat)
{
mysqli_query(
$this->koneksi,
"update biodata set no='$no',nama='$nama',
alamat='alamat',agama='agama', jenkel='jenkel','tgl_lahir='tgl_lahir',umur='umur' where id='$id'"
);
}
public function delete($id)
{
mysqli_query($this->$koneksi, "delete from biodata where id='$id'");
}
}
?>
| 9379cc01997d78ec7ce9afb0e684dfeca2cd2a73 | [
"PHP"
] | 4 | PHP | rizalfadilah/enkapsulasi | e31bdd722eaf604a2f7ea78bd51e87e88015b381 | fbf814b4c664bede4eb64f2b112d95ee7d0cd9de |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsProgramAss
{
abstract class Quadrilateral
{
//public int Length;
abstract public int Area(int Length);
}
class Sqaure : Quadrilateral
{
public override int Area(int Length)
{
return Length * Length;
}
}
class Rectangle : Quadrilateral
{
int Breath;
public Rectangle(int _breath)
{
Breath = _breath;
}
public override int Area(int Length)
{
return Breath * Length;
}
}
class Program
{
static void Main(string[] args)
{
Sqaure s = new Sqaure();
Console.WriteLine(s.Area(5));
Rectangle r = new Rectangle(6);
Console.WriteLine(r.Area(4));
Console.ReadLine();
}
}
}
| 72692a5ccb595638acc6cf0c1a15666eb72fc5f1 | [
"C#"
] | 1 | C# | Akash707985/InheritenceAssignment | 92f73ac972228b3b9ee07912d1f24f6d79eac27f | 859cf91f8e586f1593b28422b51edd33dcd300f1 |
refs/heads/master | <file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BreadcrumbComponent } from './breadcrumb/breadcrumb.component';
import { ReportClassModule } from './report-class/report-class.module';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
@NgModule({
declarations: [BreadcrumbComponent],
imports: [
CommonModule,
ReportClassModule,
NgbModule,
],
exports: [BreadcrumbComponent, ReportClassModule,]
})
export class DashboardModule { }
<file_sep>import { Component, OnInit, Input } from '@angular/core';
// services
import { ApiService } from '../../../services/api.service';
@Component({
selector: 'app-action-bar',
templateUrl: './action-bar.component.html',
styleUrls: ['./action-bar.component.scss']
})
export class ActionBarComponent implements OnInit {
teachers: any[] = [];
aulas: any[] = [];
checkins: any[] = [];
constructor(private _apiService: ApiService) {
}
ngOnInit() {
// get all teachers
this._apiService.getTeachers()
.subscribe(data => {
this.teachers = data
// console.log(data);
});
// get all types of aulas
this._apiService.getTeachersTypeClass()
.subscribe(data => {
this.aulas = data
// console.log(data);
});
// get all types of checkins
this._apiService.getCheckins()
.subscribe(data => {
this.checkins = data;
// console.log(data);
});
}
}
<file_sep>export interface Teachers {
id: number,
nome: string,
email: string,
total_aulas: number,
avatar_url: string
}
<file_sep>import { Deserializable } from './deserializable';
export class Teachers implements Deserializable {
public id: number;
public name: string;
public email: string;
public avatar_url: string;
deserialize(input: any): this {
return Object.assign(this, input);
// this.tipo_turma = input.tipo_turma.map(tipo_turma => new TiposTurma().deserialize(tipo_turma));
// return this;
}
getFullName() {
return this.name + ' ' + this.email;
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
// services
import { ApiService } from '../../../services/api.service';
import { ModalService } from '../../modal/modal.service';
@Component({
selector: 'app-teachers',
templateUrl: './teachers.component.html',
styleUrls: ['./teachers.component.scss']
})
export class TeachersComponent implements OnInit {
teachers: any[] = [];
tipo_turma;
constructor(
private _apiService: ApiService,
private _modalService: ModalService
) { }
ngOnInit() {
// get all teachers
this._apiService.getTeachers()
.subscribe(data => {
this.teachers = data
// console.log('teachers...', data);
});
this._apiService.getTeachersTypeClass()
.subscribe(data => {
this.tipo_turma = data;
// console.log('tipoturma...', data);
});
}
openModal(id: string) {
this._modalService.open(id);
}
closeModal(id: string) {
this._modalService.close(id);
}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Teachers } from '../models/teachers';
import { Aulas } from '../models/aulas';
import { Checkins } from '../models/checkins';
@Injectable({
providedIn: 'root'
})
export class ApiService {
API_KEY = 'your_api_key'; // not using yet
// private _url: string = 'https://api.myjson.com/bins/o535b';
private _url: string = './assets/data.json';
private _urlAulas: string = './assets/data-aulas.json';
private _urlCheckins: string = './assets/data-checkins.json';
constructor(private httpClient: HttpClient) { }
// teachers
public getTeachers(): Observable<Teachers[]> {
return this.httpClient.get<Teachers[]>(this._url);
}
// aulas
public getTeachersTypeClass(): Observable<Aulas[]> {
return this.httpClient.get<Aulas[]>(this._urlAulas);
}
// checkins
public getCheckins(): Observable<Checkins[]> {
return this.httpClient.get<Checkins[]>(this._urlCheckins);
}
}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { ActionBarComponent } from './action-bar/action-bar.component';
import { TeachersComponent } from './teachers/teachers.component';
import { ModalModule } from '../modal/modal.module';
@NgModule({
declarations: [ActionBarComponent, TeachersComponent],
imports: [
CommonModule,
HttpClientModule,
FormsModule,
ModalModule
],
exports: [ActionBarComponent, TeachersComponent],
})
export class ReportClassModule { }
<file_sep>import { Deserializable } from './deserializable';
export class Aulas implements Deserializable {
public id: number;
public name: string;
deserialize(input: any): this {
return Object.assign(this, input);
}
}
| 4fcbc16a37f6ee66b434386b2e01b4ab8dbfaa0c | [
"TypeScript"
] | 8 | TypeScript | jpcmf/angular-class-report | df17e58e9f62d1041aabefaaa8b28a50eed54228 | 2d18987278e0a35d57626360f0a6e1bf5ab50dbc |
refs/heads/master | <file_sep>module.exports = (sequelize, DataTypes) => {
const account = sequelize.define(
'account',
{
balance: DataTypes.INTEGER
},
{
underscored: true
}
);
account.associate = function(models) {
account.hasMany(models.flow);
};
return account;
};
<file_sep>const models = require('./../models'),
Flow = models.flow,
Account = models.account;
const retry = require('retry-as-promised'),
Sequelize = require('sequelize'),
asyncRetry = require('async-retry');
exports.index = (req, res, next) => {
return Account.findAll()
.then(accounts => {
console.log('Seding all accounts');
return res.send({ accounts });
})
.catch(e => {
console.log('Some error with index: ', e);
return next(e);
});
};
exports.show = (req, res, next) => {
return Account.findById(req.params.id)
.then(account => {
console.log('Showing account with id: ', account.id);
return res.send({ account });
})
.catch(e => {
console.log('Some error with show: ', e);
return next(e);
});
};
exports.createNewAccount = (req, res, next) => {
return Account.create({ balance: 0 })
.then(account => {
console.log('Create succesfulyy account with id: ', account.id);
return res.status(201).send({ account });
})
.catch(e => {
console.log('Some error with createNewAccount: ', e);
return next(e);
});
};
const _deposit = (id, amount) => {
return models.sequelize
.transaction({ isolationLevel: models.Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE })
.then(transaction => {
return Account.findById(id, { transaction, lock: transaction.LOCK.UPDATE })
.then(account => {
const oldBalance = account.balance;
const newBalance = oldBalance + amount;
console.log(`Founded account, with balance: ${oldBalance}, newBalance: ${newBalance}`);
return account.update({ balance: newBalance }, { transaction }).then(updatedAccount => {
return Flow.create(
{
accountId: id,
newBalance,
oldBalance,
delta: amount
},
{ transaction }
).then(() => {
return transaction.commit().then(() => {
console.log('Updated account correctly, new Balance: ', updatedAccount.balance);
return updatedAccount;
});
});
});
})
.catch(error => {
return transaction.rollback().then(() => {
throw error;
});
});
});
};
exports.deposit = (req, res, next) => {
const amount = req.body.amount;
const id = req.params.id;
asyncRetry(
bail => {
return _deposit(id, amount).catch(error => {
const regex = /(deadlock|rollback|TimeoutError|OptimisticLockError|ConnectionTimedOutError|ConnectionRefusedError|ConnectionError|timed out)/i;
if (regex.test(error.message) || regex.test(error.toString)) {
console.log('Error related with transaction or deadlock, going to retry?');
throw error;
}
console.log('Another error, bailing ', error.message, error.toString());
return bail(error);
});
},
{
retries: 10,
minTimeout: 500,
randomize: true,
onRetry: (error, i) => {
console.log('onRetry Function, actual error:', error.message);
console.log('Retry number: ', i);
}
}
)
.then(account => {
res.send({ account });
})
.catch(error => {
res.status(501).send({ error: error.message });
});
};
// exports.deposit = (req, res, next) => {
// const amount = req.body.amount;
// const id = req.params.id;
// retry(
// options => {
// console.log('OPTIONS:', options.current);
// return deposit(id, amount);
// },
// {
// max: 10,
// timeout: 10000,
// match: [
// Sequelize.ConnectionError,
// Sequelize.ConnectionRefusedError,
// Sequelize.ConnectionTimedOutError,
// Sequelize.OptimisticLockError,
// Sequelize.TimeoutError,
// /ROLLBACK TRANSACTION/i,
// /deadlock/i
// ]
// }
// )
// .then(account => {
// res.send({ account });
// })
// .catch(error => {
// res.status(501).send({ error: error.message });
// });
// };
<file_sep>const accounts = require('./controllers/accounts'),
flows = require('./controllers/flows');
exports.init = app => {
app.post('/accounts', accounts.createNewAccount);
app.get('/accounts', accounts.index);
app.get('/accounts/:id', accounts.show);
app.post('/accounts/:id/deposit', accounts.deposit);
app.get('/accounts/:accountId/flows', flows.byAccountId);
};
<file_sep>const models = require('./../models'),
Account = models.account;
exports.byAccountId = (req, res, next) => {
const accountId = req.params.accountId;
return Account.findById(accountId).then(account => {
return account.getFlows().then(flows => {
return res.send({ flows });
});
});
};
<file_sep>module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('flows', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
account_id: {
type: Sequelize.INTEGER,
allowNull: false,
references: {
model: 'accounts',
key: 'id'
}
},
delta: {
type: Sequelize.INTEGER,
allowNull: false
},
old_balance: {
type: Sequelize.INTEGER,
allowNull: false
},
new_balance: {
type: Sequelize.INTEGER,
allowNull: false
},
created_at: {
allowNull: false,
type: Sequelize.DATE
},
updated_at: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('flows');
}
};
<file_sep>module.exports = (sequelize, DataTypes) => {
const flow = sequelize.define(
'flow',
{
accountId: { type: DataTypes.INTEGER, field: 'account_id' },
delta: DataTypes.INTEGER,
oldBalance: { type: DataTypes.INTEGER, field: 'old_balance' },
newBalance: { type: DataTypes.INTEGER, field: 'new_balance' }
},
{
underscored: true
}
);
flow.associate = function(models) {
flow.belongsTo(models.account);
};
return flow;
};
| 92b57ac99484e81fc81b3dc0cca901d9887d6bd4 | [
"JavaScript"
] | 6 | JavaScript | mpizzagalli/sequelize-concurrency-test | ebe39b71ff7ec6ecf8173999337bf8873dcd589e | 4f0269e537fbd4f7eb79ab25003b66c5047f5c9b |
refs/heads/master | <repo_name>jodyn96/sortArray<file_sep>/README.md
# sortArray
Exercise 1:
Given an array of numbers, sort ascending odd numbers but leave even numbers in their original place in the array. Zero does not need to move. If the array is empty, return an empty array.
Examples:
[5, 3, 2, 8, 1, 4] should return [1, 3, 2, 8, 5, 4]
[6, 3, 2, 7, 5, 0] should return [6, 3, 2, 5, 7, 0]
<file_sep>/sortArray.js
//Exercise 1:
//Given an array of numbers, sort ascending odd numbers but leave even numbers in their original place in the array.
//Zero does not need to move.
//If the array is empty, return an empty array.
//Examples:
//[5, 3, 2, 8, 1, 4] should return [1, 3, 2, 8, 5, 4]
//[6, 3, 2, 7, 5, 0] should return [6, 3, 2, 5, 7, 0]
function sortArray(array)
{
//create new array with elements from existing array
var oddArray = array.filter(function (ele) { return (ele % 2) !== 0; }).sort(function (a, b) { return a - b; });
//set variable for new array element
var j = 0;
//set variable for existing array element; define condition; increase value
for (var i = 0; i < array.length; i++)
{
if (array[i] % 2)
{
array[i] = oddArray[j];
j++;
}
}
return array;
}
//sortArray([5, 3, 2, 8, 1, 4]);
//sortArray([6, 3, 2, 7, 5, 0]);
sortArray([0, 2, 5, 8, 3, 1, 9, 3, 6, 1, 0, 7]);
//sortArray([]);
| e96473134c44779100e85715b471b441bc5ef14d | [
"Markdown",
"JavaScript"
] | 2 | Markdown | jodyn96/sortArray | b895ed6e7b311979992203754724d84867c57e39 | 3a0de797c747cff1906302ed5b6ebf74804b262f |
refs/heads/master | <repo_name>hmerritt/node-db4-project<file_sep>/data/seeds/02-steps.js
exports.seed = function (knex) {
return knex("steps").insert([
{
id: 1,
recipe_id: 1,
order: 1,
instruction: "Heat the oven to 180c/fan 160c/gas 4",
},
{
id: 2,
recipe_id: 1,
order: 2,
instruction:
"Beat all the cake ingredients together in a large bowl",
},
{
id: 3,
recipe_id: 1,
order: 3,
instruction:
"Bake side by side for 20-25 minutes until the sponges are risen",
},
{
id: 4,
recipe_id: 2,
order: 1,
instruction: "Gather ingredients",
},
{
id: 5,
recipe_id: 2,
order: 2,
instruction: "Make oat biscuits",
},
{
id: 6,
recipe_id: 3,
order: 1,
instruction: "Start by making the sauce",
},
{
id: 7,
recipe_id: 3,
order: 2,
instruction:
"Let this simmer while you boil the noodles and get the cheeses ready",
},
{
id: 8,
recipe_id: 3,
order: 3,
instruction: "Bake until bubbly and you’re ready to eat!",
},
]);
};
<file_sep>/data/seeds/04-recipes-ingredients.js
exports.seed = function (knex) {
return knex("recipes_ingredients").insert([
{ recipe_id: 1, ingredient_id: 1, quantity: 12 },
{ recipe_id: 1, ingredient_id: 2, quantity: 4 },
{ recipe_id: 1, ingredient_id: 7, quantity: 2 },
{ recipe_id: 2, ingredient_id: 5, quantity: 55 },
{ recipe_id: 2, ingredient_id: 2, quantity: 8 },
{ recipe_id: 2, ingredient_id: 7, quantity: 3 },
{ recipe_id: 3, ingredient_id: 4, quantity: 42 },
{ recipe_id: 3, ingredient_id: 3, quantity: 23 },
{ recipe_id: 3, ingredient_id: 6, quantity: 6 },
]);
};
<file_sep>/.eslintrc.js
module.exports = {
"plugins": ["prettier"],
"extends": ["eslint:recommended", "plugin:prettier/recommended"],
"env": {
"node": true
},
"parserOptions": {
"ecmaVersion": 8,
},
"rules": {
"prettier/prettier": [
"error", {
"tabWidth": 4,
"singleQuote": false
}
]
}
}
<file_sep>/data/access.js
const knex = require("knex");
const knexfile = require("../knexfile.js");
const db = knex(knexfile["development"]);
function getRecipes() {
return db("recipes");
}
function getShoppingList(recipe_id) {
return db("ingredients")
.join(
"recipes_ingredients",
"ingredients.id",
"recipes_ingredients.ingredient_id"
)
.and("recipes_ingredients.recipe_id", recipe_id)
.select("ingredients.name", "recipes_ingredients.quantity")
.orderBy("quantity");
// SELECT [ingredients].name as "ingredient", [recipes_ingredients].quantity
// FROM [ingredients]
// JOIN [recipes_ingredients]
// ON [ingredients].id == [recipes_ingredients].ingredient_id
// AND [recipes_ingredients].recipe_id == 1
// ORDER BY [ingredients].name ASC;
}
function getInstructions(recipe_id) {
return db("recipes")
.join("steps", "steps.recipe_id", "recipes.id")
.where("recipes.id", recipe_id)
.select("recipes.name", "steps.instruction")
.orderBy("steps.order");
// SELECT [recipes].name, [steps].instruction
// FROM [recipes]
// JOIN [steps]
// ON [steps].recipe_id == [recipes].Id
// WHERE [recipes].name == "cake"
// ORDER BY [recipes].name AND [steps]."order" ASC;
}
module.exports = {
getRecipes,
getShoppingList,
getInstructions,
};
<file_sep>/queries.sql
-- Self practice SQL queries
-- Gets recipe and instruction
SELECT [recipes].name, [steps].instruction
FROM [recipes]
JOIN [steps]
ON [steps].recipe_id == [recipes].Id
ORDER BY [recipes].name AND [steps]."order" ASC;
-- Get recipe name, ingredient name and quantity
SELECT [recipes].name, [ingredients].name as "ingredient", [recipes_ingredients].quantity
FROM [ingredients]
JOIN [recipes_ingredients]
ON [ingredients].id == [recipes_ingredients].ingredient_id
JOIN [recipes]
ON [recipes].id == [recipes_ingredients].recipe_id
ORDER BY [ingredients].name ASC;
-- List of all ingredients and quantities for a given recipe
SELECT [ingredients].name as "ingredient", [recipes_ingredients].quantity
FROM [ingredients]
JOIN [recipes_ingredients]
ON [ingredients].id == [recipes_ingredients].ingredient_id
AND [recipes_ingredients].recipe_id == 1
ORDER BY [ingredients].name ASC;
<file_sep>/data/seeds/03-ingredients.js
exports.seed = function (knex) {
return knex("ingredients").insert([
{ id: 1, name: "flower" },
{ id: 2, name: "butter" },
{ id: 3, name: "lasagna" },
{ id: 4, name: "beef" },
{ id: 5, name: "oats" },
{ id: 6, name: "cheese" },
{ id: 7, name: "sugar" },
]);
};
| 5a077417ac30dbd7acbc175bdbfcbb01d82cc9b6 | [
"JavaScript",
"SQL"
] | 6 | JavaScript | hmerritt/node-db4-project | 7eef5f934c70e0b9edd229b0bdfc6c5a2b2fb1d3 | caa0b927049d7e1022860f84fe392e02d616b366 |
refs/heads/main | <file_sep>EXEC=perceptron
CFLAGS=-Wall -Wextra -Werror -Wpedantic -std=c99
all: perceptron.o
clang -o $(EXEC) $^ $(CFLAGS) -lm
debug: perceptron.o
clang -g -o $(EXEC) $^ $(CFLAGS) -lm
clean:
rm -rf $(EXEC) *.o
valgrind:
make clean; make debug;
valgrind --leak-check=full ./$(EXEC)
<file_sep>//
// Copyright © 2021 <NAME>, All rights reserved.
//
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <math.h>
#include <stdlib.h>
#define DEFAULT_NUM_INPUTS 3
#define SAMPLE_SIZE 4
#define NUM_INPUTS 3
struct Perceptron {
uint32_t num_inputs;
double *weights;
};
typedef struct Perceptron Perceptron;
// Create a Perceptron
Perceptron *pc_create(uint32_t num_inputs, double initial_weight) {
Perceptron *pc = (Perceptron *)malloc(sizeof(Perceptron));
if (pc) {
pc->num_inputs = (num_inputs == 0) ? DEFAULT_NUM_INPUTS : num_inputs;
uint32_t weight = initial_weight;
pc->weights = (double *)calloc(num_inputs, sizeof(double));
// Initialize the weights
for (uint32_t i = 0; i < pc->num_inputs; i++) {
pc->weights[i] = weight;
}
}
return pc;
}
// Delete a Perceptron
void pc_delete(Perceptron **pc) {
if (*pc && (*pc)->weights) {
free((*pc)->weights);
free(*pc);
}
*pc = NULL;
}
// Calculate the weighted sum and return
double weighted_sum(Perceptron *pc, uint32_t *inputs) {
double weighted_sum = 0.0;
for (uint32_t i = 0; i < pc->num_inputs; i++) {
weighted_sum += pc->weights[i] * inputs[i];
}
return weighted_sum;
}
// Return a result between 1 and 0 using sigmoid function
double activation(int32_t z) {
double denominator = 1.0 + exp(-z);
double result = 1.0/denominator;
return result;
}
// Return a classification threshold of either 0 or 1
// we use 0.5 as a threshold here for ease of understanding
uint32_t threshold(double value) {
double threshold = 0.5;
if (value >= threshold) {
return 1;
}
return 0;
}
// Train the neural network
void training(Perceptron *pc, uint32_t training_set[SAMPLE_SIZE][NUM_INPUTS], uint32_t *expected_data, uint32_t training_data_size) {
bool found_line = false;
uint32_t iterations = 0;
while (!found_line) {
printf("iterations=%d\n", iterations);
double total_error = 0;
for (uint32_t i = 0; i < training_data_size; i++) {
// Calculate the weighted_sum and pass it through activation function
double prediction_old = activation(weighted_sum(pc, training_set[i]));
uint32_t prediction = threshold(prediction_old);
// Check prediction against predicted data, and calculate the loss
uint32_t actual = expected_data[i];
int32_t error = actual - prediction;
total_error += abs(error);
// adjust the weight
for (uint32_t j = 0; j < pc->num_inputs; j++) {
pc->weights[j] += (int32_t)(error * training_set[i][j]);
}
}
printf("[error] %f\n", total_error);
// End the training process when the total error is 0
if (total_error < 0.01) {
found_line = true;
printf("Training completed! Total Error=%.5f\n", total_error);
}
iterations++;
}
}
// Return the prediction and confidence for a given testing data set
void predict(Perceptron *pc, uint32_t *testing_set) {
double final_prob = 0.0;
// Calculate the weighted_sum and pass it through activation function
double probability = activation(weighted_sum(pc, testing_set));
uint32_t prediction = threshold(probability);
if (prediction == 1) {
final_prob = probability;
} else {
final_prob = 1 - probability;
}
printf("Prediction: %d\n", prediction);
printf("probability: %.5f\n", final_prob);
}
int main() {
// Create a Perceptron
Perceptron *pc = pc_create(NUM_INPUTS, 1.0);
// Create training data
// Use the prediction result of (A - (B + C) > 0) to build the dataset
uint32_t small_training_set[SAMPLE_SIZE][NUM_INPUTS] = {
{ 1, 1, 0 },
{ 2, 0, 1 },
{ 3, 2, 0 },
{ 4, 5, 1 }
};
// Create expected result
uint32_t expected_result[SAMPLE_SIZE] = { 0, 1, 1, 0 };
// Train the model
training(pc, small_training_set, expected_result, SAMPLE_SIZE);
// Test the model, true case
uint32_t small_testing_data[NUM_INPUTS] = { 3, 1, 1 };
printf("Start prediction, testing_set=");
for (int i = 0; i < NUM_INPUTS; i++) {
printf("%d ", small_testing_data[i]);
}
printf("\n");
uint32_t expected = 1;
predict(pc, small_testing_data);
printf("Expected: %d\n", expected);
// Test the model, false case
uint32_t small_testing_data2[NUM_INPUTS] = { 3, 5, 6 };
printf("Start prediction, testing_set=");
for (int i = 0; i < NUM_INPUTS; i++) {
printf("%d ", small_testing_data2[i]);
}
printf("\n");
uint32_t expected2 = 0;
predict(pc, small_testing_data2);
printf("Expected: %d\n", expected2);
// garbage collection
pc_delete(&pc);
}
<file_sep># Source from Codecademy
import operator
from collections import Counter
import random
import numpy as np
np.random.seed(1)
random.seed(1)
def split(dataset, labels, column):
data_subsets = []
label_subsets = []
counts = list(set([data[column] for data in dataset]))
counts.sort()
for k in counts:
new_data_subset = []
new_label_subset = []
for i in range(len(dataset)):
if dataset[i][column] == k:
new_data_subset.append(dataset[i])
new_label_subset.append(labels[i])
data_subsets.append(new_data_subset)
label_subsets.append(new_label_subset)
return data_subsets, label_subsets
def gini(dataset):
impurity = 1
label_counts = Counter(dataset)
for label in label_counts:
prob_of_label = label_counts[label] / len(dataset)
impurity -= prob_of_label ** 2
return impurity
def information_gain(starting_labels, split_labels):
info_gain = gini(starting_labels)
for subset in split_labels:
info_gain -= gini(subset) * len(subset)/len(starting_labels)
return info_gain
class Leaf:
def __init__(self, labels, value):
self.labels = Counter(labels)
self.value = value
class Internal_Node:
def __init__(self,
feature,
branches,
value):
self.feature = feature
self.branches = branches
self.value = value
def find_best_split_subset(dataset, labels, num_features):
features = np.random.choice(6, 3, replace=False)
best_gain = 0
best_feature = 0
for feature in features:
data_subsets, label_subsets = split(dataset, labels, feature)
gain = information_gain(labels, label_subsets)
if gain > best_gain:
best_gain, best_feature = gain, feature
return best_feature, best_gain
def find_best_split(dataset, labels):
best_gain = 0
best_feature = 0
for feature in range(len(dataset[0])):
data_subsets, label_subsets = split(dataset, labels, feature)
gain = information_gain(labels, label_subsets)
if gain > best_gain:
best_gain, best_feature = gain, feature
return best_feature, best_gain
def build_tree(data, labels, value = ""):
best_feature, best_gain = find_best_split(data, labels)
if best_gain < 0.00000001:
return Leaf(Counter(labels), value)
data_subsets, label_subsets = split(data, labels, best_feature)
branches = []
for i in range(len(data_subsets)):
branch = build_tree(data_subsets[i], label_subsets[i], data_subsets[i][0][best_feature])
branches.append(branch)
return Internal_Node(best_feature, branches, value)
def build_tree_forest(data,labels, n_features, value=""):
best_feature, best_gain = find_best_split_subset(data, labels, n_features)
if best_gain < 0.00000001:
return Leaf(Counter(labels), value)
data_subsets, label_subsets = split(data, labels, best_feature)
branches = []
for i in range(len(data_subsets)):
branch = build_tree_forest(data_subsets[i], label_subsets[i], n_features, data_subsets[i][0][best_feature])
branches.append(branch)
return Internal_Node(best_feature, branches, value)
def print_tree(node, spacing=""):
"""World's most elegant tree printing function."""
question_dict = {0: "Buying Price", 1:"Price of maintenance", 2:"Number of doors", 3:"Person Capacity", 4:"Size of luggage boot", 5:"Estimated Saftey"}
# Base case: we've reached a leaf
if isinstance(node, Leaf):
print (spacing + str(node.labels))
return
# Print the question at this node
print (spacing + "Splitting on " + question_dict[node.feature])
# Call this function recursively on the true branch
for i in range(len(node.branches)):
print (spacing + '--> Branch ' + node.branches[i].value+':')
print_tree(node.branches[i], spacing + " ")
def make_cars():
f = open("car.data", "r")
cars = []
for line in f:
cars.append(line.rstrip().split(","))
return cars
def change_data(data):
dicts = [{'vhigh' : 1.0, 'high' : 2.0, 'med' : 3.0, 'low' : 4.0},
{'vhigh' : 1.0, 'high' : 2.0, 'med' : 3.0, 'low' : 4.0},
{'2' : 1.0, '3' : 2.0, '4' : 3.0, '5more' : 4.0},
{'2' : 1.0, '4' : 2.0, 'more' : 3.0},
{'small' : 1.0, 'med' : 2.0, 'big' : 3.0},
{'low' : 1.0, 'med' : 2.0, 'high' : 3.0}]
for row in data:
for i in range(len(dicts)):
row[i] = dicts[i][row[i]]
return data
def classify(datapoint, tree):
if isinstance(tree, Leaf):
return max(tree.labels.items(), key=operator.itemgetter(1))[0]
value = datapoint[tree.feature]
for branch in tree.branches:
if branch.value == value:
return classify(datapoint, branch)
#return classify(datapoint, tree.branches[random.randint(0, len(tree.branches)-1)])
cars = make_cars()
random.shuffle(cars)
car_data = [x[:-1] for x in cars]
car_labels = [x[-1] for x in cars]
<file_sep># Single-layer Percetron Algorithm
- This is an implementation of the single-layer perceptron algorithm
# The algorithm
- The algorithm have two parts, forward propagation, and back propagation, the program works by looping through forward prop, get an output, calculate a loss using a certain loss function, and than use backward prop to adjust the values of all the weights until the error rate is lower than a certain number.
### Forward propagation
- This is the process of combining all the inputs into a value between 0 and 1
- 1. Assign a random weight to each of the input nodes
- 2. Multiply each input value by their corresponding weight to get a weighted input
- 3. At all the weighted input together to get a weighted sum
- 4. Pass the weighted sum into an activation function, we are using sigmoid function here, the point of the activation function is to map the weighted sum into a value between a specific range, in this case, it is to map it between 0 and 1.
- 5. The output of the activation function is the final prediction
### Backward propagation
- This is the process of adjusting the weights in order to get the best prediction
- 1. Take the output from forward prop
- 2. Calculate a loss
- 3. Run it through an algorithm like stochastic gradient descent in order to adjust all the weights
- 4. Run forward prop again with the adjusted weights
- 5. Repeat the process until a certain amount of iterations(EPOCH), or until the error rate is below a certain acceptable value

# Define
- Here are the macro that are defined
```cpp
#define DEFAULT_NUM_INPUTS 3
#define SAMPLE_SIZE 4
#define NUM_INPUTS 3
```
# Perceptron
- This struct acts like a class, and it store all the weights of the neural network
```cpp
struct Perceptron {
uint32_t num_inputs;
double *weights;
};
```
### pc create
- Create a Perceptron
```cpp
Perceptron *pc_create(uint32_t num_inputs, double initial_weight) {
pc = allocate memory of size Perceptron
if pc exist {
if num_inputs is 0, set the number of inputs to default num_input, else, let the num_input to be the provided num_inputs
for i from 0 to num_inputs {
set weight at index i to be the initial_weight
}
}
return pc
}
```
### pc delete
- Delete the Perceptron and free all the memory of the struct
```cpp
void pc_delete(Perceptron **pc) {
if pc and the weights array exist {
free the weight array
free the pc pointer
}
set the pc pointer to NULL
}
```
### weighted sum
- Calculate the weighted sum of the entire input set
```cpp
double weighted_sum(Perceptron *pc, uint32_t *inputs) {
set the weighted_sum to 0
for i from 0 to num_inputs {
multiply the weight at index i of the weight array by the input at index i of the input set and add the result to weighted_sum
}
return the weighted sum
}
```
### activation
- This is the activation function, in this function we use sigmoid function to map the weighted sum between 0 and 1 so we can get a correct boolean output
```cpp
double activation(int32_t z) {
donominator = 1 + e^(-z)
result = 1 / denominator
return the result
}
```
### threshold
- map the output to a number that is either 1 or 0, so the final output is boolean
```cpp
uint32_t threshold(double value) {
threshold = 0.5
if the value is bigger than the threshold {
return 1
} else {
return 0
}
}
```
### training
- This is the training loop, it contains both the forward prop and the backward prop
```cpp
void training(Perceptron *pc, uint32_t training_set[SAMPLE_SIZE][NUM_INPUTS],
uint32_t *expected_data, uint32_t training_data_size) {
// A neural network is like a function, that is trying to draw a line of best fit
// between the input and the expected output
found_line = false
iterations = 0
while the line of best fit is not found {
total_error = 0
for i from 0 to training_data_size {
// forward prop
prediction_old = the output of activation function with the weighted sum of the index i of training_set as the input
prediction = the output of the threshold function with prediction_old as the input
// Calculate the loss that can be used in backward prop
actual = index i of the expected_data array
error = actual - prediction
total_error += the absolute value of the error
// backward prop
for j from 0 to num_inputs {
the weights at index j += error multiply by index [i][j] of the training_set
}
}
if the total error < 0.01 {
// We have reached out expected accuracy
set found_line to true
}
iterations++
}
}
```
### predict
- Run the forward prop with the testing data set, using the already adjusted weights
```cpp
void predict(Perceptron *pc, uint32_t *testing_set) {
final_prob = 0
probability = the output of activation function with the weighted sum of the entire testing_set
prediction = the output of the threshold function with probability as the input
if prediction is 1 {
final_prob = probability
} else {
final_prob = 1 - probability
}
print both the prediction and the probability
}
```
<file_sep># Manual implementation of a KNN algorithm from codecademy
# To predict a movie's rating
from movies import training_set, training_labels, validation_set, validation_labels, normalize_point
def distance(movie1, movie2):
"""euclidean distance implementation"""
squared_difference = 0
for i in range(len(movie1)):
squared_difference += (movie1[i] - movie2[i]) ** 2
final_distance = squared_difference ** 0.5
return final_distance
def classify(unknown, dataset, labels, k):
"""KNN algorithm implementation"""
distances = []
#Looping through all points in the dataset
for title in dataset:
movie = dataset[title]
distance_to_point = distance(movie, unknown)
#Adding the distance and point associated with that distance
distances.append([distance_to_point, title])
distances.sort()
#Taking only the k closest points
neighbors = distances[0:k]
num_good = 0
num_bad = 0
for neighbor in neighbors:
title = neighbor[1]
if labels[title] == 0:
num_bad += 1
elif labels[title] == 1:
num_good += 1
if num_good > num_bad:
return 1
else:
return 0
# Check existances
print("Call Me By Your Name" in training_set)
# Data points
my_movie = [350000, 132, 2017]
# Normalize
normalized_my_movie = normalize_point(my_movie)
# Prediction
print(classify(normalized_my_movie, training_set, training_labels, 5))
def find_validation_accuracy(training_set, training_labels, validation_set, validation_labels, k):
num_correct = 0.0
for i in validation_set:
guess = classify(validation_set[i], training_set, training_labels, k)
if guess == validation_labels[i]:
num_correct += 1
error = num_correct / len(validation_set)
return error
result = find_validation_accuracy(training_set, training_labels, validation_set, validation_labels, 3)
print(result)
<file_sep># A single perceptron network that simulate an OR gate
from sklearn.linear_model import Perceptron
import matplotlib.pyplot as plt
import numpy as np
from itertools import product
# Data set of different logic gates
data = [[0,0],[0,1],[1,0],[1,1]]
labels = [0,1,1,1]
# Scatter Plot of Data
x = [i[0] for i in data]
y = [i[1] for i in data]
c = [i for i in labels]
plt.scatter(x,y,c=labels)
# ML Model
classifier = Perceptron(max_iter=40)
classifier.fit(data, labels)
# Get score
print(classifier.score(data, labels))
# Decision Function
print(classifier.decision_function([[0, 0], [1, 1], [0.5, 0.5]]))
# Set Up Heat Map
x_values = np.linspace(0,1,100)
y_values = np.linspace(0,1,100)
point_grid = list(product(x_values, y_values))
distances = classifier.decision_function(point_grid)
abs_distances = [abs(i) for i in distances]
abs_distances_2d = np.reshape(abs_distances, (100,100))
# Draw Map
heatmap = plt.pcolormesh(x_values, y_values, abs_distances_2d)
plt.colorbar(heatmap)
# predict
x_test = [[0,0],[1,1],[1,0],[1,0],[0,0]]
y_test = [0,1,1,1,0]
print(classifier.predict(x_test))
print(classifier.score(x_test, y_test))
plt.show()
<file_sep># Source from Codecademy
from tree import build_tree, print_tree, car_data, car_labels, classify
import random
random.seed(4)
# The features are the price of the car, the cost of maintenance, the number of doors, the number of people the car can hold, the size of the trunk, and the safety rating
unlabeled_point = ['high', 'vhigh', '3', 'more', 'med', 'med']
predictions = []
for i in range(20):
indices = [random.randint(0, 999) for i in range(1000)]
data_subset = [car_data[index] for index in indices]
labels_subset = [car_labels[index] for index in indices]
subset_tree = build_tree(data_subset, labels_subset)
result = classify(unlabeled_point, subset_tree)
predictions.append(result)
print(predictions)
final_prediction = max(predictions, key=predictions.count)
print(final_prediction)
<file_sep># Calculate the log loss
import numpy as np
from exam import passed_exam, probabilities, probabilities_2
# Function to calculate log-loss
def log_loss(probabilities,actual_class):
return np.sum(-(1/actual_class.shape[0])*(actual_class*np.log(probabilities) + (1-actual_class)*np.log(1-probabilities)))
# Print passed_exam here
print(passed_exam)
# Calculate and print loss_1 here
loss_1 = log_loss(probabilities, passed_exam)
print(loss_1)
# Calculate and print loss_2 here
loss_2 = log_loss(probabilities_2, passed_exam)
print(loss_2)
<file_sep># Actual movies.py from codecademy
import pandas as pd
from random import shuffle, seed
import numpy as np
seed(100)
df = pd.read_csv("movies.csv")
df = df.dropna()
good_movies = df.loc[df['imdb_score'] >= 7]
bad_movies = df.loc[df['imdb_score'] < 7]
def min_max_normalize(lst):
minimum = min(lst)
maximum = max(lst)
normalized = []
for value in lst:
normalized_num = (value - minimum) / (maximum - minimum)
normalized.append(normalized_num)
return normalized
x_good = good_movies["budget"]
y_good = good_movies["duration"]
z_good = good_movies['title_year']
x_bad = bad_movies["budget"]
y_bad = bad_movies["duration"]
z_bad = bad_movies['title_year']
data = [x_good, y_good, z_good, x_bad, y_bad, z_bad]
arrays_data = []
for d in data:
norm_d = min_max_normalize(d)
arrays_data.append(np.array(norm_d))
good_class = list(zip(arrays_data[0].flatten(), arrays_data[1].flatten(), arrays_data[2].flatten(),(np.array(([1] * len(arrays_data[0])))) ))
bad_class = list(zip(arrays_data[3].flatten(), arrays_data[4].flatten(), arrays_data[5].flatten(),(np.array(([0] * len(arrays_data[0])))) ))
dataset = good_class + bad_class
shuffle(dataset)
movie_dataset = []
labels = []
for movie in dataset:
movie_dataset.append(movie[:-1])
labels.append(movie[-1])
<file_sep># Code and data from Codecademy with slight modification
import numpy as np
hours_studied = np.array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]).reshape(20,1)
passed_exam = np.array([0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1]).reshape(20,1)
calculated_coefficients = np.array([[0.20678491]])
zero_coefficients = np.array([0])
intercept = np.array([-1.76125712])
zero_intercept = np.array([0])
<file_sep># This is an implementation from scratch of the logistic regression
# Algorithm of logistic regression
# The main goal of logistic regression is to find the best coefficients, and intercept
# to make the prediction accurate
import numpy as np
from exam import hours_studied, passed_exam
# For some reason np array that start with an int will only be an int
coefficients = np.array([[1.1]])
intercept = np.array([1.0])
learning_rate = 0.0001
def log_odds(features, coefficients, intercept):
"""Return the log odds for all the features"""
return np.dot(features,coefficients) + intercept
def sigmoid(z):
"""Simulate the sigmoid function and return a result"""
denominator = 1 + np.exp(-z)
return 1/denominator
def log_loss(probabilities, actual_class, Xi):
"""Return a summed log loss of all values in the feature dataset"""
return np.sum(-(1/actual_class.shape[0])*(actual_class*np.log(probabilities) + (1-actual_class)*np.log(1-probabilities))*Xi)
def get_error_rate(predicted, actual):
"""Return the average error rate"""
error = 0
for i in range(len(predicted)):
error += abs(predicted[i][0] - actual[i][0])
return error/len(predicted)
def train(features, labels):
n = len(features)
error_rate = 1
i = 0
print("Training Started!")
while error_rate > 0:
print(f"Iteration={i}")
# First get the probabilities
calculated_log_odds = log_odds(features, coefficients, intercept)
probabilities = sigmoid(calculated_log_odds)
# Calculate log loss
logloss = log_loss(probabilities, labels, features)
# Apply gradient descent algorithm
derivative_sigmoid = (1/n) * logloss
coefficients[0][0] = coefficients[0][0] - learning_rate*derivative_sigmoid
intercept[0] = intercept[0] - learning_rate*derivative_sigmoid
print(f"coefficient={coefficients},intercept={intercept}")
# Calculate error rate
result = np.where(probabilities >= 0.5, 1, 0)
old_error_rate = error_rate
error_rate = get_error_rate(result,labels)
print(f"[debug]error_rate:{error_rate}")
i += 1
# Create predict_class() function
def predict(features, threshold):
calculated_log_odds = log_odds(features, coefficients, intercept)
probabilities = sigmoid(calculated_log_odds)
result = np.where(probabilities >= threshold, 1, 0)
return result
# First, train the model
train(hours_studied, passed_exam)
# Make final classifications on Codecademy University data here
final_results = predict(hours_studied, 0.5)
predicted = final_results.tolist()
print(f"predicted: {predicted}")
actual = passed_exam.tolist()
print(f"realY_val: {actual}")
<file_sep># Neural Network Coded entirely from scratch without any third party libraries
# Attention: This project only work with data sets that have three features
import math
class NeuralNetwork:
# Ignore bias for easy implementation
def __init__(self, alpha=0.0001, epoch=1000):
self.alpha = alpha
self.epoch = epoch
# Initialize all the weights and layers nodes
# Refer to the pdf for more info
self.xn, self.yn, self.zn, self.outn = 0,0,0,0
self.xw, self.yw, self.zw = 0,0,0
self.aw1, self.aw2, self.aw3 = 0,0,0
self.bw1, self.bw2, self.bw3 = 0,0,0
self.cw1, self.cw2, self.cw3 = 0,0,0
self.a, self.b, self.c = 0,0,0
def __sigmoid(self, z):
"""Return the result of the sigmoid function"""
return 1 / (1 + math.exp(-z))
def __d_sigmoid(self, z):
"""Return the derivative of the sigmoid function"""
return self.__sigmoid(z) * (1 - self.__sigmoid(z))
def __cost(self, actual, predicted):
"""Calculate and return the cost using squared error"""
return (actual - predicted) ** 2
def __d_cost(self, actual, predicted):
"""Calculate and return the derivative of the cost function"""
return 2 * (actual - predicted)
def forward_prop(self,a,b,c):
"""Run the entire forward propagation process of
a neural network
Description:
The algorithm of forward prop is that, a sum of all the input multiplied
by all weights are passed through an activation function to get another
layer of input, and this new layer of input is multiplied by another
layer of weights, and passed through another layer of activation function
this process repeat until the result finally reached the output layer.
Args:
a: The first input to the neural network
b: The second input to the neural network
c: the third input to the neural network
"""
# The sum of all the input in the input layer
# multiplied by all the weights
x = a* self.aw1 + b * self.bw1 + c*self.cw1
y = a* self.aw2 + b * self.bw2 + c*self.cw2
z = a* self.aw3 + b * self.bw3 + c*self.cw3
# all the sum are passed through an activation function
self.xn = self.__sigmoid(x)
self.yn = self.__sigmoid(y)
self.zn = self.__sigmoid(z)
# The sum of all the input from the first layer multiplied
# by the weights to the second layer, or the output layer
out = x*self.xw + y*self.yw + z*self.zw
# Result are passed through an activation function
# At the output layer
self.outn = self.__sigmoid(out)
self.a = a
self.b = b
self.c = c
def back_prop(self, actual):
"""Run the entire back propagation process and improve the weights using gradient descent
Description:
The algorithm of back propagation is that a cost is calculated, or the distance between
the predicted value and the actual output, and this cost is passed back through the
activation function to adjust every single weights, and by subtracting the cost times a
learning rate, and weights can be improved to be able to reduce the cost, this is also
called gradient descent algorithm
Equations:
new_weight = old_weight - learning_rate * derivative_of_cost_with_respect_to_weight
derivative_of_cost_with_respect_to_weights = (derivative_of_cost * derivative_of_activation_func * input)
hidden_layer_deri_cost_respect_to_weights = (derivative_of_cost_output_layer * derivative_of_activation_output_layer * old_weight_output_layer)
Args:
actual: the actual label of the data
"""
# Adjusting the weights of the output layer using gradient descent
self.xw += (self.__d_cost(actual,self.outn) * self.__d_sigmoid(self.outn) * self.xn) * self.alpha
self.yw += (self.__d_cost(actual,self.outn) * self.__d_sigmoid(self.outn) * self.yn) * self.alpha
self.zw += (self.__d_cost(actual,self.outn) * self.__d_sigmoid(self.outn) * self.zn) * self.alpha
# Adjusting the weight for the hidden layer using gradient descent
self.aw1 += ((self.__d_cost(actual,self.outn) * self.__d_sigmoid(self.outn) * self.xw) * self.__d_sigmoid(self.xn) * self.a) * self.alpha
self.bw1 += ((self.__d_cost(actual,self.outn) * self.__d_sigmoid(self.outn) * self.xw) * self.__d_sigmoid(self.xn) * self.b) * self.alpha
self.cw1 += ((self.__d_cost(actual,self.outn) * self.__d_sigmoid(self.outn) * self.xw) * self.__d_sigmoid(self.xn) * self.c) * self.alpha
self.aw2 += ((self.__d_cost(actual,self.outn) * self.__d_sigmoid(self.outn) * self.yw) * self.__d_sigmoid(self.yn) * self.a) * self.alpha
self.bw2 += ((self.__d_cost(actual,self.outn) * self.__d_sigmoid(self.outn) * self.yw) * self.__d_sigmoid(self.yn) * self.b) * self.alpha
self.cw2 += ((self.__d_cost(actual,self.outn) * self.__d_sigmoid(self.outn) * self.yw) * self.__d_sigmoid(self.yn) * self.c) * self.alpha
self.aw3 += ((self.__d_cost(actual,self.outn) * self.__d_sigmoid(self.outn) * self.zw) * self.__d_sigmoid(self.zn) * self.a) * self.alpha
self.bw3 += ((self.__d_cost(actual,self.outn) * self.__d_sigmoid(self.outn) * self.zw) * self.__d_sigmoid(self.zn) * self.b) * self.alpha
self.cw3 += ((self.__d_cost(actual,self.outn) * self.__d_sigmoid(self.outn) * self.zw) * self.__d_sigmoid(self.zn) * self.c) * self.alpha
# print(f"{self.aw1},{self.aw2},{self.aw3},{self.bw1},{self.bw2},{self.bw3},{self.cw1},{self.cw2},{self.cw3},{self.xw},{self.yw},{self.zw}")
def train(self,a,b,c,actual):
"""Run the training loop over a predefined epoch
Args:
a: The first feature set
b: The second feature set
c: The third feature set
actual: A set of final prediction
"""
for i in range(self.epoch):
for j in range(len(a)):
self.forward_prop(a[j],b[j],c[j])
self.back_prop(actual[j])
if i % 100 == 0:
print("===============================")
print(f"EPOCH={i}")
print(f"COST={self.__cost(actual[j],self.outn)}")
def __threshold_classification(self,predicted):
"""Convert a probability value to an actual prediction of 0 or 1"""
if predicted > 0.5:
return 1
else:
return 0
def predict(self,a,b,c):
"""Run the prediction from pretrained weights, and run it through threshold classification"""
self.forward_prop(a,b,c)
return self.__threshold_classification(self.outn)
def predict_proba(self,a,b,c):
"""Run the prediction from pretrained weights, and directly return the probability"""
self.forward_prop(a,b,c)
if self.outn < 0.5:
return 1 - self.outn
return self.outn
if __name__ == '__main__':
model = NeuralNetwork(epoch=100000,alpha=0.01)
# Create dataset
# Use the prediction result of (A - (B + C) > 0) to build the dataset
# So that we can actually check the model
# small_training_set = {(1,1,0):0, (2,0,1):1, (3,2,0):1, (4,5,1):0}
a = [1,2,3,4]
b = [1,0,2,5]
c = [0,1,0,1]
actual_result = [0,1,1,0]
model.train(a,b,c,actual_result)
# testing the model
x_test = (3,1,1)
print(f"Start Prediction, testing_set={x_test}")
expected = 1
result = model.predict(x_test[0],x_test[1],x_test[2])
print(f"result:{result}\tprobabilities:{model.predict_proba(x_test[0],x_test[1],x_test[2])}")
print(f"expected:{expected}")
print(f"error={expected-result}")
# testing the model
x_test2 = (10,9,2)
print(f"Start Prediction, testing_set={x_test2}")
expected2 = 0
result2 = model.predict(x_test2[0],x_test2[1],x_test2[2])
print(f"result:{result2}\tprobabilities:{model.predict_proba(x_test2[0],x_test2[1],x_test2[2])}")
print(f"expected:{expected2}")
print(f"error={expected2-result2}")
<file_sep># Self-coded Linear Regression Algorithm
import matplotlib.pyplot as plt
def get_gradient_at_b(x, y, b, m):
N = len(x)
diff = 0
for i in range(N):
x_val = x[i]
y_val = y[i]
diff += (y_val - ((m * x_val) + b))
b_gradient = -(2/N) * diff
return b_gradient
def get_gradient_at_m(x, y, b, m):
N = len(x)
diff = 0
for i in range(N):
x_val = x[i]
y_val = y[i]
diff += x_val * (y_val - ((m * x_val) + b))
m_gradient = -(2/N) * diff
return m_gradient
#Your step_gradient function here
def step_gradient(b_current, m_current, x, y, learning_rate):
b_gradient = get_gradient_at_b(x, y, b_current, m_current)
m_gradient = get_gradient_at_m(x, y, b_current, m_current)
b = b_current - (learning_rate * b_gradient)
m = m_current - (learning_rate * m_gradient)
return [b, m]
#Your gradient_descent function here:
def gradient_descent(x, y, learning_rate, num_iterations):
b, m = 0, 0
for i in range(num_iterations):
b, m = step_gradient(b, m, x, y, learning_rate)
return [b, m]
months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
revenue = [52, 74, 79, 95, 115, 110, 129, 126, 147, 146, 156, 184]
#Uncomment the line below to run your gradient_descent function
b, m = gradient_descent(months, revenue, 0.01, 1000)
#Uncomment the lines below to see the line you've settled upon!
y = [m*x + b for x in months]
plt.plot(months, revenue, "o")
plt.plot(months, y)
plt.show()
<file_sep># A self-coded perceptron (single-neuron neural net)
import numpy as np
class Perceptron:
def __init__(self, num_inputs=3, weights=[1,1,1]):
# num_inputs is the number of inputs that will be included in a list of data
self.num_inputs = num_inputs
# weights are the weight assigned to each synapse for the neural network
self.weights = weights
def weighted_sum(self, inputs):
"""return the sum for all inputs multiplied by its weight"""
weighted_sum = 0
for i in range(self.num_inputs):
weighted_sum += self.weights[i]*inputs[i]
return weighted_sum
def activation(self, z):
"""Return a result between 1 and 0 using a sigmoid function"""
denominator = 1 + np.exp(-z)
result = 1/denominator
return result
def threshold(self, value):
"""Return a classification threshold of either 0 or 1
we use 0.5 as a threshold here for ease of understanding
"""
threshold = 0.5
if value >= threshold:
return 1
else:
return 0
def training(self, training_set):
"""Train the neural network"""
# Start foundline with False until the neural network is able to
# Correctly come up with a line that can classify the dataset
foundLine = False
# Keep track of the total amount of iterations
iterations = 0
while not foundLine:
print(f"Start Training... Iterations={iterations}")
total_error = 0
for inputs in training_set:
# Start with random weights 1,1,1
# And uses simple multiplication and addition to get a weighted sum
# pass it through the activation function to get either a 1 or 0
prediction_old = self.activation(self.weighted_sum(inputs))
# pass the prediction through the threshold to be get a value of 0 or 1
# for easy training
prediction = self.threshold(prediction_old)
print(f"[Predicted]{prediction}")
actual = training_set[inputs]
print(f"[Actual]{actual}")
# Calculate the error by subtracting actual with predicted value
# So error can either be 2 or -2
# each piece of data in the dataset will have an error rate
error = actual - prediction
# total error is the sum of all errors in the entire dataset
# Take the absolute value so that error can only be 2, so both
# -2 and +2 will have to same effect to the neural network
total_error += abs(error)
for i in range(self.num_inputs):
# modify the weight by using error multiply input, this will result in a
# better weight that can work better with the dataset
# This is back backpropagation
self.weights[i] += error*inputs[i]
print(f"[Weights]{self.weights}")
# End the training process when the total error is 0
if total_error == 0:
foundLine = True
print(f"Training completed! Total Error={total_error}")
iterations += 1
def predict(self, testing_set):
"""return the prediction and confidence for a given testing data"""
# Run prediction by multiply inputs with the weight and map it
# Through the activation function
final_prob = 0
probability = self.activation(self.weighted_sum(testing_set))
prediction = self.threshold(probability)
if prediction == 1:
final_prob = probability
else:
final_prob = 1 - probability
return [prediction, final_prob]
if __name__ == '__main__':
cool_perceptron = Perceptron()
# Use the prediction result of (A - (B + C) > 0) to build the dataset
# So that we can actually check the model
small_training_set = {(1,1,0):0, (2,0,1):1, (3,2,0):1, (4,5,1):0}
cool_perceptron.training(small_training_set)
# Testing the model
testing_set = (3,1,1)
print(f"Start Prediction, testing_set={testing_set}")
expected = 1
result = cool_perceptron.predict(testing_set)
print(f"result:{result[0]}\tprobability:{result[1]}")
print(f"expected:{expected}")
print(f"error={result[0]-expected}")
<file_sep># Code from Codecademy
from tree import *
import operator
test_point = ['vhigh', 'low', '3', '4', 'med', 'med']
# print_tree(tree)
def classify(datapoint, tree):
if isinstance(tree, Leaf):
return max(tree.labels.items(), key=operator.itemgetter(1))[0]
value = datapoint[tree.feature]
for branch in tree.branches:
if branch.value == value:
return classify(datapoint, branch)
print(classify(test_point, tree))
<file_sep>import numpy as np
from sklearn.model_selection import train_test_split
from sklearn import datasets
import matplotlib.pyplot as plt
from tabulate import tabulate
class LogisticRegression:
def __init__(self, lr=0.001, epoch=1000, threshold = 0.5):
"""Initilize all the variables
lr - learning rate
epoch - numbers of iterations
"""
self.lr = lr
self.epoch = epoch
self.threshold = threshold
self.weights = None
self.bias = None
self.log_odds = None
def __sigmoid(self, z):
"""Simulate the sigmoid function"""
return 1/ (1 + np.exp(-z))
def __log_odds(self, X):
"""Calculate the return the log odds"""
return np.dot(X, self.weights) + self.bias
def fit(self, X, y):
# init parameters
num_samples, num_features = X.shape
# init weights and bias
self.weights = np.zeros(num_features)
self.bias = 0
# implement gradient descent
# weights - coefficients
# bias - intercept
print("[DEBUG]Training Started...")
for i in range(self.epoch):
print(f"[DEBUG]Iterations={i}")
self.log_odds = self.__log_odds(X)
y_predicted = self.__sigmoid(self.log_odds)
# Derivatives of weights(coefficient)
# The derivative of log loss for weights is (Y_predicted - Y) * X
dw = (1 / num_samples) * np.dot(X.T, (y_predicted - y))
# Derivatives of bias(intercept)
# Derivative of log loss for bias is (Y_predicted -Y)
db = (1 / num_samples) * np.sum(y_predicted - y)
# Update weights and bias
self.weights -= self.lr * dw
self.bias -= self.lr * db
print(f"[DEBUG]weights={self.weights}")
print(f"[DEBUG]bias={self.bias}")
print("[DEBUG]Training Completed")
def predict(self, X):
self.log_odds = self.__log_odds(X)
y_predicted = self.__sigmoid(self.log_odds)
# Apply threshold classification into predicted result
y_predicted_class = [1 if i > 0.5 else 0 for i in y_predicted]
return y_predicted_class
def predict_proba(self, X):
self.log_odds = self.__log_odds(X)
y_predicted = self.__sigmoid(self.log_odds)
return y_predicted
def score(self, y_pred, y_true):
"""Calculate and return the accuracy of the model"""
score = np.sum(y_true == y_pred) / len(y_true)
return score
if __name__ == '__main__':
# Use sklearn for data testing
bc = datasets.load_breast_cancer()
X, y = bc.data, bc.target
dataset_labels = bc.feature_names
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1234)
model = LogisticRegression(lr=0.0001, epoch=1000)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
probabilities = model.predict_proba(X_test)
print(f"Model Accuracy: {model.score(predictions, y_test)}")
# Print the data
y_test = y_test.tolist()
y_pred = predictions
print(y_test)
print(predictions)
<file_sep>import numpy as np
from sklearn.linear_model import LogisticRegression
from exam import hours_studied_scaled, passed_exam, exam_features_scaled_train, exam_features_scaled_test, passed_exam_2_train, passed_exam_2_test, guessed_hours_scaled
# Create and fit logistic regression model here
model = LogisticRegression()
model.fit(hours_studied_scaled, passed_exam)
# Save the model coefficients and intercept here
calculated_coefficients = model.coef_
intercept = model.intercept_
# Predict the probabilities of passing for next semester's students here
# This predict probabilities
passed_predictions = model.predict_proba(guessed_hours_scaled)
# Create a new model on the training data with two features here
model_2 = LogisticRegression()
model_2.fit(exam_features_scaled_train, passed_exam_2_train)
# Predict whether the students will pass here
# This output a yes or no
passed_predictions_2 = model_2.predict(exam_features_scaled_test)
print(passed_predictions_2)
<file_sep># Basic_ML_Research
My Researches on basic ML algorithms
<file_sep># Single-layer Perceptron Algorithm
- This is an implementation of the single-layer perceptron algorithm
# Code style
- This code follow the UCSC CSE13S Spring 2021 Coding Style that can be found [here](https://cdn-uploads.piazza.com/paste/hpyc1y44n3k4oo/ff1a264201988386be47c15f1d3d416a2c718ec223ec0485615b38457e5a799d/coding.pdf)
# Requirement
- clang
- make
- It is recommanded to run this code on UNIX environment
# Project Contents
- perceptron.c: The source code of the single layer perceptron implementation
- Makefile: This is the makefile of the project that makes compile and testing easier
- DESIGN.md: This is the design document of the project, it contents pseudo code
# Installation
- This project can be compiled using one of these command
```bash
make all
make
```
# Usage
- This project can be executed using this command
```bash
./perceptron
```
# License
- [MIT License](https://github.com/maxxie114/Basic_ML_Research/blob/main/LICENSE)
# Author
- This project is written by <NAME>
# Contribution
- Feel free to submit pull request, please make sure to follow the specified coding style
| 9555334bc76238eb9881d1b7a8422ce958ef7d4e | [
"Markdown",
"C",
"Python",
"Makefile"
] | 19 | Makefile | maxxie114/Basic_ML_Research | 2507ea4bb0055a56a787fb4b7eb0349c85c6a890 | f4910b8b230b5081a80839e69a35717549251f8e |
refs/heads/main | <file_sep>export const ADD_COMMENT: string = 'ADD_COMMENT';
export const SET_CURRENT_POST: string = 'SET_CURRENT_POST';
export const WRITE_NEW_COMMENT: string = 'SHOW_COMMENTS';
export const ADD_COMMENT_IN_CURRENT_POST: string = 'ADD_COMMENT_IN_CURRENT_POST';
<file_sep>import initState from './initState';
import { postReducer } from './Reducers/PostsReducer';
import { composeWithDevTools } from 'redux-devtools-extension';
import { createStore } from 'redux';
const store = createStore(postReducer, initState, composeWithDevTools());
export default store;
<file_sep>import { ADD_COMMENT, SET_CURRENT_POST, WRITE_NEW_COMMENT, ADD_COMMENT_IN_CURRENT_POST } from '../Types/Types'
import { ICurrentPost, IInitState } from '../initState';
import initState from '../initState';
export const postReducer = (state: IInitState = initState, action: any): IInitState => {
switch (action.type) {
case ADD_COMMENT:
return { ...state, posts: state.posts.map((post: any) => post.id === action.payload.id ? { ...post, comments: [...post.comments, action.payload.comment] } : post) }
case ADD_COMMENT_IN_CURRENT_POST:
return { ...state, currentPost: { ...state.currentPost, comments: [...state.currentPost.comments, action.payload] } }
case SET_CURRENT_POST:
return { ...state, currentPost: { ...state.currentPost, ...action.payload } }
case WRITE_NEW_COMMENT:
return { ...state, writeNewComment: action.payload }
default:
return state;
}
}
<file_sep>import { SET_CURRENT_POST, WRITE_NEW_COMMENT, ADD_COMMENT, ADD_COMMENT_IN_CURRENT_POST } from '../Types/Types';
export function setCurrentPost(title: string, author: string, content: string, comments: Array<string>, authorID: string, id: string) {
return {
type: SET_CURRENT_POST,
payload: { title, author, content, comments, authorID, id },
};
};
export function writeNewComment(flag: boolean) {
return {
type: WRITE_NEW_COMMENT,
payload: flag,
};
};
export function addComment(comment: string, id: string) {
return {
type: ADD_COMMENT,
payload: { comment, id }
};
};
export function addCommentInCurrentPost(comment: string) {
return {
type: ADD_COMMENT_IN_CURRENT_POST,
payload: comment
}
}
<file_sep>export interface IInitState {
users: Array<Object>;
posts: Array<{
author: string;
title: string;
content: string;
authorID: string;
id: string;
comments: Array<string>;
}>;
currentPost: ICurrentPost;
writeNewComment: boolean;
};
export interface ICurrentPost {
title: string;
author: string;
content: string;
id: string;
comments: Array<string>;
authorID: string;
}
const initState: IInitState = {
users: [
{
firstName: 'Igor',
lastName: 'Palkin',
username: 'Igrik',
city: 'Moscow',
company: 'Yahoo',
id: '1',
},
{
firstName: 'Mark',
lastName: 'Kopalkin',
username: 'Cat',
city: 'Moscow',
company: 'Yandex',
id: '2',
},
{
firstName: 'Valery',
lastName: 'Pesikov',
username: 'Dog',
city: 'Vladivostok',
company: 'Kaspersky',
id: '3',
},
{
firstName: 'Nastya',
lastName: 'Koskina',
username: 'Feya',
city: 'Samara',
company: 'Brr',
id: '4',
},
],
posts: [
{
author: 'Igrik',
title: 'Post1',
content: 'contentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontententcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentc',
authorID: '1',
id: '1',
comments: ['1', '2', '3'],
},
{
author: 'Nastya',
title: 'Post1',
content: `Post Body Preview Post Body Preview Post Body Preview Post Body Preview Post Body Preview Post Body Preview Post Body Preview Post Body Preview Preview Post Body Preview Post Body Preview Post Body Preview Post Body Preview Post Body Preview Post Body Preview Preview Post Body Preview Post Body Preview Post Body Preview Post Body Preview Post Body Preview Post Body Preview Preview Post Body Preview Post Body Preview Post Body Preview Post Body Preview Post Body Preview Post Body Preview
New Paragraph of Post Body Preview Post Body Preview Post Body Preview Post Body Preview Preview Post Body Preview Post Body Preview Post Body Preview Post Body Preview Post Body Preview Post Body Preview Preview Post Body Preview Post Body Preview Post Body Preview Post Body Preview Post Body Preview Post Body Preview Preview Post Body Preview Post Body Preview Post Body Preview Post Body Preview Post Body Preview Post Body Preview Preview Post Body Preview Post Body Preview Post Body Preview Post Body Preview Post Body Preview Post Body Preview Preview Po... `,
authorID: '4',
id: '2',
comments: ['1', '2', '3', '4'],
},
{
author: 'Igrik',
title: 'Post2',
content: 'contentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontent',
authorID: '1',
id: '3',
comments: ['1'],
},
{
author: 'Valery',
title: 'Post1',
content: 'contentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontentcontent',
authorID: '3',
id: '4',
comments: ['commentcommentcommentcommentcommentcommentcommentcommentcommentcommentcommentcommentcommentcommentcommentcommentcommentcommentcommentcommentcommentcommentcommentcommentcommentcommentcomment', '2', '3'],
},
],
currentPost: {
title: '',
author: '',
content: '',
comments: [],
id: '',
authorID: '',
},
writeNewComment: false,
}
export default initState;
| 94e32f82cd294b198e94dac678c3933ea91c9b53 | [
"TypeScript"
] | 5 | TypeScript | Bzelijah/test-SPA-app | e75f02c2f07b3a9e155cabe58ec87067ade3a787 | ad8e8b23166310c1431e81d993a5431070c97098 |
refs/heads/master | <file_sep>using System.Net.Http;
using System.Web.Http.Cors;
namespace FxOSHelper
{
public class FxOSCorsPolicyFactory : ICorsPolicyProviderFactory
{
ICorsPolicyProvider provider;
public FxOSCorsPolicyFactory(string[] allowOrigins)
{
provider = new FxOSCorsPolicyProvider(allowOrigins);
}
public FxOSCorsPolicyFactory(string allowOrigin)
{
provider = new FxOSCorsPolicyProvider(allowOrigin);
}
public ICorsPolicyProvider GetCorsPolicyProvider(HttpRequestMessage request)
{
return provider;
}
}
}
<file_sep>using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Cors;
using System.Web.Http.Cors;
namespace FxOSHelper
{
public class FxOSCorsPolicyProvider : ICorsPolicyProvider
{
private string[] origins;
public FxOSCorsPolicyProvider(string[] allowOrigins)
{
origins = allowOrigins;
}
public FxOSCorsPolicyProvider(string allowOrigin)
{
origins = new string[] { allowOrigin };
}
public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// Create a CORS policy.
var policy = new CorsPolicy
{
AllowAnyMethod = true,
AllowAnyHeader = true
};
// Add allowed origins.
foreach (string origin in origins)
{
policy.Origins.Add(origin);
}
return Task.FromResult(policy);
}
}
}
| ad95b9761ae8334d4bcf6ca71b94af1b9c875bfc | [
"C#"
] | 2 | C# | iwate/FxOSHelper | 6da15dfdc0208696bb44c90dae90cc6b55220c8a | 8afbe4bbec80b1922f14218bb488582319da0b7d |
refs/heads/master | <repo_name>barkyvonschnauzer/tango-submission<file_sep>/Dockerfile
# Official image used as part of parent image
FROM python:3-slim-buster
COPY requirements.txt .
COPY tango_submission.py .
RUN apt-get update && pip install --no-cache-dir -r requirements.txt
CMD [ "python", "tango_submission.py" ]
<file_sep>/README.md
# tango-submission
Extracting, parsing and submitting to Netcraft
<file_sep>/tango_submission.py
import binascii
import csv
import datetime
import io
import iocextract
import json
import logging
import math
import os
import pandas as pd
import pytesseract
import requests
import time
from azure.cosmos import CosmosClient
from collections import Counter
from datetime import datetime
from dateutil.relativedelta import relativedelta
from pathlib import Path
from PIL import Image
from urlextract import URLExtract
####################
# GLOBAL VARIABLES #
####################
# No monitoring support (no UUID returned) for submissions with 1000+ IOCs.
MAX_POST_REQ_NETCRAFT = 999
# Supported file types
img_exts = ['jpg', 'png', 'gif', 'bmp', 'tiff']
doc_exts = ['txt', 'csv', 'doc', 'rtf']
##########################################################################
#
# Function name: main
# Input: Blob that triggered this function to be run.
# Output: TBD
#
# Purpose: Extract and action reported URLs for categorization.
#
##########################################################################
def main():
input_file = Path('/input') / os.environ.get('INPUT_FILE')
print (input_file)
if input_file:
# Extract URLs from blob and dedup
file_content = access_input_file(input_file)
url_list = extract_URLs(file_content)
unique_url_list = dedup_URLs(url_list)
urls_to_submit = check_urls(unique_url_list)
#print("\n***** URLs sent to Netcraft *****")
#for url in urls_to_submit:
# print (url)
# Send list of deduped (unique) URLs to Netcraft for assessment
num_calls_netcraft = math.ceil((len(urls_to_submit))/MAX_POST_REQ_NETCRAFT)
#netcraft_uuids = []
print ("Number of unique IOCs to submit: " + str(len(urls_to_submit)))
print ("Number of calls to make to Netcraft: " + str(num_calls_netcraft))
for j in range(num_calls_netcraft):
# Check list of URLs againts Netcraft
list_subset_netcraft = urls_to_submit[j*MAX_POST_REQ_NETCRAFT:(MAX_POST_REQ_NETCRAFT*(1 + j))]
if (len(list_subset_netcraft) > 0):
uuid = submit_URLs_Netcraft(list_subset_netcraft)
print ("Netcraft UUID: " + uuid)
#netcraft_uuids.append(uuid)
if uuid == "0000":
print ("Error, UUID is set to default value of 0000\n")
else:
update_cosmos_db(uuid, len(url_list), len(list_subset_netcraft), list_subset_netcraft)
else:
print ("No new URLs to submit to Netcraft")
# store volumes for all URLs received in DB
store_url_counts(url_list, unique_url_list)
else:
print ("Input file not found")
##########################################################################
#
# Function name: store_url_counts
# Input: url_list
# Output: TBD
#
# Purpose: update the db to include information on urls received:
# - date/time
# - url
# - number of submissions
#
##########################################################################
def store_url_counts(url_list, unique_url_list):
print ("**** COUNT URLS ****\n")
print(url_list)
url_counts = dict(Counter(url_list))
print(url_counts)
uri = os.environ.get('ACCOUNT_URI')
key = os.environ.get('ACCOUNT_KEY')
database_id = os.environ.get('DATABASE_ID')
container_id = os.environ.get('URL_CONTAINER_ID')
client = CosmosClient(uri, {'masterKey': key})
database = client.get_database_client(database_id)
container = database.get_container_client(container_id)
date_str = datetime.today().strftime('%Y-%m-%d %H:%M:%S')
id_date = int((datetime.utcnow()).timestamp())
id_date_str = str(id_date)
output = []
for k,v in url_counts.items():
output.append({'url':k, 'count':v})
container.upsert_item({'id': id_date_str,
'date_time': id_date_str,
'date': date_str,
'urls_and_counts': output})
##########################################################################
#
# Function name: check_urls
# Input: unique_url_list
# Output: list of urls that have not been submitted in the past 24 hours.
#
# Purpose: identify which of the most-recently received URLs have not
# been submitted ot Netcraft in the past 24 hours.
#
##########################################################################
def check_urls(url_list):
print ("**** CHECK URLS ****\n")
uri = os.environ.get('ACCOUNT_URI')
key = os.environ.get('ACCOUNT_KEY')
database_id = os.environ.get('DATABASE_ID')
container_id = os.environ.get('CONTAINER_ID')
reported_urls = []
client = CosmosClient(uri, {'masterKey': key})
database = client.get_database_client(database_id)
container = database.get_container_client(container_id)
print ("Query db for UUIDs since yesterday\n")
yesterday = int((datetime.utcnow() - relativedelta(days=1)).timestamp())
query = 'SELECT c.urls_unq FROM c WHERE c._ts > {}'.format(str(yesterday))
url_results = list(container.query_items(query, enable_cross_partition_query = True))
for record in url_results:
record_urls = (record['urls_unq'].split(' '))
reported_urls.extend(record_urls)
print ("Previously Reported URLs")
print (reported_urls)
print ("\nNewly Reported URLs")
print (url_list)
# identify which urls are being submitted for the first time in 24 hours
new_unique_urls = list(set(url_list) - set(reported_urls))
print ("\nURLs to report to Netcraft")
print (new_unique_urls)
return new_unique_urls
#########################################################################
#
# Function name: access_input_file
# Input: name of inout file
# Output: Returns the content of the file.
#
# Purpose: determine the file type, extract the content and prepare for
# URL extraction.
#
##########################################################################
def access_input_file(input_file):
print ("\n***** access_input_file *****\n")
### Determine the file type ###
extension = os.path.splitext(input_file.name)[1][1:]
if extension in img_exts:
### Open image ###
input_image = input_file
screen_image = Image.open(input_image)
### Perform image-to-text conversion ###
### Python-tesseract is a wrapper for Google's Tesseract-OCR Engine.
content = pytesseract.image_to_string(screen_image)
elif extension in doc_exts:
### Read text content of csv file ###
fp = open(input_file, 'r')
content= fp.read()
fp.close()
else:
print ("Unable to process blob. File type has not been explicitly stated as part of the file name and/or is not supported.")
content = None
print ("Successfully accessed blob")
return content
##########################################################################
#
# Function name: extract_URLs
# Input: content (text)
# Output: non-deduped, non-sorted list of extracted URLs and IPs.
#
# Purpose: identify and extract the URLs and IPs present in the text input.
#
##########################################################################
def extract_URLs(content):
if content is not None:
print ("\n***** Extract URLs *****\n")
### Identify URLs in content ###
extractor = URLExtract();
extractor_urls = extractor.find_urls(content)
iocextract_urls = list(iocextract.extract_urls(content, refang=True))
iocextract_ips = list(iocextract.extract_ips(content, refang=True))
iocextract_ips_valid = []
if (len(iocextract_ips) > 0):
for ip in iocextract_ips:
# Add check to further refine list of potential IPs:
# Basic format check:
# IPv4: xxx.xxx.xxx.xxx or
# IPv6: xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
if ip.count(".") != 3 or ip.count(":") != 7:
print ("Invalid IP address: " + str(ip))
else:
iocextract_ips_valid.append(ip)
print ("iocextract.extract_ips method - format validated")
print (iocextract_ips_valid)
print ("extractor.find method")
print (extractor_urls)
print ("iocextract.extract_urls method")
print (iocextract_urls)
info_to_evaluate = extractor_urls + iocextract_urls + iocextract_ips_valid
index = 0
# Occassionally, the functions above return urls with trailing commas. Remove these.
for ioc in info_to_evaluate:
if ioc.endswith(','):
info_to_evaluate[index] = ioc[:-1]
index += 1
print ("Removed trailing commas")
print (info_to_evaluate)
print ("Successfully extracted URLs")
return info_to_evaluate
##########################################################################
#
# Function name: dedup_URLs
# Input: list of URLs
# Output: deduped list of URLs
#
# Purpose: produce a deduped list of URLs extracted from the blob
# processed.
#
##########################################################################
def dedup_URLs(url_list):
print ("\n***** De-duping URL list *****\n")
unique_url_list = list();
if url_list is not None:
unique_url_list = list(set(url_list))
print ("Successfull de-duped URL list")
print ("Initially Deduped list")
print (unique_url_list)
return unique_url_list
##########################################################################
#
# Function name: submit_URLs_Netcraft
# Input: Unique list of IPs
# Output: Returns the result of submitting the url(s) to netcraft:
# - return_string: string describing success/failure of operation
# - uuid: if call was successful, uuis should be non-zero. Else,
# populated with "0000"
# - state: the state of the request
#
#
# Purpose: Submit list of unique URLs for processing with Netcraft.
#
##########################################################################
def submit_URLs_Netcraft(unique_url_list):
print("\n***** Submit extracted URLs to Netcraft for evaluation *****\n")
# The below link is for development. Once deployed, use:
netcraftReport_url = "https://report.netcraft.com/api/v3/report/urls"
headers = {'Content-type': 'application/json'}
request_data = {
#"email": "<EMAIL>",
"email": "<EMAIL>",
"reason": "tango",
"urls": [{"url": u} for u in unique_url_list],#[u for u in unique_url_list],
}
# Check URLs with netcraft service
r_post = requests.post(netcraftReport_url, json=request_data, headers=headers)
print("Netcraft Report URLs response status code: " + str(r_post.status_code))
print(r_post.json())
#state = {}
uuid = "0000"
# Update SQL db table entries where url is in unique_url_list with the uuid returned
if r_post.status_code == 200:
uuid = r_post.json()['uuid']
print("UUID: " + str(uuid))
#state = check_URLs_state_Netcraft_bulk(uuid, unique_url_list)
return_string = "success"
elif r_post.status_code == 400:
# A number of different reasons could have caused this return code:
# 1 - a single incorrectly formatted url
# 2 - submission is an exact duplicate of a previous request
# ... to add more as they come up ...
response = r_post.json()
#print(response)
#print("**** ALL ****")
#for all_url in unique_url_list:
# print(all_url)
for field in response["details"]:
print(field)
if field["message"]:
if "Duplicate" in field["message"]:
print("Duplicate Error")
return_string = "duplicate"
if "Does not match url format" in field["message"]:
print("URL Formatting Error")
# Get the offending entries:
if field["input"]:
print(field["input"])
bad_url = field["input"]
print("Remove " + bad_url + " from list")
unique_url_list.remove(bad_url)
return_string = "formatting error"
state = {}
#print("**** GOOD ****")
#for good_url in unique_url_list:
# print(good_url)
if return_string == "formatting error" and len(unique_url_list) > 0:
# resubmit the list with the poorly formatted URLs removed
print("Resubmitting valid URLs")
uuid = submit_URLs_Netcraft(unique_url_list)
# Other possible error codes: 429 - too many submissions
#else:
# state = {}
return uuid
##########################################################################
#
# Function name: check_URLs_state_Netcraft_bulk
# Input: uuid returned from Netcraft submission,
# list of unique urls submitted to Netcraft for processing
#
# Output:
#
# Purpose: to check the characterization of each URL submitted to
# Netcraft.
# Possible results:
# (v2)
# - processing
# - no threats
# - unavailable
# - phishing
# - already blocked
# - suspicious
# - malware
# - rejected (was already submitted)
# (v3)
# - processing
# - no threats
# - unavailable
# - malicious
# - suspicious
#
##########################################################################
def check_URLs_state_Netcraft_bulk(uuid, unique_url_list):
print("\n***** Query Netcraft for URL classification by UUID *****\n")
uuid_str = str(uuid)
# submit GET request to Netcraft for each UUID identified above
# The below link is for development. Once deployed, use:
netcraftSubmissionCheck_url = "https://report.netcraft.com/api/v3/submission/" + uuid_str + "/urls"
# Check URLs with netcraft service
headers = {'Content-type': 'application/json'}
result = {}
request_data = {};
# Check URLs with netcraft service
r_get = requests.get(netcraftSubmissionCheck_url, json=request_data, headers=headers)
print("Netcraft submission check response status code (" + uuid_str + "): " + str(r_get.status_code))
print(r_get.json())
if r_get.status_code == 200:
if r_get.json() == {}:
print("No results available.")
else:
print("Results for uuid:", uuid_str, " available.")
# Get results
for entry in r_get.json()['urls']:
print(entry)
url = entry['url']
url_state = entry['url_state']
print ("url: ", url)
print ("url state: ", url_state)
if url_state in ["malicious", "suspicious"]: #v3
#if url_state in ["phishing", "already blocked", "suspicious", "malware"]: #v2
print("Likely malicious")
result[url] = {
'malicious': True,
'threats': str(url_state)
}
elif url_state == "no threats":
print("Likely safe")
result[url] = {
'malicious': False,
'threats': str(url_state)
}
else:
# These the categorization of these threats is unknown (processing or unavailable).
# Add these to the list for continued testing.
print("Currently unknown")
result[url] = {
'malicious': False,
'threats': str(url_state)
}
return result
##########################################################################
#
# Function name: update_cosmos_db
# Input:
# - list of uuids associated to report
# - number of URLs reported via partner
# - number of deduped URLs reported via partner
# Output:
#
# Purpose: Add record of uuid.
#
##########################################################################
def update_cosmos_db(uuid, num_urls_rec, num_urls_unq, unique_url_list):
print ("\n***** Add UUID to the COSMOS DB *****\n")
uri = os.environ.get('ACCOUNT_URI')
key = os.environ.get('ACCOUNT_KEY')
database_id = os.environ.get('DATABASE_ID')
container_id = os.environ.get('CONTAINER_ID')
client = CosmosClient(uri, {'masterKey': key})
database = client.get_database_client(database_id)
container = database.get_container_client(container_id)
# Get date
date_str = datetime.today().strftime('%Y-%m-%d %H:%M:%S')
all_uuid_str = uuid#' '.join(map(str, netcraft_uuids))
#for uuid in netcraft_uuids:
uuid_str = str(uuid)
print (uuid_str)
unique_url_list_str = ' '.join(map(str, unique_url_list))
print ("Informaton for new record: ")
print (" uuid: " + uuid_str)
print (" date: " + date_str)
print (" num URLs received: " + str(num_urls_rec))
print (" num unique URLs received: " + str(num_urls_unq))
print (" associated uuids: " + all_uuid_str)
print (" unique url list: " + unique_url_list_str)
# information to include:
# - uuid
# - associated uuids
# - date
# - number of URLs received from partner
# - number of unique URLs
# - number of valid URLs subitted to Netcraft
# - list URLs received from client
# statement to insert record
container.upsert_item({ 'id': uuid_str,
'date': date_str,
'uuid': uuid_str,
'assoc_uuids': all_uuid_str,
'n_urls_in': num_urls_rec,
'n_urls_unq': num_urls_unq,
'urls_unq': unique_url_list_str })
if __name__ == "__main__":
main()
| c8f20e7b3eafa900331a277d8c0b0ad1c25c1153 | [
"Markdown",
"Python",
"Dockerfile"
] | 3 | Dockerfile | barkyvonschnauzer/tango-submission | ed73f739823f4f2005665a6851956996cb9fb454 | fa122119ae3e9b06cc6f0dd387a72cf12fe3b405 |
refs/heads/main | <repo_name>Stefanopa87/sass-painter<file_sep>/src/app.js
function init(){
console.log('JS OK AGGANCIATO');
};
init(); | aa1a454bedd02a3657394fd15b3e83ab2725cb6c | [
"JavaScript"
] | 1 | JavaScript | Stefanopa87/sass-painter | 5b1447f5b18da7dddc4d9e55cd8a0615c22b9d6d | 674844dac36639d71610c1945fdad38dd8179af0 |
refs/heads/master | <file_sep>
public static class MemEntryState {
public const byte END_OF_MEMLIST = 0xff;
public const byte NOT_NEEDED = 0x00;
public const byte LOADED = 0x01;
public const byte LOAD_ME = 0x02;
}
struct MemEntry {
public byte state; // 0x0
public byte type; // 0x1, Resource::ResType
// TODO: ubyte *bufPtr; // 0x2
public ushort unk4; // 0x4, unused
public byte rankNum; // 0x6
public byte bankId; // 0x7
public uint bankOffset; // 0x8 0xA
public ushort unkC; // 0xC, unused
public ushort packedSize; // 0xE
// All ressources are packed (for a gain of 28% according to Chahi)
public ushort unk10; // 0x10, unused
public ushort size; // 0x12
};
/*
Note: state is not a boolean, it can have value 0, 1, 2 or 255, respectively meaning:
0:NOT_NEEDED
1:LOADED
2:LOAD_ME
255:END_OF_MEMLIST
See MEMENTRY_STATE_* #defines above.
*/
<file_sep>using System.Collections.Generic;
using System.IO;
namespace anotherworld_interpreter_net
{
class BytecodeReader
{
const string MemListFileName = "memlist.bin";
const string InputPath = "input";
internal List<MemEntry> Read()
{
string filepath = Path.Join(InputPath, MemListFileName);
if (!File.Exists(filepath))
{
throw new BytecodeReaderException($"Memlist file not found at {filepath}");
}
using (BinaryReader reader = new BinaryReader(File.OpenRead(filepath)))
{
var memEntries = new List<MemEntry>();
var memEntry = new MemEntry();
while (memEntry.state != MemEntryState.END_OF_MEMLIST)
{
memEntry.state = reader.ReadByte();
memEntry.type = reader.ReadByte();
// skip the bufptr
reader.ReadUInt16BE();
memEntry.unk4 = reader.ReadUInt16BE();
memEntry.rankNum = reader.ReadByte();
memEntry.bankId = reader.ReadByte();
memEntry.bankOffset = reader.ReadUInt32BE();
memEntry.unkC = reader.ReadUInt16BE();
memEntry.packedSize = reader.ReadUInt16BE();
memEntry.unk10 = reader.ReadUInt16BE();
memEntry.size = reader.ReadUInt16BE();
memEntries.Add(memEntry);
}
return memEntries;
}
}
}
}
<file_sep>using System;
class BytecodeReaderException : Exception
{
public BytecodeReaderException(string message) : base(message)
{
}
}<file_sep>using System;
using System.IO;
namespace anotherworld_interpreter_net
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("start");
new BytecodeReader().Read();
}
}
}
| 20fd4a94618a5e383e0543e7fb79be0c5b1d270d | [
"C#"
] | 4 | C# | karoletrych/anotherworld-interpreter-net | 9a47e11b8c275d6b571344456b899e8e25a3bc4e | 33eb018b44b6403a83fe1ac7283bda2063b52f4f |
refs/heads/master | <repo_name>haidragon/ios<file_sep>/HookZz/src/std_kit/std_buffer_array.c
#include "std_buffer_array.h"
buffer_array_t *buffer_array_create(int default_capacity) {
if (default_capacity == 0) {
default_capacity = 64;
}
unsigned char *data = (unsigned char *)malloc(default_capacity);
buffer_array_t *buffer_array = (buffer_array_t *)malloc(sizeof(buffer_array_t));
if (!buffer_array) {
return NULL;
}
buffer_array->data = data;
buffer_array->size = 0;
buffer_array->capacity = default_capacity;
return buffer_array;
}
void buffer_array_put(buffer_array_t *self, void *data, int length) {
if (self->size + length > self->capacity) {
unsigned char *data = (unsigned char *)realloc(self->data, self->capacity * 2);
if (!data) {
return;
}
self->capacity = self->capacity * 2;
self->data = data;
}
memcpy(self->data + self->size, data, length);
self->size += length;
}
void buffer_array_clear(buffer_array_t *self) {
self->size = 0;
memset(self->data, 0, self->capacity);
return;
}
void buffer_array_destory(buffer_array_t *self) {
free(self->data);
self->data = NULL;
free(self);
return;
}
<file_sep>/HookZz/src/interceptor_routing_trampoline.c
#include "interceptor_routing_trampoline.h"
void interceptor_trampoline_cclass(build_all)(hook_entry_t *entry) {
if (entry->type == HOOK_TYPE_FUNCTION_via_PRE_POST) {
interceptor_trampoline_cclass(prepare)(entry);
interceptor_trampoline_cclass(build_for_enter)(entry);
interceptor_trampoline_cclass(build_for_invoke)(entry);
interceptor_trampoline_cclass(build_for_leave)(entry);
} else if (entry->type == HOOK_TYPE_FUNCTION_via_REPLACE) {
interceptor_trampoline_cclass(prepare)(entry);
interceptor_trampoline_cclass(build_for_enter_transfer)(entry);
interceptor_trampoline_cclass(build_for_invoke)(entry);
} else if (entry->type == HOOK_TYPE_FUNCTION_via_GOT) {
// trampoline_prepare(self, entry);
interceptor_trampoline_cclass(build_for_enter)(entry);
interceptor_trampoline_cclass(build_for_leave)(entry);
} else if (entry->type == HOOK_TYPE_INSTRUCTION_via_DBI) {
interceptor_trampoline_cclass(prepare)(entry);
interceptor_trampoline_cclass(build_for_dynamic_binary_instrumentation)(entry);
interceptor_trampoline_cclass(build_for_invoke)(entry);
}
return;
}
<file_sep>/HookZz/src/std_kit/std_map.h
/**
* Copyright (c) 2014 rxi
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the MIT license. See LICENSE for details.
*/
#ifndef MAP_H
#define MAP_H
#include <string.h>
#define MAP_VERSION "0.1.0"
typedef union {
int _int;
float _float;
double _double;
void *_pointer;
} map_value_t;
typedef struct _map_node_t {
unsigned hash;
map_value_t value;
struct _map_node_t *next;
} map_node_t;
typedef struct {
map_node_t **buckets;
unsigned nbuckets;
unsigned nnodes;
} map_base_t, map_t;
typedef struct {
unsigned bucket_index;
map_node_t *node_next;
} map_iter_t;
map_base_t *map_new();
void map_destory(map_base_t *m);
map_value_t map_get_value(map_base_t *m, const char *key);
int map_set_value(map_base_t *m, const char *key, map_value_t value);
void map_remove_value(map_base_t *m, const char *key);
map_iter_t map_iter_new(void);
map_node_t *map_iter_next(map_base_t *m, map_iter_t *iter);
#endif
<file_sep>/HookZz/srcxx/Interceptor.cpp
//
// Created by z on 2018/6/14.
//
#include "Interceptor.h"
Interceptor *Interceptor::GETInstance() {
if (priv_interceptor == NULL) {
priv_interceptor = new Interceptor();
priv_interceptor->mm = MemoryManager::GetInstance();
}
return priv_interceptor;
}
HookEntry *Interceptor::findHookEntry(void *target_address) {
for (auto entry : hook_entries) {
if (entry->target_address == target_address) {
return entry;
}
}
return NULL;
}
void Interceptor::addHookEntry(HookEntry *entry) { hook_entries.push_back(entry); }
<file_sep>/HookZz/src/platforms/arch-arm64/writer-arm64.c
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include "memory_manager.h"
#include "writer-arm64.h"
inline void ReadBytes(void *data, void *address, int length) { memcpy(data, address, length); }
ARM64AssemblyWriter *arm64_assembly_writer_cclass(new)(void *pc) {
ARM64AssemblyWriter *writer = SAFE_MALLOC_TYPE(ARM64AssemblyWriter);
writer->start_pc = pc;
writer->instCTXs = list_new();
writer->inst_bytes = buffer_array_create(64);
return writer;
}
void arm64_assembly_writer_cclass(destory)(ARM64AssemblyWriter *self) {}
void arm64_assembly_writer_cclass(reset)(ARM64AssemblyWriter *self, void *pc) {
self->start_pc = pc;
list_destroy(self->instCTXs);
self->instCTXs = list_new();
buffer_array_clear(self->inst_bytes);
return;
}
void arm64_assembly_writer_cclass(patch_to)(ARM64AssemblyWriter *self, void *target_address) {
self->start_address = target_address;
memory_manager_t *memory_manager;
memory_manager = memory_manager_cclass(shared_instance)();
memory_manager_cclass(patch_code)(memory_manager, target_address, self->inst_bytes->data, self->inst_bytes->size);
return;
}
size_t arm64_assembly_writer_cclass(bxxx_range)() { return ((1 << 23) << 2); }
#define ARM64_INST_SIZE 4
void arm64_assembly_writer_cclass(put_bytes)(ARM64AssemblyWriter *self, void *data, int length) {
assert(length % 4 == 0);
for (int i = 0; i < (length / ARM64_INST_SIZE); i++) {
ARM64InstructionCTX *instCTX = SAFE_MALLOC_TYPE(ARM64InstructionCTX);
instCTX->pc = (zz_addr_t)self->start_pc + self->inst_bytes->size;
instCTX->address = (zz_addr_t)self->inst_bytes->data + self->inst_bytes->size;
instCTX->size = ARM64_INST_SIZE;
ReadBytes(&instCTX->bytes, (void *)((zz_addr_t)data + ARM64_INST_SIZE * i), ARM64_INST_SIZE);
buffer_array_put(self->inst_bytes, (void *)((zz_addr_t)data + ARM64_INST_SIZE * i), ARM64_INST_SIZE);
list_rpush(self->instCTXs, list_node_new(instCTX));
}
}
void arm64_assembly_writer_cclass(put_ldr_reg_imm)(ARM64AssemblyWriter *self, ARM64Reg reg, uint32_t offset) {
ARM64RegInfo ri;
arm64_register_describe(reg, &ri);
uint32_t imm19, Rt;
imm19 = offset >> 2;
Rt = ri.index;
uint32_t inst = 0x58000000 | imm19 << 5 | Rt;
arm64_assembly_writer_cclass(put_bytes)(self, (void *)&inst, 4);
}
void arm64_assembly_writer_cclass(put_str_reg_reg_offset)(ARM64AssemblyWriter *self, ARM64Reg src_reg,
ARM64Reg dest_reg, uint64_t offset) {
ARM64RegInfo rs, rd;
arm64_register_describe(src_reg, &rs);
arm64_register_describe(dest_reg, &rd);
uint32_t size, v = 0, opc = 0, Rn_ndx, Rt_ndx;
Rn_ndx = rd.index;
Rt_ndx = rs.index;
if (rs.is_integer) {
size = (rs.width == 64) ? 0b11 : 0b10;
}
uint32_t imm12 = offset >> size;
uint32_t inst = 0x39000000 | size << 30 | opc << 22 | imm12 << 10 | Rn_ndx << 5 | Rt_ndx;
arm64_assembly_writer_cclass(put_bytes)(self, (void *)&inst, 4);
}
void arm64_assembly_writer_cclass(put_ldr_reg_reg_offset)(ARM64AssemblyWriter *self, ARM64Reg dest_reg,
ARM64Reg src_reg, uint64_t offset) {
ARM64RegInfo rs, rd;
arm64_register_describe(src_reg, &rs);
arm64_register_describe(dest_reg, &rd);
uint32_t size, v = 0, opc = 0b01, Rn_ndx, Rt_ndx;
Rn_ndx = rs.index;
Rt_ndx = rd.index;
if (rs.is_integer) {
size = (rs.width == 64) ? 0b11 : 0b10;
}
uint32_t imm12 = offset >> size;
uint32_t inst = 0x39000000 | size << 30 | opc << 22 | imm12 << 10 | Rn_ndx << 5 | Rt_ndx;
arm64_assembly_writer_cclass(put_bytes)(self, (void *)&inst, 4);
}
void arm64_assembly_writer_cclass(put_br_reg)(ARM64AssemblyWriter *self, ARM64Reg reg) {
ARM64RegInfo ri;
arm64_register_describe(reg, &ri);
uint32_t op = 0, Rn_ndx;
Rn_ndx = ri.index;
uint32_t inst = 0xd61f0000 | op << 21 | Rn_ndx << 5;
arm64_assembly_writer_cclass(put_bytes)(self, (void *)&inst, 4);
}
void arm64_assembly_writer_cclass(put_blr_reg)(ARM64AssemblyWriter *self, ARM64Reg reg) {
ARM64RegInfo ri;
arm64_register_describe(reg, &ri);
uint32_t op = 0b01, Rn_ndx;
Rn_ndx = ri.index;
uint32_t inst = 0xd63f0000 | op << 21 | Rn_ndx << 5;
arm64_assembly_writer_cclass(put_bytes)(self, (void *)&inst, 4);
}
void arm64_assembly_writer_cclass(put_b_imm)(ARM64AssemblyWriter *self, uint64_t offset) {
uint32_t op = 0b0, imm26;
imm26 = (offset >> 2) & 0x03ffffff;
uint32_t inst = 0x14000000 | op << 31 | imm26;
arm64_assembly_writer_cclass(put_bytes)(self, (void *)&inst, 4);
}<file_sep>/HookZz/srcxx/InterceptorRoutingTrampoline.cpp
//
// Created by jmpews on 2018/6/15.
//
#include "InterceptorBackend.h"
void InterceptorRoutingTrampoline::BuildAllTrampoline(HookEntry *entry) {
if (entry->hook_type == HOOK_TYPE_FUNCTION_via_PRE_POST) {
Prepare(entry);
BuildForEnter(entry);
BuildForInvoke(entry);
BuildForLeave(entry);
} else if (entry->hook_type == HOOK_TYPE_FUNCTION_via_REPLACE) {
Prepare(entry);
BuildForEnterTransfer(entry);
BuildForInvoke(entry);
} else if (entry->hook_type == HOOK_TYPE_FUNCTION_via_GOT) {
BuildForEnter(entry);
BuildForLeave(entry);
} else if (entry->hook_type == HOOK_TYPE_INSTRUCTION_via_DBI) {
Prepare(entry);
BuildForDynamicBinaryInstrumentation(entry);
BuildForInvoke(entry);
}
}<file_sep>/HookZz/srcxx/Macros.h
//
// Created by jmpews on 2018/6/15.
//
#ifndef HOOKZZ_MACROS_H
#define HOOKZZ_MACROS_H
#include <stdint.h>
#define INT5_MASK 0x0000001f
#define INT8_MASK 0x000000ff
#define INT10_MASK 0x000003ff
#define INT11_MASK 0x000007ff
#define INT12_MASK 0x00000fff
#define INT14_MASK 0x00003fff
#define INT16_MASK 0x0000ffff
#define INT18_MASK 0x0003ffff
#define INT19_MASK 0x0007ffff
#define INT24_MASK 0x00ffffff
#define INT26_MASK 0x03ffffff
#define INT28_MASK 0x0fffffff
#define THUMB_FUNCTION_ADDRESS(address) ((uintptr_t)address & ~(uintptr_t)1)
#define INSTRUCTION_IS_THUMB(insn_addr) (((uintptr_t)insn_addr & 0x1) == 0x1)
#define ALIGN_FLOOR(address, range) ((uintptr_t)address & ~((uintptr_t)range - 1))
#define ALIGN_CEIL(address, range) (((uintptr_t)address + (uintptr_t)range - 1) & ~((uintptr_t)range - 1))
#endif //HOOKZZ_MACROS_H
<file_sep>/HookZz/srcxx/CommonClass/DesignPattern/Singleton.cpp
//
// Created by jmpews on 2018/6/14.
//
#include "Singleton.h"
// template <typename T> T *Singleton<T>::_instance = NULL;
// template <typename T> T *Singleton<T>::GetInstance() {
// if (_instance == NULL) {
// _instance = new T();
// }
// return _instance;
// }<file_sep>/HookZz/srcxx/Platforms/arch-arm64/ARM64Relocator.cpp
//
// Created by jmpews on 2018/6/14.
//
#include "ARM64Relocator.h"
#include <assert.h>
ARM64Relocator::ARM64Relocator(ARM64AssemblyReader *input, ARM64AssemblerWriter *output) {
input = input;
output = output;
}
void ARM64Relocator::reset() {
output->reset(0);
input->reset(0, 0);
literalInstCTXs.clear();
indexRelocatedInputOutput.clear();
}
void ARM64Relocator::tryRelocate(void *address, int bytes_min, int *bytes_max) {
int tmpSize = 0;
bool earlyEnd = false;
ARM64InstructionCTX *instCTX;
ARM64AssemblyReader *reader = new ARM64AssemblyReader(address, address);
do {
instCTX = reader->readInstruction();
switch (getInstType(instCTX->bytes)) {
case BImm:
earlyEnd = true;
break;
default:;
}
tmpSize += instCTX->size;
} while (tmpSize < bytes_min);
if (earlyEnd) {
*bytes_max = bytes_min;
}
delete (reader);
}
void ARM64Relocator::relocateTo(void *target_address) {
for (auto instCTX : literalInstCTXs) {
zz_addr_t literal_target_address;
literal_target_address = *(zz_addr_t *)instCTX->address;
if (literal_target_address > (zz_addr_t)input->start_pc &&
literal_target_address < ((zz_addr_t)input->start_pc + input->instBytes.size())) {
for (auto it : indexRelocatedInputOutput) {
ARM64InstructionCTX *inputInstCTX = input->instCTXs[it.first];
if (inputInstCTX->address == literal_target_address) {
*(zz_addr_t *)instCTX->address =
output->instCTXs[it.second]->pc - (zz_addr_t)output->start_pc + (zz_addr_t)target_address;
break;
}
}
}
}
}
void ARM64Relocator::doubleWrite(void *target_address) {
assert((zz_addr_t)target_address % 4 == 0);
int originInstByteSize = output->instBytes.size();
output->reset(0);
literalInstCTXs.clear();
indexRelocatedInputOutput.clear();
relocateWriteAll();
void *noNeedRelocateInstBuffer = output->instBytes.data() + output->instBytes.size();
output->putBytes(noNeedRelocateInstBuffer, originInstByteSize - output->instBytes.size());
}
void ARM64Relocator::registerLiteralInstCTX(ARM64InstructionCTX *instCTX) { literalInstCTXs.push_back(instCTX); }
void ARM64Relocator::relocateWriteAll() {
do {
relocateWrite();
} while (indexRelocatedInputOutput.size() < input->instCTXs.size());
}
void ARM64Relocator::relocateWrite() {
ARM64InstructionCTX *instCTX;
bool rewritten = true;
int doneRelocatedCount;
doneRelocatedCount = indexRelocatedInputOutput.size();
if (input->instCTXs.size() < indexRelocatedInputOutput.size()) {
instCTX = input->instCTXs[doneRelocatedCount];
} else
return;
switch (getInstType(instCTX->bytes)) {
case LoadLiteral:
rewrite_LoadLiteral(instCTX);
break;
case BaseCmpBranch:
rewrite_BaseCmpBranch(instCTX);
break;
case BranchCond:
rewrite_BranchCond(instCTX);
break;
case B:
rewrite_B(instCTX);
break;
case BL:
rewrite_BL(instCTX);
break;
default:
rewritten = false;
break;
}
if (!rewritten) {
output->putBytes((void *)&instCTX->bytes, instCTX->size);
}
indexRelocatedInputOutput.insert(std::pair<int, int>(doneRelocatedCount, output->instCTXs.size()));
}
inline uint32_t get_insn_sub(uint32_t insn, int start, int length) { return (insn >> start) & ((1 << length) - 1); }
void ARM64Relocator::rewrite_LoadLiteral(ARM64InstructionCTX *instCTX) {
uint32_t Rt, label;
int index;
zz_addr_t target_address;
Rt = get_insn_sub(instCTX->bytes, 0, 5);
label = get_insn_sub(instCTX->bytes, 5, 19);
target_address = (label << 2) + instCTX->pc;
/*
0x1000: ldr Rt, #0x8
0x1004: b #0xc
0x1008: .long 0x4321
0x100c: .long 0x8765
0x1010: ldr Rt, Rt
*/
ARM64Reg regRt = DisDescribeARM64Reigster(Rt, 0);
output->put_ldr_reg_imm(regRt, 0x8);
output->put_b_imm(0xc);
registerLiteralInstCTX(output->instCTXs[output->instCTXs.size()]);
output->putBytes((zz_ptr_t)&target_address, sizeof(target_address));
output->put_ldr_reg_reg_offset(regRt, regRt, 0);
};
void ARM64Relocator::rewrite_BaseCmpBranch(ARM64InstructionCTX *instCTX) {
uint32_t target;
uint32_t inst32;
zz_addr_t target_address;
inst32 = instCTX->bytes;
target = get_insn_sub(inst32, 5, 19);
target_address = (target << 2) + instCTX->pc;
target = 0x8 >> 2;
BIT32SET(&inst32, 5, 19, target);
output->putBytes(&inst32, instCTX->size);
output->put_b_imm(0x14);
output->put_ldr_reg_imm(ARM64_REG_X17, 0x8);
output->put_br_reg(ARM64_REG_X17);
registerLiteralInstCTX(output->instCTXs[output->instCTXs.size()]);
output->putBytes((zz_ptr_t)&target_address, sizeof(zz_ptr_t));
};
void ARM64Relocator::rewrite_BranchCond(ARM64InstructionCTX *instCTX) {
uint32_t target;
uint32_t inst32;
zz_addr_t target_address;
inst32 = instCTX->bytes;
target = get_insn_sub(inst32, 5, 19);
target_address = (target << 2) + instCTX->pc;
target = 0x8 >> 2;
BIT32SET(&inst32, 5, 19, target);
output->putBytes(&inst32, instCTX->size);
output->put_b_imm(0x14);
output->put_ldr_reg_imm(ARM64_REG_X17, 0x8);
output->put_br_reg(ARM64_REG_X17);
registerLiteralInstCTX(output->instCTXs[output->instCTXs.size()]);
output->putBytes((zz_ptr_t)&target_address, sizeof(zz_ptr_t));
};
void ARM64Relocator::rewrite_B(ARM64InstructionCTX *instCTX) {
uint32_t addr;
zz_addr_t target_address;
addr = get_insn_sub(instCTX->bytes, 0, 26);
target_address = (addr << 2) + instCTX->pc;
output->put_ldr_reg_imm(ARM64_REG_X17, 0x8);
output->put_br_reg(ARM64_REG_X17);
registerLiteralInstCTX(output->instCTXs[output->instCTXs.size()]);
output->putBytes((zz_ptr_t)&target_address, sizeof(zz_ptr_t));
}
void ARM64Relocator::rewrite_BL(ARM64InstructionCTX *instCTX) {
uint32_t op, addr;
zz_addr_t target_address, next_pc_address;
addr = get_insn_sub(instCTX->bytes, 0, 26);
target_address = (addr << 2) + instCTX->pc;
next_pc_address = instCTX->pc + 4;
output->put_ldr_reg_imm(ARM64_REG_X17, 0xc);
output->put_blr_reg(ARM64_REG_X17);
output->put_b_imm(0xc);
registerLiteralInstCTX(output->instCTXs[output->instCTXs.size()]);
output->putBytes((zz_ptr_t)&target_address, sizeof(zz_ptr_t));
output->put_ldr_reg_imm(ARM64_REG_X17, 0x8);
output->put_br_reg(ARM64_REG_X17);
registerLiteralInstCTX(output->instCTXs[output->instCTXs.size()]);
output->putBytes((zz_ptr_t)&next_pc_address, sizeof(zz_ptr_t));
}<file_sep>/HookZz/src/closure_bridge.c
#include "closure_bridge.h"
#include "memory_manager.h"
ClosureBridge *gClosureBridge = NULL;
ClosureBridge *ClosureBridgeCClass(SharedInstance)() {
if (gClosureBridge == NULL) {
gClosureBridge = SAFE_MALLOC_TYPE(ClosureBridge);
gClosureBridge->bridge_infos = list_new();
gClosureBridge->trampoline_tables = list_new();
}
return gClosureBridge;
}
ClosureBridgeTrampolineTable *ClosureBridgeCClass(AllocateClosureBridgeTrampolineTable)(ClosureBridge *self) {
void *mmap_page = NULL;
long page_size = 0;
memory_manager_t *memory_manager = memory_manager_cclass(shared_instance)();
void *page_ptr = memory_manager_cclass(allocate_page)(memory_manager, PROT_R_X, 1);
ClosureBridgeTrampolineTable *table = SAFE_MALLOC_TYPE(ClosureBridgeTrampolineTable);
ClosureBridgeCClass(InitializeTablePage)(table, page_ptr);
list_rpush(self->trampoline_tables, list_node_new(table));
return table;
}
ClosureBridgeInfo *ClosureBridgeCClass(AllocateClosureBridge)(ClosureBridge *self, void *user_data, void *user_code) {
ClosureBridgeInfo *cb_info = NULL;
ClosureBridgeTrampolineTable *table = NULL;
list_iterator_t *it = list_iterator_new(self->trampoline_tables, LIST_HEAD);
for (int i = 0; i < self->trampoline_tables->len; i++) {
ClosureBridgeTrampolineTable *tmp_table =
(ClosureBridgeTrampolineTable *)(list_at(self->trampoline_tables, i)->val);
if (tmp_table->free_count > 0) {
table = tmp_table;
}
}
if (!table) {
table = ClosureBridgeCClass(AllocateClosureBridgeTrampolineTable)(self);
}
cb_info = SAFE_MALLOC_TYPE(ClosureBridgeInfo);
ClosureBridgeCClass(InitializeClosureBridgeInfo)(table, cb_info, user_data, user_code);
list_rpush(self->bridge_infos, list_node_new(cb_info));
return cb_info;
}
<file_sep>/HookZz/src/std_kit/std_kit.c
#include "std_kit.h"
void *safe_malloc(size_t size) {
if (size <= 0) {
ERROR_LOG("[!] malloc with size %ld", size);
return NULL;
}
void *data = (void *)malloc(size);
if (!data) {
ERROR_LOG_STR("[!] malloc return NULL !!!");
return data;
}
memset(data, 0, size);
return data;
}
<file_sep>/HookZz/srcxx/CommonClass/DesignPattern/Singleton.h
//
// Created by jmpews on 2018/6/14.
//
#ifndef HOOKZZ_SINGLETON_H
#define HOOKZZ_SINGLETON_H
#include <pthread.h>
template <typename T> class Singleton {
private:
static T *_instance;
public:
static T *GetInstance();
};
template <typename T> T *Singleton<T>::_instance = NULL;
template <typename T> T *Singleton<T>::GetInstance() {
if (_instance == NULL) {
_instance = new T();
}
return _instance;
}
#endif //HOOKZZ_SINGLETON_H
<file_sep>/HookZz/src/platforms/backend-darwin/memory-helper-darwin.c
#include "memory-helper-darwin.h"
#include <unistd.h>
int darwin_memory_helper_cclass(get_page_size)() { return getpagesize(); }
void darwin_memory_helper_cclass(get_memory_info)(void *address, vm_prot_t *prot, vm_inherit_t *inherit) {
vm_address_t region = (vm_address_t)address;
vm_size_t region_size = 0;
struct vm_region_submap_short_info_64 info;
mach_msg_type_number_t info_count = VM_REGION_SUBMAP_SHORT_INFO_COUNT_64;
natural_t max_depth = 99999;
kern_return_t kr;
kr = vm_region_recurse_64(mach_task_self(), ®ion, ®ion_size, &max_depth, (vm_region_recurse_info_t)&info,
&info_count);
if (kr != KERN_SUCCESS) {
return;
}
*prot = info.protection;
*inherit = info.inheritance;
}
void darwin_memory_helper_cclass(set_page_permission)(void *address, int prot, int n) {
kern_return_t kr;
int page_size = memory_manager_cclass(get_page_size)();
kr = mach_vm_protect(mach_task_self(), (vm_address_t)address, page_size * n, FALSE, prot);
if (kr != KERN_SUCCESS) {
ERROR_LOG_STR("[[darwin_memory_helper_cclass(set_page_permission)]]");
}
}
<file_sep>/HookZz/src/platforms/arch-arm64/interceptor-routing-trampoline-arm64.c
#include "interceptor-routing-trampoline-arm64.h"
#include "closure_bridge.h"
#include "interceptor.h"
#include "interceptor_routing.h"
#include "interceptor_routing_trampoline.h"
#include "logging.h"
#include "macros.h"
#include "memory_manager.h"
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#define ARM64_TINY_REDIRECT_SIZE 4
#define ARM64_FULL_REDIRECT_SIZE 16
#define ARM64_NEAR_JUMP_RANGE ((1 << 25) << 2)
void interceptor_cclass(initialize_interceptor_backend)(memory_manager_t *memory_manager) {
if (memory_manager == NULL) {
memory_manager = memory_manager_cclass(shared_instance)();
}
interceptor_backend_arm64_t *backend = SAFE_MALLOC_TYPE(interceptor_backend_arm64_t);
backend->reader_arm64 = SAFE_MALLOC_TYPE(ARM64AssemblyReader);
backend->writer_arm64 = SAFE_MALLOC_TYPE(ARM64AssemblyWriter);
backend->relocator_arm64 = SAFE_MALLOC_TYPE(ARM64Relocator);
backend->memory_manager = memory_manager;
}
ARCH_API void interceptor_trampoline_cclass(prepare)(hook_entry_t *entry) {
int limit_relocate_inst_size = 0;
hook_entry_backend_arm64_t *entry_backend = SAFE_MALLOC_TYPE(hook_entry_backend_arm64_t);
entry->backend = (struct _hook_entry_backend_t *)entry_backend;
if (entry->is_try_near_jump) {
entry_backend->limit_relocate_inst_size = ARM64_TINY_REDIRECT_SIZE;
} else {
arm64_assembly_relocator_cclass(try_relocate)(entry->target_address, ARM64_FULL_REDIRECT_SIZE,
&limit_relocate_inst_size);
if (limit_relocate_inst_size != 0 && limit_relocate_inst_size > ARM64_TINY_REDIRECT_SIZE &&
limit_relocate_inst_size < ARM64_FULL_REDIRECT_SIZE) {
entry->is_near_jump = true;
entry_backend->limit_relocate_inst_size = ARM64_TINY_REDIRECT_SIZE;
} else if (limit_relocate_inst_size != 0 && limit_relocate_inst_size < ARM64_TINY_REDIRECT_SIZE) {
return;
} else {
entry_backend->limit_relocate_inst_size = ARM64_FULL_REDIRECT_SIZE;
}
}
// save original prologue
memcpy(entry->origin_prologue.data, entry->target_address, entry_backend->limit_relocate_inst_size);
entry->origin_prologue.size = entry_backend->limit_relocate_inst_size;
entry->origin_prologue.address = entry->target_address;
}
ARCH_API void interceptor_trampoline_cclass(active)(hook_entry_t *entry) {
hook_entry_backend_arm64_t *entry_backend = (hook_entry_backend_arm64_t *)entry->backend;
ARM64AssemblyWriter *writer_arm64 = NULL;
writer_arm64 = arm64_assembly_writer_cclass(new)(entry->target_address);
// if use near jump, all is same
if (entry_backend->limit_relocate_inst_size == ARM64_TINY_REDIRECT_SIZE) {
arm64_assembly_writer_cclass(put_b_imm)(writer_arm64, (zz_addr_t)entry->on_enter_transfer_trampoline -
(zz_addr_t)writer_arm64->start_pc);
} else {
arm64_assembly_writer_cclass(put_ldr_reg_imm)(writer_arm64, ARM64_REG_X17, 0x8);
arm64_assembly_writer_cclass(put_br_reg)(writer_arm64, ARM64_REG_X17);
if (entry->type == HOOK_TYPE_FUNCTION_via_REPLACE) {
arm64_assembly_writer_cclass(put_bytes)(writer_arm64, &entry->on_enter_transfer_trampoline, sizeof(void *));
} else if (entry->type == HOOK_TYPE_INSTRUCTION_via_DBI) {
arm64_assembly_writer_cclass(put_bytes)(writer_arm64, &entry->on_dynamic_binary_instrumentation_trampoline,
sizeof(void *));
} else {
arm64_assembly_writer_cclass(put_bytes)(writer_arm64, &entry->on_enter_trampoline, sizeof(void *));
}
}
memory_manager_t *memory_manager = memory_manager_cclass(shared_instance)();
memory_manager_cclass(patch_code)(memory_manager, entry->target_address, writer_arm64->inst_bytes->data,
writer_arm64->inst_bytes->size);
arm64_assembly_writer_cclass(destory)(writer_arm64);
{
char buffer[1024] = {};
sprintf(buffer + strlen(buffer), "\n======= Logging ======= \n");
sprintf(buffer + strlen(buffer), "\tTargetAddress: %p\n", entry->target_address);
sprintf(buffer + strlen(buffer), "\tArchitecture: ARM64\n");
if (entry_backend->limit_relocate_inst_size == ARM64_TINY_REDIRECT_SIZE) {
sprintf(buffer + strlen(buffer), "\tBrachJumpType: Near Jump(B xxx)\n");
} else if (entry_backend->limit_relocate_inst_size == ARM64_FULL_REDIRECT_SIZE) {
sprintf(buffer + strlen(buffer), "\ttBrachJumpType: Abs Jump(ldr r17, #4; .long address)\n");
}
if (entry->is_near_jump && entry->on_enter_transfer_trampoline)
sprintf(buffer + strlen(buffer), "\ton_enter_transfer_trampoline: %p\n",
entry->on_enter_transfer_trampoline);
if (entry->type == HOOK_TYPE_INSTRUCTION_via_DBI) {
sprintf(buffer + strlen(buffer), "\tHook Type: HOOK_TYPE_INSTRUCTION_via_DBI\n");
sprintf(buffer + strlen(buffer), "\ton_dynamic_binary_instrumentation_trampoline: %p\n",
entry->on_dynamic_binary_instrumentation_trampoline);
sprintf(buffer + strlen(buffer), "\ton_invoke_trampoline: %p\n", entry->on_invoke_trampoline);
} else if (entry->type == HOOK_TYPE_FUNCTION_via_PRE_POST) {
sprintf(buffer + strlen(buffer), "\tHook Type: HOOK_TYPE_FUNCTION_via_PRE_POST\n");
sprintf(buffer + strlen(buffer), "\ton_enter_trampoline: %p\n", entry->on_enter_trampoline);
sprintf(buffer + strlen(buffer), "\ton_leave_trampoline: %p\n", entry->on_leave_trampoline);
sprintf(buffer + strlen(buffer), "\ton_invoke_trampoline: %p\n", entry->on_invoke_trampoline);
} else if (entry->type == HOOK_TYPE_FUNCTION_via_REPLACE) {
sprintf(buffer + strlen(buffer), "\tHook Type: HOOK_TYPE_FUNCTION_via_REPLACE\n");
sprintf(buffer + strlen(buffer), "\ton_enter_transfer_trampoline: %p\n",
entry->on_enter_transfer_trampoline);
sprintf(buffer + strlen(buffer), "\ton_invoke_trampoline: %p\n", entry->on_invoke_trampoline);
} else if (entry->type == HOOK_TYPE_FUNCTION_via_GOT) {
sprintf(buffer + strlen(buffer), "\tHook Type: HOOK_TYPE_FUNCTION_via_GOT\n");
sprintf(buffer + strlen(buffer), "\ton_enter_trampoline: %p\n", entry->on_enter_trampoline);
sprintf(buffer + strlen(buffer), "\ton_leave_trampoline: %p\n", entry->on_leave_trampoline);
}
Logging("%s", buffer);
}
}
ARCH_API void interceptor_trampoline_cclass(build_for_enter_transfer)(hook_entry_t *entry) {
hook_entry_backend_arm64_t *entry_backend = (hook_entry_backend_arm64_t *)entry->backend;
ARM64AssemblyWriter *writer_arm64 = NULL;
writer_arm64 = arm64_assembly_writer_cclass(new)(0);
arm64_assembly_writer_cclass(put_ldr_reg_imm)(writer_arm64, ARM64_REG_X17, 0x8);
arm64_assembly_writer_cclass(put_br_reg)(writer_arm64, ARM64_REG_X17);
if (entry->type == HOOK_TYPE_FUNCTION_via_REPLACE) {
arm64_assembly_writer_cclass(put_bytes)(writer_arm64, &entry->replace_call, sizeof(void *));
} else if (entry->type == HOOK_TYPE_INSTRUCTION_via_DBI) {
arm64_assembly_writer_cclass(put_bytes)(writer_arm64, &entry->on_dynamic_binary_instrumentation_trampoline,
sizeof(void *));
} else {
arm64_assembly_writer_cclass(put_bytes)(writer_arm64, &entry->on_enter_trampoline, sizeof(void *));
}
memory_manager_t *memory_manager = memory_manager_cclass(shared_instance)();
if (entry_backend->limit_relocate_inst_size == ARM64_TINY_REDIRECT_SIZE) {
CodeCave *cc = NULL;
cc = memory_manager_cclass(search_code_cave)(memory_manager, entry->target_address,
arm64_assembly_writer_cclass(bxxx_range)(),
writer_arm64->inst_bytes->size);
XCHECK(cc);
arm64_assembly_writer_cclass(patch_to)(writer_arm64, cc->address);
entry->on_enter_transfer_trampoline = (void *)cc->address;
SAFE_FREE(cc);
} else {
CodeSlice *cs = NULL;
cs = memory_manager_cclass(allocate_code_slice)(memory_manager, writer_arm64->inst_bytes->size);
XCHECK(cs);
arm64_assembly_writer_cclass(patch_to)(writer_arm64, cs->data);
entry->on_enter_transfer_trampoline = (void *)cs->data;
SAFE_FREE(cs);
}
}
ARCH_API void interceptor_trampoline_cclass(build_for_enter)(hook_entry_t *entry) {
hook_entry_backend_arm64_t *entry_backend = (hook_entry_backend_arm64_t *)entry->backend;
#if DYNAMIC_CLOSURE_BRIDGE
if (entry->type == HOOK_TYPE_FUNCTION_via_GOT) {
DynamicClosureBridgeInfo *dcbInfo = NULL;
DynamicClosureBridge *dcb = DynamicClosureBridgeCClass(SharedInstance)();
DynamicClosureBridgeCClass(AllocateDynamicClosureBridge)(
dcb, entry, (void *)interceptor_routing_begin_dynamic_bridge_handler);
if (dcbInfo == NULL) {
ERROR_LOG_STR("build closure bridge failed!!!");
}
entry->on_enter_trampoline = dcbInfo->redirect_trampoline;
}
#else
if (entry->type == HOOK_TYPE_FUNCTION_via_GOT) {
ClosureBridgeInfo *cbInfo = NULL;
ClosureBridge *cb = ClosureBridgeCClass(SharedInstance)();
cbInfo =
ClosureBridgeCClass(AllocateClosureBridge)(cb, entry, (void *)interceptor_routing_begin_bridge_handler);
if (cbInfo == NULL) {
ERROR_LOG_STR("build closure bridge failed!!!");
}
entry->on_enter_trampoline = cbInfo->redirect_trampoline;
}
#endif
if (entry->type != HOOK_TYPE_FUNCTION_via_GOT) {
ClosureBridgeInfo *cbInfo = NULL;
ClosureBridge *cb = ClosureBridgeCClass(SharedInstance)();
cbInfo =
ClosureBridgeCClass(AllocateClosureBridge)(cb, entry, (void *)interceptor_routing_begin_bridge_handler);
if (cbInfo == NULL) {
ERROR_LOG_STR("build closure bridge failed!!!");
}
entry->on_enter_trampoline = cbInfo->redirect_trampoline;
}
// build the double trampline aka enter_transfer_trampoline
if (entry_backend && entry_backend->limit_relocate_inst_size == ARM64_TINY_REDIRECT_SIZE) {
if (entry->type != HOOK_TYPE_FUNCTION_via_GOT) {
interceptor_trampoline_cclass(build_for_enter_transfer)(entry);
}
}
}
ARCH_API void interceptor_trampoline_cclass(build_for_invoke)(hook_entry_t *entry) {
hook_entry_backend_arm64_t *entry_backend = (hook_entry_backend_arm64_t *)entry->backend;
zz_addr_t origin_next_inst_addr;
ARM64AssemblyReader *reader_arm64 = arm64_assembly_reader_cclass(new)(entry->target_address, entry->target_address);
ARM64AssemblyWriter *writer_arm64 = arm64_assembly_writer_cclass(new)(0);
ARM64Relocator *relocator_arm64 = arm64_assembly_relocator_cclass(new)(reader_arm64, writer_arm64);
do {
arm64_assembly_reader_cclass(read_inst)(relocator_arm64->input);
arm64_assembly_relocator_cclass(relocate_write)(relocator_arm64);
} while (relocator_arm64->input->inst_bytes->size < entry_backend->limit_relocate_inst_size);
assert(entry_backend->limit_relocate_inst_size == relocator_arm64->input->inst_bytes->size);
origin_next_inst_addr = (zz_addr_t)entry->target_address + relocator_arm64->input->inst_bytes->size;
arm64_assembly_writer_cclass(put_ldr_reg_imm)(writer_arm64, ARM64_REG_X17, 0x8);
arm64_assembly_writer_cclass(put_br_reg)(writer_arm64, ARM64_REG_X17);
arm64_assembly_writer_cclass(put_bytes)(writer_arm64, &origin_next_inst_addr, sizeof(void *));
memory_manager_t *memory_manager = memory_manager_cclass(shared_instance)();
CodeSlice *cs = NULL;
cs = memory_manager_cclass(allocate_code_slice)(memory_manager, relocator_arm64->output->inst_bytes->size);
XCHECK(cs);
arm64_assembly_relocator_cclass(double_write)(relocator_arm64, cs->data);
arm64_assembly_writer_cclass(patch_to)(relocator_arm64->output, cs->data);
entry->on_invoke_trampoline = (void *)cs->data;
SAFE_FREE(cs);
}
ARCH_API void interceptor_trampoline_cclass(build_for_leave)(hook_entry_t *entry) {
hook_entry_backend_arm64_t *entry_backend = (hook_entry_backend_arm64_t *)entry->backend;
#if DYNAMIC_CLOSURE_BRIDGE
if (entry->type == HOOK_TYPE_FUNCTION_via_GOT) {
DynamicClosureBridgeInfo *dcbInfo = NULL;
DynamicClosureBridge *dcb = DynamicClosureBridgeCClass(SharedInstance)();
dcbInfo = DynamicClosureBridgeCClass(AllocateDynamicClosureBridge)(
dcb, entry, (void *)interceptor_routing_end_dynamic_bridge_handler);
if (dcbInfo == NULL) {
ERROR_LOG_STR("build closure bridge failed!!!");
}
entry->on_leave_trampoline = dcbInfo->redirect_trampoline;
}
#else
if (entry->type == HOOK_TYPE_FUNCTION_via_GOT) {
ClosureBridgeInfo *cbInfo = NULL;
ClosureBridge *cb = ClosureBridgeCClass(SharedInstance)();
cbInfo = ClosureBridgeCClass(AllocateClosureBridge)(cb, entry, (void *)interceptor_routing_end_bridge_handler);
if (cbInfo == NULL) {
ERROR_LOG_STR("build closure bridge failed!!!");
}
entry->on_leave_trampoline = cbInfo->redirect_trampoline;
}
#endif
if (entry->type != HOOK_TYPE_FUNCTION_via_GOT) {
ClosureBridgeInfo *cbInfo = NULL;
ClosureBridge *cb = ClosureBridgeCClass(SharedInstance)();
cbInfo = ClosureBridgeCClass(AllocateClosureBridge)(cb, entry, (void *)interceptor_routing_end_bridge_handler);
if (cbInfo == NULL) {
ERROR_LOG_STR("build closure bridge failed!!!");
}
entry->on_leave_trampoline = cbInfo->redirect_trampoline;
}
}
ARCH_API void interceptor_trampoline_cclass(build_for_dynamic_binary_instrumentation)(hook_entry_t *entry) {
hook_entry_backend_arm64_t *entry_backend = (hook_entry_backend_arm64_t *)entry->backend;
ClosureBridgeInfo *cbInfo = NULL;
ClosureBridge *cb = ClosureBridgeCClass(SharedInstance)();
cbInfo = ClosureBridgeCClass(AllocateClosureBridge)(
cb, entry, (void *)interceptor_routing_dynamic_binary_instrumentation_bridge_handler);
if (cbInfo == NULL) {
ERROR_LOG_STR("build closure bridge failed!!!");
}
entry->on_dynamic_binary_instrumentation_trampoline = cbInfo->redirect_trampoline;
// build the double trampline aka enter_transfer_trampoline
if (entry_backend->limit_relocate_inst_size == ARM64_TINY_REDIRECT_SIZE) {
if (entry->type != HOOK_TYPE_FUNCTION_via_GOT) {
interceptor_trampoline_cclass(build_for_enter_transfer)(entry);
}
}
}
<file_sep>/HookZz/tests/c/hookzz_test.cpp
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
// fake the not found function.
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
void closure_bridge_template();
void closure_bridge_trampoline_template();
#ifdef __cplusplus
}
#endif //__cplusplus
void closure_bridge_template() {}
void closure_bridge_trampoline_template() {}
#include "memory_manager.h"
TEST_CASE(">>> memory_manager_t", "[memory]") {
memory_manager_t *memory_manager = memory_manager_cclass(shared_instance)();
REQUIRE(memory_manager != NULL);
int page_size = memory_manager_cclass(get_page_size)();
REQUIRE(page_size > 0);
void *page_ptr = memory_manager_cclass(allocate_page)(memory_manager, 1 | 2, 1);
REQUIRE(page_ptr != NULL);
memory_manager_cclass(get_process_memory_layout)(memory_manager);
REQUIRE(memory_manager->process_memory_layout->len > 0);
CodeSlice *cs = memory_manager_cclass(allocate_code_slice)(memory_manager, 0x16);
REQUIRE(cs != NULL);
REQUIRE(cs->size == 0x16);
}
#include "core.h"
#include "interceptor.h"
TEST_CASE(">>> interceptor_t", "[interceptor]") {
interceptor_t *interceptor = interceptor_cclass(shared_instance)();
REQUIRE(interceptor != NULL);
hook_entry_t *entry = SAFE_MALLOC_TYPE(hook_entry_t);
entry->target_address = (void *)0x1234;
interceptor_cclass(add_hook_entry)(interceptor, entry);
REQUIRE(interceptor->hook_entries->len == 1);
hook_entry_t *find_entry = interceptor_cclass(find_hook_entry)(interceptor, (void *)0x1234);
REQUIRE(find_entry != NULL);
}
#include "core.h"
#include "platforms/arch-arm64/relocator-arm64.h"
// mov x0, x0
// ldr x0, #0x10
// b #0x20
// cbz x0, #0x20
__attribute__((aligned(4))) uint32_t test_func[4] = {0xAA0003E0, 0x58000080, 0x14000008, 0xB4000100};
__attribute__((aligned(4))) uint32_t relocated_func[32] = {0};
__attribute__((aligned(4))) uint32_t correct_relocated_func[32] = {0};
// clang-format off
__attribute__((constructor)) void build_correct_relocated_func() {
/*
origin:
0x1000: mov x0, x0
relocated:
0x2000: mov x0, x0
*/
correct_relocated_func[0] = 0xAA0003E0;
/*
origin:
0x1004: ldr x0, 0x10
relocated:
0x2004: ldr x0, #0x8
0x2008: b #0xc
0x200c: .long #0x1014
0x2010: .long #0x0
0x2014: ldr x0, [x0, #0x0]
*/
correct_relocated_func[1] = 0x58000040;
correct_relocated_func[2] = 0x14000003;
*(uintptr_t *)&correct_relocated_func[3] = (uintptr_t)test_func + 4 + 0x10;
correct_relocated_func[5] = 0xF9400000;
/*
origin:
0x1008: b #0x20
relocated:
0x2018: ldr x17, #0x8
0x201c: br x17
0x2020: .long #0x1028
0x2024: .long #0x0
*/
correct_relocated_func[6] = 0x58000051;
correct_relocated_func[7] = 0xD61F0220;
*(uintptr_t *)&correct_relocated_func[8] = (uintptr_t)test_func + 8 + 0x20;
/*
origin:
0x100c: cbz x0, #0x20
relocated:
0x2028: cbz x0, #0x8
0x202c: b #0x14
0x2030: ldr x17, #0x8
0x2034: br x17
0x2038: .long #0x102c
0x203c: .long #0x0
*/
correct_relocated_func[10] = 0xB4000040;
correct_relocated_func[11] = 0x14000005;
correct_relocated_func[12] = 0x58000051;
correct_relocated_func[13] = 0xD61F0220;
*(uintptr_t *)&correct_relocated_func[14] = (uintptr_t)test_func + 0xc + 0x20;
return;
}
// clang-format on
int get_input_relocate_ouput_count(ARM64Relocator *relocator, int i) {
io_index_t *io_index = (io_index_t *)(list_at(relocator->io_indexs, i)->val);
if (i == relocator->io_indexs->len - 1) {
return relocator->output->instCTXs->len - io_index->output_index;
} else {
io_index_t *io_index_next = (io_index_t *)(list_at(relocator->io_indexs, i + 1)->val);
return io_index_next->output_index - io_index->output_index;
}
}
#define ARM64_FULL_REDIRECT_SIZE 16
TEST_CASE(">>> ARM64Relocator", "[relocator]") {
ARM64AssemblyReader *reader_arm64;
ARM64AssemblyWriter *writer_arm64;
ARM64Relocator *relocator_arm64;
reader_arm64 = arm64_assembly_reader_cclass(new)(test_func, test_func);
writer_arm64 = arm64_assembly_writer_cclass(new)(0);
relocator_arm64 = arm64_assembly_relocator_cclass(new)(reader_arm64, writer_arm64);
int limit_relocate_inst_size = 0;
arm64_assembly_relocator_cclass(try_relocate)(test_func, ARM64_FULL_REDIRECT_SIZE, &limit_relocate_inst_size);
printf(">>> limit_relocate_inst_size: %d\n", limit_relocate_inst_size);
// relocate `mov x0, x0`
arm64_assembly_reader_cclass(read_inst)(reader_arm64);
arm64_assembly_relocator_cclass(relocate_write)(relocator_arm64);
int count = get_input_relocate_ouput_count(relocator_arm64, 0);
io_index_t *io_index = (io_index_t *)(list_at(relocator_arm64->io_indexs, 0)->val);
REQUIRE(count == 1);
for (int i = io_index->output_index; i < count + io_index->output_index; i++) {
ARM64InstructionCTX *instCTX = (ARM64InstructionCTX *)(list_at(relocator_arm64->output->instCTXs, i)->val);
REQUIRE(instCTX->bytes == correct_relocated_func[i]);
// printf("0x%02x 0x%02x 0x%02x 0x%02x ", (uint8_t)instCTX->bytes, (uint8_t)(instCTX->bytes >> 8), (uint8_t)(instCTX->bytes >> 16), (uint8_t)(instCTX->bytes >> 24));
}
// relocate `ldr x0, #0x10`
arm64_assembly_reader_cclass(read_inst)(reader_arm64);
arm64_assembly_relocator_cclass(relocate_write)(relocator_arm64);
count = get_input_relocate_ouput_count(relocator_arm64, 1);
io_index = (io_index_t *)(list_at(relocator_arm64->io_indexs, 1)->val);
REQUIRE(count == 5);
for (int i = io_index->output_index; i < count + io_index->output_index; i++) {
ARM64InstructionCTX *instCTX = (ARM64InstructionCTX *)(list_at(relocator_arm64->output->instCTXs, i)->val);
REQUIRE(instCTX->bytes == correct_relocated_func[i]);
// printf("0x%02x 0x%02x 0x%02x 0x%02x ", (uint8_t)instCTX->bytes, (uint8_t)(instCTX->bytes >> 8), (uint8_t)(instCTX->bytes >> 16), (uint8_t)(instCTX->bytes >> 24));
}
// relocate `b #0x20`
arm64_assembly_reader_cclass(read_inst)(reader_arm64);
arm64_assembly_relocator_cclass(relocate_write)(relocator_arm64);
count = get_input_relocate_ouput_count(relocator_arm64, 2);
io_index = (io_index_t *)(list_at(relocator_arm64->io_indexs, 2)->val);
REQUIRE(count == 4);
for (int i = io_index->output_index; i < count + io_index->output_index; i++) {
ARM64InstructionCTX *instCTX = (ARM64InstructionCTX *)(list_at(relocator_arm64->output->instCTXs, i)->val);
REQUIRE(instCTX->bytes == correct_relocated_func[i]);
// printf("0x%02x 0x%02x 0x%02x 0x%02x ", (uint8_t)instCTX->bytes, (uint8_t)(instCTX->bytes >> 8), (uint8_t)(instCTX->bytes >> 16), (uint8_t)(instCTX->bytes >> 24));
}
// relocate `cbz x0, #0x20`
arm64_assembly_reader_cclass(read_inst)(reader_arm64);
arm64_assembly_relocator_cclass(relocate_write)(relocator_arm64);
count = get_input_relocate_ouput_count(relocator_arm64, 3);
io_index = (io_index_t *)(list_at(relocator_arm64->io_indexs, 3)->val);
REQUIRE(count == 6);
for (int i = io_index->output_index; i < count + io_index->output_index; i++) {
ARM64InstructionCTX *instCTX = (ARM64InstructionCTX *)(list_at(relocator_arm64->output->instCTXs, i)->val);
REQUIRE(instCTX->bytes == correct_relocated_func[i]);
// printf("0x%02x 0x%02x 0x%02x 0x%02x ", (uint8_t)instCTX->bytes, (uint8_t)(instCTX->bytes >> 8), (uint8_t)(instCTX->bytes >> 16), (uint8_t)(instCTX->bytes >> 24));
}
return;
}<file_sep>/HookZz/srcxx/Platforms/backend-posix/PosixClosureBridge.cpp
//
// Created by jmpews on 2018/6/14.
//
#include "PosixClosureBridge.h"
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#define closure_bridge_trampoline_template_length (7 * 4)
ClosureBridgeTrampolineTable *ClosureBridge::allocateClosureBridgeTrampolineTable() {
void *mmap_page;
long page_size;
page_size = sysconf(_SC_PAGESIZE);
mmap_page = mmap(0, 1, PROT_WRITE | PROT_READ, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
if (mmap_page == MAP_FAILED) {
// LOG-NEED
return NULL;
}
if (mprotect(mmap_page, (size_t)page_size, (PROT_READ | PROT_WRITE))) {
// LOG-NEED
return NULL;
}
int t = page_size / closure_bridge_trampoline_template_length;
void *copy_address = mmap_page;
for (int i = 0; i < t; ++i) {
copy_address = (void *)((intptr_t)mmap_page + i * closure_bridge_trampoline_template_length);
memcpy(copy_address, (void *)closure_bridge_trampoline_template, closure_bridge_trampoline_template_length);
}
if (mprotect(mmap_page, (size_t)page_size, (PROT_READ | PROT_EXEC))) {
// LOG-NEED
return NULL;
}
ClosureBridgeTrampolineTable *table = (ClosureBridgeTrampolineTable *)malloc(sizeof(ClosureBridgeTrampolineTable));
table->entry = mmap_page;
table->trampoline_page = mmap_page;
table->used_count = 0;
table->free_count = (uint16_t)t;
trampoline_tables.push_back(table);
return table;
}
ClosureBridgeInfo *ClosureBridge::allocateClosureBridge(void *user_data, void *user_code) {
ClosureBridgeInfo *cbi;
ClosureBridgeTrampolineTable *table;
long page_size = sysconf(_SC_PAGESIZE);
for (auto tmpTable : trampoline_tables) {
if (tmpTable->free_count > 0) {
table = tmpTable;
break;
}
}
if (!table)
table = allocateClosureBridgeTrampolineTable();
uint16_t trampoline_used_count = table->used_count;
void *redirect_trampoline =
(void *)((intptr_t)table->trampoline_page + closure_bridge_trampoline_template_length * trampoline_used_count);
cbi = new (ClosureBridgeInfo);
cbi->user_code = user_code;
cbi->user_data = user_data;
cbi->redirect_trampoline = redirect_trampoline;
// bind data to trampline
void *tmp = (void *)((intptr_t)cbi->redirect_trampoline + 4 * 3);
memcpy(tmp, &cbi, sizeof(ClosureBridgeInfo *));
// set trampoline to bridge
void *tmpX = (void *)closure_bridge_template;
tmp = (void *)((intptr_t)cbi->redirect_trampoline + 4 * 5);
memcpy(tmp, &tmpX, sizeof(void *));
if (mprotect(table->trampoline_page, (size_t)page_size, (PROT_READ | PROT_EXEC))) {
// LOG-NEED
return NULL;
}
table->used_count++;
table->free_count--;
return cbi;
}
<file_sep>/HookZz/src/std_kit/std_buffer_array.h
#ifndef std_buffer_array_h
#define std_buffer_array_h
#include <stdlib.h>
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct _buffer_array_t {
void *data;
int size;
int capacity;
} buffer_array_t;
buffer_array_t *buffer_array_create(int default_capacity);
void buffer_array_put(buffer_array_t *self, void *data, int length);
void buffer_array_clear(buffer_array_t *self);
void buffer_array_destory(buffer_array_t *self);
#ifdef __cplusplus
}
#endif
#endif
<file_sep>/HookZz/srcxx/Platforms/backend-posix/PosixThreadManager.cpp
//
// Created by jmpews on 2018/6/14.
//
#include "PosixThreadManager.h"
#include "ThreadManager.h"
ThreadLocalKey *ThreadManager::allocateThreadLocalKey() {
ThreadLocalKey *thread_local_key = new (ThreadLocalKey);
thread_local_keys.push_back(thread_local_key);
pthread_key_create(&thread_local_key->key, NULL);
return thread_local_key;
}
void ThreadManager::setThreadLocalData(ThreadLocalKey *thread_local_key, void *data) {
for (auto key : thread_local_keys) {
if (key == thread_local_key) {
pthread_setspecific(thread_local_key->key, data);
return;
}
}
}
void *ThreadManager::getThreadLocalData(ThreadLocalKey *thread_local_key) {
for (auto key : thread_local_keys) {
if (key == thread_local_key) {
return pthread_getspecific(thread_local_key->key);
}
}
return NULL;
}<file_sep>/HookZz/src/interceptor_routing.c
#include "interceptor_routing.h"
#include "thread_support/thread_stack.h"
void interceptor_routing_begin(RegState *rs, hook_entry_t *entry, void *next_hop_addr_PTR, void *ret_addr_PTR) {
// DEBUG_LOG("target %p call begin-invocation", entry->target_ptr);
thread_stack_manager_t *thread_stack_manager = thread_stack_cclass(shared_instance)();
call_stack_t *call_stack = call_stack_cclass(new)(thread_stack_manager);
thread_stack_cclass(push_call_stack)(thread_stack_manager, call_stack);
// call pre_call
if (entry->pre_call) {
PRECALL pre_call;
HookEntryInfo entryInfo;
entryInfo.hook_id = entry->id;
entryInfo.target_address = entry->target_address;
pre_call = entry->pre_call;
ThreadStackPublic tsp = {thread_stack_manager->thread_id, thread_stack_manager->call_stacks->len};
CallStackPublic csp = {call_stack->call_id};
(*pre_call)(rs, &tsp, &csp, &entryInfo);
}
// set next hop
if (entry->replace_call) {
*(zz_ptr_t *)next_hop_addr_PTR = entry->replace_call;
} else {
*(zz_ptr_t *)next_hop_addr_PTR = entry->on_invoke_trampoline;
}
if (entry->type == HOOK_TYPE_FUNCTION_via_PRE_POST || entry->type == HOOK_TYPE_FUNCTION_via_GOT) {
call_stack->ret_addr = *(zz_ptr_t *)ret_addr_PTR;
*(zz_ptr_t *)ret_addr_PTR = entry->on_leave_trampoline;
}
}
void interceptor_routing_end(RegState *rs, hook_entry_t *entry, void *next_hop_addr_PTR) {
// DEBUG_LOG("%p call end-invocation", entry->target_ptr);
thread_stack_manager_t *thread_stack_manager = thread_stack_cclass(shared_instance)();
call_stack_t *call_stack = thread_stack_cclass(pop_call_stack)(thread_stack_manager);
// call post_call
if (entry->post_call) {
POSTCALL post_call;
HookEntryInfo entryInfo;
entryInfo.hook_id = entry->id;
entryInfo.target_address = entry->target_address;
post_call = entry->post_call;
ThreadStackPublic tsp = {thread_stack_manager->thread_id, thread_stack_manager->call_stacks->len};
CallStackPublic csp = {call_stack->call_id};
(*post_call)(rs, &tsp, &csp, (const HookEntryInfo *)&entryInfo);
}
// set next hop
*(zz_ptr_t *)next_hop_addr_PTR = call_stack->ret_addr;
call_stack_cclass(destory)(call_stack);
}
void interceptor_routing_dynamic_binary_instrumentation(RegState *rs, hook_entry_t *entry, void *next_hop_addr_PTR) {
// DEBUG_LOG("target %p call dynamic-binary-instrumentation-invocation", entry->target_ptr);
if (entry->dbi_call) {
DBICALL dbi_call;
HookEntryInfo entryInfo;
entryInfo.hook_id = entry->id;
entryInfo.target_address = entry->target_address;
dbi_call = entry->dbi_call;
(*dbi_call)(rs, (const HookEntryInfo *)&entryInfo);
}
*(zz_ptr_t *)next_hop_addr_PTR = entry->on_invoke_trampoline;
}
void interceptor_routing_begin_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info) {
hook_entry_t *entry = cb_info->user_data;
void *next_hop_addr_PTR = get_next_hop_addr_PTR(rs);
void *ret_addr_PTR = get_ret_addr_PTR(rs);
interceptor_routing_begin(rs, entry, next_hop_addr_PTR, ret_addr_PTR);
return;
}
void interceptor_routing_end_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info) {
hook_entry_t *entry = cb_info->user_data;
void *next_hop_addr_PTR = get_next_hop_addr_PTR(rs);
interceptor_routing_end(rs, entry, next_hop_addr_PTR);
return;
}
void interceptor_routing_dynamic_binary_instrumentation_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info) {
hook_entry_t *entry = cb_info->user_data;
void *next_hop_addr_PTR = get_next_hop_addr_PTR(rs);
interceptor_routing_dynamic_binary_instrumentation(rs, entry, next_hop_addr_PTR);
return;
}
void interceptor_routing_common_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info) {
USER_CODE_CALL userCodeCall = cb_info->user_code;
// TODO: package as a function `beautiful_stack()`
uintptr_t fp_reg;
fp_reg = get_current_fp_reg();
uintptr_t *none_symbol_PTR = (uintptr_t *)fp_reg + 1;
uintptr_t none_symbol = *none_symbol_PTR;
uintptr_t *ret_addr_PTR = get_ret_addr_PTR(rs);
uintptr_t ret_addr = *ret_addr_PTR;
*none_symbol_PTR = ret_addr;
userCodeCall(rs, cb_info);
*none_symbol_PTR = none_symbol;
return;
}
#if DYNAMIC_CLOSURE_BRIDGE
void interceptor_routing_begin_dynamic_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcb_info) {
hook_entry_t *entry = dcb_info->user_data;
void *next_hop_addr_PTR = get_next_hop_addr_PTR(rs);
void *ret_addr_PTR = get_ret_addr_PTR(rs);
interceptor_routing_begin(rs, entry, next_hop_addr_PTR, ret_addr_PTR);
return;
}
void interceptor_routing_end_dynamic_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcb_info) {
hook_entry_t *entry = dcb_info->user_data;
void *next_hop_addr_PTR = get_next_hop_addr_PTR(rs);
interceptor_routing_end(rs, entry, next_hop_addr_PTR);
return;
}
void interceptor_routing_dynamic_common_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcb_info) {
DYNAMIC_USER_CODE_CALL userCodeCall = dcb_info->user_code;
userCodeCall(rs, dcb_info);
return;
}
#endif
<file_sep>/HookZz/src/std_kit/std_map.c
/**
* Copyright (c) 2014 rxi
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the MIT license. See LICENSE for details.
*/
#include "std_map.h"
#include <stdlib.h>
#include <string.h>
static unsigned map_hash(const char *str) {
unsigned hash = 5381;
while (*str) {
hash = ((hash << 5) + hash) ^ *str++;
}
return hash;
}
static map_node_t *map_node_new(const char *key, map_value_t value) {
map_node_t *node;
int key_str_len = strlen(key) + 1;
node = (map_node_t *)malloc(sizeof(map_node_t) + key_str_len);
node->hash = map_hash(key);
node->value = value;
// copy key string append the map_node_t
memcpy(node + 1, key, key_str_len);
return node;
}
static int map_bucket_index(map_base_t *m, unsigned hash) {
/* If the implementation is changed to allow a non-power-of-2 bucket count,
* the line below should be changed to use mod instead of AND */
return hash & (m->nbuckets - 1);
}
static void map_add_node(map_base_t *m, map_node_t *node) {
int n = map_bucket_index(m, node->hash);
node->next = m->buckets[n];
m->buckets[n] = node;
}
static int map_resize(map_base_t *m, int nbuckets) {
map_node_t *nodes, *node, *next;
map_node_t **buckets;
int i;
/* Chain all nodes together */
nodes = NULL;
i = m->nbuckets;
while (i--) {
node = (m->buckets)[i];
while (node) {
next = node->next;
node->next = nodes;
nodes = node;
node = next;
}
}
/* Reset buckets */
buckets = realloc(m->buckets, sizeof(*m->buckets) * nbuckets);
if (buckets != NULL) {
m->buckets = buckets;
m->nbuckets = nbuckets;
}
if (m->buckets) {
memset(m->buckets, 0, sizeof(*m->buckets) * m->nbuckets);
/* Re-add nodes to buckets */
node = nodes;
while (node) {
next = node->next;
map_add_node(m, node);
node = next;
}
}
/* Return error code if realloc() failed */
return (buckets == NULL) ? -1 : 0;
}
static map_node_t *map_get_node(map_base_t *m, const char *key) {
unsigned hash = map_hash(key);
map_node_t **next;
if (m->nbuckets > 0) {
next = &m->buckets[map_bucket_index(m, hash)];
while (*next) {
if ((*next)->hash == hash && !strcmp((char *)(*next + 1), key)) {
return *next;
}
next = &(*next)->next;
}
}
return NULL;
}
map_value_t map_get_value(map_base_t *m, const char *key) {
map_node_t *node;
node = map_get_node(m, key);
if (node)
return node->value;
return (map_value_t){0};
}
map_base_t *map_new() {
map_base_t *map = (map_base_t *)malloc(sizeof(map_base_t));
memset(map, 0, sizeof(map_base_t));
return map;
}
void map_destory(map_base_t *m) {
map_node_t *next, *node;
int i;
i = m->nbuckets;
while (i--) {
node = m->buckets[i];
while (node) {
next = node->next;
free(node);
node = next;
}
}
free(m->buckets);
}
int map_set_value(map_base_t *m, const char *key, map_value_t value) {
int n, err;
map_node_t *node;
map_value_t tmp_value;
/* Find & replace existing node */
node = map_get_node(m, key);
if (node) {
node->value = value;
return 0;
}
/* Add new node */
node = map_node_new(key, value);
if (node == NULL)
goto fail;
if (m->nnodes >= m->nbuckets) {
n = (m->nbuckets > 0) ? (m->nbuckets << 1) : 1;
err = map_resize(m, n);
if (err)
goto fail;
}
map_add_node(m, node);
m->nnodes++;
return 0;
fail:
if (node)
free(node);
return -1;
}
void map_remove_value(map_base_t *m, const char *key) {
unsigned hash = map_hash(key);
map_node_t **next;
map_node_t *node;
if (m->nbuckets > 0) {
next = &m->buckets[map_bucket_index(m, hash)];
while (*next) {
if ((*next)->hash == hash && !strcmp((char *)(*next + 1), key)) {
node = *next;
*next = (*next)->next;
free(node);
m->nnodes--;
}
next = &(*next)->next;
}
}
}
map_iter_t map_iter_new(void) {
map_iter_t iter;
iter.bucket_index = -1;
iter.node_next = NULL;
return iter;
}
map_node_t *map_iter_next(map_base_t *m, map_iter_t *iter) {
map_node_t *iter_node;
for (int i = iter->bucket_index; i < m->nbuckets; i++) {
if (iter->node_next)
iter_node = iter->node_next;
else
iter_node = m->buckets[i];
while (iter_node->next) {
iter->node_next = iter_node->next;
iter->bucket_index = i;
return iter->node_next;
}
}
return NULL;
}
<file_sep>/HookZz/src/platforms/backend-arm/custom-bridge-handler.h
//
// Created by z on 2018/4/7.
//
#ifndef CUSTOM_BRIDGE_HANDLER_H
#define CUSTOM_BRIDGE_HANDLER_H
#include "closure-bridge-arm.h"
#include "hookzz.h"
#include "interceptor.h"
#include "zkit.h"
void dynamic_context_begin_invocation_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcb_info);
void dynamic_context_end_invocation_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcb_info);
void context_begin_invocation_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info);
void context_end_invocation_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info);
void dynamic_binary_instrumentationn_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info);
#endif //CUSTOM_BRIDGE_HANDLER_H
<file_sep>/HookZz/src/interceptor_routing.h
#ifndef interceptor_routing_h
#define interceptor_routing_h
#include "closure_bridge.h"
#include "core.h"
#include "hookzz.h"
#include "interceptor.h"
ARCH_API void *get_ret_addr_PTR(RegState *rs);
ARCH_API void *get_next_hop_addr_PTR(RegState *rs);
ARCH_API void *get_current_fp_reg();
void interceptor_routing_begin(RegState *rs, hook_entry_t *entry, void *next_hop_addr_PTR, void *ret_addr_PTR);
void interceptor_routing_end(RegState *rs, hook_entry_t *entry, void *next_hop_addr_PTR);
void interceptor_routing_dynamic_binary_instrumentation(RegState *rs, hook_entry_t *entry, void *next_hop_addr_PTR);
void interceptor_routing_begin_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info);
void interceptor_routing_end_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info);
void interceptor_routing_dynamic_binary_instrumentation_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info);
void interceptor_routing_common_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info);
#if DYNAMIC_CLOSURE_BRIDGE
void interceptor_routing_begin_dynamic_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcb_info);
void interceptor_routing_end_dynamic_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcb_info);
void interceptor_routing_dynamic_common_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcb_info);
#endif
#endif<file_sep>/HookZz/src/thread_support/thread_local_storage.h
#ifndef thread_local_storage_h
#define thread_local_storage_h
#include "core.h"
#include "hookzz.h"
void *get_thread_variable_value();
void set_thread_variable_value(void *value);
#endif<file_sep>/HookZz/src/platforms/backend-posix/thread-local-storage-posix.c
#include "thread_local_storage.h"
#ifndef thread_local
#include <pthread.h>
static pthread_key_t _thread_variable_key = 0;
void *get_thread_variable_value() {
if (!_thread_variable_key)
return NULL;
void *value = pthread_getspecific(_thread_variable_key);
return value;
}
void set_thread_variable_value(void *value) {
if (!_thread_variable_key) {
int err = pthread_key_create(&_thread_variable_key, NULL);
assert(err == 0);
}
int err = pthread_setspecific(flagKey, value);
assert(err == 0);
}
#endif<file_sep>/HookZz/src/platforms/backend-darwin/dynamic-closure-bridge-darwin.c
#include "closure_bridge.h"
DynamicClosureBridge *DynamicClosureBridgeCClass(SharedInstance)() { return NULL; }
DynamicClosureBridgeInfo *DynamicClosureBridgeCClass(AllocateDynamicClosureBridge)(DynamicClosureBridge *self,
void *user_data, void *user_code) {
return NULL;
}
DynamicClosureBridgeTrampolineTable *
DynamicClosureBridgeCClass(AllocateDynamicClosureBridgeTrampolineTable)(DynamicClosureBridge *self) {
return NULL;
}
<file_sep>/HookZz/srcxx/InterceptorRouting.cpp
#include "interceptor_routing.h"
void interceptor_routing_begin(RegState *rs, hook_entry_t *entry, void *next_hop_addr_PTR, void *ret_addr_PTR) {
// DEBUG_LOG("target %p call begin-invocation", entry->target_ptr);
// call pre_call
if (entry->pre_call) {
PRECALL pre_call;
HookEntryInfo entryInfo;
entryInfo.hook_id = entry->id;
entryInfo.target_address = entry->target_address;
pre_call = entry->pre_call;
(*pre_call)(rs, (ThreadStackPublic *)NULL, (CallStackPublic *)NULL, &entryInfo);
}
// set next hop
if (entry->replace_call) {
*(zz_ptr_t *)next_hop_addr_PTR = entry->replace_call;
} else {
*(zz_ptr_t *)next_hop_addr_PTR = entry->on_invoke_trampoline;
}
if (entry->type == HOOK_TYPE_FUNCTION_via_PRE_POST || entry->type == HOOK_TYPE_FUNCTION_via_GOT) {
// TODO
// callStack->ret_addr_PTR = *(zz_ptr_t *)ret_addr_PTR;
*(zz_ptr_t *)ret_addr_PTR = entry->on_leave_trampoline;
}
}
void interceptor_routing_end(RegState *rs, hook_entry_t *entry, void *next_hop_addr_PTR) {
// DEBUG_LOG("%p call end-invocation", entry->target_ptr);
// call post_call
if (entry->post_call) {
POSTCALL post_call;
HookEntryInfo entryInfo;
entryInfo.hook_id = entry->id;
entryInfo.target_address = entry->target_address;
post_call = entry->post_call;
(*post_call)(rs, (ThreadStackPublic *)NULL, (CallStackPublic *)NULL, (const HookEntryInfo *)&entryInfo);
}
// TODO
// set next hop
// *(zz_ptr_t *)next_hop_addr_PTR = callStack->ret_addr_PTR;
}
void interceptor_routing_dynamic_binary_instrumentation(RegState *rs, hook_entry_t *entry, void *next_hop_addr_PTR) {
// DEBUG_LOG("target %p call dynamic-binary-instrumentation-invocation", entry->target_ptr);
if (entry->stub_call) {
STUBCALL stub_call;
HookEntryInfo entryInfo;
entryInfo.hook_id = entry->id;
entryInfo.target_address = entry->target_address;
stub_call = entry->stub_call;
(*stub_call)(rs, (const HookEntryInfo *)&entryInfo);
}
*(zz_ptr_t *)next_hop_addr_PTR = entry->on_invoke_trampoline;
}
void interceptor_routing_begin_bridge_handler(RegState *rs, ClosureBridgeInfo *cbInfo) {
hook_entry_t *entry = cbInfo->user_data;
void *next_hop_addr_PTR = get_next_hop_addr_PTR(rs);
void *ret_addr_PTR = get_ret_addr_PTR(rs);
interceptor_routing_begin(rs, entry, next_hop_addr_PTR, ret_addr_PTR);
return;
}
void interceptor_routing_end_bridge_handler(RegState *rs, ClosureBridgeInfo *cbInfo) {
hook_entry_t *entry = cbInfo->user_data;
void *next_hop_addr_PTR = get_next_hop_addr_PTR(rs);
interceptor_routing_end(rs, entry, next_hop_addr_PTR);
return;
}
void interceptor_routing_dynamic_binary_instrumentation_bridge_handler(RegState *rs, ClosureBridgeInfo *cbInfo) {
hook_entry_t *entry = cbInfo->user_data;
void *next_hop_addr_PTR = get_next_hop_addr_PTR(rs);
interceptor_routing_dynamic_binary_instrumentation(rs, entry, next_hop_addr_PTR);
return;
}
void interceptor_routing_common_bridge_handler(RegState *rs, ClosureBridgeInfo *cbInfo) {
USER_CODE_CALL userCodeCall = cbInfo->user_code;
userCodeCall(rs, cbInfo);
return;
}
void interceptor_routing_begin_dynamic_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcbInfo) {
hook_entry_t *entry = dcbInfo->user_data;
void *next_hop_addr_PTR = get_next_hop_addr_PTR(rs);
void *ret_addr_PTR = get_ret_addr_PTR(rs);
interceptor_routing_begin(rs, entry, next_hop_addr_PTR, ret_addr_PTR);
return;
}
void interceptor_routing_end_dynamic_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcbInfo) {
hook_entry_t *entry = dcbInfo->user_data;
void *next_hop_addr_PTR = get_next_hop_addr_PTR(rs);
interceptor_routing_end(rs, entry, next_hop_addr_PTR);
return;
}
void interceptor_routing_dynamic_common_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcbInfo) {
DYNAMIC_USER_CODE_CALL userCodeCall = dcbInfo->user_code;
userCodeCall(rs, dcbInfo);
return;
}<file_sep>/HookZz/srcxx/Platforms/backend-posix/PosixClosureBridge.h
//
// Created by jmpews on 2018/6/14.
//
#ifndef HOOKZZ_POSIXCLOSUREBRIDGE_H
#define HOOKZZ_POSIXCLOSUREBRIDGE_H
#include "ClosureBridge.h"
#include "PosixClosureBridge.h"
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#endif //HOOKZZ_POSIXCLOSUREBRIDGE_H
<file_sep>/HookZz/srcxx/Platforms/arch-arm64/ARM64Reader.cpp
//
// Created by jmpews on 2018/6/14.
//
#include "ARM64Reader.h"
#include <assert.h>
#include <string.h>
inline void ReadBytes(void *data, void *address, int length) { memcpy(data, address, length); }
ARM64AssemblyReader::ARM64AssemblyReader(void *address, void *pc) : start_address(address), start_pc(pc) {
instBytes.reserve(1024);
}
void ARM64AssemblyReader::reset(void *address, void *pc) {
instBytes.clear();
start_address = address;
start_pc = pc;
}
ARM64InstructionCTX *ARM64AssemblyReader::readInstruction() {
ARM64InstructionCTX *instCTX = new (ARM64InstructionCTX);
assert(&instBytes[0] == instBytes.data());
instCTX->pc = (zz_addr_t)this->start_pc + this->instBytes.size();
instCTX->address = (zz_addr_t)this->instBytes.data() + this->instBytes.size();
instCTX->size = 4;
ReadBytes(&instCTX->bytes, (void *)instCTX->address, 4);
ReadBytes(&instBytes[instBytes.size()], (void *)instCTX->address, 4);
instBytes.resize(instBytes.size() + 4);
instCTXs.push_back(instCTX);
return instCTX;
}<file_sep>/HookZz/src/platforms/arch-arm64/instruction.h
#ifndef platforms_arch_arm64_instruction_h
#define platforms_arch_arm64_instruction_h
#include "hookzz.h"
typedef struct _ARM64InstructionCTX {
zz_addr_t pc;
zz_addr_t address;
uint8_t size;
uint32_t bytes;
} ARM64InstructionCTX;
// get hex insn sub
uint32_t get_insn_sub(uint32_t insn, int start, int length);
#endif
<file_sep>/HookZz/src/memory_manager.h
#ifndef memory_allocator_h
#define memory_allocator_h
#include "core.h"
#include "hookzz.h"
#include "std_kit/std_list.h"
#include <stdint.h>
// memory permission prot
#define PROT_RW_ (1 | 2)
#define PROT_R_X (1 | 4)
typedef struct _CodeSlice {
void *data;
int size;
} CodeSlice;
typedef struct _CodeCave {
int size;
void *backup;
void *address;
} CodeCave;
typedef struct _MemoryBlock {
int prot; // memory permission
int size;
void *address;
} MemoryBlock;
typedef struct _FreeMemoryBlock {
int prot; // memory permission
int total_size;
int used_size;
void *address;
} FreeMemoryBlock;
typedef struct _memory_manager_t {
bool is_support_rx_memory;
list_t *code_caves;
list_t *process_memory_layout;
list_t *free_memory_blocks;
} memory_manager_t;
#define memory_manager_cclass(member) cclass(memory_manager, member)
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
memory_manager_t *memory_manager_cclass(shared_instance)();
PLATFORM_API int memory_manager_cclass(get_page_size)();
PLATFORM_API void memory_manager_cclass(set_page_permission)(void *page_address, int prot, int n);
PLATFORM_API bool memory_manager_cclass(is_support_allocate_rx_memory)(memory_manager_t *self);
PLATFORM_API void *memory_manager_cclass(allocate_page)(memory_manager_t *self, int prot, int n);
PLATFORM_API void memory_manager_cclass(patch_code)(memory_manager_t *self, void *dest, void *src, int count);
PLATFORM_API void memory_manager_cclass(get_process_memory_layout)(memory_manager_t *self);
CodeCave *memory_manager_cclass(search_code_cave)(memory_manager_t *self, void *address, int range, int size);
CodeSlice *memory_manager_cclass(allocate_code_slice)(memory_manager_t *self, int size);
#ifdef __cplusplus
}
#endif //__cplusplus
#endif<file_sep>/HookZz/srcxx/Platforms/backend-darwin/DarwinMemoryManager.h
//
// Created by jmpews on 2018/6/14.
//
#ifndef HOOKZZ_DARWINMEMORYMANAGER_H
#define HOOKZZ_DARWINMEMORYMANAGER_H
#include "MemoryManager.h"
#endif //HOOKZZ_DARWINMEMORYMANAGER_H
<file_sep>/HookZz/srcxx/Platforms/arch-arm64/ARM64Writer.cpp
//
// Created by jmpews on 2018/6/14.
//
#include "ARM64Writer.h"
#include "MemoryManager.h"
#include <assert.h>
#include <string.h>
#include "ARM64Relocator.h"
inline void ReadBytes(void *data, void *address, int length) { memcpy(data, address, length); }
ARM64AssemblerWriter::ARM64AssemblerWriter(void *pc) : start_pc(pc) { instBytes.reserve(1024); }
void ARM64AssemblerWriter::reset(void *pc) {
instBytes.clear();
start_pc = pc;
}
void ARM64AssemblerWriter::PatchTo(void *target_address) {
start_address = target_address;
MemoryManager::CodePatch(target_address, instBytes.data(), instBytes.size());
}
// void ARM64AssemblerWriter::NearPatchTo(void *target_address, int range) {
// start_address = target_address;
// CodeCave *cc;
// MemoryManager *mm = MemoryManager::GetInstance();
// cc = mm->searchNearCodeCave(target_address, range, instBytes.size());
// MemoryManager::CodePatch((void *)cc->address, instBytes.data(), instBytes.size());
// delete (cc);
// }
// void ARM64AssemblerWriter::RelocatePatchTo(ARM64Relocator *relocatorARM64, void *target_address) {
// start_address = target_address;
// CodeSlice *cs;
// MemoryManager *mm = MemoryManager::GetInstance();
// cs = mm->allocateCodeSlice(instBytes.size());
// relocatorARM64->doubleWrite(cs->data);
// MemoryManager::CodePatch(cs->data, instBytes.data(), instBytes.size());
// delete (cs);
// }
void ARM64AssemblerWriter::putBytes(void *data, int dataSize) {
ARM64InstructionCTX *instCTX = new (ARM64InstructionCTX);
assert(&instBytes[0] == instBytes.data());
instCTX->pc = (zz_addr_t)this->start_pc + this->instBytes.size();
instCTX->address = (zz_addr_t)this->instBytes.data() + this->instBytes.size();
instCTX->size = 4;
ReadBytes(&instCTX->bytes, (void *)instCTX->address, 4);
ReadBytes(&instBytes[instBytes.size()], (void *)instCTX->address, 4);
instBytes.resize(instBytes.size() + 4);
instCTXs.push_back(instCTX);
}
<file_sep>/HookZz/src/std_kit/std_macros.h
#ifndef thread_local
#if __STDC_VERSION__ >= 201112 && !defined __STDC_NO_THREADS__
#define thread_local _Thread_local
#elif defined _WIN32 && (defined _MSC_VER || defined __ICL || defined __DMC__ || defined __BORLANDC__)
#define thread_local __declspec(thread)
/* note that ICC (linux) and Clang are covered by __GNUC__ */
#elif defined __GNUC__ || defined __SUNPRO_C || defined __xlC__
#define thread_local __thread
#else
#undef thread_local
// #error "Cannot define thread_local"
#endif
#endif<file_sep>/HookZz/src/platforms/arch-arm64/relocator-arm64.c
#include "relocator-arm64.h"
#include "ARM64AssemblyCore.h"
#include "std_kit/std_kit.h"
#include <assert.h>
#include <stdlib.h>
#include <string.h>
ARM64Relocator *arm64_assembly_relocator_cclass(new)(ARM64AssemblyReader *input, ARM64AssemblyWriter *output) {
ARM64Relocator *relocator = SAFE_MALLOC_TYPE(ARM64Relocator);
relocator->input = input;
relocator->output = output;
relocator->io_indexs = list_new();
relocator->literal_instCTXs = list_new();
return relocator;
}
void arm64_assembly_relocator_cclass(reset)(ARM64Relocator *self, ARM64AssemblyReader *input, ARM64AssemblyWriter *output) {
arm64_assembly_reader_reset(self->input, 0, 0);
arm64_assembly_writer_reset(self->output, 0);
list_destroy(self->literal_instCTXs);
self->literal_instCTXs = list_new();
list_destroy(self->io_indexs);
self->io_indexs = list_new();
}
void arm64_assembly_relocator_cclass(try_relocate)(void *address, int bytes_min, int *bytes_max) {
int tmp_size = 0;
bool early_end = false;
ARM64InstructionCTX *instCTX = NULL;
ARM64AssemblyReader *reader = arm64_assembly_reader_cclass(new)(address, address);
do {
instCTX = arm64_assembly_reader_cclass(read_inst)(reader);
switch (getInstType(instCTX->bytes)) {
case BImm:
early_end = true;
break;
default:;
}
tmp_size += instCTX->size;
} while (tmp_size < bytes_min);
if (early_end) {
*bytes_max = bytes_min;
}
// TODO: free ARM64AssemblyReader
SAFE_FREE(reader);
}
void arm64_assembly_relocator_cclass(relocate_to)(ARM64Relocator *self, void *target_address) {
list_iterator_t *it = list_iterator_new(self->literal_instCTXs, LIST_HEAD);
for (int i; i < self->literal_instCTXs->len; i++) {
ARM64InstructionCTX *instCTX = (ARM64InstructionCTX *)(list_at(self->literal_instCTXs, i)->val);
zz_addr_t literal_target_address;
literal_target_address = *(zz_addr_t *)instCTX->address;
if (literal_target_address > (zz_addr_t)self->input->start_pc &&
literal_target_address < ((zz_addr_t)self->input->start_pc + self->input->inst_bytes->size)) {
list_iterator_t *it_a = list_iterator_new(self->io_indexs, LIST_HEAD);
for (int j; j < self->io_indexs->len; j++) {
io_index_t *io_index = (io_index_t *)(list_at(self->io_indexs, j)->val);
int i_index = io_index->input_index;
int o_index = io_index->output_index;
ARM64InstructionCTX *inputInstCTX =
(ARM64InstructionCTX *)(list_at(self->input->instCTXs, i_index)->val);
ARM64InstructionCTX *outputInstCTX =
(ARM64InstructionCTX *)(list_at(self->output->instCTXs, o_index)->val);
if (inputInstCTX->address == literal_target_address) {
*(zz_addr_t *)instCTX->address =
((ARM64InstructionCTX *)(list_at(self->output->instCTXs, o_index)->val))->pc -
(zz_addr_t)self->output->start_pc + (zz_addr_t)target_address;
break;
}
}
}
}
}
void arm64_assembly_relocator_cclass(double_write)(ARM64Relocator *self, void *target_address) {
assert((zz_addr_t)target_address % 4 == 0);
int origin_inst_buffer_size = self->output->inst_bytes->size;
// temporary store inst buffer
void *tmp_inst_buffer = (void *)malloc(self->output->inst_bytes->size);
memcpy(tmp_inst_buffer, self->output->inst_bytes->data, self->output->inst_bytes->size);
arm64_assembly_writer_cclass(reset)(self->output, target_address);
arm64_assembly_relocator_cclass(reset)(self, self->input, self->output);
arm64_assembly_relocator_cclass(relocate_write_all)(self);
void *no_need_relocate_inst_buffer =
(void *)((zz_addr_t)tmp_inst_buffer + self->output->inst_bytes->size);
arm64_assembly_writer_cclass(put_bytes)(self->output, no_need_relocate_inst_buffer,
origin_inst_buffer_size - self->output->inst_bytes->size);
}
void arm64_assembly_relocator_cclass(register_literal_instCTX)(ARM64Relocator *self, ARM64InstructionCTX *instCTX) {
list_rpush(self->literal_instCTXs, list_node_new(instCTX));
}
void arm64_assembly_relocator_cclass(relocate_write_all)(ARM64Relocator *self) {
do {
arm64_assembly_relocator_cclass(relocate_write)(self);
} while (self->io_indexs->len < self->input->instCTXs->len);
}
void arm64_assembly_relocator_cclass(relocate_write)(ARM64Relocator *self) {
ARM64InstructionCTX *instCTX = NULL;
bool rewritten = true;
int done_relocated_input_count;
done_relocated_input_count = self->io_indexs->len;
if (self->input->instCTXs->len > self->io_indexs->len) {
instCTX = (ARM64InstructionCTX *)(list_at(self->input->instCTXs, done_relocated_input_count)->val);
} else
return;
// push relocate input <-> output index
io_index_t *io_index = SAFE_MALLOC_TYPE(io_index_t);
io_index->input_index = done_relocated_input_count;
io_index->output_index = self->output->instCTXs->len;
list_rpush(self->io_indexs, list_node_new(io_index));
switch (getInstType(instCTX->bytes)) {
case LoadLiteral:
arm64_assembly_relocator_cclass(rewrite_LoadLiteral)(self, instCTX);
break;
case BaseCmpBranch:
arm64_assembly_relocator_cclass(rewrite_BaseCmpBranch)(self, instCTX);
break;
case BranchCond:
arm64_assembly_relocator_cclass(rewrite_BranchCond)(self, instCTX);
break;
case B:
arm64_assembly_relocator_cclass(rewrite_B)(self, instCTX);
break;
case BL:
arm64_assembly_relocator_cclass(rewrite_BL)(self, instCTX);
break;
default:
rewritten = false;
break;
}
if (!rewritten) {
arm64_assembly_writer_cclass(put_bytes)(self->output, (void *)&instCTX->bytes, instCTX->size);
}
}
void arm64_assembly_relocator_cclass(rewrite_LoadLiteral)(ARM64Relocator *self, ARM64InstructionCTX *instCTX) {
uint32_t Rt, label;
int index;
zz_addr_t target_address;
Rt = get_insn_sub(instCTX->bytes, 0, 5);
label = get_insn_sub(instCTX->bytes, 5, 19);
target_address = (label << 2) + instCTX->pc;
ARM64Reg regRt = arm64_register_disdescribe(Rt, 0);
arm64_assembly_writer_cclass(put_ldr_reg_imm)(self->output, regRt, 0x8);
arm64_assembly_writer_cclass(put_b_imm)(self->output, 0xc);
arm64_assembly_writer_cclass(put_bytes)(self->output, (zz_ptr_t)&target_address, sizeof(target_address));
arm64_assembly_relocator_cclass(register_literal_instCTX)(
self, (ARM64InstructionCTX *)(list_at(self->output->instCTXs, self->output->instCTXs->len - 1))->val);
arm64_assembly_writer_cclass(put_ldr_reg_reg_offset)(self->output, regRt, regRt, 0);
}
void arm64_assembly_relocator_cclass(rewrite_BaseCmpBranch)(ARM64Relocator *self, ARM64InstructionCTX *instCTX) {
uint32_t target;
uint32_t inst32;
zz_addr_t target_address;
inst32 = instCTX->bytes;
target = get_insn_sub(inst32, 5, 19);
target_address = (target << 2) + instCTX->pc;
target = 0x8 >> 2;
BIT32SET(&inst32, 5, 19, target);
arm64_assembly_writer_cclass(put_bytes)(self->output, &inst32, instCTX->size);
arm64_assembly_writer_cclass(put_b_imm)(self->output, 0x14);
arm64_assembly_writer_cclass(put_ldr_reg_imm)(self->output, ARM64_REG_X17, 0x8);
arm64_assembly_writer_cclass(put_br_reg)(self->output, ARM64_REG_X17);
arm64_assembly_writer_cclass(put_bytes)(self->output, (zz_ptr_t)&target_address, sizeof(zz_ptr_t));
arm64_assembly_relocator_cclass(register_literal_instCTX)(
self, (ARM64InstructionCTX *)(list_at(self->output->instCTXs, self->output->instCTXs->len - 1))->val);
}
void arm64_assembly_relocator_cclass(rewrite_BranchCond)(ARM64Relocator *self, ARM64InstructionCTX *instCTX) {
uint32_t target;
uint32_t inst32;
zz_addr_t target_address;
inst32 = instCTX->bytes;
target = get_insn_sub(inst32, 5, 19);
target_address = (target << 2) + instCTX->pc;
target = 0x8 >> 2;
BIT32SET(&inst32, 5, 19, target);
arm64_assembly_writer_cclass(put_bytes)(self->output, &inst32, instCTX->size);
arm64_assembly_writer_cclass(put_b_imm)(self->output, 0x14);
arm64_assembly_writer_cclass(put_ldr_reg_imm)(self->output, ARM64_REG_X17, 0x8);
arm64_assembly_writer_cclass(put_br_reg)(self->output, ARM64_REG_X17);
arm64_assembly_writer_cclass(put_bytes)(self->output, (zz_ptr_t)&target_address, sizeof(zz_ptr_t));
arm64_assembly_relocator_cclass(register_literal_instCTX)(
self, (ARM64InstructionCTX *)(list_at(self->output->instCTXs, self->output->instCTXs->len - 1))->val);
}
void arm64_assembly_relocator_cclass(rewrite_B)(ARM64Relocator *self, ARM64InstructionCTX *instCTX) {
uint32_t addr;
zz_addr_t target_address;
addr = get_insn_sub(instCTX->bytes, 0, 26);
target_address = (addr << 2) + instCTX->pc;
arm64_assembly_writer_cclass(put_ldr_reg_imm)(self->output, ARM64_REG_X17, 0x8);
arm64_assembly_writer_cclass(put_br_reg)(self->output, ARM64_REG_X17);
arm64_assembly_writer_cclass(put_bytes)(self->output, (zz_ptr_t)&target_address, sizeof(zz_ptr_t));
arm64_assembly_relocator_cclass(register_literal_instCTX)(
self, (ARM64InstructionCTX *)(list_at(self->output->instCTXs, self->output->instCTXs->len - 1))->val);
}
void arm64_assembly_relocator_cclass(rewrite_BL)(ARM64Relocator *self, ARM64InstructionCTX *instCTX) {
uint32_t op, addr;
zz_addr_t target_address, next_pc_address;
addr = get_insn_sub(instCTX->bytes, 0, 26);
target_address = (addr << 2) + instCTX->pc;
next_pc_address = instCTX->pc + 4;
arm64_assembly_writer_cclass(put_ldr_reg_imm)(self->output, ARM64_REG_X17, 0xc);
arm64_assembly_writer_cclass(put_blr_reg)(self->output, ARM64_REG_X17);
arm64_assembly_writer_cclass(put_b_imm)(self->output, 0xc);
arm64_assembly_writer_cclass(put_bytes)(self->output, (zz_ptr_t)&target_address, sizeof(zz_ptr_t));
arm64_assembly_relocator_cclass(register_literal_instCTX)(
self, (ARM64InstructionCTX *)(list_at(self->output->instCTXs, self->output->instCTXs->len - 1))->val);
}
<file_sep>/HookZz/srcxx/ThreadManager.h
//
// Created by jmpews on 2018/6/14.
//
#ifndef HOOKZZ_THREADMANAGER_H
#define HOOKZZ_THREADMANAGER_H
#include "CommonClass/DesignPattern/Singleton.h"
#include <iostream>
#include <vector>
typedef struct _ThreadLocalKey {
pthread_key_t key;
} ThreadLocalKey;
class ThreadManager : public Singleton<ThreadManager> {
public:
std::vector<ThreadLocalKey *> thread_local_keys;
public:
ThreadLocalKey *allocateThreadLocalKey();
void setThreadLocalData(ThreadLocalKey *thread_local_key, void *);
void *getThreadLocalData(ThreadLocalKey *thread_local_key);
};
#endif //HOOKZZ_THREADMANAGER_H
<file_sep>/HookZz/src/platforms/backend-posix/memory-helper-posix.c
#include "memory-helper-posix.h"
#include "core.h"
#include "hookzz.h"
#include "memory_manager.h"
#include <sys/mman.h>
extern void __clear_cache(void *beg, void *end);
void posix_memory_helper_cclass(set_page_permission)(void *page_address, int prot, int n) {
int page_size = posix_memory_helper_cclass(get_page_size)();
int r;
r = mprotect((zz_ptr_t)page_address, page_size * n, prot);
if (r == -1) {
ERROR_LOG("r = %d, at (%p) error!", r, (zz_ptr_t)page_address);
return;
}
return;
}
int posix_memory_helper_cclass(get_page_size)() {
int page_size = sysconf(_SC_PAGESIZE);
return page_size;
}
void *posix_memory_helper_cclass(allocate_page)(int prot, int n) {
int page_size = posix_memory_helper_cclass(get_page_size)();
void *mmap_page = mmap(0, 1, PROT_WRITE | PROT_READ, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
mprotect(mmap_page, (size_t)page_size, prot);
return mmap_page;
}
/*
ref:
substitute/lib/darwin/execmem.c:execmem_foreign_write_with_pc_patch
frida-gum-master/gum/gummemory.c:gum_memory_patch_code
frida-gum-master/gum/backend-darwin/gummemory-darwin.c:gum_alloc_n_pages
mach mmap use __vm_allocate and __vm_map
https://github.com/bminor/glibc/blob/master/sysdeps/mach/hurd/mmap.c
https://github.com/bminor/glibc/blob/master/sysdeps/mach/munmap.c
http://shakthimaan.com/downloads/hurd/A.Programmers.Guide.to.the.Mach.System.Calls.pdf
*/
void posix_memory_helper_cclass(patch_code)(void *dest, void *src, int count) {
void *dest_page = NULL;
int offset = 0;
int page_size = posix_memory_helper_cclass(get_page_size)();
// https://www.gnu.org/software/hurd/gnumach-doc/Memory-Attributes.html
dest_page = (void *)((zz_addr_t)dest & ~(page_size - 1));
offset = (zz_addr_t)dest - (zz_addr_t)dest_page;
// another method, pelease read `REF`;
// zz_ptr_t code_mmap = mmap(NULL, range_size, PROT_READ | PROT_WRITE,
// MAP_ANON | MAP_SHARED, -1, 0);
// if (code_mmap == MAP_FAILED) {
// return;
// }
void *copy_page = posix_memory_helper_cclass(allocate_page)(PROT_RW_, 1);
memcpy(copy_page, (void *)dest_page, page_size);
memcpy((void *)((zz_addr_t)copy_page + offset), src, count);
/* SAME: mprotect(code_mmap, range_size, prot); */
posix_memory_helper_cclass(set_page_permission)(dest_page, PROT_WRITE | PROT_READ | PROT_EXEC, 1);
memcpy(dest_page, copy_page, page_size);
posix_memory_helper_cclass(set_page_permission)(dest_page, PROT_EXEC | PROT_READ, 1);
#if 0
// why not working ???
// posix_memory_helper_cclass(set_page_permission)(copy_page, PROT_EXEC | PROT_READ, 1);
// void *remap_page = mremap(copy_page, page_size, page_size, MREMAP_MAYMOVE|MREMAP_FIXED, dest_page);
// if(remap_page == MAP_FAILED) {
// ERROR_LOG("r = %d, at (%p) error!", 0, (zz_ptr_t)remap_page);
// return;
// }
#endif
__clear_cache((void *)dest, (void *)((uintptr_t)dest + count));
// TODO
munmap(copy_page, page_size);
return;
}
<file_sep>/HookZz/srcxx/hookzz.cpp
//
// Created by jmpews on 2018/6/14.
//
#include "hookzz.h"
#include "Interceptor.h"
#include "InterceptorBackend.h"
#include "Trampoline.h"
RetStatus ZzHook(void *target_address, void *replace_call, void **origin_call, PRECALL pre_call, POSTCALL post_call) {
HookType type;
if (pre_call || post_call) {
type = HOOK_TYPE_FUNCTION_via_PRE_POST;
} else {
type = HOOK_TYPE_FUNCTION_via_REPLACE;
}
HookEntry *entry = new (HookEntry);
entry->target_address = target_address;
entry->replace_call = replace_call;
entry->pre_call = pre_call;
entry->post_call = post_call;
Interceptor *interceptor = Interceptor::GETInstance();
interceptor->addHookEntry(entry);
interceptor->backend->BuildAllTrampoline(entry);
interceptor->backend->ActiveTrampoline(entry);
return RS_SUCCESS;
}<file_sep>/HookZz/srcxx/MemoryManager.h
//
// Created by z on 2018/6/14.
//
#ifndef HOOKZZ_MEMORYMANAGER_H
#define HOOKZZ_MEMORYMANAGER_H
#include <iostream>
#include <stdint.h>
#include <vector>
#include "CommonClass/DesignPattern/Singleton.h"
#include "hookzz.h"
typedef enum _MemoryAttribute { MEM_RX } MemoryAttribute;
typedef struct _CodeSlice {
void *data;
int size;
} CodeSlice;
typedef struct _CodeCave {
int size;
void *backup;
zz_addr_t address;
} CodeCave;
typedef struct _MemoryBlock {
int prot; // memory permission
int size;
zz_addr_t address;
} MemoryBlock;
typedef struct _FreeMemoryBlock {
int prot; // memory permission
int total_size;
int used_size;
zz_addr_t address;
} FreeMemoryBlock;
class MemoryManager {
public:
bool is_support_rx_memory;
std::vector<CodeCave *> code_caves;
std::vector<MemoryBlock *> process_memory_layout;
std::vector<FreeMemoryBlock *> free_memory_blocks;
public:
static bool IsSupportRXMemory();
static int GetPageSize();
void patchCode(void *dest, void *src, int count);
void *allocateMemoryPage(MemoryAttribute prot, int n);
void getProcessMemoryLayout();
CodeSlice *allocateCodeSlice(int size);
CodeCave *searchCodeCave(void *address, int range, int need_size);
};
#endif //HOOKZZ_MEMORYMANAGER_H
<file_sep>/HookZz/src/interceptor.h
#ifndef interceptor_h
#define interceptor_h
#include "core.h"
#include "hookzz.h"
#include "memory_manager.h"
typedef struct _FunctionBackup {
void *address;
int size;
char data[32];
} FunctionBackup;
struct _interceptor_t;
struct _hook_entry_backend_t;
typedef struct _hook_entry_t {
void *target_address;
HookType type;
uintptr_t id;
bool is_enable;
bool is_try_near_jump;
bool is_near_jump;
PRECALL pre_call;
POSTCALL post_call;
DBICALL dbi_call;
void *replace_call;
void *on_enter_transfer_trampoline;
void *on_enter_trampoline;
void *on_invoke_trampoline;
void *on_leave_trampoline;
void *on_dynamic_binary_instrumentation_trampoline;
FunctionBackup origin_prologue;
struct _hook_entry_backend_t *backend;
struct _interceptor_t *interceptor;
} hook_entry_t;
struct _interceptor_backend_t;
typedef struct _interceptor_t {
bool is_support_rx_memory;
list_t *hook_entries;
struct _interceptor_backend_t *interceptor_backend;
memory_manager_t *memory_manager;
} interceptor_t;
#define interceptor_cclass(member) cclass(interceptor, member)
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
interceptor_t *interceptor_cclass(shared_instance)(void);
hook_entry_t *interceptor_cclass(find_hook_entry)(interceptor_t *self, void *target_address);
void interceptor_cclass(add_hook_entry)(interceptor_t *self, hook_entry_t *entry);
void interceptor_cclass(initialize_interceptor_backend)();
#ifdef __cplusplus
}
#endif //__cplusplus
#endif
<file_sep>/HookZz/srcxx/ClosureBridge.cpp
//
// Created by jmpews on 2018/6/14.
//
#include "ClosureBridge.h"
<file_sep>/HookZz/srcxx/Trampoline.cpp
//
// Created by z on 2018/6/14.
//
#include "Trampoline.h"
<file_sep>/HookZz/src/interceptor_routing_trampoline.h
#ifndef interceptor_routing_trampoline_h
#define interceptor_routing_trampoline_h
#include "core.h"
#include "hookzz.h"
#include "interceptor.h"
#define interceptor_trampoline_cclass(member) cclass(interceptor_trampoline, member)
void interceptor_trampoline_cclass(free)(hook_entry_t *entry);
void interceptor_trampoline_cclass(build_all)(hook_entry_t *entry);
ARCH_API void interceptor_trampoline_cclass(prepare)(hook_entry_t *entry);
ARCH_API void interceptor_trampoline_cclass(active)(hook_entry_t *entry);
ARCH_API void interceptor_trampoline_cclass(build_for_enter)(hook_entry_t *entry);
ARCH_API void interceptor_trampoline_cclass(build_for_enter_transfer)(hook_entry_t *entry);
ARCH_API void interceptor_trampoline_cclass(build_for_invoke)(hook_entry_t *entry);
ARCH_API void interceptor_trampoline_cclass(build_for_leave)(hook_entry_t *entry);
ARCH_API void interceptor_trampoline_cclass(build_for_dynamic_binary_instrumentation)(hook_entry_t *entry);
#endif<file_sep>/app2dylib/makefile
.PHONY:app2dylib
TMP_FILE := libMachObjC.a app2dylib.dSYM/ build/
restore-symbol:
rm -f app2dylib
xcodebuild -project "app2dylib.xcodeproj" -target "app2dylib" -configuration "Release" CONFIGURATION_BUILD_DIR="$(shell pwd)" -jobs 4 build
rm -rf $(TMP_FILE)
clean:
rm -rf app2dylib $(TMP_FILE)
<file_sep>/HookZz/src/thread_support/thread_local_storage.c
#include "thread_local_storage.h"
#ifdef thread_local
thread_local void *_thread_variable;
void *get_thread_variable_value() { return _thread_variable; }
void set_thread_variable_value(void *value) { _thread_variable = value; }
#endif
<file_sep>/HookZz/srcxx/InterceptorRoutingTrampoline.h
//
// Created by jmpews on 2018/6/15.
//
#ifndef HOOKZZ_INTERCEPTORBACKEND_H
#define HOOKZZ_INTERCEPTORBACKEND_H
#include "Interceptor.h"
class InterceptorRoutingTrampoline {
public:
virtual void Prepare(HookEntry *entry){};
virtual void BuildForEnterTransfer(HookEntry *entry){};
virtual void BuildForEnter(HookEntry *entry){};
virtual void BuildForDynamicBinaryInstrumentation(HookEntry *entry){};
virtual void BuildForLeave(HookEntry *entry){};
virtual void BuildForInvoke(HookEntry *entry){};
virtual void Active(HookEntry *entry){};
void BuildAll(HookEntry *entry);
};
#endif //HOOKZZ_INTERCEPTORBACKEND_H
<file_sep>/HookZz/src/platforms/arch-arm64/relocator-arm64.h
#ifndef platforms_arch_arm64_relocator_h
#define platforms_arch_arm64_relocator_h
#include "instruction.h"
#include "reader-arm64.h"
#include "register-arm64.h"
#include "writer-arm64.h"
#include "std_kit/std_buffer_array.h"
#include "std_kit/std_kit.h"
#include "std_kit/std_list.h"
typedef struct _io_index_t {
int input_index;
int output_index;
} io_index_t;
typedef struct _ARM64Relocator {
ARM64AssemblyReader *input;
ARM64AssemblyWriter *output;
list_t *literal_instCTXs;
list_t *io_indexs;
} ARM64Relocator;
#define arm64_assembly_relocator_cclass(member) cclass(arm64_relocator, member)
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
ARM64Relocator *arm64_assembly_relocator_cclass(new)(ARM64AssemblyReader *input, ARM64AssemblyWriter *output);
void arm64_assembly_relocator_cclass(reset)(ARM64Relocator *self, ARM64AssemblyReader *input, ARM64AssemblyWriter *output);
void arm64_assembly_relocator_cclass(try_relocate)(void *address, int bytes_min, int *bytes_max);
void arm64_assembly_relocator_cclass(relocate_to)(ARM64Relocator *self, void *target_address);
void arm64_assembly_relocator_cclass(double_write)(ARM64Relocator *self, void *target_address);
void arm64_assembly_relocator_cclass(register_literal_instCTX)(ARM64Relocator *self, ARM64InstructionCTX *instCTX);
void arm64_assembly_relocator_cclass(relocate_write)(ARM64Relocator *self);
void arm64_assembly_relocator_cclass(relocate_write_all)(ARM64Relocator *self);
void arm64_assembly_relocator_cclass(rewrite_LoadLiteral)(ARM64Relocator *self, ARM64InstructionCTX *instCTX);
void arm64_assembly_relocator_cclass(rewrite_BaseCmpBranch)(ARM64Relocator *self, ARM64InstructionCTX *instCTX);
void arm64_assembly_relocator_cclass(rewrite_BranchCond)(ARM64Relocator *self, ARM64InstructionCTX *instCTX);
void arm64_assembly_relocator_cclass(rewrite_B)(ARM64Relocator *self, ARM64InstructionCTX *instCTX);
void arm64_assembly_relocator_cclass(rewrite_BL)(ARM64Relocator *self, ARM64InstructionCTX *instCTX);
#ifdef __cplusplus
}
#endif //__cplusplus
#endif
<file_sep>/HookZz/src/platforms/backend-linux/memory-manager-linux.c
#include "core.h"
#include "memory-helper-posix.h"
#include "memory_manager.h"
PLATFORM_API bool memory_manager_cclass(is_support_allocate_rx_memory)(memory_manager_t *self) { return true; }
PLATFORM_API void memory_manager_cclass(get_process_memory_layout)(memory_manager_t *self) {
char filename[64];
char buf[256];
FILE *fp;
// self process
int pid = -1;
// given pid, open /proc/pid/maps; or not, open current maps.
if (pid > 0) {
sprintf(filename, "/proc/%d/maps", pid);
} else {
sprintf(filename, "/proc/self/maps");
}
fp = fopen(filename, "r");
if (fp < 0) {
return;
}
while (fgets(buf, sizeof(buf), fp) != NULL) {
zz_addr_t start_addr, end_addr;
unsigned dev, sdev;
unsigned long inode;
unsigned long long offset;
char prot[5];
char path[64];
int len;
/* format in /proc/pid/maps is constructed as below in fs/proc/task_mmu.c
167 seq_printf(m,
168 "%08lx-%08lx %c%c%c%c %08llx %02x:%02x %lu ",
169 vma->vm_start,
170 vma->vm_end,
171 flags & VM_READ ? 'r' : '-',
172 flags & VM_WRITE ? 'w' : '-',
173 flags & VM_EXEC ? 'x' : '-',
174 flags & VM_MAYSHARE ? flags & VM_SHARED ? 'S' : 's' : 'p',
175 pgoff,
176 MAJOR(dev), MINOR(dev), ino);
177
178 if (file) {
179 seq_pad(m, ' ');
180 seq_file_path(m, file, "");
181 } else if (mm && is_stack(priv, vma)) {
182 seq_pad(m, ' ');
183 seq_printf(m, "[stack]");
184 }
*/
if (sscanf(buf, "%lx-%lx %s %llx %x:%x %lu %s", &start_addr, &end_addr, prot, &offset, &dev, &sdev, &inode,
path) != 8)
continue;
MemoryBlock *mb = SAFE_MALLOC_TYPE(MemoryBlock);
list_rpush(self->process_memory_layout, list_node_new(mb));
mb->address = (void *)start_addr;
mb->size = end_addr - start_addr;
mb->prot = (prot[0] == 'r' ? (1 << 0) : 0) | (prot[1] == 'w' ? (1 << 1) : 0) | (prot[2] == 'x' ? (1 << 2) : 0);
}
}
<file_sep>/HookZz/srcxx/Platforms/arch-arm64/ARM64Helper.cpp
#include "ARM64Helper.h"
#include "hookzz.h"
void *get_next_hop_addr_PTR(RegState *rs) {}
void *get_ret_addr_PTR(RegState *rs) {}<file_sep>/HookZz/src/thread_support/thread_stack.c
#include "thread_stack.h"
#include "core.h"
#include "thread_local_storage.h"
thread_stack_manager_t *thread_stack_cclass(shared_instance)() {
thread_stack_manager_t *g_thread_stack_manager = (thread_stack_manager_t *)get_thread_variable_value();
if (g_thread_stack_manager == NULL) {
g_thread_stack_manager = SAFE_MALLOC_TYPE(thread_stack_manager_t);
g_thread_stack_manager->thread_id = (uintptr_t)g_thread_stack_manager;
g_thread_stack_manager->call_stacks = list_new();
set_thread_variable_value((void *)g_thread_stack_manager);
}
return g_thread_stack_manager;
}
void thread_stack_cclass(push_call_stack)(thread_stack_manager_t *self, call_stack_t *call_stack) {
list_rpush(self->call_stacks, list_node_new(call_stack));
}
call_stack_t *thread_stack_cclass(pop_call_stack)(thread_stack_manager_t *self) {
call_stack_t *call_stack = (call_stack_t *)(list_rpop(self->call_stacks)->val);
return call_stack;
}
call_stack_t *call_stack_cclass(new)(thread_stack_manager_t *thread_stack_manager) {
call_stack_t *call_stack = SAFE_MALLOC_TYPE(call_stack_t);
call_stack->call_id = (uintptr_t)call_stack;
call_stack->context_kv = map_new();
call_stack->thread_stack_manager = thread_stack_manager;
return call_stack;
}
void call_stack_cclass(destory)(call_stack_t *self) {
map_destory(self->context_kv);
SAFE_FREE(self);
}
PUBLIC_API void call_stack_cclass(kv_set)(CallStackPublic *csp, char *key, void *value) {
call_stack_t *call_stack = (call_stack_t *)csp->call_id;
map_value_t mv;
mv._pointer = value;
map_set_value(call_stack->context_kv, key, mv);
}
PUBLIC_API void *call_stack_cclass(kv_get)(CallStackPublic *csp, char *key) {
call_stack_t *call_stack = (call_stack_t *)csp->call_id;
map_value_t mv;
mv = map_get_value(call_stack->context_kv, key);
return mv._pointer;
}<file_sep>/HookZz/src/thread_support/thread_stack.h
#ifndef thread_support_thread_stack_h
#define thread_support_thread_stack_h
#include "core.h"
#include "hookzz.h"
#include "std_kit/std_list.h"
#include "std_kit/std_map.h"
typedef struct _thread_stack_manager_t {
uintptr_t thread_id;
list_t *call_stacks;
} thread_stack_manager_t;
typedef struct _call_stack_t {
uintptr_t call_id;
thread_stack_manager_t *thread_stack_manager;
void *reg_sp;
void *ret_addr;
map_t *context_kv;
} call_stack_t;
#define thread_stack_cclass(member) cclass(thread_stack, member)
#define call_stack_cclass(member) cclass(call_stack, member)
thread_stack_manager_t *thread_stack_cclass(shared_instance)();
void thread_stack_cclass(push_call_stack)(thread_stack_manager_t *self, call_stack_t *call_stack);
call_stack_t *thread_stack_cclass(pop_call_stack)(thread_stack_manager_t *self);
call_stack_t *call_stack_cclass(new)(thread_stack_manager_t *thread_stack_manager);
void call_stack_cclass(destory)(call_stack_t *self);
#endif
<file_sep>/app2dylib/README.md
# app2dylib
A reverse engineering tool to convert iOS app to dylib
# Usage
```
//https://bbs.pediy.com/thread-219004.htm
git clone --recursive https://github.com/tobefuturer/app2dylib.git
cd app2dylib && make
./app2dylib
```
example :
```
./app2dylib /tmp/AlipayWallet -o /tmp/libAlipayApp.dylib
```
You can use libAlipayApp.dylib as a normal dynamic library.
Call OC method or call C function like this:
```
#import <UIKit/UIKit.h>
#import <dlfcn.h>
#import <mach/mach.h>
#import <mach-o/loader.h>
#import <mach-o/dyld.h>
int main(int argc, char * argv[]) {
NSString * dylibName = @"libAlipayApp";
NSString * path = [[NSBundle mainBundle] pathForResource:dylibName ofType:@"dylib"];
if (dlopen(path.UTF8String, RTLD_NOW) == NULL){
NSLog(@"dlopen failed ,error %s", dlerror());
return 0;
};
uint32_t dylib_count = _dyld_image_count();
uint64_t slide = 0;
for (int i = 0; i < dylib_count; i ++) {
const char * name = _dyld_get_image_name(i);
if ([[NSString stringWithUTF8String:name] isEqualToString:path]) {
slide = _dyld_get_image_vmaddr_slide(i);
}
}
assert(slide != 0);
Class c = NSClassFromString(@"aluSecurity");
NSString * plain = @"alipay";
NSString * pubkey = @"<KEY>";
NSString * cipher = [c performSelector:NSSelectorFromString(@"rsaEncryptText:pubKey:") withObject:plain withObject:pubkey];
NSLog(@"ciphertext: %@", cipher);
typedef int (*BASE64_ENCODE_FUNC_TYPE) (char * output, int * output_size , char * input, int input_length);
/** get function pointer*/
BASE64_ENCODE_FUNC_TYPE base64_encode = (BASE64_ENCODE_FUNC_TYPE)(slide + 0xa798e4);
char output[1000] = {0};
int length = 1000;
char * input = "alipay";
base64_encode(output, & length, input, (int)strlen(input));
NSLog(@"base64 length: %d , %s", length, output);
}
```
<file_sep>/HookZz/docs/HookFrameworkDesign.md
# HookZz Framework
# Hook Framework
一般来说可以分为以下几个模块
1. 内存分配 模块
2. 指令写 模块
3. 指令读 模块
4. 指令修复 模块
5. 跳板 模块
6. 调度器 模块
7. 栈 模块
## 1. 内存分配 模块
这里主要关注三个点:
1. 内存的分配
2. 内存属性修改
3. 内存布局获取
#### 1.1 内存的分配
**设计方面:** 1. 提供一个 allocator 去管理/分配内存 2. 需要封装成架构无关的 API.
通常使用 posix 标准的 `mmap`, darwin 下的 mach kernel 分配内存使用 `mmap` 实际使用的是 `mach_vm_allocate`. [move to detail]( https://github.com/bminor/glibc/blob/master/sysdeps/mach/hurd/mmap.c)
在入口点的 patch, 通常会使用绝对地址跳到 `trampoline`, 如果使用绝对地址跳, 将会占用 4 条指令, 如下的形式.
```
ldr x17, #0x8
b #0xc
.long 0x0
.long 0x0
br x17
```
但是如果可以使用 `B #0x?`, 实现相对地址跳(near jump), 将是最好的, 在 armv8 中的可以想在 `+-128MB` 范围内进行 `near jump`, 具体可以参考 `ARM Architecture Reference Manual ARMv8, for ARMv8-A architecture profile Page: C6-550`. 所以问题转换为找到一块 `rx-` 的内存写入 enter trampline.
大概有以下几种方法可以获取到 `rx-` 内存块.
1. 尝试使用 mmap 的 fixed flag 分配相近内存
2. 当时获取进程内的所有动态库列表, 之后搜索每一个动态库的 `__TEXT`, 查找是否存在 code cave.(尝试搜索内存空洞(`code cave`), 搜索 `__text` 这个 `section` 其实更准确来说是搜索 `__TEXT` 这个 `segment`. 由于内存页对齐的原因以及其他原因很容易出现 `code cave`. 所以只需要搜索这个区间内的 `00` 即可, `00` 本身就是无效指令, 所以可以判断该位置无指令使用.)
3. 获取当前进程的内存布局, 对所有 `rx-` 属性内存页搜索 code cave. (内存布局的获取会在1.3详细提到)
#### 1.2 内存属性修改
通常使用 posix 标准的 `mprotect`, darwin 下的 mach kernel 修改内存属性使用的是 `mach_vm_protect`, 注意: ios 不允许引用 `#include <mach_vm.h>`, 可以用单独拷贝一份该头文件到项目下.
这一部分与具体的操作系统有关. 比如 .
在 lldb 中可以通过 `memory region address` 查看地址的内存属性.
当然这里也存在一个巨大的坑, ios 下无法分配 `rwx` 属性的内存页. 这导致 inlinehook 无法在非越狱系统上使用, 并且只有 `MobileSafari` 才有 `VM_FLAGS_MAP_JIT` 权限. 具体解释请参下方 **[坑 - rwx 与 codesigning]**.
#### 1.3 内存布局获取
#### 2. 指令写 模块
#### 3. 指令读 模块
#### 4. 指令修复 模块
#### 5. 跳板 模块
#### 6. 调度 模块
#### 7. 栈模块
# 坑
## `ldr` 指令
在进行指令修复时, 需要需要将 PC 相关的地址转换为绝对地址, 其中涉及到保存地址到寄存器. 一般来说是使用指令 `ldr`.
`frida-gum` 的实现原理是, 有一个相对地址表, 保存所有用到的 ldr 指令的地方, 默认 ldr 取得都是 0 相对便宜(b 等相对指令也有记录), 在指令修复后有一个 flush writer 的过程, 这个过程会把, 会将用到绝对地址写到整个指令块后面, 形成一个绝对地址表, 同时修复之前 ldr 引用的相对偏移.
```
gboolean
gum_arm64_writer_put_ldr_reg_u64 (GumARM64Writer * self,
arm64_reg reg,
guint64 val)
{
GumARM64RegInfo ri;
gum_arm64_writer_describe_reg (self, reg, &ri);
if (ri.width != 64)
return FALSE;
if (!gum_arm64_writer_add_literal_reference_here (self, val))
return FALSE;
gum_arm64_writer_put_instruction (self,
(ri.is_integer ? 0x58000000 : 0x5c000000) | ri.index);
return TRUE;
}
```
在 HookZz 中的实现, 直接将地址写在指令后, 之后使用 `b` 到正常的下一条指令, 从而实现将地址保存到寄存器, 这种方式有好有坏.
也就是下面的样子.
```
__asm__ {
"ldr x17, #0x8\n"
"b #0xc\n"
".long\n"
".long\n"
"br x17"
}
```
## 寄存器污染
在构建跳板桥的过程, 通常会以以下模板进行跳转.
```
0x0000: ldr x16, 8;
0x0004: br x16;
0x0008: 0x4321
0x000c: 0x8765
```
问题在于这会造成 `x16` 寄存器被污染(ARM64 中 `svc #0x80` 使用 `x16` 传递系统调用号) 所以这里有两种思路解决这个问题.
思路一:
在使用寄存器之前进行 `push`, 跳转后 `pop`, 这里存在一个问题就是在原地址的几条指令进行 `patch code` 时一定会污染一个寄存器(也不能说一定, 如果这时进行压栈, 在之后的 `invoke_trampline` 会导致函数栈发生改变, 此时有个解决方法可以 `pop` 出来, 由 hook-entry 或者其他变量暂时保存, 但这时需要处理锁的问题. )
思路二:
挑选合适的寄存器, 不考虑污染问题. 这时可以参考, 下面的资料, 选择 x16 or x17, 或者自己做一个实验 `otool -tv ~/Downloads/xxx > ~/Downloads/xxx.txt` 通过 dump 一个 `ARM64` 程序的指令, 来判断哪个寄存器用的最少, 但是不要使用 `x18` 寄存器, 你对该寄存器的修改是无效的.
参考资料:
```
PAGE: 9-3
Programmer’s Guide for ARMv8-A
9.1 Register use in the AArch64 Procedure Call Standard
9.1.1 Parameters in general-purpose registers
```
## `rwx` 与 `codesigning`
对于非越狱, 不能分配可执行内存, 不能进行 `code patch`.
两篇原理讲解 codesign 的原理
```
https://papers.put.as/papers/ios/2011/syscan11_breaking_ios_code_signing.pdf
http://www.newosxbook.com/articles/CodeSigning.pdf
```
以及源码分析如下:
crash 异常如下, 其中 `0x0000000100714000` 是 mmap 分配的页.
```
Exception Type: EXC_BAD_ACCESS (SIGKILL - CODESIGNING)
Exception Subtype: unknown at 0x0000000100714000
Termination Reason: Namespace CODESIGNING, Code 0x2
Triggered by Thread: 0
```
寻找对应的错误码
```
xnu-3789.41.3/bsd/sys/reason.h
/*
* codesigning exit reasons
*/
#define CODESIGNING_EXIT_REASON_TASKGATED_INVALID_SIG 1
#define CODESIGNING_EXIT_REASON_INVALID_PAGE 2
#define CODESIGNING_EXIT_REASON_TASK_ACCESS_PORT 3
```
找到对应处理函数, 请仔细阅读注释里内容, 不做解释了.
```
# xnu-3789.41.3/osfmk/vm/vm_fault.c:2632
/* If the map is switched, and is switch-protected, we must protect
* some pages from being write-faulted: immutable pages because by
* definition they may not be written, and executable pages because that
* would provide a way to inject unsigned code.
* If the page is immutable, we can simply return. However, we can't
* immediately determine whether a page is executable anywhere. But,
* we can disconnect it everywhere and remove the executable protection
* from the current map. We do that below right before we do the
* PMAP_ENTER.
*/
cs_enforcement_enabled = cs_enforcement(NULL);
if(cs_enforcement_enabled && map_is_switched &&
map_is_switch_protected && page_immutable(m, prot) &&
(prot & VM_PROT_WRITE))
{
return KERN_CODESIGN_ERROR;
}
if (cs_enforcement_enabled && page_nx(m) && (prot & VM_PROT_EXECUTE)) {
if (cs_debug)
printf("page marked to be NX, not letting it be mapped EXEC\n");
return KERN_CODESIGN_ERROR;
}
if (cs_enforcement_enabled &&
!m->cs_validated &&
(prot & VM_PROT_EXECUTE) &&
!(caller_prot & VM_PROT_EXECUTE)) {
/*
* FOURK PAGER:
* This page has not been validated and will not be
* allowed to be mapped for "execute".
* But the caller did not request "execute" access for this
* fault, so we should not raise a code-signing violation
* (and possibly kill the process) below.
* Instead, let's just remove the "execute" access request.
*
* This can happen on devices with a 4K page size if a 16K
* page contains a mix of signed&executable and
* unsigned&non-executable 4K pages, making the whole 16K
* mapping "executable".
*/
prot &= ~VM_PROT_EXECUTE;
}
/* A page could be tainted, or pose a risk of being tainted later.
* Check whether the receiving process wants it, and make it feel
* the consequences (that hapens in cs_invalid_page()).
* For CS Enforcement, two other conditions will
* cause that page to be tainted as well:
* - pmapping an unsigned page executable - this means unsigned code;
* - writeable mapping of a validated page - the content of that page
* can be changed without the kernel noticing, therefore unsigned
* code can be created
*/
if (!cs_bypass &&
(m->cs_tainted ||
(cs_enforcement_enabled &&
(/* The page is unsigned and wants to be executable */
(!m->cs_validated && (prot & VM_PROT_EXECUTE)) ||
/* The page should be immutable, but is in danger of being modified
* This is the case where we want policy from the code directory -
* is the page immutable or not? For now we have to assume that
* code pages will be immutable, data pages not.
* We'll assume a page is a code page if it has a code directory
* and we fault for execution.
* That is good enough since if we faulted the code page for
* writing in another map before, it is wpmapped; if we fault
* it for writing in this map later it will also be faulted for executing
* at the same time; and if we fault for writing in another map
* later, we will disconnect it from this pmap so we'll notice
* the change.
*/
(page_immutable(m, prot) && ((prot & VM_PROT_WRITE) || m->wpmapped))
))
))
{
```
#### 其他文章:
http://ddeville.me/2014/04/dynamic-linking
> Later on, whenever a page fault occurs the vm_fault function in `vm_fault.c` is called. During the page fault the signature is validated if necessary. The signature will need to be validated if the page is mapped in user space, if the page belongs to a code-signed object, if the page will be writable or simply if it has not previously been validated. Validation happens in the `vm_page_validate_cs` function inside vm_fault.c (the validation process and how it is enforced continually and not only at load time is interesting, see Charlie Miller’s book for more details).
> If for some reason the page cannot be validated, the kernel checks whether the `CS_KILL` flag has been set and kills the process if necessary. There is a major distinction between iOS and OS X regarding this flag. All iOS processes have this flag set whereas on OS X, although code signing is checked it is not set and thus not enforced.
> In our case we can safely assume that the (missing) code signature couldn’t be verified leading to the kernel killing the process.
---<file_sep>/HookZz/src/hookzz_internal.h
#ifndef hookzz_internal_h
#define hookzz_internal_h
#include "core.h"
#include "hookzz.h"
bool zz_is_near_jump();
#endif<file_sep>/HookZz/src/platforms/arch-arm64/writer-arm64.h
/**
* Copyright 2017 jmpews
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef platforms_arch_arm64_writer_arm64_h
#define platforms_arch_arm64_writer_arm64_h
#include "instruction.h"
#include "register-arm64.h"
#include "writer-arm64.h"
#include "std_kit/std_buffer_array.h"
#include "std_kit/std_kit.h"
#include "std_kit/std_list.h"
typedef struct _ARM64AssemblyWriter {
void *start_pc;
void *start_address;
list_t *instCTXs;
buffer_array_t *inst_bytes;
} ARM64AssemblyWriter;
#define arm64_assembly_writer_cclass(member) cclass(arm64_assembly_writer, member)
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
ARM64AssemblyWriter *arm64_assembly_writer_cclass(new)(void *pc);
void arm64_assembly_writer_cclass(destory)(ARM64AssemblyWriter *self);
void arm64_assembly_writer_cclass(reset)(ARM64AssemblyWriter *self, void *pc);
void arm64_assembly_writer_cclass(patch_to)(ARM64AssemblyWriter *self, void *target_address);
/* b xxx range for near jump */
size_t arm64_assembly_writer_cclass(bxxx_range)();
void arm64_assembly_writer_cclass(put_bytes)(ARM64AssemblyWriter *self, void *data, int length);
void arm64_assembly_writer_cclass(put_ldr_reg_imm)(ARM64AssemblyWriter *self, ARM64Reg reg, uint32_t offset);
void arm64_assembly_writer_cclass(put_str_reg_reg_offset)(ARM64AssemblyWriter *self, ARM64Reg src_reg,
ARM64Reg dest_reg, uint64_t offset);
void arm64_assembly_writer_cclass(put_ldr_reg_reg_offset)(ARM64AssemblyWriter *self, ARM64Reg dest_reg,
ARM64Reg src_reg, uint64_t offset);
void arm64_assembly_writer_cclass(put_br_reg)(ARM64AssemblyWriter *self, ARM64Reg reg);
void arm64_assembly_writer_cclass(put_blr_reg)(ARM64AssemblyWriter *self, ARM64Reg reg);
void arm64_assembly_writer_cclass(put_b_imm)(ARM64AssemblyWriter *self, uint64_t offset);
#ifdef __cplusplus
}
#endif //__cplusplus
#endif<file_sep>/HookZz/src/platforms/backend-posix/memory-manager-posix.c
#include "memory-helper-posix.h"
#include "memory_manager.h"
#if !defined(__APPLE__) || USE_POSIX_IN_DARWIN
PLATFORM_API int memory_manager_cclass(get_page_size)() {
int page_size;
page_size = posix_memory_helper_cclass(get_page_size)();
return page_size;
}
PLATFORM_API void memory_manager_cclass(patch_code)(memory_manager_t *self, void *dest, void *src, int count) {
posix_memory_helper_cclass(patch_code)(dest, src, count);
return;
}
PLATFORM_API void *memory_manager_cclass(allocate_page)(memory_manager_t *self, int prot, int n) {
return posix_memory_helper_cclass(allocate_page)(prot, n);
}
PLATFORM_API void memory_manager_cclass(set_page_permission)(void *page_address, int prot, int n) {
posix_memory_helper_cclass(set_page_permission)(page_address, prot, n);
}
#endif<file_sep>/HookZz/src/platforms/arch-arm64/reader-arm64.c
#include "reader-arm64.h"
#include "std_kit/std_kit.h"
#include <string.h>
inline void ReadBytes(void *data, void *address, int length);
void ReadBytes(void *data, void *address, int length) { memcpy(data, address, length); }
ARM64AssemblyReader *arm64_assembly_reader_cclass(new)(void *address, void *pc) {
ARM64AssemblyReader *reader = SAFE_MALLOC_TYPE(ARM64AssemblyReader);
reader->start_address = address;
reader->start_pc = pc;
reader->instCTXs = list_new();
reader->inst_bytes = buffer_array_create(64);
return reader;
}
void arm64_assembly_reader_cclass(reset)(ARM64AssemblyReader *self, void *address, void *pc) {
self->start_address = address;
self->start_pc = pc;
list_destroy(self->instCTXs);
self->instCTXs = list_new();
buffer_array_clear(self->inst_bytes);
return;
}
ARM64InstructionCTX *arm64_assembly_reader_cclass(read_inst)(ARM64AssemblyReader *self) {
ARM64InstructionCTX *instCTX = SAFE_MALLOC_TYPE(ARM64InstructionCTX);
instCTX->pc = (zz_addr_t)self->start_pc + self->inst_bytes->size;
instCTX->address = (zz_addr_t)self->start_address + self->inst_bytes->size;
instCTX->size = 4;
ReadBytes((void *)&instCTX->bytes, (void *)instCTX->address, 4);
buffer_array_put(self->inst_bytes, (void *)instCTX->address, 4);
list_rpush(self->instCTXs, list_node_new(instCTX));
return instCTX;
}<file_sep>/HookZz/src/platforms/arch-arm64/instruction.c
#include "instruction.h"
#include <stdint.h>
#include <string.h>
uint32_t get_insn_sub(uint32_t insn, int start, int length) { return (insn >> start) & ((1 << length) - 1); }<file_sep>/HookZz/src/platforms/backend-x86/custom-bridge-handler.c
//
// Created by z on 2018/4/7.
//
#include "custom-bridge-handler.h"
#include "closure-bridge-x86.h"
#include <CommonKit/log/log_kit.h>
#include <debuglog.h>
#include <hookzz.h>
void context_begin_invocation(RegState *rs, hook_entry_t *entry, void *next_hop_addr_PTR, void *ret_addr_PTR) {}
void context_begin_invocation_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info) { return; }
void context_end_invocation(RegState *rs, hook_entry_t *entry, void *next_hop_addr_PTR) {}
void context_end_invocation_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info) { return; }
void dynamic_binary_instrumentation_invocation(RegState *rs, hook_entry_t *entry, void *next_hop_addr_PTR) {}
void dynamic_binary_instrumentationn_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info) { return; }<file_sep>/HookZz/srcxx/StackManager.cpp
//
// Created by jmpews on 2018/6/14.
//
#include "StackManager.h"
ThreadStackManager::ThreadStackManager(ThreadLocalKey *key) {
ThreadManager *threadManager = Singleton<ThreadManager>::GetInstance();
threadManager->setThreadLocalData(key, static_cast<void *>(this));
}
ThreadStackManager *ThreadStackManager::initializeFromThreadLocalKey(ThreadLocalKey *key) {
ThreadManager *threadManager = Singleton<ThreadManager>::GetInstance();
ThreadStackManager *threadStack = static_cast<ThreadStackManager *>(threadManager->getThreadLocalData(key));
return threadStack;
}
void ThreadStackManager::pushCallStack(CallStackManager *call_stack) {
call_stack->id = call_stacks.size();
call_stack->thread_stack = this;
call_stacks.push_back(call_stack);
}
CallStackManager *ThreadStackManager::popCallStack() {
CallStackManager *call_stack = call_stacks[call_stacks.size() - 1];
call_stacks.pop_back();
return call_stack;
}
void *CallStackManager::getCallStackValue(char *key) {
std::map<char *, void *>::iterator it;
it = kv_map.find(key);
if (it != kv_map.end()) {
return (void *)it->second;
}
return NULL;
}
void CallStackManager::setCallStackValue(char *key, void *value) {
kv_map.insert(std::pair<char *, void *>(key, value));
}<file_sep>/HookZz/srcxx/Platforms/arch-arm64/ARM64Writer.h
//
// Created by jmpews on 2018/6/14.
//
#ifndef HOOKZZ_ARM64WRITER_H
#define HOOKZZ_ARM64WRITER_H
#include "ARM64Register.h"
#include "Instruction.h"
#include <vector>
class ARM64Relocator;
class ARM64AssemblerWriter {
public:
void *start_pc;
void *start_address;
std::vector<ARM64InstructionCTX *> instCTXs;
std::vector<char> instBytes;
public:
ARM64AssemblerWriter(void *pc);
void reset(void *pc);
void PatchTo(void *target_address);
void putBytes(void *data, int dataSize);
void put_ldr_reg_imm(ARM64Reg reg, uint32_t offset) {
ARM64RegInfo ri;
DescribeARM64Reigster(reg, &ri);
uint32_t imm19, Rt;
imm19 = offset >> 2;
Rt = ri.index;
uint32_t inst = 0x58000000 | imm19 << 5 | Rt;
putBytes((void *)&inst, 4);
}
void put_str_reg_reg_offset(ARM64Reg src_reg, ARM64Reg dst_reg, uint64_t offset) {
ARM64RegInfo rs, rd;
DescribeARM64Reigster(src_reg, &rs);
DescribeARM64Reigster(dst_reg, &rd);
uint32_t size, v = 0, opc = 0, Rn_ndx, Rt_ndx;
Rn_ndx = rd.index;
Rt_ndx = rs.index;
if (rs.isInteger) {
size = (rs.width == 64) ? 0b11 : 0b10;
}
uint32_t imm12 = offset >> size;
uint32_t inst = 0x39000000 | size << 30 | opc << 22 | imm12 << 10 | Rn_ndx << 5 | Rt_ndx;
putBytes((void *)&inst, 4);
}
void put_ldr_reg_reg_offset(ARM64Reg dst_reg, ARM64Reg src_reg, uint64_t offset) {
ARM64RegInfo rs, rd;
DescribeARM64Reigster(src_reg, &rs);
DescribeARM64Reigster(dst_reg, &rd);
uint32_t size, v = 0, opc = 0b01, Rn_ndx, Rt_ndx;
Rn_ndx = rs.index;
Rt_ndx = rd.index;
if (rs.isInteger) {
size = (rs.width == 64) ? 0b11 : 0b10;
}
uint32_t imm12 = offset >> size;
uint32_t inst = 0x39000000 | size << 30 | opc << 22 | imm12 << 10 | Rn_ndx << 5 | Rt_ndx;
putBytes((void *)&inst, 4);
}
void put_br_reg(ARM64Reg reg) {
ARM64RegInfo ri;
DescribeARM64Reigster(reg, &ri);
uint32_t op = 0, Rn_ndx;
Rn_ndx = ri.index;
uint32_t inst = 0xd61f0000 | op << 21 | Rn_ndx << 5;
putBytes((void *)&inst, 4);
}
void put_blr_reg(ARM64Reg reg) {
ARM64RegInfo ri;
DescribeARM64Reigster(reg, &ri);
uint32_t op = 0b01, Rn_ndx;
Rn_ndx = ri.index;
uint32_t inst = 0xd63f0000 | op << 21 | Rn_ndx << 5;
putBytes((void *)&inst, 4);
}
void put_b_imm(uint64_t offset) {
uint32_t op = 0b0, imm26;
imm26 = (offset >> 2) & 0x03ffffff;
uint32_t inst = 0x14000000 | op << 31 | imm26;
putBytes((void *)&inst, 4);
}
};
#endif //HOOKZZ_ARM64WRITER_H
<file_sep>/HookZz/README.md
此分支为重构分支仅支持 [Android|iOS]|[ARM64] | [转到分支MASTER(need update)](https://github.com/jmpews/HookZz/tree/master)
## What is HookZz ?
**a hook framework for arm/arm64/ios/android**
ref to: [frida-gum](https://github.com/frida/frida-gum) and [minhook](https://github.com/TsudaKageyu/minhook) and [substrate](https://github.com/jevinskie/substrate).
**special thanks to [frida-gum](https://github.com/frida/frida-gum) perfect code and modular architecture, frida is aircraft carrier, HookZz is boat, but still with some tricks**
## Features
- Static Binary Instrumentation for Mach-O [doing]
- GOT hook with `pre_call` & `post_call`
- **replace function** with `replace_call`
- **wrap function** with `pre_call` and `post_call`
- **dynamic binary instrumentation** with `dbi_call`
- the power to hook short function
- the power to access registers directly(ex: `rs->general.regs.x15`)
- runtime code patch
- it's cute, **100kb**
## Compile
**`git clone --depth 1 git@github.com:jmpews/HookZz.git --branch master-c`**
#### build for iOS/ARM64
```
mkdir build
cd build
cmake .. \
-DCMAKE_TOOLCHAIN_FILE=cmake/ios.toolchain.cmake \
-DIOS_PLATFORM=OS \
-DIOS_ARCH=arm64 \
-DENABLE_ARC=FALSE \
-DENABLE_BITCODE=OFF \
-DCXX=OFF \
-DX_ARCH=arm64 \
-DX_PLATFORM=iOS \
-DX_SHARED=ON \
-DX_LOG=ON \
-DCMAKE_VERBOSE_MAKEFILE=OFF
make
```
if you want generate Xcode Project, just replace with `cmake -G Xcode `.
#### build for Android/ARM64
```
mkdir build
cd build
export ANDROID_NDK=/Users/jmpews/Library/Android/sdk/ndk-bundle
cmake .. \
-DCMAKE_TOOLCHAIN_FILE=$ANDROID_NDK/build/cmake/android.toolchain.cmake \
-DANDROID_NDK=$ANDROID_NDK \
-DCMAKE_BUILD_TYPE=Release \
-DANDROID_ABI=arm64-v8a \
-DCXX=OFF \
-DX_ARCH=arm64 \
-DX_PLATFORM=Android \
-DX_SHARED=ON \
-DX_LOG=ON \
-DCMAKE_VERBOSE_MAKEFILE=OFF
```
## Demo
#### Android/ARMv8
https://github.com/jmpews/HookZzAndroidDemo
## Usage
#### 0. near jump
this trick is used to hook short function. it will use `b xxx` replace
```
ldr x17, #8
br x17
.long 0x1111
.long 0x1111
````
if you want enable near jump, just add `zz_enable_near_jump();` before hook funciton, and stop with `zz_disable_near_jump();`
#### 1. replace hook function
```
RetStatus ZzReplace(void *function_address, void *replace_call, void **origin_call);
size_t (*origin_fread)(void * ptr, size_t size, size_t nitems, FILE * stream);
size_t (fake_fread)(void * ptr, size_t size, size_t nitems, FILE * stream) {
printf("[FileMonitor|fread|model|%p] >>> %ld, %ld\n", ptr, size, nitems);
return origin_fread(ptr, size, nitems, stream);
}
void hook_fread() { ZzReplace((void *)fread, (void *)fake_fread, (void **)&origin_fread); }
```
#### 2. wrap hook function
```
RetStatus ZzWrap(void *function_address, PRECALL pre_call, POSTCALL post_call);
void open_pre_call(RegState *rs, ThreadStackPublic *tsp, CallStackPublic *csp, const HookEntryInfo *info) {
char *path = (char *)rs->ZREG(0);
int oflag = (int)rs->ZREG(1);
if (pathFilter(path))
return;
switch (oflag) {
case O_RDONLY:
printf("[FileMonitor|open|R] >>> %s\n", path);
break;
case O_WRONLY:
printf("[FileMonitor|open|W] >>> %s\n", path);
break;
case O_RDWR:
printf("[FileMonitor|open|RW] >>> %s\n", path);
break;
default:
printf("[FileMonitor|open|-] >>> %s\n", path);
break;
}
}
void open_post_call(RegState *rs, ThreadStackPublic *tsp, CallStackPublic *csp, const HookEntryInfo *info) {
}
void hook_open() { ZzWrap((void *)open, open_pre_call, open_post_call); }
```
#### 3. dynamic binary instrumentation
```
RetStatus ZzDynamicBinaryInstrumentation(void *inst_address, DBICALL dbi_call);
void catchDecrypt(RegState *rs, const HookEntryInfo *info) {
printf("descrypt catch by HookZz\n");
}
__attribute__((constructor)) void initlializeTemplate() {
struct mach_header *mainHeader = (struct mach_header *)_dyld_get_image_header(0);
int slide = _dyld_get_image_vmaddr_slide(0);
uintptr_t targetVmAddr = 0x1001152BC;
uintptr_t finalAddr = targetVmAddr + slide - 0x0000000000002170;
printf(">>> ASLR: 0x%x\n", slide);
printf(">>> decrypt address: %p\n", (void *)finalAddr);
ZzDynamicBinaryInstrumentation((void *)finalAddr, catchDecrypt);
}
```
## Contact me
```
recommend_email: <EMAIL>
QQ: 858982985
```
<img with="220px" height="220px" src="http://ww1.sinaimg.cn/large/a4decaedgy1ft0c1qh4s2j209a099wfi.jpg" alt="qrcode">
<file_sep>/HookZz/src/platforms/arch-arm64/arch-arm64.h
#define xASM(x) __asm(x)
#if 0
#undef get_current_fp_reg
#define get_current_fp_reg(fp_reg) xASM("mov %[fp_reg], fp" : [fp_reg] "=r"(fp_reg) :);
#endif<file_sep>/HookZz/src/memory_manager.c
#include "memory_manager.h"
#include "core.h"
#include "std_kit/std_list.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* shared instance */
memory_manager_t *g_memory_manager = NULL;
memory_manager_t *memory_manager_cclass(shared_instance)() {
if (g_memory_manager == NULL) {
g_memory_manager = SAFE_MALLOC_TYPE(memory_manager_t);
g_memory_manager->code_caves = list_new();
g_memory_manager->free_memory_blocks = list_new();
g_memory_manager->process_memory_layout = list_new();
XCHECK(g_memory_manager != NULL);
}
return g_memory_manager;
}
CodeSlice *memory_manager_cclass(allocate_code_slice)(memory_manager_t *self, int size) {
CodeSlice *cs = NULL;
list_iterator_t *it = list_iterator_new(self->free_memory_blocks, LIST_HEAD);
for (int i = 0; i < self->free_memory_blocks->len; i++) {
FreeMemoryBlock *fmb = (FreeMemoryBlock *)(list_at(self->free_memory_blocks, i)->val);
if ((fmb->total_size - fmb->used_size) > size) {
cs = SAFE_MALLOC_TYPE(CodeSlice);
cs->data = (void *)(fmb->address + fmb->used_size);
cs->size = size;
fmb->used_size += size;
return cs;
}
}
// allocate a new page
if (cs == NULL) {
void *page_ptr = memory_manager_cclass(allocate_page)(self, PROT_R_X, 1);
FreeMemoryBlock *fmb = SAFE_MALLOC_TYPE(FreeMemoryBlock);
fmb->used_size = 0;
fmb->total_size = memory_manager_cclass(get_page_size)();
fmb->prot = PROT_R_X;
fmb->address = page_ptr;
list_rpush(self->free_memory_blocks, list_node_new(fmb));
cs = SAFE_MALLOC_TYPE(CodeSlice);
cs->data = (void *)(fmb->address + fmb->used_size);
cs->size = size;
fmb->used_size += size;
return cs;
}
return NULL;
}
void *search_dummy_code_cave(zz_addr_t search_start, zz_addr_t search_end, int size) {
assert(search_start);
assert(search_start < search_end);
zz_addr_t cur_addr = search_start;
unsigned char dummy_0[1024] = {0};
while (cur_addr < search_end) {
if (!memcmp((void *)cur_addr, dummy_0, size)) {
return (void *)cur_addr;
}
cur_addr += size;
}
return NULL;
}
CodeCave *memory_manager_cclass(search_code_cave)(memory_manager_t *self, void *address, int range, int size) {
CodeCave *cc = NULL;
zz_addr_t limit_start, limit_end;
zz_addr_t search_start, search_end;
limit_start = (zz_addr_t)address - range;
limit_end = (zz_addr_t)address + range - size;
list_iterator_t *it = list_iterator_new(self->free_memory_blocks, LIST_HEAD);
if (!self->process_memory_layout->len) {
memory_manager_cclass(get_process_memory_layout)(self);
}
for (int i = 0; i < self->process_memory_layout->len; i++) {
MemoryBlock *mb = (MemoryBlock *)(list_at(self->process_memory_layout, i)->val);
// fix top/bottom limit
search_start = (zz_addr_t)mb->address > limit_start ? (zz_addr_t)mb->address : limit_start;
search_end = ((zz_addr_t)mb->address + mb->size) < limit_end ? ((zz_addr_t)mb->address + mb->size) : limit_end;
// check `fixed`
if(search_start > search_end) {
continue;
}
void *p = search_dummy_code_cave(search_start, search_end, size);
if (p) {
cc = SAFE_MALLOC_TYPE(CodeCave);
cc->size = size;
cc->address = p;
return cc;
}
}
return NULL;
}
<file_sep>/HookZz/srcxx/CommonClass/Manager.h
//
// Created by z on 2018/6/14.
//
#ifndef HOOKZZ_MANAGER_H
#define HOOKZZ_MANAGER_H
#include <iostream>
#include <vector>
#endif //HOOKZZ_MANAGER_H
<file_sep>/HookZz/src/platforms/arch-arm64/arch-arm64.c
#include "hookzz.h"
#include "arch-arm64.h"
void *get_next_hop_addr_PTR(RegState *rs) {
void *next_hop_addr_PTR = (void *)&rs->general.regs.x15;
return next_hop_addr_PTR;
}
void *get_ret_addr_PTR(RegState *rs) {
void *ret_addr_PTR = (void *)&rs->lr;
return ret_addr_PTR;
}
void *get_current_fp_reg() {
void *fp_reg;
xASM("mov %[fp_reg], fp" : [fp_reg] "=r"(fp_reg) :);
return fp_reg;
}
<file_sep>/HookZz/srcxx/Platforms/arch-arm64/ARM64InterceptorRoutingTrampoline.h
//
// Created by jmpews on 2018/6/14.
//
#ifndef HOOKZZ_ARM64INTERCEPTOR_H
#define HOOKZZ_ARM64INTERCEPTOR_H
#include "ARM64Reader.h"
#include "ARM64Relocator.h"
#include "ARM64Writer.h"
#include "Interceptor.h"
#include "InterceptorRoutingTrampoline.h"
#include "MemoryManager.h"
class ARM64InterceptorRoutingTrampoline : public InterceptorRoutingTrampoline {
public:
MemoryManager *memory_manager;
ARM64Relocator *relocatorARM64;
ARM64AssemblerWriter *writerARM64;
ARM64AssemblyReader *readerARM64;
public:
void Prepare(HookEntry *entry);
void BuildForEnterTransfer(HookEntry *entry);
void BuildForEnter(HookEntry *entry);
void BuildForDynamicBinaryInstrumentation(HookEntry *entry);
void BuildForLeave(HookEntry *entry);
void BuildForInvoke(HookEntry *entry);
void ActiveTrampoline(HookEntry *entry);
};
typedef struct _ARM64HookFuntionEntryBackend {
int limit_relocate_inst_size;
} ARM64HookEntryBackend;
#endif //HOOKZZ_INTERCEPTORARM64_H
<file_sep>/HookZz/src/hookzz.c
#include "hookzz.h"
#include "core.h"
#include "hookzz_internal.h"
#include "interceptor.h"
#include "interceptor_routing_trampoline.h"
#include "std_kit/std_kit.h"
bool g_near_jump_flag = false;
void zz_enable_near_jump() { g_near_jump_flag = true; }
bool zz_is_near_jump() { return g_near_jump_flag; }
void zz_disable_near_jump() { g_near_jump_flag = false; }
static void initialize_hook_entry(hook_entry_t *entry) {
if (zz_is_near_jump()) {
entry->is_try_near_jump = true;
}
interceptor_t *interceptor = interceptor_cclass(shared_instance)();
interceptor_cclass(add_hook_entry)(interceptor, entry);
interceptor_trampoline_cclass(build_all)(entry);
interceptor_trampoline_cclass(active)(entry);
}
RetStatus ZzWrap(void *function_address, PRECALL pre_call, POSTCALL post_call) {
hook_entry_t *entry = SAFE_MALLOC_TYPE(hook_entry_t);
entry->id = (uintptr_t)entry;
entry->target_address = function_address;
entry->type = HOOK_TYPE_FUNCTION_via_PRE_POST;
entry->pre_call = pre_call;
entry->post_call = post_call;
Logging("[*] prepare ZzWrap hook %p", function_address);
initialize_hook_entry(entry);
return RS_SUCCESS;
}
RetStatus ZzReplace(void *function_address, void *replace_call, void **origin_call) {
hook_entry_t *entry = SAFE_MALLOC_TYPE(hook_entry_t);
entry->id = (uintptr_t)entry;
entry->target_address = function_address;
entry->type = HOOK_TYPE_FUNCTION_via_REPLACE;
entry->replace_call = replace_call;
Logging("[*] prepare ZzReplace hook %p", function_address);
initialize_hook_entry(entry);
*origin_call = entry->on_invoke_trampoline;
return RS_SUCCESS;
}
RetStatus ZzDynamicBinaryInstrumentation(void *inst_address, DBICALL dbi_call) {
hook_entry_t *entry = SAFE_MALLOC_TYPE(hook_entry_t);
entry->id = (uintptr_t)entry;
entry->target_address = inst_address;
entry->type = HOOK_TYPE_INSTRUCTION_via_DBI;
entry->dbi_call = dbi_call;
Logging("[*] prepare ZzDynamicBinaryInstrumentation hook %p", inst_address);
initialize_hook_entry(entry);
return RS_SUCCESS;
}
<file_sep>/HookZz/src/platforms/backend-x86/interceptor-x86.c
#include "interceptor-x86.h"
#include "backend-x86-helper.h"
#include "closure-bridge-x86.h"
#include "custom-bridge-handler.h"
#include <debuglog.h>
#include <stdlib.h>
#include <string.h>
#define ZZ_X86_TINY_REDIRECT_SIZE 4
#define ZZ_X86_FULL_REDIRECT_SIZE 16
InterceptorBackend *InteceptorBackendNew(ExecuteMemoryManager *emm) { return NULL; }
void trampoline_free(hook_entry_t *entry) {
if (entry->on_invoke_trampoline) {
//TODO
}
if (entry->on_enter_trampoline) {
//TODO
}
if (entry->on_enter_transfer_trampoline) {
//TODO
}
if (entry->on_leave_trampoline) {
//TODO
}
if (entry->on_invoke_trampoline) {
//TODO
}
return;
}
void trampoline_prepare(InterceptorBackend *self, hook_entry_t *entry) { return; }
// double jump
void trampoline_build_for_enter_transfer(InterceptorBackend *self, hook_entry_t *entry) { return; }
void trampoline_build_for_enter(InterceptorBackend *self, hook_entry_t *entry) { return; }
void trampoline_build_for_dynamic_binary_instrumentation(InterceptorBackend *self, hook_entry_t *entry) { return; }
void trampoline_build_for_invoke(InterceptorBackend *self, hook_entry_t *entry) { return; }
void trampoline_build_for_leave(InterceptorBackend *self, hook_entry_t *entry) { return; }
void trampoline_active(InterceptorBackend *self, hook_entry_t *entry) { return; }<file_sep>/HookZz/src/interceptor.c
#include <stdlib.h>
#include <string.h>
#include "core.h"
#include "interceptor.h"
#include "memory_manager.h"
#include "std_kit/std_list.h"
interceptor_t *g_interceptor = NULL;
interceptor_t *interceptor_cclass(shared_instance)(void) {
if (g_interceptor == NULL) {
g_interceptor = SAFE_MALLOC_TYPE(interceptor_t);
g_interceptor->hook_entries = list_new();
g_interceptor->memory_manager = memory_manager_cclass(shared_instance)();
}
return g_interceptor;
}
hook_entry_t *interceptor_cclass(find_hook_entry)(interceptor_t *self, void *target_address) {
if (!self)
self = interceptor_cclass(shared_instance)();
list_iterator_t *it = list_iterator_new(self->hook_entries, LIST_HEAD);
for (int i = 0; i < self->hook_entries->len; i++) {
hook_entry_t *entry = (hook_entry_t *)(list_at(self->hook_entries, i)->val);
if (entry->target_address == target_address) {
return entry;
}
}
return NULL;
}
void interceptor_cclass(add_hook_entry)(interceptor_t *self, hook_entry_t *entry) {
list_rpush(self->hook_entries, list_node_new(entry));
return;
}<file_sep>/HookZz/srcxx/InterceptorRouting.h
#ifndef interceptor_routing_h
#define interceptor_routing_h
#include "ClosureBridge.h"
#include "hookzz.h"
#include "interceptor.h"
ARCH_API void *get_ret_addr_PTR(RegState *rs);
ARCH_API void *get_next_hop_addr_PTR(RegState *rs);
void interceptor_routing_begin(RegState *rs, hook_entry_t *entry, void *next_hop_addr_PTR, void *ret_addr_PTR);
void interceptor_routing_end(RegState *rs, hook_entry_t *entry, void *next_hop_addr_PTR);
void interceptor_routing_dynamic_binary_instrumentation(RegState *rs, hook_entry_t *entry, void *next_hop_addr_PTR);
void interceptor_routing_begin_bridge_handler(RegState *rs, ClosureBridgeInfo *cbInfo);
void interceptor_routing_end_bridge_handler(RegState *rs, ClosureBridgeInfo *cbInfo);
void interceptor_routing_dynamic_binary_instrumentation_bridge_handler(RegState *rs, ClosureBridgeInfo *cbInfo);
void interceptor_routing_common_bridge_handler(RegState *rs, ClosureBridgeInfo *cbInfo);
void interceptor_routing_begin_dynamic_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcbInfo);
void interceptor_routing_end_dynamic_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcbInfo);
void interceptor_routing_dynamic_common_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcbInfo);
#endif<file_sep>/HookZz/src/closure_bridge.h
#ifndef closure_bridge_h
#define closure_bridge_h
#include "core.h"
#include "hookzz.h"
#include "std_kit/std_list.h"
#include <stdint.h>
#define PRIVATE
// closure bridge
typedef struct _ClosureBridgeInfo {
void *user_code;
void *user_data;
void *redirect_trampoline;
} ClosureBridgeInfo;
typedef struct _ClosureBridgeTrampolineTable {
void *entry;
void *trampoline_page;
uint16_t used_count;
uint16_t free_count;
} ClosureBridgeTrampolineTable;
typedef struct _ClosureBridge {
list_t *bridge_infos;
list_t *trampoline_tables;
} ClosureBridge;
#define ClosureBridgeCClass(member) cxxclass(ClosureBridge, member)
ClosureBridge *ClosureBridgeCClass(SharedInstance)();
ClosureBridgeInfo *ClosureBridgeCClass(AllocateClosureBridge)(ClosureBridge *self, void *user_data, void *user_code);
ClosureBridgeTrampolineTable *ClosureBridgeCClass(AllocateClosureBridgeTrampolineTable)(ClosureBridge *self);
ARCH_API void ClosureBridgeCClass(InitializeTablePage)(ClosureBridgeTrampolineTable *table, void *page_address);
ARCH_API void ClosureBridgeCClass(InitializeClosureBridgeInfo)(ClosureBridgeTrampolineTable *table,
ClosureBridgeInfo *cb_info, void *user_data,
void *user_code);
typedef void (*USER_CODE_CALL)(RegState *rs, ClosureBridgeInfo *cb_info);
#if DYNAMIC_CLOSURE_BRIDGE
// dynamic closure bridge
typedef struct _DynamicClosureBridgeInfo {
void *trampolineTo PRIVATE;
void *user_code;
void *user_data;
void *redirect_trampoline;
} DynamicClosureBridgeInfo;
typedef struct _DynamicClosureTrampolineTable {
void *entry;
void *trampoline_page;
void *data_page;
uint16_t used_count;
uint16_t free_count;
} DynamicClosureBridgeTrampolineTable;
typedef struct _DynamicClosureBridge {
list_t *dynamic_bridge_infos;
list_t *dynamic_trampoline_tables;
} DynamicClosureBridge;
#define DynamicClosureBridgeCClass(member) cclass(DynamicClosureBridge, member)
DynamicClosureBridge *DynamicClosureBridgeCClass(SharedInstance)();
DynamicClosureBridgeInfo *DynamicClosureBridgeCClass(AllocateDynamicClosureBridge)(DynamicClosureBridge *self,
void *user_data, void *user_code);
DynamicClosureBridgeTrampolineTable *
DynamicClosureBridgeCClass(AllocateDynamicClosureBridgeTrampolineTable)(DynamicClosureBridge *self);
typedef void (*DYNAMIC_USER_CODE_CALL)(RegState *rs, DynamicClosureBridgeInfo *dcb_info);
#endif
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
void closure_bridge_trampoline_template();
void closure_bridge_template();
#if DYNAMIC_CLOSURE_BRIDGE
void dynamic_closure_bridge_template();
void dynamic_closure_trampoline_table_page();
#endif
#ifdef __cplusplus
}
#endif //__cplusplus
#endif<file_sep>/HookZz/src/platforms/backend-posix/memory-helper-posix.h
#ifndef platforms_backend_darwin_memory_helper_linux_h
#define platforms_backend_darwin_memory_helper_linux_h
#include "core.h"
#include <sys/mman.h>
#include <unistd.h>
#define posix_memory_helper_cclass(member) cclass(posix_memory_helper, member)
int posix_memory_helper_cclass(get_page_size)();
void *posix_memory_helper_cclass(allocate_page)(int prot, int n);
void posix_memory_helper_cclass(patch_code)(void *dest, void *src, int count);
void posix_memory_helper_cclass(set_page_permission)(void *page_address, int prot, int n);
#endif
<file_sep>/HookZz/src/platforms/arch-arm64/interceptor-routing-trampoline-arm64.h
/**
* Copyright 2017 jmpews
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef interceptor_routing_trampoline_arm64_h
#define interceptor_routing_trampoline_arm64_h
#include "hookzz.h"
#include "interceptor.h"
#include "memory_manager.h"
#include "reader-arm64.h"
#include "relocator-arm64.h"
#include "writer-arm64.h"
#define CTX_SAVE_STACK_OFFSET (8 + 30 * 8 + 8 * 16)
typedef struct _interceptor_backend_arm64_t {
memory_manager_t *memory_manager;
ARM64Relocator *relocator_arm64;
ARM64AssemblyWriter *writer_arm64;
ARM64AssemblyReader *reader_arm64;
} interceptor_backend_arm64_t;
typedef struct _hook_entry_backend_arm64_t {
int limit_relocate_inst_size;
} hook_entry_backend_arm64_t;
#endif<file_sep>/HookZz/srcxx/CommonClass/Manager.cpp
//
// Created by z on 2018/6/14.
//
#include "Manager.h"
<file_sep>/HookZz/srcxx/Platforms/arch-arm64/custom-bridge-handler-arm64.cpp
//
// Created by z on 2018/4/7.
//
#include "custom-bridge-handler-arm64.h"
#include "Invocation.h"
#include "hookzz.h"
void context_begin_invocation_bridge_handler(RegState *rs, ClosureBridgeInfo *cbInfo) {
HookEntry *entry = (HookEntry *)cbInfo->user_data;
void *nextHopPTR = (void *)&rs->general.regs.x15;
void *regLRPTR = (void *)&rs->lr;
context_begin_invocation(rs, entry, nextHopPTR, regLRPTR);
return;
}
void context_end_invocation_bridge_handler(RegState *rs, ClosureBridgeInfo *cbInfo) {
HookEntry *entry = (HookEntry *)cbInfo->user_data;
void *nextHopPTR = (void *)&rs->general.regs.x15;
context_end_invocation(rs, entry, nextHopPTR);
return;
}
void dynamic_binary_instrumentationn_bridge_handler(RegState *rs, ClosureBridgeInfo *cbInfo) {
HookEntry *entry = (HookEntry *)cbInfo->user_data;
void *nextHopPTR = (void *)&rs->general.regs.x15;
dynamic_binary_instrumentation_invocation(rs, entry, nextHopPTR);
return;
}
void dynamic_context_begin_invocation_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcbInfo) {
HookEntry *entry = (HookEntry *)dcbInfo->user_data;
void *nextHopPTR = (void *)&rs->general.regs.x15;
void *regLRPTR = (void *)&rs->lr;
context_begin_invocation(rs, entry, nextHopPTR, regLRPTR);
return;
}
void dynamic_context_end_invocation_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcbInfo) {
HookEntry *entry = (HookEntry *)dcbInfo->user_data;
void *nextHopPTR = (void *)&rs->general.regs.x15;
context_end_invocation(rs, entry, nextHopPTR);
return;
}
void dynamic_common_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcbInfo) {
DYNAMIC_USER_CODE_CALL userCodeCall = (DYNAMIC_USER_CODE_CALL)dcbInfo->user_code;
// printf("CommonBridgeHandler:");
// printf("\tTrampoline Address: %p", cbInfo->redirect_trampoline);
userCodeCall(rs, dcbInfo);
// set return address
rs->general.x[15] = rs->general.x[15];
return;
}
void common_bridge_handler(RegState *rs, ClosureBridgeInfo *cbInfo) {
USER_CODE_CALL userCodeCall = (USER_CODE_CALL)cbInfo->user_code;
// printf("CommonBridgeHandler:");
// printf("\tTrampoline Address: %p", cbInfo->redirect_trampoline);
userCodeCall(rs, cbInfo);
// set return address
rs->general.x[15] = rs->general.x[15];
return;
}<file_sep>/HookZz/srcxx/Platforms/backend-darwin/memory-helper-darwin.h
#ifndef platforms_backend_darwin_memory_helper_darwin_h
#define platforms_backend_darwin_memory_helper_darwin_h
#include "Core.h"
#include "hookzz.h"
#include "memory_manager.h"
#include "mach_vm.h"
#include <mach-o/dyld.h>
#include <mach/mach.h>
#include <mach/vm_map.h>
#include <sys/mman.h>
#define darwin_memory_helper_cclass(member) cclass(darwin_memory_helper, member)
int darwin_memory_helper_cclass(get_page_size)();
void darwin_memory_helper_cclass(get_memory_info)(void *address, vm_prot_t *prot, vm_inherit_t *inherit);
void darwin_memory_helper_cclass(set_page_memory_permission)(void *address, int prot);
#endif<file_sep>/HookZz/include/hookzz.h
#ifndef hookzz_h
#define hookzz_h
// clang-format off
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
#include <stdbool.h>
#include <stdint.h>
typedef uintptr_t zz_addr_t;
typedef void * zz_ptr_t;
#ifndef REGISTER_STATE_STRUCT
#define REGISTER_STATE_STRUCT
#if defined(__arm64__) || defined(__aarch64__)
#define Tx(type) type##arm64
#define TX() type##ARM64
#define xT() arm64##type
#define XT() ARM64##type
typedef union _FPReg {
__int128_t q;
struct {
double d1;
double d2;
} d;
struct {
float f1;
float f2;
float f3;
float f4;
} f;
} FPReg;
typedef struct _RegState {
uint64_t dmmpy_0;
union {
uint64_t x[29];
struct {
uint64_t x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21,
x22, x23, x24, x25, x26, x27, x28;
} regs;
} general;
uint64_t fp;
uint64_t lr;
union {
FPReg q[8];
struct {
FPReg q0, q1, q2, q3, q4, q5, q6, q7;
} regs;
} floating;
} RegState;
#elif defined(__arm__)
#define Tx(type) type##arm
#define TX() type##ARM
#define xT() arm##type
#define XT() ARM##type
typedef struct _RegState {
uint32_t dummy_0;
uint32_t dummy_1;
union {
uint32_t r[13];
struct {
uint32_t r0, r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12;
} regs;
} general;
uint32_t lr;
} RegState;
#elif defined(__i386__)
#define Tx(type) type##arm
#define TX() type##ARM
#define xT() arm##type
#define XT() ARM##type
typedef struct _RegState {
} RegState;
#elif defined(__x86_64__)
#define Tx(type) type##x64
#define TX() type##X64
#define xT() x64##type
#define XT() X64##type
typedef struct _RegState {
} RegState;
#endif
#define REG_SP(rs) (void *)((uintptr_t)rs + sizeof(RegState))
#endif
typedef enum _RetStatus {
RS_UNKOWN = -1,
RS_DONE = 0,
RS_SUCCESS,
RS_FAILED
} RetStatus;
typedef enum _HookType {
// HOOK_TYPE_SINGLE_INSTRUCTION_DELETED = 0,
HOOK_TYPE_FUNCTION_via_PRE_POST = 0,
HOOK_TYPE_FUNCTION_via_REPLACE,
HOOK_TYPE_FUNCTION_via_GOT,
HOOK_TYPE_INSTRUCTION_via_DBI
}HookType;
typedef struct _CallStackPublic {
uintptr_t call_id;
} CallStackPublic;
typedef struct _ThreadStackPublic {
uintptr_t thread_id;
unsigned long call_stack_count;
} ThreadStackPublic;
typedef struct _HookEntryInfo {
uintptr_t hook_id;
void *target_address;
} HookEntryInfo;
typedef void (*PRECALL)(RegState *rs, ThreadStackPublic *tsp, CallStackPublic *csp, const HookEntryInfo *info);
typedef void (*POSTCALL)(RegState *rs, ThreadStackPublic *tsp, CallStackPublic *csp, const HookEntryInfo *info);
typedef void (*DBICALL)(RegState *rs, const HookEntryInfo *info);
void call_stack_kv_set(CallStackPublic *csp, char *key, void *value);
void *call_stack_kv_get(CallStackPublic *csp, char *key);
// open near jump, use code cave & b xxx
void zz_enable_near_jump();
// close near jump, use `ldr x17, #0x8; br x17; .long 0x0; .long 0x0`
void zz_disable_near_jump();
// use pre_call and post_call wrap a function
RetStatus ZzWrap(void *function_address, PRECALL pre_call, POSTCALL post_call);
// use inline hook to replace function
RetStatus ZzReplace(void *function_address, void *replace_call, void **origin_call);
// use pre_call and post_call wrap a GOT(imported) function
RetStatus ZzWrapGOT(void *image_header, char *image_name, char *function_name, PRECALL pre_call, POSTCALL post_call);
// replace got
RetStatus ZzReplaceGOT(void *image_header, char *image_name, char *function_name, void *replace_call, void **origin_call);
// hook instruction with DBI
RetStatus ZzDynamicBinaryInstrumentation(void *inst_address, DBICALL dbi_call);
#ifdef __cplusplus
}
#endif //__cplusplus
#endif
<file_sep>/HookZz/srcxx/MemoryManager.cpp
#include "MemoryManager.h"
CodeSlice *MemoryManager::allocateCodeSlice(int size) {
CodeSlice *cs = NULL;
for (auto fmb : free_memory_blocks) {
if ((fmb->total_size - fmb->used_size) > size) {
cs = new (CodeSlice);
cs->data = (void *)(fmb->address + fmb->used_size);
cs->size = size;
fmb->used_size += size;
return cs;
}
}
if (cs == NULL) {
void *page_ptr = allocateMemoryPage(3, 1);
FreeMemoryBlock *fmb = new (FreeMemoryBlock);
fmb->used_size = 0;
fmb->total_size = PageSize() * 1;
fmb->prot = MEM_RX;
fmb->address = (zz_addr_t)page_ptr;
free_memory_blocks.push_back(fmb);
fmb->used_size += size;
cs = new (CodeSlice);
cs->data = (void *)(fmb->address + fmb->used_size);
cs->size = size;
return cs;
}
}
void *search_code_cave(zz_addr_t search_start, zz_addr_t search_end, int size) {
assert(search_start);
assert(search_start < search_end);
zz_addr_t curr_addr = search_start;
unsigned char dummy_0[1024] = {0};
while (curr_addr < search_end) {
if (!memcpy((void *)curr_addr, dummy_0, size)) {
return (void *)curr_addr;
}
curr_addr += size;
}
return NULL;
}
CodeCave *MemoryManager::searchCodeCave(void *address, int range, int size) {
CodeCave *cc = NULL;
zz_addr_t limit_start, limit_end;
zz_addr_t search_start, search_end;
limit_start = (zz_addr_t)address - range;
limit_start = (zz_addr_t)address + range - size;
for (auto mb : process_memory_layout) {
search_start = mb->address > limit_start ? mb->address : limit_start;
search_end = (mb->address + mb->size) < limit_end ? (mb->address + mb->size) : limit_end;
void *p = search_dummy_code_cave(search_start, search_end, size);
if (p) {
cc = new (CodeCave);
cc->size = size;
cc->address = (zz_addr_t)p;
return cc;
}
}
return NULL;
}
<file_sep>/HookZz/srcxx/Platforms/backend-darwin/DarwinMemoryManager.cpp
//
// Created by jmpews on 2018/6/14.
//
#include "DarwinMemoryManager.h"
#include "memory-helper-darwin.h"
#include <errno.h>
#include <mach-o/dyld.h>
#include <mach/mach.h>
#include <mach/vm_map.h>
#include <sys/mman.h>
int MemoryManager::PageSize() { return darwin_memory_helper_cclass(get_page_size)(); }
void *MemoryManager::AllocatePage(int prot, int n) {
vm_address_t page_address;
kern_return_t kr;
vm_size_t page_size;
page_size = darwin_memory_helper_cclass(get_page_size)();
/* use vm_allocate not mmap */
kr = mach_vm_allocate(mach_task_self(), (mach_vm_address_t *)&page_address, page_size * n, VM_FLAGS_ANYWHERE);
/* set page permission */
darwin_memory_helper_cclass(set_page_memory_permission)((void *)page_address, 1 | 2);
return (void *)page_address;
}
void MemoryManager::GetProcessMemoryLayout() {
mach_msg_type_number_t count;
struct vm_region_submap_info_64 info;
vm_size_t nesting_depth;
kern_return_t kr = KERN_SUCCESS;
vm_address_t tmp_addr = 0;
vm_size_t tmp_size = 0;
while (1) {
count = VM_REGION_SUBMAP_INFO_COUNT_64;
kr = vm_region_recurse_64(mach_task_self(), &tmp_addr, &tmp_size, (natural_t *)&nesting_depth,
(vm_region_info_64_t)&info, &count);
if (kr == KERN_INVALID_ADDRESS) {
break;
} else if (kr) {
mach_error("vm_region:", kr);
break; /* last region done */
}
if (info.is_submap) {
nesting_depth++;
} else {
MemoryBlock *mb = new (MemoryBlock);
process_memory_layout.push_back(mb);
tmp_addr += tmp_size;
mb->address = tmp_addr - tmp_size;
mb->size = tmp_size;
mb->prot = info.protection;
}
}
}
/*
REF:
substitute/lib/darwin/execmem.c:execmem_foreign_write_with_pc_patch
frida-gum-master/gum/gummemory.c:gum_memory_patch_code
frida-gum-master/gum/backend-darwin/gummemory-darwin.c:gum_alloc_n_pages
mach mmap use __vm_allocate and __vm_map
https://github.com/bminor/glibc/blob/master/sysdeps/mach/hurd/mmap.c
https://github.com/bminor/glibc/blob/master/sysdeps/mach/munmap.c
http://shakthimaan.com/downloads/hurd/A.Programmers.Guide.to.the.Mach.System.Calls.pdf
*/
void MemoryManager::PatchCode(void *dest, void *src, int count) {
vm_address_t dest_page;
vm_size_t offset;
int page_size = memory_manager_cclass(get_page_size)();
// https://www.gnu.org/software/hurd/gnumach-doc/Memory-Attributes.html
dest_page = (zz_addr_t)dest & ~(page_size - 1);
offset = (zz_addr_t)dest - dest_page;
vm_prot_t prot;
vm_inherit_t inherit;
kern_return_t kr;
mach_port_t task_self = mach_task_self();
darwin_memory_helper_cclass(get_memory_info)((void *)dest_page, &prot, &inherit);
// For another method, pelease read `REF`;
// zz_ptr_t code_mmap = mmap(NULL, range_size, PROT_READ | PROT_WRITE,
// MAP_ANON | MAP_SHARED, -1, 0);
// if (code_mmap == MAP_FAILED) {
// return;
// }
void *copy_page = allocateMemoryPage(1 | 2, 1);
kr = vm_copy(task_self, dest_page, page_size, (vm_address_t)copy_page);
if (kr != KERN_SUCCESS) {
// LOG-NEED
return;
}
memcpy((void *)((zz_addr_t)copy_page + offset), src, count);
// SAME: mprotect(code_mmap, range_size, prot);
set_page_memory_permission(copy_page, PROT_EXEC | PROT_READ);
// TODO: need check `memory region` again.
/*
// if only this, `memory region` is `r-x`
vm_protect((vm_map_t)mach_task_self(), 0x00000001816b2030, 16, FALSE, 0x13);
// and with this, `memory region` is `rwx`
*(char *)0x00000001816b01a8 = 'a';
*/
mach_vm_address_t target_address = dest_page;
vm_prot_t cur_protection, max_protection;
kr = mach_vm_remap(task_self, &target_address, page_size, 0, VM_FLAGS_OVERWRITE, task_self,
(mach_vm_address_t)copy_page,
/*copy*/ TRUE, &cur_protection, &max_protection, inherit);
if (kr != KERN_SUCCESS) {
// LOG-NEED
}
// read `REF`
// munmap(code_mmap, range_size);
kr = mach_vm_deallocate(task_self, (mach_vm_address_t)copy_page, page_size);
if (kr != KERN_SUCCESS) {
// LOG-NEED
}
}<file_sep>/HookZz/srcxx/Platforms/backend-posix/PosixThreadManager.h
//
// Created by jmpews on 2018/6/14.
//
#ifndef HOOKZZ_POSIXTHREADMANAGER_H
#define HOOKZZ_POSIXTHREADMANAGER_H
#endif //HOOKZZ_POSIXTHREADMANAGER_H
<file_sep>/HookZz/src/std_kit/std_list.h
#ifndef STD_LIST_H
#define STD_LIST_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef enum { LIST_HEAD, LIST_TAIL } list_direction_t;
typedef struct list_node {
struct list_node *prev;
struct list_node *next;
void *val;
} list_node_t;
typedef struct {
list_node_t *head;
list_node_t *tail;
unsigned int len;
void (*free)(void *val);
int (*match)(void *a, void *b);
} list_t;
typedef struct {
list_node_t *next;
list_direction_t direction;
} list_iterator_t;
// list_node_t
list_node_t *list_node_new(void *val);
// list_t
list_t *list_new();
list_node_t *list_rpush(list_t *self, list_node_t *node);
list_node_t *list_lpush(list_t *self, list_node_t *node);
list_node_t *list_find(list_t *self, void *val);
list_node_t *list_at(list_t *self, int index);
list_node_t *list_rpop(list_t *self);
list_node_t *list_lpop(list_t *self);
void list_remove(list_t *self, list_node_t *node);
void list_destroy(list_t *self);
// llist_iterator_t
list_iterator_t *list_iterator_new(list_t *list, list_direction_t direction);
list_iterator_t *list_iterator_new_from_node(list_node_t *node, list_direction_t direction);
list_node_t *list_iterator_next(list_iterator_t *self);
void list_iterator_destroy(list_iterator_t *self);
#ifdef __cplusplus
}
#endif
#endif // !STD_LIST_H
<file_sep>/HookZz/srcxx/Interceptor.h
//
// Created by z on 2018/6/14.
//
#ifndef HOOKZZ_INTERCEPTOR_H
#define HOOKZZ_INTERCEPTOR_H
#include "MemoryManager.h"
#include "ThreadManager.h"
#include "hookzz.h"
#include <iostream>
#include <vector>
typedef struct _FunctionBackup {
void *address;
int size;
char data[32];
} FunctionBackup;
class Interceptor;
class InterceptorBackend;
struct HookEntryBackend;
typedef struct _HookEntry {
void *target_address;
HookType type;
unsigned int id;
bool isEnabled;
bool isTryNearJump;
bool isNearJump;
PRECALL pre_call;
POSTCALL post_call;
STUBCALL stub_call;
void *replace_call;
void *on_enter_transfer_trampoline;
void *on_enter_trampoline;
void *on_invoke_trampoline;
void *on_leave_trampoline;
void *on_dynamic_binary_instrumentation_trampoline;
FunctionBackup origin_prologue;
struct HookEntryBackend *backend;
Interceptor *interceptor;
} HookEntry;
class Interceptor {
private:
static int t;
static Interceptor *priv_interceptor;
MemoryManager *mm;
public:
bool isSupportRXMemory;
std::vector<HookEntry *> hook_entries;
public:
static Interceptor *GETInstance();
HookEntry *findHookEntry(void *target_address);
void addHookEntry(HookEntry *hook_entry);
void initializeBackend(MemoryManager *mm);
private:
Interceptor() {}
};
#endif //HOOKZZ_INTERCEPTOR_H
<file_sep>/HookZz/src/std_kit/std_list.c
#include "std_list.h"
// list_t
list_t *list_new() {
list_t *self;
if (!(self = malloc(sizeof(list_t))))
return NULL;
self->head = NULL;
self->tail = NULL;
self->free = NULL;
self->match = NULL;
self->len = 0;
return self;
}
void list_destroy(list_t *self) {
unsigned int len = self->len;
list_node_t *next;
list_node_t *curr = self->head;
while (len--) {
next = curr->next;
if (self->free)
self->free(curr->val);
free(curr);
curr = next;
}
free(self);
}
list_node_t *list_rpush(list_t *self, list_node_t *node) {
if (!node)
return NULL;
if (self->len) {
node->prev = self->tail;
node->next = NULL;
self->tail->next = node;
self->tail = node;
} else {
self->head = self->tail = node;
node->prev = node->next = NULL;
}
++self->len;
return node;
}
list_node_t *list_rpop(list_t *self) {
if (!self->len)
return NULL;
list_node_t *node = self->tail;
if (--self->len) {
(self->tail = node->prev)->next = NULL;
} else {
self->tail = self->head = NULL;
}
node->next = node->prev = NULL;
return node;
}
list_node_t *list_lpop(list_t *self) {
if (!self->len)
return NULL;
list_node_t *node = self->head;
if (--self->len) {
(self->head = node->next)->prev = NULL;
} else {
self->head = self->tail = NULL;
}
node->next = node->prev = NULL;
return node;
}
list_node_t *list_lpush(list_t *self, list_node_t *node) {
if (!node)
return NULL;
if (self->len) {
node->next = self->head;
node->prev = NULL;
self->head->prev = node;
self->head = node;
} else {
self->head = self->tail = node;
node->prev = node->next = NULL;
}
++self->len;
return node;
}
list_node_t *list_find(list_t *self, void *val) {
list_iterator_t *it = list_iterator_new(self, LIST_HEAD);
list_node_t *node;
while ((node = list_iterator_next(it))) {
if (self->match) {
if (self->match(val, node->val)) {
list_iterator_destroy(it);
return node;
}
} else {
if (val == node->val) {
list_iterator_destroy(it);
return node;
}
}
}
list_iterator_destroy(it);
return NULL;
}
list_node_t *list_at(list_t *self, int index) {
list_direction_t direction = LIST_HEAD;
if (index < 0) {
direction = LIST_TAIL;
index = ~index;
}
if ((unsigned)index < self->len) {
list_iterator_t *it = list_iterator_new(self, direction);
list_node_t *node = list_iterator_next(it);
while (index--)
node = list_iterator_next(it);
list_iterator_destroy(it);
return node;
}
return NULL;
}
void list_remove(list_t *self, list_node_t *node) {
node->prev ? (node->prev->next = node->next) : (self->head = node->next);
node->next ? (node->next->prev = node->prev) : (self->tail = node->prev);
if (self->free)
self->free(node->val);
free(node);
--self->len;
}
// list_node_t
list_node_t *list_node_new(void *val) {
list_node_t *self;
if (!(self = malloc(sizeof(list_node_t))))
return NULL;
self->prev = NULL;
self->next = NULL;
self->val = val;
return self;
}
// list_iterator_t
list_iterator_t *list_iterator_new(list_t *list, list_direction_t direction) {
list_node_t *node = direction == LIST_HEAD ? list->head : list->tail;
return list_iterator_new_from_node(node, direction);
}
list_iterator_t *list_iterator_new_from_node(list_node_t *node, list_direction_t direction) {
list_iterator_t *self;
if (!(self = malloc(sizeof(list_iterator_t))))
return NULL;
self->next = node;
self->direction = direction;
return self;
}
list_node_t *list_iterator_next(list_iterator_t *self) {
list_node_t *curr = self->next;
if (curr) {
self->next = self->direction == LIST_HEAD ? curr->next : curr->prev;
}
return curr;
}
void list_iterator_destroy(list_iterator_t *self) {
free(self);
self = NULL;
}
<file_sep>/HookZz/srcxx/Platforms/arch-arm64/ARM64Reader.h
//
// Created by jmpews on 2018/6/14.
//
#ifndef HOOKZZ_READERARM64_H
#define HOOKZZ_READERARM64_H
#include "ARM64AssemblyCore.h"
#include "Instruction.h"
#include "hookzz.h"
#include <istream>
#include <streambuf>
#include <vector>
class ARM64AssemblyReader {
public:
void *start_pc;
void *start_address;
std::vector<ARM64InstructionCTX *> instCTXs;
std::vector<char> instBytes;
public:
ARM64AssemblyReader(void *address, void *pc);
void reset(void *address, void *pc);
ARM64InstructionCTX *readInstruction();
};
#endif //HOOKZZ_READERARM64_H
<file_sep>/HookZz/srcxx/Platforms/backend-darwin/DarwinDynamicClosureBridge.cpp
//
// Created by jmpews on 2018/6/15.
//
#include "DarwinDynamicClosureBridge.h"
#include "ClosureBridge.h"
DynamicClosureBridgeInfo *DynamicClosureBridge::allocateDynamicClosureBridge(void *user_data, void *user_code) {return NULL;}
DynamicClosureBridgeTrampolineTable* DynamicClosureBridge::addDynamicClosurceBridgeTrampolineTable() {return NULL;}<file_sep>/HookZz/srcxx/ThreadManager.cpp
//
// Created by jmpews on 2018/6/14.
//
#include "ThreadManager.h"
<file_sep>/HookZz/src/core.h
#ifndef core_h
#define core_h
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "logging.h"
#include "std_kit/std_kit.h"
#include "std_kit/std_macros.h"
/* define a macro to make abbreviation */
#define cclass(class, member) class##_##member
#define cxxclass(class, member) class##member
/* indicate this API's implemention is System dependent */
#define PLATFORM_API
/* indicate this API's implemention is Architecture dependent */
#define ARCH_API
/* indicate this API's implemention is public */
#define PUBLIC_API
/* hidden funtion */
#define VIS_HIDDEN __attribute__((visibility("hidden")))
#endif<file_sep>/HookZz/srcxx/Logging.h
//
// Created by jmpews on 2018/6/15.
//
#ifndef HOOKZZ_GLOGEMULATOR_H
#define HOOKZZ_GLOGEMULATOR_H
#include "CommonClass/DesignPattern/Singleton.h"
#define ENABLE_PRINT_ERROR_STRING 1
#define ENABLE_COLOR_LOG 0
#if ENABLE_COLOR_LOG
#define RED "\x1B[31m"
#define GRN "\x1B[32m"
#define YEL "\x1B[33m"
#define BLU "\x1B[34m"
#define MAG "\x1B[35m"
#define CYN "\x1B[36m"
#define WHT "\x1B[37m"
#define RESET "\x1B[0m"
#else
#define RED ""
#define GRN ""
#define YEL ""
#define BLU ""
#define MAG ""
#define CYN ""
#define WHT ""
#define RESET ""
#endif
#include <errno.h>
#include <stdio.h>
#include <string.h>
// Important!!!
// STDERR before STDOUT, because sync
#define INFO_LOG(fmt, ...) \
do { \
fprintf(stdout, RESET fmt "\n", __VA_ARGS__); \
} while (0)
#define INFO_LOG_STR(MSG) INFO_LOG("%s", MSG)
#define DEBUG_LOG(fmt, ...) \
do { \
fprintf(stdout, RESET fmt "\n", __VA_ARGS__); \
} while (0)
#define DEBUG_LOG_STR(MSG) DEBUG_LOG("%s", MSG)
#define ERROR_LOG(fmt, ...) \
do { \
fprintf(stderr, "======= ERROR LOG ======= \n"); \
fprintf(stderr, \
RED "[!] " \
"%s:%d:%s(): " fmt RESET "\n", \
__FILE__, __LINE__, __func__, __VA_ARGS__); \
if (ENABLE_PRINT_ERROR_STRING) { \
fprintf(stderr, "======= Errno [%d] String ======= \n", errno); \
perror(strerror(errno)); \
} \
fprintf(stderr, "======= Error Log End ======= \n"); \
} while (0)
#define ERROR_LOG_STR(MSG) ERROR_LOG("%s", MSG)
#define COMMON_ERROR_LOG() \
do { \
fprintf(stderr, "======= ERROR LOG ======= \n"); \
fprintf(stderr, RED "[!]error occur at %s:%d:%s()\n", __FILE__, __LINE__, __func__); \
if (ENABLE_PRINT_ERROR_STRING) { \
fprintf(stderr, "======= Errno [%d] String ======= \n", errno); \
perror(strerror(errno)); \
} \
fprintf(stderr, "======= Error Log End ======= \n"); \
} while (0)
class LogControler : public Singleton<LogControler> {
public:
bool isEnableLog;
public:
void enableLog() { isEnableLog = true; };
};
#if defined(__ANDROID__)
#include <android/log.h>
#define DEBUGLOG_COMMON_LOG(fmt, ...) \
do { \
__android_log_print(ANDROID_LOG_INFO, "HookDEBUG", fmt, __VA_ARGS__); \
} while (0);
#else
#define DEBUGLOG_COMMON_LOG(fmt, ...) \
do { \
INFO_LOG(fmt, __VA_ARGS__); \
} while (0);
#endif
#endif //HOOKZZ_GLOGEMULATOR_H
<file_sep>/HookZz/srcxx/Platforms/arch-arm64/ARM64Relocator.h
//
// Created by jmpews on 2018/6/14.
//
#ifndef HOOKZZ_ARM64RELOCATOR_H
#define HOOKZZ_ARM64RELOCATOR_H
#include "ARM64Reader.h"
#include "ARM64Writer.h"
#include "Instruction.h"
#include <iostream>
#include <map>
#include <vector>
class ARM64Relocator {
public:
int limitRelocateInstSize;
int relocatedInstSize;
int needRelocateInputCount;
int doneRelocateInputCount;
ARM64AssemblerWriter *output;
ARM64AssemblyReader *input;
// memory patch can't confirm the code slice length, so last setp of memory patch need repair the literal instruction.
std::vector<ARM64InstructionCTX *> literalInstCTXs;
std::map<int, int> indexRelocatedInputOutput;
public:
ARM64Relocator(ARM64AssemblyReader *input, ARM64AssemblerWriter *output);
void reset();
void tryRelocate(void *address, int bytes_min, int *bytes_max);
void relocateTo(void *target_address);
void doubleWrite(void *target_address);
void registerLiteralInstCTX(ARM64InstructionCTX *instCTX);
void relocateWrite();
void relocateWriteAll();
void rewrite_LoadLiteral(ARM64InstructionCTX *instCTX);
void rewrite_BaseCmpBranch(ARM64InstructionCTX *instCTX);
void rewrite_BranchCond(ARM64InstructionCTX *instCTX);
void rewrite_B(ARM64InstructionCTX *instCTX);
void rewrite_BL(ARM64InstructionCTX *instCTX);
};
#endif //HOOKZZ_ARM64RELOCATOR_H
<file_sep>/HookZz/srcxx/Platforms/arch-arm64/ARM64Register.cpp
//
// Created by jmpews on 2018/6/14.
//
#include "ARM64Register.h"
void DescribeARM64Reigster(ARM64Reg reg, ARM64RegInfo *ri) {
if (reg >= ARM64_REG_X0 && reg <= ARM64_REG_X28) {
ri->isInteger = true;
ri->width = 64;
ri->meta = ARM64_REG_X0 + (reg - ARM64_REG_X0);
} else if (reg == ARM64_REG_X29 || reg == ARM64_REG_FP) {
ri->isInteger = true;
ri->width = 64;
ri->meta = ARM64_REG_X29;
} else if (reg == ARM64_REG_X30 || reg == ARM64_REG_LR) {
ri->isInteger = true;
ri->width = 64;
ri->meta = ARM64_REG_X30;
} else if (reg == ARM64_REG_SP) {
ri->isInteger = true;
ri->width = 64;
ri->meta = ARM64_REG_X31;
} else {
ri->index = 0;
// LOG-NEED
}
ri->index = ri->meta - ARM64_REG_X0;
}
ARM64Reg DisDescribeARM64Reigster(int regIndex, int regWith) {
if (regWith == 0)
regWith = 64;
return (ARM64Reg)(regIndex - (int)ARM64_REG_X0);
}<file_sep>/HookZz/CMakeLists.txt
cmake_minimum_required(VERSION 3.5)
project(HookZz)
include(cmake/Util.cmake)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_C_STANDARD 11)
enable_language(ASM)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=gnu11")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
set(CMAKE_ASM_FLAGS "-arch arm64 -fembed-bitcode")
option(CXX OFF "use cxx source")
option(USE_POSIX_IN_DARWIN OFF "use posix function in darwin")
option(X_LOG ON "enable debug log")
option(X_SHARED ON "build shared library")
if(X_LOG)
ADD_DEFINITIONS(-DX_LOG=1)
else()
ADD_DEFINITIONS(-DX_LOG=0)
endif()
if(X_BACKEND STREQUAL "Darwin")
set(SYSTEM.Darwin 1)
elseif(X_BACKEND STREQUAL "Linux")
set(SYSTEM.Linux 1)
endif()
if(X_PLATFORM STREQUAL "iOS")
set(SYSTEM.iOS 1)
elseif(X_PLATFORM STREQUAL "Android")
set(SYSTEM.Android 1)
else()
message(FATAL_ERROR "[!] ONLY SUPPORT [iOS|Android] X_PLATFORM")
endif()
if(X_ARCH STREQUAL "arm" OR X_ARCH STREQUAL "armv7")
set(CMAKE_SYSTEM_PROCESSOR arm)
set(PROCESSOR.arm 1)
elseif(X_ARCH STREQUAL "aarch64" OR X_ARCH STREQUAL "arm64" OR X_ARCH STREQUAL "armv8")
set(CMAKE_SYSTEM_PROCESSOR aarch64)
set(PROCESSOR.aarch64 1)
else()
message(FATAL_ERROR "[!] ONLY SUPPORT [[arm|armv7]|[aarch64|arm64|armv8]] X_ARCH")
endif()
include(cmake/Macros.cmake)
set(GLOBAL.SOURCE_FILE)
set(GLOBAL.SOURCE_DIR)
set(GLOBAL.HEADER_FILE)
set(GLOBAL.HEADER_DIR)
if(CXX)
else()
# build c source
set(HookZz.Path .)
set(GLOBAL.SOURCE_DIR
${HookZz.Path}/src
${HookZz.Path}/src/std_kit
${HookZz.Path}/src/thread_support
${HookZz.Path}/src/compiler-rt/lib/builtins
)
set(GLOBAL.HEADER_DIR
${HookZz.Path}/include
)
if(SYSTEM.Android)
set(GLOBAL.SOURCE_DIR ${GLOBAL.SOURCE_DIR}
${HookZz.Path}/src/platforms/backend-posix
${HookZz.Path}/src/platforms/backend-linux
)
add_definitions(-DDYNAMIC_CLOSURE_BRIDGE=0)
elseif(SYSTEM.Darwin)
set(GLOBAL.SOURCE_DIR ${GLOBAL.SOURCE_DIR}
${HookZz.Path}/src/platforms/backend-posix
${HookZz.Path}/src/platforms/backend-darwin
)
add_definitions(-DDYNAMIC_CLOSURE_BRIDGE=1)
if(USE_POSIX_IN_DARWIN)
add_definitions(-DUSE_POSIX_IN_DARWIN=1)
else()
add_definitions(-DUSE_POSIX_IN_DARWIN=0)
endif()
endif()
if(PROCESSOR.aarch64)
set(GLOBAL.SOURCE_DIR ${GLOBAL.SOURCE_DIR}
${HookZz.Path}/src/platforms/arch-arm64
)
endif()
# *.c
search_suffix_files("c" GLOBAL.SOURCE_DIR HookZz.SOURCE_C)
# *.S
search_suffix_files("S" GLOBAL.SOURCE_DIR HookZz.SOURCE_ASSEMBLY)
# *.h
search_suffix_files("h" GLOBAL.SOURCE_DIR HookZz.HEADER_H)
set(GLOBAL.SOURCE_FILE ${GLOBAL.SOURCE_FILE} ${HookZz.SOURCE_C} ${HookZz.SOURCE_ASSEMBLY})
set(GLOBAL.HEADER_FILE ${GLOBAL.HEADER_FILE} ${HookZz.HEADER_H} include/hookzz.h)
endif()
include_directories(${GLOBAL.HEADER_DIR} ${GLOBAL.SOURCE_DIR})
if(X_SHARED)
# build shared library
add_library(hookzz SHARED ${GLOBAL.SOURCE_FILE} ${GLOBAL.HEADER_FILE})
else()
# build static library
add_library(hookzz STATIC ${GLOBAL.SOURCE_FILE} ${GLOBAL.HEADER_FILE})
endif()
target_include_directories(hookzz PUBLIC ./include)
if(CMAKE_SYSTEM_NAME MATCHES "^Android")
target_link_libraries(hookzz log)
endif()<file_sep>/HookZz/srcxx/Platforms/arch-arm64/Instruction.h
//
// Created by jmpews on 2018/6/14.
//
#ifndef HOOKZZ_INSTRUCTION_H
#define HOOKZZ_INSTRUCTION_H
#include "hookzz.h"
typedef struct _ARM64InstructionCTX {
zz_addr_t pc;
zz_addr_t address;
uint8_t size;
uint32_t bytes;
} ARM64InstructionCTX;
#endif //HOOKZZ_INSTRUCTION_H
<file_sep>/HookZz/src/platforms/arch-arm64/closure-bridge-arm64.c
#include "closure_bridge.h"
#include "core.h"
#include "memory_manager.h"
#define closure_bridge_trampoline_template_length (7 * 4)
void ClosureBridgeCClass(InitializeTablePage)(ClosureBridgeTrampolineTable *table, void *page_address) {
memory_manager_t *memory_manager = memory_manager_cclass(shared_instance)();
memory_manager_cclass(set_page_permission)(page_address, PROT_RW_, 1);
int page_size = memory_manager_cclass(get_page_size)();
int t = page_size / closure_bridge_trampoline_template_length;
void *copy_address = page_address;
for (int i = 0; i < t; ++i) {
copy_address = (void *)((intptr_t)page_address + i * closure_bridge_trampoline_template_length);
memcpy(copy_address, (void *)closure_bridge_trampoline_template, closure_bridge_trampoline_template_length);
}
memory_manager_cclass(set_page_permission)(page_address, PROT_R_X, 1);
table->entry = page_address;
table->trampoline_page = page_address;
table->used_count = 0;
table->free_count = (uint16_t)t;
}
void ClosureBridgeCClass(InitializeClosureBridgeInfo)(ClosureBridgeTrampolineTable *table, ClosureBridgeInfo *cb_info,
void *user_data, void *user_code) {
assert(cb_info);
assert(table);
uint16_t trampoline_used_count = table->used_count;
void *redirect_trampoline =
(void *)((intptr_t)table->trampoline_page + closure_bridge_trampoline_template_length * trampoline_used_count);
cb_info->user_code = user_code;
cb_info->user_data = user_data;
cb_info->redirect_trampoline = redirect_trampoline;
table->used_count++;
table->free_count--;
memory_manager_cclass(set_page_permission)(table->trampoline_page, PROT_RW_, 1);
// bind data to trampline
void *tmp = (void *)((intptr_t)cb_info->redirect_trampoline + 4 * 3);
memcpy(tmp, &cb_info, sizeof(ClosureBridgeInfo *));
// set trampoline to bridge
void *tmpX = (void *)closure_bridge_template;
tmp = (void *)((intptr_t)cb_info->redirect_trampoline + 4 * 5);
memcpy(tmp, &tmpX, sizeof(void *));
memory_manager_cclass(set_page_permission)(table->trampoline_page, PROT_R_X, 1);
}
<file_sep>/HookZz/src/platforms/backend-darwin/memory-manager-darwin.c
#include <errno.h>
#include <mach-o/dyld.h>
#include <mach/mach.h>
#include <mach/vm_map.h>
#include <sys/mman.h>
#include "core.h"
#include "mach_vm.h"
#include "memory-helper-darwin.h"
#include "memory_manager.h"
extern void __clear_cache(void *beg, void *end);
PLATFORM_API bool memory_manager_cclass(is_support_allocate_rx_memory)(memory_manager_t *self) { return true; }
PLATFORM_API void memory_manager_cclass(get_process_memory_layout)(memory_manager_t *self) {
mach_msg_type_number_t count;
struct vm_region_submap_info_64 info;
vm_size_t nesting_depth;
kern_return_t kr = KERN_SUCCESS;
vm_address_t tmp_addr = 0;
vm_size_t tmp_size = 0;
while (1) {
count = VM_REGION_SUBMAP_INFO_COUNT_64;
kr = vm_region_recurse_64(mach_task_self(), &tmp_addr, &tmp_size, (natural_t *)&nesting_depth,
(vm_region_info_64_t)&info, &count);
if (kr == KERN_INVALID_ADDRESS) {
break;
} else if (kr) {
mach_error("vm_region:", kr);
break; /* last region done */
}
if (info.is_submap) {
nesting_depth++;
} else {
MemoryBlock *mb = SAFE_MALLOC_TYPE(MemoryBlock);
list_rpush(self->process_memory_layout, list_node_new(mb));
tmp_addr += tmp_size;
mb->address = (void *)((zz_addr_t)tmp_addr - tmp_size);
mb->size = tmp_size;
mb->prot = info.protection;
}
}
}
#if !USE_POSIX_IN_DARWIN
PLATFORM_API int memory_manager_cclass(get_page_size)() {
int page_size = darwin_memory_helper_cclass(get_page_size)();
return page_size;
}
#endif
#if !USE_POSIX_IN_DARWIN
PLATFORM_API void memory_manager_cclass(set_page_permission)(void *page_address, int prot, int n) {
darwin_memory_helper_cclass(set_page_permission)(page_address, prot, n);
return;
}
#endif
#if !USE_POSIX_IN_DARWIN
PLATFORM_API void *memory_manager_cclass(allocate_page)(memory_manager_t *self, int prot, int n) {
vm_address_t page_address;
kern_return_t kr;
vm_size_t page_size;
page_size = darwin_memory_helper_cclass(get_page_size)();
/* use vm_allocate not mmap */
kr = mach_vm_allocate(mach_task_self(), (mach_vm_address_t *)&page_address, page_size * n, VM_FLAGS_ANYWHERE);
/* set page permission */
darwin_memory_helper_cclass(set_page_permission)((void *)page_address, prot, n);
return (void *)page_address;
}
#endif
#if !USE_POSIX_IN_DARWIN
/*
REF:
substitute/lib/darwin/execmem.c:execmem_foreign_write_with_pc_patch
frida-gum-master/gum/gummemory.c:gum_memory_patch_code
frida-gum-master/gum/backend-darwin/gummemory-darwin.c:gum_alloc_n_pages
mach mmap use __vm_allocate and __vm_map
https://github.com/bminor/glibc/blob/master/sysdeps/mach/hurd/mmap.c
https://github.com/bminor/glibc/blob/master/sysdeps/mach/munmap.c
http://shakthimaan.com/downloads/hurd/A.Programmers.Guide.to.the.Mach.System.Calls.pdf
*/
PLATFORM_API void memory_manager_cclass(patch_code)(memory_manager_t *self, void *dest, void *src, int count) {
vm_address_t dest_page;
vm_size_t offset;
int page_size = memory_manager_cclass(get_page_size)();
// https://www.gnu.org/software/hurd/gnumach-doc/Memory-Attributes.html
dest_page = (zz_addr_t)dest & ~(page_size - 1);
offset = (zz_addr_t)dest - dest_page;
vm_prot_t prot;
vm_inherit_t inherit;
kern_return_t kr;
mach_port_t task_self = mach_task_self();
darwin_memory_helper_cclass(get_memory_info)((void *)dest_page, &prot, &inherit);
// For another method, pelease read `REF`;
// zz_ptr_t code_mmap = mmap(NULL, range_size, PROT_READ | PROT_WRITE,
// MAP_ANON | MAP_SHARED, -1, 0);
// if (code_mmap == MAP_FAILED) {
// return;
// }
void *copy_page = memory_manager_cclass(allocate_page)(self, PROT_RW_, 1);
kr = vm_copy(task_self, (vm_address_t)dest_page, page_size, (vm_address_t)copy_page);
if (kr != KERN_SUCCESS) {
ERROR_LOG_STR("[[memory_manager_cclass(patch_code)]]");
return;
}
memcpy((void *)((zz_addr_t)copy_page + offset), src, count);
// SAME: mprotect(code_mmap, range_size, prot);
darwin_memory_helper_cclass(set_page_permission)(copy_page, PROT_R_X, 1);
// TODO: need check `memory region` again.
// // if only with this, `memory region` is `r-x`
// vm_protect((vm_map_t)mach_task_self(), 0x00000001816b2030, 16, FALSE, 0x13);
// // and with this, `memory region` is `rwx`
// *(char *)0x00000001816b01a8 = 'a';
mach_vm_address_t target_address = (vm_address_t)dest_page;
vm_prot_t cur_protection, max_protection;
kr = mach_vm_remap(task_self, &target_address, page_size, 0, VM_FLAGS_OVERWRITE, task_self,
(mach_vm_address_t)copy_page,
/*copy*/ TRUE, &cur_protection, &max_protection, inherit);
__clear_cache((void *)dest, (void *)((uintptr_t)dest + count));
if (kr != KERN_SUCCESS) {
ERROR_LOG_STR("[[memory_manager_cclass(patch_code)]]");
// LOG-NEED
}
// read `REF`
// munmap(code_mmap, range_size);
kr = mach_vm_deallocate(task_self, (mach_vm_address_t)copy_page, page_size);
if (kr != KERN_SUCCESS) {
ERROR_LOG_STR("[[memory_manager_cclass(patch_code)]]");
}
}
#endif
<file_sep>/HookZz/srcxx/Platforms/arch-arm64/ARM64Helper.h
//
// Created by jmpews on 2018/6/15.
//
#ifndef HOOKZZ_ARM64HELPER_H
#define HOOKZZ_ARM64HELPER_H
#endif //HOOKZZ_ARM64HELPER_H
<file_sep>/HookZz/src/platforms/arch-arm64/reader-arm64.h
#ifndef platforms_arch_arm64_reader_arm64_h
#define platforms_arch_arm64_reader_arm64_h
#include "ARM64AssemblyCore.h"
#include "core.h"
#include "instruction.h"
#include "std_kit/std_buffer_array.h"
#include "std_kit/std_kit.h"
#include "std_kit/std_list.h"
typedef struct _ARM64AssemblyReader {
void *start_pc;
void *start_address;
list_t *instCTXs;
buffer_array_t *inst_bytes;
} ARM64AssemblyReader;
#define arm64_assembly_reader_cclass(member) cclass(arm64_assembly_reader, member)
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
ARM64AssemblyReader *arm64_assembly_reader_cclass(new)(void *address, void *pc);
void arm64_assembly_reader_cclass(reset)(ARM64AssemblyReader *self, void *address, void *pc);
ARM64InstructionCTX *arm64_assembly_reader_cclass(read_inst)(ARM64AssemblyReader *self);
#ifdef __cplusplus
}
#endif //__cplusplus
#endif<file_sep>/HookZz/srcxx/Platforms/arch-arm64/ARM64InterceptorRoutingTrampoline.cpp
//
// Created by jmpews on 2018/6/14.
//
#include "ARM64InterceptorBackend.h"
#include "ClosureBridge.h"
#include "CommonClass/DesignPattern/Singleton.h"
#include "Logging.h"
#include "Macros.h"
#include "custom-bridge-handler-arm64.h"
#include <string.h>
#define ARM64_TINY_REDIRECT_SIZE 4
#define ARM64_FULL_REDIRECT_SIZE 16
#define ARM64_NEAR_JUMP_RANGE ((1 << 25) << 2)
void Interceptor::initializeBackend(MemoryManager *) {
if (!memory_manager->is_support_rx_memory) {
// LOG-NEED
}
ARM64InterceptorBackend *backend = new (ARM64InterceptorBackend);
backend->readerARM64 = new ARM64AssemblyReader(0, 0);
backend->writerARM64 = new ARM64AssemblerWriter(0);
backend->relocatorARM64 = new ARM64Relocator(backend->readerARM64, backend->writerARM64);
backend->memory_manager = memory_manager;
this->backend = backend;
}
void ARM64InterceptorBackend::Prepare(HookEntry *entry) {
int limit_relocate_inst_size = 0;
ARM64HookEntryBackend *entry_backend = new (ARM64HookEntryBackend);
entry->backend = (struct HookEntryBackend *)entry_backend;
if (entry->isTryNearJump) {
entry_backend->limit_relocate_inst_size = ARM64_TINY_REDIRECT_SIZE;
} else {
// check the first few instructions, preparatory work of instruction-fix
relocatorARM64->tryRelocate(entry->target_address, ARM64_FULL_REDIRECT_SIZE, &limit_relocate_inst_size);
if (limit_relocate_inst_size != 0 && limit_relocate_inst_size > ARM64_TINY_REDIRECT_SIZE &&
limit_relocate_inst_size < ARM64_FULL_REDIRECT_SIZE) {
entry->isNearJump = true;
entry_backend->limit_relocate_inst_size = ARM64_TINY_REDIRECT_SIZE;
} else if (limit_relocate_inst_size != 0 && limit_relocate_inst_size < ARM64_TINY_REDIRECT_SIZE) {
return;
} else {
entry_backend->limit_relocate_inst_size = ARM64_FULL_REDIRECT_SIZE;
}
}
relocatorARM64->limitRelocateInstSize = entry_backend->limit_relocate_inst_size;
// save original prologue
memcpy(entry->origin_prologue.data, entry->target_address, entry_backend->limit_relocate_inst_size);
entry->origin_prologue.size = entry_backend->limit_relocate_inst_size;
entry->origin_prologue.address = entry->target_address;
// arm64_relocator initialize
relocatorARM64->input->reset(entry->target_address, entry->target_address);
}
void ARM64InterceptorBackend::BuildForEnterTransfer(HookEntry *entry) {
ARM64HookEntryBackend *entry_backend = (ARM64HookEntryBackend *)entry->backend;
RetStatus status = RS_SUCCESS;
relocatorARM64->output->reset(0);
relocatorARM64->output->put_ldr_reg_imm(ARM64_REG_X17, 0x8);
relocatorARM64->output->put_br_reg(ARM64_REG_X17);
if (entry->hook_type == HOOK_TYPE_FUNCTION_via_REPLACE) {
relocatorARM64->output->putBytes(&entry->replace_call, sizeof(void *));
} else if (entry->hook_type == HOOK_TYPE_INSTRUCTION_via_DBI) {
relocatorARM64->output->putBytes(&entry->on_dynamic_binary_instrumentation_trampoline, sizeof(void *));
} else {
relocatorARM64->output->putBytes(&entry->on_enter_trampoline, sizeof(void *));
}
if (entry_backend->limit_relocate_inst_size == ARM64_TINY_REDIRECT_SIZE) {
MemoryManager *memory_manager = Singleton<MemoryManager>::GetInstance();
CodeCave *cc = memory_manager->searchNearCodeCave(entry->target_address, ARM64_NEAR_JUMP_RANGE,
relocatorARM64->output->instBytes.size());
relocatorARM64->output->NearPatchTo((void *)cc->address, ARM64_NEAR_JUMP_RANGE);
entry->on_enter_transfer_trampoline = (void *)cc->address;
delete (cc);
} else {
MemoryManager *memory_manager = Singleton<MemoryManager>::GetInstance();
CodeSlice *cs = memory_manager->allocateCodeSlice(relocatorARM64->output->instBytes.size());
relocatorARM64->output->PatchTo(cs->data);
entry->on_enter_transfer_trampoline = cs->data;
delete (cs);
}
}
void ARM64InterceptorBackend::BuildForEnter(HookEntry *entry) {
ARM64HookEntryBackend *entry_backend = (ARM64HookEntryBackend *)entry->backend;
RetStatus status = RS_SUCCESS;
if (entry->hook_type == HOOK_TYPE_FUNCTION_via_GOT) {
DynamicClosureBridgeInfo *dcbInfo;
DynamicClosureBridge *dcb = Singleton<DynamicClosureBridge>::GetInstance();
dcbInfo =
dcb->allocateDynamicClosureBridge((void *)entry, (void *)dynamic_context_begin_invocation_bridge_handler);
if (dcbInfo == NULL) {
ERROR_LOG_STR("build closure bridge failed!!!");
}
entry->on_enter_trampoline = dcbInfo->redirect_trampoline;
} else {
ClosureBridgeInfo *cbInfo;
ClosureBridge *cb = Singleton<ClosureBridge>::GetInstance();
cbInfo = cb->allocateClosureBridge(entry, (void *)context_begin_invocation_bridge_handler);
if (cbInfo == NULL) {
ERROR_LOG_STR("build closure bridge failed!!!");
}
entry->on_enter_trampoline = cbInfo->redirect_trampoline;
}
// build the double trampline aka enter_transfer_trampoline
if (entry_backend && entry_backend->limit_relocate_inst_size == ARM64_TINY_REDIRECT_SIZE) {
if (entry->hook_type != HOOK_TYPE_FUNCTION_via_GOT) {
BuildForEnterTransfer(entry);
}
}
}
void ARM64InterceptorBackend::BuildForDynamicBinaryInstrumentation(HookEntry *entry) {
ARM64HookEntryBackend *entry_backend = (ARM64HookEntryBackend *)entry->backend;
ClosureBridgeInfo *cbInfo;
ClosureBridge *cb = Singleton<ClosureBridge>::GetInstance();
cbInfo = cb->allocateClosureBridge(entry, (void *)dynamic_binary_instrumentationn_bridge_handler);
if (cbInfo == NULL) {
ERROR_LOG_STR("build closure bridge failed!!!");
}
entry->on_dynamic_binary_instrumentation_trampoline = cbInfo->redirect_trampoline;
// build the double trampline aka enter_transfer_trampoline
if (entry_backend->limit_relocate_inst_size == ARM64_TINY_REDIRECT_SIZE) {
if (entry->hook_type != HOOK_TYPE_FUNCTION_via_GOT) {
BuildForEnterTransfer(entry);
}
}
}
void ARM64InterceptorBackend::BuildForLeave(HookEntry *entry) {
ARM64HookEntryBackend *entry_backend = (ARM64HookEntryBackend *)entry->backend;
if (entry->hook_type == HOOK_TYPE_FUNCTION_via_GOT) {
DynamicClosureBridgeInfo *dcbInfo;
DynamicClosureBridge *dcb = Singleton<DynamicClosureBridge>::GetInstance();
dcbInfo = dcb->allocateDynamicClosureBridge(entry, (void *)dynamic_context_end_invocation_bridge_handler);
if (dcbInfo == NULL) {
ERROR_LOG_STR("build closure bridge failed!!!");
}
entry->on_leave_trampoline = dcbInfo->redirect_trampoline;
} else {
ClosureBridgeInfo *cbInfo;
ClosureBridge *cb = Singleton<ClosureBridge>::GetInstance();
cbInfo = cb->allocateClosureBridge(entry, (void *)context_end_invocation_bridge_handler);
if (cbInfo == NULL) {
ERROR_LOG_STR("build closure bridge failed!!!");
}
entry->on_leave_trampoline = cbInfo->redirect_trampoline;
}
}
void ARM64InterceptorBackend::BuildForInvoke(HookEntry *entry) {
ARM64HookEntryBackend *entry_backend = (ARM64HookEntryBackend *)entry->backend;
RetStatus status = RS_SUCCESS;
zz_addr_t originNextInstAddress;
relocatorARM64->input->reset(entry->target_address, entry->target_address);
relocatorARM64->output->reset(0);
relocatorARM64->reset();
do {
relocatorARM64->relocateWrite();
} while (relocatorARM64->indexRelocatedInputOutput.size() < relocatorARM64->input->instCTXs.size());
assert(entry_backend->limit_relocate_inst_size == relocatorARM64->input->instCTXs.size());
originNextInstAddress = (zz_addr_t)entry->target_address + relocatorARM64->input->instCTXs.size();
relocatorARM64->output->put_ldr_reg_imm(ARM64_REG_X17, 0x8);
relocatorARM64->output->put_br_reg(ARM64_REG_X17);
relocatorARM64->output->putBytes(&originNextInstAddress, sizeof(void *));
MemoryManager *memory_manager = MemoryManager::GetInstance();
CodeSlice *cs = memory_manager->allocateCodeSlice(relocatorARM64->output->instBytes.size());
relocatorARM64->output->RelocatePatchTo(relocatorARM64, cs->data);
entry->on_invoke_trampoline = cs->data;
delete (cs);
// debug log
if (1) {
char buffer[1024] = {};
char origin_prologue[256] = {0};
int t = 0;
sprintf(buffer + strlen(buffer), "\n======= ARM64 Invoke Logging ======= \n");
for (int i = 0; i < relocatorARM64->input->instCTXs.size(); i++) {
sprintf(origin_prologue + t, "0x%.2x ", relocatorARM64->input->instCTXs[i]->bytes);
}
sprintf(buffer + strlen(buffer), "\tARM Origin Prologue: %s\n", origin_prologue);
sprintf(buffer + strlen(buffer), "\tInput Address: %p\n", relocatorARM64->input->start_address);
sprintf(buffer + strlen(buffer), "\tInput Instruction Count: %lu\n", relocatorARM64->input->instCTXs.size());
sprintf(buffer + strlen(buffer), "\tInput Instruction ByteSize: %lu\n",
relocatorARM64->input->instBytes.size());
sprintf(buffer + strlen(buffer), "\tOutput Address: %p\n", entry->on_invoke_trampoline);
sprintf(buffer + strlen(buffer), "\tOutput Instruction Count: %lu\n", relocatorARM64->output->instCTXs.size());
sprintf(buffer + strlen(buffer), "\tOutput Instruction ByteSize: %lu\n",
relocatorARM64->output->instBytes.size());
for (auto it : relocatorARM64->indexRelocatedInputOutput) {
sprintf(buffer + strlen(buffer), "\t\tinput(%p) -> relocated ouput(%p), relocate %d instruction\n",
(void *)(relocatorARM64->input->instCTXs[it.first]->address),
(void *)(relocatorARM64->output->instCTXs[it.second]->address), 0);
}
DEBUGLOG_COMMON_LOG("%s", buffer);
}
}
void ARM64InterceptorBackend::ActiveTrampoline(HookEntry *entry) {
ARM64HookEntryBackend *entry_backend = (ARM64HookEntryBackend *)entry->backend;
RetStatus status = RS_SUCCESS;
if (entry->hook_type == HOOK_TYPE_FUNCTION_via_REPLACE) {
if (entry_backend->limit_relocate_inst_size == ARM64_TINY_REDIRECT_SIZE) {
relocatorARM64->output->put_b_imm((zz_addr_t)entry->on_enter_transfer_trampoline -
(zz_addr_t)relocatorARM64->output->start_pc);
} else {
relocatorARM64->output->put_ldr_reg_imm(ARM64_REG_X17, 0x8);
relocatorARM64->output->put_br_reg(ARM64_REG_X17);
relocatorARM64->output->putBytes(&entry->on_enter_transfer_trampoline, sizeof(void *));
}
} else {
if (entry_backend->limit_relocate_inst_size == ARM64_TINY_REDIRECT_SIZE) {
relocatorARM64->output->put_b_imm((zz_addr_t)entry->on_enter_transfer_trampoline -
(zz_addr_t)relocatorARM64->output->start_pc);
} else {
relocatorARM64->output->put_ldr_reg_imm(ARM64_REG_X17, 0x8);
relocatorARM64->output->put_br_reg(ARM64_REG_X17);
relocatorARM64->output->putBytes(&entry->on_enter_trampoline, sizeof(void *));
}
}
}<file_sep>/HookZz/src/platforms/arch-arm64/register-arm64.c
#include "register-arm64.h"
#include "std_kit/std_kit.h"
#include <string.h>
void arm64_register_describe(ARM64Reg reg, ARM64RegInfo *ri) {
if (reg >= ARM64_REG_X0 && reg <= ARM64_REG_X28) {
ri->is_integer = true;
ri->width = 64;
ri->meta = ARM64_REG_X0 + (reg - ARM64_REG_X0);
} else if (reg == ARM64_REG_X29 || reg == ARM64_REG_FP) {
ri->is_integer = true;
ri->width = 64;
ri->meta = ARM64_REG_X29;
} else if (reg == ARM64_REG_X30 || reg == ARM64_REG_LR) {
ri->is_integer = true;
ri->width = 64;
ri->meta = ARM64_REG_X30;
} else if (reg == ARM64_REG_SP) {
ri->is_integer = true;
ri->width = 64;
ri->meta = ARM64_REG_X31;
} else {
ri->index = 0;
ERROR_LOG_STR("arm64_register_describe error.");
}
ri->index = ri->meta - ARM64_REG_X0;
}
ARM64Reg arm64_register_disdescribe(int index, int width) {
if (width == 0)
width = 64;
return (ARM64Reg)(index - (int)ARM64_REG_X0);
}
<file_sep>/HookZz/srcxx/Trampoline.h
//
// Created by z on 2018/6/14.
//
#ifndef HOOKZZ_TRAMPOLINE_H
#define HOOKZZ_TRAMPOLINE_H
class Trampoline {};
#endif //HOOKZZ_TRAMPOLINE_H
<file_sep>/HookZz/src/std_kit/README.md
**0x1 std_list**
[std_list](https://github.com/clibs/list/blob/master/src/list.h)<file_sep>/HookZz/srcxx/StackManager.h
//
// Created by jmpews on 2018/6/14.
//
#ifndef HOOKZZ_STACKMANAGER_H
#define HOOKZZ_STACKMANAGER_H
#include <map>
#include "hookzz.h"
#include "ThreadManager.h"
typedef struct _CallStackEntry {
char *key;
void *value;
} CallStackEntry;
class ThreadStackManager;
class CallStackManager {
public:
int id;
class ThreadStackManager *thread_stack;
zz_ptr_t retAddr;
std::map<char *, void *> kv_map;
public:
void setCallStackValue(char *key, void *value);
void *getCallStackValue(char *key);
};
class ThreadStackManager {
public:
int id;
ThreadLocalKey *thread_local_key;
std::vector<CallStackManager *> call_stacks;
public:
ThreadStackManager(ThreadLocalKey *key);
static ThreadStackManager *initializeFromThreadLocalKey(ThreadLocalKey *key);
void pushCallStack(CallStackManager *call_stack);
CallStackManager *popCallStack();
};
#endif //HOOKZZ_STACKMANAGER_H
<file_sep>/HookZz/srcxx/ClosureBridge.h
//
// Created by jmpews on 2018/6/14.
//
#ifndef HOOKZZ_CLOSUREBRIDGE_H
#define HOOKZZ_CLOSUREBRIDGE_H
#include <stdint.h>
#include <vector>
#define PRIAVE
#include "CommonClass/DesignPattern/Singleton.h"
#include "Core.h"
#include "hookzz.h"
typedef struct _ClosureBridgeInfo {
void *user_code;
void *user_data;
void *redirect_trampoline;
} ClosureBridgeInfo;
typedef struct _ClosureBridgeTrampolineTable {
void *entry;
void *trampoline_page;
uint16_t used_count;
uint16_t free_count;
} ClosureBridgeTrampolineTable;
class ClosureBridge {
public:
std::vector<ClosureBridgeInfo *> bridge_infos;
std::vector<ClosureBridgeTrampolineTable *> trampoline_tables;
public:
ClosureBridgeInfo *allocateClosureBridge(void *user_data, void *user_code);
ClosureBridgeTrampolineTable *allocateClosureBridgeTrampolineTable();
};
typedef struct _DynamicClosureBridgeInfo {
void *trampolineTo PRIAVE;
void *user_code;
void *user_data;
void *redirect_trampoline;
} DynamicClosureBridgeInfo;
typedef struct _DynamicClosureTrampolineTable {
void *entry;
void *trampoline_page;
void *data_page;
uint16_t used_count;
uint16_t free_count;
} DynamicClosureBridgeTrampolineTable;
class DynamicClosureBridge {
public:
std::vector<DynamicClosureBridgeInfo *> bridge_infos;
std::vector<DynamicClosureBridgeTrampolineTable *> trampoline_tables;
public:
DynamicClosureBridgeInfo *allocateDynamicClosureBridge(void *user_data, void *user_code);
DynamicClosureBridgeTrampolineTable *addDynamicClosurceBridgeTrampolineTable();
};
typedef void (*USER_CODE_CALL)(RegState *rs, ClosureBridgeInfo *cbInfo);
typedef void (*DYNAMIC_USER_CODE_CALL)(RegState *rs, DynamicClosureBridgeInfo *dcbInfo);
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
void closure_bridge_trampoline_template();
void closure_bridge_template();
void dynamic_closure_bridge_template();
void dynamic_closure_trampoline_table_page();
#ifdef __cplusplus
}
#endif //__cplusplus
#endif //HOOKZZ_CLOSUREBRIDGE_H
<file_sep>/HookZz/src/instruction_relocation.h
#include "interceptor.h"
#include "macros.h"
PLATFORM_API void instruction_relocation_inspect(void *dest, int *limit_length_PTR);
PLATFORM_API void instruction_relocation_build(void *dest, void *src, int length);<file_sep>/HookZz/srcxx/Platforms/arch-arm64/custom-bridge-handler-arm64.h
//
// Created by z on 2018/4/7.
//
#ifndef CUSTOM_BRIDGE_HANDLER_H
#define CUSTOM_BRIDGE_HANDLER_H
#include "ClosureBridge.h"
#include "hookzz.h"
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
void dynamic_common_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcbInfo);
void common_bridge_handler(RegState *rs, ClosureBridgeInfo *cbInfo);
void dynamic_context_begin_invocation_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcbInfo);
void dynamic_context_end_invocation_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcbInfo);
void context_end_invocation_bridge_handler(RegState *rs, ClosureBridgeInfo *cbInfo);
void context_begin_invocation_bridge_handler(RegState *rs, ClosureBridgeInfo *cbInfo);
void dynamic_binary_instrumentationn_bridge_handler(RegState *rs, ClosureBridgeInfo *cbInfo);
#ifdef __cplusplus
}
#endif //__cplusplus
#endif //CUSTOM_BRIDGE_HANDLER_H
| e462bebfb73f54006c88280e6f6de8de62f32ab0 | [
"CMake",
"Markdown",
"Makefile",
"C",
"C++"
] | 104 | C | haidragon/ios | ac54b33fdc7472b9278abf06eeb44098b3547fc3 | b60ff1c02226acb79de67a9347ba25439c505525 |
refs/heads/master | <file_sep># despesas_pessoais
Projeto de despesas pessoais utilizando flutter.
## Getting Started
Este projeto tem o objetivo total acadêmico, e foi desenvolvido com o foco em aprender sobre os
principais conceitos do Flutter.
É um projeto de despesas pessoais onde o usuário irá cadastrar as despesas diárias, informando a
descrição, valor e data da transação.
As transações serão mostradas em uma lista e acima dessa lista, um gráfico de barras irá
representar os gastos dos ultimos 7 dias.
A few resources to get you started if this is your first Flutter project:
- [Lab: Write your first Flutter app](https://flutter.dev/docs/get-started/codelab)
- [Cookbook: Useful Flutter samples](https://flutter.dev/docs/cookbook)
For help getting started with Flutter, view our
[online documentation](https://flutter.dev/docs), which offers tutorials,
samples, guidance on mobile development, and a full API reference.
<file_sep>package br.com.roniedev.despesas_pessoais
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 66a90be00d395ec41c938d3384d2710e4d4298a8 | [
"Markdown",
"Kotlin"
] | 2 | Markdown | roniedev/despesas_pessoais | 278eac728e35d4bdf8bbf3cce8aeec1b8f6b2ea5 | 4e955d92ff14ed0f496cc3a834dc518e59d79c5c |
refs/heads/master | <repo_name>java858/vue-nested-router-demo<file_sep>/router/index.js
/* import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
}
]
})
*/
import Vue from 'vue'
import Router from 'vue-router'
import News from '@/components/News'
import User from '@/components/User'
import UserLogin from '@/components/UserLogin'
import UserRegister from '@/components/UserRegister'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/', // 首页,跳转到新闻当首页
redirect: '/news'
},
{
path: '/news', // 新闻
component: News
},
{
path: '/user', // 用户
component: User,
children: [
{ path: '/user/login', component: UserLogin }, // 用户=>登录
{ path: '/user/register', component: UserRegister } // 用户=>注册
]
}
]
})<file_sep>/README.md
# vue-nested-router-demo
vue 嵌套路由、局部路由、局部刷新、小页面刷新大页面不变的范例
| 2e71284439bea5d4b5cdfc966da2687dfc5a32db | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | java858/vue-nested-router-demo | 5fb03dce5f1a6519da07db9946d68e4c22c767b1 | 3ee89d813cc8fe1868fe747d1f90d07035672b21 |
refs/heads/master | <repo_name>sun-git/sun-git.github.io<file_sep>/udacity/pixel-art-marker/designs.js
const table = document.querySelector("#pixelCanvas");
const height = document.querySelector("#inputHeight");
const width = document.querySelector("#inputWidth");
const sizePicker = document.querySelector("#sizePicker");
const color = document.querySelector("#colorPicker");
sizePicker.onsubmit = function(event){
event.preventDefault();
clearGrid();
makeGrid();
};
function makeGrid() {
for (let r=0; r<height.value; r++){
const row = table.appendChild(document.createElement("tr"));
for (let c=0; c<width.value; c++){
const cell = row.appendChild(document.createElement("td"));
}
}
table.addEventListener("click", colorSquare);
}
function clearGrid(){
while (table.firstElementChild){
table.removeChild(table.firstElementChild);
}
}
function colorSquare (evt) {
if(evt.target.nodeName === "TD"){
evt.target.style.backgroundColor = color.value;
}
}
<file_sep>/udacity/project-memory-game/README.md
#Memory Game
Udatacity project
| 9b1c5d5d34400c19ebe65351d6548570ca216e20 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | sun-git/sun-git.github.io | 7575de5e07da004ebbdeb00ac64869731b27009d | 10f6d5570c505aef9151a4412b69f7d6c62b28a4 |
refs/heads/master | <file_sep>//
// ViewController.swift
// LoginServiceApp
//
// Created by <NAME> on 2020/08/23.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// singleton pattern 으로 데이터 공유 해서 마지막 페이지 까지 가지고 가야 함.
@IBOutlet weak var userId: UITextField!
@IBOutlet weak var userPass: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
userPass.isSecureTextEntry = true
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
_ = segue.destination as! Join1ViewController
if segue.identifier == "signUpButton" {
// 버튼을 클릭할 경우
print("signUpButton click")
} else if segue.identifier == "signUpBarButton" {
// 바 버튼을 클릭한 경우
print("signUpBarButton click")
}
}
func celebrationAlert (msg: String) {
let alert = UIAlertController(title: "성공", message: msg, preferredStyle: UIAlertController.Style.alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler : {(action) in
// 초기화
self.userId.text = ""
self.userPass.text = ""
self.userId.becomeFirstResponder() // userId로 포커스 이동
})
alert.addAction(defaultAction)
present(alert, animated: false, completion: nil)
}
func warningAlert (msg: String) {
let alert = UIAlertController(title: "경고", message: msg, preferredStyle: UIAlertController.Style.alert)
let defaultAction = UIAlertAction(title: "OK", style: .destructive, handler : {(action) in
self.userId.text = ""
self.userPass.text = ""
self.userId.becomeFirstResponder() // userId로 포커스 이동
})
alert.addAction(defaultAction)
present(alert, animated: false, completion: nil)
}
// 로그인 버튼
@IBAction func btnLogin(_ sender: Any) {
print("btnLogin click")
if (userId.text == "user" && userPass.text == "<PASSWORD>") {
print("로그인 성공")
celebrationAlert(msg: "로그인 성공 했습니다. 메인화면은 준비중 입니다.")
} else {
print("로그인 실패")
warningAlert(msg: "로그인 실패 했습니다.")
}
}
// 회원가입 버튼
@IBAction func btnSignup(_ sender: Any) {
print("btnSignUp click" )
}
override func viewWillAppear(_ animated: Bool) {
self.userId.text = ""
self.userPass.text = ""
self.userId.becomeFirstResponder() // userId 포커스이동
}
}
<file_sep>//
// UserInfo.swift
// LoginServiceApp
//
// Created by <NAME> on 2020/08/26.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
class UserInfo {
static let shared: UserInfo = UserInfo()
var name: String?
var phone: String?
var regDate: String?
var pass: String?
var memo: String?
var pic: String?
}
<file_sep>//
// Join2ViewController.swift
// LoginServiceApp
//
// Created by <NAME> on 2020/08/23.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
class Join2ViewController: UIViewController {
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var userPhone: UITextField!
let dateFormatter: DateFormatter = {
let formatter: DateFormatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .medium
formatter.dateFormat = "yyyy/MM/dd hh:mm:ss"
return formatter
}()
@IBAction func didDatePickerValueChanged(_ sender: UIDatePicker) {
print ("vlaue click")
let date: Date = sender.date
let dateString: String = self.dateFormatter.string(from: date)
self.dateLabel.text = dateString
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// 데이터 이동은 싱글톤이 깔끔하고 좋다.
// 상황에 맞춰서 써야 하니까 무조건 쓸려고 하지 말고 다른 방법도 익혀 두도록.
print("userIfo: \(UserInfo.shared.name), \(UserInfo.shared.pass), \(UserInfo.shared.memo), \(UserInfo.shared.pic)")
self.datePicker.addTarget(self, action: #selector(didDatePickerValueChanged(_:)), for: UIControl.Event.valueChanged)
}
@IBAction func btnCancel(_ sender: Any) {
print("join2 btnCancel click")
// 초기화
self.userPhone.text = ""
self.dateLabel.text = ""
// let loingViewController = self.storyboard?.instantiateViewController(identifier: "loginView") as! ViewController
// self.navigationController?.pushViewController(loingViewController, animated: true)
}
@IBAction func btnPrev(_ sender: Any) {
print("join2 btnPrev click")
let join1ViewController = self.storyboard?.instantiateViewController(identifier: "join1View") as! Join1ViewController
self.navigationController?.popViewController(animated: true)
}
@IBAction func btnJoin(_ sender: Any) {
func warningAlert (msg: String) {
let alert = UIAlertController(title: "경고", message: msg, preferredStyle: UIAlertController.Style.alert)
let defaultAction = UIAlertAction(title: "OK", style: .destructive, handler : nil)
alert.addAction(defaultAction)
present(alert, animated: false, completion: nil)
}
func celebrationAlert (msg: String) {
let alert = UIAlertController(title: "성공", message: msg, preferredStyle: UIAlertController.Style.alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler : { (action) in
let loingViewController = self.storyboard?.instantiateViewController(identifier: "loginView") as! ViewController
self.navigationController?.pushViewController(loingViewController, animated: true)
})
alert.addAction(defaultAction)
present(alert, animated: false, completion: nil)
}
let phone = self.userPhone.text
let regDate = self.dateLabel.text
UserInfo.shared.phone = phone
UserInfo.shared.regDate = regDate
guard phone != "" else {
let msg = "phone number 필수 값 입니다."
print(msg)
warningAlert(msg: msg)
return
}
guard regDate != "" else {
let msg = "regDate number 필수 값 입니다."
print(msg)
warningAlert(msg: msg)
return
}
celebrationAlert(msg: "축하 합니다. 로그인 화면으로 이동 합니다.")
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>//
// Join1ViewController.swift
// LoginServiceApp
//
// Created by <NAME> on 2020/08/23.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
class Join1ViewController: UIViewController {
@IBOutlet weak var imgView: UIImageView!
@IBOutlet weak var userName: UITextField!
@IBOutlet weak var userPass: UITextField!
@IBOutlet weak var userRePass: UITextField!
@IBOutlet weak var userMemo: UITextView!
let picker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.userName.text = nil
self.userPass.text = nil
self.userRePass.text = nil
self.userMemo.text = nil
self.userPass.isSecureTextEntry = true
self.userRePass.isSecureTextEntry = true
self.picker.sourceType = .photoLibrary // 방식 선택. 앨범에서 가져오는걸로 선택.
self.picker.allowsEditing = false // 수정가능하게 할지 선택. 하지만 false
self.picker.delegate = self // picker delegate
// imageview를 버튼으로 쓰기 위해서 사용하는 클래스, 뷰를 제스처로 만들어 주는 마법을 부린다. 이벤트도 등록이 가능하고... 암튼 그런것이다.
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
self.imgView.isUserInteractionEnabled = true
self.imgView.addGestureRecognizer(tapGestureRecognizer)
}
@objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
//let tappedImage = tapGestureRecognizer.view as! UIImageView
// Your action
self.present(self.picker, animated: true)
}
@IBAction func btnImage(_ sender: Any) {
self.present(self.picker, animated: true) // Controller이기 때문에 present 메서드를 이용해서 컨트롤러 뷰를 띄워준다!
}
@IBAction func btnCancel(_ sender: Any) {
// 정보의 흐름 : 네비게이션 push, pop
// 정보의 흐름이 필요없는것 : 모달
// push 방식으로 하면 스토리보드 방식으로 이동하는 것까지 걸 필요는 없었다.
// 만약 스토리보드까지 연결해 놓으면 두번 호출 된다.
// 당연한 걸까? 잘 모르겠다. 이유야 어찌됐든 한번만 호출해서 이대로 이해하고 넘어가자.
print("join1 btnCancel click")
_ = self.storyboard?.instantiateViewController(identifier: "loginView") as! ViewController
self.navigationController?.popViewController(animated: true)
}
@IBAction func btnNext(_ sender: Any) {
let userNm = self.userName.text ?? ""
let userP1 = self.userPass.text ?? ""
let userP2 = self.userRePass.text ?? ""
let userM = self.userMemo.text ?? ""
let pic = imgView.image.debugDescription
print ("name:\(userNm), userP1:\(userP1), userP2:\(userP2), userMemo:\(userM), pic:\(pic)")
// 싱글톤을 이용해서 넣는데 처음에는 인식을 못해서 xcode를 리스타트 하니까 잘된다. 버그가 아직 많은것 같다.
UserInfo.shared.name = userNm
UserInfo.shared.pass = <PASSWORD>
UserInfo.shared.memo = userM
UserInfo.shared.pic = pic
func warningAlert (msg: String) {
let alert = UIAlertController(title: "경고", message: msg, preferredStyle: UIAlertController.Style.alert)
let defaultAction = UIAlertAction(title: "OK", style: .destructive, handler : nil)
alert.addAction(defaultAction)
present(alert, animated: false, completion: nil)
}
guard userNm != "" else {
let msg = "이름은 필수 값입니다."
print(msg)
warningAlert(msg: msg)
return
}
guard userP1 == userP2 else {
let msg = "비밀번호와 비밀번호확인은 같아야 합니다.."
print(msg)
warningAlert(msg: msg)
return
}
guard userP1 != "" else {
let msg = "비밀번호 필수값 입니다."
print(msg)
warningAlert(msg: msg)
return
}
guard userP2 != "" else {
let msg = "비밀번호확인 필수값 입니다."
print(msg)
warningAlert(msg: msg)
return
}
guard userM != "" else {
let msg = "유저메모 필수값 입니다."
print(msg)
warningAlert(msg: msg)
return
}
print("pic:\(pic), \(pic.count)")
if pic.count == 3 {
let msg = "사진은 필수값 입니다."
print(msg)
warningAlert(msg: msg)
return
}
let join2View = self.storyboard?.instantiateViewController(identifier: "join2View") as! Join2ViewController
self.navigationController?.pushViewController(join2View, animated: true)
}
// 키보드 내리기
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
extension Join1ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
print("imagePickerController start")
var newImage: UIImage? = nil
if let possibleImage = info[UIImagePickerController.InfoKey(rawValue: "UIImagePickerControllerEditedImage")] as? UIImage { // 수정된 이미지가 있을 경우
newImage = possibleImage
} else if let possibleImage = info[UIImagePickerController.InfoKey(rawValue: "UIImagePickerControllerOriginalImage")] as? UIImage { // 오리지널 이미지가 있을 경우
newImage = possibleImage
}
print("image: \(String(describing: newImage))")
imgView.image = newImage // 받아온 이미지를 이미지 뷰에 넣어준다.
picker.dismiss(animated: true) // 그리고 picker를 닫아준다.
print("imagePickerController end")
}
}
| 9bb81f25e0c132cadc65279af9a0aa345771c505 | [
"Swift"
] | 4 | Swift | kimyongyeon/LoginServiceApp | 8e1a4e47cf5ef0d58f83ae65d6e4fcead3549f7b | 1b3c90867edf74a68bcd4defdf05e8bd179f4656 |
refs/heads/develop | <repo_name>Bishoy-Samwel/js-capstone<file_sep>/src/likes.js
const apiKey = '<KEY>';
const baseUrl = 'https://us-central1-involvement-api.cloudfunctions.net/capstoneApi/';
const post = (endpoint, body = {}) => fetch(`${baseUrl}${endpoint}`, {
method: 'POST',
body: JSON.stringify(body),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
});
export const fetchLikes = async () => {
const response = await fetch(`${baseUrl}apps/${apiKey}/likes`);
return response.json();
};
export const pokelike = async (pokeid) => {
const response = await post(`apps/${apiKey}/likes`, {
item_id: pokeid,
});
return response.status === 201;
};
export const thispokelikes = async (arr, pokeid) => {
let thislikes = 0;
arr.forEach(async (obj) => {
if (obj.item_id === pokeid) {
thislikes = obj.likes;
}
});
return thislikes;
};<file_sep>/src/comment.js
import Api from './api';
export default class Comment {
static commentsDiv = Comment.CreateCommentsDiv();
static numOfComments = 0;
static generateForm(id) {
const form = document.createElement('form');
const usernameInput = document.createElement('input');
const commentInput = document.createElement('input');
const commentBtn = document.createElement('button');
commentBtn.setAttribute('id', 'comment-btn');
usernameInput.setAttribute('placeholder', 'username');
commentInput.setAttribute('placeholder', 'write your comment here...');
commentBtn.classList.add('red');
usernameInput.type = 'text';
commentInput.type = 'text';
commentBtn.innerHTML = 'Comment';
usernameInput.setAttribute('placeholder', 'user name');
commentInput.setAttribute('placeholder', 'Write your Comment');
commentInput.classList.add('red');
commentBtn.addEventListener('click', (e) => {
e.preventDefault();
const username = usernameInput.value;
const comment = commentInput.value;
let obj = { item_id: id, username, comment };
Api.postComment(obj);
obj = { creation_date: Comment.generateDate(), username, comment };
Comment.commentsDiv.append(Comment.createComment(obj));
});
form.append(usernameInput, commentInput, commentBtn);
return form;
}
static createComment(obj) {
const p = document.createElement('p');
p.innerHTML = `${obj.creation_date} ${obj.username}: ${obj.comment}`;
return p;
}
static CreateCommentsDiv() {
Comment.commentsDiv = document.querySelector('#commentsDiv');
if (!Comment.commentsDiv) {
Comment.commentsDiv = document.createElement('div');
Comment.commentsDiv.setAttribute('id', 'commentsDiv');
}
return Comment.commentsDiv;
}
static async loadComments(itemId) {
Comment.commentsDiv.innerHTML = '';
await Api.getComments(itemId);
Api.commentsData.forEach((obj) => {
Comment.commentsDiv.append(Comment.createComment(obj));
});
this.numOfComments = Api.commentsData.length;
return Comment.commentsDiv;
}
static generateDate() {
let today = new Date();
const dd = String(today.getDate()).padStart(2, '0');
const mm = String(today.getMonth() + 1).padStart(2, '0');
const yyyy = today.getFullYear();
today = `${yyyy}-${dd}-${mm}`;
return today;
}
}
<file_sep>/README.md


## Js-capstone
This project is been made with HTML5, CSS3, JS and Webpack, following the guidelines of
[🔗](https://www.microverse.org/) for best practices.
---
# js-capstone
> This project we post and get data using Pokemon API.
---
In the project are use Pokeapi API for the data about the Pokémon world and Involvement API to record the different user interactions (likes, comments and reservations) provided from Microverse.
> This project is part of Microverse's 2.0 curriculum. and it's been built with Html5 and CSS3 and JS and webpack.
> This webapp list the pokemons
🤍 Preview Image🤍

🤍 Presentation Video🤍
[Video](https://www.loom.com/share/20767c193e484651b8ca2f80b5cfaea8)
---
## 🤍 Built With:
---
- HTML5 🤍
- CSS3 🤍
- JS 🤍
- Webpack 🤍
---
# 🤍 Live Demo 🤍
---
🤍 [Demo](https://bishoy-samwel.github.io/js-capstone)
---
# 🤍 Instructions:
To get a local copy up and running follow these simple sample steps.
## 🤍 Getting Started:
To get the content of this project locally you need to run this command on your terminal :
- ` cd <folder> `
- ` git clone https://github.com/Bishoy-Samwel/js-capstone.git`
### 🤍 Install
- Set up liveserver as an extension in your VS Code.
- If you don't have the live server extension, or are using another software just view directly in your browser.
### 🤍 Usage:
- Right click on "Go Live" in your VScode to view in your browser.
- If you don't have live server extension right click on the index.html to view in browser.
## 🤍 Test:
For tracking linter errors locally you need to follow these steps:
- After cloning the project you need to run this command:
> `npm install`
> This command will download all the dependancies of the project
- For tracking any linter errors in HTML file run:
> `npx hint .`
- And for tracking linter errors in CSS file run:
> `npx stylelint "\*_/_.{css,scss}"`
## 🤍 Authors:
👤 **<NAME>**
- GitHub: [@2bleo](https://github.com/2bleO)
- Twitter: [@OleaOnesis](https://twitter.com/OleaOnesis)
- LinkedIn: <NAME>](https://www.linkedin.com/in/onesis-olea)
👤 **<NAME>**
- GitHub: [@Bishoy Sam<NAME>](https://github.com/Bishoy-Samwel)
- LinkedIn: [@Bishoy Samwel](https://www.linkedin.com/in/bishoy-samwuel-ss/)
- Twitter: [@bisho](https://twitter.com/BishoFaheem15)
👤 **<NAME>**
- Github:[@Sheyla Pozo](https://github.com/sheylaPozo)
- Linkedin: [@Sheyla Pozo](https://www.linkedin.com/in/sheypozo/)
- Twitter: [@Sheyla Pozo](https://twitter.com/sheyPozo)
---
## 🤝 Contributing:
Contributions, issues, and feature requests are welcome! 🤍
Feel free to check the [issues page](https://github.com/Bishoy-Samwel/js-capstone/issues).
## 🤍 Show your support
Give a ⭐️ if you like this project!
## 🤍 Acknowledgments
Hat tip to anyone whose code was used
- Microverse
- Inspiration
<file_sep>/src/api.js
import axios from 'axios';
export default class Api {
static apiKey = '<KEY>';
static baseUrl = `https://us-central1-involvement-api.cloudfunctions.net/capstoneApi/apps/${Api.apiKey}/`;
static commentsData = [];
static reservesData = [];
static commentsUrl = `${Api.baseUrl}comments`;
static reservationsUrl = `${Api.baseUrl}reservations`;
static async postComment(obj) {
const commentUrl = `${Api.commentsUrl}`;
await axios.post(commentUrl, obj);
}
static async getComments(id) {
const commentUrl = `${Api.commentsUrl}?item_id=${id}`;
const result = await axios.get(commentUrl);
Api.commentsData = result.data;
}
static async postReserve(obj) {
const reservationUrl = `${Api.reservationsUrl}`;
await axios.post(reservationUrl, obj);
}
static async getReserves(id) {
const reservationsUrl = `${Api.reservationsUrl}?item_id=${id}`;
const result = await axios.get(reservationsUrl);
Api.reservesData = result.data;
return Api.reservesData;
}
static createApp() {
const request = new XMLHttpRequest();
request.open('POST', `${Api.baseUrl}apps/`, true);
request.onreadystatechange = () => {
if (request.readyState === 4 && request.status === 201) {
console.log(request.responseText);
}
};
request.send();
}
}
<file_sep>/src/modal.js
export default class Modal {
displayed = null;
// To control the window
pop = (box) => {
if (this.displayed === null) {
box.style.display = 'block';
this.displayed = true;
} else {
box.style.display = 'none';
this.displayed = null;
}
}
generateBox = (content, closeTxt = 'close') => {
this.boxDiv = document.createElement('div');
this.boxDiv.setAttribute('id', 'box');
this.boxDiv.append(...content);
this.closeBtn = document.createElement('btn');
this.closeBtn.setAttribute('class', 'close-btn');
this.closeBtn.textContent = closeTxt;
this.boxDiv.append(this.closeBtn);
this.closeBtn.addEventListener('click', (e) => {
e.preventDefault();
this.pop(this.boxDiv);
});
}
create = (content) => {
this.generateBox(content);
}
}<file_sep>/src/index.js
import './style.css';
import { layout, render, manageEvents } from './layout';
import Pokemon from './pokemon';
import { fetchLikes, pokelike, thispokelikes } from './likes';
import displaycounter from './pokecounter';
// import Api from './api';
const body = document.getElementById('body');
body.innerHTML = layout();
async function pokelist(num) {
const list = await Pokemon.getlist(num, 0);
const likes = await fetchLikes();
list.results.forEach(async (element) => {
const info = await Pokemon.getpokeinfo(element.name);
const thislikes = await thispokelikes(likes, info.id);
const pokemon = new Pokemon(info, thislikes);
render(pokemon);
const likebtn = document.getElementById(`${pokemon.id}-like`);
likebtn.addEventListener('click', async () => {
await pokelike(pokemon.id);
likebtn.classList.add('liked');
window.location.reload();
});
await displaycounter();
});
}
pokelist(9);
manageEvents();
<file_sep>/src/reserve.js
/* eslint-disable no-undef */
/* eslint-disable no-unused-vars */
import Api from './api';
export default class Reserve {
static reservesDiv = Reserve.CreateReservesDiv();
static numOfReserves = 0;
static generateForm(id) {
const form = document.createElement('form');
const usernameInput = document.createElement('input');
const startdateInput = document.createElement('input');
const endDateInput = document.createElement('input');
const reserveBtn = document.createElement('button');
usernameInput.setAttribute('placeholder', 'user name');
startdateInput.setAttribute('placeholder', 'Start date');
endDateInput.setAttribute('placeholder', 'End date');
reserveBtn.classList.add('red');
usernameInput.type = 'text';
startdateInput.type = 'date';
endDateInput.type = 'date';
reserveBtn.innerHTML = 'Reserve';
reserveBtn.addEventListener('click', (event) => {
event.preventDefault();
const username = usernameInput.value;
const dateStart = startdateInput.value;
const dateEnd = endDateInput.value;
const obj = {
item_id: id, username, date_start: dateStart, date_end: dateEnd,
};
Api.postReserve(obj);
Reserve.reservesDiv.append(Reserve.createReserve(obj));
});
form.append(usernameInput, startdateInput, endDateInput, reserveBtn);
return form;
}
static createReserve(obj) {
const p = document.createElement('p');
p.innerHTML = `${obj.date_start}-${obj.date_end} by: ${obj.username}`;
return p;
}
static CreateReservesDiv() {
Reserve.reservesDiv = document.querySelector('#reservesDiv');
if (!Reserve.reservesDiv) {
Reserve.reservesDiv = document.createElement('div');
Reserve.reservesDiv.setAttribute('id', 'reservesDiv');
}
return Reserve.reservesDiv;
}
static async loadReserves(itemId) {
Reserve.reservesDiv.innerHTML = '';
const data = await Api.getReserves(itemId);
data.forEach((obj) => {
Reserve.reservesDiv.append(Reserve.createReserve(obj));
});
this.numOfReserves = Api.reservesData.length;
return Reserve.reservesDiv;
}
}
| 9c7b6ac1839ae0a5cbe4b68a8de6ad5574f99d5b | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | Bishoy-Samwel/js-capstone | ac070acd2e3a076c3b6ff1644320252efc92a85f | b1dce4c876e40e7879ea591027bd751aa42bf549 |
refs/heads/master | <file_sep>#List, Dictionary and Iteration Review
###################################################################################
LISTS
###################################################################################
##Create a list called group_names which includes the name of every person in our group.
##READ the List
#Print the second element of the list:
#Identify the length of the list and print it in a sentence saying: Our group has _____ people.
##Update the list:
#Add a "Ellie" to the group and print your new list!
#Reassign the fourth element to be "Jeff"
##Iterate over the list
#Print out EACH name separately.
###################################################################################
DICTIONARIES
###################################################################################
##Create a dictionary called group_ice_cream, of all the students in our group and their favorite ice cream.
#What aspects of this dictionary are keys? What aspects are values?
##Read the Dictionary
#Print the second person in the dictionary.
#Print the second person in the dictionary's favorite ice cream flavor
#Print the statement: "Our dictionary has _____ elements"
##Update the Dictionary
#HOW DO I ADD SOMETHING TO A DICTIONARY? DO I APPEND?
#Replace Eliseo's favorite ice cream with "?"
##Iterate over a dictionary
#For each person in the dictionary, print "______'s favorite ice cream is _______"
###################################################################################
LISTS OF DICTIONARIES
###################################################################################
##Create a list called our_profiles that has a dictionary inside for each person in our group. The dictionary should contain the person's name, age, birthday, and favorite ice cream.
##Read our list of DICTIONARIES
#Print the first element of the list. !!PLEASE NOTE THIS PRINTS A DICTIONARY BECAUSE EACH ELEMENT IS ITS OWN DICTIONARY!!
#Print "_______ is ______ years old and loves _______ ice cream" for the second person in the group.
##Update our List
#Change the second person's age to 100.
#Add a new person to our group (Ellie, 22, 09/04/1996, <NAME>)
##Iterate over the list of DICTIONARIES
#Create a list called our_birthdays of our birthdays.
#Print a statment for each person that says: "_______'s birthday is _______ and they are currently ______ years old."
<file_sep>#List, Dictionary and Iteration Review
###################################################################################
LISTS
###################################################################################
##Create a list called group_names which includes the name of every person in our group.
group_names = ["Marisa", "Eliseo", "Aaron"]
##READ the List
#Print the second element of the list:
print(group_names[1])
#Identify the length of the list and print it in a sentence saying: Our group has _____ people.
print("Our group has " + str(len(group_names))
##Update the list:
#Add a "Ellie" to the group!
group_names.append("Ellie")
print(group_names)
#Reassign the fourth element to be "Jeff"
group_names[3] = "Jeff"
print(group_names)
##Iterate over the list
#Print out EACH name separately.
for person in group_names:
print(person)
#For each person in the group, print "The #____ person to arrive was _______"
for x in range(len(group_names)):
print("The #" + str(x + 1) + " person to arrive to our group was " + group_names[x] + ".")
###################################################################################
DICTIONARIES
###################################################################################
##Create a dictionary called group_ice_cream, of all the students in our group and their favorite ice cream.
group_ice_cream = {"Marisa": "Coffee", "Eliseo": "Rocky Road", "Aaron": "Cookie Dough"}
#What aspects of this dictionary are keys? What aspects are values?
##Read the Dictionary
#Print the second person in the dictionary.
print(group_ice_cream[1])
#Print the second person in the dictionary's favorite ice cream flavor
print(group_ice_cream["Eliseo"])
#Print the statement: "Our dictionary has _____ elements"
print("Our dictionary has " + str(len(group_ice_cream)) + " elements.")
##Update the Dictionary
#HOW DO I ADD SOMETHING TO A DICTIONARY? DO I APPEND?
#Replace Eliseo's favorite ice cream with "?"
group_ice_cream["Eliseo"] = "Coffee"
##Iterate over a dictionary
#For each person in the dictionary, print "______'s favorite ice cream is _______"
for name in group_ice_cream:
print(name + "'s favorite ice cream is " + group_ice_cream[name])
###################################################################################
LISTS OF DICTIONARIES
###################################################################################
##Create a list called our_profiles that has a dictionary inside for each person in our group. The dictionary should contain the person's name, age, birthday, and favorite ice cream.
our_profiles = [
{"name": "Marisa", "age": 28, "birthday": "08/08/1990", "fav_ice_cream": "Coffee"}
{"name": "Eliseo", "age": 29, "birthday": "06/08/1990", "fav_ice_cream": "Rocky Road"}
{"name": "Aaron", "age": 17, "birthday": "08/08/2002", "fav_ice_cream": "Cookie Dough"}
]
##Read our list of DICTIONARIES
#Print the first element of the list. !!PLEASE NOTE THIS PRINTS A DICTIONARY BECAUSE EACH ELEMENT IS ITS OWN DICTIONARY!!
print(our_profiles[0])
#Print "_______ is ______ years old and loves _______ ice cream" for the second person in the group.
print(our_profiles[1]["name"] + " is " + our_profiles[1]["age"] + " years old and loves " + our_profiles[1][fav_ice_cream] + " ice cream.")
##Update our List
#Change the second person's age to 100.
our_profiles[1]["age"] = 100
#Add a new person to our group (Ellie, 22, 09/04/1996, Chocolate Fudge Brownie)
our_profiles.append({"name": "Ellie", "age": 22, "birthday": "09/04/1996", "fav_ice_cream": "Chocolate Fudge Brownie"})
##Iterate over the list of DICTIONARIES
#Create a list called our_birthdays of our birthdays.
our_birthdays = []
for person in our_profiles:
our_birthdays.append(person["birthday"])
#Print a statment for each person that says: "_______'s birthday is _______ and they are currently ______ years old."
for person in our_profiles:
print(person["name"] + "'s birthday is " + person["birthday"] + " and they are currently " + person["age"] + " years old.")
| a80419e64b02a2fdc879dfcc52a03abd92ebe30e | [
"Python"
] | 2 | Python | Mshuman8/list_dict_review_teachers | 2fb3328938a3979dcf1b2130fcbd99f743be9c76 | 691635aede7c54174fb91dd1df79adc92f75da27 |
refs/heads/main | <file_sep>from django.contrib import admin
from django.urls import path
from .views.home import Index
from .views.signup import Signup
from .views.login import Login, logout
from .views.cart import Cart
from .views.booking import Booking
urlpatterns = [
path('', Index.as_view(), name='homepage'),
path('signup', Signup.as_view(), name='signup'),
path('login', Login.as_view(), name='login'),
path('logout', logout, name='logout'),
path('cart', Cart.as_view(), name='cart'),
path('booking', Booking.as_view(), name='booking'),
]
<file_sep>from django.shortcuts import render , redirect
from django.contrib.auth.hashers import check_password
from store.models.customer import Customer
from django.views import View
from store.models.product import Product
class Cart(View):
def get(self , request):
#print(request.session.get('cart'))
if not request.session.get('cart'):
user_name = request.session.get('name')
return render(request, 'cart.html', {'name': user_name} )
else:
ids = list(request.session.get('cart').keys())
products = Product.get_products_by_id(ids)
user_name = request.session.get('name')
data = {}
data['name'] = user_name
data['products'] = products
return render(request, 'cart.html', data)
def post(self, request):
# product is the product id selected to add in wishlist
product = request.POST.get('product')
#print(product)
cart = request.session.get('cart')
#print(cart)
remove = request.POST.get('remove')
if cart:
if remove:
cart.pop(product)
request.session['cart'] = cart
#print(request.session['cart'])
return redirect('cart')
<file_sep>
# Cafe Shop with Django
A simple Cafe website showcasing products served by the cafe and a functionality to book a reservation via Email.
## Tech Stack
**Front End:** HTML, CSS. Bootstrap
**Backend:** Python(3.7.7), Django(3.1.12)
## Screenshots
**SignUp page**

**Login page**

**Home page**

**Wishlist**

**Booking**

## Roadmap
- Additional booking model
- FrontEnd Development
## Optimizations
- Refactoring Code
<file_sep>from django.shortcuts import render, redirect
from store.models.product import Product
from store.models.category import Category
from django.views import View
from django.contrib import messages
class Index(View):
def get(self, request):
# Initializing Objects
products = Product.get_all_products();
categories = Category.get_all_categories();
# Handle and filter category GET request
categoryID = request.GET.get('category')
if categoryID:
products = Product.get_all_products_by_categoryid(categoryID)
else:
products = Product.get_all_products();
# Render index.html using database objects
session_user = request.session.get('name')
data = {}
data['products'] = products
data['categories'] = categories
data['name'] = session_user
return render(request, 'index.html', data)
def post(self, request):
product = request.POST.get('product')
#print(product)
cart = request.session.get('cart')
if cart:
cart[product] = 1
else:
cart = {}
cart[product] = 1
request.session['cart'] = cart
#print(request.session['cart'])
return redirect('homepage')
<file_sep>from django.shortcuts import render , redirect
from django.views import View
from django.core.mail import send_mail
from django.conf import settings
class Booking(View):
def get(self , request):
user_name = request.session.get('name')
user_mail = request.session.get('email')
data = {}
data['name'] = user_name
data['email'] = user_mail
#print(data)
return render(request, 'booking.html', data)
def post(self, request):
postData = request.POST
first_name = postData.get('name')
timing = postData.get('gridRadios')
email = postData.get('email')
user_name = request.session.get('name')
print(user_name,timing,email)
error_message = None
success_message = 'Reservation Booked !'
if (not first_name):
error_message = "Please provide a name for reservation !"
if (not email):
error_message = "Please provide email for reservation !"
data={}
if error_message:
data['name'] = user_name
data['error'] = error_message
else:
data['name'] = user_name
data['success'] = success_message
'''
send_mail(
'Reservation Confirmed !', # Subject
'Hello ' + first_name + ' your reservation is confirmed this ' + timing, # Message
'<EMAIL>', # From
['<EMAIL>'] # To
)
'''
return render(request, 'booking.html', data)
| 58d69f3fb580ca27e714571673ed99d84787738d | [
"Markdown",
"Python"
] | 5 | Python | Shwetik/CafeDjango | 092ea424fd53d43a0976820750fd1683634b2e03 | 6905ba806250f21cfbace94af0f3354eea1c3355 |
refs/heads/main | <repo_name>PiperLang/piper<file_sep>/src/includes/expressions/format_string_expression.hpp
#pragma once
#include <expressions/expression.hpp>
namespace piper {
class FormatStringExpression : public Expression {
public:
FormatStringExpression(std::string format_string);
std::string toString();
protected:
std::string format_string;
};
}
<file_sep>/docs/RETURNTYPE.md
struct val {
}
struct return_type {
}
struct func_return {
int return_count;
return_type *types;
val *values;
}<file_sep>/src/includes/expressions/number_expression.hpp
#pragma once
#include <expressions/expression.hpp>
namespace piper {
class NumberExpression : public Expression {
public:
NumberExpression(std::string number);
std::string toString();
protected:
std::string number;
};
}
<file_sep>/src/statements/if_statement.cpp
#include <statements/if_statement.hpp>
#include <iostream>
#include <iomanip>
#include <sstream>
namespace piper {
IfStatement::IfStatement() {
}
void IfStatement::set_condition(Expression *condition) {
this->condition = condition;
}
void IfStatement::set_then(Statement *then) {
this->then = then;
}
std::string IfStatement::toString() {
std::stringstream stream;
stream << "\"" << std::hex << this << "\"";
stream << " [label = \"If\"];\n";
stream << "\"" << std::hex << this << "\"";
stream << " -> ";
stream << "\"" << std::hex << this->condition << "\"";
stream << " [ label = \"Condition\" ];\n";
stream << "\"" << std::hex << this << "\"";
stream << " -> ";
stream << "\"" << std::hex << this->then << "\"";
stream << " [ label = \"Then\" ];\n";
stream << this->condition->toString();
stream << this->then->toString();
return stream.str();
}
}<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(piper)
set(CMAKE_BUILD_TYPE Debug)
add_executable(piper-text-to-token
src/piper-text-to-token.cpp
src/stage_filetotokens.cpp
src/scanner.cpp
)
target_include_directories(piper-text-to-token PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/src/includes
)
add_executable(piper-token-to-cst
src/piper-token-to-cst.cpp
src/scanner.cpp
)
target_include_directories(piper-token-to-cst PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/src/includes
)
add_executable(piper
src/piper.cpp
src/scanner.cpp
src/stage_filetotokens.cpp
src/stage_tokenstotree.cpp
src/statements/import_statement.cpp
src/statements/function_statement.cpp
src/statements/block_statement.cpp
src/statements/if_statement.cpp
src/statements/expression_statement.cpp
src/statements/return_statement.cpp
src/expressions/add_expression.cpp
src/expressions/call_expression.cpp
src/expressions/double_colon_expression.cpp
src/expressions/format_string_expression.cpp
src/expressions/greater_than_expression.cpp
src/expressions/identifier_expression.cpp
src/expressions/less_than_expression.cpp
src/expressions/number_expression.cpp
src/expressions/sub_expression.cpp
)
target_include_directories(piper PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/src/includes)
add_executable(jitter src/jitter.cpp)
target_link_libraries(jitter PUBLIC gccjit)
<file_sep>/src/expressions/number_expression.cpp
#include <expressions/number_expression.hpp>
#include <iomanip>
#include <sstream>
namespace piper {
NumberExpression::NumberExpression(std::string number) {
this->number = number;
}
std::string NumberExpression::toString() {
std::stringstream stream;
stream << "\"" << std::hex << this << "\"";
stream << " [label=\"Number: ";
stream << this->number;
stream << "\"];\n";
return stream.str();
}
}
<file_sep>/src/statements/block_statement.cpp
#include <statements/block_statement.hpp>
#include <iostream>
#include <iomanip>
#include <sstream>
namespace piper {
BlockStatement::BlockStatement() {
}
void BlockStatement::append(Statement *statement) {
if (statement != NULL) {
this->statements.push_back(statement);
}
}
std::string BlockStatement::toString() {
std::stringstream stream;
stream << "\"" << std::hex << this << "\"";
stream << " [label=\"Block\"];\n";
for (int i = 0; i < this->statements.size(); i++) {
auto statement = this->statements.at(i);
stream << "\"" << std::hex << this << "\"";
stream << " -> ";
stream << "\"" << std::hex << statement << "\"";
stream << " [ label = \"";
stream << std::dec << i;
stream << "\" ];\n";
stream << statement->toString();
}
return stream.str();
}
}<file_sep>/src/includes/statements/import_statement.hpp
#pragma once
#include <statements/statement.hpp>
namespace piper {
class ImportStatement : public Statement {
public:
ImportStatement(std::string import_name);
std::string toString();
protected:
std::string import_name;
};
}
<file_sep>/src/includes/statements/block_statement.hpp
#pragma once
#include <statements/statement.hpp>
#include <data_type.hpp>
#include <vector>
#include <vector>
namespace piper {
class BlockStatement : public Statement {
public:
BlockStatement();
void append(Statement *statement);
std::string toString();
protected:
std::vector<Statement *> statements;
};
}
<file_sep>/README.md
# piper
The main repo for piper. Potentially pulls in many other repositories. Start here.
## checking out
git clone https://github.com/PiperLang/piper.git
## building
mkdir build
cd build
cmake ..
make
cp ../example.piper ./
./piper example.piper
xxd ./example.piper.fft
## stages
The compiler works in small logical stages. This is mostly for my own sanity, but should also make each stage easier to work on. It may also make the compiler run more slowly, but frankly I don't care. During development / when flags are given, each stage will also output its intermediary files. Sometimes these files wil be easy to read, sometimes you will need to know their binary structure. xxd comes in handy, as it will show you the hex and also strings if those are embedded in the binary.
### Stage 0: tokenization : ftt (file to tokens)
This stage takes textual code in and outputs a stream of tokens, mostly. It does do a few special things with interning strings and string-like things.
The output is a binary file, with the following structure. Every component is 8 bits.
#### File Structure
##### MAGIC NUMBER
The magic number is ASCII for PPRALCFTT. In hex that is 50 50 52 41 4c 43 46 54 54.
##### VERSION ID
This is always zero for now. I will start updating this field when things are more stable and they do not shift literally every commit.
##### NUMBER OF STRINGS
The number of embedded strings. All strings and string-like things are interned and from here on in will be referred to as just their string ID (the index into this quasi-array, starting at zero)
##### FOR EACH STRING: LENGTH OF STRING
The length of the following string. It is NOT null terminated.
##### FOR EACH STRING: BYTES
For now this is only guaranteed to work with ASCII. UTF-8 encoding is on the horizon. Again, this is not null terminated.
##### LIST OF TOKENS
Each token is its own byte. Then there's a byte for line and a byte for column. There are (currently) four tokens that are followed by a string id to represent the additional info: FORMAT_STRING, STRING, IDENTIFIER, NUMBER.
Note that format strings at this point are not internally parsed and are just strings. Also note that numbers themselves are not parsed and are just the string version of themselves.
### Stage 1: tree : ttt (tokens to tree)
This stage takes a list of tokens and constructs a tree. Most of our syntax errors will occur here, as this is the first stage that will know that variable names must be valid identifiers, etc. There's a LOT of invalid programs that will pass the tokenization stage.
The output is again a binary file, this time though it's fundamentally a tree structure. The top level structure is a file, and there's a branch node for every top level statement in the file itself.
#### File Structure
##### Magic Number
The magic number is ASCII for PPRALCTTT. In hex that is 50 50 52 41 9c 43 54 54 54.
##### VERSION ID
This is always zero for now. I will start updating this field when things are more stable and they do not shift literally every commit.
<file_sep>/src/piper-token-to-cst.cpp
#include <array>
#include <cassert>
#include <cerrno>
#include <cstring>
#include <vector>
#include <iostream>
#include <scanner.hpp>
#include <tokentype.hpp>
#define INIT_BUFFER_SIZE 1024
int main(int argc, char *argv[]) {
std::freopen(nullptr, "rb", stdin);
if (std::ferror(stdin)) {
throw std::runtime_error(std::strerror(errno));
}
std::size_t len;
std::array<char, INIT_BUFFER_SIZE> buf;
std::vector<char> input;
while ((len = std::fread(buf.data(), sizeof(buf[0]), buf.size(), stdin)) > 0) {
if (std::ferror(stdin) && !std::feof(stdin)) {
throw std::runtime_error(std::strerror(errno));
}
input.insert(input.end(), buf.data(), buf.data() + len);
}
int idx = 0;
assert(input.at(idx++) == 'P');
assert(input.at(idx++) == 'P');
assert(input.at(idx++) == 'R');
assert(input.at(idx++) == 'A');
assert(input.at(idx++) == 'L');
assert(input.at(idx++) == 'C');
assert(input.at(idx++) == 'F');
assert(input.at(idx++) == 'T');
assert(input.at(idx++) == 'T');
assert(input.at(idx++) == 0);
int string_count = (int)input.at(idx++);
std::cout << "String Count: " << string_count << std::endl;
for (int i = 0; i < string_count; i++) {
int single_string_length = (int)input.at(idx++);
std::cout << " Single string (" << single_string_length << "): ";
for (int p = 0; p < single_string_length; p++) {
std::cout << input.at(idx++);
}
std::cout << std::endl;
}
while (true) {
bool is_at_end = false;
uint8_t token_type = input.at(idx++);
uint8_t token_line = input.at(idx++);
uint8_t token_column = input.at(idx++);
std::cout
<< "(" << std::hex << (int)token_type << "): "
<< piper::Scanner::getTokenName(static_cast<piper::TokenType>(token_type))
<< std::endl;
switch (token_type) {
case piper::TokenType::TOKEN_EOF:
is_at_end = true;
break;
case piper::TokenType::FORMAT_STRING:
case piper::TokenType::IDENTIFIER:
case piper::TokenType::NUMBER:
case piper::TokenType::STRING:
idx++;
break;
}
if (is_at_end) break;
}
// use input vector here
}<file_sep>/src/includes/scanner.hpp
#pragma once
#include <string>
#include <vector>
#include <tokentype.hpp>
namespace piper {
struct Location {
int line;
int column;
std::string filename;
};
struct Token {
TokenType type;
Location start;
Location end;
std::string str;
};
class Scanner {
public:
Scanner(std::string filename);
std::vector<Token *> *getTokens();
static std::string getTokenName(TokenType tokenType);
protected:
private:
std::string filename;
};
}
<file_sep>/src/expressions/add_expression.cpp
#include <expressions/add_expression.hpp>
#include <iomanip>
#include <sstream>
namespace piper {
AddExpression::AddExpression(Expression *left, Expression *right) {
this->left = left;
this->right = right;
}
std::string AddExpression::toString() {
std::stringstream stream;
stream << "\"" << std::hex << this << "\"";
stream << " [label=\"Add\"];\n";
stream << "\"" << std::hex << this << "\"";
stream << " -> ";
stream << "\"" << std::hex << this->left << "\"";
stream << ";\n";
stream << this->left->toString();
stream << "\"" << std::hex << this << "\"";
stream << " -> ";
stream << "\"" << std::hex << this->right << "\"";
stream << ";\n";
stream << this->right->toString();
return stream.str();
}
}
<file_sep>/src/includes/expressions/double_colon_expression.hpp
#pragma once
#include <expressions/expression.hpp>
namespace piper {
class DoubleColonExpression : public Expression {
public:
DoubleColonExpression(Expression *left, Expression *right);
std::string toString();
protected:
Expression *left;
Expression *right;
};
}
<file_sep>/src/jitter.cpp
#include <libgccjit.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <map>
#include <string>
#include <vector>
class FunctionRegistry {
public:
FunctionRegistry() {
}
void add_function(std::string name, gcc_jit_function *function) {
this->methods[name] = function;
}
gcc_jit_function *get_function(std::string name) {
return this->methods[name];
}
~FunctionRegistry() {
}
protected:
private:
std::map<std::string, gcc_jit_function *> methods;
};
class JitterMethod {
public:
JitterMethod(FunctionRegistry *function_registry, gcc_jit_context *ctx, std::string name) {
this->function_registry = function_registry;
this->ctx = ctx;
this->name = name;
}
~JitterMethod() {
}
void add_parameter(const char *name, gcc_jit_type *type) {
this->parameters.push_back(
gcc_jit_context_new_param(
this->ctx,
NULL,
type,
name
)
);
}
void build(gcc_jit_type *return_type) {
this->func = gcc_jit_context_new_function(
this->ctx,
NULL,
// This is always exported? I think so.
GCC_JIT_FUNCTION_EXPORTED,
return_type,
this->name.c_str(),
this->parameters.size(),
this->parameters.data(),
0
);
gcc_jit_rvalue *args[2];
args[0] = gcc_jit_context_new_string_literal(this->ctx, "hello %s\n");
args[1] = gcc_jit_param_as_rvalue(this->parameters.at(0));
gcc_jit_block *block = gcc_jit_function_new_block(this->func, NULL);
gcc_jit_block_add_eval(
block,
NULL,
gcc_jit_context_new_call(
this->ctx,
NULL,
this->function_registry->get_function("printf"),
2,
args
)
);
gcc_jit_block_end_with_void_return(block, NULL);
}
protected:
private:
gcc_jit_context *ctx;
gcc_jit_function *func;
std::string name;
FunctionRegistry *function_registry;
std::vector<gcc_jit_param *> parameters;
};
class Jitter {
public:
Jitter() {
this->ctx = gcc_jit_context_acquire();
gcc_jit_context_set_bool_option(
this->ctx,
GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
true
);
this->const_char_ptr_type = gcc_jit_context_get_type(this->ctx, GCC_JIT_TYPE_CONST_CHAR_PTR);
this->int_type = gcc_jit_context_get_type(this->ctx, GCC_JIT_TYPE_INT);
this->void_type = gcc_jit_context_get_type(this->ctx, GCC_JIT_TYPE_VOID);
gcc_jit_param *param_format = gcc_jit_context_new_param(
this->ctx,
NULL,
this->const_char_ptr_type,
"format"
);
this->function_registry.add_function(
"printf",
gcc_jit_context_new_function(
this->ctx,
NULL,
GCC_JIT_FUNCTION_IMPORTED,
this->int_type,
"printf",
1,
¶m_format,
1
)
);
}
gcc_jit_type *get_const_char_ptr_type() {
return this->const_char_ptr_type;
}
gcc_jit_type *get_void_type() {
return this->void_type;
}
JitterMethod *start_method(const char *name) {
return new JitterMethod(&this->function_registry, this->ctx, name);
}
void finish() {
gcc_jit_result *result;
/* Compile the code. */
result = gcc_jit_context_compile(this->ctx);
if (!result) {
fprintf(stderr, "NULL result");
exit(1);
}
/* Extract the generated code from "result". */
typedef void (*fn_type) (const char *);
fn_type greet = (fn_type)gcc_jit_result_get_code(result, "greet");
if (!greet) {
fprintf(stderr, "NULL greet");
exit(1);
}
/* Now call the generated function: */
greet("world");
fflush(stdout);
// This is done after context release in the examples.
gcc_jit_result_release(result);
}
~Jitter() {
gcc_jit_context_release(this->ctx);
}
protected:
private:
gcc_jit_context *ctx;
gcc_jit_type *const_char_ptr_type;
gcc_jit_type *int_type;
gcc_jit_type *void_type;
FunctionRegistry function_registry;
};
int main (int argc, char **argv) {
Jitter jitter;
JitterMethod *method = jitter.start_method("greet");
method->add_parameter("name", jitter.get_const_char_ptr_type());
method->build(jitter.get_void_type());
jitter.finish();
delete method;
return 0;
}<file_sep>/src/statements/function_statement.cpp
#include <statements/function_statement.hpp>
#include <iomanip>
#include <sstream>
namespace piper {
FunctionStatement::FunctionStatement(std::string function_name) {
this->function_name = function_name;
}
void FunctionStatement::set_return_type(DataType return_type) {
this->return_type = return_type;
}
void FunctionStatement::set_body(Statement *body) {
this->body = body;
}
void FunctionStatement::add_arg(std::string arg_name, DataType data_type) {
this->args.push_back({arg_name, data_type});
}
std::string FunctionStatement::toString() {
std::stringstream stream;
stream << "subgraph \"cluster_" << std::hex << this << "\" {\n";
stream << "label = \"" << this->function_name << "\";\n";
stream << "\"" << std::hex << this << "\" [ label = \"Start\" ];\n";
stream << "\"" << std::hex << this << "\"";
stream << " -> ";
stream << "\"" << std::hex << this->body << "\"";
stream << " [label=\"Body\"];\n";
stream << "subgraph \"cluster_" << std::hex << this << "_args\" {\n";
stream << "label = \"Args\";\n";
for (int i = 0; i < this->args.size(); i++) {
auto arg = this->args.at(i);
stream << "\"" << std::hex << this << "_arg" << std::dec << i << "\"";
stream << " [ label = \"{";
stream << " <f0> " << arg.first;
stream << " | <f1> ";
switch (arg.second.type) {
case MT_I64:
stream << "i64";
break;
case MT_U64:
stream << "u64";
break;
case MT_CUSTOM:
stream << arg.second.extra_data;
break;
case MT_UNKNOWN:
default:
stream << "UNKNOWN";
break;
}
arg.second;
stream << " }\"; shape = \"record\"; ];\n";
}
stream << "}\n";
stream << this->body->toString();
stream << "}\n";
return stream.str();
}
}<file_sep>/src/includes/stage_tokenstotree.hpp
#pragma once
#include <expressions/expression.hpp>
#include <stage.hpp>
#include <statements/statement.hpp>
#include <statements/function_statement.hpp>
#include <vector>
namespace piper {
class TokensToTree : public Stage {
public:
TokensToTree(std::string filename);
bool shouldRun();
void run(
std::map<std::string, parse_result> *results
);
protected:
bool debug;
std::string filename;
int idx;
std::vector<std::string> embedded_strings;
// Expressions
Expression *comparison_expression(parse_result results);
Expression *term_expression(parse_result results);
Expression *factor_expression(parse_result results);
Expression *unary_expression(parse_result results);
Expression *call_expression(parse_result results);
Expression *primary_expression(parse_result results);
// General
void parse_function_arguments(parse_result results, FunctionStatement *function);
Expression *parse_expression(parse_result results);
Statement *parse_statement(parse_result results);
Statement *parse_block(parse_result results);
void parse_strings(parse_result results);
Statement *parse_top_level_statement(parse_result results);
private:
};
}
<file_sep>/src/includes/tokentype.hpp
#pragma once
#include <map>
namespace piper {
/**
* Token types that piper recognizes. Note that the names here are
* purposefully not indicative of *use*. Some of these tokens change
* meaning based on context. Rather than having a two-tier system where
* some tokens are use-named and some are appearance-named, I am choosing
* to have everything appearance-named at this stage. Later stages, where
* symbols have been disambiguated can be more specific.
*
* Many things were stolen from https://llvm.org/docs/LangRef.html#module-structure
* Not all of these things will be used, probably, this list stands as a note to myself to some degree.
*/
enum TokenType {
ALIGN, // align
ASTERISK, // *
ASTERISK_ASTERISK, // **
ASTERISK_EQUALS, // *=
BANG, // !
BANG_EQUALS, // !=
BREAK, // break
BYREF, // byref
BYVAL, // byval
CLASS, // class
COLD, // cold
COLON, // :
COLON_COLON, // ::
COMMA, // ,
CONTINUE, // continue
DO, // do
DOT, // .
EQUALS, // =
EQUALS_EQUALS, // ==
EXTERNAL, // external
FALSE, // false
FAT_ARROW, // =>
FOR, // for
FORMAT_STRING, // `some string`
FORWARD_SLASH, // /
FORWARD_SLASH_EQUALS, // /=
FUNCTION, // function
GLOBAL, // global
GREATER_EQUALS, // >=
HASH, // #
HIDDEN, // hidden
HOT, // hot
I64, // i64
IDENTIFIER, // something
IF, // if
IMPORT, // import
INTERNAL, // internal
INTERROBANG, // ?!
LEFT_ANGLE, // <
LEFT_CURLY, // {
LEFT_PARENTHESIS, // (
LEFT_SQUARE, // [
LESS_EQUALS, // <=
LET, // let
MINUS, // -
MINUS_EQUALS, // -=
MINUS_MINUS, // --
MODULE, // module
MONOTONIC, // monotonic
NOCAPTURE, // nocapture
NOFREE, // nofree
NONNULL, // nonnull
NORECURSE, // norecurse
NUMBER, // 6
PERCENT, // %
PERCENT_EQUALS, // %=
PIPE, // |
PLUS, // +
PLUS_PLUS, // ++
PLUS_EQUALS, // +=
PREALLOCATED, // preallocated
PRIVATE, // private
PROTECTED, // protected
PUBLIC, // public
QUESTION, // ?
QUESTION_COLON, // ?:
READONLY, // readonly
RETURN, // return
RIGHT_ANGLE, // >
RIGHT_CURLY, // }
RIGHT_PARENTHESIS, // )
RIGHT_SQUARE, // ]
SEMICOLON, // ;
SKINNY_ARROW, // ->
STRING, // "string" or 'string'
STRUCT, // struct
TILDE, // ~
TOKEN_EOF, // <No Visual Representation>
TRUE, // true
U64, // u64
UNORDERED, // unordered
VAR, // var
VOID, // void
WEAK, // weak
WHILE, // while
WRITEONLY, // writeonly
TOKEN_MAX
};
}
<file_sep>/src/expressions/expression.cpp
#include <expressions/expression.hpp>
namespace piper {
}
<file_sep>/src/includes/expressions/expression.hpp
#pragma once
#include <string>
namespace piper {
class Expression {
public:
virtual std::string toString() = 0;
};
}
<file_sep>/src/includes/statements/if_statement.hpp
#pragma once
#include <expressions/expression.hpp>
#include <statements/statement.hpp>
#include <data_type.hpp>
#include <vector>
#include <vector>
namespace piper {
class IfStatement : public Statement {
public:
IfStatement();
void set_condition(Expression *condition);
void set_then(Statement *then);
std::string toString();
protected:
Expression *condition;
Statement *then;
};
}
<file_sep>/src/statements/import_statement.cpp
#include <statements/import_statement.hpp>
#include <iomanip>
#include <sstream>
namespace piper {
ImportStatement::ImportStatement(std::string import_name) {
this->import_name = import_name;
}
std::string ImportStatement::toString() {
std::stringstream stream;
stream << "\"" << std::hex << this << "\"";
stream << " [label = \"ImportStatement\"];";
return stream.str();
}
}<file_sep>/src/includes/statements/return_statement.hpp
#pragma once
#include <expressions/expression.hpp>
#include <statements/statement.hpp>
namespace piper {
class ReturnStatement : public Statement {
public:
ReturnStatement(Expression *expression);
std::string toString();
protected:
Expression *expression;
};
}
<file_sep>/src/includes/data_type.hpp
#pragma once
namespace piper {
enum MetaType {
MT_UNKNOWN,
MT_CUSTOM,
MT_U64,
MT_I64
};
struct DataType {
MetaType type;
std::string extra_data;
};
}
<file_sep>/src/scanner.cpp
#include <scanner.hpp>
#include <fstream>
#include <iostream>
#include <map>
#include <vector>
using namespace piper;
struct SimpleTokenConfig {
TokenType type;
};
std::map<TokenType, std::string> tokenToString = {
{ ASTERISK, "ASTERISK (*)" },
{ ASTERISK_ASTERISK, "ASTERISK_ASTERISK (**)" },
{ ASTERISK_EQUALS, "ASTERISK_EQUALS (*=)" },
{ BANG, "BANG" },
{ BANG_EQUALS, "BANG_EQUALS" },
{ BREAK, "BREAK" },
{ CLASS, "CLASS" },
{ COLON, "COLON (:)" },
{ COLON_COLON, "COLON_COLON (::)" },
{ COMMA, "COMMA (,)" },
{ CONTINUE, "CONTINUE (continue)" },
{ DO, "DO (do)" },
{ DOT, "DOT (.)" },
{ EQUALS, "EQUALS (=)" },
{ EQUALS_EQUALS, "EQUALS_EQUALS (==)" },
{ FALSE, "FALSE (false)" },
{ FAT_ARROW, "FAT_ARROW (=>)" },
{ FOR, "FOR (for)" },
{ FORMAT_STRING, "FORMAT_STRING ()" },
{ FORWARD_SLASH, "FORWARD_SLASH (/)" },
{ FORWARD_SLASH_EQUALS, "FORWARD_SLASH_EQUALS (/=)" },
{ FUNCTION, "FUNCTION (function)" },
{ GLOBAL, "GLOBAL (global)" },
{ GREATER_EQUALS, "GREATER_EQUALS (>=)" },
{ HASH, "HASH (#)" },
{ HIDDEN, "HIDDEN (hidden)" },
{ I64, "I64 (i64)" },
{ IDENTIFIER, "IDENTIFIER ()" },
{ IF, "IF (if)" },
{ IMPORT, "IMPORT (import)" },
{ INTERROBANG, "INTERROBANG (?!)" },
{ LEFT_ANGLE, "LEFT_ANGLE (<)" },
{ LEFT_CURLY, "LEFT_CURLY ({)" },
{ LEFT_PARENTHESIS, "LEFT_PARENTHESIS (()" },
{ LEFT_SQUARE, "LEFT_SQUARE ([)" },
{ LESS_EQUALS, "LESS_EQUALS (<=)" },
{ LET, "LET (let)" },
{ MINUS, "MINUS (-)" },
{ MINUS_EQUALS, "MINUS_EQUALS (-=)" },
{ MINUS_MINUS, "MINUS_MINUS (--)" },
{ MODULE, "MODULE (module)" },
{ NUMBER, "NUMBER ()" },
{ PERCENT, "PERCENT (%)" },
{ PERCENT_EQUALS, "PERCENT_EQUALS (%=)" },
{ PIPE, "PIPE (|)" },
{ PLUS, "PLUS (+)" },
{ PLUS_PLUS, "PLUS_PLUS (++)" },
{ PLUS_EQUALS, "PLUS_EQUALS (+=)" },
{ PROTECTED, "PROTECTED (protected)" },
{ PRIVATE, "PRIVATE (private)" },
{ PUBLIC, "PUBLIC (public)" },
{ QUESTION, "QUESTION (?)" },
{ QUESTION_COLON, "QUESTIN_COLON (?:)" },
{ RETURN, "RETURN (return)" },
{ RIGHT_ANGLE, "RIGHT_ANGLE (>)" },
{ RIGHT_CURLY, "RIGHT_CURLY (})" },
{ RIGHT_PARENTHESIS, "RIGHT_PARENTHESIS ())" },
{ RIGHT_SQUARE, "RIGHT_SQUARE (])" },
{ SEMICOLON, "SEMICOLON (;)" },
{ SKINNY_ARROW, "SKINNY_ARROW (->)" },
{ STRING, "STRING ()" },
{ STRUCT, "STRUCT (struct)" },
{ TILDE, "TILDE (~)" },
{ TOKEN_EOF, "EOF ()" },
{ TRUE, "TRUE (true)" },
{ U64, "U64 (u64)" },
{ VAR, "VAR (var)" },
{ VOID, "VOID (void)" },
{ WHILE, "WHILE (while)" },
};
std::map<std::string, SimpleTokenConfig> keywordTokens = {
{ "false", { TokenType::FALSE } },
{ "function", { TokenType::FUNCTION } },
{ "global", { TokenType::GLOBAL } },
{ "hidden", { TokenType::HIDDEN} },
{ "i64", { TokenType::I64 } },
{ "if", { TokenType::IF } },
{ "import", { TokenType::IMPORT } },
{ "let", { TokenType::LET } },
{ "module", { TokenType::MODULE } },
{ "private", { TokenType::PRIVATE } },
{ "protected", { TokenType::PROTECTED } },
{ "public", { TokenType::PUBLIC} },
{ "return", { TokenType::RETURN } },
{ "struct", { TokenType::STRUCT } },
{ "true", { TokenType::TRUE } },
{ "u64", { TokenType::U64 } },
{ "var", { TokenType::VAR } },
{ "void", { TokenType::VOID } },
};
std::map<char, SimpleTokenConfig> simpleTokens = {
{ '{', { TokenType::LEFT_CURLY } },
{ '}', { TokenType::RIGHT_CURLY } },
{ '(', { TokenType::LEFT_PARENTHESIS } },
{ ')', { TokenType::RIGHT_PARENTHESIS } },
{ '.', { TokenType::DOT } }, // This is very likely to become more in the future.
{ ';', { TokenType::SEMICOLON } },
{ '[', { TokenType::LEFT_SQUARE } },
{ ']', { TokenType::RIGHT_SQUARE } },
{ ',', { TokenType::COMMA } },
{ '~', { TokenType::TILDE } },
{ '|', { TokenType::PIPE } },
{ '#', { TokenType::HASH } },
};
std::map<char, std::pair<SimpleTokenConfig, std::map<char, SimpleTokenConfig>>> doubleTokens = {
{
'+', { { TokenType::PLUS }, {
{ '+', { TokenType::PLUS_PLUS } },
{ '=', { TokenType::PLUS_EQUALS } },
}}
},
{
'*', { { TokenType::ASTERISK }, {
{ '*', { TokenType::ASTERISK_ASTERISK } },
{ '=', { TokenType::ASTERISK_EQUALS } },
}}
},
{
'-', { { TokenType::MINUS }, {
{ '>', { TokenType::SKINNY_ARROW } },
{ '-', { TokenType::MINUS_MINUS } },
{ '=', { TokenType::MINUS_EQUALS } },
}}
},
{
'=', { { TokenType::EQUALS }, {
{ '>', { TokenType::FAT_ARROW } },
{ '=', { TokenType::EQUALS_EQUALS } },
}}
},
{
':', { { TokenType::COLON }, {
{ ':', { TokenType::COLON_COLON } },
}}
},
{
'/', { { TokenType::FORWARD_SLASH }, {
{ '=', { TokenType::FORWARD_SLASH_EQUALS } },
}}
},
{
'!', { { TokenType::BANG }, {
{ '=', { TokenType::BANG_EQUALS } },
}}
},
{
'%', { { TokenType::PERCENT }, {
{ '=', { TokenType::PERCENT_EQUALS } },
}}
},
{
'<', { { TokenType::LEFT_ANGLE }, {
{ '=', { TokenType::LESS_EQUALS } },
}}
},
{
'>', { { TokenType::RIGHT_ANGLE }, {
{ '=', { TokenType::GREATER_EQUALS } },
}}
},
{
'?', { { TokenType::QUESTION }, {
{ ':', { TokenType::QUESTION_COLON } },
{ '!', { TokenType::INTERROBANG } },
}}
}
};
namespace piper {
Scanner::Scanner(std::string filename) {
this->filename = filename;
}
std::string Scanner::getTokenName(TokenType tokenType) {
if (tokenToString.find(tokenType) != tokenToString.end()) {
return tokenToString[tokenType];
}
return "UNKNOWN";
}
std::vector<Token *> *Scanner::getTokens() {
std::ifstream file;
file.open(filename);
int line = 1;
int column = 1;
auto tokens = new std::vector<Token *>();
Location start_location;
start_location.filename = filename;
Location end_location;
end_location.filename = filename;
while (true) {
if (file.eof()) {
break;
}
char c = file.peek();
if (c == EOF) {
break;
}
// Whitespace outside of a token. Adjust some internal counters,
// but don't REALLY do anything with them.
if (c == '\n') {
line++;
column = 1;
file.get();
continue;
}
if (isspace(c) != 0) {
column++;
file.get();
continue;
}
if (isalpha(c) != 0) {
std::string buffer;
start_location.line = line;
start_location.column = column;
while (true) {
buffer += c;
file.get();
column++;
c = file.peek();
if (isalnum(c) == 0 && c != '_') {
end_location.line = line;
end_location.column = column;
break;
}
}
auto t = new Token();
t->start = start_location;
t->end = end_location;
t->str = buffer;
if (keywordTokens.find(buffer) != keywordTokens.end()) {
t->type = keywordTokens.find(buffer)->second.type;
} else {
t->type = TokenType::IDENTIFIER;
}
tokens->push_back(t);
continue;
}
// TODO: Support floating points.
if (isdigit(c) != 0) {
std::string buffer;
start_location.line = line;
start_location.column = column;
while (true) {
buffer += c;
file.get();
column++;
c = file.peek();
if (isdigit(c) == 0) {
end_location.line = line;
end_location.column = column;
break;
}
}
auto t = new Token();
t->start = start_location;
t->end = end_location;
t->str = buffer;
t->type = TokenType::NUMBER;
tokens->push_back(t);
continue;
}
// TODO: For the time being this is 100% the same as a double-quoted string. I need to do something special for this.
if (c == '`') {
std::string buffer;
start_location.line = line;
start_location.column = column;
file.get(); column++;
c = file.peek();
while (c != '`') {
if (c == EOF) {
// This should never happen with good code.
break;
}
if (c == '\\') {
file.get(); column++;
c = file.peek();
buffer += c;
file.get(); column++;
c = file.peek();
continue;
} else {
buffer += c;
file.get(); column++;
c = file.peek();
}
}
end_location.line = line;
end_location.column = column;
file.get(); column++;
c = file.peek();
Token *t = new Token();
t->start = start_location;
t->end = end_location;
t->type = TokenType::FORMAT_STRING;
t->str = buffer;
tokens->push_back(t);
continue;
}
if (c == '"') {
std::string buffer;
start_location.line = line;
start_location.column = column;
file.get(); column++;
c = file.peek();
while (c != '"') {
if (c == EOF) {
// This should never happen with good code.
break;
}
if (c == '\\') {
file.get(); column++;
c = file.peek();
buffer += c;
file.get(); column++;
c = file.peek();
continue;
} else {
buffer += c;
file.get(); column++;
c = file.peek();
}
}
end_location.line = line;
end_location.column = column;
file.get(); column++;
c = file.peek();
Token *t = new Token();
t->start = start_location;
t->end = end_location;
t->type = TokenType::STRING;
t->str = buffer;
tokens->push_back(t);
continue;
}
if (c == '\'') {
std::string buffer;
start_location.line = line;
start_location.column = column;
file.get(); column++;
c = file.peek();
while (c != '\'') {
if (c == EOF) {
// This should never happen with good code.
break;
}
if (c == '\\') {
file.get(); column++;
c = file.peek();
buffer += c;
file.get(); column++;
c = file.peek();
continue;
} else {
buffer += c;
file.get(); column++;
c = file.peek();
}
}
end_location.line = line;
end_location.column = column;
file.get(); column++;
c = file.peek();
Token *t = new Token();
t->start = start_location;
t->end = end_location;
t->type = TokenType::STRING;
t->str = buffer;
tokens->push_back(t);
continue;
}
if (doubleTokens.find(c) != doubleTokens.end()) {
start_location.line = line;
start_location.column = column;
std::string buffer;
buffer += c;
column++;
file.get();
auto def = doubleTokens.find(c)->second.first;
auto possibilities = doubleTokens.find(c)->second.second;
c = file.peek();
if (possibilities.find(c) != possibilities.end()) {
column++;
file.get();
end_location.line = line;
end_location.column = column;
buffer += c;
auto t = new Token();
t->start = start_location;
t->end = end_location;
t->type = possibilities.find(c)->second.type;
t->str = buffer;
tokens->push_back(t);
continue;
} else {
end_location.line = line;
end_location.column = column;
auto t = new Token();
t->start = start_location;
t->end = end_location;
t->type = def.type;
t->str = buffer;
tokens->push_back(t);
continue;
}
}
if (simpleTokens.find(c) != simpleTokens.end()) {
start_location.line = line;
start_location.column = column;
std::string buffer;
buffer += c;
column++;
file.get();
end_location.line = line;
end_location.column = column;
auto t = new Token();
t->start = start_location;
t->end = end_location;
t->type = simpleTokens.find(c)->second.type;
t->str = buffer;
tokens->push_back(t);
continue;
}
std::cout << "UNKNOWN: " << c << std::endl;
file.get();
column++;
}
auto t = new Token();
t->start = start_location;
t->end = end_location;
t->type = TokenType::TOKEN_EOF;
t->str = "<EOF>";
tokens->push_back(t);
return tokens;
}
}<file_sep>/src/stage_filetotokens.cpp
#include <stage_filetotokens.hpp>
#include <scanner.hpp>
#include <cstring>
#include <iostream>
namespace piper {
FileToTokens::FileToTokens(std::string filename) {
this->filename = filename;
this->debug = true;
}
bool FileToTokens::shouldRun() {
return true;
}
void FileToTokens::run(
std::map<std::string, parse_result> *results
) {
auto *scanner = new Scanner(this->filename);
parse_result pr;
// 9 -- magic number
// 1 -- file version
// 1 -- # of strings
pr.output_size = 9 + 1 + 1;
auto tokens = scanner->getTokens();
std::vector<std::string> static_strings;
for (auto token : *tokens) {
// one byte for the opcode itself
// one for the line number
// one for the column number
pr.output_size += 3;
switch (token->type) {
case piper::TokenType::FORMAT_STRING:
case piper::TokenType::IDENTIFIER:
case piper::TokenType::NUMBER:
case piper::TokenType::STRING:
{
bool found = false;
for (auto s: static_strings) {
if (s.compare(token->str) == 0) {
found = true;
break;
}
}
if (!found) {
// 1 -- size
pr.output_size += 1 + token->str.size();
static_strings.push_back(token->str);
}
// Storing the str_id regardless of if this string is "new"
pr.output_size += 1;
}
break;
}
}
char file_version = 0;
const char *magic = "PPRALCFTT";
pr.bytes = (char *)malloc(sizeof(char) * pr.output_size);
int pr_idx = 0;
for (int i = 0; i < strlen(magic); i++) {
pr.bytes[pr_idx++] = magic[i];
}
pr.bytes[pr_idx++] = file_version;
pr.bytes[pr_idx++] = static_strings.size();
for (int i = 0; i < static_strings.size(); i++) {
auto s = static_strings.at(i);
char len = s.length();
pr.bytes[pr_idx++] = len;
for (int i = 0; i < len; i++) {
pr.bytes[pr_idx++] = s.at(i);
}
}
for (auto token : *tokens) {
char c = static_cast<char>(token->type);
pr.bytes[pr_idx++] = c;
pr.bytes[pr_idx++] = token->start.line;
pr.bytes[pr_idx++] = token->start.column;
switch (token->type) {
case piper::TokenType::FORMAT_STRING:
case piper::TokenType::IDENTIFIER:
case piper::TokenType::NUMBER:
case piper::TokenType::STRING:
{
for (int i = 0; i < static_strings.size(); i++) {
auto s = static_strings.at(i);
if (s.compare(token->str) == 0) {
c = static_cast<char>(i);
pr.bytes[pr_idx++] = c;
break;
}
}
}
break;
}
}
std::string out_filename = this->filename + ".ftt";
this->write_file(pr, out_filename);
(*results)["tokens"] = pr;
}
}
<file_sep>/src/piper.cpp
#include <fstream>
#include <iostream>
#include <string>
#include <string.h>
#include <scanner.hpp>
#include <stage_filetotokens.hpp>
#include <stage_tokenstotree.hpp>
// For each stage:
// a) Do we run this stage?
// b) Do we write this out to a file at all?
// c) What stages are we passing this info on to?
// *) We could just store the output and let the future stages grab.
void parse_file(std::string filename) {
std::map<std::string /* pass_name */, piper::parse_result> results;
std::vector<piper::Stage *> stages = {
new piper::FileToTokens(filename),
new piper::TokensToTree(filename)
};
for (auto stage: stages) {
if (stage->shouldRun()) {
stage->run(&results);
}
}
}
int main(int argc, char *argv[]) {
std::string my_name = argv[0];
if (argc <= 1) {
std::cout << "Usage: " << my_name << " filename" << std::endl;
return 0;
}
std::string filename = argv[1];
parse_file(filename);
}<file_sep>/src/stage_tokenstotree.cpp
#include <stage_tokenstotree.hpp>
#include <scanner.hpp>
#include <expressions/add_expression.hpp>
#include <expressions/call_expression.hpp>
#include <expressions/double_colon_expression.hpp>
#include <expressions/format_string_expression.hpp>
#include <expressions/greater_than_expression.hpp>
#include <expressions/identifier_expression.hpp>
#include <expressions/less_than_expression.hpp>
#include <expressions/number_expression.hpp>
#include <expressions/sub_expression.hpp>
#include <statements/block_statement.hpp>
#include <statements/expression_statement.hpp>
#include <statements/function_statement.hpp>
#include <statements/if_statement.hpp>
#include <statements/import_statement.hpp>
#include <statements/return_statement.hpp>
#include <cassert>
#include <cstring>
#include <iostream>
#define BYTES_PER_INSTRUCTION 3
namespace piper {
TokensToTree::TokensToTree(std::string filename) {
this->filename = filename;
this->debug = true;
this->idx = 0;
}
bool TokensToTree::shouldRun() {
return true;
}
void TokensToTree::parse_strings(parse_result results) {
char num_strings = results.bytes[this->idx++];
for (int i = 0; i < num_strings; i++) {
char str_len = results.bytes[this->idx++];
std::string str(&(results.bytes[this->idx]), str_len);
this->idx += str_len;
this->embedded_strings.push_back(str);
}
}
Expression *TokensToTree::parse_expression(parse_result tokens) {
auto expression = this->comparison_expression(tokens);
return expression;
}
Expression *TokensToTree::comparison_expression(parse_result tokens) {
auto left = this->term_expression(tokens);
if (left == NULL) {
std::cout << "In comparison_expression, got no left." << std::endl;
return NULL;
}
TokenType tt = static_cast<TokenType>(tokens.bytes[this->idx]);
switch (tt) {
case TokenType::LEFT_ANGLE:
{
this->idx += BYTES_PER_INSTRUCTION;
auto right = this->term_expression(tokens);
if (right == NULL) {
return NULL;
}
return new LessThanExpression(left, right);
}
break;
case TokenType::RIGHT_ANGLE:
{
this->idx += BYTES_PER_INSTRUCTION;
auto right = this->term_expression(tokens);
if (right == NULL) return NULL;
return new GreaterThanExpression(left, right);
}
break;
default:
return left;
}
}
Expression *TokensToTree::term_expression(parse_result tokens) {
auto expression = this->factor_expression(tokens);
if (expression == NULL) return NULL;
while (true) {
TokenType tt = static_cast<TokenType>(tokens.bytes[this->idx]);
switch (tt) {
case TokenType::MINUS:
{
this->idx += BYTES_PER_INSTRUCTION;
auto right = this->factor_expression(tokens);
return new SubExpression(expression, right);
}
break;
case TokenType::PLUS:
{
this->idx += BYTES_PER_INSTRUCTION;
auto right = this->factor_expression(tokens);
return new AddExpression(expression, right);
break;
}
default:
return expression;
}
}
return expression;
}
Expression *TokensToTree::factor_expression(parse_result tokens) {
auto expression = this->unary_expression(tokens);
return expression;
}
Expression *TokensToTree::unary_expression(parse_result tokens) {
auto expression = this->call_expression(tokens);
return expression;
}
Expression *TokensToTree::call_expression(parse_result tokens) {
auto left = this->primary_expression(tokens);
TokenType tmp = static_cast<TokenType>(tokens.bytes[this->idx]);
if (tmp == TokenType::LEFT_PARENTHESIS) {
this->idx += BYTES_PER_INSTRUCTION;
auto call_expression = new CallExpression(left);
while (true) {
tmp = static_cast<TokenType>(tokens.bytes[this->idx]);
if (tmp == TokenType::RIGHT_PARENTHESIS) {
this->idx += BYTES_PER_INSTRUCTION;
break;
}
auto argument_expression = this->parse_expression(tokens);
tmp = static_cast<TokenType>(tokens.bytes[this->idx]);
if (tmp == TokenType::COLON) {
// argument_expression is actually the name
this->idx += BYTES_PER_INSTRUCTION;
auto actual_argument_expression = this->parse_expression(tokens);
// TODO: We are ignoring the argument name here. Bad.
call_expression->add_argument(actual_argument_expression);
} else if (tmp == TokenType::COMMA) {
this->idx += BYTES_PER_INSTRUCTION;
call_expression->add_argument(argument_expression);
continue;
} else if (tmp == TokenType::RIGHT_PARENTHESIS) {
// this->idx += BYTES_PER_INSTRUCTION;
call_expression->add_argument(argument_expression);
continue;
}
}
return call_expression;
}
return left;
}
Expression *TokensToTree::primary_expression(parse_result tokens) {
TokenType tmp = static_cast<TokenType>(tokens.bytes[this->idx]);
this->idx += BYTES_PER_INSTRUCTION;
switch (tmp) {
case TokenType::LEFT_PARENTHESIS:
{
this->primary_expression(tokens);
tmp = static_cast<TokenType>(tokens.bytes[this->idx]);
this->idx += BYTES_PER_INSTRUCTION;
assert(tmp == TokenType::RIGHT_PARENTHESIS);
}
break;
case TokenType::IDENTIFIER:
{
char str_id = tokens.bytes[this->idx++];
auto identifier_expression = new IdentifierExpression(this->embedded_strings.at(str_id));
tmp = static_cast<TokenType>(tokens.bytes[this->idx]);
switch (tmp) {
case TokenType::COLON_COLON:
{
this->idx += BYTES_PER_INSTRUCTION;
auto right = this->primary_expression(tokens);
return new DoubleColonExpression(identifier_expression, right);
}
break;
default:
return identifier_expression;
}
}
break;
case TokenType::FORMAT_STRING:
{
char str_id = tokens.bytes[this->idx++];
auto format_string_expression = new FormatStringExpression(this->embedded_strings.at(str_id));
return format_string_expression;
}
break;
case TokenType::NUMBER:
{
char str_id = tokens.bytes[this->idx++];
auto number_expression = new NumberExpression(this->embedded_strings.at(str_id));
return number_expression;
}
break;
default:
std::cout << "Failed at primary: " << Scanner::getTokenName(tmp) << std::endl;
exit(-1);
}
return NULL;
}
Statement *TokensToTree::parse_statement(parse_result tokens) {
TokenType tmp = static_cast<TokenType>(tokens.bytes[this->idx]);
this->idx += BYTES_PER_INSTRUCTION;
switch (tmp) {
case TokenType::IF:
{
auto if_statement = new IfStatement();
tmp = static_cast<TokenType>(tokens.bytes[this->idx]);
this->idx += BYTES_PER_INSTRUCTION;
assert(tmp == TokenType::LEFT_PARENTHESIS);
auto condition = this->parse_expression(tokens);
if_statement->set_condition(condition);
tmp = static_cast<TokenType>(tokens.bytes[this->idx]);
this->idx += BYTES_PER_INSTRUCTION;
assert(tmp == TokenType::RIGHT_PARENTHESIS);
if_statement->set_then(
this->parse_block(tokens)
);
return if_statement;
}
break;
case TokenType::RETURN:
{
auto expression = this->parse_expression(tokens);
tmp = static_cast<TokenType>(tokens.bytes[this->idx]);
this->idx += BYTES_PER_INSTRUCTION;
assert(tmp == TokenType::SEMICOLON);
return new ReturnStatement(expression);
}
break;
case TokenType::IDENTIFIER:
{
// This is dumb.
this->idx -= BYTES_PER_INSTRUCTION;
auto expression = this->parse_expression(tokens);
TokenType tmp = static_cast<TokenType>(tokens.bytes[this->idx]);
this->idx += BYTES_PER_INSTRUCTION;
assert(tmp == TokenType::SEMICOLON);
return new ExpressionStatement(expression);
}
break;
default:
{
std::cout << "Bad statement start" << std::endl;
this->idx += BYTES_PER_INSTRUCTION;
}
break;
}
return NULL;
}
Statement *TokensToTree::parse_block(parse_result tokens) {
TokenType tmp = static_cast<TokenType>(tokens.bytes[this->idx]);
if (tmp != TokenType::LEFT_CURLY) {
return this->parse_statement(tokens);
}
this->idx += BYTES_PER_INSTRUCTION;;
auto block_statement = new BlockStatement();
while (true) {
// Note: We do not advance here.
tmp = static_cast<TokenType>(tokens.bytes[this->idx]);
if (tmp == TokenType::RIGHT_CURLY) {
this->idx += BYTES_PER_INSTRUCTION;
return block_statement;
}
block_statement->append(
this->parse_statement(tokens)
);
}
}
void TokensToTree::parse_function_arguments(parse_result tokens, FunctionStatement *function) {
while (true) {
TokenType tmp = static_cast<TokenType>(tokens.bytes[this->idx]);
if (tmp == TokenType::RIGHT_PARENTHESIS) break;
this->idx += BYTES_PER_INSTRUCTION;
assert(tmp == TokenType::U64);
DataType dt;
dt.type = MetaType::MT_U64;
tmp = static_cast<TokenType>(tokens.bytes[this->idx]);
this->idx += BYTES_PER_INSTRUCTION;
assert(tmp == TokenType::COLON);
tmp = static_cast<TokenType>(tokens.bytes[this->idx]);
this->idx += BYTES_PER_INSTRUCTION;
assert(tmp == TokenType::IDENTIFIER);
char str_id = tokens.bytes[this->idx++];
std::string arg_name = this->embedded_strings.at(str_id);
function->add_arg(arg_name, dt);
}
}
Statement *TokensToTree::parse_top_level_statement(parse_result tokens) {
TokenType tokenType = static_cast<TokenType>(tokens.bytes[this->idx]);
this->idx += BYTES_PER_INSTRUCTION;
switch (tokenType) {
case TokenType::IMPORT:
{
TokenType tmp = static_cast<TokenType>(tokens.bytes[this->idx]);
this->idx += BYTES_PER_INSTRUCTION;
assert(tmp == TokenType::MODULE);
tmp = static_cast<TokenType>(tokens.bytes[this->idx]);
this->idx += BYTES_PER_INSTRUCTION;
assert(tmp == TokenType::STRING);
char str_id = tokens.bytes[this->idx++];
tmp = static_cast<TokenType>(tokens.bytes[this->idx]);
this->idx += BYTES_PER_INSTRUCTION;
assert(tmp == TokenType::SEMICOLON);
return new ImportStatement(this->embedded_strings.at(str_id));
}
break;
case TokenType::FUNCTION:
{
TokenType tmp = static_cast<TokenType>(tokens.bytes[this->idx]);
this->idx += BYTES_PER_INSTRUCTION;
assert(tmp == TokenType::IDENTIFIER);
char str_id = tokens.bytes[this->idx++];
std::string function_name = this->embedded_strings.at(str_id);
auto *function = new FunctionStatement(function_name);
tmp = static_cast<TokenType>(tokens.bytes[this->idx]);
this->idx += BYTES_PER_INSTRUCTION;
assert(tmp == TokenType::LEFT_PARENTHESIS);
this->parse_function_arguments(tokens, function);
tmp = static_cast<TokenType>(tokens.bytes[this->idx]);
this->idx += BYTES_PER_INSTRUCTION;
assert(tmp == TokenType::RIGHT_PARENTHESIS);
// We're done with the argument list. Return value!
tmp = static_cast<TokenType>(tokens.bytes[this->idx]);
this->idx += BYTES_PER_INSTRUCTION;
assert(tmp == TokenType::COLON);
tmp = static_cast<TokenType>(tokens.bytes[this->idx]);
this->idx += BYTES_PER_INSTRUCTION;
assert(
(tmp == TokenType::U64) ||
(tmp == TokenType::I64)
);
switch (tmp) {
case TokenType::U64:
{
DataType dt;
dt.type = MT_U64;
function->set_return_type(dt);
}
break;
case TokenType::I64:
{
DataType dt;
dt.type = MT_I64;
function->set_return_type(dt);
}
break;
}
function->set_body(this->parse_block(tokens));
return function;
}
break;
default:
std::cout << "ERROR: Cannot start top-level statement with " << Scanner::getTokenName(tokenType) << std::endl;
break;
}
std::cout << "parse_top_level_statement:" << Scanner::getTokenName(tokenType) << std::endl;
return NULL;
}
void TokensToTree::run(
std::map<std::string, parse_result> *results
) {
parse_result tokens = results->at("tokens");
if (strncmp("PPRALCFTT", tokens.bytes, 9) != 0) {
std::cout << "ERROR: Invalid magic signature for tokens: %.*s" << std::endl;
return;
}
// Skip magic bytes and (ignored, for now) version
this->idx = 10;
this->parse_strings(tokens);
std::cout << "digraph {\n" << std::endl;
while (true) {
TokenType tokenType = static_cast<TokenType>(tokens.bytes[this->idx]);
if (tokenType == TokenType::TOKEN_EOF) break;
Statement *statement = this->parse_top_level_statement(tokens);
if (statement == NULL) {
std::cout << "Top level statement was NULL" << std::endl;
} else {
std::cout << statement->toString() << std::endl;
}
}
std::cout << "}\n" << std::endl;
}
}
<file_sep>/src/expressions/format_string_expression.cpp
#include <expressions/format_string_expression.hpp>
#include <iomanip>
#include <sstream>
namespace piper {
FormatStringExpression::FormatStringExpression(std::string format_string) {
this->format_string = format_string;
}
std::string FormatStringExpression::toString() {
std::stringstream stream;
stream << "\"" << std::hex << this << "\"";
stream << " [label=\"Format String: ";
stream << this->format_string;
stream << "\"];\n";
return stream.str();
}
}
<file_sep>/src/expressions/double_colon_expression.cpp
#include <expressions/double_colon_expression.hpp>
#include <iomanip>
#include <sstream>
namespace piper {
DoubleColonExpression::DoubleColonExpression(Expression *left, Expression *right) {
this->left = left;
this->right = right;
}
std::string DoubleColonExpression::toString() {
std::stringstream stream;
stream << "\"" << std::hex << this << "\"";
stream << " [label=\"Double Colon\"];\n";
stream << "\"" << std::hex << this << "\"";
stream << " -> ";
stream << "\"" << std::hex << this->left << "\"";
stream << ";\n";
stream << this->left->toString();
stream << "\"" << std::hex << this << "\"";
stream << " -> ";
stream << "\"" << std::hex << this->right << "\"";
stream << ";\n";
stream << this->right->toString();
return stream.str();
}
}
<file_sep>/docs/STAGES.md
# Stages
## File To Tokens
Reads the text file and generates a stream of tokens. Those tokens are not at this point parsed in any way.
## Tokens To Tree
Takes the tokens as generated by File To Tokens and creates a Concrete Syntax Tree.<file_sep>/src/includes/stage.hpp
#pragma once
#include <fstream>
#include <map>
#include <string>
namespace piper {
typedef struct parse_result_t {
uint16_t output_size;
char *bytes;
} parse_result;
class Stage {
public:
// TODO: I need to pass in some things so that the stages can make
// a good decision. Flags and previous stage outputs,
// probably.
virtual bool shouldRun() = 0;
// TODO: Need to pass in compiler flags and the output of previous
// stages. Writable so I can write the output of my stage.
virtual void run(
std::map<std::string, parse_result> *previous_results
) = 0;
void write_file(parse_result result, std::string out_filename) {
std::ofstream fout;
fout.open(out_filename, std::ios::binary | std::ios::out);
fout.write(result.bytes, sizeof(char) * result.output_size);
fout.close();
}
protected:
private:
};
}
<file_sep>/src/includes/statements/function_statement.hpp
#pragma once
#include <statements/statement.hpp>
#include <data_type.hpp>
#include <vector>
namespace piper {
class FunctionStatement : public Statement {
public:
FunctionStatement(std::string function_name);
void set_return_type(DataType return_type);
void add_arg(std::string arg_name, DataType data_type);
void set_body(Statement *body);
std::string toString();
protected:
std::string function_name;
DataType return_type;
Statement *body;
std::vector<std::pair<std::string, DataType>> args;
};
}
<file_sep>/src/includes/statements/expression_statement.hpp
#pragma once
#include <expressions/expression.hpp>
#include <statements/statement.hpp>
namespace piper {
class ExpressionStatement : public Statement {
public:
ExpressionStatement(Expression *expression);
std::string toString();
protected:
Expression *expression;
};
}
<file_sep>/src/statements/expression_statement.cpp
#include <statements/expression_statement.hpp>
#include <iomanip>
#include <sstream>
namespace piper {
ExpressionStatement::ExpressionStatement(Expression *expression) {
this->expression = expression;
}
std::string ExpressionStatement::toString() {
std::stringstream stream;
stream << "\"" << std::hex << this << "\"";
stream << " [label=\"Expression Statement\"];\n";
stream << "\"" << std::hex << this << "\"";
stream << " -> ";
stream << "\"" << std::hex << this->expression << "\"";
stream << ";\n";
stream << this->expression->toString();
return stream.str();
}
}<file_sep>/src/includes/stage_filetotokens.hpp
#pragma once
#include <stage.hpp>
namespace piper {
class FileToTokens : public Stage {
public:
FileToTokens(std::string filename);
bool shouldRun();
void run(
std::map<std::string, parse_result> *results
);
protected:
bool debug;
std::string filename;
private:
};
}
<file_sep>/docs/SYNTAX.md
# Syntax
This file describes the syntax of Piper using BNF (or at least a version of it, I may not be doing it 100% strictly correctly). If you have never read BNF before, this probably isn't the right document for you. Whenever I write friendlier documentation I should link that here.
## Identifier
identifier ::= [a-zA-Z_][a-zA-Z0-9_]*
Identifiers make up valid variable names, namespace fragments, etc. They are used quite a lot.
## File
file ::= <import-statement>* <file-level-annotation>* ( <struct-file> | <function-file> )
struct-file ::= <struct-level-annotation>* <struct>
function-file ::= <function-level-annotations>? <function>
A file has a very strict order, enforced for purposes of readability and consistency. While most parts are optional, when they exist they must be in a specific order.
A file can only define a single thing, and it must be the same name as the file itself. TODO: Should I make the top-level objects name implied? Is that too implicit?
### Import Statements
import-statement ::= 'import' <namespace> ( 'as' <identifier> )?
namespace ::= <identifier> ( '.' <identifier> )*
The import statement will load the top-level symbol in the given namespace and makes it available in this file. It does not transitively load namespaces that are loaded by the other file. If you give an 'as' identifier, the top-level symbol will be available under the new name rather than its actual name.
### File-Level Annotations
file-level-annotation ::= '@' ( <namespace-annotation> )
File level annotations are annotations that affect the entire file. Currently there is only one, but I expect more to be added.
#### Namespace
namespace-annotation ::= 'namespace' '(' <namespace> ')'
The namespace annotation sets what namespace this file is considered to be under. A single file can only be in a single namespace. The namespace **should** be reflective of the file path, though the exact mechanism and how far it will be enforced is still up in the air.
### Struct-Level Annotations
struct-level-annotation ::= '@' ( <implements-annotation> | <mixin-annotation> | <testclass-annotation> )
Struct level annotations are annotations that apply to the struct at a data level. They are currently ill-defined but I hope to flesh out the precise mechanics soon.
#### Implements
implements-annotation ::= 'implements' '(' namespace ')'
This should annotate that this struct is meant to be an implementation of an interface. This is tricky to fully define in a separate-code-and-data world.
#### Mixin
mixin-annotation ::= 'mixin' '(' namespace ')'
The resulting type has all of the data members of this struct as well as the data members of the "mixin" struct. If names conflict, this is currently an error (I plan on adding a mechanism to disambiguate soon).
#### Test Class
testclass-annotation ::= 'testclass' '(' namespace ')'
Annotate what class is responsible for testing this one. This gets trickier in a separate-code-and-data world, so it needs to be revisited once that is more fully fleshed out.
### Struct
struct-declaration := 'struct' <identifier> <struct-body>
struct-body := '{' <struct-body-declaration>+ '}'
struct-body-declaration := <identifier> ':' <type> ';'
Structures are data-only.
### Function
function-declaration := <function-header> <block>
function-header := 'function' <identifier> '(' <formal-parameter-list> ')' ':' <type>
formal-parameter-list := <formal-parameter>*
formal-parameter := <identifier> ':' <type>
### Statements
statement := <return-statement>
| <expression-statement>
| <block>
| <if-then-statement>
| <if-then-else-statement>
| <if-then-elseif-statement>
| <if-then-elseif-else-statement>
| <switch-statement>
| <do-statement>
| <break-statement>
| <continue-statement>
| <for-statement>
#### Return Statement
return-statement := 'return' <expression> ';'
#### Expression Statement
expression-statement := <expression> ';'
#### Block
block := '{' <statement>* '}'
#### If Statements
if-then-statement := 'if' '(' <expression> ')' <statement>
if-then-else-statement := 'if' '(' <expression> ')' <statement> 'else' <statement>
if-then-elseif-statement := 'if' '(' <expression> ')' <statement> ( 'else if' '(' <expression> ')' <statement> )+
if-then-elseif-else-statement := 'if' '(' <expression> ')' <statement> ( 'else if' '(' <expression> ')' <statment> )+ 'else' <statement>
#### Switch Statement
switch-statement := 'switch' '(' <expression> ')' '{' <switch-case>+ '}'
switch-case := 'case' <expression> ':' <statement>
| 'default' ':' <statement>
#### Do Statement
do-statement := 'do' <statement> 'while' '(' <expression> ')' ';'
#### Break Statement
break-statement := 'break' ';'
#### Continue Statement
continue-statement := 'continue' ';'
#### For Statement
for-statement := 'for' '(' <expression>? ';' <expression> ';' <expression> ')' <statement>
#### While Statement
while-statement := 'while' '(' <expression> ')' <statement>
### Expressions
#### Expression
expression := <assignment-expression>
#### Assignment Expression
assignment-expression := <conditional-expression> | <assignment>
assignment := <left-hand-side> <assignment-operator> <assignment-expression>
left-hand-side := <expression-name> | <field-access> | <array-access>
assignment-operator := '=' | '*=' | '/=' | '%=' | '+=' | '-=' | '<<=' | '>>=' | '>>>=' | '&=' | '^=' | '|='
#### Conditional Expression
conditional-expression := <conditional-or-expression>
| <conditional-or-expression> '?' <expression> ':' <conditional-expression>
conditional-or-expression := <conditional-and-expression>
| <conditional-or-expression> '||' <conditional-and-expression>
conditional-and-expression := <incusive-or-expression>
| <conditional-and-expression>
| <exclusive-or-experssion>
inclusive-or-expression := <exclusive-or-expression>
| <inclusive-or-expression>
| <exclusive-or-expression>
exclusive-or-expression := <and-expression>
| <exclusive-or-expression> '^' <and-expression>
and-expression := <equality-expression>
| <and-expression> '&' <equality-expression>
equality-expression := <relational-expression>
| <equality-expression> '==' <relational-expression>
| <equality-expression> '!=' <relational-expression>
relational-expression := <shift-expression>
| <relational-expression> '<' <shift-expression>
| <relational-expression> '>' <shift-expression>
| <relational-expression> '<=' <shift-expression>
| <relational-expression> '>=' <shift-expression>
| <relational-expression> 'instanceof' <reference-type>
shift-expression := <additive-expression>
| <shift-expression> '<<' <additive-expression>
| <shift-expression> '>>' <additive-expression>
| <shift-expression> '>>>' <additive-expression>
additive-expression
### Misc
local-variable-declaration-statement := <local-variable-declaration> ';'
local-variable-declaration := <type> <variable-declarators>
statement-expression := <assignment>
| <preincrement-expression>
| <postincrement-expression>
| <predecrement-expression>
| <postdecrement-expression>
| <method-invocation>
| <class-instance-creation-expression>
conditional-and-expression := <inclusive-or-expression> | <conditional-and-expression> | <exclusive-or-expression>
### Function<file_sep>/src/expressions/identifier_expression.cpp
#include <expressions/identifier_expression.hpp>
#include <iomanip>
#include <sstream>
namespace piper {
IdentifierExpression::IdentifierExpression(std::string identifier_name) {
this->identifier_name = identifier_name;
}
std::string IdentifierExpression::toString() {
std::stringstream stream;
stream << "\"" << std::hex << this << "\"";
stream << " [ label = \"{ <f0> Identifier: ";
stream << this->identifier_name;
stream << "| <f1> Data Type: UNKNOWN }\"; shape = \"record\" ];\n";
return stream.str();
}
}
<file_sep>/src/statements/return_statement.cpp
#include <statements/return_statement.hpp>
#include <iomanip>
#include <sstream>
namespace piper {
ReturnStatement::ReturnStatement(Expression *expression) {
this->expression = expression;
}
std::string ReturnStatement::toString() {
std::stringstream stream;
stream << "\"" << std::hex << this << "\"";
stream << " [label=\"Return Statement\"];\n";
stream << "\"" << std::hex << this << "\"";
stream << " -> ";
stream << "\"" << std::hex << this->expression << "\"";
stream << ";\n";
stream << this->expression->toString();
return stream.str();
}
}<file_sep>/src/includes/expressions/identifier_expression.hpp
#pragma once
#include <expressions/expression.hpp>
namespace piper {
class IdentifierExpression : public Expression {
public:
IdentifierExpression(std::string identifier_name);
std::string toString();
protected:
std::string identifier_name;
};
}
<file_sep>/src/expressions/call_expression.cpp
#include <expressions/call_expression.hpp>
#include <iomanip>
#include <sstream>
namespace piper {
CallExpression::CallExpression(Expression *left) {
this->left = left;
}
void CallExpression::add_argument(Expression *argument) {
this->arguments.push_back(argument);
}
std::string CallExpression::toString() {
std::stringstream stream;
stream << "\"" << std::hex << this << "\"";
stream << " [label=\"Call Expression\"];\n";
stream << "\"" << std::hex << this << "\"";
stream << " -> ";
stream << "\"" << std::hex << this->left << "\"";
stream << " [ label = \"Base\" ];\n";
stream << this->left->toString();
for (int i = 0; i < this->arguments.size(); i++) {
auto argument = this->arguments.at(i);
stream << "\"" << std::hex << this << "\"";
stream << " -> ";
stream << "\"" << std::hex << argument << "\"";
stream << " [ label = \"";
stream << std::dec << i;
stream << "\"];\n";
stream << argument->toString();
}
return stream.str();
}
}
<file_sep>/src/piper-text-to-token.cpp
#include <fstream>
#include <iostream>
#include <string>
#include <string.h>
#include <scanner.hpp>
#include <stage_filetotokens.hpp>
void parse_file(std::string filename) {
std::map<std::string /* pass_name */, piper::parse_result> results;
auto stage = new piper::FileToTokens(filename);
stage->run(&results);
auto r = results["tokens"];
for (int i = 0; i < r.output_size; i++) {
std::cout << r.bytes[i];
}
}
int main(int argc, char *argv[]) {
std::string my_name = argv[0];
if (argc <= 1) {
std::cout << "Usage: " << my_name << " filename" << std::endl;
return 0;
}
std::string filename = argv[1];
parse_file(filename);
}<file_sep>/docs/README.md
# What is Piper?
Piper is an experimental language written by a web developer who is frustrated with the state of "web development languages." The concrete design is still pretty squishy, but there are overarching design goals. Many of them are variations on "make web languages more like systems languages."
## Terminology
I will be using some terms that do not have 100% solid definitions. Therefore, I will attempt to explain where I draw the line.
A "Systems Language" is generally designed to write long-running backend processes. The focus of the language is to make things "correct," often forcing the developer to do extra work to achieve that. Classic examples would be C or Java. You often have to declare types explicitly. You often have fairly accurate knowledge about how memory is laid out, and can optimize your code with that knowledge in mind without really worrying about version-to-version differences.
A "Web Language" is generally designed to write backend processes that handle HTTP requests. The focus of these languages tend to be on developer speed, and not correctness. You are almost never *expected* to annotate types, and in fact in the majority of languages in this category, you cannot (or when you can, they are closer to documentation than restrictions). Often you do not have to declare a variable, it just springs into being the first time you reference it. Prominent examples would be PHP, Python, or Ruby.
## Errors Should Be Caught As Early As Possible
Computers are good at catching errors. Most sysystems languages catch a huge variety of errors, especially if you opt into a level of scrutiny higher than the default. Using a C compiler with `-Wall -Werror` is sure to catch quite a few things.
Most systems languages tie their own hands when it comes to catching errors. The most wide-spread example I can think of is the lack of having to declare a variable. In a huge number of web languages, assigning to a variable will declare it if it was not already declared. This means that a typo in code will have potentially very subtle errors. Take, for example the following:
$inches = $input_value;
if ($input_units == 'feet') {
$inchs *= 12;
}
In this very contrived example, there will be a bug any time someone wants to use feet rather than inches. But the bug won't cause a compile-time error. Nor will it even error on this line. It may not "error" at all. But the value will definitely be wrong. It may take a lot of time to notice the bug. The erroenous values may be stored in a database before you notice. You may have to manually try to clean the data based on guesswork and heuristics.
This could have all been avoided if the compiler could notice that `inchs` wasn't declared.
Note that while I am not afraid to force developers to be explicit, that doesn't necessarily mean that developers should have to be explicit about **everything**. **IF** the language can be non-ambiguous and errors can be caught early, I am fine with any and all developer shortcuts. But when developer convenience bumps up against error detection, I will lean toward error detection far more than convenience.
## Memory Management Is Unimportant...
I do not want to have to call malloc and free in my web code. I don't want to have to deal with NULL pointers, or accessing memroy after it is freed. Some form of automatic memory management / garbage collection is necessary.
## .. Until It Is Important
There have been a number of cases where I have needed to interact with binary data in a web language. The API for that case is always pretty annoying, because it's so far down on the priority list of these languages. I want to make sure that I keep this in mind as design things so that I can make the binary APIs not terribly painful to use.
## Strings Are THE Most Important Data Type
If this belief wasn't here, I would probably just use a systems language and be done with it. Systems languages often either ignore their string type, or they have a string type that is fairly mediocre. Part of this pain is caused by things not directly related to strings -- stuff like memory management. But the language needs to be designed to make working with strings as convenient as possible. Splitting, joining, translating, search and replace, all of those and more need to be trivial to do. Without worrying about memory managent or generating lot of garbage. And without having to use a StringBuilder-style API.
## Data Has Interrelated Views
The database representation of data is related to the Object model of data is related to the JSON representation of data is related to the POST variables used to create said data. Web programming often involves translating between these forms, which is full of boilerplate and error-prone. A language that acknowledges that the same logical object has many forms could potentially reduce this problem.
## Data Has Trust Levels
Data that comes from the user is inherently untrusted. Data that comes from the app itself is inherently trusted. Data that comes from the database is somewhere inbetween. Almost every language treats them as the same.
## Some Data Is Shared
Some web languages have zero sharing between two different requests (ie, PHP). Some web languages have sharing allowed, but have complicated semantics around how to actually take advantage of that (Java). In memory data stores are too useful to give up, but it should not be complicated to use them for simple common use cases.
## Code Organization Is Paramount
Maintainability is directly related to how organized code is. Most web languages have very weak organizational primitives, because they are designed to make it easy to write hello world, and forced organizational elements obscure things in such a simple case. But you will want them as things get bigger, and having them be weak or non-existant will come back to bite you. Forcing them in even the simple cases allows them to be baked further into the language, which provides great benefits.
## Third Party Packages Are Important
In an application of any size, you will be using third party libraries. Using them should be convenient. As should finding the packages to use. This goes somewhat outside of language design, but it may have some interactions, and those should be kept in mind.
## Web Languages Can Be Fast
There is a very real divide over web languages and systems languages. Web languages tend to be "interpreted" or close to it. That is, while they might compile to a bytecode, they eschew a separate compilation step, which makes several things notably harder. I will not rule out having a separate compilation step, though it's far from known at this point.
## Single Entry Point
Code is easier to reason about with a single entry point. That entry point shouldn't **do** much, mostly set up configuration, but having a single well-defined entry point makes it easier for new developers to get up to speed.
## Interop With C(-like)
For languages that compile to a library, you can link the libraries together and write different parts of your app in different languages. This seems unimportant (I would never use two different languages in one project, that's just a maintenance nightmare!) until you start thinking about system libraries. To use opencv in PHP, for example, I need to find or write a wrapper around opencv using a pretty complex API that is easy to get wrong. And that API is likely to shift in different versions of PHP.
Since the C ABI is the stable one, with literal decades of libraries being written against it, we should adapt to the C ABI rather than making our own. We aim for automatically being able to use shared libraries without having to manually write a glue layer.
## Generics
Generics are useful. And there's no reason they should be kept from web languages.
## Named Parameters
## Multiple Returns
## Async
Yes. It's awesome.
<file_sep>/src/includes/expressions/add_expression.hpp
#pragma once
#include <expressions/expression.hpp>
namespace piper {
class AddExpression : public Expression {
public:
AddExpression(Expression *left, Expression *right);
std::string toString();
protected:
Expression *left;
Expression *right;
};
}
<file_sep>/src/includes/expressions/call_expression.hpp
#pragma once
#include <expressions/expression.hpp>
#include <vector>
namespace piper {
class CallExpression : public Expression {
public:
CallExpression(Expression *left);
void add_argument(Expression *argument);
std::string toString();
protected:
Expression *left;
std::vector<Expression *> arguments;
};
}
<file_sep>/src/expressions/less_than_expression.cpp
#include <expressions/less_than_expression.hpp>
#include <iomanip>
#include <sstream>
namespace piper {
LessThanExpression::LessThanExpression(Expression *left, Expression *right) {
this->left = left;
this->right = right;
}
std::string LessThanExpression::toString() {
std::stringstream stream;
stream << "\"" << std::hex << this << "\"";
stream << " [label=\"Less Than\"];\n";
stream << "\"" << std::hex << this << "\"";
stream << " -> ";
stream << "\"" << std::hex << this->left << "\"";
stream << ";\n";
stream << "\"" << std::hex << this << "\"";
stream << " -> ";
stream << "\"" << std::hex << this->right << "\"";
stream << ";\n";
stream << this->left->toString();
stream << this->right->toString();
return stream.str();
}
}
| 6632fd5b873e15937b1b10bce873129ebe306ac7 | [
"Markdown",
"CMake",
"C++"
] | 46 | C++ | PiperLang/piper | 7b2dc57793fca7f3bb153e399e36b0ad0ec33ca1 | 8e8bf15fc0221f6a4b444bfec74344ffc3d4fac1 |
refs/heads/master | <repo_name>leoliuyt/DMMacFileView<file_sep>/README.md
# DMMacFileView
演示NSTableView的使用
<file_sep>/DMMacFileView/Podfile
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
platform :osx, '10.10'
target 'DMMacFileView' do
# Uncomment the next line if you're using Swift or would like to use dynamic frameworks
# use_frameworks!
# Pods for DMMacFileView
pod 'Masonry', '~> 1.0.2'
end
| 344d0389ec0209d58d668e4ff35f47d984c257ae | [
"Markdown",
"Ruby"
] | 2 | Markdown | leoliuyt/DMMacFileView | 0efe94fead71c00d9c0badb38d59de8c2d29c804 | 136ea4cf592d4b854d57ec4c2280e910733717df |
refs/heads/master | <file_sep>package HangBro;
public class HangMain {
public static void main(String[] args) {
HangPane HangMain = new HangPane();
HangMain.HangMaker();
}
public void caller() {
}
}
| 0d4dad1f57d1fc0f8d5714786f1dfef3f7338ef8 | [
"Java"
] | 1 | Java | Thomas1023/Hangman | 4e4d4ad21ff80364d1583343a458f660736e48e3 | 095781915039cecc2943f750ba868126fa3f3adb |
refs/heads/master | <file_sep>from django.db import models
# Create your models here.
# Class for book tags
# eg: horror, fantasy ...etc
class Tag(models.Model):
# The actual name of the tag
tagName = models.CharField(max_length=30)
# Description for the tag
tagDescription = models.CharField(max_length=255)
# Function that defines the row name in the database
def __str__(self):
return self.tagName
class Category(models.Model):
name = models.CharField(max_length=255)
description = models.CharField(max_length=1000)
# a function to display the category like this example below
# Adventure: this category is about journeys and fiction ...
def __str__(self):
return self.name + ': ' + self.description
<file_sep># Code Style
-------------------
### Naming Conventinos:
-------------------
1. camelCase for variables
*eg:* `myVariable`
- camelCase for functions / methods
*eg:* `functionName()`
PacalCase for functions
*eg:* `ClassName`
---
### Indentation:
#### **Indentations uses four spaces**
---
### Comments style:
1. comment goes before variable / function / class
2. uses hashes `# Comment` instead of multiline `""" Comment """`
---
### List/Dict initialisation:
**Initialisation goes to next line**
*eg:*
myList = [
1,2,3,4
]
---
For more informations / questions please contact me at
[Facebook](https://www.facebook.com/spounka346)
[Twitter](https://www.twitter.com/boudaakkar)
or by email at:
<EMAIL><file_sep>Django==2.2
Pillow==7.2.0
psycopg2==2.8.6
python-dotenv==0.14.0
pytz==2020.1
sqlparse==0.3.1
<file_sep>Django Library Management App
===
# Getting Started
## Notes before getting started
This project uses
- postgresql as a database
- django as backend
- python for programming language
You are expected to have a working PostgreSQL installation
and have an already setup database for the project.
If not, please refer to the official website for more informations
If you're on Linux, replace the `python` and `pip` commands
with `python3` and `pip3`
## Setting up the environment for development
### Cloning the repository
Clone the repository using the command:
git clone https://github.com/Computer-Science-Group/cs-django-library.git
or by using the download zip in your browser and extract it
Switch to that directory you extracted/downloaded
### Downloading python
**The python version used in this project is 3.7.8**
To get started, you need to have python 3.7
installed along with pip and venv (or virtualenv)
You can get it from [here](https://www.python.org/downloads/release/python-379/)
For Linux, you can use your package manager or use pyenv for that
### Creating a virtual environment
#### Windows steps:
First create a virtual environemnt using the command:
python -m venv venv
or if you use virtualenv
python -m virtualenv venv
next source to your virtual envirnonment
.\venv\Scripts\activate.bat
#### Linux Steps
Create a virtual environment using the command:
python3 -m venv .venv
Notice the `.` before venv, **important**
Next source it using
source ./.venv/bin/activate
### Installing the needed libraries
Now that you have a working virtual environment,
we need to install our dependencies
Luckily, we have a requirements.txt file
containing all we need
pip install -r requirements.txt
### Setting up needed configurations
First, you need to run the script `generate_random_key.py`
in the root folder
you can run it using the command:
python generate_random_key.py
it will print out a key, copy it
Next, create a `.env` file next to `manage.py`
**IMPORTANT**
The `.` in `.env` is mandatory, you cannot remove it
Open you `.env` file and add the following line to it
SECRET_KEY=
then paste your copied key
then add the following line under your `SECRET_KEY`
DATABASE_NAME=YourPostgreSQLDatabaseName
DATABASE_USER=YourPostgreSQLUsername
DATABASE_PASSWORD=<PASSWORD>
### Running the project
Finally, run the following commands:
python manage.py migrate
python manage.py runserver 0.0.0.0:8000
If it runs without errors, open your browser to your
[localhost](http://localhost:8000) link, it should display a page
---
### Congrats, now you can start working
| 4f48e73101247bcd45bc801853586fcbdf1eca09 | [
"Markdown",
"Python",
"Text"
] | 4 | Python | samirbelhadjer/cs-django-library | 26a4e784d3c8c2f4dfd0fd42f4eca86aa014e915 | 2022df28bfaddf5b7ccdd68612153221f03e7f72 |
refs/heads/master | <file_sep>package com.github.randomcodeorg.ppplugin;
import java.io.IOException;
import org.gradle.api.DefaultTask;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.tasks.TaskAction;
import com.github.randomcodeorg.ppplugin.data.BuildLog;
import com.github.randomcodeorg.ppplugin.data.DependencyResolutionException;
import com.github.randomcodeorg.ppplugin.data.ProjectData;
import com.github.randomcodeorg.ppplugin.data.gradle.GradleBuildDataSource;
import com.github.randomcodeorg.ppplugin.data.gradle.GradleBuildLog;
import com.github.randomcodeorg.ppplugin.data.gradle.GradleProjectData;
import com.github.randomcodeorg.ppplugin.internals.InternalInvoker;
/**
* The postprocess task for gradle projects using the 'java' plugin.
*
* @author <NAME>
*
*/
public class PostProcessGradleTask extends DefaultTask {
public static final String COMPILATION_TASK_PROPERTY = "compilationTask";
public static final String COMPILED_CLASES_DIR_PROPERTY = "compiledClassesDir";
public Task compilationTask = null;
public String compiledClassesDir = null;
public PostProcessGradleTask() {
}
@TaskAction
public void postProcess() {
if (compilationTask != null && !compilationTask.getDidWork()) {
setDidWork(false);
return;
}
setDidWork(true);
Project project = getProject();
BuildLog log = getLog(this);
ProjectData projectData = new GradleProjectData(project);
GradleBuildDataSource data = new GradleBuildDataSource(this, compilationTask, compiledClassesDir, log,
projectData);
try {
new InternalInvoker(data).invoke();
} catch (ClassNotFoundException | IOException | DependencyResolutionException e) {
throw new RuntimeException(e);
}
}
protected BuildLog getLog(Task task) {
return new GradleBuildLog(task.getLogger());
}
}
<file_sep>package com.github.randomcodeorg.ppplugin.data.gradle;
import java.io.File;
import org.gradle.api.tasks.SourceSetContainer;
public class JavaSourceSetProvider implements SourceSetProvider {
private final SourceSetContainer container;
public JavaSourceSetProvider(SourceSetContainer container) {
this.container = container;
}
@Override
public SourceSet getByName(String name) {
org.gradle.api.tasks.SourceSet set = container.getByName(name);
return new SourceSet() {
@Override
public Iterable<File> getCompileClasspath() {
return set.getCompileClasspath();
}
};
}
@Override
public Iterable<String> getNames() {
return container.getNames();
}
@Override
public int size() {
return container.size();
}
}
<file_sep>package com.github.randomcodeorg.ppplugin.data.gradle;
import java.io.File;
import org.gradle.api.DefaultTask;
import org.gradle.api.Task;
import com.github.randomcodeorg.ppplugin.data.BuildDataSource;
import com.github.randomcodeorg.ppplugin.data.BuildLog;
import com.github.randomcodeorg.ppplugin.data.ProjectData;
public class GradleBuildDataSource implements BuildDataSource {
private final BuildLog log;
private final DefaultTask task;
private final ProjectData projectData;
private final Task compilationTask;
private final String compiledClassesDir;
public GradleBuildDataSource(DefaultTask task, Task compilationTask, String compiledClassesDir, BuildLog log,
ProjectData projectData) {
this.log = log;
log.info("Hello World!");
this.task = task;
this.projectData = projectData;
this.compilationTask = compilationTask;
this.compiledClassesDir = compiledClassesDir;
}
@Override
public BuildLog getLog() {
return log;
}
@Override
public String getProjectBuildDir() {
return task.getProject().getBuildDir().getAbsolutePath();
}
@Override
public String getCompiledClassesDir() {
if (compiledClassesDir != null && !compiledClassesDir.isEmpty())
return compiledClassesDir;
if (compilationTask != null && !compilationTask.getOutputs().getFiles().isEmpty()) {
return compilationTask.getOutputs().getFiles().getFiles().iterator().next().getAbsolutePath();
}
String path = task.getProject().getBuildDir().getAbsolutePath();
if (!path.endsWith(File.separator)) {
return String.format("%%sclasses%smain", path, File.separator, File.separator);
} else {
return String.format("%sclasses%smain", path, File.separator);
}
}
@Override
public ProjectData getProject() {
return projectData;
}
}
<file_sep>rootProject.name = 'ppplugin.gradle'<file_sep># PPPluginGradle [](http://www.apache.org/licenses/LICENSE-2.0.html)
<file_sep>implementation-class=com.github.randomcodeorg.ppplugin.PPPluginGradle<file_sep>package com.github.randomcodeorg.ppplugin;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
/**
* The plugin for Gradle.
*
* @author <NAME>
*
*/
public class PPPluginGradle implements Plugin<Project> {
public PPPluginGradle() {
}
@Override
public void apply(Project project) {
project.getTasks().create("showPaths", ShowPathsTask.class);
if (project.getPlugins().hasPlugin("java")) {
Task postProcess = project.getTasks().create("postProcess", PostProcessGradleTask.class);
Task javaCompilationTask = project.getTasks().getByName("compileJava");
javaCompilationTask.finalizedBy(postProcess);
postProcess.setProperty(PostProcessGradleTask.COMPILATION_TASK_PROPERTY, javaCompilationTask);
}
project.afterEvaluate(p -> {
if (p.getPlugins().hasPlugin("com.android.application")) {
Task postProcessDebug = p.getTasks().create("postProcessDebug", PostProcessGradleTask.class);
Task postProcessRelease = p.getTasks().create("postProcessRelease", PostProcessGradleTask.class);
Task compileDebugTask = p.getTasks().getByName("compileDebugJavaWithJavac");
compileDebugTask.finalizedBy(postProcessDebug);
postProcessDebug.setProperty(PostProcessGradleTask.COMPILATION_TASK_PROPERTY, compileDebugTask);
Task compileReleaseTask = p.getTasks().getByName("compileReleaseJavaWithJavac");
compileReleaseTask.finalizedBy(postProcessRelease);
postProcessRelease.setProperty(PostProcessGradleTask.COMPILATION_TASK_PROPERTY, compileReleaseTask);
}
});
}
}
<file_sep>// Build config for the gradle plugin
apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'maven-publish'
apply plugin: 'signing'
repositories {
mavenCentral()
mavenLocal()
}
task sourceJar(type: Jar) {
from sourceSets.main.allJava
}
task renamePom() {
doLast{
file('/build/publications/mavenJava/pom-default.xml.asc').renameTo(file('/build/publications/mavenJava/pom.xml.asc'))
}
}
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier = 'javadoc'
from javadoc.destinationDir
}
signing {
sign jar
sign sourceJar
}
jar {
finalizedBy signJar
}
sourceJar {
finalizedBy signSourceJar
}
task('signPom'){
doLast{
signing.sign file('/build/publications/mavenJava/pom-default.xml')
}
}.finalizedBy renamePom
afterEvaluate {
model {
tasks.generatePomFileForMavenJavaPublication {
finalizedBy signPom
}
}
}
publishing {
publications {
mavenJava(MavenPublication) {
groupId 'com.github.randomcodeorg.ppplugin'
artifactId 'ppplugin-gradle'
version '0.0.1'
from components.java
artifact source: '/build/publications/mavenJava/pom.xml.asc', extension: 'pom.asc'
artifact source: '/build/libs/ppplugin.gradle.jar.asc', extension: 'jar.asc'
artifact sourceJar {
classifier "sources"
}
artifact source: '/build/libs/ppplugin.gradle-sources.jar.asc', classifier: 'sources', extension: 'jar.asc'
pom.withXml {
asNode().appendNode('description', 'A gradle plugin that executes one or multiple user defined processors that can be used to transform or modify the compilation result.')
Node license = asNode().appendNode('licenses').appendNode('license')
license.appendNode('name', 'Apache License, Version 2.0')
license.appendNode('url', 'http://www.apache.org/licenses/LICENSE-2.0.txt')
license.appendNode('distribution', 'repo')
asNode().appendNode('name', 'Post Processor Plugin for Gradle')
asNode().appendNode('url', 'https://github.com/RandomCodeOrg/PPPluginGradle')
asNode().appendNode('scm').appendNode('url', 'https://github.com/RandomCodeOrg/PPPluginGradle.git')
Node developer = asNode().appendNode('developers').appendNode('developer')
developer.appendNode('id', 'RandomCodeOrg')
developer.appendNode('name', 'RandomCodeOrg-Team')
}
}
}
repositories {
maven {
credentials {
username project.property('maven.settings.username')
password project.property('maven.settings.password')
}
url 'https://oss.sonatype.org/service/local/staging/deploy/maven2/'
}
}
}
dependencies {
compile gradleApi()
compile 'com.github.randomcodeorg.ppplugin:ppplugin:0.2.0'
compile 'com.android.tools.build:gradle:1.5.0'
testCompile 'junit:junit:4.11'
}
| e2f7f47327c6957b1f5439fb7444cdee1d3ed0bb | [
"Markdown",
"Java",
"INI",
"Gradle"
] | 8 | Java | RandomCodeOrg/PPPluginGradle | d172df82ce8db0b77c220a73d50146998b3598ba | 0cbbdbf9c63f3c262e26401dec8ba55264b7a213 |
refs/heads/master | <file_sep>## React Grid
This was Built using `https://codesandbox.io/s/l4qx2rjv8z`
DevExtreme React Grid is a component that displays table data from a local or remote source. It supports paging, sorting, filtering, grouping and other data shaping options, row selection, and data editing. Support for controlled and uncontrolled state modes allows you to use the Grid in a regular or Redux-based application. The DevExtreme Grid component has a composable and extendable plugin-based architecture and is provided with Twitter Bootstrap and Material UI rendering and theming out of the box
Run this application
`npm install`
`npm start`
<file_sep>import * as React from "react";
import Paper from "@material-ui/core/Paper";
import { render } from "react-dom";
import {
SelectionState,
PagingState,
IntegratedPaging,
IntegratedSelection
} from "@devexpress/dx-react-grid";
import {
Grid,
Table,
TableHeaderRow,
TableSelection,
PagingPanel
} from "@devexpress/dx-react-grid-material-ui";
import { generateRows } from "./generator";
class App extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
columns: [
{ name: "name", title: "Name" },
{ name: "sex", title: "Sex" },
{ name: "city", title: "City" },
{ name: "car", title: "Car" }
],
rows: generateRows({ length: 8 }),
selection: []
};
this.changeSelection = selection => this.setState({ selection });
}
render() {
const { rows, columns, selection } = this.state;
return (
<div>
<span>Total rows selected: {selection.length}</span>
<Paper>
<Grid rows={rows} columns={columns}>
<PagingState defaultCurrentPage={0} pageSize={6} />
<SelectionState
selection={selection}
onSelectionChange={this.changeSelection}
/>
<IntegratedPaging />
<IntegratedSelection />
<Table />
<TableHeaderRow />
<TableSelection showSelectAll />
<PagingPanel />
</Grid>
</Paper>
</div>
);
}
}
render(<App />, document.getElementById("root"));
| a4a82671b9d0b125241c73522da5a8f36324d0bb | [
"Markdown",
"JavaScript"
] | 2 | Markdown | RohitoOo/react_table | ed6f4c9dfef4bf16ebd368577908cba1decc1144 | 35dbb8bae6e0dc79fcc419d121a38777d7c4e1cc |
refs/heads/master | <file_sep><?php
function fetchPassword() {
return '<PASSWORD>!';
}
?><file_sep># WeaponBuilder
Ok, I don't have a lot of time to write this right now, I will update later. If you want to actually host and use these files on your own web server, there are a few steps.
1. pphrase.php and db_connect.php are ment to be kept one directory behind the web root directory. for example on a basic Apache2 install, web root is /var/www/html. those files should be kept in /var/www
2. phatWeapons.sql needs to be imported into a database accessible by the web server.
3. edit db_connect.php and add in working username/password/etc
4. edit pphrase.php if you would like to change the passphrase
All the site styling is in the default.css file. I did this so "themes" could be easily created (I do this with all my websites) so if anyone would like to submit modifications, please DO NOT add any inline CSS
| efd0d93df6bb62763f1c999f6049c14ccf790d3d | [
"Markdown",
"PHP"
] | 2 | PHP | cbeale/WeaponBuilder | f742eb557230f4d622efa474b050dd1234063ebb | 760069ca720eba0c340ae972bc788d3f545ad3ab |
refs/heads/main | <repo_name>muath-gh/house_of_care<file_sep>/app/Helper/Uploader.php
<?php
namespace App\Helper;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage;
use File as FileManager;
class Uploader {
public static function upload2files($file1=null,$file2=null,$dir = null,$location){
$path = null;
$current_timestamp = null;
$fullPath1 = null;
$fullPath2 = null;
if($file1 != null || $file2 != null)
{
$current_timestamp = $dir != null ? $dir : Carbon::now()->timestamp;
$path = $location . "/" ;
}
if($file1)
{
$storagePath1 = Storage::disk('public')->put($path.$current_timestamp."/"."front", $file1);
$fullPath1 = url('/') . '/storage/' . $storagePath1;
}
if($file2){
$storagePath2 = Storage::disk('public')->put($path.$current_timestamp."/"."back", $file2);
$fullPath2 = url('/') . '/storage/' . $storagePath2;
}
return ["full_path1" => $fullPath1,'full_path2'=>$fullPath2, "dir" => $current_timestamp];
}
public static function upload($file, $location)
{
$current_timestamp = Carbon::now()->timestamp;
$path = $location . "/" . $current_timestamp;
$storagePath = Storage::disk('public')->put($path, $file);
$fullPath = url('/') . '/storage/' . $storagePath;
return ["full_path" => $fullPath, "dir" => $current_timestamp];
}
public static function remove($location,$type, $directory)
{
$public_path = public_path('storage/' . $location . '/' .$directory."/".$type);
if (FileManager::exists($public_path)) {
FileManager::deleteDirectory($public_path);
}
}
}<file_sep>/app/Models/CartProduct.php
<?php
namespace App\Models;
class CartProduct {
public $productId ;
public $quantity;
public function __construct($productId,$quantity)
{
$this->productId = $productId;
$this->quantity = $quantity;
}
}<file_sep>/app/Helper/FrontEndHelper.php
<?php
namespace App\Helper;
class FrontEndHelper {
public function mapTypeToString($type){
switch($type)
{
case "keto":
return "منتجات الكيتو";
case "lowcarb":
return "منتجات اللو كارب";
}
}
}<file_sep>/app/Models/DBCart.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class DBCart extends Model {
protected $table ="carts";
protected $fillable= ['items','ip_address'];
}<file_sep>/app/Http/Controllers/BackEnd/ProductController.php
<?php
namespace App\Http\Controllers\BackEnd;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Helper\Uploader;
use App\Models\Product;
class ProductController extends Controller
{
public function index(Request $request)
{
$products = Product::all();
return view('backend.products.index', ['products' => $products]);
}
public function create()
{
return view('backend.products.create');
}
public function edit($id)
{
$product = Product::findOrFail($id);
return view('backend.products.edit', ['product' => $product]);
}
public function store(Request $request)
{
try {
$this->validate($request, [
"product_name" => "required",
"product_type" => "required",
"product_price" => "required",
"product_front_image" => "mimes:jpeg,jpg,png,gif",
"product_back_image" => "mimes:jpeg,jpg,png,gif",
]);
// store images
$frontImage = $request->has('product_front_image') ? $request->product_front_image : null;
$backImage = $request->has('product_back_image') ? $request->product_back_image : null;
$uploadResult = Uploader::upload2files($frontImage, $backImage,null, "products");
$productName = $request->product_name;
$productType = $request->product_type;
$productPrice = $request->product_price;
$productDesc = $request->product_desc;
$productType = join(",", $productType);
$product = new Product([
"product_name" => $productName,
"product_type" => $productType,
"product_front_image" => $uploadResult["full_path1"],
"product_back_image" => $uploadResult['full_path2'],
"product_image_dir" => $uploadResult['dir'],
"product_desc" => $productDesc,
"product_price" => $productPrice,
]);
$product->save();
return redirect()->back()->with('success', true);
} catch (\Exception $e) {
return redirect()->back()->with('error', true);
}
}
public function update(Request $request, $id)
{
try {
$this->validate($request, [
"product_name" => "required",
"product_type" => "required",
"product_price" => "required",
"product_front_image" => "mimes:jpeg,jpg,png,gif",
"product_back_image" => "mimes:jpeg,jpg,png,gif",
]);
$product = Product::findOrFail($id);
$frontImage = $request->has('product_front_image') ? $request->product_front_image : null;
$backImage = $request->has('product_back_image') ? $request->product_back_image : null;
if($frontImage){
Uploader::remove("products","front",$product->product_image_dir);
}
if($backImage){
Uploader::remove("products","back",$product->product_image_dir);
}
$uploadResult = Uploader::upload2files($frontImage, $backImage,$product->product_image_dir, "products");
$productName = $request->product_name;
$productType = $request->product_type;
$productPrice = $request->product_price;
$productDesc = $request->product_desc;
$productType = join(",", $productType);
$product->update([
"product_name" => $productName,
"product_type" => $productType,
"product_front_image" => $uploadResult["full_path1"] ? $uploadResult["full_path1"] : $product->product_front_image,
"product_back_image" => $uploadResult['full_path2'] ? $uploadResult["full_path2"] : $product->product_back_image,
"product_image_dir" => $uploadResult['dir'],
"product_desc" => $productDesc,
"product_price" => $productPrice,
]);
$product->save();
return redirect()->back()->with('success', true);
} catch (\Exception $e) {
dd($e->getMessage());
return redirect()->back()->with('error', true);
}
}
public function destroy($id){
Product::findOrFail($id)->delete();
return response()->json([
'success'=>true
]);
}
}
<file_sep>/app/Models/Product.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model {
protected $fillable = ["product_name","product_type","product_price",'product_front_image','product_back_image',
"product_desc",'product_image_dir'];
public function orderProducts(){
return $this->hasMany(OrderProduct::class);
}
}<file_sep>/app/Http/Controllers/FrontEnd/SiteController.php
<?php
namespace App\Http\Controllers\FrontEnd;
use App\Http\Controllers\Controller;
use App\Models\Cart;
use App\Models\Order;
use App\Models\OrderProduct;
use App\Models\Product;
use Illuminate\Http\Request;
class SiteController extends Controller
{
public function shop($type){
$total = Product::where('product_type', 'like', '%' . $type. '%')->count();
$products = Product::where('product_type', 'like', '%' . $type. '%')->paginate(6);
return view('frontend.shop',['products'=>$products,"type"=>$type,'total'=>$total]);
}
public function productDetail($id){
$product = Product::findOrFail($id);
return view('frontend.product-detail',['product'=>$product]);
}
public function storeOrder(Request $request){
$request->validate([
"first_name"=>"required",
"last_name"=>"required",
"phone"=>"required",
"address"=>"required"
],[
"first_name.required"=>"هذا الحقل مطلوب",
"last_name.required"=>"هذا الحقل مطلوب",
"phone.required"=>"هذا الحقل مطلوب",
"address.required"=>"هذا الحقل مطلوب"
]);
$cartItems = app(Cart::class)->getCart();
$order = Order::create([
"customer_name"=>$request->first_name . " ".$request->last_name,
"customer_phone"=>$request->phone,
"customer_address"=>$request->address
]);
foreach($cartItems as $cartItem){
OrderProduct::create([
"order_id"=>$order->id,
"product_id"=>$cartItem['productId'],
"quantity"=>$cartItem['quantity']
]);
}
app(Cart::class)->emptyCart();
return redirect()->back();
}
public function checkOut(){
$products= [];
$cart = app(Cart::class)->getCart();
foreach($cart as $c){
$product = Product::findOrFail($c['productId']);
$products[]=[
"name"=>$product->product_name,
"price"=>$product->product_price,
"image"=>$product->product_front_image,
"quantity"=>$c['quantity']
];
}
return view('frontend.checkout',['products'=>$products]);
}
}
<file_sep>/app/Http/Livewire/Cart.php
<?php
namespace App\Http\Livewire;
use App\Models\Cart as ModelsCart;
use App\Models\CartProduct;
use App\Models\Product;
use Livewire\Component;
class Cart extends Component
{
public $cartCount;
protected $listeners = ['addToCart' => 'addToCart'];
public function mount()
{
$this->cartCount = app(ModelsCart::class)->getCartCount();
}
private function updateCartCount()
{
$this->cartCount = app(ModelsCart::class)->getCartCount();
}
public function addToCart($cartProduct)
{
$cart = app(ModelsCart::class)->addProduct($cartProduct);
$this->updateCartCount();
$this->dispatchBrowserEvent(
'alert',
['type' => 'success', 'message' => 'تم الاضافة الى السلة']
);
}
public function render()
{
return view('livewire.cart');
}
}
<file_sep>/app/Http/Livewire/AddToCartWithQuantity.php
<?php
namespace App\Http\Livewire;
use App\Models\CartProduct;
use Livewire\Component;
class AddToCartWithQuantity extends Component
{
public $quantity;
public $product;
public function mount(){
$this->quantity = 1;
}
public function incQuantity(){
$this->quantity = $this->quantity+1;
}
public function decQuantity(){
$this->quantity = $this->quantity < 0 ? 0 : $this->quantity-1;
}
public function addToCart(){
$cartProduct = new CartProduct($this->product->id,$this->quantity);
$this->emit('addToCart',$cartProduct);
}
public function render()
{
return view('livewire.add-to-cart-with-quantity');
}
}
<file_sep>/app/Http/Livewire/AddToCart.php
<?php
namespace App\Http\Livewire;
use App\Models\CartProduct;
use Livewire\Component;
class AddToCart extends Component
{
public $product;
public function addToCart(){
$cartProduct = new CartProduct($this->product->id,1);
$this->emit('addToCart',$cartProduct);
}
public function render()
{
return view('livewire.add-to-cart');
}
}
<file_sep>/database/migrations/2021_09_02_130400_product_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class ProductTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('product_name');
$table->text('product_desc')->nullable()->default(null);
$table->decimal('product_price');
$table->string('product_type');
$table->text('product_front_image')->nullable()->default(null);
$table->text('product_back_image')->nullable()->default(null);
$table->string('product_image_dir')->nullable()->default(null);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
<file_sep>/app/Models/Cart.php
<?php
namespace App\Models;
use App\Helper\BackEndHelper;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
class Cart
{
public function getCart()
{
// Session::remove('cart');
$dbCart = DBCart::where('ip_address', BackEndHelper::getIp())->first();
$cart = [];
if ($dbCart) {
$items = json_decode($dbCart->items);
foreach($items as $item)
{
$cart[] = (array) $item;
}
} else if (Session::get("cart")) {
$cart = Session::get("cart");
}
return $cart;
}
public function getCartCount(): int
{
if ($this->getCart())
return sizeof($this->getCart());
return 0;
}
public function addProduct($cartProduct)
{
$cart = $this->getCart();
$id = $this->searchForId($cartProduct["productId"], $cart);
if ($id) {
$cart = $this->updateQuantity($id, $cartProduct['quantity'], $cart);
} else {
array_push($cart, $cartProduct);
}
Session::put("cart", $cart);
DBCart::updateOrCreate(["ip_address" => BackEndHelper::getIp()], [
"items" => json_encode($cart)
]);
return $cart;
}
public function emptyCart(): void
{
$cart = [];
DBCart::where('ip_address',BackEndHelper::getIp())->delete();
Session::put('cart', $cart);
}
function searchForId($id, $array)
{
foreach ($array as $key => $val) {
if ($val['productId'] === $id) {
return $val['productId'];
}
}
return null;
}
function updateQuantity($id, $quantity, &$array)
{
foreach ($array as &$val) {
if ($val['productId'] === $id) {
$val['quantity'] = ((int)$val['quantity']) + ((int)$quantity);
}
}
return $array;
}
}
| 6338effd18e2fc635f8ae5f7a873dedee67f217a | [
"PHP"
] | 12 | PHP | muath-gh/house_of_care | d1600c8ba679c2a8abcf1c339d7120fc89d877b3 | c2506fefae935fbb67b89680a9270a4fd2632841 |
refs/heads/master | <repo_name>sysid/helper<file_sep>/sls/sls.x
#!/bin/bash
gci -r "*.txt" | go run sls.go -d -p 'jjj'
gci -r "*.txt" | go run sls.go -d -p 'jjj'|gm
<file_sep>/class/cmd/class/main.go
package main
import (
"encoding/json"
"fmt"
"os"
"github.com/sysid/helper/class"
//. "github.com/sysid/tw/basic"
)
func check(e error) {
if e != nil {
panic(e)
}
}
func main() {
fi, err := class.NewFileInfo(os.Args[0])
check(err)
//Log("fileinfo: %v", fi)
//Log("type: %T", fi)
b, err := json.Marshal(fi)
if err != nil {
fmt.Println("error:", err)
}
os.Stdout.Write(b)
//Log("\n")
}
<file_sep>/du/du.go
// vim: fdm=marker ts=4 sts=4 sw=4 fdl=0
package main
//// Imports {{{
import (
"fmt"
"os"
"path/filepath"
"time"
"github.com/sysid/tw"
. "github.com/sysid/tw/basic"
"gopkg.in/alecthomas/kingpin.v2"
)
////}}}
//// Global Variables/Constants {{{
var (
//l = tw.NewDefaultLogger(os.Stdout)
dbg = func(v ...interface{}) {}
cfg = Cfg{
Version: "0.1",
Name: filepath.Base(os.Args[0]),
Dbg: false,
}
i int = 0
)
////}}}
//// Types and Methods {{{
type Cfg struct {
Name string
Version string
Dbg bool
}
////}}}
//// Functions {{{
func check(e error) {
if e != nil {
panic(e)
}
}
func du(currentPath string, info os.FileInfo) int64 {
if cfg.Dbg {
defer tw.Enter(fmt.Sprintf("path=%s name=%s size=%d", currentPath, info.Name(), info.Size()))()
}
size := info.Size()
if !info.IsDir() {
return size
}
dir, err := os.Open(currentPath)
if err != nil {
Red("E: %s", err)
return size
}
defer dir.Close()
fis, err := dir.Readdir(-1) //read entire directory fileinfo
if err != nil {
Red("E: %s", err)
panic(tw.Exit{1})
}
if cfg.Dbg {
Debug2("dir=%s, fis=%v", dir.Name(), fis)
}
// loop over one hierarchy level
for _, fi := range fis {
if fi.Name() == "." || fi.Name() == ".." {
continue
}
size += du(currentPath+"/"+fi.Name(), fi)
i++
if cfg.Dbg {
Log("name=%s, size=%v, i=%d", fi.Name(), size, i)
}
}
fmt.Printf("%d %s %d\n", size/1024, currentPath, i)
return size
}
////}}}
//// Main {{{
func main() {
app := kingpin.New(cfg.Name, "Disc Usage in KB")
Green("START %s: %s", cfg.Name, time.Now())
defer tw.HandleExit()
defer tw.End(time.Now())
// --completion-script-bash: HintOptions, HintAction(func)
app.Flag("debug", "debug").Short('d').Envar("twDbg").BoolVar(&cfg.Dbg)
path := app.Arg("path", "path").Default(".").String()
kingpin.MustParse(app.Parse(os.Args[1:]))
if cfg.Dbg {
dbg = Debug2
}
dbg("path:%s", *path)
info, err := os.Lstat(*path)
if err != nil {
panic(tw.Exit{1})
}
du(*path, info)
panic(tw.Exit{0})
}
////}}}
<file_sep>/sls/sls.go
// vim: fdm=marker ts=4 sts=4 sw=4 fdl=0
package main
//// Imports {{{
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
_ "fmt"
"io"
"log"
"net/http"
_ "net/http/pprof"
"os"
"path/filepath"
"regexp"
"runtime"
"sync"
"time"
"gopkg.in/alecthomas/kingpin.v2"
"github.com/sysid/helper/class"
"github.com/sysid/tw"
. "github.com/sysid/tw/basic"
)
////}}}
//// Variables/Constants {{{
const (
CHAN_BUF = 1000 //does not seem to have any influence on performance
)
var (
//l = tw.NewDefaultLogger(os.Stdout)
dbg = func(v ...interface{}) {}
cfg = Cfg{
Version: "0.1",
Name: filepath.Base(os.Args[0]),
}
workers = runtime.NumCPU()
wg *sync.WaitGroup
ctr = Counter{
n: 0,
mutex: new(sync.RWMutex),
}
)
////}}}
/* Init {{{ */
func init() {
// curl http://127.0.0.1:3030/debug/pprof/goroutine?debug=2
go func() {
log.Println(http.ListenAndServe("localhost:3030", nil))
}()
}
/* }}} Init */
//// Types and Methods {{{
type Cfg struct {
Name string
Version string
Dbg bool
regex string
files []string
}
type Result struct {
Type string
Filename string
Lino int
Line string
}
func (r *Result) OutJson() string {
if js, err := json.Marshal(r); err != nil {
Red2("E: cannot create json representation: %s", err)
panic(tw.Exit{1})
} else {
return string(js)
}
}
type Counter struct {
n int
mutex *sync.RWMutex
}
func (c *Counter) add() {
c.mutex.Lock()
defer c.mutex.Unlock()
c.n += 1
}
////}}}
//// helper {{{
func check(e error) {
if e != nil {
Red("E: %s", e)
panic(tw.Exit{1})
}
}
func commandLineFiles(files []string) []string {
//if runtime.GOOS == "windows" {
args := make([]string, 0, len(files))
for _, name := range files {
if matches, err := filepath.Glob(name); err != nil {
args = append(args, name) // Invalid pattern
} else if matches != nil { // At least one match
args = append(args, matches...)
}
}
return args
//}
dbg("%s: files=%s args=%s", tw.GetFN(), files, args)
return files
}
func matchObjFunc(plain bool) func(res Result) {
return func(result Result) {
if class.OutObj && !plain {
if js, err := json.Marshal(result); err != nil {
Red("E: cannot create json representation: %s", err)
panic(tw.Exit{1})
} else {
fmt.Printf("%s\n", js)
}
} else {
fmt.Printf("%s:%d:%s\n", result.Filename, result.Lino, result.Line)
}
}
}
////}}}
//// Async {{{
// addJobs reads from stdin and puts the files into chan cJob, then closes cJob
func addJobs(cJob chan<- Job, cResult chan Result) {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
data := scanner.Text()
dbg("Input=%s", scanner.Text()) // Println will add back the final '\n'
fi := class.FileInfo{}
err := json.Unmarshal([]byte(data), &fi)
if err != nil {
Red("E: Invalid json: %s", err)
panic(tw.Exit{1})
}
dbg("fi=%v", fi)
filename := filepath.Join(fi.RelPath, fi.Name)
// start filling the workers
cJob <- Job{filename, cResult} // result channel is passed with the job
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
}
close(cJob) // start closing at the most upstream pipe
}
// doJob worker loops until cJob is closed, then sends Done signal
func doJobs(cDone chan<- struct{}, lineRx *regexp.Regexp, cJob <-chan Job) {
for job := range cJob {
job.Do(lineRx)
}
cDone <- struct{}{}
}
// awaitCompletion blocks until receiving x-time the Done signal, then closes cResult
// we cannot pass the results channel as receive-only channel (<-chan Result), since Go disallows closing such channels!!!
func awaitCompletion(cDone <-chan struct{}, cResult chan Result) {
for i := 0; i < workers; i++ {
<-cDone
}
close(cResult)
}
// processResults loops forever until cResults is closed
func processResults(cResult <-chan Result, plain *bool) {
matchObj := matchObjFunc(*plain)
for result := range cResult {
matchObj(result)
}
}
////}}}
//// Job {{{
type Job struct {
filename string
results chan<- Result
}
func (job *Job) Do(lineRx *regexp.Regexp) {
if cfg.Dbg {
defer tw.Enter(PP("%s", job.filename))()
}
/*
job.results <- Result{
Filename: "name",
Lino: 11,
Line: "2",
}
*/
file, err := os.Open(job.filename)
check(err)
defer file.Close()
fi, err := file.Stat()
check(err)
switch mode := fi.Mode(); {
case mode.IsDir():
return
case mode.IsRegular():
ctr.add()
reader := bufio.NewReader(file)
for lino := 1; ; lino++ {
line, err := reader.ReadBytes('\n')
line = bytes.TrimRight(line, "\n\r")
if lineRx.Match(line) {
//if len(job.results) == cap(job.results) {
// Red("E: chan cResults full.")
// //panic(tw.Exit{1})
//}
job.results <- Result{"Match", job.filename, lino, string(line)}
}
// As is common when processing a textfile in Go,if an error occurs when reading a line we handle it after working on the line.
// this ensures to handle the last line which might not end with \n
if err != nil {
if err != io.EOF {
Red("error:%d: %s\n", lino, err)
}
break
}
}
}
}
////}}}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
app := kingpin.New(cfg.Name, "cgrep: FileInfo objects must be piped in.")
Green2("START %s: %s", cfg.Name, time.Now())
defer tw.HandleExit()
defer tw.End(time.Now())
// --completion-script-bash: HintOptions, HintAction(func)
app.Flag("debug", "debug").Short('d').Envar("twDbg").BoolVar(&cfg.Dbg)
app.Flag("regex", "regex").Short('p').Default(".*").StringVar(&cfg.regex)
//app.Arg("files", "files").Required().StringsVar(&cfg.files)
plain := app.Flag("plain", "plain, no json output").Bool()
kingpin.MustParse(app.Parse(os.Args[1:]))
if cfg.Dbg {
dbg = Debug2
}
dbg("regex=%q", cfg.regex)
lineRx, err := regexp.Compile(cfg.regex)
if err != nil {
Red("invalid regexp: %s\n", err)
panic(tw.Exit{1})
}
cJob := make(chan Job, workers)
//cResult := make(chan Result, minimum(1000, len(filenames)))
cResult := make(chan Result, CHAN_BUF)
cDone := make(chan struct{}, workers) // value doesnt matter
for i := 0; i < workers; i++ {
go doJobs(cDone, lineRx, cJob)
}
// if not async run, then chan buffer fills up
go addJobs(cJob, cResult)
go awaitCompletion(cDone, cResult)
processResults(cResult, plain) //blocks until cResults is closed
//Log2("M: %d files processed", ctr.n)
panic(tw.Exit{0})
}
<file_sep>/gm/gm_test.sh
# vim: fdm=marker ts=4 sts=4 sw=4 fdl=0
#!/bin/bash
. $HOME/binx/myFunc.x
tE1 () {
printf "____Running tE1: FileInfo input and debugging to STDERR\n"
ref='[IsDir IsRegular ModTime Mode Name Path RelPath Size Type]'
got="$(gci *.x | go run gm.go -d)"
if [ "$got" == "$ref" ]; then
Green "Pass: $got"
else
printf "Expected: %s\n" "$ref"
printf "Got: %s\n" "$got"
Red "NOK"
fi
return 0
}
tE2 () {
printf "____Running tE2: FileInfo input\n"
ref='[IsDir IsRegular ModTime Mode Name Path RelPath Size Type]'
got="$(gci *.x | go run gm.go)"
if [ "$got" == "$ref" ]; then
Green "Pass: $got"
else
printf "Expected: %s\n" "$ref"
printf "Got: %s\n" "$got"
Red "NOK"
fi
return 0
}
#### Run {{{
case "$1" in
1)
tE1
;;
all|*)
tE1; tE2
;;
esac
####}}}
<file_sep>/sl/sl_test.sh
# vim: fdm=marker ts=4 sts=4 sw=4 fdl=0
#!/bin/bash
. $HOME/binx/myFunc.x
cmd="/Users/q187392/dev/gom/bin/g"
editCsv=./test.edit.csv
tE1 () {
printf "____Running tE1: select nothing\n"
ref=9
got=$(gci sl.go | go run sl.go | wc -l)
if [ "$got" -eq "$ref" ]; then
Green "Pass"
else
printf "Expected: %s\n" "$ref"
printf "Got: %s\n" "$got"
Red "NOK"
fi
return 0
}
tE2 () {
printf "____Running tE2: select two attributes and remove comma in debugging mode.\n"
ref="sl.go
/Users/q187392/dev/gom/src/github.com/sysid/helper/sl/sl.go"
got=$(gci sl.go | go run sl.go -d "Path", "Name")
if [ "$got" == "$ref" ]; then
Green "Pass"
else
printf "Expected: %s\n" "$ref"
printf "Got: %s\n" "$got"
Red "NOK"
fi
return 0
}
#### Run {{{
case "$1" in
1)
tE1
;;
2)
tE2
;;
all|*)
tE1; tE2;
;;
esac
####}}}
<file_sep>/install.x
#!/bin/bash
declare -a Cmds=(
"go install ./gci/gci.go"
"go install ./gm/gm.go"
"go install ./sls/sls.go"
"go install ./rpl/rpl.go"
)
for cmd in "${Cmds[@]}"; do
echo "$cmd"
$cmd
done
<file_sep>/README.md
# Cross-platform helper
## rpl
Replaces string in input, either from file or from stdin. Write to stdout.
```bash
cat file | rpl -s 'toBeReplaced' -r 'replacement'
```
## du
Disk Usage calculates the cumulative size of all files below the designated path in KB.
```bash
du .
```
# Objects down the Pipe
Wouldn't it be beautiful to have objects passed down the pipe instead of just plain text? Yes, we
know this from PowerShell.
At least as we Poor Man's solution simple key-value objects can be passed as JSON to downstream
receivers.
To see the JSON object charcter:
```
gci -r *.sh | cat
```
## gci
Get-ChildItems walks the directory starting from the current path and shows all files
according to the filter. If not filter ist given all files are printed out. Analogous to
`Get-ChildItem` from Powershell.
```bash
gci -r *.go
```
## gm
Get-Member prints the members' name of the piped in objects (property bags).
```bash
gci -r *.sh | gm
```
## sl
Select: print the members of the piped-in objects.
To print the Name and Path of the piped-in files:
```bash
gci -r *.sh | sl Name Path
```
<file_sep>/class/cmd/class/read.go
package main
import (
"bufio"
"encoding/json"
"fmt"
"os"
"github.com/sysid/helper/class"
. "github.com/sysid/tw/basic"
)
func main() {
fi := class.FileInfo{}
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
fmt.Println(scanner.Text()) // Println will add back the final '\n'
err := json.Unmarshal(scanner.Bytes(), &fi)
if err != nil {
fmt.Println("error:", err)
}
Debug("%+v", fi)
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
}
}
<file_sep>/sls/cgrep.go
// vim: fdm=marker ts=4 sts=4 sw=4 fdl=0
package main
//// Imports {{{
import (
"bufio"
"bytes"
"fmt"
_ "fmt"
"io"
"os"
"path/filepath"
"regexp"
"runtime"
"sync"
"time"
"gopkg.in/alecthomas/kingpin.v2"
"github.com/sysid/tw"
. "github.com/sysid/tw/basic"
)
////}}}
//// Variables/Constants {{{
var (
//l = tw.NewDefaultLogger(os.Stdout)
dbg = func(v ...interface{}) {}
cfg = Cfg{
Version: "0.1",
Name: filepath.Base(os.Args[0]),
}
workers = runtime.NumCPU()
wg *sync.WaitGroup
)
////}}}
//// Types and Methods {{{
type Cfg struct {
Name string
Version string
Dbg bool
regex string
files []string
}
type Result struct {
filename string
lino int
line string
}
////}}}
//// init {{{
/*
func init() {
app.Name = filepath.Base(os.Args[0])
app.Usage = "appusage"
app.EnableBashCompletion = false
// global flags
app.Flags = []cli.Flag{
cli.BoolFlag{
Name: "d, debug",
Usage: "show debug output",
},
cli.StringFlag{
Name: "regex, r",
Usage: "regular expression",
},
}
// executes before any commands in any case -> init
app.Before = func(c *cli.Context) error {
if c.Bool("debug") || c.Bool("d") {
debug = Debug
}
if !c.IsSet("r") && !c.IsSet("regex") {
return errors.New("regex must be given")
}
debug("%b, %s, %v", c.Bool("debug"), c.String("regex"), c.Args())
return nil
}
}
*/
////}}}
//// helper {{{
func minimum(x int, ys ...int) int {
for _, y := range ys {
if y < x {
x = y
}
}
return x
}
func check(e error) {
if e != nil {
panic(e)
}
}
func commandLineFiles(files []string) []string {
//if runtime.GOOS == "windows" {
args := make([]string, 0, len(files))
for _, name := range files {
if matches, err := filepath.Glob(name); err != nil {
args = append(args, name) // Invalid pattern
} else if matches != nil { // At least one match
args = append(args, matches...)
}
}
return args
//}
dbg("%s: files=%s args=%s", tw.GetFN(), files, args)
return files
}
////}}}
//// Async {{{
func grep(lineRx *regexp.Regexp, filenames []string) {
cJob := make(chan Job, workers)
cResult := make(chan Result, minimum(1000, len(filenames)))
cDone := make(chan struct{}, workers) // value doesnt matter
go addJobs(cJob, filenames, cResult)
for i := 0; i < workers; i++ {
go doJobs(cDone, lineRx, cJob)
}
go awaitCompletion(cDone, cResult)
processResults(cResult) //blocks until cResults is closed
}
// addJobs loops until all jobs are put into chan, then closes chan
func addJobs(cJob chan<- Job, filenames []string, cResult chan Result) {
for _, filename := range filenames {
cJob <- Job{filename, cResult} // result channel is passed with the job
}
close(cJob)
}
// doJob loops until cJob is closed, then sends Done signal
func doJobs(cDone chan<- struct{}, lineRx *regexp.Regexp, cJob <-chan Job) {
for job := range cJob {
job.Do(lineRx)
}
cDone <- struct{}{}
}
// awaitCompletion blocks until receiving x-time the Done signal, then closes cResult
// we cannot pass the results channel as receive-only channel (<-chan Result), since Go disallows closing such channels!!!
func awaitCompletion(cDone <-chan struct{}, cResult chan Result) {
for i := 0; i < workers; i++ {
<-cDone
}
close(cResult)
}
// processResults loops forever until cResults is closed
func processResults(cResult <-chan Result) {
for result := range cResult {
fmt.Printf("%s:%d:%s\n", result.filename, result.lino, result.line)
}
}
////}}}
//// Job {{{
type Job struct {
filename string
results chan<- Result
}
func (job *Job) Do(lineRx *regexp.Regexp) {
defer tw.Enter(PP("%s", job.filename))()
/*
job.results <- Result{
filename: "name",
lino: 11,
line: "2",
}
*/
file, err := os.Open(job.filename)
check(err)
defer file.Close()
fi, err := file.Stat()
check(err)
switch mode := fi.Mode(); {
case mode.IsDir():
return
case mode.IsRegular():
reader := bufio.NewReader(file)
for lino := 1; ; lino++ {
line, err := reader.ReadBytes('\n')
line = bytes.TrimRight(line, "\n\r")
if lineRx.Match(line) {
job.results <- Result{job.filename, lino, string(line)}
}
// As is common when processing a textfile in Go,if an error occurs when reading a line we handle it after working on the line.
// this ensures to handle the last line which might not end with \n
if err != nil {
if err != io.EOF {
Red("error:%d: %s\n", lino, err)
}
break
}
}
}
}
////}}}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
app := kingpin.New(cfg.Name, "My App with Bash Completion")
Green("START %s: %s", cfg.Name, time.Now())
defer tw.HandleExit()
defer tw.End(time.Now())
// --completion-script-bash: HintOptions, HintAction(func)
app.Flag("debug", "debug").Short('d').Envar("twDbg").BoolVar(&cfg.Dbg)
app.Flag("regex", "regex").Short('p').Default(".*").StringVar(&cfg.regex)
app.Arg("files", "files").Required().StringsVar(&cfg.files)
kingpin.MustParse(app.Parse(os.Args[1:]))
if cfg.Dbg {
dbg = Debug
}
dbg("regex=%q", cfg.regex)
if lineRx, err := regexp.Compile(cfg.regex); err != nil {
Red("invalid regexp: %s\n", err)
panic(tw.Exit{1})
} else {
Green("Running grep now...")
grep(lineRx, commandLineFiles(cfg.files))
}
panic(tw.Exit{0})
}
<file_sep>/rpl/test.sh
#!/bin/bash
printf "..... Running Pipe input .....\n"
echo "xxx" | go run rpl.go -s "xxx" -r "___"
printf "..... Running file input .....\n"
if [ -f ./output.txt ]; then
rm ./output.txt
fi
go run rpl.go -d -s "xxx" -r "___" input.txt
<file_sep>/gm/gm.go
// vim: fdm=marker ts=4 sts=4 sw=4 fdl=0
package main
//// Imports {{{
import (
"bufio"
"encoding/json"
"fmt"
"os"
"path/filepath"
"github.com/sysid/helper/class"
"github.com/sysid/tw"
. "github.com/sysid/tw/basic"
"gopkg.in/alecthomas/kingpin.v2"
)
////}}}
//// Global Variables/Constants {{{
var (
dbg = func(v ...interface{}) {}
cfg = Cfg{
Version: "0.1",
Name: filepath.Base(os.Args[0]),
}
)
////}}}
//// Types and Methods {{{
type Cfg struct {
Name string
Version string
Dbg bool
}
////}}}
//// Functions {{{
func check(e error) {
if e != nil {
panic(tw.Exit{1})
}
}
////}}}
//// Main {{{
func main() {
app := kingpin.New(cfg.Name, "My App with Bash Completion")
defer tw.HandleExit()
// --completion-script-bash: HintOptions, HintAction(func)
app.Flag("debug", "debug").Short('d').Envar("twDbg").BoolVar(&cfg.Dbg)
kingpin.MustParse(app.Parse(os.Args[1:]))
if cfg.Dbg {
dbg = Debug2
}
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
data := scanner.Text()
dbg("Input=%s", scanner.Text()) // Println will add back the final '\n'
typ, keys, _ := class.ReadType(data)
// OUTPUT RESULT
fmt.Printf("%s\n", keys) // NOT LOG!!!
if _, ok := class.TypeFactory[typ]; ok {
// TypeOf shows type *class.FileInfo of interface{}
obj := class.TypeFactory[typ]()
err := json.Unmarshal([]byte(data), obj)
check(err)
switch v := obj.(type) {
case string:
case int32, int64:
case *class.FileInfo:
dbg("%s: %T, %+v", tw.GetFN(), *v, *v)
case nil:
//Red("Nil: Nothing to check?")
default:
//Red("Type unkknown: %T", v)
}
} else {
fmt.Fprintf(os.Stderr, "Type not in TypeFactory. %s\n", typ)
}
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
}
panic(tw.Exit{0})
}
////}}}
<file_sep>/gm/gmReflection.go
// vim: fdm=marker ts=4 sts=4 sw=4 fdl=0
package main
//// Imports {{{
import (
"bufio"
"encoding/json"
"fmt"
"os"
"path/filepath"
"reflect"
"time"
"github.com/sysid/helper/class"
"github.com/sysid/tw"
. "github.com/sysid/tw/basic"
"gopkg.in/alecthomas/kingpin.v2"
)
////}}}
//// Global Variables/Constants {{{
var (
dbg = func(v ...interface{}) {}
cfg = Cfg{
Version: "0.1",
Name: filepath.Base(os.Args[0]),
}
m map[string]reflect.Type
)
////}}}
//// Types and Methods {{{
type Cfg struct {
Name string
Version string
Dbg bool
}
// http://stackoverflow.com/questions/10210188/instance-new-type-golang
type Creator func() interface{}
type A struct {
a int
}
type B struct {
a bool
}
func NewA() interface{} {
return new(A)
}
func NewB() interface{} {
return new(B)
}
////}}}
//// Functions {{{
func init() {
// helper to get reflect.Type by name
m = make(map[string]reflect.Type)
m["FileInfo"] = reflect.TypeOf((*class.FileInfo)(nil)).Elem()
}
func check(e error) {
if e != nil {
panic(e)
}
}
////}}}
//// Main {{{
func main() {
app := kingpin.New(cfg.Name, "My App with Bash Completion")
Green("START %s: %s", cfg.Name, time.Now())
defer tw.HandleExit()
defer tw.End(time.Now())
// --completion-script-bash: HintOptions, HintAction(func)
app.Flag("debug", "debug").Short('d').Envar("twDbg").BoolVar(&cfg.Dbg)
kingpin.MustParse(app.Parse(os.Args[1:]))
if cfg.Dbg {
dbg = Debug
}
dbg("Hello World from debug.")
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
data := scanner.Text()
fmt.Println(scanner.Text()) // Println will add back the final '\n'
// preparsing to get object type
var objmap map[string]*json.RawMessage
err := json.Unmarshal([]byte(data), &objmap)
check(err)
var str string
err = json.Unmarshal(*objmap["Type"], &str)
Debug("%+v", str)
// http://stackoverflow.com/questions/10210188/instance-new-type-golang
// https://groups.google.com/forum/#!topic/golang-nuts/IXyJXbca1f4
// fi is FileInfo Type
fi := reflect.New(m["FileInfo"]).Elem().Interface().(class.FileInfo) // type assertion!!!
Debug("%+v, %T", fi, fi)
err = json.Unmarshal([]byte(data), &fi)
check(err)
Red("%+v", fi)
Red("%T", fi)
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
}
panic(tw.Exit{0})
}
////}}}
<file_sep>/class/class_test.go
// vim: fdm=marker ts=4 sts=4 sw=4 fdl=0
package class
import (
"reflect"
"testing"
"time"
. "github.com/sysid/tw/basic"
)
func check(e error) {
if e != nil {
panic(e)
}
}
func warn(e error) {
if e != nil {
Warn("%s", e)
}
}
func TestNewFileInfo(t *testing.T) {
fi, err := NewFileInfo("./testfile.txt")
check(err)
Green("%+v", fi)
}
func TestoutJson(t *testing.T) {
fi, err := NewFileInfo("./testfile.txt")
check(err)
s, err := outJson(fi)
check(err)
Green("%s", s)
}
func TestOutJson(t *testing.T) {
fi, err := NewFileInfo("./testfile.txt")
check(err)
s := fi.OutJson()
Green("%s", s)
}
func TestReadJson(t *testing.T) {
var err error
reference := FileInfo{
Name: "testfile.txt",
Size: 24,
Mode: "-rw-r--r--",
IsDir: false,
IsRegular: true,
Path: "/Users/q187392/dev/gom/src/github.com/sysid/helper/class/testfile.txt",
}
reference.ModTime, err = time.Parse("2006-01-02T15:04:05-07:00", "2016-06-30T22:20:00+02:00")
check(err)
fi := FileInfo{}
s := `{"Name":"testfile.txt","Size":24,"Mode":"-rw-r--r--","ModTime":"2016-06-30T22:20:00+02:00","IsDir":false,"IsRegular":true,"Path":"/Users/q187392/dev/gom/src/github.com/sysid/helper/class/testfile.txt"}`
err = fi.ReadJson(s)
warn(err)
//fmt.Println(fi)
if !reflect.DeepEqual(fi, reference) {
t.Errorf("got :%v", fi)
t.Errorf("Expected:%v", reference)
}
}
func TestReadType(t *testing.T) {
json := `{"Type":"FileInfo","Name":"gm.go","Size":1784,"Mode":"-rw-r--r--","ModTime":"2016-07-09T14:41:22+02:00","IsDir":false,"IsRegular":true,"Path":"/Users/q187392/dev/gom/src/github.com/sysid/helper/gm/gm.go","RelPath":"."}`
typ, keys, m := ReadType(json)
t.Logf("typ=%s, keys=%v, m=%v", typ, keys, m)
ref := "FileInfo"
if typ != ref {
t.Errorf("got :%v", typ)
t.Errorf("Expected:%v", ref)
}
}
<file_sep>/class/class.go
// vim: fdm=marker ts=4 sts=4 sw=4 fdl=0
package class
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"sort"
"time"
"github.com/sysid/tw"
. "github.com/sysid/tw/basic"
)
//// Global Variables/Constants {{{
var (
dbg = func(v ...interface{}) {}
)
////}}}
//// TypeFactory {{{
// http://stackoverflow.com/questions/10210188/instance-new-type-golang
type Creator func() interface{}
var (
// http://stackoverflow.com/questions/10210188/instance-new-type-golang
// Alternative: Factory
TypeFactory map[string]Creator
)
func init() {
TypeFactory = map[string]Creator{}
TypeFactory["FileInfo"] = NewFileInfoBase
}
/*
obj := class.TypeFactory[typ]()
err := json.Unmarshal([]byte(data), obj)
check(err)
// type shows as type *class.FileInfo, but is interface{} so objrst type assertion
Green("%+v", *obj.(*class.FileInfo))
Green("%T", obj)
*/
////}}}
//// FileInfo {{{
type FileInfo struct {
Type string // type name
Name string // base name of the file
Size int64 // length in bytes for regular files; system-dependent for others
Mode string // file mode bits
//Mode os.FileMode // file mode bits
ModTime time.Time // modification time
IsDir bool
IsRegular bool
Path string
RelPath string
}
func NewFileInfo(name string) (*FileInfo, error) {
_fi, err := os.Stat(name)
if err != nil {
return nil, err
}
fip := &FileInfo{
Type: "FileInfo",
Name: _fi.Name(),
Size: _fi.Size(),
Mode: _fi.Mode().String(),
ModTime: _fi.ModTime(),
IsDir: _fi.IsDir(),
IsRegular: _fi.Mode().IsRegular(),
}
fip.Path, err = filepath.Abs(name)
if err != nil {
return nil, err
}
fip.RelPath = filepath.Dir(name)
return fip, nil
}
func NewFileInfoBase() interface{} {
fip := &FileInfo{}
return fip
}
func (fi *FileInfo) OutJson() string {
s, err := outJson(fi)
if err != nil {
fmt.Fprintf(os.Stderr, "%s", err)
}
return s
}
// ReadJson populates the backing structure from JSON string
func (fi *FileInfo) ReadJson(js string) error {
err := json.Unmarshal([]byte(js), fi)
if err != nil {
return err
}
return nil
}
////}}}
//// Helper {{{
// OutJson generats JSON encoded object as string.
func outJson(c interface{}) (string, error) {
b, err := json.Marshal(c)
if err != nil {
return "", err
}
//os.Stdout.Write(b)
return string(b), nil
}
// ReadType gets object type and returns ordered slice of keys
func ReadType(data string) (string, []string, map[string]interface{}) {
var objmap interface{}
if err := json.Unmarshal([]byte(data), &objmap); err != nil {
Red("E: No valid JSON: %s", err)
panic(tw.Exit{1})
}
m := objmap.(map[string]interface{})
keys := make([]string, 0, len(m))
for k, _ := range m {
keys = append(keys, k)
}
sort.Strings(keys)
typ, ok := m["Type"].(string)
if !ok {
Red2("%s E: illegal typ assertion.", tw.GetFN)
}
return typ, keys, m
}
////}}}
<file_sep>/gci/gci.go
// vim: fdm=marker ts=4 sts=4 sw=4 fdl=0
package main
//// Imports {{{
import (
"fmt"
"os"
"path/filepath"
"github.com/sysid/helper/class"
"github.com/sysid/tw"
. "github.com/sysid/tw/basic"
"gopkg.in/alecthomas/kingpin.v2"
)
////}}}
//// Global Variables/Constants {{{
var (
dbg = func(v ...interface{}) {}
cfg = Cfg{
Version: "0.1",
Name: filepath.Base(os.Args[0]),
}
fileObj func(f string)
)
////}}}
//// Types and Methods {{{
type Cfg struct {
Name string
Version string
Dbg bool
}
////}}}
//// Functions {{{
func getPatternHelp() string {
help := `
pattern:
{ term }
term:
'*' matches any sequence of non-Separator characters
'?' matches any single non-Separator character
'[' [ '^' ] { character-range } ']'
character class (must be non-empty)
c matches character c (c != '*', '?', '\\', '[')
'\\' c matches character c
character-range:
c matches character c (c != '\\', '-', ']')
'\\' c matches character c
lo '-' hi matches character c for lo <= c <= hi
`
return help
}
func VisitFileFn(pattern string) filepath.WalkFunc {
return func(fp string, fi os.FileInfo, err error) error {
if err != nil {
fmt.Println(err) // can't walk here,
return nil // but continue walking elsewhere
}
//if fi.IsDir() {
// fileObj(fp)
// return nil // not a file. ignore.
//}
matched, err := filepath.Match(pattern, fi.Name())
if err != nil {
fmt.Println(err) // malformed pattern
return err // this is fatal.
}
if matched {
fileObj(fp)
}
return nil
}
}
func fileObjFunc(plain bool) func(f string) {
return func(f string) {
fi, err := class.NewFileInfo(f)
if err != nil {
Warn(err)
}
if class.OutObj && !plain {
fmt.Printf("%s\n", fi.OutJson())
} else {
fmt.Printf("%s %6s %s\n", fi.ModTime.Format("02.Jan.06 15:04"), tw.ByteSize(uint64(fi.Size)), fi.Path)
}
}
}
////}}}
//// Main {{{
func main() {
app := kingpin.New(cfg.Name, "Get Child Items (ala Powershell)")
//Green("START %s: %s", cfg.Name, time.Now())
defer tw.HandleExit()
//defer tw.End(time.Now())
// --completion-script-bash: HintOptions, HintAction(func)
app.Flag("debug", "debug").Short('d').Envar("twDbg").BoolVar(&cfg.Dbg)
recursive := app.Flag("recursive", "recursive").Short('r').Bool()
plain := app.Flag("plain", "plain, no json output").Short('p').Bool()
pattern := app.Arg("pattern", getPatternHelp()).Default("*").String()
kingpin.MustParse(app.Parse(os.Args[1:]))
fileObj = fileObjFunc(*plain)
if cfg.Dbg {
dbg = Debug2
}
dbg("pattern:%s, rec:%s", *pattern, *recursive)
if *recursive {
filepath.Walk(".", VisitFileFn(*pattern))
} else {
files, err := filepath.Glob(*pattern)
if err != nil {
panic(tw.Exit{1})
}
for _, v := range files {
fileObj(v)
}
}
panic(tw.Exit{0})
}
////}}}
<file_sep>/rpl/rpl.go
// vim: fdm=marker ts=4 sts=4 sw=4 fdl=0
package main
//// Imports {{{
import (
"bufio"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"time"
"github.com/sysid/tw"
. "github.com/sysid/tw/basic"
"gopkg.in/alecthomas/kingpin.v2"
)
////}}}
//// Global Variables/Constants {{{
var (
//l = tw.NewDefaultLogger(os.Stdout)
dbg = func(v ...interface{}) {}
cfg = Cfg{
Version: "0.1",
Name: filepath.Base(os.Args[0]),
}
)
////}}}
//// Types and Methods {{{
type Cfg struct {
Name string
Version string
Dbg bool
}
////}}}
//// Functions {{{
func check(e error) {
if e != nil {
panic(e)
}
}
func replace(r io.Reader, search, replace string) {
scanner := bufio.NewScanner(r)
//scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
output := strings.Replace(scanner.Text(), search, replace, -1)
fmt.Println(output)
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
panic(tw.Exit{3})
}
}
func openStdinOrFile(input string) (io.Reader, error) {
var err error
r := os.Stdin
if input != "" {
r, err = os.Open(input)
if err != nil {
return nil, err
}
}
// make sure input is pipe
//info, _ := os.Stdin.Stat()
//if (info.Mode() & os.ModeCharDevice) == os.ModeCharDevice {
// fmt.Println("The command is intended to work with pipes.")
//} else if info.Size() > 0 {
// reader := bufio.NewReader(os.Stdin)
// match(*pattern, reader)
//}
return r, nil
}
////}}}
//// Main {{{
func main() {
app := kingpin.New(cfg.Name, "My App with Bash Completion")
Green("START %s: %s", cfg.Name, time.Now())
defer tw.HandleExit()
defer tw.End(time.Now())
// --completion-script-bash: HintOptions, HintAction(func)
app.Flag("debug", "debug").Short('d').Envar("twDbg").BoolVar(&cfg.Dbg)
searchStr := app.Flag("search", "search").Short('s').Required().String()
replaceStr := app.Flag("replace", "replace").Short('r').Required().String()
input := app.Arg("input", "input file").ExistingFile()
kingpin.MustParse(app.Parse(os.Args[1:]))
if cfg.Dbg {
dbg = Debug2
}
dbg("input:%s", *input)
r, err := openStdinOrFile(*input)
if err != nil {
panic(tw.Exit{3})
}
replace(r, *searchStr, *replaceStr)
}
////}}}
<file_sep>/class/helper.go
// vim: fdm=marker ts=4 sts=4 sw=4 fdl=0
package class
import (
"os"
"github.com/sysid/tw"
)
var (
InObj bool
OutObj bool
)
func init() {
InObj = IsPipe(os.Stdin)
OutObj = IsPipe(os.Stdout)
}
func IsPipe(f *os.File) bool {
//fi, err := os.Stdout.Stat()
fi, err := f.Stat()
if err != nil {
panic(tw.Exit{1})
}
if fi.Mode()&os.ModeNamedPipe == 0 {
return false
} else {
return true
}
}
<file_sep>/sl/sl.go
// vim: fdm=marker ts=4 sts=4 sw=4 fdl=0
package main
//// Imports {{{
import (
"bufio"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/sysid/helper/class"
"github.com/sysid/tw"
. "github.com/sysid/tw/basic"
"gopkg.in/alecthomas/kingpin.v2"
)
////}}}
//// Global Variables/Constants {{{
var (
dbg = func(v ...interface{}) {}
cfg = Cfg{
Version: "0.1",
Name: filepath.Base(os.Args[0]),
}
)
////}}}
//// Types and Methods {{{
type Cfg struct {
Name string
Version string
Dbg bool
}
////}}}
//// Functions {{{
func check(e error) {
if e != nil {
Red2("E: %s", e)
panic(tw.Exit{1})
}
}
func sanitize(ss *[]string) {
for i, s := range *ss {
(*ss)[i] = strings.Trim(s, ", ")
}
}
////}}}
//// Main {{{
func main() {
app := kingpin.New(cfg.Name, "My App with Bash Completion")
defer tw.HandleExit()
// --completion-script-bash: HintOptions, HintAction(func)
app.Flag("debug", "debug").Short('d').Envar("twDbg").BoolVar(&cfg.Dbg)
selectKeys := app.Arg("keys", "keys").Strings()
kingpin.MustParse(app.Parse(os.Args[1:]))
if cfg.Dbg {
dbg = Debug2
}
dbg("selectKeys=%+v", *selectKeys)
sanitize(selectKeys)
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
data := scanner.Text()
dbg("Input=%s", scanner.Text()) // Println will add back the final '\n'
_, keys := class.ReadType(data)
var objmap map[string]interface{}
err := json.Unmarshal([]byte(data), &objmap)
check(err)
dbg("objmap=%v", objmap)
for _, k := range keys {
if len(*selectKeys) <= 0 {
fmt.Printf("%v\n", objmap[k])
} else {
if tw.IsStrInSlice(k, *selectKeys) {
fmt.Printf("%v\n", objmap[k])
}
}
}
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
}
panic(tw.Exit{0})
}
////}}}
<file_sep>/gm/gm.x
#!/bin/bash
gci *.x | go run gm.go -d
<file_sep>/gci/gci.sh
# If you're using Bash
eval "$(./gci --completion-script-bash)"
| 97ac4290df922e4c618b56c6ed2c686268966f5d | [
"Markdown",
"Go",
"Shell"
] | 21 | Shell | sysid/helper | e8f680c4a991dfd7b594ee3ab9577c709954df86 | f20282faac37469ea03262beba227c5fbb89ffb5 |
refs/heads/master | <repo_name>syarul/webpack-tape-run<file_sep>/index.js
const runParallel = require('run-parallel')
const execSpawn = require('execspawn')
const tapeRun = require('tape-run')
const str = require('string-to-stream')
class WebpackTapeRun {
constructor (options) {
this.options = options || {}
}
apply (compiler) {
compiler.hooks.emit.tapAsync('WebpackTapeRun', run.bind(null, this.options))
function run (options, compilation, callback) {
const source = []
compilation.chunks
.forEach((chunk) => {
if (chunk.hasRuntime()) {
const files = []
chunk.files.forEach((filename) => {
files.push(compilation.assets[filename].source())
})
source.push(files.join('\n'))
}
})
const stream = str(source.join('\n'))
.pipe(tapeRun(options.tapeRun))
return runParallel([
options.reporter ? report : _default,
exit
], callback)
function report (callback) {
const reporter = execSpawn(options.reporter,
{ stdio: ['pipe', 'inherit', 'inherit'] })
stream.pipe(reporter.stdin)
reporter.on('exit', exited)
function exited (code) {
if (code !== 0) addError('test reporter non-zero exit code')
return callback()
}
}
function _default (callback) {
stream.pipe(process.stdout)
stream.on('results', results)
function results (code) {
if (!code.ok) addError('test reporter non-zero exit code')
return callback()
}
}
function exit (callback) {
stream.on('results', results)
function results (code) {
if (!code.ok) addError('tests failed')
return callback()
}
}
function addError (message) {
compilation.errors.push(new Error(message))
}
}
}
}
module.exports = WebpackTapeRun
<file_sep>/README.md
# webpack-tape-run
[](https://www.npmjs.com/package/webpack-tape-run)
[](https://ci.appveyor.com/project/syarul/webpack-tape-run/branch/master)
Run [tape-run](https://github.com/juliangruber/tape-run) as [webpack](https://webpack.github.io/) plugin
Runs webpack with the generated output bundle in browser with tape-run (headless or non-headless).
This works well with ```webpack --watch``` as it will run your test every time a file changed.
## Webpack 5.x.x changes
Update to support webpack 5.x.x, some modules require in the webpack config for this to work :-
- path-browserify
- stream-browserify
- process/browser
## Usage
```javascript
var WebpackTapeRun = require('webpack-tape-run')
new WebpackTapeRun(opts)
```
- **opts.tapeRun**: *(object)* ***optional*** tape-run options.
- **opts.reporter**: *(string)* ***optional*** reporter options.
```javascript
module.exports = {
entry: './test',
mode: 'development',
output: {
path: path.resolve(__dirname, './output'),
filename: 'test.js'
},
resolve: {
modules: ['node_modules'],
extensions: ['*', '.js'],
fallback: {
fs: false,
buffer: false,
path: require.resolve('path-browserify'),
stream: require.resolve('stream-browserify')
}
},
target: 'web',
plugins: [
new webpack.ProvidePlugin({
process: 'process/browser'
}),
new WebpackTapeRun({
tapeRun: {
browser: 'phantomjs'
},
reporter: 'tap-spec'
})
]
}
```
By default, output is pipe to ```process.stdout```. You can specify a [reporter](https://github.com/sindresorhus/awesome-tap#reporters) as an option for the output,
if you using [coverify](https://github.com/substack/coverify), you also need [transform-loader](https://github.com/webpack-contrib/transform-loader) in
the ```webpack.config.js```, check [this](https://github.com/syarul/webpack-tape-run/blob/master/webpack.test.js) for a working example
<file_sep>/test.js
var test = require('tape')
test('test success', function(t) {
t.plan(1)
t.equal(1, 1)
t.end()
})<file_sep>/webpack.test.js
const WebpackTapeRun = require('./')
const path = require('path')
const webpack = require('webpack')
module.exports = {
entry: './test',
mode: 'development',
output: {
path: path.resolve(__dirname, './output'),
filename: 'test.js'
},
module: {
rules: [
{
loader: 'transform-loader',
enforce: 'post',
exclude: [/node_modules/],
options: {
coverify: true
}
}
]
},
resolve: {
modules: ['node_modules'],
extensions: ['*', '.js'],
fallback: {
fs: false,
buffer: false,
path: require.resolve('path-browserify'),
stream: require.resolve('stream-browserify')
}
},
target: 'web',
plugins: [
new webpack.ProvidePlugin({
process: 'process/browser'
}),
new WebpackTapeRun({
tapeRun: {
/* browser: 'phantomjs' */
},
reporter: 'coverify'
})
]
}
| c12432f0c9b25cfd1f182724c4a1ffa3da92abc2 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | syarul/webpack-tape-run | 15f8b7e0a3576090ffbc8682685a7b33db2ea2ae | 2fe6b084e715d974f0512988f1a340da5957b870 |
refs/heads/master | <file_sep>package Java_Assignment_2_Statements;
public class Assignment6 {
// 6. Write a class named Assignment6 which creates a float variable x. Set x to some value.
// Then write an if-statement that checks if x is equal to 3. If so, print the message, “x is equal to 3”.
// Write an else-if statement to check if x is greater than 5, and, if so, prints the message,
// “x is greater than 5”. Write another else-if statement to check if x is less than or equal to 0.
// If so, it prints the message, “x is less than or equal to 0”. Write an else-statement to prints the message,
// “x is none of the other options”.
public static void main(String[] args) {
float x = 2.075f;
if (x == 3){
System.out.println("x == 3");
}
else if (x == 5){
System.out.println("x == 5");
}
else if (x <= 0){
System.out.println("x <= 0");
}
else{
System.out.println("x is none of the other options");
}
}
}<file_sep>public class Engine extends CarPart{
public void function(){
System.out.println("Engine runs car.");
}
}<file_sep>package Java_Assignment_1_Introduction;
public class Assignment3 {
public int x = 15;
public int y = 10;
public static void main(String[] args) {
Assignment3 a = new Assignment3();
int z = a.x + a.y;
System.out.println(z);
}
}<file_sep>package two;
import one.Movable;
// Create a package, “two” to place files in.
// Create an interface Animatable that extends Movable (from the above assignment) and declares a
// method animate(). Create a class named MoverAndAnimate that implements Animatable. In an
// Application2 class, create an instance of a MoverAndAnimate and execute both the move() and
// animate() methods.
public interface Animatable extends Movable {
public void animate();
}<file_sep>package model;
// Write a class named Person that declares instance variables name (String) and age(int); they should be
// marked protected. Create a default no-arg constructor for Person. Create another class named
// AwesomePerson that extends Person. AwesomePerson should declare a method talk() that prints its name
// and age properties. AwesomePerson should also have its own default, no-arg constructor.
// In an Application class, instantiate an AwesomePerson and call its talk() method.
// Place the Person and AwesomePerson in the package, model. Place the Application.java file in the
// package, main.
public class Person {
protected String name;
protected int age;
public Person (){
name = "None";
age = -1;
}
public Person(String newName, int newAge){
this.name = newName;
this.age = newAge;
}
public void setName(String newName){
this.name = newName;
}
public void setAge(int newAge){
this.age = newAge;
}
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
}<file_sep>package model;
// Create a class named ReallyAwesomePerson that extends AwesomePerson. Overload the inherited talk()
// method to print a statement of your choice. Update the constructors of Person, AwesomePerson and
// ReallyAwesomePerson to print a message of your choice.
// Update the Application class from the above assignment to instantiate a ReallyAwesomePerson and run its
// talk() method that you overloaded.
// Notice the order of the constructors executed when you run the application.
// ReallyAwesomePerson.java should be in the package, model.
public class ReallyAwesomePerson extends AwesomePerson{
public ReallyAwesomePerson(String newName, int newAge){
this.name = newName;
this.age = newAge;
}
public void talk(){
System.out.printf("\nYo! Name's %s. %d.\n", this.name, this.age);
}
}<file_sep>package Java_Assignment_2_Statements;
public class Assignment2 {
public static void main(String[] args) {
int x = 5;
System.out.println(x>3 ? "x is greater then 3" : "x is less then 3");
x = 3;
System.out.println(x>3 ? "x is greater then 3" : "x is less then 3");
x = 2;
System.out.println(x>3 ? "x is greater then 3" : "x is less then 3");
}
}<file_sep>import java.util.ArrayList;
import java.util.List;
import java.util.Random;
// Write a class Account that declares an id (long) property and an accountType (String) property. Create
// a method that has the following signature:
// List<Account> createAccounts(int numAccounts).
// The method should create a number of Accounts equal to the numAccounts parameter and return those
// accounts in a List. For example, createAccounts(5) should create five instances of Account and return
// those in a List.
// In an Application class, call the createAccounts() and then loop through the returned List and print the
// ids of each Account.
public class Account{
protected long id;
protected String accountType;
public Account(){
Random r = new Random();
this.id = r.nextInt(1000);
this.accountType = "checking";
}
public static List<Account> createAccounts(int numAccounts){
int i = 0;
List<Account> l = new ArrayList();
while (i<numAccounts){
Account a = new Account();
l.add(a);
i++;
}
return l;
}
}<file_sep>package Java_Assignment_2_Statements;
public class Assignment10 {
public static void main(String[] args) {
double[] arr = {1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0};
for(double i : arr){
System.out.println(i);
}
}
}<file_sep>package com.mycompany.main;
// Create a class named FinalClass and define an instance variable, myConstant. Use the final keyword
// to mark the instance variable as final. This makes it a constant. Add a statement to your Application
// class to print the value of this constant.
public class FinalClass {
final int myConstant = 1;
}<file_sep>// Write a class MyObject that declares a property id (long). Override the equals method to compare two
// objects and if the following occurs, returns true:
// a. The second object is of type MyObject
// b. The second object has an id property that is equal to this MyObject’s id property.
// You will need to write an Application class to create two instances of MyObject that have the same
// value for their id property. Write a conditional statement to test if the two objects are equivalent using
// the .equals() method of your MyObject class. Print statements in the true condition and in the false
// condition.
// For this exercise, you’ll need to use the instanceof operator to check if a class is the same type as
// another.
// ex:
// if (o instanceof SomeObject) { … }
public class MyObject{
private long propertyId;
public MyObject(long id){
this.propertyId = id;
}
@Override
public boolean equals(Object o){
if (o instanceof MyObject){
return ((MyObject) o).propertyId == this.propertyId;
}
return false;
}
}<file_sep>// Write a class CustomException that extends the Exception class. In another class Runner, write a
// method, run() that throws this CustomException. Use a try/catch/block to manage exception handling in
// an Application class that instantiates a Runner and calls its run method.
public class Application {
public static void main(String[] args) {
Runner r = new Runner();
try {
r.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}<file_sep>package Java_Assignment_1_Introduction;
public class Assignment6 {
public double[] arr = {10.5, 11.5};
public static void main(String[] args) {
Assignment6 a = new Assignment6();
System.out.println(a.arr[0]+a.arr[1]);
}
}<file_sep>// Create a Java project in eclipse, called "PracticeCar"
// Create a class called "Simulator", with a main() method.
// Create a "Car" class, with a run() method.
// Inside the main() method of Simulator, create an instance of a Car object, and invoke that object's run() method.
public class Car {
Engine engine;
FuelTank tank;
public Car(){
this.engine = new Engine();
this.tank = new FuelTank();
}
public void run(){
System.out.println("running...");
}
}
<file_sep>import java.util.List;
import java.util.ArrayList;
// Write a class Account that declares an id (long) property and an accountType (String) property. Create
// a method that has the following signature:
// List<Account> createAccounts(int numAccounts).
// The method should create a number of Accounts equal to the numAccounts parameter and return those
// accounts in a List. For example, createAccounts(5) should create five instances of Account and return
// those in a List.
// In an Application class, call the createAccounts() and then loop through the returned List and print the
// ids of each Account.
public class Application {
public static void main(String[] args) {
List<Account> l = Account.createAccounts(5);
for(Account a : l){
System.out.println(a.id);
System.out.println(a.accountType);
}
}
}<file_sep>package Java_Assignment_1_Introduction;
public class Assignment8 {
public float x = 105.678f;
public float y = 22.4871f;
public static void main(String[] args) {
Assignment8 a = new Assignment8();
System.out.println(a.x + a.y);
}
}<file_sep>package Java_Assignment_3_Strings;
// Write a class named Assignment6 that finds the index of the 2nd space character in "Hello My Name is
// Java"; Print this number. (Hint: you may have to combine two String methods)
public class Assignment6 {
public static void main(String[] args) {
String s = "Hello my name is Java";
System.out.println(s.indexOf(' ', s.indexOf(' ') + 1));
}
}<file_sep>package Java_Assignment_2_Statements;
public class Assignment4 {
public static void main(String[] args) {
int x = 5;
System.out.println(x==3 ? "x == 3" : "x != 3");
x = 3;
System.out.println(x==3 ? "x == 3" : "x != 3");
x = 2;
System.out.println(x==3 ? "x == 3" : "x != 3");
}
}<file_sep>package Java_Assignment_1_Introduction;
public class Assignment7 {
public int[] arr = {11, 22, 33};
public static void main(String[] args) {
Assignment7 a = new Assignment7();
System.out.println((a.arr[0]-a.arr[1])+a.arr[2]);
}
}<file_sep>package Java_Assignment_3_Strings;
// Write a class named Assignment4 that declares a string "abcdefghijklmnopqrstuvwxyz". Use the
// indexOf() method to print the index of "s" and "f".
public class Assignment4 {
public static void main(String[] args) {
String s1 = "abcdefghijklmnopqrstuvwxyz";
System.out.printf("%d %d", s1.indexOf("s"), s1.indexOf("f"));
}
}<file_sep>package Java_Assignment_3_Strings;
// Write a class named Assignment2 that uses a 2 if-statement to compare the strings “abc” and “ABC”.
// The first if-statement should use the double equals (==) operator and the other that uses the .equals()
// method of one of the strings to compare to the other. Print a message in both if-statements to indicate
// that the strings are equal
public class Assignment2 {
public static void main(String[] args) {
String lower = "abc";
String upper = "ABC";
if (lower == upper){
System.out.println("strings are ==");
}
else if (upper.equals(lower)){
System.out.println("strings are equals()");
}
else if (upper.equalsIgnoreCase(lower)){
System.out.println("strings are equalsIgnoreCase()");
}
else {
System.out.println("strings are !=");
}
}
} | d6ebd851d203cd225eecdef925b270a8971f429d | [
"Java"
] | 21 | Java | LNPappas/Java | cbd7afceb836cd3a918e9a33c66c649c12d4f645 | 15e4d3e85f3194b41745c85d26f98d1aa678eb77 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.