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> #include <ctype.h> #include <string.h> #include <time.h> #include "Genericas.h" #include "LinkedList.h" #include "LinkedList.h" #include "parser.h" #include "Paises.h" //-------------------------------------------------[ Crear/Eliminar ]-------------------------------------------------// ePais* newPais() { ePais* newPais= (ePais*) malloc(sizeof(ePais)); if(newPais!=NULL) { pais_setId(newPais,0); pais_setNombre(newPais," "); pais_setPrimeraDosis(newPais,0); pais_setSegundaDosis(newPais,0); pais_setSinVacunar(newPais,0); } return newPais; } ePais* newPaisParam(char* strId, char* strNombre, char* strDosis1, char* strDosis2, char* strSinVacunar) { ePais* auxPais = newPais(); if(auxPais!=NULL) { if(!(pais_setId(auxPais, atoi(strId)) && pais_setNombre(auxPais, strNombre) && pais_setPrimeraDosis(auxPais, atoi(strDosis1)) && pais_setSegundaDosis(auxPais, atoi(strDosis2)) && pais_setSinVacunar(auxPais, atoi(strSinVacunar)) )) { destroyPais(auxPais); } } return auxPais; } int destroyPais(ePais* pais) { int retorno = 0; if( pais != NULL ) { free(pais); retorno = 1; } return retorno; } //-----------------------------------------------[ Setters ]-----------------------------------------------// int pais_setId(ePais* pais, int idRef) { int retorno=0; if( pais != NULL && idRef > 0 ) { pais->id = idRef; retorno=1; } return retorno; } int pais_setNombre(ePais* pais, char* pNombre) { int retorno=0; if( pais!=NULL && pNombre!=NULL && (strlen(pNombre) > 3 || strlen(pNombre) < 30) ) { strcpy(pais->nombre, pNombre); retorno=1; } return retorno; } int pais_setPrimeraDosis(ePais* pais, int dosis1Ref) { int retorno=0; if( pais != NULL && dosis1Ref >=0 ) { pais->vac1Dosis = dosis1Ref; retorno=1; } return retorno; } int pais_setSegundaDosis(ePais* pais, int dosis2Ref) { int retorno=0; if( pais != NULL && dosis2Ref >= 0) { pais->vac2Dosis = dosis2Ref; retorno=1; } return retorno; } int pais_setSinVacunar(ePais* pais, int sinVacunarRef) { int retorno=0; if(pais!=NULL && sinVacunarRef >= 0) { pais->sinVacunar = sinVacunarRef; retorno=1; } return retorno; } //-----------------------------------------------[ Getters ]-----------------------------------------------// int pais_getId(ePais* pais, int* pId) { int retorno = 0; if( pais != NULL && pId != NULL) { *pId = pais->id; retorno=1; } return retorno; } int pais_getNombre(ePais* pais, char* pNombre) { int retorno = 0; if( pais != NULL && pNombre != NULL ) { strcpy(pNombre, pais->nombre); retorno = 1; } return retorno; } int pais_getPrimeraDosis(ePais* pais, int* pVac1Dosis) { int retorno = 0; if( pais != NULL && pVac1Dosis != NULL) { *pVac1Dosis = pais->vac1Dosis; retorno = 1; } return retorno; } int pais_getSegundaDosis(ePais* pais, int* pVac2Dosis) { int retorno=0; if( pais != NULL && pVac2Dosis != NULL) { *pVac2Dosis = pais->vac2Dosis; retorno=1; } return retorno; } int pais_getSinVacunar(ePais* pais, int* pSinVacunar) { int retorno=0; if( pais != NULL && pSinVacunar != NULL) { *pSinVacunar = pais->sinVacunar; retorno=1; } return retorno; } //-----------------------------------------------[ Imprimir por Pantalla ]-----------------------------------------------// int menu() { int opcion; system("cls"); printf("Menu\n"); printf("---------------------------\n"); printf("1. Cargar datos desde archivo\n"); printf("2. Imprimir lista\n"); printf("3. Generar estadisticas\n"); printf("4. Filtrar por paises exitosos\n"); printf("5. Filtrar por paises en el horno\n"); printf("6. Ordenar por nivel de vacunacion\n"); printf("7. Mostrar mas castigados\n"); printf("8. Salir\n\n\n"); getInt(&opcion, "Ingrese opcion: \n", "\nError, Ingrese opcion: \n", 1, 8, 3); return opcion; } int mostrarListaPaises(LinkedList* lista) { int retorno=0; int len = ll_len(lista); if(lista!=NULL) { printf("*************************************************************\n"); printf(" Id Nombre \tDosis-1 Dosis-2 S/Vacuna \n"); printf("*************************************************************\n\n");; for(int i=0; i<len; i++) { mostrarUnPais( (ePais*) ll_get(lista,i)); retorno=1; } } return retorno; } int mostrarUnPais(ePais* unPais) { int retorno=0; int id; char nombre[30]; int dosis1; int dosis2; int sinVacunar; if(unPais!=NULL) { if( pais_getId(unPais, &id) && pais_getNombre(unPais, nombre) && pais_getPrimeraDosis(unPais, &dosis1) && pais_getSegundaDosis(unPais, &dosis2) && pais_getSinVacunar(unPais, &sinVacunar)) { printf("%3d %20s %4d %4d %4d \n", id, nombre, dosis1, dosis2, sinVacunar); retorno=1; } } return retorno; } int menuSort() { int buffer; system("cls"); printf("\n**Menur Orden**"); printf("\n1) Dosis Totales."); printf("\n2) Primera Dosis."); printf("\n3) Segunda Dosis."); printf("\n4) Sin Vacunar Dosis."); getInt(&buffer,"","\nDato invalido!\n",1,4,5); return buffer; } int menuTypeSort() { int buffer; system("cls"); printf("\n**Menur Orden**"); printf("\n1) Ascendente."); printf("\n2) Descendente."); getInt(&buffer,"","\nDato invalido!\n",1,2,5); return buffer; } //-----------------------------------------------[ Ordenamiento / Filtrado ]-----------------------------------------------// void* cargarRandom(void* pais) { int dosis1, dosis2, sinVacuna; if( pais != NULL ) { //Genero valores random dosis1 = numeroRandom(1,60); dosis2 = numeroRandom(1,40); sinVacuna = 100 - (dosis1 + dosis2); // Asigno los valores Al pais con los setters if(!(pais_setPrimeraDosis(pais,dosis1) && pais_setSegundaDosis(pais, dosis2) && pais_setSinVacunar(pais, sinVacuna))) { printf("\n***Error al cargar datos!.***\n"); } } return pais; } int numeroRandom(int min,int max) { int numero; numero = rand() % (max - min + 1) + min;// Devuelve siempre los mismos numeros aleatorios return numero; } int filtrarPaisExitoso(void* pais) { int retorno = 0; int dosis1; int dosis2; int sinVacunar; int porcentaje; if( pais != NULL ) { if( pais_getPrimeraDosis(pais,&dosis1) &&pais_getSegundaDosis(pais, &dosis2) && pais_getSinVacunar(pais,&sinVacunar)) { porcentaje = (sinVacunar*0.30); if( dosis1+dosis2 > porcentaje ) { retorno = 1; } } } return retorno; } int filtrarPaisAlHorno(void* pais) { int retorno = 0; int sinVacunar; int dosis1; int dosis2; if( pais != NULL ) { // Tomo dosis 1, dosis 2 y cantidad sin vacunar if( (pais_getPrimeraDosis(pais, &dosis1) && pais_getSegundaDosis(pais, &dosis2) && pais_getSinVacunar(pais, &sinVacunar)) ) { // Si la cantidad de gente sin vacunar es Mayor a los vacunados if( sinVacunar > (dosis1+dosis2) ) { retorno = 1; } } } return retorno; } int ordenarPorDosisUno(void* a, void* b) { int retorno; if(a != NULL && b != NULL) { ePais* NodoAux1 = (ePais*) a; ePais* NodoAux2 = (ePais*) b; if( NodoAux1->vac1Dosis > NodoAux2->vac1Dosis ) { retorno = -1; } else if( NodoAux1->vac1Dosis < NodoAux2->vac1Dosis ) { retorno = 1; } else // Si son iguales { retorno = 0; } } return retorno; } int ordenarPorDosisDos(void* a, void* b) { int retorno; if(a != NULL && b != NULL) { ePais* NodoAux1 = (ePais*) a; ePais* NodoAux2 = (ePais*) b; if( NodoAux1->vac2Dosis > NodoAux2->vac2Dosis ) { retorno = -1; } else if( NodoAux1->vac2Dosis < NodoAux2->vac2Dosis ) { retorno = 1; } else // Si son iguales { retorno = 0; } } return retorno; } int ordenarSinVacuna(void* a, void* b) { int retorno; if(a != NULL && b != NULL) { ePais* NodoAux1 = (ePais*) a; ePais* NodoAux2 = (ePais*) b; if( NodoAux1->sinVacunar > NodoAux2->sinVacunar ) { retorno = -1; } else if( NodoAux1->sinVacunar < NodoAux2->sinVacunar ) { retorno = 1; } else // Si son iguales { retorno = 0; } } return retorno; } int ordenarPorDosisTotales(void* a, void* b) { int retorno; int pais1; int pais2; if(a != NULL && b != NULL) { ePais* NodoAux1 = (ePais*) a; ePais* NodoAux2 = (ePais*) b; pais1 = NodoAux1->vac1Dosis + NodoAux1->vac2Dosis; pais2 = NodoAux2->vac1Dosis + NodoAux2->vac2Dosis; if( pais1 > pais2 ) { retorno = -1; } else if( pais1 < pais2 ) { retorno = 1; } else // Si son iguales { retorno = 0; } } return retorno; } int mostrarPaisMasCastigado(LinkedList* lista) { int retorno = 0; int len = ll_len(lista); int sinVacunar; int mayor; if(lista != NULL) { ePais* auxPais = NULL; for(int i=0; i<len; i++) { auxPais = ll_get(lista, i); pais_getSinVacunar(auxPais, &sinVacunar); if( i == 0 || sinVacunar > mayor ) { mayor = sinVacunar; retorno = 1; } } system("cls"); printf("\nPais Mas Castigado\n"); printf("\nId Pais Dosis1 Dosis2 S/Vacuna\n"); for(int i=0; i<len; i++) { auxPais= (ePais*) ll_get(lista, i); pais_getSinVacunar(auxPais, &sinVacunar); if( sinVacunar == mayor ) { mostrarUnPais(auxPais); } } } return retorno; } <file_sep>#include <stdio.h> #include <stdlib.h> #include "LinkedList.h" #include "Paises.h" #include "parser.h" #define ERROR -1 #define ALLOK 1 int loadFromtText(LinkedList* lista, int* flag) { int retorno = 0; char buffer[20]; if( buffer!=NULL && lista != NULL && (*flag == 0)) { system("cls"); printf("Ingrese path del archivo [ej: 'vacunas.csv']: \n"); scanf("%s", buffer); FILE* bufferFile = fopen(buffer, "r"); if( bufferFile != NULL ) { if( parser_FromTxt(bufferFile, lista) ) { retorno=1; *flag=1; } } fclose(bufferFile); } return retorno; } int parser_FromTxt(FILE* pFile, LinkedList* lista){ int retorno=0; char buffer[5][128]; if( pFile != NULL && lista != NULL ) { ePais* bufferPais = NULL;// //Escaneo fscanf(pFile, "%[^,], %[^,], %[^,], %[^,], %[^\n]\n", buffer[0], buffer[1], buffer[2], buffer[3], buffer[4]); do { if( fscanf(pFile, "%[^,], %[^,], %[^,], %[^,], %[^\n]\n", buffer[0], buffer[1], buffer[2], buffer[3], buffer[4]) == 5 ) { //Asigno bufferPais = newPaisParam(buffer[0], buffer[1], buffer[2], buffer[3], buffer[4]); if(bufferPais != NULL) { ll_add(lista, bufferPais); retorno=1; } else { destroyPais(bufferPais); } } else { printf("Hubo un problema al leer los datos desde el archivo\n"); } } while(!feof(pFile)); } return retorno; } int saveAsText(char* path, LinkedList* lista){ int id, dosis1, dosis2, sinVacunar, len, retorno = 0; char nombrePais[24]; ePais* bufferPais = NULL; if( path != NULL && lista != NULL) { len = ll_len(lista); // Leo el tamaņo de la lista y lo guardo en len FILE* bufferF = fopen(path, "w"); // Abro archivo if( bufferF != NULL ) { fprintf(bufferF, "Id, Pais, Primera Dosis, Segunda Dosis, Sin Vacunar\n"); for(int i=0; i<len; i++) { bufferPais = (ePais*) ll_get(lista, i); // tomo el elemento en cada 'posicion' if( bufferPais != NULL) { if( (pais_getId(bufferPais, &id) && pais_getNombre(bufferPais, nombrePais) && pais_getPrimeraDosis(bufferPais, &dosis1) && pais_getSegundaDosis(bufferPais, &dosis2) && pais_getSinVacunar(bufferPais, &sinVacunar) ) ) { if(fprintf(bufferF, "%d, %s, %d, %d, %d\n", id, nombrePais, dosis1, dosis2, sinVacunar) < 5 ) { printf("\nError al salvar datos\n"); destroyPais(bufferPais); break; } else { bufferPais = NULL; retorno = 1; } } } } fclose(bufferF); } else { printf("No se pudo abrir el archivo '%s'\n", path); } } return retorno; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "Genericas.h" #include "LinkedList.h" #include "Paises.h" #include "parser.h" /* 1. Cargar datos desde consola (data.csv) 2. Imprimir lista (listar) 3. Generar estadisticas (random) 4. Filtrar por paises exitosos (ll_filter) 5. Filtrar por paises en el horno (ll_filter) 6. Ordenar por nivel de vacunacion (ll_sort) 7. Mostrar mas castigados (listar) 8. Salir */ int main() { LinkedList* lista = ll_newLinkedList(); //Lista paises Gral LinkedList* listaResultado = NULL; LinkedList* listaExitosos = NULL; LinkedList* listaAlHorno = NULL; srand(time(NULL)); //random int flag = 0; // flag archivo data.csv int flag2 = 0; // flag Estadistica generada char buffer = 'n'; //entrada usuario do { switch( menu()) { system("cls"); case 1: if(!loadFromtText(lista,&flag)) { printf("\nError al cargar los datos!\n"); } else { printf("\nDatos cargados. Ya puede imprimirlos.\n"); } break; case 2: if(flag) { mostrarListaPaises(lista); } else { printf("\nPrimero debe cargar la lista!\n"); } break; case 3: if(flag) { listaResultado = ll_map(lista,cargarRandom); system("pause"); mostrarListaPaises(listaResultado); system("pause"); flag2 = 1; } else { printf("\nPrimero debe cargar la lista![opcion 1]\n"); } break; case 4: if(flag2) { // LLamo a ll_filter le paso mi lista original y la condicion de filtro y ll_filter me retorna la nueva lista que la asigno a 'listaExitosos' listaExitosos = ll_filter(lista, filtrarPaisExitoso); if(listaExitosos != NULL) { // Si pudo generar la nueva lista la guardo en un nuevo archivo saveAsText("PaisesExitosos.csv", listaExitosos); printf("\n Se genero la lista 'PaisesExitosos.csv'!\n"); } else { printf("\n No se puedo generar la lista 'Lista Paises Exitosos'!\n"); } } else { printf("\nPrimero debe generar una estadistica [opcion 3]!\n"); } break; case 5: if(flag2) { // LLamo a ll_filter le paso mi lista original y la condicion de filtro y ll_filter me retorna la nueva lista que la asigno a 'listaAlHorno' listaAlHorno = ll_filter(lista, filtrarPaisAlHorno); if(listaAlHorno != NULL) { // Si pudo generar la nueva lista la guardo en un nuevo archivo saveAsText("PaisesAlHorno.csv", listaAlHorno); printf("\n Se genero la lista 'PaisesAlHorno.csv'!\n"); } else { printf("\n No se puedo generar la lista 'PaisesAlHorno.csv'!.\n"); } } else { printf("\nPrimero debe generar una estadistica [opcion 3]!\n"); } break; case 6: if(flag2) { switch(menuSort()) { case 1: ll_sort(lista,ordenarPorDosisTotales,1); printf("\nLista Ordenada!. Puede imprimirla!.\n"); break; case 2: ll_sort(lista,ordenarPorDosisUno,1); printf("\nLista Ordenada!. Puede imprimirla!.\n"); break; case 3: ll_sort(lista,ordenarPorDosisDos,1); printf("\nLista Ordenada!. Puede imprimirla!.\n"); break; case 4: ll_sort(lista,ordenarSinVacuna,1); printf("\nLista Ordenada!. Puede imprimirla!.\n"); break; } } else { printf("\nPrimero debe generar una estadistica [opcion 3]!\n"); } break; case 7: if(flag2) { mostrarPaisMasCastigado(lista); system("pause"); mostrarPaisMasCastigado(lista); } else { printf("\nPrimero debe generar una estadistica [opcion 3]!\n"); } break; case 8: printf("\nConfirma Salida? [s/n]:\n"); fflush(stdin); scanf("%c",&buffer); break; } printf("\n\n"); system("pause"); } while( buffer == 'n' ); return 0; } <file_sep>#ifndef PAISES_H_INCLUDED #define PAISES_H_INCLUDED typedef struct{ int id; char nombre[30]; int vac1Dosis; int vac2Dosis; int sinVacunar; }ePais; //-----------------------------------------------------[ Crear/Eliminar ]-----------------------------------------------------------// ePais* newPais(); ePais* newPaisParam(char* strId, char* strNombre, char* strVac1Dosis, char* strVac2Dosis, char* strSinVacunar); int destroyPais(ePais* pais); //----------------------------------------------------------[ Setters ]-------------------------------------------------------------// int pais_setId(ePais* pais, int id); int pais_setNombre(ePais* pais, char* pNombre); int pais_setPrimeraDosis(ePais* pais, int vac1Dosis); int pais_setSegundaDosis(ePais* pais, int vac2Dosis); int pais_setSinVacunar(ePais* pais, int sinVacunar); //------------------------------------------------------------[ Getters ]------------------------------------------------------------// int pais_getId(ePais* pais, int* pId); int pais_getNombre(ePais* pais, char* pNombre); int pais_getPrimeraDosis(ePais* pais, int* pVac1Dosis); int pais_getSegundaDosis(ePais* pais, int* pVac2Dosis); int pais_getSinVacunar(ePais* pais, int* pSinVacunar); //-------------------------------------------------------------[ Print ]-----------------------------------------------------------------// int menu(); int mostrarListaPaises(LinkedList* lista); int mostrarUnPais(ePais* unPais); int menuSort(); int menuTypeSort(); //---------------------------------------------------------[ Ordenamiento / Filtrado ]---------------------------------------------------------// void* cargarRandom(void* pais); int numeroRandom(int min,int max); int filtrarPaisExitoso(void* pais); int filtrarPaisAlHorno(void* pais); int ordenarPorDosisTotales(void* a, void* b); int ordenarPorDosisUno(void* a, void* b); int ordenarPorDosisDos(void* a, void* b); int ordenarSinVacuna(void* a, void* b); int mostrarPaisMasCastigado(LinkedList* lista); #endif // PAISES_H_INCLUDED <file_sep>#ifndef PARSER_H_INCLUDED #define PARSER_H_INCLUDED int loadFromtText(LinkedList* lista, int* flagYaSeCargo); int saveAsText(char* path, LinkedList* lista); int parser_FromTxt(FILE* pFile, LinkedList* lista); #endif // PARSER_H_INCLUDED
9b11c8c7b52ad809d926113cf290d39ce46a050b
[ "C" ]
5
C
rijmjada/Ormeno.Diego.SPLabI1A
ba4a1c0f9f3f61e6c456408186ad5b4b92a51673
1f0db984b5eda214ead5bcd02b8fde9424ba08c0
refs/heads/main
<repo_name>norpie-dev/yts-api<file_sep>/api.py import requests BASE_API = "https://yts.mx/api/v2/" def request(base_url, *args): url = base_url + "?" for arg in args: url = url + arg + "&" reponse = requests.get(url) return reponse.json() # List Movies - https://yts.mx/api#list_movies def raw_list_movies(limit="20", page="1", quality="1080p", minimum_rating="0", query_term="0", genre="all", sort_by="date_added", order_by="desc", with_rt_ratings="false"): return request(BASE_API+"list_movies.json", "limit=" + str(limit), "page=" + str(page), "quality" + str(quality), "minimum_rating" + str(minimum_rating), "query_term=" + str(query_term), "genre=" + str(genre), "sort_by" + str(sort_by), "order_by=" + str(order_by), "with_rt_ratings=" + str(with_rt_ratings)) class Torrent: def __init__(self, url, hash, quality, type, size, size_bytes): self.url = url self.hash = hash self.quality = quality self.type = type self.size_colloquial = size self.size_bytes = size_bytes class Movie: def __init__(self, movie_json): # Codes self.id = movie_json["id"] self.url = movie_json["url"] self.imdb_code = movie_json["imdb_code"] # Data self.mpa_rating = movie_json["mpa_rating"] self.rating = movie_json["rating"] self.year = movie_json["year"] self.runtime = movie_json["runtime"] # Genres parsing self.genres = movie_json["genres"] # Text self.title = movie_json["title"] self.title_long = movie_json["title_long"] self.slug = movie_json["slug"] self.summary = movie_json["summary"] self.description = movie_json["description_full"] self.synopsis = movie_json["synopsis"] # Images self.yt_trailer_url = "https://www.youtube.com/watch?v="\ + movie_json["yt_trailer_code"] self.background_image = movie_json["background_image"] self.background_image_original = \ movie_json["background_image_original"] self.small_cover_image = movie_json["small_cover_image"] self.medium_cover_image = movie_json["medium_cover_image"] self.large_cover_image = movie_json["large_cover_image"] # Torrents parsing self.torrents = [] for torrent_json in movie_json["torrents"]: self.torrents.append(Torrent(torrent_json["url"], torrent_json["hash"], torrent_json["quality"], torrent_json["type"], torrent_json["size"], torrent_json["size_bytes"])) # List Movies - https://yts.mx/api#list_movies def list_movies(limit="20", page="1", quality="1080p", minimum_rating="0", query_term="0", genre="all", sort_by="date_added", order_by="desc", with_rt_ratings="false"): json = raw_list_movies(limit=limit, page=page, quality=quality, minimum_rating=minimum_rating, query_term=query_term, genre=genre, sort_by=sort_by, order_by=order_by, with_rt_ratings=with_rt_ratings) movie_json = json["data"]["movies"][0] return Movie(movie_json)
4febf2f49f548b062caee05f200b01df721e1be2
[ "Python" ]
1
Python
norpie-dev/yts-api
7db69a78801922af41157ce8cf7fbd126b3d83fe
b8847ddc57fade213e20e5e6f21156295c57481f
refs/heads/master
<repo_name>VFerrari/OperationalResearch<file_sep>/Project8/README.md Performance Evaluation of Solutions for the MAX-QBF Problem With Forbidden Triples (MAX-QBFPT) ============================================================================================== MO824 - Operational Research: Activity 8. **Team:** - <NAME> (187890) - <NAME> (202495) - <NAME> (208395) Course given by professor [<NAME>](https://www.ic.unicamp.br/~fusberti/). [Instituto de Computação](http://ic.unicamp.br/) - [UNICAMP](http://www.unicamp.br/unicamp/) (S> <file_sep>/Project8/src/metaheuristics/tabusearch/Intensificator.java package metaheuristics.tabusearch; /** * Simple class where the intensification parameters are defined. */ public class Intensificator { /** * Number of consecutive failures that the metaheuristic toleres before it * triggers the intensification method. */ private Integer tolerance; /** * Number of iterations that the intensification lasts. */ private Integer iterations; /** * How many iterations it remains to stop the method. */ private Integer remainingIt; /** * Identifies if the intensification method is running or has stopped. */ private Boolean running; /** * Constructor for the Intensificator class. * * @param tolerance * Number of consecutive failures that the tabu search toleres. * @param iterations * Intensification number of iterations. */ public Intensificator(Integer tolerance, Integer iterations) { this.tolerance = tolerance; this.iterations = iterations; this.running = false; } /** * 'tolerance' getter. * * @return {@link #tolerance}. */ public Integer getTolerance() { return tolerance; } /** * 'iterations' getter. * * @return {@link #iterations}. */ public Integer getIterations() { return iterations; } /** * 'remainingIt' getter. * * @return {@link #remainingIt}. */ public Integer getRemainingIt() { return remainingIt; } /** * 'remainingIt' setter. * * @param newIt * The new number of remaining iterations. */ public void setRemainingIt(Integer newIt) { remainingIt = newIt; } /** * 'running' getter. * * @return {@link #running}. */ public Boolean getRunning() { return running; } /** * 'running' setter. * * @param running * Either the method started running or stopped. */ public void setRunning(Boolean running) { this.running = running; } } <file_sep>/Project8/scripts/pp.py # %% import matplotlib as mpl import matplotlib.pyplot as plt import numpy import pandas import seaborn as sn logplot = False # %% T = pandas.read_csv("runtime.csv") np = len(T) ns = len(T.columns) # %% Minimal performance per solver. minperf = numpy.zeros(np) for k in range(np): minperf[k] = min(T.to_numpy()[k]) # %% Compute ratios and divide by smallest element in each row. r = numpy.zeros((np, ns)) for k in range(np): r[k, :] = T.to_numpy()[k, :] / minperf[k] if logplot: r = numpy.log2(r) max_ratio = r.max() for k in range(ns): r[:, k] = numpy.sort(r[ :, k]) # %% Plot stair graphs with markers. n = [] for k in range(1, np + 1): n.append(k / np) # %% plt.figure(figsize = (8, 5)) plt.plot(r[:, 0], n, color = '#3CB371', linewidth = 1, label = 'GRASP') plt.plot(r[:, 1], n, color = '#FFD700', linewidth = 1, label = 'TS') plt.plot(r[:, 2], n, color = '#4B0082', linewidth = 1, label = 'GA') plt.plot(r[:, 3], n, color = '#FF6347', linewidth = 1, label = 'GUROBI') plt.plot(r[:, 4], n, color = '#4169E1', linewidth = 1, label = 'GUROBI_LINEAR') plt.ylabel('Probabilidade (%)') sn.despine(left = True, bottom = True) plt.grid(True, axis = 'x') plt.grid(True, axis = 'y') plt.legend() plt.savefig('objectiveFunction1.eps', dpi = 1500, transparent = True, bbox_inches = 'tight') plt.show() # %% <file_sep>/Project8/src/problems/qbfpt/solvers/GUROBI_QBFPT.java package problems.qbfpt.solvers; import gurobi.GRB; import gurobi.GRBEnv; import gurobi.GRBException; import gurobi.GRBLinExpr; import gurobi.GRBModel; import gurobi.GRBQuadExpr; import gurobi.GRBVar; import problems.qbf.solvers.GUROBI_QBF; import problems.qbfpt.triples.ForbiddenTriplesGenerator; import problems.qbfpt.triples.Triple; import java.io.FileWriter; import java.io.IOException; public class GUROBI_QBFPT extends GUROBI_QBF { private ForbiddenTriplesGenerator forbiddenTriplesGenerator; public GUROBI_QBFPT(String filename) throws IOException { super(filename); forbiddenTriplesGenerator = new ForbiddenTriplesGenerator(problem.size); } protected void populateNewModel(GRBModel model) throws GRBException { // decision variables x = new GRBVar[problem.size]; for (int i = 0; i < problem.size; i++) { x[i] = model.addVar(0, 1, 0.0f, GRB.BINARY, "x[" + i + "]"); } model.update(); // objective function GRBQuadExpr obj = new GRBQuadExpr(); for (int i = 0; i < problem.size; i++) { for (int j = i; j < problem.size; j++) { obj.addTerm(problem.A[i][j], x[i], x[j]); } } model.setObjective(obj); model.update(); // constraints GRBLinExpr expr; for (Triple triple : forbiddenTriplesGenerator.getForbiddenTriple()) { expr = new GRBLinExpr(); expr.addTerm(1, x[triple.getX() - 1]); expr.addTerm(1, x[triple.getY() - 1]); expr.addTerm(1, x[triple.getZ() - 1]); model.addConstr(expr, GRB.LESS_EQUAL, 2.0, String.valueOf("x_" + triple.getX() + "," + triple.getY() + "," + triple.getZ())); } // maximization objective function model.set(GRB.IntAttr.ModelSense, -1); } public static void main(String[] args) throws IOException, GRBException { // instances String[] instances = {"qbf020", "qbf040", "qbf060", "qbf080", "qbf100", "qbf200", "qbf400"}; // create text file FileWriter fileWriter = new FileWriter("results/GUROBI_QBFPT.txt"); for (String instance : instances) { // read the problem GUROBI_QBFPT gurobi = new GUROBI_QBFPT("instances/" + instance); // create the environment and model env = new GRBEnv(); model = new GRBModel(env); model.getEnv().set(GRB.DoubleParam.TimeLimit, 1800.0); // generate the model gurobi.populateNewModel(model); // solve the model model.optimize(); // save the solution in text file fileWriter.append(instance + ";" + model.get(GRB.DoubleAttr.ObjVal) + ";" + model.get(GRB.DoubleAttr.ObjBound) + ";" + model.get(GRB.DoubleAttr.Runtime)); // dispose the environment and model model.dispose(); env.dispose(); } fileWriter.close(); } } <file_sep>/Project1/generator.py ''' Activity 1 - IP and LP models for paper production and routing problem. generator.py: instance generator, for a certain amount of clients. Subject: MC859/MO824 - Operational Research. Authors: <NAME> - RA 186633 <NAME> - RA 187101 <NAME> - RA 187890 University of Campinas - UNICAMP - 2020 Last Modified: 03/02/2021 ''' from json import dump import numpy as np from sys import argv, exit from os.path import join def generate_instance(n_clients): inst = {} #All ranges were adapted to create feasible instances inst['J'] = n_clients inst['F'] = np.random.randint(inst['J'], 2*inst['J']) inst['L'] = np.random.randint(5,10) inst['M'] = np.random.randint(5,10) inst['P'] = np.random.randint(5,10) inst['D'] = np.random.randint(10, 21, (inst['J'], inst['P'] )).tolist() inst['r'] = np.random.randint(1, 6, (inst['M'], inst['P'], inst['L'])).tolist() inst['R'] = np.random.randint(800, 1001, (inst['M'], inst['F'] )).tolist() inst['C'] = np.random.randint(80, 101, (inst['L'], inst['F'] )).tolist() inst['p'] = np.random.randint(10, 101, (inst['P'], inst['L'], inst['F'])).tolist() inst['t'] = np.random.randint(10, 21, (inst['P'], inst['F'], inst['J'])).tolist() return inst if __name__ == "__main__": if len(argv) < 2: print("Please provide the amount of clients for the instance!") exit() cli = int(argv[1]) inst = generate_instance(cli) #Writing instance in a json file filename = 'inst_' + str(cli) + '.json' filename = join('instances', filename) with open(filename, 'w') as f: dump(inst, f) <file_sep>/Project8/src/problems/qbfpt/solvers/TS_QBFPT.java package problems.qbfpt.solvers; import java.io.FileWriter; import java.io.IOException; import java.util.*; import metaheuristics.tabusearch.Intensificator; import problems.qbf.solvers.TS_QBF; import problems.qbfpt.QBFPT_TS; import solutions.Solution; /** * Metaheuristic Tabu Search for obtaining an optimal solution to a QBFPT * (Quadractive Binary Function with Prohibited Triples). * * @author einnarelli, jmenezes, vferrari */ public class TS_QBFPT extends TS_QBF { private enum SearchStrategy { FI, BI } private final Integer fake = -1; /** * Step of iterations on which the penalty will be dynamically adjusted. */ private final Integer penaltyAdjustmentStep = 25; /** * The set T of prohibited triples. */ private final Set<List<Integer>> T; /** * Value to represent local search type. * Can be first-improving (FI) or best-improving (BI). */ private final SearchStrategy searchType; /** * Variable that indicates if strategic oscillation is active. */ private final boolean oscillation; /** * Constructor for the TS_QBFPT class. * * @param iterations * The number of iterations which the TS will be executed. * @param filename * Name of the file for which the objective function parameters * should be read. * @param type * Local search strategy type, being either first improving or * best improving. * @param intensificator * Intensificator parameters. If {@code null}, intensification is not * applied. * @param oscillation * Indicates if strategic oscillation is active or not. * @param seed * Seed to initialize random number generator. * @throws IOException * Necessary for I/O operations. */ public TS_QBFPT( Integer tenure, Integer iterations, String filename, SearchStrategy type, Intensificator intensificator, boolean oscillation, Integer seed ) throws IOException { super(tenure, iterations, filename, intensificator, seed); // Instantiate QBFPT problem, store T and update objective reference. QBFPT_TS qbfpt = new QBFPT_TS(filename); T = qbfpt.getT(); ObjFunction = qbfpt; searchType = type; this.oscillation = oscillation; } /* * (non-Javadoc) * * @see tabusearch.abstracts.AbstractTS#updateCL() */ @Override public void updateCL() { // Adjust the oscillation penalty based on the number of infeasible solutions found // in the previous penaltyAdjustmentStep iterations if (iterationsCount!=null && (iterationsCount+1) % penaltyAdjustmentStep == 0) { double penalty = ((QBFPT_TS)ObjFunction).getPenalty(); if(iterationsCount - lastFeasibleIteration >= penaltyAdjustmentStep-1) ((QBFPT_TS)ObjFunction).setPenalty(Math.min(penalty*2, 1000000.0)); else if((iterationsCount+1)%200 == 0) ((QBFPT_TS)ObjFunction).setPenalty(Math.max(penalty/2, 0.0000001)); } // Store numbers in solution and _CL as hash sets. Set<Integer> sol = new HashSet<Integer>(currentSol); Set<Integer> _CL = new HashSet<Integer>(); Integer _violator[] = new Integer[ObjFunction.getDomainSize()]; // Initialize _CL with all elements not in solution. for (Integer e = 0; e < ObjFunction.getDomainSize(); e++) { _violator[e]=0; if (!sol.contains(e)) { _CL.add(e); } } Integer e1, e2, e3; Integer infeasible; for (List<Integer> t : T) { infeasible = -1; /** * Detach elements from (e1, e2, e3). They are stored as numbers * from [0, n-1] in sol. and CL, different than in T ([1, n]). */ e1 = t.get(0) - 1; e2 = t.get(1) - 1; e3 = t.get(2) - 1; // e1 and e2 in solution -> e3 infeasible. if (sol.contains(e1) && sol.contains(e2)) { infeasible = e3; } // e1 and e3 in solution -> e2 infeasible. else if (sol.contains(e1) && sol.contains(e3)) { infeasible = e2; } // e2 and e3 in solution -> e1 infeasible. else if (sol.contains(e2) && sol.contains(e3)) { infeasible = e1; } if(infeasible > -1) { if(oscillation) _violator[infeasible]+=1; else _CL.remove(infeasible); } } CL = new ArrayList<Integer>(_CL); ((QBFPT_TS)ObjFunction).setViolations(_violator); } /** * {@inheritDoc} */ @Override public Solution<Integer> neighborhoodMove() { Solution<Integer> sol; // Check local search method. if (this.searchType == SearchStrategy.BI) sol = super.neighborhoodMove(); else sol = firstImprovingNM(); return sol; } /* * First improving neighborhood move. */ private Solution<Integer> firstImprovingNM(){ // Cost Variables Double minDeltaCost, minCost; Double inCost, outCost, exCost; // Cand variables. Integer firstCandIn = null, firstCandOut = null; Integer firstCandExIn = null, firstCandExOut = null; // Auxiliary variables. Double deltaCost; Boolean ignoreCand; Boolean done = false; // Initializing. minDeltaCost = 0.0; inCost = outCost = exCost = Double.POSITIVE_INFINITY; updateCL(); // Evaluate insertions for (Integer candIn : CL) { deltaCost = ObjFunction.evaluateInsertionCost(candIn, currentSol); ignoreCand = TL.contains(candIn) || fixed.contains(candIn); if (!ignoreCand || currentSol.cost+deltaCost < incumbentSol.cost) { if (deltaCost < minDeltaCost) { inCost = deltaCost; firstCandIn = candIn; break; } } } // Evaluate removals for (Integer candOut : currentSol) { deltaCost = ObjFunction.evaluateRemovalCost(candOut, currentSol); ignoreCand = TL.contains(candOut) || fixed.contains(candOut); if (!ignoreCand || currentSol.cost+deltaCost < incumbentSol.cost) { if (deltaCost < minDeltaCost) { outCost = deltaCost; firstCandOut = candOut; break; } } } // Evaluate exchanges for (Integer candIn : CL) { for (Integer candOut : currentSol) { deltaCost = ObjFunction.evaluateExchangeCost(candIn, candOut, currentSol); ignoreCand = TL.contains(candIn) || TL.contains(candOut) || fixed.contains(candIn) || fixed.contains(candOut); if (!ignoreCand || currentSol.cost+deltaCost < incumbentSol.cost) { if (deltaCost < minDeltaCost) { exCost = deltaCost; firstCandExIn = candIn; firstCandExOut = candOut; done = true; break; } } } if (done) break; } // Implement the best of the first non-tabu moves. TL.poll(); minCost = Math.min(Math.min(inCost, outCost), exCost); // In case of tie, insertion is prioritized. if(minCost == inCost && firstCandIn != null) { firstCandOut = null; } // Removal. else if (minCost == outCost && firstCandOut != null) { firstCandIn = null; } // Exchange else if (firstCandExIn != null) { firstCandIn = firstCandExIn; firstCandOut = firstCandExOut; } // Make the move. if (firstCandOut != null) { currentSol.remove(firstCandOut); CL.add(firstCandOut); TL.add(firstCandOut); } else { TL.add(fake); } TL.poll(); if (firstCandIn != null) { currentSol.add(firstCandIn); CL.remove(firstCandIn); TL.add(firstCandIn); } else { TL.add(fake); } ObjFunction.evaluate(currentSol); return null; } /** * {@inheritDoc} * * Check if any triple restriction is violated. */ @Override public boolean isSolutionFeasible(Solution<Integer> sol) { boolean feasible = true; Integer e1, e2, e3; // Check strategic oscillation. if(!oscillation) return true; for (List<Integer> t : T) { /** * Detach elements from (e1, e2, e3). They are stored as numbers * from [0, n-1] in sol., different than in T ([1, n]). */ e1 = t.get(0) - 1; e2 = t.get(1) - 1; e3 = t.get(2) - 1; // e1, e2 and e3 in solution -> infeasible. if (sol.contains(e1) && sol.contains(e2) && sol.contains(e3)) { feasible = false; break; } } return feasible; } /** * Run Tabu Search for QBFPT. */ public static void run(Integer tenure, Integer maxIt, String filename, SearchStrategy searchType, Intensificator intensify, Boolean oscillation, Double maxTime, Integer refCost, Integer smallCost, Integer seed, FileWriter fileWriter) throws IOException { TS_QBFPT tabu = new TS_QBFPT(tenure, maxIt, "instances/qbf" + filename, searchType, intensify, oscillation, seed ); Map<String, Object> log = tabu.solve(maxTime, refCost, smallCost); if (fileWriter != null) { fileWriter.append("qbf" + filename + ";" + log.get("objectiveFunction") + ";" + log.get("targetTime") + ";" + log.get("totalTime") + "\n"); } } public static void testAll(Integer tenure, Integer maxIt, SearchStrategy searchType, Intensificator intensify, Boolean oscillation, Double maxTime, Integer refCost, Integer smallCost, Integer seed) throws IOException { String inst[] = {"020", "040", "060", "080", "100", "200", "400"}; Intensificator intensify2 = intensify; // create a text file FileWriter fileWriter = new FileWriter("results/TS_QBFPT_PP.txt"); for(String file : inst) { if(file == "200" && intensify != null) { intensify2 = new Intensificator(2000, 100); } else { intensify2 = intensify; } TS_QBFPT.run(tenure, maxIt, file, searchType, intensify2, oscillation, maxTime, refCost, smallCost, seed, fileWriter); } fileWriter.close(); } /** * A main method used for testing the Tabu Search metaheuristic. */ public static void main(String[] args) throws IOException { Integer nTimes = 100; final Random seeds = new Random(1327); // Fixed Parameters Integer tenure = 30; Integer maxRefCost = Integer.MIN_VALUE; Integer refCost100 = -1263, smallCost100 = -1000; // Changeable Parameters Integer maxIterations1 = 10000, maxIterations2 = 5000; Intensificator intensificator = new Intensificator(1000, 100); Double maxTime1 = 1800.0, maxTime2 = 600.0; Integer seed0 = 0; // Testing // TS_QBFPT.run(tenure, maxIterations, "020", SearchStrategy.BI, // intensificator, true, maxTime1, maxRefCost, maxRefCost, // seed0, null); // Performance Profile TS_QBFPT.testAll(tenure, maxIterations1, SearchStrategy.BI, intensificator, true, maxTime1, maxRefCost, maxRefCost, seed0); // TTT Plots FileWriter fileWriter = new FileWriter("results/TS_QBFPT_TTT.txt"); for (int i = 0; i < nTimes; i++) { TS_QBFPT.run(tenure, maxIterations2, "100", SearchStrategy.BI, intensificator, true, maxTime2, refCost100, smallCost100, seeds.nextInt(), fileWriter); } fileWriter.close(); } } <file_sep>/README.md MC859/MO824 - Operational Research ================================== Repo with every project from the MO824 course, consisting of Operational Research problems solved using optimization techniques such as Linear or Integer Programming, metaheuristics and matheuristics. Every report is in Portuguese, and some projects are entirely in Portuguese, such as the Final Project. ## Projects **Project 1**: Integer and Continuous Programming models for the paper production problem, and implementation using the Gurobi solver with its Python API. Also has an instance generator. Grade: 9/10. **Project 2**: Integer Programming models for the TSP and 2-TSP problems, along with an instance generator. Using the Gurobi solver with its Python API. Grade: 10/10. **Project 3**: Lagrangian Relaxation framework with 2-TSP solution. Grade: 10/10. **Project 4**: GRASP metaheuristic for the MAX-QBFPT problem. Grade: 10/10. **Project 5**: Tabu Search metaheuristic for the MAX-QBFPT problem. Grade: 10/10. **Project 6**: Genetic Algorithm metaheuristic for the MAX-QBFPT problem. Grade: 10/10. **Project 7**: Not available, revise other final project proposals. Grade: 10/10. **Project 8**: TTT-Plot and Performance Profile evaluations of solutions for the MAX-QBFPT problem. Grade: 10/10. **Project 9**: GRASP metaheuristic for the Professor Allocation Problem. Grade: 10/10. **Final Project**: GRASP-based matheuristic for the Firefighter Problem. More information inside the module. Grade: 10/10. Course given by professor [<NAME>](https://www.ic.unicamp.br/~fusberti/) in the second semester of 2020. [Instituto de Computação](http://ic.unicamp.br/) - [UNICAMP](http://www.unicamp.br/unicamp/) (Universidade Estadual de Campinas) <file_sep>/Project8/src/metaheuristics/tabusearch/AbstractTS.java package metaheuristics.tabusearch; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.*; import problems.Evaluator; import solutions.Solution; /** * Abstract class for metaheuristic Tabu Search. It consider a minimization problem. * * @author ccavellucci, fusberti, einnarelli, jmenezes, vferrari * @param <E> * Generic type of the candidate to enter the solution. */ public abstract class AbstractTS<E> { /** * flag that indicates whether the code should print more information on * screen. */ public static boolean verbose = false; /** * a random number generator. */ public final Random rng; /** * the objective function being optimized. */ protected Evaluator<E> ObjFunction; /** * the incumbent solution cost. */ protected Double incumbentCost; /** * the current solution cost. */ protected Double currentCost; /** * the incumbent solution. */ protected Solution<E> incumbentSol; /** * the current solution. */ protected Solution<E> currentSol; /** * the number of iterations the TS main loop executes. */ protected Integer iterations; /** * current iteration. */ protected Integer iterationsCount; /** * iteration where the last feasible solution was found. */ protected Integer lastFeasibleIteration; /** * the tabu tenure. */ protected Integer tenure; /** * the Candidate List of elements to enter the solution. */ protected ArrayList<E> CL; /** * the Restricted Candidate List of elements to enter the solution. */ protected ArrayList<E> RCL; /** * the Tabu List of elements to enter the solution. */ protected ArrayDeque<E> TL; /** * the consecutive number of times the solution did not improve. */ protected Integer consecFailures; /** * array that informs how long a component has been used. */ protected Integer[] recency; /** * intensification parameters. */ protected Intensificator intensificator; /** * path to store the history file. */ protected String resultsFileName; /** * Creates the Candidate List, which is an ArrayList of candidate elements * that can enter a solution. * * @return The Candidate List. */ public abstract ArrayList<E> makeCL(); /** * Creates the Restricted Candidate List, which is an ArrayList of the best * candidate elements that can enter a solution. * * @return The Restricted Candidate List. */ public abstract ArrayList<E> makeRCL(); /** * Creates the Tabu List, which is an ArrayDeque of the Tabu * candidate elements. The number of iterations a candidate * is considered tabu is given by the Tabu Tenure {@link #tenure} * * @return The Tabu List. */ public abstract ArrayDeque<E> makeTL(); /** * Updates the Candidate List according to the incumbent solution * {@link #currentSol}. In other words, this method is responsible for * updating the costs of the candidate solution elements. */ public abstract void updateCL(); /** * Creates a new solution which is empty, i.e., does not contain any * candidate solution element. * * @return An empty solution. */ public abstract Solution<E> createEmptySol(); /** * The TS local search phase is responsible for repeatedly applying a * neighborhood operation while the solution is getting improved, i.e., * until a local optimum is attained. When a local optimum is attained * the search continues by exploring moves which can make the current * solution worse. Cycling is prevented by not allowing forbidden * (tabu) moves that would otherwise backtrack to a previous solution. * * @return An local optimum solution. */ public abstract Solution<E> neighborhoodMove(); /** * Updates the {@link #recency} array. */ public abstract void updateRecency(); /** * Initialize the intensification method. In this method, the search * should restart in the incumbent solution with some components fixed, * such as the ones that most appeared in solutions recently ({@link * #recency}). */ public abstract void startIntensification(); /** * Stop the intensification method, i.e., revert the components fix * applied in the method initialization. */ public abstract void endIntensification(); /** * Constructor for the AbstractTS class. * * @param objFunction * The objective function being minimized. * @param tenure * The Tabu tenure parameter. * @param iterations * The number of iterations which the TS will be executed. * @param intensificator * Intensificator parameters. If {@code null}, intensification is not * applied. */ public AbstractTS( Evaluator<E> objFunction, Integer tenure, Integer iterations, Intensificator intensificator, Integer seed ){ this.ObjFunction = objFunction; this.tenure = tenure; this.iterations = iterations; this.intensificator = intensificator; rng = new Random(seed); } /** * The TS constructive heuristic, which is responsible for building a * feasible solution by selecting in a greedy fashion, candidate * elements to enter the solution. * * @return A feasible solution to the problem being minimized. */ public Solution<E> constructiveHeuristic() { CL = makeCL(); RCL = makeRCL(); currentSol = createEmptySol(); currentCost = Double.POSITIVE_INFINITY; /* Main loop, which repeats until the stopping criteria is reached. */ while (!constructiveStopCriteria()) { Double maxCost = Double.NEGATIVE_INFINITY, minCost = Double.POSITIVE_INFINITY; currentCost = currentSol.cost; updateCL(); /* * Explore all candidate elements to enter the solution, saving the * highest and lowest cost variation achieved by the candidates. */ for (E c : CL) { Double deltaCost = ObjFunction.evaluateInsertionCost(c, currentSol); if (deltaCost < minCost) minCost = deltaCost; if (deltaCost > maxCost) maxCost = deltaCost; } /* * Among all candidates, insert into the RCL those with the highest * performance. */ for (E c : CL) { Double deltaCost = ObjFunction.evaluateInsertionCost(c, currentSol); if (deltaCost <= minCost) { RCL.add(c); } } /* Choose a candidate randomly from the RCL */ int rndIndex = rng.nextInt(RCL.size()); E inCand = RCL.get(rndIndex); CL.remove(inCand); currentSol.add(inCand); ObjFunction.evaluate(currentSol); RCL.clear(); } return currentSol; } /** * The TS mainframe. It consists of a constructive heuristic followed by * a loop, in which each iteration a neighborhood move is performed on * the current solution. The best solution is returned as result. * * @return The best feasible solution obtained throughout all iterations. */ public Map<String, Object> solve(Double maxTime, Integer refCost, Integer smallCost) { boolean isFeasible; boolean pastSmall = false; long startTime = System.currentTimeMillis(); double totalTime = 0.0; double targetTime = 0.0; Map<String, Object> log = new HashMap<>(); incumbentSol = createEmptySol(); TL = makeTL(); consecFailures = Integer.valueOf(0); // Only make recency array if intensification is enabled if (intensificator != null) { makeRecency(); } // Build a initial solution constructiveHeuristic(); lastFeasibleIteration = 0; for (iterationsCount = 0; iterationsCount < iterations && totalTime < maxTime; iterationsCount++) { /* Start intensification if it's enabled, not running and the * number of consecutive failures reached the intensificator * tolerance. */ if ( intensificator != null && !intensificator.getRunning() && consecFailures >= intensificator.getTolerance() ) { consecFailures = 0; // Reset failures startIntensification(); if (verbose) System.out.println("Intensification started at: " + iterationsCount); } // Perform local search neighborhoodMove(); // Update incumbent if a better solution was found isFeasible = isSolutionFeasible(currentSol); if(isFeasible) this.lastFeasibleIteration = iterationsCount; if (incumbentSol.cost > currentSol.cost && isFeasible) { consecFailures = 0; // Reset failures incumbentSol = new Solution<E>(currentSol); if (verbose) printSolutionMeasure((System.currentTimeMillis() - startTime)/(double)1000); // Reference cost check if(incumbentSol.cost > smallCost && !pastSmall) { targetTime = (double) (System.currentTimeMillis() - startTime) / (double) 1000; pastSmall = true; } if (refCost > incumbentSol.cost) break; } // Register consecutive failure otherwise else { consecFailures++; } if (intensificator != null) { // Only update recency array if intensification is enabled updateRecency(); if (intensificator.getRunning()) { // Stop intensification if there are no iterations left if (intensificator.getRemainingIt() == 0) { endIntensification(); if (verbose) System.out.println("Intensification ended at: " + iterationsCount); } // Decrement remaining intensification iterations otherwise else { intensificator.setRemainingIt( intensificator.getRemainingIt() - 1 ); } // end if intensificator iteration } // end if intensificator running } // end if intensificator not null // Current time. totalTime = (double) (System.currentTimeMillis() - startTime) / (double) 1000; } log.put("objectiveFunction", incumbentSol.cost); log.put("targetTime", targetTime); log.put("totalTime", totalTime); return log; } /** * Initialize the recency array with zeros. */ public void makeRecency() { recency = new Integer[ObjFunction.getDomainSize()]; Arrays.fill(recency, 0); } /** * A standard stopping criteria for the constructive heuristic is to repeat * until the incumbent solution improves by inserting a new candidate * element. * * @return true if the criteria is met. */ public Boolean constructiveStopCriteria() { return (currentCost > currentSol.cost) ? false : true; } /** * Check if solution is feasible. * @param sol Current solution to check. * @return true if feasible, false otherwise. */ public boolean isSolutionFeasible(Solution<E> sol) { return true; } /** * Prints the measures of the new incumbent solution * @param totalTime Time ellapsed */ private void printSolutionMeasure(double totalTime) { if (verbose) System.out.println("(Iter. " + iterationsCount + ", Time " + totalTime + ") BestSol = " + incumbentSol); if(resultsFileName != null){ try { printSolutionMeasuresToFile(totalTime); } catch (IOException e) { e.printStackTrace(); System.exit(0); } } } /** * Saves the measures of the new incumbent solution to file * @param totalTime Time ellapsed * @throws IOException */ private void printSolutionMeasuresToFile(double totalTime) throws IOException { FileWriter file; File fp = new File(resultsFileName); if(!fp.exists()){ file = new FileWriter(resultsFileName); String header = "instance;solutionCost;iterations;time;solutionSize\n"; file.write(header); } else { file = new FileWriter(resultsFileName, true); } String result = String.format("%s;%s;%s;%s;%s\n", ObjFunction.getDomainSize(), -1.00*incumbentSol.cost, iterationsCount, totalTime, incumbentSol.size() ); file.write(result); file.close(); } } <file_sep>/Project8/src/problems/qbfpt/solvers/GRASP_QBFPT.java package problems.qbfpt.solvers; import problems.qbf.solvers.GRASP_QBF; import problems.qbfpt.triples.ForbiddenTriplesGenerator; import solutions.Solution; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; public class GRASP_QBFPT extends GRASP_QBF { private final ForbiddenTriplesGenerator forbiddenTriplesGenerator; private final Map<Integer, Integer> frequency = new HashMap<>(); public GRASP_QBFPT(Double alpha, Integer iterations, String filename, Integer seed) throws IOException { super(alpha, iterations, filename, seed); forbiddenTriplesGenerator = new ForbiddenTriplesGenerator(ObjFunction.getDomainSize()); } @Override public void updateCL() { if (!this.currentSol.isEmpty()) { List<Integer> forbiddenValues = new ArrayList<>(); Integer lastElement = this.currentSol.get(this.currentSol.size() - 1); for (int i = 0; i < this.currentSol.size() - 1; i++) { forbiddenValues.addAll(forbiddenTriplesGenerator.getForbiddenValues(this.currentSol.get(i) + 1, lastElement + 1)); } for (Integer forbiddenValue : forbiddenValues) { int index = CL.indexOf(forbiddenValue - 1); if (index >= 0) { CL.remove(index); } } } } private Integer getFrequency(Integer elem) { Integer freq = frequency.get(elem); if (freq == null) { return Integer.MIN_VALUE; } return freq; } private Integer putIncrease(Integer elem) { Integer value = frequency.get(elem); if (value == null) { frequency.put(elem, 1); return 1; } value = value + 1; frequency.put(elem, value); return value; } private Double perturbationFunction(Integer elem) { Double f = ObjFunction.evaluateInsertionCost(elem, currentSol); return f / (Integer.MAX_VALUE * getFrequency(elem)); } private void updateFrequency() { currentSol.stream().forEach(elem -> putIncrease(elem)); } @Override public Solution<Integer> localSearch() { Solution<Integer> sol = super.localSearch(); updateFrequency(); return sol; } @Override public Solution<Integer> constructiveHeuristic() { CL = makeCL(); RCL = makeRCL(); currentSol = createEmptySol(); currentCost = Double.POSITIVE_INFINITY; while (!constructiveStopCriteria()) { Double maxCost = Double.NEGATIVE_INFINITY, minCost = Double.POSITIVE_INFINITY; currentCost = ObjFunction.evaluate(currentSol); updateCL(); for (Integer c : CL) { Double deltaCost = ObjFunction.evaluateInsertionCost(c, currentSol); if (deltaCost < minCost) { minCost = deltaCost; } if (deltaCost > maxCost) { maxCost = deltaCost; } } for (Integer c : CL) { Double deltaCost = ObjFunction.evaluateInsertionCost(c, currentSol); if (deltaCost <= minCost + alpha * (maxCost - minCost)) { RCL.add(c); } } Double minPertubationCost = Double.MAX_VALUE; Integer candidate = null; for (Integer value : RCL) { Double functionPertubationValue = perturbationFunction(value); if (minPertubationCost > functionPertubationValue) { minPertubationCost = functionPertubationValue; candidate = value; } } if (candidate != null) { CL.remove(candidate); currentSol.add(candidate); } ObjFunction.evaluate(currentSol); RCL.clear(); } return currentSol; } /** * Run GRASP for QBFPT */ public static void run(Double alpha, Integer maxIterations, String filename, Double maxTime, Integer refCost, Integer smallCost, Integer seed, FileWriter fileWriter) throws IOException { GRASP_QBFPT grasp = new GRASP_QBFPT(alpha, maxIterations, "instances/qbf"+filename, seed); Map<String, Object> log = grasp.solve(maxTime, refCost, smallCost); if (fileWriter != null) { fileWriter.append("qbf" + filename + ";" + log.get("objectiveFunction") + ";" + log.get("targetTime") + ";" + log.get("totalTime") + "\n"); } } public static void testAll(Double alpha, Integer maxIt, Double maxTime, Integer refCost, Integer smallCost, Integer seed) throws IOException { String instances[] = {"020", "040", "060", "080", "100", "200", "400"}; // create a text file FileWriter fileWriter = new FileWriter("results/GRASP_QBFPT_PP.txt"); for(String instance : instances) { GRASP_QBFPT.run(alpha, maxIt, instance, maxTime, refCost, smallCost, seed, fileWriter); } fileWriter.close(); } public static void main(String[] args) throws IOException { Integer nTimes = 100; final Random seeds = new Random(1327); // Fixed Parameters Double alpha = 0.40; Integer maxRefCost = Integer.MIN_VALUE; Integer refCost100 = -1263, smallCost100 = -1000; // Changeable Parameters Integer maxIt1 = 10000, maxIt2 = 5000; Double maxTime1 = 1800.0, maxTime2 = 600.0; Integer seed0 = 0; // Testing // GRASP_QBFPT.run(alpha, maxIt1, "020", maxTime1, maxRefCost, maxRefCost, seed0, null); // Performance Profiles GRASP_QBFPT.testAll(alpha, maxIt1, maxTime1, maxRefCost, maxRefCost, seed0); // TTT Plots FileWriter fileWriter = new FileWriter("results/GRASP_QBFPT_TTT.txt"); for (int i = 0; i < nTimes; i++) { GRASP_QBFPT.run(alpha, maxIt2, "100", maxTime2, refCost100, smallCost100, seeds.nextInt(), fileWriter); } fileWriter.close(); } } <file_sep>/Project8/src/problems/qbf/solvers/TS_QBF.java package problems.qbf.solvers; import java.io.IOException; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.TreeMap; import java.util.Map; import java.util.NavigableMap; import metaheuristics.tabusearch.AbstractTS; import metaheuristics.tabusearch.Intensificator; import problems.qbf.QBF_Inverse_TS; import solutions.Solution; /** * Metaheuristic TS (Tabu Search) for obtaining an optimal solution to a QBF * (Quadractive Binary Function). Since by default this TS considers minimization * problems, an inverse QBF function is adopted. * * @author ccavellucci, fusberti, einnarelli, jmenezes, vferrari */ public class TS_QBF extends AbstractTS<Integer> { private final Integer fake = -1; /** * Set of fixed variables, always empty if intensification is disabled. */ protected Set<Integer> fixed; /** * Constructor for the TS_QBF class. An inverse QBF objective function is * passed as argument for the superclass constructor. * * @param tenure * The Tabu tenure parameter. * @param iterations * The number of iterations which the TS will be executed. * @param filename * Name of the file for which the objective function parameters * should be read. * @param intensificator * Intensificator parameters. If {@code null}, intensification is not * applied. * @param seed * Seed to initialize random number generator. * @throws IOException * Necessary for I/O operations. */ public TS_QBF( Integer tenure, Integer iterations, String filename, Intensificator intensificator, Integer seed ) throws IOException { super(new QBF_Inverse_TS(filename), tenure, iterations, intensificator, seed); fixed = new HashSet<Integer>(); } /* (non-Javadoc) * @see metaheuristics.tabusearch.AbstractTS#makeCL() */ @Override public ArrayList<Integer> makeCL() { ArrayList<Integer> _CL = new ArrayList<Integer>(); for (int i = 0; i < ObjFunction.getDomainSize(); i++) { Integer cand = i; _CL.add(cand); } return _CL; } /* (non-Javadoc) * @see metaheuristics.tabusearch.AbstractTS#makeRCL() */ @Override public ArrayList<Integer> makeRCL() { ArrayList<Integer> _RCL = new ArrayList<Integer>(); return _RCL; } /* (non-Javadoc) * @see metaheuristics.tabusearch.AbstractTS#makeTL() */ @Override public ArrayDeque<Integer> makeTL() { ArrayDeque<Integer> _TS = new ArrayDeque<Integer>(2*tenure); for (int i=0; i<2*tenure; i++) { _TS.add(fake); } return _TS; } /* (non-Javadoc) * @see metaheuristics.tabusearch.AbstractTS#updateCL() */ @Override public void updateCL() { // do nothing } /** * {@inheritDoc} * * This createEmptySol instantiates an empty solution and it attributes a * zero cost, since it is known that a QBF solution with all variables set * to zero has also zero cost. */ @Override public Solution<Integer> createEmptySol() { Solution<Integer> sol = new Solution<Integer>(); sol.cost = 0.0; return sol; } /** * {@inheritDoc} * * The local search operator developed for the QBF objective function is * composed by the neighborhood moves Insertion, Removal and 2-Exchange. */ @Override public Solution<Integer> neighborhoodMove() { Double minDeltaCost; Integer bestCandIn = null, bestCandOut = null; minDeltaCost = Double.POSITIVE_INFINITY; updateCL(); // Evaluate insertions for (Integer candIn : CL) { Double deltaCost = ObjFunction.evaluateInsertionCost(candIn, currentSol); Boolean ignoreCand = TL.contains(candIn) || fixed.contains(candIn); if (!ignoreCand || currentSol.cost+deltaCost < incumbentSol.cost) { if (deltaCost < minDeltaCost) { minDeltaCost = deltaCost; bestCandIn = candIn; bestCandOut = null; } } } // Evaluate removals for (Integer candOut : currentSol) { Double deltaCost = ObjFunction.evaluateRemovalCost(candOut, currentSol); Boolean ignoreCand = TL.contains(candOut) || fixed.contains(candOut); if (!ignoreCand || currentSol.cost+deltaCost < incumbentSol.cost) { if (deltaCost < minDeltaCost) { minDeltaCost = deltaCost; bestCandIn = null; bestCandOut = candOut; } } } // Evaluate exchanges for (Integer candIn : CL) { for (Integer candOut : currentSol) { Double deltaCost = ObjFunction.evaluateExchangeCost(candIn, candOut, currentSol); Boolean ignoreCands = TL.contains(candIn) || TL.contains(candOut) || fixed.contains(candIn) || fixed.contains(candOut); if (!ignoreCands || currentSol.cost+deltaCost < incumbentSol.cost) { if (deltaCost < minDeltaCost) { minDeltaCost = deltaCost; bestCandIn = candIn; bestCandOut = candOut; } } } } // Implement the best non-tabu move TL.poll(); if (bestCandOut != null) { currentSol.remove(bestCandOut); CL.add(bestCandOut); TL.add(bestCandOut); } else { TL.add(fake); } TL.poll(); if (bestCandIn != null) { currentSol.add(bestCandIn); CL.remove(bestCandIn); TL.add(bestCandIn); } else { TL.add(fake); } ObjFunction.evaluate(currentSol); return null; } /** * {@inheritDoc} */ @Override public void updateRecency() { // Cast obj. to problem to get the variables QBF_Inverse_TS qbf = (QBF_Inverse_TS) ObjFunction; qbf.setVariables(currentSol); for (int e = 0; e < ObjFunction.getDomainSize(); e++) { // Increment field if element is in solution and reset it if not if (qbf.variables[e] == 1.0) { recency[e]++; } else { recency[e] = 0; } } } /** * {@inheritDoc} */ @Override public void startIntensification() { NavigableMap<Integer, Integer> recencyMap = new TreeMap<Integer, Integer>(); // Initialize intensificator attributes intensificator.setRunning(true); intensificator.setRemainingIt(intensificator.getIterations()); // Search will restart at incumbentSol currentSol = new Solution<Integer>(incumbentSol); // Cast obj. to problem to get the variables QBF_Inverse_TS qbf = (QBF_Inverse_TS) ObjFunction; qbf.setVariables(currentSol); // Create recency {recency[e], e} tree map in recency ascending order for (int e = 0; e < ObjFunction.getDomainSize(); e++) { /* Only add element to map if it was used recently and if it is in * incumbent solution */ if (recency[e] > 0 && qbf.variables[e] == 1.0) { recencyMap.put(recency[e], e); } } // Reverse order recencyMap = recencyMap.descendingMap(); // Iterate over map entries, now stored in descending order for (Map.Entry<Integer, Integer> kv : recencyMap.entrySet()) { // Fix element fixed.add(kv.getValue()); // Fix at most n / 2 elements if (fixed.size() == ObjFunction.getDomainSize() / 2) { break; } } // Reset recency array to avoid repetition in future intensifications Arrays.fill(recency, 0); } /** * {@inheritDoc} */ @Override public void endIntensification() { intensificator.setRunning(false); fixed.clear(); } /** * A main method used for testing the TS metaheuristic. */ public static void main(String[] args) throws IOException { TS_QBF tabusearch = new TS_QBF(20, 10000, "instances/qbf020", null, 0); Map<String, Object> log = tabusearch.solve(1800.0, Integer.MIN_VALUE, Integer.MIN_VALUE); } } <file_sep>/Project8/src/problems/qbfpt/solvers/GA_QBFPT.java package problems.qbfpt.solvers; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.*; import problems.qbf.solvers.GA_QBF; import problems.qbfpt.QBFPT_GA; import solutions.Solution; /** * Metaheuristic GA (Genetic Algorithm) for obtaining an optimal solution * to a QBFPT (Quadractive Binary Function with Prohibited Triples). * * @author rsaraiva, sipamplona, vferrari */ public class GA_QBFPT extends GA_QBF { /** * The set T of prohibited triples. */ private final ArrayList<List<Integer[]>> T; /** * Constructor for the GA_QBF class. The QBF objective function is passed as * argument for the superclass constructor. * * @param generations * Maximum number of generations. * @param popSize * Size of the population. * @param mutationRate * The mutation rate. * @param filename * Name of the file for which the objective function parameters * should be read. * @param seed * Seed to initialize random number generator. * @throws IOException * Necessary for I/O operations. */ public GA_QBFPT(Integer generations, Integer popSize, Double mutationRate, String filename, populationReplacement popMethod, Boolean divMaintenance, Integer seed) throws IOException { super(generations, popSize, mutationRate, filename, popMethod, divMaintenance, seed); // Instantiate QBFPT problem, store T and update objective reference. QBFPT_GA qbfpt = new QBFPT_GA(filename); T = qbfpt.getT(); ObjFunction = qbfpt; } /** * Viabilizes chromosomes for QBFPT. * Checks if a triple is being violated, and removes random element from said triple. * @param ind Individual to be viabilized for QBFPT. * @return viable individual. */ private Chromosome viabilize(Chromosome ind) { Integer e, i; for (i = 0; i < chromosomeSize; i++) { // If the gene is not active, ignore. if(ind.get(i) == 0) continue; // Check triples for (Integer[] t : T.get(i)) { // If the triple is active (infeasible), set random element as 0. if (ind.get(t[0]) == 1 && ind.get(t[1]) == 1 && ind.get(t[2]) == 1) { e = rng.nextInt(3); ind.set(t[e], 0); } } } return ind; } /* * (non-Javadoc) * * @see metaheuristics.ga.AbstractGA#generateRandomChromosome() */ @Override protected Chromosome generateRandomChromosome() { Chromosome chromosome = new Chromosome(); // Generate for (int i = 0; i < chromosomeSize; i++) { chromosome.add(rng.nextInt(2)); } // Viabilize and return return viabilize(chromosome); } /** * {@inheritDoc} * * Adds penalty if solution is infeasible. */ @Override protected Double fitness(Chromosome chromosome) { Solution<Integer> sol = decode(chromosome); return sol.cost; //- (isSolutionFeasible(sol) ? 0 : 1000000); } /** * Check if any triple restriction is violated. */ private boolean isSolutionFeasible(Solution<Integer> sol) { boolean feasible = true; Set<Integer> _sol = new HashSet<Integer>(sol); for (Integer e : sol) { for(Integer[] t : T.get(e)) { if(_sol.contains(t[1]) && _sol.contains(t[2])) { feasible = false; break; } } if(!feasible) break; } return feasible; } /** * {@inheritDoc} * * Viabilizes infeasible solutions. */ protected Population selectPopulation(Population original, Population offsprings) { // Viabilize for(int i=0; i<offsprings.size(); i++) offsprings.set(i, viabilize(offsprings.get(i))); // Select pop. if(this.popMethod == populationReplacement.ELITE) return elitism(offsprings); else if(this.popMethod == populationReplacement.STSTATE) return steadyState(original, offsprings); return offsprings; } /** * Run GA for QBFPT */ public static void run(Integer generations, Integer popSize, Double mutationRateInd, String filename, populationReplacement popMethod, Boolean divMaintenance, Double maxTime, Integer refCost, Integer smallCost, Integer seed, FileWriter fileWriter) throws IOException { Double mutationRate; Integer size; // Mutation rate. if(mutationRateInd < 0.0) { size = Integer.parseInt(filename); mutationRate = 1.0 / (float)size; } else { mutationRate = mutationRateInd; } long startTime = System.currentTimeMillis(); GA_QBFPT ga = new GA_QBFPT(generations, popSize, mutationRate, "instances/qbf" + filename, popMethod, divMaintenance, seed); Map<String, Object> log = ga.solve(maxTime, refCost, smallCost); if (fileWriter != null) { fileWriter.append("qbf" + filename + ";" + log.get("objectiveFunction") + ";" + log.get("targetTime") + ";" + log.get("totalTime") + "\n"); } } public static void testAll(Integer generations, Integer popSize, Double mutationRate, populationReplacement popMethod, Boolean divMaintenance, Double maxTime, Integer refCost, Integer smallCost, Integer seed) throws IOException { String inst[] = {"020", "040", "060", "080", "100", "200", "400"}; // create a text file FileWriter fileWriter = new FileWriter("results/GA_QBFPT_PP.txt"); for(String file : inst) { GA_QBFPT.run(generations, popSize, mutationRate, file, popMethod, divMaintenance, maxTime, refCost, smallCost, seed, fileWriter); } fileWriter.close(); } /** * A main method used for testing the GA metaheuristic. */ public static void main(String args[]) throws IOException { Integer nTimes = 100; final Random seeds = new Random(1327); // Fixed parameters Integer popSize = 50; Double mutationRate = -1.0; Integer maxRefCost = Integer.MAX_VALUE; Integer refCost100 = 1263, smallCost100 = 1000; // Changeable parameters. Integer generations1 = 10000, generations2 = 5000; Double maxTime1 = 1800.0, maxTime2 = 600.0; Integer seed0 = 0; // Testing // GA_QBFPT.run(generations, popSize, mutationRate, // "020", populationReplacement.STSTATE, // true, maxTime1, maxRefCost, maxRefCost, seed0); // Performance Profiles GA_QBFPT.testAll(generations1, popSize, mutationRate, populationReplacement.STSTATE, true, maxTime1, maxRefCost, maxRefCost, seed0); // TTT Plots FileWriter fileWriter = new FileWriter("results/GA_QBFPT_TTT.txt"); for(int i = 0; i < nTimes; i++) { GA_QBFPT.run(generations2, popSize, mutationRate, "100", populationReplacement.STSTATE, true, maxTime2, refCost100, smallCost100, seeds.nextInt(), fileWriter); } fileWriter.close(); } } <file_sep>/Project1/solve_paper_problem.py ''' Activity 1 - IP and LP models for paper production and routing problem. solve_paper_problem.py: solves paper production and routing problem, using Gurobi Subject: MC859/MO824 - Operational Research. Authors: <NAME> - RA 186633 <NAME> - RA 187101 <NAME> - RA 187890 University of Campinas - UNICAMP - 2020 Last Modified: 01/10/2020 ''' from gurobipy import * import json import numpy as np from sys import argv, exit def solver(dict_const): factories = range(0,dict_const['F']) machines = range(0,dict_const['L']) raw_material = range(0, dict_const['M']) paper_types = range(0, dict_const['P']) clients = range(0, dict_const['J']) #creating model model = Model("paperproblem") #----------------Please, choose an option----------------# #variables - INTEGER X = model.addVars(paper_types, machines, factories, lb=0, vtype=GRB.INTEGER, name="X") T = model.addVars(paper_types, factories, clients, lb=0, vtype=GRB.INTEGER, name="T") total_cost = model.addVar(lb=0, vtype=GRB.INTEGER,name="total_cost") #variables - CONTINUOUS # X = model.addVars(paper_types, machines, factories, lb=0, vtype=GRB.CONTINUOUS, name="X") # T = model.addVars(paper_types, factories, clients, lb=0, vtype=GRB.CONTINUOUS, name="T") # total_cost = model.addVar(lb=0, vtype=GRB.CONTINUOUS,name="total_cost") #objective function model.setObjective(total_cost,GRB.MINIMIZE) #time limit to execute 30 min model.setParam('TimeLimit',1800) #constraints #main model.addConstr(total_cost >= quicksum(quicksum(quicksum(X.sum(p,l,f) * dict_const['p'][p][l][f] for p in paper_types) for f in factories) for l in machines) + quicksum(quicksum(quicksum(T.sum(p,f,j) * dict_const['t'][p][f][j] for p in paper_types) for f in factories) for j in clients), "MainConstraint") #second for p in paper_types: for j in clients: model.addConstr(quicksum(T.sum(p,f,j) for f in factories) == dict_const['D'][j][p], "TransportDemandConstraint") #third for p in paper_types: for f in factories: model.addConstr(quicksum(T.sum(p,f,j) for j in clients) == quicksum(X.sum(p,l,f) for l in machines), "TransportProductionConstraint") #forth for f in factories: for m in raw_material: model.addConstr(quicksum(quicksum(X.sum(p,l,f) * dict_const['r'][m][p][l] for p in paper_types) for l in machines) <= dict_const['R'][m][f], "RawMaterialAvailability") #fifth for f in factories: for l in machines: model.addConstr(quicksum(X.sum(p,l,f) for p in paper_types) <= dict_const['C'][l][f], "ProductionCapacityConstraint") #Refresh model.update() #Saving model model.write('paperproblem{}clients.lp'.format(dict_const['J'])) #Optimizing model.optimize() #if it has an optimal solution print("==========================================") if model.status == GRB.Status.OPTIMAL: print('\nOptimal Solution:') print('\ntotal_cost: {}'.format(model.objVal)) for p in paper_types: for l in machines: for f in factories: if X[p,l,f].X > 0.0: print('Quantity of type {} produced by machine {} in factory {} : {}'.format(p,l,f,X[p,l,f].X)) for p in paper_types: for f in factories: for j in clients: if T[p,f,j].X > 0.0: print('Quantity of type {} transported by factory {} to client {} : {}'.format(p,f,j,T[p,f,j].X)) print('\nOptimal Solution:') print('\ntotal_cost: {}'.format(model.objVal)) elif model.status == GRB.Status.TIME_LIMIT: print('\nCouldn\'t find an optimal solution. Time limit reached.\n') print('\ntotal_cost: {}'.format(model.objVal)) print('\n') for p in paper_types: for l in machines: for f in factories: if X[p,l,f].X > 0.0: print('Quantity of type {} produced by machine {} in factory {} : {}'.format(p,l,f,X[p,l,f].X)) for p in paper_types: for f in factories: for j in clients: if T[p,f,j].X > 0.0: print('Quantity of type {} transported by factory {} to client {} : {}'.format(p,f,j,T[p,f,j].X)) print('\nCouldn\'t find an optimal solution. Time limit reached.') print('\nSolution:') print('\ntotal_cost: {}'.format(model.objVal)) elif model.status == GRB.Status.INFEASIBLE: print('\nCouldn\'t find an optimal solution. Status: Infeasible.\n') else: print('Model Status Code: {}'.format(model.Status)) print("==========================================") if __name__ == "__main__": if len(argv) < 2: print("Please provide the path of the file!") exit() with open(argv[1]) as file: dict_const = json.load(file) print(dict_const['J']) solver(dict_const) <file_sep>/Project1/README.md # Projeto 1 ## Equipe - <NAME> (186633) - <NAME> (187101) - <NAME> (187890) ## Gerar Instância Comando: ```BASH python3 generator.py <NUMBER-OF-CLIENTS> ``` Este comando cria um arquivo com o nome `inst_<NUMBER-OF-CLIENTS>.json` no diretório `instances`. ## Otimizar Problema Linear Comando: ``` python3 solve_paper_problem.py <PATH-TO-JSON-FILE> ``` Este comando carrega a instância e devolve no terminal o resultado da otimização do Gurobi e, se existir, os valores atribuídos para as variáveis do problema.
036278c4ba34ed06f17bdc438b17112b34392454
[ "Markdown", "Java", "Python" ]
13
Markdown
VFerrari/OperationalResearch
dd3013ed6f2488060689094836f0a7dd8442cf41
265991d5bdba0014f971645f856e4f59c23dc7b9
refs/heads/master
<repo_name>fridayy/spring-repositories<file_sep>/src/main/java/ninja/harmless/data/StudentBaseRepository.java package ninja.harmless.data; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import java.util.UUID; /** * @author <EMAIL> - 4/23/17. */ @Repository public interface StudentBaseRepository extends CrudRepository<Student, UUID> { } <file_sep>/README.md # Spring Data Mongo & Spring Data JPA Demo Showcases how to use Spring Data Mongo or Spring Data JPA with the same Repository in one project. You can choose between the Mongo and JPA Profile by specifying: * spring.profiles.active=jpa || mongo _(in application.properties)_ * -Dspring.profiles.active=jpa || mongo _(system property)_<file_sep>/src/main/java/ninja/harmless/SpringRepositoriesApplication.java package ninja.harmless; import org.springframework.boot.SpringApplication; import org.springframework.context.annotation.ComponentScan; @ComponentScan(basePackages = "ninja.harmless") public class SpringRepositoriesApplication { public static void main(String[] args) { SpringApplication.run(SpringRepositoriesApplication.class, args); } }
f39c23ac8112d7320cfc6e92bb78a37cf67e8d56
[ "Markdown", "Java" ]
3
Java
fridayy/spring-repositories
28e49ffeb43268b1f7dda003853d29dfdd4c714a
47265bbc344b0dd54949955608a396249d3035a7
refs/heads/master
<file_sep>package com.mlaboratory.justcall; import android.Manifest; import android.annotation.SuppressLint; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private Button mBtnStartDial; private Button mBtnStopDial; private EditText mEdtTxtPhoneNumber; private EditText mEdtTxtDialTimes; private Dialer mDialer; private Intent mIntent; private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mBtnStartDial = (Button) findViewById(R.id.btnStartDial); mBtnStopDial = (Button) findViewById(R.id.btnStopDial); mEdtTxtPhoneNumber = (EditText) findViewById(R.id.edtTxtPhoneNumber); mEdtTxtDialTimes = (EditText) findViewById(R.id.edtTxtDialTimes); mIntent = new Intent(this, RedialService.class); mBtnStartDial.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { btnStartDialOnClick(v); } }); mBtnStopDial.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { btnStopDialOnClick(v); } }); } @Override protected void onDestroy() { stopService(mIntent); super.onDestroy(); } public void btnStartDialOnClick(View v) { if (mEdtTxtPhoneNumber.getText().length() <= 0) { Toast.makeText(this, "Empty", Toast.LENGTH_SHORT).show(); return; } if (mEdtTxtDialTimes.getText().length() <= 0) { Toast.makeText(this, "Empty", Toast.LENGTH_SHORT).show(); return; } if (mDialer == null) { mDialer = new Dialer(this); } mDialer.setPhoneNumber(mEdtTxtPhoneNumber.getText().toString()); if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) { // Should we show an explanation? if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.CALL_PHONE)) { // Show an expanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. new AlertDialog.Builder(MainActivity.this) .setMessage(R.string.alert_dialog_request_permission_msg) .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CALL_PHONE}, MY_PERMISSIONS_REQUEST_CALL_PHONE); } }) .setNegativeButton("Cancel", null) .create() .show(); } else { // No explanation needed, we can request the permission. ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CALL_PHONE}, MY_PERMISSIONS_REQUEST_CALL_PHONE); } } else { mBtnStartDial.setEnabled(false); mDialer.dial(); MyPhoneStateListener.setCounter(0); RedialService.setHandler(mCodeHandler); mIntent.putExtra("PhoneNumber", mEdtTxtPhoneNumber.getText().toString()); mIntent.putExtra("DialTimes", mEdtTxtDialTimes.getText().toString()); stopService(mIntent); startService(mIntent); } } public void btnStopDialOnClick(View v) { stopService(mIntent); initBtnStartDial(); } public void initBtnStartDial() { mBtnStartDial.setEnabled(true); mBtnStartDial.setText(R.string.button_start_dial); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_CALL_PHONE: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { mDialer.dial(); mBtnStartDial.setEnabled(false); RedialService.setHandler(mCodeHandler); mIntent.putExtra("PhoneNumber", mEdtTxtPhoneNumber.getText().toString()); mIntent.putExtra("DialTimes", mEdtTxtDialTimes.getText().toString()); stopService(mIntent); startService(mIntent); } else { // permission denied, boo! Disable the // functionality that depends on this permission. Toast.makeText(MainActivity.this, "CALL_PHONE permission denied.", Toast.LENGTH_SHORT) .show(); } break; } default: super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } @SuppressLint("HandlerLeak") Handler mCodeHandler = new Handler() { public void handleMessage(Message msg) { if (msg.what == MyCountDownTimer.IN_RUNNING) {// 正在倒计时 mBtnStartDial.setText(getString(R.string.button_redial_count_down, msg.obj.toString())); } else if (msg.what == MyCountDownTimer.END_RUNNING) {// 完成倒计时 mBtnStartDial.setText(getString(R.string.button_redialing)); mDialer.dial(); } else if (msg.what == MyCountDownTimer.FINAL_STATE) { initBtnStartDial(); } } }; } <file_sep>package com.mlaboratory.justcall; import android.os.Handler; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.util.Log; public class MyPhoneStateListener extends PhoneStateListener { private static final String LOG_TAG = MyPhoneStateListener.class.getSimpleName(); private Dialer mDialer; private int mDialTimes = -1; private static int counter = 0; private static int delay = 5; private boolean mIsFirstDial = true; private static Handler mHandler; private static MyCountDownTimer mMycouMyCountDownTimer; public static void setCounter(int counter) { MyPhoneStateListener.counter = counter; } public static void setHandler(Handler mHandler) { MyPhoneStateListener.mHandler = mHandler; } public void setDialer(Dialer mDialer) { this.mDialer = mDialer; } public void setDialTimes(int dialTimes) { this.mDialTimes = dialTimes; } public static void setDelay(int delay) { MyPhoneStateListener.delay = delay; } public void cancelMyCountDownTimer() { if (mMycouMyCountDownTimer != null) mMycouMyCountDownTimer.cancel(); } @Override public void onCallStateChanged(int state, String incomingNumber) { switch (state) { case TelephonyManager.CALL_STATE_IDLE: Log.v(LOG_TAG, "CALL_STATE_IDLE"); if (counter >= mDialTimes && mDialTimes != -1) { mHandler.obtainMessage(MyCountDownTimer.FINAL_STATE).sendToTarget(); return; } if (mDialer != null && !mIsFirstDial) { mMycouMyCountDownTimer = new MyCountDownTimer(5000, 1000, mHandler); mMycouMyCountDownTimer.start(); } mIsFirstDial = false; if (mDialTimes != -1) { counter++; } break; case TelephonyManager.CALL_STATE_RINGING: Log.v(LOG_TAG, "CALL_STATE_RINGING"); break; case TelephonyManager.CALL_STATE_OFFHOOK: Log.v(LOG_TAG, "CALL_STATE_OFFHOOK"); break; default: break; } super.onCallStateChanged(state, incomingNumber); } } <file_sep># JustCall A simple app for redialing. <br>And nothing else
b15083b664a1114b4f1dc1c9812fcbeb32349910
[ "Markdown", "Java" ]
3
Java
TimmyMa/JustCall
5d4dd5c0d85990ecb13d97d584750e18fa9d3b14
23d1ec5f7b31e8e82088f847391b340f2c36fac0
refs/heads/master
<repo_name>froniusm/Family-Tree<file_sep>/FamilyTree/Models/RelationshipCategory.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace FamilyTree.Models { public class RelationshipCategory { public int TypeId { get; set; } public string RelationshipType { get; set; } } }<file_sep>/FamilyTree/Models/Person.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace FamilyTree.Models { public class Person { public int PersonID { get; set; } public string FirstName { get; set; } public string MiddleInitial { get; set; } public string LastName { get; set; } public DateTime BirthDate { get; set; } public DateTime DeathDate { get; set; } public bool IsAlive { get; set; } public char Gender { get; set; } } }<file_sep>/FamilyTree/Controllers/HomeController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using FamilyTree.Models; using FamilyTree.DAL; namespace FamilyTree.Controllers { public class HomeController : Controller { private IPersonDAL personDAL; public HomeController(IPersonDAL personDAL) { this.personDAL = personDAL; } public ActionResult Index() { return View("Index"); } public ActionResult PersonOne(Person p) { Person one = new Person(); one.FirstName = p.FirstName; one.MiddleInitial = p.MiddleInitial; one.LastName = p.LastName; one.BirthDate = p.BirthDate; one.IsAlive = p.IsAlive; one.DeathDate = p.DeathDate; one.Gender = p.Gender; return View("PersonOne", one); } } }<file_sep>/FamilyTree/Models/Relationship.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace FamilyTree.Models { public class Relationship { public int FromId { get; set; } public int ToId { get; set; } public int TypeId { get; set; } } }<file_sep>/FamilyTreeScript.sql drop table person; drop table relationship; drop table relationship_type; create Table relationship_category ( typeId int identity(1,1), relationshipType varchar(100) not null, CONSTRAINT pk_relationship_category_typeId PRIMARY KEY (typeId) ); create Table person ( personId int identity(1,1), firstName varchar(100) not null, middleInitial varchar(1), lastName varchar(100) not null, birthDate date not null, deathDate date, isAlive bit not null, gender char not null, CONSTRAINT chk_gender CHECK (Gender IN ('M', 'F')), CONSTRAINT pk_personId PRIMARY KEY (personId) ); create Table relationship ( fromId int not null, toId int not null, typeId int not null, CONSTRAINT pk_relationship_fromId_toId PRIMARY KEY (fromId, toId), CONSTRAINT fk_relationship_typeId FOREIGN KEY (typeId) REFERENCES relationship_category(typeId), CONSTRAINT fk_relationship_fromId FOREIGN KEY (fromId) REFERENCES person(personId), CONSTRAINT fk_relationship_toId FOREIGN KEY (toId) REFERENCES person(personId) ); <file_sep>/FamilyTree/DAL/IPersonDAL.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FamilyTree.Models; namespace FamilyTree.DAL { public interface IPersonDAL { void SavePerson(Person person); } } <file_sep>/FamilyTree/DAL/PersonSqlDAL.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.SqlClient; using FamilyTree.Models; using Dapper; namespace FamilyTree.DAL { public class PersonSqlDAL : IPersonDAL { private readonly string connectionString; private const string SQL_SavePerson = "INSERT INTO person (firstName, middleInitial, lastName, birthDate, deathDate, isAlive, gender)" + "VALUES (@firstName, @middleInitial, @lastName, @birthDate, @deathDate, @isAlive, @gender);"; public PersonSqlDAL(string connectionString) { this.connectionString = connectionString; } public void SavePerson(Person person) { try { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); conn.Query(SQL_SavePerson, new { firstName = person.FirstName, middleInitial = person.MiddleInitial, lastName = person.LastName, birthDate = person.BirthDate, deathDate = person.DeathDate, isAlive = person.IsAlive, gender = person.Gender, }); } } catch (Exception e) { throw; } } } }
9e6a13092c88a9f3f6082f1c70c4f7f454f8384e
[ "C#", "SQL" ]
7
C#
froniusm/Family-Tree
ea337540bf961204227e3f4662b3980ff8d9d013
290d3a0e8d7d8c6c84ea087c84106f8ce31b9a18
refs/heads/master
<repo_name>liumingdfx/weather<file_sep>/src/Exceptions/InvalidArgumentException.php <?php namespace Lmdfx\Weather\Exceptions; class InvalidArgumentException extends Exception { }
444d78c056e58047c0de366b6aef4998b4b6611d
[ "PHP" ]
1
PHP
liumingdfx/weather
399c5847232c098d72a59021697555aacfe90eac
f9eb2122430a411ff762ee7a4b79b74e6b9e5645
refs/heads/master
<repo_name>Zediz/Interfaz_UTR<file_sep>/Samples/prueba_image.py #! /usr/bin/python # -*- coding: utf-8 -* from Tkinter import * v0 = Tk() v0.config(bg = "white") v0.title('Alarmas del Transformador') v0.geometry('700x500+290+150') imagen = Canvas (v0,height = 300, width =300, bg="blue") imagen.place(x=10,y=10) file = PhotoImage(file="termometro.gif") imagen.create_image(1,1, image =file) v0.mainloop()<file_sep>/Samples/gettext_Entry.py #! /usr/bin/python # -*- coding: utf-8 -*- from Tkinter import * class label_alarmas(Tk): def __init__(self,parent): Tk.__init__(self,parent) self.parent = parent self.entrythingy = Entry(self) self.entrythingy.pack() self.boton = Button(self, text="Aceptar", command = self.imprimir_texto) self.boton.pack() self.contenido = StringVar() self.entrythingy.config(textvariable = self.contenido) self.entrythingy.bind('<Key-Return>', self.imprimir_texto) def imprimir_texto (self): print ("Esto es lo que se escribio en el cuadro ----- > " + self.contenido.get()) self.etiqueta = Label(self,text= self.contenido.get(), fg="green",bg = "black") self.etiqueta.pack() root = label_alarmas(None) root.mainloop() <file_sep>/Samples/Prueba_listbox.py #! /usr/bin/python # -*- coding: utf-8 -* from Tkinter import * import tkMessageBox import Tkinter top = Tk() Lb1 = Listbox(top) Lb1.insert(1, "Python") Lb1.insert(2, "Perl") Lb1.insert(3, "C") Lb1.insert(4, "PHP") Lb1.insert(5, "JSP") Lb1.insert(6, "Ruby") Lb1.pack() b1 = Button(top, text= "Imprime", command=lambda : imprimir()) b1.pack() def imprimir(): print (Lb1.curselection()[0]) top.mainloop()<file_sep>/Samples/Reloj_prueba.py #!/usr/bin/env python # -*- coding: utf-8 -*- # from Tkinter import * import time # root = Tk() root.focus() root.title("ǝɯıʇ uoɥʇʎd") root.config(cursor='watch') time1 = '' clock = Label(root, font=('ubuntu', 10, 'bold'), bg='#3C3B37', fg='white', bd=0) clock.pack(fill=BOTH, expand=1) def tick(): global time1 time2 = time.strftime('%H:%M:%S') if time2 != time1: time1 = time2 clock.config(text=time2) clock.after(200, tick) tick() root.mainloop()<file_sep>/Samples/alarmas_analogas.py #! /usr/bin/python # -*- coding: utf-8 -* from Tkinter import * import time, os import thread lock = thread.allocate_lock() class alarmas_analogas(Frame): def __init__(self, master): Frame.__init__(self, master,height=116,width=400, bg="black") self.place(x = 1 , y = 282) title_analog = Label(self,text="Alarmas Analogas", fg ="green", bg = "black") title_analog.place(x= 130, y =1) analog1 = Label (self, text =" Alarma Analoga 1", fg = "green", bg = "black") analog1.place(x= 15, y= 30) analog2 = Label (self, text =" Alarma Analoga 2", fg = "green", bg = "black") analog2.place(x= 15, y= 60) self.voltaje = Label(self,text="") self.voltaje.place(x=200, y=30) self.corriente= Label(self,text="") self.corriente.place(x=200, y=60) self.valv = "" self.valc = "" def checando_analog(self): # Metodo que checa los archivos adc para ver los valores que estos tienen global lock ADC_PATH = os.path.normpath('/proc/') ADC_FILENAME = "adc" adcFiles=[] conta = 0 x=0 punto = 0 for i in range(0,6): # Guardamos las direcciones de los archivos en un arreglo adcFiles.append(os.path.join(ADC_PATH, ADC_FILENAME+ str(i))) while True: # El bucle que se ejecuta para que continuamente se esten revisando el contenido de los archivos lock.acquire() #print("Se esta ejecutando el While Analogas") time.sleep(.3) # El tiempo entre revision y revision for file in adcFiles: #Este abre los 6 archivos de los pines fd = open(file,'r') # se abre el archivo fd.seek(0) # Se situa en el character 5 del archivo valor = fd.read() # de ahi en adelante lee el valor if conta == 3: self.voltaje.config(text=valor+" V") # si esta en el pin 3 asigna el valor en la alarma analoga 1 self.valv = valor #print self.valv elif conta ==4: # si esta en el pin 4 asigna el valor a la label de la alarma analoga 2 self.corriente.config(text=valor+" mA") self.valc = valor #print self.valc conta += 1 # aumenta conta para saber en que momento entra en el pin 3 y 4 fd.close() # Cierra el archivo cada vez que se termina de leer conta = 0 # la variable conta la ponemos en 0 nuevamente apra que empiece a contar de nuevo lock.release() def dar_valv(self): numero = self.valv return numero def dar_valc(self): numero = self.valc return numero """v0 = Tk() v0.config(bg = "white") v0.title('Alarmas del Transformador') v0.geometry('700x500+290+150') ola = alarmas_analogas(v0) thread.start_new_thread(ola.checando_analog, ()) v0.mainloop() #"""<file_sep>/borrar_repeticiones.py from Tkinter import * import time, os import thread from datetime import datetime import threading file = open ("archivo.txt", 'r+') for line in file.readlines(): if <file_sep>/cambio_alarmas.py #! /usr/bin/python # -*- coding: utf-8 -*- from Tkinter import * class cambio_alarmas(Frame): def __init__(self, master): Frame.__init__(self, master,height=170, width=297, bg= "black") self.place(x=402,y=1) titulo = Label(self, text="Cambio de Nombre de las alarmas", fg= "green", bg ="black") titulo.place(x=40, y=1) paso1 = Label(self, text="1.- Seleccione una alarma -->", fg ="green", bg= "black") paso1.place(x=1, y=50) paso2 = Label(self, text ="2.- Escriba el texto y de click en aceptar", fg="green", bg="black") paso2.place(x=1,y=115) self.lista = Listbox(self, height=5, width=9) self.lista.insert(1, " Alarma 1") self.lista.insert(2, " Alarma 2") self.lista.insert(3, " Alarma 3") self.lista.insert(4, " Alarma 4") self.lista.insert(5, " Alarma 5") self.lista.place(x=210, y=30) self.lista.select_set(0) self.entrythingy = Entry(self,width=24) self.entrythingy.place(x=1, y=140) self.contenido = StringVar() self.entrythingy.config(textvariable = self.contenido) def num_lista(self): # Metodo que entrega el numero de la alarma que esta seleccionada en la lista num = self.lista.curselection() num2 = num[0] #print (num2) return num2 def gettext (self): # Metodo que adquiere el texto que esta en el campo de texto y lo entrega. texto = self.contenido.get() #print ("Esto es lo que se escribio en el cuadro ----- > " + texto) return (texto) def vaciar (self): # Metodo que vacia el campo de texto despues de oprimir el boton self.entrythingy.delete (0, END ) """v0 = Tk() v0.config(bg = "white") v0.title('Alarmas del Transformador') v0.geometry('700x500+290+150') ola = cambio_alarmas(v0) v0.mainloop() #*********************""" <file_sep>/Samples/alarmas_digitales.py #! /usr/bin/python # -*- coding: utf-8 -* from Tkinter import * import time, os from datetime import datetime import thread lock = thread.allocate_lock() class alarmas_digitales(Frame): def __init__(self, master): Frame.__init__(self, master,height=100, width=297 ,bg="black") self.place(x=402, y=399) fecha = datetime.today() self.time1 = '' self.clock = Label(self, font=('ubuntu', 10, 'bold'), bg='black', fg='green', bd=0) self.clock.place(x=200, y=85) self.date = Label (self, bg = "black", fg ="green", text= fecha.strftime("%d %b %Y ") ) self.date.place(x=1, y=80) self.b1 = Button(self, text = "Guardar", command = lambda : self.salida()) self.b1.place(x=200, y = 35) self.l1 = Label (self, text= "Guarda un nuevo archivo", fg = "green", bg= "black") self.l1.place(x=1, y = 35) def tick(self): self.time2 = time.strftime('%H:%M:%S') if self.time2 != self.time1: self.time1 = self.time2 self.clock.config(text=self.time2) self.clock.after(200, self.tick) #Aqui iba cambio del nombre de la alarma def cambio (self,num,texto): # Cambio del nombre de la alarma print ("Si tiene el valor " + str(num)) print ("Si tiene el valor " + texto) global alarma1 if num == 0: self.alarma1.config(text =texto) elif num == 1: self.alarma2.config(text =texto) elif num == 2: self.alarma3.config(text =texto) elif num == 3: self.alarma4.config(text =texto) elif num == 4: self.alarma5.config(text =texto) def checando(self): global lock GPIO_MODE_PATH = os.path.normpath('/sys/devices/virtual/misc/gpio/mode/') GPIO_PIN_PATH = os.path.normpath('/sys/devices/virtual/misc/gpio/pin/') GPIO_FILENAME = "gpio" HIGH = "1" LOW ="0" INPUT = "0" OUTPUT = "1" INPUT_PU = "8" pinMode = [] pinData = [] for i in range(0,5): pinMode.append(os.path.join(GPIO_MODE_PATH, 'gpio' + str(i))) pinData.append(os.path.join(GPIO_PIN_PATH, 'gpio'+ str(i))) for pin in range (0,5): file = open(pinMode[pin], 'r+') file.write(INPUT_PU) file.close while True: print("Se esta ejecutando el While digitales") time.sleep(.55) #.5 for pin in range (0,5): print ("Estoy checando el gpio" + str(pin)) file = open(pinData[pin], 'r') lock.acquire() if int(file.read()) == 1: self.set_color_red(pin) else: self.set_color_green(pin) file.close() lock.release() def set_color_red(self, num): if num == 0: self.foco1.config(bg = "red") elif num == 1: self.foco2.config(bg = "red") elif num == 2: self.foco3.config(bg = "red") elif num == 3: self.foco4.config(bg = "red") elif num == 4: self.foco5.config(bg = "red") def set_color_green(self, num): if num == 0: self.foco1.config(bg = "green") elif num == 1: self.foco2.config(bg = "green") elif num == 2: self.foco3.config(bg = "green") elif num == 3: self.foco4.config(bg = "green") elif num == 4: self.foco5.config(bg = "green") v0 = Tk() v0.config(bg = "white") v0.title('Alarmas del Transformador') v0.geometry('700x500+290+150') ola = alarmas_digitales(v0) thread.start_new_thread(ola.checando, ()) v0.mainloop() #****************************************""" <file_sep>/Samples/prueba_lista.py #! /usr/bin/python # -*- coding: utf-8 -* from datetime import datetime import time, os import thread from mtTkinter import * lock = thread.allocate_lock() def uno (): return "1" def dos (): return "2" def tres (): return "3" def cuatro (): return "4" def cinco (): return "5" def seis (): return "5" def siete (): return "5" def ocho (): return "8" numeros = ["8","8","8","8","8","8","8",] alarma1= uno() alarma2 = dos() alarma3 = tres() alarma4= cuatro() alarma5 = cinco() alarma6 = seis() alarma7 = siete() alarma8 = ocho() def creararchivo (): fecha = datetime.today() nome_file = 'Dia_' + str(fecha.strftime("%x")).replace('/','-') + '_Start_Time' + str(fecha.strftime("%X")).replace(':','-') + '_log.txt' f = open(nome_file, 'w'); # cria arquivo para armazenar as leituras recebidas pela serial port print ("Si se abre el archivo") f.write("Lectura de Alarmas\n"); # escreve esta linha no arquivo f.write("------------------------------------------------------------------------------------------------------------------------------------------------------\n"); # escreve esta linha no arquivo f.write("Hora\t\t" + "| Alarma 1\t" + "| Alarma 2\t" + "| Alarma 3\t" + "| Alarma 4\t" + "| Alarma 5\t" + "| Alarma Analoga 1\t" + "| Alarma Analoga 2\t" + "| Switch\n"); # escreve esta linha no arquivo f.write("-----------\n") f.close() print ("El archivo se cerro") return nome_file salir = 0 def salida(): global salir salir = 1 def escribir (alarma1, alarma2,alarma3,alarma4,alarma5,alarmaanalog1,alarmaanalog2,switch): global salir while True: print ("Si entro al while 1") fecha = datetime.today() archivo = creararchivo() print ("El archivo se abrio nuevamente") print (salir) while salir == 0: print "Si entro al while 2" f = open(archivo, "a") f.write(str(fecha.strftime("%H" + ":" + "%M" + ":" + "%S" + "\t" +"|\t" + alarma1 +"\t" +"|\t"+ alarma2 +"\t" +"|\t" + alarma3+"\t"+"|\t" + alarma4+"\t"+"|\t" + alarma5+"\t" +"|\t"+ alarmaanalog1+"\t\t" +"|\t"+ alarmaanalog2+"\t\t" +"|"+ switch+"\n" ))) time.sleep(1) f.close() def iniciar (): print ("Se inicio el nuevo thread") thread.start_new_thread(escribir(alarma1,alarma2, alarma3, alarma4,alarma5,alarma6, alarma7,alarma8)) v0 = Tk() v0.config(bg = "white") v0.title('Alarmas del Transformador') v0.geometry('700x500+290+150') b1 = Button(v0, text = "Guardar", command = lambda : salida()) b1.pack() b2 = Button (v0, text = "Iniciar" , command = lambda : iniciar()) b2.pack() v0.mainloop() <file_sep>/Samples/nueva_pruebatrhreas.py #! /usr/bin/python # -*- coding: utf-8 -* from Tkinter import * import time, os import thread from datetime import datetime import threading lock = thread.allocate_lock() class alarmas_digitales(Frame): def __init__(self, master): Frame.__init__(self, master,height=100, width=297 ,bg="black") self.place(x=402, y=399) self.fecha = datetime.today() self.time1 = '' self.clock = Label(self, font=('ubuntu', 10, 'bold'), bg='black', fg='green', bd=0) self.clock.place(x=200, y=85) self.date = Label (self, bg = "black", fg ="green", text= self.fecha.strftime("%d %b %Y ") ) self.date.place(x=1, y=80) self.l1 = Label (self, text= "Guarda un nuevo archivo", fg = "green", bg= "black") self.l1.place(x=1, y = 35) self.salir = 0 def tick(self): self.time2 = time.strftime('%H:%M:%S') if self.time2 != self.time1: self.time1 = self.time2 self.clock.config(text=self.time2) self.clock.after(200, self.tick) #Aqui iba cambio del nombre de la alarma def guardando(self, val1,val2,val3,val4,val5,valanalog1,valanalog2,valswitch): global lock, salir num = 0 while True: archi = self.archivo() nombre = archi.get_name() print "entre al While1" while self.salir == 0: print "entre al while 2" lock.acquire() archi = open(nombre, 'a') archi.write(str(self.fecha.strftime("%H:%M:%S "))+ "\t\t" + val1() +"\t\t" + val2() + "\t\t" + val3() + "\t\t" + val4() + "\t\t" + val5() + "\t\t "+ valanalog1() + "\t\t\t " + valanalog2()+ "\t\t "+ valswitch() + "\n") archi.close() lock.release() print(num) num +=1 time.sleep(1) self.salir = 0 def salida(self): global salir self.salir = 1 class archivo (threading.Thread): def __init__(self): threading.Thread.__init__(self) self.fecha = datetime.today() self.name_file= 'Dia_' + str(self.fecha.strftime("%x")).replace('/','-') + '_Start_time_' + str(self.fecha.strftime("%X")).replace(':','-') + '_log.txt' self.f = open(self.name_file, 'a') self.f.write("Lectura de alarmas\n") self.f.write("----------------------------------------------------------------------------------------------------------------------------------------------------------\n") self.f.write("Hora\t\t"+ "|" + " Alarma 1\t" + "|" + " Alarma 2\t" + "|" + " Alarma 3\t" + "|" + " Alarma 4\t" + "|" + " Alarma 5\t" + "|" + " Alarma Analoga 1\t" + "|" + " Alarma Analoga 2\t" + "|" + " Switch\n") # escreve esta linha no arquivo self.f.write("----------------------------------------------------------------------------------------------------------------------------------------------------------\n") self.f.close() def get_name (self): name = self.name_file return name v0 = Tk() v0.config(bg = "white") v0.title('Alarmas del Transformador') v0.geometry('700x500+290+150') ola = alarmas_digitales(v0) b1 = Button(ola, text = "Guardar", command = lambda : ola.salida()) b1.place(x=200, y = 35) def dar_val1(): return "1" def dar_val2(): return "2" def dar_val3(): return "3" def dar_val4(): return "4" def dar_val5(): return "5" def dar_val6(): return "6" def dar_val7(): return "7" def dar_val8(): return "8" thread.start_new_thread(ola.guardando, (dar_val1,dar_val2,dar_val3,dar_val4,dar_val5,dar_val6,dar_val7,dar_val8)) v0.mainloop() #****************************************""" <file_sep>/mode.py #! /usr/bin/python # -*- coding: utf-8 -*- import time, os GPIO_MODE_PATH = os.path.normpath('/sys/devices/virtual/misc/gpio/mode') GPIO_PIN_PATH = os.path.normpath('/sys/devices/virtual/misc/gpio/pin') GPIO_FILENAME = "gpio" HIGH = "1" LOW ="0" INPUT = "0" OUTPUT = "1" INPUT_PU = "8" pinMode = [] pinData = [] for i in range(0,18): pinMode.append(os.path.join(GPIO_MODE_PºATH, 'gpio' + str(i))) pinData.append(os.path.join(GPIO_PIN_PATH, 'gpio'+ str(i))) def Change_Mode(pin,mode): file = open(GPIO_MODE_PATH+"/"+GPIO_FILENAME+str(pin), 'r+') file.write(mode) file.close() def HIGH(pin): file = open(GPIO_PIN_PATH + "/"+GPIO_FILENAME+str(pin), 'r+') file.write("1") file.close() def LOW (pin): file = open(GPIO_PIN_PATH + "/"+GPIO_FILENAME+str(pin), 'r+') file.write("0") file.close() print ("Programa terminado Todos los Archivos Cambiados") <file_sep>/Samples/prueba2_horas #! /usr/bin/python # -*- coding: utf-8 -* from Tkinter import * import time, os import threading from datetime import datetime import thread lock = thread.allocate_lock() class alarmas_digitales(Frame): def __init__(self, master): Frame.__init__(self, master,height=100, width=297 ,bg="black") self.place(x=402, y=399) fecha = datetime.today() self.time1 = '' self.clock = Label(self, font=('ubuntu', 10, 'bold'), bg='black', fg='green', bd=0) self.clock.place(x=200, y=85) self.date = Label (self, bg = "black", fg ="green", text= fecha.strftime("%d %b %Y ") ) self.date.place(x=1, y=80) self.l1 = Label (self, text= "Guarda un nuevo archivo", fg = "green", bg= "black") self.l1.place(x=1, y = 35) def tick(self): self.time2 = time.strftime('%H:%M:%S') if self.time2 != self.time1: self.time1 = self.time2 self.clock.config(text=self.time2) self.clock.after(200, self.tick) class archivo (threading.Thread): def __init__(self): threading.Thread.__init__(self) self.fecha = datetime.today() self.name_file= 'Dia_' + str(self.fecha.strftime("%x")).replace('/','-') + '_Start_time_' + str(self.fecha.strftime("%X")).replace(':','-') + '_log.txt' self.f = open(self.name_file, 'a') self.f.write("Lectura de las alarmas\n") self.f.write("-------------------------------------------\n") self.f.write("Leitura\t" + "Hora\t" + "Celsius\t" + "Fahrenheit\n") # escreve esta linha no arquivo self.f.write("-------------------------------------------\n") self.f.close() def run (self): #@Esto es lo que se va a correr global ala1, ala2,ala3,salir,lock while salir == 0: print "entre al While" lock.acquire() self.f = open(self.name_file, 'a') self.f.write(ala1 + ala2 + ala3) self.f.close() lock.release() print salir time.sleep(1) def salida(self): global salir salir = 1 v0 = Tk() v0.config(bg = "white") v0.title('Alarmas del Transformador') v0.geometry('700x500+290+150') ola = alarmas_digitales(v0) #ola.tick() salir = 0 ala1 ="1" ala2 ="2" ala3="3" b1 = Button(ola, text = "Guardar", command = lambda : archi.salida()) b1.place(x=200, y = 35) archi = archivo() archi.start() archi.join() lock.acquire() lock.release() v0.mainloop() #****************************************"""<file_sep>/Samples/analogprueba.py from Tkinter import * import time, os import thread lock = thread.allocate_lock() class alarmas_analogas(Frame): def __init__(self, master): Frame.__init__(self, master,height=116,width=400, bg="black") self.place(x = 1 , y = 282) title_analog = Label(self,text="Alarmas Analogas", fg ="green", bg = "black") title_analog.place(x= 130, y =1) analog1 = Label (self, text =" Alarma Analoga 1", fg = "green", bg = "black") analog1.place(x= 15, y= 30) analog2 = Label (self, text =" Alarma Analoga 2", fg = "green", bg = "black") analog2.place(x= 15, y= 60) self.voltaje = Label(self,text="") self.voltaje.place(x=200, y=30) self.corriente= Label(self,text="") self.corriente.place(x=200, y=60) self.valv = "" self.valc = "" def checando_analog(self): # Metodo que checa los archivos adc para ver los valores que estos tienen global lock while True: # El bucle que se ejecuta para que continuamente se esten revisando el contenido de los archivos lock.acquire() #print("Se esta ejecutando el While Analogas") time.sleep(.3) # El tiempo entre revision y revision file = open('/proc/adc3','r') valor = file.read() self.voltaje.config(text=valor) self.valv=valor file.close() file2 = open ('/proc/adc4','r') valor2= file2.read() self.valc = valor2 self.corriente.config(text = valor2) file2.close() valor = "" valor2 ="" # de ahi en adelante lee el valor lock.release() def dar_valv(self): numero = self.valv return numero def dar_valc(self): numero = self.valc return numero v0 = Tk() v0.config(bg = "white") v0.title('Alarmas del Transformador') v0.geometry('700x500+290+150') ola = alarmas_analogas(v0) thread.start_new_thread(ola.checando_analog, ()) v0.mainloop() #"""<file_sep>/README.md # Interfaz_UTR Sistema de UTRs para la Tesis de carrera <file_sep>/Samples/prueba_segundos.py from Tkinter import * import time, os import thread from datetime import datetime import threading current_milli_time = lambda: int(round(time.time() * 1000)) print current_milli_time <file_sep>/control2.py #! /usr/bin/python # -*- coding: utf-8 -* from Tkinter import * import time, os import thread lock = thread.allocate_lock() estado = "" class control(Frame): def __init__(self, master): Frame.__init__(self, master,height=116, width=400, bg= "black") self.place(x=1,y=282) self.l1 = Label (self, text = "", bg="black", fg = "green") self.l1.place (x=15, y=40) self.b1 = Button(self, text= "Switch", command = lambda: self.switch()) self.b1.place(x=300, y =37) self.foco= Label(self, text = " ", bg = "red") self.foco.place(x=200, y = 40) self.start() def cambio_modo (self): file = open('/sys/devices/virtual/misc/gpio/mode/gpio6', 'r+' ) file.write("1") file.close() def start(self): global estado file = open('/sys/devices/virtual/misc/gpio/pin/gpio6','r+') valor = int(file.read()) if valor== 1: self.l1.config(text = "El switch esta cerrado") self.foco.config(bg = "green") self.b1.config(text = "Abrir") estado = "Cerrado" file.close() elif valor == 0: self.l1.config(text = "El switch esta abierto") self.foco.config(bg = "red") self.b1.config(text = "Cerrar") estado = "Abierto" file.close() def switch(self): global estado lock.acquire() #print ("Si funciona el boton") file = open('/sys/devices/virtual/misc/gpio/pin/gpio6','r+') valor = int(file.read()) file.seek(0) #print(valor) if valor == 1: self.l1.config(text = "El switch esta abierto") self.foco.config(bg = "red") self.b1.config(text = "Cerrar") estado = "Abierto" print self.dar_estado() file.write("0") file.close() elif valor == 0: self.l1.config(text = "El switch esta cerrado") self.foco.config(bg = "green") self.b1.config(text = "Abrir") estado = "Cerrado" print self.dar_estado() file.write("1") file.close() lock.release() def dar_estado (self): val = estado return val v0 = Tk() v0.config(bg = "white") v0.title('Alarmas del Transformador') v0.geometry('700x500+290+150') ola = control(v0) ola.cambio_modo() print ola.dar_estado() v0.mainloop() #"""<file_sep>/alarmas_digitales.py #! /usr/bin/python # -*- coding: utf-8 -* from Tkinter import * import time, os import thread lock = thread.allocate_lock() class alarmas_digitales(Frame): def __init__(self, master): Frame.__init__(self, master,height=280, width=400 ,bg="black") self.place(x=1, y=1) titulo = Label (self, text= "Alarmas Digitales", fg ="green", bg= "black") titulo.place(x= 130, y= 1) self.alarma1 = Label (self, text =" Alarma 1", fg = "green", bg = "black") self.alarma1.place(x= 15, y= 50) self.alarma2 = Label (self, text =" Alarma 2", fg = "green", bg = "black") self.alarma2.place(x= 15, y= 90) self.alarma3 = Label (self, text =" Alarma 3", fg = "green", bg = "black") self.alarma3.place(x= 15, y= 130) self.alarma4 = Label (self, text =" Alarma 4", fg = "green", bg = "black") self.alarma4.place(x= 15, y= 170) self.alarma5 = Label (self, text =" Alarma 5", fg = "green", bg = "black") self.alarma5.place(x= 15, y= 210) flecha1 = Label (self, text =" >>>>", fg = "green", bg = "black") flecha1.place(x= 280, y= 50) flecha2 = Label (self, text =" >>>>", fg = "green", bg = "black") flecha2.place(x= 280, y= 90) flecha3 = Label (self, text =" >>>>", fg = "green", bg = "black") flecha3.place(x= 280, y= 130) flecha4 = Label (self, text =" >>>>", fg = "green", bg = "black") flecha4.place(x= 280, y= 170) flecha5 = Label (self, text =" >>>>", fg = "green", bg = "black") flecha5.place(x= 280, y= 210) self.foco1 = Label (self, text =" ", fg = "green", bg = "green") self.foco1.place(x= 340, y= 52) self.foco2 = Label (self, text =" ", fg = "green", bg = "green") self.foco2.place(x= 340, y= 92) self.foco3 = Label (self, text =" ", fg = "green", bg = "green") self.foco3.place(x= 340, y= 132) self.foco4 = Label (self, text =" ", fg = "green", bg = "green") self.foco4.place(x= 340, y= 172) self.foco5 = Label (self, text =" ", fg = "green", bg = "green") self.foco5.place(x= 340, y= 212) self.val1 = "" self.val2 = "" self.val3 = "" self.val4 = "" self.val5 = "" #Aqui iba cambio del nombre de la alarma def cambio (self,num,texto): # Cambio del nombre de la alarma #print ("Si tiene el valor " + str(num)) #print ("Si tiene el valor " + texto) global alarma1 if num == 0: self.alarma1.config(text =texto) elif num == 1: self.alarma2.config(text =texto) elif num == 2: self.alarma3.config(text =texto) elif num == 3: self.alarma4.config(text =texto) elif num == 4: self.alarma5.config(text =texto) def checando(self): global lock GPIO_MODE_PATH = os.path.normpath('/sys/devices/virtual/misc/gpio/mode/') GPIO_PIN_PATH = os.path.normpath('/sys/devices/virtual/misc/gpio/pin/') GPIO_FILENAME = "gpio" HIGH = "1" LOW ="0" INPUT = "0" OUTPUT = "1" INPUT_PU = "8" pinMode = [] pinData = [] for i in range(0,5): pinMode.append(os.path.join(GPIO_MODE_PATH, 'gpio' + str(i))) pinData.append(os.path.join(GPIO_PIN_PATH, 'gpio'+ str(i))) for pin in range (0,5): file = open(pinMode[pin], 'r+') file.write(INPUT_PU) file.close while True: #print("Se esta ejecutando el While digitales") time.sleep(.05) lock.acquire() #.5 for pin in range (0,5): #print ("Estoy checando el gpio" + str(pin)) file = open(pinData[pin], 'r') if int(file.read()) == 1: self.set_color_red(pin) else: self.set_color_green(pin) file.close() lock.release() def set_color_red(self, num): if num == 0: self.foco1.config(bg = "green") self.val1 = "0" elif num == 1: self.foco2.config(bg = "green") self.val2 = "0" elif num == 2: self.foco3.config(bg = "green") self.val3 = "0" elif num == 3: self.foco4.config(bg = "green") self.val4 = "0" elif num == 4: self.foco5.config(bg = "green") self.val5 = "0" def set_color_green(self, num): if num == 0: self.foco1.config(bg = "red") self.val1 = "1" elif num == 1: self.foco2.config(bg = "red") self.val2 = "1" elif num == 2: self.foco3.config(bg = "red") self.val3 = "1" elif num == 3: self.foco4.config(bg = "red") self.val4 = "1" elif num == 4: self.foco5.config(bg = "red") self.val5 = "1" def dar_val1 (self): val = self.val1 return val def dar_val2 (self): val = self.val2 return val def dar_val3 (self): val = self.val3 return val def dar_val4 (self): val = self.val4 return val def dar_val5 (self): val = self.val5 return val """v0 = Tk() v0.config(bg = "white") v0.title('Alarmas del Transformador') v0.geometry('700x500+290+150') ola = alarmas_digitales(v0) thread.start_new_thread(ola.checando, ()) v0.mainloop() #****************************************""" <file_sep>/user.py #!/usr/bin/env python # -*- coding: utf-8 -*- # from Tkinter import * from time import sleep from random import randint import interfaz # # correct password is: <PASSWORD> # def check(Event = None): if str(var.get()) != "Sh0ck123": # hash for password o = root.geometry() l['text'] = 'Password Equivocada\nSi introduces otra password incorrecta puedes ser reportado' l.config(font=('eurostile', 14), fg='red', bg = "black") for times in range(50): root.geometry("+%d+%d" %(int(root.geometry().split("+")[1])+randint(-69, 69), int(root.geometry().split("+")[2])+randint(-69, 69))) root.update() sleep(.05) root.geometry(o) root.geometry(o) root.update() else: l['text'] = 'OK: Entrando al sistema de alarmas' print ('\nEstas conectado al sistema de alarmas\n') l.config(fg='black') sleep(.25) root.deiconify() root.geometry() root.destroy() interfaz.shido() var.set("") # root = Tk() root.config(bg = "black", cursor = "hand2") root.title("IDU-UM v1.0") root.geometry("413x260+430+230") root.wm_attributes("-topmost", 1) root.focus() fit = Canvas (root,height = 240, width =273, bg="black", bd = 0 ,highlightthickness=0, relief = 'ridge') fit.place(x=141, y=0) file2 = PhotoImage(file="fit.gif") fit.create_image(150,100, image =file2) cfe = Canvas (root,height = 100, width =140, bg="black", bd = 0 ,highlightthickness=0, relief = 'ridge') cfe.place(x=1, y=1) file1 = PhotoImage(file="cfelogo.gif") cfe.create_image(50,30, image =file1) um = Canvas (root,height = 75, width =413, bg="black", bd = 0 ,highlightthickness=0, relief = 'ridge') um.place(x=1, y=185) file = PhotoImage(file="umlogo.gif") um.create_image(205,40, image =file) var = StringVar() l = Label(root, text = "Bienvenido Hiram... \n Introduce tu Password", bg="black", fg = "gray", bd=0, relief='flat', cursor='hand2') l.place(x=5, y=103) a = Entry(root, show = '●', bg='#D7DAED', bd=0, relief='flat', cursor='xterm', highlightcolor='red', textvariable = var) # show = '*' a.place(x=5, y =150) a.bind("<Return>", check) a.focus() root.mainloop()<file_sep>/Samples/adc_test.py import time, os ADC_PATH = os.path.normpath('/proc/') ADC_FILENAME = "adc" adcFiles=[] conta = 0 for i in range(0,6): adcFiles.append(os.path.join(ADC_PATH, ADC_FILENAME+ str(i))) for file in adcFiles: fd = open(file,'r') fd.seek(0) if conta == 3: print ("ADC Channel : " + str(adcFiles.index(file))+ " Result: " + fd.read()) elif conta ==4: print ("ADC Channel : " + str(adcFiles.index(file))+ " Result: " + fd.read()) conta += 1 fd.close() conta = 0 <file_sep>/interfaz.py #! /usr/bin/python # -*- coding: utf-8 -*- from Tkinter import * import thread import cambio_alarmas import alarmas_digitales import control import Hora_archivos lock = thread.allocate_lock() def cambio_de_ala (): # Este es el metodo que se ejectua al presionar el boton para cambiar la alarma global control, digi, change, archivos lock.acquire() num = int(change.num_lista()) # Aqui obtengo el valor de la alarma que esta seleccionada texto = change.gettext() # Aqui obtengo el texto que esta en el campo de texto digi.cambio(num,texto) # Ejecuto el metodo cambio, que es el que cambia la alarma del frame de alarmas digitales change.vaciar() # Vacio el campo para que escriban otra alarma. lock.release() # FRAME DE LOS PINES ********************* def shido (): global control, digi, change, archivos v0 = Tk() v0.config(bg = "white") v0.title('IDU-UM v1.20') v0.geometry('700x500+290+150') lock = thread.allocate_lock() digi = alarmas_digitales.alarmas_digitales(v0) change = cambio_alarmas.cambio_alarmas(v0) control = control.control(v0) archivos = Hora_archivos.win_archivos(v0) pines =Frame(height = 260, width= 297, bg="black") pines.place(x = 402, y = 172) analogas = Frame(height=100, width=297, bg= "black") analogas.place (x=402,y=399) #*************************************************************** boton = Button(change, text="Aceptar" ,command = lambda : cambio_de_ala() ) # El boton que lo situo en el frame de cambio de alarma y ejecuta boton.place(x=210,y=140) # el metodo de cambio de la alarma bguardar = Button(archivos, text = "Guardar", command = lambda : archivos.salida()) bguardar.place(x=300, y = 35) archivos.tick () thread.start_new_thread(digi.checando, ()) # Un metodo que se ejecuta al mismo tiempo que el de abajo # El otro metdo que se ejecuta con el de arriba thread.start_new_thread(archivos.guardando, (digi.dar_val1, digi.dar_val2, digi.dar_val3, digi.dar_val4, digi.dar_val5, control.dar_estado)) print control.dar_estado() v0.mainloop()<file_sep>/Samples/Threading_prueba.py #! /usr/bin/python # -*- coding: utf-8 -* import time, os import threading class MiThread(threading.Thread): def __init__(self, num): threading.Thread.__init__(self) self.num = num def run(self): print "Soy un Hilo", self.num print "Soy el hilo principal" for i in range (0,10): t=MiThread(i) t.start() t.join <file_sep>/Dar de alta GPIO.py import wiringpi2 OUTPUT = 1 pin = 2 HIGH = 1 LOW = 0 wiringpi2.wiringPiSetupPhys() wiringpi2.pinMode(pin,OUTPUT) # se asignaba el pin 2 como salida while 1: wiringpi2.digitalWrite(pin,HIGH) # Escribe 1 en el pin 2 wiringpi2.delay(1000) # Se espera 1 segundo wiringpi2.digitalWrite(pin,LOW) # Escribe 0 en el pin 2 wiringpi2.delay(1000) # Se espera 1 segundo
785d83d8a9f583d1caeac38fd9e3a96f35ffbeb0
[ "Markdown", "Python" ]
22
Python
Zediz/Interfaz_UTR
8252199cab614105456902a197862e397649467e
2648e812213127cf2ffdea25581353f07cd08e31
refs/heads/master
<file_sep>var React = require('react'); var Router = require('react-router'); var Link = Router.Link; var DocumentTitle = require("react-document-title"); var Home = React.createClass({ mixins: [Router.Navigation], getInitialState: function () { return { search: "", }; }, handleSubmit: function(e) { e.preventDefault(); if($.trim(this.state.search)){ this.context.router.transitionTo('/sort=hot&q=' + this.state.search); } }, handleChange: function(event) { this.setState({search: event.target.value.substr(0, 140)}); }, render: function() { return( <DocumentTitle title="Searchdit"> <div id="content"> <div className="l-home"> <a className="home-logo" href="#"> <img className="img-responsive" alt="Searchdit" src="assets/images/logo1.png"/> </a> <form className="input-group home-search-bar" onSubmit={this.handleSubmit}> <input className="form-control" value={this.state.search} onChange={this.handleChange} type="text" autoFocus={true}/> <span className="input-group-btn"> <button className="btn" type="submit"><i className="glyphicon glyphicon-search"></i></button> </span> </form> </div> <div className="m-footer"> <Link to="home">Home</Link> <Link to="help">Help</Link> <Link to="about">About</Link> <Link to="search" params={{sort: "hot", splat:"/r/random"}}>Random</Link> </div> </div> </DocumentTitle> ) } }); module.exports = Home;<file_sep>var React = require('react'); var Router = require('react-router'); var Link = Router.Link; var DocumentTitle = require("react-document-title"); var About = React.createClass({ render: function() { return( <DocumentTitle title="About - Searchdit"> <div id="content"> <div className="m-info"> <a className="info-logo" href="#"> <img className="img-responsive" alt="Searchdit" src="assets/images/logo1.png"/> </a> <div className="info-body"> <div className="title">ABOUT</div> <div className="body">Browse reddit at work without getting caught</div> <div className="body">Built with ReactJs and React-Router</div> <div className="body">Source code at <a target="_blank" href="https://github.com/kevhou/Searchdit">Github</a></div> </div> <div className="m-footer"> <Link to="home">Home</Link> <Link to="help">Help</Link> <Link to="about">About</Link> <Link to="search" params={{sort: "hot", splat:"/r/random"}}>Random</Link> </div> </div> </div> </DocumentTitle> ) } }); module.exports = About;<file_sep>var React = require('react'); var Truncate = require('truncate'); var Moment = require('moment'); var Router = require('react-router'); var Link = Router.Link; var DocumentTitle = require("react-document-title"); var RedditAPI = require('./RedditAPI.js'); var entities = require("entities"); var Comments = React.createClass({ mixins: [Router.Navigation], getInitialState: function () { return { post: null, comments: [], path: this.props.params.splat, sort: this.props.params.sort, search: null, title: null, }; }, comments: function(sub, sort) { RedditAPI.getComment(sub, sort).then(function(data){ if(this.isMounted()){ this.setState({ post: data[0].data.children, comments: data[1].data.children, title: data[0].data.children[0].data.title }); } }.bind(this)); }, handleChange: function(event) { this.setState({search: event.target.value.substr(0, 140)}); }, handleSubmit: function(e) { e.preventDefault(); this.context.router.transitionTo('/sort=hot&q=' + this.state.search); }, componentDidMount: function(){ this.comments(this.state.path, this.state.sort); }, componentWillReceiveProps: function(nextProps) { this.setState({path: nextProps.params.splat, sort: nextProps.params.sort}); this.comments(nextProps.params.splat, nextProps.params.sort); }, getComments: function(comments){ return( <div className="m-comments"> {comments.map(function(item, i) { var data = item.data; var text = entities.decodeHTML(data.body_html); var author = data.author; var date = Moment.unix(data.created_utc).fromNow(); var score = data.score + ' pts'; return( <ul className="comments-list" key={i}> { item.kind == "more" ? <li><Link to="comments" params={{sort: "best", splat: this.state.path + '/' + this.state.title + "/" + item.data.id}}> more </Link></li> : ( <li className="comments-item"> <div className="comments-author"> {author} <span className="comments-info"> {date} - {score}</span> </div> <div className="comments-text" dangerouslySetInnerHTML={{__html: text}} /> </li> )} { data.replies ? <div> {this.getComments(data.replies.data.children)} </div> : null } </ul> ) }.bind(this))} </div> ) }, getPost: function(){ var data, author, title, titleLink, subreddit, date, score, comments, text, nsfw, subredditLink, numComments; data = this.state.post[0].data; author = data.author; title = entities.decodeHTML(data.title); subreddit = '/r/' + data.subreddit; subredditLink = '/#/q=' + subreddit; date = Moment.unix(data.created_utc).fromNow(); score = data.score + ' pts'; numComments = data.num_comments + ' comments'; if(data.selftext){ text = entities.decodeHTML(data.selftext_html); }else{ text = data.url; titleLink = data.url; } if(data.over_18){ nsfw = "[NSFW]"; } return( <div className="m-post"> <div className="post-block"> <div><a className="post-title" href={titleLink}>{title}</a> <Link className="post-subreddit" to="search" params={{sort: "hot", splat: subreddit}}>{subreddit}</Link></div> <div className="post-text" dangerouslySetInnerHTML={{__html: text}} /> <div className="post-footer">{nsfw} {date} - {score} - {numComments} - {author}</div> </div> </div> ) }, render: function() { return( <DocumentTitle title="Comment - Searchdit"> <div id="content"> <div className="l-comments"> <div className="comments-bar"> <div className="m-searchbar"> <a href="#"> <span className="searchbar-logo">Searchdit</span> </a> <form className="input-group" onSubmit={this.handleSubmit}> <input className="form-control " value={this.state.search} onChange={this.handleChange} type="text"/> <div className="input-group-btn"> <button className="btn btn-default" type="submit"><i className="glyphicon glyphicon-search"></i></button> </div> </form> </div> </div> <div className="comments-sort"> <div className="m-sort"> <Link activeClassName="selected" to="comments" params={{sort: "best", splat: this.props.params.splat}}>Best</Link> <Link activeClassName="selected" to="comments" params={{sort: "top", splat: this.props.params.splat}}>Top</Link> <Link activeClassName="selected" to="comments" params={{sort: "new", splat: this.props.params.splat}}>New</Link> <Link activeClassName="selected" to="comments" params={{sort: "controversial", splat: this.props.params.splat}}>Controversial</Link> <Link activeClassName="selected" to="comments" params={{sort: "old", splat: this.props.params.splat}}>Old</Link> <Link activeClassName="selected" to="comments" params={{sort: "qa", splat: this.props.params.splat}}>Q&A</Link> </div> </div> { this.state.post ? <div className="comments-post">{this.getPost()}</div> :null } <div className="comments-body"> {this.getComments(this.state.comments)} </div> </div> </div> </DocumentTitle> ) } }); module.exports = Comments;<file_sep><a name"1.4.0"></a> ## 1.4.0 (2015-08-30) #### Bug Fixes * **app:** * meta tags (b913c9f8) * limit # of ajax return objects (34735165) * no more redirect from /r/* (c36ca0f5) * comments page along with ooverall style (0b89d7ba) * remove autoreload on production (0b796c9d) * **comments:** comments page glitch with invisible post (a01caa55) * **route:** routing complete for search #TODO subreddit (6d40d699) * **search bar:** change form submit button to onclick (a83b6e3c) * **style:** fix margin for logo (e7169e28) #### Features * **app:** * infinite scroll and help pages added (7607e129) * sort comments (640002c5) * view more comments (3ab97b5c) * sort posts between hot/new/top... (47738b82) * check if subreddit exist, if not treat it as search (086aa57b) * search subreddit and route subreddit in url (25d4ccd6) * **comments:** add comments page (435ee4cf) <a name"1.3.0"></a> ## 1.3.0 (2015-08-29) #### Bug Fixes * **app:** * limit # of ajax return objects (34735165) * no more redirect from /r/* (c36ca0f5) * comments page along with ooverall style (0b89d7ba) * remove autoreload on production (0b796c9d) * **comments:** comments page glitch with invisible post (a01caa55) * **route:** routing complete for search #TODO subreddit (6d40d699) * **search bar:** change form submit button to onclick (a83b6e3c) * **style:** fix margin for logo (e7169e28) #### Features * **app:** * infinite scroll and help pages added (7607e129) * sort comments (640002c5) * view more comments (3ab97b5c) * sort posts between hot/new/top... (47738b82) * check if subreddit exist, if not treat it as search (086aa57b) * search subreddit and route subreddit in url (25d4ccd6) * **comments:** add comments page (435ee4cf) <a name"1.2.0"></a> ## 1.2.0 (2015-08-28) #### Bug Fixes * **app:** * no more redirect from /r/* (c36ca0f5) * comments page along with ooverall style (0b89d7ba) * remove autoreload on production (0b796c9d) * **comments:** comments page glitch with invisible post (a01caa55) * **route:** routing complete for search #TODO subreddit (6d40d699) * **search bar:** change form submit button to onclick (a83b6e3c) #### Features * **app:** * infinite scroll and help pages added (7607e129) * sort comments (640002c5) * view more comments (3ab97b5c) * sort posts between hot/new/top... (47738b82) * check if subreddit exist, if not treat it as search (086aa57b) * search subreddit and route subreddit in url (25d4ccd6) * **comments:** add comments page (435ee4cf) <a name"1.1.0"></a> ## 1.1.0 (2015-08-27) #### Bug Fixes * **app:** * no more redirect from /r/* (c36ca0f5) * comments page along with ooverall style (0b89d7ba) * remove autoreload on production (0b796c9d) * **comments:** comments page glitch with invisible post (a01caa55) * **route:** routing complete for search #TODO subreddit (6d40d699) * **search bar:** change form submit button to onclick (a83b6e3c) #### Features * **app:** * sort comments (640002c5) * view more comments (3ab97b5c) * sort posts between hot/new/top... (47738b82) * check if subreddit exist, if not treat it as search (086aa57b) * search subreddit and route subreddit in url (25d4ccd6) * **comments:** add comments page (435ee4cf) <a name"1.0.0"></a> ## 1.0.0 (2015-08-26) #### Bug Fixes * **app:** * no more redirect from /r/* (c36ca0f5) * comments page along with ooverall style (0b89d7ba) * remove autoreload on production (0b796c9d) * **comments:** comments page glitch with invisible post (a01caa55) * **route:** routing complete for search #TODO subreddit (6d40d699) * **search bar:** change form submit button to onclick (a83b6e3c) #### Features * **app:** * view more comments (3ab97b5c) * sort posts between hot/new/top... (47738b82) * check if subreddit exist, if not treat it as search (086aa57b) * search subreddit and route subreddit in url (25d4ccd6) * **comments:** add comments page (435ee4cf) <a name"0.5.0"></a> ## 0.5.0 (2015-08-25) #### Bug Fixes * **app:** * comments page along with ooverall style (0b89d7ba) * remove autoreload on production (0b796c9d) * **comments:** comments page glitch with invisible post (a01caa55) * **route:** routing complete for search #TODO subreddit (6d40d699) * **search bar:** change form submit button to onclick (a83b6e3c) #### Features * **app:** * sort posts between hot/new/top... (47738b82) * check if subreddit exist, if not treat it as search (086aa57b) * search subreddit and route subreddit in url (25d4ccd6) * **comments:** add comments page (435ee4cf) <a name"0.4.1"></a> ### 0.4.1 (2015-08-22) #### Bug Fixes * **app:** * comments page along with ooverall style (0b89d7ba) * remove autoreload on production (0b796c9d) * **comments:** comments page glitch with invisible post (a01caa55) * **route:** routing complete for search #TODO subreddit (6d40d699) * **search bar:** change form submit button to onclick (a83b6e3c) #### Features * **app:** * check if subreddit exist, if not treat it as search (086aa57b) * search subreddit and route subreddit in url (25d4ccd6) * **comments:** add comments page (435ee4cf) <a name"0.4.0"></a> ## 0.4.0 (2015-08-17) #### Bug Fixes * **app:** * comments page along with ooverall style (0b89d7ba) * remove autoreload on production (0b796c9d) * **route:** routing complete for search #TODO subreddit (6d40d699) * **search bar:** change form submit button to onclick (a83b6e3c) #### Features * **app:** * check if subreddit exist, if not treat it as search (086aa57b) * search subreddit and route subreddit in url (25d4ccd6) * **comments:** add comments page (435ee4cf) <a name"0.3.0"></a> ## 0.3.0 (2015-08-02) #### Bug Fixes * **app:** remove autoreload on production (0b796c9d) * **route:** routing complete for search #TODO subreddit (6d40d699) #### Features * **app:** * check if subreddit exist, if not treat it as search (086aa57b) * search subreddit and route subreddit in url (25d4ccd6) * **comments:** add comments page (435ee4cf) <a name"0.2.0"></a> ## 0.2.0 (2015-07-29) #### Bug Fixes * **app:** remove autoreload on production (0b796c9d) * **route:** routing complete for search #TODO subreddit (6d40d699) #### Features * **app:** * check if subreddit exist, if not treat it as search (086aa57b) * search subreddit and route subreddit in url (25d4ccd6) <a name"0.1.0"></a> ## 0.1.0 (2015-07-17) #### Features * **app:** search subreddit and route subreddit in url (25d4ccd6) <file_sep>##TODO - ~~use `selftext_html` to display listing text~~ - ~~show og post in comments page~~ - ~~tabs to sort listings~~ - ~~limit # of preview text `http://stackoverflow.com/questions/6983912/how-to-limit-inner-text-of-div-to-175-characters`~~ - ~~add google analytics~~ - ~~add guide~~ - ~~different color name in comments for author~~ - ~~Reduce the number of returned posts with api call~~ - fix command-click on link - change `random` link to be like wolfram's random link (homepage) - add ads to make it more real (refer to yahoo for example) <file_sep>var React = require('react'); var InfiniteScroll = require('react-infinite-scroll')(React); var Moment = require('moment'); var Truncate = require('truncate'); var Router = require('react-router'); var Route = Router.Route; var Link = Router.Link; var entities = require("entities"); var DocumentTitle = require("react-document-title"); var RedditAPI = require('./RedditAPI.js'); var Search = React.createClass({ mixins: [Router.Navigation], getInitialState: function () { return { posts: [], next: null, path: this.props.params.splat, sort: this.props.params.sort, type: null, }; }, sub: function(sub, sort) { RedditAPI.getSub(sub, sort).then(function(data){ if(this.isMounted()){ if(sub === "/r/random"){ this.context.router.transitionTo('/sort=hot&q=/r/' + data.data.children[0].data.subreddit); } if(data.data.children.length == 0){ this.setState({ posts: [{data: {title: "No posts found", subreddit: null, id: null, selftext: "there doesn't seem to be anything here"}}], next: null, type: "sub" }); }else{ this.setState({ posts: data.data.children, next: data.data.after, type: "sub" }); } } }.bind(this)).fail(function(){ this.search(sub, sort); }.bind(this)); }, search: function(sub, sort) { RedditAPI.getSearch(sub, sort).then(function(data){ if(this.isMounted()){ if(data.data.children.length == 0){ this.setState({ posts: [{data: {title: "No search results found", subreddit: null, id: null, selftext: "there doesn't seem to be anything here"}}], next: null, type: "search" }); }else{ this.setState({ posts: data.data.children, next: data.data.after, type: "search" }); } } }.bind(this)); }, handleShowMore: function(){ RedditAPI.getNext(this.state.next).then(function(data){ if(this.isMounted()){ var appendPosts = this.state.posts.concat(data.data.children); this.setState({ posts: appendPosts, next: data.data.after}); } }.bind(this)); }, componentDidMount: function(){ this.sub(this.state.path, this.state.sort); }, componentWillReceiveProps: function(nextProps) { this.setState({path: nextProps.params.splat, sort: nextProps.params.sort}); this.sub(nextProps.params.splat, nextProps.params.sort); }, handleChange: function(event) { this.setState({path: event.target.value.substr(0, 140)}); }, handleSubmit: function(e) { e.preventDefault(); this.context.router.transitionTo('/sort=hot&q=' + this.state.path); }, getComponent: function() { $(this.getDOMNode()).addClass("selected"); }, render: function() { var title, titleLink, subreddit, date, score, comments, text, nsfw; return ( <DocumentTitle title={this.props.params.splat + "- Searchdit"}> <div id="content"> <div className="l-result"> <div className="result-bar"> <div className="m-searchbar"> <a href="#"> <span className="searchbar-logo">Searchdit</span> </a> <form className="input-group" onSubmit={this.handleSubmit}> <input className="form-control" value={this.state.path} onChange={this.handleChange} type="text"/> <div className="input-group-btn"> <button className="btn" type="submit"><i className="glyphicon glyphicon-search"></i></button> </div> </form> </div> </div> <div className="result-sort"> <div className="m-sort"> { this.state.type ? <Link activeClassName="selected" to="search" params={{sort: "hot", splat: this.props.params.splat}}>Hot</Link> : null} { this.state.type ? <Link activeClassName="selected" to="search" params={{sort: "new", splat: this.props.params.splat}}>New</Link> : null} { this.state.type === "sub" ? <Link activeClassName="selected" to="search" params={{sort: "rising", splat: this.props.params.splat}}>Rising</Link> : null} { this.state.type === "sub" ? <Link activeClassName="selected" to="search" params={{sort: "controversial", splat: this.props.params.splat}}>Controversial</Link> : null} { this.state.type ? <Link activeClassName="selected" to="search" params={{sort: "top", splat: this.props.params.splat}}>Top</Link> : null} { this.state.type === "search" ? <Link activeClassName="selected" to="search" params={{sort: "relevance", splat: this.props.params.splat}}>Relevance</Link> : null} </div> </div> <div className="result-body"> <div className="m-post"> <InfiniteScroll loadMore={this.handleShowMore} hasMore={this.state.next} loader={<div className="loader">Loading ...</div>}> {this.state.posts.map(function(item, i) { var data = item.data; title = entities.decodeHTML(item.data.title); subreddit = '/r/' + data.subreddit; date = Moment.unix(data.created_utc).fromNow(); score = data.score + ' pts'; numComments = data.num_comments + ' comments'; if(data.id){ commentsLink = '/#/sort=best&comments=' + data.id; }else{ commentsLink = null; } if(data.selftext){ text = Truncate(data.selftext, 150); titleLink = commentsLink; }else{ text = Truncate(data.url, 150); titleLink = data.url; } if(data.over_18){ nsfw = "[NSFW]"; } return( <div className="post-block" key={i}> <div><a className="post-title" href={titleLink}>{title}</a> { data.subreddit ? <Link className="post-subreddit" to="search" params={{sort: "hot", splat: subreddit}}>{subreddit}</Link> : null}</div> <div className="post-text">{text}</div> { data.id ? <div className="post-footer">{nsfw} {date} - {score} - <a href={commentsLink}>{numComments}</a> </div> : null} </div> ) }.bind(this))} </InfiniteScroll> </div> </div> </div> </div> </DocumentTitle> ) } }); module.exports = Search;<file_sep>var $ = require('jquery'); var Q = require('q'); var RedditAPI = { CURRENT_ENDPOINT: null, REDDIT_ENDPOINT: 'https://reddit.com', request: function(url, option) { var options = option || {}; var deferred = Q.defer(); $.ajax({ dataType: "jsonp", url: url, jsonp: "jsonp", options: options}) .done(function(res) { deferred.resolve(res); }) .fail(function(err) { deferred.reject(err); }); return deferred.promise; }, get: function(url, options) { options.data = options.data || {}; options.type = 'GET'; return RedditAPI.request(url, options); }, getSub: function(text, sort) { var options = {}; var search = text + "/" + sort; var endPoint = RedditAPI.REDDIT_ENDPOINT + search + ".json?limit=10&jsonp=?"; this.CURRENT_ENDPOINT = endPoint; return RedditAPI.get(endPoint, options); }, getSearch: function(text, sort) { var options = {}; var search = text + "&sort=" + sort; var endPoint = RedditAPI.REDDIT_ENDPOINT + "/search.json?limit=10&q=" + search + "&jsonp=?"; this.CURRENT_ENDPOINT = endPoint; return RedditAPI.get(endPoint, options); }, getComment: function(id, sort) { var options = {}; // var search = id + "/?sort=" + sort; var endPoint = RedditAPI.REDDIT_ENDPOINT + "/comments/" + id + ".json?sort=" + sort; this.CURRENT_ENDPOINT = endPoint; return RedditAPI.get(endPoint, options); }, getNext: function(next) { var options = {}; var endPoint = this.CURRENT_ENDPOINT + "&after=" + next; return RedditAPI.get(endPoint, options); } }; module.exports = RedditAPI;<file_sep># Searchdit Simple & minimalist way to search and read reddit. Looks like a typical search engine. Browse reddit at work without getting caught! ## Usage npm install grunt server
a20299119358db3468ced437e85e3e6f03986317
[ "JavaScript", "Markdown" ]
8
JavaScript
kevhou/Searchdit
2cfd0ff148540cfc3346ed35732fd6937c1034dc
4388dbcbb422d55d977b96a6b5f41ddd1f6476a0
refs/heads/master
<file_sep>#!/usr/bin/env python # Purpose : Python Boot Camp - Basemap Teaching Program 4. # Ensure that environment variable PYTHONUNBUFFERED=yes # This allows STDOUT and STDERR to both be logged in chronological order import sys # platform, args, run tools import os # platform, args, run tools import argparse # For parsing command line import datetime # For date/time processing import numpy as np import h5py import matplotlib as mpl mpl.use('Agg', warn=False) import matplotlib.pyplot as plt from matplotlib.pyplot import figure, show, subplots from mpl_toolkits.basemap import Basemap from mpl_toolkits.basemap import cm as bm_cm import matplotlib.cm as mpl_cm ######################################################################### # Command Line Parameters Class ######################################################################### class Bcbm4CP(): def bcbm4_cp(self, bcbm4_cmd_line): description = ("Python Boot Camp - Basemap Teaching Program 4") parser = argparse.ArgumentParser(description=description) help_text = ("Input file name") parser.add_argument('input_file_name', metavar='input_file_name', #type=string, help=help_text) help_text = ("Display processing messages to STDOUT " + "(DEFAULT=NO)") parser.add_argument("-v", "--verbose", default=False, help=help_text, action="store_true", dest="verbose") help_text = ("Run program in test mode " + "(DEFAULT=NO)") parser.add_argument("-t", "--test_mode", default=False, help=help_text, action="store_true", dest="test_mode") self.args = parser.parse_args(bcbm4_cmd_line) if (self.args.verbose): sys.stdout.write("BCBM4 : bcbm4_cmd_line = " + str(bcbm4_cmd_line) + "\n") # Return return(0) ######################################################################### # Main Program ######################################################################### class Bcbm4(): def bcbm4(self, bcbm4_cmd_line): # Start time self.start_time = datetime.datetime.today() # Parse input parameters from cmd line bcbm4_cp1 = Bcbm4CP() bcbm4_cp1_ret = bcbm4_cp1.bcbm4_cp(bcbm4_cmd_line) self.bcbm4_cmd_line = bcbm4_cmd_line if (len(self.bcbm4_cmd_line) == 0): self.bcbm4_cmd_line = " " if (bcbm4_cp1_ret): return(bcbm4_cp1_ret) self.verbose = bcbm4_cp1.args.verbose self.test_mode = bcbm4_cp1.args.test_mode self.input_file_name = bcbm4_cp1.args.input_file_name if (self.test_mode): self.timestamp = "Test Mode Date/Time Stamp" if (self.verbose): sys.stdout.write("BCBM4 : Running in test mode\n") sys.stdout.write("BCBM4 : sys.version = " + str(sys.version) + "\n") else: self.timestamp = datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S") if (self.verbose): sys.stdout.write("BCBM4 : Program started : " + str(self.start_time) + "\n") sys.stdout.write("BCBM4 : sys.version = " + str(sys.version) + "\n") if (self.verbose): sys.stdout.write("BCBM4 : sys.version = " + str(sys.version) + "\n") sys.stdout.write("BCBM4 : self.verbose = " + str(self.verbose) + "\n") sys.stdout.write("BCBM4 : self.test_mode = " + str(self.test_mode) + "\n") sys.stdout.write("BCBM4 : self.input_file_name = " + str(self.input_file_name) + "\n") # Call functions bcbm4_f11_ret = self.read_omps_data() if (bcbm4_f11_ret): return(bcbm4_f11_ret) bcbm4_f11_ret = self.make_north_america_map() if (bcbm4_f11_ret): return(bcbm4_f11_ret) # End program self.end_time = datetime.datetime.today() self.run_time = self.end_time - self.start_time if (self.verbose): if (self.test_mode): pass else: sys.stdout.write("BCBM4 : Program ended : " + str(self.end_time) + "\n") sys.stdout.write("BCBM4 : Run time : " + str(self.run_time) + "\n") if (self.verbose): sys.stdout.write("BCBM4 : Program completed normally\n") return(0) # Define functions #------------------------------------------------------------------------------ def read_omps_data(self): if (self.verbose): sys.stdout.write("BCBM4 : read_omps_data ACTIVATED\n") # Open input HDF5 file self.input_file = h5py.File(self.input_file_name, "r") sys.stdout.write("BCBM2 : self.input_file = " + str(self.input_file) + "\n") self.o3 = self.input_file["DataFields/O3CombinedValue"] self.lats = self.input_file["GeolocationFields/Latitude"] self.lons = self.input_file["GeolocationFields/Longitude"] self.orbit_num = self.input_file["GeolocationFields/OrbitNumber"] # Convert from Numpy objects to list arrays # Select only centre slit data self.lat_cs = self.lats[:,1] self.lon_cs = self.lons[:,1] self.orbit_num_cs = self.orbit_num[:,1] sys.stdout.write("BCBM2 : self.lat_cs = " + str(self.lat_cs) + "\n") sys.stdout.write("BCBM2 : self.lon_cs = " + str(self.lon_cs) + "\n") sys.stdout.write("BCBM2 : self.orbit_num_cs = " + str(self.orbit_num_cs) + "\n") return(0) #------------------------------------------------------------------------------ def make_north_america_map(self): if (self.verbose): sys.stdout.write("BCBM4 : make_north_america_map ACTIVATED\n") # Set up figure in Matplotlib self.current_figure = mpl.pyplot.figure(1, figsize=(14.0, 10.0)) self.current_figure.suptitle("Basemap - Lambert Conformal Projection Map\n" + self.timestamp) self.current_figure.text(0.05, 0.95, "A Map of North America") self.current_figure.subplots_adjust(left=0.05, right=0.95, top=0.80, bottom=0.05, wspace=0.2, hspace=0.4) self.current_plot = self.current_figure.add_subplot(1, 1, 1) # Plot figure self.map = Basemap(width=12000000, height=9000000, projection='lcc', resolution='c', lat_1=45., lat_2=55, lat_0=50, lon_0=-107.) #self.map.drawmapboundary(fill_color='aqua') #self.map.fillcontinents(color='coral',lake_color='aqua') self.map.drawcoastlines() #self.map.shadedrelief() # - Basemap V.1.0.2 onwards #self.map.etopo() # - Basemap V.1.0.2 onwards #self.map.drawcountries() #self.map.drawrivers() #self.map.drawstates() self.parallels = np.arange(0.0, 81.0, 10.0) self.map.drawparallels(self.parallels, labels=[False, True, True, False]) self.meridians = np.arange(10.0, 351.0, 20.0) self.map.drawmeridians(self.meridians, labels=[True, False, False, True]) # Include City Data # Comment out colour/relief overlays before running this #self.city_data() # Write the output to a graphic file self.current_figure.savefig("bcbm4_plot1") mpl.pyplot.close(self.current_figure) return(0) #------------------------------------------------------------------------------ def city_data(self): if (self.verbose): sys.stdout.write("BCBM4 : city_data ACTIVATED\n") # Dictionary city populations self.pop={'New York':8244910, 'Los Angeles':3819702, 'Chicago':2707120, 'Houston':2145146, 'Phoenix':1469471, 'Dallas':1223229, 'Jacksonville':827908, 'Indianapolis':827908, 'San Francisco':812826, 'Lawrence':876430} # Dictionary of city latitudes self.lat={'New York':40.6643, 'Los Angeles':34.0194, 'Chicago':41.8376, 'Houston':29.7805, 'Phoenix':33.5722, 'Dallas':32.7942, 'Jacksonville':30.3370, 'Indianapolis':39.7767, 'San Francisco':37.7750, 'Lawrence':38.9666} # Dictionary of city longitudes self.lon={'New York':73.9385, 'Los Angeles':118.4108, 'Chicago':87.6818, 'Houston':95.3863, 'Phoenix':112.0880, 'Dallas':96.7655, 'Jacksonville':81.6613, 'Indianapolis':86.1459, 'San Francisco':122.4183, 'Lawrence':95.2333} # Plot city population sizes # Add the city names self.max_size=80 for self.city in self.lon.keys(): self.x, self.y = self.map(-self.lon[self.city], self.lat[self.city]) self.map.scatter(self.x, self.y, self.max_size*self.pop[self.city]/self.pop['New York'], marker='o', color='r') plt.text(self.x+50000, self.y+50000, self.city) return(0) #------------------------------------------------------------------------------ #################################################### def main(argv=None): # When run as a script if argv is None: bcbm4_cmd_line = sys.argv[1:] bcbm4 = Bcbm4() bcbm4_ret = bcbm4.bcbm4(bcbm4_cmd_line) if __name__ == '__main__': sys.exit(main()) <file_sep>"""Circuitous LLC - An advanced circle analytics company. """ import math class Circle(object): """An advanced circle analytic toolkit""" version = "0.1" spam = 0.5 def __init__(self, radius): self.radius = radius def area(self): "Perform quadrature on this circle." return math.pi * self.radius ** 2 <file_sep>ipython nbconvert oo_python.ipynb --to slides --post serve --config slides_config.py <file_sep>## Exercise Solutions General polynomial function: def calc_poly(params, data): x = np.c_[[data**i for i in range(len(params))]] return np.dot(params, x) Microbiome exercise: metadata = pd.read_excel('data/microbiome/metadata.xls', sheetname='Sheet1') chunks = [] for i in range(9): this_file = pd.read_excel('data/microbiome/MID{0}.xls'.format(i+1), 'Sheet 1', index_col=0, header=None, names=['Taxon', 'Count']) this_file.columns = ['Count'] this_file.index.name = 'Taxon' for m in metadata.columns: this_file[m] = metadata.ix[i][m] chunks.append(this_file) pd.concat(chunks) Titanic proportions: titanic = pd.read_excel("data/titanic.xls", "titanic") titanic.groupby('sex')['survived'].mean() titanic.groupby(['pclass','sex'])['survived'].mean() titanic['agecat'] = pd.cut(titanic.age, [0, 13, 20, 64, 100], labels=['child', 'adolescent', 'adult', 'senior']) titanic.groupby(['agecat', 'pclass','sex'])['survived'].mean() Survivor KDE plots: surv = dict(list(titanic.groupby('survived'))) for s in surv: surv[s]['age'].dropna().plot(kind='kde', label=bool(s)*'survived' or 'died', grid=False) legend() xlim(0,100) OBP: baseball[['h','bb', 'hbp']].sum(axis=1).div( baseball[['bb', 'hbp','ab', 'sf']].sum(axis=1) ).order(ascending=False) Cervical dystonia estimation: norm_like = lambda theta, x: -np.log(norm.pdf(x, theta[0], theta[1])).sum() fmin(norm_like, np.array([1,2]), args=(cdystonia.twstrs[(cdystonia.obs==6) & (cdystonia.treat=='Placebo')],)) fmin(norm_like, np.array([1,2]), args=(cdystonia.twstrs[(cdystonia.obs==6) & (cdystonia.treat=='5000U')],)) Cervical dystonia bootstrapping: x = cdystonia.twstrs[(cdystonia.obs==6) & (cdystonia.treat=='Placebo') & (cdystonia.twstrs.notnull())].values n = len(x) s = [x[np.random.randint(0,n,n)].mean() for i in range(R)] placebo_mean = np.sum(s)/R s_sorted = np.sort(s) alpha = 0.05 s_sorted[[(R+1)*alpha/2, (R+1)*(1-alpha/2)]]<file_sep>#!/usr/bin/env python # Purpose : Python Boot Camp - Basemap Teaching Program 3. # Ensure that environment variable PYTHONUNBUFFERED=yes # This allows STDOUT and STDERR to both be logged in chronological order import sys # platform, args, run tools import os # platform, args, run tools import argparse # For parsing command line import datetime # For date/time processing import numpy as np import h5py import matplotlib as mpl mpl.use('Agg', warn=False) import matplotlib.pyplot as plt from matplotlib.pyplot import figure, show, subplots from mpl_toolkits.basemap import Basemap from mpl_toolkits.basemap import cm as bm_cm import matplotlib.cm as mpl_cm ######################################################################### # Command Line Parameters Class ######################################################################### class Bcbm3CP(): def bcbm3_cp(self, bcbm3_cmd_line): description = ("Python Boot Camp - Basemap Teaching Program 3") parser = argparse.ArgumentParser(description=description) help_text = ("Input file name") parser.add_argument('input_file_name', metavar='input_file_name', #type=string, help=help_text) help_text = ("Display processing messages to STDOUT " + "(DEFAULT=NO)") parser.add_argument("-v", "--verbose", default=False, help=help_text, action="store_true", dest="verbose") help_text = ("Run program in test mode " + "(DEFAULT=NO)") parser.add_argument("-t", "--test_mode", default=False, help=help_text, action="store_true", dest="test_mode") self.args = parser.parse_args(bcbm3_cmd_line) if (self.args.verbose): sys.stdout.write("BCBM3 : bcbm3_cmd_line = " + str(bcbm3_cmd_line) + "\n") # Return return(0) ######################################################################### # Main Program ######################################################################### class Bcbm3(): def bcbm3(self, bcbm3_cmd_line): # Start time self.start_time = datetime.datetime.today() # Parse input parameters from cmd line bcbm3_cp1 = Bcbm3CP() bcbm3_cp1_ret = bcbm3_cp1.bcbm3_cp(bcbm3_cmd_line) self.bcbm3_cmd_line = bcbm3_cmd_line if (len(self.bcbm3_cmd_line) == 0): self.bcbm3_cmd_line = " " if (bcbm3_cp1_ret): return(bcbm3_cp1_ret) self.verbose = bcbm3_cp1.args.verbose self.test_mode = bcbm3_cp1.args.test_mode self.input_file_name = bcbm3_cp1.args.input_file_name if (self.test_mode): self.timestamp = "Test Mode Date/Time Stamp" if (self.verbose): sys.stdout.write("BCBM3 : Running in test mode\n") sys.stdout.write("BCBM3 : sys.version = " + str(sys.version) + "\n") else: self.timestamp = datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S") if (self.verbose): sys.stdout.write("BCBM3 : Program started : " + str(self.start_time) + "\n") sys.stdout.write("BCBM3 : sys.version = " + str(sys.version) + "\n") if (self.verbose): sys.stdout.write("BCBM3 : sys.version = " + str(sys.version) + "\n") sys.stdout.write("BCBM3 : self.verbose = " + str(self.verbose) + "\n") sys.stdout.write("BCBM3 : self.test_mode = " + str(self.test_mode) + "\n") sys.stdout.write("BCBM3 : self.input_file_name = " + str(self.input_file_name) + "\n") # Call functions bcbm3_f11_ret = self.read_omps_data() if (bcbm3_f11_ret): return(bcbm3_f11_ret) bcbm3_f11_ret = self.make_mercator_projection() if (bcbm3_f11_ret): return(bcbm3_f11_ret) # End program self.end_time = datetime.datetime.today() self.run_time = self.end_time - self.start_time if (self.verbose): if (self.test_mode): pass else: sys.stdout.write("BCBM3 : Program ended : " + str(self.end_time) + "\n") sys.stdout.write("BCBM3 : Run time : " + str(self.run_time) + "\n") if (self.verbose): sys.stdout.write("BCBM3 : Program completed normally\n") return(0) # Define functions #------------------------------------------------------------------------------ def read_omps_data(self): if (self.verbose): sys.stdout.write("BCBM3 : read_omps_data ACTIVATED\n") # Open input HDF5 file self.input_file = h5py.File(self.input_file_name, "r") sys.stdout.write("BCBM3 : self.input_file = " + str(self.input_file) + "\n") self.o3 = self.input_file["ColumnAmountO3"] self.lat = self.input_file["Latitude"] self.lon = self.input_file["Longitude"] # Convert from Numpy objects to list arrays #self.o3 = self.o3[:,:] #self.lat = self.lat[:] #self.lon = self.lon[:] sys.stdout.write("BCBM3 : self.o3 = " + str(self.o3) + "\n") sys.stdout.write("BCBM3 : self.lat = " + str(self.lat) + "\n") sys.stdout.write("BCBM3 : self.lon = " + str(self.lon) + "\n") sys.stdout.write("BCBM3 : len(self.o3) = " + str(len(self.o3)) + "\n") sys.stdout.write("BCBM3 : len(self.lat) = " + str(len(self.lat)) + "\n") sys.stdout.write("BCBM3 : len(self.lon) = " + str(len(self.lon)) + "\n") return(0) #------------------------------------------------------------------------------ def make_mercator_projection(self): if (self.verbose): sys.stdout.write("BCBM3 : make_mercator_projection ACTIVATED\n") # Set up figure in Matplotlib self.current_figure = mpl.pyplot.figure(1, figsize=(14.0, 10.0)) self.current_figure.suptitle("Basemap - Mercator Map\n" + self.timestamp) self.current_figure.text(0.05, 0.95, "A Mercator Projection of the Earth") self.current_figure.subplots_adjust(left=0.05, right=0.95, top=0.80, bottom=0.05, wspace=0.2, hspace=0.4) self.current_plot = self.current_figure.add_subplot(1, 1, 1) # Plot figure self.map = Basemap(projection='merc', lat_0=0, lon_0=0, llcrnrlat=-80, urcrnrlat=80, llcrnrlon=-180, urcrnrlon=180, resolution='c') #self.map.drawmapboundary(fill_color='aqua') #self.map.fillcontinents(color='coral',lake_color='aqua') self.map.drawcoastlines() #self.map.drawcountries() #self.map.drawrivers() #self.map.drawstates() self.map.drawparallels(np.arange( -90.0, 90.0, 20.0)) self.map.drawmeridians(np.arange(-180.0, 181.0, 20.0)) # Write the output to a graphic file self.current_figure.savefig("bcbm3_plot1") mpl.pyplot.close(self.current_figure) # Plot colour scale and contour maps #self.plot_colour_scale() #self.plot_colour_contours() return(0) #------------------------------------------------------------------------------ def plot_colour_scale(self): if (self.verbose): sys.stdout.write("BCBM3 : plot_colour_scale ACTIVATED\n") # Set up mesh for plotting self.xmesh, self.ymesh = self.map(*np.meshgrid(self.lon, self.lat)) #sys.stdout.write("BCBM3 : self.xmesh = " + str(self.xmesh) + "\n") #sys.stdout.write("BCBM3 : self.ymesh = " + str(self.ymesh) + "\n") # Set colour map and levels self.colormap = mpl_cm.jet self.colormap.set_under(color='k', alpha=1.0) self.colormap.set_over(color='k', alpha=1.0) # Set colour levels self.plot_colormap_level_lower = 200 self.plot_colormap_level_upper = 525 self.plot_colormap_level_space = 25 self.color_levels = np.arange(self.plot_colormap_level_lower, self.plot_colormap_level_upper, self.plot_colormap_level_space) # Set plotting of data outside color map range to display in (default=)black # If this is not done then python will take the first and last colors of the colormap # and apply them to data outside the range. # IE.: It will effectively shorten the color scale by two colors # and then rescale everything else to fit that shortened scale. # Normalize : "clip" must be set to FALSE # "alpha=1.0" means use solid color values # "alpha" controls transparency, alpha=1=solid, alpha=0=transparent # 0<alpha<1, range of transparent values self.norm_range = mpl.colors.Normalize(vmin=self.plot_colormap_level_lower, vmax=(self.plot_colormap_level_upper-self.plot_colormap_level_space), clip=False) # Plot map self.map_contourf = self.map.contourf(self.xmesh, self.ymesh, self.o3, self.color_levels, colors=None, cmap=self.colormap, #norm=self.norm_range, extend="both") # Add colour scale to output self.current_colorbar = mpl.pyplot.colorbar(orientation="horizontal", fraction=0.05, pad=0.15, aspect=60.0, shrink=1.0, extend="both", spacing="uniform", ticks=self.color_levels, #ticks=None, format=None) self.current_colorbar.set_label("Ozone scale in Dobson Units", fontsize=20) # Write the output to a graphic file self.current_figure.savefig("bcbm3_plot2") mpl.pyplot.close(self.current_figure) return(0) #------------------------------------------------------------------------------ def plot_colour_contours(self): if (self.verbose): sys.stdout.write("BCBM3 : plot_colour_contours ACTIVATED\n") # Set up mesh for plotting self.xmesh, self.ymesh = self.map(*np.meshgrid(self.lon, self.lat)) #sys.stdout.write("BCBM3 : self.xmesh = " + str(self.xmesh) + "\n") #sys.stdout.write("BCBM3 : self.ymesh = " + str(self.ymesh) + "\n") # Set colour map and levels self.colormap = mpl_cm.jet self.colormap.set_under(color='k', alpha=1.0) self.colormap.set_over(color='k', alpha=1.0) # Set colour levels self.plot_colormap_level_lower = 200 self.plot_colormap_level_upper = 525 self.plot_colormap_level_space = 25 self.color_levels = np.arange(self.plot_colormap_level_lower, self.plot_colormap_level_upper, self.plot_colormap_level_space) # Set plotting of data outside color map range to display in (default=)black # If this is not done then python will take the first and last colors of the colormap # and apply them to data outside the range. # IE.: It will effectively shorten the color scale by two colors # and then rescale everything else to fit that shortened scale. # Normalize : "clip" must be set to FALSE # "alpha=1.0" means use solid color values # "alpha" controls transparency, alpha=1=solid, alpha=0=transparent # 0<alpha<1, range of transparent values self.norm_range = mpl.colors.Normalize(vmin=self.plot_colormap_level_lower, vmax=(self.plot_colormap_level_upper-self.plot_colormap_level_space), clip=False) # Plot map self.map_contour = self.map.contour(self.xmesh, self.ymesh, self.o3, self.color_levels, colors=None, cmap=self.colormap, #norm=self.norm_range, extend="both") # Label the contours self.map_contour_label = mpl.pyplot.clabel(self.map_contour, self.color_levels, inline=1, fontsize=9, fmt='%1.0f',) # Write the output to a graphic file self.current_figure.savefig("bcbm3_plot3") mpl.pyplot.close(self.current_figure) return(0) #------------------------------------------------------------------------------ #################################################### def main(argv=None): # When run as a script if argv is None: bcbm3_cmd_line = sys.argv[1:] bcbm3 = Bcbm3() bcbm3_ret = bcbm3.bcbm3(bcbm3_cmd_line) if __name__ == '__main__': sys.exit(main()) <file_sep>#!/usr/bin/env python # Purpose : Python Boot Camp - Basemap Teaching Program 2. # Ensure that environment variable PYTHONUNBUFFERED=yes # This allows STDOUT and STDERR to both be logged in chronological order import sys # platform, args, run tools import os # platform, args, run tools import argparse # For parsing command line import datetime # For date/time processing import numpy as np import h5py import matplotlib as mpl mpl.use('Agg', warn=False) import matplotlib.pyplot as plt from matplotlib.pyplot import figure, show, subplots from mpl_toolkits.basemap import Basemap from mpl_toolkits.basemap import cm as bm_cm import matplotlib.cm as mpl_cm ################################################ ######################################################################### # Command Line Parameters Class ######################################################################### class Bcbm2CP(): def bcbm2_cp(self, bcbm2_cmd_line): description = ("Python Boot Camp - Basemap Teaching Program 2") parser = argparse.ArgumentParser(description=description) help_text = ("Input file name") parser.add_argument('input_file_name', metavar='input_file_name', #type=string, help=help_text) help_text = ("Display processing messages to STDOUT " + "(DEFAULT=NO)") parser.add_argument("-v", "--verbose", default=False, help=help_text, action="store_true", dest="verbose") help_text = ("Run program in test mode " + "(DEFAULT=NO)") parser.add_argument("-t", "--test_mode", default=False, help=help_text, action="store_true", dest="test_mode") self.args = parser.parse_args(bcbm2_cmd_line) if (self.args.verbose): sys.stdout.write("BCBM2 : bcbm2_cmd_line = " + str(bcbm2_cmd_line) + "\n") # Return return(0) ######################################################################### # Main Program ######################################################################### class Bcbm2(): def bcbm2(self, bcbm2_cmd_line): # Start time self.start_time = datetime.datetime.today() # Parse input parameters from cmd line bcbm2_cp1 = Bcbm2CP() bcbm2_cp1_ret = bcbm2_cp1.bcbm2_cp(bcbm2_cmd_line) self.bcbm2_cmd_line = bcbm2_cmd_line if (len(self.bcbm2_cmd_line) == 0): self.bcbm2_cmd_line = " " if (bcbm2_cp1_ret): return(bcbm2_cp1_ret) self.verbose = bcbm2_cp1.args.verbose self.test_mode = bcbm2_cp1.args.test_mode self.input_file_name = bcbm2_cp1.args.input_file_name if (self.test_mode): self.timestamp = "Test Mode Date/Time Stamp" if (self.verbose): sys.stdout.write("BCBM2 : Running in test mode\n") sys.stdout.write("BCBM2 : sys.version = " + str(sys.version) + "\n") else: self.timestamp = datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S") if (self.verbose): sys.stdout.write("BCBM2 : Program started : " + str(self.start_time) + "\n") sys.stdout.write("BCBM2 : sys.version = " + str(sys.version) + "\n") if (self.verbose): sys.stdout.write("BCBM2 : sys.version = " + str(sys.version) + "\n") sys.stdout.write("BCBM2 : self.verbose = " + str(self.verbose) + "\n") sys.stdout.write("BCBM2 : self.test_mode = " + str(self.test_mode) + "\n") sys.stdout.write("BCBM2 : self.input_file_name = " + str(self.input_file_name) + "\n") # Call functions bcbm2_f11_ret = self.make_mercator_projection() if (bcbm2_f11_ret): return(bcbm2_f11_ret) # End program self.end_time = datetime.datetime.today() self.run_time = self.end_time - self.start_time if (self.verbose): if (self.test_mode): pass else: sys.stdout.write("BCBM2 : Program ended : " + str(self.end_time) + "\n") sys.stdout.write("BCBM2 : Run time : " + str(self.run_time) + "\n") if (self.verbose): sys.stdout.write("BCBM2 : Program completed normally\n") return(0) # Define functions #------------------------------------------------------------------------------ def make_mercator_projection(self): if (self.verbose): sys.stdout.write("BCBM2 : make_mercator_projection ACTIVATED\n") # Set up figure in Matplotlib self.current_figure = mpl.pyplot.figure(1, figsize=(14.0, 10.0)) self.current_figure.suptitle("Basemap - Mercator Map\n" + self.timestamp) self.current_figure.text(0.05, 0.95, "A Mercator Projection of the Earth") self.current_figure.subplots_adjust(left=0.05, right=0.95, top=0.80, bottom=0.05, wspace=0.2, hspace=0.4) self.current_plot = self.current_figure.add_subplot(1, 1, 1) # Plot figure self.map = Basemap(projection='merc', lat_0=0, lon_0=0, llcrnrlat=-80, urcrnrlat=80, llcrnrlon=-180, urcrnrlon=180, resolution='c') #self.map.drawmapboundary(fill_color='aqua') #self.map.fillcontinents(color='coral',lake_color='aqua') self.map.drawcoastlines() #self.map.drawcountries() #self.map.drawrivers() #self.map.drawstates() self.map.drawparallels(np.arange( -90.0, 90.0, 20.0)) self.map.drawmeridians(np.arange(-180.0, 181.0, 20.0)) # Display day and night shading #self.date = datetime.datetime.utcnow() #self.map_nightshade = self.map.nightshade(self.date) # Write the output to a graphic file self.current_figure.savefig("bcbm2_plot1") mpl.pyplot.close(self.current_figure) # Read data from input file #self.read_omps_data() # Plot satellite tracks #self.plot_satellite_tracks_dots() #self.plot_satellite_tracks_lines() return(0) #------------------------------------------------------------------------------ def read_omps_data(self): if (self.verbose): sys.stdout.write("BCBM2 : read_omps_data ACTIVATED\n") # Open input HDF5 file self.input_file = h5py.File(self.input_file_name, "r") sys.stdout.write("BCBM2 : self.input_file = " + str(self.input_file) + "\n") self.o3 = self.input_file["DataFields/O3CombinedValue"] self.lats = self.input_file["GeolocationFields/Latitude"] self.lons = self.input_file["GeolocationFields/Longitude"] self.orbit_num = self.input_file["GeolocationFields/OrbitNumber"] # Convert from Numpy objects to list arrays # Select only centre slit data self.lat_cs = self.lats[:,1] self.lon_cs = self.lons[:,1] self.orbit_num_cs = self.orbit_num[:,1] sys.stdout.write("BCBM2 : self.lat_cs = " + str(self.lat_cs) + "\n") sys.stdout.write("BCBM2 : self.lon_cs = " + str(self.lon_cs) + "\n") sys.stdout.write("BCBM2 : self.orbit_num_cs = " + str(self.orbit_num_cs) + "\n") return(0) #------------------------------------------------------------------------------ def plot_satellite_tracks_dots(self): if (self.verbose): sys.stdout.write("BCBM2 : plot_satellite_tracks_dots ACTIVATED\n") # Set up mesh for plotting self.xmesh, self.ymesh = self.map(self.lon_cs, self.lat_cs) self.map_scatter = self.map.scatter(self.xmesh, self.ymesh, 1, marker='o', color='r', label="OMPS" ) # Write the output to a graphic file self.current_figure.savefig("bcbm2_plot2") mpl.pyplot.close(self.current_figure) return(0) #------------------------------------------------------------------------------ def plot_satellite_tracks_lines(self): if (self.verbose): sys.stdout.write("BCBM2 : plot_satellite_tracks_lines ACTIVATED\n") # Make unique list of orbit numbers self.orbit_num_cs_unique = np.unique(self.orbit_num_cs) sys.stdout.write("BCBM2 : self.orbit_num_cs_unique = " + str(self.orbit_num_cs_unique) + "\n") # Loop on unique orbit numbers for self.orbit_num in self.orbit_num_cs_unique: #sys.stdout.write("BCBM2 : self.orbit_num = " + str(self.orbit_num) + "\n") # Find the data for just that orbit self.lat_cs_orbit = self.lat_cs[np.where(self.orbit_num_cs == self.orbit_num)] self.lon_cs_orbit = self.lon_cs[np.where(self.orbit_num_cs == self.orbit_num)] #sys.stdout.write("BCBM2 : len(self.lat_cs_orbit) = " + str(len(self.lat_cs_orbit)) + "\n") #sys.stdout.write("BCBM2 : len(self.lon_cs_orbit) = " + str(len(self.lon_cs_orbit)) + "\n") # Set up mesh for plotting self.xmesh_orbit, self.ymesh_orbit = self.map(self.lon_cs_orbit, self.lat_cs_orbit) self.map_plot = self.map.plot(self.xmesh_orbit, self.ymesh_orbit, "-", #marker='o', color='r', label="OMPS" ) # Write the output to a graphic file self.current_figure.savefig("bcbm2_plot3") mpl.pyplot.close(self.current_figure) return(0) #------------------------------------------------------------------------------ #################################################### def main(argv=None): # When run as a script if argv is None: bcbm2_cmd_line = sys.argv[1:] bcbm2 = Bcbm2() bcbm2_ret = bcbm2.bcbm2(bcbm2_cmd_line) if __name__ == '__main__': sys.exit(main()) <file_sep>## solutions to the breakout #1 (Day 1) sent = "" while True: newword = raw_input("Please enter a word in the sentence (enter . ! or ? to end.): ") if newword == "." or newword == "?" or newword == "!": if len(sent) > 0: # get rid of the nasty space we added in sent = sent[:-1] sent += newword break sent += newword + " " print "...currently: " + sent print "--->" + sent <file_sep>c = get_config() c.Exporter.template_file = 'default_transition' <file_sep>from circle import Circle class Tire(Circle): "Tires are circles with a corrected perimeter." def perimeter(self): "Circumference corrected for the tire width." return Circle.perimeter(self) * 1.25 t = Tire(22) print 'A tire of radius', t.radius print 'has an inner area of', t.area() print 'and an odometer corrected perimeter of', print t.perimeter() print <file_sep># Tutorial from circle import Circle print 'Circuitous version', Circle.version c = Circle(10) print 'A circle of radius', c.radius print 'has an area of', c.area() print <file_sep>from random import random, seed from circle import Circle seed(8675309) print 'Using Circuitous(tm) version', Circle.version n = 10 circles = [Circle(random()) for i in xrange(n)] print 'The average area of', n, 'random circles' avg = sum([c.area() for c in circles]) / n print 'is %1.f' % avg print <file_sep># Statistical Data Analysis in Python Introductory Tutorial, SciPy 2013, 25 June 2013 ***<NAME> - Vanderbilt University School of Medicine*** <NAME> is an Assistant Professor in the Department of Biostatistics at the Vanderbilt University School of Medicine. He specializes in computational statistics, Bayesian methods, meta-analysis, and applied decision analysis. He originally hails from Vancouver, BC and received his Ph.D. from the University of Georgia. ## Description This tutorial will introduce the use of Python for statistical data analysis, using data stored as Pandas DataFrame objects. Much of the work involved in analyzing data resides in importing, cleaning and transforming data in preparation for analysis. Therefore, the first half of the course is comprised of a 2-part overview of basic and intermediate Pandas usage that will show how to effectively manipulate datasets in memory. This includes tasks like indexing, alignment, join/merge methods, date/time types, and handling of missing data. Next, we will cover plotting and visualization using Pandas and Matplotlib, focusing on creating effective visual representations of your data, while avoiding common pitfalls. Finally, participants will be introduced to methods for statistical data modeling using some of the advanced functions in Numpy, Scipy and Pandas. This will include fitting your data to probability distributions, estimating relationships among variables using linear and non-linear models, and a brief introduction to bootstrapping methods. Each section of the tutorial will involve hands-on manipulation and analysis of sample datasets, to be provided to attendees in advance. The target audience for the tutorial includes all new Python users, though we recommend that users also attend the NumPy and IPython session in the introductory track. ### Student Instructions For students familiar with Git, you may simply clone this repository to obtain all the materials (iPython notebooks and data) for the tutorial. Alternatively, you may [download a zip file containing the materials](https://github.com/fonnesbeck/statistical-analysis-python-tutorial/archive/master.zip). A third option is to simply view static notebooks by clicking on the titles of each section below. ## Outline ### [Introduction to Pandas][1] * Importing data * Series and DataFrame objects * Indexing, data selection and subsetting * Hierarchical indexing * Reading and writing files * Sorting and ranking * Missing data * Data summarization ### [Data Wrangling with Pandas][2] * Date/time types * Merging and joining DataFrame objects * Concatenation * Reshaping DataFrame objects * Pivoting * Data transformation * Permutation and sampling * Data aggregation and GroupBy operations ### [Plotting and Visualization][3] * Plotting in Pandas vs Matplotlib * Bar plots * Histograms * Box plots * Grouped plots * Scatterplots * Trellis plots ### [Statistical Data Modeling][4] * Statistical modeling * Fitting data to probability distributions * Fitting regression models * Model selection * Bootstrapping ## Required Packages * Python 2.7 or higher (including Python 3) * pandas >= 0.11.1 and its dependencies * NumPy >= 1.6.1 * matplotlib >= 1.0.0 * pytz * IPython >= 0.12 * pyzmq * tornado **Optional**: statsmodels, xlrd and openpyxl For students running the latest version of Mac OS X (10.8), the easiest way to obtain all the packages is to install the [Scipy Superpack](http://bit.ly/scipy_superpack) which works with Python 2.7.2 that ships with OS X. Otherwise, another easy way to install all the necessary packages is to use Continuum Analytics' [Anaconda](http://docs.continuum.io/anaconda/install.html). ## Statistical Reading List [The Ecological Detective: Confronting Models with Data](http://www.amazon.com/Ecological-Detective-Confronting-Models-Data/dp/0691034974/ref=sr_1_1?s=books&ie=UTF8&qid=1372250186&sr=1-1&keywords=ecological+detective), <NAME> and <NAME> Though targeted to ecologists, Mangel and Hilborn identify key methods that scientists can use to build useful and credible models for their data. They don't shy away from the math, but the book is very readable and example-laden. [Data Analysis Using Regression and Multilevel/Hierarchical Models](http://www.amazon.com/Analysis-Regression-Multilevel-Hierarchical-Models/dp/052168689X/ref=sr_1_1?s=books&ie=UTF8&qid=1372250274&sr=1-1&keywords=gelman), <NAME> and <NAME> The go-to reference for applied hierarchical modeling. [The Elements of Statistical Learning](http://www-stat.stanford.edu/~tibs/ElemStatLearn/), <NAME> and Friedman A comprehensive machine learning guide for statisticians. [A First Course in Bayesian Statistical Methods](http://www.amazon.com/Bayesian-Statistical-Methods-Springer-Statistics/dp/1441928286/ref=sr_1_24?ie=UTF8&qid=1372250835&sr=8-24&keywords=bayesian), <NAME> An excellent, approachable book to get started with Bayesian methods. [Regression Modeling Strategies](http://www.amazon.com/Regression-Modeling-Strategies-Applications-Statistics/dp/1441929185/ref=sr_1_1?s=books&ie=UTF8&qid=1372250898&sr=1-1&keywords=harrell+regression), <NAME> <NAME>'s bag of tricks for regression modeling. I pull this off the shelf every week. [1]: http://nbviewer.ipython.org/urls/gist.github.com/fonnesbeck/5850375/raw/c18cfcd9580d382cb6d14e4708aab33a0916ff3e/1.+Introduction+to+Pandas.ipynb "Introduction to Pandas" [2]: http://nbviewer.ipython.org/urls/gist.github.com/fonnesbeck/5850413/raw/3a9406c73365480bc58d5e75bc80f7962243ba17/2.+Data+Wrangling+with+Pandas.ipynb "Data wrangling with Pandas" [3]: http://nbviewer.ipython.org/urls/gist.github.com/fonnesbeck/5850463/raw/a29d9ffb863bfab09ff6c1fc853e1d5bf69fe3e4/3.+Plotting+and+Visualization.ipynb "Plotting and visualization" [4]: http://nbviewer.ipython.org/urls/gist.github.com/fonnesbeck/5850483/raw/5e049b2fdd1c83ae386aa3205d3fc50a1a05e5b0/4.+Statistical+Data+Modeling.ipynb "Statistical data modeling"<file_sep>from circle import Circle cuts = [0.1, 0.7, 0.8] circles = [Circle(r) for r in cuts] for c in circles: print 'A circlet with a radius of', c.radius print 'has a perimeter of', c.perimeter() print 'and a cold area of', c.area() c.radius *= 1.1 print 'and a warm area of', c.area() print <file_sep>#!/usr/bin/env python def divide_one_by(divisor): return 1/divisor if __name__ == '__main__': divide_one_by(0) <file_sep>#!/usr/bin/env python # Purpose : Skeleton Python program. # Ensure that environment variable PYTHONUNBUFFERED=yes # This allows STDOUT and STDERR to both be logged in chronological order import sys # platform, args, run tools import os # platform, args, run tools import argparse # For parsing command line import datetime # For date/time processing ######################################################################### # Command Line Parameters Class ######################################################################### class PyskelCP(): def pyskel_cp(self, pyskel_cmd_line): description = ("Skeleton Python program") parser = argparse.ArgumentParser(description=description) help_text = ("Input file name") parser.add_argument('input_file_name', metavar='input_file_name', #type=string, help=help_text) help_text = ("Display processing messages to STDOUT " + "(DEFAULT=NO)") parser.add_argument("-v", "--verbose", default=False, help=help_text, action="store_true", dest="verbose") help_text = ("Run program in test mode " + "(DEFAULT=NO)") parser.add_argument("-t", "--test_mode", default=False, help=help_text, action="store_true", dest="test_mode") self.args = parser.parse_args(pyskel_cmd_line) if (self.args.verbose): sys.stdout.write("PYSKEL : pyskel_cmd_line = " + str(pyskel_cmd_line) + "\n") # Return return(0) ######################################################################### # Main Program ######################################################################### class Pyskel(): def pyskel(self, pyskel_cmd_line): # Start time self.start_time = datetime.datetime.today() # Parse input parameters from cmd line pyskel_cp1 = PyskelCP() pyskel_cp1_ret = pyskel_cp1.pyskel_cp(pyskel_cmd_line) self.pyskel_cmd_line = pyskel_cmd_line if (len(self.pyskel_cmd_line) == 0): self.pyskel_cmd_line = " " if (pyskel_cp1_ret): return(pyskel_cp1_ret) self.verbose = pyskel_cp1.args.verbose self.test_mode = pyskel_cp1.args.test_mode self.input_file_name = pyskel_cp1.args.input_file_name if (self.test_mode): self.timestamp = "Test Mode Date/Time Stamp" if (self.verbose): sys.stdout.write("PYSKEL : Running in test mode\n") sys.stdout.write("PYSKEL : sys.version = " + str(sys.version) + "\n") else: self.timestamp = datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S") if (self.verbose): sys.stdout.write("PYSKEL : Program started : " + str(self.start_time) + "\n") sys.stdout.write("PYSKEL : sys.version = " + str(sys.version) + "\n") if (self.verbose): sys.stdout.write("PYSKEL : sys.version = " + str(sys.version) + "\n") sys.stdout.write("PYSKEL : self.verbose = " + str(self.verbose) + "\n") sys.stdout.write("PYSKEL : self.test_mode = " + str(self.test_mode) + "\n") sys.stdout.write("PYSKEL : self.input_file_name = " + str(self.input_file_name) + "\n") # Call functions pyskel_f11_ret = self.function1() if (pyskel_f11_ret): return(pyskel_f11_ret) pyskel_f21_ret = self.function2() if (pyskel_f21_ret): return(pyskel_f21_ret) # End program self.end_time = datetime.datetime.today() self.run_time = self.end_time - self.start_time if (self.verbose): if (self.test_mode): pass else: sys.stdout.write("PYSKEL : Program ended : " + str(self.end_time) + "\n") sys.stdout.write("PYSKEL : Run time : " + str(self.run_time) + "\n") if (self.verbose): sys.stdout.write("PYSKEL : Program completed normally\n") return(0) # Define functions #------------------------------------------------------------------------------ def function1(self): if (self.verbose): sys.stdout.write("PYSKEL : function1 ACTIVATED\n") return(0) #------------------------------------------------------------------------------ def function2(self): if (self.verbose): sys.stdout.write("PYSKEL : function2 ACTIVATED\n") return(0) #################################################### def main(argv=None): # When run as a script if argv is None: pyskel_cmd_line = sys.argv[1:] pysk1 = Pyskel() pysk1_ret = pysk1.pyskel(pyskel_cmd_line) if __name__ == '__main__': sys.exit(main()) <file_sep># gsfcpyboot Goddard Python Bootcamp This is the repository for all of the notebooks, code, and other documents for the GSFC Python Bootcamp. Click on the 'wiki' link for the current agenda. Click on the 'issues' if you're struggling with something to see if you can find help. Check the INSTALLATION INSTRUCTION: http://asd.gsfc.nasa.gov/conferences/pythonbootcamp/2015/install/ In particular, the ANACONDA installation check and required packages. Test<file_sep>#!/usr/bin/env python # Purpose : Python Boot Camp - Basemap Teaching Program 1. # Ensure that environment variable PYTHONUNBUFFERED=yes # This allows STDOUT and STDERR to both be logged in chronological order import sys # platform, args, run tools import os # platform, args, run tools import argparse # For parsing command line import datetime # For date/time processing import numpy as np import h5py import matplotlib as mpl mpl.use('Agg', warn=False) import matplotlib.pyplot as plt from matplotlib.pyplot import figure, show, subplots from mpl_toolkits.basemap import Basemap from mpl_toolkits.basemap import cm as bm_cm import matplotlib.cm as mpl_cm ######################################################################### # Command Line Parameters Class ######################################################################### class Bcbm1CP(): def bcbm1_cp(self, bcbm1_cmd_line): description = ("Python Boot Camp - Basemap Teaching Program 1") parser = argparse.ArgumentParser(description=description) help_text = ("Display processing messages to STDOUT " + "(DEFAULT=NO)") parser.add_argument("-v", "--verbose", default=False, help=help_text, action="store_true", dest="verbose") help_text = ("Run program in test mode " + "(DEFAULT=NO)") parser.add_argument("-t", "--test_mode", default=False, help=help_text, action="store_true", dest="test_mode") self.args = parser.parse_args(bcbm1_cmd_line) if (self.args.verbose): sys.stdout.write("BCBM1 : bcbm1_cmd_line = " + str(bcbm1_cmd_line) + "\n") # Return return(0) ######################################################################### # Main Program ######################################################################### class Bcbm1(): def bcbm1(self, bcbm1_cmd_line): # Start time self.start_time = datetime.datetime.today() # Parse input parameters from cmd line bcbm1_cp1 = Bcbm1CP() bcbm1_cp1_ret = bcbm1_cp1.bcbm1_cp(bcbm1_cmd_line) self.bcbm1_cmd_line = bcbm1_cmd_line if (len(self.bcbm1_cmd_line) == 0): self.bcbm1_cmd_line = " " if (bcbm1_cp1_ret): return(bcbm1_cp1_ret) self.verbose = bcbm1_cp1.args.verbose self.test_mode = bcbm1_cp1.args.test_mode if (self.test_mode): self.timestamp = "Test Mode Date/Time Stamp" if (self.verbose): sys.stdout.write("BCBM1 : Running in test mode\n") sys.stdout.write("BCBM1 : sys.version = " + str(sys.version) + "\n") else: self.timestamp = datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S") if (self.verbose): sys.stdout.write("BCBM1 : Program started : " + str(self.start_time) + "\n") sys.stdout.write("BCBM1 : sys.version = " + str(sys.version) + "\n") if (self.verbose): sys.stdout.write("BCBM1 : sys.version = " + str(sys.version) + "\n") sys.stdout.write("BCBM1 : self.verbose = " + str(self.verbose) + "\n") sys.stdout.write("BCBM1 : self.test_mode = " + str(self.test_mode) + "\n") # Call functions bcbm1_f11_ret = self.display_map1() if (bcbm1_f11_ret): return(bcbm1_f11_ret) #bcbm1_f21_ret = self.display_map2() #if (bcbm1_f21_ret): # return(bcbm1_f21_ret) #bcbm1_f31_ret = self.display_map3() #if (bcbm1_f31_ret): # return(bcbm1_f31_ret) # End program self.end_time = datetime.datetime.today() self.run_time = self.end_time - self.start_time if (self.verbose): if (self.test_mode): pass else: sys.stdout.write("BCBM1 : Program ended : " + str(self.end_time) + "\n") sys.stdout.write("BCBM1 : Run time : " + str(self.run_time) + "\n") if (self.verbose): sys.stdout.write("BCBM1 : Program completed normally\n") return(0) # Define functions #------------------------------------------------------------------------------ def display_map1(self): if (self.verbose): sys.stdout.write("BCBM1 : display_map1 ACTIVATED\n") # Set up figure in Matplotlib self.current_figure = mpl.pyplot.figure(1, figsize=(14.0, 10.0)) self.current_figure.suptitle("Basemap - First Map\n" + self.timestamp) self.current_figure.text(0.05, 0.95, "Mollweide Projection") self.current_figure.subplots_adjust(left=0.05, right=0.95, top=0.80, bottom=0.05, wspace=0.2, hspace=0.4) self.current_plot = self.current_figure.add_subplot(1, 1, 1) # Plot figure self.map = Basemap(projection='moll', lon_0=0, #lat_0=0, resolution='c') #self.map.drawmapboundary(fill_color='aqua') #self.map.fillcontinents(color='coral',lake_color='aqua') self.map.drawcoastlines() #self.map.drawcountries() #self.map.drawrivers() #self.map.drawstates() self.map.drawparallels(np.arange( -90.0, 90.0, 20.0)) self.map.drawmeridians(np.arange(-180.0, 181.0, 20.0)) # Write the output to a graphic file self.current_figure.savefig("bcbm1_plot1") mpl.pyplot.close(self.current_figure) return(0) #------------------------------------------------------------------------------ def display_map2(self): if (self.verbose): sys.stdout.write("BCBM1 : display_map2 ACTIVATED\n") # Set up figure in Matplotlib self.current_figure = mpl.pyplot.figure(1, figsize=(14.0, 10.0)) self.current_figure.suptitle("Basemap - Second Map\n" + self.timestamp) self.current_figure.text(0.05, 0.95, "Robinson Projection - Blue Marble") self.current_figure.subplots_adjust(left=0.05, right=0.95, top=0.80, bottom=0.05, wspace=0.2, hspace=0.4) self.current_plot = self.current_figure.add_subplot(1, 1, 1) # Plot figure self.map = Basemap(projection='robin', lon_0=0, lat_0=0, resolution='c') #self.map.drawcoastlines() #self.map.drawcountries() #self.map.drawrivers() #self.map.drawstates() self.map.drawparallels(np.arange( -90.0, 90.0, 20.0)) self.map.drawmeridians(np.arange(-180.0, 181.0, 20.0)) self.map.bluemarble() # Known bug here - may appear upside down # Write the output to a graphic file self.current_figure.savefig("bcbm1_plot2") mpl.pyplot.close(self.current_figure) return(0) #------------------------------------------------------------------------------ def display_map3(self): if (self.verbose): sys.stdout.write("BCBM1 : display_map3 ACTIVATED\n") # Set up figure in Matplotlib self.current_figure = mpl.pyplot.figure(1, figsize=(14.0, 10.0)) self.current_figure.suptitle("Basemap - Third Map\n" + self.timestamp) self.current_figure.text(0.05, 0.95, "Near-Sided Perspective Projection - Different Colours") self.current_figure.subplots_adjust(left=0.05, right=0.95, top=0.80, bottom=0.05, wspace=0.2, hspace=0.4) self.current_plot = self.current_figure.add_subplot(1, 1, 1) # Plot figure self.map = Basemap(projection='nsper', lon_0=0, lat_0=0, resolution='c') #self.map.drawmapboundary(fill_color='#7777ff') #self.map.fillcontinents(color='#ddaa66',lake_color='#7777ff') self.map.drawlsmask(land_color = "#ddaa66", ocean_color="#7777ff") #self.map.drawcoastlines() #self.map.drawcountries() #self.map.drawrivers() #self.map.drawstates() self.map.drawparallels(np.arange( -90.0, 90.0, 20.0)) self.map.drawmeridians(np.arange(-180.0, 181.0, 20.0)) # Display day and night shading #self.date = datetime.datetime.utcnow() #self.map_nightshade = self.map.nightshade(self.date) # Write the output to a graphic file self.current_figure.savefig("bcbm1_plot3") mpl.pyplot.close(self.current_figure) return(0) #------------------------------------------------------------------------------ #################################################### def main(argv=None): # When run as a script if argv is None: bcbm1_cmd_line = sys.argv[1:] bcbm1 = Bcbm1() bcbm1_ret = bcbm1.bcbm1(bcbm1_cmd_line) if __name__ == '__main__': sys.exit(main()) <file_sep>faren = raw_input("Enter the temperature in Fahrenheit): ") faren = float(faren) # The calculation on the right gets saved to the variable on the left cel = 5./9. * (faren - 32.) print "The temperature in Celcius is " + str(cel) + " degrees."<file_sep>#!/usr/bin/env python # Purpose : Python Boot Camp - Basemap Test Program. # Ensure that environment variable PYTHONUNBUFFERED=yes # This allows STDOUT and STDERR to both be logged in chronological order import sys # platform, args, run tools import os # platform, args, run tools import argparse # For parsing command line import datetime # For date/time processing import numpy as np import h5py import matplotlib as mpl mpl.use('Agg', warn=False) import matplotlib.pyplot as plt from matplotlib.pyplot import figure, show, subplots from mpl_toolkits.basemap import Basemap from mpl_toolkits.basemap import cm as bm_cm import matplotlib.cm as mpl_cm ######################################################################### # Command Line Parameters Class ######################################################################### class Bcbm_testCP(): def bcbm_test_cp(self, bcbm_test_cmd_line): description = ("Python Boot Camp - Basemap Test Program") parser = argparse.ArgumentParser(description=description) help_text = ("Display processing messages to STDOUT " + "(DEFAULT=NO)") parser.add_argument("-v", "--verbose", default=False, help=help_text, action="store_true", dest="verbose") help_text = ("Run program in test mode " + "(DEFAULT=NO)") parser.add_argument("-t", "--test_mode", default=False, help=help_text, action="store_true", dest="test_mode") self.args = parser.parse_args(bcbm_test_cmd_line) if (self.args.verbose): sys.stdout.write("BCBM_TEST : bcbm_test_cmd_line = " + str(bcbm_test_cmd_line) + "\n") # Return return(0) ######################################################################### # Main Program ######################################################################### class Bcbm_test(): def bcbm_test(self, bcbm_test_cmd_line): # Start time self.start_time = datetime.datetime.today() # Parse input parameters from cmd line bcbm_test_cp1 = Bcbm_testCP() bcbm_test_cp1_ret = bcbm_test_cp1.bcbm_test_cp(bcbm_test_cmd_line) self.bcbm_test_cmd_line = bcbm_test_cmd_line if (len(self.bcbm_test_cmd_line) == 0): self.bcbm_test_cmd_line = " " if (bcbm_test_cp1_ret): return(bcbm_test_cp1_ret) self.verbose = bcbm_test_cp1.args.verbose self.test_mode = bcbm_test_cp1.args.test_mode if (self.test_mode): self.timestamp = "Test Mode Date/Time Stamp" if (self.verbose): sys.stdout.write("BCBM_TEST : Running in test mode\n") sys.stdout.write("BCBM_TEST : sys.version = " + str(sys.version) + "\n") else: self.timestamp = datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S") if (self.verbose): sys.stdout.write("BCBM_TEST : Program started : " + str(self.start_time) + "\n") sys.stdout.write("BCBM_TEST : sys.version = " + str(sys.version) + "\n") if (self.verbose): sys.stdout.write("BCBM_TEST : sys.version = " + str(sys.version) + "\n") sys.stdout.write("BCBM_TEST : self.verbose = " + str(self.verbose) + "\n") sys.stdout.write("BCBM_TEST : self.test_mode = " + str(self.test_mode) + "\n") # Call functions bcbm_test_f11_ret = self.display_map1() if (bcbm_test_f11_ret): return(bcbm_test_f11_ret) # End program self.end_time = datetime.datetime.today() self.run_time = self.end_time - self.start_time if (self.verbose): if (self.test_mode): pass else: sys.stdout.write("BCBM_TEST : Program ended : " + str(self.end_time) + "\n") sys.stdout.write("BCBM_TEST : Run time : " + str(self.run_time) + "\n") if (self.verbose): sys.stdout.write("BCBM_TEST : Program completed normally\n") return(0) # Define functions #------------------------------------------------------------------------------ def display_map1(self): if (self.verbose): sys.stdout.write("BCBM_TEST : display_map1 ACTIVATED\n") # Set up figure in Matplotlib self.current_figure = mpl.pyplot.figure(1, figsize=(14.0, 10.0)) self.current_figure.suptitle("Basemap - First Map\n" + self.timestamp) self.current_figure.text(0.05, 0.95, "Mollweide Projection") self.current_figure.subplots_adjust(left=0.05, right=0.95, top=0.80, bottom=0.05, wspace=0.2, hspace=0.4) self.current_plot = self.current_figure.add_subplot(1, 1, 1) # Plot figure self.map = Basemap(projection='moll', lon_0=0, #lat_0=0, resolution='c') self.map.drawcoastlines() self.map.drawparallels(np.arange( -90.0, 90.0, 20.0)) self.map.drawmeridians(np.arange(-180.0, 181.0, 20.0)) # Write the output to a graphic file self.current_figure.savefig("bcbm_test_plot1") mpl.pyplot.close(self.current_figure) return(0) #------------------------------------------------------------------------------ #################################################### def main(argv=None): # When run as a script if argv is None: bcbm_test_cmd_line = sys.argv[1:] bcbm_test = Bcbm_test() bcbm_test_ret = bcbm_test.bcbm_test(bcbm_test_cmd_line) if __name__ == '__main__': sys.exit(main())
d38e06d6c621ceef6e7f52399abb2baf05868e64
[ "Markdown", "Python", "Shell" ]
19
Python
kialio/gsfcpyboot
993143b7ef7a604445b7b4a81ddc2f4bde9e2793
b21680bb7f4a773f55cf2e5cd023c973e9a7909d
refs/heads/main
<file_sep># Primes program to find many prime numbers Enter an integer n, find several prime numbers between 1 and n (including n) <file_sep>def Finding(Prime): #statement for finding primes x = 2 #x start value while x <= Prime/2 : #term for Prime if Prime % x == 0 : #checking it's prime or not return False #false x += 1 #x + 1 return True #true n = int(input()) #input n's value Prime = 2 #start Prime Value result = 0 #Start result value while Prime <= n : #term for get prime if Finding(Prime) : #get in to statement result += 1 #result + 1 Prime += 1 #Prime + 1 print(result) #print out the result
4002e5d1711b7c6a0fbdc4e7428600114843b96f
[ "Markdown", "Python" ]
2
Markdown
MarvinZhong/Primes
2c820d9bd9bec9158bbf8f366e33b99569064b64
8b30a55791a1c627ee949a6640d629a2738cd436
refs/heads/main
<file_sep><?php /* Template Name: G2-Profile-User */ if (isset($_COOKIE['userName'])) { get_header(); $user = new User(); $user->setUser($_COOKIE['userName']); ?> <hr> <div class="container bootstrap snippet profile" style="margin-bottom: 15px;"> <div class="row"> <div class="col-sm-10"> <h1>Thông tin cá nhân</h1> </div> </div> <div class="row"> <div class="col-sm-4"> <!--left col--> <div class="text-center"> <a style="padding-bottom: 10px;" href="<?php echo $user->getFilter("avatar") ?>" class="pull-right"> <img style="box-shadow: 1px 1px 4px 0px rgba(0, 0, 0, 0.75);width:70%;" title="profile image" class="img-responsive" src="<?php echo $user->getFilter("avatar") ?>"> </a> </div> </div> <!--/col-3--> <div class="col-sm-8"> <ul class="nav nav-tabs"> <li class="active" style="margin-right: 15px;"><a data-toggle="tab" href="http://localhost/wordpress/profile-user/">Thông tin</a></li> </ul> <div class="tab-content"> <div class="tab-pane active" id="home"> <hr> <form class="form" action="" method="post" enctype="multipart/form-data"> <div class="form-group"> <div class="col-6"> <label for="profile_user"> <h4>Tên tài khoản</h4> </label> <input disabled type="text" class="form-control" name="profile_user" id="profile_user" placeholder="<NAME>" title="Không chỉnh sửa" value="<?php echo $user->getFilter("user") ?>"> </div> </div> <div class="form-group"> <div class="col-6"> <label for="sex"> <h4>Giới tính</h4> </label> <br> <?php if ($user->getFilter("sex") == 0) { echo '<input type="radio" name="profile_sex" id="sex" value="0" checked>Nam <input type="radio" name="profile_sex" id="sex" value="1">Nữ <input type="radio" name="profile_sex" id="sex" value="2">Khác'; } else if ($user->getFilter("sex") == 1) { echo '<input type="radio" name="profile_sex" id="sex" value="0" >Nam <input type="radio" name="profile_sex" id="sex" value="1" checked>Nữ <input type="radio" name="profile_sex" id="sex" value="2">Khác'; } else { echo '<input type="radio" name="profile_sex" id="sex" value="0" checked>Nam <input type="radio" name="profile_sex" id="sex" value="1">Nữ <input type="radio" name="profile_sex" id="sex" value="2" checked>Khác'; } ?> </div> </div> <div class="form-group"> <div class="col-6"> <label for="profile_email"> <h4>Email</h4> </label> <input type="email" class="form-control" name="profile_email" id="profile_email" placeholder="<EMAIL>" value="<?php echo $user->getFilter("email") ?>"> </div> </div> <div class="form-group"> <div class="col-6"> <label for="profile_phone"> <h4>Điện thoại</h4> </label> <input type="text" class="form-control" name="profile_phone" id="profile_phone" placeholder="1234 567 890" value="<?php echo $user->getFilter("phone") ?>"> </div> </div> <div class="form-group"> <div class="col-6"> <label for="profile_password_old"> <h4>Mật khẩu</h4> </label> <input type="password" class="form-control" name="profile_password_old" id="profile_password_old" placeholder="<PASSWORD>" required> </div> </div> <div class="form-group"> <div class="col-6"> <label for="profile_password_new"> <h4>Mật khẩu mới</h4> </label> <input type="password" class="form-control" name="profile_password_new" id="profile_password_new" placeholder="<PASSWORD>"> </div> </div> <div class="form-group"> <div class="col-6"> <img src="http://ssl.gstatic.com/accounts/ui/avatar_2x.png" class="avatar img-circle img-thumbnail" alt="avatar"> <h6>Thêm ảnh đại diện </h6> <input type="file" class="text-center center-block file-upload" name="profile_avatar"> </div> </div> <div class="form-group"> <div class="col-xs-12"> <br> <input type="hidden" name="profile_update" value="true"> <button class="btn btn-lg btn-success" type="submit"><i class="glyphicon glyphicon-ok-sign"></i> Lưu</button> <button class="btn btn-lg" type="reset"><i class="glyphicon glyphicon-repeat"></i> Reset</button> </div> </div> </form> <hr> </div> </div> </div> </div> <!--/col-9--> </div> <!--/row--> <script> $(document).ready(function() { var readURL = function(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function(e) { $('.avatar').attr('src', e.target.result); } reader.readAsDataURL(input.files[0]); } } $(".file-upload").on('change', function() { readURL(this); }); }); </script> <?php get_footer(); } else { wp_redirect("http://localhost/wordpress/"); } <file_sep><?php /* Template Name: G2-Thanh-Toan */ get_header(); ?> <div class="cart_checkout"> <div class="container"> <?php echo do_shortcode('[woocommerce_checkout]') ?> </div> </div> <?php get_footer(); <file_sep><footer id="footer"> <div class="footer-contact" style="background: url('<?php echo bloginfo('template_directory') ?>/public/img/footer.png');;"> <div class="container"> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-4 col-lg-4 footer-logo"> <a href="<?php echo esc_url(home_url()) ?>"> <?php if (has_custom_logo()) { echo '<img src="' . esc_url(get_link_custom_logo()) . '" alt="' . get_bloginfo('name') . '" class="img-fluid"> '; } else {?> <img src="<?php echo bloginfo('template_directory') ?>/public/img/logo_transparent.png" alt="logoFooter" class="img-fluid"> <?php }?> </a> </div> <div class="col-xs-12 col-sm-12 col-md-4 col-lg-8 contact"> <div class="row"> <div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 "> <h6 class="footer-title">HỖ TRỢ KHÁCH HÀNG</h6> <li><a href="<?php echo esc_url(home_url()) ?>">Trang chủ</a></li> <li><a href="<?php echo esc_url( get_permalink( get_page_by_path( 'tat-ca-san-pham' ) ) )?>">Sản phẩm</a></li> <li><a href="<?php echo esc_url( get_permalink( get_page_by_path( 'contact' ) ) )?>">liên hệ</a></li> </div> <div class="col-xs-12 col-sm-4 col-md-4 col-lg-4"> <h6>THÔNG TIN</h6> <li><a href="#" onclick="updatingLinkPage();">Hướng dẫn mua hàng</a></li> <li><a href="#" onclick="updatingLinkPage();">Hình thức thanh toán</a></li> <li><a href="#" onclick="updatingLinkPage();">Chính sách bảo mật thông tin</a></li> </div> <div class="col-xs-12 col-sm-4 col-md-4 col-lg-4"> <h6><NAME></h6> <a href="#" onclick="updatingLinkPage();"><i class="fab fa-facebook-f"></i></a> <img src="<?php echo bloginfo('template_directory') ?>/public/img/payment.png" alt="payment" class="img-fluid payment-logo"> </div> </div> </div> </div> </div> <div class="footer-author"> <span>Copyright &copy; 2020 G2 SHOP </span> </div> </div> </footer> <script> function updatingLinkPage() { alert('Chúng tôi đang cập nhật trang này sớm nhất có thể'); return false; } </script> <script src="<?php echo bloginfo('template_directory') ?>/public/js/jquery.min.js"></script> <script src="<?php echo bloginfo('template_directory') ?>/public/js/bootstrap.min.js"></script> <script src="<?php echo bloginfo('template_directory') ?>/public/js/login.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> </body> </html><file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Shop G2</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,400;0,600;0,700;1,400;1,600;1,700&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.6.0/css/all.css"> <link rel="stylesheet" href="<?php echo bloginfo('template_directory') ?>/public/css/style.css"> <link rel="stylesheet" href="<?php echo bloginfo('template_directory') ?>/public/css/style-products.css"> <link rel="stylesheet" href="<?php echo bloginfo('template_directory') ?>/public/css/styles.css"> <link rel="stylesheet" href="<?php echo bloginfo('template_directory') ?>/public/css/style-single.css"> <link rel="stylesheet" href="<?php echo bloginfo('template_directory') ?>/public/css/login.css"> <link rel="stylesheet" href="<?php echo bloginfo('template_directory') ?>/public/css/avatar.scss"> <link rel="stylesheet" href="<?php echo bloginfo('template_directory') ?>/public/css/bootstrap.css"> <link rel="stylesheet" href="<?php echo bloginfo('template_directory') ?>/public/css/bootstrap.min.css"> <style> .dropdown button { background: none !important; border: none !important; } .avatar { vertical-align: middle; width: 50px; height: 50px; border-radius: 50%; } .dropbtn:hover, .dropbtn:focus .avatar { background: none !important; border: none !important; } .dropdown { position: relative; display: inline-block; } .dropdown-content { display: none; position: absolute; background-color: #f1f1f1; min-width: 160px; overflow: auto; box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2); z-index: 1; } .dropdown-content input { border: none; background: none; } .dropdown-content a, .dropdown-content input { color: black; padding: 12px 16px; text-decoration: none; display: block; text-align: center; } .dropdown a:hover, .dropdown-content input:hover { background-color: #ddd; } .show { display: block; } /* tablet mini */ @media only screen and (min-width: 576px) and (max-width: 1100px) { .carousel-caption { display: none; } } /* mobile */ @media only screen and (max-width: 575px) { .carousel-caption { display: none; } } </style> <link rel="stylesheet" href="<?php echo bloginfo('template_directory') ?>/public/css/style-products.css"> <link rel="stylesheet" href="<?php echo bloginfo('template_directory') ?>/public/css/cart_style.css"> <link rel="stylesheet" href="<?php echo bloginfo('template_directory') ?>/public/css/checkout_style.css"> <link rel="stylesheet" href="<?php echo bloginfo('template_directory') ?>/public/css/contact.css"> </head> <body> <header> <div class="header"> <div class="header__top"> <a href="<?php echo esc_url(home_url()) ?>"> <?php if (has_custom_logo()) { echo '<img class="logo" src="' . esc_url(get_link_custom_logo()) . '" alt="' . get_bloginfo('name') . '">'; } else { ?> <img class="logo" src="<?php echo bloginfo('template_directory') ?>/public/img/logo.png" alt="logo"> <?php } ?> </a> <ul class="nav__link"> <li class="nav__link--item"> <a href="<?php echo esc_url(home_url()) ?>">Home</a> </li> <li class="nav__link--item"> <a href="<?php echo esc_url(get_permalink(get_page_by_path('tat-ca-san-pham'))) ?>">sản phẩm</a> </li> <li class="nav__link--item"> <a href="<?php echo esc_url(get_permalink(get_page_by_path('contact'))) ?>">liên hệ</a> </li> <li class="nav__link--item"> <?php global $woocommerce; ?> <a class="cart-contents" style="color:#FEC144" href="<?php echo $woocommerce->cart->get_cart_url(); ?>" title="<?php _e('View your shopping cart', 'woothemes'); ?>"> <?php echo sprintf(_n('%d item', '%d <i class="fas fa-cart-plus"></i>', $woocommerce->cart->cart_contents_count, 'woothemes'), $woocommerce->cart->cart_contents_count); ?> <!-- <?php echo $woocommerce->cart->get_cart_total(); ?> --> </a> </li> <?php if (isset($_COOKIE['userName'])) { $user = new User(); $user->setUser($_COOKIE['userName']); ?> <div class="dropdown"> <button> <img onclick="myFunction()" src="<?php echo $user->getFilter("avatar")?>" alt="Avatar" class="avatar dropbtn img-fluid" style="box-shadow: 1px 1px 4px 0px rgba(0, 0, 0, 0.75);"> </button> <div id="myDropdown" class="dropdown-content"> <a href="<?php echo esc_url(get_permalink(get_page_by_path('profile-user'))) ?>">Profile</a> <form action="" method="post"> <input type="hidden" name="logout" value="true"> <input type="submit" value="Logout" class="form-control"> </form> <!-- <a href="#about">Logout</a> --> </div> </div> <?php } else { echo ' <li class="nav__link--item"><a data-toggle="modal" href="javascript:void(0)" onclick="openLoginModal();">Đăng Nhập</a></li>'; } ?> </ul> <?php get_template_part('template-parts/modal/modal', 'login') ?> </div> <div class="header__bottom"> <ul class="nav__link"> <?php $categories = get_category_wc(); foreach ($categories as $cat) { ?> <li class="nav__link--item" title="<?php echo $cat->ID; ?>"> <a href="<?php echo get_term_link($cat); ?> "><?php echo $cat->name; ?></a> </li> <?php } ?> </ul> </div> </div> </header> <script> function myFunction() { document.getElementById("myDropdown").classList.toggle("show"); } window.onclick = function(event) { if (!event.target.matches('.dropbtn')) { var dropdowns = document.getElementsByClassName("dropdown-content"); var i; for (i = 0; i < dropdowns.length; i++) { var openDropdown = dropdowns[i]; if (openDropdown.classList.contains('show')) { openDropdown.classList.remove('show'); } } } } </script><file_sep><?php /* Template Name: G2-All-Product */ get_header(); ?> <div class="all_product"> <div class="container"> <h2 class="products_title"> <?php echo get_the_title() . ':' ?> </h2> <div class="products_content"> <?php echo do_shortcode('[products columns=4 paginate=true order=ASC per_page=8]') ?> </div> </div> </div> <?php get_footer(); <file_sep><?php $cat_slug = getCatSlugById(get_queried_object_id()); ?> <div class="cate_product"> <div class="container"> <h2 class="products_title"> <?php the_archive_title() ?> </h2> <div class="products_content"> <?php echo do_shortcode('[product_category category='.$cat_slug.' per_page=5 columns=4 orderby=date order=desc paginate=true]') ?> </div> </div> </div> <file_sep> <div id="myCarousel" class="carousel slide" data-ride="carousel" style="margin-top:-20px"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#myCarousel" data-slide-to="0" class="active"></li> <li data-target="#myCarousel" data-slide-to="1"></li> <li data-target="#myCarousel" data-slide-to="2"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner" style="width:30%;margin:auto"> <div class="item active"> <img src="<?php echo bloginfo('template_directory') ?>/public/img/logo.png" alt="Los Angeles" style="width:100%;"> <div class="carousel-caption" style="color:#000;top:-8%"> <h3>G2 Shop</h3> <p>Welcome!</p> </div> </div> <?php $products = getProduct(); foreach ($products as $product) { ?> <div class="item" title="<?php echo $product->name?>"> <img src="<?php echo get_the_post_thumbnail_url($product->id) ?>" alt="<?php echo $product->name?>" style="width:100%;"> <div class="carousel-caption" style="color:#000;top:-8%"> <h3><?php echo $product->name?></h3> </div> </div> <?php } ?> </div> <!-- Left and right controls --> <a class="left carousel-control" href="#myCarousel" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left"></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#myCarousel" data-slide="next"> <span class="glyphicon glyphicon-chevron-right"></span> <span class="sr-only">Next</span> </a> </div><file_sep><?php #########=========THEME======######### use PHPMailer\PHPMailer\PHPMailer; /** * thông báo thành công */ function g2_alert_success($msg) { echo '<div class="alert alert-success alert-dismissible" id="alert-success"> <a href="#" class="close" data-dismiss="alert" aria-label="close" onclick="close_success()">&times;</a> <strong>Success! </strong>' . $msg . ' </div> '; ?> <script> function close_success() { document.getElementById('alert-success').style.display = "none"; } </script> <?php } /** * thông báo lỗi */ function g2_alert_error($msg) { echo '<div class="alert alert-danger alert-dismissible" id="alert-danger"> <a href="#" class="close" data-dismiss="alert" aria-label="close" onclick="close_danger()">&times;</a> <strong>Error! </strong>' . $msg . ' </div> '; ?> <script> function close_danger() { document.getElementById('alert-danger').style.display = "none"; } </script> <?php } /** * Khởi tạo hàm custom logo * * Thêm lựa chọn vào theme trên wp-admin (website) */ function themename_custom_logo_setup() { $defaults = array( 'height' => 70, 'width' => 70, 'flex-height' => true, 'flex-width' => true, 'header-text' => array('site-title', 'site-description'), 'unlink-homepage-logo' => true, ); add_theme_support('custom-logo', $defaults); } add_action('after_setup_theme', 'themename_custom_logo_setup'); /** * Khởi tạo hàm trả về giá trị là đường dẫn logo * * Đường link sẽ lấy theo url */ function get_link_custom_logo() { $custom_logo_id = get_theme_mod('custom_logo'); $logo = wp_get_attachment_image_src($custom_logo_id, 'full'); return $logo[0]; } #########=========PRODUCT======######### /** * Hàm lấy toàn bộ danh mục sản phẩm * * Danh mục ít nhất 1 sản phẩm */ function get_category_wc() { $categories = get_terms(['taxonomy' => 'product_cat']); return $categories; } /** * Hàm lấy 10 sản phẩm * * Số lượng sản phẩm là */ function getProduct() { $args = array( 'status' => 'publish', 'numberposts' => 10, ); $products = wc_get_products($args); return $products; } /** * Hàm lấy slug danh mục theo id * */ function getCatSlugById($cat_id) { $term = get_term_by('id', $cat_id, 'product_cat', 'ARRAY_A'); return $term['slug']; } add_filter('add_to_cart_fragments', 'woocommerce_header_add_to_cart_fragment'); function woocommerce_header_add_to_cart_fragment($fragments) { global $woocommerce; ob_start(); ?> <a class="cart-contents" href="<?php echo $woocommerce->cart->get_cart_url(); ?>" title="<?php _e('View your shopping cart', 'woothemes'); ?>"><?php echo sprintf(_n('%d item', '%d items', $woocommerce->cart->cart_contents_count, 'woothemes'), $woocommerce->cart->cart_contents_count); ?> - <?php echo $woocommerce->cart->get_cart_total(); ?></a> <?php $fragments['a.cart-contents'] = ob_get_clean(); return $fragments; } /** * Hàm lấy sản phẩm theo danh mục * * Danh mục ở đây là nhập vào để hiển thị ra giao diện chính (Home) * Số lượng sản phẩm là 6 */ function getProductByCategory($category) { $args = array( 'post_type' => 'product', 'category' => array($category), 'orderby' => 'name', 'numberposts' => 6, ); $products = wc_get_products($args); return $products; } /** * Hàm tính phần trăm giảm giá của sản phẩm * */ function getSale($price, $sale_price) { $sale = 100 - ((intval($sale_price) * 100) / intval($price)); return intval($sale); } function getHtmlProducts($product) { echo '<a href="' . esc_url(get_post_permalink($product->id, false, false)) . '"> <div class="el-wrapper" title="' . $product->name . '"> <div class="box-up"> <img class="img" src="' . get_the_post_thumbnail_url($product->id) . '" alt=""> <div class="img-info"> <div class="info-inner">'; if ($product->sale_price > 0) { echo '<span class="p-sale"> <span class="sale">Sale</span> ' . getSale($product->regular_price, $product->sale_price) . ' %</span>'; } echo '<span class="p-name">' . $product->name . '</span> </div> </div> </div> <div class="box-down"> <div class="h-bg"> <div class="h-bg-inner"></div> </div>'; if ($product->sale_price > 0) { echo '<a class="shop-cart" href="#"> <span class="price" style="left:25%"><s style="color:#818181;left:15%">' . number_format_i18n($product->regular_price) . ' đ</s></span> <span class="price-sale" style="left:65%">' . number_format_i18n($product->sale_price) . ' đ</span> <span class="add-to-shop-cart"> <span class="txt">Thêm vào giỏ hàng</span> </span> </a>'; } else { echo '<a class="shop-cart" href="#"> <span class="price">' . number_format_i18n($product->price) . ' đ</span> <span class="add-to-shop-cart"> <span class="txt">Thêm vào giỏ hàng</span> </span> </a>'; } echo '</div> </div> </a> '; } /** * Xuất ra html của 6 sản phẩm theo danh mục * * Giá trị là tên của danh mục */ function getHtmlProductByCategory($category) { echo '<div class="container page-wrapper"> <div class="page-inner"> <div class="heading_hotdeal"> <h2 class="title-head" title="' . $category . '"> <a href="">' . $category . ' Mới Nhất</a> </h2> </div> <div class="row">'; $products = getProductByCategory($category); foreach ($products as $product) { echo '<a href="' . esc_url(get_post_permalink($product->id, false, false)) . '"> <div class="el-wrapper" title="' . $product->name . '"> <div class="box-up"> <img class="img" src="' . get_the_post_thumbnail_url($product->id) . '" alt=""> <div class="img-info"> <div class="info-inner">'; if ($product->sale_price > 0) { echo '<span class="p-sale"> <span class="sale">Sale</span> ' . getSale($product->regular_price, $product->sale_price) . ' %</span>'; } echo '<span class="p-name">' . $product->name . '</span> </div> </div> </div> <div class="box-down"> <div class="h-bg"> <div class="h-bg-inner"></div> </div>'; if ($product->sale_price > 0) { echo '<a class="shop-cart" href="' . esc_url(get_post_permalink($product->id, false, false)) . '"> <span class="price" style="left:25%"><s style="color:#818181;left:15%">' . number_format_i18n($product->regular_price) . ' đ</s></span> <span class="price-sale" style="left:65%">' . number_format_i18n($product->sale_price) . ' đ</span> <span class="add-to-shop-cart"> <span class="txt">Thêm vào giỏ hàng</span> </span> </a>'; } else { echo '<a class="shop-cart" href="' . do_shortcode('[add_to_cart_url id="' . $product->id . '"]') . '"> <span class="price">' . number_format_i18n($product->price) . ' đ</span> <span class="add-to-shop-cart"> <span class="txt">Thêm vào giỏ hàng</span> </span> </a>'; } echo '</div> </div> </a> '; } echo ' </div> </div> </div>'; } #########=========DATABASE======######### /** * lấy thời gian ngày-tháng-năm giờ-phút-giây * * Hồ Chí Minh City */ function getTimeNow() { date_default_timezone_set('asia/ho_chi_minh'); $getTime = date("d-m-Y H:i:s"); return $getTime; } /** * Thêm thông tin vào bảng trong db * * Tên bảng, dữ liệu cần thêm */ function g2_insert_db($table_name, $data) { global $wpdb; $table = $wpdb->prefix . $table_name; $wpdb->insert( $table, $data ); $fl = $wpdb->insertId; } /** * Cập nhật thông tin vào bảng trong db * * Tên bảng, dữ liệu cần cập nhật, cập nhật ở đâu */ function g2_update_db($table_name, $data, $where) { global $wpdb; $table = $wpdb->prefix . $table_name; $wpdb->update( $table, $data, $where ); } /** * Lấy thông tin của 1 bảng trong db * * Tên bảng */ function g2_get_db($table_name) { global $wpdb; $table = $wpdb->prefix . $table_name; $sql = "SELECT * FROM $table"; $results = $wpdb->get_results($sql); return $results; } /** * Lấy thông tin của 1 cột trong 1 bảng db * * Tên bảng, Id của cột cần lấy */ function g2_get_row_db($table_name, $id) { global $wpdb; $table = $wpdb->prefix . $table_name; $sql = "SELECT * FROM $table WHERE `id` = '$id' "; $results = $wpdb->get_results($sql); return $results; } #########=========ACCOUNT======######### /** * tạo db cho người dùng * * Thuộc tính của một user */ function g2_create_db_users() { global $wpdb; $charset_collate = $wpdb->get_charset_collate(); $table_name = $wpdb->prefix . "g2_users"; $sql = "CREATE TABLE IF NOT EXISTS {$table_name} ( id int(11) NOT NULL AUTO_INCREMENT COMMENT 'auto', user varchar(64) DEFAULT NULL , password varchar(64) DEFAULT NULL, email varchar(64) DEFAULT NULL, phone varchar(15) DEFAULT NULL, avatar varchar(254) DEFAULT NULL, register_time varchar(64) COMMENT '(dd/mm/yy-h:m:s)', sex int(1) DEFAULT 0 COMMENT '0: Nam / 1: Nữ / 2: Khác', user_type int(1) DEFAULT 1 COMMENT '0: Admin / 1: user', PRIMARY KEY (id) ) $charset_collate;"; if (!function_exists('dbDelta')) { require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); } dbDelta($sql); } add_action('init', 'g2_create_db_users'); function g2_activate_create_db() { g2_create_db_users(); // Clear the permalinks after the post type has been registered. flush_rewrite_rules(); } register_activation_hook(__FILE__, 'g2_activate_create_db'); /** * Kiểm tra tài khoản có trong db hay chưa * * 1: Có * * 0: Chưa có */ function g2_check_user($userName) { $check_user = 0; $g2_users = array(); $g2_users = g2_get_db("g2_users"); foreach ($g2_users as $user) { if ($user->user == $userName) { $check_user = 1; } } return $check_user; } /** * Kiểm tra password * * 1: <PASSWORD> * * 0: Sai */ function g2_check_password($password) { $check_pass = 0; $g2_users = array(); $g2_users = g2_get_db("g2_users"); foreach ($g2_users as $user) { if ($user->password == md5($password)) { $check_pass = 1; } } return $check_pass; } /** * Tạo class để xuất lấy từng thông tin của user */ class User { public $id; public $user; public $password; public $email; public $phone; public $sex; public $user_type; public $avatar; public $create_time; /** * Truyền vào tên user để kiểm tra user tồn tại hay không */ function setUser($user) { if (g2_check_user($user) == 1) { $this->user = $user; } } /** * Truyền giá trị filter cần lấy của tài khoản đó * * * * id; * * * user; * * * password; * * * email; * * * phone; * * * sex; * * * user_type; * * * avatar; * * * create_time; */ function getFilter($filter) { if ($this->user != "") { $g2_users = g2_get_db("g2_users"); foreach ($g2_users as $user) { if ($user->user == $this->user) { $this->$filter = $user->$filter; } } return $this->$filter; } else { return "Không tồn tại tài khoản"; } } } /** * Đăng ký tài khoản * * thời gian khởi tạo là thời gian đăng ký thành công * gmt +7 / tp hồ chí minh */ function g2_register_account($re_user, $re_pass) { $data = array( 'user' => $re_user, 'password' => md5($<PASSWORD>), 'register_time' => getTimeNow(), 'avatar' => 'http://localhost/wordpress/wp-content/uploads/2020/11/defaul-avatar.png', ); g2_insert_db("g2_users", $data); } if ($_POST['register'] === "Đăng Ký") { if ($_POST['userRegister'] != '' || $_POST['passRegister'] != '') { $re_user = $_POST['userRegister']; $re_pass = $_POST['passRegister']; $check_user = g2_check_user($re_user); if ($check_user == 1) { if (!isset($_COOKIE['userName'])) { if (!isset($_COOKIE['re_false'])) { g2_alert_error('Đã có tài khoản'); $_COOKIE['re_false'] = $re_user; setcookie("re_false", $re_user, time() + (WEEK_IN_SECONDS), COOKIEPATH, COOKIE_DOMAIN); } } } else { g2_register_account($re_user, $re_pass); if (!isset($_COOKIE['userName'])) { g2_alert_success('Tạo tài khoản thành công'); unset($_COOKIE['re_false']); setcookie("re_false", '', 0, COOKIEPATH, COOKIE_DOMAIN); $_COOKIE['userName'] = $re_user; setcookie("userName", $re_user, time() + (WEEK_IN_SECONDS), COOKIEPATH, COOKIE_DOMAIN); } } } } /** * Đăng Nhập * */ if ($_POST['login'] === "Đăng Nhập") { if ($_POST['userLogin'] != '' || $_POST['passLogin'] != '') { $login_user = $_POST['userLogin']; $login_pass = $_POST['passLogin']; $check_user = g2_check_user($login_user); $check_pass = g2_check_password($login_pass); if ($check_user == 1) { if ($check_pass == 1) { if (!isset($_COOKIE['userName'])) { g2_alert_success("Đăng nhập thành công"); $_COOKIE['userName'] = $login_user; setcookie("userName", $login_user, time() + (WEEK_IN_SECONDS), COOKIEPATH, COOKIE_DOMAIN); } } else { g2_alert_error('Tài khoản hoặc mật khẩu không đúng!'); } } else { g2_alert_error('Tài khoản hoặc mật khẩu không đúng!'); } } } /** * Đăng Xuất * */ if (isset($_POST['logout']) && $_POST['logout'] == "true") { unset($_COOKIE['userName']); setcookie("userName", '', 0, COOKIEPATH, COOKIE_DOMAIN); } /** * Update Profile * */ if (isset($_POST['profile_update']) && $_POST['profile_update'] == "true") { if (isset($_COOKIE['userName'])) { require_once(ABSPATH . 'wp-admin/includes/image.php'); require_once(ABSPATH . 'wp-admin/includes/file.php'); require_once(ABSPATH . 'wp-admin/includes/media.php'); $overrides = array( 'test_form' => false, 'test_type' => false, ); $pf_user = $_COOKIE['userName']; $pf_email = $_POST['profile_email']; $pf_pass_old = $_POST['profile_password_old']; $pf_pass_new = $_POST['profile_password_new']; $pf_phone = $_POST['profile_phone']; $pf_sex = $_POST['profile_sex']; $user = new User(); $user->setUser($pf_user); $pf_avatar = $user->getFilter("avatar"); if ($_FILES['profile_avatar']['name'] != "") { $upload = wp_handle_upload($_FILES['profile_avatar'], $overrides); } else { $upload['url'] = $pf_avatar; } $pass = $user->getFilter("password"); if (md5($pf_pass_old) != $pass && $pf_pass_old != "") { g2_alert_error("Sai mật khẩu cũ!"); } else { if ($pf_pass_new == "") { $pf_pass_new = $pf_pass_old; $where = array('user' => $pf_user); $data = array( 'user' => $pf_user, 'password' => md5($<PASSWORD>_new), 'avatar' => $upload['url'], 'phone' => $pf_phone, 'email' => $pf_email, 'sex' => intval($pf_sex), ); } g2_update_db("g2_users", $data, $where); } } else { g2_alert_error("Bạn phải đăng nhập!"); } } /** * Contact form * * Gửi thông tin về mail của admin bằng phpmailer */ // add_action('phpmailer_init','sendContact'); // function sendContact(PHPMailer $phpMailer) // { // $phpMailer->setFrom($_POST['contact-email'], $_POST['contact-name']); // $phpMailer->Host = 'smtp1.example.com;smtp2.example.com'; // $phpMailer->Port = 110; // $phpMailer->SMTPAuth = true; // $phpMailer->SMTPSecure = 'tls'; // $phpMailer->Username = '<EMAIL>'; // $phpMailer->Password = '<PASSWORD>'; // $phpMailer->Body = $_POST['contact-messenger']; // $phpMailer->isSMTP(); // }<file_sep><?php $product = wc_get_product(get_the_ID()); ?> <section class="u-clearfix u-section-2" id="sec-9bc7"> <div class="u-clearfix u-sheet u-valign-middle-lg u-sheet-1"> <div class="u-container-style u-expanded-width u-product u-product-1"> <div class="u-container-layout u-valign-top-md u-valign-top-sm u-valign-top-xs u-container-layout-1"> <!--product_image--> <img alt="" class="u-image u-image-default u-product-control u-image-1" src="<?php echo get_the_post_thumbnail_url(); ?>"> <!--/product_image--> <div class="u-align-left u-container-style u-expanded-width-md u-expanded-width-sm u-expanded-width-xs u-group u-shape-rectangle u-group-1"> <div class="u-container-layout u-valign-middle-lg u-valign-middle-xl u-container-layout-2"> <!--product_title--> <h2 class="u-product-control u-text u-text-1"> <div class="u-product-title-link" style="font-weight:450;text-transform: capitalize"> <?php echo $product->name ?> </div> </h2> <!--product_price--> <div class="u-product-control u-product-price u-product-price-1"> <div class="u-price-wrapper u-spacing-10"> <!--product_regular_price--> <?php if ($product->sale_price > 0) { ?> <div class="u-price u-text-palette-2-base" style="font-size: 1.5rem; font-weight: 700;text-decoration: line-through;color:#8a8686!important"> <!--product_regular_price_content--><?php echo number_format_i18n($product->regular_price) ?>đ <!--/product_regular_price_content--> </div> <div class="u-price u-text-palette-2-base" style="font-size: 1.5rem; font-weight: 700;"> <!--product_regular_price_content--><?php echo number_format_i18n($product->sale_price) ?>đ <!--/product_regular_price_content--> </div> <?php } else { ?> <div class="u-price u-text-palette-2-base" style="font-size: 1.5rem; font-weight: 700;"> <!--product_regular_price_content--><?php echo number_format_i18n($product->regular_price) ?>đ <!--/product_regular_price_content--> </div> <?php } ?> <!--/product_regular_price--> </div> </div> <!--/product_price--> <div class="u-border-3 u-border-grey-dark-1 u-line u-line-horizontal u-line-1"></div> <form action="" method="POST" id="formCart"> <label for="qty">Số lượng mua:</label> <input type="hidden" name="productId" value="<?php echo $product->id ?>"> <input type="number" name="qty" id="qty" min="1" max="50" value="1" class="form-control" style="width:30%"> </form> <a href="<?php echo do_shortcode('[add_to_cart_url id="' . $id . '"]') ?>" class="u-black u-border-2 u-border-grey-75 u-btn u-button-style u-hover-grey-75 u-product-control u-btn-1">Thêm vào giỏ hàng</a> <!--/product_button--> </div> </div> <div class="desc"> <h5>Thông tin sản phẩm</h5> <div class="u-border-3 u-border-grey-dark-1 u-line u-line-horizontal u-line-1"></div> <p> <?php echo $product->description ?> </p> </div> </div> </div> <!--/product_item--> <!--/product--> </div> </section><file_sep><?php /* Template Name: G2-Contact */ get_header(); ?> <!-- <div class="container"> <div class="contact"> <h1 class="text-center">Liên Hệ</h1> <form class="contact-form" action="" method="POST"> <div class="contact-form-group"> <label for="name" class="contact-form-label">Tên</label> <input name="contact-name" id="contact-name" type="text" class="contact-form-input" /> </div> <div class="contact-form-group"> <label for="email" class="contact-form-label">Email</label> <input name="contact-email" id="contact-email" type="email" class="contact-form-input" /> </div> <div class="contact-form-group"> <label for="message" class="contact-form-label">Phản hồi của bạn</label> <textarea name="contact-message" id="message" class="contact-form-area" placeholder="Nhập phản hồi tại đây"></textarea> </div> <button type="submit" class="contact-form-submit">Gửi phản hồi</button> </form> </div> </div> --> <?php get_footer(); <file_sep><?php get_header(); ?> <!-- content project --> <div class="main"> <!-- slide show --> <div class="slide"> <?php get_template_part('template-parts/content/content') ?> </div> <!-- Lấy 6 sp theo danh mục --> <div class="content" style="margin-top:20px;"> <?php getHtmlProductByCategory('Áo'); getHtmlProductByCategory('Giày'); ?> </div> </div> <!-- end content --> <?php get_footer(); ?><file_sep><?php get_header(); if (is_tax()) { get_template_part('archive'); } else { get_template_part('template-parts/content/content', 'single'); } get_footer();
a3b45ff9fec961e80dfaa635a91f889017f09f42
[ "PHP" ]
12
PHP
JokerNVT102/CMS_Project
052997d042230c6fae93df343732639dfd67ab76
7f60dd956109c25fc7e9cb1d4fc83d11dfda6a3a
refs/heads/master
<file_sep>from tkinter import * from tkinter import ttk import os import subprocess import shlex #create window object app = Tk() #window propery app.title('Test Suite v1.0') app.geometry('700x400') #create tabbed window tabControl = ttk.Notebook(app) #create tabs mTestTab = ttk.Frame(tabControl) spiTestTab = ttk.Frame(tabControl) i2cTestTab = ttk.Frame(tabControl) uartTestTab = ttk.Frame(tabControl) cameraTestTab = ttk.Frame(tabControl) #adding tabs tabControl.add(mTestTab, text='Memory Test') tabControl.add(spiTestTab, text='SPI Test') tabControl.add(i2cTestTab, text='I2C Test') tabControl.add(uartTestTab, text='UART Test') tabControl.add(cameraTestTab, text='Camera Test') #packing the tab tabControl.pack(expand=1,fill="both") #Content for Tabs text = ttk.Label(mTestTab, text="MEMORY TEST",font=("Bold",14)).grid(column = 0,row = 0,padx = 30, pady = 30) ok = ttk.Label(mTestTab, text="OK", font=('Aerial',12)) ttk.Label(spiTestTab, text="SPI TEST",font=("Bold",14)).grid(column = 0,row = 0,padx = 30, pady = 10, sticky = E) ttk.Label(i2cTestTab, text="I2C TEST",font=("Bold",14)).grid(column = 0,row = 0,padx = 30, pady = 30) ttk.Label(uartTestTab, text="UART TEST",font=("Bold",14)).grid(column = 0,row = 0,padx = 30, pady = 30) ttk.Label(cameraTestTab, text="CAMERA TEST",font=("Bold",14)).grid(column = 0,row = 0,padx = 30, pady = 30) #memory test listbox lbox = Listbox(mTestTab,height="15",width="60") lbox1 = Listbox(spiTestTab, height="15", width="60") tbox = Text(spiTestTab) tbox2 = Text(i2cTestTab) lbox.grid(row=1,column=0) lbox.place(x=120,y=65) # lbox1.grid(row=1,column=0) # lbox1.place(x=120,y=65) xString = StringVar() yString = StringVar() ssVal = StringVar() Label(cameraTestTab, text="x-coordinate").grid(row=1,column=0) Coox = Entry(cameraTestTab, textvariable = xString).grid(row=1,column=1,padx=10) Label(cameraTestTab, text="y-coordinate").grid(row=1,column=2) Cooy = Entry(cameraTestTab,textvariable= yString).grid(row=1, column=3) Label(cameraTestTab,text="Shutter Speed: ").grid(row=2,column=0) shutterText = Entry(cameraTestTab, textvariable = ssVal).grid(row=2, column=1) def onClickBtn(): lbox.insert(1,"Stuck Address: ............OK") lbox.insert(2,"Random Value: ............OK") lbox.insert(3,"Comapre XOR: ............OK") lbox.insert(4,"Comapre SUB: ............OK") lbox.insert(5,"Comapre MUL: ............OK") lbox.insert(6,"Comapre DIV: ............OK") lbox.insert(7,"Comapre OR: ............OK") lbox.insert(8,"Comapre AND: ............OK") lbox.insert(9,"Sequential Increament: ............OK") lbox.insert(10,"Solid Bits: ............OK") lbox.insert(11,"Block Sequential: ............OK") lbox.insert(12,"CheckerBoard: ............OK") lbox.insert(13,"Bit Spread: ............OK") lbox.insert(14,"Bit Flip: ............OK") lbox.insert(15,"Walking ones: ............OK") lbox.insert(16,"Walking zeroes: ............OK") lbox.insert(17,"8-Bits writes: ............OK") lbox.insert(18,"16-bit writes: ............OK") memtest = subprocess.run(["sudo", "memtester","5","1"]) print(str(memtest.returncode)) exitcode = str(memtest.returncode) lbox.insert(19,"DONE "+exitcode) def onClickBtnSPI(): commands = ''' cd /home/pi/Documents/TestSuitGUI ./spidev_test -v ''' process = subprocess.Popen('/bin/bash', stdin=subprocess.PIPE, stdout=subprocess.PIPE) out, err = process.communicate(commands.encode('utf-8')) #lbox1.insert(1,out.decode("ISO-8859-1")) tbox.place(x=20,y=70) tbox.insert(END, out) def onClickBtnI2C(): commands = ''' i2cdetect -y 1 ''' i2ctest = subprocess.Popen('/bin/bash', stdin=subprocess.PIPE, stdout=subprocess.PIPE) out, err = i2ctest.communicate(commands.encode('utf-8')) tbox2.place(x=20,y=70) tbox2.insert(END, out) #def onClickBtnUART(): # command = 'minicom -b 9600 -o -D /dev/ttyACM0' # process = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE) # while True: # output = process.stdout.readline() # if output == '' and process.poll() is not None: # break # if output: # print(output.strip()) # rc = process.poll() # return rc def onClickBtnCAMERA(): x = xString.get() y = yString.get() command = 'raspistill -roi '+x+','+y+',0.25,0.25 -o test.jpg' output = subprocess.call(command,shell=True) print(output) if output == 70: Label(cameraTestTab, text="exit code: 70: Camera not connected",bg="red").grid(row=5,column=0,padx=5) if output == 0: Label(cameraTestTab, text="exit code: 0: PASS",fg="green").grid(row=5,column=0,padx=5) def onClickBtnCAMERA1(): ss = ssVal.get() command = 'raspistill -ss '+ss+' -o test2.jpg' output = subprocess.call(command,shell=True) if output == 70: Label(cameraTestTab, text="exit code: 70: Camera not connected",bg="red").grid(row=5,column=0,padx=5) if output == 0: Label(cameraTestTab, text="exit code: 0: PASS",bg="green").grid(row=5,column=0,padx=5) my_btn = Button(mTestTab, text="TEST",command = onClickBtn).grid(column = 1, row=0,padx = 20, pady = 30) spiBtn = Button(spiTestTab, text="TEST",command = onClickBtnSPI).grid(column = 1, row=0,padx = 20, pady = 10) i2cBtn = Button(i2cTestTab, text="TEST",command = onClickBtnI2C).grid(column = 1, row=0,padx = 20, pady = 30) uartBtn = Button(uartTestTab, text="TEST").grid(column = 1, row=0,padx = 20, pady = 30) cameraBtn = Button(cameraTestTab, text="TEST",command = onClickBtnCAMERA).grid(column = 5, row=1,padx = 30, pady = 30) cameraBtn1 = Button(cameraTestTab, text="TEST Shutter Speed",command = onClickBtnCAMERA1).grid(column = 2, row=2,padx = 30, pady = 30) #start program app.mainloop()
dc52d9aa85d44c2bb7d4e31079d8fbb29fb51041
[ "Python" ]
1
Python
mahanthesh0r/TestsuiteRaspi
eb35e62f9fa6461acf856dde2995519b3e84bb5d
8367ea005acff2cc0491d8105469daf01b84de17
refs/heads/master
<file_sep>const models = require("./schemas") const vps = models.vps; const user = models.user; const login= async (username, pass)=>{ const data = await user.findOne({user:username,password:pass}).exec() if(data){ return {caducidad:data.caducidad,rol:data.rol,status:200} }else{ return {status:404} } } const creating=async(username,pass,caducidad,rol)=>{ exist = await login(username,pass); if(exist.status == 404){ const datos = new user({ user:username, password:<PASSWORD>, caducidad:caducidad, rol:rol }) datos.save(); return "Usuario creado satisfactoriamente" }else{ return "El usuario ya existe" } } const nVps = async(ip,puertos,username,password,conex,localidad)=>{ const new_vps = new vps({ ip:ip, puertos:puertos, user:username, pass:<PASSWORD>, conexiones:conex, localidad:localidad }) new_vps.save(); } const getVps = async ()=>{ const vpss = await vps.find().exec() return vpss } module.exports = { login, creating, nVps, getVps }<file_sep>const express = require('express'); const app = express(); const hbs = require('hbs') const mongoose = require('mongoose') const path = require('path') const bodyParser = require("body-parser") const queries = require("./bbdd/queries.js"); hbs.registerPartials(__dirname + "/partials") app.set("view engine",'hbs') app.use(bodyParser.urlencoded({extended:false})) app.use(bodyParser.json()) const publicDir = path.join(__dirname, '/public'); app.use(express.static(publicDir)); mongoose.connect("mongodb://localhost/vpsdb",{ useUnifiedTopology: true, useNewUrlParser: true },(err,conneted)=>{ if(err){ console.log(err) return 500 } console.log("conected to database") }) app.get("/",(req,res)=>{ res.render("index") }) app.get("/netflix",(req,res)=>{ res.render("netflix") }) app.get("/prime",(req,res)=>{ res.render("prime") }) app.get("/vps",(req,res)=>{ res.render("login") }) app.post("/home",async (req,res)=>{ user = req.body.user; pass = req.body.pass; const response = await queries.login(user,pass); if(response.status==404){ res.render("login",{ error:"Usuario o contraseña incorrecto" }) } if(response.status==200){ switch(response.rol){ case 0: res.render("homeadm") break; default: const today = Date.now(); if(today>response.caducidad){ res.render("login",{ error:"cuenta caducada" }) }else{ const vpss = await queries.getVps(); res.render("vps",{vpss}) } } } }) app.post("/create-user",async (req,res)=>{ const d = new Date(req.body.caducidad).getTime(); const response = await queries.creating(req.body.user,req.body.pass,d,req.body.rol); res.render("homeadm",{user:response}) }) //ip, puertos,usuario, contraseña, conexiones, localidad app.post('/create-vps', async (req,res)=>{ queries.nVps(req.body.ip, req.body.puertos, req.body.user, req.body.pass, req.body.conexiones, req.body.localidad) res.render("homeadm") }) app.listen(3000,()=>{ console.log("listening on port 3000") })<file_sep>const mongoose = require("mongoose"); const schema = mongoose.Schema; const userSchema = new schema({ user:String, password:String, caducidad:Number, rol:Number }) const vpsSchema = new schema({ ip:String, puertos:String, user:String, pass:String, conexiones:Number, localidad:String }) const user = mongoose.model("user", userSchema); const vps = mongoose.model("vps",vpsSchema); module.exports={ user, vps }
cd3e4efdf3b96028bd8fe45fef55d941219b42cd
[ "JavaScript" ]
3
JavaScript
jhoanhsgs/tienda
46dc3d20b56058aadea36fc2e9703b9a67d194fa
d83ae1e5f99118f34b7f41e8d36b8d73291c171f
refs/heads/master
<repo_name>cafrank/bootcamp<file_sep>/Section-22/Exercise-47.js function cleanNames(oldArray) { return oldArray.map( function(x) { return x.trim(); } ); } // cleanArray( [' Hello ', ' World '] ); <file_sep>/Section-12/grid-work.html <html> <head> <title>Bootstrap Buttons Exercise</title> <!--INCLUDING BOOTSTRAP--> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> </head> <body> <!-- Cool shortcuts !!! .col-6 ==> <div class="col-6"></div> h1.diaplay1 ==> <h1 class="display1"></h1> #foo ==> <div id="foo"></div> img.img-fluid ==> <img src="" alt="" class="img-fluid"> Emmet. Check out http://eljefa.com/ .container>.row>.col-xs-12.col-sm-12.col-md-12 --> <h1 class="display-1 text-center text-primary">The Grid System</h1> <div class="container"> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-12"></div> </div> </div> <div class="container"> <div class="row"> <div class="col-6 bg-success">Hello</div> <div class="col-2 bg-info">World</div> <div class="col-4 bg-danger">2</div> </div> <div class="row"> <div class="col bg-success">Hello</div> <div class="col bg-info">World</div> <div class="col bg-danger">2</div> </div> <h2 class="display-2">Responsive Grid</h2> <div class="row align-items-end"> <div class="col-md-6 col-xl-3 bg-success">Writing objects: 100% (6/6), 1.34 KiB | 685.00 KiB/s, done. remote: Resolving deltas: 100% (1/1), completed with 1 local object. To https://github.com/cafrank/bootcamp 33b6a35..26a1453 master -> master cfrank@spin:~/git/bootcamp/Section-12$ ^C cfrank@spin:~/git/bootcamp/Section-12$ Lorem, ipsum dolor sit amet consectetur adipisicing elit. Veniam quam fugiat consequatur quod ab deleniti eveniet perspiciatis non tempora rem itaque quasi suscipit ipsum magni culpa facilis, error ipsa reiciendis!Inventore incidunt aliquid earum fuga maxime perferendis magnam aut dolor quam esse, excepturi vero sapiente labore? Aperiam, eaque possimus perferendis adipisci, eveniet sapiente ratione quia deleniti atque sit velit quas. </div> <div class="col-md-6 col-xl-3 bg-info">Writing objects: 100% (6/6), 1.34 KiB | 685.00 KiB/s, done. Total 6 (delta 1), reused 0 (delta 0) remote: Resolving deltas: 100% (1/1), completed with 1 local object. To https://github.com/cafrank/bootcamp 33b6a35..26a1453 master -> master cfrank@spin:~/git/bootcamp/Section-12$ ^C cfrank@spin:~/git/bootcamp/Section-12$ Total 6 (delta 1), reused 0 (delta 0) remote: Resolving deltas: 100% (1/1), completed with 1 local object. To https://github.com/cafrank/bootcamp 33b6a35..26a1453 master -> master cfrank@spin:~/git/bootcamp/Section-12$ ^C cfrank@spin:~/git/bootcamp/Section-12$ </div> <div class="col-md-6 col-xl-3 bg-success">Writing objects: 100% (6/6), 1.34 KiB | 685.00 KiB/s, done. Total 6 (delta 1), reused 0 (delta 0) remote: Resolving deltas: 100% (1/1), completed with 1 local object. To https://github.com/cafrank/bootcamp 33b6a35..26a1453 master -> master cfrank@spin:~/git/bootcamp/Section-12$ ^C cfrank@spin:~/git/bootcamp/Section-12$ </div> <div class="col-md-6 col-xl-3 bg-info">Writing objects: 100% (6/6), 1.34 KiB | 685.00 KiB/s, done. Total 6 (delta 1), reused 0 (delta 0) remote: Resolving deltas: 100% (1/1), completed with 1 local object. To https://github.com/cafrank/bootcamp 33b6a35..26a1453 master -> master cfrank@spin:~/git/bootcamp/Section-12$ ^C cfrank@spin:~/git/bootcamp/Section-12$ </div> </div> <h2 class="display-2">Fliud Image</h2> <div class="row no-gutters"> <img class="col-xl-4 col-md-6" alt="" class="img-fluid" src="https://images.unsplash.com/photo-1452570053594-1b985d6ea890?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80"> <img class="col-xl-4 col-md-6" alt="" class="img-fluid" src="https://images.unsplash.com/photo-1548509925-0e7aa59c6bc3?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=700&q=80"> <img class="col-xl-4 col-md-6" alt="" class="img-fluid" src="https://images.unsplash.com/photo-1542382156909-9ae37b3f56fd?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1113&q=80"> </div> </div> </body> </html <file_sep>/Section-21/Exercise-45.js const square = { area: function(sideLength) { return sideLength * sideLength; }, perimeter: function(sideLength) { return sideLength * 4; } } <file_sep>/Section-22/Exercise-49.js function validUserNames(userNames) { return userNames.filter(name => name.length < 10) } <file_sep>/Section-20/Exercise-40.js // DEFINE YOUR FUNCTION BELOW: function lastElement(arr) { if (!arr || !arr.length) { return null; } return arr[arr.length-1] } <file_sep>/Section-24/Exercise-54.js // The url you need: 'https://www.flaticon.com/svg/static/icons/svg/3523/3523063.svg' // YOUR CODE GOES IN HERE: // Three waus to get the imang. //let image = document.querySelector('img'); //let image = document.querySelector('#egg'); let image = document.getElementById("egg"); // I like this when available image.alt = 'chicken'; image.src = 'https://www.flaticon.com/svg/static/icons/svg/3523/3523063.svg'; image.setAttribute('alt' = 'chicken'); image.setAttribute('src' = 'https://www.flaticon.com/svg/static/icons/svg/3523/3523063.svg'); <file_sep>/Section-20/calc.js // Version 1 // ======================= // Prompt num1: 5 // Prompt num2: 10 // Prompt Operation: add // Print out 15 // Version 2 // ======================= // // Prompt num1: 5 // Prompt num2: 10 // Prompt Operation: add // Print out 15 // Start over at line 13 unless the command is quit function add(num1, num2) { return num1 + num2; } function subtract(num1, num2) { return num1 - num2; } function multiply(num1, num2) { return num1 * num2; } function divide(num1, num2) { return num1 / num2; } let number1String = prompt ('Enter first number'); let number2String = prompt ('Enter second number'); let operation = prompt ('Enter operation'); //console.log(`You entered ${number1} ${number2} and ${operation}`); let number1 = parseInt(number1String); let number2 = Number (number2String); console.log( multiply(number1, number2) ); // Return the function // How // ========================== Testing ============================ function unitTest() { console.log(add(5,10)); // 15 console.log(multiply(3,5)); // 15 console.log(subtract(10,5)); // 5 console.log(divide(10,5)); // 2 }<file_sep>/Section-20/todos.js const cmdPrompt = 'Enter command: list, add, delete, or quit'; for (let cmd=prompt(cmdPrompt); cmd != 'quit'; cmd=prompt(cmdPrompt) ) { console.log('You typed::', cmd); } // It is nice to get exact mesages from stake holders, and // make constants that cn be quickly reviewed by the team. const cmdPrompt = 'Enter command: list, add, delete, or quit'; const delPrompt = 'Enter number of todo to delete'; const newPrompt = 'Enter new todo'; // Pick the best data structure to hold the data. // The name makes its purpouse obvious. // let todosData = ['Review code', 'REad the entire document']; // Functions, functions, functions !!! function doList() { for(let i=0; i<todosData.length; i++) { console.log(`${i}: ${todosData[i]}...`); } } function doDelete() { let delTodo = cmd=prompt(delPrompt); todosData.splice(delTodo, 1); } // Compact, elegant, but might be hard to read !!! for (let cmd=prompt(cmdPrompt); cmd != 'quit'; cmd=prompt(cmdPrompt) ) { if (cmd.toLowerCase() == 'list') { doList(); } else if (cmd.toLowerCase() == 'delete') { doList(); doDelete(); } else if (cmd.toLowerCase() == 'add') { let newTodo = cmd=prompt(newPrompt); todosData.push(newTodo); } else { console.log('Invalid command:', cmd); } } // cmd=prompt(cmdPrompt); // while (cmd != 'quit') { // if (cmd.toLowerCase() == 'list') { // // console.log('LIST:', cmd); // for (let i=0; i<todosData.length; i++) { // console.log(`${i}: ${todosData[i]}`); // } // } else if (cmd.toLowerCase() == 'delete') { // // console.log('DELETE:', cmd); // for (let i=0; i<todosData.length; i++) { // Same loop above. Fonction? // console.log(`${i}: ${todosData[i]}`); // } // let delIndex = cmd=prompt(delPrompt); // todosData.splice(delIndex, 1); // } else if (cmd.toLowerCase() == 'new') { // let newTodo = cmd=prompt(newPrompt); // todosData.push(newTodo); // // console.log('NEW:', cmd); // } else { // console.log('Invlid command:', cmd); // } // cmd=prompt(cmdPrompt) // } // Dense for loop for (let isCold=true; isCold; isCold=false) { console.log('Heating up'); } // The same thing done with more lines in a while loop let isCold = true; let temp = 40; // This is cold isCold = (temp < 70) while(temp < 70) { console.log('Heating up'); isCold = false; } <file_sep>/Section-20/Exercise-38.js // DEFINE YOUR FUNCTION BELOW: function multiply(x, y) { return x * y; } <file_sep>/Section-20/Exercise-43.js // DEFINE YOUR FUNCTION BELOW: function returnDay(dayNum) { const day = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]; if (dayNum <1 || dayNum>7) { return null; } else { return day[dayNum - 1]; } } <file_sep>/Section-24/Exercise-51.js // Write your code in here: let image = document.getElementById("unicorn"); let heading = document.getElementById("mainheading"); <file_sep>/Section-17/stuff.js // Multi-type array OK let junk = [true, undefined, 12, 99.999, NaN]; let days = ["Manday", "Tuesday", "Wednesday", "THursday", "Friday"]; days[3][1]; // H let stuff = ["Manday", "Tuesday", empty "Wednesday", "THursday", "Friday"]; stuff[20] = "Someday"; // Array with empty slots 'LOL'.length; days.push("Saturday"); // Adds to end of array days.pop(); // returns the last element: "Saturday" days.shift("ZeroDay"); // adds to front of array days.unshift();<file_sep>/Section-17/Exercise-25/index.js // Define lottoNumbers below: let lottoNumbers = [ 11, 36, 55, 44, 55, 66];<file_sep>/Section-20/Exercise-37.js // define isSnakeEyes below: function isSnakeEyes(x, y) { if (x===1 && y===1) { console.log("Snake Eyes!") } else { console.log("Not Snake Eyes!") } } <file_sep>/Section-14/Exercise-16/stuff.js // Increment, autoincrement, autodecrement... let score = 1; score++; score += 4; // Constant const pi = 3.141592654; // OLd ver stype let oldScore = 1; // Obsolete // Changing types sucks. DOn't do!!! // Start with // Naming convistion let n = 4; // Not descriptive enough // Snake case. OK but not best convention let foo_bar = 4; // Camel case. Good boolean neam let isLoggisIn = true;<file_sep>/Section-19/loop-stuff.js for (let i=0; i<6; i++) { console.log(i); } for (let i=0; i<60; i+=5) { console.log(i); } const animals = [ 'lions', 'tigers', 'goats']; for (let i=0; i<3; i++) { console.log(i, anamals[i]); } for (let i=0; i<anamals.length; i++) { console.log(i, anamals[i]); } for (let i=0; i<anamals.length; i++) { console.log(i, anamals[i]); } for (let a of anamals) { console.log(a); } let num = parseInt(prompt("Emter a number: ")); console.log(num); const testScores = { jim: 44, bob: 43, tim: 55, bill: 46 }; for (let key in testScores) { console.log(key, testScores[key]); } <file_sep>/Section-25/Exercise-61.js // Leave the next line, the form must be assigned to a variable named 'form' in order for the exercise test to pass const form = document.querySelector('form'); // console.dir(form) Play in the browser console to figure it out. // 1. We need to clear out form action. form.action = null ??? NO! // e.preventDefault(); // 2. Ah, that's right onsubmit const list = document.getElementById('list'); const handleSubmit = e => { console.log('SUBMIT'); const li = document.createElement('li') // const qty = document.querySelector('form input#qty'); // This works const qty = document.getElementById('qty'); // Faster const name = document.getElementById('product'); li.innerText = `${name.value} ${qty.value}` list.appendChild(li) qty.value = null; name.value = null; e.preventDefault(); } form.addEventListener('submit', handleSubmit); // form.onsubmit = handleSubmit; This also works. Single handler // ======================= Method 2 =========================== // OR combined with an anonymous handler function. // This prevents the handler from getting separated or used somewhere // else, but when the handler gets too large this looks ugly form.addEventListener('submit', e => { const li = document.createElement('li') const qty = document.getElementById('qty'); // Faster const name = document.getElementById('product'); li.innerText = `${name.value} ${qty.value}` list.appendChild(li) qty.value = name.value = null; // Setting two variables at the same time to the same thing e.preventDefault(); }); <file_sep>/Section-22/Exercise-48.js const greet = (message) => { return `Hey ${message}!` }; // greet('Joe'); // greet('Kevin'); <file_sep>/Section-24/Exercise-58.js let div = document.getElementById("container"); for (let i=0; i<100; i++) { let button = document.createElement("button"); button.innerText = 'b'+i; div.appendChild(button); } <file_sep>/Section-20/Exercise-41.js // DEFINE YOUR FUNCTION BELOW: function capitalize(x) { return x[0].toUpperCase() + x.substring(1) } <file_sep>/Section-20/Exercise-42.js // DEFINE YOUR FUNCTION BELOW: function sumArray(arr) { let sum = 0; for(let x of arr) { sum += x; } return sum; } <file_sep>/Section-25/Exercise-60.js const handleHay = e => { console.log('hello') } // Anon function expression assignment function handleBye(e) { // Oldschool function definition console.log('goodbye') } let hay = document.getElementById("hello"); let bye = document.getElementById("goodbye"); hay.addEventListener('click', handleHay) bye.addEventListener('click', handleBye) // Geek shortcut. Harder to follow // document.getElementById("hello").addEventListener('click', e => console.log('hello'))<file_sep>/Section-20/Exercise-35.js // Write your functcd ion here: function printHeart() { console.log("<3"); } printHeart();<file_sep>/Section-22/Exercise-50.js // Note is number is Even if the remainder is 0 when divided by 2 // num %2 === 0 function allEvens(nums) { return nums.every(x => x%2==0); } <file_sep>/Section-20/Exercise-36.js // DEFINE YOUR FUNCTION: function rant(message) { for(let i=0; i<3; i++) { console.log(message.toUpperCase()) } }
31cb99477f75326be00281fcbe1502e9f582dd8e
[ "JavaScript", "HTML" ]
25
JavaScript
cafrank/bootcamp
c12ce7ab575972168384ff727b6f15623d976d6f
04cf334479b3f8a134ee19985b7557f980b54d98
refs/heads/master
<file_sep>package cn.com.lasong.zapp.base.contract import android.content.Context import android.content.Intent import android.net.Uri import android.provider.DocumentsContract import androidx.activity.result.contract.ActivityResultContract import java.io.File /** * Author: zhusong * Email: <EMAIL> * Date: 2021/6/28 * Description: */ class PickDirectory : ActivityResultContract<String, Uri>() { override fun createIntent(context: Context, input: String): Intent { val dir = File(input) var file = dir if (dir.isDirectory) { file = File(dir, "file") } return Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply { putExtra(DocumentsContract.EXTRA_INITIAL_URI, Uri.fromFile(file)); } } override fun parseResult(resultCode: Int, intent: Intent?): Uri? { return intent?.data/*FileUtils.getFilePath(applicationContext(), intent?.data)*/ } }<file_sep>package cn.com.lasong.zapp.base import android.R import android.view.View import android.view.ViewGroup import cn.com.lasong.base.BaseActivity import cn.com.lasong.widget.utils.ViewHelper /** * Author: zhusong * Email: <EMAIL> * Date: 2021/6/5 * Description: 应用类基础activity */ open class AppBaseActivity : BaseActivity() { /** * 适配状态栏类型枚举 */ enum class FitStatusBarType { NONE, // 没有适配 PADDING, // 以padding适配 MARGIN // 以margin适配 } /** * 设置完布局后的回调 */ override fun onContentChanged() { super.onContentChanged() // 透明化状态栏 if (transparentStatusBar()) { ViewHelper.transparentStatusBar(this) } // 适配状态栏 if (transparentStatusBar() && fitStatusBarType() != FitStatusBarType.NONE) { val content = findViewById<View>(R.id.content) if (content is ViewGroup) { val resId = fitStatusBarResId() val appContent = if (resId == View.NO_ID) { content.getChildAt(0) } else { content.findViewById(resId) } ViewHelper.fitStatusBar(appContent, fitStatusBarType() == FitStatusBarType.PADDING) } } } /** * 适配透明化状态栏的方式 * 默认使用PADDING方式 * @return */ open fun fitStatusBarType(): FitStatusBarType { return FitStatusBarType.PADDING } /** * 返回 需要适配透明化状态栏的控件ID * NO_ID 代表当前activity布局的ROOT控件 * @return */ open fun fitStatusBarResId(): Int { return View.NO_ID } /** * 是否透明化状态栏 * @return */ open fun transparentStatusBar(): Boolean { return false } }<file_sep>package cn.com.lasong.zapp.ui.home import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.navigation.findNavController import androidx.navigation.fragment.findNavController import cn.com.lasong.base.BaseFragment import cn.com.lasong.widget.utils.ViewHelper import cn.com.lasong.zapp.R import cn.com.lasong.zapp.databinding.FragmentHomeBinding class HomeFragment : BaseFragment() { private lateinit var homeViewModel: HomeViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { homeViewModel = ViewModelProvider(this).get(HomeViewModel::class.java) val binding = FragmentHomeBinding.inflate(layoutInflater, container, false) ViewHelper.setClickAlpha(binding.cardRecordScreen) // ViewHelper.setClickAlpha(binding.cardRecordCamera) binding.cardRecordScreen.setOnClickListener { findNavController().also {controller -> controller.navigate(R.id.action_nav_home_to_nav_screen) } } // binding.cardRecordCamera.setOnClickListener { // // } return binding.root } }<file_sep>package cn.com.lasong.zapp.ui.home.screen import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import cn.com.lasong.zapp.ZApp import cn.com.lasong.zapp.data.RecordBean import cn.com.lasong.zapp.data.RecordKey import com.tencent.mmkv.MMKV /** * Author: zhusong * Email: <EMAIL> * Date: 2021/6/8 * Description: */ class RecordScreenViewModel : ViewModel() { val params = MutableLiveData<RecordBean>().apply { MMKV.defaultMMKV().let { it?.getString(ZApp.KEY_RECORD_SAVE, null) }.let { if (it != null) { value = ZApp.JSON.fromJson(it, RecordBean::class.java) } value = value ?: RecordBean() } } fun updateFreeSize() { val value = params.value params.postValue(value) } fun updateVideo(key : RecordKey, position: Int) { val value = params.value when(key) { RecordKey.DIRECTION -> value?.videoDirection = position RecordKey.RESOLUTION -> value?.videoResolution = position RecordKey.VIDEO_BITRATE -> value?.videoBitrate = position RecordKey.FPS -> value?.videoFps = position RecordKey.SAMPLE_RATE -> value?.audioSampleRate = position RecordKey.AUDIO_BITRATE -> value?.audioBitrate = position RecordKey.CHANNEL -> value?.audioChannel = position else -> Unit } params.postValue(value) } fun setAudioEnable(checked: Boolean) { val value = params.value value?.audioEnable = checked params.postValue(value) } }<file_sep>package cn.com.lasong.zapp.ui.home import android.content.Context import android.os.Bundle import android.widget.CheckedTextView import androidx.recyclerview.widget.LinearLayoutManager import cn.com.lasong.widget.adapterview.adapter.OnItemClickListener import cn.com.lasong.widget.adapterview.adapter.ZRecyclerViewAdapter import cn.com.lasong.zapp.R import cn.com.lasong.zapp.databinding.DialogOptionsBinding import com.google.android.material.bottomsheet.BottomSheetDialog /** * Author: zhusong * Email: <EMAIL> * Date: 2021/7/6 * Description: * 选项弹窗 */ class OptionDialog(context: Context) : BottomSheetDialog(context, R.style.ZBottomSheetDialog) { companion object { fun newInstance( context: Context, title: String, options: Array<String>, selectedIndex: Int = 0, listener: OnItemClickListener? = null ): OptionDialog { val dialog = OptionDialog(context) dialog.title = title dialog.options = options dialog.selectedIndex = selectedIndex dialog.listener = listener return dialog } } lateinit var title: String lateinit var options: Array<String> var selectedIndex: Int = 0 var listener: OnItemClickListener? = null lateinit var adapter: ZRecyclerViewAdapter<String> val data : MutableList<String> = ArrayList() lateinit var binding: DialogOptionsBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DialogOptionsBinding.inflate(layoutInflater) setContentView(binding.root) data.addAll(options) adapter = object : ZRecyclerViewAdapter<String>(data, R.layout.item_option, OnItemClickListener { view, position -> listener?.onItemClick(view, position) dismiss() }) { override fun bind(holder: AdapterViewHolder, item: String?, position: Int) { val textView = holder.itemView as CheckedTextView textView.text = item textView.isChecked = position == selectedIndex } } binding.rvOptions.layoutManager = LinearLayoutManager(context) binding.rvOptions.adapter = adapter binding.tvTitle.text = title } }<file_sep>// Top-level build file where you can add configuration options common to all sub-projects/modules. apply from: 'config.gradle' buildscript { ext { kotlin_version = '1.4.31' } repositories { google() jcenter() mavenCentral() maven { url "https://jitpack.io" } } dependencies { classpath "com.android.tools.build:gradle:3.6.4" // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1' classpath "cn.com.lasong:plugin:0.0.7.1" classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" // classpath "com.github.zhusonger.androidz:plugin:1.0.0" } } allprojects { repositories { google() jcenter() maven { url "https://jitpack.io" } } //最好加上全局编码设置 tasks.withType(Javadoc) { options { encoding "UTF-8" charSet 'UTF-8' links "http://docs.oracle.com/javase/8/docs/api" failOnError false } } if (JavaVersion.current().isJava8Compatible()) { tasks.withType(Javadoc) { // disable the crazy super-strict doclint tool in Java 8 //noinspection SpellCheckingInspection options.addStringOption('Xdoclint:none', '-quiet') } } configurations.all { resolutionStrategy.cacheChangingModulesFor 0, 'seconds' } group = rootProject.ext.groupId } task clean(type: Delete) { delete rootProject.buildDir } <file_sep>package cn.com.lasong.widget; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import androidx.annotation.Nullable; import cn.com.lasong.utils.TN; import cn.com.lasong.widget.touch.MoveView; import cn.com.lasong.R; /** * Author: zhusong * Email: <EMAIL> * Date: 2021/2/4 * Description: */ public class IconMoveView extends MoveView implements View.OnClickListener { public IconMoveView(Context context) { this(context, null); } public IconMoveView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public IconMoveView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); LayoutInflater.from(context).inflate(R.layout.view_icon, this); findViewById(R.id.ll_icon).setOnClickListener(this); } @Override public void onClick(View v) { TN.show("点击浮窗"); } } <file_sep>package cn.com.lasong.zapp.data enum class RecordKey { NONE, DIRECTION, RESOLUTION, VIDEO_BITRATE, FPS, SAMPLE_RATE, AUDIO_BITRATE, CHANNEL, DELAY }<file_sep>package cn.com.lasong.sms; import android.Manifest; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.telephony.SmsManager; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.NumberPicker; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.widget.AppCompatCheckBox; import java.io.BufferedReader; import java.io.FileReader; import java.util.Locale; import java.util.Queue; import java.util.concurrent.LinkedBlockingQueue; import cn.com.lasong.R; import cn.com.lasong.app.AppBaseActivity; import cn.com.lasong.utils.FileUtils; import cn.com.lasong.utils.ILog; import cn.com.lasong.utils.TN; /** * Author: zhusong * Email: <EMAIL> * Date: 2020/7/28 * Description: 短信群发 */ public class SmsActivity extends AppBaseActivity implements View.OnClickListener, ISmsListener { private EditText mEdtContent; private Button mBtnSend; private NumberPicker mNpNum; private SmsSendReceiver mSendReceiver; private SmsDeliverReceiver mDeliverReceiver; private AppCompatCheckBox mCbLoad; private TextView mTvSend; private TextView mTvDeliver; private TextView mTvDeliverRatio; private int mAllPhoneNum; private int mOnceNum = 100; private int mAllSendNum = 0; private int mAllDeliverNum = 0; private Queue<String> mPhoneQueue = new LinkedBlockingQueue<>(); public final int REQUEST_CODE_DOC = 111; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sms); mCbLoad = findViewById(R.id.cb_load); mEdtContent = findViewById(R.id.edt_content); mBtnSend = findViewById(R.id.btn_send); mTvSend = findViewById(R.id.tv_send); mTvDeliver = findViewById(R.id.tv_deliver); mTvDeliverRatio = findViewById(R.id.tv_deliver_ratio); mNpNum = findViewById(R.id.np_num); mNpNum.setMinValue(1); mNpNum.setMaxValue(200); mNpNum.setValue(mOnceNum); mNpNum.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() { @Override public void onValueChange(NumberPicker numberPicker, int previous, int current) { mOnceNum = current; } }); mCbLoad.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { mBtnSend.setText("加载"); } else { mBtnSend.setText("发送"); } } }); //注册广播 mSendReceiver = new SmsSendReceiver(); registerReceiver(mSendReceiver, SmsSendReceiver.createFilter()); mDeliverReceiver = new SmsDeliverReceiver(); registerReceiver(mDeliverReceiver, SmsDeliverReceiver.createFilter()); mSendReceiver.setListener(this); mDeliverReceiver.setListener(this); mBtnSend.setOnClickListener(this); mBtnSend.setText("加载"); ILog.setLogLevel(Log.DEBUG); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mSendReceiver); unregisterReceiver(mDeliverReceiver); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (grantResults[0] != PackageManager.PERMISSION_GRANTED || grantResults[1] != PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show(); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQUEST_CODE_DOC: if (resultCode == Activity.RESULT_OK && data != null) { Uri uri = data.getData(); try { String path = FileUtils.getFilePath(this, uri); BufferedReader reader = new BufferedReader(new FileReader(path)); boolean checked = false; String line; while ((line = reader.readLine()) != null) { if (!checked) { if(line.length() != 11) { break; } checked = true; } mPhoneQueue.offer(line); } if (!mPhoneQueue.isEmpty()) { mAllPhoneNum = mPhoneQueue.size(); mTvSend.setText(String.format(Locale.CHINA, "发送成功(0/%d)", mAllPhoneNum)); mTvDeliver.setText(String.format(Locale.CHINA, "送达成功(0/%d)", mAllPhoneNum)); TN.show("加载成功"); mCbLoad.setChecked(false); } else { TN.show("不符合要求的文件"); } reader.close(); } catch (Exception e) { e.printStackTrace(); TN.showError("文件读取失败"); } } mBtnSend.setEnabled(true); break; } } @Override public void onClick(View v) { requestPermissions((isGrant, result) -> { if (!isGrant || v != mBtnSend) { return; } if (mCbLoad.isChecked()) { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE); intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); try { startActivityForResult(Intent.createChooser(intent, "Choose File"), REQUEST_CODE_DOC); } catch (ActivityNotFoundException e) { Toast.makeText(SmsActivity.this, "亲,木有文件管理器啊-_-!!", Toast.LENGTH_SHORT).show(); } return; } String content = mEdtContent.getText().toString(); if (TextUtils.isEmpty(content) || TextUtils.isEmpty(content.trim())) { TN.show("短信内容不能为空"); return; } if (mPhoneQueue.isEmpty()) { TN.show("没有有效的电话号码"); return; } mBtnSend.setEnabled(false); SmsManager manager = SmsManager.getDefault(); int sendNum = 0; while (!mPhoneQueue.isEmpty() && sendNum < mOnceNum) { String phone = mPhoneQueue.poll(); manager.sendTextMessage(phone, null, content, SmsSendReceiver.createIntent(getApplicationContext()), SmsDeliverReceiver.createIntent(getApplicationContext())); sendNum++; } mBtnSend.setEnabled(true); }, Manifest.permission.SEND_SMS, Manifest.permission.READ_EXTERNAL_STORAGE); } @Override public void onSend(String message) { // 发送成功 if (TextUtils.isEmpty(message)) { mAllSendNum++; mTvSend.setText(String.format(Locale.CHINA, "发送成功(%d/%d)", mAllSendNum, mAllPhoneNum)); } // 发送失败 else { TN.showError(message); } } @Override public void onDeliver() { // 发送到目标用户 mAllDeliverNum++; mTvDeliver.setText(String.format(Locale.CHINA, "送达成功(%d/%d)", mAllDeliverNum, mAllPhoneNum)); mTvDeliverRatio.setText(String.format(Locale.CHINA, "送达率(%.1f%%)", (mAllDeliverNum * 100.0f / mAllSendNum))); } }<file_sep>package cn.com.lasong.zapp.ui.home.screen import android.content.Context import android.content.Intent import android.os.Build import android.os.Bundle import android.os.storage.StorageManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.content.ContextCompat import androidx.lifecycle.ViewModelProvider import cn.com.lasong.base.BaseFragment import cn.com.lasong.widget.utils.ViewHelper import cn.com.lasong.zapp.R import cn.com.lasong.zapp.ZApp.Companion.applicationContext import cn.com.lasong.zapp.data.RecordBean import cn.com.lasong.zapp.data.RecordKey import cn.com.lasong.zapp.databinding.FragmentRecordScreenBinding import cn.com.lasong.zapp.ui.home.OptionDialog /** * Author: zhusong * Email: <EMAIL> * Date: 2021/6/8 * Description: * 屏幕录制页面 */ class RecordScreenFragment : BaseFragment(), View.OnClickListener { private lateinit var viewModel: RecordScreenViewModel private lateinit var binding: FragmentRecordScreenBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { viewModel = ViewModelProvider(this).get(RecordScreenViewModel::class.java) binding = FragmentRecordScreenBinding.inflate(layoutInflater, container, false) viewModel.params.observe(viewLifecycleOwner, { binding.tvFreeSize.text = it.freeSizeDisplay when { it.appFreeSize >= RecordBean.SIZE_MIN_VALUE -> { binding.tvFreeSize.setTextColor( ContextCompat.getColor( applicationContext(), R.color.colorPrimaryDark ) ) } else -> { binding.tvFreeSize.setTextColor( ContextCompat.getColor( applicationContext(), R.color.colorError ) ) } } binding.tvVideoDirection.text = it.directionDisplay binding.tvVideoResolution.text = it.videoResolutionDisplay binding.tvVideoBitrate.text = it.videoBitrateDisplay binding.tvVideoFps.text = it.videoFpsDisplay binding.stAudio.isChecked = it.audioEnable binding.tvSampleRate.text = it.audioSampleRateDisplay binding.tvChannel.text = it.audioChannelDisplay binding.tvAudioBitrate.text = it.audioBitrateDisplay binding.tvDelay.text = it.delayDisplay if (it.audioEnable) { binding.llAudioParams.visibility = View.VISIBLE } else { binding.llAudioParams.visibility = View.GONE } }) binding.llFreeSize.setOnClickListener(this) binding.llVideoDirection.setOnClickListener(this) binding.llResolution.setOnClickListener(this) binding.llVideoBitrate.setOnClickListener(this) binding.llFps.setOnClickListener(this) binding.llSampleRate.setOnClickListener(this) binding.llChannel.setOnClickListener(this) binding.llAudioBitrate.setOnClickListener(this) binding.llDelay.setOnClickListener(this) binding.layoutRecord.setOnClickListener(this) ViewHelper.setClickAlpha(binding.layoutRecord) binding.stAudio.setOnCheckedChangeListener { _, isChecked -> viewModel.setAudioEnable(isChecked) } return binding.root } override fun onReStart() { super.onReStart() viewModel.updateFreeSize() } override fun onClick(v: View) { val context = v.context when (v) { binding.llFreeSize -> { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) { val storageIntent = Intent().apply { action = StorageManager.ACTION_MANAGE_STORAGE } startActivity(storageIntent) } } binding.llVideoDirection, binding.llResolution, binding.llVideoBitrate, binding.llFps, binding.llSampleRate, binding.llChannel, binding.llAudioBitrate -> { val key = when (v) { binding.llVideoDirection -> RecordKey.DIRECTION binding.llResolution -> RecordKey.RESOLUTION binding.llVideoBitrate -> RecordKey.VIDEO_BITRATE binding.llFps -> RecordKey.FPS binding.llSampleRate -> RecordKey.SAMPLE_RATE binding.llChannel -> RecordKey.CHANNEL binding.llAudioBitrate -> RecordKey.AUDIO_BITRATE else -> RecordKey.NONE } showRecordOptions(context, key) } binding.layoutRecord -> { startRecord() } } } /*显示视频选项*/ private fun showRecordOptions(context: Context, key: RecordKey) { val title: String val array: Array<String> val selectIndex: Int when (key) { RecordKey.DIRECTION -> { title = context.getString(R.string.record_video_direction) array = resources.getStringArray(R.array.array_direction) selectIndex = viewModel.params.value?.videoDirection!! } RecordKey.RESOLUTION -> { title = context.getString(R.string.record_video_resolution) array = resources.getStringArray(R.array.array_resolution) selectIndex = viewModel.params.value?.videoResolution!! } RecordKey.VIDEO_BITRATE -> { title = context.getString(R.string.record_bitrate) array = resources.getStringArray(R.array.array_video_bitrate) selectIndex = viewModel.params.value?.videoBitrate!! } RecordKey.FPS -> { title = context.getString(R.string.record_video_fps) array = resources.getStringArray(R.array.array_fps) selectIndex = viewModel.params.value?.videoFps!! } RecordKey.SAMPLE_RATE -> { title = context.getString(R.string.record_sample_rate) array = resources.getStringArray(R.array.array_sample_rate) selectIndex = viewModel.params.value?.audioSampleRate!! } RecordKey.AUDIO_BITRATE -> { title = context.getString(R.string.record_bitrate) array = resources.getStringArray(R.array.array_audio_bitrate) selectIndex = viewModel.params.value?.audioBitrate!! } RecordKey.CHANNEL -> { title = context.getString(R.string.record_channel) array = resources.getStringArray(R.array.array_channels) selectIndex = viewModel.params.value?.audioChannel!! } RecordKey.DELAY -> { title = context.getString(R.string.record_delay) array = resources.getStringArray(R.array.array_delay) selectIndex = viewModel.params.value?.delay!! } else -> { title = "" array = emptyArray() selectIndex = 0 } } OptionDialog.newInstance( context, title, array, selectIndex ) { _, position -> viewModel.updateVideo(key, position) } .show() } private fun startRecord() { } }<file_sep>package cn.com.lasong.zapp import android.app.Service import android.content.Intent import android.os.* /** * Author: zhusong * Email: <EMAIL> * Date: 2021/6/5 * Description: * 核心服务 */ class CoreService : Service(), Handler.Callback { companion object { /** * Command to the service to register a client, receiving callbacks * from the service. The Message's replyTo field must be a Messenger of * the client where callbacks should be sent. */ const val MSG_REGISTER_CLIENT = 1 /** * Command to the service to unregister a client, ot stop receiving callbacks * from the service. The Message's replyTo field must be a Messenger of * the client as previously given with MSG_REGISTER_CLIENT. */ const val MSG_UNREGISTER_CLIENT = 2 /** * 回复OK表示成功 */ const val RES_OK = "OK" } /** Keeps track of all current registered clients. */ var mClients = ArrayList<Messenger>() private val handler = Handler(this) /** * Target we publish for clients to send messages to IncomingHandler. */ private val mMessenger: Messenger = Messenger(handler) override fun onBind(intent: Intent?): IBinder? { return mMessenger.binder } override fun onDestroy() { super.onDestroy() mClients.clear() handler.removeCallbacksAndMessages(null) } /** * 通知客户端 */ private fun notifyClients(msg: Message) { for (i in mClients.indices.reversed()) { try { mClients[i].send(msg) } catch (e: RemoteException) { // The client is dead. Remove it from the list; // we are going through the list from back to front // so this is safe to do inside the loop. mClients.removeAt(i) } } } /** 实际业务功能↓ **/ override fun handleMessage(msg: Message): Boolean { when (msg.what) { MSG_REGISTER_CLIENT -> { mClients.add(msg.replyTo) val replayMsg = Message.obtain(handler) replayMsg.what = MSG_REGISTER_CLIENT replayMsg.obj = RES_OK notifyClients(replayMsg) } MSG_UNREGISTER_CLIENT -> { val replayMsg = Message.obtain(handler) replayMsg.what = MSG_UNREGISTER_CLIENT replayMsg.obj = RES_OK notifyClients(replayMsg) mClients.remove(msg.replyTo) } } return true } }<file_sep># AndroidZ AndroidZ开源项目, 简化平时开发时的重复性工作 由于jcenter的停用, 迁移到jitpack 需要引入jitpack存储库 ``` allprojects { repositories { // 其他 ... maven { url "https://jitpack.io" } } } ``` ## Base 基础库 https://github.com/zhusonger/zbase ``` implementation 'com.github.zhusonger:zbase:master-SNAPSHOT' ``` ## Widget 控件库 https://github.com/zhusonger/zwidget ``` implementation 'com.github.zhusonger:zwidget:master-SNAPSHOT' ``` ## Media 媒体库 https://github.com/zhusonger/zmedia ``` implementation 'com.github.zhusonger:zmedia:master-SNAPSHOT' ``` ## Plugin 插件库 https://github.com/zhusonger/androidz/tree/master/plugin ``` // 根目录build.gradle buildscript { repositories { // 其他 ... maven { url "https://jitpack.io" } } dependencies { // 1.添加classpath classpath 'com.github.zhusonger.androidz:plugin:master-SNAPSHOT' } } // module的build.gradle apply plugin: 'cn.com.lasong.inject' // 统计耗时 apply plugin: 'cn.com.lasong.time' ```<file_sep>apply plugin: 'com.android.application' apply plugin: 'cn.com.lasong.time' apply plugin: 'cn.com.lasong.inject' android { compileSdkVersion rootProject.ext.compileSdkVersion buildToolsVersion rootProject.ext.buildToolsVersion defaultConfig { applicationId "cn.com.lasong" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } viewBinding { enabled = true } } repositories { flatDir { dirs 'libs' } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar', '*.aar']) implementation 'androidx.constraintlayout:constraintlayout:2.0.4' implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.1' implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1' testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test.ext:junit:1.1.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' implementation 'androidx.appcompat:appcompat:1.1.0' implementation 'com.google.android.material:material:1.3.0' implementation "androidx.recyclerview:recyclerview:1.1.0" // implementation 'com.github.zhusonger:zbase:1.0.0' // implementation 'com.github.zhusonger:zwidget:1.0.0' // implementation 'com.github.zhusonger:zmedia:1.1.0' implementation project(":media") implementation project(":widget") implementation project(":base") // 单独添加核心 module Transferee, 之后至少还需要添加以下三种图片加载器中的一种 implementation "com.github.Hitomis.transferee:Transferee:1.6.1@aar" // 添加 Glide 图片加载器 implementation 'com.github.Hitomis.transferee:GlideImageLoader:1.6.1' implementation 'com.github.bumptech.glide:glide:4.11.0' annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0' implementation 'com.github.MZCretin:CitySelect:1.0.5' } allInjects { // 是否开启debug 目前主要打印日志 injectDebug true // 注入的节点, 区分注入的对象 injectDomains { Transferee { group "com.github.Hitomis.transferee:Transferee:1.6.1" // 需要修改的字节码包 clzModify = [ [ className : 'com.hitomi.tilibrary.transfer.TransferAdapter', modifiers: "public", // 修改方法 injectList : [ [ name : "newParentLayout", params : "(Landroid.view.ViewGroup;I)", newName: "newParentLayout_impl" ], [ action : "ADD_METHOD", content: """ private FrameLayout newParentLayout(android.view.ViewGroup container, int pos){ FrameLayout parentLayout = newParentLayout_impl(container, pos); View contentView = parentLayout.getChildAt(0); contentView.setBackgroundColor(Color.parseColor("#80000000")); Context context = container.getContext(); TransferConfig config = transfer.getTransConfig(); ImageView ivBg = new ImageView(context); ivBg.setLayoutParams(new android.widget.FrameLayout.LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT, android.view.ViewGroup.LayoutParams.MATCH_PARENT)); parentLayout.addView(ivBg, 0); String url = (String) config.getSourceUrlList().get(pos); // com.youxi.yxapp.utils.glide.GlideUtils.loadViewAppleBlue(context, url, ivBg); ivBg.setBackgroundColor(Color.parseColor("#FFFFFF")); return parentLayout; } """ ], [ name : "getImageItem", params : "(I)", type : "setBody", content: """{ FrameLayout parentLayout = (FrameLayout) containLayoutArray.get(\$1); if (parentLayout != null && parentLayout.getChildAt(1) instanceof TransferImage) { return ((TransferImage) parentLayout.getChildAt(1)); } return null; }""" ] ] ], [ className : 'com.hitomi.tilibrary.loader.ImageProcessor$ImageTask', // 修改方法 injectList : [ [ name : "run", params : "()", catchType : "java.lang.Exception", catchContent : "return;" ] ] ] ] } CitySelect { group "com.github.MZCretin:CitySelect:1.0.5" // 需要修改的字节码包 clzModify = [ [ className: "com.cretin.tools.cityselect.view.CitySelectView", injectList : [ [ name: "init", params: "(Landroid/content/Context;Landroid/util/AttributeSet;I)", type: "insertBefore", content: "android.view.View.inflate(\$1, 123, this);" ], [ name: "init", params: "(Landroid/content/Context;Landroid/util/AttributeSet;I)", type: "deleteAt", lineRange: "2#1" ] ] ], [ className: "com.cretin.tools.cityselect.view.FastIndexView", injectList : [ [ isConstructor : true, params: "(Landroid/content/Context;Landroid/util/AttributeSet;I)", type: "deleteAt", lineRange: "6" ], [ isConstructor : true, params: "(Landroid/content/Context;Landroid/util/AttributeSet;I)", type: "insertAt", lineNum:6, content: """selectedColor = Color.parseColor("#999999");""" ] ] ] ] } } }<file_sep>package cn.com.lasong.zapp import android.net.Uri import android.os.Bundle import android.os.Environment import androidx.activity.result.ActivityResultCallback import androidx.activity.result.contract.ActivityResultContracts import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.navigateUp import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import cn.com.lasong.utils.ILog import cn.com.lasong.zapp.base.CoreActivity import cn.com.lasong.zapp.databinding.ActivityMainBinding class MainActivity : CoreActivity() { private lateinit var appBarConfiguration: AppBarConfiguration private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.appBarMain.toolbar) val navController = findNavController(R.id.nav_host_fragment) // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. appBarConfiguration = AppBarConfiguration(setOf( R.id.nav_home, R.id.nav_gallery, R.id.nav_video), binding.drawerLayout) setupActionBarWithNavController(navController, appBarConfiguration) binding.navView.setupWithNavController(navController) // val pickLauncher = registerForActivityResult( // ActivityResultContracts.GetContent(), // object : ActivityResultCallback<Uri?> { // override fun onActivityResult(uri: Uri?) { // // Handle the returned Uri // ILog.d("uri :" + uri) // } // }) // // pickLauncher.launch(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).absolutePath) } override fun onSupportNavigateUp(): Boolean { val navController = findNavController(R.id.nav_host_fragment) return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } }<file_sep>include ':zapp' include ':app' //include ':widget' //include ':base' //include ':media' //include ':plugin' <file_sep>ext { // android sdk minSdkVersion = 21 targetSdkVersion = 29 compileSdkVersion = 29 buildToolsVersion = "29.0.2" // jitpack groupId = "com.github.zhusonger" base = "1.0.0" widget = "1.0.0" media = "1.0.0" plugin = "1.0.0" }<file_sep>#!/bin/bash echo "开始git clone任务" echo "开始Base项目" rm -rf base mkdir base ret=`git clone <EMAIL>:zhusonger/zbase.git base` cd base cp -f build.gradle.bak build.gradle cd .. echo "完成Base项目" echo "开始Widget项目" rm -rf widget mkdir widget ret=`git clone <EMAIL>:zhusonger/zwidget.git widget` cd widget cp -f build.gradle.bak build.gradle cd .. echo "完成Widget项目" echo "开始Media项目" rm -rf media mkdir media ret=`git clone <EMAIL>:zhusonger/zmedia.git media` cd media cp -f build.gradle.bak build.gradle cd .. echo "完成Media项目" echo "完成git clone任务" echo "添加完成" <file_sep>package cn.com.lasong.widget; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView.ViewHolder; import java.util.ArrayList; import java.util.List; import cn.com.lasong.R; import cn.com.lasong.app.AppBaseActivity; import cn.com.lasong.databinding.ActivityStickHeaderBinding; import cn.com.lasong.utils.TN; import cn.com.lasong.widget.adapterview.itemdecoration.StickHeaderProvider; import cn.com.lasong.widget.adapterview.itemdecoration.StickyHeaderDecoration; import cn.com.lasong.widget.adapterview.adapter.OnItemClickListener; import cn.com.lasong.widget.adapterview.adapter.ZRecyclerViewAdapter; import cn.com.lasong.widget.any.AnyIndexProvider; /** * Author: zhusong * Email: <EMAIL> * Date: 2021/5/10 * Description: */ public class StickHeaderActivity extends AppBaseActivity implements StickHeaderProvider{ ActivityStickHeaderBinding binding; ZRecyclerViewAdapter<String> adapter; List<String> data = new ArrayList<>(); List<String> group = new ArrayList<>(); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityStickHeaderBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); binding.viewIndex.setProvider(new AnyIndexProvider() { @Override public int indexCount() { return group.size(); } @Override public View inflateIndex(LayoutInflater inflater, AnyIndexView parent, int position) { TextView textView = new TextView(parent.getContext()); textView.setText(group.get(position)); textView.setGravity(Gravity.CENTER_HORIZONTAL); textView.setPadding(20, 20, 20, 20); textView.setBackgroundColor(Color.YELLOW); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.e("Test", "点击索引位置:" + position+", text:" + textView.getText()); } }); return textView; } }); for (int i = 0; i < 100; i++) { if (i % 10 == 0) { data.add("Group"+i); group.add("G"+i); } else { data.add("Text"+i); } } binding.viewIndex.updateIndex(); adapter = new ZRecyclerViewAdapter<String>(data, R.layout.item_sticker_header, new OnItemClickListener() { @Override public void onItemClick(View view, int position) { TN.show(data.get(position) +":show"); } }) { @Override public void bind(AdapterViewHolder holder, String item, int position) { boolean group = position % 10 == 0; holder.setVisible(group, R.id.tv_header); holder.setVisible(!group, R.id.tv_text); holder.setText(R.id.tv_header, item); holder.setText(R.id.tv_text, item); holder.setOnClickListener(R.id.tv_text); } final StickyHeaderDecoration stickyHeaderDecoration = new StickyHeaderDecoration(); @Override public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) { super.onAttachedToRecyclerView(recyclerView); stickyHeaderDecoration.attachRecyclerView(recyclerView, StickHeaderActivity.this); } @Override public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) { super.onDetachedFromRecyclerView(recyclerView); stickyHeaderDecoration.detachRecyclerView(recyclerView); } }; StickyHeaderDecoration decoration = new StickyHeaderDecoration(); binding.rv.addItemDecoration(decoration); binding.rv.setLayoutManager(new LinearLayoutManager(this)); binding.rv.setAdapter(adapter); } @Override public RecyclerView.ViewHolder createOrUpdateHeader(RecyclerView.ViewHolder cache, LayoutInflater inflater, RecyclerView parent, int position) { if (!isStickHeader(position)) { return null; } ViewHolder holder = cache; if (null == holder) { View v = inflater.inflate(R.layout.item_sticker_header, parent, false); holder = new ZRecyclerViewAdapter.AdapterViewHolder(v, null, null); } adapter.bind((ZRecyclerViewAdapter.AdapterViewHolder) holder, data.get(position), position); return holder; } @Override public boolean isStickHeader(int position) { return position % 10 == 0; } } <file_sep>package cn.com.lasong.app; import android.view.View; import android.view.ViewGroup; import cn.com.lasong.base.BaseActivity; import cn.com.lasong.widget.utils.ViewHelper; /** * Author: zhusong * Email: <EMAIL> * Date: 2021/2/3 * Description: 应用activity基类 */ public class AppBaseActivity extends BaseActivity { /** * 适配状态栏类型枚举 */ protected enum FitStatusBarType { NONE, // 没有适配 PADDING, // 以padding适配 MARGIN // 以margin适配 } /** * 设置完布局后的回调 */ @Override public void onContentChanged() { super.onContentChanged(); // 透明化状态栏 if (transparentStatusBar()) { ViewHelper.transparentStatusBar(this); } // 适配状态栏 if (transparentStatusBar() && fitStatusBarType() != FitStatusBarType.NONE) { View content = findViewById(android.R.id.content); if (content instanceof ViewGroup) { int resId = fitStatusBarResId(); View appContent; if (resId == View.NO_ID) { appContent = ((ViewGroup) content).getChildAt(0); } else { appContent = ((ViewGroup) content).findViewById(resId); } ViewHelper.fitStatusBar(appContent, fitStatusBarType() == FitStatusBarType.PADDING); } } } /** * 适配透明化状态栏的方式 * 默认使用PADDING方式 * @return */ protected FitStatusBarType fitStatusBarType() { return FitStatusBarType.PADDING; } /** * 返回 需要适配透明化状态栏的控件ID * NO_ID 代表当前activity布局的ROOT控件 * @return */ protected int fitStatusBarResId() { return View.NO_ID; } /** * 是否透明化状态栏 * @return */ protected boolean transparentStatusBar() { return true; } } <file_sep>package cn.com.lasong.zapp import android.content.Context import android.util.Log import cn.com.lasong.base.BaseApplication import cn.com.lasong.utils.ILog import com.google.gson.Gson import com.tencent.mmkv.MMKV /** * Author: zhusong * Email: <EMAIL> * Date: 2021/6/7 * Description: */ class ZApp : BaseApplication() { init { INSTANCE = this } companion object { lateinit var INSTANCE: ZApp private set const val KEY_RECORD_SAVE: String = "record_save" val JSON = Gson() fun applicationContext() : Context { return INSTANCE.applicationContext } fun appInstance() : ZApp { return INSTANCE } } override fun onCreate() { super.onCreate() if (BuildConfig.DEBUG) { ILog.setLogLevel(Log.DEBUG) } val rootDir: String = MMKV.initialize(this) ILog.d("mmkv root: $rootDir") } }<file_sep># Android vector标签 PathData 画图超详解 <https://www.cnblogs.com/yuhanghzsd/p/5466846.html> <https://www.jianshu.com/p/c819ae16d29b> **每个命令都有大小写形式,大写代表后面的参数是绝对坐标,小写表示相对坐标,相对于上一个点的位置。** **参数之间用空格或逗号隔开。** * M:move to 移动绘制点,作用相当于把画笔落在哪一点。 * L:line to 直线,就是一条直线,注意,只是直线,直线是没有宽度的,所以你什么也看不到。 * Z:close 闭合,嗯,就是把图封闭起来。 * C:cubic bezier 三次贝塞尔曲线 * Q:quatratic bezier 二次贝塞尔曲线 * A:ellipse 圆弧 * M (x y) 把画笔移动到x,y,要准备在这个地方画图了。 * L (x y) 直线连到x,y,还有简化命令H(x) 水平连接、V(y)垂直连接。 * Z,没有参数,连接起点和终点 * C(x1 y1 x2 y2 x y),控制点(x1,y1)( x2,y2),终点x,y 。 * Q(x1 y1 x y),控制点(x1,y1),终点x,y * C和Q会在下文做简单对比。 * A(rx ry x-axis-rotation large-arc-flag sweep-flag x y) rx ry 椭圆半径 x-axis-rotation x轴旋转角度 large-arc-flag 为0时表示取小弧度,1时取大弧度 (舍取的时候,是要长的还是短的) sweep-flag 0取逆时针方向,1取顺时针方向 ## 额外说明 * C/c 三次贝塞尔曲线, 原理就是从当前点开始, 伸出到x1,y1(第一控制点)形成一条直线, 然后根据x2,y2(第二控制点) 与 x,y组成的直线进行弯曲, 中间的变化根据x1,y1 和 x2,y2连接的线进行变化 * Q/q 二次贝塞尔曲线, 原理就是从当前点开始, 经过x1,y1(控制点), 最终到x,y(终点), 形成一个曲线 * A/a 圆弧, rx, ry确定椭圆的半径, 相同就是圆, x-axis-rotation旋转角度, 就是坐标系的x轴, 45就是向右下旋转45度, 负值反向旋转。 sweep-flag从起点到终点是顺时针还是逆时针画圆弧。 * large-arc-flag, 这个开始理解起来很难, 后来摸索出来, 其实就是当前点到x,y(终点)会画一个圆弧, 如果两个点之间的距离比直径(2个半径)短, 就会在直线一侧(根据sweep-flag顺/逆时针), 出现一个较大的圆弧, 但如果想要的是对面那个比较小的圆弧呢, 这个参数作用就是这个, 其实可以理解成把对面的画到这边来。 # 分区存储 <https://open.oppomobile.com/wiki/doc#id=10432> # 编码 * MediaCodec <https://juejin.cn/post/6844903725417365512> * <https://ragnraok.github.io/android_video_record.html> * ![video](video.jpeg) * ![audio](audio.png) <file_sep>package cn.com.lasong.sms; /** * Author: zhusong * Email: <EMAIL> * Date: 2020/7/28 * Description: */ public interface ISmsListener { void onSend(String message); void onDeliver(); } <file_sep>package cn.com.lasong.move; import android.os.Bundle; import androidx.annotation.Nullable; import cn.com.lasong.R; import cn.com.lasong.lyric.LyricActivity; /** * Author: zhusong * Email: <EMAIL> * Date: 2020-03-08 * Description: 移动控件展示Demo */ public class MoveActivity extends LyricActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void setContentView(int layoutResID) { super.setContentView(R.layout.activity_move); } } <file_sep>apply plugin: 'java-gradle-plugin' apply plugin: 'maven' sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 dependencies { //gradle sdk implementation gradleApi() //从2.0.0版本开始就是在gradle-api中了 implementation 'com.android.tools.build:gradle:3.6.4' // javassist 相关修改字节码 implementation 'org.javassist:javassist:3.27.0-GA' } gradlePlugin { plugins { inject { id = 'cn.com.lasong.inject' version = '1.0.0' displayName = 'InjectClass.' description = 'Modify the bytecode.' implementationClass = 'cn.com.lasong.inject.InjectPlugin' } time { id = 'cn.com.lasong.time' version = '1.0.0' displayName = 'Gradle Cost Time' description = 'Calculate the time spent.' implementationClass = 'cn.com.lasong.time.TaskTimePlugin' } } } uploadArchives { repositories { mavenDeployer { repository(url: uri('../repo/greeting')) snapshotRepository(url: uri('../snapshotRepo/greeting')) } version "1.0.0-SNAPSHOT" } } <file_sep>package cn.com.lasong.zapp.data import android.media.AudioFormat import android.os.Build import android.os.Environment import android.os.StatFs import android.os.storage.StorageManager import androidx.core.content.getSystemService import cn.com.lasong.zapp.R import cn.com.lasong.zapp.ZApp.Companion.applicationContext import java.io.File import java.util.* /** * Author: zhusong * Email: <EMAIL> * Date: 2021/6/15 * Description: */ class RecordBean { data class Video(val index: Int, var width: Int, var height: Int, var bitrate: Int) companion object { // 空间 const val SIZE_1_KB = 1024 const val SIZE_1_MB = SIZE_1_KB * 1024 const val SIZE_1_GB = SIZE_1_MB * 1024 const val SIZE_MIN_VALUE = 50 * SIZE_1_MB // 视频方向 const val DIRECTION_AUTO = 0 const val DIRECTION_VERTICAL = 1 const val DIRECTION_LANDSCAPE = 2 // 视频分辨率 val VIDEO_MOBILE = Video(0, 0, 0, 0) val VIDEO_1080P = Video(1, 1920, 1080, 4860_000) val VIDEO_720P = Video(2, 1280, 720, 2160_000) val VIDEO_480P = Video(3, 854, 480, 960_000) val VIDEO_360P = Video(4, 640, 360, 600_000) val allResolution = arrayOf(VIDEO_MOBILE, VIDEO_1080P, VIDEO_720P, VIDEO_480P, VIDEO_360P) } // save dir var saveDir: String = applicationContext().getExternalFilesDir(Environment.DIRECTORY_DCIM)?.absolutePath!! var appFreeSize: Long = 0 // free size get() { field = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val storageManager = applicationContext().getSystemService<StorageManager>()!! val appSpecificInternalDirUuid: UUID = storageManager.getUuidForPath(File(saveDir)) storageManager.getAllocatableBytes(appSpecificInternalDirUuid) } else { val stat = StatFs(saveDir) val blockSize = stat.blockSizeLong val totalBlocks = stat.blockCountLong totalBlocks * blockSize } return field } var videoDirection = 0 // video direction var videoResolution = 0 // resolution index var videoBitrate = 0 // bitrate index var videoFps = 3 // FPS index var audioEnable = true // enable audio var audioSampleRate = 1 // sample rate index var audioBitrate = 1 // bitrate index var audioChannel = 0 // channel index 单双声道 var delay = 0 // 录制开始倒计时 val freeSizeDisplay : String get() { return when { appFreeSize > SIZE_1_GB -> { "%.2fGB".format(appFreeSize * 1.0 / SIZE_1_GB) } appFreeSize > SIZE_1_MB -> { "%.2fMB".format(appFreeSize * 1.0 / SIZE_1_MB) } appFreeSize > SIZE_1_KB -> { "%.2fKB".format(appFreeSize * 1.0 / SIZE_1_KB) } else -> { "%.2fBytes".format(appFreeSize * 1.0) } } } val directionDisplay : String get() { val array = applicationContext().resources.getStringArray(R.array.array_direction) return array[videoDirection] } // val videoWidth : Int // get() { // return when(videoDirection) { // DIRECTION_VERTICAL -> videoResolution.second // else -> videoResolution.first // } // } // // val videoHeight : Int // get() { // return when(videoDirection) { // DIRECTION_VERTICAL -> videoResolution.first // else -> videoResolution.second // } // } val videoResolutionDisplay : String get() { val resolution = allResolution[videoResolution] return when(resolution.height) { 0 -> { applicationContext().getString(R.string.record_video_resolution_default) } else -> { "%dp".format(resolution.height) } } } val videoResolutionValue : Video get() { val resolution = allResolution[videoResolution] if (resolution.index == 0 && resolution.width == 0) { val metrics = applicationContext().resources.displayMetrics resolution.width = metrics.widthPixels.coerceAtLeast(metrics.heightPixels) resolution.height = metrics.heightPixels.coerceAtMost(metrics.widthPixels) resolution.bitrate = ((resolution.width * resolution.height * 3.0 / 1000).toInt() * 1000) } return resolution } val videoBitrateDisplay : String get() { val array = applicationContext().resources.getStringArray(R.array.array_video_bitrate) return array[videoBitrate] } val videoBitrateValue : Int get() { val array = applicationContext().resources.getIntArray(R.array.array_video_bitrate_value) return array[videoBitrate] } val videoFpsDisplay : String get() { val array = applicationContext().resources.getStringArray(R.array.array_fps) return array[videoFps] } val videoFpsValue : Int get() { val array = applicationContext().resources.getIntArray(R.array.array_fps_value) return array[videoFps] } val audioSampleRateDisplay : String get() { val array = applicationContext().resources.getStringArray(R.array.array_sample_rate) return array[audioSampleRate] } val audioSampleRateValue : Int get() { val array = applicationContext().resources.getIntArray(R.array.array_sample_rate_value) return array[audioSampleRate] } val audioBitrateDisplay : String get() { val array = applicationContext().resources.getStringArray(R.array.array_audio_bitrate) return array[audioBitrate] } val audioBitrateValue : Int get() { val array = applicationContext().resources.getIntArray(R.array.array_audio_bitrate_value) return array[audioBitrate] } val audioChannelDisplay : String get() { val array = applicationContext().resources.getStringArray(R.array.array_channels) return array[audioChannel] } val audioChannelValue : Int get() { return when(audioChannel) { 1 -> AudioFormat.CHANNEL_IN_STEREO else -> AudioFormat.CHANNEL_IN_MONO } } val delayDisplay : String get() { val array = applicationContext().resources.getStringArray(R.array.array_delay) return array[delay] } val delayValue : Int get() { val array = applicationContext().resources.getIntArray(R.array.array_delay_value) return array[delay] } }<file_sep>package cn.com.lasong.zapp.base import android.content.ComponentName import android.content.Intent import android.content.ServiceConnection import android.os.* import cn.com.lasong.utils.ILog import cn.com.lasong.zapp.CoreService /** * Author: zhusong * Email: <EMAIL> * Date: 2021/6/7 * Description: * 需要使用核心服务的Activity */ open class CoreActivity : AppBaseActivity() { protected var mService: Messenger? = null private var bound = false private val connection = object : ServiceConnection { override fun onServiceConnected(name: ComponentName?, service: IBinder?) { mService = Messenger(service) bound = true // We want to monitor the service for as long as we are // connected to it. // We want to monitor the service for as long as we are // connected to it. try { val msg: Message = Message.obtain(null, CoreService.MSG_REGISTER_CLIENT) msg.replyTo = mMessenger mService!!.send(msg) } catch (e: RemoteException) { // In this case the service has crashed before we could even // do anything with it; we can count on soon being // disconnected (and then reconnected if it can be restarted) // so there is no need to do anything here. } } override fun onServiceDisconnected(name: ComponentName?) { // Never Happen mService = null bound = false } } private val handler = Handler(Handler.Callback { msg -> return@Callback handleMessage(msg) }) /** * Target we publish for clients to send messages to IncomingHandler. */ private val mMessenger: Messenger = Messenger(handler) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Intent(this, CoreService::class.java).also { intent-> bindService(intent, connection, BIND_AUTO_CREATE) } } override fun onDestroy() { super.onDestroy() // 先移除所有消息 handler.removeCallbacksAndMessages(null) if (bound) { // 发送最后一条消息 // unregister client if (mService != null) { try { val msg: Message = Message.obtain(null, CoreService.MSG_UNREGISTER_CLIENT) msg.replyTo = mMessenger mService!!.send(msg) } catch (e: RemoteException) { // There is nothing special we need to do if the service // has crashed. } } unbindService(connection) bound = false } } /** 实际业务功能↓ **/ open fun handleMessage(msg: Message): Boolean { when (msg.what) { CoreService.MSG_REGISTER_CLIENT -> ILog.d("MSG_REGISTER_CLIENT Response : " + msg.obj) CoreService.MSG_UNREGISTER_CLIENT -> ILog.d("MSG_UNREGISTER_CLIENT Response : " + msg.obj) } return true } }
82061e567b070416b367825951914628eb5f553e
[ "Markdown", "Gradle", "Java", "Kotlin", "Shell" ]
26
Kotlin
zhusonger/androidz
a85c35ecc213e8956da96a39eb0f50dafb96caf5
ec43336bc042c727e30042e01c7fe8b5982ce01d
refs/heads/master
<repo_name>lukelbd/matplotlib<file_sep>/lib/matplotlib/afm.py from matplotlib._afm import * # noqa: F401, F403 from matplotlib import _api _api.warn_deprecated( "3.6", message="The module %(name)s is deprecated since %(since)s.", name=f"{__name__}") <file_sep>/doc/api/next_api_changes/behavior/22229-TAC.rst AritistList proxies copy contents on iteration ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When iterating over the contents of the the dynamically generated proxy lists for the Artist-type accessors (see :ref:`Behavioural API Changes 3.5 - Axes children combined`), a copy of the contents is made. This ensure that artists can safely be added or removed from the Axes while iterating over their children. This is a departure from the expected behavior of mutable iterable data types in Python -- iterating over list while mutating it has surprising consequences and dictionaries will error if they change size during iteration. Because all of the accessors are filtered views of the same underlying list, it is possible for seemingly unrelated changes, such as removing a Line, to affect the iteration over any of the other accessors. In this case, we have opted to make a copy of the relevant children before yielding them to the user. This change is also consistent with our plan to make these accessors immutable in Matplotlib 3.7.
ec6933f0468ba7379638f02d602068d5514f01f8
[ "Python", "reStructuredText" ]
2
Python
lukelbd/matplotlib
89b21b517df0b2a9c378913bae8e1f184988b554
6dfb31154381e2443974132fa6ea97323a67d35d
refs/heads/master
<repo_name>sergfreeman/djangoApp<file_sep>/FriendsList/friends_list/models.py from django.db import models class MyDB(models.Model): name = models.CharField('Ім`я', max_length=50) age = models.IntegerField('Вік') def __str__(self): result = f'Ім`я: {self.name} - {self.age}: років.' return result <file_sep>/FriendsList/friends_list/forms.py from .models import MyDB from django.forms import ModelForm, TextInput class MyDBForm(ModelForm): class Meta: model = MyDB fields = ['name', 'age'] widgets = { 'name': TextInput(attrs={ 'class': 'form-control', 'placeholder': "Введіть ім'я" }), 'age': TextInput(attrs={ 'class': 'form-control', 'placeholder': "Введіть вік" }), } <file_sep>/FriendsList/friends_list/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('index', views.index, name='index'), path('additional', views.add_to_list, name='additional'), path('show', views.show_all_list, name='show'), path('contact', views.contact, name='contact'), ] <file_sep>/FriendsList/friends_list/admin.py from django.contrib import admin from .models import MyDB admin.site.register(MyDB) <file_sep>/FriendsList/friends_list/views.py from django.shortcuts import render, redirect from .models import MyDB from .forms import MyDBForm def index(request): return render(request, 'friends_list/index.html') def add_to_list(request): error = '' if request.method == 'POST': form = MyDBForm(request.POST) print(form) if form.is_valid(): form.save() return redirect('index') else: error = 'Форма заповнена не кректно' form = MyDBForm() context = { 'form': form, 'error': error } return render(request, 'friends_list/addition.html', context) def show_all_list(request): all_data = MyDB.objects.all() return render(request, 'friends_list/show.html', {'res': all_data}) def contact(request): return render(request, 'friends_list/contact.html')
edfcb939b6865d0ec92e004cc7dee58711074ead
[ "Python" ]
5
Python
sergfreeman/djangoApp
3a5699b7aa98d532918a7fd87f72b0dac1600715
8c3d6559befd661c874446dfc74a43c16cbb4bb3
refs/heads/master
<repo_name>icebreaker2/eventfinder<file_sep>/src/main/java/de/Servlets/FacebookShareServlet.java package de.Servlets; import de.Database.DatabasePreparer; import de.Events.Event; 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; /** * Created by Icebreaker on 24.06.2015. */ @WebServlet("/api/shares") public class FacebookShareServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String date = request.getParameter("date"); int shares = Integer.parseInt(request.getParameter("shares")) + 1; // fetch and increase String location = request.getParameter("location"); new DatabasePreparer().updateEvent(new Event(DatabasePreparer.convertDate(date), location, shares)); // response part response.setContentType("application/json"); PrintWriter out = response.getWriter(); out.write("{\"shares\": \"" + shares + "\"}"); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } } <file_sep>/src/main/webapp/js/eioScript.js $(function () { // Configure the GOOGLE MAPS API var useragent = navigator.userAgent; if (useragent.indexOf('iPhone') != -1 || useragent.indexOf('Android') != -1) { var mapOptions = { zoom: 14, center: new google.maps.LatLng(53.1462326, 8.2209063), // location of Oldenburg keyboardShortcuts: false, streetViewControl: false, mapTypeControl: false, zoomControl: false }; } else { var mapOptions = { zoom: 14, streetViewControl: false, center: new google.maps.LatLng(53.1462326, 8.2209063), // location of Oldenburg keyboardShortcuts: false }; } map = new google.maps.Map(document.getElementById('mapCanvas'), mapOptions); var myLocation = false; google.maps.event.addDomListener(document.getElementById('locateMeButton'), 'click', function () { var icon = { url: '/Images/position.png', // url scaledSize: new google.maps.Size(25, 25), // scaled size origin: new google.maps.Point(0, 0), // origin anchor: new google.maps.Point(0, 0) // anchor }; if (!myLocation) { myLocation = new google.maps.Marker({ clickable: false, icon: icon, animation: google.maps.Animation.DROP, map: map }); } if (navigator.geolocation) navigator.geolocation.getCurrentPosition(function (pos) { var me = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude); myLocation.setPosition(me); map.panTo(myLocation.getPosition()); }, function (error) {}); }); locateMeButton.index = 1; map.controls[google.maps.ControlPosition.BOTTOM_CENTER].push(locateMeButton); var oms = new OverlappingMarkerSpiderfier(map); var iw = new google.maps.InfoWindow(); oms.addListener('click', function (marker, event) { iw.setContent(marker.infoText); iw.open(map, marker); }); var directionRequest = {travelMode: google.maps.TravelMode.DRIVING}; /**GOOGLE-DIRECTION**/ var directionsRenderer = new google.maps.DirectionsRenderer({suppressMarkers: true}); // hide the markers created by the navigation directionsRenderer.setMap(map); var directionService = new google.maps.DirectionsService(); var markers = []; var searchCache = " "; var yourPositionMarker; var categoryCache = ""; var showFirstResult = false; /** Initially show ALL markers **/ search("", ""); $(".tabs").hide(); /*****************/ /*Site Navigation*/ /*****************/ // Navigate via arrow keys $(document).keydown(function (key) { var firstTab = document.getElementById('tab1'); var secondTab = document.getElementById('tab2'); var thirdTab = document.getElementById('tab3'); if (firstTab.checked) { switch (key.which) { case 13: // enter openMarker($('.resultList.selected').attr('data-resultnr')); break; case 38: // up if (parseInt($('.resultList.selected').attr('data-resultnr')) == (parseInt($('.resultList').length)) - 1) { break; } if ($('.resultList.selected').length > 0) { var nextSelected = parseInt($('.resultList.selected').attr('data-resultnr')) + 1; $('.resultList.selected').removeClass('selected'); // Deselect current $('.resultList[data-resultnr=' + nextSelected + ']').addClass('selected') // Select next jQuery('.tab-content').scrollTo('.selected'); } break; case 40: // down $('#tabLabel1').addClass('tabSelected'); $(".menu").hide(); $(".tabs").show(); if (parseInt($('.resultList.selected').attr('data-resultnr')) == 0) { break; } if ($('.resultList.selected').length == 0) { $('.resultList[data-resultnr=' + ((parseInt($('.resultList').length)) - 1) + ']').addClass('selected'); } else { var nextSelected = parseInt($('.resultList.selected').attr('data-resultnr')) - 1; $('.resultList.selected').removeClass('selected'); // Deselect current $('.resultList[data-resultnr=' + nextSelected + ']').addClass('selected') // Select next jQuery('.tab-content').scrollTo('.selected'); } break; case 39: //right document.getElementById('tab1').checked = false; document.getElementById('tab2').checked = true; break; case 27: //escape $(".tabs").hide(); $(".menu").hide(); $("article").fadeOut('fast'); break; default: return; // exit this handler for other keys } } else if (secondTab.checked) { switch (key.which) { case 37: //left if ($('#cat1_3').hasClass('selected')) { $('.categoryButton').removeClass('selected'); $('#cat1_2').addClass('selected'); } else if ($('#cat1_2').hasClass('selected')) { $('.categoryButton').removeClass('selected'); $('#cat1_1').addClass('selected'); } else if ($('#cat1_1').hasClass('selected')) { $('.categoryButton').removeClass('selected'); $('#tab2').prop('checked', false); $('#tab1').prop('checked', true); } else if ($('#cat2_3').hasClass('selected')) { $('.categoryButton').removeClass('selected'); $('#cat2_2').addClass('selected'); } else if ($('#cat2_2').hasClass('selected')) { $('.categoryButton').removeClass('selected'); $('#cat2_1').addClass('selected'); } else if ($('#cat2_1').hasClass('selected')) { $('.categoryButton').removeClass('selected'); $('#tab2').prop('checked', false); $('#tab1').prop('checked', true); } else if ($('#cat3_3').hasClass('selected')) { $('.categoryButton').removeClass('selected'); $('#cat3_2').addClass('selected'); } else if ($('#cat3_2').hasClass('selected')) { $('.categoryButton').removeClass('selected'); $('#cat3_1').addClass('selected'); } else { $('.categoryButton').removeClass('selected'); $('#tab2').prop('checked', false); $('#tab1').prop('checked', true); } break; case 39: //right if ($('#cat1_1').hasClass('selected')) { $('.categoryButton').removeClass('selected'); $('#cat1_2').addClass('selected'); } else if ($('#cat1_2').hasClass('selected')) { $('.categoryButton').removeClass('selected'); $('#cat1_3').addClass('selected'); } else if ($('#cat1_3').hasClass('selected')) { $('.categoryButton').removeClass('selected'); $('#tab2').prop('checked', false); $('#tab3').prop('checked', true); } else if ($('#cat2_1').hasClass('selected')) { $('.categoryButton').removeClass('selected'); $('#cat2_2').addClass('selected'); } else if ($('#cat2_2').hasClass('selected')) { $('.categoryButton').removeClass('selected'); $('#cat2_3').addClass('selected'); } else if ($('#cat2_3').hasClass('selected')) { $('#tab2').prop('checked', false); $('#tab3').prop('checked', true); $('.categoryButton').removeClass('selected') } else if ($('#cat3_1').hasClass('selected')) { $('.categoryButton').removeClass('selected'); $('#cat3_2').addClass('selected'); } else if ($('#cat3_2').hasClass('selected')) { $('.categoryButton').removeClass('selected'); $('#cat3_3').addClass('selected'); } else { $('.categoryButton').removeClass('selected'); $('#tab2').prop('checked', false); $('#tab3').prop('checked', true); } break; case 38: // up if ($('#cat1_1').hasClass('selected')) { $('.categoryButton').removeClass('selected') } else if ($('#cat2_1').hasClass('selected')) { $('.categoryButton').removeClass('selected'); $('#cat1_1').addClass('selected'); } else if ($('#cat3_1').hasClass('selected')) { $('.categoryButton').removeClass('selected'); $('#cat2_1').addClass('selected'); } else if ($('#cat1_2').hasClass('selected')) { $('.categoryButton').removeClass('selected') } else if ($('#cat2_2').hasClass('selected')) { $('.categoryButton').removeClass('selected'); $('#cat1_2').addClass('selected'); } else if ($('#cat3_2').hasClass('selected')) { $('.categoryButton').removeClass('selected'); $('#cat2_2').addClass('selected'); } else if ($('#cat1_3').hasClass('selected')) { $('.categoryButton').removeClass('selected'); } else if ($('#cat2_3').hasClass('selected')) { $('.categoryButton').removeClass('selected'); $('#cat1_3').addClass('selected'); } else if ($('#cat3_3').hasClass('selected')) { $('.categoryButton').removeClass('selected'); $('#cat2_3').addClass('selected'); } break; case 40: //down if ($('#cat1_1').hasClass('selected')) { $('.categoryButton').removeClass('selected'); $('#cat2_1').addClass('selected'); } else if ($('#cat2_1').hasClass('selected')) { $('.categoryButton').removeClass('selected'); $('#cat3_1').addClass('selected'); } else if ($('#cat3_1').hasClass('selected')) { break; } else if ($('#cat1_2').hasClass('selected')) { $('.categoryButton').removeClass('selected'); $('#cat2_2').addClass('selected'); } else if ($('#cat2_2').hasClass('selected')) { $('.categoryButton').removeClass('selected'); $('#cat3_2').addClass('selected'); } else if ($('#cat1_3').hasClass('selected')) { $('.categoryButton').removeClass('selected'); $('#cat2_3').addClass('selected'); } else if ($('#cat2_3').hasClass('selected')) { $('.categoryButton').removeClass('selected'); $('#cat3_3').addClass('selected'); } else if ($('#cat3_2').hasClass('selected')) { break; } else if ($('#cat3_3').hasClass('selected')){ break; } else { $(".tabs").show(); $('#cat1_2').addClass('selected') } break; case 13: // enter $.each($('input[name="category"]'), function (key, data) { if ($('label[for=\'' + data.id + '\']').hasClass('selected')) { if($('#' + data.id).is(':checked')) { $(this).removeClass('categoryActive'); $("nav").removeClass("categoryEnabled"); $('#' + data.id).prop('checked', false); $("#tab1").prop("checked", true); // Start search without category search($("#search").val(), ''); } else { $.each($('input[name="category"]'), function () { $(this).removeClass('categoryActive'); }); // check the radio and set category text $('#' + data.id).prop('checked', true); $(".categoryHTML").html($('label[for=\'' + data.id + '\']').html()); $("nav").addClass("categoryEnabled"); // Make search smaller $("#tab1").prop("checked", true); // fire post, if query with category has changed if ($("#search").val() != searchCache || $('input[name="category"]:checked').val() != categoryCache) { //Has the query changed? search($("#search").val(), $('input[name="category"]:checked').val()); } $(this).addClass('categoryActive'); } $('label[for=\'' + data.id + '\']').removeClass('selected'); } }); break; case 27: //escape $('.categoryButton').removeClass('selected') $(".tabs").hide(); $(".menu").hide(); $("article").fadeOut('fast'); break; } } else { //thirdTab.checked switch (key.which) { case 37: //left if ($('#city').is(":focus")) { $('#activity').focus(); break; } else { $('#tab3').prop('checked', false); $('#tab2').prop('checked', true); } break; case 39: //right if ($('#activity').is(":focus")) { $('#city').focus(); break; } else { break; } break; case 40: //down if ($(".tabs").is(":visible")){ $('#activity').focus(); } else { $(".tabs").show(); } break; case 13: //enter showFirstResult = true; search($("#activity").val() + " " + $("#city").val(), ""); break; case 27: //escape $(".tabs").hide(); $(".menu").hide(); $("article").fadeOut('fast'); break; } } }); //function to autoscroll through results when navigating with keyboard //source: http://lions-mark.com/jquery/scrollTo/ $.fn.scrollTo = function (target, options, callback) { if (typeof options == 'function' && arguments.length == 2) { callback = options; options = target; } var settings = $.extend({ scrollTarget: target, offsetTop: 200, duration: 150, easing: 'linear' }, options); return this.each(function () { var scrollPane = $(this); var scrollTarget = (typeof settings.scrollTarget == "number") ? settings.scrollTarget : $(settings.scrollTarget); var scrollY = (typeof scrollTarget == "number") ? scrollTarget : scrollTarget.offset().top + scrollPane.scrollTop() - parseInt(settings.offsetTop); scrollPane.animate({ scrollTop: scrollY }, parseInt(settings.duration), settings.easing, function () { if (typeof callback == 'function') { callback.call(this); } }); }); }; // Toggle mobile menu $(".showMenu").click(function () { $(".tabs").hide(); $(".menu").toggle(); }); $("#mapCanvas").click(function () { $(".tabs").hide(); $(".menu").hide(); $("article").fadeOut('fast'); }); // Open content windows (about, share, ...) $(".openContent").click(function () { $(".tabs").hide(); $(".menu").hide(); var contentWindow = $(this); $("article").fadeOut('fast').promise().done(function () { $(contentWindow.attr('data-href')).fadeIn('fast'); }); }); // Close content windows $(".close a").click(function () { $(".menu").hide(); $("article").fadeOut('fast'); }); /*****************************/ /*Searchbar and User Requests*/ /*****************************/ $('#feelingLucky').click(function () { showFirstResult = true; search($("#activity").val() + " " + $("#city").val(), ""); }); executeAfterSearch = function () { if (showFirstResult == true) { if (markers.length > 0) { openMarker(0); } else { alert("Leider keine passenden Events gefunden!"); } showFirstResult = false; } }; $("#search").click(function () { $(".menu").hide(); $(".tabs").show(); $("article").fadeOut('fast'); if ($("#search").val() != searchCache || $('input[name="category"]:checked').val() != categoryCache) { //Has the query changed? search($("#search").val(), $('input[name="category"]:checked').val()); } }); $("#search").keyup(function (event) { $(".menu").hide(); if (event.keyCode != '13') { // Do not fire when enter is pressed if ($("#search").val() != searchCache || $('input[name="category"]:checked').val() != categoryCache) { //Has the query changed? search($("#search").val(), $('input[name="category"]:checked').val()); } } }); $('.categoryActive').click( function () { $("nav").removeClass("categoryEnabled"); $("input[name='category']:checked").prop("checked", false); // Clear invisible radio buttons search($("#search").val(), ''); }); //Click event for categories $('input[name="category"]:radio').click(function () { if ($(this).hasClass('categoryActive')){ $("nav").removeClass("categoryEnabled"); $(this).prop("checked", false); $(this).removeClass('categoryActive'); search($("#search").val(), ''); } else { $.each($('input[name="category"]'), function () { $(this).removeClass('categoryActive'); }); var html = $("label[for='" + $(this).attr('id') + "']").html(); $(".categoryHTML").html(html); $("nav").addClass("categoryEnabled"); $("#tab1").prop("checked", true); if ($("#search").val() != searchCache || $('input[name="category"]:checked').val() != categoryCache) { //Has the query changed? search($("#search").val(), $('input[name="category"]:checked').val()); } $(this).addClass('categoryActive'); } }); function search(query, category) { searchCache = query; // refresh cache categoryCache = category; //refresh cache $.ajax({ url: "/api/search", type: 'POST', dataType: 'json', data: { searchText: query, category: category }, success: function (results) { if (results[0] != undefined) { showResults(results); executeAfterSearch(); } else { showEmptyResultMessage(); } } }); } function showEmptyResultMessage() { // eliminate previous results $("#tab-content1").empty(); // flush markers from the map and the array in addition to previous locationResults $.each(markers, function (index, value) { value.setMap(null); }); // Clear markers & windows markers = []; $("#tab-content1").appendAt( '<div class="result resultList">' + '<div>' + '<h2 style="line-height: 25px; padding-left: 10px"> Deine Suche ergab leider keine Treffer. </h2>' + '<p style="padding-left: 10px"> Sieh nach ob du dich eventuell verschrieben hast... </p>' + '</div>' + '</div>' , 0 ); } function showResults(results) { // eliminate previous results $("#tab-content1").empty(); // flush markers from the map and the array in addition to previous locationResults $.each(markers, function (index, value) { value.setMap(null); }); // Clear markers & windows markers = []; // append results with each-loop $.each(results, function (key, data) { //Colour for event markers if (data.isToday) { var markerIcon = '/Images/marker-today.png'; } else if (data.isTomorrow) { var markerIcon = '/Images/marker-tomorrow.png'; } else if (data.isInNextThreeDays) { var markerIcon = '/Images/marker-three-days.png'; } else if (data.isNextWeek) { var markerIcon = '/Images/marker-next-week.png'; } else { var markerIcon = '/Images/marker-far-away.png'; } var infoBlock = '<a class="sideButton showDirection" href="#"><img src="/Images/route.png" alt="directions"> Route</a>' + '<div class="openMarker">' + '<img class="marker" src="' + markerIcon + '">' + '<h4>' + data.date + '</h4>' + '<h3>' + data.title + '</h3>' + '<h5>' + data.location + '</h5>' + '<p >' + data.description + '</p>' + '<a target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(data.infoUrl) + '" class="like" data-shares="' + data.likes + '"><span class="glyphicon glyphicon-share"></span> Teilen - [' + data.likes + ']</a>' + '<a class="sourceLink" style="color:#4889F3;" href="' + data.infoUrl + '" target="_blank">Quelle</a>' + '</div>'; // append results to the list $("#tab-content1").appendAt( '<div class="result resultList" data-resultNr="' + key + '">' + infoBlock + '</div>' , 0 ); // append marker on map var marker = new google.maps.Marker({ position: new google.maps.LatLng(data.latitude, data.longitude), animation: google.maps.Animation.DROP, map: map, title: data.title, icon: markerIcon }); // create info-window for the marker marker.infoText = '<div class="result infoWindow" data-resultNr="' + key + '">' + '<a class="sideButton openNavigation" target="_blank" href="#"><span class="glyphicon glyphicon-new-window"></span><br/>Navigation</a>' + infoBlock + '</div>'; // add marker-listener oms.addListener('click', function (marker, event) { $('#mapCanvas').removeClass('navMode'); }); markers.push(marker); // store marker to delete on new input oms.addMarker(marker); }); } jQuery.fn.appendAt = function (content, index) { this.each(function (i, item) { var $content = $(content).clone(); if (index === 0) { $(item).prepend($content); } else { $content.insertAfter($(item).children().eq(index - 1)); } }); $(content).remove(); return this; }; /*************/ /*Google Maps*/ /*************/ // increase the facebook count on click $(document).on('click', '.like', function () { var parent = $(this).parent(); var date = $($(parent).find("h4")).html(); var location = $($(parent).find("h5")).html(); var dataShares = $(this).attr("data-shares"); var target = $(this).attr("href"); var eventNr = $($(this).parent()).parent().attr('data-resultNr'); $.ajax({ url: "/api/shares", type: 'POST', data: { date: date, location: location, shares: dataShares }, success: function (result) { $("a[href='" + target + "']").html('Teilen - [' + result.shares + ']'); $("a[href='" + target + "']").attr("data-shares", result.shares); markers[eventNr].infoText = markers[eventNr].infoText.replace('data-shares=\"' + (result.shares - 1) + '\"', 'data-shares=\"' + result.shares + '\"'); markers[eventNr].infoText = markers[eventNr].infoText.replace('Teilen - [' + (result.shares - 1) + ']', 'Teilen - [' + result.shares + ']'); } }); }); // Use external routing service for turn-by-turn-directions function setMapExport(location, latlng) { latlng = latlng.toString().replace(' ', ''); latlng = latlng.replace('(', ''); latlng = latlng.replace(')', ''); // check which device our page is running on if (useragent.match(/iPad/i) || useragent.match(/iPhone/i) || useragent.match(/iPod/i)) { // the /i indicates that there will be an integer after the string routeString = 'maps://maps.apple.com/?q="' + latlng; } else if (useragent.match(/Android/i)) { routeString = 'geo:' + latlng + '?q=' + latlng; } else { routeString = 'http://maps.google.com/maps?saddr=(' + location.coords.latitude + ',' + location.coords.longitude + ')&daddr=' + latlng; } $('.openNavigation').attr('href', routeString); } // jump to the marker of the selected event and open infoWindow $(document).on('click', '.openMarker', function () { // use on for dynamically added results openMarker($(this).parent().attr('data-resultNr')); }); // jump to the marker of the selected event and open infoWindow function openMarker(id) { var marker = markers[id]; map.panTo(marker.getPosition()); // pan animates the jump and is better than setMap $('#mapCanvas').removeClass('navMode'); iw.setContent(marker.infoText); iw.open(map, marker); $(".tabs").hide(); } // show the route to the event from the current position $(document).on('click', '.showDirection', function () { $(".tabs").hide(); // get the the destination position var eventNr = $(this).parent().attr('data-resultNr'); var marker = markers[eventNr]; iw.setContent(marker.infoText); iw.open(map, marker); directionRequest.destination = markers[eventNr].getPosition(); // ask current location and show route if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showRoute, showError); // sends the answer and results to the handle // Show app link $('#mapCanvas').addClass("navMode"); } else { alert("Dein Browser unterstützt leider keine geoLocation"); } }); // callback-funtction of the geoLocation function showRoute(location) { // append marker on map and flush the last position --> can be another than a minute ago if (yourPositionMarker) { yourPositionMarker.setMap(null); } yourPositionMarker = new google.maps.Marker({ position: new google.maps.LatLng(location.coords.latitude, location.coords.longitude), map: map, title: 'Deine Position', icon: '/Images/position.png' // Blue dot }); // show the route directionRequest.origin = new google.maps.LatLng(location.coords.latitude, location.coords.longitude); directionService.route(directionRequest, function (result, status) { if (status == google.maps.DirectionsStatus.OK) { directionsRenderer.setDirections(result); } }); setMapExport(location, directionRequest.destination); } function showError(error) { switch (error.code) { case error.PERMISSION_DENIED: alert("Bitte erlauben Sie den Zugriff auf Ihre Position"); break; default: alert("Ihre Position ist gerade nicht verfügbar"); } } });<file_sep>/README.md # Event Finder The **Event Finder** searches for local events in Oldenburg and its surroundings. The **Event Finder** uses the [Google Maps APIs](https://developers.google.com/maps/) to display the events on a map with various additional information about the location. In addition, the EventFinder uses a **EventCrawler** to crawl for events at other websites. ## Installation ### Prerequisites Jetty 9.3 requires Java 8 (or greater) to run. Make sure you have it installed. To install jetty follow this step-by-step guide: ```bash wget -c http://repo1.maven.org/maven2/org/eclipse/jetty/jetty-distribution/9.3.12.v20160915/jetty-distribution-9.3.12.v20160915.tar.gz tar xzf jetty-distribution-9.3.12.v20160915.tar.gz mv jetty-distribution-9.3.12.v20160915 jetty9 sudo mv jetty9 /opt sudo chmod u=rwx,g=rxs,o= /opt/jetty9 cp /opt/jetty9/bin/jetty.sh /etc/init.d/jetty vim /etc/default/jetty ``` Copy this to your into the vim window: ```bash JAVA=/usr/bin/java # Path to Java NO_START=0 # Start on boot JETTY_HOST=0.0.0.0 # Listen to all hosts JETTY_ARGS=jetty.port=8085 JETTY_USER=icebreaker # Run as this user [ADD HERE] JETTY_HOME=/opt/jetty9 ``` ### EventFinder ```bash git clone https://github.com/icebreaker2/eventfinder.git cd eventfinder mvn clean install ``` Use the `target/eventfinder-1.0.war` to deploy the website. ### Database and the Crawler You need to setup a database for the event entries (otherwise you will not see any events on the map later on). After you have done it you can add your database in the [config.properties](src/main/resources/config.properties). The database is then used to store new events found by the crawler or to request them while using the **EventFinder**. To start the crawler just run the `main` within `de.EventCrawler.CrawlerMain` or build a `jar` with the given `MANIFEST.MF` within `de/META-INF/MANIFEST.MF` to let the crawler crawl til the end of time. ### Deploy If you want to refine this **EventFinder** or adapt it you should start with your IDE. For *IntelliJ* follow the steps below: 1. In the `Run/Debug Configurations` settings select `Jetty Server` and then `local`. 2. Set the `Application Server` to `/opt/jetty9` and the deployment artifact to `target/eventfinder-1.0.war` at the `Deployment` tab. 3. Press the `run` button If you want to deploy the **EventFinder** on your server here some basic steps to do so: 1. Copy the `target/eventfinder-1.0.war` into your `/opt/jetty9/webapps/` dir. 2. Start the server by either running `java -jar start.jar` within your jetty home `/opt/jetty9/` or start the service by typing `service jetty start`. If no further settings are done by yourself you should see the website at `http://localhost:8080/eventfinder-1.0/`. *ENJOY!* ## Backend Structure There is a UML 2.0 Class diagramm description of the Server Backend: ![](backend.png) <file_sep>/src/main/java/de/EventCrawler/GeoFinder.java package de.EventCrawler; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import java.io.*; import java.net.*; /** * Created by Icebreaker on 17.06.2015. */ public class GeoFinder { private static String link = "https://maps.googleapis.com/maps/api/geocode/json"; public static synchronized JSONObject findGeoLocation(String location) { // initialize the resultJson and the json to fetch the response JSONObject latLngPointsAdress = new JSONObject(); JSONObject json = null; // prepare a URL for the geocoder-rest URL url = null; try { // create url url = new URL(link + "?address=" + URLEncoder.encode(location, "UTF-8") + "&region=de&sensor=false&key=<KEY>"); } catch (MalformedURLException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } // send request and get the response written in the urlConnection try { URLConnection conn = url.openConnection(); //System.out.println("GEOCODER-URL: " + conn.getURL()); // convert the response to a string readable by org.json-simple.* BufferedReader streamReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); StringBuilder responseStrBuilder = new StringBuilder(); String inputStr; while ((inputStr = streamReader.readLine()) != null) responseStrBuilder.append(inputStr); // parse the result send by google in a json that has been requested json = (JSONObject) JSONValue.parse(responseStrBuilder.toString()); // first parse the whole response // check whether there are no results if (json.get("status").toString().equals("OK")) { JSONObject results = (JSONObject) ((JSONArray) json.get("results")).get(0); // first array-Element JSONObject geoTags = (JSONObject) (((JSONObject) results.get("geometry"))).get("location"); // exakt path in the json-objekt to the latLng-Points // add the points and return them latLngPointsAdress.put("lng", Double.parseDouble(geoTags.get("lng").toString())); latLngPointsAdress.put("lat", Double.parseDouble(geoTags.get("lat").toString())); // remove the germany tag String address = results.get("formatted_address").toString(); try { latLngPointsAdress.put("address", address.substring(0, address.indexOf(", Germany"))); } catch (Exception e) { // index out of bounds latLngPointsAdress.put("address", address); } return latLngPointsAdress; } else if (json.get("status").toString().equals("OVER_QUERY_LIMIT")) { try { //System.out.println("Sleeping"); Thread.sleep(1000 * 60 * 60); // wait 1 hour and then let others try it, will minimize the failures findGeoLocation(location); // call again and return the result recursive } catch (InterruptedException e) { e.printStackTrace(); } } else { //System.out.println("ExitCode: " + json.get("status") + " and response is: " + json); } } catch (IOException e) { //System.out.println("IOException: " + json); e.printStackTrace(); } catch (Exception e) { //System.out.println("Other Exception: " + json); e.printStackTrace(); } return null; } } <file_sep>/src/main/java/de/Database/PropertyReader.java package de.Database; /** * Created by Dario on 28.05.15. */ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class PropertyReader { private InputStream inputStream; private Properties properties; private final String config = "config.properties"; private String getConfigFilePath() { return getClass().getClassLoader().getResource(config).getPath(); } public String readFromProperties(String input){ properties = new Properties(); try { inputStream = new FileInputStream(getConfigFilePath()); properties.load(inputStream); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return properties.getProperty(input); } }
091c3b4a446099eafb1fa137caf9b1305d337a35
[ "JavaScript", "Java", "Markdown" ]
5
Java
icebreaker2/eventfinder
a17692f90a862645bc109391ade5993f1a8dbf97
ceb9f2e450768d737b0f895a3ce1bc74dfe49561
refs/heads/master
<file_sep>console.log('================'); console.log('scratch-pad-2.js'); console.log('================'); <file_sep>function Animal(name) { var self = {}; self.name = name; self.identify = function() { console.log('I am ' + self.name); }; return self; } function Dog(name) { var self = Animal(name); self.bark = function() { console.log('woof'); }; return self; } var dog = Dog('Bunk'); dog.identify(); dog.bark(); console.log(dog); <file_sep>var Animal = { init: function(name) { this.name = name; return this; }, identify: function() { console.log('I am ' + this.name); } }; var Dog = Object.create(Animal); Dog.bark = function bark() { console.log('woof'); }; var dog = Object.create(Dog).init('Bernard'); dog.identify(); dog.bark(); console.log(dog);
f5b0ce56c368733fed7497ab134b0fe1bd1b1ea2
[ "JavaScript" ]
3
JavaScript
kenneth-gray/js-study-group-inheritance
cbe93d40d7a01c593d8c2fda94d587209d3b514f
1eef44c0b4ebb2b5b547713c638b2e5340237968
refs/heads/master
<repo_name>glebrech/LUDOGAMM<file_sep>/Emprunt.cs using System; using System.Collections.Generic; using System.Text; namespace LUDOGAMM { class Emprunt { public int idBoite; public DateTime dateEmprunt; public DateTime dateRetour; public Boolean horsDelais; public void alerter() { } } } <file_sep>/TempsDeJeu.cs using System; using System.Collections.Generic; using System.Text; namespace LUDOGAMM { class TempsDeJeu { public int duree; } } <file_sep>/Stock.cs using System; using System.Collections.Generic; using System.Text; namespace LUDOGAMM { class Stock { public void recupererStock() { } public void renouvelerStock() { } } } <file_sep>/Reservation.cs using System; using System.Collections.Generic; using System.Text; namespace LUDOGAMM { class Reservation { public DateTime dateDebutReservation; public DateTime dateFinReservation; } } <file_sep>/View Controller/ListeJeux.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace LUDOGAMM { public partial class ListeJeux : MenuView { public ListeJeux() { InitializeComponent(); } private void ListeJeux_Load(object sender, EventArgs e) { } } } <file_sep>/Adhesion.cs using System; using System.Collections.Generic; using System.Text; namespace LUDOGAMM { class Adhesion { public Boolean cotisation; public Boolean caution; public DateTime debutAdhesion; public DateTime finAdhesion; } } <file_sep>/GererEmpruntSQL.cs using System; using System.Collections.Generic; using System.Text; namespace LUDOGAMM { class GererEmpruntSQL { } } <file_sep>/Connexion.cs using System; using System.Collections.Generic; using System.Text; using System.Data.SqlClient; using System.Windows.Forms; namespace LUDOGAMM { class Connexion { private static SqlConnection LaConnexion { get; set; } = null; public static SqlConnection GetInstance() { // Préparation de la connexion à la base de données if (LaConnexion == null) { string connectionString = "Data Source=DESKTOP-7O2DRQE\\SQLEXPRESS;Initial Catalog=LUDOGAMM;User Id=gwenchlan;Password=<PASSWORD>;"; //string connectionString = "Data Source=DESKTOP-7O2DRQE\SQLEXPRESS;Initial Catalog=LUDOGAMM;User Id=Mireille;Password=sio;"; //string connectionString = "Data Source=DESKTOP-7O2DRQE;Initial Catalog=LUDOGAMM;User Id=Antoine;Password=sio"; //string connectionString = "Data Source=DESKTOP-7O2DRQE;Initial Catalog=Aero; User Id=Marc; Password=sio;"; LaConnexion = new SqlConnection(connectionString); try { // Connexion à la base de données LaConnexion.Open(); //Form dlg1 = new Form(); //dlg1.ShowDialog(); System.Diagnostics.Debug.WriteLine("Co réussie"); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("PROBLEME : " + ex.Message); } } //Commentaire test return LaConnexion; } private Connexion() { } } } <file_sep>/Contenu.cs using System; using System.Collections.Generic; using System.Text; namespace LUDOGAMM { public class Contenu { public int quantite; } }<file_sep>/View Controller/Accueil.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LUDOGAMM { public partial class Accueil : MenuView //partial signifie que la classe est définie // à plusieurs endroits. Ici vous ne voyez que ce que vous devez toucher. // L'autre partie de la classe a été faite automatiquement et se charge du reste. { public Accueil() { InitializeComponent(); //MessageBox.Show(); } private void Accueil_Load(object sender, EventArgs e) { } private void pictureBox1_Click(object sender, EventArgs e) { } private void label2_Click(object sender, EventArgs e) { } } } <file_sep>/Adresse.cs using System; using System.Collections.Generic; using System.Text; namespace LUDOGAMM { class Adresse { public int idAdresse; public string rue; public string ville; public int codePostal; } } <file_sep>/NbrJoueurs.cs using System; using System.Collections.Generic; using System.Text; namespace LUDOGAMM { class NbrJoueurs { public int joueurMini; public int joueurMaxi; } } <file_sep>/ContenuManquant.cs using System; using System.Collections.Generic; using System.Text; namespace LUDOGAMM { class ContenuManquant { public int quantiteManquante; } } <file_sep>/Adherent.cs using System; using System.Collections.Generic; using System.Text; namespace LUDOGAMM { class Adherent { public string nom; public string prenom; public int idAdresse; public string email; public int telephone; public string adherentSecondaire; } } <file_sep>/Materiel.cs using System; using System.Collections.Generic; using System.Text; namespace LUDOGAMM { class Materiel { public string nom; } } <file_sep>/BoiteJeu.cs using System; using System.Collections.Generic; using System.Text; namespace LUDOGAMM { class BoiteJeu { public int idBoite; public Boolean boiteEmpruntable; } } <file_sep>/Etat.cs using System; using System.Collections.Generic; using System.Text; namespace LUDOGAMM { class Etat { public String etatBoite; public Boolean boiteEmpruntable; } } <file_sep>/View Controller/AjouterJeu.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; namespace LUDOGAMM { public partial class AjouterJeu : MenuView { public bool estAjoute; public int idJeu; public string genre; public string nom; public string auteur; public int anneeEdition; public string regleJeu; public AjouterJeu() { InitializeComponent(); } private bool AjouterJeuDB(SqlCommand bdd, string genre, string nom, string auteur, string anneeEdition, string editeur, string nbJoueurMini, string nbJoueurMaxi, string ageMini, string ageMaxi, string tempsJeu, string regleJeu) { estAjoute = true; // Définition de la requête. bdd.CommandText = "INSERT INTO LUDOTHEQUE.dbo.JEU(genre,titre,auteur,anneeEdition,editeur,nbrJoueurMini,nbrJoueurMaxi,ageMini,ageMaxi,tempsDeJeu,regleDuJeu)VALUES(@genre,@titre,@auteur,@anneeEdition,@editeur,@nbrJoueurMini,@nbrJoueurMaxi,@ageMini,@ageMaxi,@tempsDeJeu,@regleDuJeu)"; // Définition des paramètres de la requête. bdd.Parameters.AddWithValue("@genre", genre); bdd.Parameters.AddWithValue("@titre", nom); bdd.Parameters.AddWithValue("@auteur", auteur); bdd.Parameters.AddWithValue("@anneeEdition", anneeEdition); bdd.Parameters.AddWithValue("@editeur", editeur); bdd.Parameters.AddWithValue("@nbrJoueurMini", nbJoueurMini); bdd.Parameters.AddWithValue("@nbrJoueurMaxi", nbJoueurMaxi); bdd.Parameters.AddWithValue("@ageMini", ageMini); bdd.Parameters.AddWithValue("@ageMaxi", ageMaxi); bdd.Parameters.AddWithValue("@tempsDeJeu", tempsJeu); bdd.Parameters.AddWithValue("@regleDuJeu", regleJeu); // Exécution de la requête try { bdd.ExecuteNonQuery(); } catch (Exception e) { estAjoute = false; MessageBox.Show("Requete invalide: " + e.Message, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error); } return estAjoute; } private string GetIdJeu(SqlCommand bdd, string genre, string nom, string auteur, string anneeEdition, string editeur, string nbJoueurMini, string nbJoueurMaxi, string ageMini, string ageMaxi, string tempsJeu, string regleJeu) { // Définition de la requête. bdd.CommandText = "SELECT JEU.idJeu FROM JEU where genre = @genre and titre = @titre and auteur = @auteur and anneeEdition = @anneeEdition and editeur = @editeur and nbrJoueurMini = @nbrJoueurMini and nbrJoueurMaxi = @nbrJoueurMaxi and ageMini = @ageMini and ageMaxi = @ageMaxi and tempsDeJeu = @tempsDeJeu and regleDuJeu = @regleDuJeu"; string idJeu = null; try { using (SqlDataReader reader = bdd.ExecuteReader()) { if (reader.Read()) { idJeu = String.Format("{0}", reader["idJeu"]); } } } catch (Exception e) { MessageBox.Show("Requete invalide: " + e.Message, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error); } return idJeu; } private bool AjoutDeJeu() { // 1 Réupérer les données. // 2 Vérifier les infos rentrées par l'utilisateur. // 3 Si ok -> requete SQL // Sinon -> message d'erreur et on ne fait rien. // 3.1 Verifier le retour de la requete // Si ok -> Message "bien enregistré" // Sinon -> message d'erreur et on ne fait rien. string genre = dataGridView1.Rows[0].Cells[0].Value.ToString(); string nom = dataGridView1.Rows[0].Cells[1].Value.ToString(); string auteur = dataGridView1.Rows[0].Cells[2].Value.ToString(); string anneeEdition = dataGridView1.Rows[0].Cells[3].Value.ToString(); string editeur = dataGridView1.Rows[0].Cells[4].Value.ToString(); string nbJoueurMini = dataGridView2.Rows[0].Cells[0].Value.ToString(); string nbJoueurMaxi = dataGridView2.Rows[0].Cells[1].Value.ToString(); string ageMini = dataGridView2.Rows[0].Cells[2].Value.ToString(); string ageMaxi = dataGridView2.Rows[0].Cells[3].Value.ToString(); string tempsJeu = dataGridView2.Rows[0].Cells[4].Value.ToString(); string regleJeu = dataGridView3.Rows[0].Cells[0].Value.ToString(); estAjoute = true; if (!String.IsNullOrEmpty(genre) && !String.IsNullOrEmpty(nom) && !String.IsNullOrEmpty(auteur) && !String.IsNullOrEmpty(anneeEdition) && !String.IsNullOrEmpty(editeur) && !String.IsNullOrEmpty(nbJoueurMini) && !String.IsNullOrEmpty(nbJoueurMaxi) && !String.IsNullOrEmpty(ageMini) || !String.IsNullOrEmpty(ageMaxi) || !String.IsNullOrEmpty(tempsJeu) || !String.IsNullOrEmpty(regleJeu)) { SqlCommand bdd = Connexion.GetInstance().CreateCommand(); if (bdd != null) { // Ajout du jeu dans la base de données _ = AjouterJeuDB(bdd, genre, nom, auteur, anneeEdition, editeur, nbJoueurMini, nbJoueurMaxi, ageMini, ageMaxi, tempsJeu, regleJeu); string idJeu = GetIdJeu(bdd, genre, nom, auteur, anneeEdition, editeur, nbJoueurMini, nbJoueurMaxi, ageMini, ageMaxi, tempsJeu, regleJeu); // Définition des paramètres de la requête // Exécution de la requête try { bdd.ExecuteNonQuery(); } catch (Exception e) { estAjoute = false; MessageBox.Show("Requete invalide: " + e.Message, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { estAjoute = false; MessageBox.Show("La connexion à la bdd a échoué. Merci de réessayer ultérieurement.", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { estAjoute = false; MessageBox.Show("Les informations sont incomplètes.", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error); } return estAjoute; } private void ValiderClick(object sender, EventArgs e) { Valider_Button.Anchor = (AnchorStyles.Bottom | AnchorStyles.Right); Valider_Button.Text = "Valider"; Valider_Button.BackColor = Color.Blue; if (AjoutDeJeu()) { MessageBox.Show("Le jeu a été ajouté!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("Le jeu n'a pas pu être ajouté!", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void AjouterJeu_Load(object sender, EventArgs e) { } } } <file_sep>/Age.cs using System; using System.Collections.Generic; using System.Text; namespace LUDOGAMM { class Age { public int ageMini; public int ageMaxi; } } <file_sep>/View Controller/Adherents.cs using System; using System.Drawing; using System.Windows.Forms; using System.Data.SqlClient; namespace LUDOGAMM { public partial class Adherents : MenuView //partial signifie que la classe est définie // à plusieurs endroits. Ici vous ne voyez que ce que vous devez toucher. // L'autre partie de la classe a été faite automatiquement et se charge du reste. { // Gère la fermeture du formulaire par l'utilisateur //private void MainForm_FormClosing(object sender, FormClosingEventArgs e) //{ // if (MessageBox.Show("Etes-vous sûr(e) de vouloir quitter ?", "Demande de confirmation", // MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) // { // e.Cancel = true; // } //} public bool cotisation = false; public bool caution = false; public bool estAjoute; public string nom; public string prenom; public string rue; public int codePostal; public string ville; public string email; public int telephone; public string adherentsSecondaires; public int idAdresse; public int idAdherent; public int idAbonnement; public Adherents() { // Constructeur : initialise tout ce qui ce trouve sur la vue. InitializeComponent(); } private bool AjouterAdresseBDD(SqlCommand bdd, string rue, string codePostal, string ville) { estAjoute = true; // Définition de la requête. bdd.CommandText = "INSERT INTO LUDOTHEQUE.dbo.ADRESSE(rue,codePostal,ville)VALUES(@rue,@codePostal,@ville)"; // Définition des paramètres de la requête. bdd.Parameters.AddWithValue("@rue", rue); bdd.Parameters.AddWithValue("@codePostal", codePostal); bdd.Parameters.AddWithValue("@ville", ville); // Exécution de la requête try { bdd.ExecuteNonQuery(); } catch (Exception e) { estAjoute = false; MessageBox.Show("Requete invalide: " + e.Message, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error); } return estAjoute; } private string GetIdAdresse(SqlCommand bdd ,string rue, string codePostal, string ville) { // Définition de la requête. bdd.CommandText = "SELECT ADRESSE.idAdresse FROM ADRESSE where rue = @rue and codePostal = @codePostal and ville = @ville "; string idAdresse = null; try { using (SqlDataReader reader = bdd.ExecuteReader()) { if (reader.Read()) { idAdresse = String.Format("{0}", reader["idAdresse"]); } } } catch (Exception e) { MessageBox.Show("Requete invalide: " + e.Message, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error); } return idAdresse; } private bool AjouterAdherentBDD(SqlCommand bdd, string idAdresse, string nom, string prenom, string email, string telephone, string adherentsSecondaires) { bool estAjoute = true; // Définition de la requête. bdd.CommandText = "INSERT INTO LUDOTHEQUE.dbo.ADHERENT(idAdresse,Nom,Prenom,Email,Telephone,AdherentsSecondaires)VALUES(@idAdresse,@nom,@prenom,@email,@tel,@adherentsSecondaires)"; // Définition des paramètres de la requête. bdd.Parameters.AddWithValue("@idAdresse", idAdresse); bdd.Parameters.AddWithValue("@nom", nom); bdd.Parameters.AddWithValue("@prenom", prenom); bdd.Parameters.AddWithValue("@email", email); bdd.Parameters.AddWithValue("@tel", telephone); bdd.Parameters.AddWithValue("@adherentsSecondaires", adherentsSecondaires); // Exécution de la requête try { bdd.ExecuteNonQuery(); } catch (Exception e) { estAjoute = false; MessageBox.Show("Requete invalide: " + e.Message, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error); } return estAjoute; } private string GetIdAdherent(SqlCommand bdd, string nom,string prenom) { // Définition de la requête. bdd.CommandText = "SELECT ADHERENT.idAdherent FROM ADHERENT WHERE ADHERENT.Nom = @nom AND Prenom = @prenom"; string idAdherent = null; try { using (SqlDataReader reader = bdd.ExecuteReader()) { if (reader.Read()) { idAdherent = String.Format("{0}", reader["idAdherent"]); } } } catch (Exception e) { MessageBox.Show("Requete invalide: " + e.Message, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error); } return idAdherent; } private bool AjouterAdhesionBDD(SqlCommand bdd,string idAdherent,bool cotisation, bool caution, string dateDebut) { estAjoute = true; // Définition de la requête. bdd.CommandText = "INSERT INTO LUDOTHEQUE.dbo.ADHESION(idAdherent,cotisation,caution,debutAdhesion)VALUES(@idAdherent,@cotisation,@caution,@debutAdhesion)"; bdd.Parameters.AddWithValue("@caution", caution); bdd.Parameters.AddWithValue("@cotisation", cotisation); bdd.Parameters.AddWithValue("@idAdherent", idAdherent); bdd.Parameters.AddWithValue("@debutAdhesion", dateDebut); // Définition des paramètres de la requête. // Exécution de la requête try { bdd.ExecuteNonQuery(); } catch (Exception e) { estAjoute = false; MessageBox.Show("Requete invalide: " + e.Message, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error); } return estAjoute; } private bool AjouterAdherents() { // 1 Réupérer les données. // 2 Vérifier les infos rentrées par l'utilisateur. // 3 Si ok -> requete SQL // Sinon -> message d'erreur et on ne fait rien. // 3.1 Verifier le retour de la requete // Si ok -> Message "bien enregistré" // Sinon -> message d'erreur et on ne fait rien. string nom = dataGridAdherentPrincipal.Rows[0].Cells[0].Value.ToString(); string prenom = dataGridAdherentPrincipal.Rows[0].Cells[1].Value.ToString(); string rue = dataGridAdherentPrincipal.Rows[0].Cells[2].Value.ToString(); string codePostal = dataGridAdherentPrincipal.Rows[0].Cells[3].Value.ToString(); string ville = dataGridAdherentPrincipal.Rows[0].Cells[4].Value.ToString(); string email = dataGridAdherentPrincipal.Rows[0].Cells[5].Value.ToString(); string telephone = dataGridAdherentPrincipal.Rows[0].Cells[6].Value.ToString(); string adherent1 = dataGridAdherentsSecondaires.Rows[0].Cells[0].Value.ToString(); string adherent2 = dataGridAdherentsSecondaires.Rows[0].Cells[1].Value.ToString(); string adherent3 = dataGridAdherentsSecondaires.Rows[0].Cells[2].Value.ToString(); string adherent4 = dataGridAdherentsSecondaires.Rows[0].Cells[3].Value.ToString(); string dateDebut = dataGridAdhesion.Rows[0].Cells[0].Value.ToString(); estAjoute = true; if (!String.IsNullOrEmpty(nom) && !String.IsNullOrEmpty(prenom) && !String.IsNullOrEmpty(rue) && !String.IsNullOrEmpty(codePostal) && !String.IsNullOrEmpty(ville) && !String.IsNullOrEmpty(email) && !String.IsNullOrEmpty(telephone) && !String.IsNullOrEmpty(adherent1) || !String.IsNullOrEmpty(adherent2) || !String.IsNullOrEmpty(adherent3) || !String.IsNullOrEmpty(adherent4) && !String.IsNullOrEmpty(dateDebut)) { SqlCommand bdd = Connexion.GetInstance().CreateCommand(); if (bdd != null) { // Ajout de l'adresse dans la base de donnée + adhérent + date adhésion _ = AjouterAdresseBDD(bdd, rue, codePostal, ville); string idAdresse = GetIdAdresse(bdd, rue, codePostal, ville); //string idAdherent = GetIdAdherent(bdd); string adherentsSecondaires = (adherent1 + " " + adherent2 + " " + adherent3 + " " + adherent4); _ = AjouterAdherentBDD(bdd,idAdresse, nom, prenom, email, telephone, adherentsSecondaires); string idAdherent = GetIdAdherent(bdd, nom, prenom); estAjoute = AjouterAdhesionBDD(bdd, idAdherent, cotisation, caution, dateDebut); // Définition des paramètres de la requête // Exécution de la requête try { bdd.ExecuteNonQuery(); } catch (Exception e) { estAjoute = false; MessageBox.Show("Requete invalide: " + e.Message, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { estAjoute = false; MessageBox.Show("La connexion à la bdd a échoué. Merci de réessayer ultérieurement.", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error); } // requeste SQL } else { estAjoute = false; MessageBox.Show("Les informations sont incomplètes.", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error); } return estAjoute; } private void ValiderClick(object sender, EventArgs e) { // Ancre le bouton dans le coin inférieur droit Valider_Button.Anchor = (AnchorStyles.Bottom | AnchorStyles.Right); Valider_Button.Text = "Valider"; Valider_Button.BackColor = Color.OrangeRed; if (AjouterAdherents()) { MessageBox.Show("Adhérent enregistré!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("Adhérent non enregistré!", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void textBox3_TextChanged(object sender, EventArgs e) { } private void Adherents_Load(object sender, EventArgs e) { } private void Cotisation_CheckBox_CheckedChanged(object sender, EventArgs e) { cotisation = true; } private void Caution_CheckBox_CheckedChanged(object sender, EventArgs e) { caution = true; } private void textBox1_TextChanged(object sender, EventArgs e) { } } } <file_sep>/View Controller/Administration.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; namespace LUDOGAMM { public partial class Administration : MenuView { public bool estAjoute; public int prixCotisation; public int prixCaution; public int dureeAdhesion; public int nbJeuxEmpruntable; public int dureeEmprunt; public string dateDebut; public string dateFin; public Administration() { InitializeComponent(); } private bool AjouterAdministrationBDD(SqlCommand bdd, int prixCotisation, int prixCaution, int dureeAdhesion, int nbJeuxEmpruntable, int dureeEmprunt, string dateDebut, string dateFin) { estAjoute = true; // Définition de la requête. bdd.CommandText = "INSERT INTO LUDOTHEQUE.dbo.ADMINISTRATION(prixCotisation,prixCaution,dureeAdhesion, nbJeuxEmpruntable, dureeEmprunt, dateDebut, dateFin)VALUES(@prixcotisation,@prixCaution,@dureeAdhesion,@nbJeuxEmpruntable,@dureeEmprunt,@dateDebut,@dateFin)"; // Définition des paramètres de la requête. bdd.Parameters.AddWithValue("@prixCotisation", prixCotisation); bdd.Parameters.AddWithValue("@prixCaution", prixCaution); bdd.Parameters.AddWithValue("@dureeAdhesion", dureeAdhesion); bdd.Parameters.AddWithValue("@nbJeuxEmpruntable", nbJeuxEmpruntable); bdd.Parameters.AddWithValue("@dureeEmprunt", dureeEmprunt); bdd.Parameters.AddWithValue("@dateDebut", dateDebut); bdd.Parameters.AddWithValue("@dateFin", dateFin); // Exécution de la requête try { bdd.ExecuteNonQuery(); } catch (Exception e) { estAjoute = false; MessageBox.Show("Requete invalide: " + e.Message, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error); } return estAjoute; } private string GetAdministration(SqlCommand bdd, int prixCotisation, int prixCaution, int dureeAdhesion, int nbJeuxEmpruntable, int dureeEmprunt, string dateDebut, string dateFin) { // Définition de la requête. bdd.CommandText = "SELECT ADMINISTRATION.idAbonnement FROM ADRESSE where prixCotisation = @prixCotisation and prixCaution = @prixCaution and dureeAdhesion = @dureeAdhesion and nbJeuxEmpruntable = @nbJeuxEmpruntable and dureeEmprunt = @dureeEmprunt and dateDebut = @dateDebut and dateFin = @dateFin "; string idAabonnement = null; try { using (SqlDataReader reader = bdd.ExecuteReader()) { if (reader.Read()) { idAabonnement = String.Format("{0}", reader["idAabonnement"]); } } } catch (Exception e) { MessageBox.Show("Requete invalide: " + e.Message, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error); } return idAabonnement; } private bool AjouterAdministration() { // 1 Réupérer les données. // 2 Vérifier les infos rentrées par l'utilisateur. // 3 Si ok -> requete SQL // Sinon -> message d'erreur et on ne fait rien. // 3.1 Verifier le retour de la requete // Si ok -> Message "bien enregistré" // Sinon -> message d'erreur et on ne fait rien. string prixCotisation = dataGridAdminF.Rows[0].Cells[0].Value.ToString(); string prixCaution = dataGridAdminF.Rows[0].Cells[1].Value.ToString(); string dureeAdhesion = dataGridAdminF.Rows[0].Cells[2].Value.ToString(); string nbJeuxEmpruntable = dataGridAdminF.Rows[0].Cells[3].Value.ToString(); string dureeEmprunt = dataGridAdminF.Rows[0].Cells[4].Value.ToString(); string dateDebut = dataGridAdminF.Rows[0].Cells[5].Value.ToString(); string dateFin = dataGridAdminF.Rows[0].Cells[6].Value.ToString(); estAjoute = true; if (!String.IsNullOrEmpty(prixCotisation) && !String.IsNullOrEmpty(prixCaution) && !String.IsNullOrEmpty(dureeAdhesion) && !String.IsNullOrEmpty(nbJeuxEmpruntable) && !String.IsNullOrEmpty(dureeEmprunt) && !String.IsNullOrEmpty(dateDebut) && !String.IsNullOrEmpty(dateFin)) { SqlCommand bdd = Connexion.GetInstance().CreateCommand(); if (bdd != null) { // Ajout de l'adresse dans la base de donnée + adhérent + date adhésion _ = AjouterAdministrationBDD(bdd, Convert.ToInt32(prixCotisation), Convert.ToInt32(prixCaution), Convert.ToInt32(dureeAdhesion), Convert.ToInt32(nbJeuxEmpruntable), Convert.ToInt32(dureeEmprunt), dateDebut, dateFin); string idAbonnement = GetAdministration(bdd, Convert.ToInt32(prixCotisation), Convert.ToInt32(prixCaution), Convert.ToInt32(dureeAdhesion), Convert.ToInt32(nbJeuxEmpruntable), Convert.ToInt32(dureeEmprunt), dateDebut, dateFin); estAjoute = AjouterAdministrationBDD(bdd, Convert.ToInt32(prixCotisation), Convert.ToInt32(prixCaution), Convert.ToInt32(dureeAdhesion), Convert.ToInt32(nbJeuxEmpruntable), Convert.ToInt32(dureeEmprunt), dateDebut, dateFin); // Définition des paramètres de la requête // Exécution de la requête try { bdd.ExecuteNonQuery(); } catch (Exception e) { estAjoute = false; MessageBox.Show("Requete invalide: " + e.Message, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { estAjoute = false; MessageBox.Show("La connexion à la bdd a échoué. Merci de réessayer ultérieurement.", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error); } // requeste SQL } else { estAjoute = false; MessageBox.Show("Les informations sont incomplètes.", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error); } return estAjoute; } private void ValiderClick(object sender, EventArgs e) { // Ancre le bouton dans le coin inférieur droit Valider_ButtonF.Anchor = (AnchorStyles.Bottom | AnchorStyles.Right); Valider_ButtonF.Text = "Valider"; Valider_ButtonF.BackColor = Color.Blue; if (AjouterAdministration()) { MessageBox.Show("Adhérent enregistré!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("Adhérent non enregistré!", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void Administration_Load(object sender, EventArgs e) { } private void label1_Click(object sender, EventArgs e) { } private void label2_Click(object sender, EventArgs e) { } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void dataGridAdmin_CellContentClick(object sender, DataGridViewCellEventArgs e) { this.dataGridAdminF.GridColor = Color.Black; this.dataGridAdminF.BorderStyle = BorderStyle.Fixed3D; this.Controls.Add(dataGridAdminF); dataGridAdminF.ColumnCount = 10; DataGridViewCellStyle style = dataGridAdminF.ColumnHeadersDefaultCellStyle; style.BackColor = Color.OrangeRed; style.ForeColor = Color.Black; style.Font = new Font(dataGridAdminF.Font, FontStyle.Bold); dataGridAdminF.EditMode = DataGridViewEditMode.EditOnEnter; dataGridAdminF.Name = "Ajouter administration"; dataGridAdminF.Location = new Point(8, 8); dataGridAdminF.Size = new Size(500, 400); dataGridAdminF.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders; dataGridAdminF.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Raised; dataGridAdminF.CellBorderStyle = DataGridViewCellBorderStyle.Single; dataGridAdminF.GridColor = SystemColors.ActiveBorder; dataGridAdminF.RowHeadersVisible = true; dataGridAdminF.Columns[0].Name = "prixCotisation"; dataGridAdminF.Columns[1].Name = "prixCaution"; dataGridAdminF.Columns[2].Name = "dureeAdhesion"; dataGridAdminF.Columns[3].Name = "nbJeuxEmpruntable"; dataGridAdminF.Columns[4].Name = "dureeEmprunt"; dataGridAdminF.Columns[5].Name = "dateDebut"; dataGridAdminF.Columns[6].Name = "dateFin"; } } } <file_sep>/Jeu.cs using System; using System.Collections.Generic; using System.Text; namespace LUDOGAMM { public class Jeu { public string titre; public string auteur; public string editeur; public string regleDuJeu; public int idJeu; public string contenuComplementaire; } } <file_sep>/GererAdherentSQL.cs using LUDOGAMM; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Text; namespace LUDOGAMM { class GererAdherentSQL { public static void CreerAdherent(string nom, string prenom, string rue, string ville, int codePostal, string mail, string telephone) { SqlCommand command = Connexion.GetInstance().CreateCommand(); command.CommandText = "INSERT INTO LUDOTHEQUE.dbo.ADHERENT(nom,prenom,rue,ville,codePostal,mail,telephone)VALUES(@nom,@prenom,@rue,@ville,@cp,@mail,@tel)"; // Définition de la requête command.Parameters.AddWithValue("@nom", nom); command.Parameters.AddWithValue("@prenom", prenom); command.Parameters.AddWithValue("@rue", rue); command.Parameters.AddWithValue("@ville", ville); command.Parameters.AddWithValue("@cp", codePostal); command.Parameters.AddWithValue("@mail", mail); command.Parameters.AddWithValue("@tel", telephone); // Exécution de la requête command.ExecuteNonQuery(); } } } <file_sep>/View Controller/MenuView.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace LUDOGAMM { public partial class MenuView : Form { public MenuView() { InitializeComponent(); } private void MenuView_Load(object sender, EventArgs e) { } private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) { } private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) { if (e.Node.Text == "Ajouter adhérent") { var adherent = new Adherents(); adherent.Show(); Hide(); } if (e.Node.Text == "Ajouter un exemplaire") { var jeu = new AjouterJeu(); jeu.Show(); Hide(); } if (e.Node.Text == "Administration") { var admin = new Administration(); admin.Show(); Hide(); } } } } <file_sep>/GererStockSQL.cs using System; using System.Collections.Generic; using System.Text; namespace LUDOGAMM { class GererStockSQL { } }
30c0c5ef2f9846bfa4d8c251ec1b479923b149c7
[ "C#" ]
25
C#
glebrech/LUDOGAMM
60ec0ca9c6673112dcc15fc287006b450c8a43d4
911af1ee31be655f423e8f7c043f313900529797
refs/heads/master
<file_sep>from selenium import webdriver import unittest import time from selenium.webdriver import ActionChains from selenium.webdriver.common.by import By class CreateInterface(unittest.TestCase): @classmethod def setUpClass(cls): cls.driver = webdriver.Chrome() cls.driver.get("http://www.doclever.cn") cls.driver.maximize_window() @classmethod def tearDownClass(cls): cls.driver.quit() def test_login(self): driver = self.driver time.sleep(2) # driver.find_element_by_link_text(u"登录").click() driver.find_element_by_xpath("//*[contains(text(),'登录')]").click() time.sleep(2) driver.find_element_by_xpath("//input[@type='text']").click() driver.find_element_by_xpath("//input[@type='text']").clear() driver.find_element_by_xpath("//input[@type='text']").send_keys("<PASSWORD>") driver.find_element_by_xpath("//input[@type='password']").clear() driver.find_element_by_xpath("//input[@type='password']").send_keys("<PASSWORD>") driver.find_element_by_id("login").click() time.sleep(2) self.assertEqual(driver.current_url,"http://www.doclever.cn/controller/console/console.html") def test_creat_interface(self): driver = self.driver time.sleep(5) #进入MyHome项目 # driver.find_element_by_xpath("//*[contains(text(),'MyHome')]").click() driver.find_element_by_xpath( u"(.//*[normalize-space(text()) and normalize-space(.)='MyHome'])[1]/following::div[6]").click() #在Homework文件夹下创建接口createport driver.find_element_by_xpath("//div[@id='group1']/div[3]/div[3]/i").click() driver.find_element_by_xpath("(//input[@type='text'])[4]").click() driver.find_element_by_xpath("(//input[@type='text'])[4]").clear() driver.find_element_by_xpath("(//input[@type='text'])[4]").send_keys("createport") driver.find_element_by_xpath("(//input[@type='text'])[8]").click() driver.find_element_by_xpath("(.//*[normalize-space(text()) and normalize-space(.)='GET'])[1]/following::span[1]").click() driver.find_element_by_xpath("(//input[@type='text'])[9]").click() driver.find_element_by_xpath("(//input[@type='text'])[9]").clear() driver.find_element_by_xpath("(//input[@type='text'])[9]").send_keys("/user/login") driver.find_element_by_xpath("(//input[@type='text'])[15]").click() driver.find_element_by_xpath("(//input[@type='text'])[15]").clear() driver.find_element_by_xpath("(//input[@type='text'])[15]").send_keys("username") driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='必选'])[2]/following::span[2]").click() driver.find_element_by_xpath("(//input[@type='text'])[44]").click() driver.find_element_by_xpath("(//input[@type='text'])[44]").clear() driver.find_element_by_xpath("(//input[@type='text'])[44]").send_keys("seist") driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='新增'])[2]/following::button[1]").click() driver.find_element_by_xpath("(//input[@type='text'])[18]").click() driver.find_element_by_xpath("(//input[@type='text'])[18]").clear() driver.find_element_by_xpath("(//input[@type='text'])[18]").send_keys("<PASSWORD>") driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='必选'])[3]/following::span[2]").click() driver.find_element_by_xpath("(//input[@type='text'])[47]").click() driver.find_element_by_xpath("(//input[@type='text'])[47]").clear() driver.find_element_by_xpath("(//input[@type='text'])[47]").send_keys("123456") driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='新增'])[2]/following::button[1]").click() driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='运行'])[1]/following::button[1]").click() driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='自动保存'])[1]/following::span[1]").click() driver.find_element_by_xpath("(//input[@type='text'])[5]").click() driver.find_element_by_xpath("(//input[@type='text'])[5]").clear() driver.find_element_by_xpath("(//input[@type='text'])[5]").send_keys("www.doclever.cn") driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='导入分组'])[2]/following::span[1]").click() driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='取消'])[1]/following::button[1]").click() driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='运行'])[1]/following::span[2]").click() driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='自动保存'])[1]/following::span[1]").click() driver.find_element_by_xpath(u"(.//*[normalize-space(text()) and normalize-space(.)='生成'])[1]/following::span[1]").click() def test_logout(self): driver = self.driver time.sleep(3) logout = driver.find_element_by_xpath('//*[contains(text(),"test_yoyo")]') ActionChains(driver).move_to_element(logout).perform() # 把鼠标放到元素上,其他的什么都不动 time.sleep(1) driver.find_element_by_xpath( "(.//*[normalize-space(text()) and normalize-space(.)='帮助中心'])[1]/following::li[1]").click() time.sleep(5) self.assertTrue(self.is_element_present(By.LINK_TEXT, "登录")) if __name__ == '__main__': suite = unittest.TestSuite() suite.addTests[CreateInterface("test_login"),CreateInterface("test_creat_interface"),CreateInterface("test_logout")] runner = unittest.TextTestRunner runner.run(suite)<file_sep>[INFO] USER = seist-x PASSWORD = <PASSWORD>
04c51d6c0cd5c8c7a72299eb23708cfb3a908c0a
[ "Python", "INI" ]
2
Python
seist-x/py_demo
295a62bd0ffb5faa529a3551d69f95db7247135e
0fce6b20ac454cc7ef7979a91569739d58bbb0dc
refs/heads/master
<file_sep>package com.example.myapplication; import android.content.Context; import android.support.annotation.NonNull; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.facebook.drawee.view.SimpleDraweeView; import java.util.List; /** * Created by liuzhouliang on 2018/1/8. */ public class MyPagerAdapter extends PagerAdapter { private Context context; private List<View> list; // private int newPosition; public MyPagerAdapter(Context context, List<View> list) { this.context = context; this.list = list; } @Override public int getCount() { //使用Integer的最大值,这样基本上就不需要滑动到最后了 //除非用户很蛋疼 // return Integer.MAX_VALUE; return list.size(); } @Override public Object instantiateItem(final ViewGroup container, final int position) { //当前位置模上总数等于图片在数组中的位置 // newPosition =position% list.size(); // if (newPosition < 0) { // newPosition = list.size() + newPosition; // } SimpleDraweeView imageView = list.get(position).findViewById(R.id.iv); //设置轮播点击事件 imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // if(newPosition==0){ // Toast.makeText(context, "test"+"最后一页", Toast.LENGTH_SHORT).show(); // }else{ // Toast.makeText(context, "test"+newPosition, Toast.LENGTH_SHORT).show(); // } Toast.makeText(context, "test"+(position+1), Toast.LENGTH_SHORT).show(); } }); ViewGroup parent = (ViewGroup) list.get(position).getParent(); if (parent != null) { parent.removeView(list.get(position)); } container.addView(list.get(position)); return list.get(position); } @Override public boolean isViewFromObject(View view, Object object) { return object == view; } @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { } } <file_sep>package com.example.myapplication; import android.os.Handler; import android.os.Message; import java.lang.ref.WeakReference; /** * Created by liuzhouliang on 2018/1/8. */ public class MyHandler extends Handler { public static final int BANNER_NEXT = 0; public static final int BANNER_PAUSE = 1; public static final int BANNER_RESUME = 2; public static final int CHANGE_TIME=2000; //使用弱引用,避免handler造成内存泄露 private WeakReference<MainActivity> weakReference; public MyHandler(WeakReference<MainActivity> weakReference) { this.weakReference = weakReference; } @Override public void handleMessage(Message msg) { MainActivity activity = weakReference.get(); //Activity不存在了,就不需要再处理了 if (activity == null) { return; } //如果已经有消息了,先移除消息 if (activity.handler.hasMessages(BANNER_NEXT)) { activity.handler.removeMessages(BANNER_NEXT); } switch (msg.what) { case BANNER_NEXT: //跳到下一页, int currentItem = activity.viewPager.getCurrentItem(); // Log.e("TAG","BANNER_NEXT==当前页"+currentItem); activity.viewPager.setCurrentItem(++currentItem); //2秒后继续轮播 // activity.handler.sendEmptyMessageDelayed(BANNER_NEXT, CHANGE_TIME); break; case BANNER_PAUSE: //暂停,不需要做任务操作 removeMessages(BANNER_NEXT); break; case BANNER_RESUME: //继续轮播 // activity.handler.sendEmptyMessageDelayed(BANNER_NEXT, CHANGE_TIME); break; } } } <file_sep>package com.example.myapplication; import android.app.Activity; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.RadioGroup; import android.widget.TextView; import com.facebook.drawee.view.SimpleDraweeView; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; public class MainActivity extends Activity { public ViewPager viewPager; public MyHandler handler; private LayoutInflater layoutInflater; private View childOne; private View childTwo; private View childThree; private View childFour; private RadioGroup radioGroup; //当前索引位置以及上一个索引位置 public int index = 0, preIndex = 0; private List<View> list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); radioGroup = findViewById(R.id.group); layoutInflater = LayoutInflater.from(this); childOne = layoutInflater.inflate(R.layout.item, null); childTwo = layoutInflater.inflate(R.layout.item, null); childThree = layoutInflater.inflate(R.layout.item, null); childFour = layoutInflater.inflate(R.layout.item, null); SimpleDraweeView imageView1 = childOne.findViewById(R.id.iv); SimpleDraweeView imageView2 = childTwo.findViewById(R.id.iv); SimpleDraweeView imageView3 = childThree.findViewById(R.id.iv); // SimpleDraweeView imageView4 = childFour.findViewById(R.id.iv); TextView textView1 = childOne.findViewById(R.id.title); TextView textView2 = childTwo.findViewById(R.id.title); TextView textView3 = childThree.findViewById(R.id.title); // TextView textView4 = childFour.findViewById(R.id.title); textView1.setText("1"); textView2.setText("2"); textView3.setText("3"); // textView4.setText("4"); Uri uri1 = Uri.parse("http://pic4.nipic.com/20091217/3885730_124701000519_2.jpg"); Uri uri2 = Uri.parse("http://pic47.nipic.com/20140826/9532020_221427317000_2.jpg"); Uri uri3 = Uri.parse("http://img3.redocn.com/tupian/20150318/qingxinshuzhibiankuang_4021000.jpg"); // Uri uri4 = Uri.parse("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1515416541169&di=8bc94a4be8e64b56dbe90d4241e4651d&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimgad%2Fpic%2Fitem%2F32fa828ba61ea8d3d8d6c33f9c0a304e251f5810.jpg"); imageView1.setImageURI(uri1); imageView2.setImageURI(uri2); imageView3.setImageURI(uri3); // imageView4.setImageURI(uri4); list = new ArrayList<>(); list.add(childOne); list.add(childTwo); list.add(childThree); // list.add(childFour); initRadioButton(list.size()); WeakReference<MainActivity> weakReference = new WeakReference(this); MyPagerAdapter adapter = new MyPagerAdapter(this, list, weakReference); viewPager = findViewById(R.id.view_pager); viewPager.setAdapter(adapter); handler = new MyHandler(weakReference); //开始轮播 // handler.sendEmptyMessageDelayed(MyHandler.BANNER_NEXT, 2000); viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { index = position % list.size(); } @Override public void onPageSelected(int position) { index = position % list.size();//当前位置赋值给索引 setCurrentDot(index); } @Override public void onPageScrollStateChanged(int state) { switch (state) { case ViewPager.SCROLL_STATE_DRAGGING: //用户正在滑动,暂停轮播 // handler.sendEmptyMessage(MyHandler.BANNER_PAUSE); break; case ViewPager.SCROLL_STATE_IDLE: //滑动结束,继续轮播 // handler.sendEmptyMessageDelayed(MyHandler.BANNER_NEXT, MyHandler.CHANGE_TIME); break; } } }); String url="http://pic4.nipic.com/20091217/3885730_124701000519_2.jpg"; String url1="http://172.16.17.32:8080/ncme/ncme/%E7%AC%AC%E4%B8%80%E8%B7%96%E9%AA%A8%E6%88%AA%E9%AA%A8.png?AWSAccessKeyId=<KEY>&Expires=1541643041&Signature=3zf5SaNXzqdO0zmMYp%2ByE40IDmc%3D"; FrescoLoadUtil.getInstance().loadImageBitmap(url, new FrescoBitmapCallback<Bitmap>() { @Override public void onSuccess(Uri uri, Bitmap result) { Bitmap bitmap=result; } @Override public void onFailure(Uri uri, Throwable throwable) { Log.e("tag","onFailure"); } @Override public void onCancel(Uri uri) { Log.e("tag","onCancel"); } }); } /** * 根据图片个数初始化按钮 * * @param length */ private void initRadioButton(int length) { for (int i = 0; i < length; i++) { ImageView imageview = new ImageView(this); imageview.setImageResource(R.drawable.gj_home_banner_indicator_bg);//设置背景选择器 imageview.setPadding(20, 0, 0, 0);//设置每个按钮之间的间距 //将按钮依次添加到RadioGroup中 radioGroup.addView(imageview, 40, 40); //默认选中第一个按钮,因为默认显示第一张图片 radioGroup.getChildAt(0).setEnabled(false); } } /** * 设置对应位置按钮的状态 * * @param i 当前位置 */ private void setCurrentDot(int i) { for (int m = 0; m < radioGroup.getChildCount(); m++) { if (radioGroup.getChildAt(m) != null) { radioGroup.getChildAt(m).setEnabled(true);//当前按钮选中 } } if (radioGroup.getChildAt(i) != null) { radioGroup.getChildAt(i).setEnabled(false);//当前按钮选中 } } @Override protected void onDestroy() { super.onDestroy(); handler.removeMessages(MyHandler.BANNER_NEXT); } } <file_sep>include ':GradleTest', ':GradleLib', ':GradleLib1', 'BottomBar', ':bottom-bar', ':app', ':广告轮播', ':广告轮播Lib', ':广告轮播1', ':banner', ':城市选择lib', ':城市选择', '下拉刷新', '下拉刷新2' include ':下拉刷新1' include ':图片回落到原处' <file_sep>package com.example.myapplication; import android.app.Activity; import android.os.Bundle; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class MainActivity extends Activity { private String TAG="TAG"; private ViewPager pager; //每一个界面 private List<View> views; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); pager=findViewById(R.id.viewPager); views=new ArrayList<View>(); LayoutInflater li=getLayoutInflater(); views.add(li.inflate(R.layout.f1, null)); views.add(li.inflate(R.layout.f2, null)); views.add(li.inflate(R.layout.f3, null)); views.add(li.inflate(R.layout.f4, null)); //需要给ViewPager设置适配器 PagerAdapter adapter=new PagerAdapter() { @Override public boolean isViewFromObject(View arg0, Object arg1) { // TODO Auto-generated method stub return arg0==arg1; } //有多少个切换页 @Override public int getCount() { // TODO Auto-generated method stub return views.size(); } //对超出范围的资源进行销毁 @Override public void destroyItem(ViewGroup container, int position, Object object) { // TODO Auto-generated method stub //super.destroyItem(container, position, object); Log.e(TAG,"destroyItem==="+position); container.removeView(views.get(position)); } //对显示的资源进行初始化 @Override public Object instantiateItem(ViewGroup container, final int position) { // TODO Auto-generated method stub Log.e(TAG,"instantiateItem==="+position); views.get(position).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this,position+"",Toast.LENGTH_SHORT).show(); } }); container.addView(views.get(position)); return views.get(position); } }; pager.setAdapter(adapter); } }
2407e020be0114594023322b1d975fbfcf9348c2
[ "Java", "Gradle" ]
5
Java
alexlzl/AndroidDemo8
82ffc0627aca6212baac1c32381459baba0fe1f5
1b7332140d798460b8e7849579bab36348d802bf
refs/heads/master
<repo_name>midas-journal/midas-journal-705<file_sep>/Source/itkGaussianInterpolateImageFunctionTest.cxx /*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkGaussianInterpolateImageFunctionTest.cxx,v $ Language: C++ Date: $Date: $ Version: $Revision: $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "itkGaussianInterpolateImageFunction.h" #include "itkIdentityTransform.h" #include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkLinearInterpolateImageFunction.h" #include "itkNearestNeighborInterpolateImageFunction.h" #include "itkResampleImageFilter.h" #include "itkTimeProbe.h" #include <stdio.h> #include <string> #include <vector> template<class TValue> TValue Convert( std::string optionString ) { TValue value; std::istringstream iss( optionString ); iss >> value; return value; } template<class TValue> std::vector<TValue> ConvertVector( std::string optionString ) { std::vector<TValue> values; std::string::size_type crosspos = optionString.find( 'x', 0 ); if ( crosspos == std::string::npos ) { values.push_back( Convert<TValue>( optionString ) ); } else { std::string element = optionString.substr( 0, crosspos ) ; TValue value; std::istringstream iss( element ); iss >> value; values.push_back( value ); while ( crosspos != std::string::npos ) { std::string::size_type crossposfrom = crosspos; crosspos = optionString.find( 'x', crossposfrom + 1 ); if ( crosspos == std::string::npos ) { element = optionString.substr( crossposfrom + 1, optionString.length() ); } else { element = optionString.substr( crossposfrom + 1, crosspos ) ; } std::istringstream iss( element ); iss >> value; values.push_back( value ); } } return values; } template <unsigned int ImageDimension> int ResampleImage( int argc, char *argv[] ) { typedef double RealType; typedef double PixelType; typedef itk::Image<PixelType, ImageDimension> ImageType; typedef itk::ImageFileReader<ImageType> ReaderType; typename ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[2] ); reader->Update(); typedef itk::IdentityTransform<RealType, ImageDimension> TransformType; typename TransformType::Pointer transform = TransformType::New(); transform->SetIdentity(); typedef itk::LinearInterpolateImageFunction<ImageType, RealType> LinearInterpolatorType; typename LinearInterpolatorType::Pointer interpolator = LinearInterpolatorType::New(); interpolator->SetInputImage( reader->GetOutput() ); typedef itk::NearestNeighborInterpolateImageFunction<ImageType, RealType> NearestNeighborInterpolatorType; typename NearestNeighborInterpolatorType::Pointer nn_interpolator = NearestNeighborInterpolatorType::New(); nn_interpolator->SetInputImage( reader->GetOutput() ); typedef itk::GaussianInterpolateImageFunction<ImageType, RealType> GaussianInterpolatorType; typename GaussianInterpolatorType::Pointer g_interpolator = GaussianInterpolatorType::New(); g_interpolator->SetInputImage( reader->GetOutput() ); double sigma[ImageDimension]; for( unsigned int d = 0; d < ImageDimension; d++ ) { sigma[d] = reader->GetOutput()->GetSpacing()[d]; } double alpha = 1.0; if( argc > 7 ) { std::vector<RealType> sg = ConvertVector<RealType>( std::string( argv[7] ) ); for( unsigned int d = 0; d < ImageDimension; d++ ) { sigma[d] = sg[d]; } } if( argc > 8 ) { alpha = static_cast<double>( atof( argv[8] ) ); } g_interpolator->SetParameters( sigma, alpha ); typedef itk::ResampleImageFilter<ImageType, ImageType, RealType> ResamplerType; typename ResamplerType::Pointer resampler = ResamplerType::New(); typename ResamplerType::SpacingType spacing; typename ResamplerType::SizeType size; std::vector<RealType> sp = ConvertVector<RealType>( std::string( argv[4] ) ); if( argc <= 5 || atoi( argv[5] ) == 0 ) { if ( sp.size() == 1 ) { spacing.Fill( sp[0] ); } else if ( sp.size() == ImageDimension ) { for ( unsigned int d = 0; d < ImageDimension; d++ ) { spacing[d] = sp[d]; } } else { std::cerr << "Invalid spacing." << std::endl; } for ( unsigned int i = 0; i < ImageDimension; i++ ) { RealType spacing_old = reader->GetOutput()->GetSpacing()[i]; RealType size_old = reader->GetOutput()->GetLargestPossibleRegion().GetSize()[i]; size[i] = static_cast<int>( ( spacing_old * size_old ) / spacing[i] + 0.5 ); } } else { if ( sp.size() == 1 ) { size.Fill( static_cast<unsigned int>( sp[0] ) ); } else if ( sp.size() == ImageDimension ) { for ( unsigned int d = 0; d < ImageDimension; d++ ) { size[d] = static_cast<unsigned int>( sp[d] ); } } else { std::cerr << "Invalid size." << std::endl; } for ( unsigned int i = 0; i < ImageDimension; i++ ) { RealType spacing_old = reader->GetOutput()->GetSpacing()[i]; RealType size_old = reader->GetOutput()->GetLargestPossibleRegion().GetSize()[i]; spacing[i] = spacing_old * static_cast<float>( size_old - 1.0 ) / static_cast<float>( size[i] - 1.0 ); } } resampler->SetTransform( transform ); resampler->SetInterpolator( interpolator ); if( argc > 6 && atoi( argv[6] ) ) { switch( atoi( argv[6] ) ) { case 0: default: resampler->SetInterpolator( interpolator ); break; case 1: resampler->SetInterpolator( nn_interpolator ); break; case 2: resampler->SetInterpolator( g_interpolator ); break; } } resampler->SetInput( reader->GetOutput() ); resampler->SetOutputSpacing( spacing ); resampler->SetOutputOrigin( reader->GetOutput()->GetOrigin() ); resampler->SetSize( size ); resampler->SetNumberOfThreads( 1 ); resampler->SetOutputDirection( reader->GetOutput()->GetDirection() ); itk::TimeProbe timer; timer.Start(); try { resampler->Update(); } catch(...) { return EXIT_FAILURE; } timer.Stop(); std::cout << "Elapsed time: " << timer.GetMeanTime() << std::endl; typedef itk::ImageFileWriter<ImageType> WriterType; typename WriterType::Pointer writer = WriterType::New(); writer->SetFileName( argv[3] ); writer->SetInput( resampler->GetOutput() ); writer->Update(); return 0; } int main( int argc, char *argv[] ) { if ( argc < 5 ) { std::cout << "Usage: " << argv[0] << " imageDimension inputImage " << "outputImage MxNxO [size=1,spacing=0] [interpolate type]" << std::endl; std::cout << " Interpolation type: " << std::endl; std::cout << " 0. linear (default)" << std::endl; std::cout << " 1. nearest neighbor " << std::endl; std::cout << " 2. gaussian [sigma] [alpha]" << std::endl; exit( 1 ); } switch( atoi( argv[1] ) ) { case 2: ResampleImage<2>( argc, argv ); break; case 3: ResampleImage<3>( argc, argv ); break; default: std::cerr << "Unsupported dimension" << std::endl; exit( EXIT_FAILURE ); } } <file_sep>/Source/CMakeLists.txt cmake_minimum_required(VERSION 2.4) PROJECT( GaussianInterpolation ) #The following lines are required to use Dart ENABLE_TESTING() INCLUDE(Dart) # Set up ITK IF(USE_ITK) FIND_PACKAGE(ITK) IF(ITK_FOUND) INCLUDE(${ITK_USE_FILE}) ELSE(ITK_FOUND) MESSAGE(FATAL_ERROR "Cannot build without ITK. Please set ITK_DIR.") ENDIF(ITK_FOUND) ENDIF(USE_ITK) INCLUDE (${CMAKE_ROOT}/Modules/FindITK.cmake) IF (USE_ITK_FILE) INCLUDE(${USE_ITK_FILE}) ENDIF(USE_ITK_FILE) LINK_DIRECTORIES(${ITK_LIBRARY_PATH}) IF(BUILD_TESTING) # non-templated class -- this should be stored in a library and linked in... ADD_EXECUTABLE(itkGaussianInterpolateImageFunctionTest itkGaussianInterpolateImageFunctionTest.cxx) TARGET_LINK_LIBRARIES(itkGaussianInterpolateImageFunctionTest ITKIO) ENDIF(BUILD_TESTING) ### # Perform testing ### ADD_TEST( NN_INTERP ${CMAKE_BINARY_DIR}/itkGaussianInterpolateImageFunctionTest 2 ${CMAKE_SOURCE_DIR}/r16slice.nii.gz ${CMAKE_BINARY_DIR}/r16slice_interp_nn.nii.gz 50x50 1 1 ) ADD_TEST( LINEAR_INTERP ${CMAKE_BINARY_DIR}/itkGaussianInterpolateImageFunctionTest 2 ${CMAKE_SOURCE_DIR}/r16slice.nii.gz ${CMAKE_BINARY_DIR}/r16slice_interp_linear.nii.gz 50x50 1 0 ) ADD_TEST( GAUSS1x1_INTERP ${CMAKE_BINARY_DIR}/itkGaussianInterpolateImageFunctionTest 2 ${CMAKE_SOURCE_DIR}/r16slice.nii.gz ${CMAKE_BINARY_DIR}/r16slice_interp_guassian1x1.nii.gz 50x50 1 2 1x1 3.0 ) ADD_TEST( GAUSS5x5_INTERP ${CMAKE_BINARY_DIR}/itkGaussianInterpolateImageFunctionTest 2 ${CMAKE_SOURCE_DIR}/r16slice.nii.gz ${CMAKE_BINARY_DIR}/r16slice_interp_guassian5x5.nii.gz 50x50 1 2 5x5 3.0 ) ADD_TEST( GAUSS1x5_INTERP ${CMAKE_BINARY_DIR}/itkGaussianInterpolateImageFunctionTest 2 ${CMAKE_SOURCE_DIR}/r16slice.nii.gz ${CMAKE_BINARY_DIR}/r16slice_interp_guassian1x5.nii.gz 50x50 1 2 1x5 3.0 )
a1ebc6dde17c1c9b13eac6f93c6dd479b535751d
[ "CMake", "C++" ]
2
C++
midas-journal/midas-journal-705
a0440a28d6bd9784a4b1d46648952c866c3d48ed
815e0cc16a88766a09cf3179377a46e9b77539d7
refs/heads/master
<file_sep>include ':ndege' <file_sep>Ndege ===== <file_sep>package com.droid.ndege.ui.frags; /** * Created by james on 10/02/14. */ public class TagBirdFrag { }
f4af5156958d59c9fcb1e3d6f159cf0b3b46da11
[ "Markdown", "Java", "Gradle" ]
3
Gradle
oguya/Ndege
66f7f5623af5a574f5d6d338609dcdc2b5241aae
08451044058af9a37c5eed333b3e9925c590672f
refs/heads/master
<file_sep>// // ViewController.swift // Gamez // // Created by SHAGUN on 10/18/16. // Copyright © 2016 SHAGUN . All rights reserved. // import UIKit class ViewController: UIViewController,UITextFieldDelegate { @IBOutlet weak var label_ques: UILabel! @IBOutlet weak var label_ans: UILabel! @IBAction func playAgain(sender: UIButton) { question() solution() textField.text=nil label_ans!.text=nil ansFieldNormalState() textField.resignFirstResponder() } @IBOutlet weak var textField: UITextField! @IBAction func Submit(sender: UIButton) { submitHit() textField.resignFirstResponder() } var answer: Int?{ didSet{ changeAnswerLabel(label_ans!) } } override func viewDidLoad() { super.viewDidLoad() ansFieldNormalState() question() textField.delegate = self label_ans?.textColor = UIColor.clearColor() textField.keyboardType = UIKeyboardType.NumbersAndPunctuation } var num: Int = 0 var num1: Int = 0 var num2: Int = 0 func textFieldShouldReturn(textField: UITextField) -> Bool { submitHit() textField.resignFirstResponder() return true } func submitHit(){ if let text = textField.text, let value = Int(text){ answer = value; } else{ answer = nil ansFieldNormalState() label_ans?.textColor = UIColor.clearColor() } } func randomOperatorgenerator()-> String{ let operator_array = ["+", "-", "X"] num = Int(arc4random_uniform(3)) return operator_array[num] } func question(){ num1 = Int(arc4random_uniform(10) + 1) num2 = Int(arc4random_uniform(10) + 1) label_ques?.text = "\(num1) \(randomOperatorgenerator()) \(num2)" } func solution() -> Int{ var solution: Int? switch num { case 0: solution = (num1 + num2) case 1: solution = (num1 - num2) case 2: solution = (num1 * num2) default: solution = 0 } print(solution) return solution! } func ansFieldNormalState(){ textField.placeholder = "Answer" textField.textColor = UIColor.grayColor() } func changeAnswerLabel(ansLabel: UILabel){ if(answer == solution()){ ansLabel.text = "CORRECT" ansLabel.textColor = UIColor.greenColor() } else{ ansLabel.text = "INCORRECT" ansLabel.textColor = UIColor.redColor() } } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { // print("Current text = \(textField.text)") // print("Replacement text = \(string)") let existingTextHasDecimalPoint = textField.text! let replacementTextHasDecimalPoint = string.rangeOfString("0") if existingTextHasDecimalPoint.isEmpty && replacementTextHasDecimalPoint != nil && !(answer==0){ return false } return true } } <file_sep># TicTacToe iOS Project for TicTacToe Game <file_sep>// // TicTacToe.swift // TicTacToe // // Created by teacher on 8/22/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit class TicTacToeViewController: UIViewController { var game = TicTacToeBrain() override func viewDidLoad() { super.viewDidLoad() startNewGame() } @IBOutlet var buttons: [UIButton]! var winnerArray = [[0,0,1,0,1,0,1,0,0],[0,1,0,0,1,0,0,1,0],[1,0,0,1,0,0,1,0,0],[0,0,1,0,0,1,0,0,1],[0,0,0,0,0,0,1,1,1],[1,0,0,0,1,0,0,0,1],[1,1,1,0,0,0,0,0,0],[0,0,0,1,1,1,0,0,0]] var clickCount:Int! @IBAction func buttonPressed(button: UIButton) { for i in 0...8{ if(button.tag == buttons[i].tag && button.currentTitle == nil){ clickCount = clickCount+1 if(game.playerIdentity == 1 ){ button.setTitle("X", forState: .Normal) game.player1Array![i] = 1 if(clickCount >= 5){ if(game.winCondition(game.player1Array!)){ winnerTitleGreen(winnerArray[game.combination]) gameOverWithWinner(game.playerIdentity) } if(clickCount == 9){ gameOverWithWinner(nil) } } game.changeIdentity() } else if game.playerIdentity == 2 { button.setTitle("O", forState: .Normal) game.player2Array![i] = 1 if(clickCount >= 5){ if(game.winCondition(game.player2Array!)){ winnerTitleGreen(winnerArray[game.combination ]) gameOverWithWinner(game.playerIdentity) } if(clickCount == 9){ gameOverWithWinner(nil) } } game.changeIdentity() } } } } func winnerTitleGreen(board2: Array<Int>){ for i in 0...8 { if(board2[i] == 1){ buttons[i].setTitleColor(UIColor.greenColor(), forState: .Normal) } } } func gameOverWithWinner(playerID: Int?) { let title = "Game Over" var message = String() if let ID = playerID { message = "Player \(ID) wins" } else { message = "No Winner" } let ac = UIAlertController(title: title, message: message, preferredStyle: .ActionSheet) let newGameAction = UIAlertAction(title: "New Game", style: .Default , handler: { (action) -> Void in self.startNewGame() }) ac.addAction(newGameAction) presentViewController(ac, animated: true, completion: nil) } func startNewGame() { clickCount = 0 for i in 0...8 { buttons[i].setTitleColor(UIColor.redColor(), forState: UIControlState.Normal) buttons[i].backgroundColor = UIColor.grayColor() buttons[i].setTitle(nil, forState: .Normal) game.resetGame() } } } <file_sep>// // TicTacToe.swift // TicTacToe // // Created by teacher on 8/22/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit class TicTacToeBrain { var count: Int = 0 var combination:Int! var playerIdentity: Int = 1 var count1:Int = 0 var player1Array:Array<Int>? var player2Array:Array<Int>? var array1 = [0,0,1,0,1,0,1,0,0] var array2 = [0,1,0,0,1,0,0,1,0] var array3 = [1,0,0,1,0,0,1,0,0] var array4 = [0,0,1,0,0,1,0,0,1] var array5 = [0,0,0,0,0,0,1,1,1] var array6 = [1,0,0,0,1,0,0,0,1] var array7 = [1,1,1,0,0,0,0,0,0] var array8 = [0,0,0,1,1,1,0,0,0] func changeIdentity(){ if(playerIdentity == 1){ playerIdentity = 2 } else{ playerIdentity = 1 } } func winCondition(playerArray: Array<Int>) -> Bool { if(compare(playerArray, winCombination: array1)){ combination = 0 return true } else if(compare(playerArray, winCombination: array2)){ combination = 1 return true } else if(compare(playerArray, winCombination: array3)){ combination = 2 return true } else if(compare(playerArray, winCombination: array4)){ combination = 3 return true } else if(compare(playerArray, winCombination: array5)){ combination = 4 return true } else if(compare(playerArray, winCombination: array6)){ combination = 5 return true } else if(compare(playerArray, winCombination: array7)){ combination = 6 return true } else if(compare(playerArray, winCombination: array8)){ combination = 7 return true } else{ return false } } func compare(winningArray: Array<Int>, winCombination: Array<Int>) -> Bool{ count1 = 0 for i in 0...8{ if(winningArray[i] == winCombination[i] && winningArray[i] == 1){ count1 = count1+1 print("Count: \(count1)") if(count1 >= 3){ return true } } } return false } func resetGame() { playerIdentity = 1 player1Array=[0,0,0,0,0,0,0,0,0] player2Array=[0,0,0,0,0,0,0,0,0] } }
634fee41c13ecda1ca14bb7090b7c8558814e157
[ "Swift", "Markdown" ]
4
Swift
sphegde/TicTacToe
1f04a918f2b5deccb78797a82ed74d5375223b3b
acf194c60ab52a7923df6f4575413ba4a55416cb
refs/heads/master
<repo_name>BobChuang/RecyclerViewMoveToTop<file_sep>/app/src/main/java/com/example/recyclerviewtop/MainActivity.java package com.example.recyclerviewtop; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private LinearLayoutManager layoutManager; private RecyclerView recyclerView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = (RecyclerView) findViewById(R.id.recycler); layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); ArrayList<String> dataList = new ArrayList<>(); for (int i = 0; i < 30; i++) { dataList.add(i + "******" + i); } RecyclerAdapter adp = new RecyclerAdapter(this, dataList); adp.setOnRecyclerItemClickListener(new OnRecyclerItemClickListener() { @Override public void onItemClick(View view, int position) { smoothMoveToPosition(position); } }); recyclerView.setAdapter(adp); } /** * 滚动方法 */ private void smoothMoveToPosition(int position) { int firstPosition = layoutManager.findFirstVisibleItemPosition(); int lastPosition = layoutManager.findLastVisibleItemPosition(); if (position <= lastPosition) { int top = recyclerView.getChildAt(position - firstPosition).getTop(); recyclerView.smoothScrollBy(0, top); } } } <file_sep>/README.md # RecyclerViewMoveToTop 点击后的Item移动到屏幕的顶端(不是Item置顶)
2e2080bf9ecb41af797da14767108bc697d00b50
[ "Markdown", "Java" ]
2
Java
BobChuang/RecyclerViewMoveToTop
051714e7a94704a769db29f3b6e383870a0cfd58
e3667d0054f40748d26d75e9105ada5700079e44
refs/heads/master
<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="DashboardControllerFixture.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Web.Tests.WebAdmin { using System.Web.Mvc; using Firebrick.Admin.Web.Controllers; using Xunit; /// <summary> /// The dashboard controller fixture. /// </summary> public class DashboardControllerFixture { #region Public Methods /// <summary> /// The when default index method called_ valid view model returned. /// </summary> [Fact] public void WhenDefaultIndexMethodCalled_ValidViewModelReturned() { // ARRANGE // ACT var controller = new CmsDashboardController(); var viewResult = controller.Index() as ViewResult; // ASSERT Assert.NotNull(viewResult); Assert.Equal(string.Empty, viewResult.ViewName); Assert.True(viewResult.ViewData.ModelState.IsValid); Assert.True(controller.ModelState.IsValid); } #endregion } }<file_sep>namespace Firebrick.Web.UI.Controllers { using System.Web.Mvc; using System.Web.WebPages; public class ViewSwitcherController : BaseController { #region Public Methods public RedirectResult SwitchView(bool mobile, string returnUrl) { if (this.Request.Browser.IsMobileDevice == mobile) { this.HttpContext.ClearOverriddenBrowser(); } else { this.HttpContext.SetOverriddenBrowser(mobile ? BrowserOverride.Mobile : BrowserOverride.Desktop); } return this.Redirect(returnUrl); } #endregion } }<file_sep> 1. Name tables as singular not plural i.e. Page not Pages 2. All tables should have a Unique PK 3. Do NOT use composite keys, I may love them but ORMs generally don't 4. Name PKs as > PageId NOT Id 18/07/2012 1. It would be fair to assume (but always dangerous) that any data annotations added here would not be maximised > Use the Views man! NEW Entity ---------- 1. Firebrick.Model > Entity 2. Firebrick.Data.EF > Modify FirebrickContext > Add new DbSet (This may be plural < What the table is known at in SQL) 3. Firebrick.Data > Create new respoitory contract : Inherits IRespository<EntityType> 4. Firebrick.Data.EF > Create EF Repository Implementation : Inherits BaseRepository<EntityType> and implements Respository contract 5. Firebrick.Service > Create Service contract 6. Firebrick.Service > Create Service implementation 7. Web.Config > Add new Unity mappings for service and repository OR 8. Firebrick.UI.Core > UnityContainerFactory - Register new service and respository types Optional: x. Create Entity Initializer to load basic data into DB on codeFirst creation y. Firebrick.Data.EF > Migrations.Configuration > Add new entity initializer <file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="UserRoleInitializer.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.EF.Initializers { using System.Data.Entity.Migrations; using System.Data.Entity.Validation; using System.Diagnostics; using Firebrick.Model; /// <summary> /// The user role initializer. /// </summary> public static class UserRoleInitializer { #region Public Methods /// <summary> /// The Add. /// </summary> /// <param name="context"> /// The context. /// </param> public static void Add(FirebrickContext context) { var userRole1 = new UserRole { UserRoleId = 1, RoleId = 1, UserId = 1 }; var userRole2 = new UserRole { UserRoleId = 2, RoleId = 10, UserId = 1 }; var userRole3 = new UserRole { UserRoleId = 3, RoleId = 9, UserId = 2 }; var userRole4 = new UserRole { UserRoleId = 4, RoleId = 10, UserId = 2 }; context.UserRoles.AddOrUpdate(userRole1); context.UserRoles.AddOrUpdate(userRole2); context.UserRoles.AddOrUpdate(userRole3); context.UserRoles.AddOrUpdate(userRole4); try { context.SaveChanges(); } catch (DbEntityValidationException dbEx) { foreach (DbEntityValidationResult validationErrors in dbEx.EntityValidationErrors) { foreach (DbValidationError validationError in validationErrors.ValidationErrors) { Debug.WriteLine( "Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } } } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="SeoDecorator.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Model { using System; using System.ComponentModel.DataAnnotations; /// <summary> /// The seo info. /// </summary> public class SeoDecorator { #region Public Properties /// <summary> /// Gets or sets ChangeFrequency. /// </summary> public string ChangeFrequency { get; set; } /// <summary> /// Gets or sets CreatedDate. /// </summary> public DateTime CreatedDate { get; set; } /// <summary> /// Gets or sets Description. /// </summary> public string Description { get; set; } /// <summary> /// Gets or sets FileName. /// </summary> public string FileName { get; set; } /// <summary> /// Gets or sets Keywords. /// </summary> public string Keywords { get; set; } /// <summary> /// Gets or sets LastModified. /// </summary> public DateTime LastModified { get; set; } /// <summary> /// Gets or sets LinkType. /// </summary> public int LinkType { get; set; } /// <summary> /// Gets or sets LookFor. /// </summary> public string LookFor { get; set; } /// <summary> /// Gets or sets PageId. /// </summary> public int PageId { get; set; } /// <summary> /// Gets or sets PortalId. /// </summary> public int PortalId { get; set; } /// <summary> /// Gets or sets Priority. /// </summary> public string Priority { get; set; } /// <summary> /// Gets or sets a value indicating whether RobotsFollow. /// </summary> public bool RobotsFollow { get; set; } /// <summary> /// Gets or sets a value indicating whether RobotsIndex. /// </summary> public bool RobotsIndex { get; set; } /// <summary> /// Gets or sets SeoDecoratorId. /// </summary> [Key] public int SeoDecoratorId { get; set; } /// <summary> /// Gets or sets Title. /// </summary> public string Title { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="CmsPageManagerEditViewModel.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.ViewModels.WebAdmin.CmsPageManager { using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; using Firebrick.Domain.Helpers.Route; /// <summary> /// The cms page view model. /// </summary> public class CmsPageManagerEditViewModel : CmsPageManagerBaseViewModel { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="CmsPageManagerEditViewModel"/> class. /// </summary> public CmsPageManagerEditViewModel() { this.ActionIsSaveSuccessful = null; this.ActionIsDeleteSuccessful = null; } #endregion #region Public Properties /// <summary> /// Gets ActionCancel. /// </summary> public override string ActionCancelUrl { get { return WebAdmin.AdminPageList; } } public bool? ActionIsDeleteSuccessful { get; set; } public bool? ActionIsSaveSuccessful { get; set; } public IEnumerable<CmsPageManagerEditPartViewModel> ZoneFourSelectedParts { get; set; } public IEnumerable<CmsPageManagerEditPartViewModel> ZoneThreeSelectedParts { get; set; } public IEnumerable<CmsPageManagerEditPartViewModel> ZoneTwoSelectedParts { get; set; } public string LastModifiedBy { get; set; } public bool IsPublished { get; set; } public IEnumerable<SelectListItem> AvailablePartTypeList { get; set; } public int AvailablePartSelectedItem { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="EnginePartTypeMap.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Model { using System.ComponentModel.DataAnnotations; /// <summary> /// The engine part type map. /// </summary> public class EnginePartTypeMap { #region Public Properties /// <summary> /// Gets or sets EngineId. /// </summary> public int EngineId { get; set; } /// <summary> /// Gets or sets EnginePartTypeMapId. /// </summary> [Key] public int EnginePartTypeMapId { get; set; } /// <summary> /// Gets or sets PartTypeId. /// </summary> public int PartTypeId { get; set; } #endregion } }<file_sep>namespace Firebrick.Domain.ViewModels.WebAdmin.CmsPlugins { using System; using System.Collections.Generic; public class CmsPluginLoginUserViewModel { #region Constructors and Destructors public CmsPluginLoginUserViewModel() { this.UserRoles = new List<string>(); } #endregion #region Public Properties public string CreatedBy { get; set; } public DateTime? DateCreated { get; set; } public string EMail { get; set; } public string FirstName { get; set; } public string FullName { get; set; } public string JobTitle { get; set; } public int UserId { get; set; } public List<string> UserRoles { get; set; } #endregion } }<file_sep>namespace Firebrick.Service.Contracts { using Firebrick.Model; ///<summary> ///The i analytics type config ///</summary> public interface IAnalyticsTypeService : IService<AnalyticsType> { } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="UnityContainerFactory.cs" company="Beyond"> // Copyright Beyond 2012 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.UI.Core.UnityExtensions { using Firebrick.Data.EF.Repositories; using Firebrick.Data.RepositoryContracts; using Firebrick.Service.Contracts; using Firebrick.Service.Implementations; using Microsoft.Practices.Unity; using Microsoft.Practices.Unity.Configuration; /// <summary> /// The unity container factory. /// </summary> public class UnityContainerFactory { #region Public Methods /// <summary> /// The create configured container. /// </summary> /// <returns> /// The container /// </returns> public IUnityContainer CreateConfiguredContainer() { var container = new UnityContainer(); LoadConfigurationOverrides(container); return container; } #endregion #region Methods /// <summary> /// The load configuration overrides. /// </summary> /// <param name="container"> /// The container. /// </param> private static void LoadConfigurationOverrides(IUnityContainer container) { //// Repositories container.RegisterType<IPageControllerActionRepository, PageControllerActionRepository>(); container.RegisterType<IPartContainerRepository, PartContainerRepository>(); container.RegisterType<IClientAssetConfigRepository, ClientAssetConfigRepository>(); container.RegisterType<IClientAssetTypeRepository, ClientAssetTypeRepository>(); container.RegisterType<IClientAssetRepository, ClientAssetRepository>(); container.RegisterType<IEnquiryRepository, EnquiryRepository>(); container.RegisterType<ISeoDecoratorRepository, SeoDecoratorRepository>(); container.RegisterType<IUserRepository, UserRepository>(); container.RegisterType<IPageRepository, PageRepository>(); container.RegisterType<IPageTemplateRepository, PageTemplateRepository>(); container.RegisterType<IPageTemplateZoneMapRepository, PageTemplateZoneMapRepository>(); container.RegisterType<IPageZoneRepository, PageZoneRepository>(); container.RegisterType<IPartRepository, PartRepository>(); container.RegisterType<IPartTypeRepository, PartTypeRepository>(); container.RegisterType<IPortalRepository, PortalRepository>(); container.RegisterType<IContentBlobRepository, ContentBlobRepository>(); container.RegisterType<IDomainRepository, DomainRepository>(); container.RegisterType<IRoleRespository, RoleRepository>(); container.RegisterType<IUserRolesRepository, UserRolesRepository>(); container.RegisterType<IRolePageRestrictionRepository, RolePageRestrictionRepository>(); container.RegisterType<IRolePartRestrictionRepository, RolePartRestrictionRepository>(); container.RegisterType<INotificationTypeRepository, NotificationTypeRepository>(); container.RegisterType<INotificationRepository, NotificationRepository>(); container.RegisterType<IAnalyticsTypeRepository, AnalyticsTypeRepository>(); container.RegisterType<IAnalyticsAccountRepository, AnalyticsAccountRepository>(); container.RegisterType<ISeoRouteValueRepository, SeoRouteValueRepository>(); //// Services container.RegisterType<IPageControllerActionService, PageControllerActionService>(); container.RegisterType<IPartContainerService, PartContainerService>(); container.RegisterType<IClientAssetConfigService, ClientAssetConfigService>(); container.RegisterType<IClientAssetService, ClientAssetService>(); container.RegisterType<IClientAssetTypeService, ClientAssetTypeService>(); container.RegisterType<IEnquiryService, EnquiryService>(); container.RegisterType<ISeoDecoratorService, SeoDecoratorService>(); container.RegisterType<IUserService, UserService>(); container.RegisterType<IPageService, PageService>(); container.RegisterType<IPageTemplateService, PageTemplateService>(); container.RegisterType<IPageTemplateZoneMapService, PageTemplateZoneMapService>(); container.RegisterType<IPageZoneService, PageZoneService>(); container.RegisterType<IPartService, PartService>(); container.RegisterType<IPartTypeService, PartTypeService>(); container.RegisterType<IPortalService, PortalService>(); container.RegisterType<IContentBlobService, ContentBlobService>(); container.RegisterType<IDomainService, DomainService>(); container.RegisterType<IRoleService, RoleService>(); container.RegisterType<IUserRolesService, UserRolesService>(); container.RegisterType<IRolePageRestrictionService, RolePageRestrictionService>(); container.RegisterType<IRolePartRestrictionService, RolePartRestrictionService>(); container.RegisterType<INotificationTypeService, NotificationTypeService>(); container.RegisterType<INotificationService, NotificationService>(); container.RegisterType<IAnalyticsTypeService, AnalyticsTypeService>(); container.RegisterType<IAnalyticsAccountService, AnalyticsAccountService>(); container.RegisterType<ISeoRouteValueService, SeoRouteValueService>(); //// XML Web.config container.LoadConfiguration("container"); } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="SeoDecoratorService.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Service.Implementations { using Firebrick.Data; using Firebrick.Data.RepositoryContracts; using Firebrick.Model; using Firebrick.Service.Contracts; /// <summary> /// The seo info service. /// </summary> public class SeoDecoratorService : BaseService<SeoDecorator>, ISeoDecoratorService { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="SeoDecoratorService"/> class. /// </summary> /// <param name="seoDecoratorRepository"> /// The user repository. /// </param> /// <param name="unitOfWork"> /// The unit of work. /// </param> public SeoDecoratorService(ISeoDecoratorRepository seoDecoratorRepository, IUnitOfWork unitOfWork) { this.Repository = seoDecoratorRepository; this.UnitOfWork = unitOfWork; } #endregion #region Public Methods /// <summary> /// Gets seoInfo based on look for /// </summary> /// <param name="lookFor"> /// The look for. /// </param> /// <returns> /// Returns page based on url /// </returns> public SeoDecorator GetByLookFor(string lookFor) { return this.Repository.Get(seo => seo.LookFor.ToLower() == lookFor.ToLower()); } public SeoDecorator GetByPage(int pageId) { return this.Repository.Get(seo => seo.PageId == pageId); } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PartTypeInitializer.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.EF.Initializers { using System.Data.Entity.Migrations; using System.Data.Entity.Validation; using System.Diagnostics; using Firebrick.Model; /// <summary> /// The part type initializer. /// </summary> public static class PartTypeInitializer { #region Public Methods /// <summary> /// The Add. /// </summary> /// <param name="context"> /// The context. /// </param> public static void Add(FirebrickContext context) { //// REAL PARTS context.PartTypes.AddOrUpdate( new PartType { PartTypeId = 1, Action = "Index", Controller = "RichContent", Title = "HTML Content", ViewIdentifier = string.Empty, AddAction = "Add", EditAction = "EditMode" }); context.PartTypes.AddOrUpdate( new PartType { PartTypeId = 2, Action = "SideMenu", Controller = "Menu", Title = "Side Menu", ViewIdentifier = string.Empty, AddAction = string.Empty, EditAction = string.Empty }); context.PartTypes.AddOrUpdate( new PartType { PartTypeId = 3, Action = "ContactUs", Controller = "Enquiry", Title = "Contact Us", ViewIdentifier = string.Empty, AddAction = string.Empty, EditAction = "ContactUs" }); context.PartTypes.AddOrUpdate( new PartType { PartTypeId = 4, Action = "Index", Controller = "FlexSlider", Title = "Flex Banner Slider", ViewIdentifier = string.Empty, AddAction = "Index", EditAction = "Index", AdminEditController = "FlexSliderAdmin", AdminEditAction = "AdminEditMode" }); try { context.SaveChanges(); } catch (DbEntityValidationException dbEx) { foreach (DbEntityValidationResult validationErrors in dbEx.EntityValidationErrors) { foreach (DbValidationError validationError in validationErrors.ValidationErrors) { Debug.WriteLine( "Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } } } #endregion } }<file_sep>namespace Firebrick.Data.EF.Initializers { using System.Data.Entity.Migrations; using System.Data.Entity.Validation; using System.Diagnostics; using Firebrick.Model; public static class RoleRestrictionsInitializer { #region Public Methods public static void Add(FirebrickContext context) { // Pages context.RolePageRestrictions.AddOrUpdate( new RolePageRestriction { RolePageRestrictionId = 1, PageId = 2, RoleId = 1, IsEditable = false, IsViewable = true }); context.RolePageRestrictions.AddOrUpdate( new RolePageRestriction { RolePageRestrictionId = 2, PageId = 2, RoleId = 9, IsEditable = false, IsViewable = true }); try { context.SaveChanges(); } catch (DbEntityValidationException dbEx) { foreach (DbEntityValidationResult validationErrors in dbEx.EntityValidationErrors) { foreach (DbValidationError validationError in validationErrors.ValidationErrors) { Debug.WriteLine( "Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } } } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PageControllerAction.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Model { using System.ComponentModel.DataAnnotations; /// <summary> /// The page controller action. /// </summary> public class PageControllerAction { #region Public Properties /// <summary> /// Gets or sets ActionName. /// </summary> public string ActionName { get; set; } /// <summary> /// Gets or sets ControllerName. /// </summary> public string ControllerName { get; set; } /// <summary> /// Gets or sets FriendlyName. /// </summary> public string FriendlyName { get; set; } /// <summary> /// Gets or sets IsSelectable. /// </summary> public bool IsSelectable { get; set; } /// <summary> /// Gets or sets PageControllerActionId. /// </summary> [Key] public int PageControllerActionId { get; set; } #endregion } }<file_sep>using System; namespace Firebrick.Domain.ViewModels.WebAdmin.CmsPlugins { public class CmsPluginAdditionalInfoViewModel { public DateTime MemberSince { get; set; } public int NumEnquiries { get; set; } public string FirebrickVersion { get; set; } } } <file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="DefaultModelHelper.cs" company=""> // // </copyright> // <summary> // The default model helper. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Test.Helper { using Firebrick.Model; /// <summary> /// The default model helper. /// </summary> public static class DefaultModelHelper { #region Public Methods /// <summary> /// The dummy populated content blob. /// </summary> /// <returns> /// </returns> public static ContentBlob DummyPopulatedContentBlob() { return new ContentBlob { ContentBlobId = 1, PartId = 1, Html = "Html" }; } /// <summary> /// The dummy populated domain. /// </summary> /// <returns> /// </returns> public static Domain DummyPopulatedDomain() { return new Domain { DomainId = 1, HostHeader = "HostHeader", PortalId = 1 }; } public static PageControllerAction DummyPageControllerAction() { return new PageControllerAction { PageControllerActionId = 1, ActionName = "ActionName", ControllerName = "ControllerName", FriendlyName = "FriendlyName", IsSelectable = true }; } /// <summary> /// The dummy populated page. /// </summary> /// <returns> /// </returns> public static Page DummyPopulatedPage() { return new Page { PageId = 1, PortalId = 1, ActionName = "ActionName", ControllerName = "ControllerName", PageParentId = 0, Title = "Title" }; } public static PageTemplate DummyPopulatedPageTemplate() { return new PageTemplate { PageTemplateId = 1, Title = "Title", LayoutTemplateSrc = "LayoutTemplateSrc" }; } /// <summary> /// The dummy populated page template zone map. /// </summary> /// <returns> /// </returns> public static PageTemplateZoneMap DummyPopulatedPageTemplateZoneMap() { return new PageTemplateZoneMap { PageTemplateId = 1, PageTemplateZoneMapId = 1, PageZoneId = 1 }; } public static PageZone DummyPopulatedPageZone() { return new PageZone { PageZoneId = 1, Title = "Title" }; } /// <summary> /// The dummy populated part. /// </summary> /// <returns> /// </returns> public static Part DummyPopulatedPart() { return new Part { PartId = 1, PageId = 1, PartTypeId = 1, Title = "Title", ZoneId = 1 }; } /// <summary> /// The dummy populated part type. /// </summary> /// <returns> /// </returns> public static PartType DummyPopulatedPartType() { return new PartType { PartTypeId = 1, Action = "Index", AddAction = "Add", AdminEditAction = "AdminEdit", AdminEditController = "AdminEditController", Controller = "Controller", Title = "Title" }; } /// <summary> /// The dummy populated portal. /// </summary> /// <returns> /// </returns> public static Portal DummyPopulatedPortal() { return new Portal { PortalId = 1, ParentPortalId = 0, PrimaryDomainId = 1, PrimaryMobileDomainId = 2, Title = "Title" }; } /// <summary> /// The dummy populated seo decorator. /// </summary> /// <returns> /// </returns> public static SeoDecorator DummyPopulatedSeoDecorator() { return new SeoDecorator { SeoDecoratorId = 1, PageId = 2, PortalId = 1, Description = "Description", LookFor = "LookFor", Title = "Title" }; } public static User DummyPopulatedUser() { return new User { UserId = 1, DisplayName = "DisplayName", EMail = "EMail", UserName = "UserName", PortalId = 1, IsActive = true }; } #endregion } }<file_sep>namespace Firebrick.Data.RepositoryContracts { using Firebrick.Model; public interface INotificationTypeRepository : IRepository<NotificationType> { } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PageTemplate.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Model { using System.ComponentModel.DataAnnotations; /// <summary> /// The web page template. /// </summary> public class PageTemplate { #region Public Properties /// <summary> /// Gets or sets LayoutTemplateSrc. /// </summary> public string LayoutTemplateSrc { get; set; } /// <summary> /// Gets or sets Id. /// </summary> [Key] public int PageTemplateId { get; set; } /// <summary> /// Gets or sets Title. /// </summary> public string Title { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ClientAsset.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Model { using System.ComponentModel.DataAnnotations; /// <summary> /// The client asset. /// </summary> public class ClientAsset { #region Public Properties /// <summary> /// Gets or sets ClientAssetId. /// </summary> [Key] public int ClientAssetId { get; set; } /// <summary> /// Gets or sets ClientAssetTypeId. /// </summary> public int ClientAssetTypeId { get; set; } /// <summary> /// Gets or sets RelativeFilePath. /// </summary> public string RelativeFilePath { get; set; } /// <summary> /// Gets or sets Title. /// </summary> public string Title { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="RichContentServiceBinder.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.ServiceBinders.ContentManagement { using System; using AutoMapper; using Firebrick.Domain.ViewModels.ContentManagement.RichContent; using Firebrick.Model; using Firebrick.Service.Contracts; /// <summary> /// The rich content service binder. /// </summary> public class RichContentServiceBinder { #region Constants and Fields /// <summary> /// The content blob service. /// </summary> private readonly IContentBlobService contentBlobService; #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="RichContentServiceBinder"/> class. /// </summary> /// <param name="contentBlobService"> /// The content blob service. /// </param> public RichContentServiceBinder(IContentBlobService contentBlobService) { this.contentBlobService = contentBlobService; } #endregion #region Public Methods /// <summary> /// The add. /// </summary> /// <param name="viewModel"> /// The view model. /// </param> /// <returns> /// The add /// </returns> public bool Add(RichContentAddViewModel viewModel) { return true; } /// <summary> /// The edit view model bind. /// </summary> /// <param name="pageId"> /// The id. /// </param> /// <param name="partId"> /// The part Id. /// </param> /// <param name="zoneId"> /// The zone Id. /// </param> /// <returns> /// edit view model /// </returns> public RichContentEditViewModel EditViewModelBind(string pageId, string partId, string zoneId) { var viewModel = new RichContentEditViewModel(); var contentBlob = this.contentBlobService.GetByPartId(Convert.ToInt32(partId)); if (contentBlob != null) { Mapper.CreateMap<ContentBlob, RichContentEditViewModel>(); Mapper.Map(contentBlob, viewModel); } else { viewModel.ContentBlobId = -1; viewModel.Html = string.Empty; viewModel.PartId = Convert.ToInt32(partId); } return viewModel; } public RichContentEditViewModel EditViewModelUpdate(string partId, RichContentEditViewModel viewModel) { ContentBlob contentBlob = this.contentBlobService.GetByPartId(Convert.ToInt32(partId)); Mapper.CreateMap<RichContentEditViewModel, ContentBlob>(); Mapper.Map(viewModel, contentBlob); this.contentBlobService.Update(contentBlob); return viewModel; } public RichContentEditViewModel EditViewModelAdd(string partId, RichContentEditViewModel viewModel) { ContentBlob contentBlob = new ContentBlob(); contentBlob.Html = viewModel.Html; contentBlob.PartId = Convert.ToInt32(partId); this.contentBlobService.Add(contentBlob); viewModel.ContentBlobId = contentBlob.ContentBlobId; return viewModel; } public RichContentIndexViewModel IndexViewModelBind(string pageId, string partId, string zoneId) { var viewModel = new RichContentIndexViewModel(); ContentBlob contentBlob = this.contentBlobService.GetByPartId(Convert.ToInt32(partId)); Mapper.CreateMap<ContentBlob, RichContentIndexViewModel>(); Mapper.Map(contentBlob, viewModel); return viewModel; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="UserServiceFixture.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Services.Tests { using Firebrick.Data; using Firebrick.Data.RepositoryContracts; using Firebrick.Framework.Exceptions; using Firebrick.Model; using Firebrick.Service.Implementations; using Moq; using Xunit; // NEED TO VERIFY WE ARE HANDLING PROBLEMS HERE MORE THAN UPDATING/ADDING ENTITIES IN THE REPOSITORY // ARE THE CORRECT EXCEPTIONS BEING THROWN AND PASSED BACK FOR EXAMPLE... /// <summary> /// The user service fixture. /// </summary> public class UserServiceFixture { #region Public Methods /// <summary> /// The when assigning user role with null token_ then throws argument null exception. /// </summary> [Fact] public void WhenAssigningUserRoleWithNullToken_ThenThrowsBusinessServicesException() { var services = new UserService(new Mock<IUserRepository>().Object, new Mock<IUnitOfWork>().Object); Assert.Throws<BusinessServicesException>(() => services.AssignRole(null, null)); } /// <summary> /// The when creating user_ then returns updated user with user id. /// </summary> [Fact] public void WhenCreatingUser_ThenReturnsUpdatedUserWithUserId() { var userRepositoryMock = new Mock<IUserRepository>(); userRepositoryMock.Setup(u => u.Add(It.IsAny<User>())).Callback<User>(user => user.UserId = 12); var services = new UserService(userRepositoryMock.Object, new Mock<IUnitOfWork>().Object); var servicesUser = new User { DisplayName = "test", Password = "<PASSWORD>" }; Assert.Equal(0, servicesUser.UserId); User createdUser = services.Create(servicesUser); Assert.Equal(12, createdUser.UserId); } /// <summary> /// The when getting user_ then returns user. /// </summary> [Fact] public void WhenGettingUser_ThenReturnsCorrectUser() { var userRepositoryMock = new Mock<IUserRepository>(); var dataUser = new User { UserId = 1, DisplayName = "test", Password = "<PASSWORD>" }; userRepositoryMock.Setup(repo => repo.GetById(It.IsAny<int>())).Returns(dataUser); var services = new UserService(userRepositoryMock.Object, new Mock<IUnitOfWork>().Object); User returnedUser = services.GetById(0); Assert.NotNull(returnedUser); Assert.Equal("test", returnedUser.DisplayName); } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="UserService.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Service.Implementations { using System; using System.Collections.Generic; using System.Web.Security; using Firebrick.Data; using Firebrick.Data.RepositoryContracts; using Firebrick.Framework.Exceptions; using Firebrick.Model; using Firebrick.Service.Contracts; /// <summary> /// The user service. /// </summary> public class UserService : BaseService<User>, IUserService { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="UserService"/> class. /// </summary> /// <param name="userRepository"> /// The user repository. /// </param> /// <param name="unitOfWork"> /// The unit of work. /// </param> public UserService(IUserRepository userRepository, IUnitOfWork unitOfWork) { this.Repository = userRepository; this.UnitOfWork = unitOfWork; } #endregion #region Public Methods /// <summary> /// The assign role. /// </summary> /// <param name="userName"> /// The user name. /// </param> /// <param name="roleName"> /// The role name. /// </param> /// <exception cref="NotImplementedException"> /// </exception> public void AssignRole(string userName, List<string> roleName) { throw new BusinessServicesException(); } /// <summary> /// </summary> /// <param name="userName"> /// The user name. /// </param> /// <param name="password"> /// The password. /// </param> /// <returns> /// </returns> public bool AuthenticatedUser(string userName, string password) { User myUser = this.Repository.Get(user => user.UserName.ToLower() == userName.ToLower()); //string hash = this.HashedPassword(myUser.Password); if (myUser != null) { if (myUser.Password == this.HashedPassword(password)) { return true; } } return false; } public User GetByUsername(string userName) { return this.Repository.Get(user => user.UserName.ToLower() == userName.ToLower()); } /// <summary> /// The special get users. /// </summary> /// <returns> /// </returns> /// <exception cref="NotImplementedException"> /// </exception> public IEnumerable<User> SpecialGetUsers() { throw new NotImplementedException(); } #endregion #region Methods private string HashedPassword(string password) { return FormsAuthentication.HashPasswordForStoringInConfigFile(password, "<PASSWORD>"); } #endregion } }<file_sep>namespace Firebrick.Admin.Web.Controllers { using System; using System.Text; using System.Web.Mvc; using Firebrick.Domain.ServiceBinders.WebAdmin; using Firebrick.Domain.ViewModels.WebAdmin.CmsPlugins; using Firebrick.Service.Contracts; using Firebrick.UI.Core.Controllers; public class CmsPluginsController : BaseAdminController { #region Constants and Fields private readonly IEnquiryService enquiryService; private readonly IUserService userService; private readonly IRoleService roleService; private readonly IUserRolesService userRolesService; #endregion public CmsPluginsController(IUserService userService, IRoleService roleService, IUserRolesService userRolesService, IEnquiryService enquiryService) { this.userService = userService; this.roleService = roleService; this.userRolesService = userRolesService; this.enquiryService = enquiryService; } #region Public Methods [ChildActionOnly] public ActionResult AdditionalInfo() { var viewModel = new CmsPluginAdditionalInfoViewModel(); try { CmsPluginServiceBinder modelBinder = this.GetServiceBinder(); viewModel = modelBinder.AdditionalInfoBind(User.Identity.Name); } catch (Exception ex) { this.LoggingService.Log(ex.Message); } return this.PartialView(viewModel); } [ChildActionOnly] public ActionResult AdditionalInfoPage(string id) { return this.PartialView(); } [ChildActionOnly] public ActionResult LoginUser() { var viewModel = new CmsPluginLoginUserViewModel(); try { CmsPluginServiceBinder modelBinder = this.GetServiceBinder(); viewModel = modelBinder.LoginUserViewModelBind(User.Identity.Name); } catch (Exception ex) { this.LoggingService.Log(ex.Message); } return this.PartialView(viewModel); } [ChildActionOnly] public ActionResult MainSideMenu() { //// TODO: [RP] [16052013] What role is this logged-in user in? Lets pass this to the service and generate the menu accoridinly var viewModel = new CmsPluginMainSideMenuViewModel(); try { //var currentUrl = this.Request.Url; CmsPluginServiceBinder modelBinder = this.GetServiceBinder(); viewModel = modelBinder.MainSideMenuBind(this.CurrentUrl()); } catch (Exception ex) { this.LoggingService.Log(ex.Message); } return this.PartialView(viewModel); } #endregion #region Methods private string CurrentUrl() { StringBuilder sb = new StringBuilder(); var index = 0; foreach (var segment in Request.Url.Segments) { if (index < 3) { sb.Append(segment); } index++; } return sb.ToString(); } /// <summary> /// The get service binder. /// </summary> /// <returns> /// </returns> private CmsPluginServiceBinder GetServiceBinder() { return new CmsPluginServiceBinder(this.userService, this.roleService, this.userRolesService, this.enquiryService); } #endregion } }<file_sep>namespace Firebrick.Admin.Web.Controllers { using System; using System.Web.Mvc; using Firebrick.Domain.ServiceBinders.WebAdmin; using Firebrick.Domain.ViewModels.WebAdmin.CmsMenuManager; using Firebrick.Domain.ViewModels.WebAdmin.CmsUserManager; using Firebrick.Service.Contracts; using Firebrick.UI.Core.Controllers; public class CmsUserManagerController : BaseAdminController { #region Constants and Fields /// <summary> /// The page service. /// </summary> private readonly IUserService userService; private readonly IRoleService roleService; private readonly IUserRolesService userRolesService; #endregion #region Constructors and Destructors public CmsUserManagerController(IUserService userService, IRoleService roleService, IUserRolesService userRolesService) { this.userService = userService; this.roleService = roleService; this.userRolesService = userRolesService; } #endregion #region Public Methods public ActionResult Add(string id) { CmsUserManagerServiceBinder modelBinder = this.GetServiceBinder(); CmsUserManagerAddViewModel viewModel = modelBinder.AddViewModelBind(Convert.ToInt32(id)); return this.View(viewModel); } [HttpPost] public ActionResult Add(CmsUserManagerAddViewModel viewModel) { CmsUserManagerServiceBinder modelBinder = this.GetServiceBinder(); if (this.ModelState.IsValid) { viewModel = modelBinder.AddViewModelInsert(viewModel); } return this.View(viewModel); } public ActionResult Edit(string id) { CmsUserManagerEditViewModel viewModel = null; try { CmsUserManagerServiceBinder modelBinder = this.GetServiceBinder(); viewModel = modelBinder.EditViewModelBind(Convert.ToInt32(id)); } catch (Exception ex) { this.LoggingService.Log(ex.Message); } return this.View(viewModel); } [HttpPost] public ActionResult Edit(string cancel, string delete, string save, CmsUserManagerEditViewModel viewModel) { CmsUserManagerServiceBinder modelBinder = this.GetServiceBinder(); if (this.ModelState.IsValid) { if (save != null) { viewModel = modelBinder.EditViewModelUpdate(viewModel); } if (delete != null) { } } else { //// Okay there has been an error as the ModelState is inValid, chances are they have not completed the form all in //// however, we may now also be missing other data such as select lists viewModel = modelBinder.EditViewModelStateInValid(viewModel); this.ModelState.AddModelError("Update Error", "Failed to submit. Correct any errors"); } return View(viewModel); } public ActionResult Index() { CmsUserManagerIndexViewModel viewModel = null; try { CmsUserManagerServiceBinder modelBinder = this.GetServiceBinder(); viewModel = modelBinder.IndexViewModelBind(); } catch (Exception ex) { this.LoggingService.Log(ex.Message); } return this.View(viewModel); } #endregion #region Methods /// <summary> /// The get service binder. /// </summary> /// <returns> /// </returns> private CmsUserManagerServiceBinder GetServiceBinder() { return new CmsUserManagerServiceBinder(this.userService, this.roleService, this.userRolesService); } #endregion } }<file_sep>namespace Firebrick.Domain.ServiceBinders.WebAdmin { using AutoMapper; using Firebrick.Domain.ViewModels.WebAdmin.CmsPortalManager; using Firebrick.Model; using Firebrick.Service.Contracts; public class CmsPortalManagerServiceBinder { #region Constants and Fields /// <summary> /// The part service. /// </summary> private readonly IAnalyticsAccountService analyticsAccountService; /// <summary> /// The page template service /// </summary> private readonly IDomainService domainService; /// <summary> /// The page service. /// </summary> private readonly IPortalService portalService; #endregion #region Constructors and Destructors public CmsPortalManagerServiceBinder( IPortalService portalService, IDomainService domainService, IAnalyticsAccountService analyticsAccountService) { this.portalService = portalService; this.domainService = domainService; this.analyticsAccountService = analyticsAccountService; } #endregion #region Public Methods public CmsPortalManagerSimpleSettingsViewModel SimpleSettingsViewModelBind() { var viewModel = new CmsPortalManagerSimpleSettingsViewModel(); Portal portal = this.portalService.GetById(1); Domain domain = this.domainService.GetById(1); AnalyticsAccount analytics = this.analyticsAccountService.GetById(1); Mapper.CreateMap<Portal, CmsPortalManagerSimpleSettingsViewModel>(); Mapper.Map(portal, viewModel); Mapper.CreateMap<Domain, CmsPortalManagerSimpleSettingsViewModel>(); Mapper.Map(domain, viewModel); Mapper.CreateMap<AnalyticsAccount, CmsPortalManagerSimpleSettingsViewModel>(); Mapper.Map(analytics, viewModel); return viewModel; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PartSetting.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Model { using System.ComponentModel.DataAnnotations; /// <summary> /// The part setting. /// </summary> public class PartSetting { #region Public Properties /// <summary> /// Gets or sets PartId. /// </summary> public int PartId { get; set; } /// <summary> /// Gets or sets PartSettingId. /// </summary> [Key] public int PartSettingId { get; set; } /// <summary> /// Gets or sets SettingIdentifier. /// </summary> public string SettingIdentifier { get; set; } /// <summary> /// Gets or sets SettingValue. /// </summary> public string SettingValue { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="MainMenuViewModel.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.ViewModels { using System.Collections.Generic; /// <summary> /// The main menu view model. /// </summary> public class SideMenuViewModel { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="MainMenuViewModel"/> class. /// </summary> public SideMenuViewModel() { this.MenuList = new List<IMenuItemViewModel>(); } #endregion #region Public Properties /// <summary> /// Gets or sets MenuList. /// </summary> public IList<IMenuItemViewModel> MenuList { get; set; } #endregion } }<file_sep>namespace Firebrick.UI.Core.Filters { using System; using System.Collections.Generic; using System.Web.Mvc; using System.Web.Security; using System.Linq; using Firebrick.UI.Core.Security; public class ValidateWebsiteUserRoles : FilterAttribute, IAuthorizationFilter { #region Public Methods /* * WHEN VIEWING PAGES FROM THE WEBSITE (Not FIREBRICK CMS ADMIN) APPLY THIS LOGIC * * 1. Is the user authenticated? No - Just a plain old visitor * Yes - A visitor and at least most likely a Registered user for example, maybe also a Publisher etc. * 2. If the controller is WebFramework, then check Page Role restrictions > ALWAYS TRUE AS [ValidateWebsiteUserRoles] only applied on this controller * If none exist > show the page, no questions asked * If some do exists > check if the user is first authenticated > if they are not > AUTHORISATION DENIED * If they are authenticated, check the roles they are in > If valid, show page * Otherwise > AUTHORISATION DENIES */ public void OnAuthorization(AuthorizationContext filterContext) { bool isAuthorised = true; try { IEnumerable<int> pageRoleRestrictions; var pageId = filterContext.RouteData.Values["id"]; if (pageId != null) { pageRoleRestrictions = CmsSecurityProvider.GetPageRoleRestrictions(Convert.ToInt32(pageId)); var pageRoles = pageRoleRestrictions.Count(); if (pageRoles > 0) { isAuthorised = ValidateUserPageAuthorisation(filterContext, pageRoleRestrictions); } } } catch { ShowSecurityError(ref filterContext); } if (!isAuthorised) { ShowSecurityError(ref filterContext); } } #endregion #region Methods private bool ValidateUserPageAuthorisation(AuthorizationContext filterContext, IEnumerable<int> pageRoleRestrictions) { bool isAuthorised = false; if (filterContext.HttpContext.Request.IsAuthenticated) { // Now check user roles against page roles and if they MATCH string[] userRoles = Roles.GetRolesForUser(filterContext.RequestContext.HttpContext.User.Identity.Name); foreach(var restrictedRole in pageRoleRestrictions) { if (userRoles.Any(ur => int.Parse(ur).Equals(restrictedRole))) { isAuthorised = true; } } } return isAuthorised; } private static void ShowSecurityError(ref AuthorizationContext filterContext) { var viewResult = new ViewResult { ViewName = "SecurityError" }; viewResult.ViewBag.ErrorMessage = "You are not authorized to use this page. Please contact an administrator!"; filterContext.Result = viewResult; } #endregion } }<file_sep>namespace Firebrick.Domain.SEO { public static class CmsUrl { #region Public Methods public static string BuildLookFor(string pageTitle, string parentLookFor) { var parentFolder = string.Empty; if (parentLookFor != string.Empty) { parentFolder = string.Format("{0}/", TrimParentFolder(parentLookFor)); } string lookFor = string.Format("{0}{1}", parentFolder, StripForiegnChars(pageTitle)); return lookFor; } #endregion #region Methods private static string StripForiegnChars(string dirtyTitle) { var cleanTitle = dirtyTitle; cleanTitle = cleanTitle.Replace(" ", "-"); return cleanTitle; } private static string TrimParentFolder(string dirtyFolder) { var cleanFolder = dirtyFolder; cleanFolder = cleanFolder.Replace(".aspx", string.Empty); return cleanFolder; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="MenuServiceBinder.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.ServiceBinders { using System; using System.Collections.Generic; using Firebrick.Domain.ViewModels; using Firebrick.Model; using Firebrick.Service.Contracts; /// <summary> /// The main menu service binder. /// </summary> public class MenuServiceBinder { #region Constants and Fields /// <summary> /// The page service. /// </summary> private readonly IPageService pageService; private readonly ISeoDecoratorService seoDecoratorService; #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="MenuServiceBinder"/> class. /// </summary> /// <param name="pageService"> /// The page service. /// </param> public MenuServiceBinder(IPageService pageService, ISeoDecoratorService seoDecoratorService) { this.pageService = pageService; this.seoDecoratorService = seoDecoratorService; } #endregion #region Public Methods /// <summary> /// Binds PageViewModel /// </summary> /// <param name="parentPageId"> /// The page id. /// </param> /// <returns> /// Returns Page View Model /// </returns> public MainMenuViewModel BindModel(int parentPageId) { var viewModel = new MainMenuViewModel(); IList<SeoDecorator> seoDecorators = new List<SeoDecorator>(); IEnumerable<Page> pages = this.pageService.GetMany(p => p.PageParentId == parentPageId); foreach (Page page in pages) { Page seoPage = page; // Avoid access to modified seoDecorators.Add( this.seoDecoratorService.Get( s => s.PageId == seoPage.PageId && seoPage.ShowOnMenu && seoPage.IsPublished)); } foreach (SeoDecorator seo in seoDecorators) { if (seo != null) { viewModel.MenuList.Add( new MenuItemViewModel { Id = seo.PageId, FriendlyUrl = seo.LookFor, HelperText = seo.Title, Title = seo.Title }); } } return viewModel; } /// <summary> /// Binds SideMenuViewModel /// </summary> /// <param name="pageId"> /// The page id. /// </param> /// <returns> /// Returns Page View Model /// </returns> public SideMenuViewModel SideMenuBindModel(string pageId) { int parentPageId = -1; if (pageId != null) { parentPageId = Convert.ToInt32(pageId); } var viewModel = new SideMenuViewModel(); IList<SeoDecorator> seoDecorators = new List<SeoDecorator>(); IEnumerable<Page> pages = this.pageService.GetMany(p => p.PageParentId == parentPageId); foreach (Page page in pages) { Page seoPage = page; // Avoid access to modified seoDecorators.Add( this.seoDecoratorService.Get( s => s.PageId == seoPage.PageId && seoPage.ShowOnMenu && seoPage.IsPublished)); } foreach (SeoDecorator seo in seoDecorators) { if (seo != null) { viewModel.MenuList.Add( new MenuItemViewModel { Id = seo.PageId, FriendlyUrl = seo.LookFor, HelperText = seo.Title, Title = seo.Title }); } } return viewModel; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IPageZoneService.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Service.Contracts { using Firebrick.Model; /// <summary> /// The i web page zone service. /// </summary> public interface IPageZoneService : IService<PageZone> { } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="SeoDecoratorRepository.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.EF.Repositories { using Firebrick.Data.RepositoryContracts; using Firebrick.Model; /// <summary> /// The seo info repository. /// </summary> public class SeoDecoratorRepository : BaseRepository<SeoDecorator>, ISeoDecoratorRepository { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="SeoDecoratorRepository"/> class. /// </summary> /// <param name="databaseFactory"> /// The database factory. /// </param> public SeoDecoratorRepository(IDatabaseFactory databaseFactory) : base(databaseFactory) { } #endregion } }<file_sep>namespace Firebrick.Domain.ViewModels.WebAdmin.CmsPortalManager { using Firebrick.Domain.Helpers.Route; public class CmsPortalManagerSimpleSettingsViewModel : CmsPortalManagerBaseViewModel { #region Constructors and Destructors public CmsPortalManagerSimpleSettingsViewModel() { this.ActionIsSaveSuccessful = null; this.ActionIsDeleteSuccessful = null; } #endregion #region Public Properties public override string ActionCancelUrl { get { return WebAdmin.AdminDashboard; } } /// <summary> /// Gets or sets ActionIsDeleteSuccessful. /// </summary> public bool? ActionIsDeleteSuccessful { get; set; } /// <summary> /// Gets or sets a value indicating whether ActionIsSaveSuccessful. /// </summary> public bool? ActionIsSaveSuccessful { get; set; } public int AnalytcisAccountId { get; set; } public int DomainId { get; set; } /// <summary> /// Gets or sets HostHeader. /// </summary> public string HostHeader { get; set; } ///<summary> ///Gets or sets PrimaryDomainName ///</summary> public string PrimaryDomainName { get; set; } ///<summary> ///Gets or sets TrackingCode ///</summary> public string TrackingCode { get; set; } ///<summary> ///Gets or sets TrackingType ///</summary> public string TrackingType { get; set; } #endregion } }<file_sep>var ManageParts = function () { init = function () { }, getZoneId = function getZoneId(col) { //zoneid 2 Left Column >> 1 col //zoneid 3 Right Column >> 3 col //zoneid 4 Center Column >> 2 col if (col == 1) { return 2; } if (col == 2) { return 4; } return col; }, removeItem = function removeItem(partid) { $.ajax({ url: '/CmsPageManager/AsyncRemovePart', data: { partId: partid }, success: function (data) { // alert(data); }, error: function () { //alert('Error'); } }); var gridster = $(".gridster ul").gridster().data('gridster'); var el = $(".gridster ul").find("[data-partid='" + partid + "']"); gridster.remove_widget(el); }, addItem = function addItem(col, id) { var partTypeId = $('#AvailablePartSelectedItem :selected').val(); var partName = $('#partName').val(); var pageId = id; var colSpan = $('input:radio[name=colsize]:checked').val(); var zoneId = getZoneId(col); var pageStructureId = $('#PageStructureStyleId :selected').val(); if (colSpan == 2 && zoneId == 3) { colSpan = 1; } if (colSpan == 3 && zoneId != 2) { zoneId = 2; col = 1; } if (partName == "") { partName = "New Part"; } /* from inside*/ var row = 1; var order = 1; $(".gridster ul li").each(function () { var itemRow = $(this).attr('data-row'); var itemCol = $(this).attr('data-col'); if (itemCol == col) { if (itemRow >= row) { row++; } } }); $(".gridster ul li").each(function () { var itemRow = $(this).attr('data-row'); var itemSize = $(this).attr('data-sizex'); if (itemRow == row) { if (col > 1) { if (itemSize > 1) { row++; } } } }); /* from inside*/ //alert(pageStructureId); $.ajax({ url: '/CmsPageManager/AsyncAddPart', data: { partTypeId: partTypeId, partName: partName, zoneId: zoneId, pageId: pageId, colSpan: colSpan, rowId: row, pageStructureId: pageStructureId }, success: function (data) { var gridItem = '<li class="new" data-partid="' + data + '">' + partName + ' <a class="delpart">delete</a></li>'; var gridster = $(".gridster ul").gridster().data('gridster'); /* was inside */ gridster.add_widget(gridItem, colSpan, 1, col, row); //.add_widget(html, [size_x], [size_y], [col], [row]) }, error: function () { //alert('Error'); } }); }; return { init: init, getZoneId: getZoneId, addItem: addItem, removeItem: removeItem }; }(); $(function () { $(".gridster ul").gridster({ widget_margins: [8, 8], widget_base_dimensions: [230, 40], draggable: { stop: function (event, ui) { // var gridster = $(".gridster ul").gridster().data('gridster'); // var grdData = JSON.stringify(gridster.serialize()); var gridItems = new Array(); $(".gridster ul li").each(function () { var partid = $(this).attr('data-partid'); var row = $(this).attr('data-row'); var col = $(this).attr('data-col'); var gridItem = new Object(); gridItem.PartId = partid; gridItem.RowId = row; gridItem.ColId = col; gridItems.push(gridItem); }); var myJsonData = JSON.stringify(gridItems); $.ajax({ url: '/CmsPageManager/AsyncUpdatePartOrder', data: { jsonData: myJsonData }, contentType: 'application/json; charset=utf-8', dataType: 'json', success: function (data) { alert(data); }, error: function () { //alert('Error'); } }); }, serialize_params: function ($w, wgd) { return { row: wgd.row, col: wgd.col }; } } }); }); <file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IClientAssetTypeService.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Service.Contracts { using Firebrick.Model; /// <summary> /// The i client asset type. /// </summary> public interface IClientAssetTypeService : IService<ClientAssetType> { } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="SendEmailResult.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Entities.Messaging { using System; using System.Net.Mail; /// <summary> /// The send email result. /// </summary> public class SendEmailResult { #region Public Properties /// <summary> /// Gets or sets Exception. /// </summary> public Exception Exception { get; set; } /// <summary> /// Gets a value indicating whether Failed. /// </summary> public bool Failed { get { return this.Exception != null; } } /// <summary> /// Gets Message. /// </summary> public MailMessage Message { get; set; } #endregion } }<file_sep>namespace Firebrick.Test.Helper { public static class DefaultWebHelper { } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="RoleServiceFixture.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Services.Tests { /// <summary> /// The role service fixture. /// </summary> public class RoleServiceFixture { } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IRepository.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data { using System; using System.Collections.Generic; using System.Linq.Expressions; /// <summary> /// The i repository. /// </summary> /// <typeparam name="T"> /// </typeparam> public interface IRepository<T> where T : class { #region Public Methods void Add(T entity); void Delete(T entity); void Delete(Expression<Func<T, bool>> where); T Get(Expression<Func<T, bool>> where); IEnumerable<T> GetAll(); T GetById(int Id); IEnumerable<T> GetMany(Expression<Func<T, bool>> where); void Update(T entity); #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PostalCodeValidatorAttribute.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.Validators { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text.RegularExpressions; using System.Web.Mvc; using Firebrick.Domain.Properties; using Firebrick.Domain.ViewModels; /// <summary> /// The postal code validator attribute. /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public sealed class PostalCodeValidatorAttribute : ValidationAttribute, IClientValidatable { #region Constants and Fields /// <summary> /// The international postal code regex. /// </summary> private static readonly Regex InternationalPostalCodeRegex = new Regex( Resources.InternationalPostalCodeRegex, RegexOptions.Compiled); /// <summary> /// The us postal code regex. /// </summary> private static readonly Regex USPostalCodeRegex = new Regex(Resources.USPostalCodeRegex, RegexOptions.Compiled); #endregion #region Public Methods /// <summary> /// The get client validation rules. /// </summary> /// <param name="metadata"> /// The metadata. /// </param> /// <param name="context"> /// The context. /// </param> /// <returns> /// </returns> public IEnumerable<ModelClientValidationRule> GetClientValidationRules( ModelMetadata metadata, ControllerContext context) { var rule = new ModelClientValidationRule { ErrorMessage = Resources.InvalidInputCharacter, ValidationType = "postalcode" }; rule.ValidationParameters.Add( "internationalerrormessage", Resources.InternationalPostalCodeValidationErrorMessage); rule.ValidationParameters.Add("unitedstateserrormessage", Resources.USPostalCodeValidationErrorMessage); rule.ValidationParameters.Add("internationalpattern", Resources.InternationalPostalCodeRegex); rule.ValidationParameters.Add("unitedstatespattern", Resources.USPostalCodeRegex); return new List<ModelClientValidationRule> { rule }; } #endregion #region Methods /// <summary> /// The is valid. /// </summary> /// <param name="value"> /// The value. /// </param> /// <param name="context"> /// The context. /// </param> /// <returns> /// </returns> protected override ValidationResult IsValid(object value, ValidationContext context) { var userToValidate = context.ObjectInstance as FirebrickUserViewModel; var memberNames = new List<string> { context.MemberName }; if (userToValidate != null) { if (string.IsNullOrEmpty(userToValidate.Country) && string.IsNullOrEmpty(userToValidate.PostalCode)) { return ValidationResult.Success; } if (string.IsNullOrEmpty(userToValidate.PostalCode)) { return ValidationResult.Success; } if (userToValidate.Country == Resources.UnitedStatesDisplayString) { if (USPostalCodeRegex.IsMatch(userToValidate.PostalCode)) { return ValidationResult.Success; } return new ValidationResult(Resources.USPostalCodeValidationErrorMessage, memberNames); } else { if (InternationalPostalCodeRegex.IsMatch(userToValidate.PostalCode)) { return ValidationResult.Success; } return new ValidationResult(Resources.InternationalPostalCodeValidationErrorMessage, memberNames); } } return ValidationResult.Success; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Page.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Model { using System; using System.ComponentModel.DataAnnotations; /// <summary> /// The web page. /// </summary> public class Page { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="Page"/> class. /// </summary> public Page() { this.PageId = -1; } #endregion #region Public Properties /// <summary> /// Gets or sets ActionName. /// </summary> public string ActionName { get; set; } /// <summary> /// Gets or sets ControllerName. /// </summary> public string ControllerName { get; set; } public bool IsPublished { get; set; } public int Order { get; set; } /// <summary> /// Gets or sets PageId. /// </summary> [Key] public int PageId { get; set; } /// <summary> /// Gets or sets ParentId. /// </summary> public int PageParentId { get; set; } /// <summary> /// Gets or sets TemplateId. /// </summary> public int PageTemplateId { get; set; } public int PageStructureStyleId { get; set; } /// <summary> /// Gets or sets PortalId. /// </summary> public int PortalId { get; set; } /// <summary> /// Gets or sets a value indicating whether ShowOnMenu. /// </summary> public bool ShowOnMenu { get; set; } /// <summary> /// Gets or sets Title. /// </summary> public string Title { get; set; } public string LastModifiedBy { get; set; } public DateTime LastModified { get; set; } public string CreatedBy { get; set; } public DateTime Created { get; set; } #endregion /* * [Key] * * [ForiegnKey(PortalId)] * * [Range(35,44)] * [Range(typeof(decimal), "0.00", "49.99")] * * [Required(ErrorMessage="Your last name is required")] * [StringLength(160)] * * [RegularExpression(@"[A-Za-z0-9._%+-]")] * * [Compare("Email")] * * [DataType(DataType.Password)] * * */ } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="UnityPerRequestLifetimeManagerFixture.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Web.Tests.UnityTests { using System; using Firebrick.UI.Core.UnityExtensions; using Moq; using Xunit; /// <summary> /// The unity per request lifetime manager fixture. /// </summary> public class UnityPerRequestLifetimeManagerFixture { #region Public Methods /// <summary> /// The when disposing lifetime manager_ disposes value. /// </summary> [Fact] public void WhenDisposingLifetimeManager_DisposesValue() { var valueMock = new Mock<IDisposable>(); valueMock.Setup(x => x.Dispose()).Verifiable(); var storeMock = new Mock<IPerRequestStore>(); storeMock.Setup(s => s.GetValue(It.IsAny<object>())).Returns(valueMock.Object); storeMock.Setup(s => s.RemoveValue(It.IsAny<object>())).Verifiable(); var lifetimeManager = new UnityPerRequestLifetimeManager(storeMock.Object); lifetimeManager.SetValue(valueMock.Object); ((IDisposable)lifetimeManager).Dispose(); valueMock.Verify(); } /// <summary> /// The when get value called_ then retrieved from http items context. /// </summary> [Fact] public void WhenGetValueCalled_ThenRetrievedFromHttpItemsContext() { var newValue = new object(); var storeMock = new Mock<IPerRequestStore>(); storeMock.Setup(s => s.GetValue(It.IsAny<object>())).Returns(newValue).Verifiable(); var lifetimeManager = new UnityPerRequestLifetimeManager(storeMock.Object); lifetimeManager.SetValue(newValue); object returnedValue = lifetimeManager.GetValue(); storeMock.Verify(); } /// <summary> /// The when removing disposable values_ then dispose invoked. /// </summary> [Fact] public void WhenRemovingDisposableValues_ThenDisposeInvoked() { var valueMock = new Mock<IDisposable>(); valueMock.Setup(x => x.Dispose()).Verifiable(); var storeMock = new Mock<IPerRequestStore>(); storeMock.Setup(s => s.GetValue(It.IsAny<object>())).Returns(valueMock.Object); storeMock.Setup(s => s.RemoveValue(It.IsAny<object>())).Verifiable(); var lifetimeManager = new UnityPerRequestLifetimeManager(storeMock.Object); lifetimeManager.SetValue(valueMock.Object); lifetimeManager.RemoveValue(); valueMock.Verify(); } /// <summary> /// The when request ends_ then removed from context. /// </summary> [Fact] public void WhenRequestEnds_ThenRemovedFromContext() { var newValue = new object(); var storeMock = new Mock<IPerRequestStore>(); storeMock.Setup(s => s.GetValue(It.IsAny<object>())).Returns(newValue); storeMock.Setup(s => s.RemoveValue(It.IsAny<object>())).Verifiable(); var lifetimeManager = new UnityPerRequestLifetimeManager(storeMock.Object); lifetimeManager.SetValue(newValue); storeMock.Raise(a => a.EndRequest += null, EventArgs.Empty); storeMock.Verify(); } /// <summary> /// The when set value called_ then stored in http items contex. /// </summary> [Fact] public void WhenSetValueCalled_ThenStoredInHttpItemsContex() { var newValue = new object(); var storeMock = new Mock<IPerRequestStore>(); storeMock.Setup(s => s.SetValue(It.IsAny<object>(), newValue)).Verifiable(); var lifetimeManager = new UnityPerRequestLifetimeManager(storeMock.Object); lifetimeManager.SetValue(newValue); storeMock.Verify(); } /// <summary> /// The when value removed_ then removed from context. /// </summary> [Fact] public void WhenValueRemoved_ThenRemovedFromContext() { var newValue = new object(); var storeMock = new Mock<IPerRequestStore>(); storeMock.Setup(s => s.GetValue(It.IsAny<object>())).Returns(newValue); storeMock.Setup(s => s.RemoveValue(It.IsAny<object>())).Verifiable(); var lifetimeManager = new UnityPerRequestLifetimeManager(storeMock.Object); lifetimeManager.SetValue(newValue); lifetimeManager.RemoveValue(); storeMock.Verify(); } #endregion } }<file_sep>namespace Firebrick.Service.Contracts { using Firebrick.Model; ///<summary> ///The i notification type service config ///</summary> public interface INotificationTypeService : IService<NotificationType> { } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IPerRequestStore.cs" company="Beyond"> // Copyright Beyond 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.UI.Core.UnityExtensions { using System; /// <summary> /// The i per request store. /// </summary> public interface IPerRequestStore { #region Public Events /// <summary> /// The end request. /// </summary> event EventHandler EndRequest; #endregion #region Public Methods /// <summary> /// The get value. /// </summary> /// <param name="key"> /// The key. /// </param> /// <returns> /// The get value. /// </returns> object GetValue(object key); /// <summary> /// The remove value. /// </summary> /// <param name="key"> /// The key. /// </param> void RemoveValue(object key); /// <summary> /// The set value. /// </summary> /// <param name="key"> /// The key. /// </param> /// <param name="value"> /// The value. /// </param> void SetValue(object key, object value); #endregion } }<file_sep>namespace Firebrick.Domain.ViewModels.WebAdmin.CmsPageManager { /// <summary> /// The cms page manager index view model list item. /// </summary> public sealed class CmsPageManagerIndexViewModelListItem { #region Public Properties public bool IsPublished { get; set; } /// <summary> /// Gets or sets PageId. /// </summary> public int PageId { get; set; } public bool ShowOnMenu { get; set; } /// <summary> /// Gets or sets Title. /// </summary> public string Title { get; set; } public string LookFor { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IPartTypeRepository.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.RepositoryContracts { using Firebrick.Model; /// <summary> /// The i web part type repository. /// </summary> public interface IPartTypeRepository : IRepository<PartType> { } }<file_sep>namespace Firebrick.Model { using System.ComponentModel.DataAnnotations; public class RolePageRestriction { #region Public Properties public bool IsEditable { get; set; } public bool IsViewable { get; set; } public int PageId { get; set; } public int RoleId { get; set; } [Key] public int RolePageRestrictionId { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PageService.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Service.Implementations { using Firebrick.Data; using Firebrick.Data.RepositoryContracts; using Firebrick.Model; using Firebrick.Service.Contracts; /// <summary> /// The web page service. /// </summary> public class PageService : BaseService<Page>, IPageService { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="PageService"/> class. /// </summary> /// <param name="pageRepository"> /// The user repository. /// </param> /// <param name="unitOfWork"> /// The unit of work. /// </param> public PageService(IPageRepository pageRepository, IUnitOfWork unitOfWork) { this.Repository = pageRepository; this.UnitOfWork = unitOfWork; } #endregion #region Public Methods /// <summary> /// Gets page based on look for /// </summary> /// <param name="lookFor"> /// The look for. /// </param> /// <returns> /// Returns page based on url /// </returns> public Page GetByLookFor(string lookFor) { return this.Repository.Get(webpage => webpage.ActionName.ToLower() == lookFor.ToLower()); } #endregion } }<file_sep>namespace Firebrick.Web.Tests.ContentManagement { using System.Web.Mvc; using Firebrick.ContentManagement.Web.Controllers; using Firebrick.Data; using Firebrick.Data.RepositoryContracts; using Firebrick.Domain.ViewModels.ContentManagement.RichContent; using Firebrick.Service.Implementations; using Firebrick.Test.Helper; using Moq; using Xunit; public class RichContentControllerFixture { #region Public Methods [Fact] public void WhenDefaultIndexMethodCalledWithPageId_ValidViewModelReturned() { // Arrange const string PageId = "1"; var contentRepositoryMock = new Mock<IContentBlobRepository>(); contentRepositoryMock.Setup(repo => repo.GetById(It.IsAny<int>())).Returns( DefaultModelHelper.DummyPopulatedContentBlob); var contentBlobService = new ContentBlobService( contentRepositoryMock.Object, new Mock<IUnitOfWork>().Object); var controller = new RichContentController(contentBlobService); // Act var viewResult = controller.Index(PageId, "1", "1") as PartialViewResult; // Assert Assert.NotNull(viewResult); Assert.Equal(string.Empty, viewResult.ViewName); Assert.True(viewResult.ViewData.ModelState.IsValid); Assert.True(controller.ModelState.IsValid); } [Fact] public void WhenPassedAValidViewModel_ThenPersists() { // Arrange const string PageId = "1"; var contentRepositoryMock = new Mock<IContentBlobRepository>(); contentRepositoryMock.Setup(repo => repo.GetById(It.IsAny<int>())).Returns( DefaultModelHelper.DummyPopulatedContentBlob); var contentBlobService = new ContentBlobService( contentRepositoryMock.Object, new Mock<IUnitOfWork>().Object); var controller = new RichContentController(contentBlobService); var viewModel = new RichContentEditViewModel { Html = "EditedHtml", ContentBlobId = 1, PartId = 1 }; // Act var viewResult = controller.EditMode(PageId, "", "", viewModel) as PartialViewResult; // Assert Assert.NotNull(viewResult); Assert.Equal(string.Empty, viewResult.ViewName); Assert.True(viewResult.ViewData.ModelState.IsValid); Assert.True(controller.ModelState.IsValid); } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="RepositoryInitializer.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.EF.Initializers { using System.Data.Entity; using Firebrick.Data.EF.Migrations; // public class RepositoryInitializer : DropCreateDatabaseIfModelChanges<FirebrickContext>, IRepositoryInitializer // public class RepositoryInitializer : MigrateDatabaseToLatestVersion<FirebrickContext, Configuration>, IRepositoryInitializer // new CreateDatabaseIfNotExists<Models.FunContext>() // To run migrations to start with > drop database // Then run the update-database command from the package manager console inside vs2010 against Data.EF // This will create the database, then use the Migrate... above, but below as the class inheritance, and that should be it? /// <summary> /// The repository initializer. /// </summary> public class RepositoryInitializer : MigrateDatabaseToLatestVersion<FirebrickContext, Configuration>, IRepositoryInitializer { #region Public Methods /// <summary> /// The initialize. /// </summary> public void Initialize() { } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IClientAssetTypeRepository.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.RepositoryContracts { using Firebrick.Model; /// <summary> /// The i client asset type repository. /// </summary> public interface IClientAssetTypeRepository : IRepository<ClientAssetType> { } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="TextLineInputValidatorAttribute.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.Validators { using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; using Firebrick.Domain.Properties; /// <summary> /// The text line input validator attribute. /// </summary> public class TextLineInputValidatorAttribute : RegularExpressionAttribute, IClientValidatable { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="TextLineInputValidatorAttribute"/> class. /// </summary> public TextLineInputValidatorAttribute() : base(Resources.TextLineInputValidatorRegEx) { this.ErrorMessage = Resources.InvalidInputCharacter; } #endregion #region Public Methods /// <summary> /// The get client validation rules. /// </summary> /// <param name="metadata"> /// The metadata. /// </param> /// <param name="context"> /// The context. /// </param> /// <returns> /// </returns> public IEnumerable<ModelClientValidationRule> GetClientValidationRules( ModelMetadata metadata, ControllerContext context) { var rule = new ModelClientValidationRule { ErrorMessage = Resources.InvalidInputCharacter, ValidationType = "textlineinput" }; rule.ValidationParameters.Add("pattern", Resources.TextLineInputValidatorRegEx); return new List<ModelClientValidationRule> { rule }; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PartType.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Model { using System.ComponentModel.DataAnnotations; /// <summary> /// The web part type. /// </summary> public class PartType { #region Public Properties /// <summary> /// Gets or sets Action. /// </summary> public string Action { get; set; } /// <summary> /// Gets or sets AddAction. /// </summary> public string AddAction { get; set; } /// <summary> /// Gets or sets AdminEditAction. /// </summary> public string AdminEditAction { get; set; } /// <summary> /// Gets or sets AdminEditController. /// </summary> public string AdminEditController { get; set; } /// <summary> /// Gets or sets Controller. /// </summary> public string Controller { get; set; } /// <summary> /// Gets or sets EditAction. /// </summary> public string EditAction { get; set; } /// <summary> /// Gets or sets Id. /// </summary> [Key] public int PartTypeId { get; set; } /// <summary> /// Gets or sets Title. /// </summary> public string Title { get; set; } /// <summary> /// Gets or sets ViewIdentifier. /// </summary> public string ViewIdentifier { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="CmsPageManagerAddViewModel.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.ViewModels { using System.Collections.Generic; using System.Web.Mvc; using Firebrick.Domain.ViewModels.WebAdmin.CmsPageManager; /// <summary> /// The page view model. /// </summary> public class CmsPageManagerAddViewModel : CmsPageManagerBaseViewModel { #region Constructors and Destructors public CmsPageManagerAddViewModel() { this.ActionIsAddSuccessful = null; } #endregion #region Public Properties /// <summary> /// Gets ActionCancel. /// </summary> public override string ActionCancelUrl { get { return Helpers.Route.WebAdmin.AdminPageList; } } /// <summary> /// Gets or sets a value indicating whether ActionIsAddSuccessful. /// </summary> public bool? ActionIsAddSuccessful { get; set; } public IEnumerable<SelectListItem> ParentPagesAvailableList { get; set; } public int ParentPagesSelectedItem { get; set; } public string CreatedBy { get; set; } #endregion } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Firebrick.Domain.ViewModels.WebAdmin.CmsPlugins { public class CmsPluginMainSideMenuViewModel { public CmsPluginMainSideMenuViewModel() { ParentItems = new List<CmsPluginMainSideMenuViewModelItem>(); } public IList<CmsPluginMainSideMenuViewModelItem> ParentItems { get; set; } } } <file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Engine.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Model { using System.ComponentModel.DataAnnotations; /// <summary> /// The engine. /// </summary> public class Engine { #region Public Properties /// <summary> /// Gets or sets Description. /// </summary> public string Description { get; set; } /// <summary> /// Gets or sets EngineId. /// </summary> [Key] public int EngineId { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Part.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Model { using System.ComponentModel.DataAnnotations; /// <summary> /// The web part. /// </summary> public class Part { #region Public Properties public bool IsEnabled { get; set; } /// <summary> /// Gets or sets Order. /// </summary> public int Order { get; set; } /// <summary> /// Gets or sets PageId. /// </summary> public int PageId { get; set; } /// <summary> /// Gets or sets PartContainerId. /// </summary> public int PartContainerId { get; set; } /// <summary> /// Gets or sets Id. /// </summary> [Key] public int PartId { get; set; } /// <summary> /// Gets or sets PartTypeId. /// </summary> public int PartTypeId { get; set; } /// <summary> /// Gets or sets Title. /// </summary> public string Title { get; set; } /// <summary> /// Gets or sets ZoneId. /// </summary> public int ZoneId { get; set; } public int ColSpan { get; set; } public string ColSpanDescriptor { get; set; } public int RowId { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="SeoDecoratorFixture.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Model.Tests.EFModels { using Xunit; /// <summary> /// The seo decorator fixture. /// </summary> public class SeoDecoratorFixture { #region Public Methods /// <summary> /// The when instantiating class with default constructor_ suceeds. /// </summary> [Fact] public void WhenInstantiatingClassWithDefaultConstructor_Succeeds() { // Arrange SeoDecorator userRole; // Act userRole = new SeoDecorator(); // Assert Assert.NotNull(userRole); } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="CmsPageServiceBinder.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.ServiceBinders.WebAdmin { using Firebrick.Domain.ViewModels.WebAdmin.CmsDashboard; using Firebrick.Service.Contracts; /// <summary> /// The cms page service binder. /// </summary> public class CmsDashboardServiceBinder { #region Constants and Fields /// <summary> /// The page service. /// </summary> private readonly IPageService pageService; /// <summary> /// The page template service. /// </summary> private readonly IPageTemplateService pageTemplateService; #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="CmsPageManagerServiceBinder"/> class. /// </summary> /// <param name="pageService"> /// The page service. /// </param> /// <param name="pageTemplateService"> /// The page template service. /// </param> public CmsDashboardServiceBinder(IPageService pageService, IPageTemplateService pageTemplateService) { this.pageService = pageService; this.pageTemplateService = pageTemplateService; } #endregion #region Public Methods /// <summary> /// The bind model. /// </summary> /// <param name="id"> /// The id. /// </param> /// <returns> /// </returns> public CmsDashboardIndexViewModel BindModel(int id) { var viewModel = new CmsDashboardIndexViewModel(); return viewModel; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IClientAssetService.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Service.Contracts { using Firebrick.Model; /// <summary> /// The i client asset service. /// </summary> public interface IClientAssetService : IService<ClientAsset> { } }<file_sep>namespace Firebrick.Domain.ViewModels.WebAdmin.CmsMenuManager { public class TreePageViewModel { #region Public Properties public string LookFor { get; set; } public int Order { get; set; } public int PageId { get; set; } public int ParentId { get; set; } public string Title { get; set; } #endregion } }<file_sep>namespace Firebrick.Data.EF.Initializers { using System.Data.Entity.Migrations; using System.Data.Entity.Validation; using System.Diagnostics; using Firebrick.Model; public class AnalyticsInitializer { #region Public Methods public static void Add(FirebrickContext context) { AddAnalyticsTypes(context); AddAnalytcisAccount(context); } #endregion #region Methods private static void AddAnalytcisAccount(FirebrickContext context) { context.AnalyticsTypes.AddOrUpdate( new AnalyticsType { AnalyticsTypeId = 1, Description = "Website Account", IsActive = true }); try { context.SaveChanges(); } catch (DbEntityValidationException dbEx) { foreach (DbEntityValidationResult validationErrors in dbEx.EntityValidationErrors) { foreach (DbValidationError validationError in validationErrors.ValidationErrors) { Debug.WriteLine( "Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } } } private static void AddAnalyticsTypes(FirebrickContext context) { context.AnalyticsAccounts.AddOrUpdate( new AnalyticsAccount { AnalytcisAccountId = 1, AccountName = "<NAME>", PortalId = 1, PrimaryDomainName = "www.firebrick-content-management.co.uk", ShowMobile = true, TrackingCode = "UA-11-22-33", TrackingType = "type" }); try { context.SaveChanges(); } catch (DbEntityValidationException dbEx) { foreach (DbEntityValidationResult validationErrors in dbEx.EntityValidationErrors) { foreach (DbValidationError validationError in validationErrors.ValidationErrors) { Debug.WriteLine( "Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } } } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PageControllerActionService.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Service.Implementations { using Firebrick.Data; using Firebrick.Data.RepositoryContracts; using Firebrick.Model; using Firebrick.Service.Contracts; /// <summary> /// The page controller action service. /// </summary> public class PageControllerActionService : BaseService<PageControllerAction>, IPageControllerActionService { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="PageControllerActionService"/> class. /// </summary> /// <param name="controllerActionRepository"> /// The controller action repository. /// </param> /// <param name="unitOfWork"> /// The unit of work. /// </param> public PageControllerActionService( IPageControllerActionRepository controllerActionRepository, IUnitOfWork unitOfWork) { this.Repository = controllerActionRepository; this.UnitOfWork = unitOfWork; } #endregion #region Public Methods /// <summary> /// Gets a match on controller and action /// </summary> /// <param name="controller"> /// The controller. /// </param> /// <param name="action"> /// The action. /// </param> /// <returns> /// page control action id /// </returns> public int GetPageControllerActionId(string controller, string action) { return this.Repository.Get(ca => ca.ControllerName == controller && ca.ActionName == action). PageControllerActionId; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IPortalService.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Service.Contracts { using Firebrick.Model; /// <summary> /// The i web site service. /// </summary> public interface IPortalService : IService<Portal> { } }<file_sep>namespace Firebrick.Model { using System.ComponentModel.DataAnnotations; public class NotificationType { #region Public Properties ///<summary> ///Gets or sets Description ///</summary> public string Description { get; set; } ///<summary> ///Gets or sets IsActive ///</summary> public bool IsActive { get; set; } ///<summary> ///Gets or sets NotificationTypeId ///</summary> [Key] public int NotificationTypeId { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ClientAssetType.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Model { using System.ComponentModel.DataAnnotations; /// <summary> /// The design asset type. /// </summary> public class ClientAssetType { #region Public Properties /// <summary> /// Gets or sets DesignAssetTypeId. /// </summary> [Key] public int ClientAssetTypeId { get; set; } /// <summary> /// Gets or sets Title. /// </summary> public string Title { get; set; } #endregion } }<file_sep>Firebrick-CMS ============= Firebrick Content Management System (and Beyond...) ASP.Net MVC 4 Entity Framework 5 SQL Server 2008 Unity AutoMapper Log4Net Cassette SquishIt Visual Studio 2012 xUnit MOQ C# Razor JavaScript JQuery HTML5 <file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PageViewModel.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.ViewModels { using System.Collections.Generic; using System.Web.Mvc; using Firebrick.Model; /// <summary> /// The page view model. /// </summary> public class PageViewModel : IPageViewModel { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="PageViewModel"/> class. /// </summary> public PageViewModel() { this.Page = new Page(); } /// <summary> /// Initializes a new instance of the <see cref="PageViewModel"/> class. /// </summary> /// <param name="page"> /// The page. /// </param> public PageViewModel(Page page) { this.Page = page; } #endregion #region Public Properties /// <summary> /// Gets or sets Page. /// </summary> public Page Page { get; set; } /// <summary> /// Gets or sets PageTemplateList. /// </summary> public IEnumerable<SelectListItem> PageTemplateList { get; set; } /// <summary> /// Gets or sets ParentPageList. /// </summary> public IEnumerable<SelectListItem> ParentPageList { get; set; } #endregion } /// <summary> /// The i page view model. /// </summary> public interface IPageViewModel { #region Public Properties /// <summary> /// Gets or sets Page. /// </summary> Page Page { get; set; } #endregion } /// <summary> /// The i page view model admin edit. /// </summary> internal interface IPageViewModelAdminEdit { #region Public Properties /// <summary> /// Gets or sets Page. /// </summary> Page Page { get; set; } /// <summary> /// Gets or sets PageTemplateList. /// </summary> IEnumerable<SelectListItem> PageTemplateList { get; set; } /// <summary> /// Gets or sets ParentPageList. /// </summary> IEnumerable<SelectListItem> ParentPageList { get; set; } #endregion } }<file_sep>namespace Firebrick.Data.EF.Repositories { using Firebrick.Data.RepositoryContracts; using Firebrick.Model; public class SeoRouteValueRepository : BaseRepository<SeoRouteValue>, ISeoRouteValueRepository { #region Constructors and Destructors public SeoRouteValueRepository(IDatabaseFactory databaseFactory) : base(databaseFactory) { } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="RichContentController.cs" company=""> // // </copyright> // <summary> // The rich content controller. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.ContentManagement.Web.Controllers { using System; using System.Web.Mvc; using Firebrick.Domain.ServiceBinders.ContentManagement; using Firebrick.Domain.ViewModels.ContentManagement.RichContent; using Firebrick.Service.Contracts; using Firebrick.UI.Core.Controllers; /// <summary> /// The rich content controller. /// </summary> public class RichContentController : BasePartController { #region Constants and Fields /// <summary> /// The content blob service. /// </summary> private readonly IContentBlobService contentBlobService; #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="RichContentController"/> class. /// </summary> /// <param name="contentBlobService"> /// The content blob service. /// </param> public RichContentController(IContentBlobService contentBlobService) { this.contentBlobService = contentBlobService; } #endregion // GET: /RichContent/ #region Public Methods public ActionResult Add() { return this.PartialView(); } [HttpPost] public ActionResult EditMode(string id, string partId, string zoneId, RichContentEditViewModel viewModel) { try { RichContentServiceBinder modelBinder = this.GetServiceBinder(); if (viewModel.Html == null) { viewModel = modelBinder.EditViewModelBind(id, partId, zoneId); } viewModel = viewModel.ContentBlobId != -1 ? modelBinder.EditViewModelUpdate(partId, viewModel) : modelBinder.EditViewModelAdd(partId, viewModel); } catch (Exception ex) { this.LoggingService.Log(ex.Message); } return PartialView(viewModel); } [ChildActionOnly] public ActionResult Index(string id, string partId, string zoneId) { RichContentIndexViewModel viewModel = null; try { RichContentServiceBinder modelBinder = this.GetServiceBinder(); viewModel = modelBinder.IndexViewModelBind(id, partId, zoneId); } catch (Exception ex) { this.LoggingService.Log(ex.Message); } return PartialView(viewModel); } #endregion #region Methods private RichContentServiceBinder GetServiceBinder() { return new RichContentServiceBinder(this.contentBlobService); } #endregion } }<file_sep>namespace Firebrick.Data.EF.Repositories { using Firebrick.Data.RepositoryContracts; using Firebrick.Model; public class RolePageRestrictionRepository : BaseRepository<RolePageRestriction>, IRolePageRestrictionRepository { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="PortalRepository"/> class. /// </summary> /// <param name="databaseFactory"> /// The database factory. /// </param> public RolePageRestrictionRepository(IDatabaseFactory databaseFactory) : base(databaseFactory) { } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="BaseHttpHandler.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Framework.Http { using System; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Net; using System.Text; using System.Web; /// <summary> /// An abstract base Http Handler for all your /// <see cref="IHttpHandler"/> needs. /// </summary> /// <remarks> /// <p> /// For the most part, classes that inherit from this /// class do not need to override <see cref="ProcessRequest"/>. /// Instead implement the abstract methods and /// properties and put the main business logic /// in the <see cref="HandleRequest"/>. /// </p> /// <p> /// HandleRequest should respond with a StatusCode of /// 200 if everything goes well, otherwise use one of /// the various "Respond" methods to generate an appropriate /// response code. Or use the HttpStatusCode enumeration /// if none of these apply. /// </p> /// </remarks> public abstract class BaseHttpHandler : IHttpHandler { #region Public Properties /// <summary> /// Gets the content MIME type. /// </summary> /// <value></value> public abstract string ContentMimeType { get; } /// <summary> /// Gets a value indicating whether or not this handler can be /// reused between successive requests. /// </summary> /// <remarks> /// Return true if this handler does not maintain /// any state (generally a good practice). Otherwise /// returns false. /// </remarks> public bool IsReusable { get { return true; } } /// <summary> /// Gets a value indicating whether this handler /// requires users to be authenticated. /// </summary> /// <value> /// <c>true</c> if authentication is required /// otherwise, <c>false</c>. /// </value> public abstract bool RequiresAuthentication { get; } #endregion #region Properties /// <summary> /// Gets a value indicating whether RequiresCompression. /// </summary> private static bool RequiresCompression { get { // if (ConfigurationManager.AppSettings["UseGzip"] != null) // return Convert.ToBoolean(ConfigurationManager.AppSettings["UseGzip"]); return true; } } #endregion #region Public Methods /// <summary> /// The handle request. /// </summary> /// <param name="context"> /// The context. /// </param> /// <returns> /// The handle request string /// </returns> public abstract string HandleRequest(HttpContext context); /// <summary> /// Processs the incoming HTTP request. /// </summary> /// <param name="context"> /// Context http /// </param> public void ProcessRequest(HttpContext context) { Trace.WriteLine("Starting ProcessRequest", "BaseHttpHandler"); Trace.Indent(); context.Response.ClearHeaders(); context.Response.ClearContent(); this.SetResponseCachePolicy(context.Response.Cache); if (!this.ValidateParameters(context)) { this.RespondInternalError(context); return; } if (this.RequiresAuthentication && !context.User.Identity.IsAuthenticated) { this.RespondForbidden(context); return; } context.Response.Charset = "utf-8"; context.Response.ContentEncoding = Encoding.UTF8; context.Response.ContentType = this.ContentMimeType; string fullContent = this.HandleRequest(context); if (RequiresCompression) { Trace.WriteLine("RequiresCompression = True", "BaseHttpHandler"); string compressionType = GetCompressionType(context); if (compressionType == "gzip") { Trace.WriteLine("compressionType = gzip", "BaseHttpHandler"); using (var stream = new MemoryStream()) { using ( var writer = new StreamWriter( new GZipStream(stream, CompressionMode.Compress), Encoding.UTF8)) { writer.Write(fullContent); } byte[] buffer = stream.ToArray(); WriteBytes(buffer, context, compressionType); } } else if (compressionType == "deflate") { Trace.WriteLine("compressionType = deflate", "BaseHttpHandler"); using (var stream = new MemoryStream()) { using ( var writer = new StreamWriter( new DeflateStream(stream, CompressionMode.Compress), Encoding.UTF8)) { writer.Write(fullContent); } byte[] buffer = stream.ToArray(); WriteBytes(buffer, context, compressionType); } } else { Trace.WriteLine("compressionType = None", "BaseHttpHandler"); // no compression plain text... byte[] buffer = Encoding.UTF8.GetBytes(fullContent); context.Response.AddHeader("Content-Length", buffer.Length.ToString()); context.Response.Write(fullContent); context.Response.End(); } } else { // no compression plain text... Trace.WriteLine("RequiresCompression = False", "BaseHttpHandler"); byte[] buffer = Encoding.UTF8.GetBytes(fullContent); context.Response.AddHeader("Content-Length", buffer.Length.ToString()); Trace.Write(string.Format("Content-Length: {0}", buffer.Length), "BaseHttpHandler"); context.Response.AddHeader("Content-encoding", string.Empty); Trace.Write(string.Format("Content-encoding: {0}", string.Empty), "BaseHttpHandler"); context.Response.Write(fullContent); context.Response.End(); } Trace.Unindent(); Trace.WriteLine("Ending Process Request", "BaseHttpHandler"); } /// <summary> /// Sets the cache policy. Unless a handler overrides /// this method, handlers will not allow a respons to be /// cached. /// </summary> /// <param name="cache"> /// Cache policy /// </param> public virtual void SetResponseCachePolicy(HttpCachePolicy cache) { cache.SetCacheability(HttpCacheability.NoCache); cache.SetNoStore(); cache.SetExpires(DateTime.MinValue); } /// <summary> /// Validates the parameters. Inheriting classes must /// implement this and return true if the parameters are /// valid, otherwise false. /// </summary> /// <param name="context"> /// Context http /// </param> /// <returns> /// <c>true</c> if the parameters are valid, /// otherwise <c>false</c> /// </returns> public abstract bool ValidateParameters(HttpContext context); #endregion #region Methods /// <summary> /// Helper method used to Respond to the request /// that the file was not found. /// </summary> /// <param name="context"> /// Context http /// </param> protected void RespondFileNotFound(HttpContext context) { context.Response.StatusCode = (int)HttpStatusCode.NotFound; context.Response.End(); } /// <summary> /// Helper method used to Respond to the request /// that the request in attempting to access a resource /// that the user does not have access to. /// </summary> /// <param name="context"> /// Context http /// </param> protected void RespondForbidden(HttpContext context) { context.Response.StatusCode = (int)HttpStatusCode.Forbidden; context.Response.End(); } /// <summary> /// Helper method used to Respond to the request /// that an error occurred in processing the request. /// </summary> /// <param name="context"> /// Context http /// </param> protected void RespondInternalError(HttpContext context) { // It's really too bad that StatusCode property // is not of type HttpStatusCode. context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.End(); } /// <summary> /// The get compression type. /// </summary> /// <param name="context"> /// The context. /// </param> /// <returns> /// The get compression type as string /// </returns> private static string GetCompressionType(HttpContext context) { Trace.WriteLine("Starting GetCompressionType", "BaseHttpHandler"); Trace.Indent(); string compressionType = "none"; string encodingTypes = context.Request.Headers["Accept-Encoding"]; Trace.WriteLine(string.Format("encodingTypes: {0}", encodingTypes), "BaseHttpHandler"); if (!string.IsNullOrEmpty(encodingTypes)) { encodingTypes = encodingTypes.ToLower(); if (context.Request.Browser.Browser == "IE") { if (context.Request.Browser.MajorVersion < 6) { compressionType = "none"; } else if (context.Request.Browser.MajorVersion == 6 && !string.IsNullOrEmpty(context.Request.ServerVariables["HTTP_USER_AGENT"]) && context.Request.ServerVariables["HTTP_USER_AGENT"].Contains("EV1")) { compressionType = "none"; } } if (encodingTypes.Contains("gzip") || encodingTypes.Contains("x-gzip") || encodingTypes.Contains("*")) { compressionType = "gzip"; } else if (encodingTypes.Contains("deflate")) { compressionType = "deflate"; } } Trace.Unindent(); Trace.WriteLine("Ending GetCompressionType", "BaseHttpHandler"); return compressionType; } /// <summary> /// The write bytes. /// </summary> /// <param name="bytes"> /// The bytes. /// </param> /// <param name="context"> /// The context. /// </param> /// <param name="compressionType"> /// The compression type. /// </param> private static void WriteBytes(byte[] bytes, HttpContext context, string compressionType) { Trace.WriteLine("Starting WriteBytes", "BaseHttpHandler"); Trace.Indent(); HttpResponse response = context.Response; response.AddHeader("Content-Length", bytes.Length.ToString()); Trace.Write(string.Format("Content-Length: {0}", bytes.Length), "BaseHttpHandler"); response.AddHeader("Content-encoding", compressionType); Trace.Write(string.Format("Content-encoding: {0}", compressionType), "BaseHttpHandler"); response.OutputStream.Write(bytes, 0, bytes.Length); response.End(); Trace.WriteLine("Response.End", "BaseHttpHandler"); Trace.Unindent(); Trace.WriteLine("Ending WriteBytes", "BaseHttpHandler"); } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="BaseService.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Service { using System; using System.Collections.Generic; using System.Linq.Expressions; using Firebrick.Data; /// <summary> /// The base service. /// </summary> /// <typeparam name="T"> /// </typeparam> public class BaseService<T> where T : class { #region Constants and Fields /// <summary> /// The repository. /// </summary> protected IRepository<T> Repository; /// <summary> /// The unit of work. /// </summary> protected IUnitOfWork UnitOfWork; #endregion #region Public Methods /// <summary> /// The add. /// </summary> /// <param name="entity"> /// The entity. /// </param> public virtual void Add(T entity) { this.Repository.Add(entity); this.Save(); } public virtual T Create(T entity) { if (entity == null) { throw new ArgumentNullException("entity"); } this.Repository.Add(entity); this.Save(); return entity; } /// <summary> /// The delete. /// </summary> /// <param name="id"> /// The id. /// </param> public virtual void Delete(int id) { T entity = this.Repository.GetById(id); this.Repository.Delete(entity); this.Save(); } /// <summary> /// </summary> /// <param name="where"> /// The where. /// </param> /// <exception cref="NotImplementedException"> /// </exception> public virtual void Delete(Expression<Func<T, bool>> where) { this.Repository.Delete(where); } /// <summary> /// The get. /// </summary> /// <param name="where"> /// The where. /// </param> /// <returns> /// </returns> /// <exception cref="NotImplementedException"> /// </exception> public virtual T Get(Expression<Func<T, bool>> where) { return this.Repository.Get(where); } /// <summary> /// The get all. /// </summary> /// <returns> /// </returns> public virtual IEnumerable<T> GetAll() { IEnumerable<T> entities = this.Repository.GetAll(); return entities; } /// <summary> /// The get by id. /// </summary> /// <param name="Id"> /// The id. /// </param> /// <returns> /// </returns> public virtual T GetById(int Id) { return this.Repository.GetById(Id); } /// <summary> /// The get many. /// </summary> /// <param name="where"> /// The where. /// </param> /// <returns> /// </returns> /// <exception cref="NotImplementedException"> /// </exception> public virtual IEnumerable<T> GetMany(Expression<Func<T, bool>> where) { return this.Repository.GetMany(where); } /// <summary> /// The save. /// </summary> public virtual void Save() { this.UnitOfWork.Commit(); } /// <summary> /// The update. /// </summary> /// <param name="entity"> /// The entity. /// </param> public virtual void Update(T entity) { this.Repository.Update(entity); this.Save(); } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PageTemplateZoneMap.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Model { using System.ComponentModel.DataAnnotations; /// <summary> /// The web page template zone map. /// </summary> public class PageTemplateZoneMap { #region Public Properties /// <summary> /// Gets or sets TemplateId. /// </summary> public int PageTemplateId { get; set; } /// <summary> /// Gets or sets Id. /// </summary> [Key] public int PageTemplateZoneMapId { get; set; } /// <summary> /// Gets or sets ZoneId. /// </summary> public int PageZoneId { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PageZone.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Model { using System.ComponentModel.DataAnnotations; /// <summary> /// The web page zone. /// </summary> public class PageZone { #region Public Properties /// <summary> /// Gets or sets Id. /// </summary> [Key] public int PageZoneId { get; set; } /// <summary> /// Gets or sets Title. /// </summary> public string Title { get; set; } #endregion } }<file_sep>namespace Firebrick.Web.UI { using System.Web.Optimization; public class BundleMobileConfig { #region Public Methods public static void RegisterBundles(BundleCollection bundles) { bundles.Add( new ScriptBundle("~/bundles/jquerymobile").Include("~/Scripts/jquery/jquery.mobile-{version}.js")); bundles.Add( new StyleBundle("~/Content/Mobile/css").Include("~/Content/themes/jquery-mobile/Site.Mobile.css")); bundles.Add( new StyleBundle("~/Content/themes/jquery-mobile").Include( "~/Content/themes/jquery-mobile/jquery.mobile-{version}.css")); } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="WebFrameworkServiceBinder.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.ServiceBinders.Web { using System.Collections.Generic; using System.Linq; using Firebrick.Domain.ViewModels.Web.Core; using Firebrick.Model; using Firebrick.Service.Contracts; /// <summary> /// The web framework service binder. /// </summary> public class WebFrameworkServiceBinder { #region Constants and Fields private readonly IClientAssetConfigService clientAssetConfigService; private readonly IClientAssetService clientAssetService; private readonly IClientAssetTypeService clientAssetTypeService; private readonly IDomainService domainService; private readonly IPageService pageService; private readonly IPageTemplateService pageTemplateService; private readonly IPageTemplateZoneMapService pageTemplateZoneMapService; private readonly IPageZoneService pageZoneService; private readonly IPartContainerService partContainerService; private readonly IPartService partService; private readonly IPartTypeService partTypeService; private readonly ISeoDecoratorService seoDecoratorService; private readonly IUserService userService; #endregion #region Constructors and Destructors public WebFrameworkServiceBinder( IDomainService domainService, IClientAssetConfigService clientAssetConfigService, IClientAssetService clientAssetService, IClientAssetTypeService clientAssetTypeService, IPageService pageService, IPageTemplateService pageTemplateService, IPageTemplateZoneMapService pageTemplateZoneMapService, IPageZoneService pageZoneService, IPartService partService, IPartTypeService partTypeService, ISeoDecoratorService seoDecoratorService, IUserService userService, IPartContainerService partContainerService) { this.domainService = domainService; this.clientAssetConfigService = clientAssetConfigService; this.clientAssetService = clientAssetService; this.clientAssetTypeService = clientAssetTypeService; this.pageService = pageService; this.pageTemplateService = pageTemplateService; this.pageTemplateZoneMapService = pageTemplateZoneMapService; this.pageZoneService = pageZoneService; this.partService = partService; this.partTypeService = partTypeService; this.seoDecoratorService = seoDecoratorService; this.userService = userService; this.partContainerService = partContainerService; } #endregion #region Properties /// <summary> /// Gets or sets a value indicating whether EditModeActivated. /// </summary> private bool EditModeActivated { get; set; } #endregion #region Public Methods public WebFrameworkViewModel WebFrameworkViewModelBind(int pageId) { var viewModel = new WebFrameworkViewModel(); Page page = this.GetPage(pageId); Domain domain = this.GetDomain(page.PortalId); SeoDecorator seo = this.GetSeo(pageId); PageTemplate pageTemplate = this.GetPageTemplate(page.PageTemplateId); viewModel.HostHeader = domain.HostHeader; viewModel.LayoutTemplateSrc = pageTemplate.LayoutTemplateSrc; viewModel.PageActionName = page.ActionName; viewModel.PageControllerName = page.ControllerName; viewModel.PageId = pageId; viewModel.PageTemplateId = page.PageTemplateId; viewModel.PageTitle = page.Title; viewModel.PageTemplateZoneIdList = this.GetPageTemplateZoneIdList(page.PageTemplateId); viewModel.PartViewModelList = this.GetPartViewModelList(pageId); viewModel.PartViewModelDictionary = this.GetPartViewModelListDictionary(viewModel.PartViewModelList); viewModel.PortalId = page.PortalId; viewModel.PrimaryDomainId = domain.DomainId; viewModel.SeoCanonical = string.Format("http://{0}/{1}", domain.HostHeader, seo.LookFor); viewModel.SeoDescription = seo.Description; viewModel.SeoKeywords = seo.Keywords; viewModel.SeoLookFor = seo.LookFor; viewModel.SeoRobots = GetRobotsMetaContent(seo.RobotsFollow, seo.RobotsIndex); viewModel.CssAssets = this.GetCssAssets(pageId); viewModel.JavaScriptAssets = this.GetJavascriptAssets(pageId); viewModel.UserId = -1; viewModel.EditModeActivated = false; return viewModel; } public WebFrameworkViewModel WebFrameworkViewModelBind(int pageId, bool editModeActivated) { this.EditModeActivated = editModeActivated; WebFrameworkViewModel viewModel = this.WebFrameworkViewModelBind(pageId); viewModel.EditModeActivated = editModeActivated; return viewModel; } #endregion #region Methods #region "Meta Data" private static string GetRobotsFollowMeta(bool robotsFollow) { return robotsFollow ? "follow" : "nofollow"; } private static string GetRobotsIndexMeta(bool robotsIndex) { return robotsIndex ? "index" : "noindex"; } private static string GetRobotsMetaContent(bool robotsFollow, bool robotsIndex) { return string.Format("{0},{1}", GetRobotsFollowMeta(robotsFollow), GetRobotsIndexMeta(robotsIndex)); } #endregion #region "Assets" private List<string> GetCssAssets(int pageId) { IEnumerable<ClientAssetConfig> pageAssetsConfig = this.clientAssetConfigService.GetMany(ca => ca.PageId == pageId); IEnumerable<ClientAsset> pageAssets = this.clientAssetService.GetAll(); IEnumerable<string> cssAssets = from pac in pageAssetsConfig join pa in pageAssets on pac.ClientAssetId equals pa.ClientAssetId where pa.ClientAssetTypeId == 1 select pa.RelativeFilePath; return cssAssets.ToList(); } private List<string> GetJavascriptAssets(int pageId) { IEnumerable<ClientAssetConfig> pageAssetsConfig = this.clientAssetConfigService.GetMany(ca => ca.PageId == pageId); IEnumerable<ClientAsset> pageAssets = this.clientAssetService.GetAll(); IEnumerable<string> cssAssets = from pac in pageAssetsConfig join pa in pageAssets on pac.ClientAssetId equals pa.ClientAssetId where pa.ClientAssetTypeId == 2 select pa.RelativeFilePath; return cssAssets.ToList(); } #endregion private Domain GetDomain(int portalId) { return this.domainService.Get(d => d.PortalId == portalId); } private Page GetPage(int pageId) { return this.pageService.GetById(pageId); } private PageTemplate GetPageTemplate(int pageTemplateId) { return this.pageTemplateService.GetById(pageTemplateId); } private List<int> GetPageTemplateZoneIdList(int pageTemplateId) { IEnumerable<PageTemplateZoneMap> zones = this.pageTemplateZoneMapService.GetMany(z => z.PageTemplateId == pageTemplateId); IEnumerable<int> zoneIds = from z in zones select z.PageZoneId; return zoneIds.ToList(); } private List<WebFrameworkPartViewModel> GetPartViewModelList(int pageId) { IEnumerable<Part> parts = this.partService.GetMany(p => p.PageId == pageId).OrderBy(p => p.Order); IEnumerable<PartType> partTypes = this.partTypeService.GetAll(); IEnumerable<PartContainer> partContainers = this.partContainerService.GetAll(); IEnumerable<WebFrameworkPartViewModel> viewModelList = from p in parts join pt in partTypes on p.PartTypeId equals pt.PartTypeId join pc in partContainers on p.PartContainerId equals pc.PartContainerId select new WebFrameworkPartViewModel { PartAction = this.EditModeActivated ? pt.EditAction : pt.Action, PartController = pt.Controller, PartId = p.PartId, PartZoneId = p.ZoneId, PartContainerElementId = pc.ElementId, AdminPartAction = pt.AdminEditAction, AdminPartController = pt.AdminEditController, PartSectionDescriptor = p.ColSpanDescriptor, RowId = p.RowId }; //// http://stackoverflow.com/questions/9120088/how-to-join-3-tables-with-lambda-expression return viewModelList.ToList(); } private IDictionary<int, List<WebFrameworkPartViewModel>> GetPartViewModelListDictionary(IEnumerable<WebFrameworkPartViewModel> partList) { IDictionary<int, List<WebFrameworkPartViewModel>> rowPartsDictionary = new Dictionary<int, List<WebFrameworkPartViewModel>>(); foreach (WebFrameworkPartViewModel part in partList.OrderBy(p => p.RowId)) { if (rowPartsDictionary.ContainsKey(part.RowId)) { // This row has already been created in the Dict List<WebFrameworkPartViewModel> rowParts = rowPartsDictionary[part.RowId]; //Get the current part list for this row rowParts.Add(part); // Add the new part rowPartsDictionary[part.RowId] = rowParts; //Update the row dict value } else { // This row does NOT exist and must be added List<WebFrameworkPartViewModel> rowParts = new List<WebFrameworkPartViewModel>(); // Create a new list rowParts.Add(part); // The the new part to the new list rowPartsDictionary.Add(part.RowId, rowParts); // Add the new row item to the Dict } } //// TODO: [RP] [23062013] This logic is misplaced - this needs to be in a suitable place - here for now to validate //var rowPartsDictionaryWith3ColSupport = new Dictionary<int, List<WebFrameworkPartViewModel>>(); //foreach (var rowId in rowPartsDictionary.Keys) //{ // if (rowPartsDictionary[rowId].Count == 3) // { // rowPartsDictionaryWith3ColSupport.Add(rowId, SetThreeColumnSectionDescriptors(rowPartsDictionary[rowId])); // } // else // { // rowPartsDictionaryWith3ColSupport.Add(rowId, rowPartsDictionary[rowId]); // } //} return rowPartsDictionary; } private SeoDecorator GetSeo(int pageId) { return this.seoDecoratorService.Get(s => s.PageId == pageId); } //private string GetSectionDescriptor(int colSpan) //{ // switch (colSpan) // { // case 2: // return "two-thirds column"; // case 3: // return "sixteen columns"; // default: // return "one-third column"; // } //} //private List<WebFrameworkPartViewModel> SetThreeColumnSectionDescriptors(List<WebFrameworkPartViewModel> parts) //{ // foreach (var webFrameworkPartViewModel in parts) // { // switch (webFrameworkPartViewModel.PartZoneId) // { // case 2: // webFrameworkPartViewModel.PartSectionDescriptor = "three columns"; // break; // case 4: // webFrameworkPartViewModel.PartSectionDescriptor = "nine columns"; // break; // default: // webFrameworkPartViewModel.PartSectionDescriptor = "four columns"; // break; // } // } // return parts; //} #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Enquiry.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Model { using System; using System.ComponentModel.DataAnnotations; /// <summary> /// The enquiry. /// </summary> public class Enquiry { #region Public Properties /// <summary> /// Gets or sets Address2. /// </summary> public string Address2 { get; set; } /// <summary> /// Gets or sets Address3. /// </summary> public string Address3 { get; set; } /// <summary> /// Gets or sets County. /// </summary> public string County { get; set; } /// <summary> /// Gets or sets DateCreated. /// </summary> public DateTime? DateCreated { get; set; } /// <summary> /// Gets or sets DOB. /// </summary> public DateTime? Dob { get; set; } /// <summary> /// Gets or sets EMail. /// </summary> public string EMail { get; set; } /// <summary> /// Gets or sets EnquiryId. /// </summary> [Key] public int EnquiryId { get; set; } public string FirstName { get; set; } public string FullName { get; set; } /// <summary> /// Gets or sets a value indicating whether HasAcceptedTerms. /// </summary> public bool HasAcceptedTerms { get; set; } /// <summary> /// Gets or sets a value indicating whether IsContactable. /// </summary> public bool IsContactable { get; set; } public string LastName { get; set; } /// <summary> /// Gets or sets PortalId. /// </summary> public int PortalId { get; set; } /// <summary> /// Gets or sets Postcode. /// </summary> public string Postcode { get; set; } /// <summary> /// Gets or sets Street. /// </summary> public string Street { get; set; } /// <summary> /// Gets or sets Telephone. /// </summary> public string Telephone { get; set; } /// <summary> /// Gets or sets Town. /// </summary> public string Town { get; set; } /// <summary> /// Gets or sets UserIP. /// </summary> public string UserIP { get; set; } /// <summary> /// Gets or sets UserId. /// </summary> public int? UserId { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="RoleService.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Service.Implementations { using Firebrick.Data; using Firebrick.Data.RepositoryContracts; using Firebrick.Model; using Firebrick.Service.Contracts; /// <summary> /// The role service. /// </summary> public class RoleService : BaseService<Roles>, IRoleService { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="RoleService"/> class. /// </summary> /// <param name="rolesRepository"> /// The roles repository. /// </param> /// <param name="unitOfWork"> /// The unit of work. /// </param> public RoleService(IRoleRespository rolesRepository, IUnitOfWork unitOfWork) { this.Repository = rolesRepository; this.UnitOfWork = unitOfWork; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="EnquiryRepository.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.EF.Repositories { using Firebrick.Data.RepositoryContracts; using Firebrick.Model; /// <summary> /// The enquiry repository. /// </summary> public class EnquiryRepository : BaseRepository<Enquiry>, IEnquiryRepository { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="EnquiryRepository"/> class. /// Initializes a new instance of the <see cref="DomainRepository"/> class. /// </summary> /// <param name="databaseFactory"> /// The database factory. /// </param> public EnquiryRepository(IDatabaseFactory databaseFactory) : base(databaseFactory) { } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="WebFrameworkControllerFixture.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Web.Tests.Controllers { using System; using System.Linq.Expressions; using System.Web.Mvc; using Firebrick.Data; using Firebrick.Data.RepositoryContracts; using Firebrick.Model; using Firebrick.Service.Implementations; using Firebrick.Test.Helper; using Firebrick.Web.UI.Controllers; using Moq; using Xunit; /// <summary> /// The web framework controller fixture. /// </summary> public class WebFrameworkControllerFixture { #region Constants and Fields private Mock<IClientAssetConfigRepository> clientAssetConfigRepositoryMock; private ClientAssetConfigService clientAssetConfigService; private Mock<IClientAssetRepository> clientAssetRepositoryMock; private ClientAssetService clientAssetService; private Mock<IClientAssetTypeRepository> clientAssetTypeRepositoryMock; private ClientAssetTypeService clientAssetTypeService; /// <summary> /// The domain repository mock. /// </summary> private Mock<IDomainRepository> domainRepositoryMock; private DomainService domainService; private int? pageId; /// <summary> /// The page repository mock. /// </summary> private Mock<IPageRepository> pageRepositoryMock; private PageService pageService; /// <summary> /// The page template repository mock. /// </summary> private Mock<IPageTemplateRepository> pageTemplateRepositoryMock; private PageTemplateService pageTemplateService; /// <summary> /// The page template zone map repository mock. /// </summary> private Mock<IPageTemplateZoneMapRepository> pageTemplateZoneMapRepositoryMock; private PageTemplateZoneMapService pageTemplateZoneMapService; /// <summary> /// The page zone repository mock. /// </summary> private Mock<IPageZoneRepository> pageZoneRepositoryMock; private PageZoneService pageZoneService; private Mock<IPartContainerRepository> partContainerRepositoryMock; private PartContainerService partContainerService; /// <summary> /// The part repository mock. /// </summary> private Mock<IPartRepository> partRepositoryMock; private PartService partService; /// <summary> /// The part type repository mock. /// </summary> private Mock<IPartTypeRepository> partTypeRepositoryMock; private PartTypeService partTypeService; /// <summary> /// The seo decorator repository mock. /// </summary> private Mock<ISeoDecoratorRepository> seoDecoratorRepositoryMock; private SeoDecoratorService seoDecoratorService; /// <summary> /// The user repository mock. /// </summary> private Mock<IUserRepository> userRepositoryMock; private UserService userService; #endregion #region Public Methods [Fact] public void WhenDefaultIndexMethodCalledWithNOPageId_InValidViewModelReturned() { // Arrange this.pageId = null; this.InitializeConstructorParameters(); this.RespositoryMockSetup(); this.InitializeServices(); // Act var controller = new WebFrameworkController( this.domainService, this.clientAssetConfigService, this.clientAssetService, this.clientAssetTypeService, this.pageService, this.pageTemplateService, this.pageTemplateZoneMapService, this.pageZoneService, this.partService, this.partTypeService, this.seoDecoratorService, this.userService, this.partContainerService); // Asserts Assert.Throws<InvalidOperationException>(() => controller.Index((int)this.pageId)); } /// <summary> /// The index. /// </summary> [Fact] public void WhenDefaultIndexMethodCalledWithPageId_ValidViewModelReturned() { // Arrange this.pageId = 1; this.InitializeConstructorParameters(); this.RespositoryMockSetup(); this.InitializeServices(); // Act var controller = new WebFrameworkController( this.domainService, this.clientAssetConfigService, this.clientAssetService, this.clientAssetTypeService, this.pageService, this.pageTemplateService, this.pageTemplateZoneMapService, this.pageZoneService, this.partService, this.partTypeService, this.seoDecoratorService, this.userService, this.partContainerService); // Asserts var viewResult = controller.Index((int)this.pageId) as ViewResult; Assert.NotNull(viewResult); Assert.Equal(string.Empty, viewResult.ViewName); Assert.True(viewResult.ViewData.ModelState.IsValid); Assert.True(controller.ModelState.IsValid); } #endregion #region Methods /// <summary> /// The initialize fixture. /// </summary> private void InitializeConstructorParameters() { this.domainRepositoryMock = new Mock<IDomainRepository>(); this.pageRepositoryMock = new Mock<IPageRepository>(); this.pageTemplateRepositoryMock = new Mock<IPageTemplateRepository>(); this.pageTemplateZoneMapRepositoryMock = new Mock<IPageTemplateZoneMapRepository>(); this.pageZoneRepositoryMock = new Mock<IPageZoneRepository>(); this.partRepositoryMock = new Mock<IPartRepository>(); this.partTypeRepositoryMock = new Mock<IPartTypeRepository>(); this.seoDecoratorRepositoryMock = new Mock<ISeoDecoratorRepository>(); this.userRepositoryMock = new Mock<IUserRepository>(); this.clientAssetTypeRepositoryMock = new Mock<IClientAssetTypeRepository>(); this.clientAssetRepositoryMock = new Mock<IClientAssetRepository>(); this.clientAssetConfigRepositoryMock = new Mock<IClientAssetConfigRepository>(); this.partContainerRepositoryMock = new Mock<IPartContainerRepository>(); } private void InitializeServices() { this.domainService = new DomainService(this.domainRepositoryMock.Object, new Mock<IUnitOfWork>().Object); this.clientAssetConfigService = new ClientAssetConfigService( this.clientAssetConfigRepositoryMock.Object, new Mock<IUnitOfWork>().Object); this.clientAssetService = new ClientAssetService( this.clientAssetRepositoryMock.Object, new Mock<IUnitOfWork>().Object); this.clientAssetTypeService = new ClientAssetTypeService( this.clientAssetTypeRepositoryMock.Object, new Mock<IUnitOfWork>().Object); this.pageService = new PageService(this.pageRepositoryMock.Object, new Mock<IUnitOfWork>().Object); this.pageTemplateService = new PageTemplateService( this.pageTemplateRepositoryMock.Object, new Mock<IUnitOfWork>().Object); this.pageTemplateZoneMapService = new PageTemplateZoneMapService( this.pageTemplateZoneMapRepositoryMock.Object, new Mock<IUnitOfWork>().Object); this.pageZoneService = new PageZoneService( this.pageZoneRepositoryMock.Object, new Mock<IUnitOfWork>().Object); this.partService = new PartService(this.partRepositoryMock.Object, new Mock<IUnitOfWork>().Object); this.partTypeService = new PartTypeService( this.partTypeRepositoryMock.Object, new Mock<IUnitOfWork>().Object); this.seoDecoratorService = new SeoDecoratorService( this.seoDecoratorRepositoryMock.Object, new Mock<IUnitOfWork>().Object); this.userService = new UserService(this.userRepositoryMock.Object, new Mock<IUnitOfWork>().Object); this.partContainerService = new PartContainerService( this.partContainerRepositoryMock.Object, new Mock<IUnitOfWork>().Object); } /// <summary> /// The respository mock setup. /// </summary> private void RespositoryMockSetup() { this.domainRepositoryMock.Setup(repo => repo.Get(It.IsAny<Expression<Func<Domain, bool>>>())).Returns( DefaultModelHelper.DummyPopulatedDomain()); this.pageRepositoryMock.Setup(repo => repo.GetById(It.IsAny<int>())).Returns( DefaultModelHelper.DummyPopulatedPage()); this.pageTemplateRepositoryMock.Setup(repo => repo.GetById(It.IsAny<int>())).Returns( DefaultModelHelper.DummyPopulatedPageTemplate()); this.pageTemplateZoneMapRepositoryMock.Setup(repo => repo.GetById(It.IsAny<int>())).Returns( DefaultModelHelper.DummyPopulatedPageTemplateZoneMap()); this.pageZoneRepositoryMock.Setup(repo => repo.GetById(It.IsAny<int>())).Returns( DefaultModelHelper.DummyPopulatedPageZone()); this.partRepositoryMock.Setup(repo => repo.GetById(It.IsAny<int>())).Returns( DefaultModelHelper.DummyPopulatedPart()); this.partTypeRepositoryMock.Setup(repo => repo.GetById(It.IsAny<int>())).Returns( DefaultModelHelper.DummyPopulatedPartType()); this.seoDecoratorRepositoryMock.Setup(repo => repo.Get(It.IsAny<Expression<Func<SeoDecorator, bool>>>())). Returns(DefaultModelHelper.DummyPopulatedSeoDecorator()); this.userRepositoryMock.Setup(repo => repo.GetById(It.IsAny<int>())).Returns( DefaultModelHelper.DummyPopulatedUser()); } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="EnquiryServiceBinder.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.ServiceBinders.ContentManagement { using System.Net.Mail; using AutoMapper; using Firebrick.Domain.Messaging.EMail; using Firebrick.Domain.ViewModels.ContentManagement.Enquiry; using Firebrick.Entities.Messaging; using Firebrick.Model; using Firebrick.Service.Contracts; using Exception = System.Exception; /// <summary> /// The enquiry service binder. /// </summary> public class EnquiryServiceBinder { #region Constants and Fields /// <summary> /// The content blob service. /// </summary> private readonly IEnquiryService enquiryService; #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="EnquiryServiceBinder"/> class. /// </summary> /// <param name="enquiryService"> /// The EnquiryServiceBinder service. /// </param> public EnquiryServiceBinder(IEnquiryService enquiryService) { this.enquiryService = enquiryService; } #endregion #region Public Methods /// <summary> /// The contact us send. /// </summary> /// <param name="viewModel"> /// The view model. /// </param> /// <returns> /// </returns> public EnquiryContactUsViewModel ContactUsSend(EnquiryContactUsViewModel viewModel) { try { var enquiry = new Enquiry(); Mapper.CreateMap<EnquiryContactUsViewModel, Enquiry>(); Mapper.Map(viewModel, enquiry); this.enquiryService.Add(enquiry); this.SendContactUsEmail(viewModel); } catch (Exception ex) { viewModel.ActionIsSentSuccessful = false; viewModel.ErrorMessage = "There has been a problem processing your request."; viewModel.Exception = ex.Message; } //// If we've got this far - we should be good viewModel.ActionIsSentSuccessful = true; return viewModel; } #endregion #region Methods private void SendContactUsEmail(EnquiryContactUsViewModel viewModel) { var emailConfiguration = new SendEmailConfiguration { ToAddress = "<EMAIL>", SenderAddress = "<EMAIL>", Subject = "Thank you for your enquiry" }; MailMessage email = EMailMessageFactory.GetContactUsEmail(emailConfiguration, viewModel.FullName, viewModel.Telephone, viewModel.EMail, viewModel.Message); EMailClient.SendEMail(email, true); } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="FutureDateAttribute.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Model.Validators { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Firebrick.Domain.Properties; /// <summary> /// The future date attribute. /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public class FutureDateAttribute : ValidationAttribute { #region Methods /// <summary> /// The is valid. /// </summary> /// <param name="value"> /// The value. /// </param> /// <param name="context"> /// The context. /// </param> /// <returns> /// </returns> protected override ValidationResult IsValid(object value, ValidationContext context) { var dateValue = value as DateTime?; var memberNames = new List<string> { context.MemberName }; if (dateValue != null) { if (dateValue.Value.Date < DateTime.UtcNow.Date) { return new ValidationResult(Resources.FutureDateValidationMessage, memberNames); } } return ValidationResult.Success; } #endregion } }<file_sep>namespace Firebrick.Model { using System.ComponentModel.DataAnnotations; public class SeoRouteValue { #region Public Properties public string Key { get; set; } public int SeoDecoratorId { get; set; } [Key] public int SeoRouteValueId { get; set; } public string Value { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="SeoDecoratorInitializer.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.EF.Initializers { using System; using System.Data.Entity.Migrations; using System.Data.Entity.Validation; using System.Diagnostics; using Firebrick.Model; /// <summary> /// The seo initializer. /// </summary> public static class SeoDecoratorInitializer { #region Public Methods /// <summary> /// The add. /// </summary> /// <param name="context"> /// The context. /// </param> public static void Add(FirebrickContext context) { SeoDecorator home = GenericallyComplete(); SeoDecorator about = GenericallyComplete(); SeoDecorator services = GenericallyComplete(); SeoDecorator features = GenericallyComplete(); SeoDecorator contact = GenericallyComplete(); SeoDecorator logon = GenericallyComplete(); home.SeoDecoratorId = 1; home.PageId = 1; home.Title = "Home"; home.Description = "The Home page"; home.FileName = "Home"; home.LookFor = "Home"; home.Keywords = "Home"; about.SeoDecoratorId = 2; about.PageId = 2; about.Title = "About"; about.Description = "The About page"; about.FileName = "About"; about.LookFor = "About"; about.Keywords = "About"; services.SeoDecoratorId = 3; services.PageId = 3; services.Title = "Services"; services.Description = "The Services page"; services.FileName = "Services"; services.LookFor = "Services"; services.Keywords = "Services"; features.SeoDecoratorId = 4; features.PageId = 4; features.Title = "Features"; features.Description = "The Features page"; features.FileName = "Features"; features.LookFor = "Features"; features.Keywords = "Features"; contact.SeoDecoratorId = 5; contact.PageId = 5; contact.Title = "Contact"; contact.Description = "The Contact page"; contact.FileName = "Contact"; contact.LookFor = "Contact"; contact.Keywords = "Contact"; logon.SeoDecoratorId = 6; logon.PageId = 6; logon.Title = "Login"; logon.Description = "The Login page"; logon.FileName = "Login"; logon.LookFor = "Account/Login"; logon.Keywords = "Login"; context.SeoDecorators.AddOrUpdate(home); context.SeoDecorators.AddOrUpdate(about); context.SeoDecorators.AddOrUpdate(services); context.SeoDecorators.AddOrUpdate(features); context.SeoDecorators.AddOrUpdate(contact); context.SeoDecorators.AddOrUpdate(logon); try { context.SaveChanges(); } catch (DbEntityValidationException dbEx) { foreach (DbEntityValidationResult validationErrors in dbEx.EntityValidationErrors) { foreach (DbValidationError validationError in validationErrors.ValidationErrors) { Debug.WriteLine( "Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } } } #endregion #region Methods /// <summary> /// Creates new SeoDecorator with generically comlpeted props /// </summary> /// <returns> /// New Seo Info /// </returns> private static SeoDecorator GenericallyComplete() { var genericProperties = new SeoDecorator(); genericProperties.ChangeFrequency = "monthly"; genericProperties.CreatedDate = DateTime.Now; genericProperties.LastModified = DateTime.Now; genericProperties.LinkType = 1; genericProperties.PortalId = 1; genericProperties.Priority = "0.5"; genericProperties.RobotsFollow = true; genericProperties.RobotsIndex = true; return genericProperties; } #endregion } }<file_sep>namespace Firebrick.Domain.ViewModels.WebAdmin.CmsMenuManager { using System.Collections.Generic; public class TreeNodeViewModel { #region Constructors and Destructors public TreeNodeViewModel() { this.attributes = new Dictionary<string, string>(); } #endregion #region Public Properties public IDictionary<string, string> attributes { get; set; } public bool @checked { get; set; } public List<TreeNodeViewModel> children { get; set; } public string iconCls { get; set; } public int id { get; set; } public string state { get; set; } public string target { get; set; } public string text { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PageZoneInitializer.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.EF.Initializers { using System.Data.Entity.Migrations; using System.Data.Entity.Validation; using System.Diagnostics; using Firebrick.Model; /// <summary> /// The page zone initializer. /// </summary> public static class PageZoneInitializer { #region Public Methods /// <summary> /// The Add. /// </summary> /// <param name="context"> /// The context. /// </param> public static void Add(FirebrickContext context) { var headerZone = new PageZone { PageZoneId = 1, Title = "Header" }; var leftColumn = new PageZone { PageZoneId = 2, Title = "Left Column" }; var rightColumn = new PageZone { PageZoneId = 3, Title = "Right Column" }; var centerColumn = new PageZone { PageZoneId = 4, Title = "Center Column" }; var footerZone = new PageZone { PageZoneId = 5, Title = "Footer" }; context.PageZones.AddOrUpdate(headerZone); context.PageZones.AddOrUpdate(leftColumn); context.PageZones.AddOrUpdate(rightColumn); context.PageZones.AddOrUpdate(centerColumn); context.PageZones.AddOrUpdate(footerZone); try { context.SaveChanges(); } catch (DbEntityValidationException dbEx) { foreach (DbEntityValidationResult validationErrors in dbEx.EntityValidationErrors) { foreach (DbValidationError validationError in validationErrors.ValidationErrors) { Debug.WriteLine( "Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } } } #endregion } }<file_sep>namespace Firebrick.Domain.ViewModels { using System.Collections.Generic; /// <summary> /// The Page Definition /// </summary> public class PageDefinitionViewModel : IPageDefinitionViewModel { #region Public Properties /// <summary> /// Gets or sets TemplateLayoutSrc. /// </summary> public string TemplateLayoutSrc { get; set; } /// <summary> /// Gets or sets ZonePartDictionary. /// </summary> public IDictionary<int, List<PartDefintionViewModel>> ZonePartDictionary { get; set; } #endregion } /// <summary> /// The Page Definition interface /// </summary> internal interface IPageDefinitionViewModel { #region Public Properties /// <summary> /// Gets or sets TemplateLayoutSrc. /// </summary> string TemplateLayoutSrc { get; set; } /// <summary> /// Gets or sets ZonePartDictionary. /// </summary> IDictionary<int, List<PartDefintionViewModel>> ZonePartDictionary { get; set; } #endregion } }<file_sep>namespace Firebrick.Domain.ViewModels.WebAdmin.CmsPlugins { using System.Collections.Generic; public class CmsPluginMainSideMenuViewModelItem { public CmsPluginMainSideMenuViewModelItem() { } #region Public Properties public IEnumerable<CmsPluginMainSideMenuViewModelItem> ChildItems { get; set; } public int ItemId { get; set; } public string Title { get; set; } public string Url { get; set; } #endregion } }<file_sep>namespace Firebrick.UI.Core.Filters { using System.Web.Mvc; using System.Web.Security; public class ValidateUserRoles : FilterAttribute, IAuthorizationFilter { #region Public Methods public void OnAuthorization(AuthorizationContext filterContext) { if (filterContext.HttpContext.Request.IsAuthenticated) { /* * WHEN VIEWING PAGES FROM THE WEBSITE (Not FIREBRICK CMS ADMIN) APPLY THIS LOGIC * * 1. Is the user authenticated? No - Just a plain old visitor * Yes - A visitor and at least most likely a Registered user for example, maybe also a Publisher etc. * 2. If the controller is WebFramework, then check Page Role restrictions * If none exist > show the page, no questions asked * If some do exists > check if the user is first authenticated > if they are not > AUTHORISATION DENIED * If they are authenticated, check the roles they are in > If valid, show page * Otherwise > AUTHORISATION DENIES */ if (!Roles.IsUserInRole("Turnips")) // Administrators { var result = new ViewResult { ViewName = "SecurityError" }; result.ViewBag.ErrorMessage = "You are not authorized to use this page. Please contact an administrator!"; filterContext.Result = result; } /* * So in this test scenario I've added the [ValidateUserRoles] attribute to the default ContactUs action in the Enquiry Controller] * This now means if a user is logged on then check if they are in a given role i.e. Admin * * Now we could apply this filter globally - but do we really want to? * * Ideally if a authenticated user is viewing a part that is outside there role, we ideally just don't want it to load * * The same really for areas of given Admin pages i.e. Not all users should be able to edit/create/delete pages for example * So ideally everything should be role based * * How about having a controller/role definition table... this can specify what controller/actions are available to a given role...? * * However, ideally we want the situation where certain roles, have a precident over other roles... ie. Admin is anything * * Add another block to handle if any processing should happen if the user is not logged in? * * * * OKAY - for the public website in the CMS we could just manage the roles and loading of controls based on the database... * infact we could handle that security in the webframework service binder?? This would be fine for filtering views.. * * However should we still use the authorise attribute when logged in, in terms of pages? - That doesn't make sense * * BUT - for the admin pages we still need to manage various elements that are only viewable to particular roles * We could do this in Razor again? * */ } //else //{ // var result = new ViewResult { ViewName = "SecurityError" }; // result.ViewBag.ErrorMessage = "You are not authenticated. Please log-in and try again!"; // filterContext.Result = result; //} } #endregion } }<file_sep>namespace Firebrick.Model { using System.ComponentModel.DataAnnotations; public class Notification { #region Public Properties ///<summary> ///Gets or sets Description ///</summary> public string Description { get; set; } ///<summary> ///Gets or sets IsViewed ///</summary> public bool IsViewed { get; set; } ///<summary> ///Gets or sets NotificationId ///</summary> [Key] public int NotificationId { get; set; } ///<summary> ///Gets or sets NotificationTypeId ///</summary> public int NotificationTypeId { get; set; } ///<summary> ///Gets or sets UserId ///</summary> public int UserId { get; set; } #endregion } }<file_sep>namespace Firebrick.Model { using System.ComponentModel.DataAnnotations; /// <summary> /// The Role /// </summary> public class Roles { #region Public Properties /// <summary> /// Gets or sets a value indicating whether IsAvailable. /// </summary> public bool IsAvailable { get; set; } /// <summary> /// Gets or sets Name. /// </summary> public string Name { get; set; } /// <summary> /// Gets or sets Order. /// </summary> public int Order { get; set; } /// <summary> /// Gets or sets the identifier for the role. /// </summary> [Key] public int RoleId { get; set; } #endregion } }<file_sep>// ----------------------------------------------------------------------- // <copyright file="SharedAdminMainMenuViewModel.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // ----------------------------------------------------------------------- namespace Firebrick.Domain.ViewModels.WebAdmin.Shared { /// <summary> /// Shared Admin Menu View Model /// </summary> public class SharedAdminMainMenuViewModel { } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ClientAssetService.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Service.Implementations { using Firebrick.Data; using Firebrick.Data.RepositoryContracts; using Firebrick.Model; using Firebrick.Service.Contracts; /// <summary> /// The client asset service. /// </summary> public class ClientAssetService : BaseService<ClientAsset>, IClientAssetService { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="ClientAssetService"/> class. /// </summary> /// <param name="clientAssetRepository"> /// The client asset repository. /// </param> /// <param name="unitOfWork"> /// The unit of work. /// </param> public ClientAssetService(IClientAssetRepository clientAssetRepository, IUnitOfWork unitOfWork) { this.Repository = clientAssetRepository; this.UnitOfWork = unitOfWork; } #endregion } }<file_sep>namespace Firebrick.Web.Tests.Controllers { public class AccountControllerFixture { } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="TextMultilineValidatorAttribute.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.Validators { using System.ComponentModel.DataAnnotations; using Firebrick.Domain.Properties; /// <summary> /// The text multiline validator attribute. /// </summary> public class TextMultilineValidatorAttribute : RegularExpressionAttribute { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="TextMultilineValidatorAttribute"/> class. /// </summary> public TextMultilineValidatorAttribute() : base(Resources.TextMultilineValidatorRegEx) { this.ErrorMessage = Resources.InvalidMultilineInput; } #endregion } }<file_sep>namespace Firebrick.ContentManagement.Web.Controllers { using System.Web.Mvc; using Firebrick.Domain.ServiceBinders.ContentManagement; using Firebrick.Service.Contracts; public class AnalyticsController : Controller { private readonly IAnalyticsAccountService analyticsAccountService; private readonly IPageService pageService; public AnalyticsController(IAnalyticsAccountService analyticsAccountService, IPageService pageService) { this.analyticsAccountService = analyticsAccountService; this.pageService = pageService; } #region Public Methods [ChildActionOnly] public ActionResult GoogleIndividualAccount(int id) { var modelBinder = new AnalyticsServiceBinder(analyticsAccountService, pageService); var viewModel = modelBinder.BindGoogleIndividualAccount(id); return this.PartialView("GoogleIndividualAccount", viewModel); } #endregion } }<file_sep>namespace Firebrick.Model { using System.ComponentModel.DataAnnotations; public class Domain { #region Public Properties [Key] public int DomainId { get; set; } /// <summary> /// Gets or sets HostHeader. /// </summary> public string HostHeader { get; set; } /// <summary> /// Gets or sets PortalId. /// </summary> public int PortalId { get; set; } #endregion } }<file_sep>namespace Firebrick.Service.Implementations { using Firebrick.Data; using Firebrick.Data.RepositoryContracts; using Firebrick.Model; using Firebrick.Service.Contracts; public class SeoRouteValueService : BaseService<SeoRouteValue>, ISeoRouteValueService { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="SeoRouteValueService"/> class. /// </summary> /// <param name="seoRouteValueRepository"> /// The user repository. /// </param> /// <param name="unitOfWork"> /// The unit of work. /// </param> public SeoRouteValueService(ISeoRouteValueRepository seoRouteValueRepository, IUnitOfWork unitOfWork) { this.Repository = seoRouteValueRepository; this.UnitOfWork = unitOfWork; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Portal.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Model { using System.ComponentModel.DataAnnotations; /// <summary> /// The web site. /// </summary> public class Portal { #region Public Properties /// <summary> /// Gets or sets AssetImageDomainId. /// </summary> public int AssetImageDomainId { get; set; } /// <summary> /// Gets or sets AssetScriptDomainId. /// </summary> public int AssetScriptDomainId { get; set; } /// <summary> /// Gets or sets AssetStyleDomainId. /// </summary> public int AssetStyleDomainId { get; set; } /// <summary> /// Gets or sets CopyrightName. /// </summary> public string CopyrightName { get; set; } /// <summary> /// Gets or sets FavIcon. /// </summary> public string FavIcon { get; set; } /// <summary> /// Gets or sets ParentId. /// </summary> public int ParentPortalId { get; set; } /// <summary> /// Gets or sets Id. /// </summary> [Key] public int PortalId { get; set; } /// <summary> /// Gets or sets PrimaryDomainId. /// </summary> public int PrimaryDomainId { get; set; } /// <summary> /// Gets or sets PrimaryMobileDomainId. /// </summary> public int PrimaryMobileDomainId { get; set; } /// <summary> /// Gets or sets Theme. /// </summary> public string Theme { get; set; } /// <summary> /// Gets or sets Title. /// </summary> public string Title { get; set; } #endregion } }<file_sep>namespace Firebrick.Data.RepositoryContracts { using Firebrick.Model; public interface IAnalyticsTypeRepository : IRepository<AnalyticsType> { } }<file_sep>namespace Firebrick.Web.UI.UI { using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.WebPages; using System.Web.Routing; using Firebrick.Data.EF.Initializers; using Firebrick.UI.Core.UnityExtensions; using Firebrick.UI.Core.Logging; using log4net.Config; using Microsoft.Practices.ServiceLocation; using Microsoft.Practices.Unity; // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { #region Constants and Fields /// <summary> /// The container. /// </summary> private static IUnityContainer container; /// <summary> /// logging service member variable /// </summary> private ILoggingService loggingService; /// <summary> /// Gets or sets the logging service /// </summary> protected ILoggingService LoggingService { get { return this.loggingService ?? (this.loggingService = new LoggingService()); } set { this.loggingService = value; } } #endregion #region Public Methods /// <summary> /// The init. /// </summary> public override void Init() { this.EndRequest += this.EndRequestHandler; base.Init(); } #endregion #region Methods protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); WebApiConfig.Register(GlobalConfiguration.Configuration); RouteConfig.RegisterRoutes(RouteTable.Routes); //// TODO: [RP] [061112] Check out Bundles //// BundleConfig.RegisterBundles(BundleTable.Bundles); this.InitializeLogging(); this.InitializeDatabase(); //// TODO: [RP] [18052013] Does this need to be turned off if DB Exists? this.InitializeDependencyInjectionContainer(); //// TODO: [RP] [28032013] >> This should now pick up i.e. Index.WindowsPhone.cshtml rather than the default Index.Mobile.cshtml for example DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("WindowsPhone") { ContextCondition = (context => context.Request.UserAgent != null && context.Request.UserAgent.IndexOf("Windows Phone OS", StringComparison.OrdinalIgnoreCase) >= 0) }); //// http://www.hanselman.com/blog/MakingASwitchableDesktopAndMobileSiteWithASPNETMVC4AndJQueryMobile.aspx //// TODO: [RP] [22032013] ?? To enable default mobile view, you must add the following line as the last line in the Application_Start method in Global.asax.cs: BundleMobileConfig.RegisterBundles(BundleTable.Bundles); } protected void Application_Error(object sender, EventArgs e) { Exception ex = Server.GetLastError().GetBaseException(); var logService = this.LoggingService; logService.Fatal(ex.Message, ex); } /// <summary> /// The end request handler. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> private void EndRequestHandler(object sender, EventArgs e) { // This is a workaround since subscribing to HttpContext.Current.ApplicationInstance.EndRequest // from HttpContext.Current.ApplicationInstance.BeginRequest does not work. IEnumerable<UnityHttpContextPerRequestLifetimeManager> perRequestManagers = container.Registrations.Select(r => r.LifetimeManager).OfType<UnityHttpContextPerRequestLifetimeManager>().ToArray(); foreach (UnityHttpContextPerRequestLifetimeManager manager in perRequestManagers) { manager.Dispose(); } } /// <summary> /// The initialize database. /// </summary> private void InitializeDatabase() { System.Data.Entity.Database.SetInitializer(new RepositoryInitializer()); } /// <summary> /// The initialize dependency injection container. /// </summary> private void InitializeDependencyInjectionContainer() { container = new UnityContainerFactory().CreateConfiguredContainer(); var serviceLocator = new UnityServiceLocator(container); ServiceLocator.SetLocatorProvider(() => serviceLocator); DependencyResolver.SetResolver(new UnityDependencyResolver(container)); } /// <summary> /// The initialize logging. /// </summary> private void InitializeLogging() { XmlConfigurator.Configure(); } #endregion } }<file_sep>namespace Firebrick.Data.RepositoryContracts { using Firebrick.Model; public interface IRolePageRestrictionRepository : IRepository<RolePageRestriction> { } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PartInitializer.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.EF.Initializers { using System.Data.Entity.Migrations; using System.Data.Entity.Validation; using System.Diagnostics; using Firebrick.Model; /// <summary> /// The part initializer. /// </summary> public static class PartInitializer { #region Public Methods /// <summary> /// The Add. /// </summary> /// <param name="context"> /// The context. /// </param> public static void Add(FirebrickContext context) { context.Parts.AddOrUpdate( new Part { PartId = 1, PageId = 1, PartTypeId = 1, Title = "Home Text 1A", ZoneId = 2, PartContainerId = 1, Order = 10, ColSpan = 1, RowId = 1, ColSpanDescriptor = "one-third column" }); context.Parts.AddOrUpdate( new Part { PartId = 2, PageId = 1, PartTypeId = 1, Title = "Home Text 1B", ZoneId = 4, PartContainerId = 1, Order = 20, ColSpan = 1, RowId = 1, ColSpanDescriptor = "one-third column" }); context.Parts.AddOrUpdate( new Part { PartId = 3, PageId = 1, PartTypeId = 1, Title = "Home Text 1C", ZoneId = 3, PartContainerId = 1, Order = 40, ColSpan = 1, RowId = 1, ColSpanDescriptor = "one-third column" }); context.Parts.AddOrUpdate( new Part { PartId = 4, PageId = 1, PartTypeId = 1, Title = "Home Text 2", ZoneId = 2, PartContainerId = 1, Order = 40, ColSpan = 3, RowId = 2, ColSpanDescriptor = "sixteen columns" }); context.Parts.AddOrUpdate( new Part { PartId = 5, PageId = 1, PartTypeId = 1, Title = "Home Text 3A", ZoneId = 2, PartContainerId = 1, Order = 50, ColSpan = 1, RowId = 3, ColSpanDescriptor = "one-third column" }); context.Parts.AddOrUpdate( new Part { PartId = 6, PageId = 1, PartTypeId = 1, Title = "Home Text 3B", ZoneId = 4, PartContainerId = 1, Order = 60, ColSpan = 1, RowId = 3, ColSpanDescriptor = "one-third column" }); context.Parts.AddOrUpdate( new Part { PartId = 7, PageId = 1, PartTypeId = 1, Title = "Home Text 3C", ZoneId = 3, PartContainerId = 1, Order = 70, ColSpan = 1, RowId = 3, ColSpanDescriptor = "one-third column" }); context.Parts.AddOrUpdate( new Part { PartId = 8, PageId = 5, PartTypeId = 1, Title = "Contact 1", ZoneId = 2, PartContainerId = 1, Order = 10, ColSpan = 3, RowId = 1, ColSpanDescriptor = "sixteen columns" }); context.Parts.AddOrUpdate( new Part { PartId = 9, PageId = 5, PartTypeId = 1, Title = "Contact 2A", ZoneId = 3, PartContainerId = 1, Order = 20, ColSpan = 1, RowId = 2, ColSpanDescriptor = "one-third column" }); context.Parts.AddOrUpdate( new Part { PartId = 10, PageId = 5, PartTypeId = 3, Title = "Contact 2B", ZoneId = 4, PartContainerId = 1, Order = 30, ColSpan = 2, RowId = 2, ColSpanDescriptor = "two-thirds column" }); context.Parts.AddOrUpdate( new Part { PartId = 11, PageId = 2, PartTypeId = 1, Title = "About 1A", ZoneId = 2, PartContainerId = 1, Order = 10, ColSpan = 2, RowId = 1, ColSpanDescriptor = "two-thirds column" }); context.Parts.AddOrUpdate( new Part { PartId = 12, PageId = 2, PartTypeId = 1, Title = "About 1B", ZoneId = 3, PartContainerId = 1, Order = 20, ColSpan = 1, RowId = 1, ColSpanDescriptor = "one-third column" }); context.Parts.AddOrUpdate( new Part { PartId = 13, PageId = 2, PartTypeId = 1, Title = "About Text 2A", ZoneId = 2, PartContainerId = 1, Order = 40, ColSpan = 1, RowId = 2, ColSpanDescriptor = "one-third column" }); context.Parts.AddOrUpdate( new Part { PartId = 14, PageId = 2, PartTypeId = 1, Title = "About Text 2B", ZoneId = 4, PartContainerId = 1, Order = 50, ColSpan = 1, RowId = 2, ColSpanDescriptor = "one-third column" }); context.Parts.AddOrUpdate( new Part { PartId = 15, PageId = 2, PartTypeId = 1, Title = "About Text 2C", ZoneId = 3, PartContainerId = 1, Order = 60, ColSpan = 1, RowId = 2, ColSpanDescriptor = "one-third column" }); context.Parts.AddOrUpdate( new Part { PartId = 16, PageId = 4, PartTypeId = 1, Title = "Features Text 1A", ZoneId = 2, PartContainerId = 1, Order = 10, ColSpan = 1, RowId = 1, ColSpanDescriptor = "three columns" }); context.Parts.AddOrUpdate( new Part { PartId = 17, PageId = 4, PartTypeId = 1, Title = "Features Text 1B", ZoneId = 4, PartContainerId = 1, Order = 20, ColSpan = 1, RowId = 1, ColSpanDescriptor = "nine columns" }); context.Parts.AddOrUpdate( new Part { PartId = 18, PageId = 4, PartTypeId = 1, Title = "Features Text 1C", ZoneId = 3, PartContainerId = 1, Order = 30, ColSpan = 1, RowId = 1, ColSpanDescriptor = "four columns" }); context.Parts.AddOrUpdate( new Part { PartId = 19, PageId = 3, PartTypeId = 1, Title = "Services 1A", ZoneId = 2, PartContainerId = 1, Order = 10, ColSpan = 2, RowId = 1, ColSpanDescriptor = "" }); context.Parts.AddOrUpdate( new Part { PartId = 20, PageId = 3, PartTypeId = 1, Title = "Services 1B", ZoneId = 4, PartContainerId = 1, Order = 20, ColSpan = 1, RowId = 1, ColSpanDescriptor = "" }); try { context.SaveChanges(); } catch (DbEntityValidationException dbEx) { foreach (DbEntityValidationResult validationErrors in dbEx.EntityValidationErrors) { foreach (DbValidationError validationError in validationErrors.ValidationErrors) { Debug.WriteLine( "Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } } } #endregion } }<file_sep>$('a[href$="@Request.Url.LocalPath"]').parent().addClass('current'); <file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IUserRepository.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.RepositoryContracts { using System.Collections.Generic; using Firebrick.Model; /// <summary> /// The i user repository. /// </summary> public interface IUserRepository : IRepository<User> { #region Public Methods /// <summary> /// The assign role. /// </summary> /// <param name="userName"> /// The user name. /// </param> /// <param name="roleName"> /// The role name. /// </param> void AssignRole(string userName, List<string> roleName); /// <summary> /// </summary> /// <param name="userName"> /// The user name. /// </param> /// <param name="password"> /// The password. /// </param> /// <returns> /// </returns> bool AuthenticateUser(string userName, string password); #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="WebAdmin.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.Helpers.Route { /// <summary> /// The web admin. /// </summary> public static class WebAdmin { #region Public Properties /// <summary> /// Gets AdminDashboard. /// </summary> public static string AdminDashboard { get { return "/CmsDashboard"; } } /// <summary> /// Gets AdminPageAddNew. /// </summary> public static string AdminPageAddNew { get { return "/CmsPageManager/Add"; } } /// <summary> /// Gets AdminPageEdit. /// </summary> public static string AdminPageEdit { get { return "CmsPageManager/Edit/{0}"; } } /// <summary> /// Gets AdminPageList. /// </summary> public static string AdminPageList { get { return "/CmsPageManager"; } } /// <summary> /// Gets AdminUserList. /// </summary> public static string AdminUserList { get { return "/CmsUserManager"; } } /// <summary> /// Gets AdminUserEdit. /// </summary> public static string AdminUserEdit { get { return "CmsUserManager/Edit/{0}"; } } /// <summary> /// Gets AdminUserAddNew. /// </summary> public static string AdminUserAddNew { get { return "/CmsUserManager/Add"; } } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="WebAdmin.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.Helpers.PartialViews { /// <summary> /// The web admin. /// </summary> public static class AdditionalInfo { #region Public Properties /// <summary> /// Gets AdminDashboard. /// </summary> public static string Default { get { return "AdditionalInfo"; } } /// <summary> /// Gets AdminPageAddNew. /// </summary> public static string PageEdit { get { return "AdditionalInfoPage"; } } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Configuration.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.EF.Migrations { using System.Data.Entity; using System.Data.Entity.Migrations; using Firebrick.Data.EF.Initializers; //public sealed class Configuration : CreateDatabaseIfNotExists<FirebrickContext> //public sealed class Configuration : DbMigrationsConfiguration<FirebrickContext> /// <summary> /// The configuration. /// </summary> public sealed class Configuration : DbMigrationsConfiguration<FirebrickContext> { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="Configuration"/> class. /// </summary> public Configuration() { this.AutomaticMigrationsEnabled = true; } #endregion #region Methods /// <summary> /// The seed. /// </summary> /// <param name="context"> /// The context. /// </param> protected override void Seed(FirebrickContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "<NAME>" }, // new Person { FullName = "<NAME>" }, // new Person { FullName = "<NAME>" } // ); DomainInitializer.Add(context); PortalInitializer.Add(context); RoleInitializer.Add(context); UserInitializer.Add(context); UserRoleInitializer.Add(context); PageZoneInitializer.Add(context); PageTemplateInitializer.Add(context); PageTemplateZoneMapInitializer.Add(context); PartContainerInitializer.Add(context); PartTypeInitializer.Add(context); PageInitializer.Add(context); SeoDecoratorInitializer.Add(context); SeoRouteValueInitializer.Add(context); PartInitializer.Add(context); ContentInitializer.Add(context); PageControllerActionInitializer.Add(context); ClientAssetInitializer.Add(context); RoleRestrictionsInitializer.Add(context); AnalyticsInitializer.Add(context); } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PageTemplateInitializer.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.EF.Initializers { using System.Data.Entity.Migrations; using System.Data.Entity.Validation; using System.Diagnostics; using Firebrick.Model; /// <summary> /// The page template initializer. /// </summary> public static class PageTemplateInitializer { #region Public Methods /// <summary> /// The add. /// </summary> /// <param name="context"> /// The context. /// </param> public static void Add(FirebrickContext context) { var defaultTemplate = new PageTemplate { PageTemplateId = 1, Title = "Small Head [Grey Matter]", LayoutTemplateSrc = "~/Content/themes/new-grey-matter/Layouts/_Layout.cshtml" }; var bigHeadTemplate = new PageTemplate { PageTemplateId = 2, Title = "Big Head [Grey Matter]", LayoutTemplateSrc = "~/Content/themes/new-grey-matter/Layouts/_LayoutBigHead.cshtml" }; context.PageTemplates.AddOrUpdate(defaultTemplate); context.PageTemplates.AddOrUpdate(bigHeadTemplate); try { context.SaveChanges(); } catch (DbEntityValidationException dbEx) { foreach (DbEntityValidationResult validationErrors in dbEx.EntityValidationErrors) { foreach (DbValidationError validationError in validationErrors.ValidationErrors) { Debug.WriteLine( "Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } } } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IPartService.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Service.Contracts { using System.Collections.Generic; using Firebrick.Model; /// <summary> /// The i web part service. /// </summary> public interface IPartService : IService<Part> { #region Public Methods /// <summary> /// </summary> /// <param name="pageId"> /// The page id. /// </param> /// <param name="zoneId"> /// The zone id. /// </param> /// <param name="partTypeId"> /// The part Type Id. /// </param> /// <returns> /// </returns> Part Get(int pageId, int zoneId, int partTypeId); /// <summary> /// </summary> /// <param name="pageId"> /// The page id. /// </param> /// <returns> /// </returns> IEnumerable<Part> GetManyByPageId(int pageId); int GetNextOrderId(int pageId, int zoneId); #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ContentInitializer.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.EF.Initializers { using System.Data.Entity.Migrations; using System.Data.Entity.Validation; using System.Diagnostics; using Firebrick.Model; /// <summary> /// The content initializer. /// </summary> public static class ContentInitializer { private const string AboutText1 = @"<div class='two-thirds column'> <img src='http://placehold.it/620x170'> </div> <div class='one-third column'> <p> Vivamus imperdiet enim a metus hendrerit bibendum. Aenean at arcu id urna eleifend tristique. Mauris nec vehicula nulla, quis ultricies est. Integer adipiscing massa vel faucibus luctus? Mauris lacinia bibendum volutpat. </p> <p> Vivamus imperdiet enim a metus hendrerit bibendum. Aenean at arcu id urna eleifend tristique. Mauris nec vehicula nulla, quis ultricies est. Integer adipiscing massa vel faucibus luctus? Mauris lacinia bibendum volutpat. </p> </div> <div class='clear'></div> <hr />"; private const string AboutText2 = @" <div class='four columns'> <img src='http://placehold.it/220x170'> <h3>Managing Director</h3> <p>Nam feugiat metus id orci gravida, vitae suscipit nunc elementum. Quisque metus.</p> <p><i class='icon-phone'></i><a href='tel:01242 999 999'>01242 999 999</a></p> <p><i class='icon-envelope'></i><a href='mailto:<EMAIL>'><EMAIL></a></p> </div> <div class='four columns'> <img src='http://placehold.it/220x170'> <h3>Financial Director</h3> <p>Nam feugiat metus id orci gravida, vitae suscipit nunc elementum. Quisque metus.</p> <p><i class='icon-phone'></i><a href='tel:01242 999 999'>01242 999 999</a></p> <p><i class='icon-envelope'></i><a href='mailto:<EMAIL>'><EMAIL></a></p> </div> <div class='four columns'> <img src='http://placehold.it/220x170'> <h3>Supply Chain</h3> <p>Nam feugiat metus id orci gravida, vitae suscipit nunc elementum. Quisque metus.</p> <p><i class='icon-phone'></i><a href='tel:01242 999 999'>01242 999 999</a></p> <p><i class='icon-envelope'></i><a href='mailto:<EMAIL>'><EMAIL></a></p> </div> <div class='four columns'> <img src='http://placehold.it/220x170'> <h3>Associate</h3> <p>Nam feugiat metus id orci gravida, vitae suscipit nunc elementum. Quisque metus.</p> <p><i class='icon-phone'></i><a href='tel:01242 999 999'>01242 999 999</a></p> <p><i class='icon-envelope'></i><a href='mailto:<EMAIL>'><EMAIL></a></p> </div> "; private const string HomeText1A = @"<article> <img src='http://placehold.it/300x150'> <h2>Clients</h2> <p>Nulla in lacus laoreet, commodo quam nec, auctor lectus. Phasellus sit amet aliquam lorem. Mauris et ligula est. Donec consequat orci at nibh posuere.</p> </article>"; private const string HomeText1B = @"<article> <img src='http://placehold.it/300x150'> <h2>Clients</h2> <p>Nulla in lacus laoreet, commodo quam nec, auctor lectus. Phasellus sit amet aliquam lorem. Mauris et ligula est. Donec consequat orci at nibh posuere.</p> </article>"; private const string HomeText1C = @"<article> <img src='http://placehold.it/300x150'> <h2>Clients</h2> <p>Nulla in lacus laoreet, commodo quam nec, auctor lectus. Phasellus sit amet aliquam lorem. Mauris et ligula est. Donec consequat orci at nibh posuere.</p> </article>"; private const string HomeText2 = @"<p class='slogan'>ASP.NET // MVC // HTML 5 // CSS 3</p>"; private const string HomeText3A = @" <i class='icon-shield icon-5x'></i> <p>Nulla mi eros, consectetur eu aliquam ut, iaculis ac nulla. Etiam pretium diam dui, sed blandit sed.</p>"; private const string HomeText3B = @" <i class='icon-shield icon-5x'></i> <p>Nulla mi eros, consectetur eu aliquam ut, iaculis ac nulla. Etiam pretium diam dui, sed blandit sed.</p>"; private const string HomeText3C = @" <i class='icon-shield icon-5x'></i> <p>Nulla mi eros, consectetur eu aliquam ut, iaculis ac nulla. Etiam pretium diam dui, sed blandit sed.</p>"; private const string Contact1 = "<iframe width='940' height='350' frameborder='0' scrolling='no' marginheight='0' marginwidth='0' src='https://maps.google.co.uk/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=&amp;q=cheltenham&amp;aq=&amp;sll=52.8382,-2.327815&amp;sspn=8.883892,26.784668&amp;ie=UTF8&amp;hq=&amp;hnear=Cheltenham,+Gloucestershire,+United+Kingdom&amp;t=m&amp;ll=51.927543,-2.067833&amp;spn=0.074099,0.322723&amp;z=12&amp;iwloc=A&amp;output=embed'></iframe>"; private const string Contact2A = @"<h2>Enquire</h2><p>Maecenas enim tellus, mollis a molestie quis; auctor sed tellus. Etiam facilisis hendrerit arcu, et blandit sapien vestibulum ac? Morbi quis est amet.</p>"; private const string About1A = "<img src='http://placehold.it/620x170'>"; private const string About1B = @"<p>Vivamus imperdiet enim a metus hendrerit bibendum. Aenean at arcu id urna eleifend tristique. Mauris nec vehicula nulla, quis ultricies est. Integer adipiscing massa vel faucibus luctus? Mauris lacinia bibendum volutpat. </p> <p> Vivamus imperdiet enim a metus hendrerit bibendum. Aenean at arcu id urna eleifend tristique. Mauris nec vehicula nulla, quis ultricies est. Integer adipiscing massa vel faucibus luctus? Mauris lacinia bibendum volutpat. </p>"; private const string About2A = @" <img src='http://placehold.it/220x170'> <h3>Managing Director</h3> <p>Nam feugiat metus id orci gravida, vitae suscipit nunc elementum. Quisque metus.</p> <p><i class='icon-phone'></i><a href='tel:01242 999 999'>01242 999 999</a></p> <p><i class='icon-envelope'></i><a href='mailto:<EMAIL>'><EMAIL></a></p>"; private const string About2B = @" <img src='http://placehold.it/220x170'> <h3>Finance Director</h3> <p>Nam feugiat metus id orci gravida, vitae suscipit nunc elementum. Quisque metus.</p> <p><i class='icon-phone'></i><a href='tel:01242 999 999'>01242 999 999</a></p> <p><i class='icon-envelope'></i><a href='mailto:<EMAIL>'><EMAIL></a></p>"; private const string About2C = @" <img src='http://placehold.it/220x170'> <h3>Associate</h3> <p>Nam feugiat metus id orci gravida, vitae suscipit nunc elementum. Quisque metus.</p> <p><i class='icon-phone'></i><a href='tel:01242 999 999'>01242 999 999</a></p> <p><i class='icon-envelope'></i><a href='mailto:<EMAIL>'><EMAIL></a></p>"; private const string Features1A = @" <ul> <li><a href='#'>Bullet One</a></li> <li><a href='#'>Bullet Two</a></li> <li><a href='#'>Bullet Three</a></li> <li><a href='#'>Bullet Four</a></li> </ul>"; private const string Features1B = @"<p> Donec venenatis dolor sit amet sapien sollicitudin, semper consequat sem laoreet? Pellentesque porta pharetra nisi a fermentum. Proin vitae dui ac libero mattis tincidunt. Integer sodales ante ipsum, id tristique elit tincidunt et. Vestibulum ac dui non ipsum semper lobortis! Cras luctus consectetur arcu vel tempus. Maecenas malesuada venenatis dapibus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc a nulla et neque ultricies suscipit congue ac nisl? Nullam porta sit amet justo sit amet tempor. </p> <img src='http://placehold.it/580x150'> <p> Vivamus posuere porttitor viverra. Maecenas ullamcorper felis ipsum, vitae sollicitudin libero scelerisque ac! Nulla facilisi. Praesent congue mauris metus; sit amet ultricies nisl condimentum eget. Vestibulum mattis convallis nisi. Donec magna urna, porta volutpat aliquet et, vestibulum eget nunc! Nulla facilisi. Vivamus varius, sapien eget accumsan varius, est lorem commodo sem, a condimentum erat quam quis turpis. Maecenas pellentesque nisi vel libero cursus mollis. Ut rutrum libero leo, ut commodo mauris placerat quis. Nulla interdum accumsan consequat. Donec aliquam, metus non pharetra dictum; mi eros euismod velit, ut fringilla nibh eros quis sapien. </p>"; private const string Features1C = @"<p>Etiam mattis felis in elementum consequat? Vivamus pulvinar vel ante sit amet auctor. Nulla eget pharetra nunc. Vestibulum sollicitudin tempor libero nec rhoncus. Donec venenatis neque et odio bibendum, eget turpis duis.</p> "; private const string Services1A = @" <img src='http://placehold.it/620x350'> <h2>Article One</h2> <p>Sed tristique nibh quis mi hendrerit lacinia. Nullam ullamcorper felis ut ante semper quis auctor ante venenatis. Nam rhoncus euismod hendrerit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam nec dolor vitae neque semper aliquet sed et nibh. Cras quis libero quis urna commodo vulputate. Integer lacinia erat gravida nibh aliquam lobortis. Nunc urna arcu, dapibus a egestas non, ultricies a nibh. Aenean turpis purus, mattis non adipiscing malesuada, placerat in justo. Proin eu nibh eget odio imperdiet dictum eget eu quam. Proin vestibulum leo nec eros rutrum nec vulputate mauris volutpat. Integer a nisi sed felis venenatis consequat. Suspendisse quis tellus mi.</p> <p>In laoreet venenatis ultricies. Nunc ac ipsum eget ante porta consectetur id non libero. Sed sed sem vitae metus mattis porta. Sed euismod risus quis sem gravida bibendum. Fusce mi quam, pharetra quis pretium vitae, laoreet non eros. Nullam fermentum lobortis pretium. Sed non condimentum nisl. Mauris bibendum facilisis tempus. Ut felis nulla, auctor quis pretium sit amet, rhoncus ut felis. Integer quis mi vitae libero gravida vulputate ac ac erat. Maecenas et orci pharetra felis imperdiet bibendum sit amet sit amet sem. Sed velit tortor, luctus id placerat at, posuere nec nibh. Mauris semper rutrum dolor vel ultricies.</p> "; private const string Services2B = @" <p>Vivamus imperdiet enim a metus hendrerit bibendum. Aenean at arcu id urna eleifend tristique. Mauris nec vehicula nulla, quis ultricies est. Integer adipiscing massa vel faucibus luctus? Mauris lacinia bibendum volutpat.</p> <p>Vivamus imperdiet enim a metus hendrerit bibendum. Aenean at arcu id urna eleifend tristique. Mauris nec vehicula nulla, quis ultricies est.</p> "; #region Public Methods /// <summary> /// The Add. /// </summary> /// <param name="context"> /// The context. /// </param> public static void Add(FirebrickContext context) { context.ContentBlobs.AddOrUpdate(new ContentBlob { Html = HomeText1A, ContentBlobId = 1, PartId = 1 }); context.ContentBlobs.AddOrUpdate(new ContentBlob { Html = HomeText1B, ContentBlobId = 2, PartId = 2 }); context.ContentBlobs.AddOrUpdate(new ContentBlob { Html = HomeText1C, ContentBlobId = 3, PartId = 3 }); context.ContentBlobs.AddOrUpdate(new ContentBlob { Html = HomeText2, ContentBlobId = 4, PartId = 4 }); context.ContentBlobs.AddOrUpdate(new ContentBlob { Html = HomeText3A, ContentBlobId = 5, PartId = 5 }); context.ContentBlobs.AddOrUpdate(new ContentBlob { Html = HomeText3B, ContentBlobId = 6, PartId = 6 }); context.ContentBlobs.AddOrUpdate(new ContentBlob { Html = HomeText3C, ContentBlobId = 7, PartId = 7 }); context.ContentBlobs.AddOrUpdate(new ContentBlob { Html = Contact1, ContentBlobId = 8, PartId = 8 }); context.ContentBlobs.AddOrUpdate(new ContentBlob { Html = Contact2A, ContentBlobId = 9, PartId = 9 }); context.ContentBlobs.AddOrUpdate(new ContentBlob { Html = About1A, ContentBlobId = 10, PartId = 11 }); context.ContentBlobs.AddOrUpdate(new ContentBlob { Html = About1B, ContentBlobId = 11, PartId = 12 }); context.ContentBlobs.AddOrUpdate(new ContentBlob { Html = About2A, ContentBlobId = 12, PartId = 13 }); context.ContentBlobs.AddOrUpdate(new ContentBlob { Html = About2B, ContentBlobId = 13, PartId = 14 }); context.ContentBlobs.AddOrUpdate(new ContentBlob { Html = About2C, ContentBlobId = 14, PartId = 15 }); context.ContentBlobs.AddOrUpdate(new ContentBlob { Html = Features1A, ContentBlobId = 15, PartId = 16 }); context.ContentBlobs.AddOrUpdate(new ContentBlob { Html = Features1B, ContentBlobId = 16, PartId = 17 }); context.ContentBlobs.AddOrUpdate(new ContentBlob { Html = Features1C, ContentBlobId = 17, PartId = 18 }); context.ContentBlobs.AddOrUpdate(new ContentBlob { Html = Services1A, ContentBlobId = 18, PartId = 19 }); context.ContentBlobs.AddOrUpdate(new ContentBlob { Html = Services2B, ContentBlobId = 19, PartId = 20 }); try { context.SaveChanges(); } catch (DbEntityValidationException dbEx) { foreach (DbEntityValidationResult validationErrors in dbEx.EntityValidationErrors) { foreach (DbValidationError validationError in validationErrors.ValidationErrors) { Debug.WriteLine( "Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } } } #endregion } }<file_sep>namespace Firebrick.Model { using System.ComponentModel.DataAnnotations; public class RolePartRestriction { #region Public Properties public bool IsAdminEditable { get; set; } public bool IsEditable { get; set; } public bool IsViewable { get; set; } public int PartId { get; set; } public int RoleId { get; set; } [Key] public int RolePartRestrictionId { get; set; } #endregion } }<file_sep>namespace Firebrick.Service.Implementations { using Firebrick.Data; using Firebrick.Data.RepositoryContracts; using Firebrick.Model; using Firebrick.Service.Contracts; public class RolePartRestrictionService : BaseService<RolePartRestriction>, IRolePartRestrictionService { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="RolePartRestrictionService"/> class. /// </summary> /// <param name="rolePartRestrictionRepository"> /// The domainrepository. /// </param> /// <param name="unitOfWork"> /// The unit of work. /// </param> public RolePartRestrictionService( IRolePartRestrictionRepository rolePartRestrictionRepository, IUnitOfWork unitOfWork) { this.Repository = rolePartRestrictionRepository; this.UnitOfWork = unitOfWork; } #endregion } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; namespace Firebrick.Domain.ViewModels.WebAdmin.CmsUserManager { public abstract class CmsUserManagerBaseViewModel { public abstract string ActionCancelUrl { get; } public int UserId { get; set; } [Required] public string UserName { get; set; } /// <summary> /// Gets or sets Postcode. /// </summary> public string Postcode { get; set; } /// <summary> /// Gets or sets Street. /// </summary> public string Street { get; set; } /// <summary> /// Gets or sets Telephone. /// </summary> public string Telephone { get; set; } /// <summary> /// Gets or sets Town. /// </summary> public string Town { get; set; } [Required] public string LastName { get; set; } public string JobTitle { get; set; } [Required] [MaxLength(250, ErrorMessage = "Email length must be 250 characters or less")] [MinLength(5)] public string EMail { get; set; } [Required] public string FirstName { get; set; } public DateTime? Dob { get; set; } [Required] [MaxLength(10, ErrorMessage = "Email length must be 10 characters or less")] [MinLength(3)] public string DisplayName { get; set; } /// <summary> /// Gets or sets Address2. /// </summary> public string Address2 { get; set; } /// <summary> /// Gets or sets Address3. /// </summary> public string Address3 { get; set; } /// <summary> /// Gets or sets the country for the user. /// </summary> public string Country { get; set; } /// <summary> /// Gets or sets County. /// </summary> public string County { get; set; } } } <file_sep>namespace Firebrick.Domain.ViewModels { using Firebrick.Model; public class PartDefintionViewModel : IPartDefintionViewModel { #region Public Properties public Part Part { get; set; } public PartType PartType { get; set; } #endregion } internal interface IPartDefintionViewModel { #region Public Properties Part Part { get; set; } PartType PartType { get; set; } #endregion } }<file_sep>namespace Firebrick.Admin.Web.Controllers { using System; using System.Web.Mvc; using Firebrick.Domain.ServiceBinders.WebAdmin; using Firebrick.Domain.ViewModels.WebAdmin.CmsPortalManager; using Firebrick.Service.Contracts; using Firebrick.UI.Core.Controllers; public class CmsPortalManagerController : BaseAdminController { #region Constants and Fields /// <summary> /// The part service. /// </summary> private readonly IAnalyticsAccountService analyticsAccountService; /// <summary> /// The page template service /// </summary> private readonly IDomainService domainService; /// <summary> /// The page service. /// </summary> private readonly IPortalService portalService; #endregion #region Constructors and Destructors public CmsPortalManagerController( IPortalService portalService, IDomainService domainService, IAnalyticsAccountService analyticsAccountService) { this.portalService = portalService; this.domainService = domainService; this.analyticsAccountService = analyticsAccountService; } #endregion #region Public Methods public ActionResult SimpleSettings() { CmsPortalManagerSimpleSettingsViewModel viewModel = null; try { CmsPortalManagerServiceBinder modelBinder = this.GetServiceBinder(); viewModel = modelBinder.SimpleSettingsViewModelBind(); return this.View(viewModel); } catch (Exception ex) { this.LoggingService.Log(ex.Message); } return this.View(viewModel); } #endregion #region Methods /// <summary> /// The get service binder. /// </summary> /// <returns> /// </returns> private CmsPortalManagerServiceBinder GetServiceBinder() { return new CmsPortalManagerServiceBinder( this.portalService, this.domainService, this.analyticsAccountService); } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ContentBlobService.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Service.Implementations { using Firebrick.Data; using Firebrick.Data.RepositoryContracts; using Firebrick.Model; using Firebrick.Service.Contracts; /// <summary> /// The content blob service. /// </summary> public class ContentBlobService : BaseService<ContentBlob>, IContentBlobService { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="ContentBlobService"/> class. /// </summary> /// <param name="contentBlobRepository"> /// The user repository. /// </param> /// <param name="unitOfWork"> /// The unit of work. /// </param> public ContentBlobService(IContentBlobRepository contentBlobRepository, IUnitOfWork unitOfWork) { this.Repository = contentBlobRepository; this.UnitOfWork = unitOfWork; } #endregion #region Public Methods /// <summary> /// </summary> /// <param name="partId"> /// The part id. /// </param> /// <returns> /// </returns> public ContentBlob GetByPartId(int partId) { return this.Repository.Get(cb => cb.PartId == partId); } #endregion } }<file_sep>namespace Firebrick.Model { using System.ComponentModel.DataAnnotations; public class AnalyticsAccount { #region Public Properties ///<summary> ///Gets or sets AccountName ///</summary> public string AccountName { get; set; } ///<summary> ///Gets or sets AnalytcisAccountId ///</summary> [Key] public int AnalytcisAccountId { get; set; } ///<summary> ///Gets or sets PortalId ///</summary public int PortalId { get; set; } ///<summary> ///Gets or sets PrimaryDomainName ///</summary> public string PrimaryDomainName { get; set; } ///<summary> ///Gets or sets ShowMobile ///</summary> public bool ShowMobile { get; set; } ///<summary> ///Gets or sets TrackingCode ///</summary> public string TrackingCode { get; set; } ///<summary> ///Gets or sets TrackingType ///</summary> public string TrackingType { get; set; } #endregion } }<file_sep>namespace Firebrick.Domain.ViewModels.WebAdmin.CmsUserManager { using System.Collections.Generic; using System.Web.Mvc; using Firebrick.Domain.Helpers.Route; public class CmsUserManagerEditViewModel : CmsUserManagerBaseViewModel { public CmsUserManagerEditViewModel() { this.ActionIsSaveSuccessful = null; this.ActionIsDeleteSuccessful = null; } #region Public Properties public override string ActionCancelUrl { get { return WebAdmin.AdminUserList; } } /// <summary> /// Gets or sets ActionIsDeleteSuccessful. /// </summary> public bool? ActionIsDeleteSuccessful { get; set; } /// <summary> /// Gets or sets a value indicating whether ActionIsSaveSuccessful. /// </summary> public bool? ActionIsSaveSuccessful { get; set; } public IEnumerable<SelectListItem> UserRolesAvailableList { get; set; } public IEnumerable<int> UserRolesSelectedItems { get; set; } #endregion } }<file_sep>namespace Firebrick.Admin.Web.Controllers { using System.Web.Mvc; using Firebrick.UI.Core.Controllers; public class CmsDashboardController : BaseAdminController { // // GET: /Dashboard/ #region Public Methods public ActionResult Index() { return this.View(); } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="BaseAdminController.cs" company="Beyond"> // Copyright Beyond 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.UI.Core.Controllers { using System.Web.Mvc; using Firebrick.UI.Core.Logging; /// <summary> /// The base admin controller. /// </summary> public abstract class BaseAdminController : Controller { #region Constants and Fields /// <summary> /// logging service member variable /// </summary> private ILoggingService loggingService; #endregion #region Properties /// <summary> /// Gets or sets the logging service /// </summary> protected ILoggingService LoggingService { get { return this.loggingService ?? (this.loggingService = new LoggingService()); } set { this.loggingService = value; } } #endregion } }<file_sep>namespace Firebrick.Data.EF.Repositories { using Firebrick.Data.RepositoryContracts; using Firebrick.Model; public class NotificationRepository : BaseRepository<Notification>, INotificationRepository { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="NotificationRepository"/> class. /// </summary> /// <param name="databaseFactory"> /// The database factory. /// </param> public NotificationRepository(IDatabaseFactory databaseFactory) : base(databaseFactory) { } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="UrlRouteViewModel.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.ViewModels.Web.Core { using System.Collections.Generic; /// <summary> /// The url route view model. /// </summary> public class UrlRouteViewModel { #region Constructors and Destructors public UrlRouteViewModel() { this.RouteValues = new Dictionary<string, string>(); } #endregion #region Public Properties /// <summary> /// Gets or sets ActionName. /// </summary> public string ActionName { get; set; } /// <summary> /// Gets or sets ControllerName. /// </summary> public string ControllerName { get; set; } /// <summary> /// Gets or sets LookFor. /// </summary> public string LookFor { get; set; } /// <summary> /// Gets or sets PageId. /// </summary> public int PageId { get; set; } /// <summary> /// Gets or sets PortalId. /// </summary> public int PortalId { get; set; } public IDictionary<string, string> RouteValues { get; set; } /// <summary> /// Gets or sets Title. /// </summary> public string Title { get; set; } #endregion } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Firebrick.Domain.ServiceBinders.Web { using Firebrick.Model; using Firebrick.Service.Contracts; public class WebCoreSecurityServiceBinder { #region Constants and Fields private readonly IUserService userService; private readonly IRoleService roleService; private readonly IUserRolesService userRolesService; private readonly IRolePageRestrictionService rolePageRestrictionService; #endregion #region Constructors and Destructors public WebCoreSecurityServiceBinder(IUserService userService, IRoleService roleService, IUserRolesService userRolesService, IRolePageRestrictionService rolePageRestrictionService) { this.userService = userService; this.roleService = roleService; this.userRolesService = userRolesService; this.rolePageRestrictionService = rolePageRestrictionService; } #endregion #region Public Methods public IEnumerable<int> GetRolePageRestrictions(int pageId) { return rolePageRestrictionService.GetMany(rp => rp.PageId == pageId).Select(rp => rp.RoleId); } public string[] GetRolesForUser(int userId) { return userRolesService.GetUserRoles(userId); } public int GetUserId(string userName) { return userService.GetByUsername(userName).UserId; } #endregion } } <file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="BaseRepository.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.EF.Repositories { using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Linq.Expressions; /// <summary> /// Base Respository /// </summary> /// <typeparam name="T"> /// </typeparam> public class BaseRepository<T> where T : class { #region Constants and Fields /// <summary> /// The dbset. /// </summary> private readonly IDbSet<T> dbset; /// <summary> /// The data context. /// </summary> private FirebrickContext dataContext; #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="BaseRepository{T}"/> class. /// </summary> /// <param name="databaseFactory"> /// The database factory. /// </param> protected BaseRepository(IDatabaseFactory databaseFactory) { this.DatabaseFactory = databaseFactory; this.dbset = this.DataContext.Set<T>(); } #endregion #region Properties /// <summary> /// Gets DataContext. /// </summary> protected FirebrickContext DataContext { get { return this.dataContext ?? (this.dataContext = this.DatabaseFactory.Get()); } } /// <summary> /// Gets DatabaseFactory. /// </summary> protected IDatabaseFactory DatabaseFactory { get; private set; } #endregion #region Public Methods /// <summary> /// The add. /// </summary> /// <param name="entity"> /// The entity. /// </param> public virtual void Add(T entity) { this.dbset.Add(entity); } public virtual void Commit() { this.DataContext.Commit(); } /// <summary> /// The delete. /// </summary> /// <param name="entity"> /// The entity. /// </param> public virtual void Delete(T entity) { this.dbset.Remove(entity); } /// <summary> /// The delete. /// </summary> /// <param name="where"> /// The where. /// </param> public virtual void Delete(Expression<Func<T, bool>> where) { IEnumerable<T> objects = this.dbset.Where(where).AsEnumerable(); foreach (T obj in objects) { this.dbset.Remove(obj); } } /// <summary> /// The get. /// </summary> /// <param name="where"> /// The where. /// </param> /// <returns> /// </returns> public T Get(Expression<Func<T, bool>> where) { return this.dbset.Where(where).FirstOrDefault(); } /// <summary> /// The get all. /// </summary> /// <returns> /// </returns> public virtual IEnumerable<T> GetAll() { return this.dbset.ToList(); } /// <summary> /// The get by id. /// </summary> /// <param name="id"> /// The id. /// </param> /// <returns> /// </returns> public virtual T GetById(int id) { return this.dbset.Find(id); } /// <summary> /// The get by id. /// </summary> /// <param name="id"> /// The id. /// </param> /// <returns> /// </returns> public virtual T GetById(string id) { return this.dbset.Find(id); } /// <summary> /// The get many. /// </summary> /// <param name="where"> /// The where. /// </param> /// <returns> /// </returns> public virtual IEnumerable<T> GetMany(Expression<Func<T, bool>> where) { return this.dbset.Where(where).ToList(); } /// <summary> /// The update. /// </summary> /// <param name="entity"> /// The entity. /// </param> public virtual void Update(T entity) { this.dbset.Attach(entity); this.dataContext.Entry(entity).State = EntityState.Modified; } #endregion } }<file_sep>jQuery Templates http://weblogs.asp.net/dwahlin/archive/2010/11/20/reducing-code-by-using-jquery-templates.aspx Nearly every language out there uses templates in some shape or form to minimize the amount of code that has to be written in an application. By using templates you can define a template structure once and use it to generate code, HTML or other formats. If you’ve created ASP.NET applications then you’re aware of how powerful and productive templates are when it comes to generating HTML output. However, what if you want to use templates on the client-side to generate HTML rather than writing a lot of JavaScript to manipulate the DOM? Although templates have been available in jQuery for quite awhile through various plug-ins, the latest template framework worked on jointly by Microsoft and the jQuery team provides a great solution that doesn’t use CSS in strange ways or require a lot of knowledge about a template language. By using it you can define HTML templates in web pages and use them to render HTML output dynamically at runtime. I’ll cover the basics of using the jQuery Templates in this post but you can get additional information from http://api.jquery.com/category/plugins/templates. <file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="EnquiryService.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Service.Implementations { using Firebrick.Data; using Firebrick.Data.RepositoryContracts; using Firebrick.Model; using Firebrick.Service.Contracts; /// <summary> /// The enquiry service. /// </summary> public class EnquiryService : BaseService<Enquiry>, IEnquiryService { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="EnquiryService"/> class. /// </summary> /// <param name="enquiryRepository"> /// The domainrepository. /// </param> /// <param name="unitOfWork"> /// The unit of work. /// </param> public EnquiryService(IEnquiryRepository enquiryRepository, IUnitOfWork unitOfWork) { this.Repository = enquiryRepository; this.UnitOfWork = unitOfWork; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IUserRolesService.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Service.Contracts { using System.Collections.Generic; using Firebrick.Model; /// <summary> /// The i user roles service. /// </summary> public interface IUserRolesService : IService<UserRole> { #region Public Methods UserRole Get(int roleId, int userId); string[] GetUserRoles(int userId); #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PageManagerControllerFixturecs.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Web.Tests.WebAdmin { using System; using System.Linq.Expressions; using System.Web.Mvc; using Firebrick.Admin.Web.Controllers; using Firebrick.Data; using Firebrick.Data.RepositoryContracts; using Firebrick.Model; using Firebrick.Service.Contracts; using Firebrick.Service.Implementations; using Firebrick.Test.Helper; using Moq; using Xunit; /// <summary> /// The page manager controller fixturecs. /// </summary> public class PageManagerControllerFixturecs { #region Constants and Fields /// <summary> /// The page controller action mock. /// </summary> private Mock<IPageControllerActionRepository> pageControllerRepositoryActionMock; /// <summary> /// The page controller action service. /// </summary> private PageControllerActionService pageControllerActionService; /// <summary> /// The page repository mock. /// </summary> private Mock<IPageRepository> pageRepositoryMock; /// <summary> /// The page service. /// </summary> private PageService pageService; /// <summary> /// The page template repository mock. /// </summary> private Mock<IPageTemplateRepository> pageTemplateRepositoryMock; /// <summary> /// The page template service. /// </summary> private PageTemplateService pageTemplateService; private Mock<IPartRepository> partRepositoryMock; /// <summary> /// The part service. /// </summary> private IPartService partService; private Mock<IPartTypeRepository> partTypeRepositoryMock; /// <summary> /// The part type service. /// </summary> private IPartTypeService partTypeService; private Mock<ISeoDecoratorRepository> seoDecoratorRepositoryMock; private Mock<IRolePageRestrictionRepository> rolePageRestrictionRepositoryMock; /// <summary> /// The seo decorator service /// </summary> private SeoDecoratorService seoDecoratorService; private readonly IRoleService roleService; private IRolePageRestrictionService rolePageRestrictionService; #endregion #region Public Methods /// <summary> /// The when default add method called_ valid view model returned. /// </summary> [Fact] public void WhenDefaultAddMethodCalled_ValidViewModelReturned() { // ARRANGE this.InitializeConstructorParameters(); this.RespositoryMockSetup(); this.InitializeServices(); // ACT var controller = new CmsPageManagerController( this.pageService, this.pageTemplateService, this.pageControllerActionService, this.partTypeService, this.partService, this.seoDecoratorService, this.roleService, this.rolePageRestrictionService); var viewResult = controller.Add("1") as ViewResult; // ASSERT Assert.NotNull(viewResult); Assert.Equal(string.Empty, viewResult.ViewName); Assert.True(viewResult.ViewData.ModelState.IsValid); Assert.True(controller.ModelState.IsValid); } /// <summary> /// The when default edit method called_ valid view model returned. /// </summary> [Fact] public void WhenDefaultEditMethodCalled_ValidViewModelReturned() { // ARRANGE this.InitializeConstructorParameters(); this.RespositoryMockSetup(); this.InitializeServices(); // ACT var controller = new CmsPageManagerController( this.pageService, this.pageTemplateService, this.pageControllerActionService, this.partTypeService, this.partService, this.seoDecoratorService, this.roleService, this.rolePageRestrictionService); var viewResult = controller.Edit("1") as ViewResult; // ASSERT Assert.NotNull(viewResult); Assert.Equal(string.Empty, viewResult.ViewName); Assert.True(viewResult.ViewData.ModelState.IsValid); Assert.True(controller.ModelState.IsValid); } /// <summary> /// The when default index method called with page id_ valid view model returned. /// </summary> [Fact] public void WhenDefaultIndexMethodCalled_ValidViewModelReturned() { // ARRANGE this.InitializeConstructorParameters(); this.RespositoryMockSetup(); this.InitializeServices(); // ACT var controller = new CmsPageManagerController( this.pageService, this.pageTemplateService, this.pageControllerActionService, this.partTypeService, this.partService, this.seoDecoratorService, this.roleService, this.rolePageRestrictionService); var viewResult = controller.Index() as ViewResult; // ASSERT Assert.NotNull(viewResult); Assert.Equal(string.Empty, viewResult.ViewName); Assert.True(viewResult.ViewData.ModelState.IsValid); Assert.True(controller.ModelState.IsValid); } #endregion #region Methods /// <summary> /// The initialize constructor parameters. /// </summary> private void InitializeConstructorParameters() { this.pageRepositoryMock = new Mock<IPageRepository>(); this.pageTemplateRepositoryMock = new Mock<IPageTemplateRepository>(); this.pageControllerRepositoryActionMock = new Mock<IPageControllerActionRepository>(); this.partTypeRepositoryMock = new Mock<IPartTypeRepository>(); this.partRepositoryMock = new Mock<IPartRepository>(); this.seoDecoratorRepositoryMock = new Mock<ISeoDecoratorRepository>(); this.rolePageRestrictionRepositoryMock = new Mock<IRolePageRestrictionRepository>(); } /// <summary> /// The initialize services. /// </summary> private void InitializeServices() { this.pageService = new PageService(this.pageRepositoryMock.Object, new Mock<IUnitOfWork>().Object); this.pageTemplateService = new PageTemplateService(this.pageTemplateRepositoryMock.Object, new Mock<IUnitOfWork>().Object); this.pageControllerActionService = new PageControllerActionService(this.pageControllerRepositoryActionMock.Object, new Mock<IUnitOfWork>().Object); this.partTypeService = new PartTypeService(this.partTypeRepositoryMock.Object, new Mock<IUnitOfWork>().Object); this.partService = new PartService(this.partRepositoryMock.Object, new Mock<IUnitOfWork>().Object); this.seoDecoratorService = new SeoDecoratorService(this.seoDecoratorRepositoryMock.Object, new Mock<IUnitOfWork>().Object); this.rolePageRestrictionService = new RolePageRestrictionService(this.rolePageRestrictionRepositoryMock.Object, new Mock<IUnitOfWork>().Object); } /// <summary> /// The respository mock setup. /// </summary> private void RespositoryMockSetup() { this.pageRepositoryMock.Setup(repo => repo.GetById(It.IsAny<int>())).Returns(DefaultModelHelper.DummyPopulatedPage()); this.pageTemplateRepositoryMock.Setup(repo => repo.GetById(It.IsAny<int>())).Returns(DefaultModelHelper.DummyPopulatedPageTemplate()); this.pageControllerRepositoryActionMock.Setup(repo => repo.Get(It.IsAny<Expression<Func<PageControllerAction, bool>>>())). Returns(DefaultModelHelper.DummyPageControllerAction()); } #endregion } }<file_sep>namespace Firebrick.Data.EF.Repositories { using Firebrick.Data.RepositoryContracts; using Firebrick.Model; public class AnalyticsAccountRepository : BaseRepository<AnalyticsAccount>, IAnalyticsAccountRepository { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="AnalyticsAccountRepository"/> class. /// </summary> /// <param name="databaseFactory"> /// The database factory. /// </param> public AnalyticsAccountRepository(IDatabaseFactory databaseFactory) : base(databaseFactory) { } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="FirebrickContext.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.EF { using System.Data.Entity; using Firebrick.Model; /// <summary> /// The firebrick context. /// </summary> public class FirebrickContext : DbContext { #region Constructors and Destructors public FirebrickContext() : base("Name=FirebrickContext") { } #endregion #region Public Properties ///<summary> ///Gets or sets AnalyticsAccounts /// </summary> public DbSet<AnalyticsAccount> AnalyticsAccounts { get; set; } /// <summary> /// Gets or sets AnalyticsTypes. /// </summary> public DbSet<AnalyticsType> AnalyticsTypes { get; set; } /// <summary> /// Gets or sets ClientAssetConfigs. /// </summary> public DbSet<ClientAssetConfig> ClientAssetConfigs { get; set; } /// <summary> /// Gets or sets ClientAssetTypes. /// </summary> public DbSet<ClientAssetType> ClientAssetTypes { get; set; } /// <summary> /// Gets or sets ClientAssets. /// </summary> public DbSet<ClientAsset> ClientAssets { get; set; } /// <summary> /// Gets or sets ContentBlobs. /// </summary> public DbSet<ContentBlob> ContentBlobs { get; set; } /// <summary> /// Gets or sets Domains. /// </summary> public DbSet<Domain> Domains { get; set; } /// <summary> /// Gets or sets EnginePartTypeMaps. /// </summary> public DbSet<EnginePartTypeMap> EnginePartTypeMaps { get; set; } /// <summary> /// Gets or sets Engines. /// </summary> public DbSet<Engine> Engines { get; set; } /// <summary> /// Gets or sets Enquiries. /// </summary> public DbSet<Enquiry> Enquiries { get; set; } /// <summary> /// Gets or sets Exceptions. /// </summary> public DbSet<Exception> Exceptions { get; set; } /// <summary> /// Gets or sets Log. /// </summary> public DbSet<Log> Log { get; set; } ///<summary> ///Gets or sets NotificationTypes /// </summary> public DbSet<NotificationType> NotificationTypes { get; set; } /// <summary> /// Gets or sets Notifications /// </summary> public DbSet<Notification> Notifications { get; set; } /// <summary> /// Gets or sets PageControllerActions. /// </summary> public DbSet<PageControllerAction> PageControllerActions { get; set; } /// <summary> /// Gets or sets PageTemplateZoneMaps. /// </summary> public DbSet<PageTemplateZoneMap> PageTemplateZoneMaps { get; set; } /// <summary> /// Gets or sets PageTemplates. /// </summary> public DbSet<PageTemplate> PageTemplates { get; set; } /// <summary> /// Gets or sets PageZones. /// </summary> public DbSet<PageZone> PageZones { get; set; } /// <summary> /// Gets or sets Pages. /// </summary> public DbSet<Page> Pages { get; set; } /// <summary> /// Gets or sets PartContainers. /// </summary> public DbSet<PartContainer> PartContainers { get; set; } /// <summary> /// Gets or sets PartSettings. /// </summary> public DbSet<PartSetting> PartSettings { get; set; } /// <summary> /// Gets or sets PartTypes. /// </summary> public DbSet<PartType> PartTypes { get; set; } /// <summary> /// Gets or sets Parts. /// </summary> public DbSet<Part> Parts { get; set; } /// <summary> /// Gets or sets PortalSettings. /// </summary> public DbSet<PortalSetting> PortalSettings { get; set; } /// <summary> /// Gets or sets Portals. /// </summary> public DbSet<Portal> Portals { get; set; } public DbSet<RolePageRestriction> RolePageRestrictions { get; set; } public DbSet<RolePartRestriction> RolePartRestrictions { get; set; } /// <summary> /// Gets or sets Roles. /// </summary>Roles public DbSet<Roles> Roles { get; set; } /// <summary> /// Gets or sets SeoDecorators. /// </summary> public DbSet<SeoDecorator> SeoDecorators { get; set; } public DbSet<SeoRouteValue> SeoRouteValues { get; set; } /// <summary> /// Gets or sets UserRoles. /// </summary> public DbSet<UserRole> UserRoles { get; set; } /// <summary> /// Gets or sets Users. /// </summary> public DbSet<User> Users { get; set; } #endregion #region Public Methods /// <summary> /// The commit. /// </summary> public virtual void Commit() { this.SaveChanges(); } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ClientAssetTypeService.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Service.Implementations { using Firebrick.Data; using Firebrick.Data.RepositoryContracts; using Firebrick.Model; using Firebrick.Service.Contracts; /// <summary> /// The client asset type service. /// </summary> public class ClientAssetTypeService : BaseService<ClientAssetType>, IClientAssetTypeService { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="ClientAssetTypeService"/> class. /// </summary> /// <param name="clientAssetTypeRepository"> /// The client asset type repository. /// </param> /// <param name="unitOfWork"> /// The unit of work. /// </param> public ClientAssetTypeService(IClientAssetTypeRepository clientAssetTypeRepository, IUnitOfWork unitOfWork) { this.Repository = clientAssetTypeRepository; this.UnitOfWork = unitOfWork; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PortalRepository.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.EF.Repositories { using Firebrick.Data.RepositoryContracts; using Firebrick.Model; /// <summary> /// The web site repository. /// </summary> public class PortalRepository : BaseRepository<Portal>, IPortalRepository { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="PortalRepository"/> class. /// </summary> /// <param name="databaseFactory"> /// The database factory. /// </param> public PortalRepository(IDatabaseFactory databaseFactory) : base(databaseFactory) { } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IPageService.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Service.Contracts { using Firebrick.Model; /// <summary> /// The i web page service. /// </summary> public interface IPageService : IService<Page> { #region Public Methods /// <summary> /// The get by look for. /// </summary> /// <param name="lookFor"> /// The look for. /// </param> /// <returns> /// </returns> Page GetByLookFor(string lookFor); #endregion } }<file_sep>namespace Firebrick.Service.Contracts { using Firebrick.Model; /// <summary> /// The i notification config /// </summary> public interface INotificationService : IService<Notification> { } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="UserRolesServiceFixture.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Services.Tests { /// <summary> /// The user roles service fixture. /// </summary> public class UserRolesServiceFixture { } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="LoggingService.cs" company="Beyond"> // Copyright Beyond 2012 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.UI.Core.Logging { using System; using System.Reflection; using log4net; /// <summary> /// The logging service. /// </summary> public class LoggingService : ILoggingService { #region Constants and Fields /// <summary> /// The log. /// </summary> private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Public Methods /// <summary> /// The fatal. /// </summary> /// <param name="message"> /// The message. /// </param> /// <param name="ex"> /// The ex. /// </param> public void Fatal(string message, Exception ex) { log.Fatal(message, ex); } /// <summary> /// The info. /// </summary> /// <param name="message"> /// The message. /// </param> /// <param name="ex"> /// The ex. /// </param> public void Info(string message, Exception ex) { log.Info(message, ex); } /// <summary> /// The log. /// </summary> /// <param name="message"> /// The message. /// </param> public void Log(string message) { log.Info(message); } /// <summary> /// The warning. /// </summary> /// <param name="message"> /// The message. /// </param> /// <param name="ex"> /// The ex. /// </param> public void Warning(string message, Exception ex) { log.Warn(message, ex); } #endregion } }<file_sep>namespace Firebrick.Service.Implementations { using Firebrick.Data; using Firebrick.Data.RepositoryContracts; using Firebrick.Model; using Firebrick.Service.Contracts; /// <summary> /// The analytics account service. /// </summary> public class AnalyticsAccountService : BaseService<AnalyticsAccount>, IAnalyticsAccountService { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="AnalyticsAccountService"/> class. /// </summary> /// <param name="analyticsAccountRepository"> /// The analytics account repository. /// </param> /// <param name="unitOfWork"> /// The unit of work. /// </param> public AnalyticsAccountService(IAnalyticsAccountRepository analyticsAccountRepository, IUnitOfWork unitOfWork) { this.Repository = analyticsAccountRepository; this.UnitOfWork = unitOfWork; } #endregion } }<file_sep>namespace Firebrick.Data.RepositoryContracts { using Firebrick.Model; public interface IAnalyticsAccountRepository : IRepository<AnalyticsAccount> { } }<file_sep>namespace Firebrick.Domain.ViewModels.WebAdmin.CmsUserManager { using System.Collections.Generic; using System.Web.Mvc; using Firebrick.Domain.Helpers.Route; public class CmsUserManagerAddViewModel : CmsUserManagerBaseViewModel { public CmsUserManagerAddViewModel() { this.ActionIsAddSuccessful = null; } #region Public Properties public override string ActionCancelUrl { get { return WebAdmin.AdminUserList; } } public bool? ActionIsAddSuccessful { get; set; } public string AddErrorMessage { get; set; } public IEnumerable<SelectListItem> UserRolesAvailableList { get; set; } public IEnumerable<int> UserRolesSelectedItems { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IPageTemplateZoneMapRepository.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.RepositoryContracts { using Firebrick.Model; /// <summary> /// The i web page template zone map repository. /// </summary> public interface IPageTemplateZoneMapRepository : IRepository<PageTemplateZoneMap> { } }<file_sep>namespace Firebrick.ContentManagement.Web.Controllers { using System.Web.Mvc; using Firebrick.Domain.ServiceBinders; using Firebrick.Domain.ViewModels; using Firebrick.Service.Contracts; using Firebrick.UI.Core.Controllers; public class MenuController : BasePartController { #region Constants and Fields /// <summary> /// The user service. /// </summary> private readonly IPageService pageService; private readonly ISeoDecoratorService seoDecoratorService; #endregion #region Constructors and Destructors public MenuController(IPageService pageService, ISeoDecoratorService seoDecoratorService) { this.pageService = pageService; this.seoDecoratorService = seoDecoratorService; } #endregion #region Public Methods [HttpGet] [ChildActionOnly] public ActionResult Index() { return this.PartialView(); } [ChildActionOnly] public ActionResult RenderMain() { var modelBinder = new MenuServiceBinder(this.pageService, this.seoDecoratorService); MainMenuViewModel viewModel = modelBinder.BindModel(-1); return this.PartialView("MainMenu", viewModel); } [ChildActionOnly] public ActionResult SideMenu(string id) { var modelBinder = new MenuServiceBinder(this.pageService, this.seoDecoratorService); SideMenuViewModel viewModel = modelBinder.SideMenuBindModel(id); return this.PartialView(viewModel); } #endregion } }<file_sep>namespace Firebrick.Domain.ServiceBinders.WebAdmin { using System; using System.Collections.Generic; using System.Linq; using AutoMapper; using Firebrick.Domain.ViewModels.WebAdmin.CmsMenuManager; using Firebrick.Model; using Firebrick.Service.Contracts; using Exception = System.Exception; public class CmsMenuManagerServiceBinder { #region Constants and Fields /// <summary> /// The page service. /// </summary> private readonly IPageService pageService; /// <summary> /// The seo decorator service /// </summary> private readonly ISeoDecoratorService seoDecoratorService; private IEnumerable<SeoDecorator> decorators; #endregion #region Constructors and Destructors public CmsMenuManagerServiceBinder(IPageService pageService, ISeoDecoratorService seoDecoratorService) { this.pageService = pageService; this.seoDecoratorService = seoDecoratorService; } #endregion #region Public Methods #region "Menu Tree Async Calls" public string AddPage(string parentPageId) { string response = "Page Added"; try { //// TODO: [RP] [25092012] Look at Page Manager Add, some of this generic functionality needs to be accessible from here > Refactor //// TODO: [RP] [02102012] Need to add safe guard against duplicate seo look-for records Page page = this.pageService.GetById(Convert.ToInt32(parentPageId)); Page pageCopy = AddPage(page); this.pageService.Add(pageCopy); SeoDecorator seo = this.seoDecoratorService.GetByPage(Convert.ToInt32(parentPageId)); SeoDecorator seoCopy = this.AddSeo(seo, pageCopy.PageId); this.seoDecoratorService.Add(seoCopy); } catch (Exception ex) { response = string.Format("Add Failed - {0}", ex.Message); } return response; } public string CopyPage(string copyPageId) { //// TODO: [RP] [02102012] Refactor this simplistic and long method - not adding parts etc. either string response = "Page Copied"; try { Page page = this.pageService.GetById(Convert.ToInt32(copyPageId)); Page pageCopy = CopyPage(page); this.pageService.Add(pageCopy); SeoDecorator seo = this.seoDecoratorService.GetByPage(Convert.ToInt32(copyPageId)); SeoDecorator seoCopy = this.CopySeo(seo, pageCopy.PageId); this.seoDecoratorService.Add(seoCopy); } catch (Exception ex) { response = string.Format("Copy Failed - {0}", ex.Message); } return response; } public string DeletePage(string pageId) { string response = "Page Deleted"; try { //// this.pageService.Delete(Convert.ToInt32(pageId)); //// var seo = seoDecoratorService.GetByPage(Convert.ToInt32(pageId)); //// seoDecoratorService.Delete(seo.SeoDecoratorId); //// TODO: [RP] [02102012] What about everything else "related" to page...? It all needs to go. } catch (Exception ex) { response = string.Format("Delete Failed - {0}", ex.Message); } return response; } public string MovePage(string sourcePageId, string action, string targetPageId) { string response = "Page Moved"; try { Page sourcePage = this.pageService.GetById(Convert.ToInt32(sourcePageId)); Page targetPage = this.pageService.GetById(Convert.ToInt32(targetPageId)); // 1, -1, 10 // 3, -1, 30 switch (action) { case "append": sourcePage.PageParentId = targetPage.PageId; sourcePage.Order = 100; break; case "top": sourcePage.Order = targetPage.Order - 1; sourcePage.PageParentId = targetPage.PageParentId; break; default: //// bottom sourcePage.Order = targetPage.Order + 1; sourcePage.PageParentId = targetPage.PageParentId; break; } this.pageService.Update(sourcePage); } catch (Exception ex) { response = string.Format("Move Failed - {0}", ex.Message); } return response; } public IEnumerable<TreeNodeViewModel> PopulateTree() { this.decorators = this.seoDecoratorService.GetAll(); return this.TranslatePagesAsNodes(-1); } public string RenamePage(string pageId, string newPageTitle) { string response = "Page Updated"; try { Page page = this.pageService.GetById(Convert.ToInt32(pageId)); page.Title = newPageTitle; this.pageService.Update(page); } catch (Exception ex) { response = string.Format("Update Failed - {0}", ex.Message); } return response; } #endregion #region "Menu Tree Manager" public PageInfoViewModel BindPageInfo(string pageId) { PageInfoViewModel viewModel = new PageInfoViewModel(); Page page = this.pageService.GetById(Convert.ToInt32(pageId)); Mapper.CreateMap<Page, PageInfoViewModel>(); Mapper.Map(page, viewModel); return viewModel; } #endregion #endregion #region Methods private Page AddPage(Page sourcePage) { var pageCopy = new Page { ActionName = sourcePage.ActionName, ControllerName = sourcePage.ControllerName, Order = (sourcePage.Order + 1), PageParentId = sourcePage.PageParentId, PageTemplateId = sourcePage.PageTemplateId, PortalId = sourcePage.PortalId, ShowOnMenu = sourcePage.ShowOnMenu, Title = "New Page" }; return pageCopy; } private SeoDecorator AddSeo(SeoDecorator sourceSeo, int pageId) { var seoCopy = new SeoDecorator { ChangeFrequency = sourceSeo.ChangeFrequency, CreatedDate = sourceSeo.CreatedDate, Description = sourceSeo.Description, FileName = "New Page", Keywords = sourceSeo.Keywords, LastModified = sourceSeo.LastModified, LinkType = sourceSeo.LinkType, LookFor = "new-page", PageId = pageId, PortalId = sourceSeo.PortalId, Priority = sourceSeo.Priority, RobotsFollow = sourceSeo.RobotsFollow, RobotsIndex = sourceSeo.RobotsIndex, Title = "New Page" }; return seoCopy; } private Page CopyPage(Page sourcePage) { var pageCopy = new Page { ActionName = sourcePage.ActionName, ControllerName = sourcePage.ControllerName, Order = (sourcePage.Order + 1), PageParentId = sourcePage.PageParentId, PageTemplateId = sourcePage.PageTemplateId, PortalId = sourcePage.PortalId, ShowOnMenu = sourcePage.ShowOnMenu, Title = string.Format("Copy of {0}", sourcePage.Title) }; return pageCopy; } private SeoDecorator CopySeo(SeoDecorator sourceSeo, int pageId) { var seoCopy = new SeoDecorator { ChangeFrequency = sourceSeo.ChangeFrequency, CreatedDate = sourceSeo.CreatedDate, Description = sourceSeo.Description, FileName = string.Format("Copy of {0}", sourceSeo.FileName), Keywords = sourceSeo.Keywords, LastModified = sourceSeo.LastModified, LinkType = sourceSeo.LinkType, LookFor = string.Format("{0}-copy", sourceSeo.LookFor), PageId = pageId, PortalId = sourceSeo.PortalId, Priority = sourceSeo.Priority, RobotsFollow = sourceSeo.RobotsFollow, RobotsIndex = sourceSeo.RobotsIndex, Title = string.Format("Copy of {0}", sourceSeo.Title) }; return seoCopy; } private IEnumerable<TreePageViewModel> GetPages(int parentPageId) { IEnumerable<Page> pages = this.pageService.GetMany(p => p.PageParentId == parentPageId); IEnumerable<TreePageViewModel> pageDecorators = from p in pages join d in this.decorators on p.PageId equals d.PageId orderby p.PageParentId , p.Order select new TreePageViewModel { PageId = p.PageId, ParentId = p.PageParentId, Title = p.Title, LookFor = d.LookFor, Order = p.Order }; return pageDecorators; } private IEnumerable<TreeNodeViewModel> TranslatePagesAsNodes(int parentPageId) { var treeNodes = new List<TreeNodeViewModel>(); IEnumerable<TreePageViewModel> pages = this.GetPages(parentPageId); foreach (TreePageViewModel page in pages) { var node = new TreeNodeViewModel(); var attributes = new Dictionary<string, string> { { "url", page.LookFor } }; node.id = page.PageId; node.text = page.Title; node.iconCls = "someCss"; node.@checked = false; node.state = "open"; node.attributes = attributes; IEnumerable<TreeNodeViewModel> children = this.TranslatePagesAsNodes(page.PageId); if (children != null) { node.children = (List<TreeNodeViewModel>)children; } treeNodes.Add(node); } return treeNodes; } #endregion } }<file_sep>namespace Firebrick.Data.EF.Initializers { using System.Data.Entity.Migrations; using System.Data.Entity.Validation; using System.Diagnostics; using Firebrick.Model; public class ClientAssetInitializer { #region Public Methods public static void Add(FirebrickContext context) { AddClientAssetTypes(context); AddClientAssets(context); AddClientAssetConfig(context); } #endregion #region Methods private static void AddClientAssetConfig(FirebrickContext context) { context.ClientAssetConfigs.AddOrUpdate( new ClientAssetConfig { ClientAssetConfigId = 1, ClientAssetId = 1, PageId = 1 }); context.ClientAssetConfigs.AddOrUpdate( new ClientAssetConfig { ClientAssetConfigId = 2, ClientAssetId = 2, PageId = 1, PartId = 1 }); context.ClientAssetConfigs.AddOrUpdate( new ClientAssetConfig { ClientAssetConfigId = 3, ClientAssetId = 3, PageId = 1 }); context.ClientAssetConfigs.AddOrUpdate( new ClientAssetConfig { ClientAssetConfigId = 4, ClientAssetId = 4, PageId = 1, PartId = 1 }); try { context.SaveChanges(); } catch (DbEntityValidationException dbEx) { foreach (DbEntityValidationResult validationErrors in dbEx.EntityValidationErrors) { foreach (DbValidationError validationError in validationErrors.ValidationErrors) { Debug.WriteLine( "Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } } } private static void AddClientAssetTypes(FirebrickContext context) { context.ClientAssetTypes.AddOrUpdate(new ClientAssetType { ClientAssetTypeId = 1, Title = "CSS" }); context.ClientAssetTypes.AddOrUpdate(new ClientAssetType { ClientAssetTypeId = 2, Title = "JavaScript" }); context.ClientAssetTypes.AddOrUpdate(new ClientAssetType { ClientAssetTypeId = 3, Title = "Image" }); try { context.SaveChanges(); } catch (DbEntityValidationException dbEx) { foreach (DbEntityValidationResult validationErrors in dbEx.EntityValidationErrors) { foreach (DbValidationError validationError in validationErrors.ValidationErrors) { Debug.WriteLine( "Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } } } private static void AddClientAssets(FirebrickContext context) { context.ClientAssets.AddOrUpdate( new ClientAsset { ClientAssetId = 1, ClientAssetTypeId = 1, Title = "TestPageCss", RelativeFilePath = "~/content/themes/grey-matter/css/pages/TestPage.css" }); context.ClientAssets.AddOrUpdate( new ClientAsset { ClientAssetId = 2, ClientAssetTypeId = 1, Title = "TestPartCss", RelativeFilePath = "~/content/themes/grey-matter/css/parts/TestPart.css" }); context.ClientAssets.AddOrUpdate( new ClientAsset { ClientAssetId = 3, ClientAssetTypeId = 2, Title = "TestPageJavascript", RelativeFilePath = "~/scripts/Pages/default/js/page/TestCustom.js" }); context.ClientAssets.AddOrUpdate( new ClientAsset { ClientAssetId = 4, ClientAssetTypeId = 2, Title = "TestPartJavascript", RelativeFilePath = "~/scripts/views/shared/TestPartJavascript.js" }); try { context.SaveChanges(); } catch (DbEntityValidationException dbEx) { foreach (DbEntityValidationResult validationErrors in dbEx.EntityValidationErrors) { foreach (DbValidationError validationError in validationErrors.ValidationErrors) { Debug.WriteLine( "Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } } } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IContentBlobService.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Service.Contracts { using Firebrick.Model; /// <summary> /// The i content blob service. /// </summary> public interface IContentBlobService : IService<ContentBlob> { #region Public Methods /// <summary> /// </summary> /// <param name="partId"> /// The part id. /// </param> /// <returns> /// </returns> ContentBlob GetByPartId(int partId); #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="EMailClient.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.Messaging.EMail { using System; using System.Net.Mail; using System.Text; using Firebrick.Entities.Messaging; /// <summary> /// The e mail client. /// </summary> public static class EMailClient { #region Public Methods /// <summary> /// The send e mail. /// </summary> /// <param name="message"> /// The message. /// </param> /// <param name="isHtml"> /// The isHtml /// </param> /// <returns> /// </returns> public static SendEmailResult SendEMail(MailMessage message, bool isHtml) { message.BodyEncoding = Encoding.UTF8; message.IsBodyHtml = isHtml; var sendEmailResult = new SendEmailResult { Message = message }; var mailClient = new SmtpClient(); try { mailClient.Send(message); //// TODO: [RP] [11092012] Investigate sending ASync > This would be more beneficial } catch (Exception ex) { sendEmailResult.Exception = ex; } return sendEmailResult; } #endregion #region Methods private static SmtpClient GetSmtpClient() { var mailClient = new SmtpClient(); //// TODO: [RP] [11092012] Configure SMTP here via Config or DB or ?? return mailClient; } #endregion } }<file_sep>namespace Firebrick.Domain.ViewModels.WebAdmin.CmsMenuManager { /// <summary> /// The cms page manager index view model list item. /// </summary> public sealed class CmsUserManagerIndexViewModelListItem { #region Public Properties /// <summary> /// Gets or sets PageId. /// </summary> public int UserId { get; set; } /// <summary> /// Gets or sets Title. /// </summary> public string UserName { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IPageTemplateZoneMapService.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Service.Contracts { using Firebrick.Model; /// <summary> /// The i web page template zone map service. /// </summary> public interface IPageTemplateZoneMapService : IService<PageTemplateZoneMap> { } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="HttpContextPerRequestStore.cs" company="Beyond"> // Copyright Beyond 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.UI.Core.UnityExtensions { using System; using System.Web; /// <summary> /// The http context per request store. /// </summary> public class HttpContextPerRequestStore : IPerRequestStore { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="HttpContextPerRequestStore"/> class. /// </summary> public HttpContextPerRequestStore() { if (HttpContext.Current.ApplicationInstance != null) { // Note: We'd like to do this, but you cannot sign up for the EndRequest from // from this application instance as it is actually different than the one the // the EndRequest handler is actually invoked from. // HttpContext.Current.ApplicationInstance.EndRequest += this.EndRequestHandler; } } #endregion #region Public Events /// <summary> /// The end request. /// </summary> public event EventHandler EndRequest; #endregion #region Public Methods /// <summary> /// The get value. /// </summary> /// <param name="key"> /// The key. /// </param> /// <returns> /// The get value. /// </returns> public object GetValue(object key) { return HttpContext.Current.Items[key]; } /// <summary> /// The remove value. /// </summary> /// <param name="key"> /// The key. /// </param> public void RemoveValue(object key) { HttpContext.Current.Items.Remove(key); } /// <summary> /// The set value. /// </summary> /// <param name="key"> /// The key. /// </param> /// <param name="value"> /// The value. /// </param> public void SetValue(object key, object value) { HttpContext.Current.Items[key] = value; } #endregion #region Methods /// <summary> /// The end request handler. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> private void EndRequestHandler(object sender, EventArgs e) { EventHandler handler = this.EndRequest; if (handler != null) { handler(this, e); } } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Log.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Model { using System; using System.ComponentModel.DataAnnotations; /// <summary> /// The log. /// </summary> public class Log { #region Public Properties /// <summary> /// Gets or sets Date. /// </summary> public DateTime Date { get; set; } /// <summary> /// Gets or sets Level. /// </summary> public string Level { get; set; } /// <summary> /// Gets or sets LogId. /// </summary> [Key] public int LogId { get; set; } /// <summary> /// Gets or sets Logger. /// </summary> public string Logger { get; set; } /// <summary> /// Gets or sets Message. /// </summary> public string Message { get; set; } /// <summary> /// Gets or sets Thread. /// </summary> public string Thread { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="SitemapHandler.cs" company="Beyond"> // Copyright Beyond 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.UI.Core.Handlers { using System.Web; using Firebrick.Domain.ServiceBinders.Web; using Firebrick.Framework.Http; using Firebrick.Service.Contracts; using Microsoft.Practices.ServiceLocation; /// <summary> /// The sitemap handler. /// </summary> public class SitemapHandler : BaseHttpHandler { #region Public Properties /// <summary> /// Gets ContentMimeType. /// </summary> public override string ContentMimeType { get { return "text/xml"; } } /// <summary> /// Gets a value indicating whether RequiresAuthentication. /// </summary> public override bool RequiresAuthentication { get { return false; } } #endregion #region Public Methods /// <summary> /// The handle request. /// </summary> /// <param name="context"> /// The context. /// </param> /// <returns> /// The handle request string /// </returns> public override string HandleRequest(HttpContext context) { var serviceBinder = new WebCoreServiceBinder( ServiceLocator.Current.GetService(typeof(IPageService)) as IPageService, ServiceLocator.Current.GetService(typeof(ISeoDecoratorService)) as ISeoDecoratorService, ServiceLocator.Current.GetService(typeof(ISeoRouteValueService)) as ISeoRouteValueService, ServiceLocator.Current.GetService(typeof(IDomainService)) as IDomainService); return serviceBinder.SiteMapViewModelBind(); } /// <summary> /// The validate parameters. /// </summary> /// <param name="context"> /// The context. /// </param> /// <returns> /// The validate parameters boolean /// </returns> public override bool ValidateParameters(HttpContext context) { return true; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="WebFrameworkFixture.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Model.Tests.ViewModels { using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Firebrick.Domain.ViewModels.Web.Core; using Xunit; /// <summary> /// The web framework. /// </summary> public class WebFrameworkFixture { #region Public Methods /// <summary> /// The when validating web framework without data_ then validation fails. /// </summary> [Fact] public void WhenValidatingWebFrameworkWithoutData_ThenValidationFails() { // Arrange var viewModel = new WebFrameworkViewModel { PageId = 1 }; // Act List<ValidationResult> validationResults = ValidateModel(viewModel); // Assert Assert.Equal(validationResults.Count, 1); } #endregion #region Methods /// <summary> /// The validate model. /// </summary> /// <param name="viewModel"> /// The view model. /// </param> private static List<ValidationResult> ValidateModel(WebFrameworkViewModel viewModel) { var context = new ValidationContext(viewModel, null, null); //// Validator.ValidateObject(viewModel, context, true); var validationResults = new List<ValidationResult>(); Validator.TryValidateObject(viewModel, context, validationResults); return validationResults; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="DomainInitializer.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.EF.Initializers { using System.Data.Entity.Migrations; using System.Data.Entity.Validation; using System.Diagnostics; using Firebrick.Model; /// <summary> /// The domain initializer. /// </summary> public static class DomainInitializer { #region Public Methods /// <summary> /// The Add. /// </summary> /// <param name="context"> /// The context. /// </param> public static void Add(FirebrickContext context) { context.Domains.AddOrUpdate(new Domain { DomainId = 1, HostHeader = "localhost", PortalId = 1 }); context.Domains.AddOrUpdate(new Domain { DomainId = 2, HostHeader = "www.firebrick-content-management.co.uk", PortalId = 1 }); context.Domains.AddOrUpdate(new Domain { DomainId = 3, HostHeader = "m.www.firebrick-content-management.co.uk", PortalId = 1 }); try { context.SaveChanges(); } catch (DbEntityValidationException dbEx) { foreach (DbEntityValidationResult validationErrors in dbEx.EntityValidationErrors) { foreach (DbValidationError validationError in validationErrors.ValidationErrors) { Debug.WriteLine( "Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } } } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="DomainRepositoryFixture.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.Tests.Repositories { using System; using System.Collections.Generic; using System.Linq; using Firebrick.Data.EF; using Firebrick.Data.EF.Repositories; using Firebrick.Data.Sql; using Firebrick.Model; using Firebrick.Test.Helper; using Xunit; /// <summary> /// The domain repository fixture. /// </summary> public class DomainRepositoryFixture { #region Public Methods [Fact] public void WhenAddingEntity_ThenGetAndUpdate() { DatabaseTestUtility.DropCreateFirebrickDatabase(); // Arrange var repository = new DomainRepository(new DatabaseFactory()); Domain newEntity = DefaultModelHelper.DummyPopulatedDomain(); // Act repository.Add(newEntity); repository.Commit(); // Use a new context and repository to verify the vehicle was added var repositoryTwo = new DomainRepository(new DatabaseFactory()); Domain loadedEntity = repositoryTwo.GetById(1); loadedEntity.HostHeader = "NewHostHeader"; repositoryTwo.Update(loadedEntity); repositoryTwo.Commit(); // Use a new context and repository to verify the vehicle was added var repositoryThree = new DomainRepository(new DatabaseFactory()); newEntity = repositoryThree.GetById(1); Assert.NotNull(newEntity); Assert.Equal("NewHostHeader", newEntity.HostHeader); } /// <summary> /// The when constructed with null database factory_ then throws. /// </summary> [Fact] public void WhenConstructedWithNullDatabaseFactory_ThenThrows() { Assert.Throws<NullReferenceException>(() => new DomainRepository(null)); } [Fact] public void WhenEntityDeleted_ThenPersists() { DatabaseTestUtility.DropCreateFirebrickDatabase(); // Arrange var repository = new DomainRepository(new DatabaseFactory()); Domain entity = DefaultModelHelper.DummyPopulatedDomain(); // Act repository.Add(entity); repository.Commit(); IEnumerable<Domain> returnedEntities = repository.GetAll(); // Assert Assert.Equal(1, returnedEntities.Count()); // Act repository.Delete(entity); repository.Commit(); // Arrange // Use a new context and repository to verify the vehicle was deleted var repositoryTwo = new DomainRepository(new DatabaseFactory()); IEnumerable<Domain> verifyEntities = repositoryTwo.GetAll(); // Assert Assert.NotNull(verifyEntities); Assert.Equal(0, verifyEntities.Count()); } /// <summary> /// The when get all from empty database_ then returns empty collection. /// </summary> [Fact] public void WhenGetAllFromEmptyDatabase_ThenReturnsEmptyCollection() { DatabaseTestUtility.DropCreateFirebrickDatabase(); var repository = new DomainRepository(new DatabaseFactory()); IEnumerable<Domain> actual = repository.GetAll(); Assert.NotNull(actual); var actualList = new List<Domain>(actual); Assert.Equal(0, actualList.Count); } #endregion } }<file_sep>namespace Firebrick.Domain.ServiceBinders.WebAdmin { using System.Collections.Generic; using System.Web.Mvc; using AutoMapper; using Firebrick.Domain.ViewModels.WebAdmin.CmsMenuManager; using Firebrick.Domain.ViewModels.WebAdmin.CmsUserManager; using Firebrick.Model; using Firebrick.Service.Contracts; public class CmsUserManagerServiceBinder { #region Constants and Fields private readonly IUserService userService; private readonly IRoleService roleService; private readonly IUserRolesService userRolesService; #endregion #region Constructors and Destructors public CmsUserManagerServiceBinder(IUserService userService, IRoleService roleService, IUserRolesService userRolesService) { this.userService = userService; this.roleService = roleService; this.userRolesService = userRolesService; } #endregion #region Public Methods #region "Add User" public CmsUserManagerAddViewModel AddViewModelBind(int pageId) { var viewModel = new CmsUserManagerAddViewModel(); PopulateUserRolesAvailable(ref viewModel); return viewModel; } public CmsUserManagerAddViewModel AddViewModelInsert(CmsUserManagerAddViewModel viewModel) { var isSuccess = false; var user = this.userService.GetByUsername(viewModel.UserName); if (user == null) { try { user = new User(); Mapper.CreateMap<CmsUserManagerAddViewModel, User>(); Mapper.Map(viewModel, user); user.Password = "<PASSWORD>"; this.userService.Add(user); AddNewUserRoles(user, viewModel); PopulateUserRolesAvailable(ref viewModel); isSuccess = true; } catch (System.Exception) { isSuccess = false; } } else { viewModel.AddErrorMessage = "Username already exists. Please choose another username."; } viewModel.ActionIsAddSuccessful = isSuccess; return viewModel; } #endregion #region "Edit User" public CmsUserManagerEditViewModel EditViewModelBind(int userId) { var viewModel = new CmsUserManagerEditViewModel(); var user = this.userService.GetById(userId); var userRoles = this.userRolesService.GetMany(ur => ur.UserId == userId); var selectedUserRoles = new List<int>(); Mapper.CreateMap<User, CmsUserManagerEditViewModel>(); Mapper.Map(user, viewModel); foreach (var userRole in userRoles) { selectedUserRoles.Add(userRole.RoleId); } PopulateUserRolesAvailable(ref viewModel); viewModel.UserRolesSelectedItems = selectedUserRoles; return viewModel; } public CmsUserManagerEditViewModel EditViewModelUpdate(CmsUserManagerEditViewModel viewModel) { bool isSuccess; try { User user = this.userService.GetById(viewModel.UserId); Mapper.CreateMap<CmsUserManagerEditViewModel, User>(); Mapper.Map(viewModel, user); //// Update User this.userService.Update(user); //// Update User Roles if (viewModel.UserRolesSelectedItems != null) { foreach (int roleId in viewModel.UserRolesSelectedItems) { this.AddNewUserRole(roleId, viewModel.UserId); } } isSuccess = true; } catch (System.Exception) { isSuccess = false; } viewModel = this.EditViewModelBind(viewModel.UserId); viewModel.ActionIsSaveSuccessful = isSuccess; return viewModel; } public CmsUserManagerEditViewModel EditViewModelStateInValid(CmsUserManagerEditViewModel viewModel) { PopulateUserRolesAvailable(ref viewModel); viewModel.ActionIsSaveSuccessful = false; return viewModel; } #endregion #region "List User" public CmsUserManagerIndexViewModel IndexViewModelBind() { var viewModel = new CmsUserManagerIndexViewModel(); IEnumerable<User> users = this.userService.GetAll(); Mapper.CreateMap<User, CmsUserManagerIndexViewModelListItem>(); Mapper.Map(users, viewModel.Users); return viewModel; } #endregion #endregion #region "Methods" private void PopulateUserRolesAvailable(ref CmsUserManagerEditViewModel viewModel) { if (this.roleService != null) { viewModel.UserRolesAvailableList = new SelectList(this.roleService.GetAll(), "RoleId", "Name"); } } private void PopulateUserRolesAvailable(ref CmsUserManagerAddViewModel viewModel) { if (this.roleService != null) { viewModel.UserRolesAvailableList = new SelectList(this.roleService.GetAll(), "RoleId", "Name"); } } private void AddNewUserRole(int roleId, int userId) { UserRole newUserRole = this.userRolesService.Get(roleId, userId); if (newUserRole == null) { newUserRole = new UserRole { RoleId = roleId, UserId = userId }; this.userRolesService.Add(newUserRole); } } private void AddNewUserRoles(User user, CmsUserManagerAddViewModel viewModel) { foreach(var roleId in viewModel.UserRolesSelectedItems) { this.AddNewUserRole(user.UserId, roleId); } } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IPartContainerRepository.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.RepositoryContracts { using Firebrick.Model; /// <summary> /// The i part container repository. /// </summary> public interface IPartContainerRepository : IRepository<PartContainer> { } }<file_sep>// ----------------------------------------------------------------------- // <copyright file="CmsDashboardIndexViewModel.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // ----------------------------------------------------------------------- namespace Firebrick.Domain.ViewModels.WebAdmin.CmsDashboard { /// <summary> /// Dashboard Index /// </summary> public class CmsDashboardIndexViewModel { } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IPageRepository.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.RepositoryContracts { using Firebrick.Model; /// <summary> /// The i web page repository. /// </summary> public interface IPageRepository : IRepository<Page> { } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="User.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Model { using System; using System.ComponentModel.DataAnnotations; /// <summary> /// The user. /// </summary> public class User { #region Public Properties /// <summary> /// Gets or sets Address2. /// </summary> public string Address2 { get; set; } /// <summary> /// Gets or sets Address3. /// </summary> public string Address3 { get; set; } /// <summary> /// Gets or sets the country for the user. /// </summary> [MaxLength(50, ErrorMessage = "UserCountryStringLengthValidationError")] public string Country { get; set; } /// <summary> /// Gets or sets County. /// </summary> public string County { get; set; } public int? CreatedById { get; set; } /// <summary> /// Gets or sets DateCreated. /// </summary> public DateTime? DateCreated { get; set; } /// <summary> /// Gets or sets the user's display name. /// </summary> [Required] [MaxLength(15, ErrorMessage = "BloggerName must be 12 characters or less")] [MinLength(3)] public string DisplayName { get; set; } /// <summary> /// Gets or sets DOB. /// </summary> public DateTime? Dob { get; set; } /// <summary> /// Gets or sets EMail. /// </summary> public string EMail { get; set; } public string FirstName { get; set; } public string FullName { get; set; } /// <summary> /// Gets or sets a value indicating whether HasAcceptedTerms. /// </summary> public bool HasAcceptedTerms { get; set; } /// <summary> /// Gets or sets a value indicating whether the user has completed or dismissed their profile registration. /// </summary> public bool HasRegistered { get; set; } /// <summary> /// Gets or sets a value indicating whether IsActive. /// </summary> public bool IsActive { get; set; } /// <summary> /// Gets or sets a value indicating whether IsContactable. /// </summary> public bool IsContactable { get; set; } public string JobTitle { get; set; } /// <summary> /// Gets or sets LastModified. /// </summary> public DateTime? LastModified { get; set; } public string LastName { get; set; } /// <summary> /// Gets or sets Password. /// </summary> [Required] public string Password { get; set; } /// <summary> /// Gets or sets PortalId. /// </summary> public int PortalId { get; set; } /// <summary> /// Gets or sets the country for the user. /// </summary> public string PostalCode { get; set; } /// <summary> /// Gets or sets Postcode. /// </summary> public string Postcode { get; set; } /// <summary> /// Gets or sets Street. /// </summary> public string Street { get; set; } /// <summary> /// Gets or sets Telephone. /// </summary> public string Telephone { get; set; } /// <summary> /// Gets or sets Town. /// </summary> public string Town { get; set; } /// <summary> /// Gets or sets the identifier for the user. /// </summary> [Key] public int UserId { get; set; } /// <summary> /// Gets or sets UserName. /// </summary> [Required] public string UserName { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="UnitOfWork.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.EF { /// <summary> /// The unit of work. /// </summary> public class UnitOfWork : IUnitOfWork { #region Constants and Fields /// <summary> /// The database factory. /// </summary> private readonly IDatabaseFactory databaseFactory; /// <summary> /// The data context. /// </summary> private FirebrickContext dataContext; #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="UnitOfWork"/> class. /// </summary> /// <param name="databaseFactory"> /// The database factory. /// </param> public UnitOfWork(IDatabaseFactory databaseFactory) { this.databaseFactory = databaseFactory; } #endregion #region Properties /// <summary> /// Gets DataContext. /// </summary> protected FirebrickContext DataContext { get { return this.dataContext ?? (this.dataContext = this.databaseFactory.Get()); } } #endregion #region Public Methods /// <summary> /// The commit. /// </summary> public void Commit() { this.DataContext.Commit(); } #endregion } }<file_sep>namespace Firebrick.ContentManagement.Web.Controllers { using System.Web.Mvc; using Firebrick.UI.Core.Controllers; public class HeaderController : BasePartController { #region Public Methods [HttpGet] [ChildActionOnly] public ActionResult Page() { return this.PartialView(); } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="WebFrameworkPartViewModel.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.ViewModels.Web.Core { /// <summary> /// The web framework part view model. /// </summary> public class WebFrameworkPartViewModel { #region Public Properties public string AdminPartAction { get; set; } public string AdminPartController { get; set; } /// <summary> /// Gets or sets PartAction. /// </summary> public string PartAction { get; set; } /// <summary> /// Gets or sets PartContainerElementId. /// </summary> public string PartContainerElementId { get; set; } /// <summary> /// Gets or sets PartController. /// </summary> public string PartController { get; set; } /// <summary> /// Gets or sets PartId. /// </summary> public int PartId { get; set; } /// <summary> /// Gets or sets PartZoneId. /// </summary> public int PartZoneId { get; set; } public string PartSectionDescriptor { get; set; } public int RowId { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PartService.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Service.Implementations { using System.Collections.Generic; using System.Linq; using Firebrick.Data; using Firebrick.Data.RepositoryContracts; using Firebrick.Model; using Firebrick.Service.Contracts; /// <summary> /// The web part service. /// </summary> public class PartService : BaseService<Part>, IPartService { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="PartService"/> class. /// </summary> /// <param name="partRepository"> /// The user repository. /// </param> /// <param name="unitOfWork"> /// The unit of work. /// </param> public PartService(IPartRepository partRepository, IUnitOfWork unitOfWork) { this.Repository = partRepository; this.UnitOfWork = unitOfWork; } #endregion #region Public Methods /// <summary> /// </summary> /// <param name="pageId"> /// The page id. /// </param> /// <param name="zoneId"> /// The zone id. /// </param> /// <param name="partTypeId"> /// The part Type Id. /// </param> /// <returns> /// </returns> public Part Get(int pageId, int zoneId, int partTypeId) { return this.Repository.Get(p => p.PageId == pageId && p.ZoneId == zoneId && p.PartTypeId == partTypeId); } /// <summary> /// </summary> /// <param name="pageId"> /// The page id. /// </param> /// <returns> /// </returns> public IEnumerable<Part> GetManyByPageId(int pageId) { return this.Repository.GetMany(p => p.PageId == pageId); } public int GetNextOrderId(int pageId, int zoneId) { IEnumerable<Part> parts = this.Repository.GetMany(p => p.PageId == pageId && p.ZoneId == zoneId); Part last = (from p in parts orderby p.Order descending select p).FirstOrDefault(); return last != null ? last.Order + 1 : 1; } #endregion } }<file_sep>namespace Firebrick.Service.Implementations { using Firebrick.Data; using Firebrick.Data.RepositoryContracts; using Firebrick.Model; using Firebrick.Service.Contracts; /// <summary> /// The notification service. /// </summary> public class NotificationService : BaseService<Notification>, INotificationService { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="NotificationService"/> class. /// </summary> /// <param name="notificationRepository"> /// The notification repository. /// </param> /// <param name="unitOfWork"> /// The unit of work. /// </param> public NotificationService(INotificationRepository notificationRepository, IUnitOfWork unitOfWork) { this.Repository = notificationRepository; this.UnitOfWork = unitOfWork; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="FirebrickUserViewModel.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.ViewModels { using System; using System.ComponentModel.DataAnnotations; using Firebrick.Domain.Properties; using Firebrick.Domain.Validators; /// <summary> /// The firebrick user view model. /// </summary> public class FirebrickUserViewModel { #region Public Properties /// <summary> /// Gets or sets the country for the user. /// </summary> [StringLength(50, ErrorMessageResourceName = "UserCountryStringLengthValidationError", ErrorMessageResourceType = typeof(Resources))] [TextLineInputValidator] [Display(Name = "UserCountryLabelText", ResourceType = typeof(Resources))] public string Country { get; set; } /// <summary> /// Gets or sets the user's display name. /// </summary> [Required] [MaxLength(12, ErrorMessage = "DisplayName must be 12 characters or less")] [MinLength(3)] public string DisplayName { get; set; } /// <summary> /// Gets or sets DOB. /// </summary> public DateTime? Dob { get; set; } /// <summary> /// Gets or sets EMail. /// </summary> public string EMail { get; set; } /// <summary> /// Gets or sets Password. /// </summary> [Required] public string Password { get; set; } /// <summary> /// Gets or sets PortalId. /// </summary> public int PortalId { get; set; } /// <summary> /// Gets or sets the country for the user. /// </summary> [StringLength(10, ErrorMessageResourceName = "UserPostalCodeStringLengthValidationError", ErrorMessageResourceType = typeof(Resources))] [TextLineInputValidator] [Display(Name = "UserPostalCodeLabelText", ResourceType = typeof(Resources))] [PostalCodeValidator] public string PostalCode { get; set; } /// <summary> /// Gets or sets Telephone. /// </summary> public string Telephone { get; set; } /// <summary> /// Gets or sets the identifier for the user. /// </summary> public int UserId { get; set; } /// <summary> /// Gets or sets UserName. /// </summary> [Required] public string UserName { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="UserRepository.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.EF.Repositories { using System.Collections.Generic; using Firebrick.Data.RepositoryContracts; using Firebrick.Model; /// <summary> /// The user repository. /// </summary> public class UserRepository : BaseRepository<User>, IUserRepository { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="UserRepository"/> class. /// </summary> /// <param name="databaseFactory"> /// The database factory. /// </param> public UserRepository(IDatabaseFactory databaseFactory) : base(databaseFactory) { } #endregion #region Public Methods /// <summary> /// The assign role. /// </summary> /// <param name="userName"> /// The user name. /// </param> /// <param name="roleNames"> /// The role names. /// </param> public void AssignRole(string userName, List<string> roleNames) { } /// <summary> /// </summary> /// <param name="userName"> /// The user name. /// </param> /// <param name="password"> /// The password. /// </param> /// <returns> /// </returns> public bool AuthenticateUser(string userName, string password) { return true; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PageControllerActionInitializer.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.EF.Initializers { using System.Data.Entity.Migrations; using System.Data.Entity.Validation; using System.Diagnostics; using Firebrick.Model; /// <summary> /// The page controller action initializer. /// </summary> public static class PageControllerActionInitializer { #region Public Methods /// <summary> /// The Add. /// </summary> /// <param name="context"> /// The context. /// </param> public static void Add(FirebrickContext context) { context.PageControllerActions.AddOrUpdate( new PageControllerAction { ActionName = "Index", ControllerName = "WebFramework", FriendlyName = "Default View", PageControllerActionId = 1, IsSelectable = true }); //context.PageControllerActions.AddOrUpdate( // new PageControllerAction // { // ActionName = "IndexTwoColWideLeft", // ControllerName = "WebFramework", // FriendlyName = "Two Column Wide Left", // PageControllerActionId = 2, // IsSelectable = true // }); //context.PageControllerActions.AddOrUpdate( // new PageControllerAction // { // ActionName = "IndexTripleRow", // ControllerName = "WebFramework", // FriendlyName = "Triple Row", // PageControllerActionId = 3, // IsSelectable = true // }); //context.PageControllerActions.AddOrUpdate( // new PageControllerAction // { // ActionName = "Index", // ControllerName = "WebFramework", // FriendlyName = "Unused One", // PageControllerActionId = 4, // IsSelectable = false // }); //context.PageControllerActions.AddOrUpdate( // new PageControllerAction // { // ActionName = "Index", // ControllerName = "WebFramework", // FriendlyName = "Unused Two", // PageControllerActionId = 5, // IsSelectable = false // }); context.PageControllerActions.AddOrUpdate( new PageControllerAction { ActionName = "Login", ControllerName = "Account", FriendlyName = "User Login Page", PageControllerActionId = 2, IsSelectable = false }); context.PageControllerActions.AddOrUpdate( new PageControllerAction { ActionName = "Register", ControllerName = "Account", FriendlyName = "User Register Page", PageControllerActionId = 3, IsSelectable = false }); context.PageControllerActions.AddOrUpdate( new PageControllerAction { ActionName = "ChangePassword", ControllerName = "Account", FriendlyName = "User Change Password Page", PageControllerActionId = 4, IsSelectable = false }); try { context.SaveChanges(); } catch (DbEntityValidationException dbEx) { foreach (DbEntityValidationResult validationErrors in dbEx.EntityValidationErrors) { foreach (DbValidationError validationError in validationErrors.ValidationErrors) { Debug.WriteLine( "Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } } } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ClientAssetConfig.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Model { using System.ComponentModel.DataAnnotations; /// <summary> /// The client asset config. /// </summary> public class ClientAssetConfig { #region Public Properties /// <summary> /// Gets or sets ClientAssetConfigId. /// </summary> [Key] public int ClientAssetConfigId { get; set; } /// <summary> /// Gets or sets ClientAssetId. /// </summary> public int ClientAssetId { get; set; } /// <summary> /// Gets or sets PageId. /// </summary> public int? PageId { get; set; } /// <summary> /// Gets or sets PartId. /// </summary> public int? PartId { get; set; } #endregion } }<file_sep>namespace Firebrick.Data.RepositoryContracts { using Firebrick.Model; public interface ISeoRouteValueRepository : IRepository<SeoRouteValue> { } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="UserInitializer.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // <summary> // The user initializer. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.EF.Initializers { using System; using System.Data.Entity.Migrations; using System.Data.Entity.Validation; using System.Diagnostics; using Firebrick.Model; /// <summary> /// The user initializer. /// </summary> public static class UserInitializer { #region Public Methods /// <summary> /// The add. /// </summary> /// <param name="context"> /// The context. /// </param> public static void Add(FirebrickContext context) { var admin = new User { Country = "England", DisplayName = "Mr Admin", HasRegistered = true, Password = "<PASSWORD>", PortalId = 1, PostalCode = "GL50", UserId = 1, UserName = "admin", FirstName = "John", LastName = "Barnes", FullName = "<NAME>", DateCreated = DateTime.Now, JobTitle = "Winger", LastModified = DateTime.Now, IsContactable = true, IsActive = true, EMail = "<EMAIL>" }; var registered = new User { Country = "England", DisplayName = "Rushy", HasRegistered = true, Password = "<PASSWORD>", PortalId = 1, PostalCode = "GL50", UserId = 2, UserName = "ianrush", FirstName = "Ian", LastName = "Rush", FullName = "<NAME>", DateCreated = DateTime.Now, JobTitle = "Striker", LastModified = DateTime.Now, IsContactable = true, IsActive = true, EMail = "<EMAIL>" }; // Password "<PASSWORD>" equals "a" // <PASSWORD>61E4C<PASSWORD>F3F0682<PASSWORD> = password context.Users.AddOrUpdate(admin); context.Users.AddOrUpdate(registered); try { context.SaveChanges(); } catch (DbEntityValidationException dbEx) { foreach (DbEntityValidationResult validationErrors in dbEx.EntityValidationErrors) { foreach (DbValidationError validationError in validationErrors.ValidationErrors) { Debug.WriteLine( "Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } } } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IRoleRespository.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.RepositoryContracts { using Firebrick.Model; /// <summary> /// The i role respository. /// </summary> public interface IRoleRespository : IRepository<Roles> { } }<file_sep>1. Code and Style Conventions = ReSharper + StyleCop 2. Use of "var" should be done appropriately. Do not over use. Ensure code is easily readable. <file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Exception.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Model { using System; using System.ComponentModel.DataAnnotations; /// <summary> /// The exception. /// </summary> public class Exception { #region Public Properties /// <summary> /// Gets or sets Created. /// </summary> public DateTime Created { get; set; } /// <summary> /// Gets or sets ExceptionId. /// </summary> [Key] public int ExceptionId { get; set; } /// <summary> /// Gets or sets Message. /// </summary> public string Message { get; set; } /// <summary> /// Gets or sets Method. /// </summary> public string Method { get; set; } /// <summary> /// Gets or sets PortalId. /// </summary> public int PortalId { get; set; } /// <summary> /// Gets or sets Source. /// </summary> public string Source { get; set; } /// <summary> /// Gets or sets UserId. /// </summary> public int UserId { get; set; } #endregion } }<file_sep>namespace Firebrick.UI.Core.Security { using System; using System.Web.Security; using Firebrick.Domain.ServiceBinders.Web; using Firebrick.Service.Contracts; using Microsoft.Practices.ServiceLocation; internal class CmsRoleProvider : RoleProvider { #region Public Properties public override string ApplicationName { get; set; } #endregion #region Public Methods public override void AddUsersToRoles(string[] usernames, string[] roleNames) { throw new NotImplementedException(); } public override void CreateRole(string roleName) { throw new NotImplementedException(); } public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) { throw new NotImplementedException(); } public override string[] FindUsersInRole(string roleName, string usernameToMatch) { throw new NotImplementedException(); } public override string[] GetAllRoles() { throw new NotImplementedException(); } public override string[] GetRolesForUser(string username) { var serviceBinder = GetServiceBinder(); var userId = serviceBinder.GetUserId(username); return serviceBinder.GetRolesForUser(userId); } public override string[] GetUsersInRole(string roleName) { throw new NotImplementedException(); } public override bool IsUserInRole(string username, string roleName) { var serviceBinder = GetServiceBinder(); var rps = serviceBinder.GetRolePageRestrictions(2); return true; } public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) { throw new NotImplementedException(); } public override bool RoleExists(string roleName) { throw new NotImplementedException(); } #endregion #region Methods private WebCoreSecurityServiceBinder GetServiceBinder() { return new WebCoreSecurityServiceBinder( ServiceLocator.Current.GetService(typeof(IUserService)) as IUserService, ServiceLocator.Current.GetService(typeof(IRoleService)) as IRoleService, ServiceLocator.Current.GetService(typeof(IUserRolesService)) as IUserRolesService, ServiceLocator.Current.GetService(typeof(IRolePageRestrictionService)) as IRolePageRestrictionService); } #endregion } }<file_sep>namespace Firebrick.Domain.Helpers.PartialViews { using System; using System.Collections.Generic; using Firebrick.Domain.ViewModels.WebAdmin.CmsPlugins; public class MainSideMenu { #region Constants and Fields private readonly string currentUrl; private readonly CmsPluginMainSideMenuViewModel mainSideMenu = new CmsPluginMainSideMenuViewModel(); #endregion #region Constructors and Destructors public MainSideMenu(string currentUrl) { this.currentUrl = currentUrl; this.BuildSideMenu(); } #endregion #region Public Properties public CmsPluginMainSideMenuViewModel ViewModel { get { return this.mainSideMenu; } } #endregion #region Methods private void AddMenuManagerMenu() { this.mainSideMenu.ParentItems.Add( new CmsPluginMainSideMenuViewModelItem { ItemId = 20, Title = "Menu Manager", Url = "/CmsMenuManager/Tree" }); } private void AddPageMenu() { IEnumerable<CmsPluginMainSideMenuViewModelItem> submenu = null; var subMenuDefintion = new Dictionary<string, Func<MainSideMenu, IEnumerable<CmsPluginMainSideMenuViewModelItem>>>(); subMenuDefintion.Add("/CmsPageManager", @this => @this.PageListSubMenu()); subMenuDefintion.Add("/CmsPageManager/Edit/", @this => @this.PageEditSubMenu()); if (subMenuDefintion.ContainsKey(this.currentUrl)) { submenu = subMenuDefintion[this.currentUrl](this); } this.mainSideMenu.ParentItems.Add( new CmsPluginMainSideMenuViewModelItem { ItemId = 10, Title = "Pages", Url = "/CmsPageManager", ChildItems = submenu }); } private void AddSettingsMenu() { this.mainSideMenu.ParentItems.Add( new CmsPluginMainSideMenuViewModelItem { ItemId = 40, Title = "Settings", Url = "/CmsPortalManager/SimpleSettings" }); } private void AddUsersMenu() { IEnumerable<CmsPluginMainSideMenuViewModelItem> submenu = null; var subMenuDefintion = new Dictionary<string, Func<MainSideMenu, IEnumerable<CmsPluginMainSideMenuViewModelItem>>>(); subMenuDefintion.Add("/CmsUserManager", @this => @this.UserListSubMenu()); if (subMenuDefintion.ContainsKey(this.currentUrl)) { submenu = subMenuDefintion[this.currentUrl](this); } this.mainSideMenu.ParentItems.Add(new CmsPluginMainSideMenuViewModelItem { ItemId = 30, Title = "Users", Url = "/CmsUserManager", ChildItems = submenu }); } private void BuildSideMenu() { // The order they are called will affect this.AddPageMenu(); this.AddMenuManagerMenu(); this.AddUsersMenu(); this.AddSettingsMenu(); //AddSocialMediaMenu(); //AddAutomotiveMenu(); } private IEnumerable<CmsPluginMainSideMenuViewModelItem> PageEditSubMenu() { var submenu = new List<CmsPluginMainSideMenuViewModelItem>(); submenu.Add( new CmsPluginMainSideMenuViewModelItem { ItemId = 11, Title = "Parts", Url = "/CmsPageManager#Parts" }); submenu.Add( new CmsPluginMainSideMenuViewModelItem { ItemId = 12, Title = "SEO", Url = "/CmsPageManager#SEO" }); return submenu; } private IEnumerable<CmsPluginMainSideMenuViewModelItem> PageListSubMenu() { var submenu = new List<CmsPluginMainSideMenuViewModelItem>(); submenu.Add( new CmsPluginMainSideMenuViewModelItem { ItemId = 11, Title = "Add New", Url = "/CmsPageManager/Add" }); return submenu; } private IEnumerable<CmsPluginMainSideMenuViewModelItem> UserListSubMenu() { var submenu = new List<CmsPluginMainSideMenuViewModelItem>(); submenu.Add( new CmsPluginMainSideMenuViewModelItem { ItemId = 31, Title = "Add New", Url = "/CmsUserManager/Add" }); return submenu; } #endregion } }<file_sep>namespace Firebrick.UI.Core.Helpers { public static class BooleanExtensions { #region Public Methods public static string ToYesNoString(this bool value) { return value ? "Yes" : "No"; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="WebCoreServiceBinder.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.ServiceBinders.Web { using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; using Firebrick.Domain.IO; using Firebrick.Domain.ViewModels.Web.Core; using Firebrick.Model; using Firebrick.Service.Contracts; /// <summary> /// The web core service binder. /// </summary> public class WebCoreServiceBinder { #region Constants and Fields private readonly IDomainService domainService; private readonly IPageService pageService; private readonly ISeoDecoratorService seoDecoratorService; private readonly ISeoRouteValueService seoRouteValueService; #endregion #region Constructors and Destructors public WebCoreServiceBinder( IPageService pageService, ISeoDecoratorService seoDecoratorService, ISeoRouteValueService seoRouteValueService, IDomainService domainService) { this.pageService = pageService; this.seoDecoratorService = seoDecoratorService; this.seoRouteValueService = seoRouteValueService; this.domainService = domainService; } #endregion #region Public Methods public string RobotsViewModelBind() { //// TODO: [RP] [14082012] Need to get the primary domain here (and here...) Domain domain = this.GetDomain(1); var sb = new StringBuilder(); IEnumerable<SeoDecorator> seoDecoratorsList = this.seoDecoratorService.GetMany(smp => smp.RobotsIndex); IEnumerable<Page> pages = this.pageService.GetMany(p => p.IsPublished); IEnumerable<SeoDecorator> pageSeoDecoratorsQuery = from s in seoDecoratorsList join p in pages on s.PageId equals p.PageId select new SeoDecorator { LookFor = s.LookFor, RobotsFollow = s.RobotsFollow, SeoDecoratorId = s.SeoDecoratorId }; sb.AppendLine(string.Format("Sitemap: http://{0}/sitemap.xml", domain.HostHeader)); sb.AppendLine("User-agent: *"); foreach (SeoDecorator seoDecorator in pageSeoDecoratorsQuery.ToList()) { sb.AppendLine( string.Format("{0}: /{1}", GetAllowDisallow(seoDecorator.RobotsFollow), seoDecorator.LookFor)); } return sb.ToString(); } /// <summary> /// The site map view model bind. /// </summary> /// <returns> /// xml string /// </returns> public string SiteMapViewModelBind() { //// TODO: [RP] [14082012] Need to get the primary domain here Domain domain = this.GetDomain(1); string xslStylesheet = string.Format( "\n<?xml-stylesheet type=\"text/xsl\" href=\"http://{0}/ClientConfig/Design/xsl/sitemap.xsl\"?>", domain.HostHeader); var serializer = new XmlSerializer(typeof(SiteMapViewModel)); var xmlResult = new Utf8StringWriter(); IEnumerable<SeoDecorator> seoDecoratorsList = this.seoDecoratorService.GetMany(smp => smp.RobotsIndex); IEnumerable<Page> pages = this.pageService.GetMany(p => p.IsPublished); IEnumerable<SeoDecorator> pageSeoDecoratorsQuery = from s in seoDecoratorsList join p in pages on s.PageId equals p.PageId select new SeoDecorator { LookFor = s.LookFor, LastModified = s.LastModified, Priority = s.Priority, SeoDecoratorId = s.SeoDecoratorId }; var siteMapModel = new SiteMapViewModel(); foreach (SeoDecorator seoDecorator in pageSeoDecoratorsQuery.ToList()) { siteMapModel.Add( new Location { Url = string.Format("http://{0}/{1}", domain.HostHeader, seoDecorator.LookFor), LastModified = seoDecorator.LastModified.ToString("yyyy-MM-dd"), ChangeFrequency = Location.ChangeFrequencyEnum.monthly, Priority = seoDecorator.Priority }); } serializer.Serialize(xmlResult, siteMapModel); return xmlResult.ToString().Insert(38, xslStylesheet); } /// <summary> /// The url route view model bind. /// </summary> /// <param name="lookFor"> /// The look for. /// </param> /// <returns> /// the url route view model /// </returns> public UrlRouteViewModel UrlRouteViewModelBind(string lookFor) { UrlRouteViewModel viewModel = null; SeoDecorator seo = this.seoDecoratorService.GetByLookFor(lookFor); IEnumerable<SeoRouteValue> routeValues = null; Page page = null; if (seo != null) { page = this.pageService.GetById(seo.PageId); routeValues = this.seoRouteValueService.GetMany(rv => rv.SeoDecoratorId == seo.SeoDecoratorId); } if (page != null) { viewModel = new UrlRouteViewModel { PageId = page.PageId, ActionName = page.ActionName, ControllerName = page.ControllerName, PortalId = page.PortalId, Title = page.Title, LookFor = seo.LookFor }; if (routeValues != null) { foreach (SeoRouteValue seoRouteValue in routeValues) { viewModel.RouteValues.Add(seoRouteValue.Key, seoRouteValue.Value); } } } return viewModel; } #endregion #region Methods private static string GetAllowDisallow(bool index) { return index ? "Allow" : "Disallow"; } private Domain GetDomain(int portalId) { return this.domainService.Get(d => d.PortalId == portalId); } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ClientAssetRepository.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.EF.Repositories { using Firebrick.Data.RepositoryContracts; using Firebrick.Model; /// <summary> /// The client asset repository. /// </summary> public class ClientAssetRepository : BaseRepository<ClientAsset>, IClientAssetRepository { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="ClientAssetRepository"/> class. /// </summary> /// <param name="databaseFactory"> /// The database factory. /// </param> public ClientAssetRepository(IDatabaseFactory databaseFactory) : base(databaseFactory) { } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="UserService.cs" company="Beyond"> // Copyright Beyond 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Service { using System.Collections.Generic; using Firebrick.Data; using Firebrick.Data.EF.Repositories; using Firebrick.Model; using Firebrick.Service.Contracts; /// <summary> /// The user service. /// </summary> public class UserService : IUserService { #region Constants and Fields /// <summary> /// The unit of work. /// </summary> private readonly IUnitOfWork unitOfWork; /// <summary> /// The user repository. /// </summary> private readonly IUserRepository userRepository; #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="UserService"/> class. /// </summary> /// <param name="userRepository"> /// The category repository. /// </param> /// <param name="unitOfWork"> /// The unit of work. /// </param> public UserService(IUserRepository userRepository, IUnitOfWork unitOfWork) { this.userRepository = userRepository; this.unitOfWork = unitOfWork; } #endregion #region Public Methods /// <summary> /// The get users. /// </summary> /// <returns> /// Enumeration of users /// </returns> public IEnumerable<User> GetUsers() { IEnumerable<User> users = this.userRepository.GetAll(); return users; } /// <summary> /// The save user. /// </summary> /// <param name="user"> /// The user. /// </param> public void SaveUser(User user) { this.unitOfWork.Commit(); } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PageInitializer.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.EF.Initializers { using System; using System.Collections.Generic; using System.Data.Entity.Migrations; using System.Data.Entity.Validation; using System.Diagnostics; using Firebrick.Model; /// <summary> /// The page initializer. /// </summary> public static class PageInitializer { #region Public Methods /// <summary> /// The add. /// </summary> /// <param name="context"> /// The context. /// </param> public static void Add(FirebrickContext context) { var pages = new List<Page>(); pages.Add( new Page { ActionName = "Index", ControllerName = "WebFramework", Title = "Home", PageId = 1, PageParentId = -1, PageTemplateId = 2, PortalId = 1, ShowOnMenu = true, Order = 10, IsPublished = true, Created = DateTime.Now, CreatedBy = "Admin", LastModified = DateTime.Now, LastModifiedBy = "Admin", PageStructureStyleId = 1 }); pages.Add( new Page { ActionName = "Index", ControllerName = "WebFramework", Title = "About", PageId = 2, PageParentId = -1, PageTemplateId = 1, PortalId = 1, ShowOnMenu = true, Order = 20, IsPublished = true, Created = DateTime.Now, CreatedBy = "Admin", LastModified = DateTime.Now, LastModifiedBy = "Admin", PageStructureStyleId = 1 }); pages.Add( new Page { ActionName = "Index", ControllerName = "WebFramework", Title = "Services", PageId = 3, PageParentId = -1, PageTemplateId = 1, PortalId = 1, ShowOnMenu = true, Order = 30, IsPublished = true, Created = DateTime.Now, CreatedBy = "Admin", LastModified = DateTime.Now, LastModifiedBy = "Admin", PageStructureStyleId = 1 }); pages.Add( new Page { ActionName = "Index", ControllerName = "WebFramework", Title = "Features", PageId = 4, PageParentId = -1, PageTemplateId = 1, PortalId = 1, ShowOnMenu = true, Order = 40, IsPublished = true, Created = DateTime.Now, CreatedBy = "Admin", LastModified = DateTime.Now, LastModifiedBy = "Admin", PageStructureStyleId = 1 }); pages.Add( new Page { ActionName = "Index", ControllerName = "WebFramework", Title = "Contact", PageId = 5, PageParentId = -1, PageTemplateId = 1, PortalId = 1, ShowOnMenu = true, Order = 50, IsPublished = true, Created = DateTime.Now, CreatedBy = "Admin", LastModified = DateTime.Now, LastModifiedBy = "Admin", PageStructureStyleId = 1 }); pages.Add( new Page { ActionName = "Login", ControllerName = "Account", Title = "Login", PageId = 6, PageParentId = -1, PageTemplateId = 1, PortalId = 1, ShowOnMenu = false, Order = 60, IsPublished = true, Created = DateTime.Now, CreatedBy = "Admin", LastModified = DateTime.Now, LastModifiedBy = "Admin", PageStructureStyleId = 1 }); pages.ForEach(p => context.Pages.AddOrUpdate(p)); try { context.SaveChanges(); } catch (DbEntityValidationException dbEx) { foreach (DbEntityValidationResult validationErrors in dbEx.EntityValidationErrors) { foreach (DbValidationError validationError in validationErrors.ValidationErrors) { Debug.WriteLine( "Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } } } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="CustomWebException.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Framework.Exceptions { using System; /// <summary> /// The custom web exception. /// </summary> [Serializable] public class CustomWebException : Exception { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="CustomWebException"/> class. /// </summary> public CustomWebException() : base("Custom Web Exception has been thrown.") { } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IUserService.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Service.Contracts { using System.Collections.Generic; using Firebrick.Model; /// <summary> /// The i user service. /// </summary> public interface IUserService : IService<User> { #region Public Methods void AssignRole(string userName, List<string> roleName); /// <summary> /// </summary> /// <param name="userName"> /// The user name. /// </param> /// <param name="password"> /// The password. /// </param> /// <returns> /// </returns> bool AuthenticatedUser(string userName, string password); User GetByUsername(string userName); /// <summary> /// The get users. /// </summary> /// <returns> /// Enumeration of users /// </returns> IEnumerable<User> SpecialGetUsers(); #endregion } }<file_sep>namespace Firebrick.ContentManagement.Web.Controllers { using System.Web.Mvc; using Firebrick.UI.Core.Controllers; public class SocialMediaController : BasePartController { #region Public Methods [ChildActionOnly] public ActionResult Index() { return this.PartialView(); } #endregion } }<file_sep>namespace Firebrick.Admin.Web.Controllers { using System.Collections.Generic; using System.Web.Http; using Firebrick.Domain.ServiceBinders.WebAdmin; using Firebrick.Domain.ViewModels.WebAdmin.CmsMenuManager; using Firebrick.Service.Contracts; public class CmsApiController : ApiController { #region Constants and Fields /// <summary> /// The page service. /// </summary> private readonly IUserService userService; #endregion #region Constructors and Destructors public CmsApiController(IUserService userService) { this.userService = userService; } #endregion #region Public Methods //public IEnumerable<CmsUserManagerIndexViewModelListItem> GetUsers() //{ // CmsUserManagerServiceBinder modelBinder = this.GetServiceBinder(); // CmsUserManagerIndexViewModel viewModel = modelBinder.IndexViewModelBind(); // return viewModel.Users; //} #endregion #region Methods //private CmsUserManagerServiceBinder GetServiceBinder() //{ // return new CmsUserManagerServiceBinder(this.userService); //} #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ClientAssetConfigService.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Service.Implementations { using Firebrick.Data; using Firebrick.Data.RepositoryContracts; using Firebrick.Model; using Firebrick.Service.Contracts; /// <summary> /// The client asset config service. /// </summary> public class ClientAssetConfigService : BaseService<ClientAssetConfig>, IClientAssetConfigService { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="ClientAssetConfigService"/> class. /// </summary> /// <param name="clientAssetConfigRepository"> /// The client asset config repository. /// </param> /// <param name="unitOfWork"> /// The unit of work. /// </param> public ClientAssetConfigService( IClientAssetConfigRepository clientAssetConfigRepository, IUnitOfWork unitOfWork) { this.Repository = clientAssetConfigRepository; this.UnitOfWork = unitOfWork; } #endregion } }<file_sep>namespace Firebrick.Data.RepositoryContracts { using Firebrick.Model; public interface INotificationRepository : IRepository<Notification> { } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="RoleInitializer.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.EF.Initializers { using System.Data.Entity.Migrations; using System.Data.Entity.Validation; using System.Diagnostics; using Firebrick.Model; /// <summary> /// The role initializer. /// </summary> public static class RoleInitializer { #region Public Methods /// <summary> /// The Add. /// </summary> /// <param name="context"> /// The context. /// </param> public static void Add(FirebrickContext context) { var administrator = new Roles { IsAvailable = true, Name = "Administrator", Order = 10, RoleId = 1 }; var manager = new Roles { IsAvailable = true, Name = "System Manager", Order = 20, RoleId = 2 }; var publisher = new Roles { IsAvailable = true, Name = "Content Publisher", Order = 30, RoleId = 3 }; var author = new Roles { IsAvailable = true, Name = "Content Author", Order = 40, RoleId = 4 }; var extranet = new Roles { IsAvailable = true, Name = "Extranet User", Order = 50, RoleId = 5 }; var intranet = new Roles { IsAvailable = true, Name = "Intranet User", Order = 60, RoleId = 6 }; var spare1 = new Roles { IsAvailable = false, Name = "Spare One", Order = 70, RoleId = 7 }; var spare2 = new Roles { IsAvailable = false, Name = "Spare Two", Order = 80, RoleId = 8 }; var registered = new Roles { IsAvailable = true, Name = "Registered", Order = 90, RoleId = 9 }; var visitor = new Roles { IsAvailable = true, Name = "Visitor", Order = 100, RoleId = 10 }; context.Roles.AddOrUpdate(administrator); context.Roles.AddOrUpdate(manager); context.Roles.AddOrUpdate(publisher); context.Roles.AddOrUpdate(author); context.Roles.AddOrUpdate(extranet); context.Roles.AddOrUpdate(intranet); context.Roles.AddOrUpdate(spare1); context.Roles.AddOrUpdate(spare2); context.Roles.AddOrUpdate(registered); context.Roles.AddOrUpdate(visitor); try { context.SaveChanges(); } catch (DbEntityValidationException dbEx) { foreach (DbEntityValidationResult validationErrors in dbEx.EntityValidationErrors) { foreach (DbValidationError validationError in validationErrors.ValidationErrors) { Debug.WriteLine( "Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } } } #endregion } }<file_sep>namespace Firebrick.Data.EF.Repositories { using Firebrick.Data.RepositoryContracts; using Firebrick.Model; public class NotificationTypeRepository : BaseRepository<NotificationType>, INotificationTypeRepository { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="NotificationTypeRepository"/> class. /// </summary> /// <param name="databaseFactory"> /// The database factory. /// </param> public NotificationTypeRepository(IDatabaseFactory databaseFactory) : base(databaseFactory) { } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IRepositoryInitializer.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data { /// <summary> /// Repository Initializer Interface /// </summary> public interface IRepositoryInitializer { #region Public Methods /// <summary> /// The initialize. /// </summary> void Initialize(); #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="UnityDependencyResolver.cs" company="Beyond"> // Copyright Beyond 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.UI.Core.UnityExtensions { using System; using System.Collections.Generic; using System.Web.Mvc; using Microsoft.Practices.Unity; /// <summary> /// The unity dependency resolver. /// </summary> public class UnityDependencyResolver : IDependencyResolver { #region Constants and Fields /// <summary> /// The unity. /// </summary> private readonly IUnityContainer unity; #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="UnityDependencyResolver"/> class. /// </summary> /// <param name="unity"> /// The unity. /// </param> public UnityDependencyResolver(IUnityContainer unity) { this.unity = unity; } #endregion #region Public Methods /// <summary> /// The get service. /// </summary> /// <param name="serviceType"> /// The service type. /// </param> /// <returns> /// The get service. /// </returns> public object GetService(Type serviceType) { try { return this.unity.Resolve(serviceType); } catch (ResolutionFailedException) { // By definition of IDependencyResolver contract, this should return null if it cannot be found. return null; } } /// <summary> /// The get services. /// </summary> /// <param name="serviceType"> /// The service type. /// </param> /// <returns> /// </returns> public IEnumerable<object> GetServices(Type serviceType) { try { return this.unity.ResolveAll(serviceType); } catch (ResolutionFailedException) { // By definition of IDependencyResolver contract, this should return null if it cannot be found. return null; } } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="UserRolesService.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Service.Implementations { using System.Collections.Generic; using Firebrick.Data; using Firebrick.Data.RepositoryContracts; using Firebrick.Model; using Firebrick.Service.Contracts; using System.Linq; /// <summary> /// The user roles service. /// </summary> public class UserRolesService : BaseService<UserRole>, IUserRolesService { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="UserRolesService"/> class. /// </summary> /// <param name="userRolesRepository"> /// The user roles repository. /// </param> /// <param name="unitOfWork"> /// The unit of work. /// </param> public UserRolesService(IUserRolesRepository userRolesRepository, IUnitOfWork unitOfWork) { this.Repository = userRolesRepository; this.UnitOfWork = unitOfWork; } #endregion #region Public Methods public UserRole Get(int roleId, int userId) { return this.Repository.Get(ur => ur.RoleId == roleId && ur.UserId == userId); } public string[] GetUserRoles(int userId) { return this.Repository.GetMany(ur => ur.UserId == userId).Select(ur => ur.RoleId.ToString()).ToArray(); } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="RichContentEditViewModel.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.ViewModels.ContentManagement.RichContent { using System.ComponentModel.DataAnnotations; using System.Web.Mvc; /// <summary> /// The rich content edit view model. /// </summary> public class RichContentEditViewModel { #region Public Properties /// <summary> /// Gets or sets Html. /// </summary> [UIHint("tinymce_jquery_full")] [AllowHtml] public string Html { get; set; } /// <summary> /// Gets or sets Id. /// </summary> public int ContentBlobId { get; set; } /// <summary> /// Gets or sets PartId. /// </summary> public int PartId { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IUserRolesRepository.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.RepositoryContracts { using Firebrick.Model; /// <summary> /// The i user roles repository. /// </summary> public interface IUserRolesRepository : IRepository<UserRole> { } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="CmsPageManagerEditPartViewModel.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.ViewModels.WebAdmin.CmsPageManager { /// <summary> /// The cms page manager edit part view model. /// </summary> public class CmsPageManagerEditPartViewModel { #region Public Properties public string AdminPartAction { get; set; } public string AdminPartController { get; set; } /// <summary> /// Gets or sets Order. /// </summary> public int Order { get; set; } public int RowId { get; set; } /// <summary> /// Gets or sets PartId. /// </summary> public int PartId { get; set; } /// <summary> /// Gets or sets Title. /// </summary> public string Title { get; set; } public int ColSpan { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ClientAssetTypeRepository.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.EF.Repositories { using Firebrick.Data.RepositoryContracts; using Firebrick.Model; /// <summary> /// The client asset type repository. /// </summary> public class ClientAssetTypeRepository : BaseRepository<ClientAssetType>, IClientAssetTypeRepository { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="ClientAssetTypeRepository"/> class. /// </summary> /// <param name="databaseFactory"> /// The database factory. /// </param> public ClientAssetTypeRepository(IDatabaseFactory databaseFactory) : base(databaseFactory) { } #endregion } }<file_sep>namespace Firebrick.Domain.Messaging.EMail { using System.Net.Mail; using Firebrick.Entities.Messaging; public static class EMailMessageFactory { #region Public Methods public static MailMessage GetContactUsEmail(SendEmailConfiguration emailConfiguration, string modelUserName, string modelTelephone, string modelEmail, string modelMessage) { //// var templatePath = ConfigurationManager.AppSettings["WelcomeTemplate"]; const string templatePath = "C:\\Raj\\TESTING\\Templates\\EMail\\ContactUsEmailTemplate.cshtml"; string body = EMailTemplateResolver.GetMessageBody( templatePath, new { Fullname = modelUserName, Telephone = modelTelephone, UserEmail = modelEmail, Message = modelMessage }); //// Dynamic object can be created and passed in the n'Parameters as the model object return new MailMessage( emailConfiguration.SenderAddress, emailConfiguration.ToAddress, emailConfiguration.Subject, body); } public static MailMessage GetResetUserPasswordEmail(SendEmailConfiguration emailConfiguration) { string body = string.Empty; return new MailMessage( emailConfiguration.SenderAddress, emailConfiguration.ToAddress, emailConfiguration.Subject, body); } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IDatabaseFactory.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.EF { using System; /// <summary> /// The i database factory. /// </summary> public interface IDatabaseFactory : IDisposable { #region Public Methods /// <summary> /// The get. /// </summary> /// <returns> /// </returns> FirebrickContext Get(); #endregion } }<file_sep>namespace Firebrick.Web.UI.UI { using System.Web.Mvc; using System.Web.Routing; using Firebrick.UI.Core.Routing; public class RouteConfig { #region Public Methods public static void RegisterRoutes(RouteCollection routes) { //routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); //routes.MapRoute( // name: "Default", // url: "{controller}/{action}/{id}", // defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } //); routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.([iI][cC][oO]|[gG][iI][fF])(/.*)?" }); routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.IgnoreRoute("{resource}.xml/{*pathInfo}"); routes.IgnoreRoute("{resource}.ashx/{*pathInfo}"); routes.IgnoreRoute("sitemap.xml"); routes.IgnoreRoute("robots.txt"); routes.MapRoute("Default", "{*FriendlyUrl}", new[] { "Firebrick.Web.Controllers" }).RouteHandler = new FriendlyUrlRouteHandler(); } #endregion } }<file_sep>namespace Firebrick.Domain.ServiceBinders { using System.Collections.Generic; using System.Linq; using Firebrick.Domain.ViewModels; using Firebrick.Model; using Firebrick.Service.Contracts; /// <summary> /// The page defintion service binder. /// </summary> public class PageDefinitionServiceBinder { #region Constants and Fields /// <summary> /// The page service. /// </summary> private readonly IPageService pageService; /// <summary> /// The page template service. /// </summary> private readonly IPageTemplateService pageTemplateService; private readonly IPartService partService; private readonly IPartTypeService partTypeService; private readonly IPageTemplateZoneMapService templateZoneMapService; #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="PageDefinitionServiceBinder"/> class. /// </summary> /// <param name="pageService"> /// The page service. /// </param> /// <param name="pageTemplateService"> /// The page template service. /// </param> public PageDefinitionServiceBinder( IPageService pageService, IPageTemplateService pageTemplateService, IPageTemplateZoneMapService templateZoneMapService, IPartService partService, IPartTypeService partTypeService) { this.pageService = pageService; this.pageTemplateService = pageTemplateService; this.templateZoneMapService = templateZoneMapService; this.partService = partService; this.partTypeService = partTypeService; } #endregion #region Public Methods /// <summary> /// Binds PageDefinitionViewModel /// </summary> /// <param name="pageId"> /// The page id. /// </param> /// <returns> /// Returns Page View Model /// </returns> public PageDefinitionViewModel BindModel(int pageId) { var viewModel = new PageDefinitionViewModel(); Page page = this.pageService.GetById(pageId); // GET PAGE-TEMPLATE ID PageTemplate pageTemplate = this.pageTemplateService.GetById(page.PageTemplateId); //GET THE ZONES FOR THAT TEMPLATE IEnumerable<PageTemplateZoneMap> templateZoneMaps = this.templateZoneMapService.GetMany(t => t.PageTemplateId == pageTemplate.PageTemplateId); //GET THE PARTS FOR THAT PAGE IEnumerable<Part> parts = this.partService.GetMany(p => pageId == page.PageId); //ASSOCIATE PARTS TO ZONES IDictionary<int, List<PartDefintionViewModel>> zonePartDictionary = new Dictionary<int, List<PartDefintionViewModel>>(); //CREATE PART TYPE LOOKUP IEnumerable<PartType> partTypes = this.partTypeService.GetAll(); foreach (PageTemplateZoneMap pageTemplateZoneMap in templateZoneMaps) { var zoneParts = new List<PartDefintionViewModel>(); foreach (Part part in parts) { if (part.ZoneId == pageTemplateZoneMap.PageZoneId) { var partDefViewModel = new PartDefintionViewModel(); partDefViewModel.Part = part; Part part1 = part; partDefViewModel.PartType = partTypes.FirstOrDefault(pt => pt.PartTypeId == part1.PartTypeId); zoneParts.Add(partDefViewModel); } } zonePartDictionary.Add(pageTemplateZoneMap.PageZoneId, zoneParts); } viewModel.TemplateLayoutSrc = pageTemplate.LayoutTemplateSrc; viewModel.ZonePartDictionary = zonePartDictionary; return viewModel; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="EMailTemplateResolver.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.Messaging.EMail { using System.IO; using RazorEngine; /// <summary> /// The e mail template resolver. /// </summary> public static class EMailTemplateResolver { #region Public Methods /// <summary> /// The get message body from the RAZOR view template /// </summary> /// <param name="templatePath"> /// The temaple path. /// </param> /// <param name="model"> /// The model. /// </param> /// <returns> /// The get message body. /// </returns> public static string GetMessageBody(string templatePath, dynamic model) { string template = File.ReadAllText(templatePath); dynamic body = Razor.Parse(template, model); return body; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ContentBlobRepository.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.EF.Repositories { using Firebrick.Data.RepositoryContracts; using Firebrick.Model; public class ContentBlobRepository : BaseRepository<ContentBlob>, IContentBlobRepository { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="ContentBlobRepository"/> class. /// </summary> /// <param name="databaseFactory"> /// The database factory. /// </param> public ContentBlobRepository(IDatabaseFactory databaseFactory) : base(databaseFactory) { } #endregion } }<file_sep>namespace Firebrick.Data.EF.Initializers { using System.Data.Entity.Migrations; using System.Data.Entity.Validation; using System.Diagnostics; using Firebrick.Model; public static class SeoRouteValueInitializer { #region Public Methods public static void Add(FirebrickContext context) { //context.SeoRouteValues.AddOrUpdate( // new SeoRouteValue { SeoRouteValueId = 1, SeoDecoratorId = 3, Key = "RegNo", Value = "MK55 123" }); //context.SeoRouteValues.AddOrUpdate( // new SeoRouteValue { SeoRouteValueId = 2, SeoDecoratorId = 3, Key = "NewCarOfferId", Value = "25" }); try { context.SaveChanges(); } catch (DbEntityValidationException dbEx) { foreach (DbEntityValidationResult validationErrors in dbEx.EntityValidationErrors) { foreach (DbValidationError validationError in validationErrors.ValidationErrors) { Debug.WriteLine( "Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } } } #endregion } }<file_sep>$('#btnLogout').bind('click', function () { window.location = "/Account/Logoff"; }); $('#btnEditUser').bind('click', function () { window.location = "/CmsUserManager/Edit/" + $(this).attr('data-edituser'); });<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="UserRolesRepository.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.EF.Repositories { using Firebrick.Data.RepositoryContracts; using Firebrick.Model; /// <summary> /// The user roles repository. /// </summary> public class UserRolesRepository : BaseRepository<UserRole>, IUserRolesRepository { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="UserRolesRepository"/> class. /// </summary> /// <param name="databaseFactory"> /// The database factory. /// </param> public UserRolesRepository(IDatabaseFactory databaseFactory) : base(databaseFactory) { } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="RouteManager.cs" company="Beyond"> // Copyright Beyond 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.UI.Core.Routing { using Firebrick.Domain.ViewModels.Web.Core; /// <summary> /// The route manager. /// </summary> public class RouteManager { // private readonly IPageService webPageService; #region Public Methods /// <summary> /// The get by friendly url. /// </summary> /// <param name="lookFor"> /// The look for. /// </param> /// <returns> /// </returns> public static RouteManagerPageViewModel GetByFriendlyUrl(string lookFor) { // Talk to DB here ! var webPage = new RouteManagerPageViewModel(); if (lookFor == "home") { webPage.PageId = 1; webPage.Title = "About"; webPage.PageTemplateId = 1; webPage.PortalId = 1; webPage.ControllerName = "Home"; webPage.ActionName = "Index"; } else { webPage.PageId = 7; webPage.Title = "Dummy test page"; webPage.PageTemplateId = 76; webPage.PortalId = 1; webPage.ControllerName = "Page"; webPage.ActionName = "Index"; } return webPage; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="CmsPageManagerController.cs" company=""> // // </copyright> // <summary> // The cms page manager controller. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Admin.Web.Controllers { using System; using System.Web.Mvc; using Firebrick.Domain.Helpers.Route; using Firebrick.Domain.ServiceBinders.WebAdmin; using Firebrick.Domain.ViewModels; using Firebrick.Domain.ViewModels.WebAdmin.CmsPageManager; using Firebrick.Service.Contracts; using Firebrick.UI.Core.Controllers; /// <summary> /// The cms page manager controller. /// </summary> public class CmsPageManagerController : BaseAdminController { #region Constants and Fields /// <summary> /// The page controller action service. /// </summary> private readonly IPageControllerActionService pageControllerActionService; /// <summary> /// The page service. /// </summary> private readonly IPageService pageService; /// <summary> /// The page template service /// </summary> private readonly IPageTemplateService pageTemplateService; /// <summary> /// The part service. /// </summary> private readonly IPartService partService; /// <summary> /// The part type service. /// </summary> private readonly IPartTypeService partTypeService; /// <summary> /// The seo decorator service /// </summary> private readonly ISeoDecoratorService seoDecoratorService; private readonly IRoleService roleService; private readonly IRolePageRestrictionService rolePageRestrictionService; #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="CmsPageManagerController"/> class. /// </summary> /// <param name="pageService"> /// The page service. /// </param> /// <param name="pageTemplateService"> /// The page Template Service. /// </param> /// <param name="pageControllerActionService"> /// The page Controller Action Service. /// </param> /// <param name="partTypeService"> /// The part Type Service. /// </param> /// <param name="partService"> /// The part Service. /// </param> /// <param name="seoDecoratorService">the seo decorator service</param> public CmsPageManagerController( IPageService pageService, IPageTemplateService pageTemplateService, IPageControllerActionService pageControllerActionService, IPartTypeService partTypeService, IPartService partService, ISeoDecoratorService seoDecoratorService, IRoleService roleService, IRolePageRestrictionService rolePageRestrictionService) { this.pageService = pageService; this.seoDecoratorService = seoDecoratorService; this.pageTemplateService = pageTemplateService; this.pageControllerActionService = pageControllerActionService; this.partTypeService = partTypeService; this.partService = partService; this.seoDecoratorService = seoDecoratorService; this.roleService = roleService; this.rolePageRestrictionService = rolePageRestrictionService; this.ViewBag.AddInfo = "AdditionalInfo"; } #endregion #region Public Methods /// <summary> /// The create page. /// </summary> /// <param name="id"> /// The id. /// </param> /// <returns> /// </returns> public ActionResult Add(string id) { CmsPageManagerServiceBinder modelBinder = this.GetServiceBinder(); CmsPageManagerAddViewModel viewModel = modelBinder.AddViewModelBind(Convert.ToInt32(id)); return this.View(viewModel); } /// <summary> /// The add. /// </summary> /// <param name="viewModel"> /// The view model. /// </param> /// <returns> /// </returns> [HttpPost] public ActionResult Add(CmsPageManagerAddViewModel viewModel) { CmsPageManagerServiceBinder modelBinder = this.GetServiceBinder(); if (this.ModelState.IsValid) { viewModel.CreatedBy = User.Identity.Name; viewModel = modelBinder.AddViewModelInsert(viewModel); } // viewModel = modelBinder.AddViewModelBind(pageId); return View(viewModel); } public ActionResult AsyncAddPart(string partTypeid, string partName, string zoneId, string pageId, string colSpan, string rowId, string pageStructureId) { CmsPageManagerServiceBinder modelBinder = this.GetServiceBinder(); Tuple<string, int, int> result = modelBinder.AysncEditViewAddPagePart(Convert.ToInt32(partTypeid), partName, Convert.ToInt32(zoneId), Convert.ToInt32(pageId), Convert.ToInt32(colSpan), Convert.ToInt32(rowId), Convert.ToInt32(pageStructureId)); return this.Content(result.Item2.ToString()); } public ActionResult AsyncRemovePart(string partid) { if (this.HttpContext.Request.IsAjaxRequest()) { CmsPageManagerServiceBinder modelBinder = this.GetServiceBinder(); return this.Content(modelBinder.AysncEditViewDeletePagePart(Convert.ToInt32(partid))); } return this.Content("Request failed."); } public ActionResult AsyncUpdatePartOrder(string jsonData) { CmsPageManagerServiceBinder modelBinder = this.GetServiceBinder(); return this.Content(modelBinder.AysncEditViewUpdatePageParts(jsonData)); } // GET: /AdminPage/ /// <summary> /// The page detail. /// </summary> /// <param name="id"> /// The id. /// </param> /// <returns> /// The view model /// </returns> public ActionResult Edit(string id) { CmsPageManagerServiceBinder modelBinder = this.GetServiceBinder(); CmsPageManagerEditViewModel viewModel = modelBinder.EditViewModelBind(Convert.ToInt32(id)); this.ViewBag.Page = viewModel; return this.View(viewModel); } /// <summary> /// The edit. /// </summary> /// <param name="save"> /// The save. /// </param> /// <param name="cancel"> /// The cancel. /// </param> /// <param name="delete"> /// The delete. /// </param> /// <param name="updateParts"></param> /// <param name="publish"> </param> /// <param name="viewModel"> /// The view model. /// </param> /// <returns> /// the view model /// </returns> [HttpPost] public ActionResult Edit(string cancel, string delete, string save, string updateParts, string publish, CmsPageManagerEditViewModel viewModel) { CmsPageManagerServiceBinder modelBinder = this.GetServiceBinder(); if (this.ModelState.IsValid) { if (save != null || publish != null) { if (publish != null) { viewModel.IsPublished = true; } viewModel.LastModifiedBy = User.Identity.Name; viewModel = modelBinder.EditViewModelUpdate(viewModel); } if (delete != null) { viewModel = modelBinder.EditViewModelDelete(viewModel); if (viewModel.ActionIsDeleteSuccessful != null && (bool)viewModel.ActionIsDeleteSuccessful) { return this.Redirect(WebAdmin.AdminPageList); } } if (updateParts != null) { viewModel = modelBinder.EditViewModelUpdate(viewModel); } } else { //// Okay there has been an error as the ModelState is inValid, chances are they have not completed the form all in //// however, we may now also be missing other data such as select lists viewModel = modelBinder.EditViewModelStateInValid(viewModel); this.ModelState.AddModelError("pants", "Failed to submit. Correct any errors"); //// this will display if validation fails to pass } //// TODO: [RP] [170612] Correctly handling edit screens on success and failures //// After reviewing Wordpress I think the save action should result in the user staying on the current view return View(viewModel); } /// <summary> /// The index. /// </summary> /// <returns> /// returns a view /// </returns> public ActionResult Index() { try { // IEnumerable<Model.Page> pages = this.pageService.GetAll(); CmsPageManagerServiceBinder modelBinder = this.GetServiceBinder(); CmsPageManagerIndexViewModel viewModel = modelBinder.IndexViewModelBind(); this.ViewBag.Pages = viewModel.Pages; } catch (Exception ex) { this.LoggingService.Log(ex.Message); } return this.View(); } #endregion #region Methods /// <summary> /// The get service binder. /// </summary> /// <returns> /// </returns> private CmsPageManagerServiceBinder GetServiceBinder() { return new CmsPageManagerServiceBinder( this.pageService, this.pageTemplateService, this.pageControllerActionService, this.partTypeService, this.partService, this.seoDecoratorService, this.roleService, this.rolePageRestrictionService); } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PageTemplateZoneMapServiceFixture.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Services.Tests { using Firebrick.Data; using Firebrick.Data.RepositoryContracts; using Firebrick.Model; using Firebrick.Service.Implementations; using Firebrick.Test.Helper; using Moq; using Xunit; /// <summary> /// The page template zone map service fixture. /// </summary> public class PageTemplateZoneMapServiceFixture { #region Public Methods [Fact] public void WhenGettingEntity_ThenReturnsCorrectEntity() { // Arrange var repositoryMock = new Mock<IPageTemplateZoneMapRepository>(); PageTemplateZoneMap newEntity = DefaultModelHelper.DummyPopulatedPageTemplateZoneMap(); repositoryMock.Setup(repo => repo.GetById(It.IsAny<int>())).Returns(newEntity); // Act var services = new PageTemplateZoneMapService(repositoryMock.Object, new Mock<IUnitOfWork>().Object); PageTemplateZoneMap returnedEntity = services.GetById(1); // Assert Assert.NotNull(returnedEntity); Assert.Equal(1, returnedEntity.PageZoneId); } #endregion } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Firebrick.Domain.ViewModels.WebAdmin.CmsMenuManager { public class PageInfoViewModel { public int PageId { get; set; } public string Title { get; set; } public bool IsPublished { get; set; } public bool ShowOnMenu { get; set; } } } <file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PartContainerInitializer.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.EF.Initializers { using System.Data.Entity.Migrations; using System.Data.Entity.Validation; using System.Diagnostics; using Firebrick.Model; /// <summary> /// The part container initializer. /// </summary> public class PartContainerInitializer { #region Public Methods /// <summary> /// The add. /// </summary> /// <param name="context"> /// The context. /// </param> public static void Add(FirebrickContext context) { context.PartContainers.AddOrUpdate( new PartContainer { PartContainerId = 1, Description = "Blank Container", ElementId = "ps-blank" }); context.PartContainers.AddOrUpdate( new PartContainer { PartContainerId = 2, Description = "No Header", ElementId = "ps-no-header" }); try { context.SaveChanges(); } catch (DbEntityValidationException dbEx) { foreach (DbEntityValidationResult validationErrors in dbEx.EntityValidationErrors) { foreach (DbValidationError validationError in validationErrors.ValidationErrors) { Debug.WriteLine( "Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } } } #endregion } }<file_sep>namespace Firebrick.Web.Tests.Controllers { public class MenuControllerFixture { } }<file_sep>namespace Firebrick.Domain.ServiceBinders.ContentManagement { using AutoMapper; using Firebrick.Domain.ViewModels.ContentManagement.Analytics; using Firebrick.Model; using Firebrick.Service.Contracts; public class AnalyticsServiceBinder { private readonly IAnalyticsAccountService analyticsAccountService; private readonly IPageService pageService; public AnalyticsServiceBinder(IAnalyticsAccountService analyticsAccountService, IPageService pageService) { this.analyticsAccountService = analyticsAccountService; this.pageService = pageService; } public GoogleIndividualAccountViewModel BindGoogleIndividualAccount(int pageId) { var page = pageService.GetById(pageId); var analyticsAccount = analyticsAccountService.Get(a => a.PortalId == page.PortalId); var viewModel = new GoogleIndividualAccountViewModel(); if (analyticsAccount != null) { Mapper.CreateMap<AnalyticsAccount, GoogleIndividualAccountViewModel>(); Mapper.Map(analyticsAccount, viewModel); } return viewModel; } } } <file_sep>namespace Firebrick.Service.Contracts { using Firebrick.Model; public interface ISeoRouteValueService : IService<SeoRouteValue> { } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="UnityHttpContextPerRequestLifetimeManager.cs" company="Beyond"> // Copyright Beyond 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.UI.Core.UnityExtensions { /// <summary> /// The UnityHttpContextPerRequestLifetimeManager exists solely to make it easier /// to configure the per-request lifetime manager in a configuration file. /// </summary> /// <remarks> /// An alternative approach would be to use a type converter to convert the /// configuration string and new up a <see cref="UnityPerRequestLifetimeManager"/> /// from this type converter. /// </remarks> public class UnityHttpContextPerRequestLifetimeManager : UnityPerRequestLifetimeManager { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="UnityHttpContextPerRequestLifetimeManager"/> class. /// </summary> public UnityHttpContextPerRequestLifetimeManager() : base(new HttpContextPerRequestStore()) { } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="RouteManagerPageViewModel.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.ViewModels.Web.Core { /// <summary> /// The route manager page view model. /// </summary> public class RouteManagerPageViewModel { #region Public Properties /// <summary> /// Gets or sets ActionName. /// </summary> public string ActionName { get; set; } /// <summary> /// Gets or sets ControllerName. /// </summary> public string ControllerName { get; set; } /// <summary> /// Gets or sets PageId. /// </summary> public int PageId { get; set; } /// <summary> /// Gets or sets ParentId. /// </summary> public int PageParentId { get; set; } /// <summary> /// Gets or sets TemplateId. /// </summary> public int PageTemplateId { get; set; } /// <summary> /// Gets or sets PortalId. /// </summary> public int PortalId { get; set; } /// <summary> /// Gets or sets a value indicating whether ShowOnMenu. /// </summary> public bool ShowOnMenu { get; set; } /// <summary> /// Gets or sets Title. /// </summary> public string Title { get; set; } #endregion } }<file_sep>namespace Firebrick.Admin.Web.Controllers { using System.Collections.Generic; using System.Web.Mvc; using Firebrick.Domain.ServiceBinders.WebAdmin; using Firebrick.Domain.ViewModels.WebAdmin.CmsMenuManager; using Firebrick.Service.Contracts; using Firebrick.UI.Core.Controllers; public class CmsMenuManagerController : BaseAdminController { #region Constants and Fields /// <summary> /// The page service. /// </summary> private readonly IPageService pageService; /// <summary> /// The seo decorator service /// </summary> private readonly ISeoDecoratorService seoDecoratorService; #endregion #region Constructors and Destructors public CmsMenuManagerController(IPageService pageService, ISeoDecoratorService seoDecoratorService) { this.pageService = pageService; this.seoDecoratorService = seoDecoratorService; } #endregion #region Public Methods public ActionResult AddPage(string parentPageId) { CmsMenuManagerServiceBinder modelBinder = this.GetServiceBinder(); return this.Content(modelBinder.AddPage(parentPageId)); } public ActionResult CheckId(string password) { const string ReturnString = "Winner"; return this.Content(ReturnString); } public ActionResult CopyPage(string copyPageId) { CmsMenuManagerServiceBinder modelBinder = this.GetServiceBinder(); return this.Content(modelBinder.CopyPage(copyPageId)); } public ActionResult DeletePage(string pageId) { CmsMenuManagerServiceBinder modelBinder = this.GetServiceBinder(); return this.Content(modelBinder.DeletePage(pageId)); } public ActionResult MovePage(string sourcePageId, string moveAction, string targetPageId) { CmsMenuManagerServiceBinder modelBinder = this.GetServiceBinder(); return this.Content(modelBinder.MovePage(sourcePageId, moveAction, targetPageId)); } public ActionResult RenamePage(string pageId, string newPageTitle) { CmsMenuManagerServiceBinder modelBinder = this.GetServiceBinder(); return this.Content(modelBinder.RenamePage(pageId, newPageTitle)); } public ActionResult Tree() { return this.View(); } public JsonResult TreeView() { CmsMenuManagerServiceBinder modelBinder = this.GetServiceBinder(); IEnumerable<TreeNodeViewModel> treeNodes = modelBinder.PopulateTree(); return this.Json(treeNodes); } [HttpPost] public JsonResult GetPageInfo(string pageId) { CmsMenuManagerServiceBinder modelBinder = this.GetServiceBinder(); PageInfoViewModel viewModel = modelBinder.BindPageInfo(pageId); return this.Json(viewModel, JsonRequestBehavior.AllowGet); } #endregion #region Methods /// <summary> /// The get service binder. /// </summary> /// <returns> /// </returns> private CmsMenuManagerServiceBinder GetServiceBinder() { return new CmsMenuManagerServiceBinder(this.pageService, this.seoDecoratorService); } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="DomainService.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Service.Implementations { using Firebrick.Data; using Firebrick.Data.RepositoryContracts; using Firebrick.Model; using Firebrick.Service.Contracts; /// <summary> /// The domain service. /// </summary> public class DomainService : BaseService<Domain>, IDomainService { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="DomainService"/> class. /// </summary> /// <param name="domainrepository"> /// The domainrepository. /// </param> /// <param name="unitOfWork"> /// The unit of work. /// </param> public DomainService(IDomainRepository domainrepository, IUnitOfWork unitOfWork) { this.Repository = domainrepository; this.UnitOfWork = unitOfWork; } #endregion } }<file_sep>namespace Firebrick.Domain.ServiceBinders.WebAdmin { using System; using System.Collections.Generic; using System.Linq; using AutoMapper; using Firebrick.Domain.Helpers.PartialViews; using Firebrick.Domain.ViewModels.WebAdmin.CmsPlugins; using Firebrick.Model; using Firebrick.Service.Contracts; public class CmsPluginServiceBinder { #region Constants and Fields private readonly IEnquiryService enquiryService; private readonly IRoleService roleService; private readonly IUserRolesService userRolesService; private readonly IUserService userService; #endregion #region Constructors and Destructors public CmsPluginServiceBinder(IUserService userService, IRoleService roleService, IUserRolesService userRolesService, IEnquiryService enquiryService) { this.userService = userService; this.roleService = roleService; this.userRolesService = userRolesService; this.enquiryService = enquiryService; } #endregion #region Public Methods public CmsPluginLoginUserViewModel LoginUserViewModelBind(string username) { var viewModel = new CmsPluginLoginUserViewModel(); User user = this.userService.GetByUsername(username); Mapper.CreateMap<User, CmsPluginLoginUserViewModel>(); Mapper.Map(user, viewModel); //// TODO: [RP] [06052013] Ensure this is correctly populated via the DB viewModel.CreatedBy = "Admin"; viewModel.DateCreated = DateTime.Today.AddDays(-30); viewModel.JobTitle = "Super Developer"; IEnumerable<Roles> roles = this.roleService.GetAll(); IEnumerable<UserRole> userRoles = this.userRolesService.GetMany(ur => ur.UserId == user.UserId); var userRolesDescriptions = from r in roles join ur in userRoles on r.RoleId equals ur.RoleId select new { ur.RoleId, r.Name }; foreach (var userRolesDescription in userRolesDescriptions) { viewModel.UserRoles.Add(userRolesDescription.Name); } return viewModel; } public CmsPluginMainSideMenuViewModel MainSideMenuBind(string url) { var mainSideMenu = new MainSideMenu(url); return mainSideMenu.ViewModel; } public CmsPluginAdditionalInfoViewModel AdditionalInfoBind(string username) { var viewmodel = new CmsPluginAdditionalInfoViewModel(); var user = this.userService.GetByUsername(username); if (user.DateCreated != null) { viewmodel.MemberSince = (DateTime) user.DateCreated; } viewmodel.FirebrickVersion = "ALPHA RELEASE 1.0"; viewmodel.NumEnquiries = enquiryService.GetAll().Count(); return viewmodel; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IEnquiryService.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Service.Contracts { using Firebrick.Model; /// <summary> /// The i enquiry service. /// </summary> public interface IEnquiryService : IService<Enquiry> { } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PartTypeServiceFixture.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Services.Tests { using Firebrick.Data; using Firebrick.Data.RepositoryContracts; using Firebrick.Model; using Firebrick.Service.Implementations; using Firebrick.Test.Helper; using Moq; using Xunit; /// <summary> /// The part type service fixture. /// </summary> public class PartTypeServiceFixture { #region Public Methods [Fact] public void WhenGettingEntity_ThenReturnsCorrectEntity() { // Arrange var repositoryMock = new Mock<IPartTypeRepository>(); PartType newEntity = DefaultModelHelper.DummyPopulatedPartType(); repositoryMock.Setup(repo => repo.GetById(It.IsAny<int>())).Returns(newEntity); // Act var services = new PartTypeService(repositoryMock.Object, new Mock<IUnitOfWork>().Object); PartType returnedEntity = services.GetById(1); // Assert Assert.NotNull(returnedEntity); Assert.Equal("Title", returnedEntity.Title); } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PageZoneRepositoryFixture.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.Tests.Repositories { using System; using System.Collections.Generic; using Firebrick.Data.EF; using Firebrick.Data.EF.Repositories; using Firebrick.Model; using Xunit; /// <summary> /// The page zone repository fixture. /// </summary> public class PageZoneRepositoryFixture { #region Public Methods /// <summary> /// The when constructed with null database factory_ then throws. /// </summary> [Fact] public void WhenConstructedWithNullDatabaseFactory_ThenThrows() { Assert.Throws<NullReferenceException>(() => new PageZoneRepository(null)); } /// <summary> /// The when get all from empty database_ then returns empty collection. /// </summary> [Fact] public void WhenGetAllFromEmptyDatabase_ThenReturnsEmptyCollection() { var repository = new PageZoneRepository(new DatabaseFactory()); IEnumerable<PageZone> actual = repository.GetAll(); Assert.NotNull(actual); var actualList = new List<PageZone>(actual); Assert.Equal(0, actualList.Count); } #endregion } }<file_sep>namespace Firebrick.Domain.ViewModels.ContentManagement.FlexSlider { using System.Collections.Generic; public class FlexSliderAdminEditViewModel { #region Public Properties public int BannerSetId { get; set; } public string BannerSetTitle { get; set; } public List<string> Banners { get; set; } #endregion } }<file_sep>// ----------------------------------------------------------------------- // <copyright file="MainMenuViewModel.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // ----------------------------------------------------------------------- namespace Firebrick.Domain.ViewModels { /// <summary> /// The MenuItemViewModel /// </summary> public class MenuItemViewModel : IMenuItemViewModel { #region Public Properties /// <summary> /// Gets or sets FriendlyUrl. /// </summary> public string FriendlyUrl { get; set; } /// <summary> /// Gets or sets HelperText. /// </summary> public string HelperText { get; set; } /// <summary> /// Gets or sets Id. /// </summary> public int Id { get; set; } /// <summary> /// Gets or sets Title. /// </summary> public string Title { get; set; } #endregion } /// <summary> /// The IMenuItemViewModel Interface /// </summary> public interface IMenuItemViewModel { #region Public Properties /// <summary> /// Gets or sets FriendlyUrl. /// </summary> string FriendlyUrl { get; set; } /// <summary> /// Gets or sets HelperText. /// </summary> string HelperText { get; set; } /// <summary> /// Gets or sets Id. /// </summary> int Id { get; set; } /// <summary> /// Gets or sets Title. /// </summary> string Title { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="WebFrameworkViewModel.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.ViewModels.Web.Core { using System.Collections.Generic; using System.ComponentModel.DataAnnotations; /// <summary> /// The web framework view model. /// </summary> public class WebFrameworkViewModel { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="WebFrameworkViewModel"/> class. /// </summary> public WebFrameworkViewModel() { this.PageTemplateZoneIdList = new List<int>(); this.PartViewModelList = new List<WebFrameworkPartViewModel>(); this.PartViewModelDictionary = new Dictionary<int, List<WebFrameworkPartViewModel>>(); // rowId, parts } #endregion #region Enums /// <summary> /// The zones enum. /// </summary> public enum PageZonesEnum { /// <summary> /// The header. /// </summary> Header = 1, /// <summary> /// The left column. /// </summary> LeftColumn = 2, /// <summary> /// The right column. /// </summary> RightColumn = 3, /// <summary> /// The center column. /// </summary> CenterColumn = 4, /// <summary> /// The footer. /// </summary> Footer = 5 } #endregion #region Public Properties public string AdminMode { get; set; } public List<string> CssAssets { get; set; } /// <summary> /// Gets or sets a value indicating whether EditModeActivated. /// </summary> public bool EditModeActivated { get; set; } /// <summary> /// Gets or sets HostHeader. /// </summary> public string HostHeader { get; set; } public List<string> JavaScriptAssets { get; set; } /// <summary> /// Gets or sets LayoutTemplateSrc. /// </summary> [Required(ErrorMessage = "LayoutTemplateSrc is required")] public string LayoutTemplateSrc { get; set; } /// <summary> /// Gets or sets PageActionName. /// </summary> public string PageActionName { get; set; } /// <summary> /// Gets or sets PageControllerName. /// </summary> public string PageControllerName { get; set; } /// <summary> /// Gets or sets PageId. /// </summary> public int PageId { get; set; } /// <summary> /// Gets or sets PageTemplateId. /// </summary> public int PageTemplateId { get; set; } /// <summary> /// Gets or sets PageTemplateZoneIdList. /// </summary> public List<int> PageTemplateZoneIdList { get; set; } public string PageTitle { get; set; } /// <summary> /// Gets or sets PartViewModelList. /// </summary> public List<WebFrameworkPartViewModel> PartViewModelList { get; set; } public IDictionary<int, List<WebFrameworkPartViewModel>> PartViewModelDictionary { get; set; } /// <summary> /// Gets or sets PortalId. /// </summary> public int PortalId { get; set; } /// <summary> /// Gets or sets PrimaryDomainId. /// </summary> public int PrimaryDomainId { get; set; } public string SeoCanonical { get; set; } /// <summary> /// Gets or sets SeoDescription. /// </summary> public string SeoDescription { get; set; } /// <summary> /// Gets or sets SeoKeywords. /// </summary> public string SeoKeywords { get; set; } /// <summary> /// Gets or sets SeoLookFor. /// </summary> public string SeoLookFor { get; set; } public string SeoRobots { get; set; } /// <summary> /// Gets or sets UserId. /// </summary> public int UserId { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IUnitOfWork.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data { /// <summary> /// The i unit of work. /// </summary> public interface IUnitOfWork { #region Public Methods /// <summary> /// The commit. /// </summary> void Commit(); #endregion } }<file_sep>namespace Firebrick.Service.Contracts { using Firebrick.Model; public interface IRolePageRestrictionService : IService<RolePageRestriction> { RolePageRestriction Get(int roleId, int pageId); } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="WebFrameworkController.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Web.UI.Controllers { using System; using System.Collections.Generic; using System.Web.Mvc; using Cassette.Views; using Firebrick.Domain.ServiceBinders.Web; using Firebrick.Domain.ViewModels.Web.Core; using Firebrick.Service.Contracts; using Firebrick.UI.Core.Filters; /// <summary> /// The web framework controller. /// </summary> public class WebFrameworkController : BaseController { #region Constants and Fields /// <summary> /// The model binder. /// </summary> private readonly WebFrameworkServiceBinder modelBinder; #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="WebFrameworkController"/> class. /// </summary> /// <param name="domainService"> /// The domain service. /// </param> /// <param name="clientAssetTypeService"> </param> /// <param name="pageService"> /// The page service. /// </param> /// <param name="pageTemplateService"> /// The page template service. /// </param> /// <param name="pageTemplateZoneMapService"> /// The page template zone map service. /// </param> /// <param name="pageZoneService"> /// The page zone service. /// </param> /// <param name="partService"> /// The part service. /// </param> /// <param name="partTypeService"> /// The part type service. /// </param> /// <param name="seoDecoratorService"> /// The seo decorator service. /// </param> /// <param name="userService"> /// The user service. /// </param> /// <param name="clientAssetConfigService"> </param> /// <param name="clientAssetService"> </param> /// <param name="partContainerService"> </param> public WebFrameworkController( IDomainService domainService, IClientAssetConfigService clientAssetConfigService, IClientAssetService clientAssetService, IClientAssetTypeService clientAssetTypeService, IPageService pageService, IPageTemplateService pageTemplateService, IPageTemplateZoneMapService pageTemplateZoneMapService, IPageZoneService pageZoneService, IPartService partService, IPartTypeService partTypeService, ISeoDecoratorService seoDecoratorService, IUserService userService, IPartContainerService partContainerService) { this.modelBinder = new WebFrameworkServiceBinder( domainService, clientAssetConfigService, clientAssetService, clientAssetTypeService, pageService, pageTemplateService, pageTemplateZoneMapService, pageZoneService, partService, partTypeService, seoDecoratorService, userService, partContainerService); } #endregion #region Public Methods [ValidateWebsiteUserRoles] public ActionResult Index(int id) { return View(GetDefaultViewModel(id)); } [HttpPost] [ValidateWebsiteUserRoles] public ActionResult Index(int id, string editMode) { return View(GetDefaultPostedViewModel(id, editMode)); } [ValidateWebsiteUserRoles] public ActionResult IndexTripleRow(int id) { return View(GetDefaultViewModel(id)); } [HttpPost] [ValidateWebsiteUserRoles] public ActionResult IndexTripleRow(int id, string editMode) { return View(GetDefaultPostedViewModel(id, editMode)); } [ValidateWebsiteUserRoles] public ActionResult IndexTwoColWideLeft(int id) { return View(GetDefaultViewModel(id)); } [HttpPost] [ValidateWebsiteUserRoles] public ActionResult IndexTwoColWideLeft(int id, string editMode) { return View(GetDefaultPostedViewModel(id, editMode)); } #endregion #region Methods private void AddCassetteAssetReference(IEnumerable<string> assets) { foreach (string asset in assets) { Bundles.Reference(asset); } } private WebFrameworkViewModel GetDefaultViewModel(int id) { WebFrameworkViewModel viewModel = null; try { // var role = User.IsInRole("Admin"); viewModel = this.modelBinder.WebFrameworkViewModelBind(id); this.AddCassetteAssetReference(viewModel.CssAssets); this.AddCassetteAssetReference(viewModel.JavaScriptAssets); } catch (UnauthorizedAccessException ex) { //// TODO: [RP] [16052013] Do what exactly? Show custom error page? this.LoggingService.Fatal(ex.Message, ex); } catch (Exception ex) { this.LoggingService.Fatal(ex.Message, ex); } return viewModel; } private WebFrameworkViewModel GetDefaultPostedViewModel(int id, string editMode) { WebFrameworkViewModel viewModel = null; try { bool isEditModeOn = Convert.ToBoolean(editMode); viewModel = this.modelBinder.WebFrameworkViewModelBind(id, isEditModeOn); } catch (Exception ex) { this.LoggingService.Fatal(ex.Message, ex); } return viewModel; } #endregion } }<file_sep>namespace Firebrick.Service.Implementations { using Firebrick.Data; using Firebrick.Data.RepositoryContracts; using Firebrick.Model; using Firebrick.Service.Contracts; public class RolePageRestrictionService : BaseService<RolePageRestriction>, IRolePageRestrictionService { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="RolePageRestrictionService"/> class. /// </summary> /// <param name="pageRestrictionRepository"> /// The domainrepository. /// </param> /// <param name="unitOfWork"> /// The unit of work. /// </param> public RolePageRestrictionService( IRolePageRestrictionRepository pageRestrictionRepository, IUnitOfWork unitOfWork) { this.Repository = pageRestrictionRepository; this.UnitOfWork = unitOfWork; } #endregion #region Public Methods public RolePageRestriction Get(int roleId, int pageId) { return this.Repository.Get(pr => pr.RoleId == roleId && pr.PageId == pageId); } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="CmsPageViewModel.cs" company="Beyond"> // Copyright Beyond 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.ViewModels.WebAdmin { using System.Collections.Generic; using System.Web.Mvc; /// <summary> /// The cms page view model. /// </summary> public class CmsPageViewModel { #region Public Properties /// <summary> /// Gets or sets ActionName. /// </summary> // public string ActionName { get; set; } /// <summary> /// Gets or sets ControllerName. /// </summary> // public string ControllerName { get; set; } /// <summary> /// Gets or sets PageId. /// </summary> public int PageId { get; set; } /// <summary> /// Gets or sets PageTemplateList. /// </summary> public IEnumerable<SelectListItem> PageTemplateList { get; set; } /// <summary> /// Gets or sets a value indicating whether ShowOnMenu. /// </summary> // public bool ShowOnMenu { get; set; } /// <summary> /// Gets or sets Title. /// </summary> public string Title { get; set; } #endregion } }<file_sep>namespace Firebrick.Entities.Messaging { using System.Collections.Generic; public class SendEmailConfiguration { #region Constructors and Destructors public SendEmailConfiguration() { this.ToAddressList = new List<string>(); } #endregion #region Public Properties public string SenderAddress { get; set; } public string Subject { get; set; } public string ToAddress { get; set; } public List<string> ToAddressList { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Disposable.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data { using System; /// <summary> /// The disposable. /// </summary> public class Disposable : IDisposable { #region Constants and Fields /// <summary> /// The is disposed. /// </summary> private bool isDisposed; #endregion #region Constructors and Destructors /// <summary> /// Finalizes an instance of the <see cref="Disposable"/> class. /// </summary> ~Disposable() { this.Dispose(false); } #endregion #region Public Methods /// <summary> /// The dispose. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } #endregion #region Methods /// <summary> /// The dispose core. /// </summary> protected virtual void DisposeCore() { } /// <summary> /// The dispose. /// </summary> /// <param name="disposing"> /// The disposing. /// </param> private void Dispose(bool disposing) { if (!this.isDisposed && disposing) { this.DisposeCore(); } this.isDisposed = true; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="EnquiryContactUsViewModel.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.ViewModels.ContentManagement.Enquiry { using System.ComponentModel.DataAnnotations; /// <summary> /// The enquiry contact us view model. /// </summary> public class EnquiryContactUsViewModel { #region Public Properties public bool? ActionIsSentSuccessful { get; set; } /// <summary> /// Gets or sets Email. /// </summary> [Required] [MaxLength(100, ErrorMessage = "Email must be 100 characters or less")] [MinLength(5)] public string EMail { get; set; } /// <summary> /// Gets or sets ErrorMessage. /// </summary> public string ErrorMessage { get; set; } public string Exception { get; set; } /// <summary> /// Gets or sets Name. /// </summary> public string FullName { get; set; } /// <summary> /// Gets or sets Message. /// </summary> public string Message { get; set; } public string Telephone { get; set; } #endregion } }<file_sep>namespace Firebrick.Domain.ViewModels.ContentManagement.Analytics { public class GoogleIndividualAccountViewModel { public string AccountName { get; set; } public int AnalytcisAccountId { get; set; } public int PortalId { get; set; } public string PrimaryDomainName { get; set; } public bool ShowMobile { get; set; } public string TrackingCode { get; set; } public string TrackingType { get; set; } } } <file_sep>namespace Firebrick.Service.Implementations { using Firebrick.Data; using Firebrick.Data.RepositoryContracts; using Firebrick.Model; using Firebrick.Service.Contracts; /// <summary> /// The notification type service. /// </summary> public class NotificationTypeService : BaseService<NotificationType>, INotificationTypeService { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="NotificationTypeService"/> class. /// </summary> /// <param name="notificationTypeRepository"> /// The notification type repository. /// </param> /// <param name="unitOfWork"> /// The unit of work. /// </param> public NotificationTypeService(INotificationTypeRepository notificationTypeRepository, IUnitOfWork unitOfWork) { this.Repository = notificationTypeRepository; this.UnitOfWork = unitOfWork; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="RichContentIndexViewModel.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.ViewModels.ContentManagement.RichContent { /// <summary> /// The rich content index view model. /// </summary> public class RichContentIndexViewModel { #region Public Properties /// <summary> /// Gets or sets Html. /// </summary> public string Html { get; set; } /// <summary> /// Gets or sets Id. /// </summary> public int Id { get; set; } /// <summary> /// Gets or sets PartId. /// </summary> public int PartId { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="DatabaseFactory.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.EF { /// <summary> /// The database factory. /// </summary> public class DatabaseFactory : Disposable, IDatabaseFactory { #region Constants and Fields /// <summary> /// The data context. /// </summary> private FirebrickContext dataContext; #endregion #region Public Methods /// <summary> /// The get. /// </summary> /// <returns> /// </returns> public FirebrickContext Get() { return this.dataContext ?? (this.dataContext = new FirebrickContext()); } #endregion #region Methods /// <summary> /// The dispose core. /// </summary> protected override void DisposeCore() { if (this.dataContext != null) { this.dataContext.Dispose(); } } #endregion } }<file_sep>$(document).ready(function () { $.mobile.ajaxEnabled = false; });<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="GridPartItemViewModel.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.ViewModels.WebAdmin.CmsPageManager { /// <summary> /// The grid part item view model. /// </summary> public class GridPartItemViewModel { #region Public Properties /// <summary> /// Gets or sets ColId. /// </summary> public int ColId { get; set; } /// <summary> /// Gets or sets PartId. /// </summary> public int PartId { get; set; } /// <summary> /// Gets or sets RowId. /// </summary> public int RowId { get; set; } public int ColSpan { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="CmsPageManagerServiceBinder.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.ServiceBinders.WebAdmin { using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using AutoMapper; using Firebrick.Domain.SEO; using Firebrick.Domain.ViewModels; using Firebrick.Domain.ViewModels.WebAdmin.CmsPageManager; using Firebrick.Model; using Firebrick.Service.Contracts; using Newtonsoft.Json; using Exception = System.Exception; /// <summary> /// The cms page service binder. /// </summary> public class CmsPageManagerServiceBinder { #region Constants and Fields private readonly IPageControllerActionService pageControllerActionService; private readonly IPageService pageService; private readonly IPageTemplateService pageTemplateService; private readonly IPartService partService; private readonly IPartTypeService partTypeService; private readonly IRolePageRestrictionService rolePageRestrictionService; private readonly IRoleService roleService; private readonly ISeoDecoratorService seoDecoratorService; #endregion #region Constructors and Destructors public CmsPageManagerServiceBinder( IPageService pageService, IPageTemplateService pageTemplateService, IPageControllerActionService pageControllerActionService, IPartTypeService partTypeService, IPartService partService, ISeoDecoratorService seoDecoratorService, IRoleService roleService, IRolePageRestrictionService rolePageRestrictionService) { this.pageService = pageService; this.pageTemplateService = pageTemplateService; this.pageControllerActionService = pageControllerActionService; this.partTypeService = partTypeService; this.partService = partService; this.seoDecoratorService = seoDecoratorService; this.roleService = roleService; this.rolePageRestrictionService = rolePageRestrictionService; } #endregion #region Public Methods and Operators //public bool Add(CmsPageManagerEditViewModel viewModel) //{ // return true; //} #region "Add Page" public CmsPageManagerAddViewModel AddViewModelBind(int pageId) { var viewModel = new CmsPageManagerAddViewModel(); this.PopulateTemplateService(ref viewModel); this.PopulatePageConrollerActionList(ref viewModel); this.PopulatePageRolesAvailable(ref viewModel); this.PopulateParentPagesAvailable(ref viewModel); return viewModel; } public CmsPageManagerAddViewModel AddViewModelInsert(CmsPageManagerAddViewModel viewModel) { bool isSuccess; try { Page page = this.pageService.GetById(viewModel.PageId); PageControllerAction controllerAction = this.pageControllerActionService.GetById(viewModel.PageControllerActionId); if (page == null) { page = new Page(); } Mapper.CreateMap<CmsPageManagerAddViewModel, Page>(); Mapper.Map(viewModel, page); //// Dummy Properties that need to be populated page.PageParentId = viewModel.ParentPagesSelectedItem; page.PageTemplateId = viewModel.PageTemplateId; page.PortalId = 1; page.ShowOnMenu = viewModel.ShowOnMenu; page.Created = DateTime.Now; page.LastModifiedBy = viewModel.CreatedBy; page.LastModified = DateTime.Now; if (controllerAction != null) { page.ControllerName = controllerAction.ControllerName; page.ActionName = controllerAction.ActionName; } this.pageService.Add(page); this.PopulateTemplateService(ref viewModel); this.PopulatePageConrollerActionList(ref viewModel); this.PopulatePageRolesAvailable(ref viewModel); this.PopulateParentPagesAvailable(ref viewModel); //// Add SeoDecorator for page this.BuildDefaultSeo(page, viewModel); isSuccess = true; } catch (Exception) { isSuccess = false; } viewModel.ActionIsAddSuccessful = isSuccess; return viewModel; } #endregion #region "Edit Page Async Calls" public Tuple<string, int, int> AysncEditViewAddPagePart(int partTypeid, string partName, int zoneId, int pageId, int colSpan, int row, int pageStructureId) { try { var part = new Part(); part.Order = this.partService.GetNextOrderId(pageId, zoneId); part.PageId = pageId; part.PartContainerId = 1; part.Title = string.Format("{0}", partName); part.PartTypeId = partTypeid; part.RowId = row; ValidateZoneIdAndColumn(ref part, colSpan, zoneId, pageStructureId); this.partService.Add(part); return new Tuple<string, int, int>("Part Added.", part.PartId, part.Order); } catch (Exception) { return new Tuple<string, int, int>("Add Part Failed.", -1, -1); } } private void ValidateZoneIdAndColumn(ref Part part, int desiredColSpan, int desiredZoneId, int pageStructureId) { //zoneid 2 Left Column >> 1 col //zoneid 3 Right Column >> 3 col //zoneid 4 Center Column >> 2 col var determinedColSpan = desiredColSpan; var determinedZoneId = desiredZoneId; if (desiredColSpan != 1) { if (desiredColSpan > 1 && desiredZoneId == 3) { determinedColSpan = 1; } if (desiredColSpan > 2 && desiredZoneId != 2) { determinedZoneId = 2; } } part.ColSpan = determinedColSpan; part.ZoneId = determinedZoneId; part.ColSpanDescriptor = GetColSpanDescriptor(pageStructureId, determinedColSpan, determinedZoneId); } private string GetColSpanDescriptor(int pageStructureId, int colSpan, int determinedZoneId) { if (pageStructureId == 1) { switch (determinedZoneId) { case 2: return "three columns"; case 4: return "nine columns"; default: return "four columns"; } } switch (colSpan) { case 2: return "two-thirds column"; case 3: return "sixteen columns"; default: return "one-third column"; } } public string AysncEditViewDeletePagePart(int partid) { string response = "Part Deleted"; try { this.partService.Delete(partid); } catch (Exception ex) { response = string.Format("Delete Failed - {0}", ex.Message); } return response; } public string AysncEditViewUpdatePageParts(string jsonData) { var deserializedParts = JsonConvert.DeserializeObject<List<GridPartItemViewModel>>(jsonData); IEnumerable<GridPartItemViewModel> orderedParts = from p in deserializedParts orderby p.ColId, p.RowId where p.PartId != 0 select new GridPartItemViewModel { PartId = p.PartId, ColId = p.ColId, RowId = p.RowId, ColSpan = p.ColSpan }; int order = 1; foreach (GridPartItemViewModel item in orderedParts) { switch (item.ColId) { case 1: this.UpdatePartPosition(item.PartId, 2, order, item.RowId); break; case 2: this.UpdatePartPosition(item.PartId, 4, order, item.RowId); break; default: this.UpdatePartPosition(item.PartId, 3, order, item.RowId); break; } order = order + 1; } return "Done."; } #endregion #region "Edit Page" public CmsPageManagerEditViewModel EditViewModelBind(int pageId) { var viewModel = new CmsPageManagerEditViewModel(); var selectedPageRoles = new List<int>(); Page page = this.pageService.GetById(pageId); SeoDecorator seo = this.seoDecoratorService.GetByPage(pageId); IEnumerable<RolePageRestriction> pageRoles = this.rolePageRestrictionService.GetMany(rp => rp.PageId == pageId); Mapper.CreateMap<Page, CmsPageManagerEditViewModel>(); Mapper.Map(page, viewModel); Mapper.CreateMap<SeoDecorator, CmsPageManagerEditViewModel>(); Mapper.Map(seo, viewModel); this.PopulateTemplateService(ref viewModel); this.PopulatePageConrollerActionList(ref viewModel); this.PopulatePageRolesAvailable(ref viewModel); foreach (RolePageRestriction pageRole in pageRoles) { selectedPageRoles.Add(pageRole.RoleId); } viewModel.PageRolesSelectedItems = selectedPageRoles; viewModel.PageControllerActionId = this.pageControllerActionService.GetPageControllerActionId( viewModel.ControllerName, viewModel.ActionName); //// TODO: [RP] Replace hard-coded localhost viewModel.LookFor = string.Format("http://localhost/{0}", seo.LookFor); IEnumerable<Part> pageParts = this.partService.GetManyByPageId(pageId); this.PopulatePartTypeList(ref viewModel, pageParts); return viewModel; } public CmsPageManagerEditViewModel EditViewModelDelete(CmsPageManagerEditViewModel viewModel) { bool isSuccess; try { this.pageService.Delete(viewModel.PageId); isSuccess = true; } catch (Exception) { isSuccess = false; } // Update EditViewModel viewModel = this.EditViewModelBind(viewModel.PageId); viewModel.ActionIsDeleteSuccessful = isSuccess; return viewModel; } public CmsPageManagerEditViewModel EditViewModelStateInValid(CmsPageManagerEditViewModel viewModel) { this.PopulateTemplateService(ref viewModel); this.PopulatePageConrollerActionList(ref viewModel); this.PopulatePageRolesAvailable(ref viewModel); viewModel.ActionIsSaveSuccessful = false; return viewModel; } public CmsPageManagerEditViewModel EditViewModelUpdate(CmsPageManagerEditViewModel viewModel) { bool isSuccess; try { Page page = this.pageService.GetById(viewModel.PageId); PageControllerAction controllerAction = this.pageControllerActionService.GetById(viewModel.PageControllerActionId); //// This should work to ignore null values in the source object >> Automapper 2.1 issue? //// Mapper.CreateMap<CmsPageManagerEditViewModel, Page>().ForAllMembers(opt => opt.Condition(src => src.SourceValue != null)); Mapper.CreateMap<CmsPageManagerEditViewModel, Page>(); Mapper.Map(viewModel, page); if (controllerAction != null) { page.ControllerName = controllerAction.ControllerName; page.ActionName = controllerAction.ActionName; } page.LastModified = DateTime.Now; //// Update Page this.pageService.Update(page); //// Update SEO on Page this.EditViewModelUpdatePageSeo(viewModel); //// Update Roles on Page this.EditViewModelUpdatePageRoles(viewModel); isSuccess = true; } catch (Exception) { isSuccess = false; } // Update EditViewModel viewModel = this.EditViewModelBind(viewModel.PageId); viewModel.ActionIsSaveSuccessful = isSuccess; return viewModel; } #endregion #region "Page List" public CmsPageManagerIndexViewModel IndexViewModelBind() { var viewModel = new CmsPageManagerIndexViewModel(); IEnumerable<Page> pages = this.pageService.GetAll(); IEnumerable<SeoDecorator> seoDecorators = this.seoDecoratorService.GetAll(); Mapper.CreateMap<Page, CmsPageManagerIndexViewModelListItem>(); Mapper.Map(pages, viewModel.Pages); Mapper.CreateMap<SeoDecorator, CmsPageManagerIndexViewModelListItem>(); Mapper.Map(seoDecorators, viewModel.Pages); return viewModel; } #endregion #endregion #region Methods #region "Add Page" private void PopulateParentPagesAvailable(ref CmsPageManagerAddViewModel viewModel) { var parentPages = new List<SelectListItem>(); parentPages.Add(this.BuildWebsiteRootItem()); if (this.pageService != null) { parentPages.AddRange(new SelectList(this.pageService.GetAll(), "PageId", "Title")); } viewModel.ParentPagesAvailableList = parentPages; } private void AddNewPageRole(int roleId, int pageId) { RolePageRestriction rolePageRestriction = this.rolePageRestrictionService.Get(roleId, pageId); if (rolePageRestriction == null) { rolePageRestriction = new RolePageRestriction { PageId = pageId, RoleId = roleId, IsViewable = true, IsEditable = true }; this.rolePageRestrictionService.Add(rolePageRestriction); } } private void BuildDefaultSeo(Page page, CmsPageManagerAddViewModel viewModel) { string lookFor = this.BuildLookFor(page.Title, page.PageParentId); SeoDecorator seo = this.seoDecoratorService.GetByLookFor(lookFor); if (seo == null) { seo = new SeoDecorator { ChangeFrequency = "monthly", Description = viewModel.Keywords, Keywords = viewModel.Keywords, LastModified = DateTime.Now, LookFor = lookFor, PageId = page.PageId, Priority = "0.5", FileName = page.Title, Title = page.Title, CreatedDate = DateTime.Now, RobotsFollow = viewModel.RobotsFollow, RobotsIndex = viewModel.RobotsIndex, PortalId = 1, LinkType = 1 }; this.seoDecoratorService.Add(seo); } } private string BuildLookFor(string pageTitle, int parentPageId) { string parentLookFor = string.Empty; if (parentPageId > 0) { SeoDecorator parentSeo = this.seoDecoratorService.GetByPage(parentPageId); parentLookFor = parentSeo.LookFor; } return CmsUrl.BuildLookFor(pageTitle, parentLookFor); } private SelectListItem BuildWebsiteRootItem() { var websiteRoot = new SelectListItem { Text = "Website Root", Value = "-1" }; return websiteRoot; } #endregion #region "Edit Page" private void EditViewModelUpdatePageRoles(CmsPageManagerEditViewModel viewModel) { if (viewModel.PageRolesSelectedItems != null) { foreach (int roleId in viewModel.PageRolesSelectedItems) { this.AddNewPageRole(roleId, viewModel.PageId); } } } private void EditViewModelUpdatePageSeo(CmsPageManagerEditViewModel viewModel) { SeoDecorator seo = this.seoDecoratorService.GetByPage(viewModel.PageId); Mapper.CreateMap<CmsPageManagerEditViewModel, SeoDecorator>(); Mapper.Map(viewModel, seo); if (seo != null) { seo.LookFor = this.BuildLookFor(viewModel.Title, viewModel.PageParentId); this.seoDecoratorService.Update(seo); } } private void PopulatePartTypeList(ref CmsPageManagerEditViewModel viewModel, IEnumerable<Part> pageParts) { var partTypeList = new SelectList(this.partTypeService.GetAll(), "PartTypeId", "Title"); var partTypeControllerLookup = new SelectList(this.partTypeService.GetAll(), "PartTypeId", "Controller"); var partControllerLookup = new Dictionary<int, string>(); foreach (SelectListItem partType in partTypeControllerLookup) { partControllerLookup.Add(Convert.ToInt32(partType.Value), partType.Text); } viewModel.AvailablePartTypeList = partTypeList; var selectedZoneTwoParts = new List<CmsPageManagerEditPartViewModel>(); var selectedZoneThreeParts = new List<CmsPageManagerEditPartViewModel>(); var selectedZoneFourParts = new List<CmsPageManagerEditPartViewModel>(); int col2Index = 1; int col3Index = 1; int col4Index = 1; foreach (Part part in pageParts.OrderBy(p => p.Order)) { switch (part.ZoneId) { case 2: selectedZoneTwoParts.Add( this.GetPartViewModel(part, col2Index, partControllerLookup[part.PartTypeId])); col2Index++; break; case 3: selectedZoneThreeParts.Add( this.GetPartViewModel(part, col3Index, partControllerLookup[part.PartTypeId])); col3Index++; break; case 4: selectedZoneFourParts.Add( this.GetPartViewModel(part, col4Index, partControllerLookup[part.PartTypeId])); col4Index++; break; } } viewModel.ZoneTwoSelectedParts = selectedZoneTwoParts; viewModel.ZoneThreeSelectedParts = selectedZoneThreeParts; viewModel.ZoneFourSelectedParts = selectedZoneFourParts; } private void UpdatePartPosition(int partId, int zoneId, int order, int rowId) { Part part = this.partService.GetById(partId); part.ZoneId = zoneId; part.Order = order; part.RowId = rowId; this.partService.Update(part); } private CmsPageManagerEditPartViewModel GetPartViewModel(Part part, int index, string controller) { var viewModelItem = new CmsPageManagerEditPartViewModel(); viewModelItem.PartId = part.PartId; viewModelItem.Title = part.Title; viewModelItem.Order = index; viewModelItem.RowId = part.RowId; viewModelItem.AdminPartAction = "AdminEditMode"; viewModelItem.AdminPartController = string.Format("{0}Admin", controller); viewModelItem.ColSpan = 1; if (part.ColSpan > 1) { viewModelItem.ColSpan = part.ColSpan; } return viewModelItem; } #endregion #region "Shared" private void PopulatePageConrollerActionList<T>(ref T viewModel) where T : CmsPageManagerBaseViewModel { if (this.pageControllerActionService != null) { viewModel.PageControllerActionList = new SelectList( this.pageControllerActionService.GetAll(), "PageControllerActionId", "FriendlyName"); } } private void PopulatePageRolesAvailable<T>(ref T viewModel) where T : CmsPageManagerBaseViewModel { if (this.roleService != null) { viewModel.PageRolesAvailableList = new SelectList(this.roleService.GetAll(), "RoleId", "Name"); } } private void PopulateTemplateService<T>(ref T viewModel) where T : CmsPageManagerBaseViewModel { if (this.pageTemplateService != null) { viewModel.PageTemplateList = new SelectList( this.pageTemplateService.GetAll(), "PageTemplateId", "Title"); } } #endregion #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IPageControllerActionService.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Service.Contracts { using Firebrick.Model; /// <summary> /// The i page controller action service. /// </summary> public interface IPageControllerActionService : IService<PageControllerAction> { #region Public Methods int GetPageControllerActionId(string controllerName, string actionName); #endregion } }<file_sep>namespace Firebrick.ContentManagement.Web.Controllers { using System.Web.Mvc; using Firebrick.Domain.ServiceBinders.ContentManagement; using Firebrick.Domain.ViewModels.ContentManagement.Enquiry; using Firebrick.Service.Contracts; using Firebrick.UI.Core.Controllers; public class EnquiryController : BasePartController { #region Constants and Fields /// <summary> /// The page controller action service. /// </summary> private readonly IEnquiryService enquiryService; #endregion #region Constructors and Destructors public EnquiryController(IEnquiryService enquiryService) { this.enquiryService = enquiryService; } #endregion //[HttpGet] //[ChildActionOnly] //[ValidateUserRoles] //public ActionResult ContactUs() //{ // return this.PartialView(); //} #region Public Methods [HttpGet] [ChildActionOnly] public ActionResult ContactUs() { //// throw new ApplicationException("Testing default ErrorHandler attribute"); object routeValue = this.Url.RequestContext.RouteData.Values["RegNo"]; return this.PartialView(); } [HttpPost] public ActionResult ContactUs(string submit, EnquiryContactUsViewModel viewModel) { object routeValue = this.Url.RequestContext.RouteData.Values["RegNo"]; if (this.ModelState.IsValid) { if (submit != null) { EnquiryServiceBinder modelBinder = this.GetServiceBinder(); modelBinder.ContactUsSend(viewModel); } } return PartialView(viewModel); } #endregion #region Methods /// <summary> /// The get service binder. /// </summary> /// <returns> /// </returns> private EnquiryServiceBinder GetServiceBinder() { return new EnquiryServiceBinder(this.enquiryService); } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="UnityPerRequestLifetimeManager.cs" company="Beyond"> // Copyright Beyond 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.UI.Core.UnityExtensions { using System; using Microsoft.Practices.Unity; /// <summary> /// The unity per request lifetime manager. /// </summary> public class UnityPerRequestLifetimeManager : LifetimeManager, IDisposable { #region Constants and Fields /// <summary> /// The context store. /// </summary> private readonly IPerRequestStore contextStore; /// <summary> /// The key. /// </summary> private readonly Guid key = Guid.NewGuid(); #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="UnityPerRequestLifetimeManager"/> class. /// Initializes a new instance of UnityPerRequestLifetimeManager with a per-request store. /// </summary> /// <param name="contextStore"> /// </param> public UnityPerRequestLifetimeManager(IPerRequestStore contextStore) { this.contextStore = contextStore; this.contextStore.EndRequest += this.EndRequestHandler; } #endregion #region Public Methods /// <summary> /// The dispose. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// The get value. /// </summary> /// <returns> /// The get value. /// </returns> public override object GetValue() { return this.contextStore.GetValue(this.key); } /// <summary> /// The remove value. /// </summary> public override void RemoveValue() { object oldValue = this.contextStore.GetValue(this.key); this.contextStore.RemoveValue(this.key); var disposable = oldValue as IDisposable; if (disposable != null) { disposable.Dispose(); } } /// <summary> /// The set value. /// </summary> /// <param name="newValue"> /// The new value. /// </param> public override void SetValue(object newValue) { this.contextStore.SetValue(this.key, newValue); } #endregion #region Methods /// <summary> /// The dispose. /// </summary> /// <param name="disposing"> /// The disposing. /// </param> protected virtual void Dispose(bool disposing) { this.RemoveValue(); } /// <summary> /// The end request handler. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> private void EndRequestHandler(object sender, EventArgs e) { this.RemoveValue(); } #endregion } }<file_sep>$('#btnEditMode').bind('click', function () { toggleEditMode(); }); function toggleEditMode() { var editMode = document.getElementById("editMode").value; if (editMode == "True") { document.getElementById("editMode").value = "False"; } else { document.getElementById("editMode").value = "True"; } document.forms.item(0).submit(); } <file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PortalSetting.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Model { using System.ComponentModel.DataAnnotations; /// <summary> /// The portal setting. /// </summary> public class PortalSetting { #region Public Properties /// <summary> /// Gets or sets PortalId. /// </summary> public int PortalId { get; set; } /// <summary> /// Gets or sets PortalSettingId. /// </summary> [Key] public int PortalSettingId { get; set; } /// <summary> /// Gets or sets SettingIdentifier. /// </summary> public string SettingIdentifier { get; set; } /// <summary> /// Gets or sets SettingValue. /// </summary> public string SettingValue { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ISeoDecoratorService.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Service.Contracts { using Firebrick.Model; /// <summary> /// The i seo info service. /// </summary> public interface ISeoDecoratorService : IService<SeoDecorator> { #region Public Methods /// <summary> /// The get by look for. /// </summary> /// <param name="lookFor"> /// The look for. /// </param> /// <returns> /// </returns> SeoDecorator GetByLookFor(string lookFor); SeoDecorator GetByPage(int pageId); #endregion } }<file_sep>namespace Firebrick.Data.EF.Repositories { using Firebrick.Data.RepositoryContracts; using Firebrick.Model; public class AnalyticsTypeRepository : BaseRepository<AnalyticsType>, IAnalyticsTypeRepository { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="AnalyticsTypeRepository"/> class. /// </summary> /// <param name="databaseFactory"> /// The database factory. /// </param> public AnalyticsTypeRepository(IDatabaseFactory databaseFactory) : base(databaseFactory) { } #endregion } }<file_sep>See "Revealing Module Pattern" for JavaScript http://weblogs.asp.net/dwahlin/archive/2011/08/02/techniques-strategies-and-patterns-for-structuring-javascript-code-revealing-module-pattern.aspx - Avoid spaghetti code - Compartmentalise code - can be encapsulated into a more re-useable object. <file_sep>namespace Firebrick.Service { using System; using System.Collections.Generic; using System.Linq.Expressions; public interface IService<T> where T : class { #region Public Methods void Add(T entity); void Delete(int id); void Delete(Expression<Func<T, bool>> where); T Get(Expression<Func<T, bool>> where); IEnumerable<T> GetAll(); T GetById(int Id); IEnumerable<T> GetMany(Expression<Func<T, bool>> where); void Save(); void Update(T entity); #endregion } }<file_sep>Migrations ---------- To install a new database, from the Package Manager Console for this project type: PM> Update-Database This will fire the package to generate a new start point DB. Lovely. <file_sep>namespace Firebrick.UI.Core.Security { using System; using System.Collections.Generic; using System.Web.Security; using Firebrick.Domain.ServiceBinders.Web; using Firebrick.Service.Contracts; using Microsoft.Practices.ServiceLocation; public static class CmsSecurityProvider { #region Public Methods public static IEnumerable<int> GetPageRoleRestrictions(int pageId) { var serviceBinder = GetServiceBinder(); return serviceBinder.GetRolePageRestrictions(pageId); } #endregion #region Methods private static WebCoreSecurityServiceBinder GetServiceBinder() { return new WebCoreSecurityServiceBinder( ServiceLocator.Current.GetService(typeof(IUserService)) as IUserService, ServiceLocator.Current.GetService(typeof(IRoleService)) as IRoleService, ServiceLocator.Current.GetService(typeof(IUserRolesService)) as IUserRolesService, ServiceLocator.Current.GetService(typeof(IRolePageRestrictionService)) as IRolePageRestrictionService); } #endregion } } <file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="FriendlyUrlRouteHandler.cs" company="Beyond"> // Copyright Beyond 2012 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.UI.Core.Routing { using System; using System.Collections.Generic; using System.Globalization; using System.Web; using System.Web.Mvc; using System.Web.Routing; using Firebrick.Domain.ServiceBinders.Web; using Firebrick.Domain.ViewModels.Web.Core; using Firebrick.Service.Contracts; using Microsoft.Practices.ServiceLocation; /// <summary> /// The friendly url route handler. /// </summary> public class FriendlyUrlRouteHandler : MvcRouteHandler { #region Methods /// <summary> /// The get http handler. /// </summary> /// <param name="requestContext"> /// The request context. /// </param> /// <returns> /// Ihttp handler /// </returns> protected override IHttpHandler GetHttpHandler(RequestContext requestContext) { string lookFor = (string)requestContext.RouteData.Values["FriendlyUrl"] ?? "home"; UrlRouteViewModel routeViewModel = null; if (!string.IsNullOrEmpty(lookFor)) { if (this.IsValidRequest(lookFor)) { if (!lookFor.Contains("Admin/")) { var serviceBinder = new WebCoreServiceBinder( ServiceLocator.Current.GetService(typeof(IPageService)) as IPageService, ServiceLocator.Current.GetService(typeof(ISeoDecoratorService)) as ISeoDecoratorService, ServiceLocator.Current.GetService(typeof(ISeoRouteValueService)) as ISeoRouteValueService, ServiceLocator.Current.GetService(typeof(IDomainService)) as IDomainService); routeViewModel = serviceBinder.UrlRouteViewModelBind(lookFor); if (routeViewModel != null) { this.MapRequestContext( requestContext, routeViewModel.ControllerName, routeViewModel.ActionName, routeViewModel.PageId.ToString(CultureInfo.InvariantCulture), routeViewModel.RouteValues); } } else { // routeViewModel = new UrlRouteViewModel(); this.MapRequestContext(requestContext, lookFor); } } } if (routeViewModel == null) { if (this.IsValidRequest(lookFor)) { this.MapRequestContext(requestContext, lookFor); } // page = RouteManager.GetByFriendlyUrl("home"); // this.MapRequestContext(requestContext, page.ControllerName, page.ActionName, page.PageId.ToString()); } return base.GetHttpHandler(requestContext); } /// <summary> /// The is valid request. /// </summary> /// <param name="lookFor"> /// The look for. /// </param> /// <returns> /// if this is a valid look for /// </returns> private bool IsValidRequest(string lookFor) { lookFor = lookFor.ToLower(); if (lookFor.Contains("scripts/")) { return false; } if (lookFor.Contains("favicon.")) { return false; } if (lookFor.Contains(".gif")) { return false; } return true; } /// <summary> /// The map request context. /// </summary> /// <param name="requestContext"> /// The request context. /// </param> /// <param name="controller"> /// The controller. /// </param> /// <param name="action"> /// The action. /// </param> /// <param name="pageId"> /// The page id. /// </param> /// <param name="routeValues"> </param> private void MapRequestContext( RequestContext requestContext, string controller, string action, string pageId, ICollection<KeyValuePair<string, string>> routeValues) { requestContext.RouteData.Values["controller"] = controller; requestContext.RouteData.Values["action"] = action; requestContext.RouteData.Values["id"] = pageId; if (routeValues.Count <= 0) { return; } foreach (var routeValue in routeValues) { requestContext.RouteData.Values[routeValue.Key] = routeValue.Value; } // Love this: // requestContext.RouteData.Values["random"] = 1976; // Create a routine to add n (x) NVP to route data < Winner } /// <summary> /// The map request context. /// </summary> /// <param name="requestContext"> /// The request context. /// </param> /// <param name="lookFor"> /// The look for. /// </param> /// <exception cref="NotImplementedException"> /// Not implemented exception /// </exception> private void MapRequestContext(RequestContext requestContext, string lookFor) { try { string[] urlSegments = lookFor.Split(Convert.ToChar("/")); string controller = urlSegments[0]; string action = "Index"; string id = string.Empty; if (urlSegments.Length > 1) { action = urlSegments[1]; if (urlSegments.Length > 2) { id = urlSegments[2]; } } if (controller.ToLower() == "api") { controller = "CmsAPI"; action = "GetUsers"; id = string.Empty; } requestContext.RouteData.Values["controller"] = controller; requestContext.RouteData.Values["action"] = action; if (id != string.Empty) { requestContext.RouteData.Values["id"] = id; } //// TODO: [RP] [170612] Do we need to check the query string for ReturnToAction for example? } catch (Exception) { throw new NotImplementedException(); } } #endregion } }<file_sep>namespace Firebrick.Model.Tests.ViewModels.WebAdmin.CmsPageManager { using Firebrick.Domain.ViewModels; using Firebrick.Domain.ViewModels.WebAdmin.CmsPageManager; using Xunit; public class CmsPageManagerViewModelFixture { #region Public Methods /// <summary> /// The when instantiating class with default constructor_ suceeds. /// </summary> [Fact] public void WhenInstantiatingClassWithDefaultConstructor_Add_Succeeds() { // Arrange CmsPageManagerAddViewModel model; // Act model = new CmsPageManagerAddViewModel(); // Assert Assert.NotNull(model); } /// <summary> /// The when instantiating class with default constructor_ suceeds. /// </summary> [Fact] public void WhenInstantiatingClassWithDefaultConstructor_Edit_Succeeds() { // Arrange CmsPageManagerEditViewModel model; // Act model = new CmsPageManagerEditViewModel(); // Assert Assert.NotNull(model); } /// <summary> /// The when instantiating class with default constructor_ suceeds. /// </summary> [Fact] public void WhenInstantiatingClassWithDefaultConstructor_Index_Succeeds() { // Arrange CmsPageManagerIndexViewModel model; // Act model = new CmsPageManagerIndexViewModel(); // Assert Assert.NotNull(model); } #endregion } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Firebrick.Model; using Firebrick.Service.Contracts; namespace Firebrick.Service { public class TestUserService : BaseService<User>, IUserService { public IEnumerable<User> SpecialGetUsers() { throw new NotImplementedException(); } public void AssignRole(string userName, List<string> roleName) { throw new NotImplementedException(); } } } <file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="UserRepositoryFixture.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.Tests.Repositories { using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Firebrick.Data.EF; using Firebrick.Data.EF.Repositories; using Firebrick.Data.Sql; using Firebrick.Model; using Xunit; /// <summary> /// The user repository fixture. /// </summary> public class UserRepositoryFixture { #region Constants and Fields /// <summary> /// The default test user. /// </summary> private User defaultTestUser; #endregion #region Public Methods /// <summary> /// The when a test takes just too damn long_ then timeout. /// </summary> [Fact(Timeout = 50)] public void WhenATestTakesJustTooDamnLong_ThenTimeout() { Thread.Sleep(250); } /// <summary> /// The when constructed with null database factory_ then throws. /// </summary> [Fact] public void WhenConstructedWithNullDatabaseFactory_ThenThrows() { Assert.Throws<NullReferenceException>(() => new UserRepository(null)); } /// <summary> /// The when get all from empty database_ then returns empty collection. /// </summary> [Fact] public void WhenGetAllFromEmptyDatabase_ThenReturnsEmptyCollection() { this.InitializeFixture(); var repository = new UserRepository(new DatabaseFactory()); IEnumerable<User> actual = repository.GetAll(); Assert.NotNull(actual); var actualList = new List<User>(actual); Assert.Equal(0, actualList.Count); } /// <summary> /// The when laying out a test_ then arrange act assert. /// </summary> [Fact] public void WhenLayingOutATest_ThenArrangeActAssert() { // Arrange const int EXPECTED_RESULT = 4; int calculatedResult; // Act calculatedResult = 2 + 2; // Assert Assert.Equal(EXPECTED_RESULT, calculatedResult); } /// <summary> /// The when test just does not work_ then skip. /// </summary> [Fact(Skip = "Unresolved issue - need to resolve - THIS IS A PLANNED FAILURE!")] public void WhenTestJustDoesNotWork_ThenSkip() { Assert.Equal(5, 2 + 2); } /// <summary> /// The when user added_ then updates repository. /// </summary> [Fact] public void WhenUserAdded_ThenUpdatesRepository() { DatabaseTestUtility.DropCreateFirebrickDatabase(); var repository = new UserRepository(new DatabaseFactory()); var newUser = new User { DisplayName = "name", Country = "United States", PostalCode = "a1b2c3", Password = "<PASSWORD>", UserName = "username" }; repository.Add(newUser); repository.Commit(); List<User> actualList = repository.GetAll().ToList(); Assert.Equal(1, actualList.Count); Assert.Equal(newUser.DisplayName, actualList[0].DisplayName); } #endregion #region Methods /// <summary> /// The initialize fixture. /// </summary> private void InitializeFixture() { DatabaseTestUtility.DropCreateFirebrickDatabase(); this.defaultTestUser = new User { DisplayName = "name", Country = "United States", PostalCode = "a1b2c3", Password = "<PASSWORD>", UserName = "username" }; var repository = new UserRepository(new DatabaseFactory()); repository.Add(this.defaultTestUser); } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="CmsPageManagerIndexViewModel.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.ViewModels.WebAdmin.CmsMenuManager { using System.Collections.Generic; using Firebrick.Domain.ViewModels.WebAdmin.CmsPageManager; /// <summary> /// The cms page manager index view model. /// </summary> public class CmsUserManagerIndexViewModel { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="CmsPageManagerIndexViewModel"/> class. /// </summary> public CmsUserManagerIndexViewModel() { this.Users = new List<CmsUserManagerIndexViewModelListItem>(); } #endregion #region Public Properties /// <summary> /// Gets or sets Pages. /// </summary> public IEnumerable<CmsUserManagerIndexViewModelListItem> Users { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PageTemplateFixture.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Model.Tests.EFModels { using Xunit; /// <summary> /// The page template fixture. /// </summary> public class PageTemplateFixture { #region Public Methods /// <summary> /// The when instantiating class with default constructor_ suceeds. /// </summary> [Fact] public void WhenInstantiatingClassWithDefaultConstructor_Succeeds() { // Arrange PageTemplate model; // Act model = new PageTemplate(); // Assert Assert.NotNull(model); } #endregion } }<file_sep>namespace Firebrick.Model { using System.ComponentModel.DataAnnotations; public class UserRole { #region Public Properties /// <summary> /// Gets or sets RoleId. /// </summary> public int RoleId { get; set; } /// <summary> /// Gets or sets UserId. /// </summary> public int UserId { get; set; } /// <summary> /// Gets or sets UserRoleId. /// </summary> [Key] public int UserRoleId { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="CmsPageManagerBaseViewModel.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.ViewModels.WebAdmin.CmsPageManager { using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; using Firebrick.Domain.Validators; /// <summary> /// The cms page manager base view model. /// </summary> public abstract class CmsPageManagerBaseViewModel { #region Public Properties /// <summary> /// Gets ActionCancel. /// </summary> public abstract string ActionCancelUrl { get; } /// <summary> /// Gets or sets ActionName. /// </summary> [Display(Name = "Action Name")] public string ActionName { get; set; } /// <summary> /// Gets or sets ControllerName. /// </summary> [TextLineInputValidator] [Display(Name = "Controller Name")] public string ControllerName { get; set; } public string Description { get; set; } public string Keywords { get; set; } public string LookFor { get; set; } [Display(Name = "Page Structure Style")] public int PageStructureStyleId { get; set; } /// <summary> /// Gets or sets PageControllerActionId. /// </summary> [Display(Name = "Page Type")] public int PageControllerActionId { get; set; } /// <summary> /// Gets or sets PageControllerActionList. /// </summary> public IEnumerable<SelectListItem> PageControllerActionList { get; set; } //// [Display(Name = "UserPostalCodeLabelText", ResourceType = typeof(Resources))] /// <summary> /// Gets or sets PageId. /// </summary> public int PageId { get; set; } public int PageParentId { get; set; } /// <summary> /// Gets or sets PageTemplateId. /// </summary> [Display(Name = "Page Layout")] public int PageTemplateId { get; set; } /// <summary> /// Gets or sets PageTemplateList. /// </summary> public IEnumerable<SelectListItem> PageTemplateList { get; set; } //// TODO: [RP] [170612] Do we need to dispay parent page name? :: Does this open questions about editing parent page at edit time? public bool RobotsFollow { get; set; } public bool RobotsIndex { get; set; } /// <summary> /// Gets or sets a value indicating whether ShowOnMenu. /// </summary> [Display(Name = "Show on Menu")] public bool ShowOnMenu { get; set; } /// <summary> /// Gets or sets Title. /// </summary> [Required] [MaxLength(50, ErrorMessage = "Page length must be 50 characters or less")] [MinLength(3)] public string Title { get; set; } public IEnumerable<SelectListItem> PageRolesAvailableList { get; set; } public IEnumerable<int> PageRolesSelectedItems { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="UserFixture.cs" company=""> // // </copyright> // <summary> // The user fixture. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Model.Tests { using System.ComponentModel.DataAnnotations; using Firebrick.Domain.ViewModels; using Xunit; /// <summary> /// The user fixture. /// </summary> public class UserFixture { #region Public Methods /// <summary> /// The when validating user with country as us and alpha numeric postal code_ then validation fails. /// </summary> [Fact] public void WhenValidatingUserWithCountryAsUSAndAlphaNumericPostalCode_ThenValidationFails() { var user = new FirebrickUserViewModel { DisplayName = "name", Country = "United States", PostalCode = "a1b2c3", Password = "<PASSWORD>", UserName = "username" }; var exception = Assert.Throws<ValidationException>(() => ValidateUser(user)); Assert.Contains("PostalCode", exception.ValidationResult.MemberNames); } /// <summary> /// The when validating user with country as us and five digit numeric postal code_ then validation succeeds. /// </summary> [Fact] public void WhenValidatingUserWithCountryAsUSAndFiveDigitNumericPostalCode_ThenValidationSucceeds() { var user = new FirebrickUserViewModel { DisplayName = "name", Country = "United States", PostalCode = "12345", Password = "<PASSWORD>", UserName = "username" }; ValidateUser(user); } /// <summary> /// The when validating user with country as us and long numeric postal code_ then validation fails. /// </summary> [Fact] public void WhenValidatingUserWithCountryAsUSAndLongNumericPostalCode_ThenValidationFails() { var user = new FirebrickUserViewModel { DisplayName = "name", Country = "United States", PostalCode = "123456", Password = "<PASSWORD>", UserName = "username" }; var exception = Assert.Throws<ValidationException>(() => ValidateUser(user)); Assert.Contains("PostalCode", exception.ValidationResult.MemberNames); } /// <summary> /// The when validating user with country as us and short numeric postal code_ then validation fails. /// </summary> [Fact] public void WhenValidatingUserWithCountryAsUSAndShortNumericPostalCode_ThenValidationFails() { var user = new FirebrickUserViewModel { DisplayName = "name", Country = "United States", PostalCode = "123", Password = "<PASSWORD>", UserName = "username" }; var exception = Assert.Throws<ValidationException>(() => ValidateUser(user)); Assert.Contains("PostalCode", exception.ValidationResult.MemberNames); } /// <summary> /// The when validating user with long country_ then validation fails. /// </summary> [Fact] public void WhenValidatingUserWithLongCountry_ThenValidationFails() { var user = new FirebrickUserViewModel { DisplayName = "name", Country = "ThisIsAVeryVeryVeryVeryVeryLongStringThatShouldNotBeAllowed", PostalCode = "12345", Password = "<PASSWORD>", UserName = "username" }; var exception = Assert.Throws<ValidationException>(() => ValidateUser(user)); Assert.Contains("Country", exception.ValidationResult.MemberNames); } /// <summary> /// The when validating user with long postal code_ then validation fails. /// </summary> [Fact] public void WhenValidatingUserWithLongPostalCode_ThenValidationFails() { var user = new FirebrickUserViewModel { DisplayName = "name", Country = "United States", PostalCode = "12345678901234567890", Password = "<PASSWORD>", UserName = "username" }; var exception = Assert.Throws<ValidationException>(() => ValidateUser(user)); Assert.Contains("PostalCode", exception.ValidationResult.MemberNames); } #endregion #region Methods /// <summary> /// The validate user. /// </summary> /// <param name="user"> /// The user. /// </param> private static void ValidateUser(FirebrickUserViewModel user) { var context = new ValidationContext(user, null, null); Validator.ValidateObject(user, context, true); } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ContentBlob.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Model { using System.ComponentModel.DataAnnotations; /// <summary> /// The content blob. /// </summary> public class ContentBlob { #region Public Properties /// <summary> /// Gets or sets ContentBlobId. /// </summary> [Key] public int ContentBlobId { get; set; } /// <summary> /// Gets or sets Html. /// </summary> public string Html { get; set; } /// <summary> /// Gets or sets PartId. /// </summary> public int PartId { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Portals.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // <summary> // The portals. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.EF.Initializers { using System.Data.Entity.Migrations; using System.Data.Entity.Validation; using System.Diagnostics; using Firebrick.Model; /// <summary> /// The portals. /// </summary> public static class PortalInitializer { #region Public Methods /// <summary> /// The add portals. /// </summary> /// <param name="context"> /// The context. /// </param> public static void Add(FirebrickContext context) { var myFirebrick = new Portal { PortalId = 1, Title = "FIREBRICK" }; context.Portals.AddOrUpdate(myFirebrick); try { context.SaveChanges(); } catch (DbEntityValidationException dbEx) { foreach (DbEntityValidationResult validationErrors in dbEx.EntityValidationErrors) { foreach (DbValidationError validationError in validationErrors.ValidationErrors) { Debug.WriteLine( "Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } } } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PageServiceFixture.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Services.Tests { using Firebrick.Data; using Firebrick.Data.RepositoryContracts; using Firebrick.Model; using Firebrick.Service.Implementations; using Firebrick.Test.Helper; using Moq; using Xunit; /// <summary> /// The page service fixture. /// </summary> public class PageServiceFixture { #region Public Methods [Fact] public void WhenGettingEntity_ThenReturnsCorrectEntity() { // Arrange var repositoryMock = new Mock<IPageRepository>(); Page newEntity = DefaultModelHelper.DummyPopulatedPage(); repositoryMock.Setup(repo => repo.GetById(It.IsAny<int>())).Returns(newEntity); // Act var services = new PageService(repositoryMock.Object, new Mock<IUnitOfWork>().Object); Page returnedEntity = services.GetById(1); // Assert Assert.NotNull(returnedEntity); Assert.Equal("ActionName", returnedEntity.ActionName); } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="RichContentAddViewModel.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.ViewModels.ContentManagement.RichContent { /// <summary> /// The rich content add view model. /// </summary> public class RichContentAddViewModel { #region Public Properties /// <summary> /// Gets or sets Html. /// </summary> public string Html { get; set; } /// <summary> /// Gets or sets PartId. /// </summary> public int PartId { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PageRepository.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.EF.Repositories { using Firebrick.Data.RepositoryContracts; using Firebrick.Model; /// <summary> /// The web page repository. /// </summary> public class PageRepository : BaseRepository<Page>, IPageRepository { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="PageRepository"/> class. /// </summary> /// <param name="databaseFactory"> /// The database factory. /// </param> public PageRepository(IDatabaseFactory databaseFactory) : base(databaseFactory) { } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="SiteMapViewModel.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.ViewModels.Web.Core { using System.Collections; using System.Xml.Serialization; /// <summary> /// The site map view model. /// </summary> [XmlRoot("urlset", Namespace = "http://www.google.com/schemas/sitemap/0.9")] public class SiteMapViewModel { #region Constants and Fields [XmlAttribute("schemaLocation")] public string SchemaLocation = "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"; private ArrayList map; #endregion #region Constructors and Destructors public SiteMapViewModel() { this.map = new ArrayList(); } #endregion #region Public Properties [XmlElement("url")] public Location[] Locations { get { var items = new Location[this.map.Count]; this.map.CopyTo(items); return items; } set { if (value == null) { return; } Location[] items = value; this.map.Clear(); foreach (Location item in items) { this.map.Add(item); } } } #endregion #region Public Methods public int Add(Location item) { return this.map.Add(item); } #endregion } public class Location { #region Enums public enum ChangeFrequencyEnum { always, hourly, daily, weekly, monthly, yearly, never } #endregion #region Public Properties [XmlElement("changefreq", Order = 3)] public ChangeFrequencyEnum? ChangeFrequency { get; set; } [XmlElement("lastmod", Order = 2)] public string LastModified { get; set; } [XmlElement("priority", Order = 4)] public string Priority { get; set; } [XmlElement("loc", Order = 1)] public string Url { get; set; } #endregion #region Public Methods public bool ShouldSerializeChangeFrequency() { return this.ChangeFrequency.HasValue; } #endregion } }<file_sep>namespace Firebrick.Service.Implementations { using Firebrick.Data; using Firebrick.Data.RepositoryContracts; using Firebrick.Model; using Firebrick.Service.Contracts; /// <summary> /// The analytics type service. /// </summary> public class AnalyticsTypeService : BaseService<AnalyticsType>, IAnalyticsTypeService { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="AnalyticsTypeService"/> class. /// </summary> /// <param name="analyticsTyperepository"> /// The analtics type repository. /// </param> /// <param name="unitOfWork"> /// The unit of work. /// </param> public AnalyticsTypeService(IAnalyticsTypeRepository analyticsTyperepository, IUnitOfWork unitOfWork) { this.Repository = analyticsTyperepository; this.UnitOfWork = unitOfWork; } #endregion } }<file_sep>namespace Firebrick.Web.UI.UI { using System.Web.Mvc; using Firebrick.Framework.Exceptions; using Firebrick.UI.Core.Filters; public class FilterConfig { #region Public Methods public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); // http://blogs.msdn.com/b/rickandy/archive/2011/05/02/securing-your-asp-net-mvc-3-application.aspx#comments // Now, any controller (not named account) is protected by the [Authorize] attribute. filters.Add(new LogonAuthorise()); // Global Authorise Filter /* * If the account controller is renamed, it won’t be excluded. That’s not a security risk, as no one will be able to log on and you’ll quickly find the problem. * If you have multiple areas, all account controllers will be exempted from authorization. */ filters.Add( new HandleErrorAttribute { ExceptionType = typeof(CustomWebException), View = "CustomWebException", Order = 1 }); filters.Add(new HandleErrorAttribute()); } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="CmsPageManagerIndexViewModel.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.ViewModels.WebAdmin.CmsPageManager { using System.Collections.Generic; /// <summary> /// The cms page manager index view model. /// </summary> public class CmsPageManagerIndexViewModel { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="CmsPageManagerIndexViewModel"/> class. /// </summary> public CmsPageManagerIndexViewModel() { this.Pages = new List<CmsPageManagerIndexViewModelListItem>(); } #endregion #region Public Properties /// <summary> /// Gets or sets Pages. /// </summary> public IEnumerable<CmsPageManagerIndexViewModelListItem> Pages { get; set; } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IClientAssetRepository.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Data.RepositoryContracts { using Firebrick.Model; /// <summary> /// The i client asset repository. /// </summary> public interface IClientAssetRepository : IRepository<ClientAsset> { } }<file_sep>namespace Firebrick.Service.Contracts { using Firebrick.Model; ///<summary> ///The i analytics account service config ///</summary> public interface IAnalyticsAccountService : IService<AnalyticsAccount> { } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ILoggingService.cs" company="Beyond"> // Copyright Beyond 2012 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.UI.Core.Logging { using System; /// <summary> /// The i logging service. /// </summary> public interface ILoggingService { #region Public Methods /// <summary> /// The fatal. /// </summary> /// <param name="message"> /// The message. /// </param> /// <param name="ex"> /// The ex. /// </param> void Fatal(string message, Exception ex); /// <summary> /// The info. /// </summary> /// <param name="message"> /// The message. /// </param> /// <param name="ex"> /// The ex. /// </param> void Info(string message, Exception ex); /// <summary> /// The log. /// </summary> /// <param name="message"> /// The message. /// </param> void Log(string message); /// <summary> /// The warning. /// </summary> /// <param name="message"> /// The message. /// </param> /// <param name="ex"> /// The ex. /// </param> void Warning(string message, Exception ex); #endregion } }<file_sep>namespace Firebrick.Service.Contracts { using Firebrick.Model; public interface IRolePartRestrictionService : IService<RolePartRestriction> { } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="UrlHelperExtensions.cs" company="Beyond"> // Copyright Beyond 2012 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.UI.Core.Helpers { using System.Text; using System.Web.Mvc; using System.Web.Routing; /// <summary> /// The url helper extensions. /// </summary> public static class UrlHelperExtensions { #region Public Methods public static string AdminAction( this UrlHelper urlHelper, string actionName, string controllerName, object routeValues) { return GenerateUrl(actionName, controllerName, new RouteValueDictionary(routeValues)); } #endregion #region Methods private static string GenerateRouteValues(RouteValueDictionary routeValueDictionary) { var routeValues = new StringBuilder(); if (routeValueDictionary != null) { if (routeValueDictionary.Count > 0) { int index = 0; foreach (var route in routeValueDictionary) { if (index == 0) { routeValues.AppendFormat("{0}", route.Value); } if (index == 1) { routeValues.AppendFormat("?{0}={1}", route.Key, route.Value); } if (index > 1) { routeValues.AppendFormat("&{0}={1}", route.Key, route.Value); } index++; } } } return routeValues.ToString(); } /// <summary> /// The generate url. /// </summary> /// <param name="actionName"> /// The action name. /// </param> /// <param name="controllerName"> /// The controller name. /// </param> /// <param name="routeValueDictionary"> /// The route value dictionary. /// </param> /// <returns> /// The generated url. /// </returns> private static string GenerateUrl( string actionName, string controllerName, RouteValueDictionary routeValueDictionary) { return string.Format("/{0}/{1}/{2}", controllerName, actionName, GenerateRouteValues(routeValueDictionary)); } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="LogonAuthorise.cs" company="Beyond"> // Copyright Beyond 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.UI.Core.Filters { using System.Web.Mvc; using Firebrick.UI.Core.Controllers; /// <summary> /// The logon authorise. /// </summary> public class LogonAuthorise : AuthorizeAttribute { #region Public Methods /// <summary> /// The on authorization. /// </summary> /// <param name="filterContext"> /// The filter context. /// </param> public override void OnAuthorization(AuthorizationContext filterContext) { // Runs the Authorize filter on every controller except the Account controller //if (!(filterContext.Controller is AccountController)) //{ // base.OnAuthorization(filterContext); //} // Runs the Authorise filter only on types of BaseAdminController if (filterContext.Controller is BaseAdminController) { base.OnAuthorization(filterContext); } } #endregion } }<file_sep>// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PageServiceBinder.cs" company="Firebrick"> // Copyright Firebrick 2011 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Firebrick.Domain.ServiceBinders { using System.Web.Mvc; using Firebrick.Domain.ViewModels; using Firebrick.Model; using Firebrick.Service.Contracts; /// <summary> /// The page service binder. /// </summary> public class PageServiceBinder { #region Constants and Fields /// <summary> /// The page service. /// </summary> private readonly IPageService pageService; /// <summary> /// The page template service. /// </summary> private readonly IPageTemplateService pageTemplateService; #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="PageServiceBinder"/> class. /// </summary> /// <param name="pageService"> /// The page service. /// </param> /// <param name="pageTemplateService"> /// The page template service. /// </param> public PageServiceBinder(IPageService pageService, IPageTemplateService pageTemplateService) { this.pageService = pageService; this.pageTemplateService = pageTemplateService; } #endregion #region Public Methods public bool Add(IPageViewModel viewModel) { this.pageService.Add(viewModel.Page); return true; } /// <summary> /// Binds PageViewModel /// </summary> /// <param name="pageId"> /// The page id. /// </param> /// <returns> /// Returns Page View Model /// </returns> public PageViewModel BindModel(int pageId) { var viewModel = new PageViewModel(); Page page = this.pageService.GetById(pageId); if (page != null) { viewModel.Page = page; } else { viewModel.Page = new Page { PageId = -1 }; } if (this.pageTemplateService != null) { viewModel.PageTemplateList = new SelectList( this.pageTemplateService.GetAll(), "PageTemplateId", "Title"); viewModel.ParentPageList = new SelectList( this.pageService.GetMany(p => p.PageParentId == 1), "PageId", "Title"); } return viewModel; } /// <summary> /// Updates the view model /// </summary> /// <param name="viewModel"> /// The view model. /// </param> /// <returns> /// boolean if failed or suceeded /// </returns> public bool Update(IPageViewModel viewModel) { this.pageService.Update(viewModel.Page); return true; } #endregion } }
7376de2fe7f8cd3d091c32533a3f6d76f1789063
[ "JavaScript", "C#", "Text", "Markdown" ]
275
C#
rajbyexample/Firebrick-CMS
e0615292fea836572e7443da0a11d493e2b67980
5ff14d69ca147c8c881d048a4292f77e3d587678
refs/heads/main
<repo_name>ericktomaliwan/image-downloader-url-csv<file_sep>/index.php <?php echo 'hello world'; $filename = 'test.csv'; $fp = fopen($filename, 'r+'); fputs($fp, $csvText); rewind($fp); $csv = []; while ( ($data = fgetcsv($fp) ) !== FALSE ) { $csv[] = $data; } //echo '<pre>'; print_r($csv); echo '</pre>'; $final_array = []; $i = 0; foreach($csv as $data){ #get category $explode_data = explode("_", $data[5]); #Check for empty titles $local_title = empty($data[3]) ? 'no_title_'.$explode_data[1] : $data[3]; #assign to array $final_array[] = array( 'title' => $local_title , 'url' => $data[4], 'category' => $explode_data[0] ); } #Remove header array_shift($final_array); #Downfile File foreach ($final_array as $fa){ #assign to local variable $ftitle = $fa['title']; $furl = $fa['url']; $fcategory = $fa['category']; #Get file extension $info = getimagesize($furl); $extension = image_type_to_extension($info[2]); #print out all entries echo '<pre>'; print_r($fa); echo '</pre>'; #Assign to a folder //copy($furl, $fcategory); file_put_contents($fcategory.'/'.$ftitle.$extension, file_get_contents($furl)); } ?>
5d949adb739774f7bc994405f2346fc20d255383
[ "PHP" ]
1
PHP
ericktomaliwan/image-downloader-url-csv
73c059a9fbb89bddd95787ef8ac5124de1d73bcb
b51d71d47e7eeee4dbe0e589f7f754241e870bc7
refs/heads/master
<file_sep>(function () { angular.module('app', ['toaster', 'rzSlider', 'ngAnimate', 'ngMaterial', 'ngRoute', 'pascalprecht.translate']) angular.module('app') .config(['$routeProvider', '$locationProvider', RouteConfig]) // .directive('myModel', function() { // return { // restrict: 'A', // link: function(scope, element, attr) { // scope.dismiss = function() { // element.modal('hide'); // }; // } // } // }) .config(['$translateProvider', function ($translateProvider) { $translateProvider.useStaticFilesLoader({ prefix: 'assets/i18n/locale-', suffix: '.json' }); $translateProvider.useSanitizeValueStrategy(null); // $translateProvider.preferredLanguage('en'); $translateProvider.use('en') // document.documentElement.style.setProperty('--dir', $translateProvider.use() == 'ar' ? 'rtl' : 'ltr') }]) .service('translateService', ['$translate', translateService]) .controller('MainController', MainController) .controller('CoreController', CoreController) .controller('HomePageController', HomePageController) .controller('RentalPageController', RentalPageController) .controller('PartnerPageController', PartnerPageController) .controller('PricingPageController', PricingPageController) .controller('ManagementPageController', ManagementPageController) .controller('CustomerOwnerAssociationPageController', CustomerOwnerAssociationPageController) .controller('CustomerBuilderPageController', CustomerBuilderPageController) .controller('CustomerFacilityManagementPageController', CustomerFacilityManagementPageController) .controller('CustomerSecurityPageController', CustomerSecurityPageController) .controller('CustomerRentalOwnersPageController', CustomerRentalOwnersPageController) .controller('ChooseProductPageController', ChooseProductPageController) .controller('RentalPropertyManagementPageController', RentalPropertyManagementPageController) .controller('CustomerRentalPropertyManagementPageController', CustomerRentalPropertyManagementPageController) .controller('ContactUsPageController', ContactUsPageController) .controller('FooterController', FooterController) .controller('PrivacyPolicyController', PrivacyPolicyController) .controller('VisionController', VisionController) .controller('OutTeamController', OutTeamController) .controller('ModalController', ModalController) .controller('TermsOfUseController', TermsOfUseController) .controller('ContactUsModalController', ContactUsModalController) .component('bottomFooter', { bindings: {}, templateUrl: 'pages/footer.html', controller: 'FooterController' }) .directive('changeClassOnScroll', function ($window) { return { restrict: 'A', scope: { offset: "@", scrollClass: "@" }, link: function (scope, element) { angular.element($window).bind("scroll", function () { if (this.pageYOffset >= parseInt(scope.offset)) { element.addClass(scope.scrollClass); } else { element.removeClass(scope.scrollClass); } }); } }; }) .directive( "mAppLoading", function ($animate) { // Return the directive configuration. return ({ link: link, restrict: "C" }); // I bind the JavaScript events to the scope. function link(scope, element, attributes) { // Due to the way AngularJS prevents animation during the bootstrap // of the application, we can't animate the top-level container; but, // since we added "ngAnimateChildren", we can animated the inner // container during this phase. // -- // NOTE: Am using .eq(1) so that we don't animate the Style block. $animate.leave(element.children().eq(1)).then( function cleanupAfterAnimation() { // Remove the root directive element. element.remove(); // Clear the closed-over variable references. scope = element = attributes = null; } ); } }) .directive('keepWidth', function () { return { restrict: 'A', link: function (scope, element, attrs, controller) { var width = element.prop('offsetWidth'); var otherCss = element.css('cssText'); attrs.$set('style', 'width: ' + width + 'px;' + otherCss); } } }); function RouteConfig($routeProvider, $locationProvider) { 'use strict'; $routeProvider .when('/', { templateUrl: 'home.html', controller: 'HomePageController' }) .when('/terms-of-use', { templateUrl: 'pages/terms-of-use.html', controller: "TermsOfUseController" }) .when('/privacy-policy', { templateUrl: 'pages/privacy-policy.html' }) .when('/refund-terms', { templateUrl: 'pages/refund-terms.html', controller: 'PrivacyPolicyController' }) .when('/vision', { templateUrl: 'pages/vision.html', controller: 'VisionController' }) .when('/our-team', { templateUrl: 'pages/our-team.html', controller: 'OutTeamController' }) .when('/partners', { templateUrl: 'pages/partners.html', controller: 'PartnerPageController' }) .when('/pricing', { templateUrl: 'pages/pricing.html', controller: 'PricingPageController' }) .when('/customer-owner-association', { templateUrl: 'pages/customer-owner-association.html', controller: 'CustomerOwnerAssociationPageController' }) .when('/customer-facility-management', { templateUrl: 'pages/customer-facility-management.html', controller: 'CustomerFacilityManagementPageController' }) // .when('/customer-security', { templateUrl: 'pages/customer-security.html', controller: 'CustomerSecurityPageController' }) .when('/customer-builder', { templateUrl: 'pages/customer-builder.html', controller: 'CustomerBuilderPageController' }) .when('/customer-rental-owners', { templateUrl: 'pages/customer-rental-owners.html', controller: 'CustomerRentalOwnersPageController' }) .when('/choose-product', { templateUrl: 'pages/choose-product.html', controller: 'ChooseProductPageController' }) .when('/rental-management', { templateUrl: 'pages/customer-rental-property-management.html', controller: 'CustomerRentalPropertyManagementPageController' }) .when('/contact-us', { templateUrl: 'pages/contact-us.html', controller: 'ContactUsPageController' }) .otherwise({ redirectTo: '/' }); $locationProvider.html5Mode(true); } function CoreController($scope, $http, $document, $window, $location, toaster, $filter) { $scope.progressBarLoading = false; $scope.callbackForm = {}; $scope.onCallbackSubmitHandler = function (form) { $scope.callbackOverlayActive = true; $scope.progressBarLoading = true; $scope.loading = true $http({ method: 'POST', url: 'https://rentals.thehousemonk.com/shared-resource/webhook/capture-website-contact?organization=5e1ad3b4d0ffee5fb4fc0410', data: { 'name': $scope.callbackModalForm.name, 'phoneNumber': $scope.callbackModalForm.countryCode + $scope.callbackModalForm.phoneNumber, 'page': $location.path(), 'message': $scope.callbackModalForm.message, 'email': $scope.callbackModalForm.email } }).then(function (response) { $('#callbackModal').modal('hide'); // var capterra_vkey = '9deeec374e1dfff5b5dbb3a168be56e3', // capterra_vid = '2130197', // capterra_prefix = (('https:' == $window.location.protocol) // ? 'https://ct.capterra.com' : 'http://ct.capterra.com'); // var ct = $document[0].createElement('script'); // ct.type = 'text/javascript'; // ct.async = true; // ct.src = capterra_prefix + '/capterra_tracker.js?vid=' // + capterra_vid + '&vkey=' + capterra_vkey; // var s = $document[0].getElementsByTagName('script')[0]; // s.parentNode.insertBefore(ct, s); $scope.callbackForm = { countryCode: '+965' } $scope.loading = false; $scope.callbackModalForm = { countryCode: '+965' } form.$setPristine() form.$setUntouched(); $scope.showSuccessToast(); }, function (response) { $scope.loading = false; $scope.showErrorToast(); }).finally(function () { $scope.callbackOverlayActive = false; $scope.progressBarLoading = false; $scope.loading = false }); }; $scope.callbackModalForm = { }; $scope.onCallbackModalSubmitHandler = function (form) { $scope.callbackModalOverlayActive = true; $scope.progressBarLoading = true; $http({ method: 'POST', // url: '/shared-resource/webhook/support/contact-us/send-email', url: 'https://rentals.thehousemonk.com/shared-resource/webhook/capture-website-contact?organization=5e1ad3b4d0ffee5fb4fc0410', data: { 'name': $scope.callbackModalForm.name, 'phoneNumber': $scope.callbackModalForm.countryCode + $scope.callbackModalForm.phoneNumber, 'page': $location.path(), 'email': $scope.callbackModalForm.email, 'message': $scope.callbackModalForm.message, } }).then(function (response) { $scope.callbackModalForm = {}; $scope.showSuccessToast(); }, function (response) { $scope.showErrorToast(); }).finally(function () { $scope.callbackModalForm = { product: $scope.callbackModalForm.product }; $scope.progressBarLoading = false; $scope.callbackModalOverlayActive = false; }); } $scope.demoSignupForm = {}; // $scope.onDemoSignupSubmitHandler = function (form) { // $scope.progressBarLoading = true; // $scope.demoSignupOverlayActive = true; // $http({ // method: 'POST', // url: '/api/support/demo-registration', // data: { // 'name': $scope.demoSignupForm.name, // 'phoneNumber': $scope.demoSignupForm.countryCode + $scope.demoSignupForm.phoneNumber, // 'email': $scope.demoSignupForm.email, // 'organisation': $scope.demoSignupForm.organization, // } // }).then(function (response) { // var capterra_vkey = '9deeec374e1dfff5b5dbb3a168be56e3', // capterra_vid = '2130197', // capterra_prefix = (('https:' == $window.location.protocol) // ? 'https://ct.capterra.com' : 'http://ct.capterra.com'); // var ct = $document[0].createElement('script'); // ct.type = 'text/javascript'; // ct.async = true; // ct.src = capterra_prefix + '/capterra_tracker.js?vid=' // + capterra_vid + '&vkey=' + capterra_vkey; // var s = $document[0].getElementsByTagName('script')[0]; // s.parentNode.insertBefore(ct, s); // form.$setPristine(); // form.$setUntouched(); // $('#exampleModal').modal('hide') // $scope.showSuccessToast(); // }, function (response) { // $scope.showErrorToast(); // }).finally(function () { // $scope.demoSignupForm = { // countryCode: '+91' // }; // $scope.progressBarLoading = false; // setTimeout((() => { // window.location.href = 'api/demo-login?src=demopage'; // $scope.demoSignupOverlayActive = false; // }), 1500); // }); // } $scope.showSuccessToast = function () { toaster.pop('success', $filter('translate')("Success"), $filter('translate')("Your form has been submitted. We will get back to you.")); } $scope.showErrorToast = function () { toaster.pop('error', $filter('translate')("Error"), $filter('translate')("Something went wrong. Please try again")); } } function MainController($scope, $location, $controller, countryCodeService, $translate, translateService) { $controller('CoreController', { $scope: $scope }); var fetchCodes = []; var finalCodeArray = []; $scope.languages = [ { language: "en", name: "English", dir: 'ltr', imagePath: "assets/icons/USA.png" }, { language: "ar", name: "Arabic", dir: 'rtl', imagePath: "assets/icons/kuwait.png" } ]; $scope.selectLanguage = translateService.getCurrentLanguage() $scope.ChangeLanguage = function (langObject) { translateService.setCurrentLanguage(langObject.language) } for (var i = 0; i < countryCodeService.countryCodeList.length; i++) { if (!fetchCodes.includes(countryCodeService.countryCodeList[i].code)) { fetchCodes.push(countryCodeService.countryCodeList[i].code); } } fetchCodes = fetchCodes.sort(); for (var j = 0; j < fetchCodes.length; j++) { finalCodeArray.push({ 'code': fetchCodes[j] }); } $scope.citiCodes = finalCodeArray; $scope.routeToLoginPage = function () { window.location.href = '/authenticate'; }; $scope.routeToRenatlLoginPage = function () { window.location.href = 'https://dashboard.tryaqaraty.com/'; }; $scope.isActive = function (destination) { return destination === $location.path(); }; $scope.isAboutActive = function () { return "/vision" === $location.path() || "/our-team" === $location.path(); }; $scope.isCustomerActive = function () { return "/rental-management" === $location.path() || "/customer-co-living" === $location.path() || "/customer-co-working" === $location.path() || "/customer-owner-association" === $location.path() || "/customer-builder" === $location.path() || "/customer-facility-management" === $location.path() || "/customer-rental-owners" === $location.path(); } } function translateService($translate) { var translateService = {}; // this.language = translateService.getCurrentLanguage() translateService.getCurrentLanguage = function () { return $translate.use() } translateService.setCurrentLanguage = function (lang) { $translate.use(lang) } translateService.setDirection = function (dir) { // document.documentElement.style.setProperty("--dir", $translate.use() == 'ar' ? 'rtl' : 'ltr') } return translateService } function CustomerOwnerAssociationPageController($scope, $controller, $window, translateService) { // Extend CoreController controller functionalities $controller('CoreController', { $scope: $scope }); $scope.translateService = translateService $window.scroll(0, 0); $window.document.title = 'Real Estate Customer Experience Management Platform | Property Management Solutions'; $scope.callbackForm = { }; $scope.callbackModalForm = { }; $scope.routeToSignupPage = function () { window.location.href = '/authenticate/#!/signup'; }; } function CustomerBuilderPageController($scope, $controller, $window, translateService) { // Extend CoreController controller functionalities $controller('CoreController', { $scope: $scope }); $window.document.title = 'Real Estate Customer Experience Management Platform | Property Management Solutions'; $scope.translateService = translateService $scope.callbackForm = { product: 'Building Management' }; $scope.callbackModalForm = { }; $window.scroll(0, 0); $scope.routeToSignupPage = function () { window.location.href = '/authenticate/#!/signup'; }; } function CustomerFacilityManagementPageController($scope, $controller, $window, translateService) { // Extend CoreController controller functionalities $controller('CoreController', { $scope: $scope }); $scope.translateService = translateService $window.document.title = 'Real Estate Customer Experience Management Platform | Property Management Solutions'; $window.scroll(0, 0); $scope.callbackForm = { product: 'Building Management' }; $scope.callbackModalForm = { product: 'Building Management' }; $scope.routeToSignupPage = function () { window.location.href = '/authenticate/#!/signup'; } } function RentalPropertyManagementPageController($scope, $controller) { $controller('CoreController', { $scope: $scope }); $window.document.title = 'Real Estate Customer Experience Management Platform | Property Management Solutions'; $scope.callbackForm = { product: 'Rental Management' }; $scope.callbackModalForm = { product: 'Rental Management' }; $scope.routeToRentalsSignupPage = function () { window.location.href = 'https://rentals.thehousemonk.com/authenticate/#!/signup'; }; } function CustomerSecurityPageController($scope, $controller, $window) { // Extend CoreController controller functionalities $controller('CoreController', { $scope: $scope }); $window.document.title = 'Real Estate Customer Experience Management Platform | Property Management Solutions'; $window.scroll(0, 0); $scope.callbackForm = { product: 'Building Management' }; $scope.callbackModalForm = { product: 'Building Management' }; } function CustomerRentalOwnersPageController($scope, $controller, $window) { // Extend CoreController controller functionalities $controller('CoreController', { $scope: $scope }); $window.scroll(0, 0); $window.document.title = 'Real Estate Customer Experience Management Platform | Property Management Solutions'; $scope.callbackForm = { product: 'Rental Management' }; $scope.callbackModalForm = { product: 'Rental Management' }; $scope.routeToSignupPage = function () { window.location.href = '/authenticate/#!/signup'; }; } function CustomerCoLivingPageController($scope, $controller, $window) { // Extend CoreController controller functionalities $controller('CoreController', { $scope: $scope }); $window.scroll(0, 0); $window.document.title = 'Real Estate Customer Experience Management Platform | Property Management Solutions'; $scope.callbackForm = { product: 'Rental Management' }; $scope.callbackModalForm = { product: 'Rental Management' }; $scope.routeToSignupPage = function () { window.location.href = '/authenticate/#!/signup'; }; } function CustomerCoWorkingPageController($scope, $controller, $window) { // Extend CoreController controller functionalities $controller('CoreController', { $scope: $scope }); $window.document.title = 'Real Estate Customer Experience Management Platform | Property Management Solutions'; $window.scroll(0, 0); $scope.callbackForm = { product: 'Rental Management' }; $scope.callbackModalForm = { product: 'Rental Management' }; $scope.routeToSignupPage = function () { window.location.href = '/authenticate/#!/signup'; }; } function CustomerRentalPropertyManagementPageController($scope, $controller, $window, translateService) { // Extend CoreController controller functionalities $controller('CoreController', { $scope: $scope }); $scope.translateService = translateService $window.document.title = 'Real Estate Customer Experience Management Platform | Property Management Solutions'; $window.scroll(0, 0); $scope.callbackForm = { product: 'Rental Management' }; $scope.callbackModalForm = { product: 'Rental Management' }; $scope.routeToSignupPage = function () { window.location.href = '/authenticate/#!/signup'; }; } function ChooseProductPageController($scope, $controller, $window, translateService) { // Extend CoreController controller functionalities $controller('CoreController', { $scope: $scope }); $scope.toggleKey = (key) => { $scope[key] = !$scope[key]; }; $scope.translateService = translateService $window.scroll(0, 0); $window.document.title = 'Real Estate Customer Experience Management Platform | Property Management Solutions'; $scope.routeToRentalsSignupPage = function () { window.location.href = 'https://rentals.thehousemonk.com/authenticate/#!/signup'; } $scope.routeToSignupPage = function () { window.location.href = '/authenticate/#!/signup'; } } function HomePageController($scope, $controller, $location, $window, translateService) { $controller('CoreController', { $scope: $scope }); $scope.currentLanguage = translateService.getCurrentLanguage() $window.scroll(0, 0); $window.document.title = 'Real Estate Customer Experience Management Platform | Property Management Solutions'; $scope.callbackForm = { product: 'Building Management' }; $scope.callbackModalForm = { product: 'Building Management' }; } function RentalPageController($scope, $controller, $window) { $controller('CoreController', { $scope: $scope }); $window.scroll(0, 0); $window.document.title = 'Real Estate Customer Experience Management Platform | Property Management Solutions'; $scope.callbackForm = { product: 'Rental Management' }; $scope.callbackModalForm = { product: 'Rental Management' }; $scope.routeToRentalsSignupPage = function () { window.location.href = 'https://rentals.thehousemonk.com/authenticate/#!/signup'; }; } function DataManagementPageController($scope, $controller, $window) { $controller('CoreController', { $scope: $scope }); $window.scroll(0, 0); $window.document.title = 'Data Management'; $scope.callbackForm = { product: 'Rental Management' }; $scope.callbackModalForm = { product: 'Rental Management' }; $scope.routeToRentalsSignupPage = function () { window.location.href = 'https://rentals.thehousemonk.com/authenticate/#!/signup'; }; } function AccountFinancePageController($scope, $controller, $window) { $controller('CoreController', { $scope: $scope }); $window.scroll(0, 0); $window.document.title = 'Accounts & Finance'; $scope.callbackForm = { product: 'Rental Management' }; $scope.callbackModalForm = { product: 'Rental Management' }; $scope.routeToRentalsSignupPage = function () { window.location.href = 'https://rentals.thehousemonk.com/authenticate/#!/signup'; }; } function OperationManagementPageController($scope, $controller, $window) { $controller('CoreController', { $scope: $scope }); $window.scroll(0, 0); $window.document.title = 'Operation Management'; $scope.callbackForm = { product: 'Rental Management' }; $scope.callbackModalForm = { product: 'Rental Management' }; $scope.routeToRentalsSignupPage = function () { window.location.href = 'https://rentals.thehousemonk.com/authenticate/#!/signup'; }; } function CommunityBuilderPageController($scope, $controller, $window) { $controller('CoreController', { $scope: $scope }); $window.scroll(0, 0); $window.document.title = 'Community Builder'; $scope.callbackForm = { product: 'Rental Management' }; $scope.callbackModalForm = { product: 'Rental Management' }; $scope.routeToRentalsSignupPage = function () { window.location.href = 'https://rentals.thehousemonk.com/authenticate/#!/signup'; }; } function VisitorManagementPageController($scope, $controller, $window) { $controller('CoreController', { $scope: $scope }); $window.document.title = 'Visitor Management'; $window.scroll(0, 0); $scope.callbackForm = { product: 'Rental Management' }; $scope.callbackModalForm = { product: 'Rental Management' }; $scope.routeToRentalsSignupPage = function () { window.location.href = 'https://rentals.thehousemonk.com/authenticate/#!/signup'; }; } function PricingPageController($scope, $controller, $window, translateService) { $controller('CoreController', { $scope: $scope }); $scope.translateService = translateService console.log($scope.translateService.getCurrentLanguage()); $window.document.title = 'Real Estate Customer Experience Management Platform | Property Management Solutions'; $scope.priceList = [ { name: 'US', value: 1.5, baseUnit: 94 }, { name: 'Europe', value: 1.5, baseUnit: 94 }, { name: 'Middle East', value: 2, baseUnit: 63 }, { name: 'Kuwait', value: 1, baseUnit: 175 }, { name: 'Singapore', value: 1.5, baseUnit: 94 }, { name: 'South East Asia', value: 1, baseUnit: 175 }, { name: 'Australia', value: 1, baseUnit: 94 }, { name: 'Rest of the world', value: 1, baseUnit: 175 } ] $scope.options = { floor: 0, ceil: 2500, step: 5, onChange: (sliderId, modelValue, highValue, pointerType) => { $scope.updatePrice(modelValue); }, translate: function (value, sliderId, label) { if (label == 'model') return value + ' units'; return value; } }; $scope.countryPrice = 'India'; $window.scroll(0, 0); $scope.unit = { value: 0 }; $scope.price = 200; $scope.billedAt = 0; $scope.basePrice = 0; $scope.regionUnit = 175; $scope.updatePrice = (value) => { $scope.priceList.forEach(price => { if (price.name === $scope.countryPrice) { $scope.basePrice = price.value; $scope.regionUnit = parseInt(price.baseUnit); } }) if ((value !== 0) && (value <= 100)) { $scope.actualPrice = Math.round(parseInt(value) * 1.50 * $scope.basePrice); if ($scope.actualPrice > 200) { $scope.price = $scope.actualPrice; $scope.regionUnit = value; } $scope.billedAt = (parseInt($scope.price) / parseInt(value)).toFixed(2); } else if ((value !== 0) && (value <= 300)) { $scope.actualPrice = Math.round(parseInt(value) * 1.20 * $scope.basePrice); if ($scope.actualPrice > 200) { $scope.price = $scope.actualPrice; $scope.regionUnit = value; } $scope.billedAt = (parseInt($scope.price) / parseInt(value)).toFixed(2); } else if ((value !== 0) && (value <= 1000)) { $scope.actualPrice = Math.round(parseInt(value) * 1 * $scope.basePrice); if ($scope.actualPrice > 200) { $scope.price = $scope.actualPrice; $scope.regionUnit = value; } $scope.billedAt = (parseInt($scope.price) / parseInt(value)).toFixed(2); } else if ((value !== 0) && (value <= 2500)) { $scope.actualPrice = Math.round(parseInt(value) * 1 * $scope.basePrice); if ($scope.actualPrice > 200) { $scope.price = $scope.actualPrice; $scope.regionUnit = value; } $scope.billedAt = (parseInt($scope.price) / parseInt(value)).toFixed(2); } else if ((value == 0)) { $scope.price = 200; $scope.billedAt = 0; } }; } function PartnerPageController($scope, $controller, $window, translateService) { $controller('CoreController', { $scope: $scope }); $scope.translateService = translateService $window.scroll(0, 0); $window.document.title = 'Real Estate Customer Experience Management Platform | Property Management Solutions'; $scope.callbackForm = { product: 'Building Management' }; } function ContactUsPageController($scope, $controller, $window, $filter, translateService, $http, $location) { $controller('CoreController', { $scope: $scope }); $scope.translateService = translateService $window.scroll(0, 0); $window.document.title = 'Real Estate Customer Experience Management Platform | Property Management Solutions'; $scope.onContactUsSubmitHandler = function () { $scope.callbackModalOverlayActive = true; $scope.progressBarLoading = true; $scope.loading = true $http({ method: 'POST', url: 'https://rentals.thehousemonk.com/shared-resource/webhook/capture-website-contact?organization=5e1ad3b4d0ffee5fb4fc0410', data: { 'name': $scope.contactUsForm.name, 'phoneNumber': $scope.contactUsForm.countryCode + $scope.contactUsForm.phoneNumber, 'page': $location.path(), 'email': $scope.contactUsForm.email, 'message': $scope.contactUsForm.message, } }).then(function (response) { $scope.contactUsForm = {}; $scope.loading = false $scope.showSuccessToast(); }, function (response) { $scope.loading = false; $scope.showErrorToast(); }).finally(function () { $scope.contactUsForm = { product: $scope.contactUsForm.product }; $scope.progressBarLoading = false; $scope.callbackModalOverlayActive = false; }); } $scope.callbackForm = { product: 'Rental Management' }; } function ManagementPageController($scope, $controller, $window) { $controller('CoreController', { $scope: $scope }); $scope.callbackForm = { product: 'Building Management' } $scope.callbackModalForm = { product: 'Building Management' }; $window.scroll(0, 0); $scope.routeToSignupPage = function () { window.location.href = '/authenticate/#!/signup'; } $scope.featureScrollSelected = 'tickets'; $scope.featureScrollImage = '../assets/images/management-scroll-5-tickets.png'; $scope.featureScrollHeading = 'some text'; $scope.verticalScrollSelected = 'owner-associations'; $scope.buildersContent = [{ image: './assets/images/rental-scroll-4.png', title: 'Management', description: 'Manage all your residential and commercial projects through TheHouseMonk' }, { image: './assets/images/rental-scroll-4.png', title: 'All in one', description: 'Take care of facility management, rental management and other tasks' }, { image: './assets/images/rental-scroll-4.png', title: 'Staff management', description: 'Keep tabs on your staff and ensure they maintain your projects well' }]; $scope.ownerAssociationContent = [{ image: './assets/images/rental-scroll-4.png', title: 'Transparency', description: 'Maintain transparent records for all accounts and finances' }, { image: './assets/images/rental-scroll-4.png', title: 'Communication', description: 'Send important communications to all residents' }, { image: './assets/images/rental-scroll-4.png', title: 'Management', description: 'Manage all vendors and contract employees' }]; $scope.facilityManagementContent = [{ image: './assets/images/rental-scroll-4.png', title: 'Track & Monitor', description: 'Track and monitor all the maintenance activities across all your projects' }, { image: './assets/images/rental-scroll-4.png', title: 'Staff management', description: 'Manage the staff at various projects including their in and out time' }, { image: './assets/images/rental-scroll-4.png', title: 'Customer satisfaction', description: 'Ensure good level of service to customer through our review and rating system' }]; $scope.verticalScrollContent = $scope.ownerAssociationContent; $scope.onFeatureScrollClickHandler = function (key, text, imagePath) { $scope.featureScrollSelected = key; $scope.featureScrollHeading = text; $scope.featureScrollImage = imagePath; }; $scope.onVerticalScrollClickHandler = function (key, text, imagePath) { $scope.verticalScrollSelected = key; if (key === 'builders') { $scope.verticalScrollContent = $scope.buildersContent; } else { if (key === 'owner-associations') { $scope.verticalScrollContent = $scope.ownerAssociationContent; } else { if (key === 'facility-management') { $scope.verticalScrollContent = $scope.facilityManagementContent; } } } }; } function FooterController($scope, translateService) { $scope.translateService = translateService; $scope.currentLanguage = translateService.getCurrentLanguage() } function PrivacyPolicyController($scope, translateService) { $scope.translateService = translateService } function VisionController($scope, translateService) { $scope.translateService = translateService } function TermsOfUseController($scope, translateService) { $scope.translateService = translateService } function OutTeamController($scope, translateService) { $scope.translateService = translateService } function ModalController($scope, translateService, $http) { $scope.translateService = translateService $scope.onDemoSignupSubmitHandler = function (form) { $scope.progressBarLoading = true; $scope.demoSignupOverlayActive = true; $scope.currentLanguage = translateService.getCurrentLanguage(); $http({ method: 'POST', url: 'https://rentals.thehousemonk.com/shared-resource/webhook/demo-registration?organization=5e1ad3b4d0ffee5fb4fc0410', data: { 'name': $scope.demoSignupForm.name, 'phoneNumber': $scope.demoSignupForm.countryCode + $scope.demoSignupForm.phoneNumber, 'email': $scope.demoSignupForm.email, 'organisation': $scope.demoSignupForm.organization, 'fromExternalWebsite': true, } }).then(function (response) { // var capterra_vkey = '9deeec374e1dfff5b5dbb3a168be56e3', // capterra_vid = '2130197', // capterra_prefix = (('https:' == $window.location.protocol) // ? 'https://ct.capterra.com' : 'http://ct.capterra.com'); // var ct = $document[0].createElement('script'); // ct.type = 'text/javascript'; // ct.async = true; // ct.src = capterra_prefix + '/capterra_tracker.js?vid=' // + capterra_vid + '&vkey=' + capterra_vkey; // var s = $document[0].getElementsByTagName('script')[0]; // s.parentNode.insertBefore(ct, s); form.$setPristine(); form.$setUntouched(); $('#exampleModal').modal('hide') $scope.showSuccessToast(); }, function (response) { $scope.showErrorToast(); }).finally(function () { $scope.demoSignupForm = { countryCode: '+91' }; $scope.progressBarLoading = false; // setTimeout((() => { // window.location.href = 'api/demo-login?src=demopage'; // $scope.demoSignupOverlayActive = false; // }), 1500); }); } } function ContactUsModalController($scope, translateService) { $scope.translateService = translateService console.log(translateService.getCurrentLanguage()); } })();
860f77a460f47f5475f35aa62ed82d09e020e5cb
[ "JavaScript" ]
1
JavaScript
AkashBathala/Aqaraty-Website-translation
a317624fc5aad6cd09efd083316af892041e304b
9e5b248aa74324b8867fd53323b6d238d246104e
refs/heads/master
<file_sep>#! Rscript --vanilla ### Input: 1) metafile for the genomeic features ### 2) intmarkerGFoverlapped ### 3) randommarkerGFoverlapped ### 4) number of samples ### Final output files: i) feature specific (p-val_emp; p-val_norm (z-score); # of obs overlapped; expected overlap); ii) cell specific (min p-val_emp; feat_minp_emp; min p-val_norm (z-score); feat_minp_norm; cell p-val_norm_Q; cell p-val_norm_sample_Q; obs_overlapped_average; exp_overlapped_average; median FC ;numberoffeatures) Args <- commandArgs(TRUE) if (length(Args)!=5){ print("Usage: i) metafile; ii) intmarkerGFoverlapped; iii) randommarkerGFoverlapped; iv) number of samples; v) output prefix") quit() } library(MASS) metafile <- as.matrix(read.table(Args[1],colClasses="character")); intmarkerGFoverlapped <- as.matrix(read.table(Args[2],colClasses="numeric",header=T,check.names=F)); randommarkerGFoverlapped <- as.matrix(read.table(Args[3],colClasses="numeric",sep="\t",header=T,check.names=F)); numsamples <- as.numeric(Args[4]) ### metafile <- as.matrix(read.table("/net/assembly/alextsoi/Researches/Psoriasis_Immunochip_Kiel_GAIN_WTCCC2_Finemapping/MetaAnalysis/r2_common_known_novel5/data/GFmetafile",colClasses="character"));intmarkerGFoverlapped <- as.matrix(read.table("/net/assembly/alextsoi/Researches/Psoriasis_Immunochip_Kiel_GAIN_WTCCC2_Finemapping/MetaAnalysis/r2_common_known_novel5/function/temp.intmarkerGFoverlapped",colClasses="numeric",header=T,check.names=F));randommarkerGFoverlapped <- as.matrix(read.table("/net/assembly/alextsoi/Researches/Psoriasis_Immunochip_Kiel_GAIN_WTCCC2_Finemapping/MetaAnalysis/r2_common_known_novel5/function/temp.randommarkerGFoverlapped",colClasses="numeric",sep="\t",header=T,check.names=F));numsamples <- 2000 features <- colnames(intmarkerGFoverlapped) cells <- unique(metafile[match(metafile[,1],features,nomatch=0)!=0,3]) ######## A) feature specific result print("Computing p-value for each faeture...") result_f <- matrix(numeric(),length(features),4) rownames(result_f) <- features colnames(result_f) <- c("Emp_p","Norm_p","Obs","Exp") for (f in 1:length(features)){ tempobs <- intmarkerGFoverlapped[,features[f]] tempsample <- randommarkerGFoverlapped[,features[f]] ### !!! use adjusted p-value (give half score when samplecount==obscount) temp1 <- (sum(tempsample>tempobs)+0.5*sum(tempsample==tempobs))/length(tempsample) temp2 <- pnorm((tempobs-mean(tempsample))/sqrt(var(tempsample)),lower.tail=F) result_f[f,] <- c(temp1,temp2,tempobs,mean(tempsample)) } ####### B) cell type specific result print("Computing p-value for each cell type...") result_c <- matrix(numeric(),length(cells),10) rownames(result_c) <- cells colnames(result_c) <- c("minp_emp","minp_emp_feat","minp_norm","minp_norm_feat","Qpval_norm","Qpval_norm_sample","Obs_overlapped_average","Exp_overlapped_average","Median_FC","Number_of_features") ##### !! cannot use the feature if it does not have any variation in the tempsample availablefeatures <- colnames(randommarkerGFoverlapped)[colSums(randommarkerGFoverlapped)>0] ##### for (c in 1:length(cells)){ tempfeatures <- intersect(availablefeatures,metafile[metafile[,3]==cells[c],1]) tempresult_f <- result_f[tempfeatures,] if (length(tempfeatures)>1){ temp1 <- min(tempresult_f[,1]) temp2 <- paste(rownames(tempresult_f)[tempresult_f[,1]==temp1],collapse="; ") temp3 <- min(tempresult_f[,2]) temp4 <- paste(rownames(tempresult_f)[tempresult_f[,2]==temp3],collapse="; ") } else { temp1 <- tempresult_f[1] temp2 <- tempfeatures temp3 <- tempresult_f[2] temp4 <- tempfeatures } tempobs <- intmarkerGFoverlapped[,tempfeatures] tempsample <- randommarkerGFoverlapped[,tempfeatures] ### compute observed z-score if (class(tempsample)=="matrix"){ tempobs_z <- (tempobs-colMeans(tempsample))/apply(tempsample,2,function(x){sqrt(var(x))}) } else { tempobs_z <- (tempobs-mean(tempsample))/sqrt(var(tempsample)) } ### compute random z-score using already existing random samples if (class(tempsample)=="matrix"){ tempsample_z <- (tempsample-t(matrix(colMeans(tempsample),dim(tempsample)[2],dim(tempsample)[1])))/t(matrix(apply(tempsample,2,function(x){sqrt(var(x))}),dim(tempsample)[2],dim(tempsample)[1])) ###temp5 <- (sum(rowSums(tempsample_z^2) > sum(tempobs_z^2))+0.5*sum(rowSums(tempsample_z^2) == sum(tempobs_z^2)))/dim(tempsample_z)[1] temp5 <- (sum(rowSums(tempsample_z) > sum(tempobs_z))+0.5*sum(rowSums(tempsample_z) == sum(tempobs_z)))/dim(tempsample_z)[1] } else { tempsample_z <- (tempsample-mean(tempsample))/sqrt(var(tempsample)) ###temp5 <- (sum((tempsample_z^2) > (tempobs_z^2))+0.5*sum((tempsample_z^2) > (tempobs_z^2)))/length(tempsample_z) temp5 <- (sum((tempsample_z) > (tempobs_z))+0.5*sum((tempsample_z) > (tempobs_z)))/length(tempsample_z) } ### compute random z-score by sampling from multivariate normal in which the covariance learned from existing random samples if (class(tempsample)=="matrix"){ tempcov <- cov(tempsample_z) tempsample_mvrnormz <- mvrnorm(numsamples,rep(0,length(tempobs_z)),tempcov) ###temp6 <- (sum(rowSums(tempsample_mvrnormz^2) > sum(tempobs_z^2))+0.5*sum(rowSums(tempsample_mvrnormz^2) == sum(tempobs_z^2)))/dim(tempsample_mvrnormz)[1] temp6 <- (sum(rowSums(tempsample_mvrnormz) > sum(tempobs_z))+0.5*sum(rowSums(tempsample_mvrnormz) == sum(tempobs_z)))/dim(tempsample_mvrnormz)[1] } else{ tempcov <- var(tempsample) tempsample_mvrnormz <- rnorm(numsamples) ###temp6 <- (sum((tempsample_mvrnormz^2) > (tempobs_z^2))+0.5*sum((tempsample_mvrnormz^2) > (tempobs_z^2)))/length(tempsample_mvrnormz) temp6 <- (sum((tempsample_mvrnormz) > (tempobs_z))+0.5*sum((tempsample_mvrnormz) > (tempobs_z)))/length(tempsample_mvrnormz) } temp7 <- mean(tempobs) if (class(tempsample)=="matrix"){ temp.8 <- colMeans(tempsample) temp8 <- mean(colMeans(tempsample)) } else{ temp.8 <- tempsample temp8 <- mean(tempsample) } temp9 <- median(tempobs/temp.8) temp10 <- length(tempobs) result_c[c,] <- c(temp1,temp2,temp3,temp4,temp5,temp6,temp7,temp8,temp9,temp10) } write.table(result_f,file=paste(Args[5],"result.feature",sep="."),row.names=T,col.names=T,sep="\t",quote=F) write.table(result_c,file=paste(Args[5],"result.cell",sep="."),row.names=T,col.names=T,sep="\t",quote=F) <file_sep># GEGA GEGA is an approach which uses a sampling technique to perform regulatory element enrichment. It can calculate the cell-type specific score by combining the chromatin marks for that cell type. It also allows sampling a small amount and uses z-statistics to estimate the p-value. An example command to run GEGA is as follows: ./GEGA.py -m ../data/GFmetafile -g ../data/common_v3g1keurimputed_r27_Allchr_ldblock_maf_numgenes -i ../data/indep66_Allchr_ldblock_maf_numgenes -f ../data/GEGA_ENCODE_gwas_ldsnp/common_v3g1keurimputed_r27_Allchr_tag0.8 -p ../data/indep66_Allchr_tag0.8snp.bed -s 20000 -t 10 -o ../results/GEGA_20000_snp <file_sep>Skin-specific Co-expression <file_sep>#! Rscript --vanilla ### Input: 1) gwasinfo ### 2) intmarksinfo ### 3) number of samples ### Final output file: number of samples x markers matrix Args <- commandArgs(TRUE) if (length(Args)!=4){ print("Usage: i) gwasinfo; ii) intmarksinfo; iii) numsamples; iv) output") quit() } ### numsamples <- 10000;gwasinfo <- as.matrix(read.table("../data/common_v3g1keurimputed_r27_Allchr_ldblock_maf_numgenes",colClasses="character",sep="\t")); intmarksinfo <- as.matrix(read.table("../data/indep66_Allchr_ldblock_maf_numgenes",colClasses="character",sep="\t")) numsamples <- as.numeric(Args[3]) gwasinfo <- as.matrix(read.table(Args[1],colClasses="character",sep="\t")) intmarksinfo <- as.matrix(read.table(Args[2],colClasses="character",sep="\t")) results <- matrix(character(),numsamples,dim(intmarksinfo)[1]) for (j in 1:dim(intmarksinfo)[1]){ tempm1 <- intmarksinfo[j,1] templ1 <- as.numeric(intmarksinfo[j,5]) tempf1 <- as.numeric(intmarksinfo[j,6]) tempg1 <- as.numeric(intmarksinfo[j,7]) ### cannot sample itself or markers in same locus tempc <- intmarksinfo[j,2] temps <- as.numeric(intmarksinfo[j,3])-100000 tempe <- as.numeric(intmarksinfo[j,4])+100000 tempgwas <- gwasinfo[(gwasinfo[,1]!=tempm1) & !((as.numeric(gwasinfo[,2])==tempc) & (as.numeric(gwasinfo[,3])>=temps) & (as.numeric(gwasinfo[,4])<=tempe)),] ### give higher probability to sample the marker if it has maf/ld length/number genes similar to the interested marker tempr1 <- 1/rank(abs(as.numeric(tempgwas[,5])-templ1)) tempr2 <- 1/rank(abs(as.numeric(tempgwas[,6])-tempf1)) tempr3 <- 1/rank(abs(as.numeric(tempgwas[,7])-tempg1)) ### rank product temprp <- tempr1*tempr2*tempr3 ### if apply stringent matching criteria, we will not end up with higher diversity of sampled markers ###tempw <- (temprp^2)/(sum(temprp^2)) tempw <- (temprp)/(sum(temprp)) results[,j] <- sample(tempgwas[,1],numsamples,prob=tempw,replace=T) } write.table(results,file=Args[4],row.names=F,col.names=F,quote=F,sep="\t") <file_sep>#! /usr/bin/python """ Given the metafiles (ID\tfilelocation\tcell\tFeature) of the genomic features (e.g. from ENCODE), the GWAS info file (marke,chr,start,end,ld-length,maf,numgenes), the interested marker info file, the prefix of the folder containing files of GF overlapping GWAS marker, and number of samplings: perform genomic feature enrichment analysis for individual feature and cell-type based while considering correlations between features within same cell type """ from optparse import OptionParser import sys import os from multiprocessing import * from math import * sys.path.append(os.path.dirname(os.path.realpath(sys.argv[0]))) def main(): usage="usage: %prog -m metafile -g gwasinfo -i intmarksinfo -f GF_folder_fileprefix [-s numsamples -t numProcesses] -o outprefx" parser=OptionParser(usage) parser.add_option("-m", "--metafile",dest="metafile",help="metafile storing the files of the genomic features (ID\tfilelocation\tcell\tFeature)") parser.add_option("-g", "--gwasinfo",dest="gwasinfo",help="gwas info file (marke\tchr\tstart\tend\tld-length\tmaf\tnumgenes)") parser.add_option("-i", "--intmarksinfo",dest="intmarksinfo",help="interested markers info file (marke\tchr\tstart\tend\tld-length\tmaf\tnumgenes)") parser.add_option("-f", "--featurepre",dest="featurepre",help="folder and prefix of the files storing the features overlapping GWAS markers") parser.add_option("-s", "--numsamples",dest="numsamples",type="int",default=10000) parser.add_option("-t","--numProcess",dest="numProcess",type="int",default=1) parser.add_option("-o", "--outDir",dest="outDir",help="output directory and prefix") parser.add_option("-p", "--intmarks_ldsnps",dest="intmarks_ldsnps",help="Indicating using ld-markers instead of ld-regions for the interested markers: need to provide a bed file showing each ld-marker per row (4th column indicates the interested marker)") (options,args)=parser.parse_args() if options.metafile==None or options.gwasinfo==None or options.intmarksinfo==None or options.featurepre==None or options.numsamples==None or options.outDir==None: parser.error("Input arguments are not fully specified") metafile=options.metafile gwasinfo=options.gwasinfo intmarksinfo=options.intmarksinfo featurepre=options.featurepre numsamples=options.numsamples numProcess=options.numProcess outDir=options.outDir if options.intmarks_ldsnps !=None: print "Using ld-markers instead of ld-regions for genomic feature overlap.." intmarks_ldsnps=options.intmarks_ldsnps ########################################################### ### A) sample markers print "Sampling markers from the GWAS list..." tempout=outDir+".sampledmarkers" tempscript="Rscript --vanilla "+os.path.dirname(os.path.realpath(sys.argv[0]))+"/samplemarkers.R "+gwasinfo+" "+intmarksinfo+" "+str(numsamples)+" "+tempout os.system(tempscript) ########################################################### ### B) overlap with genomic features features=[] for tempstr in open(metafile): features.append(tempstr.rstrip().split()[0]) ### i) int markers print "Counting numbers of queried markers overlapping with each feature..." intmarks_feat_X=[] tempout=outDir+".tempout" if options.intmarks_ldsnps ==None: ### create temporary bed file for int markers tempbed=outDir+".intmarkerbed" tempscript="cat "+intmarksinfo+" | perl -lane 'print \"chr$F[1]\t$F[2]\t$F[3]\t$F[0]\";' > "+tempbed os.system(tempscript) for tempstr in open(metafile): tempstr=tempstr.rstrip().split() tempfile=tempstr[1] tempname=tempstr[0] tempscript="bedtools intersect -wa -u -a "+tempbed+" -b "+tempfile+" > "+tempout os.system(tempscript) count=0 for tempstr2 in open(tempout): count+=1 ### print tempname+": "+str(count) intmarks_feat_X.append(str(count)) else: ### compute overlap using only ld-marks instead of ld-block for tempstr in open(metafile): tempstr=tempstr.rstrip().split() tempfile=tempstr[1] tempname=tempstr[0] tempscript="bedtools intersect -wa -u -a "+intmarks_ldsnps+" -b "+tempfile+" | cut -f4 | uniq > "+tempout os.system(tempscript) count=0 for tempstr2 in open(tempout): count+=1 ### print tempname+": "+str(count) intmarks_feat_X.append(str(count)) os.system("rm -f "+tempout) tempout=open(outDir+".intmarkerGFoverlapped",'w') tempout.write('\t'.join(features)+"\n") tempout.write('\t'.join(intmarks_feat_X)) tempout.close() ############################################################################# ### ii) sampled markers print "Counting numbers of sampled markers overlapping with each feature..." tempout=open(outDir+".randommarkerGFoverlapped",'w') tempout.write('\t'.join(features)) ### dict storing the overlapped GWAS markers per feature gfmarks={} for f in features: gfmarks[f]=[] for tempstr2 in open(featurepre+"."+f): gfmarks[f].append(tempstr2.rstrip()) ### random genes randmarkslist=[] for tempstr in open(outDir+".sampledmarkers"): randmarkslist.append(tempstr.rstrip().split()) ### Multi processing if numProcess>1: print "Start multi-processing...." randgenes_gf_count=[] processes=[] queues=Queue() avgnumrandmarks=int(ceil(numsamples/float(numProcess))) culnumrandmarks=0 for i in range(numProcess): if i==(numProcess-1): temprandmarks=randmarkslist[culnumrandmarks:] else: temprandmarks=randmarkslist[culnumrandmarks:(culnumrandmarks+avgnumrandmarks)] culnumrandmarks+=avgnumrandmarks processes.append(Process(target=process_randmarks_gf_overlap,args=(temprandmarks,gfmarks,features,queues))) ### start new processes for t in processes: t.start() ### gather the counts for t in range(numProcess): randgenes_gf_count+=queues.get() for r in randgenes_gf_count: tempout.write("\n"+'\t'.join(r)) tempout.close() ################################################################################### ### C) computed p-values tempscript="Rscript --vanilla "+os.path.dirname(os.path.realpath(sys.argv[0]))+"/computep.R "+metafile+" "+outDir+".intmarkerGFoverlapped "+outDir+".randommarkerGFoverlapped "+str(numsamples)+" "+outDir os.system(tempscript) ################################################################### def process_randmarks_gf_overlap(temprandmarks,gfmarks,features,queues): tempresult=[] count=0 for r in temprandmarks: count+=1 temptempresult=[] print "Processed "+str(count)+" samples in one of the processes..." for f in features: temptempresult.append(str(len(list(set(r) & set(gfmarks[f]))))) tempresult.append(temptempresult) queues.put(tempresult) ################################################################### if __name__ == "__main__": main() <file_sep>#! /usr/bin/python """ Given the metafiles (ID\tfilelocation\tcell\tFeature) of the genomic features (e.g. from ENCODE) and the bed file contains the LD blocks of interested markers, create, for each feature, a file annotating which markers overlap with the feature """ from optparse import OptionParser import sys import os sys.path.append(os.path.dirname(os.path.realpath(sys.argv[0]))) def main(): usage="usage: %prog -m metafile -g gwas.bed -o outprefix" parser=OptionParser(usage) parser.add_option("-m", "--metafile",dest="metafile",help="metafile storing the files of the genomic features (ID\tfilelocation\tcell\tFeature)") parser.add_option("-g", "--gwas.bed",dest="gwasbed",help="bed file contains the LD blocks of markers") parser.add_option("-o", "--outDir",dest="outDir",help="output directory and prefix") (options,args)=parser.parse_args() if options.metafile==None or options.gwasbed==None or options.outDir==None: parser.error("Input arguments are not fully specified") metafile=options.metafile gwasbed=options.gwasbed outDir=options.outDir ############################################################ tempout=outDir+".temp.bed" for tempstr in open(metafile): tempstr=tempstr.rstrip().split() tempfile=tempstr[1] tempname=tempstr[0] print tempfile tempscript="bedtools intersect -wa -u -a "+gwasbed+" -b "+tempfile+" > "+ tempout os.system(tempscript) ### only need the identifiers tempscript="cut -f4 "+tempout+" | sort | uniq > "+outDir+"."+tempname os.system(tempscript) os.system("rm -f "+tempout) ################################################################### if __name__ == "__main__": main()
817aafb3fe275f4bdd62a4ce8c1818fae9dba11a
[ "Markdown", "Python", "R" ]
6
R
CutaneousBioinf/GenomicAnalysis
0297270edddc6514df8a25a42f0a3e33b78881fa
39304f3ff22b101dcb642af8ec75919b1dd79a41
refs/heads/master
<file_sep>package com.example.newsapp.ui.fragment import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.example.newsapp.R import com.example.newsapp.adapter.SelectionFragmentPagerAdapter import com.example.newsapp.databinding.FragmentTabHolderBinding import com.example.newsapp.ui.transmission.ZoomOutPageTransformer import com.google.android.material.tabs.TabLayoutMediator class TabFragmentHolder : Fragment() { private lateinit var holderBinding: FragmentTabHolderBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { holderBinding = FragmentTabHolderBinding.inflate(layoutInflater) val fragmentList: ArrayList<Fragment> = ArrayList() fragmentList.add(BreakingNewsFragment()) fragmentList.add(SelectCountryFragment()) val adapter = SelectionFragmentPagerAdapter(childFragmentManager, lifecycle, fragmentList) holderBinding.optionNewsViewPager2.setPageTransformer(ZoomOutPageTransformer()) holderBinding.optionNewsViewPager2.adapter = adapter TabLayoutMediator(holderBinding.optionNewsTabLayout, holderBinding.optionNewsViewPager2) { tab, position -> when (position) { 0 -> { tab.setIcon(R.drawable.ic_all_news) } 1 -> { tab.setIcon(R.drawable.ic_favorite) } } }.attach() return holderBinding.root } }<file_sep>package com.example.newsapp.ui.fragment import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.webkit.WebViewClient import androidx.navigation.NavArgs import androidx.navigation.fragment.navArgs import com.example.newsapp.NewsActivity import com.example.newsapp.R import com.example.newsapp.databinding.FragmentArticleBinding import com.example.newsapp.databinding.FragmentBreakingNewsBinding import com.example.newsapp.ui.NewsViewModel import com.google.android.material.snackbar.Snackbar class ArticleFragment : Fragment() { lateinit var viewModel: NewsViewModel private lateinit var articleBinding : FragmentArticleBinding private val args by navArgs<ArticleFragmentArgs>() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel = (activity as NewsActivity).viewModel val article = args.articleData articleBinding.articleWebView.apply { webViewClient = WebViewClient() if(article.url != null){ loadUrl(article.url!!) } } articleBinding.saveArticleFloatingActionButton.setOnClickListener { viewModel.saveArticle(article) Snackbar.make(view, "Article saved successfully.....", Snackbar.LENGTH_SHORT).show() } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { articleBinding = FragmentArticleBinding.inflate(layoutInflater) return articleBinding.root } }<file_sep>package com.example.newsapp.adapter import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.constraintlayout.widget.ConstraintLayout import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.newsapp.R import com.example.newsapp.model.Country class SelectCountryAdapter( private val countryList: ArrayList<Country>, private val countryCode: String?, private val listener: SelectCountryListener ) : RecyclerView.Adapter<SelectCountryAdapter.SelectCountryHolder>() { private val TAG: String = "SelectCountyAdapter:---" class SelectCountryHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val correctImage: ImageView = itemView.findViewById(R.id.ivCountrySelect) val countryImage: ImageView = itemView.findViewById(R.id.ivCountryImage) val countryName: TextView = itemView.findViewById(R.id.tvCountryName) val countryLayout: ConstraintLayout = itemView.findViewById(R.id.selectCountryLayout) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SelectCountryHolder { return SelectCountryHolder( LayoutInflater.from(parent.context).inflate(R.layout.country_layout, parent, false) ) } override fun onBindViewHolder(holder: SelectCountryHolder, position: Int) { val country = countryList[position] Log.d(TAG,"Country Code is $countryCode") if(countryCode != null){ if (countryCode == country.countryCode) { Log.d(TAG,"Country Save is $countryCode and FormClass ${country.countryCode}") holder.correctImage.visibility = View.VISIBLE }else{ holder.correctImage.visibility = View.INVISIBLE } } Glide.with(holder.countryImage.context).load(country.countryImage).into(holder.countryImage) holder.countryName.text = country.countryName holder.countryLayout.setOnClickListener { listener.selectCountryListener(country) } } override fun getItemCount(): Int { return countryList.size } } interface SelectCountryListener { fun selectCountryListener(country: Country) }<file_sep># NewsApp Project Overview the goal is to create a News App Which gives a user regularly-Beaking news from the internet related to a particular country and category. News app can save the news so that you can watch it later and also you can search news. in this project, use [News API](https://newsapi.org/). This is a well-maintained API which returns information in a JSON Format ### API key Note You need to insert your API key. Go to the file name `Constants.kt` and find the value of API_KEY Replace "YOUR API KEY " with your API KEY (e.g <KEY>) ``` const val API_KEY = "Your Api Key" ```` ### Features * Retrofit * Room Database * Navigation Drawer * View Binding * JSON Parsing * Fragment * Glide * Recycler View * SharedPreference ### App Structure ### Home <img src="GIF/home.gif" width="300"> This screen shows the country's breaking news and also give option to choose your favorite news ### Select Country <img src="GIF/select%20country.gif" width="300"> This screen are use to select country than it will show news according to your country ### Save News <img src="GIF/save%20news.gif" width="300"> This screen are used to save news ### Show Save News <img src="GIF/show%20news.gif" width="300"> This screen are show save news and you can also search your save news ### Search News <img src="GIF/search%20news.gif" width="300"> This screen are use to search new <file_sep>package com.example.newsapp.ui.fragment import android.content.Context import android.os.Bundle import android.util.Log import android.view.LayoutInflater import androidx.fragment.app.Fragment import android.view.View import android.view.ViewGroup import android.widget.AbsListView import android.widget.Toast import androidx.lifecycle.Observer import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.newsapp.NewsActivity import com.example.newsapp.R import com.example.newsapp.adapter.NewsAdapter import com.example.newsapp.adapter.OnClickArticle import com.example.newsapp.databinding.FragmentBreakingNewsBinding import com.example.newsapp.model.Article import com.example.newsapp.ui.NewsViewModel import com.example.newsapp.util.Constants.Companion.QUERY_PAGE_SIZE import com.example.newsapp.util.Resource import com.google.android.material.snackbar.Snackbar class BreakingNewsFragment : Fragment(), OnClickArticle { private val TAG: String = "BreakingNewsFragment: " private lateinit var breakingNewsBinding: FragmentBreakingNewsBinding lateinit var viewModel: NewsViewModel lateinit var newsAdapter: NewsAdapter var isLoading = false var isLastPage = false var isScrolling = false var category: String = "general" var myCountryCode: String = "in" override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val sharedCountry = requireActivity().getSharedPreferences("country", Context.MODE_PRIVATE) val countryCode: String? = sharedCountry.getString("countryCode", "in") Log.d(TAG,"Country Code Save is :$countryCode") viewModel = (activity as NewsActivity).viewModel if(countryCode != null){ myCountryCode = countryCode viewModel.getBreakingNewsAccordingToCategory(countryCode, "general") }else{ myCountryCode = "in" viewModel.getBreakingNewsAccordingToCategory(myCountryCode, "general") } setupRecyclerAdapter() viewModel.breakingNews.observe(viewLifecycleOwner, Observer { response -> when (response) { is Resource.Success -> { hideProgressBar() response.data?.let { newsResponse -> newsAdapter.differ.submitList(newsResponse.articles.toList()) val totalPage = newsResponse.totalResults / QUERY_PAGE_SIZE + 2 isLastPage = viewModel.breakingNewsPage == totalPage } } is Resource.Error -> { hideProgressBar() response.message?.let { message -> Snackbar.make(view, "$message", Snackbar.LENGTH_LONG).show() } } is Resource.Loading ->{ showProgressBar() } } }) breakingNewsBinding.selectCountryButton.setOnClickListener { findNavController().navigate(R.id.action_breakingNewsFragment_to_selectCountryFragment) } breakingNewsBinding.businessChip.setOnClickListener { category = "business" viewModel.getBreakingNewsAccordingToCategory(myCountryCode, category) } breakingNewsBinding.entertainmentChip.setOnClickListener { category = "entertainment" viewModel.getBreakingNewsAccordingToCategory(myCountryCode, category) } breakingNewsBinding.generalChip.setOnClickListener { category = "general" viewModel.getBreakingNewsAccordingToCategory(myCountryCode, category) } breakingNewsBinding.healthChip.setOnClickListener { category = "health" viewModel.getBreakingNewsAccordingToCategory(myCountryCode, category) } breakingNewsBinding.scienceChip.setOnClickListener { category = "science" viewModel.getBreakingNewsAccordingToCategory(myCountryCode, category) } breakingNewsBinding.sportChip.setOnClickListener { category = "sport" viewModel.getBreakingNewsAccordingToCategory(myCountryCode, category) } breakingNewsBinding.technologyChip.setOnClickListener { category = "technology" viewModel.getBreakingNewsAccordingToCategory(myCountryCode, category) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { breakingNewsBinding = FragmentBreakingNewsBinding.inflate(layoutInflater) return breakingNewsBinding.root } private fun hideProgressBar() { Log.d(TAG,"Progress Bar Invisible") breakingNewsBinding.paginationProgressBar.visibility = View.INVISIBLE breakingNewsBinding.paginationProgressBar.alpha = 0F isLoading = false } private fun showProgressBar() { Log.d(TAG,"Progress Bar Visible") breakingNewsBinding.paginationProgressBar.visibility = View.VISIBLE breakingNewsBinding.paginationProgressBar.alpha = 1F isLoading = true } private val scrollListener = object : RecyclerView.OnScrollListener(){ override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { super.onScrollStateChanged(recyclerView, newState) if(newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL){ isScrolling = true } } override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) val layoutManager = recyclerView.layoutManager as LinearLayoutManager val firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition() val visibleItemCount = layoutManager.childCount val totalItemCount = layoutManager.itemCount val isNotLoadingAndNotLastPage = !isLoading && !isLastPage val isAtLastItem = firstVisibleItemPosition + visibleItemCount >= totalItemCount val isTotalMoreThanVisible = totalItemCount >= QUERY_PAGE_SIZE val shouldPaginate = isNotLoadingAndNotLastPage && isAtLastItem && isNotLoadingAndNotLastPage && isTotalMoreThanVisible && isScrolling if(shouldPaginate){ viewModel.getBreakingNewsAccordingToCategory(myCountryCode, category) isScrolling = false }/* else{ breakingNewsBinding.rvBreakingNews.setPadding(0,0,0,0) }*/ } } private fun setupRecyclerAdapter() { newsAdapter = NewsAdapter(this) breakingNewsBinding.rvBreakingNews.adapter = newsAdapter breakingNewsBinding.rvBreakingNews.layoutManager = LinearLayoutManager(requireActivity()) breakingNewsBinding.rvBreakingNews.addOnScrollListener([email protected]) } override fun onClickArticle(article: Article) { val bundle = Bundle().apply { putSerializable("articleData", article) } findNavController().navigate( R.id.action_breakingNewsFragment_to_articleFragment, bundle ) } }<file_sep>package com.example.newsapp.ui.fragment import android.content.Context import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import com.example.newsapp.NewsActivity import com.example.newsapp.R import com.example.newsapp.adapter.SelectCountryAdapter import com.example.newsapp.adapter.SelectCountryListener import com.example.newsapp.databinding.FragmentSelectCountryBinding import com.example.newsapp.model.Country import com.example.newsapp.ui.NewsViewModel class SelectCountryFragment : Fragment(), SelectCountryListener { private val TAG: String = "SelectCountryFragment:----" private lateinit var countryBinding: FragmentSelectCountryBinding private lateinit var selectCountryAdapter: SelectCountryAdapter private lateinit var viewModel: NewsViewModel override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val countryList: ArrayList<Country> = getCountryList() Log.d(TAG,"Countries : $countryList") viewModel = (activity as NewsActivity).viewModel val sharedCountry = requireActivity().getSharedPreferences("country", Context.MODE_PRIVATE) val countryCode: String? = sharedCountry.getString("countryCode", "in") Log.d(TAG,"Get CountryCode from Shared Preference: $countryCode") selectCountryAdapter = SelectCountryAdapter(countryList, countryCode,this) countryBinding.rvSelectCountry.adapter = selectCountryAdapter countryBinding.rvSelectCountry.layoutManager = LinearLayoutManager(requireContext()) } private fun getCountryList(): ArrayList<Country> { val list = ArrayList<Country>() val ae = Country("United Arab Emirates", R.drawable.ae,"ae") list.add(ae) val ar = Country("Argentina", R.drawable.ar,"ar") list.add(ar) val au = Country("Australia", R.drawable.au,"au") list.add(au) val be = Country("Belgium", R.drawable.be,"be") list.add(be) val br = Country("Brazil", R.drawable.br,"br") list.add(br) val ca = Country("Canada", R.drawable.ca,"ca") list.add(ca) val cn = Country("China", R.drawable.cn,"cn") list.add(cn) val de = Country("Germany", R.drawable.de,"de") list.add(de) val eg = Country("Egypt", R.drawable.eg,"eg") list.add(eg) val fr = Country("France", R.drawable.fr,"fr") list.add(fr) val gb = Country("United Kingdom", R.drawable.gb,"gb") list.add(gb) val hk = Country("Hong Kong", R.drawable.hk,"hk") list.add(hk) val il = Country("Israel", R.drawable.il,"il") list.add(il) val india = Country("India", R.drawable.india,"in") list.add(india) val it = Country("Italy", R.drawable.it,"it") list.add(it) val jp = Country("Japan", R.drawable. jp,"jp") list.add(jp) val kr = Country("South Korea", R.drawable. kr,"kr") list.add(kr) val ru = Country("Russia", R.drawable. ru,"ru") list.add(ru) val sa = Country("Saudi Arabia", R.drawable. sa,"sa") list.add(sa) val us = Country("United State", R.drawable. us,"us") list.add(us) return list } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { countryBinding = FragmentSelectCountryBinding.inflate(layoutInflater) return countryBinding.root } override fun selectCountryListener(country: Country) { val sharedCountry = requireActivity().getSharedPreferences("country", Context.MODE_PRIVATE) val editor = sharedCountry.edit() editor.putString("countryCode", country.countryCode) editor.commit() Log.d(TAG, "Save In Presence By selected User is ${country.countryCode}") viewModel.breakingNewsPage = 1 findNavController().navigate(R.id.action_selectCountryFragment_to_breakingNewsFragment) } }<file_sep>package com.example.newsapp.db import androidx.lifecycle.LiveData import androidx.room.* import com.example.newsapp.model.Article import com.example.newsapp.model.Source @Dao interface ArticleDoa { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun upsert(article: Article): Long @Query("select * from articles") fun getAllArticles(): List<Article> @Delete suspend fun deleteArticle(article: Article) @Query("Select * From articles Where author LIKE :searchQuery OR content LIKE :searchQuery OR description LIKE :searchQuery OR publishedAt LIKE :searchQuery OR title LIKE :searchQuery") fun searchSaveNews(searchQuery: String): List<Article> }<file_sep> package com.example.newsapp.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.constraintlayout.widget.ConstraintLayout import androidx.recyclerview.widget.AsyncListDiffer import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.newsapp.R import com.example.newsapp.model.Article class NewsAdapter(private val listener: OnClickArticle): RecyclerView.Adapter<NewsAdapter.NewsAdapterHolder>() { class NewsAdapterHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val ivArticleImage: ImageView = itemView.findViewById(R.id.ivArticleImage) val tvTitle: TextView = itemView.findViewById(R.id.tvTitle) val tvDescription: TextView = itemView.findViewById(R.id.tvDescription) val tvSource: TextView = itemView.findViewById(R.id.tvSource) val tvPublishedAt: TextView = itemView.findViewById(R.id.tvPublishedAt) val articleLayout: ConstraintLayout = itemView.findViewById(R.id.articleLayout) } private val differCallback = object : DiffUtil.ItemCallback<Article>(){ override fun areItemsTheSame(oldItem: Article, newItem: Article): Boolean { return oldItem.url == newItem.url } override fun areContentsTheSame(oldItem: Article, newItem: Article): Boolean { return oldItem == newItem } } val differ = AsyncListDiffer(this, differCallback) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NewsAdapterHolder { return NewsAdapterHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_article_preview, parent, false)) } override fun onBindViewHolder(holder: NewsAdapterHolder, position: Int) { val article = differ.currentList[position] Glide.with(holder.ivArticleImage.context).load(article.urlToImage).into(holder.ivArticleImage) holder.tvSource.text = article.source?.name holder.tvTitle.text = article.title holder.tvDescription.text = article.description holder.tvPublishedAt.text = article.publishedAt holder.articleLayout.setOnClickListener { listener.onClickArticle(article) } } override fun getItemCount(): Int { return differ.currentList.size } } interface OnClickArticle{ fun onClickArticle(article: Article) }<file_sep>package com.example.newsapp.model data class Country( val countryName: String, val countryImage: Int, val countryCode: String )<file_sep>package com.example.newsapp import android.graphics.Color import android.graphics.drawable.ColorDrawable import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.setupWithNavController import com.example.newsapp.databinding.ActivityNewsBinding import com.example.newsapp.db.ArticleDatabase import com.example.newsapp.repository.NewsRepository import com.example.newsapp.ui.NewsViewModel import com.example.newsapp.ui.NewsViewModelProviderFactory class NewsActivity : AppCompatActivity() { private lateinit var binding: ActivityNewsBinding lateinit var viewModel: NewsViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityNewsBinding.inflate(layoutInflater) setContentView(binding.root) val navHostFragment = supportFragmentManager .findFragmentById(R.id.fragmentContainerView) as NavHostFragment val navController = navHostFragment.navController binding.bottomNavigationView.setupWithNavController(navController) val newsRepository = NewsRepository(ArticleDatabase(this)) val viewModelProviderFactory = NewsViewModelProviderFactory(application, newsRepository) viewModel = ViewModelProvider(this, viewModelProviderFactory).get(NewsViewModel::class.java) } }<file_sep>package com.example.newsapp.adapter import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.lifecycle.Lifecycle import androidx.viewpager2.adapter.FragmentStateAdapter import com.example.newsapp.R class SelectionFragmentPagerAdapter( fragmentManager: FragmentManager, lifecycle: Lifecycle, private val fragmentList: ArrayList<Fragment> ) : FragmentStateAdapter(fragmentManager, lifecycle) { override fun getItemCount(): Int { return 2 } override fun createFragment(position: Int): Fragment { var fragment: Fragment = fragmentList[0] when (position) { 0 -> { fragment = fragmentList[0] } 1 -> { fragment = fragmentList[1] } } return fragment } }<file_sep>package com.example.newsapp.ui.fragment import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AbsListView import android.widget.Toast import androidx.core.widget.addTextChangedListener import androidx.lifecycle.Observer import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.newsapp.NewsActivity import com.example.newsapp.R import com.example.newsapp.adapter.NewsAdapter import com.example.newsapp.adapter.OnClickArticle import com.example.newsapp.databinding.FragmentSearchNewsBinding import com.example.newsapp.model.Article import com.example.newsapp.ui.NewsViewModel import com.example.newsapp.util.Constants import com.example.newsapp.util.Constants.Companion.SEARCH_NEWS_TIME_DELAY import com.example.newsapp.util.Resource import com.google.android.material.snackbar.Snackbar import kotlinx.coroutines.Job import kotlinx.coroutines.MainScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch class SearchNewsFragment : Fragment(), OnClickArticle { private val TAG: String = "SearchNewsFragment: " lateinit var viewModel: NewsViewModel private lateinit var searchNewsBinding: FragmentSearchNewsBinding lateinit var searchNewsAdapter: NewsAdapter var isLoading = false var isLastPage = false var isScrolling = false override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel = (activity as NewsActivity).viewModel setupRecyclerAdapter() var job: Job? = null searchNewsBinding.tvSearchNews.addTextChangedListener { editable -> job?.cancel() job = MainScope().launch { delay(SEARCH_NEWS_TIME_DELAY) editable?.let { if (editable.toString().isNotEmpty()) { viewModel.searchForNews(editable.toString(), false) } } } } viewModel.searchNews.observe(viewLifecycleOwner, Observer { response -> when (response) { is Resource.Success -> { hideProgressBar() response.data?.let { newsResponse -> searchNewsAdapter.differ.submitList(newsResponse.articles.toList()) } } is Resource.Error -> { hideProgressBar() response.message?.let { message -> Snackbar.make(view, "$message", Snackbar.LENGTH_LONG).show() } } is Resource.Loading -> { showProgressBar() } } }) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { searchNewsBinding = FragmentSearchNewsBinding.inflate(layoutInflater) return searchNewsBinding.root } private fun hideProgressBar() { searchNewsBinding.searchPaginationProgressBar.visibility = View.INVISIBLE } private fun showProgressBar() { searchNewsBinding.searchPaginationProgressBar.visibility = View.VISIBLE } val scrollListener = object : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { super.onScrollStateChanged(recyclerView, newState) if (!recyclerView.canScrollVertically(1) && newState == RecyclerView.SCROLL_STATE_IDLE) { val query: String = searchNewsBinding.tvSearchNews.text.toString() if(!query.isNullOrEmpty()){ viewModel.searchForNews(searchNewsBinding.tvSearchNews.text.toString(), true) } } } } private fun setupRecyclerAdapter() { searchNewsAdapter = NewsAdapter(this) searchNewsBinding.rvSearchNews.adapter = searchNewsAdapter searchNewsBinding.rvSearchNews.layoutManager = LinearLayoutManager(requireActivity()) searchNewsBinding.rvSearchNews.addOnScrollListener([email protected]) } override fun onClickArticle(article: Article) { val bundle = Bundle().apply { putSerializable("articleData", article) } findNavController().navigate( R.id.action_searchNewsFragment_to_articleFragment, bundle ) } }<file_sep>package com.example.newsapp.repository import androidx.lifecycle.LiveData import com.example.newsapp.api.RetrofitInstance import com.example.newsapp.db.ArticleDatabase import com.example.newsapp.model.Article import com.example.newsapp.model.NewsResponse import retrofit2.Response class NewsRepository(val db: ArticleDatabase) { suspend fun getBreakingNews(countryCode: String, pageNumber: Int) = RetrofitInstance.api.getBreakingNews(countryCode, pageNumber) suspend fun searchNews(searchQuery: String, pageNumber: Int) = RetrofitInstance.api.searchForNews(searchQuery, pageNumber) suspend fun getBreakingNewsAccordingToCategory(countryCode: String, category: String, pageNumber: Int): Response<NewsResponse>{ return RetrofitInstance.api.getBreakingNewsAccordingToCategory(countryCode, category, pageNumber) } suspend fun upsert(article: Article) = db.getArticleDoa().upsert(article) suspend fun deleteArticle(article: Article) = db.getArticleDoa().deleteArticle(article) fun getSavedNews(): List<Article> { return db.getArticleDoa().getAllArticles() } fun searchSaveNews(searchQuery: String): List<Article>{ return db.getArticleDoa().searchSaveNews(searchQuery) } }<file_sep>package com.example.newsapp.ui.fragment import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.core.widget.addTextChangedListener import androidx.lifecycle.Observer import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.newsapp.NewsActivity import com.example.newsapp.R import com.example.newsapp.adapter.NewsAdapter import com.example.newsapp.adapter.OnClickArticle import com.example.newsapp.databinding.FragmentSaveNewsBinding import com.example.newsapp.model.Article import com.example.newsapp.ui.NewsViewModel import com.example.newsapp.util.Constants import com.google.android.material.snackbar.Snackbar import kotlinx.coroutines.Job import kotlinx.coroutines.MainScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch class SaveNewsFragment : Fragment(), OnClickArticle { private val TAG: String = "SaveNewsFragment:---" private lateinit var saveNewsAdapter: NewsAdapter lateinit var viewModel: NewsViewModel private lateinit var saveNewsBinding: FragmentSaveNewsBinding override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel = (activity as NewsActivity).viewModel setupRecyclerAdapter() val itemTouchHelperCallBack = object : ItemTouchHelper.SimpleCallback( ItemTouchHelper.UP or ItemTouchHelper.DOWN, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT ) { override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { return true } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { val position = viewHolder.adapterPosition val article = saveNewsAdapter.differ.currentList[position] viewModel.deleteArticle(article) Snackbar.make(view, "successfully deleted article", Snackbar.LENGTH_LONG).apply { setAction("UNDO") { viewModel.saveArticle(article) } show() } } } ItemTouchHelper(itemTouchHelperCallBack).apply { attachToRecyclerView(saveNewsBinding.rvSavedArticle) } viewModel.getSavedNews() // viewModel.searchGetAllNews.observe(viewLifecycleOwner, Observer { articles -> // Log.d(TAG, "Articles: - $articles") // if(articles.isNotEmpty()){ // saveNewsAdapter.differ.submitList(articles) // } // }) var job: Job? = null saveNewsBinding.tvSearchNewNews.addTextChangedListener { editable -> job?.cancel() job = MainScope().launch { delay(Constants.SEARCH_NEWS_TIME_DELAY) editable?.let { Log.d(TAG,"$editable") if (editable.toString().isNotEmpty()) { val query = "%${editable.toString()}%" Log.d(TAG,"Sent Query : $query") viewModel.searchSaveNews(query) } else { viewModel.getSavedNews() } } } } viewModel.searchSaveNews.observe(viewLifecycleOwner, Observer { articles -> Log.d(TAG, "Articles: - $articles") if(articles.isNotEmpty()){ saveNewsAdapter.differ.submitList(articles) }else{ Toast.makeText(requireContext(), "List is empty", Toast.LENGTH_SHORT).show() } }) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { saveNewsBinding = FragmentSaveNewsBinding.inflate(layoutInflater) return saveNewsBinding.root } private fun setupRecyclerAdapter() { saveNewsAdapter = NewsAdapter(this) saveNewsBinding.rvSavedArticle.adapter = saveNewsAdapter saveNewsBinding.rvSavedArticle.layoutManager = LinearLayoutManager(requireActivity()) } override fun onClickArticle(article: Article) { val bundle = Bundle().apply { putSerializable("articleData", article) } findNavController().navigate( R.id.action_saveNewsFragment_to_articleFragment, bundle ) } }
c185c45401b4e0fbbb1b76df1b3b5ce79ab8bd9c
[ "Markdown", "Kotlin" ]
14
Kotlin
Atharva-jain/NewsApp-Kotin-
11eef884be1dbe2640b0862d26a6d6b9d1bdd33a
afb5f93b0b79e48012ce95d475ba8a280420f4cb
refs/heads/master
<file_sep># Autism-2.0"# AutismRealms" <file_sep>package com.rednetty.redpractice.mechanic.items; import com.rednetty.redpractice.mechanic.items.itemgenerator.ItemRarity; import org.bukkit.Material; public enum ItemType { STAFF(Material.GOLD_HOE), POLEARM(Material.GOLD_SPADE), SWORD(Material.GOLD_SWORD), AXE(Material.GOLD_AXE), BOW(Material.BOW), HELMET(Material.GOLD_HELMET), CHEST(Material.GOLD_CHESTPLATE), LEGS(Material.GOLD_LEGGINGS), BOOTS(Material.GOLD_BOOTS); private Material material; ItemType(Material material) { this.material = material; } public Material getMaterial() { return material; } public static ItemType fromInt(int count) { for(ItemType itemType : ItemType.values()) { if(itemType.ordinal() == count) { return itemType; } } return ItemType.SWORD; } } <file_sep>package com.rednetty.redpractice.mechanic.world.entity.spawners; import org.bukkit.Location; import org.bukkit.entity.EntityType; import java.util.UUID; public class Spawner { private UUID spawnerUUID; private EntityType entityType; private Location location; private int amount; private int radius; private int timer; public Spawner(UUID spawnerUUID, EntityType entityType, Location location, int amount, int radius, int timer) { this.spawnerUUID = spawnerUUID; this.entityType = entityType; this.location = location; this.amount = amount; this.radius = radius; this.timer = timer; } public Location getLocation() { return location; } public void setLocation(Location location) { this.location = location; } public UUID getSpawnerUUID() { return spawnerUUID; } public void setSpawnerUUID(UUID spawnerUUID) { this.spawnerUUID = spawnerUUID; } public EntityType getEntityType() { return entityType; } public void setEntityType(EntityType entityType) { this.entityType = entityType; } public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } public int getRadius() { return radius; } public void setRadius(int radius) { this.radius = radius; } public int getTimer() { return timer; } public void setTimer(int timer) { this.timer = timer; } }<file_sep>package com.rednetty.redpractice; import com.rednetty.redpractice.commands.CommandManager; import com.rednetty.redpractice.mechanic.MechanicManager; import org.bukkit.plugin.java.JavaPlugin; public class RedPractice extends JavaPlugin { /** * @author Jackson(Red29) * This project was started on 11/14/17 * The project is currently being worked on by: Jackson(Red29) */ /** * Instance of Main Class */ private static RedPractice instance; /** * used to receive instance of the mechanicManager class. */ private static MechanicManager mechanicManager; private static CommandManager commandManager; public static RedPractice getInstance() { return instance; } public static MechanicManager getMechanicManager() { return mechanicManager; } public static CommandManager getCommandManager() { return commandManager; } @Override public void onEnable() { instance = this; /*Sets instanceof RedPractice as this class*/ mechanicManager = new MechanicManager(); commandManager = new CommandManager(); mechanicManager.init(); commandManager.registerCommands(); this.getConfig().options().copyDefaults(true); this.saveConfig(); } @Override public void onDisable() { mechanicManager.stop(); } } <file_sep>package com.rednetty.redpractice.mechanic.player.toggles; import com.rednetty.redpractice.RedPractice; import com.rednetty.redpractice.mechanic.player.GamePlayer; import com.rednetty.redpractice.utils.menu.Button; import com.rednetty.redpractice.utils.menu.Menu; import org.bukkit.Sound; public class ToggleMenu extends Menu { public ToggleMenu(GamePlayer gamePlayer) { super("&eToggle Menu", 9); ToggleHandler toggleHandler = RedPractice.getMechanicManager().getToggleHandler(); for (ToggleType toggleType : ToggleType.values()) { newButton(new Button(this, this.emptySlot(), toggleHandler.getToggleItem(toggleType, gamePlayer), true) { @Override protected void onClick(int slot, GamePlayer gamePlayer) { gamePlayer.getPlayer().playSound(gamePlayer.getPlayer().getLocation(), Sound.BLOCK_STONE_BUTTON_CLICK_ON, 1F, 1F); toggleHandler.doToggle(toggleType, gamePlayer); plainSet(slot, toggleHandler.getToggleItem(toggleType, gamePlayer)); } }); } } @Override public void onClose(GamePlayer player) { } @Override public void onOpen(GamePlayer player) { } } <file_sep>package com.rednetty.redpractice.mechanic.player.toggles; import com.rednetty.redpractice.RedPractice; import com.rednetty.redpractice.mechanic.Mechanics; import com.rednetty.redpractice.mechanic.player.GamePlayer; import com.rednetty.redpractice.mechanic.player.PlayerHandler; import com.rednetty.redpractice.utils.items.ItemBuilder; import com.rednetty.redpractice.utils.items.ItemBuilder; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ToggleHandler extends Mechanics { @Override public void onEnable() { } @Override public void onDisable() { } public void doToggle(ToggleType toggleType, GamePlayer gamePlayer) { ToggleHandler toggleHandler = RedPractice.getMechanicManager().getToggleHandler(); PlayerHandler playerHandler = RedPractice.getMechanicManager().getPlayerHandler(); List<ToggleType> togglesList = new ArrayList<>(); togglesList.addAll(gamePlayer.getToggleList()); if (toggleHandler.isEnabled(toggleType, gamePlayer)) { togglesList.remove(toggleType); } else { togglesList.add(toggleType); } gamePlayer.setToggleList(togglesList); playerHandler.updateGamePlayer(gamePlayer); } public ItemStack getToggleItem(ToggleType toggleType, GamePlayer gamePlayer) { if (isEnabled(toggleType, gamePlayer)) { return new ItemBuilder(Material.INK_SACK).setDurability((short) 10).setName("&e" + toggleType.getDisplayName() + " &7 - &a&lENABLED").setLore(Arrays.asList("&7Click to &c&lDISABLE")).build(); } else { return new ItemBuilder(Material.INK_SACK).setDurability((short) 1).setName("&e" + toggleType.getDisplayName() + " &7 - &c&lDISABLED").setLore(Arrays.asList("&7Click to &alENABLE")).build(); } } public boolean isEnabled(ToggleType toggleType, GamePlayer gamePlayer) { if (gamePlayer.getToggleList().contains(toggleType)) { return true; } else { return false; } } } <file_sep>package com.rednetty.redpractice; import lombok.Getter; import org.bukkit.ChatColor; public class Constants { @Getter private static String SERVER_NAME = ChatColor.translateAlternateColorCodes('&', RedPractice.getInstance().getConfig().getString("Server Name")); } <file_sep>package com.rednetty.redpractice.events; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; public class RankChangeEvent extends Event { private static final HandlerList handlers = new HandlerList(); private CommandSender setter; private Player target; private String rank; public RankChangeEvent(CommandSender setter, Player target, String rank) { this.target = target; this.setter = setter; this.rank = rank; } public static HandlerList getHandlerList() { return handlers; } public HandlerList getHandlers() { return handlers; } /** * Used to get the RankEnum that was just set * * @return - Returns the Rank that was set by the setter */ public String getRank() { return rank; } /** * Allows you to set the rank before it is handled * * @param rank- Requires a Enum from the EnumClass RankEnum */ public void setRank(String rank) { this.rank = rank; } /** * Returns the person setting the Rank of the Target * * @return - Returns instance of Player that attempted to Set the Rank */ public CommandSender getSetter() { return setter; } /** * The Target would the the Person being Targeted and rank being set * * @return - Returns the player that was targeted when the event was called. */ public Player getTarget() { return target; } }<file_sep>package com.rednetty.redpractice.mechanic.player.bossbar; import com.rednetty.redpractice.RedPractice; import com.rednetty.redpractice.mechanic.Mechanics; import com.rednetty.redpractice.mechanic.player.GamePlayer; import com.rednetty.redpractice.utils.strings.StringUtil; import org.bukkit.Bukkit; import org.bukkit.boss.BarColor; import org.bukkit.boss.BarStyle; import org.bukkit.boss.BossBar; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; public class BarHandler extends Mechanics { @Override public void onEnable() { new BukkitRunnable() { @Override public void run() { for (Player player : Bukkit.getOnlinePlayers()) { updateBar(RedPractice.getMechanicManager().getPlayerHandler().getGamePlayer(player)); } } }.runTaskTimerAsynchronously(RedPractice.getInstance(), 1L, 1L); } @Override public void onDisable() { } public void updateBar(GamePlayer gamePlayer) { BossBar bossBar = gamePlayer.getBossBar() == null ? Bukkit.createBossBar("Loading..", BarColor.PINK, BarStyle.SOLID) : gamePlayer.getBossBar(); float barProgress = 1F / (float) (gamePlayer.getPlayer().getMaxHealth() / gamePlayer.getPlayer().getHealth()); bossBar.setTitle(StringUtil.colorCode("&d&lHP &r&d" + (int) gamePlayer.getPlayer().getHealth() + " &d&l/ &r&d" + (int) gamePlayer.getPlayer().getMaxHealth())); bossBar.setProgress(barProgress); gamePlayer.setBossBar(bossBar); bossBar.addPlayer(gamePlayer.getPlayer()); RedPractice.getMechanicManager().getPlayerHandler().updateGamePlayer(gamePlayer); } } <file_sep>package com.rednetty.redpractice.mechanic.player.energy; import com.rednetty.redpractice.RedPractice; import com.rednetty.redpractice.mechanic.Mechanics; import com.rednetty.redpractice.mechanic.player.damage.DamageHandler; import org.bukkit.Bukkit; import org.bukkit.Effect; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.scheduler.BukkitRunnable; import java.util.concurrent.ConcurrentHashMap; public class EnergyHandler extends Mechanics implements Listener { public ConcurrentHashMap<Player, Integer> cooldownMap = new ConcurrentHashMap<>(); @Override public void onEnable() { listener(this); new BukkitRunnable() { // Removes Energy from Running @Override public void run() { removePlayerEnergySprint(); } }.runTaskTimer(RedPractice.getInstance(), 40, 9L); new BukkitRunnable() { // Regen Player Energy @Override public void run() { regenAllPlayerEnergy(); } }.runTaskTimer(RedPractice.getInstance(), 1, 1); } @Override public void onDisable() { } //Used when a player attacks something @EventHandler(priority = EventPriority.HIGHEST) public void onDamageEnergy(EntityDamageByEntityEvent event) { if (event.getDamager() instanceof Player) { Player player = (Player) event.getDamager(); if (cooldownMap.contains(player)) { player.playSound(player.getLocation(), Sound.ENTITY_WOLF_PANT, 1, 1); player.playEffect(player.getEyeLocation(), Effect.CRIT, 10); event.setCancelled(true); return; } player.sendMessage(getPlayerTotalEnergy(player) + " NRG"); takeEnergy(player, getEnergyUsage(player.getInventory().getItemInMainHand().getType())); } } //Used when a player clicks the air @EventHandler public void onEnergyUse(PlayerInteractEvent event) { if (event.getAction() == Action.LEFT_CLICK_AIR) { Player player = event.getPlayer(); if (cooldownMap.contains(player)) { player.playSound(player.getLocation(), Sound.ENTITY_WOLF_PANT, 1, 1); player.playEffect(player.getEyeLocation(), Effect.CRIT, 10); event.setCancelled(true); } player.sendMessage(getPlayerTotalEnergy(player) + " NRG"); takeEnergy(player, getEnergyUsage(player.getInventory().getItemInMainHand().getType()) / 1.5F); } } /** * Regens player Energy for all Players online */ private void regenAllPlayerEnergy() { for (Player player : Bukkit.getOnlinePlayers()) { float playerEnergy = getPlayerTotalEnergy(player); //Deals with the cooldown when a player runs out of energy if (cooldownMap.containsKey(player)) { if (cooldownMap.get(player) > 0) { cooldownMap.put(player, cooldownMap.get(player) - 1); } if (cooldownMap.get(player) == 0) { cooldownMap.remove(player); } } else { // Deals with Energy Regen if (getPlayerEnergy(player) > 1F || (player.getExp() + (playerEnergy / 15)) > 1F) { //If player energy is greater than 100 just set to 100 obviously. player.setExp(1.0F); } else if (!(getPlayerEnergy(player) == 100)) { player.setExp(player.getExp() + (playerEnergy / 15)); } } updatePlayerEnergyBar(player); } } /** * Updates the players Level Bar to match with the percentage of the Players Bar * @param player - Player you want to change the bar for */ private void updatePlayerEnergyBar(Player player) { float currExp = getPlayerEnergy(player); double percent = currExp * 100.00D; if (percent > 100) { percent = 100; } if (percent < 0) { percent = 0; } player.setLevel(((int) percent)); } /** * Removes energy for players sprinting online */ private void removePlayerEnergySprint() { Bukkit.getOnlinePlayers().stream().filter(Player::isSprinting).forEach(player -> { takeEnergy(player, 0.15F); if (getPlayerEnergy(player) <= 0) { player.setSprinting(false); } }); } /** * Takes energy from the player and updates it * @param player - Player you want to change it for * @param amount - Amount you wanna take (FLOAT 1F would be all of it) */ public void takeEnergy(Player player, float amount) { if ((player.getExp() - amount) <= 0) { player.setExp(0.0F); updatePlayerEnergyBar(player); player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW_DIGGING, 35, 1, true, false)); cooldownMap.put(player, 35); } else { player.setExp(player.getExp() - amount); } } /** * Gets the players total energy from all his gear * @param player - the player you want to get * @return - Returns float of players total energy */ public float getPlayerTotalEnergy(Player player) { float energy = .10F; // base energy pretty much 15 because it would be SUPER slow otherwise (pss ingame its 5 energy just for looks) DamageHandler damageHandler = RedPractice.getMechanicManager().getDamageHandler(); for (ItemStack itemStack : player.getInventory().getArmorContents()) { if (damageHandler.hasStat(itemStack, "energy")) energy += (damageHandler.getStat(itemStack, "energy") / 100.0); if (damageHandler.hasStat(itemStack, "int")) energy += (damageHandler.getStat(itemStack, "int") / 100.0); } return energy; } /** * Gets the players current energy * @param player - Players you wanna get * @return - Returns the players Energy Float */ public float getPlayerEnergy(Player player) { if (player.getExp() > 1F) { return 1F; } else { return player.getExp(); } } /** * Gets the energy requires to use specific items * @param material - Material you are trying to get the energy for * @return - Returns the float (Energy) */ public float getEnergyUsage(Material material) { switch (material) { case GOLD_SWORD: case BOW: case GOLD_HOE: return .08F; case GOLD_AXE: return .1F; case GOLD_SPADE: return .07F; } return .04F; } } <file_sep>package com.rednetty.redpractice.mechanic.items; import com.rednetty.redpractice.RedPractice; import com.rednetty.redpractice.mechanic.items.itemgenerator.Armor; import com.rednetty.redpractice.mechanic.items.itemgenerator.ItemRarity; import com.rednetty.redpractice.mechanic.items.itemgenerator.Weapon; import com.rednetty.redpractice.mechanic.player.damage.DamageHandler; import com.rednetty.redpractice.utils.items.NBTEditor; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import java.util.concurrent.ThreadLocalRandom; public class ItemRandomizer { public static ItemRarity getRarity(ItemStack itemStack) { NBTEditor nbtEditor = new NBTEditor(itemStack).check(); if (nbtEditor.hasKey("rarity")) { return ItemRarity.valueOf(nbtEditor.getString("rarity").toUpperCase()); } return null; } public static ItemStack randomMainStat(ItemType item, int tier, ItemRarity itemRarity) { ThreadLocalRandom random = ThreadLocalRandom.current(); Material material = item.getMaterial(); int armorHealth = 0; int weaponMinDamage = 0; int weaponMaxDamage = 0; int armor = 0; int dps = 0; int energy = 0; int hps = 0; int armorDpsChance = random.nextInt(2); int energyHPsChance = random.nextInt(2); if (armorDpsChance == 1) { armor = random.nextInt(5) + 12; } else { dps = random.nextInt(5) + 12; } if (energyHPsChance == 1) { energy = random.nextInt(3) + 3; } else { hps = random.nextInt(60) + 90; } switch (material) { case GOLD_HOE: case GOLD_SPADE: if (itemRarity.ordinal() > 0) { weaponMinDamage = random.nextInt(30) + 70 * itemRarity.ordinal(); weaponMaxDamage = random.nextInt(60) + weaponMinDamage * itemRarity.ordinal(); } else { weaponMinDamage = random.nextInt(30) + 70; weaponMaxDamage = random.nextInt(60) + weaponMinDamage; } //TODO break; case GOLD_SWORD: if (itemRarity.ordinal() > 0) { weaponMinDamage = random.nextInt(100) + 120 * itemRarity.ordinal(); weaponMaxDamage = random.nextInt(140) + weaponMinDamage * itemRarity.ordinal(); } else { weaponMinDamage = random.nextInt(100) + 120; weaponMaxDamage = random.nextInt(140) + weaponMinDamage; } //TODO break; case GOLD_AXE: case BOW: if (itemRarity.ordinal() > 0) { weaponMinDamage = random.nextInt(130) + 120 * itemRarity.ordinal(); weaponMaxDamage = random.nextInt(150) + weaponMinDamage * itemRarity.ordinal(); } else { weaponMinDamage = random.nextInt(130) + 120; weaponMaxDamage = random.nextInt(150) + weaponMinDamage; } break; case GOLD_HELMET: case GOLD_BOOTS: if (itemRarity.ordinal() > 0) { armorHealth = random.nextInt(200) + 1000 * itemRarity.ordinal(); } else { armorHealth = random.nextInt(200) + 1000; } break; case GOLD_CHESTPLATE: case GOLD_LEGGINGS: if (itemRarity.ordinal() > 0) { armorHealth = random.nextInt(500) + 1700 * itemRarity.ordinal(); } else { armorHealth = random.nextInt(500) + 1700; } break; } if (armorHealth > 0) { Armor armorFinal = new Armor(item.getMaterial(), armorHealth, itemRarity); armorFinal.setEnergy(energy); armorFinal.setDPS(dps); armorFinal.setHps(hps); armorFinal.setArmor(armor); return armorFinal.build(); } else { return new Weapon(item.getMaterial(), weaponMinDamage, weaponMaxDamage, itemRarity).build(); } } public static ItemStack ranomizeStats(ItemStack itemStack) { DamageHandler damageHandler = RedPractice.getMechanicManager().getDamageHandler(); ThreadLocalRandom random = ThreadLocalRandom.current(); int thornsChance = random.nextInt(5); int strChance = random.nextInt(5); int vitChance = random.nextInt(5); int intelectChance = random.nextInt(5); int reflectionChance = random.nextInt(5); int dexChance = random.nextInt(5); int dodgeChance = random.nextInt(5); int blockChance = random.nextInt(5); int fireChance = random.nextInt(5); int iceChance = random.nextInt(5); int poisonChance = random.nextInt(5); int pureChance = random.nextInt(5); int blindChance = random.nextInt(5); int lifestealChance = random.nextInt(5); int armorpenChance = random.nextInt(5); int accuracyChance = random.nextInt(5); int vsplayersChance = random.nextInt(5); switch (itemStack.getType()) { case GOLD_LEGGINGS: case GOLD_HELMET: case GOLD_BOOTS: case GOLD_CHESTPLATE: int thorns = 0; int str = 0; int vit = 0; int intelect = 0; int reflection = 0; int dex = 0; int dodge = 0; int block = 0; if (thornsChance == 0) { thorns = random.nextInt(7) + 1; } if (strChance == 0) { str = random.nextInt(300) + 1; } if (vitChance == 0) { vit = random.nextInt(300) + 1; } if (dexChance == 0) { dex = random.nextInt(300) + 1; } if (intelectChance == 0) { intelect = random.nextInt(300) + 1; } if (reflectionChance == 0) { reflection = random.nextInt(6) + 1; } if (dodgeChance == 0) { dodge = random.nextInt(12) + 1; } if (blockChance == 0) { block = random.nextInt(12) + 1; } Armor armor = new Armor(itemStack, damageHandler.getStat(itemStack, "health"), getRarity(itemStack)); armor.setArmor(damageHandler.getStat(itemStack, "armor")); armor.setDPS(damageHandler.getStat(itemStack, "dps")); armor.setEnergy(damageHandler.getStat(itemStack, "energy")); armor.setHps(damageHandler.getStat(itemStack, "hps")); armor.setThorns(thorns); armor.setReflection(reflection); armor.setBlock(block); armor.setVit(vit); armor.setDex(dex); armor.setIntelect(intelect); armor.setStr(str); armor.setDodge(dodge); return armor.build(); case GOLD_SWORD: case GOLD_AXE: case BOW: case GOLD_SPADE: case GOLD_HOE: int fire = 0; int ice = 0; int poison = 0; int pure = 0; int blind = 0; int lifesteal = 0; int armorpen = 0; int accuracy = 0; int vsplayers = 0; if (fireChance == 0) { fire = random.nextInt(40) + 1; } if (iceChance == 0 && fireChance != 0) { ice = random.nextInt(40) + 1; } if (poisonChance == 0 && iceChance != 0) { poison = random.nextInt(40) + 1; } if (pureChance == 0) { pure = random.nextInt(40) + 1; } if (blindChance == 0) { blind = random.nextInt(9) + 1; } if (lifestealChance == 0) { lifesteal = random.nextInt(12) + 1; } if (vsplayersChance == 0) { vsplayers = random.nextInt(12) + 1; } if (armorpenChance == 0 && itemStack.getType() == Material.GOLD_AXE) { armorpen = random.nextInt(12) + 1; } if (accuracyChance == 0 && itemStack.getType() == Material.GOLD_SWORD) { accuracy = random.nextInt(30) + 1; } Weapon weapon = new Weapon(itemStack, damageHandler.getStat(itemStack, "mindmg"), damageHandler.getStat(itemStack, "maxdmg"), getRarity(itemStack)); weapon.setArmorpen(armorpen); weapon.setLifesteal(lifesteal); weapon.setBlind(blind); weapon.setAccuracy(accuracy); weapon.setVsplayers(vsplayers); weapon.setPure(pure); weapon.setPoison(poison); weapon.setFire(fire); weapon.setIce(ice); return weapon.build(); } return null; } } <file_sep>package com.rednetty.redpractice.mechanic.player; import com.rednetty.redpractice.utils.items.ItemBuilder; import com.rednetty.redpractice.utils.menu.Button; import com.rednetty.redpractice.utils.menu.Menu; import com.rednetty.redpractice.utils.strings.StringUtil; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.ItemStack; import java.util.Arrays; import java.util.stream.IntStream; public class BetaMenu extends Menu { BetaMenu(GamePlayer gamePlayer) { super(InventoryType.HOPPER, "&c&lBETA SERVER!"); ItemStack acceptItem = new ItemBuilder(Material.INK_SACK).setDurability((short) 10).setName("&aACCEPT").setLore(Arrays.asList("&7Clicking will allow you to play.")).build(); ItemStack infoItem = new ItemBuilder(Material.BOOK).setName("&bINFO").setLore(Arrays.asList("&7The server is in very early Alpha", "&7Crying about bugs will not help", "&7Please report any bugs you find", "&7Abusing bugs will result in a perma-ban")).build(); ItemStack denyItem = new ItemBuilder(Material.INK_SACK).setDurability((short) 1).setName("&cDENY").setLore(Arrays.asList("&7Clicking will &l&nREMOVE&7 you from the server.")).build(); newButton(new Button(this, 0, acceptItem, true) { @Override protected void onClick(GamePlayer gamePlayer) { gamePlayer.closeMenu(true); } }); newButton(new Button(this, 4, denyItem, true) { @Override protected void onClick(GamePlayer gamePlayer) { gamePlayer.getPlayer().kickPlayer(StringUtil.colorCode("&c&nYou have been kicked for not accepting the Beta Bug Rules.")); } }); IntStream.range(1, 4).forEach(slot -> newButton(new Button(this, slot, infoItem, true) { @Override protected void onClick(GamePlayer gamePlayer) { //DO NOTHING } })); } @Override public void onClose(GamePlayer player) { Player bukkitPlayer = player.getPlayer(); bukkitPlayer.sendMessage(StringUtil.colorCode("&aThanks for playing and accepting the Beta Rules!")); bukkitPlayer.playSound(bukkitPlayer.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1F, 1F); } @Override public void onOpen(GamePlayer player) { Player bukkitPlayer = player.getPlayer(); bukkitPlayer.playSound(bukkitPlayer.getLocation(), Sound.BLOCK_NOTE_PLING, 1F, 1F); } } <file_sep>package com.rednetty.redpractice.mechanic.items.durability; import com.rednetty.redpractice.mechanic.Mechanics; import org.bukkit.event.Listener; public class DurabilityHandler extends Mechanics implements Listener { } <file_sep>package com.rednetty.redpractice.mechanic.player; import com.rednetty.redpractice.mechanic.player.toggles.ToggleType; import com.rednetty.redpractice.utils.menu.Menu; import org.bukkit.boss.BossBar; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.permissions.PermissionAttachment; import java.util.List; public class GamePlayer{ private Player player; private int gemAmount; private Inventory bankInventory; private int bankSize; private String playerRank; private PermissionAttachment permissions; private Menu openMenu; private BossBar bossBar; private List<ToggleType> toggleList; /** * This is used the initialize a instance of the GamePlayer class * * @param gemAmount - The players currency amount * @param bankInventory - The players bank inventory * @param bankSize - slot size of players bank * @param playerRank - Requires a RankEnum */ public GamePlayer(Player player, String playerRank, int gemAmount, Inventory bankInventory, int bankSize) { setBankInventory(bankInventory); setBankSize(bankSize); setGemAmount(gemAmount); setPlayerRank(playerRank); this.player = player; } public BossBar getBossBar() { return bossBar; } public void setBossBar(BossBar bossBar) { this.bossBar = bossBar; } /** * Used to get the Player * * @return - Player Specified in Class */ public Player getPlayer() { return player; } /** * Used to get the Size of the Players Bank * * @return - Returns a int that gives the size of the players bank */ public int getBankSize() { return bankSize; } /** * Used to set the Bank Size of the Player */ public void setBankSize(int bankSize) { this.bankSize = bankSize; } /** * Used to get the Gem Amount of the Player * * @return - Returns a int that gives you that players gem count */ public int getGemAmount() { return gemAmount; } /** * Used to set the Gem Amount of the Player */ public void setGemAmount(int gemAmount) { this.gemAmount = gemAmount; } /** * Used to get the Bank of the Player * * @return - Returns a int that gives you that players Bank Inventory */ public Inventory getBankInventory() { return bankInventory; } /** * Used to set the Bank Inventory of the Player */ public void setBankInventory(Inventory bankInventory) { this.bankInventory = bankInventory; } /** * Used to get the PermissionAttachmennt from the Player * * @return - Returns the Permission file for the Player */ public PermissionAttachment getPermissions() { return permissions; } /** * Used to set the Permissions of the Player */ public void setPermissions(PermissionAttachment permissions) { this.permissions = permissions; } /** * Used to get the Rank of the Specified Player * * @return - Returns the Players Rank */ public String getPlayerRank() { return playerRank; } public void setPlayerRank(String playerRank) { this.playerRank = playerRank; } /** * Open a menu for the player * * @param openMenu The menu to open */ public void openMenu(Menu openMenu) { if (viewingMenu()) closeMenu(true); this.openMenu = openMenu; this.openMenu.getViewers().add(this); this.openMenu.onOpen(this); getPlayer().openInventory(openMenu.getInventory()); } /** * Close the currently opened menu of the player */ public void closeMenu(boolean closeBukkitInv) { if (!viewingMenu()) return; openMenu.getViewers().remove(this); openMenu.onClose(this); if (closeBukkitInv) getPlayer().closeInventory(); openMenu = null; } /** * Get the currently opened menu of the player * * @return Menu */ public Menu getOpenMenu() { return openMenu; } public List<ToggleType> getToggleList() { return toggleList; } public void setToggleList(List<ToggleType> toggleList) { this.toggleList = toggleList; } public boolean viewingMenu() { return openMenu != null; } } <file_sep>package com.rednetty.redpractice.configs; import com.rednetty.redpractice.RedPractice; import lombok.Getter; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.UUID; public class PlayerConfigs { @Getter private static HashMap<UUID, FileConfiguration> playerFileConfigMap = new HashMap<>(); public static void setupConfig() { File file = new File(RedPractice.getInstance().getDataFolder(), "PlayerData"); if (!file.exists()) { file.mkdirs(); } } public static void setupPlayerConfig(UUID playerID) { File file = new File(RedPractice.getInstance().getDataFolder() + "/PlayerData", playerID.toString() + ".yml"); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } playerFileConfigMap.put(playerID, YamlConfiguration.loadConfiguration(file)); } public static FileConfiguration getPlayerConfig(UUID playerID) { if (!playerFileConfigMap.containsKey(playerID)) setupPlayerConfig(playerID); return playerFileConfigMap.get(playerID); } public static void savePlayerConfig(UUID playerID) { if (!playerFileConfigMap.containsKey(playerID)) setupPlayerConfig(playerID); try { File file = new File(RedPractice.getInstance().getDataFolder() + "/PlayerData", playerID.toString() + ".yml"); FileConfiguration fileConfiguration = playerFileConfigMap.get(playerID); fileConfiguration.save(file); } catch (IOException e) { e.printStackTrace(); } } } <file_sep>package com.rednetty.redpractice.mechanic.items.itemgenerator; public enum ItemRarity { COMMON("&7&oCommon"), UNCOMMON("&a&oUncommon"), RARE("&b&oRare"), UNIQUE("&e&oUnique"); String name; ItemRarity(String name) { this.name = name; } public String getName() { return name; } public static ItemRarity fromInt(int count) { for(ItemRarity itemRarity : ItemRarity.values()) { if(itemRarity.ordinal() == count) { return itemRarity; } } return ItemRarity.COMMON; } } <file_sep>package com.rednetty.redpractice.mechanic.player; import com.rednetty.redpractice.RedPractice; import com.rednetty.redpractice.configs.PlayerConfigs; import com.rednetty.redpractice.configs.RankConfig; import com.rednetty.redpractice.mechanic.Mechanics; import com.rednetty.redpractice.mechanic.items.itemgenerator.Armor; import com.rednetty.redpractice.mechanic.items.itemgenerator.ItemRarity; import com.rednetty.redpractice.mechanic.items.itemgenerator.Weapon; import com.rednetty.redpractice.utils.strings.StringUtil; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.attribute.Attribute; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.scheduler.BukkitRunnable; import java.util.ArrayList; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class PlayerHandler extends Mechanics implements Listener { /*Hashmap that stores GamePlayer instances temporarily*/ public Map<Player, GamePlayer> gamePlayerHashMap = new ConcurrentHashMap<>(); @Override public void onEnable() { PlayerConfigs.setupConfig(); new BukkitRunnable() { @Override public void run() { Bukkit.getOnlinePlayers().forEach(player -> saveGamePlayer(player)); } }.runTaskTimerAsynchronously(RedPractice.getInstance(), 200L, 200L); listener(this); } @Override public void onDisable() { for (Player player : Bukkit.getOnlinePlayers()) { saveGamePlayer(player); } } /** * Generates the Default Config Entries for the Player * * @param player - Requires you to specify a SpigotAPI Player */ public void generatePlayerConfig(Player player) { FileConfiguration fileConfig = PlayerConfigs.getPlayerConfig(player.getUniqueId()); if (!fileConfig.isSet("Gems")) fileConfig.set("Gems", 0); if (!fileConfig.isSet("Guild Name")) fileConfig.set("Guild Name", ""); if (!fileConfig.isSet("Bank Size")) fileConfig.set("Bank Size", 9); if (!fileConfig.isSet("Bank Inventory")) fileConfig.set("Bank Inventory", "Empty"); if (!RankConfig.getConfig().contains(player.getUniqueId().toString())) RankConfig.getConfig().set(player.getUniqueId().toString(), "Default"); PlayerConfigs.savePlayerConfig(player.getUniqueId()); RankConfig.saveConfig(); } /** * Saves player data in all the correct configs. * * @param player - Player data that needs saving */ public void saveGamePlayer(Player player) { FileConfiguration fileConfig = PlayerConfigs.getPlayerConfig(player.getUniqueId()); fileConfig.set("Gems", getGamePlayer(player).getGemAmount()); fileConfig.set("Bank Size", getGamePlayer(player).getBankSize()); fileConfig.set("Bank Inventory", getGamePlayer(player).getBankInventory().getContents()); RankConfig.getConfig().set(player.getUniqueId().toString(), getGamePlayer(player).getPlayerRank().toString()); PlayerConfigs.savePlayerConfig(player.getUniqueId()); RankConfig.saveConfig(); } @EventHandler public void onLogout(PlayerQuitEvent event) { saveGamePlayer(event.getPlayer()); } @EventHandler public void onKick(PlayerKickEvent event) { saveGamePlayer(event.getPlayer()); } /** * Loads the Data of a Player Correctly * * @param player - The player you want to load Data */ public void loadPlayer(Player player) { PlayerConfigs.setupPlayerConfig(player.getUniqueId()); generatePlayerConfig(player); FileConfiguration fileConfig = PlayerConfigs.getPlayerConfig(player.getUniqueId()); /*Loads Gems and Bank Size*/ int gemBalance = fileConfig.getInt("Gems"); int bankSize = fileConfig.getInt("Bank Size"); String guildName = fileConfig.getString("Guild Name"); String playerRank = RankConfig.getConfig().getString(player.getUniqueId().toString()); /*Loads Bank Inventory*/ Inventory inventory = Bukkit.createInventory(null, bankSize, player.getName() + "'s Bank (1/1)"); if (!fileConfig.get("Bank Inventory").equals("Empty")) { loadBankItems(fileConfig).forEach(itemStack -> { if (itemStack != null && itemStack.getType() != Material.EMERALD && itemStack.getType() != Material.THIN_GLASS) inventory.addItem(itemStack); }); } GamePlayer gamePlayer = new GamePlayer(player, playerRank, gemBalance, inventory, bankSize); gamePlayerHashMap.put(player, gamePlayer); RedPractice.getMechanicManager().getModerationHandler().updatePermission(player); } /** * Deals with the loading of Data on Player Login * If there is any issues with a players data is would likely be here. */ @EventHandler public void onLogin(PlayerJoinEvent event) { Player player = event.getPlayer(); if (gamePlayerHashMap.containsKey(event.getPlayer())) return; //Data Loading loadPlayer(player); //Damage Loading player.setMaximumNoDamageTicks(0); player.getAttribute(Attribute.GENERIC_ATTACK_SPEED).setBaseValue(7200); player.saveData(); //Health Loading player.setMaxHealth(RedPractice.getMechanicManager().getHealthHandler().getMaxHealth(player.getInventory().getArmorContents())); player.setHealthScale(20); player.setHealthScaled(true); //BETA MESSAGE new BukkitRunnable() { @Override public void run() { getGamePlayer(player).openMenu(new BetaMenu(getGamePlayer(player))); } }.runTaskLaterAsynchronously(RedPractice.getInstance(), 3L); //TEST Weapon weapon = new Weapon(Material.GOLD_SWORD, 200, 500, ItemRarity.UNIQUE); weapon.setIce(40); weapon.setArmorpen(20); player.getInventory().addItem(weapon.build()); Weapon weapon1 = new Weapon(Material.GOLD_SWORD, 200, 500, ItemRarity.UNIQUE); weapon1.setPoison(40); weapon1.setAccuracy(20); weapon1.setBlind(10); weapon1.setLifesteal(10); player.getInventory().addItem(weapon1.build()); Armor armor = new Armor(Material.GOLD_HELMET, 5400, ItemRarity.UNIQUE); armor.setArmor(20); armor.setEnergy(6); armor.setVit(400); armor.setDodge(12); armor.setBlock(12); armor.setReflection(4); armor.setThorns(20); player.getInventory().addItem(armor.build()); Armor chest = new Armor(Material.GOLD_CHESTPLATE, 7000, ItemRarity.UNIQUE); chest.setDPS(15); chest.setEnergy(5); chest.setDodge(12); chest.setBlock(12); chest.setReflection(4); chest.setThorns(20); player.getInventory().addItem(chest.build()); Armor legs = new Armor(Material.GOLD_LEGGINGS, 7000, ItemRarity.UNIQUE); legs.setDPS(15); legs.setEnergy(5); legs.setDodge(12); legs.setBlock(12); legs.setReflection(4); player.getInventory().addItem(legs.build()); Armor boots = new Armor(Material.GOLD_BOOTS, 7000, ItemRarity.UNIQUE); boots.setDPS(15); boots.setEnergy(5); boots.setDodge(12); boots.setBlock(12); boots.setReflection(4); player.getInventory().addItem(boots.build()); } /** * Used to update Player Data * * @param gamePlayer - Instance of the GamePlayer class that is stored in the HashMap above */ public void updateGamePlayer(GamePlayer gamePlayer) { gamePlayerHashMap.put(gamePlayer.getPlayer(), gamePlayer); } /*Returns instance of the GamePlayer of this Player*/ public GamePlayer getGamePlayer(Player player) { if (!gamePlayerHashMap.containsKey(player)) loadPlayer(player); return gamePlayerHashMap.get(player); } /** * Method used for turning the Strings into ItemStacks * * @return Returns a ItemStack[] that is used to add the items into the invenntory */ public ArrayList<ItemStack> loadBankItems(FileConfiguration fileConfig) { ArrayList<ItemStack> content = (ArrayList<ItemStack>) fileConfig.getList("Bank Inventory"); for (int i = 0; i < content.size(); i++) { ItemStack item = content.get(i); if (item == null) continue; content.set(i, item); } return content; } } <file_sep>package com.rednetty.redpractice.utils; import org.bukkit.Bukkit; import org.bukkit.Location; public class LocationUtils { public static Location fromString(String string) { String[] locationString = string.split(","); return new Location(Bukkit.getWorld(locationString[0]), Integer.parseInt(locationString[1]), Integer.parseInt(locationString[2]), Integer.parseInt(locationString[3])); } } <file_sep>package com.rednetty.redpractice.commands.chat; import com.rednetty.redpractice.RedPractice; import com.rednetty.redpractice.mechanic.player.chat.ChatHandler; import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.HashSet; import java.util.Set; public class GlobalCommand implements CommandExecutor { @Override public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) { if (commandSender.hasPermission("practice.globalchat") && commandSender instanceof Player) { ChatHandler chatHandler = RedPractice.getMechanicManager().getChatHandler(); Player player = (Player) commandSender; Set<Player> recipients = new HashSet<>(Bukkit.getOnlinePlayers()); String globalPrefix = "&b<&lG&r&b> "; /*Used to Determine what Prefix to use*/ String fullMessage = StringUtils.join(strings, " "); /*Joins the Spaces between the Args into a Single Message*/ String lowerCase = fullMessage.toLowerCase(); if (lowerCase.contains("wts") || lowerCase.contains("wtb") || lowerCase.contains("trading") || lowerCase.contains("buying")) { globalPrefix = "&a<&lT&r&a> "; } String beforeMessage = ChatColor.translateAlternateColorCodes('&', globalPrefix + chatHandler.getFullTag(player) + "&7" + player.getName() + ": &f"); if (lowerCase.contains("@i@") && player.getInventory().getItemInMainHand().getType() != Material.AIR) { /*If player is trying to show a Item Display it with the Method Below*/ chatHandler.sendShowMessage(player, recipients, globalPrefix + chatHandler.getFullTag(player), fullMessage, player.getInventory().getItemInMainHand()); } else { for (Player target : recipients) { target.sendMessage(beforeMessage + fullMessage); } } } return false; } } <file_sep>package com.rednetty.redpractice.commands.moderation; import com.rednetty.redpractice.RedPractice; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; public class SpawnMobCommand implements CommandExecutor{ @Override public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) { if(commandSender instanceof Player) { Player player = (Player)commandSender; EntityType entityType = EntityType.ZOMBIE; RedPractice.getMechanicManager().getSpawnerHandler().spawnMob(player.getLocation(), entityType, 5); return true; } return false; } } <file_sep>package com.rednetty.redpractice.mechanic.server.menu; import com.rednetty.redpractice.RedPractice; import com.rednetty.redpractice.mechanic.Mechanics; import com.rednetty.redpractice.mechanic.player.GamePlayer; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; public class MenuHandler extends Mechanics implements Listener { @Override public void onEnable() { listener(this); } @Override public void onDisable() { } @EventHandler public void onInteract(InventoryClickEvent event) { Player player = (Player) event.getWhoClicked(); GamePlayer gamePlayer = RedPractice.getMechanicManager().getPlayerHandler().getGamePlayer(player); if (!gamePlayer.viewingMenu()) return; gamePlayer.getOpenMenu().handleClick(event.getRawSlot(), gamePlayer, event); } @EventHandler public void onClose(InventoryCloseEvent event) { Player player = (Player) event.getPlayer(); GamePlayer gamePlayer = RedPractice.getMechanicManager().getPlayerHandler().getGamePlayer(player); if (gamePlayer == null) return; if (!gamePlayer.viewingMenu()) return; gamePlayer.closeMenu(false); } } <file_sep>package com.rednetty.redpractice.commands.moderation; import com.rednetty.redpractice.mechanic.items.ItemRandomizer; import com.rednetty.redpractice.mechanic.items.ItemType; import com.rednetty.redpractice.mechanic.items.itemgenerator.ItemRarity; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.concurrent.ThreadLocalRandom; public class RandomGearCommand implements CommandExecutor { @Override public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) { if(commandSender instanceof Player) { Player player = (Player)commandSender; ThreadLocalRandom random = ThreadLocalRandom.current(); int bootRarity = random.nextInt(ItemRarity.values().length); int legsRarity = random.nextInt(ItemRarity.values().length); int chestRarity = random.nextInt(ItemRarity.values().length); int helmetRarity = random.nextInt(ItemRarity.values().length); player.getInventory().addItem(ItemRandomizer.ranomizeStats(ItemRandomizer.randomMainStat(ItemType.BOOTS, 5, ItemRarity.fromInt(bootRarity)))); player.getInventory().addItem(ItemRandomizer.ranomizeStats(ItemRandomizer.randomMainStat(ItemType.LEGS, 5, ItemRarity.fromInt(legsRarity)))); player.getInventory().addItem(ItemRandomizer.ranomizeStats(ItemRandomizer.randomMainStat(ItemType.CHEST, 5, ItemRarity.fromInt(chestRarity)))); player.getInventory().addItem(ItemRandomizer.ranomizeStats(ItemRandomizer.randomMainStat(ItemType.HELMET, 5, ItemRarity.fromInt(helmetRarity)))); player.getInventory().addItem(ItemRandomizer.ranomizeStats(ItemRandomizer.randomMainStat(ItemType.SWORD, 5, ItemRarity.COMMON))); } return true; } }
f76f64794b290f8fc484b9bc29fbba6b3e45ec99
[ "Markdown", "Java" ]
22
Markdown
RedNetty/RedPractice
ecaed2740d27a12e3db918fc3a7f9b88ac28bc11
ec4eacb51e727a2d3d24c058359ea56bb5dea5ea
refs/heads/master
<repo_name>zs1993608/test1111<file_sep>/src/components/nav/Nav.js import React, { Component } from 'react'; import { Menu, Dropdown, Button, message, Tooltip } from 'antd'; import "./Nav.css" const menu = ( <Menu> <Menu.Item key="0"> {/* {this.props.numberS} */} </Menu.Item> <Menu.Item key="1"> <a href="http://www.taobao.com/">2nd menu item</a> </Menu.Item> <Menu.Item key="2">3rd menu item</Menu.Item> <Menu.Item> {/* {this.props.numberS} */} </Menu.Item> </Menu> ); class Nav extends Component { constructor(props) { super(props); this.state = { hidden:true }; } componentWillUnmount() { this.wowo() } wowo = () => { if (this.props.numberS) { this.setState({ hiddenS: 0 }) } else if (this.props.numberM) { this.setState({ hiddenM: false }) } else if (this.props.numberL) { this.setState({ hiddenL: false }) } } // getItems=()=>{ // this.setState({ // arr:this.props.arr // }) // } getS() { if (this.props.numberS) { return [ <img width={100} src={this.props.url} />, <div> <div className="itemName">{this.props.name}</div> <div>{this.props.numberS}x<span className="itemPrice">{this.props.price}</span></div> <div className="itemSize">Size:S</div> </div> ] } } getM() { if (this.props.numberM) { return [ <img width={100} src={this.props.url} />, <div> <div className="itemName">{this.props.name}</div> <div>{this.props.numberM}x<span className="itemPrice">{this.props.price}</span></div> <div className="itemSize">Size:M</div> </div> ] } } getL() { if (this.props.numberL) { return [ <img width={100} src={this.props.url} />, <div> <div className="itemName">{this.props.name}</div> <div>{this.props.numberL}x<span className="itemPrice">{this.props.price}</span></div> <div className="itemSize">Size:L</div> </div> ] } } handleDropdown=()=>{ var hidden=!this.state.hidden this.setState({ hidden:hidden }) } render() { return ( <div className="navbar"> <button type="text" className="ant-dropdown-link" onClick={this.handleDropdown}> My Cart ( {this.props.sum} ) </button> <div className="cartItems" hidden={this.state.hidden}> <div className="item"> {this.getS()} </div> <div className="item"> {this.getM()} </div> <div className="item"> {this.getL()} </div> {/* <div> <img width={100} src={this.props.url}/> <div>{this.props.numberM}x{this.props.price}</div> <div>Size:M</div> </div> <div> <img width={100} src={this.props.url}/> <div>{this.props.numberL}x{this.props.price}</div> <div>Size:L</div> </div> */} </div> </div> ); } } export default Nav;<file_sep>/src/components/Right.js import React, { Component } from 'react'; import './Right.css' class Right extends Component { constructor(props) { super(props); this.state = { name:'<NAME>', price:'$75.00', size:'', numberS:0, numberM:0, numberL:0, sum:0, } } onButtonClick=(size)=>{ // var sum = this.state.sum+1 this.setState({ size:size, // sum:sum }) } addToCart=()=>{ var number = this.state.number+1 this.setState({ number:number, }) } addData=()=>{ let sum = this.state.sum+1 let numberS = this.state.numberS let numberM = this.state.numberM let numberL = this.state.numberL this.setState({ sum:sum, }) if(this.state.size=='S'){ numberS = this.state.numberS+1 this.setState({ numberS:numberS }) } else if(this.state.size=='M'){ numberM = this.state.numberM+1 this.setState({ numberM:numberM }) } else if(this.state.size=='L'){ numberL = this.state.numberL+1 this.setState({ numberL:numberL }) } this.props.getData(this.state.name,this.state.price,sum,numberS,numberM,numberL,this.state.size) } render() { return ( <div> {/* <RightDocs title={this.state.name} price={this.state.price}/> <AddToCart/> */} {/* <div className="leftPictures"> {/* <Image width={600} src={pic}/> */} {/* <img alt="Developer-Test-Minicart-Size-Click" src="https://s3.invisionapp-cdn.com/storage.invisionapp.com/screens/files/221745405.png?x-amz-meta-iv=4&amp;response-cache-control=max-age%3D2419200&amp;x-amz-meta-ck=daee10707631a9a3504f6cf055e0eb9a&amp;AWSAccessKeyId=AKIAJFUMDU3L6GTLUDYA&amp;Expires=1606780800&amp;Signature=vWZVxw%2F5MW1ICyTu7w3UkCbWHFE%3D" height="731" width="1440" decoding="sync"> */} {/* </div> */} <div className="title"> {this.state.name} </div> <div class="DividingLine"></div> <div className="price"> {this.state.price} </div> <div class="DividingLine"></div> <div className="text"> <p> Dolor sit amet, consectetur adipiscing elit. Haec et tu ita posuisti, et verba vestra sunt. Quod autem ratione actum est, id officium appellamus dolor sit amet, consectetur adipiscing slit. Haec et tu ita posuistim, et verba vestra sunt. Quod autem ratione actum est, id officium appellamus </p> </div> <div className="size"> SIZE<span>*</span> <span className="sizec">{this.state.size}</span> </div> <div className="buttons"> <button id='1' onClick={()=>this.onButtonClick('S')}>S</button> <button id='2' onClick={()=>this.onButtonClick('M')}>M</button> <button id='3' onClick={()=>this.onButtonClick('L')}>L</button> </div> <button className="addToCart" onClick={this.addData}>ADD TO CART</button> {/* {this.state.sum}numbers:{this.state.numberS}numberM:{this.state.numberM}numberL:{this.state.numberL} */} </div> ); } } export default Right;
8b3e93313aff44a022103a44cb7db951b26fdd48
[ "JavaScript" ]
2
JavaScript
zs1993608/test1111
a57c883e92c6f40f3576680e7794a438a4b5a52e
6cdf55902b4fcbcb660c6ae7bb5700bc13f1840e
refs/heads/master
<repo_name>thomascherickal/julia<file_sep>/cli/loader_lib.c // This file is a part of Julia. License is MIT: https://julialang.org/license // This file defines an RPATH-style relative path loader for all platforms #include "loader.h" #ifdef __cplusplus extern "C" { #endif /* Bring in definitions of symbols exported from libjulia. */ #include "jl_exports.h" /* Bring in helper functions for windows without libgcc. */ #ifdef _OS_WINDOWS_ #include "loader_win_utils.c" #endif // Save DEP_LIBS to a variable that is explicitly sized for expansion static char dep_libs[512] = DEP_LIBS; JL_DLLEXPORT void jl_loader_print_stderr(const char * msg) { fputs(msg, stderr); } // I use three arguments a lot. void jl_loader_print_stderr3(const char * msg1, const char * msg2, const char * msg3) { jl_loader_print_stderr(msg1); jl_loader_print_stderr(msg2); jl_loader_print_stderr(msg3); } /* Wrapper around dlopen(), with extra relative pathing thrown in*/ static void * load_library(const char * rel_path, const char * src_dir) { void * handle = NULL; // See if a handle is already open to the basename const char *basename = rel_path + strlen(rel_path); while (basename-- > rel_path) if (*basename == PATHSEPSTRING[0] || *basename == '/') break; basename++; #if defined(_OS_WINDOWS_) if ((handle = GetModuleHandleW(basename))) return handle; #else if ((handle = dlopen(basename, RTLD_NOLOAD | RTLD_NOW | RTLD_GLOBAL))) return handle; #endif char path[2*PATH_MAX + 1] = {0}; strncat(path, src_dir, sizeof(path) - 1); strncat(path, PATHSEPSTRING, sizeof(path) - 1); strncat(path, rel_path, sizeof(path) - 1); #if defined(_OS_WINDOWS_) wchar_t wpath[2*PATH_MAX + 1] = {0}; if (!utf8_to_wchar(path, wpath, 2*PATH_MAX)) { jl_loader_print_stderr3("ERROR: Unable to convert path ", path, " to wide string!\n"); exit(1); } handle = (void *)LoadLibraryExW(wpath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); #else handle = dlopen(path, RTLD_NOW | RTLD_GLOBAL); #endif if (handle == NULL) { jl_loader_print_stderr3("ERROR: Unable to load dependent library ", path, "\n"); #if defined(_OS_WINDOWS_) LPWSTR wmsg = TEXT(""); FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK, NULL, GetLastError(), MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), (LPWSTR)&wmsg, 0, NULL); char err[256] = {0}; wchar_to_utf8(wmsg, err, 255); jl_loader_print_stderr3("Message:", err, "\n"); #else jl_loader_print_stderr3("Message:", dlerror(), "\n"); #endif exit(1); } return handle; } static void * lookup_symbol(const void * lib_handle, const char * symbol_name) { #ifdef _OS_WINDOWS_ return GetProcAddress((HMODULE) lib_handle, symbol_name); #else return dlsym((void *)lib_handle, symbol_name); #endif } // Find the location of libjulia. char lib_dir[PATH_MAX]; JL_DLLEXPORT const char * jl_get_libdir() { // Reuse the path if this is not the first call. if (lib_dir[0] != 0) { return lib_dir; } #if defined(_OS_WINDOWS_) // On Windows, we use GetModuleFileNameW wchar_t libjulia_path[PATH_MAX]; HMODULE libjulia = NULL; // Get a handle to libjulia. if (!utf8_to_wchar(LIBJULIA_NAME, libjulia_path, PATH_MAX)) { jl_loader_print_stderr3("ERROR: Unable to convert path ", LIBJULIA_NAME, " to wide string!\n"); exit(1); } libjulia = LoadLibraryW(libjulia_path); if (libjulia == NULL) { jl_loader_print_stderr3("ERROR: Unable to load ", LIBJULIA_NAME, "!\n"); exit(1); } if (!GetModuleFileNameW(libjulia, libjulia_path, PATH_MAX)) { jl_loader_print_stderr("ERROR: GetModuleFileName() failed\n"); exit(1); } if (!wchar_to_utf8(libjulia_path, lib_dir, PATH_MAX)) { jl_loader_print_stderr("ERROR: Unable to convert julia path to UTF-8\n"); exit(1); } #else // On all other platforms, use dladdr() Dl_info info; if (!dladdr(&jl_get_libdir, &info)) { jl_loader_print_stderr("ERROR: Unable to dladdr(&jl_get_libdir)!\n"); jl_loader_print_stderr3("Message:", dlerror(), "\n"); exit(1); } strcpy(lib_dir, info.dli_fname); #endif // Finally, convert to dirname const char * new_dir = dirname(lib_dir); if (new_dir != lib_dir) { // On some platforms, dirname() mutates. On others, it does not. memcpy(lib_dir, new_dir, strlen(new_dir)+1); } return lib_dir; } void * libjulia_internal = NULL; __attribute__((constructor)) void jl_load_libjulia_internal(void) { // Only initialize this once if (libjulia_internal != NULL) { return; } // Introspect to find our own path const char * lib_dir = jl_get_libdir(); // Pre-load libraries that libjulia-internal needs. int deps_len = strlen(dep_libs); char * curr_dep = &dep_libs[0]; while (1) { // try to find next colon character, if we can't, escape out. char * colon = strchr(curr_dep, ':'); if (colon == NULL) break; // Chop the string at the colon, load this library. *colon = '\0'; load_library(curr_dep, lib_dir); // Skip ahead to next dependency curr_dep = colon + 1; } // Last dependency is `libjulia-internal`, so load that and we're done with `dep_libs`! libjulia_internal = load_library(curr_dep, lib_dir); // Once we have libjulia-internal loaded, re-export its symbols: for (unsigned int symbol_idx=0; jl_exported_func_names[symbol_idx] != NULL; ++symbol_idx) { void *addr = lookup_symbol(libjulia_internal, jl_exported_func_names[symbol_idx]); if (addr == NULL) { jl_loader_print_stderr3("ERROR: Unable to load ", jl_exported_func_names[symbol_idx], " from libjulia-internal\n"); exit(1); } (*jl_exported_func_addrs[symbol_idx]) = addr; } } // Load libjulia and run the REPL with the given arguments (in UTF-8 format) JL_DLLEXPORT int jl_load_repl(int argc, char * argv[]) { // Some compilers/platforms are known to have `__attribute__((constructor))` issues, // so we have a fallback call of `jl_load_libjulia_internal()` here. if (libjulia_internal == NULL) { jl_load_libjulia_internal(); if (libjulia_internal == NULL) { jl_loader_print_stderr("ERROR: libjulia-internal could not be loaded!\n"); exit(1); } } // Next, if we're on Linux/FreeBSD, set up fast TLS. #if !defined(_OS_WINDOWS_) && !defined(_OS_DARWIN_) void (*jl_pgcstack_setkey)(void*, void*(*)(void)) = lookup_symbol(libjulia_internal, "jl_pgcstack_setkey"); if (jl_pgcstack_setkey == NULL) { jl_loader_print_stderr("ERROR: Cannot find jl_pgcstack_setkey() function within libjulia-internal!\n"); exit(1); } void *fptr = lookup_symbol(RTLD_DEFAULT, "jl_get_pgcstack_static"); void *(*key)(void) = lookup_symbol(RTLD_DEFAULT, "jl_pgcstack_addr_static"); if (fptr == NULL || key == NULL) { jl_loader_print_stderr("ERROR: Cannot find jl_get_pgcstack_static(), must define this symbol within calling executable!\n"); exit(1); } jl_pgcstack_setkey(fptr, key); #endif // Load the repl entrypoint symbol and jump into it! int (*entrypoint)(int, char **) = (int (*)(int, char **))lookup_symbol(libjulia_internal, "jl_repl_entrypoint"); if (entrypoint == NULL) { jl_loader_print_stderr("ERROR: Unable to find `jl_repl_entrypoint()` within libjulia-internal!\n"); exit(1); } return entrypoint(argc, (char **)argv); } #ifdef _OS_WINDOWS_ int __stdcall DllMainCRTStartup(void* instance, unsigned reason, void* reserved) { setup_stdio(); // Because we override DllMainCRTStartup, we have to manually call our constructor methods jl_load_libjulia_internal(); return 1; } #endif #ifdef __cplusplus } // extern "C" #endif <file_sep>/cli/jl_exports.h // This file is a part of Julia. License is MIT: https://julialang.org/license // Bring in the curated lists of exported data and function symbols, then // perform C preprocessor magic upon them to generate lists of declarations and // functions to re-export our function symbols from libjulia-internal to libjulia. #include "../src/jl_exported_data.inc" #include "../src/jl_exported_funcs.inc" // Define pointer data as `const void * $(name);` #define XX(name) JL_DLLEXPORT const void * name; JL_EXPORTED_DATA_POINTERS(XX) #undef XX // Define symbol data as `$(type) $(name);` #define XX(name, type) JL_DLLEXPORT type name; JL_EXPORTED_DATA_SYMBOLS(XX) #undef XX // Declare list of exported functions (sans type) #define XX(name) JL_DLLEXPORT void name(void); typedef void (anonfunc)(void); JL_EXPORTED_FUNCS(XX) #ifdef _OS_WINDOWS_ JL_EXPORTED_FUNCS_WIN(XX) #endif #undef XX // Define holder locations for function addresses as `const void * $(name)_addr = NULL; #define XX(name) JL_HIDDEN anonfunc * name##_addr = NULL; JL_EXPORTED_FUNCS(XX) #ifdef _OS_WINDOWS_ JL_EXPORTED_FUNCS_WIN(XX) #endif #undef XX // Generate lists of function names and addresses #define XX(name) "i" #name, static const char *const jl_exported_func_names[] = { JL_EXPORTED_FUNCS(XX) #ifdef _OS_WINDOWS_ JL_EXPORTED_FUNCS_WIN(XX) #endif NULL }; #undef XX #define XX(name) &name##_addr, static anonfunc **const jl_exported_func_addrs[] = { JL_EXPORTED_FUNCS(XX) #ifdef _OS_WINDOWS_ JL_EXPORTED_FUNCS_WIN(XX) #endif NULL }; #undef XX <file_sep>/.buildkite/pipelines/main/platforms/platforms.sh #!/bin/bash SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )" PLATFORM="$1" cat "$SCRIPT_DIR/$PLATFORM.arches" | tr -s ' ' | while read _line; do # Remove whitespace from the beginning and end of each line line=`echo $_line | tr -s ' '` # Skip all lines that begin with `#` if [[ $line == \#* ]]; then continue fi export ARCH=`echo $line | cut -d ' ' -f 1` export ARCH_LABEL=`echo $line | cut -d ' ' -f 2` export ROOTFS_ARCH=`echo $line | cut -d ' ' -f 3` export TIMEOUT=`echo $line | cut -d ' ' -f 4` export ROOTFS_TAG=`echo $line | cut -d ' ' -f 5` export ROOTFS_TREE=`echo $line | cut -d ' ' -f 6` echo "Launching: $PLATFORM $ARCH $ARCH_LABEL $ROOTFS_ARCH $TIMEOUT" buildkite-agent pipeline upload "$SCRIPT_DIR/$PLATFORM.yml" done <file_sep>/src/clangsa/ImplicitAtomics.cpp //===-- ImplicitAtomicsChecker.cpp - Null dereference checker -----------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This defines NullDerefChecker, a builtin check in ExprEngine that performs // checks for null pointers at loads and stores. // //===----------------------------------------------------------------------===// #include "clang/AST/ExprObjC.h" #include "clang/AST/ExprOpenMP.h" #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" #include "clang/StaticAnalyzer/Core/Checker.h" #include "clang/StaticAnalyzer/Core/CheckerManager.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/raw_ostream.h" #include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" using namespace clang; using namespace ento; namespace { class ImplicitAtomicsChecker : public Checker< check::PreStmt<CastExpr>, check::PreStmt<BinaryOperator>, check::PreStmt<UnaryOperator>, check::PreCall> { //check::Bind //check::Location BugType ImplicitAtomicsBugType{this, "Implicit Atomic seq_cst synchronization", "Atomics"}; void reportBug(const Stmt *S, CheckerContext &C) const; void reportBug(const Stmt *S, CheckerContext &C, StringRef desc) const; void reportBug(const CallEvent &S, CheckerContext &C, StringRef desc="") const; public: //void checkLocation(SVal location, bool isLoad, const Stmt* S, // CheckerContext &C) const; //void checkBind(SVal L, SVal V, const Stmt *S, CheckerContext &C) const; void checkPreStmt(const CastExpr *CE, CheckerContext &C) const; void checkPreStmt(const UnaryOperator *UOp, CheckerContext &C) const; void checkPreStmt(const BinaryOperator *BOp, CheckerContext &C) const; void checkPreCall(const CallEvent &Call, CheckerContext &C) const; }; } // end anonymous namespace // Checks if RD has name in Names and is in std namespace static bool hasStdClassWithName(const CXXRecordDecl *RD, ArrayRef<llvm::StringLiteral> Names) { // or could check ASTContext::getQualifiedTemplateName()->isDerivedFrom() ? if (!RD || !RD->getDeclContext()->isStdNamespace()) return false; if (RD->getDeclName().isIdentifier()) { StringRef Name = RD->getName(); return llvm::any_of(Names, [&Name](StringRef GivenName) -> bool { return Name == GivenName; }); } return false; } constexpr llvm::StringLiteral STD_PTR_NAMES[] = {"atomic", "atomic_ref"}; static bool isStdAtomic(const CXXRecordDecl *RD) { return hasStdClassWithName(RD, STD_PTR_NAMES); } static bool isStdAtomicCall(const Expr *E) { return E && isStdAtomic(E->IgnoreImplicit()->getType()->getAsCXXRecordDecl()); } static bool isStdAtomic(const Expr *E) { return E->getType()->isAtomicType(); } void ImplicitAtomicsChecker::reportBug(const CallEvent &S, CheckerContext &C, StringRef desc) const { reportBug(S.getOriginExpr(), C, desc); } // try to find the "best" node to attach this to, so we generate fewer duplicate reports void ImplicitAtomicsChecker::reportBug(const Stmt *S, CheckerContext &C) const { while (1) { const auto *expr = dyn_cast<Expr>(S); if (!expr) break; expr = expr->IgnoreParenCasts(); if (const auto *UO = dyn_cast<UnaryOperator>(expr)) S = UO->getSubExpr(); else if (const auto *BO = dyn_cast<BinaryOperator>(expr)) S = isStdAtomic(BO->getLHS()) ? BO->getLHS() : isStdAtomic(BO->getRHS()) ? BO->getRHS() : BO->getLHS(); else break; } reportBug(S, C, ""); } void ImplicitAtomicsChecker::reportBug(const Stmt *S, CheckerContext &C, StringRef desc) const { SmallString<100> buf; llvm::raw_svector_ostream os(buf); os << ImplicitAtomicsBugType.getDescription() << desc; PathDiagnosticLocation N = PathDiagnosticLocation::createBegin( S, C.getSourceManager(), C.getLocationContext()); auto report = std::make_unique<BasicBugReport>(ImplicitAtomicsBugType, buf.str(), N); C.emitReport(std::move(report)); } void ImplicitAtomicsChecker::checkPreStmt(const CastExpr *CE, CheckerContext &C) const { //if (isStdAtomic(CE) != isStdAtomic(CE->getSubExpr())) { // AtomicToNonAtomic or NonAtomicToAtomic CastExpr if (CE->getCastKind() == CK_AtomicToNonAtomic) { reportBug(CE, C); } } void ImplicitAtomicsChecker::checkPreStmt(const UnaryOperator *UOp, CheckerContext &C) const { if (UOp->getOpcode() == UO_AddrOf) return; const Expr *Sub = UOp->getSubExpr(); if (isStdAtomic(UOp) || isStdAtomic(Sub)) reportBug(UOp, C); } void ImplicitAtomicsChecker::checkPreStmt(const BinaryOperator *BOp, CheckerContext &C) const { const Expr *Lhs = BOp->getLHS(); const Expr *Rhs = BOp->getRHS(); if (isStdAtomic(Lhs) || isStdAtomic(Rhs) || isStdAtomic(BOp)) reportBug(BOp, C); } void ImplicitAtomicsChecker::checkPreCall(const CallEvent &Call, CheckerContext &C) const { const auto *MC = dyn_cast<CXXInstanceCall>(&Call); if (!MC || !isStdAtomicCall(MC->getCXXThisExpr())) return; if (const auto *OC = dyn_cast<CXXMemberOperatorCall>(&Call)) { OverloadedOperatorKind OOK = OC->getOverloadedOperator(); if (CXXOperatorCallExpr::isAssignmentOp(OOK) || OOK == OO_PlusPlus || OOK == OO_MinusMinus) { reportBug(Call, C, " (std::atomic)"); } } else if (const auto *Convert = dyn_cast<CXXConversionDecl>(MC->getDecl())) { reportBug(Call, C, " (std::atomic)"); } } //// These seem probably unnecessary: // //static const Expr *getDereferenceExpr(const Stmt *S, bool IsBind=false) { // const Expr *E = nullptr; // // // Walk through lvalue casts to get the original expression // // that syntactically caused the load. // if (const Expr *expr = dyn_cast<Expr>(S)) // E = expr->IgnoreParenLValueCasts(); // // if (IsBind) { // const VarDecl *VD; // const Expr *Init; // std::tie(VD, Init) = parseAssignment(S); // if (VD && Init) // E = Init; // } // return E; //} // //// load or bare symbol //void ImplicitAtomicsChecker::checkLocation(SVal l, bool isLoad, const Stmt* S, // CheckerContext &C) const { // const Expr *expr = getDereferenceExpr(S); // assert(expr); // if (isStdAtomic(expr)) // reportBug(S, C); //} // //// auto &r = *l, or store //void ImplicitAtomicsChecker::checkBind(SVal L, SVal V, const Stmt *S, // CheckerContext &C) const { // const Expr *expr = getDereferenceExpr(S, /*IsBind=*/true); // assert(expr); // if (isStdAtomic(expr)) // reportBug(S, C, " (bind)"); //} namespace clang { namespace ento { void registerImplicitAtomicsChecker(CheckerManager &mgr) { mgr.registerChecker<ImplicitAtomicsChecker>(); } bool shouldRegisterImplicitAtomicsChecker(const CheckerManager &mgr) { return true; } } // namespace ento } // namespace clang #ifdef CLANG_PLUGIN extern "C" const char clang_analyzerAPIVersionString[] = CLANG_ANALYZER_API_VERSION_STRING; extern "C" void clang_registerCheckers(CheckerRegistry &registry) { registry.addChecker<ImplicitAtomicsChecker>( "julia.ImplicitAtomics", "Flags implicit atomic operations", "" ); } #endif
5ce7f551d6094bcd9008c7b01eae1b43c759e7d1
[ "C", "C++", "Shell" ]
4
C
thomascherickal/julia
94f5f388fe390e5bf86b8a94fd63d55836017199
4b572a98dffa360161efaa5cd9fba5cbf5d4825b
refs/heads/master
<file_sep># Exploratory Data Analysis # Course Project 4 # plot1.R # coded by <NAME> # file encoding Windows CP-1250 # read in data # file is located in: # "C:\R_WORK\Exploratory Data Analysis notes" # where "C:\R_WORK" is R's working directory # NOTE!!! data.table package is needed library(data.table) # get only dates: 2007-02-01 and 2007-02-02 mypattern <- "^(1|2).2.2007" # subset only those lines which match pattern, save them in temporary file cat( grep(as.character(mypattern) , readLines('./Exploratory Data Analysis notes/household_power_consumption.txt') , value = TRUE ) , sep="\n" , file = "my.small.data" ) # create data.table data.set <- data.table( read.table( file = "my.small.data" , na.strings = "?" , stringsAsFactors = F , header = FALSE , quote = "" , sep = ";" , dec = "." , colClasses = c("character", "character", rep("numeric",7)) ) ) # drop temporary file unlink("my.small.data") setnames(data.set, c("Date" , "Time" , "Global_active_power" , "Global_reactive_power" , "Voltage" , "Global_intensity" , "Sub_metering_1" , "Sub_metering_2" , "Sub_metering_3") ) # creating new timestamp from Date and Time columns data.set[, c("time.stamp", "Date", "Time") := { tmp.time <- as.character(paste(as.Date(Date, "%d/%m/%Y"), Time, sep = ' ')); tmp.time <- as.POSIXct(strptime(tmp.time, "%Y-%m-%d %H:%M:%S")); list(tmp.time,NULL,NULL) }] # look through summary str(data.set) summary(data.set) # set international dates and time lct <- Sys.getlocale("LC_TIME") lct Sys.setlocale("LC_TIME", "C") # open device png(filename = "plot4.png" , width = 480 , height = 480 , units = "px" , pointsize = 12 , bg = "transparent" ) # setting multiple plots par(mfrow = c(2, 2)) # create plot for Global_active_power plot(data.set[, time.stamp] , data.set[, Global_active_power] , type = "l" , main = "" , xlab = "" , ylab = "Global Active Power" ) # create plot for Voltage plot(data.set[, time.stamp] , data.set[, Voltage] , type = "l" , main = "" , xlab = "datetime" , ylab = "Voltage" ) # create plot Sub_metering_1, Sub_metering_2 and Sub_metering_3 plot(data.set[, time.stamp] , data.set[, Sub_metering_1] , col = 'black' , type = "l" , main = "" , xlab = "" , ylab = "Energy sub metering" ) lines(data.set[, time.stamp] , data.set[, Sub_metering_2] , col = 'red' ) lines(data.set[, time.stamp] , data.set[, Sub_metering_3] , col = 'blue' ) legend("topright" , lty = 1 , col = c("black", "red", "blue") , legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3") , bty = "n" ) # create plot for Global_reactive_power plot(data.set[, time.stamp] , data.set[, Global_reactive_power] , type = "l" , main = "" , xlab = "datetime" , ylab = "Global_reactive_power" ) # close device dev.off() # get back to orycinal datetime settings Sys.setlocale("LC_TIME", lct)
d1a4b21c7586e85ec87ae1a82ddf72a371bd1a48
[ "R" ]
1
R
yabwon/ExData_Plotting1
434daa8f722ba22bdaa0a913ef8dc6d1d17b7597
e20a121cfbefa538e20d8aa5cb056b3b965a7178
refs/heads/master
<file_sep>// @flow /** * Verify if `hash` is a git-rev sha1 hash. */ const isGitRev = (hash: string): boolean => /^[0-9a-f]{7,40}$/i.test(hash) export default isGitRev <file_sep># is-git-rev [![Generated with nod](https://img.shields.io/badge/generator-nod-2196F3.svg?style=flat-square)](https://github.com/diegohaz/nod) [![NPM version](https://img.shields.io/npm/v/is-git-rev.svg?style=flat-square)](https://npmjs.org/package/is-git-rev) [![Build Status](https://img.shields.io/travis/diegohaz/is-git-rev/master.svg?style=flat-square)](https://travis-ci.org/diegohaz/is-git-rev) [![Coverage Status](https://img.shields.io/codecov/c/github/diegohaz/is-git-rev/master.svg?style=flat-square)](https://codecov.io/gh/diegohaz/is-git-rev/branch/master) Verify if a string is a git-rev hash ## Install $ npm install --save is-git-rev ## Usage ```js import isGitRev from 'is-git-rev' isGitRev('f9b9150f71db48a49a2e3de5f817cec120334d81') ``` ## API <!-- Generated by documentation.js. Update this documentation by updating the source code. --> ### isGitRev Verify if `hash` is a git-rev sha1 hash. **Parameters** - `hash` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** Returns **[boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** ## License MIT © [<NAME>](https://github.com/diegohaz)
0aaca0442ecdd741e1208ec8a90565e8a927a629
[ "JavaScript", "Markdown" ]
2
JavaScript
diegohaz/is-git-rev
1f0e901959e5c6eac53855ca0023419e9a55d358
543dae5c26087c22cfb4529db8ad4cd62e1910ba
refs/heads/master
<repo_name>zebbyzeb/csharpFundamentals<file_sep>/Grades/Grades/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Speech.Synthesis; using System.Text; using System.Threading.Tasks; namespace Grades { class Program { static void Main(string[] args) { //SpeechSynthesizer synth = new SpeechSynthesizer(); //synth.Speak("hello"); //GradeBook book = new GradeBook(); IGradeTracker book = new ThrowAwayGradeBook(); book.NameChanged += new NameChangedDelegate(OnNameChanged); //use += to point delegates to many methods. / add subscription // book.NameChanged += new NameChangedDelegate(OnNameChanged2); // book.NameChanged -= new NameChangedDelegate(OnNameChanged2); //-= remove subscription // book.NameChanged = null; //this will point the delegate to null. removing subsriptions of all the above methods. //use events to prevent this. book.Name = "This is my book"; book.Name = null; //this is not set because of the logic on the setter for Name. book.AddGrade(91); book.AddGrade(89.5f); foreach (float grade in book) { Console.WriteLine(grade); } Console.WriteLine(book.Name); GradeStatistics stats = book.ComputeStatistics(); //Console.WriteLine(stats.HighestGrade); // WriteResult("Avg grade is", stats.AverageGrade,2,3,4,5); WriteResult("Highest grade is", (int)stats.HighestGrade); } /* static void OnNameChanged(string existingName, string newName) { Console.WriteLine("Name changed from "+existingName+" to "+newName); } */ static void OnNameChanged(object sender, NameChangedEventArgs args) { Console.WriteLine("Name changed from " + args.ExistingName + " to " + args.NewName); } static void OnNameChanged2(string existingName, string newName) { Console.WriteLine("***"); } static void WriteResult(string description, float result) { Console.WriteLine(description + ": " + result); } static void WriteResult(string description, params float[] result) { foreach (float res in result) { Console.WriteLine(description + ": " + res); } } static void WriteResult(string description, int result) { Console.WriteLine(description + ": " + result); } } } <file_sep>/Grades/Grades/ThrowAwayGradeBook.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Grades { public class ThrowAwayGradeBook : GradeBook { public override GradeStatistics ComputeStatistics() { float lowestGrade = grades.Min(); grades.Remove(lowestGrade); return base.ComputeStatistics(); } } } <file_sep>/Grades/Grades.Tests/Types/ReferenceTypes.cs using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Grades; namespace Grades.Tests.Types { [TestClass] public class ReferenceTypes { [TestMethod] public void RefernceTypes() { GradeBook book1 = new GradeBook(); GradeBook book2 = book1; GiveBookAName(book2); Assert.AreEqual("A Gradebook",book2.Name); } public void GiveBookAName(GradeBook book) { book = new GradeBook(); book.Name = "A Gradebook"; } } }
8a0809ff76b418a723b56f1a61c0d4e8409bd613
[ "C#" ]
3
C#
zebbyzeb/csharpFundamentals
ec85675641b4ac5d15e778eb008c6ecd765da84c
3a14132866bb2eb087e733406042fd9bd92b4898
refs/heads/master
<repo_name>Zachladnykas/Testing<file_sep>/git.py def function(): return None
3787c435b33cf9b5d56e17457e462e27f99914e7
[ "Python" ]
1
Python
Zachladnykas/Testing
55cbaf53ee33ac4a3e37f49db63d7e22abe54758
9ff317e536d08320a9bcece79ecb2a0b1a6df6b0
refs/heads/master
<file_sep>import requests import random import json import sys import serial ser = serial.Serial( port='/dev/ttyACM0', baudrate=9600 ) test = { "hub_id": 1, "key": "9783653f691bf86982a2d3f19442ef99", "secret": "<KEY>", "sensor_data": [{ "id": 1, "data": random.randint(0,10) }, { "id": 2, "data": random.randint(0,10) }, { "id": 3, "data": random.randint(0,10) }, { "id": 4, "data": random.randint(0,10) }] } def get_push_data(a, b, c, d): return { "hub_id": 1, "key": "bf327001430f40999e0a493138797d4c", "secret": "6a89c9aff18f76c5e29a3d11464f985f", "sensor_data": [{ "id": 1, "data": a }, { "id": 2, "data": b }, { "id": 3, "data": c }, { "id": 4, "data": d }] } def push(data): #r = requests.post("{}/push/{}/".format("http://hygiea.pd.io", data['hub_id']), data=json.dumps(data), ) r = requests.post("{}/push/{}/".format("http://demo.hygiea.tech", data['hub_id']), data=json.dumps(data), ) r.raise_for_status() if __name__ == "__main__": count = 0 new_string = False new_data= False a=b=c=d=0 #push(get_push_data(a,b,c,5)) #sys.exit(1) while 1: a=102 b=52 c=202 push(get_push_data(a,b,c,5)) <file_sep>import requests import random import json import sys import serial import time import datetime import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText fromaddr = "<EMAIL>" toaddr = "<EMAIL>" #msg['Subject'] = "Status email" ser = serial.Serial( port='/dev/ttyACM0', baudrate=115200, timeout=15 ) test = { "hub_id": 1, "key": "9783653f691bf86982a2d3f19442ef99", "secret": "<KEY>", "sensor_data": [{ "id": 1, "data": random.randint(0,10) }, { "id": 2, "data": random.randint(0,10) }, { "id": 3, "data": random.randint(0,10) }, { "id": 4, "data": random.randint(0,10) }] } def get_push_data(a, b, c, d): return { "hub_id": 1, "key": "bf327001430f40999e0a493138797d4c", "secret": "6a89c9aff18f76c5e29a3d11464f985f", "sensor_data": [{ "id": 1, "data": a }, { "id": 2, "data": b }, { "id": 3, "data": c }, { "id": 4, "data": d }] } dateString = '%Y/%m/%d %H:%M:%S' def push(data): #r = requests.post("{}/push/{}/".format("http://hygiea.pd.io", data['hub_id']), data=json.dumps(data), ) #r = requests.post("{}/push/{}/".format("http://demo.hygiea.tech", data['hub_id']), data=json.dumps(data), ) #r.raise_for_status() pass if __name__ == "__main__": count = 0 new_string = False new_data= False a=b=c=d=0 #push(get_push_data(a,b,c,5)) #sys.exit(1) b = 1 c = 2 d = 20 while 1: a=10 # b=5 # c=20 # push(get_push_data(a,b,c,5)) print("printed in a file") ser.flushInput() response = ser.readline() #int(response) print "read_data", response #,type(response) print len(response) time.sleep(0.1) if len(response)==12 or len(response)==13: new_string=True if new_string: if int((response[0:1].strip()).rstrip()) == 2: a = int((response[9:11].strip()).rstrip()) print "A" ,a #with open('/home/pi/gdrivefs/log_2.txt','a') as f: # print >> f, datetime.datetime.now().strftime(dateString) # f.write((response[0:1].strip()).rstrip()) # f.write(" ") # f.write((response[3:7].strip()).rstrip()) # f.write(" ") # f.write((response[9:11].strip()).rstrip()) # f.write("\n") #f.close() elif int((response[0:1].strip()).rstrip()) == 3: b = int((response[9:11].strip()).rstrip()) print "B",b #with open('/home/pi/gdrivefs/log_3.txt','wa') as f: # print >> f, datetime.datetime.now().strftime(dateString) # f.write((response[0:1].strip()).rstrip()) # f.write(" ") # f.write((response[3:7].strip()).rstrip()) # f.write(" ") # f.write((response[9:11].strip()).rstrip()) # f.write("\n") #f.close() msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = "Status email from " + (response[0:1].strip()).rstrip() body = datetime.datetime.now().strftime(dateString) + " NodeID : " + (response[0:1].strip()).rstrip() + " Battery : " + (response[3:7].strip()).rstrip() + " Level : " + (response[9:11].strip()).rstrip() msg.attach(MIMEText(body, 'plain')) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(fromaddr, "hygiea1234") text = msg.as_string() server.sendmail(fromaddr, toaddr, text) server.quit() print("email sent") # b = b*2 if b*2 < 10 else 1 c = 2+c if 2+c <10 else 1 d = d/3 if d/3>1 else 9 print type(response) # import IPython # IPython.embed() print "len ", a,b push(get_push_data(a,b,c,d)) count =0 new_string=False new_data=False # print new_string,count,new_data ser.close() <file_sep>import requests import random import json import sys import serial ser = serial.Serial( port='/dev/ttyACM0', baudrate=9600 ) test = { "hub_id": 1, "key": "9783653f691bf86982a2d3f19442ef99", "secret": "<KEY>", "sensor_data": [{ "id": 1, "data": random.randint(0,10) }, { "id": 2, "data": random.randint(0,10) }, { "id": 3, "data": random.randint(0,10) }, { "id": 4, "data": random.randint(0,10) }] } def get_push_data(a, b, c, d): return { "hub_id": 1, "key": "bf327001430f40999e0a493138797d4c", "secret": "6a89c9aff18f76c5e29a3d11464f985f", "sensor_data": [{ "id": 1, "data": a }, { "id": 2, "data": b }, { "id": 3, "data": c }, { "id": 4, "data": d }] } def push(data): #r = requests.post("{}/push/{}/".format("http://hygiea.pd.io", data['hub_id']), data=json.dumps(data), ) r = requests.post("{}/push/{}/".format("http://demo.hygiea.tech", data['hub_id']), data=json.dumps(data), ) r.raise_for_status() if __name__ == "__main__": count = 0 new_string = False new_data= False a=b=c=d=0 #push(get_push_data(a,b,c,5)) #sys.exit(1) while 1: # a=10 # b=5 # c=20 # push(get_push_data(a,b,c,5)) response = ser.readline() #int(response) print "read_data", response#,type(response) if response == str("7E\r\n"): new_string=True if new_string: count=count+1 if count==12: new_data = True sensor=response if new_data: if count==16: if sensor==str("BC\r\n"): #pdp a=response print "a",int((a.strip()).rstrip(),16) a=int((a.strip()).rstrip(),16) if sensor==str("4A\r\n"): #pdv b=response print "b",int((b.strip()).rstrip(),16) b=int((b.strip()).rstrip(),16) if sensor==str("4C\r\n"): #ss c=response print "c",int((c.strip()).rstrip(),16) c=int((c.strip()).rstrip(),16) print a,b,c push(get_push_data(a,b,c,5)) count =0 new_string=False new_data=False # print new_string,count,new_data ser.close()
9c0a160f5b0ea938f7dd88b2105b9e011d78f05f
[ "Python" ]
3
Python
hygieatech/rpi_gateway
e9416024c8f0f270cb0b60dd4cfc393e58d1aaef
3ce4a8f7c09d549a0b54357c8cb2827d5f3aa9dc
refs/heads/master
<file_sep> <h1>发布新品</h1> <br> <div class="products form"> <div id="step-holder"> <div class="step-no">1</div> <div class="step-dark-left"> <a href="">Add product details</a> </div> <div class="step-dark-right">&nbsp;</div> <div class="step-no-off">2</div> <div class="step-light-left">Select related products</div> <div class="step-light-right">&nbsp;</div> <div class="step-no-off">3</div> <div class="step-light-left">Preview</div> <div class="step-light-round">&nbsp;</div> <div class="clear"></div> </div> <?php echo $this->Form->create('Product');?> <?php echo $this->Form->input('name',array('class'=>'inp-form','label'=>'产品名称:')); echo $this->Form->input('product_size',array('class'=>'inp-form','label'=>"产品尺寸:")); echo $this->Form->input('product_power',array('class'=>'inp-form','label'=>"功率:")); echo $this->Form->input('product_voltage',array('class'=>'inp-form','label'=>"电压:")); echo $this->Form->input('product_bulbnumber',array('class'=>'inp-form','label'=>"灯泡个数:")); //echo $this->Form->input('is_established'); echo $this->Form->input('store_id',array('class'=>'styledselect_form_1','label'=>"商店:")); echo $this->Form->input('category_id',array('class'=>'styledselect_form_1','label'=>"产品目录:")); echo $this->Form->input('order',array('class'=>'inp-form','label'=>"商店:")); ?> <input type="submit" class="form-submit" value="下一步"/> </div> <!--- <div class="actions"> <h3><?php echo __('Actions'); ?></h3> <ul> <li><?php echo $this->Html->link(__('List Products'), array('action' => 'index'));?></li> <li><?php echo $this->Html->link(__('List Stores'), array('controller' => 'stores', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Store'), array('controller' => 'stores', 'action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Categories'), array('controller' => 'categories', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Category'), array('controller' => 'categories', 'action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Product Details'), array('controller' => 'product_details', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Product Detail'), array('controller' => 'product_details', 'action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Product Srcs'), array('controller' => 'product_srcs', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Product Src'), array('controller' => 'product_srcs', 'action' => 'add')); ?> </li> </ul> </div> ---!><file_sep> <div class="stores form"> <div id="related-activities" style="float:right"> <div id="related-act-top"> <img height="43" width="271" alt="" src="../images/forms/header_related_act.gif"> </div> <div id="related-act-bottom"> <div id="related-act-inner"> <ul> <li><?php echo $this->Html->link(__('List Stores'), array('action' => 'index'));?></li> <li><?php echo $this->Html->link(__('List Markets'), array('controller' => 'markets', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Market'), array('controller' => 'markets', 'action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Products'), array('controller' => 'products', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Product'), array('controller' => 'products', 'action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Store Srcs'), array('controller' => 'store_srcs', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Store Src'), array('controller' => 'store_srcs', 'action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Users'), array('controller' => 'users', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New User'), array('controller' => 'users', 'action' => 'add')); ?> </li> </ul> <div class="clear"></div> </div> </div> </div> <?php echo $this->Form->create('Store');?> <?php echo $this->Form->input('market_id',array('label'=>'市场:')); echo $this->Form->input('name',array('class'=>'inp-form','label'=>'商铺名称:')); echo $this->Form->input('store_url',array('class'=>'inp-form','label'=>'商铺URL:')); echo $this->Form->input('store_address',array('class'=>'inp-form','label'=>'商铺地址:')); echo $this->Form->input('store_boss',array('class'=>'inp-form','label'=>'商铺老板:')); echo $this->Form->input('store_mobile',array('class'=>'inp-form','label'=>'联系方式:')); echo $this->Form->input('description',array('class'=>'inp-form','label'=>'描述:')); echo $this->Form->input('service',array('class'=>'inp-form','label'=>'商铺服务:')); echo $this->Form->input('src',array('id'=>'file_upload','label'=>'商家图片:','type'=>'file')); ?> <?php echo $this->Form->end(__('Submit'));?> </div> <?php echo $this->Html->Script("uploadify/swfobject"); echo $this->Html->Script("uploadify/jquery.uploadify.v2.1.4.min"); ?> <script type="text/javascript"> var count=1; $(document).ready(function(){ $('#file_upload').uploadify({ 'uploader' :'<?php echo $this->Html->url('/app/webroot/uploadify/uploadify.swf');?>', 'script' :'<?php echo $this->Html->url('/app/webroot/uploadify/uploadify.php');?>', 'cancelImg':'<?php echo $this->Html->url('/app/webroot/uploadify/cancel.png');?>', 'folder' :'<?php //echo $this->Html->url("/app/webroot/$dir/");?>', 'multi' :true, 'auto' :false, 'onSelect' :function(e, queueId, fileObj){ $child=$("<input type='hidden' value="+fileObj.name+" name=data[ProductSrc][src1]["+count+"]/>") $parent=$("#file_upload"); $parent.append($child); count++; } }); }); function uploadify() { $('#file_upload').uploadifyUpload(); } </script><file_sep><div class="markets form"> <h2><?php echo __('Add Market'); ?></h2> <?php echo $this->Form->create('Market');?> <?php echo $this->Form->input('name',array('class'=>'inp-form','label'=>'市场名称:')); echo $this->Form->input('address',array('class'=>'inp-form','label'=>'地址:')); ?> </fieldset> <?php echo $this->Form->end(__('Submit'));?> </div> <div class="actions"> <h3><?php echo __('Actions'); ?></h3> <ul> <li><?php echo $this->Html->link(__('List Markets'), array('action' => 'index'));?></li> <li><?php echo $this->Html->link(__('List Stores'), array('controller' => 'stores', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Store'), array('controller' => 'stores', 'action' => 'add')); ?> </li> </ul> </div> <file_sep><?php App::uses('AppController', 'Controller'); /** * Home Controller * * @property User $User */ class HomeController extends AppController { var $layout = null; /** * index method * * @return void */ public function index() { $this->set('home', 'hello world'); } } <file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <?php echo $this->Html->css('front/home'); ?> <title>3D灯具网上商城</title> </head> <body> <div class="main"> <!-- top --> <div class="top"> <div class="login">欢迎来到3D灯具城 &nbsp; &nbsp;[<a href="#"> 请登录 </a>] &nbsp; &nbsp;[<a href="#"> 注册 </a>]</div> <div class="help"><a href="#">收藏本页</a> &nbsp; &nbsp;<a href="#">新手帮助</a></div> <div class="clearit"></div> <div class="logo"> <?php echo $this->Html->image('front/logo.gif', array('alt' => '3D灯具网上商城'));?> <?php echo $this->Html->image('front/logo2.gif', array('alt' => '3D灯具网上商城', 'width'=>'218', 'height'=>'71'));?> </div> <div class="search"><select name="" class="search_select"> <option>商品</option> <option>商铺</option> </select> <input type="text" name="textfield" class="search_txt"/><input type="button" class="search_button" value=" "/></div> </div> <!-- end of top --> <!-- nav --> <div class="nav"> <ul> <li class="navli01"> <?php echo $this->Html->image('front/nav1.gif', array('alt' => '灯具', 'border'=>0, 'width'=>'144', 'height'=>'53'));?> </li> <li class="navli02"></li> <li class="navli01"> <?php echo $this->Html->image('front/nav2.gif', array('alt' => '灯具', 'border'=>0, 'width'=>'144', 'height'=>'53'));?> </li> <li class="navli02"></li> <li class="navli01"> <?php echo $this->Html->image('front/nav3.gif', array('alt' => '灯具', 'border'=>0, 'width'=>'144', 'height'=>'53'));?> </li> <li class="navli02"></li> <li class="navli01"> <?php echo $this->Html->image('front/nav4.gif', array('alt' => '灯具', 'border'=>0, 'width'=>'144', 'height'=>'53'));?> </li> <li class="navli02"></li> <li class="navli01"> <?php echo $this->Html->image('front/nav5.gif', array('alt' => '灯具', 'border'=>0, 'width'=>'144', 'height'=>'53'));?> </li> <li class="navli03"></li> <li class="navli04"> <?php echo $this->Html->image('front/side_nav1.gif', array('alt' => '灯具', 'border'=>0));?> </li> <li class="navli04"> <?php echo $this->Html->image('front/side_nav2.gif', array('alt' => '灯具', 'border'=>0));?> </li> <li class="navli04"> <?php echo $this->Html->image('front/side_nav3.gif', array('alt' => '灯具', 'border'=>0));?> </li> </ul> </div> <!-- end of nav --> <!-- content --> <div class="content"> <!-- content left --> <div class="content_left"> <div class="flash_top"> <div class="flash_top_left"></div> <div class="flash_top_right"></div> </div> <div class="flash"></div> <div class="space"></div> <div class="content_left_ye"> <div class="content_left_ye_title">新品上市</div> <div class="content_left_ye_titleno">促销活动</div> <div class="content_left_ye_more"><ul class="Recommended_shops_cat"> <li>吊灯 | 台灯 | 光源 | 开关电器</li> </ul></div> <div class="clearit"></div> <div class="content_left_ye_titleye"></div> <div class="content_left_ye_con"> <div class="pic_01"> <?php echo $this->Html->image('front/demo.gif', array('alt' => '灯具'));?> </div> <div class="pic_01"> <?php echo $this->Html->image('front/demo.gif', array('alt' => '灯具'));?> </div> <div class="pic_01"> <?php echo $this->Html->image('front/demo.gif', array('alt' => '灯具'));?> </div> <div class="pic_01"> <?php echo $this->Html->image('front/demo.gif', array('alt' => '灯具'));?> </div> </div> </div> <div class="space"></div> <div class="content_left_ye"> <div class="content_left_ye_title">新品推荐</div> <div class="content_left_ye_titleno">商铺推荐</div> <div class="content_left_ye_titlebl"></div> <div class="content_left_ye_titleno">商场推荐</div> <div class="content_left_ye_more"><ul class="Recommended_shops_cat"> <li>吊灯 | 台灯 | 光源 | 开关电器</li> </ul></div> <div class="clearit"></div> <div class="content_left_ye_titleye"></div> <div class="content_left_ye_con_b"> <div class="content_left_ye_con_b_left"> <div class="pic_02"> <?php echo $this->Html->image('front/demo.gif', array('alt' => '灯具', 'width'=>'241', 'height'=>'318'));?> </div> <div class="content_left_ye_con_b_left_tit">DTL 灯饰 吊灯</div> <div style="float:left"> <table width="252px" style="line-height:24px;"> <tr> <td width="52">品牌:</td> <td>DTL 灯饰</td> </tr> <tr> <td width="52">价格:</td> <td>RMB 480</td> </tr> <tr> <td width="52">推荐理由:</td> <td>带回家诶哦粉红色哦好</td> </tr> </table> </div> </div> <div class="pic03"></div> <div class="pic03"></div> <div class="pic03"></div> <div class="pic03"></div> <div class="pic03"></div> <div class="pic03"></div> </div> </div> <div class="space"></div> <div class="content_left_ye"> <div class="content_left_ye_title">灯具导购</div> <div class="content_left_ye_titleno"> 优秀设计师</div> <div class="content_left_ye_titlebl"></div> <div class="content_left_ye_titleno">装饰公司</div> <div class="clearit"></div> <div class="content_left_ye_titleye"></div> <div class="content_left_ye_con_bb"> <div class="Lighting_articles"> <div class="Lighting_articles_tit">灯具测评</div> <div class="Lighting_articles_more">更多</div> <div class="clearit"></div> <ul class="ulLighting_articles"> <li>小编电灯:3D灯具网地图灯具城查询上线查询上线查询</li> <li>小编电灯:3D灯具网地图灯具城查询上线啦!</li> <li>小编电灯:3D灯具网地图灯具城查询上线查询上线啦!</li> <li>小编电灯:3D灯具网地图灯具城查查询上线询上线啦!</li> <li>小编电灯:3D灯具网地图灯具城查询上线查询上线查询</li> </ul> </div> <div class="Lighting_articles01"> <div class="Lighting_articles_tit">灯具测评</div> <div class="Lighting_articles_more">更多</div> <div class="clearit"></div> <ul class="ulLighting_articles"> <li>小编电灯:3D灯具网地图灯具城查询上线查询上线查询</li> <li>小编电灯:3D灯具网地图灯具城查询上线啦!</li> <li>小编电灯:3D灯具网地图灯具城查询上线查询上线啦!</li> <li>小编电灯:3D灯具网地图灯具城查查询上线询上线啦!</li> <li>小编电灯:3D灯具网地图灯具城查询上线查询上线查询</li> </ul></div> <div class="clearit"></div> <div class="Lighting_articles"> <div class="Lighting_articles_tit">灯具测评</div> <div class="Lighting_articles_more">更多</div> <div class="clearit"></div> <ul class="ulLighting_articles"> <li>小编电灯:3D灯具网地图灯具城查询上线查询上线</li> <li>小编电灯:3D灯具网地图灯具城查询上线啦!</li> <li>小编电灯:3D灯具网地图灯具城查询上线查询上线啦!</li> <li>小编电灯:3D灯具网地图灯具城查查询上线询上线啦!</li> <li>小编电灯:3D灯具网地图灯具城查询上线查询上线查询</li> </ul> </div> <div class="Lighting_articles01"> <div class="Lighting_articles_tit">灯具测评</div> <div class="Lighting_articles_more">更多</div> <div class="clearit"></div> <ul class="ulLighting_articles"> <li>小编电灯:3D灯具网地图灯具城查询上线查询上线查询</li> <li>小编电灯:3D灯具网地图灯具城查询上线啦!</li> <li>小编电灯:3D灯具网地图灯具城查询上线查询上线啦!</li> <li>小编电灯:3D灯具网地图灯具城查查询上线询上线啦!</li> <li>小编电灯:3D灯具网地图灯具城查询上线查询上线查询</li> </ul></div> </div> </div> </div> <!-- end of content left --> <!-- content right --> <div class="content_right"> <div class="broad"> <div class="broad_top"></div> <div class="broad_title">网站公告</div> <div class="board_content"> <ul class="ulblack"> <li class="linew">3D灯具网站全新上线啦<?php echo $this->Html->image('front/new.gif', array('alt' => '新'));?></li> <li>3D灯具网站全新上线啦</li> <li>3D灯具网站全新上线啦</li> <li>3D灯具网站全新上线啦</li> <li>3D灯具网站全新上线啦</li> <li>3D灯具网站全新上线啦</li> <li>3D灯具网站全新上线啦</li> </ul> </div> </div> <div class="clearit"></div> <div class="gui"> <div class="guide01"><?php echo $this->Html->image('front/func1.gif', array('alt' => '商家入驻', 'width'=>'23', 'height'=>'21'));?>商家入驻</div> <div class="guide01"><?php echo $this->Html->image('front/func2.gif', array('alt' => '信誉认证', 'width'=>'23', 'height'=>'21'));?>信誉认证</div> <div class="guide01"><?php echo $this->Html->image('front/func3.gif', array('alt' => '三维展示', 'width'=>'23', 'height'=>'21'));?>三维展示</div> <div class="guide01"><?php echo $this->Html->image('front/func3.gif', array('alt' => '地图', 'width'=>'23', 'height'=>'21'));?>地图</div> </div> <div class="space_s"></div> <div class="style_title">风格分类</div> <div class="style_gen01">装修风格</div> <div class="space_ss"></div> <div class="style_gen01">适用面积</div> <div class="style_gen02">适用场合</div> <div class="space_ss"></div> <div class="style_gen02">光源类型</div> <div class="style_gen03">灯架材质</div> <div class="space_ss"></div> <div class="style_gen03">灯罩材质</div> <div class="style_gen04">产品类型</div> <div class="space_s"></div> <div class="style_title">精品推荐</div> <div class="bou"> <div class="pic04"></div> <div class="pic05"></div> </div> <div class="space_s"></div> <div class="style_title">装修日记·照片篇</div> <div class="notic_list"> <div class="notic_listpic"> <?php echo $this->Html->image('front/pic.gif', array('alt' => '灯具', 'width'=>'120', 'height'=>'90'));?> </div> <div class="notic_listtxtbig">松下吊灯</div> <div class="notic_listnumb">dasdd大大声的a</div> <div class="notic_listnumb">散打散打的繁荣若干</div> <div class="notic_listnumb">散打散打的繁荣若干</div> <div class="notic_listnumb">散打散打的繁荣若干</div> <div class="notic_listnumb">散打散打的繁荣若干</div> <div class="notic_listnumb">散打散打的繁荣若干</div> <div class="notic_listnumb">散打散打的繁荣若干</div> </div> </div> <!-- end of content right --> </div> <div class="clearit"></div> <div class="space"></div> <!-- end of content --> <!-- footer --> <div class="Footer"> <div class="Footer_top"></div> <div class="Footer_con"> <div class="Footer_contop"> <div class="Footer_contop_pic">购物指南</div> <div class="Footer_contop_txt">·购物流程</div> <div class="Footer_contop_txt">·购物流程</div> <div class="Footer_contop_txt">·购物流程</div> <div class="Footer_contop_txt">·购物流程</div> <div class="Footer_contop_txt">·购物流程</div> <div class="Footer_contop_txt">·购物流程</div> </div> <div class="Footer_contop"> <div class="Footer_contop_pic01">购物指南</div> <div class="Footer_contop_txt">·购物流程</div> <div class="Footer_contop_txt">·购物流程</div> <div class="Footer_contop_txt">·购物流程</div> <div class="Footer_contop_txt">·购物流程</div> <div class="Footer_contop_txt">·购物流程</div> <div class="Footer_contop_txt">·购物流程</div> </div> <div class="Footer_contop"> <div class="Footer_contop_pic02">购物指南</div> <div class="Footer_contop_txt">·购物流程</div> <div class="Footer_contop_txt">·购物流程</div> <div class="Footer_contop_txt">·购物流程</div> <div class="Footer_contop_txt">·购物流程</div> <div class="Footer_contop_txt">·购物流程</div> <div class="Footer_contop_txt">·购物流程</div> </div> <div class="Footer_contop"> <div class="Footer_contop_pic03">购物指南</div> <div class="Footer_contop_txt">·购物流程</div> <div class="Footer_contop_txt">·购物流程</div> <div class="Footer_contop_txt">·购物流程</div> <div class="Footer_contop_txt">·购物流程</div> <div class="Footer_contop_txt">·购物流程</div> <div class="Footer_contop_txt">·购物流程</div> </div> <div class="Footer_conbut"> <table width="906px" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="center"> <?php echo $this->Html->image('front/bottom1.gif', array('alt' => '灯具'));?> </td> <td align="center"> <?php echo $this->Html->image('front/bottom2.gif', array('alt' => '灯具'));?> </td> <td align="center"> <?php echo $this->Html->image('front/bottom3.gif', array('alt' => '灯具'));?> </td> </tr> </table> </div> </div> </div> <!-- end of footer --> <!-- bottom --> <div class="bottom"> 关于我们 | 联系我们 | 关于我们 | 联系我们 | 关于我们 | 联系我们 | 关于我们<br /> 备案许可证:<br /> copyright@ 版权所有<br /> <br /> <?php echo $this->Html->image('front/bottom4.gif', array('alt' => '灯具'));?> &nbsp; <?php echo $this->Html->image('front/bottom5.gif', array('alt' => '灯具'));?> </div> <!-- end of bottom --> </div> </body> </html> <file_sep><div class="products view"> <h2><?php echo __('Product');?></h2> <dl> <dt><?php echo __('Id'); ?></dt> <dd> <?php echo h($product['Product']['id']); ?> &nbsp; </dd> <dt><?php echo __('Name'); ?></dt> <dd> <?php echo h($product['Product']['name']); ?> &nbsp; </dd> <dt><?php echo __('Product Size'); ?></dt> <dd> <?php echo h($product['Product']['product_size']); ?> &nbsp; </dd> <dt><?php echo __('Product Power'); ?></dt> <dd> <?php echo h($product['Product']['product_power']); ?> &nbsp; </dd> <dt><?php echo __('Product Voltage'); ?></dt> <dd> <?php echo h($product['Product']['product_voltage']); ?> &nbsp; </dd> <dt><?php echo __('Product Bulbnumber'); ?></dt> <dd> <?php echo h($product['Product']['product_bulbnumber']); ?> &nbsp; </dd> <dt><?php echo __('Created'); ?></dt> <dd> <?php echo h($product['Product']['created']); ?> &nbsp; </dd> <dt><?php echo __('Modified'); ?></dt> <dd> <?php echo h($product['Product']['modified']); ?> &nbsp; </dd> <dt><?php echo __('Is Established'); ?></dt> <dd> <?php echo h($product['Product']['is_established']); ?> &nbsp; </dd> <dt><?php echo __('Store'); ?></dt> <dd> <?php echo $this->Html->link($product['Store']['name'], array('controller' => 'stores', 'action' => 'view', $product['Store']['id'])); ?> &nbsp; </dd> <dt><?php echo __('Category'); ?></dt> <dd> <?php echo $this->Html->link($product['Category']['name'], array('controller' => 'categories', 'action' => 'view', $product['Category']['id'])); ?> &nbsp; </dd> <dt><?php echo __('Order'); ?></dt> <dd> <?php echo h($product['Product']['order']); ?> &nbsp; </dd> </dl> </div> <div class="actions"> <h3><?php echo __('Actions'); ?></h3> <ul> <li><?php echo $this->Html->link(__('Edit Product'), array('action' => 'edit', $product['Product']['id'])); ?> </li> <li><?php echo $this->Form->postLink(__('Delete Product'), array('action' => 'delete', $product['Product']['id']), null, __('Are you sure you want to delete # %s?', $product['Product']['id'])); ?> </li> <li><?php echo $this->Html->link(__('List Products'), array('action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Product'), array('action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Stores'), array('controller' => 'stores', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Store'), array('controller' => 'stores', 'action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Categories'), array('controller' => 'categories', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Category'), array('controller' => 'categories', 'action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Product Details'), array('controller' => 'product_details', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Product Detail'), array('controller' => 'product_details', 'action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Product Srcs'), array('controller' => 'product_srcs', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Product Src'), array('controller' => 'product_srcs', 'action' => 'add')); ?> </li> </ul> </div> <div class="related"> <h3><?php echo __('Related Product Details');?></h3> <?php if (!empty($product['ProductDetail'])):?> <table cellpadding = "0" cellspacing = "0"> <tr> <th><?php echo __('Id'); ?></th> <th><?php echo __('Product Id'); ?></th> <th><?php echo __('Detail Id'); ?></th> <th class="actions"><?php echo __('Actions');?></th> </tr> <?php $i = 0; foreach ($product['ProductDetail'] as $productDetail): ?> <tr> <td><?php echo $productDetail['id'];?></td> <td><?php echo $productDetail['product_id'];?></td> <td><?php echo $productDetail['detail_id'];?></td> <td class="actions"> <?php echo $this->Html->link(__('View'), array('controller' => 'product_details', 'action' => 'view', $productDetail['id'])); ?> <?php echo $this->Html->link(__('Edit'), array('controller' => 'product_details', 'action' => 'edit', $productDetail['id'])); ?> <?php echo $this->Form->postLink(__('Delete'), array('controller' => 'product_details', 'action' => 'delete', $productDetail['id']), null, __('Are you sure you want to delete # %s?', $productDetail['id'])); ?> </td> </tr> <?php endforeach; ?> </table> <?php endif; ?> <div class="actions"> <ul> <li><?php echo $this->Html->link(__('New Product Detail'), array('controller' => 'product_details', 'action' => 'add'));?> </li> </ul> </div> </div> <div class="related"> <h3><?php echo __('Related Product Srcs');?></h3> <?php if (!empty($product['ProductSrc'])):?> <table cellpadding = "0" cellspacing = "0"> <tr> <th><?php echo __('Id'); ?></th> <th><?php echo __('Product Id'); ?></th> <th><?php echo __('Position Id'); ?></th> <th><?php echo __('Src'); ?></th> <th><?php echo __('Created'); ?></th> <th><?php echo __('Modified'); ?></th> <th class="actions"><?php echo __('Actions');?></th> </tr> <?php $i = 0; foreach ($product['ProductSrc'] as $productSrc): ?> <tr> <td><?php echo $productSrc['id'];?></td> <td><?php echo $productSrc['product_id'];?></td> <td><?php echo $productSrc['position_id'];?></td> <td><?php echo $productSrc['src'];?></td> <td><?php echo $productSrc['created'];?></td> <td><?php echo $productSrc['modified'];?></td> <td class="actions"> <?php echo $this->Html->link(__('View'), array('controller' => 'product_srcs', 'action' => 'view', $productSrc['id'])); ?> <?php echo $this->Html->link(__('Edit'), array('controller' => 'product_srcs', 'action' => 'edit', $productSrc['id'])); ?> <?php echo $this->Form->postLink(__('Delete'), array('controller' => 'product_srcs', 'action' => 'delete', $productSrc['id']), null, __('Are you sure you want to delete # %s?', $productSrc['id'])); ?> </td> </tr> <?php endforeach; ?> </table> <?php endif; ?> <div class="actions"> <ul> <li><?php echo $this->Html->link(__('New Product Src'), array('controller' => 'product_srcs', 'action' => 'add'));?> </li> </ul> </div> </div>
32e9eccbce2638ee0732e7bb9da327ee62fa9e25
[ "PHP" ]
6
PHP
3ddengju/lampkiller_front
b4e0ae984e4b2955d1990b96e218f29df99bba4f
6596ea6516bd7de80d2bdd0832b1e8487935327f
refs/heads/master
<repo_name>LoveLeAnon/VanCoin<file_sep>/build/build.h // No build information available #define BUILD_DATE "2016-01-03 17:20:35 -0800" <file_sep>/README.md VanCoin A cryptocurrency created for learning and experimental purposes < based on Litecoin -> BarCoin -> VanCoin> -SCRYPT -42 Vancoin per block TUTORIAL on how to create your own coin based on VanCoin coming soon vancoin.conf file should be put into your ~/.vancoin directory (on linux) if you run VanCoin/src/vancoind from terminal it will create the directory for you, then it will fail run VanCoin/src/vancoind stop to be sure that it stops then put vancoin.conf into the ~/.vancoin directory (on linux) run src/vancoind or vancoin-qt again it should find and connect to my original node and sync with yours ======================================================================== BUILD: vancoin-qt is built for linux src/bitcoind also built for linux there are makefiles in the src folder for other systems if you want to build (again) for linux: sudo make -f makefile.unix USE_UPNP=- ======================================================================== OPTIONAL: I would recommend setting up a virtual machine on your system to experiment with VanCoin I use VirtualBox for a VM with Ubuntu 14.04 ======================================================================== DEPENDENCIES: once you have ubuntu installed, here are dependencies: sudo apt-get install build-essential libtool autotools-dev automake pkg- config libssl-dev libevent-dev bsdmainutils sudo apt-get install libboost-system-dev libboost-filesystem-dev libboost- chrono-dev libboost-program-options-dev libboost-test-dev libboost- thread-dev sudo apt-get install libboost-all-dev sudo apt-get update sudo apt-get install libdb4.8-dev libdb4.8++-dev apt-get install libqt5gui5 libqt5core5a libqt5dbus5 qttools5-dev qttools5-dev-tools libprotobuf-dev protobuf-compiler sudo apt-get install git sudo apt-get update ======================================================================== OPTIONAL ======================================================================== DESKTOP: sudo apt-get install --no-install-recommends lubuntu-desktop on your VM go to 'Devices' -> 'Insert Guest Additions CD image' ssh to your VM, run sudo /media/<user name>/VboxLinuxAdditions.run <user name> is the account your created on the VM there will me more on it in the upcoming tutorial ========================================================================
645ab8413d4d4f1cb411f15b2ade07123ef8cab4
[ "Markdown", "C" ]
2
C
LoveLeAnon/VanCoin
bbecc05ee5c6ace92f79df1aa59eeb5bd7c019dc
221dadc9850886d46d3590e0a1251b60c63ec4af
refs/heads/master
<file_sep>/* * File: gpuUtilities.h * Author: saifmulla * * Created on 02 October 2013, 12:19 */ #ifndef GPUUTILITIES_H #define GPUUTILITIES_H //#include "gpuPolyFoam.h" extern std::vector<Vec3> ommpositions, ommforces, ofpositions; /** * initialize the openmm system * this function creates list of number of particles in the syste * by retriving relevant information from OF and assigns to OMM * system, additionally initialises * context * system * integrator */ void initialiseOMM(struct poly_solver_t* solver); /** * extract sigma and eps values * to create a string of lennardJones parameters * which could be used as argument to custom non bonded force function */ void extractCoeffParameters(const MOLECULE& mol, const polyIdPairs& plid, std::vector<std::string>& coeffStr); /** * extract OF particles * and correspondingly add to the OMM system */ void extractOFParticles(struct poly_solver_t* solver, CustomNonbondedForce* const nonbonded); /** * extract OF positions and generate and OMM equivalent * array to be passed to OMM system */ int extractOFPostoOMM(std::vector<Vec3>& posinnm, const struct poly_solver_t* sol, const boundBox& bb); /** * setOMMBox * extract information from OF to generate relevant data structures * such as reference units and box information */ void setOMMBox(struct poly_solver_t* solver,const boundBox& bBoxOF,const double dt); /** * add particle to custom non bonded force * by retriving from potential dict list */ void addParticlesToNonBonded(CustomNonbondedForce* const nonbonded, const struct poly_solver_t* solver); /** * set obtained and calculate forces from omm to * openfoam */ int setOFforce(struct poly_solver_t* solver, const std::vector<Vec3>& ommForces); /** * getOMMState * get information from openmm */ void getOMMState(const Context* context,std::vector<Vec3>& statearray); // enum STATES st); #endif /* GPUUTILITIES_H */ <file_sep>**GPU PolyFOAM** ================ This OF solver is coupled with OpenMM GPU library to delegate functionality on GPU. This solver is intended to run polymolecule simulations consisting molecule sizes of N. It's a generic solver which enables running MonoAtomic and polyAtomic simulations. **Functionality available** --------------------------- \* Force Calculation on GPU **Download** ------------ Please follow steps to download Gpu PolyFoam solver. - *change directory to *`cd $FOAM_APP/solvers/discreteMethods/molecularDynamics/ ` - on changing directory run this command `git clone <EMAIL>:saifmulla/gpupolyfoam.git` - if the comand executes successfully you must see a new directory created automantically with the name **gpupolyfoam** **Installation** ----------------- This installation assumes you already have OpenMM installed in your system and its path is set in your bashrc. Moreover you must also create another environment variable inside your bashrc file which essentially specifies the parent directory of OpenMM installation. inside you bashrc create a varible `export FOAM_OMM=<path-to-omm-install-dir>` *Note: Do not forget to source your bashrc to reflect this new variable* Essentially the *FOAM_OMM* varible is used as a relative path inside the gpuPolyFoam options file, this is done to keep the installation standard and error free therefore please do not change this variable inside the options file Please execute the following step for installing **GPU PolyFOAM** solver - change directory to the newly created **gpupolyfoam** directory - inside the directory execute *wmake USE_OMM=POLY* for polyAtomic class or alternatively for motoatomic you must execute *wmake USE_OMM=MONO* *Note: please take care of upper case letters which are vital for appropriate compilation* if you do not get any compilation errors then there should be an executable generated inside *$FOAM_APPBIN* folder with the name **gpuPolyFoam** you should use the same executable name to execute GPU based polyAtomistic simulation. **Thanks** ================== <file_sep>/** * //identity: $Id$ * filename: gpuPolyFoam.h * @developer: <NAME> * @created: 21/09/2013 * Application: gpuPolyFoam * Description: */ #ifndef GPUPOLYFOAM_H #define GPUPOLYFOAM_H #include <stdio.h> #include <iostream> #include <exception> #include "fvCFD.H" #include "clockTimer.H" #ifdef USE_OMM #include "polyIdPairs.H" #include "OpenMM.h" using namespace OpenMM; #endif //#ifdef WATER //#include "mdWater.H" //#include "molecularField.H" #ifdef MONO #include "mdAtomistic.H" #else #include "mdPoly.H" #endif //CONSTANT VARIABLES #define FEM2SEC 1e-15 #define NM 1e9 #define NANO 1e-9 #define NM2RUF 1.66053886e-12 #define DALTON 1.66053886e-27 //from KONSTANTINOS water code #define CHARGE 1.602176487e-19 using namespace std; //- use typedef to declare clouds in common term #ifdef MONO typedef atomisticMoleculeCloud MOLECULE; #else typedef polyMoleculeCloud MOLECULE; #endif /** * structure to represent the classes into single block * so that it becomes easier to transfer */ #ifdef USE_OMM enum STATES { Forces = 1, Positions = 2, Velocities = 3 }; #endif struct poly_solver_t { reducedUnits* redUnits; potential* pot; #ifdef MONO atomisticMoleculeCloud* molecules; //if atomistic molecule #else polyMoleculeCloud* molecules;//if polyatomic molecule #endif clockTimer* evolveTimer; //declare OMM data structure #ifdef USE_OMM clockTimer* ommTimer; clockTimer* openFoamTimer; System* system; Context* context; Integrator* integrator; Vec3 bBoxOMMinNm; double refTime, refMass, refLength, refForce, refCharge, deltaT,rCutInNM; polyIdPairs* plid; //open foam #endif poly_solver_t() : redUnits(0), pot(0), molecules(0), #ifdef USE_OMM evolveTimer(0),system(0), context(0), integrator(0){} #else evolveTimer(0) {} #endif ~poly_solver_t() { delete redUnits; delete pot; delete molecules; delete evolveTimer; #ifdef USE_OMM std::cout << "Deleting everything ..."<<std::endl; delete context; delete integrator; delete system; #endif } }; /** * get the scalling function for the current * simulation */ const Foam::word getScallingFunction(const MOLECULE& mol); #endif <file_sep>#include "gpuUtilities.h" void initialiseOMM(struct poly_solver_t* solver) { // Load OpenMM platform-specific plugins: Platform::loadPluginsFromDirectory(Platform::getDefaultPluginsDirectory()); int numPlatforms = Platform::getNumPlatforms(); cout<<numPlatforms<<" OMM platforms found on this system"<<std::endl; for(int i=0;i<numPlatforms;i++) { Platform& tempPlatform = OpenMM::Platform::getPlatform(i); std::string tempPlatformName = tempPlatform.getName(); cout << "Platform " << i << " is " << tempPlatformName.c_str() << std::endl; } cout<<"==================================\n"<<std::endl; solver->system = new System(); MOLECULE& tempmol = *solver->molecules; //get the scalling function required for this simulation Foam::word scallingfunction = getScallingFunction(tempmol); Info << "Scalling function " << scallingfunction << nl; //dynamic coeff string array std::vector<std::string> coeffStr; /* * extract the coeff parameters generated by polyIdPairs class * from potentialDict */ extractCoeffParameters(tempmol,*solver->plid,coeffStr); std::string coefftype = solver->plid->coeffType(); Info << "CoeffType " << coefftype << nl; const label cs = solver->plid->coeffSize(); const List<word>& coeffnames = solver->plid->coeffNames(); std::stringstream tempstr;; /* * gather the N coeff parameters and their repective coeff string * generated by polyIdPairs. */ for(int i=0;i<cs;++i){ tempstr << coeffnames[i] << "= " << coeffStr[i] << ";"; } std::string formulastr; if(coefftype == "lennardJones"){ formulastr = "4*epsilon*((sigma/r)^12-(sigma/r)^6)+(138.9354561469*q)*(1/r-1/rCut+(r-rCut)/rCut^2); " + tempstr.str() + " q=q1*q2"; } else if(coefftype == "morse"){ formulastr = "D*(exp(-2*alpha*(r-r0))-2*exp(-alpha*(r-r0)));" + tempstr.str(); } else{ Info << "no coeff type found, quitting ..." << nl; exit(-1); } Info << "====Equation====" << nl; Info << formulastr << nl; // Initialise customNonbonded force for OpenMM CustomNonbondedForce* nonbonded; if(scallingfunction == "shiftedForce"){ // ================================================ // Coulomb potential with shifted force correction: // ================================================ nonbonded = new CustomNonbondedForce(formulastr); nonbonded->addGlobalParameter("rCut",solver->rCutInNM); } else{ Info << "Error: (Solver) Cannot find electrostatic potential" << "specification in potentialDict" << nl; exit(-1); } //add per particles to nonbonded force addParticlesToNonBonded(nonbonded,solver); //set OMM box size solver->system->setDefaultPeriodicBoxVectors( Vec3(solver->bBoxOMMinNm[0],0,0), Vec3(0,solver->bBoxOMMinNm[0],0), Vec3(0,0,solver->bBoxOMMinNm[0]) ); /** * extract OF information to initialise the * system inside openmm, this information includes * masses, exclusion list, custom parameters, etc */ extractOFParticles(solver,nonbonded); Info << "CUSTOMNONBONDEDFORCE INFO"<<nl; Info << "Num particles "<< nonbonded->getNumParticles() << nl; Info << "Num exclusion "<< nonbonded->getNumExclusions() << nl; Info << "Num perparticle params "<< nonbonded->getNumPerParticleParameters() << nl; Info << "Num global params "<< nonbonded->getNumGlobalParameters() << nl; Info << "Nonbonded method "<< nonbonded->getNonbondedMethod() << nl; Info << "Cutoff distance "<< nonbonded->getCutoffDistance() << nl; Info << "==============================="<<nl; solver->system->addForce(nonbonded); Platform& platform = Platform::getPlatformByName("OpenCL"); solver->integrator = new VerletIntegrator(solver->deltaT*OpenMM::PsPerFs); solver->context = new Context(*solver->system,*solver->integrator,platform); Info << "Initialised sytem on OMM with " << solver->system->getNumParticles() << " particles " << nl; Info << "Using OMM "<< solver->context->getPlatform().getName().c_str() << " platform " << nl; } void extractCoeffParameters(const MOLECULE& mol, const polyIdPairs& p, std::vector<std::string>& coeffStr) { const List<word>& idList = mol.pot().siteIdList(); const List<word>& coefflist = p.coeffNames(); label coeffsize = coefflist.size(); std::vector<std::string> coeffstr(coeffsize); int counter = 0; for(label c = 0; c < coeffsize; ++c) { counter = 0; forAll(p.coeffVals()[c],i){ forAll(p.coeffVals()[c][i],j){ const word& idAStr = idList[i]; const word& idBStr = idList[j]; //TODO: delete later if all is well scalar coeffAB; if(coefflist[c] == "sigma") coeffAB = p.coeffVals()[c][i][j]/1e-9; else if(coefflist[c] == "epsilon") coeffAB = p.coeffVals()[c][i][j]*6.02214129e23/1e3f; else if(coefflist[c] == "D") coeffAB = p.coeffVals()[c][i][j] * 6.02214129e20; else if(coefflist[c] == "alpha") coeffAB = p.coeffVals()[c][i][j] * 1.0f / 1e9; else if(coefflist[c] == "r0") coeffAB = p.coeffVals()[c][i][j] * 1e9; std::string ABstr; std::stringstream outAB; outAB << coeffAB; ABstr = outAB.str(); std::string tempstr = ABstr+"*("+idAStr+"1*"+idBStr+"2)"; if(counter == 0) coeffstr[c] = coeffstr[c]+""+tempstr; else coeffstr[c] = coeffstr[c]+" + "+tempstr; counter++; } } } for(counter = 0; counter < coeffsize; ++counter) coeffStr.push_back(coeffstr[counter]); } void extractOFParticles(struct poly_solver_t* solver, CustomNonbondedForce* const nonbonded) { const std::string coefftype = solver->plid->coeffType(); int temp = 0; if(coefftype == "lennardJones") temp = solver->plid->nIds() + 1; else temp = solver->plid->nIds(); const int species = temp; int* midx=NULL; MOLECULE& mol = *solver->molecules; IDLList<polyMolecule>::iterator m(mol.begin()); for (m = mol.begin(); m != mol.end(); ++m) { const polyMolecule::constantProperties& constprop = mol.constProps(m().id()); int molsize = constprop.sites().size(); //allocate memory for array holding molecule index based on molecule size midx = (int*) malloc(sizeof(int)*molsize); //now traverse throught the N sites of each molecule size obtained //from previous retrive int itr = 0; while(itr<molsize) { double tempmolmass = constprop.sites()[itr].siteMass() *solver->refMass/DALTON; double tempmolcharge = constprop.sites()[itr].siteCharge() *solver->refCharge/CHARGE; midx[itr] = solver->system->addParticle(tempmolmass); int sid = constprop.sites()[itr].siteId(); std::vector<double> params(species); for(int k=0;k<species;k++) params[k]=0; params[sid] = 1; if(coefftype == "lennardJones") params[species-1] = tempmolcharge; nonbonded->addParticle(params); itr++; } //add exclusion for each molecule obtained if(molsize>1) for(int i=0;i<molsize-1;i++) for(int j=i+1;j<molsize;j++) nonbonded->addExclusion(midx[i],midx[j]); // clear the mol id list for further assignment free(midx); }//first for loop ends } int extractOFPostoOMM(std::vector<Vec3>& posInNm,struct poly_solver_t* sol, const boundBox& bb) { posInNm.clear(); int numMols = 0; int numParticles = 0; IDLList<polyMolecule>::iterator mol(sol->molecules->begin()); for (mol = sol->molecules->begin(); mol != sol->molecules->end(); ++mol) { int molsize = mol().sitePositions().size(); int m = 0; while (m<molsize) { Foam::vector rI = (mol().sitePositions()[m] - bb.min())*sol->refLength*NM; posInNm.push_back(Vec3(rI.x(), rI.y(), rI.z())); m++; } numParticles += molsize; numMols++; } return numParticles; } int setOFforce(struct poly_solver_t* solver, const std::vector<Vec3>& ommForces) { IDLList<polyMolecule>::iterator mol(solver->molecules->begin()); int numparticle = 0; for (mol = solver->molecules->begin(); mol != solver->molecules->end(); ++mol){ int molsize = mol().siteForces().size(); int m = 0; while(m<molsize){ mol().siteForces()[m] = Foam::vector ( ommForces[numparticle][0], ommForces[numparticle][1], ommForces[numparticle][2] )*NM2RUF/solver->refForce; numparticle++; m++; } } return numparticle; } //set OMM box void setOMMBox(struct poly_solver_t* solver, const boundBox& bBoxOF,const double dt) { solver->refLength = solver->redUnits->refLength(); solver->refMass = solver->redUnits->refMass(); solver->refForce = solver->redUnits->refForce(); solver->refCharge = solver->redUnits->refCharge(); solver->refTime = solver->redUnits->refTime(); // Convert to femtoseconds [fs] for OpenMM: solver->deltaT = dt*solver->refTime/FEM2SEC; //convert to reduced omm rcut size solver->rCutInNM = solver->molecules->pot().pairPotentials().rCutMax()*solver->refLength/NANO; // Convert individual bounding-box length-scales to nanometres [nm] double Lx = bBoxOF.span().x()*solver->refLength/NANO; double Ly = bBoxOF.span().y()*solver->refLength/NANO; double Lz = bBoxOF.span().z()*solver->refLength/NANO; //create boxsize for OMM solver->bBoxOMMinNm = Vec3(Lx,Ly,Lz); } void addParticlesToNonBonded(CustomNonbondedForce* const nonbonded, const struct poly_solver_t* solver) { const List<word>& idlist = solver->molecules->pot().siteIdList(); const std::string coefftype = solver->plid->coeffType(); for(int i = 0; i < solver->plid->nIds(); ++i){ const word& idAstr = idlist[i]; nonbonded->addPerParticleParameter(idAstr); } if(coefftype == "lennardJones") nonbonded->addPerParticleParameter("q"); //set nonbondedmethod nonbonded->setNonbondedMethod(CustomNonbondedForce::CutoffPeriodic); nonbonded->setCutoffDistance(solver->rCutInNM); } void getOMMState(const Context* context,std::vector<Vec3>& statearray) // enum STATES st) { statearray.clear(); State state = context->getState(OpenMM::State::Forces|State::Energy,true); statearray = state.getForces(); } <file_sep>/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2008-2009 OpenCFD Ltd. \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. OpenFOAM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenFOAM; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Application mdPolyFoam Description Molecular dynamics solver for fluid dynamics -- polyatomics only \*---------------------------------------------------------------------------*/ #include "gpuPolyFoam.h" #ifdef USE_OMM #include "gpuUtilities.h" #include "gpuUtilities.C" #endif int main(int argc, char *argv[]) { # include "setRootCase.H" # include "createTime.H" # include "createMesh.H" poly_solver_t* solver = new poly_solver_t(); solver->redUnits = new reducedUnits(runTime, mesh); solver->pot = new potential(mesh,*solver->redUnits); solver->molecules = new MOLECULE(runTime,mesh,*solver->pot,*solver->redUnits); solver->evolveTimer = new clockTimer(runTime,"evolve",true); //obtain reference properties #ifdef USE_OMM int num = 0; solver->plid = new polyIdPairs(mesh, *solver->pot); double dt = mesh.time().deltaT().value(); const boundBox bBoxOF = mesh.bounds(); setOMMBox(solver,bBoxOF,dt); initialiseOMM(solver); std::vector<Vec3> posInNm; num = extractOFPostoOMM(posInNm,solver,bBoxOF); Info << "extracted " << num << " particles from OF" << nl; solver->context->setPositions(posInNm); std::vector<Vec3> atomForces; getOMMState(solver->context,atomForces); num = setOFforce(solver,atomForces); Info << "set " << num << " forces to OF" << nl; solver->molecules->updateAcceleration(); solver->ommTimer = new clockTimer(runTime, "openMMTimer", true); solver->openFoamTimer = new clockTimer(runTime, "openFoamTimer", true); solver->openFoamTimer->startClock(); #endif Info << "\nStarting time loop\n" << endl; while (runTime.loop()){ Info << "Time = " << runTime.timeName() << endl; solver->evolveTimer->startClock(); #ifdef USE_OMM solver->molecules->evolveBeforeForces(); solver->openFoamTimer->stopClock(); num = extractOFPostoOMM(posInNm,solver,bBoxOF); solver->ommTimer->startClock(); solver->context->setPositions(posInNm); getOMMState(solver->context,atomForces); solver->ommTimer->stopClock(); num = setOFforce(solver,atomForces); solver->openFoamTimer->startClock(); solver->molecules->evolveAfterForces(); #else solver->molecules->evolve(); #endif solver->evolveTimer->stopClock(); runTime.write(); Info << "ExecutionTime = " << runTime.elapsedCpuTime() << " s" << " ClockTime = " << runTime.elapsedClockTime() << " s" << nl << endl; } Info << "End\n" << endl; delete solver; return 0; } const Foam::word getScallingFunction(const MOLECULE& mol) { Foam::word scallingFunction; //explicity namespace declaration IOdictionary potentialDict ( IOobject ("potentialDict",mol.mesh().time().system(), mol.mesh(),IOobject::MUST_READ,IOobject::NO_WRITE) ); const dictionary& pairdict = potentialDict.subDict("pair"); try { if(pairdict.found("electrostatic")){ const dictionary& pairpotentialdict = pairdict.subDict("electrostatic"); Foam::word temp = pairpotentialdict.lookup("energyScalingFunction"); scallingFunction = temp; } else{ throw 20; } } catch(int msg){ Info << "getScallingFunction():: " << msg << nl; } return scallingFunction; }
7c1b4c68deece87be5ee2f2bf7f8cd9404f9d280
[ "Markdown", "C", "C++" ]
5
C++
samech/gpupolyfoam
a9d36f028a2f3319c98cda06e92fe6d721c6cc57
b1db2025e0e50a87e1f89e617c9dc385cbcb0154
refs/heads/master
<file_sep>angular.module('friendsAng', []);
be2712347aff024dd45c11859672c5a737d416c1
[ "JavaScript" ]
1
JavaScript
dougalderman/angular-friends
510efa17b2c594ac970393c2ee3880ad37ca4f58
9a412991635e9acf94c29720bcca7cc40175d4a1
refs/heads/master
<repo_name>shedelin/ft-select<file_sep>/srcs/ft_sl_move.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_sl_move.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: shedelin <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/01/09 18:09:14 by shedelin #+# #+# */ /* Updated: 2014/01/11 19:07:50 by shedelin ### ########.fr */ /* */ /* ************************************************************************** */ #include <string.h> #include <termcap.h> #include "ft_select.h" void ft_sl_moveup(void) { t_dlst *list; t_dlst *tmp; list = ft_sl_singleton()->lst; tmp = list->next; while (tmp->cond % 2 == 0) tmp = tmp->next; tmp->cond -= 1; if (tmp->prev == list) { while (tmp->next) tmp = tmp->next; tmp->cond += 1; } else (tmp->prev)->cond += 1; } void ft_sl_movedw(void) { t_dlst *list; t_dlst *tmp; list = ft_sl_singleton()->lst; tmp = list->next; while (tmp->cond % 2 == 0) tmp = tmp->next; if (tmp->next == NULL) list->next->cond += 1; else (tmp->next)->cond += 1; tmp->cond -= 1; } void ft_sl_moveright(void) { t_dlst *list; t_dlst *tmp; int i; int len; list = ft_sl_singleton()->lst->next; len = ft_sl_singleton()->line; tmp = list; while (tmp->cond % 2 == 0) tmp = tmp->next; tmp->cond -= 1; i = 0; while (tmp->next && i < len) { tmp = tmp->next; i++; } tmp->cond += 1; } void ft_sl_moveleft(void) { t_dlst *list; t_dlst *tmp; int i; int len; i = 0; list = ft_sl_singleton()->lst->next; tmp = list; len = ft_sl_singleton()->line; while (tmp->cond % 2 == 0) { i++; tmp = tmp->next; } tmp->cond -= 1; if (i - len < 0) while ((tmp->prev)->prev) tmp = tmp->prev; else while (len--) tmp = tmp->prev; tmp->cond += 1; } <file_sep>/srcs/ft_sl_signal.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_sl_signal.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: shedelin <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/01/08 20:28:26 by shedelin #+# #+# */ /* Updated: 2014/01/08 20:28:29 by shedelin ### ########.fr */ /* */ /* ************************************************************************** */ #include <signal.h> #include <sys/ioctl.h> #include <libft.h> #include "ft_select.h" void ft_sl_signal(void) { signal(SIGINT, ft_sl_sigint); signal(SIGQUIT, ft_sl_sigint); signal(SIGWINCH, ft_sl_getsize); signal(SIGTSTP, ft_sl_sigtstp); signal(SIGCONT, ft_sl_sigcont); } void ft_sl_sigint(int sig) { char key[2]; (void)sig; key[0] = 3; key[1] = 0; ft_sl_exit(); signal(SIGINT, SIG_DFL); ioctl(0, TIOCSTI, key); } void ft_sl_sigtstp(int sig) { char key[2]; (void)sig; key[0] = 26; key[1] = 0; ft_sl_exit(); signal(SIGTSTP, SIG_DFL); ioctl(0, TIOCSTI, key); } void ft_sl_sigcont(int sig) { (void)sig; ft_sl_initshell(); ft_sl_put(); } <file_sep>/srcs/ft_sl_out.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_sl_out.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: shedelin <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/01/08 19:35:11 by shedelin #+# #+# */ /* Updated: 2014/01/08 19:35:14 by shedelin ### ########.fr */ /* */ /* ************************************************************************** */ #include <sys/ioctl.h> #include <termcap.h> #include <stdlib.h> #include "libft.h" #include "ft_select.h" void ft_sl_getsize(int sig) { struct winsize wsize; ioctl(0, TIOCGSIZE, &wsize); ft_sl_singleton()->col = wsize.ws_col; ft_sl_singleton()->line = wsize.ws_row; if (sig == SIGWINCH) { tputs(tgetstr("cl", NULL), 1, &ft_sl_putchar); ft_sl_put(); } } void ft_sl_put(void) { t_dlst *list; t_glob *glob; char *cm; int x; int y; x = 0; y = 0; glob = ft_sl_singleton(); cm = tgetstr("cm", NULL); list = (glob->lst)->next; if (ft_sl_sizecheck(list, glob)) return ; while (list) { tputs(tgoto(cm, x, y), 1, &ft_sl_putchar); ft_sl_putone(list); if (++y > glob->line - 1 && (y = 0) == 0) x += glob->maxlen + 2; else ft_putchar_fd('\n', 0); list = list->next; } } int ft_sl_sizecheck(t_dlst *lst, t_glob *g) { if (((ft_sl_countlst(lst) / g->line) + 1) * (g->maxlen + 2) > g->col) { ft_sl_errorsize(); return (1); } return (0); } void ft_sl_putone(t_dlst *list) { if (list->cond == 1) ft_sl_printcolor(list, UNDERLINE); if (list->cond == 2) ft_sl_printcolor(list, REV); if (list->cond == 3) ft_sl_printcolor(list, REVUNDER); if (list->cond == 0) ft_sl_printcolor(list, NORMAL); } void ft_sl_printcolor(t_dlst *list, char *type) { if (list->type == 'd') ft_putstr_col(list->name, BLUE, type, 0); else if (list->type == 'x') ft_putstr_col(list->name, RED, type, 0); else if (list->type == 's') ft_putstr_col(list->name, CYAN, type, 0); else if (list->type == 'p') ft_putstr_col(list->name, PURPLE, type, 0); else if (list->type == 'c') ft_putstr_col(list->name, GREEN, type, 0); else if (list->type == 'b') ft_putstr_col(list->name, GREEN, type, 0); else ft_putstr_col(list->name, WHITE, type, 0); } <file_sep>/srcs/ft_sl_dolst.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_sl_dolst.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: shedelin <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/01/08 18:05:28 by shedelin #+# #+# */ /* Updated: 2014/01/08 18:05:30 by shedelin ### ########.fr */ /* */ /* ************************************************************************** */ #include <unistd.h> #include <sys/stat.h> #include "libft.h" #include "ft_select.h" t_dlst *ft_sl_dolst(int ac, char **av) { t_dlst *lst; int i; i = 1; lst = ft_sl_creatlst("", -1, 'z'); while (i < ac) { ft_sl_lstaddend(&lst, ft_sl_creatlst(av[i], 0, ft_sl_gettype(av[i]))); i++; } (lst->next)->cond = 1; return (lst); } int ft_sl_getmaxlen(t_dlst *lst) { int maxlen; maxlen = 0; while (lst->next) { if ((int)ft_strlen(lst->name) > maxlen) maxlen = ft_strlen(lst->name); lst = lst->next; } return (maxlen); } char ft_sl_gettype(char *str) { char c; struct stat data; stat(str, &data); c = '-'; if (S_ISDIR(data.st_mode)) c = 'd'; else if (access(str, X_OK) == 0) c = 'x'; else if (S_ISSOCK(data.st_mode)) c = 's'; else if (S_ISFIFO(data.st_mode)) c = 'p'; else if (S_ISCHR(data.st_mode)) c = 'c'; else if (S_ISBLK(data.st_mode)) c = 'b'; else if (S_ISREG(data.st_mode)) c = '-'; return (c); } <file_sep>/Makefile # **************************************************************************** # # # # ::: :::::::: # # Makefile :+: :+: :+: # # +:+ +:+ +:+ # # By: vcosson <<EMAIL>> +#+ +:+ +#+ # # +#+#+#+#+#+ +#+ # # Created: 2014/02/06 14:23:25 by shedelin #+# #+# # # Updated: 2014/04/30 16:53:36 by shedelin ### ########.fr # # # # **************************************************************************** # NAME = ft_select CC = gcc FLAGS = -Wall -Wextra -Werror -g DIRLIB = libft/ DIRSRC = srcs/ DIRH = includes/ SRC = main.c \ ft_sl_dokey.c \ ft_sl_dolst.c \ ft_sl_error.c \ ft_sl_lst.c \ ft_sl_move.c \ ft_sl_out.c \ ft_sl_put.c \ ft_sl_signal.c \ ft_sl_search.c \ ft_sl_singleton.c OBJ = $(SRC:.c=.o) all: init $(NAME) init: @echo "\033[0;32m $(NAME) PROJECT\033[0m" $(NAME): $(OBJ) @make -s -C $(DIRLIB) @$(CC) $(FLAGS) -o $(NAME) $^ -I$(DIRLIB) -I$(DIRH) -L$(DIRLIB) -lft -ltermcap @echo "\033[1;32m ft_select: OK\033[0m" %.o: $(DIRSRC)%.c @echo -n . @$(CC) $(FLAGS) -o $@ -c $< -I$(DIRLIB)$(DIRH) -I$(DIRH) clean: @rm -f $(OBJ) @make clean -s -C $(DIRLIB) @echo "\033[4;32mDeleted:\033[0;33m $(OBJ)\033[0m" fclean: clean @make -C $(DIRLIB) $@ @rm -f $(NAME) @echo "\033[4;32mDeleted:\033[0;33m $(NAME)\033[0m" re: fclean all exec: all rm -f log.txt ./ft_select * * * * * * * * * * cat log.txt | less .PHONY: all clean fclean re <file_sep>/srcs/ft_sl_lst.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_sl_lst.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: shedelin <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/01/08 17:39:18 by shedelin #+# #+# */ /* Updated: 2014/01/08 17:39:21 by shedelin ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include "libft.h" #include "ft_select.h" void ft_sl_lstaddend(t_dlst **lst, t_dlst *new) { t_dlst *tmp; tmp = *lst; while (tmp->next) tmp = tmp->next; tmp->next = new; new->prev = tmp; } t_dlst *ft_sl_creatlst(char *name, int condition, char type) { t_dlst *new; if ((new = (t_dlst *)malloc(sizeof(t_dlst)))) { new->next = NULL; new->prev = NULL; new->name = ft_strdup(name); new->cond = condition; new->type = type; return (new); } ft_sl_error(1); return (NULL); } void ft_sl_delone(t_dlst **lst, t_dlst *todel) { if ((*lst)->next == NULL || *lst == todel) ft_sl_error(3); (todel->prev)->next = todel->next; if (todel->next) (todel->next)->prev = todel->prev; ft_sl_freelst(todel); } void ft_sl_freelst(t_dlst *todel) { if (todel) { ft_strdel(&(todel->name)); free(todel); } } int ft_sl_countlst(t_dlst *lst) { int len; len = 0; while (lst) { len++; lst = lst->next; } return (len); } <file_sep>/srcs/ft_sl_error.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_sl_error.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: shedelin <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/01/08 17:41:06 by shedelin #+# #+# */ /* Updated: 2014/01/08 17:41:08 by shedelin ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include <termcap.h> #include "libft.h" #include "ft_select.h" void ft_sl_error(int error) { if (error == 0) ft_putendl_fd("Not enough arguments.", 2); if (error == 1) ft_putendl_fd("Malloc fail.", 2); if (error == 2) ft_putendl_fd("Incompatible terminal.", 2); if (error == 3) ft_putendl_fd("Try to del bad link.", 2); exit(error); } void ft_sl_errorsize(void) { tputs(tgetstr("cl", NULL), 1, &ft_sl_putchar); ft_putendl_fd("window's too small, enlarge", 2); } <file_sep>/srcs/ft_sl_dokey.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_sl_dokey.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: shedelin <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/01/10 19:37:11 by shedelin #+# #+# */ /* Updated: 2014/01/10 19:37:15 by shedelin ### ########.fr */ /* */ /* ************************************************************************** */ #include <termcap.h> #include <stdlib.h> #include "libft.h" #include "ft_select.h" void ft_sl_key(char *key) { if (key[0] == 27 && key[1] == 91 && key[2] == 65) ft_sl_moveup(); else if (key[0] == 27 && key[1] == 91 && key[2] == 66) ft_sl_movedw(); else if (key[0] == 27 && key[1] == 91 && key[2] == 67) ft_sl_moveright(); else if (key[0] == 27 && key[1] == 91 && key[2] == 68) ft_sl_moveleft(); else if (key[0] == 32 && key[1] == 0 && key[2] == 0) ft_sl_dospace(); else if (key[0] == 10 && key[1] == 0 && key[2] == 0) ft_sl_doentry(); else if (key[0] == 127 && key[1] == 0 && key[2] == 0) ft_sl_del(); else if (key[0] == 126 && key[1] == 0 && key[2] == 0) ft_sl_del(); else if (key[0] >= 97 && key[0] <= 122 && key[1] == 0 && key[2] == 0) ft_sl_search(key[0]); } void ft_sl_exit(void) { tputs(tgetstr("ve", NULL), 1, &ft_sl_putchar); tputs(tgetstr("cl", NULL), 1, &ft_sl_putchar); tputs(tgetstr("te", NULL), 1, &ft_sl_putchar); tcsetattr(0, 0, &(ft_sl_singleton()->term)); } void ft_sl_del(void) { t_dlst *list; t_dlst *tmp; list = ft_sl_singleton()->lst; tmp = list->next; while (tmp->cond % 2 == 0) tmp = tmp->next; if (tmp->next) (tmp->next)->cond += 1; else (tmp->prev)->cond += 1; if ((int)ft_strlen(tmp->name) == ft_sl_singleton()->maxlen) { ft_sl_delone(&list, tmp); ft_sl_singleton()->maxlen = ft_sl_getmaxlen(list); } else ft_sl_delone(&list, tmp); if (list->next == NULL) { ft_sl_exit(); exit(0); } } void ft_sl_dospace(void) { t_dlst *list; t_dlst *tmp; list = ft_sl_singleton()->lst; tmp = list->next; while (tmp->cond % 2 == 0) tmp = tmp->next; if (tmp->next == NULL) { if (tmp->cond == 3) tmp->cond = 0; else tmp->cond = 2; (list->next)->cond += 1; } else { if (tmp->cond == 3) tmp->cond = 0; else tmp->cond = 2; (tmp->next)->cond += 1; } } void ft_sl_doentry(void) { t_dlst *list; int nb; ft_sl_exit(); nb = 0; list = ft_sl_singleton()->lst->next; while (list) { if (list->cond >= 2) nb++; list = list->next; } list = ft_sl_singleton()->lst->next; while (list) { if (list->cond >= 2) { ft_putstr(list->name); if (nb-- > 1) ft_putstr(" "); } list = list->next; } ft_putendl(""); exit(0); } <file_sep>/includes/ft_select.h /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_select.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: shedelin <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/01/08 17:38:50 by shedelin #+# #+# */ /* Updated: 2014/01/08 17:38:53 by shedelin ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef FT_SELECT_H # define FT_SELECT_H # include <termios.h> typedef struct s_dlst { char *name; int cond; char type; struct s_dlst *next; struct s_dlst *prev; } t_dlst; typedef struct s_glob { int line; int col; int maxlen; t_dlst *lst; struct termios term; } t_glob; void ft_sl_initshell(void); void ft_sl_read(void); void ft_sl_key(char *key); void ft_sl_exit(void); void ft_sl_del(void); void ft_sl_dospace(void); void ft_sl_doentry(void); void ft_sl_signal(void); void ft_sl_sigint(int sig); void ft_sl_sigtstp(int sig); void ft_sl_sigcont(int sig); t_glob *ft_sl_singleton(void); void ft_sl_getsize(int sig); void ft_sl_put(void); int ft_sl_sizecheck(t_dlst *lst, t_glob *g); void ft_sl_putone(t_dlst *list); void ft_sl_moveup(void); void ft_sl_movedw(void); void ft_sl_moveright(void); void ft_sl_moveleft(void); t_dlst *ft_sl_dolst(int ac, char **av); int ft_sl_getmaxlen(t_dlst *lst); void ft_sl_error(int error); void ft_sl_errorsize(void); int ft_sl_putchar(int c); int ft_sl_putstr(char *str); void ft_sl_lstaddend(t_dlst **lst, t_dlst *new); t_dlst *ft_sl_creatlst(char *name, int condition, char type); void ft_sl_delone(t_dlst **lst, t_dlst *todel); void ft_sl_freelst(t_dlst *todel); int ft_sl_countlst(t_dlst *lst); void ft_sl_search(char c); char ft_sl_gettype(char *str); void ft_sl_printcolor(t_dlst *list, char *type); #endif <file_sep>/srcs/main.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: shedelin <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/01/08 17:38:15 by shedelin #+# #+# */ /* Updated: 2014/01/08 17:38:18 by shedelin ### ########.fr */ /* */ /* ************************************************************************** */ #include <termios.h> #include <termcap.h> #include <term.h> #include <unistd.h> #include <stdlib.h> #include "ft_select.h" int main(int ac, char **av) { char buffer[2048]; if (ac < 2) ft_sl_error(0); tcgetattr(0, &(ft_sl_singleton()->term)); ft_sl_signal(); ft_sl_singleton()->lst = ft_sl_dolst(ac, av); ft_sl_singleton()->maxlen = ft_sl_getmaxlen(ft_sl_singleton()->lst); ft_sl_getsize(0); if (tgetent(buffer, getenv("TERM")) < 1) ft_sl_error(2); ft_sl_initshell(); ft_sl_read(); return (0); } void ft_sl_initshell(void) { struct termios term; tcgetattr(0, &term); term.c_lflag &= ~(ICANON | ECHO); tcsetattr(0, 0, &term); tputs(tgetstr("ti", NULL), 1, &ft_sl_putchar); tputs(tgetstr("vi", NULL), 1, &ft_sl_putchar); }
3ec1308c4933d9b33ba8d8e821d51746c8f19d5b
[ "C", "Makefile" ]
10
C
shedelin/ft-select
e2177d24b8df517700d8f3ca78f4a0e5e9db27a1
c83ccb8e91236c3bfa9b91ce01cc68d2966afea0
refs/heads/master
<repo_name>Isti115/dotfiles<file_sep>/.config/helix/languages.toml [[language]] name = "typescript" formatter = { command = 'prettier', args = ["--parser", "typescript"] } auto-format = true <file_sep>/.config/qutebrowser/config.py config.load_autoconfig(True) config.source('base16-gruvbox-dark-hard.config.py') c.fonts.default_family = "Iosevka" # c.fonts.default_family = "DejaVuSansMono Nerd Font" c.tabs.last_close = "close" c.session.lazy_restore = True c.url.searchengines = { "DEFAULT": "google.com/search?q={}", "g": "google.com/search?q={}", "d": "duckduckgo.com/?q={}", "y": "youtube.com/results?search_query={}", "enhu": "translate.google.com/?op=translate&sl=en&tl=hu&text={}", "huen": "translate.google.com/?op=translate&sl=hu&tl=en&text={}" } # c.aliases['r'] = 'session-load' c.aliases['suspend'] = 'open qute://back ;; tab-next' # config.set('content.autoplay', False, '*://*.youtube.com/*') # config.bind("<Space>1", ' ;; '.join([f'tab-select {x}/1' for x in range(20)])) config.bind("<Space>A", "set-cmd-text :open -t file:///home/isti/tmp/tmp.html#") config.bind( "<Space>a", "spawn --userscript qutebrowser-sway.ps1" ) config.bind("<Ctrl+k>", "tab-move -") config.bind("<Ctrl+j>", "tab-move +") config.bind("<Space><Space>", "mode-enter passthrough") config.bind("<Space>,", "set-cmd-text -s :tab-select") config.bind("<Space>qq", "tab-close") config.bind("<Space>qQ", "close") config.bind("<Space>qa", "quit") config.bind("<Space>qr", "config-source") config.bind("<Space>sS", "session-save all") config.bind("<Space>ss", "set-cmd-text -s :session-save -o") config.bind("<Space>sl", "set-cmd-text -s :session-load") config.bind("<Space>tt", "config-cycle tabs.show always multiple never") config.bind("<Space>ts", "config-cycle statusbar.show always never") config.bind("<Space>tf", "jseval document.body.requestFullscreen()") config.bind("<Space><Ctrl+m>", "spawn mpv --force-window=immediate {url}") config.bind("<Space>m", "spawn umpv --force-window=immediate {url}") config.bind("<Space>M", "hint --rapid links spawn umpv --force-window=immediate {hint-url}") <file_sep>/.local/bin/mnt.js #!/usr/bin/env -S deno -q run --allow-run console.log(Deno.args) const lsblk = Deno.run({ cmd: [ "lsblk", "-p", "--json", '-o', 'PATH,SIZE,FSTYPE,LABEL' ], stdout: "piped", }) const devices = JSON.parse( new TextDecoder().decode( await lsblk.output() ) ).blockdevices // const devices = [].concat(...blk.blockdevices.map(d => d.path)) const fuzzel = Deno.run({ cmd: [ "fuzzel", "-w", "60", "--dmenu", "--index" ], stdin: "piped", stdout: "piped", }) await fuzzel.stdin.write(new TextEncoder().encode( devices.map(d => `${d.path} | ${d.size} | ${d.fstype} | ${d.label}`).join('\n') )) await fuzzel.stdin.close() const choice = Number(new TextDecoder().decode(await fuzzel.output())) console.log(devices[choice].path) const mnt = Deno.run({ cmd: [ "udisksctl", Deno.args[0] === '--un' ? 'unmount' : 'mount', "-b", devices[choice].path ], }) await mnt.status() <file_sep>/.local/bin/open.lua #!/usr/bin/env lua associations = { { filter = '.*.png$', command = "vimiv" }, { filter = '.*.jpg$', command = "vimiv" }, { filter = '.*.pdf$', command = "zathura" }, { filter = '.*.mp3$', command = "mpv --force-window" }, { filter = '.*.mp4$', command = "mpv --force-window" }, { filter = '.*.svg$', command = "inkscape" }, { filter = '.*.doc$', command = "libreoffice" } } for _, a in pairs(associations) do if string.match(arg[1], a.filter) then os.execute(a.command .. ' "' .. arg[1] .. '"') break end end <file_sep>/.local/bin/swaymsg-anywhere.sh #! /usr/bin/env sh SWAYSOCK=$(find /run/user/1000/ -name "sway-*" -print -quit) swaymsg "$@" <file_sep>/.profile # ~/.profile is loaded under PowerShell when launched as login shell: # https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_pwsh?view=powershell-7.1#-login---l export PATH="${PATH}:${HOME}/.local/bin" export EDITOR=nvim export VISUAL=nvim export MOZ_ENABLE_WAYLAND=1 export MOZ_USE_XINPUT2=1 <file_sep>/.config/qutebrowser/greasemonkey/discord-auth-fix.user.js // ==UserScript== // @name Discord Auth Fix // @namespace http://istvan.donko.hu/ // @version 0.1 // @description Fix Discord auth issue with window sizing // @author <NAME> (Isti115) // @match https://discord.com/* // @run-at document-start // ==/UserScript== ;(function() { 'use strict'; /* Not needed since the following commit: https://github.com/qutebrowser/qutebrowser/commit/be37524f47bcb78a319eae4e1d61794dfec6cc36 */ // Object.defineProperty(window, 'outerWidth', { get() { return window.innerWidth; } }); // unsafeWindow.outerWidth = unsafeWindow.innerWidth })(); <file_sep>/.local/bin/dotfiles-install.sh #! /usr/bin/env sh # Based on: https://www.atlassian.com/git/tutorials/dotfiles # git://github.com/<user>/<repo> git clone --bare http://github.com/Isti115/dotfiles.git $HOME/.dotfiles function dotfiles { /usr/bin/git --git-dir=$HOME/.dotfiles/ --work-tree=$HOME $@ } dotfiles checkout dotfiles config status.showUntrackedFiles no <file_sep>/.local/bin/quick-commands.sh #! /usr/bin/env sh # Disabled options # --cache-file /dev/null \ # --sort-order alphabetical \ wofi \ --show dmenu \ --insensitive \ --prompt "Quick commands:" \ <<COMMANDS | sh # - Sway --------------------------------------- # swaymsg "input * tap enabled" # Enable tapping on the touchpad swaymsg output HEADLESS-1 position 4480 600 # Fix the position of the headless output swaymsg create_output # Create virtual output # - Termite ------------------------------------ # termite -e "pwsh -c 'echo sajt; sleep 5'" # Echo something termite -e "pwsh --noexit -c fc-list" # List available fonts # - Audio -------------------------------------- # pactl load-module module-loopback latency_msec=1 # PulseAudio - Load loopback module pactl unload-module module-loopback # PulseAudio - Unload loopback module pulseaudio -k # PulseAudio - Kill pkill pipewire # PipeWire - Kill pw-jack catia # Catia with Jack pw-jack qjackctl # QJackCtl with Jack pw-jack bitwig-studio # Bitwig with Jack # - LifeBook ----------------------------------- # ssh lifebook-wifi "~/swaymsg-anywhere.sh 'exec vncviewer 192.168.0.205 -FullScreen'" # Start VNC viewer ssh lifebook-wifi "~/swaymsg-anywhere.sh 'workspace back_and_forth'" # Blank or unblank screen # Wake LifeBook 00:17:42:c2:a4:4b ssh lifebook-wifi sudo reboot # Reboot LifeBook ssh lifebook-wifi sudo poweroff # Power off / shut down LifeBook # - Screen Sharing ----------------------------- # /usr/lib/xdg-desktop-portal-wlr -r -o DP-1 # Share main screen /usr/lib/xdg-desktop-portal-wlr -r -o HDMI-A-1 # Share secondary screen /usr/lib/xdg-desktop-portal-wlr -r -o DP-2 # Share tertiary screen pkill -f xdg-desktop-portal # Kill screen sharing # - Programs with special parameters ----------- # progl /opt/resolve/bin/resolve # Davinci Resolve grep -oP "(?<=\[).*\.pdf(?=\])" ~/.local/share/zathura/history | wofi --dmenu | xargs zathura COMMANDS # - Clipboard ---------------------------------- # # urxvt -e "sh -c 'wl-paste | xclip -sel clip'" # Copy clipboard content to XWayland <file_sep>/.local/bin/open.ts #!/usr/bin/env -S deno -q run --allow-run const file = Deno.args[0] const associations = [ { filter: /.*\.(png|jpg)$/, command: ['vimiv'] }, { filter: /.*\.pdf$/, command: ['zathura'] }, { filter: /.*\.(mp3|mp4)$/, command: ['mpv', '--force-window'] }, { filter: /.*\.svg$/, command: ['inkscape'] }, { filter: /.*\.doc$/, command: ['libreoffice'] } ] for (let { filter, command } of associations) { if (filter.test(file)) { await Deno.run({ cmd: [...command, file] }).status() } } <file_sep>/.local/bin/open.mjs #!/usr/bin/env node // const exec = require('child_process').exec import { exec } from 'child_process' const file = process.argv[2] const associations = [ { filter: /.*\.(png|jpg)$/, command: ['vimiv'] }, { filter: /.*\.pdf$/, command: ['zathura'] }, { filter: /.*\.(mp3|mp4)$/, command: ['mpv', '--force-window'] }, { filter: /.*\.svg$/, command: ['inkscape'] }, { filter: /.*\.doc$/, command: ['libreoffice'] } ] for (let { filter, command } of associations) { if (filter.test(file)) { exec(`${command} "${file}"`) } } <file_sep>/.config/helix/config.toml # Language configuration at: # ~/.config/helix/languages.toml # (`gf` over the path to access) # theme = "monokai_pro" # theme = "tokyonight" theme = "onedark" [editor] color-modes = true rulers = [ 80 ] [editor.cursor-shape] insert = "bar" normal = "block" select = "underline" [keys.normal.space] c = ":config-open" C = ":config-reload" # z = { g = ":sh zelligit.sh", f = ":sh zellilf.sh" } [keys.normal.space.z] g = ":sh zellij action new-tab --layout lazygit" f = ":sh zellij action new-tab --layout lf" [keys.insert] j = { k = "normal_mode" } # Maps `jk` to exit insert mode
6060627ee9cb8078ce6999716ed6ed1c43251a2d
[ "Lua", "TOML", "JavaScript", "Python", "TypeScript", "Shell" ]
12
TOML
Isti115/dotfiles
034316efb1f56ebc1b0b65da5ee44e40bc1c41d9
bfb126ff9abf391f6b1afa5e5697ec6b84121a99
refs/heads/master
<file_sep>package com.squad.betakua.tap_neko.nfc; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.drawable.AnimationDrawable; import android.media.AudioManager; import android.media.ToneGenerator; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; import android.nfc.Tag; import android.nfc.tech.MifareClassic; import android.nfc.tech.MifareUltralight; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Parcelable; import android.os.VibrationEffect; import android.os.Vibrator; import android.provider.Settings; import android.speech.tts.TextToSpeech; import android.support.constraint.ConstraintLayout; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.squad.betakua.tap_neko.R; import com.airbnb.lottie.LottieAnimationView; import java.util.HashMap; import java.util.Locale; public class NFCActivity extends AppCompatActivity { public static final int NFC_REQ_CODE = 123; public static final String NFC_ID_KEY = "nfc_id"; TextView text; TextView textSuccess; NfcAdapter nfcAdapter; PendingIntent pendingIntent; static final String TAG = "TTS"; TextToSpeech mTts; LottieAnimationView nfcAnimation; LottieAnimationView checkAnimation; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_nfc); text = findViewById(R.id.nfc_text); text.setText("Tap the medicine cap or device tag!"); textSuccess = findViewById(R.id.nfc_text_success); textSuccess.setVisibility(View.GONE); nfcAnimation = findViewById(R.id.lottie_nfc); checkAnimation = findViewById(R.id.lottie_nfc_success); checkAnimation.setVisibility(View.GONE); // background gradient animation RelativeLayout relativeLayout = findViewById(R.id.activity_nfc); AnimationDrawable animationDrawable = (AnimationDrawable) relativeLayout.getBackground(); animationDrawable.setEnterFadeDuration(2000); animationDrawable.setExitFadeDuration(4000); animationDrawable.start(); nfcAdapter = NfcAdapter.getDefaultAdapter(this); if (nfcAdapter == null) { Toast.makeText(this, "No NFC", Toast.LENGTH_SHORT).show(); Intent data = new Intent(); data.putExtra(NFC_ID_KEY, "321"); setResult(RESULT_OK, data); finish(); return; } pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, this.getClass()) .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); } void speak(String s){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Log.v(TAG, "Speak new API"); Bundle bundle = new Bundle(); bundle.putInt(TextToSpeech.Engine.KEY_PARAM_STREAM, AudioManager.STREAM_MUSIC); mTts.speak(s, TextToSpeech.QUEUE_FLUSH, bundle, null); } else { Log.v(TAG, "Speak old API"); HashMap<String, String> param = new HashMap<>(); param.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_MUSIC)); mTts.speak(s, TextToSpeech.QUEUE_FLUSH, param); } } @Override protected void onResume() { super.onResume(); if (nfcAdapter != null) { if (!nfcAdapter.isEnabled()) showWirelessSettings(); nfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null); } } private void showWirelessSettings() { Toast.makeText(this, "You need to enable NFC", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS); startActivity(intent); } private String dumpTagData(Tag tag) { StringBuilder sb = new StringBuilder(); byte[] id = tag.getId(); // TODO: Here, we transmit the ID to the callback sb.append("ID (hex): ").append(Utils.toHex(id)).append('\n'); sb.append("ID (reversed hex): ").append(Utils.toReversedHex(id)).append('\n'); sb.append("ID (dec): ").append(Utils.toDec(id)).append('\n'); sb.append("ID (reversed dec): ").append(Utils.toReversedDec(id)).append('\n'); String prefix = "android.nfc.tech."; sb.append("Technologies: "); for (String tech : tag.getTechList()) { sb.append(tech.substring(prefix.length())); sb.append(", "); } sb.delete(sb.length() - 2, sb.length()); for (String tech : tag.getTechList()) { if (tech.equals(MifareClassic.class.getName())) { sb.append('\n'); String type = "Unknown"; try { MifareClassic mifareTag = MifareClassic.get(tag); switch (mifareTag.getType()) { case MifareClassic.TYPE_CLASSIC: type = "Classic"; break; case MifareClassic.TYPE_PLUS: type = "Plus"; break; case MifareClassic.TYPE_PRO: type = "Pro"; break; } sb.append("Mifare Classic type: "); sb.append(type); sb.append('\n'); sb.append("Mifare size: "); sb.append(mifareTag.getSize() + " bytes"); sb.append('\n'); sb.append("Mifare sectors: "); sb.append(mifareTag.getSectorCount()); sb.append('\n'); sb.append("Mifare blocks: "); sb.append(mifareTag.getBlockCount()); } catch (Exception e) { sb.append("Mifare classic error: " + e.getMessage()); } } if (tech.equals(MifareUltralight.class.getName())) { sb.append('\n'); MifareUltralight mifareUlTag = MifareUltralight.get(tag); String type = "Unknown"; switch (mifareUlTag.getType()) { case MifareUltralight.TYPE_ULTRALIGHT: type = "Ultralight"; break; case MifareUltralight.TYPE_ULTRALIGHT_C: type = "Ultralight C"; break; } sb.append("Mifare Ultralight type: "); sb.append(type); } } return sb.toString(); } @Override protected void onNewIntent(Intent intent) { setIntent(intent); resolveIntent(intent); } private void resolveIntent(Intent intent) { String action = intent.getAction(); if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action) || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action) || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) { Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); NdefMessage[] msgs; if (rawMsgs != null) { msgs = new NdefMessage[rawMsgs.length]; for (int i = 0; i < rawMsgs.length; i++) { msgs[i] = (NdefMessage) rawMsgs[i]; } } else { byte[] empty = new byte[0]; byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID); Tag tag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); byte[] payload = dumpTagData(tag).getBytes(); NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, id, payload); NdefMessage msg = new NdefMessage(new NdefRecord[] {record}); msgs = new NdefMessage[] {msg}; Intent data = new Intent(); data.putExtra(NFC_ID_KEY, Utils.toHex(id)); setResult(RESULT_OK, data); } displayMsgs(msgs); } } private void displayMsgs(NdefMessage[] msgs) { if (msgs == null || msgs.length == 0) return; // StringBuilder builder = new StringBuilder(); // List<ParsedNdefRecord> records = NdefMessageParser.parse(msgs[0]); // final int size = records.size(); // // for (int i = 0; i < size; i++) { // ParsedNdefRecord record = records.get(i); // String str = record.str(); // builder.append(str).append("\n"); // } // Play a noise ToneGenerator toneG = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, ToneGenerator.MAX_VOLUME); toneG.startTone(ToneGenerator.TONE_CDMA_ANSWER, 200); //200 is duration in ms // Vibrate phone Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); // Vibrate for 500 milliseconds if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { v.vibrate(VibrationEffect.createOneShot(200, VibrationEffect.DEFAULT_AMPLITUDE)); } else { //deprecated in API 26 v.vibrate(200); } displaySuccessAnimation(); } private void displaySuccessAnimation() { nfcAnimation.setVisibility(View.GONE); text.setVisibility(View.GONE); checkAnimation.setVisibility(View.VISIBLE); textSuccess.setVisibility(View.VISIBLE); checkAnimation.playAnimation(); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { finish(); } }, 2500); } } <file_sep>package com.squad.betakua.tap_neko; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.TableRow; import android.widget.TextView; import android.widget.Toast; import com.airbnb.lottie.LottieAnimationView; import com.squad.betakua.tap_neko.azure.AzureInterface; import com.squad.betakua.tap_neko.azure.AzureInterfaceException; import com.squad.betakua.tap_neko.nfc.NFCActivity; import java.io.FileInputStream; import java.io.FileNotFoundException; import static com.squad.betakua.tap_neko.nfc.NFCActivity.NFC_ID_KEY; import static com.squad.betakua.tap_neko.nfc.NFCActivity.NFC_REQ_CODE; /** * Created by sherryuan on 2019-01-26. */ public class PharmacistActivity extends AppCompatActivity { public static final int BARCODE_REQ_CODE = 100; public static final String BARCODE_KEY = "barcode"; public static final int AUDIO_REQ_CODE = 101; private TableRow audioRecorderButton; private String outputFile; private boolean hasAudio = false; private TableRow barcodeScannerButton; private String barcodeId; private boolean hasBarcode = false; private TableRow nfcButton; private ImageButton submitButton; private String nfcId; private boolean hasNfcId = false; private TextView textBarcode; private TextView textNFC; private TextView textAudio; private LottieAnimationView lottieBarcode; private LottieAnimationView lottieNFC; private LottieAnimationView lottieAudio; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pharmacist); initAudioRecorderButton(); initBarcodeScannerButton(); initNfcButton(); initSubmitButton(); refreshSubmitButton(); textBarcode = findViewById(R.id.scan_text); textNFC = findViewById(R.id.nfc_text); textAudio = findViewById(R.id.audio_text); lottieBarcode = findViewById(R.id.check_barcode); lottieNFC = findViewById(R.id.check_nfc); lottieAudio = findViewById(R.id.check_audio); outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp"; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == BARCODE_REQ_CODE && resultCode == RESULT_OK) { barcodeId = data.getStringExtra(BARCODE_KEY); hasBarcode = true; // change colors textBarcode.setTextColor(Color.parseColor("#FFFFFF")); barcodeScannerButton.setBackgroundColor(Color.parseColor("#6dcc5b")); lottieBarcode.playAnimation(); refreshSubmitButton(); } else if (requestCode == AUDIO_REQ_CODE && resultCode == RESULT_OK) { // get audio hasAudio = true; Toast.makeText(this, "got audio", Toast.LENGTH_SHORT).show(); // change colors textAudio.setTextColor(Color.parseColor("#FFFFFF")); audioRecorderButton.setBackgroundColor(Color.parseColor("#6dcc5b")); lottieAudio.playAnimation(); refreshSubmitButton(); } else if (requestCode == NFC_REQ_CODE && resultCode == RESULT_OK) { // get NFC id nfcId = data.getStringExtra(NFC_ID_KEY); hasNfcId = true; // change colors textNFC.setTextColor(Color.parseColor("#FFFFFF")); nfcButton.setBackgroundColor(Color.parseColor("#6dcc5b")); lottieNFC.playAnimation(); refreshSubmitButton(); } } private void initAudioRecorderButton() { audioRecorderButton = findViewById(R.id.audio_recorder_button); audioRecorderButton.setOnClickListener((View view) -> { Intent audioRecorderIntent = new Intent(getApplicationContext(), AudioRecorderActivity.class); startActivityForResult(audioRecorderIntent, AUDIO_REQ_CODE); }); } private void initBarcodeScannerButton() { barcodeScannerButton = findViewById(R.id.barcode_scanner_button); barcodeScannerButton.setOnClickListener((View view) -> { Intent barcodeScannerIntent = new Intent(getApplicationContext(), BarcodeScannerActivity.class); startActivityForResult(barcodeScannerIntent, BARCODE_REQ_CODE); }); } private void initSubmitButton() { submitButton = findViewById(R.id.submit_button); submitButton.setOnClickListener((View view) -> { try { final String translationID = nfcId + "_fr"; AzureInterface.getInstance().uploadAudio(nfcId, new FileInputStream(outputFile), -1); AzureInterface.getInstance().writeInfoItem(nfcId, barcodeId, "", "https://www.youtube.com/watch?v=uGkbreu169Q"); final Handler handler = new Handler(); handler.postDelayed(() -> { }, 1500); } catch (AzureInterfaceException | FileNotFoundException e) { e.printStackTrace(); } }); } // submit button should only be enabled if both audio, barcode, and NFC have been prepared private void refreshSubmitButton() { if (hasAudio && hasBarcode && hasNfcId) { submitButton.setEnabled(true); } else { submitButton.setEnabled(false); } } public void initNfcButton() { nfcButton = findViewById(R.id.nfc_button); nfcButton.setOnClickListener((View view) -> { Intent intent = new Intent(PharmacistActivity.this, NFCActivity.class); startActivityForResult(intent, NFC_REQ_CODE); }); } } <file_sep>package com.squad.betakua.tap_neko; import android.Manifest; import android.content.pm.PackageManager; import android.media.MediaPlayer; import android.media.MediaRecorder; import android.os.Bundle; import android.os.Environment; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.Toast; import java.io.IOException; /** * Created by sherryuan on 2019-01-26. */ public class AudioRecorderActivity extends AppCompatActivity { public static final String TRANSCRIPTION_STR_KEY = "transcribed string"; public static final String TRANSLATION_STR_KEY = "translated string"; private Button recordButton; private Button stopButton; private Button playButton; private Button saveButton; private static int REQUEST_CODE = 24; private MediaRecorder audioRecorder; private String outputFile; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_audio_recorder); outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp"; // ask for permissions if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, REQUEST_CODE); } else { initAudioRecorder(); initRecordButton(); initStopButton(); initPlayButton(); initSaveButton(); stopButton.setEnabled(false); playButton.setEnabled(false); saveButton.setEnabled(false); } } private void initAudioRecorder() { audioRecorder = new MediaRecorder(); audioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); audioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); audioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB); audioRecorder.setOutputFile(outputFile); } private void initRecordButton() { recordButton = findViewById(R.id.record_button); recordButton.setOnClickListener((View view) -> { try { audioRecorder.prepare(); audioRecorder.start(); } catch (IllegalStateException | IOException e) { e.printStackTrace(); } recordButton.setEnabled(false); stopButton.setEnabled(true); Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show(); }); } private void initStopButton() { stopButton = findViewById(R.id.stop_button); stopButton.setOnClickListener((View view) -> { if (ContextCompat.checkSelfPermission(AudioRecorderActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(AudioRecorderActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE); } else { audioRecorder.stop(); audioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); audioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); audioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB); audioRecorder.setOutputFile(outputFile); } recordButton.setEnabled(true); stopButton.setEnabled(false); playButton.setEnabled(true); saveButton.setEnabled(true); Toast.makeText(getApplicationContext(), "Audio Recorder stopped", Toast.LENGTH_LONG).show(); }); } private void initPlayButton() { playButton = findViewById(R.id.play_button); playButton.setOnClickListener((View view) -> { MediaPlayer mediaPlayer = new MediaPlayer(); try { mediaPlayer.setDataSource(outputFile); mediaPlayer.prepare(); mediaPlayer.start(); Toast.makeText(getApplicationContext(), "Playing Audio", Toast.LENGTH_LONG).show(); } catch (Exception e) { // make something e.printStackTrace(); } }); } private void initSaveButton() { saveButton = findViewById(R.id.save_button); saveButton.setOnClickListener((View view) -> { setResult(RESULT_OK); finish(); }); } } <file_sep>package com.squad.betakua.tap_neko; import android.content.Intent; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.MediaController; import android.widget.ScrollView; import android.widget.Toast; import android.widget.VideoView; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.microsoft.windowsazure.mobileservices.MobileServiceList; import com.rd.PageIndicatorView; import com.squad.betakua.tap_neko.azure.AzureInterface; import com.squad.betakua.tap_neko.azure.AzureInterfaceException; import com.squad.betakua.tap_neko.azure.InfoItem; import com.squad.betakua.tap_neko.nfc.NFCActivity; import com.squad.betakua.tap_neko.patientListeners.TranscriptListener; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import static com.squad.betakua.tap_neko.nfc.NFCActivity.NFC_ID_KEY; import static com.squad.betakua.tap_neko.nfc.NFCActivity.NFC_REQ_CODE; /** * Created by sherryuan on 2019-01-26. */ public class PatientActivity extends AppCompatActivity { private Button stopButton; private Button playButton; //Pages in pagerView private static final int NUM_PAGES = 3; //Allows swiping between fragments private ViewPager mPager; //Provides the pages (fragments) to the ViewPager private PagerAdapter mPagerAdapter; private TranscriptListener transcriptListener; VideoView vidView; MediaController vidControl; private boolean hasInfo = false; private String nfcId; private String barcodeId; private boolean hasAudio = false; private MediaPlayer mediaPlayer = new MediaPlayer(); private String outputFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp"; private File outputFile = new File(outputFilePath); private FileOutputStream audioStream; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_patient); nfcId = getIntent().getStringExtra(NFC_ID_KEY); loadData(); initAudioPlayer(); initPlayButton(); initStopButton(); initVideoPlayer(); mPager = findViewById(R.id.pager); mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager()); mPager.setAdapter(mPagerAdapter); } private void loadData() { try { ListenableFuture<MobileServiceList<InfoItem>> infoItemsFuture = AzureInterface.getInstance().readInfoItem(nfcId); Futures.addCallback(infoItemsFuture, new FutureCallback<MobileServiceList<InfoItem>>() { public void onSuccess(MobileServiceList<InfoItem> infoItems) { hasInfo = true; barcodeId = infoItems.get(0).getProductID(); } public void onFailure(Throwable t) { t.printStackTrace(); } }); outputFile.createNewFile(); audioStream = new FileOutputStream(outputFile, false); AzureInterface.getInstance().downloadAudio(outputFilePath, audioStream); audioStream.close(); } catch (AzureInterfaceException | IOException e) { e.printStackTrace(); } } // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // if (requestCode == NFC_REQ_CODE && resultCode == RESULT_OK) { // try { // String nfcId = data.getStringExtra(NFC_ID_KEY); // ListenableFuture<MobileServiceList<InfoItem>> infoItemsFuture = AzureInterface.getInstance().readInfoItem(nfcId); // // Futures.addCallback(infoItemsFuture, new FutureCallback<MobileServiceList<InfoItem>>() { // public void onSuccess(MobileServiceList<InfoItem> infoItems) { // hasInfo = true; // barcodeId = infoItems.get(0).getProductID(); // } // // public void onFailure(Throwable t) { // t.getStackTrace(); // } // }); // audioStream = new FileOutputStream(outputFile, false); // AzureInterface.getInstance().downloadAudio(outputFilePath, audioStream); // audioStream.close(); // } catch (AzureInterfaceException | IOException e) { // e.printStackTrace(); // } // } // } private void initAudioPlayer() { try { mediaPlayer.setDataSource(outputFilePath); mediaPlayer.prepare(); mediaPlayer.start(); Toast.makeText(getApplicationContext(), "Playing Audio", Toast.LENGTH_LONG).show(); } catch (Exception e) { // make something e.printStackTrace(); } } private void initPlayButton() { playButton = findViewById(R.id.play_button); playButton.setOnClickListener((View view) -> { mediaPlayer.start(); Toast.makeText(getApplicationContext(), "Playing Audio", Toast.LENGTH_LONG).show(); }); } private void initStopButton() { stopButton = findViewById(R.id.stop_button); stopButton.setOnClickListener((View view) -> { mediaPlayer.stop(); }); } private void initVideoPlayer() { vidView = findViewById(R.id.video); String vidAddress = "https://archive.org/download/ksnn_compilation_master_the_internet/ksnn_compilation_master_the_internet_512kb.mp4"; Uri vidUri = Uri.parse(vidAddress); vidView.setVideoURI(vidUri); // vidView.start(); vidControl = new MediaController(this); vidControl.setAnchorView(vidView); vidView.setMediaController(vidControl); } @Override public void onBackPressed() { if (mPager.getCurrentItem() == 0) { // If the user is currently looking at the first step, allow the system to handle the // Back button. This calls finish() on this activity and pops the back stack. super.onBackPressed(); } else { // Otherwise, select the previous step. mPager.setCurrentItem(mPager.getCurrentItem() - 1); } } private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter { public ScreenSlidePagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { switch (position) { case 0: { return new ScreenSlideAudioPlayFragment(); } case 1: { ScreenSlideTextPanelFragment screenSlideTextPanelFragment = new ScreenSlideTextPanelFragment(); transcriptListener = screenSlideTextPanelFragment; return screenSlideTextPanelFragment; } case 2: { return new ScreenSlideVideoPanelFragment(); } } return null; } @Override public int getCount() { return NUM_PAGES; } } } <file_sep>package com.squad.betakua.tap_neko.azure; import android.content.Context; import com.google.common.util.concurrent.ListenableFuture; import com.microsoft.azure.storage.CloudStorageAccount; import com.microsoft.azure.storage.StorageException; import com.microsoft.azure.storage.blob.*; import com.microsoft.cognitiveservices.speech.*; import com.microsoft.cognitiveservices.speech.translation.SpeechTranslationConfig; import com.microsoft.cognitiveservices.speech.translation.TranslationRecognizer; import com.microsoft.windowsazure.mobileservices.MobileServiceClient; import com.microsoft.windowsazure.mobileservices.MobileServiceList; import com.microsoft.windowsazure.mobileservices.table.MobileServiceTable; import com.squad.betakua.tap_neko.BuildConfig; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.security.InvalidKeyException; import java.util.List; import java.util.UUID; public class AzureInterface { private static final String CONNECTION_STRING_TEMPLATE = "DefaultEndpointsProtocol=https;" + "AccountName=%s;" + "AccountKey=%s"; private static final String STORAGE_ACCOUNT_NAME = BuildConfig.AzureStorageAccountName; private static final String STORAGE_ACCOUNT_KEY = BuildConfig.AzureStorageAccountKey; private static final String SPEECH_SUB_KEY = BuildConfig.AzureSpeechSubscriptionKey; private static final String SERVICE_REGION = "westus"; private static AzureInterface AZURE_INTERFACE = null; private final CloudStorageAccount storageAccount; private final MobileServiceTable<InfoItem> infoTable; private final MobileServiceTable<DrugInfoItem> drugInfoTable; private final SpeechConfig speechConfig; /** * Initialize singleton instance of Azure interface * Note: Ensure you have Azure storage account name and key in gradle.properties * * @param context Context to pass to Azure Mobile App SDK * @throws AzureInterfaceException If something goes wrong */ public static void init(Context context) throws AzureInterfaceException { if (AZURE_INTERFACE == null) { AZURE_INTERFACE = new AzureInterface(context); } throw new AzureInterfaceException("AzureInterface already initialized"); } /** * Get singleton instance of Azure interface * * @return Singleton instance of Azure interface * @throws AzureInterfaceException If something goes wrong */ public static AzureInterface getInstance() throws AzureInterfaceException { if (AZURE_INTERFACE == null) { throw new AzureInterfaceException("AzureInterface not initialized yet"); } return AZURE_INTERFACE; } private AzureInterface(Context context) throws AzureInterfaceException { try { final String connectionString = String.format(CONNECTION_STRING_TEMPLATE, STORAGE_ACCOUNT_NAME, STORAGE_ACCOUNT_KEY); this.storageAccount = CloudStorageAccount.parse(connectionString); final MobileServiceClient mobileServiceClient = new MobileServiceClient("https://neko-tap.azurewebsites.net", context); this.infoTable = mobileServiceClient.getTable("InfoTable", InfoItem.class); this.drugInfoTable = mobileServiceClient.getTable("DrugInfoTable", DrugInfoItem.class); this.speechConfig = SpeechConfig.fromSubscription(SPEECH_SUB_KEY, SERVICE_REGION); } catch (URISyntaxException | InvalidKeyException | MalformedURLException e) { throw new AzureInterfaceException(e.getMessage()); } } /** * Write a new info item to the Azure InfoTable * * @param nfcID NFC ID * @param productID Product ID * @param transcript Transcript of instruction audio */ public void writeInfoItem(String nfcID, String productID, String transcript, String url) { final InfoItem item = new InfoItem(); item.setId(UUID.randomUUID().toString()); item.setNfcID(nfcID); item.setProductID(productID); item.setTranscript(transcript); item.setURL(url); this.infoTable.insert(item); } /** * Look up an info item in Azure InfoTable by NFC ID * * @param nfcID NFC ID to look up * @return Future for a list of matching InfoItems */ public ListenableFuture<MobileServiceList<InfoItem>> readInfoItem(String nfcID) { return this.infoTable.where().field("nfcID").eq(nfcID).execute(); } /** * Write a new drug info item to the Azure DrugInfoTable * * @param nfcID NFC ID * @param text Text of instructions * @param youtubeURL YouTube URL of how-to video */ public void writeDrugInfoItem(String nfcID, String text, String youtubeURL) { final DrugInfoItem item = new DrugInfoItem(); item.setId(UUID.randomUUID().toString()); item.setNfcID(nfcID); item.setText(text); item.setYoutubeURL(youtubeURL); this.drugInfoTable.insert(item); } /** * Look up a drug info item in Azure DrugInfoTable by NFC ID * @param nfcID NFC ID to look up * @return Future for a list of matching InfoItems */ public ListenableFuture<MobileServiceList<DrugInfoItem>> readDrugInfoItem(String nfcID) { return this.drugInfoTable.where().field("nfcID").eq(nfcID).execute(); } /** * Upload an audio file to Azure * Warning: will overwrite file if file with the same audioTitle already exists * * @param audioTitle Title of audio clip to store; note: should be `$NFCID_$LANG` * @param in InputStream to read from * @param length Length in bytes of file (or -1 if unknown) */ public void uploadAudio(final String audioTitle, final InputStream in, final long length) { new Thread(() -> { try { final CloudBlobClient blobClient = this.storageAccount.createCloudBlobClient(); final CloudBlobContainer container = blobClient.getContainerReference("instructionaudio"); final CloudBlockBlob blockBlob = container.getBlockBlobReference(audioTitle); blockBlob.upload(in, length); } catch (URISyntaxException | StorageException | IOException e) { e.printStackTrace(); } }).start(); } /** * Download audio file from Azure * * @param audioTitle Title of audio clip in Azure Storage; note: should be `$NFCID_$LANG` * @param out OutputStream to write to */ public void downloadAudio(final String audioTitle, final OutputStream out) { new Thread(() -> { try { final CloudBlobClient blobClient = this.storageAccount.createCloudBlobClient(); final CloudBlobContainer container = blobClient.getContainerReference("instructionaudio"); final CloudBlockBlob blockBlob = container.getBlockBlobReference(audioTitle); blockBlob.download(out); } catch (URISyntaxException | StorageException e) { try { throw new AzureInterfaceException(e.getMessage()); } catch (AzureInterfaceException e1) { e1.printStackTrace(); } } }).start(); } /** * Create a new speech recognizer (for speech-to-text). * Subscribe to `recognizing` and `recognized` events to receive data while transcribing * and after transcription complete, respectively, then call `startContinuousRecognitionAsync()` * and `stopContinuousRecognitionAsync()` to start and stop transcription. * <p> * Note: see https://docs.microsoft.com/en-ca/azure/cognitive-services/speech-service/how-to-recognize-speech-java * for more details * * @return New speech recognizer */ public SpeechRecognizer getSpeechRecognizer() { return new SpeechRecognizer(speechConfig); } /** * Create a new translation recognizer (for speech translation). * Subscribe to the `recognizing`, `recognized`, and `synthesizing` events to * receive text data while translating, text data after translation complete, and speech * data after translation complete, respectively, then call `startContinuousRecognitionAsync()` * and `stopContinuousRecognitionAsync()` to start and stop transcription. * <p> * Note: see https://docs.microsoft.com/en-ca/azure/cognitive-services/speech-service/how-to-translate-speech-java * for more details * * @param outputLanguages List of languages to translate to * @return New speech translator */ public TranslationRecognizer getTranslationRecognizer(final List<String> outputLanguages) { SpeechTranslationConfig config = SpeechTranslationConfig.fromSubscription(SPEECH_SUB_KEY, SERVICE_REGION); for (final String lang : outputLanguages) { config.addTargetLanguage(lang); } return new TranslationRecognizer(config); } }
052b78d9fcd5a5b669e5d448a4cdc5ca3f13682e
[ "Java" ]
5
Java
PiggySpeed/NekoTap
6fa291796432f09ef866ca819288bceef7da5762
d42bf09464803710e8e46e207519bc062419f02a
refs/heads/master
<file_sep>// // CollectionViewCell.swift // Flix // // Created by <NAME> on 2/6/19. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit class CollectionViewCell: UICollectionViewCell { } <file_sep>// // MovieGridCell.swift // Flix // // Created by <NAME> on 2/6/19. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit import AlamofireImage class MovieGridCell: UICollectionViewCell { @IBOutlet weak var posterView: UIImageView! }
888f220c76b322e1089570899dcfbbd7032577fd
[ "Swift" ]
2
Swift
iTransCode/Flix2
b4b97fbd40f12f1d37b8a85674f838376b2ab608
7fe8f45759c6d5cbae4c7f98921c083b5763f191
refs/heads/master
<repo_name>dasger3/Dasha_Dmitrenko<file_sep>/src/main/java/models/Wardrobe.java package models; import lombok.AllArgsConstructor; import lombok.Data; import java.util.*; @Data @AllArgsConstructor public class Wardrobe { private ArrayList<Look> looks; }
378a398eb31d9bd97bfe0cabb360a35719e2a195
[ "Java" ]
1
Java
dasger3/Dasha_Dmitrenko
1040cda220175f8d7d3844baba4918c1ab133b7b
8c9d1897dd0a2065a7b1dff1f0cd9ad1de83d25a
refs/heads/master
<file_sep># tomee-microprofile-rest-client-demo Type-Safe Approach to Invoking RESTful Services with MicroProfile Rest Client on TomEE ## Build mvn clean install ### Build specific module mvn clean install -pl movie-app/services -am ## Run movies service mvn clean install -pl movie-app/services tomee:run Navigate to `http://localhost:8181/moviefun/api/movies/` ## Run cinema web app Go to cinema-app/cinema-webapp mvn clean install tomee:run Navigate to http://localhost:4444/cinema-webapp/api/cinema/movies <file_sep><?xml version="1.0" encoding="UTF-8"?> <!-- ~ Tomitribe Confidential ~ ~ Copyright Tomitribe Corporation. 2016 ~ ~ The source code for this program is not published or otherwise divested ~ of its trade secrets, irrespective of what has been deposited with the ~ U.S. Copyright Office. --> <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>org.superbiz</groupId> <artifactId>tomee-microprofile-rest-client-demo</artifactId> <version>1.0-SNAPSHOT</version> <packaging>pom</packaging> <modules> <module>movie-app</module> <module>cinema-app</module> </modules> </project> <file_sep>/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. */ package org.superbiz.moviefun; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import org.superbiz.moviefun.model.Movie; import org.superbiz.moviefun.rest.ApplicationConfig; import org.superbiz.moviefun.rest.MoviesResource; import org.superbiz.moviefun.service.MoviesService; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.logging.Logger; import static org.junit.Assert.assertEquals; //https://jersey.github.io/documentation/latest/client.html @RunWith(Arquillian.class) public class JaxRsClientTest { private static final Logger LOGGER = Logger.getLogger(JaxRsClientTest.class.getName()); @Deployment() public static WebArchive createDeployment() { final WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "test.war") .addClasses(Movie.class, MoviesService.class) .addClasses(MoviesResource.class, ApplicationConfig.class) .addAsWebInfResource(new StringAsset("<beans/>"), "beans.xml"); LOGGER.info(webArchive.toString(true)); return webArchive; } @Test public void Get() { Client client = ClientBuilder.newClient(); String response = client.target("http://localhost:4444/test/api/movies/count") .request(MediaType.TEXT_PLAIN) .get(String.class); LOGGER.info("I found ["+response+"] movies."); assertEquals("5",response); client.close(); } @Test public void Post() throws Exception{ Client client = ClientBuilder.newClient(); //POST Movie newMovieObj = new Movie("Duke","The JAX-RS WebClient API.",2018); Response response = client.target("http://localhost:4444/test/api/movies") .request(MediaType.APPLICATION_JSON).post(Entity.json(newMovieObj)); LOGGER.info("POST request obtained ["+response.getStatus()+"]response code."); assertEquals(200,response.getStatus()); //GET Movie obtainedMovie = client.target("http://localhost:4444/test/api/movies/6") .request(MediaType.APPLICATION_JSON).get(Movie.class); LOGGER.info("Movie with id [200] hast the title: " +obtainedMovie.getTitle()); assertEquals("The JAX-RS WebClient API.",obtainedMovie.getTitle()); client.close(); } } <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"> <parent> <groupId>org.superbiz</groupId> <artifactId>cinema-app</artifactId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <groupId>io.superbiz.netflix</groupId> <artifactId>cinema-webapp</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>org.superbiz</groupId> <artifactId>client</artifactId> <version>1.0-SNAPSHOT</version> <exclusions> <exclusion> <groupId>org.apache.cxf</groupId> <artifactId>*</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.tomee</groupId> <artifactId>javaee-api</artifactId> <version>8.0</version> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.tomee.maven</groupId> <artifactId>tomee-maven-plugin</artifactId> <version>8.0.0-M1</version> <configuration> <tomeeClassifier>microprofile</tomeeClassifier> <tomeeAjpPort>1111</tomeeAjpPort> <tomeeShutdownPort>2222</tomeeShutdownPort> <tomeeHttpPort>4444</tomeeHttpPort> <context>${artifactId}</context> </configuration> </plugin> </plugins> </build> </project><file_sep>/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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. */ package org.superbiz.moviefun.service; import com.github.javafaker.Faker; import org.superbiz.moviefun.model.Movie; import javax.ejb.Lock; import javax.ejb.LockType; import javax.ejb.Singleton; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Random; @Singleton @Lock(LockType.READ) public class MoviesService { public List<Movie> catalog; public int id=0; public List<Movie> getCatalog() { return catalog; } public MoviesService() { catalog = new ArrayList(); load(); } public Movie addMovie(Movie movie) { this.id++; movie.setId(this.id); catalog.add(movie); return movie; } public List<Movie> getMovies(){ return catalog; } public void deleteMovie(long id) { boolean b = catalog.removeIf(obj -> obj.getId() == id); } public Movie find(Long id) { for (Movie movie : catalog) { if(movie.getId() == id){ return movie; } } return null; } public void updateMovie(Long id, Movie newMovieData){ Movie oldMovieData = find(id); if (newMovieData.getTitle() != null){ oldMovieData.setTitle(newMovieData.getTitle());} if (newMovieData.getDirector() != null){ oldMovieData.setDirector(newMovieData.getDirector());} if (newMovieData.getYear() != -1){ oldMovieData.setYear(newMovieData.getYear());} if (newMovieData.getGenre() != null){ oldMovieData.setGenre(newMovieData.getGenre());} if (newMovieData.getRating() != -1){ oldMovieData.setRating(newMovieData.getRating());} } public int count(){ return catalog.size(); } public void clear(){ catalog.clear(); } public void load() { final Faker faker = new Faker(Locale.ENGLISH); final Random random = new Random(System.nanoTime()); for (int i = 0 ; i < 5 ; i++) { addMovie( new Movie( faker.book().title(), faker.book().author(), faker.book().genre(), random.nextInt(10), 1960 + random.nextInt(50) ) ); } } }<file_sep>package org.superbiz.moviefun; import org.eclipse.microprofile.rest.client.RestClientBuilder; import org.eclipse.microprofile.rest.client.inject.RestClient; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import org.superbiz.moviefun.model.Movie; import org.superbiz.moviefun.mpclient.MovieResourceClient; import org.superbiz.moviefun.rest.ApplicationConfig; import org.superbiz.moviefun.rest.MoviesResource; import org.superbiz.moviefun.service.MoviesService; import javax.inject.Inject; import java.net.URL; import java.util.List; import java.util.logging.Logger; @RunWith(Arquillian.class) public class MpRestClientTest { private static final Logger LOGGER = Logger.getLogger(MpRestClientTest.class.getName()); @Deployment() public static WebArchive createDeployment() { final WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "movies.war") .addClasses(Movie.class, MoviesService.class, MovieResourceClient.class) .addClasses(MoviesResource.class, ApplicationConfig.class) .addAsWebInfResource(new StringAsset("<beans/>"), "beans.xml") .addAsResource("META-INF/microprofile-config.properties"); LOGGER.info(webArchive.toString(true)); return webArchive; } @Test public void GetProgrammatic() throws Exception{ MovieResourceClient simpleGetApi = RestClientBuilder.newBuilder() .baseUrl(new URL("http://localhost:4444")) .build(MovieResourceClient.class); int count = simpleGetApi.count("",""); LOGGER.info(Integer.toString(count)); } @Inject @RestClient private MovieResourceClient movieResourceClient; @Test public void GetCDI(){ int count = movieResourceClient.count("",""); LOGGER.info(Integer.toString(count)); } @Test public void GetCDIMovies(){ List<Movie> movies = movieResourceClient.getMovies(); for (Movie movie : movies) { LOGGER.info(movie.toString()); } } @Test public void PostCDI() { Movie newMovie = new Movie ("Duke","The MicroProfile Type-safe REST Client.",2018); movieResourceClient.addMovie(newMovie); List<Movie> movies = movieResourceClient.getMovies(); for (Movie movie : movies) { LOGGER.info(movie.toString()); } } } <file_sep># tomee-microprofile-rest-client-demo Type-Safe Approach to Invoking RESTful Services with MicroProfile Rest Client on TomEE ## Run prject arquillian tests mvn clean test ## Run with TomEE embedded mvn clean install tomee:run Navigate to `http://localhost:8181/moviefun/api/movies/` <file_sep><?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You 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. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.superbiz</groupId> <artifactId>movie-app</artifactId> <version>1.0-SNAPSHOT</version> </parent> <groupId>org.superbiz</groupId> <artifactId>services</artifactId> <version>1.0.0-SNAPSHOT</version> <packaging>war</packaging> <name>services</name> <scm> <connection>scm:git:git<EMAIL>:eclipse/microprofile-rest-client.git</connection> <developerConnection>scm:git:git@<EMAIL>:eclipse/microprofile-rest-client.git</developerConnection> <url>scm:git:git@<EMAIL>:eclipse/microprofile-rest-client.git</url> <tag>HEAD</tag> </scm> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <tomee.version>8.0.0-M1</tomee.version> <version.shrinkwrap.resolver>2.0.0</version.shrinkwrap.resolver> <version.microprofile>1.3</version.microprofile> </properties> <distributionManagement> <repository> <id>localhost</id> <url>file://${basedir}/target/repo/</url> </repository> <snapshotRepository> <id>localhost</id> <url>file://${basedir}/target/snapshot-repo/</url> </snapshotRepository> </distributionManagement> <repositories> <repository> <id>apache.milestone.https</id> <name>Apache Development Snapshot Repository</name> <url>https://repository.apache.org/content/repositories/orgapachetomee-1127</url> </repository> <repository> <id>apache.snapshots.https</id> <name>Apache Development Snapshot Repository</name> <url>https://repository.apache.org/content/repositories/snapshots</url> </repository> <repository> <id>apache-m2-snapshot</id> <name>Apache Snapshot Repository</name> <url>https://repository.apache.org/content/groups/snapshots</url> </repository> <repository> <id>tomitribe-public</id> <name>Tomitribe Releases Public</name> <url>https://repository.tomitribe.com/content/repositories/releases</url> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>apache.milestone.https</id> <name>Apache Development Snapshot Repository</name> <url>https://repository.apache.org/content/repositories/orgapachetomee-1127</url> </pluginRepository> <pluginRepository> <id>apache.snapshots.https</id> <name>Apache Development Snapshot Repository</name> <url>https://repository.apache.org/content/repositories/snapshots</url> </pluginRepository> <pluginRepository> <id>apache-m2-snapshot</id> <name>Apache Snapshot Repository</name> <url>https://repository.apache.org/content/groups/snapshots</url> </pluginRepository> <pluginRepository> <id>tomitribe-public</id> <name>Tomitribe Releases Public</name> <url>https://repository.tomitribe.com/content/repositories/releases</url> </pluginRepository> </pluginRepositories> <build> <defaultGoal>install</defaultGoal> <finalName>services</finalName> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.java</include> </includes> </resource> </resources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>3.1.0</version> <executions> <execution> <phase>package</phase> <goals> <goal>jar</goal> </goals> <configuration> <classifier>classes</classifier> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.18.1</version> <configuration> <reuseForks>false</reuseForks> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.tomee.maven</groupId> <artifactId>tomee-maven-plugin</artifactId> <version>${tomee.version}</version> <configuration> <tomeeClassifier>microprofile</tomeeClassifier> <tomeeHttpPort>8181</tomeeHttpPort> <args>-Xmx512m -XX:PermSize=256m</args> <config>${project.basedir}/src/main/tomee/</config> </configuration> </plugin> </plugins> </build> <dependencyManagement> <dependencies> <!-- Override dependency resolver with test version. This must go *BEFORE* the Arquillian BOM. --> <dependency> <groupId>org.jboss.shrinkwrap.resolver</groupId> <artifactId>shrinkwrap-resolver-bom</artifactId> <version>${version.shrinkwrap.resolver}</version> <scope>import</scope> <type>pom</type> </dependency> <!-- Now pull in our server-based unit testing framework --> <dependency> <groupId>org.jboss.arquillian</groupId> <artifactId>arquillian-bom</artifactId> <version>1.0.3.Final</version> <scope>import</scope> <type>pom</type> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>org.apache.tomee</groupId> <artifactId>javaee-api</artifactId> <version>8.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.github.javafaker</groupId> <artifactId>javafaker</artifactId> <version>0.15</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.jboss.arquillian.junit</groupId> <artifactId>arquillian-junit-container</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.jboss.shrinkwrap.resolver</groupId> <artifactId>shrinkwrap-resolver-depchain</artifactId> <type>pom</type> <scope>test</scope> </dependency> <!-- to make sure the dependency is downloaded for the tomee maven plugin --> <dependency> <groupId>org.apache.tomee</groupId> <artifactId>apache-tomee</artifactId> <version>${tomee.version}</version> <scope>test</scope> <classifier>microprofile</classifier> <type>zip</type> </dependency> <dependency> <groupId>org.superbiz</groupId> <artifactId>model</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-rs-client</artifactId> <version>3.3.0-SNAPSHOT</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.6</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>fluent-hc</artifactId> <version>4.5.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.eclipse.microprofile</groupId> <artifactId>microprofile</artifactId> <version>${version.microprofile}</version> <type>pom</type> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.tomee</groupId> <artifactId>arquillian-tomee-remote</artifactId> <version>${tomee.version}</version> </dependency> </dependencies> </project><file_sep>org.superbiz.moviefun.mpclient.MovieResourceClient/mp-rest/url=http://localhost:4444<file_sep>/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. */ package org.superbiz.moviefun; import org.apache.cxf.jaxrs.client.WebClient; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import org.superbiz.moviefun.model.Movie; import org.superbiz.moviefun.rest.ApplicationConfig; import org.superbiz.moviefun.rest.MoviesResource; import org.superbiz.moviefun.service.MoviesService; import javax.ws.rs.core.Response; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.logging.Logger; import static org.junit.Assert.assertEquals; //CXF WebClient API http://cxf.apache.org/docs/jax-rs-client-api.html @RunWith(Arquillian.class) public class CxfJaxrsClientTest { private static final Logger LOGGER = Logger.getLogger(CxfJaxrsClientTest.class.getName()); @Deployment() public static WebArchive createDeployment() { final WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "test.war") .addClasses(Movie.class, MoviesService.class) .addClasses(MoviesResource.class, ApplicationConfig.class) .addAsWebInfResource(new StringAsset("<beans/>"), "beans.xml"); LOGGER.info(webArchive.toString(true)); return webArchive; } @Test public void Get() throws Exception{ WebClient webClient = WebClient.create("http://localhost:4444/test"); //GET webClient.reset(); Response response = webClient.path("/api/movies/count").get(); String content = slurp ((InputStream) response.getEntity()); LOGGER.info("I found ["+content+"] movies."); assertEquals(200, response.getStatus()); webClient.close(); } @Test public void Post() { WebClient webClient = WebClient.create("http://localhost:4444/test"); //POST webClient.path("api/movies").type("application/json").accept("application/json"); Movie newMovieObj = new Movie("Duke","The CXF WebClient API.",2018); Response response = webClient.post(newMovieObj); LOGGER.info("POST request obtained ["+response.getStatus()+"]response code."); assertEquals(200,response.getStatus()); //GET webClient.reset(); Movie obtainedMovie = webClient.path("api/movies/6") .accept("application/json").get(Movie.class); LOGGER.info("Movie with id [200] hast the title: " +obtainedMovie.getTitle()); assertEquals("The CXF WebClient API.",obtainedMovie.getTitle()); webClient.close(); } /** * Reusable utility method * Move to a shared class or replace with equivalent */ public static String slurp (final InputStream in) throws IOException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final byte[] buffer = new byte[1024]; int length; while ((length = in.read(buffer)) != -1) { out.write(buffer, 0, length); } out.flush(); return new String(out.toByteArray()); } }
e688fe8a776bf40d5ad27866ce25a47b340d7958
[ "Markdown", "Java", "Maven POM", "INI" ]
10
Markdown
maurojava/tomee-microprofile-rest-client-demo
96985d3ba4f100197ca609d1b4079fe1a4758585
3c0e4cefafe7c3b02c02269c42bd2ca99c4ebb21
refs/heads/master
<file_sep># jpdocx [![Go Report Card](https://goreportcard.com/badge/github.com/sergey-chechaev/jpdocx)](https://goreportcard.com/report/github.com/sergey-chechaev/jpdocx) Library for replacing special words in Microsoft word docx document. Library takes three args – JSON params with key and value, path to docx file and path to result docx file ## Installation If you haven't setup Go before, you need to first set a `GOPATH` (see [https://golang.org/doc/code.html#GOPATH](https://golang.org/doc/code.html#GOPATH)). To fetch and build the code: $ go get github.com/sergey-chechaev/jpdocx/ Then compile it with the go tool: $ go install github.com/sergey-chechaev/jpdocx/ ## Example Usage You have test.docx documents with special words {{val_1}} and {{val_2}}: ``` Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud {{val_1}} ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur {{val_2}} occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum ``` Run: $ jpdocx "{\"val_1\": \"exercitation\", \"val_2\": \"sint\"}" / $ "/path/to/you/file.docx" "/path/to/you/new_file.docx" Output file new_test.docx: ``` Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum ``` <file_sep>package docx import ( "archive/zip" "bufio" "bytes" "encoding/xml" "errors" "io" "io/ioutil" "os" "strings" ) type ReplaceDocx struct { zipReader *zip.ReadCloser content string } func (r *ReplaceDocx) Editable() *Docx { return &Docx{ files: r.zipReader.File, content: r.content, } } func (r *ReplaceDocx) Close() error { return r.zipReader.Close() } type Docx struct { files []*zip.File content string } func (d *Docx) Replace(oldString string, newString string, num int) (err error) { oldString, err = encode(oldString) if err != nil { return err } newString, err = encode(newString) if err != nil { return err } d.content = strings.Replace(d.content, oldString, newString, num) return nil } func (d *Docx) WriteToFile(path string) (err error) { var target *os.File target, err = os.Create(path) if err != nil { return } defer target.Close() err = d.Write(target) return } func (d *Docx) Write(ioWriter io.Writer) (err error) { w := zip.NewWriter(ioWriter) for _, file := range d.files { var writer io.Writer var readCloser io.ReadCloser writer, err = w.Create(file.Name) if err != nil { return err } readCloser, err = file.Open() if err != nil { return err } if file.Name == "word/document.xml" { writer.Write([]byte(d.content)) } else { writer.Write(streamToByte(readCloser)) } } w.Close() return } func ReadDocxFile(path string) (*ReplaceDocx, error) { reader, err := zip.OpenReader(path) if err != nil { return nil, err } content, err := readText(reader.File) if err != nil { return nil, err } return &ReplaceDocx{zipReader: reader, content: content}, nil } func readText(files []*zip.File) (text string, err error) { var documentFile *zip.File documentFile, err = retrieveWordDoc(files) if err != nil { return text, err } var documentReader io.ReadCloser documentReader, err = documentFile.Open() if err != nil { return text, err } text, err = wordDocToString(documentReader) return } func wordDocToString(reader io.Reader) (string, error) { b, err := ioutil.ReadAll(reader) if err != nil { return "", err } return string(b), nil } func retrieveWordDoc(files []*zip.File) (file *zip.File, err error) { for _, f := range files { if f.Name == "word/document.xml" { file = f } } if file == nil { err = errors.New("document.xml file not found") } return } func streamToByte(stream io.Reader) []byte { buf := new(bytes.Buffer) buf.ReadFrom(stream) return buf.Bytes() } func encode(s string) (string, error) { var b bytes.Buffer enc := xml.NewEncoder(bufio.NewWriter(&b)) if err := enc.Encode(s); err != nil { return s, err } return strings.Replace(strings.Replace(b.String(), "<string>", "", 1), "</string>", "", 1), nil } <file_sep>package main import ( "encoding/json" "fmt" "jpdocx/docx" "os" ) func main(){ params := os.Args[1] path := os.Args[2] path_to := os.Args[3] path_str := fmt.Sprintf("%v", path) path_to_str := fmt.Sprintf("%v", path_to) data := []byte(params) objmap := make(map[string]interface{}) err := json.Unmarshal(data, &objmap) if err != nil { fmt.Println(err) } r, err := docx.ReadDocxFile(path_str) if err != nil { panic(err) } docx1 := r.Editable() for key, value := range objmap { str_key := fmt.Sprintf("{{%v}}", key) str_value := fmt.Sprintf("%v", value) docx1.Replace(str_key, str_value, -1) } docx1.WriteToFile(path_to_str) r.Close() fmt.Println("ok") }
1c7a2c395e272448682373450e26079d464ebe25
[ "Markdown", "Go" ]
3
Markdown
sergey-chechaev/jpdocx
105d8ea386b35b71b00662478144e198f756793c
7d902881f6af54ea4b2703c0640aa2761301cb2f
refs/heads/main
<file_sep># Network science Toolbox ### TS2FC The ```TS2FC``` function takes as input the time-series, then it computes the pearson correlation between pair of nodes and generates the time-averaged static FC (functional connectivity) matrix as output with size nxn where n is the number of nodes. The FC gives information on the apatial aspect of time-series and quantifies the degree of similarity between pair of nodes. <img src="images/TS2FC.png" width="800"> ### TS2dFCstream Time-series containe important temporal information which by time-averaged static FC we may miss these informations. One solution to extract the temporal information from time-series is by applying a sliding window approach. The ```TS2dFCstream``` function takes as input the time-series, a fixed size of a window (w), and a length of sliding step (lag). The output of this function is a stream of FC matrices as shown in below cartoon. As you can see in 5 FC matrices, the pairwise correlation between nodes varies by time and it's different for each window. However, the above figure represents only the average of these FCs. The in the below figure, last panel you can also see the 2D representation for each link (between pair of nodes). <img src="images/TS2dFCstream.png" width="500"> ### dFCstream2dFC Sometimes it's important to know how frequent different events (spatial correlations) is repeated along the time-series. The ```dFCstream2dFC``` function takes as input the dFcstream (in 2D or 3D) generated by ```TS2dFCstream``` function and computes a FCD matrix which contains the temporal information of time-series. In below cartoon you can see the spatial events within and between yellow section of time-series are highly correlated or in the other words, the spatial network for a short period of time-series has been repeated along time. On the other hand, the pink windows are rare events which their spatial pattern doesn't correlate with other periods of time. <img src="images/dFCstream2dFC.png" width="800"> ### dFCstream2MC FC quantifies the spatial aspect of time-series, while FCD quantifies the temporal aspect. The ```dFCstream2MC``` function takes as input the dFCstream and generates the MC (meta-connectivity) matrix as output. MC matrix contains the value of correlation between pair of links and since already in link time-series (or streams) the temporal informations are extracted, the MC matrix can provide the spatio-temporal information on the time-series. The sise of MC is lxl where l is the total number of links in a network with n nodes (l=n(n-1)/2). <img src="images/dFCstream2MC.png" width="800"> ### dFCstream2Trimers The MC matrix shown in below is identical with the one above with different colormap. Here we will introduce the concept of trimers. As it was mentioned in the previous paragraph, each MC enteries is the correlation between pair of links where the two links can be driven from 4 nodes (tetramers) or 3 nodes (trimers) where one of the nodes is shared between the two links. Since the MC method is a higher-order correlation, by increasing the number of nodes in a network the number of links may grow exponentially therefore it will be cumbersome to interpret the results. The objective of trimers method was to summaries the spatio-temporal information of time-series drived from MC, on the node-level and all trimers can be stored in a 3D matrix with size of nxnxn. In below cartoon each entrie of MC (on the left) has been identically mapped in trimers format (in the middle). The FC quantifies the direct link between two nodes while trimers quantifies the indirect path between two nodes through a 3rd node in the middle, therefore provides redundant information on the network. If a direct path between two nodes are strongly positive or negative, the value of indirect path (by trimers method) would be approximately equal to the direct path, like first (2-1-3) and third trimer (1-3-2, below middle figure). However, cases can be find in a network like second trimer (1-2-3) where the magnitude of direct path derived from FC differs by indirect path derived from trimers. (trimer 1-2-3: direct path is negative while the indirect path between node 1-3 is positive). <img src="images/dFCstream2Trimers.png" width="800"> <file_sep>#!/usr/bin/env python # coding: utf-8 # In[1]: # This function takes as input the 2D or 3D "dFCstream" calculated from TS2dFCstream function and returns dynamic functional connectivity (dFC) as output. # Example: dfc = dFCstream2MC(dfcstream) # Reference: <NAME> et al. (2020) MethodsX import numpy as np from Matrix2Vec import Matrix2Vec def dFCstream2dFC(dFCstream): if len(dFCstream.shape)==3: FCstr=Matrix2Vec(dFCstream) if len(dFCstream.shape)==2: FCstr=dFCstream if FCstr.shape[1] > 20000: return print('Caution! If length of your dFCstream > 20,000 time-points, this function may take one minutes, if you persist, please comment me!') dFC = np.corrcoef(FCstr.T) return dFC<file_sep>#!/usr/bin/env python # coding: utf-8 # In[1]: # This function takes as input the "time-series" and optional "format" to calculate static functional connectivity (FC) as output. # inputs: TS(t,n) --> rows are t different time-points # columns are n different regions # frmt --> '2D' (default) provides a square [n]x[n] FC matrix # '1D' provides the upper-triangular portion of the FC matrix as [n(n-1)/2]x[1] column vector # Example: fc = TS2FC(ts,'1D') # Reference: <NAME> et al. (2020) MethodsX import numpy as np def TS2FC(*args): TS = args[0] if len(args) < 2: frmt = '2D' else: frmt = args[1] n = TS.shape[1] xo = np.triu_indices(n, k = 1) FCm = np.corrcoef(TS.T) np.fill_diagonal(FCm, 0) FCv = FCm[xo] if frmt == '2D': return FCm else: return FCv<file_sep>#!/usr/bin/env python # coding: utf-8 # In[1]: # This function takes as input the '3D' dFCstream and convert it to '2D' dFCstream. # Reference: <NAME> et al. (2020) MethodsX import numpy as np def Matrix2Vec(dFCstream_3D): if len(dFCstream_3D.shape)==2: return print('You do not need this function since your dFCstream is alread 2D') n = dFCstream_3D.shape[0] l = n*(n-1)/2 F = dFCstream_3D.shape[2] xo = np.triu_indices(n, k = 1) dFCstream_2D = np.zeros((int(l), int(F))); for f in range(F): fc = dFCstream_3D[:,:,f] dFCstream_2D[:,f] = fc[xo] return dFCstream_2D <file_sep>#!/usr/bin/env python # coding: utf-8 # In[1]: # This function takes as input the 2D or 3D "dFCstream" calculated from TS2dFCstream function and returns meta-connectivity (MC) as output. # Example: mc = dFCstream2MC(dfcstream) # Reference: <NAME> et al. (2020) MethodsX import numpy as np from Matrix2Vec import Matrix2Vec def dFCstream2MC(dFCstream): if len(dFCstream.shape)==3: FCstr=Matrix2Vec(dFCstream) if len(dFCstream.shape)==2: FCstr=dFCstream if FCstr.shape[0] > 20000: return print('Caution! If number of your parcellation > 200 regions, this function may take one minutes, instead you can only calculate trimers of MC, using dFCstream2Tri function!') MC = np.corrcoef(FCstr) MC = MC - np.eye(MC.shape[0]) return MC<file_sep>#!/usr/bin/env python # coding: utf-8 # In[1]: # This function takes dFCstream as input ('2D' or '3D') and calculates "trimers" of meta-connectivity # (MC) [nxnxn] matrix, where n is the number of nodes in your network. # You may use this function instead of dFCstream2MC if number of # nodes in your network > 200 regions. # # input: dFCstream --> generated by FCstr2dFCstream (2D or 3D) # # Example: MC3=dFCstream2Trimers(dfcstream) # Reference: <NAME> et al. (2020) MethodsX import numpy as np from Vec2Matrix import Vec2Matrix import itertools def dFCstream2Trimers(dFCstream): if len(dFCstream.shape)==2: FCstr=Vec2Matrix(dFCstream) if len(dFCstream.shape)==3: FCstr=dFCstream n = FCstr.shape[0] MC3 = np.zeros((n,n,n)) var1=np.zeros((FCstr.shape[0],FCstr.shape[2])) for i in range(n): var1[:,:] = FCstr[:,i,:] var2 = np.corrcoef(var1) var2=np.nan_to_num(var2) np.fill_diagonal(var2, 0) # var2[var2==1]=0 MC3[:,:,i]=var2 return MC3 <file_sep>#!/usr/bin/env python # coding: utf-8 # In[3]: # This function takes as input "time-series", size of window "W", and the value of shifting the window "lag", to calculate the dynamic functional connectivity stream "dFCstream" as output # inputs: TS(t,n) --> rows are t different time-points # columns are n different regions # W --> size of window to slide # lag --> shifting value, default is lag = W # frmt --> '2D' (default) provides a [l]x[F] dFCstream (FC vector over time) where l = n(n-1)/2 is # the number of links for n regions and F is the number frames depending on value of (t,W,lag) # '3D' provides a [n]x[n]x[F] dFCstream (FC matrix over time) # # # Example: dfcstream = TS2dFCstream(ts,10,10,'2D') # Example: dfcstream = TS2dFCstram(ts,10,None,'2D') # these two examples compute the dFCstream with window size 10 and without overlap between windows. # since lag assumes a value equal to the default one. The above syntax is equivalent to the simpler version in below: # Example: dfcstream = TS2dFCstream(ts,10) # Reference: <NAME> et al. (2020) MethodsX import numpy as np from TS2FC import TS2FC def TS2dFCstream(*args): TS = args[0] if len(args) == 1: return print('Prove at least a window size!') if len(args) == 2: W = args[1] lag = W frmt = '2D' if len(args) == 3: W = args[1] lag = args[2] frmt = '2D' if len(args) == 4: W = args[1] frmt = args[3] if args[2]!=None: lag = args[2] else: lag = W t = TS.shape[0] n = TS.shape[1] l = int(n*(n-1)/2) wstart = 0 wstop = W k = 0 while (wstop <= t): wstart = wstart + lag wstop = wstop + lag k = k + 1 kmax = k if frmt == '2D': dFCstream = np.zeros((l,kmax)) wstart = 0 wstop = W k = 0 while (wstop <= t): dFCstream[:,k] = TS2FC(TS[wstart:wstop,:],'1D') wstart = wstart + lag wstop = wstop +lag k = k + 1 return dFCstream else: dFCstream = np.zeros((n,n,kmax)) wstart = 0 wstop = W k = 0 while (wstop <= t): dFCstream[:,:,k] = TS2FC(TS[wstart:wstop,:],'2D') wstart = wstart + lag wstop = wstop +lag k = k + 1 return dFCstream<file_sep>#!/usr/bin/env python # coding: utf-8 # In[1]: # This function takes as input the '3D' dFCstream and convert it to '2D' dFCstream. # Reference: <NAME> et al. (2020) MethodsX import numpy as np import itertools def Vec2Matrix(dFCstream_2D): if len(dFCstream_2D.shape)==3: return print('You do not need this function since your dFCstream is alread 3D') l = dFCstream_2D.shape[0] t = dFCstream_2D.shape[1] n = int((1 + np.sqrt(1+8*l)) / 2) CN = np.array(list(itertools.combinations(range(n), 2))) dFCstream_3D = np.zeros((n,n,t)) for i in range(l): dFCstream_3D[CN[i,0],CN[i,1],:] = dFCstream_2D[i,:] dFCstream_3D = dFCstream_3D + np.transpose(dFCstream_3D, (1,0,2)) return dFCstream_3D
186897f87f9432a8c063fedcc99642f13d05ecad
[ "Markdown", "Python" ]
8
Markdown
yilewang/Network-science-Toolbox
2e1cdcd0a4159bd5d302a13b5a292d9146776b64
ca51a830f56675557798e36c42264c3ad5aefd5b
refs/heads/main
<file_sep>import React from 'react' import Login from './Login' import ContactProvider from './ContactProvider.js' import Dashboard from './Dashboard' import useLocalStorage from '../CustomHook/useLocalStorage' import ConversationProvider from './ConversationProvider' import Conversations from './Conversations' function App() { const [id,setId]=useLocalStorage('ID',""); const dashboard=( <ContactProvider> <ConversationProvider> <Dashboard id={id}/> </ConversationProvider> </ContactProvider> ) return ( <> {id==="" || id===null? <Login onIdSubmit={setId}/> : dashboard} </> ) } export default App; <file_sep>Instructions to run program: 1.Clone and pull repository 2.Type and enter "cd messenger" on the git bash 3.Type and enter "npm start" on the git bash 4.Go to localhost:3000 This app allows you to login with a chosen name or generate a random name. It also allows you to create contacts, delete contacts, create conversations with one or more people, delete said conversations, add messages as the reciever (messages on the left side) or as the sender (messages on the right side). This app also uses a custom hook to store information in local storage. I used this app to help build my knowledge of react and react bootstrap and learned how to efficiently use the useState, useEffect, useRef, and useContext hooks. PHOTOS: LoginPage: <img src="./Photos/loginPage.PNG"> <br> Create New Contact Modal: <img src="Photos/CreateNewContact.PNG"> <br> Added Contacts: <img src="Photos/AddedContacts.PNG"> <br> Create New Conversation Modal: <img src="Photos/CreateNewConversation.PNG"> <br> Added Conversations: <img src="Photos/AddedConversations.PNG"> <br/> Entire Dashboard with Active Messages: <img src="Photos/EntireDashboard.PNG"> <file_sep>import React from 'react' import {useState} from 'react' import {InputGroup,Form,Button} from 'react-bootstrap' import Conversations from './Conversations' import {useConversation} from './ConversationProvider' import useLocalStorage from '../CustomHook/useLocalStorage' export default function MessageField() { const [newMessage,setNewMessage]=useState(""); const [sent,setSent]=useLocalStorage('messagesSent',0) const conversation=useConversation() function handleSubmit(){ conversation.addToConv(conversation.selectedConv,newMessage) setSent(prev=>prev+1) setNewMessage("") } const onEmojiClick = (event, emojiObject) => { setNewMessage(prev=>[...prev,emojiObject]) console.log(emojiObject) }; return ( <> <div style={{height:"80vh",overflowY:"scroll"}}> <Conversations sent={sent}/> </div> <div style={{height:"16vh"}}> <InputGroup style={{width:"73vw"}}> <Form.Control value={newMessage} onChange={(e)=>{setNewMessage(e.target.value)}} as="textarea" rows={3} style={{resize:"none"}}/> <Button type="submit" onClick={handleSubmit} >Send Message</Button> </InputGroup> </div> </> ) } <file_sep>import { useEffect, useState } from 'react' const PREFIX = 'messenger-' export default function useLocalStorage(key, initialValue) { const prefixedKey = PREFIX + key const [value, setValue] = useState(() => { let storedValue=sessionStorage.getItem(prefixedKey); if (storedValue){ return JSON.parse(storedValue) } else { return initialValue } }) useEffect(() => { sessionStorage.setItem(prefixedKey,JSON.stringify(value)) }, [value]) return [value, setValue] }<file_sep>import {React,useState} from 'react' import {Modal,Form,Button} from 'react-bootstrap' import {useConversation} from './ConversationProvider' import {useContact} from './ContactProvider' import useLocalStorage from '../CustomHook/useLocalStorage' function NewContactModal({show,setShow}) { const contacts=useContact(); const conversations=useConversation(); const [selectedIds,setSelectedIds]=useLocalStorage('selectedIDs',[]) function handleHide(){ setShow(false); } function handleCheck(e,value){ e.stopPropagation(); if (!selectedIds.includes(value)){ setSelectedIds(prevIds=>[...prevIds,value]) } else{ setSelectedIds(prevIds=>prevIds.filter(id=>{ return id!==value})) } } function handleSubmit(){ if(selectedIds.length>0){ conversations.addToMap(selectedIds) setSelectedIds([]) } setShow(false) } return ( <div> <Modal show={show} onHide={handleHide}> <Modal.Header closeButton> <Modal.Title>Create Conversation</Modal.Title> </Modal.Header> <Modal.Body> <div> { contacts.contactList.map(value=>( <Form.Check type="checkbox" label={value} onChange={(e)=>{handleCheck(e,value)}}/> )) } </div> </Modal.Body> <Modal.Footer> <Button type="Submit" onClick={handleSubmit}>Add New Conversation</Button> </Modal.Footer> </Modal> </div> ) } export default NewContactModal; <file_sep>import {React,useRef} from 'react' import {Modal,Form,Button} from 'react-bootstrap' import {useContact} from './ContactProvider' function NewContactModal({show,setShow}) { const newContactContact=useRef(); const contacts=useContact(); function handleHide(){ setShow(false); } function HandleSubmit(){ if (newContactContact.current.value!==""){ contacts.addContact(newContactContact.current.value) setShow(false);} } return ( <div> <Modal show={show} onHide={handleHide}> <Modal.Header closeButton> <Modal.Title>Create Contact</Modal.Title> </Modal.Header> <Modal.Body> <span>Contact</span> <Form.Control type="text" ref={newContactContact}></Form.Control> </Modal.Body> <Modal.Footer> <Button type="Submit" onClick={HandleSubmit}>Add New Contact</Button> </Modal.Footer> </Modal> </div> ) } export default NewContactModal; <file_sep>import React from 'react' import {useState,useContext} from 'react' import useLocalStorage from '../CustomHook/useLocalStorage' export const ContactContext=React.createContext(); export function useContact(){ return useContext(ContactContext); } export default function ContactProvider({children}){ const [contactList,setContactList]=useLocalStorage('contactList',[]); function addContact(value){ setContactList(prev=>[...prev,value]); } return( <ContactContext.Provider value={{contactList,addContact,setContactList}}> {children} </ContactContext.Provider> ) } <file_sep>import {React,useState} from 'react' import {Button} from 'react-bootstrap' import '../cssStyles/ConversationStyles.css' import {useConversation} from './ConversationProvider' import ConversationProvider from './ConversationProvider' export default function Conversations({sent}) { const conversation=useConversation(); const [selectedButton,setSelectedButton]=useState("primary") const [unselectedButton,setUnselectedButton]=useState("secondary"); function handleClick(e){ conversation.setSender(e.target.value) let temp=selectedButton setSelectedButton(unselectedButton) setUnselectedButton(temp) } return ( <ConversationProvider> <div> <div style={{color:"gray",fontSize:"12px"}}> <span style={{marginLeft:"2vw",backgroundColor:"red"}}> <Button variant={selectedButton} value="isMe" onClick={handleClick}>Me</Button> <Button variant={unselectedButton} value="noMe" onClick={handleClick}>Other Person</Button> </span> </div> <div> { conversation.conversationMap.get(conversation.selectedConv).map(value=>( <div className={(value.startsWith("isMe"))==true ? "isMe" : "noMe"}>{String(value).slice(4,value.length)}</div> )) } </div> </div> </ConversationProvider> ) }
5e78668e7d48de0b46fb63b7025fb601ed4720d5
[ "JavaScript", "Markdown" ]
8
JavaScript
AmaanEziz/reactMessenger
ed378b75263d85d44a8951f148f4ec1460d05c7a
a4bc979f28e359f2b607c08358abc0f5f6ea4af9
refs/heads/master
<repo_name>munkith-abid/ruby-music-library-cli<file_sep>/lib/artist.rb class Artist @@all = [] attr_accessor :name attr_reader :songs def initialize(name) @name = name @songs = [] save end def self.all @@all end def self.destroy_all @@all.clear end def self.create(name) new(name) end def save @@all << self end # def songs # @songs # end def add_song(song) if song.artist == nil @songs << song song.artist1 self end end end
35f3e7ec5a3b80ca075816bcb31c04c76278ae74
[ "Ruby" ]
1
Ruby
munkith-abid/ruby-music-library-cli
8a4d90d7218955cfe0bbbb97c4d2de3d7ba74e84
03cadd0039885614c69ac0559a678a624333ae0b
refs/heads/master
<file_sep>import React, { Component } from 'react'; import PropTypes from 'prop-types'; import FeedItem from './FeedItem'; class FeedContainer extends Component { render() { let pictures = this.props.pics; let isLoading = this.props.feedLoading; let pics = pictures.map(pic => <li> <FeedItem key={pic.id} regUrl={pic.urls.regular} downUrl={pic.urls.custom} unsplashLink={pic.links.html} creator={pic.user} /> </li> ); if (isLoading) { return( <p>Loading</p> ); } else { return( <ul className="FeedContainer"> {pics} </ul> ); } } } FeedContainer.PropTypes ={ pics: PropTypes.array.isRequired, feedLoading: PropTypes.func.isRequired, } export default FeedContainer; <file_sep>import React, { Component } from 'react'; import axios from 'axios'; import './styles/App.css'; import FilterContainer from './FilterContainer'; import FeedContainer from './FeedContainer'; class App extends Component { state = { filterSearch: '', filterWidth: '', filterHeight: '', parameters: '', pics: [], feedLoading: false, }; filterSearchHandler = e => { this.setState({ filterSearch: e.target.value }); } filterWidthHandler = e => { this.setState({ filterWidth: e.target.value }); } filterHeightHandler = e => { this.setState({ filterHeight: e.target.value }); } filterHeightHandler = e => { this.setState({ filterHeight: e.target.value }); } submitHandler = e => { e.preventDefault(); let imgSearch = this.state.filterSearch; let imgWidth = this.state.filterWidth; let imgHeight = this.state.filterHeight; this.setState({ parameters: `count=10&w=${imgWidth}&h=${imgHeight}&query=${imgSearch}`, feedLoading: true }) setTimeout((function() { axios.get(`https://api.unsplash.com/photos/random/?client_id=908d18974a71cf3e3407fb7a22361a912efd8ce3e5823c26d55c2488103f9010&count=12&w=${imgWidth}&h=${imgHeight}&query=${imgSearch}`) .then(response => { this.setState({ pics: response.data }); }).then(e => { setTimeout((function() { this.setState({ feedLoading: false }); }).bind(this), 1000); }) .catch(error => { console.log('Error fetching and parsing data', error); }); }).bind(this), 250); } render() { return ( <div className="App"> <header className="FilterWrapper"> <h1>Un<em>Sized</em></h1> <FilterContainer filterSearch={this.state.filterSearch} filterWidth={this.state.filterWidth} filterHeight={this.state.filterHeight} submitHandler = {this.submitHandler} filterSearchHandler = {this.filterSearchHandler} filterWidthHandler = {this.filterWidthHandler} filterHeightHandler = {this.filterHeightHandler} /> </header> <div className="FeedWrapper"> <FeedContainer pics={this.state.pics} feedLoading={this.state.feedLoading} /> </div> </div> ); } } export default App; <file_sep>import React, { Component } from 'react'; import PropTypes from 'prop-types'; class FilterSearch extends Component { render() { return ( <span className="FilterSearch"> <input type="text" placeholder="filter images" onChange={this.props.filterSearchHandler} value={this.props.filterSearch} /> </span> ); } } FilterSearch.PropTypes ={ filterSearchHandler: PropTypes.func.isRequired, filterSearch: PropTypes.func.isRequired, } export default FilterSearch;
fd316371b79b922f8e1d5dfa57d962ba2fd9cc7b
[ "JavaScript" ]
3
JavaScript
nolanperk/UnSized
af7aea959c4706b6051f8362a25d2f8d73b62352
5aca8831a69e0ea8192800d970b6b1c50b0ca756
refs/heads/master
<repo_name>ashinkuniyil/angular-profile-keeper<file_sep>/src/app/login/login.component.ts import { Component, OnInit } from '@angular/core'; import { faImdb } from '@fortawesome/free-brands-svg-icons'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { HttpClient } from '@angular/common/http'; import { DataStore } from '../utilities/data-store'; import { config } from '../config/app.config'; import { MatSnackBar } from '@angular/material/snack-bar'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.scss'], }) export class LoginComponent implements OnInit { faImdb = faImdb; loginForm: FormGroup; data: any = {}; dataStore: DataStore; constructor( private formBuilder: FormBuilder, private router: Router, private httpClient: HttpClient, private _snackBar: MatSnackBar ) { this.dataStore = DataStore.getInstance(); this.loginForm = this.formBuilder.group({ username: ['<EMAIL>', Validators.required], password: ['<PASSWORD>', Validators.required], }); } ngOnInit(): void {} actLogin() { this.httpClient .post(`${config.apiURL}login`, this.loginForm.value) .subscribe( (data) => { this.dataStore.setData('token', data); this.router.navigate(['/', 'dashboard']); }, (error) => { this._snackBar.open(error?.error?.error, 'close', { duration: 2000, }); } ); } } <file_sep>/src/app/dashboard/user-profile/user-profile.component.ts import { Component, OnInit } from '@angular/core'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; @Component({ selector: 'app-user-profile', templateUrl: './user-profile.component.html', styleUrls: ['./user-profile.component.scss'], }) export class UserProfileComponent implements OnInit { profileForm: FormGroup; constructor(private formBuilder: FormBuilder) { this.profileForm = this.formBuilder.group({ firstname: [null, Validators.required], lastname: [null, Validators.required], email: [null, [Validators.required, Validators.email]], addressOne: [null, Validators.required], addressTwo: [null], city: [null, Validators.required], }); } ngOnInit(): void {} submit() {} } <file_sep>/src/app/shared/component/navigation/navigation.component.ts import { Component, OnInit } from '@angular/core'; import { faHome, faEye, faAddressBook, } from '@fortawesome/free-solid-svg-icons'; import { faEnvira } from '@fortawesome/free-brands-svg-icons'; @Component({ selector: 'app-navigation', templateUrl: './navigation.component.html', styleUrls: ['./navigation.component.scss'], }) export class NavigationComponent implements OnInit { icons = [ { name: faHome, color: 'white', active: true }, { name: faEnvira, color: 'none' }, { name: faEye, color: 'none' }, { name: faAddressBook, color: 'none' }, ]; constructor() {} ngOnInit(): void {} } <file_sep>/src/app/utilities/data-store.ts /** * Data Store main class */ export class DataStore { private static _instance: DataStore = new DataStore(); applnContext: any = {}; constructor() { if (DataStore._instance) { throw new Error('Error: Instantiation failed: Use DataStore.getInstance() instead of new.'); } DataStore._instance = this; } /** * Returns DataStore instance */ public static getInstance(): DataStore { return DataStore._instance; } clearAll() { this.applnContext = {}; } /** * Creates new application context data * @param {type} carrierName - creates application context data for provided name. * @param {type} carrierValue - application context value */ setData(contextName, contextValue) { this.applnContext[contextName] = contextValue; } /** * Returns data stored in 'contextName' */ getData(contextName) { if (this.applnContext[contextName]) { return this.applnContext[contextName]; } } /** * Clear data stored in 'contextName' */ clearContextData(contextName) { if (this.applnContext[contextName]) { this.applnContext[contextName] = null; } } /** * Check whether data stored in 'contextName' */ isContextDataExists(contextName) { if (this.applnContext[contextName]) { return true; } return false; } }<file_sep>/src/app/dashboard/user-list/user-list.component.ts import { HttpClient } from '@angular/common/http'; import { Component, AfterViewInit } from '@angular/core'; import { DataStore } from '../../utilities/data-store'; import { config } from '../../config/app.config'; @Component({ selector: 'app-user-list', templateUrl: './user-list.component.html', styleUrls: ['./user-list.component.scss'], }) export class UserListComponent implements AfterViewInit { dataStore: DataStore; displayedColumns: string[] = ['first_name', 'age', 'last_name', 'employee']; data: UserDetails[] = []; isLoadingResults = true; isRateLimitReached = false; constructor(private _httpClient: HttpClient) { this.dataStore = DataStore.getInstance(); } ngAfterViewInit() { this._httpClient .get(`${config.apiURL}users?page=2`) .subscribe((data: any) => { this.data = data?.data; this.isLoadingResults = false; }); } } export interface UserDetails { first_name: string; age?: string; last_name: string; employee?: string; } <file_sep>/src/app/config/app.config.ts export const config = { apiURL: 'https://reqres.in/api/', }; <file_sep>/src/app/config/nav.config.ts export const navConfig = [ { name: 'faHome', active: true, }, { name: 'faEnvira', }, { name: 'faEye', }, { name: 'faAddressBook', }, ];
247fda964b60cc3b1ff4dc87268d37a729daae5e
[ "TypeScript" ]
7
TypeScript
ashinkuniyil/angular-profile-keeper
43f6c48e886f8e83fde24c89d154455c10580e58
b91c8c1529ec964cc036fa571a08062356785177
refs/heads/master
<file_sep><?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('index'); }); Auth::routes(); Route::get('/delivaryRegister', 'delivariesController@index'); Route::get('/supplierRegister', 'suppliersController@index'); Route::get('/home', 'HomeController@index'); Route::resource('contacts', 'contactController'); Route::resource('delivaries', 'delivariesController'); Route::resource('suppliers', 'suppliersController'); Route::resource('orders', 'ordersController'); Route::get('ordersList', 'ordersController@view'); Route::get('delivaryList', 'delivariesController@viewList'); Route::get('/delivaryProfile','delivariesController@view'); Route::resource('admin', 'adminProfileController'); Route::get('delivaryType', 'adminProfileController@viewList'); //Route::get('contacts/contactList', 'contactController.index'); //Route::get('/contacts', 'contactController@index'); <file_sep><?php namespace App\Http\Controllers\Auth; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\AuthenticatesUsers; use DB; class LoginController extends Controller { /* |-------------------------------------------------------------------------- | Login Controller |-------------------------------------------------------------------------- | | This controller handles authenticating users for the application and | redirecting them to your home screen. The controller uses a trait | to conveniently provide its functionality to your applications. | */ use AuthenticatesUsers; /** * Where to redirect users after login. * * @var string */ // protected $redirectTo = '/home'; /** * Create a new controller instance. * * @return void */ protected function authenticated(Request $request, $user) { if ( $user->type == 1 ) { return redirect('/orders'); } if ( $user->type == 0 ) { //// $DeliveryTypeValue = DB::table('delivaries')->where('user_id', $user->id)->first(); /// if($DeliveryTypeValue->status==1) { //// dd('hello delivary'); //// return redirect('/delivaryprofile'); return redirect('/ordersList'); } // return redirect('/welcome'); // if($user->type== 0) // { // return redirect('/delivaryProfile'); //// $DeliveryTypeValue = DB::table('delivaries')->where('user_id', $user->id)->first(); //// if($DeliveryTypeValue->status==1) { //// //// return redirect('/delivaryProfile'); //// } //// // } } public function __construct() { $this->middleware('guest')->except('logout'); } } <file_sep><?php namespace App\Http\Controllers; Use App\Delivary; Use App\User; use Illuminate\Support\Facades\DB; use App\DeliveryType; use App\Order; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; use Illuminate\Foundation\Auth\RegistersUsers; class delivariesController extends Controller { /* * |-------------------------------------------------------------------------- | Register Controller |-------------------------------------------------------------------------- | | This controller handles the registration of new users as well as their | validation and creation. By default this controller uses a trait to | provide this functionality without requiring any additional code. | */ public function index() { $DeliveryTypeValue = DB::table('DeliveryTypes')->select('id', 'dname')->get(); return view('auth.registerDelivary')->with('DeliveryTypeList' , $DeliveryTypeValue); } use RegistersUsers; /** * Where to redirect users after registration. * * @var string */ protected $redirectTo = '/home'; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest'); } /** * Get a validator for an incoming registration request. * * @param array $data * @return \Illuminate\Contracts\Validation\Validator */ protected function validator(array $data) { return Validator::make($data, [ 'name' => 'required|string|max:255', 'address' => 'required|string|max:255', 'job' => 'required|string|max:255', 'Delivery' => 'required|string|max:255', 'field' => 'required|string|max:255', 'phone' => 'required|string|max:14', 'email' => 'required|string|email|max:255|unique:users', 'password' => '<PASSWORD>', ]); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $data=$request->all(); $user=new User; $user->email=$data['email']; $user->type=0; $user->password=<PASSWORD>($data['<PASSWORD>']); $user->name=$data['name']; $user->save(); $delivary=new Delivary; $delivary->phone=$data['phone']; $delivary->address=$data['address']; $delivary->job=$data['job']; $delivary->nid=$data['nid']; $delivary->delivary_type_forginKey=$data['Delivery_type_id']; $delivary->birthDate=$data['birthDate']; $delivary->user_id=$user->id; $delivary->save(); return view('delivary'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // $data=DB::table('delivaries') ->join('DeliveryTypes', 'delivaries.delivary_type_forginKey', '=', 'DeliveryTypes.id') ->join('users', 'users.id', '=', 'delivaries.user_id') ->select('DeliveryTypes.dname','users.name','users.email','delivaries.*')//->where('delivaries.id','=',$id) ->get(); $orders = DB::table('orders') // ->where('delivary_forginKey','=',$id) ->count(); // $data=Delivary::orderBy('updated_at','desc')->get(); return view('profile.delivery',['Delivery'=>$data,'ordersNo'=>$orders]); } public function view() { $data=DB::table('delivaries') ->join('DeliveryTypes', 'delivaries.delivary_type_forginKey', '=', 'DeliveryTypes.id') ->join('users', 'users.id', '=', 'delivaries.user_id') ->select('DeliveryTypes.dname','users.name','users.email','delivaries.*')->where('delivaries.id','=',5) ->get(); $orders = DB::table('orders') ->where('delivary_forginKey','=',5) ->count(); // $data=Delivary::orderBy('updated_at','desc')->get(); return view('profile.delivery',['Delivery'=>$data,'ordersNo'=>$orders]); } public function viewList() { $data=DB::table('delivaries') ->join('DeliveryTypes', 'delivaries.delivary_type_forginKey', '=', 'DeliveryTypes.id') ->join('users', 'users.id', '=', 'delivaries.user_id') ->select('DeliveryTypes.dname','users.name','delivaries.id','delivaries.status')->where('delivaries.status',1) ->get(); $data1=DB::table('delivaries') ->join('DeliveryTypes', 'delivaries.delivary_type_forginKey', '=', 'DeliveryTypes.id') ->join('users', 'users.id', '=', 'delivaries.user_id') ->select('DeliveryTypes.dname','users.name','delivaries.id','delivaries.status')->where('delivaries.status',0) ->get(); // $data=Delivary::orderBy('updated_at','desc')->get(); return view('admin.delivaryList',['allDeliveries'=>$data],['allDeliveries1'=>$data1]); // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update($id) { $data1=DB::table('delivaries') ->where('id',$id) ->update(['status'=> 1]); $data=DB::table('delivaries') ->join('DeliveryTypes', 'delivaries.delivary_type_forginKey', '=', 'DeliveryTypes.id') ->join('users', 'users.id', '=', 'delivaries.user_id') ->select('DeliveryTypes.dname','users.name','delivaries.id','delivaries.status')->where('delivaries.status',1) ->get(); $data1=DB::table('delivaries') ->join('DeliveryTypes', 'delivaries.delivary_type_forginKey', '=', 'DeliveryTypes.id') ->join('users', 'users.id', '=', 'delivaries.user_id') ->select('DeliveryTypes.dname','users.name','delivaries.id','delivaries.status')->where('delivaries.status',0) ->get(); // $data=Delivary::orderBy('updated_at','desc')->get(); return view('admin.delivaryList',['allDeliveries'=>$data],['allDeliveries1'=>$data1]); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // $data=DB::table('users')->where( 'id','=' ,$id )->delete(); return back(); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Contact; use Illuminate\Support\Facades\Auth; class contactController extends Controller { public function index() { $contacts = DB::table('contacts')->get(); return view('contacts.contactList', ['contacts' => $contacts]); //// return view('contacts/contactList'); } public function store(Request $request) { $request->validate([ 'contactName'=>'required', 'email'=>'required', 'contactMobile'=>'required', 'city'=>'required', 'country'=>'required' ]); // dd($request->contactName); $data=Contact::all(); $contact = new Contact(); $contact->name = $request->contactName; $contact->email = $request->email; $contact->mobile = $request->contactMobile; $contact->city = $request->city; $contact->country = $request->country; $contact->user_id = 1; $contact->save(); // return back()->with('success','Contact ADDED SUCCESSEFULY'); return view('contacts.contactList',['contacts' => $data]); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Support\Facades\DB; use Illuminate\Http\Request; use App\DeliveryType; use App\Order; use Illuminate\Support\Facades\Auth; class ordersController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $DeliveryTypeValue = DB::table('DeliveryTypes')->select('id', 'dname')->get(); return view('order.add')->with('DeliveryTypeList' , $DeliveryTypeValue); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function __construct() { $this->middleware('auth'); } public function view() { $ordersList=DB::table('orders') ->join('suppliers', 'orders.supplier_forginKey', '=', 'suppliers.id') ->join('users', 'users.id', '=', 'suppliers.user_id') ->join('DeliveryTypes', 'orders.delivary_type_forginKey', '=', 'DeliveryTypes.id') ->select('DeliveryTypes.dname', 'users.name', 'orders.description', 'orders.direction', 'orders.allowedTime') ->get(); $user=DB::table('users') ->where('id','=',Auth::id()) ->first(); // dd($user[0]); if($user->type==0) { return view('order.ordersList')->with('ordersList', $ordersList); } } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $request->validate([ 'orderName' => 'required', 'direction' => 'required', 'orderTime' => 'required', 'dType' => 'required', ]); //store $data=$request->all(); $order=new Order; $order->description=$data['orderName']; $order->delivary_type_forginKey=$data['dType']; $order->allowedTime=$data['orderTime']; $order->direction=$data['direction']; // $order->supplier_forginKey=Auth::id(); $order->save(); //redirect return back()->with('success','تم الطلب بنجاح'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep><?php namespace App\Http\Controllers; Use App\Supplier; Use App\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; use Illuminate\Foundation\Auth\RegistersUsers; class suppliersController extends Controller { /* |-------------------------------------------------------------------------- | Register Controller |-------------------------------------------------------------------------- | | This controller handles the registration of new users as well as their | validation and creation. By default this controller uses a trait to | provide this functionality without requiring any additional code. | */ use RegistersUsers; /** * Where to redirect users after registration. * * @var string */ protected $redirectTo = '/home'; public function index() { return view('auth.registerSupplier'); } /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest'); } /** * Get a validator for an incoming registration request. * * @param array $data * @return \Illuminate\Contracts\Validation\Validator */ protected function validator(array $data) { return Validator::make($data, [ 'name' => 'required|string|max:255', 'address' => 'required|string|max:255', 'field' => 'required|string|max:255', 'phone' => 'required|string|max:14', 'email' => 'required|string|email|max:255|unique:users', 'password' => '<PASSWORD>', ]); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $data=$request->all(); $user=new User; $user->email=$data['email']; $user->type=1; $user->password=<PASSWORD>($data['<PASSWORD>']); $user->name=$data['name']; $user->save(); $supplier=new Supplier; $supplier->phone=$data['phone']; $supplier->address=$data['address']; $supplier->field=$data['field']; $supplier->user_id=$user->id; $supplier->save(); return redirect('/orders'); // $post->save(); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } }
0a9f2c281e3e7b065061ed01efd2642c5f7bfa2c
[ "PHP" ]
6
PHP
omeyad/taiar
2dab05f192ff710c0b193e0674cebdd387cd3a43
e0c0d22cf54fa09d4617ee107fb65b58fc5da918
refs/heads/master
<repo_name>StevenZabolotny/Battle-For-The-Brook<file_sep>/static/register.js var sub = d3.select("#sub") var subuse = false; var subform = ['<legend>Substitute Player</legend>', '<p>This is your substitute player. You may only have one substitute player. The substitute may replace any part of your roster, however, if your team captain is not present, you will need to give the responsibility to one of the players (to make check-in easier).', '<div class="pure-g">', '<div class="pure-u-5-24">', '<label for="fname6">First Name</label>', '<input id="fname6" type="text" name="fname6" placeholder="First Name"><br>', '</div>', '<div class="pure-u-5-24">', '<label for="lname6">Last Name</label>', '<input id="lname6" type="text" name="lname6" placeholder="Last Name"><br>', '</div>', '<div class="pure-u-5-24">', '<label for="id6">Stony Brook ID Number</label>', '<input id="id6" type="text" name="id6" placeholder="9-Digit ID"><br>', '</div>', '</div>', '<div class="pure-g">', '<div class="pure-u-5-24">', '<label for="sname6">Summoner Name</label>', '<input id="sname6" type="text" name="sname6" placeholder="In-Game Name"><br>', '</div>', '<div class="pure-u-5-24">', '<label for="tier6">Rank Tier</label>', '<select id="tier6" name="tier6" class="pure-input-1-2">', '<option>Unranked</option>', '<option>Bronze</option>', '<option>Silver</option>', '<option>Gold</option>', '<option>Platinum</option>', '<option>Diamond</option>', '<option>Master</option>', '<option>Challenger</option>', '</select><br>', '</div>', '<div class="pure-u-5-24">', '<label for="division6">Rank Division</label>', '<select id="division6" name="division6" class="pure-input-1-2">', '<option>Unranked</option>', '<option>I</option>', '<option>II</option>', '<option>III</option>', '<option>IV</option>', '<option>V</option>', '</select><br>', '</div>', '<div class="pure-u-5-24">', '<label for="desktop6">', '<input id="desktop6" type="radio" name="computer6" value="desktop" checked>', 'Desktop', '</label>', '<label for="laptop6">', '<input id="laptop6" type="radio" name="computer6" value="laptop">', 'Laptop', '</label>', '</div>', '</div><br><br>'].join(""); var subfalse = '<input type="hidden" name="subinuse" value="false" id="subinuse">'; var subtrue = '<input type="hidden" name="subinuse" value="true" id="subinuse">'; var subbutton = d3.select("#subbutton") .on("click", function() { if (subuse) { sub.html(""); subbutton.text("Add Substitute Player"); d3.select("#subinusetag") .html(subfalse); subuse = false; } else { sub.html(subform); subbutton.text("Remove Substitute Player"); d3.select("#subinusetag") .html(subtrue); subuse = true; } }); <file_sep>/README.md # Battle-For-The-Brook Stony Brook League of Legends Tournament Page I'll add more stuff here later. <file_sep>/app.py from flask import Flask,render_template,request app = Flask(__name__) @app.route("/", methods=["GET"]) def index(): return render_template("index.html") @app.route("/register", methods=["GET", "POST"]) def register(): if request.method == "GET": return render_template("register.html") text = "" text += request.form["tname"] + "\n" text += request.form["fname1"] + "," + request.form["lname1"] + "," + request.form["id1"] + "," + request.form["email1"] + "," + request.form["sname1"] + "," + request.form["tier1"] + "," + request.form["division1"] + "," + request.form["computer1"] + "\n" for i in range(2,6): text += request.form["fname" + str(i)] + "," + request.form["lname" + str(i)] + "," + request.form["id" + str(i)] + "," + request.form["sname" + str(i)] + "," + request.form["tier" + str(i)] + "," + request.form["division" + str(i)] + "," + request.form["computer" + str(i)] + "\n" #if (request.form["subinuse"] == "true"): text += request.form["fname6"] + "," + request.form["lname6"] + "," + request.form["id6"] + "," + request.form["sname6"] + "," + request.form["tier6"] + "," + request.form["division6"] + "," + request.form["computer6"] text += "\n" fo = open("teams.txt", "a") fo.write(text) fo.close() return render_template("register.html") if __name__=="__main__": app.debug=True app.run(host="0.0.0.0",port=5000)
b0f1f848d80c3ebc448dbe779b309d0b120eed98
[ "JavaScript", "Python", "Markdown" ]
3
JavaScript
StevenZabolotny/Battle-For-The-Brook
4320d67bc9f2c92cbe43ad38426e8c354e938e85
6558543a0ce44395296cfb78bb80b3e4ba3c5753
refs/heads/master
<file_sep>import json import unittest from lxml import html from src.app import app app.testing = True class TestApi(unittest.TestCase): def test_domain_oracle(self): with app.test_client() as client: # send data as POST form to endpoint sent = {'domain': 'oracle.com'} result = client.post( '/api/domain', data=sent ) content = html.fromstring(result.data) domain_result = content.xpath('//p/text()') print(domain_result) expected = ['{"20 aserp2020.oracle.com.": "aserp2020.oracle.com.", "20 aserp2030.oracle.com.": "aserp2030.oracle.com.", "20 aserp2040.oracle.com.": "aserp2040.oracle.com.", "20 aserp2050.oracle.com.": "aserp2050.oracle.com.", "20 aserp2060.oracle.com.": "aserp2060.oracle.com.", "20 userp2020.oracle.com.": "userp2020.oracle.com.", "20 userp2030.oracle.com.": "userp2030.oracle.com.", "20 userp2040.oracle.com.": "userp2040.oracle.com.", "20 userp2050.oracle.com.": "userp2050.oracle.com.", "20 userp2060.oracle.com.": "userp2060.oracle.com."}'] self.assertEqual( expected, domain_result ) def test_domain_google(self): with app.test_client() as client: # send data as POST form to endpoint sent = {'domain': 'google.com'} result = client.post( '/api/domain', data=sent ) content = html.fromstring(result.data) domain_result = content.xpath('//p/text()') print(domain_result) expected = ['{"10 aspmx.l.google.com.": "aspmx.l.google.com.", "20 alt1.aspmx.l.google.com.": "alt1.aspmx.l.google.com.", "30 alt2.aspmx.l.google.com.": "alt2.aspmx.l.google.com.", "40 alt3.aspmx.l.google.com.": "alt3.aspmx.l.google.com.", "50 alt4.aspmx.l.google.com.": "alt4.aspmx.l.google.com."}'] self.assertEqual( expected, domain_result ) if __name__ == '__main__': unittest.main() <file_sep>FROM python:alpine3.7 COPY . /app WORKDIR /app RUN pip install -r src/requirements.txt EXPOSE 5000 CMD python src/app.py<file_sep># ============================================================================= # Created By : <NAME> # Created Date: Mon October 1st 2019 # ============================================================================= import dns.resolver from dns.resolver import NXDOMAIN from flask import Flask, render_template, request import json app = Flask(__name__ , template_folder="templates") # '__main__' app.secret_key = "andrew" #Route to homepage - http://127.0.0.1:5000/ @app.route('/') def home_template(): return render_template('home.html') @app.route('/api/domain', methods=['POST']) def post_domain(domain=None): domain = request.form['domain'] try: mxquery = dns.resolver.query(domain, 'MX') except NXDOMAIN: return render_template('error.html', domain=domain) mxrecords = {str(data): str(data.exchange) for data in mxquery} json_data = json.dumps(mxrecords, sort_keys=True) return render_template('domain.html', domain=domain, mxrecords=json_data), 200 @app.route('/api/domain/<string:domain>', methods=['GET']) def get_domain(domain=None): if domain is not None: try: mxquery = dns.resolver.query(domain, 'MX') except NXDOMAIN: return render_template('error.html', domain=domain), 500 else: return render_template('error.html', domain=domain), 500 mxrecords = {str(data): str(data.exchange) for data in mxquery} json_data = json.dumps(mxrecords, sort_keys=True) return render_template('domain.html', domain=domain, mxrecords=json_data) if __name__ == '__main__': app.run(host="0.0.0.0") <file_sep>Flask dns-batch-resolver==0.0.2 dnspython==1.16.0<file_sep># oracleProject # Application Title: Andrew's MX Domain App # Author: <NAME> # Create Date: Oct 1st 2019 # ============================================================================= # Installation Instructions # ============================================================================= If Running from Python IDE (i.e I use Pycharm) 1) Unzip the contents of the application to a local directory location (i.e /Users/<YourMacUserName>/Python/OracleProject) 2) Open the project from your IDE 3) Make sure the below Project Interpreter/Packages are installed on the project Flask dns-batch-resolver==0.0.2 dnspython==1.16.0 4) Run the src/app.py file. You should see the below output Serving Flask app "app" (lazy loading) * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: off 5) Open a web browser and go to URL http://127.0.0.1:5000/ . This is the homepage of the application If Running from docker 1) First make sure Docker Desktop is up and running. Instructions are here https://docs.docker.com/v17.09/docker-for-mac/install/ 2) In a terminal command line pull the project from my docker hub repository docker pull ancolon/python-domain-mx-project 3) Start and run a container from the image docker container run -d --name provide-name -p 5000:5000 ancolon/python-domain-mx-project 4) Open a web browser and go to URL http://127.0.0.1:5000/ . This is the homepage of the application If Running from Shell 1) Unzip the contents of the application to a local directory location (i.e /Users/<YourMacUserName>/Python/OracleProject) 2) Open a new terminal and navigate to /src directory of project 3) Execute the below commands in order pip install -r requirements.txt python app.py 4) You should see the below output, after which open a web browser and go to URL http://127.0.0.1:5000/ . This is the homepage of the application MacBook-Pro-9:src mymac$ python app.py * Serving Flask app "app" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: off * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) # ============================================================================= # Developer Notes # ============================================================================= Given that I had more time to work on this project I would have done the below improvements/Enhancements 1) Added features to the UI for customizing search results (i.e Filters and checkboxes that support more format outputs such as string, list, table, etc) 2) Added database support enhancement for tracking previously searched domains using mongodb to store JSON MX record entries. 3) Would have gone a step future out of pulling MX records and will have extended the app to perform advanced search capabilities for pulling other domain specific and/or details from websites and API's 4) Setup Connexion and swagger.yml in order to create the swagger.json api for Bonus points 5) Would have completed the unit and functional testing under testing/TestApi.py
c72628226064900642feafc223aca1d4fb53e413
[ "Markdown", "Python", "Text", "Dockerfile" ]
5
Python
ancolon2/oracleProject
8750c10dcbb0c9df28e16d90d36b68c13bb70676
92da8532c7c375e0922774d58418537e02f48f20
refs/heads/master
<file_sep>WILLBNB PROJECT (AIRBNB PROJECT) ###Create Simple Project with Bootstrap Fist of all, we need to install the Bootstrap gem to handle the grids where are stored on this framework. <pre> subl /wllbnb/<b>Gemfile</b> <b> gem 'bootstrap', git: 'https://github.com/twbs/bootstrap-rubygem' gem 'sass-rails', '~> 5.0' </b> </pre> After that, run the **bundle command** to install those gems in our project on **terminal**: <pre> bundle install </pre> After this step, **import** the Bootstrap JS and SCSS resources to run these features: <pre> subl wllbnb/app/assets/javascripts/<b>application.js</b> <b> //= require jquery3 //= require popper //= require bootstrap-sprockets </b> subl wllbnb/app/assets/stylesheets/<b>application.scss</b> <b> * require_tree . *= require_self */ @import 'bootstrap'; </b> </pre> Set the database fields and after run the command to create the database: <pre> subl wllbnb/config/<b>database.yml</b> default: &default adapter: mysql2 encoding: utf8 pool: 5 username: root <b>password: <PASSWORD></b> host: localhost </pre> Create the database on **Terminal**: <pre> rails <b>db:create</b> </pre> And now, run the server: <pre> rails <b>server</b> or <b>s</b> </pre> ###Create Basic Authentication Open the gemfile and add the **Devise** features: <pre> subl wllbnb/<b>Gemfile</b> <b>gem 'devise'</b> </pre> After that, run the **Devise** generator installer: <pre> rails g <b>devise:install</b> Running via Spring preloader in process 74466 create config/initializers/devise.rb create config/locales/devise.en.yml =============================================================================== Some setup you must do manually if you haven't yet: 1. Ensure you have defined default url options in your environments files. Here is an example of default_url_options appropriate for a development environment in config/environments/development.rb: config.action_mailer.default_url_options = { host: 'localhost', port: 3000 } In production, :host should be set to the actual host of your application. 2. Ensure you have defined root_url to *something* in your config/routes.rb. For example: root to: "home#index" 3. Ensure you have flash messages in app/views/layouts/application.html.erb. For example: &lt;p class="notice"&gt;&lt;%= notice %&gt;&lt;/p&gt; &lt;p class="alert"&gt;&lt;%= alert %&gt;&lt;/p&gt; 4. You can copy Devise views (for customization) to your app by running: rails g devise:views =============================================================================== </pre> After that, run the **User Devise Model** with the next command in terminal: <pre> rails g <b>devise User</b> Running via Spring preloader in process 74689 invoke active_record create db/migrate/20170614023125_devise_create_users.rb create app/models/user.rb invoke test_unit create test/models/user_test.rb create test/fixtures/users.yml insert app/models/user.rb route devise_for :users </pre> And before to create the **User Devise Model**: <pre> rails <b>db:migrate</b> == 20170614023125 DeviseCreateUsers: migrating ================================ -- create_table(:users) -> 0.0185s -- add_index(:users, :email, {:unique=>true}) -> 0.0291s -- add_index(:users, :reset_password_token, {:unique=>true}) -> 0.0170s == 20170614023125 DeviseCreateUsers: migrated (0.0648s) ======================= </pre> Now, generate the devise views and this will create all the views and routes which will be used to the authenthication system: <pre> rails <b>g devise:views</b> </pre> Later, set the **default URL** which will be used on the **Development Environment**: <pre> <b>config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }</b> </pre> Now, set the **Flash Event** which will run the **Message Events**: <pre> subl wllbnb/app/views/layouts/<b>application.html.erb</b> &lt;% flash.each do |key, value| %&gt; &lt;div class="alert alert-&lt;%= key %&gt; alert-dismissable top-login-bar"&gt; &lt;button type="button" class="close" data-dismiss="alert" aria-hidden="true"&gt;×&lt;/button&gt; &lt;%= value %&gt; &lt;/div&gt; &lt;% end %&gt; </pre> After run the application, set the **Next Helper** to handle the **Flash Messages**: <pre> subl wllbnb/helpers/<b>application_helper.rb</b> module ApplicationHelper def flash_messages return if flash.empty? messages = flash.map do |key, value| if key == 'notice' content_tag(:div, value, class: 'success') elsif key == 'alert' content_tag(:div, value, class: 'error') end end safe_join(messages) end end </pre> Next, to check if everything works, run the run server command and go to the **Devise Routes**: <pre> rails <b>s</b> And in the explorer: <b>localhost:3000/users/sign_up</b> </pre> ###Building Navbar with Partial View We will get the code from this example from [Bootstrap Navbar Static Top](https://getbootstrap.com/examples/navbar-static-top/) to handle the first view which will be used in the whole platform. Also, insert the **Yield Helper** into a **container div class** to insert any content inside of that block. <pre> &lt;nav class="navbar navbar-default navbar-static-top"&gt; &lt;div class="container"&gt; &lt;div class="navbar-header"&gt; &lt;button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"&gt; &lt;span class="sr-only"&gt;Toggle navigation&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;/button&gt; &lt;a class="navbar-brand" href="#"&gt; &lt;%= image_tag 'wllbnb-logo.svg', alt: 'wllbnb-logo', style:'height: auto; width: 40px;' %&gt;AirAlien &lt;/a&gt; &lt;/div&gt; &lt;div id="navbar" class="navbar-collapse collapse"&gt; &lt;ul class="nav navbar-nav navbar-right"&gt; &lt;% if(!user_signed_in?) %&gt; &lt;li&gt;&lt;%= link_to "Log In", new_user_session_path %&gt;&lt;/li&gt; &lt;li&gt;&lt;%= link_to "Sign Up", new_user_registration_path %&gt;&lt;/li&gt; &lt;% else %&gt; &lt;li class="dropdown"&gt; &lt;a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"&gt;&lt;%= current_user.email %&gt; &lt;span class="caret"&gt;&lt;/span&gt;&lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a href="#"&gt;Your Trips&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Wish Lists&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;%= link_to "Edit Profile", edit_user_registration_path %&gt;&lt;/li&gt; &lt;li role="separator" class="divider"&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Account Setting&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;%= link_to "Log out", destroy_user_session_path, method: :delete %&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;% end %&gt; &lt;/ul&gt; &lt;/div&gt;&lt;!--/.nav-collapse --&gt; &lt;/div&gt; &lt;/nav&gt; &lt;div class="container"&gt; &lt;%= yield %&gt; &lt;/div&gt; </pre> After this, we will create the **Pages Controller** to set the main static pages in terminal: <pre> rails g <b>controller Pages homme</b> Running via Spring preloader in process 86155 create app/controllers/pages_controller.rb route get 'pages/home' invoke erb create app/views/pages create app/views/pages/home.html.erb invoke test_unit create test/controllers/pages_controller_test.rb invoke helper create app/helpers/pages_helper.rb invoke test_unit invoke assets invoke coffee create app/assets/javascripts/pages.coffee invoke scss create app/assets/stylesheets/pages.scss </pre> Now insert <file_sep>module ApplicationHelper def flash_messages return if flash.empty? messages = flash.map do |key, value| if key == 'notice' content_tag(:div, value, class: 'success') elsif key == 'alert' content_tag(:div, value, class: 'error') end end safe_join(messages) end end
7d9a9ef56573125808e38d1467f26be4cb8f249a
[ "Markdown", "Ruby" ]
2
Markdown
williamromero/Code4Startup-Courses
f3a1de4df88e03d0e64bcccb7e483176e0ee9492
a534591fe6a63436aca20370358c2901258c94c3
refs/heads/master
<repo_name>RahulKondaparthi/Rahul1204<file_sep>/memcpyVstrcpy.c Explain the difference between strcpy() and memcpy() function. strcpy() copies a string until it comes across the termination character ‘\0’. With memcopy(), the programmer needs to specify the size of data to be copied. strncpy() is similar to memcopy() in which the programmer specifies n bytes that need to be copied. The following are the differences between strcpy() and memcpy(): - memcpy() copies specific number of bytes from source to destinatio in RAM, where as strcpy() copies a constant / string into another string. - memcpy() works on fixed length of arbitrary data, where as strcpy() works on null-terminated strings and it has no length limitations. - memcpy() is used to copy the exact amount of data, whereas strcpy() is used of copy variable-length null terminated strings. #include <stdio.h> #include <string.h> int main () { char a[] = "Firststring"; const char b[] = "Secondstring"; memcpy(a, b, 5); printf("New arrays : %s\t%s", a, b); return 0; } Output New arrays : SeconstringSecondstring //memcpy() Implementation, name: myMemCpy() void myMemCpy(void* target, void* source, size_t n){ int i; //declare string and type casting char *t = (char*)target; char *s = (char*)source; //copying "n" bytes of source to target for(i=0;i<n;i++) t[i]=s[i]; } op" Before copying... str1: Hello Wold! str2: Nothing is impossible After copying... str1: Nothing is impossible str2: Nothing is impossible <file_sep>/findsetornotatgivenpos.c #include <stdio.h> int main() { int n,k; printf("enter a 32 bit number\n"); scanf("%d",&k); printf("enter the bit no to check...\n"); printf("bit-no 0-indexed & 0 starts from LSB...\n"); scanf("%d",&n); if(n>32){ printf("enter between 0-31\n"); return; } k=k>>n; //right shift the no to get nth bit at LSB if(k&1==1) //check whether nth bit set or not printf("%d th bit is set\n",n); else printf("%d th bit not set\n",n); return 0; }
a3e67d65cfdc7931cb13c8c11aa7200591468539
[ "C" ]
2
C
RahulKondaparthi/Rahul1204
97e20107feaee52b8355b843d785f99bfa065aef
3799dcff566b96771df68f49c7f47430cb027513
refs/heads/main
<file_sep># LFCamera 自定义相机,可选带拍摄区域边框及半透明遮罩层 <file_sep>platform :ios, '7.0' target 'LFCamera' do pod 'Masonry' pod 'AMapSearch' pod 'AMapLocation' pod 'AMap2DMap' pod 'UMengAnalytics-NO-IDFA'#无IDFA版SDK(请根据需要选择其中一个) end
ad8c1db8a559f94ffd272b6ace93523c6446907b
[ "Markdown", "Ruby" ]
2
Markdown
liyingjia/2020Project
ac33496418e9fd88a064ab062b64ab46f334222b
8640dcf7d46823ecb054367ab9a85131214ac317
refs/heads/master
<file_sep>package com.baba.gitdemo; public class App { public static void main( String[] args ) { System.out.println( "modified hello world" ); System.out.println( "modified hello world" ); System.out.println( "after jenkins" ); System.out.println( "at github.com" ); } }
0c9cd0ba3681aa5b70319cb6c821cfcb531ba779
[ "Java" ]
1
Java
mrinmoyR/gitdemo
6348691b5187b70d90c5647585d1d3bcacc41d4b
d288b1c8916b2ef7355478d3f3f0c4eecdb6f547
refs/heads/master
<file_sep>include ':app' rootProject.name='BestWeather' <file_sep>package com.bestweather.android.util; import android.text.TextUtils; import android.util.Log; import android.widget.Toast; import com.bestweather.android.db.City; import com.bestweather.android.db.District; import com.bestweather.android.db.Province; import com.bestweather.android.gson.Weather; import com.google.gson.Gson; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import static android.content.ContentValues.TAG; /* 解析从服务器返回的json数据。 */ public class Utility { //省级数据 public static boolean handleProvinceResponse(String response){ if (!TextUtils.isEmpty(response)){ try { JSONArray allProvinces=new JSONArray(response); for (int i=0;i<allProvinces.length();i++){ JSONObject provinceObject=allProvinces.getJSONObject(i); Province province=new Province(); Log.w(TAG, "handleProvinceResponse: "+provinceObject.getInt("id") ); province.setProvinceCode(provinceObject.getInt("id")); province.setProvinceName(provinceObject.getString("name")); province.save(); } return true; }catch (JSONException e){ e.printStackTrace(); } } return false; } //市级数据 public static boolean handleCityResponse(String response,int provinceId){ Log.w(TAG, "handleCityResponse: city going" ); if (!TextUtils.isEmpty(response)){ try { JSONArray allCityies=new JSONArray(response); for (int i=0;i<allCityies.length();i++){ JSONObject cityObject=allCityies.getJSONObject(i); City city=new City(); city.setCityName(cityObject.getString("name")); city.setCityCode(cityObject.getInt("id")); city.setProvinceId(provinceId); city.save(); } return true; }catch (JSONException e){ e.printStackTrace(); } } Log.w(TAG, "handleCityResponse: No data" ); return false; } //区级数据 public static boolean handleDistrictResponse(String response,int cityId){ if (!TextUtils.isEmpty(response)){ try { JSONArray allDistricts=new JSONArray(response); for (int i=0;i<allDistricts.length();i++){ JSONObject districtObject=allDistricts.getJSONObject(i); District district=new District(); district.setDistrictName(districtObject.getString("name")); district.setWeatherId(districtObject.getString("weather_id")); district.setCityId(cityId); district.save(); } return true; }catch (JSONException e){ e.printStackTrace(); } } return false; } public static Weather handleWeatherResponse(String response){ try { JSONObject jsonObject=new JSONObject(response); JSONArray jsonArray=jsonObject.getJSONArray("HeWeather"); String weatherContent=jsonArray.getJSONObject(0).toString(); return new Gson().fromJson(weatherContent,Weather.class); }catch (Exception e){ e.printStackTrace(); } return null; } }
92af4ff1048a0b73270b1967dcd71303135d1718
[ "Java", "Gradle" ]
2
Gradle
QwQ-maker/bestweather
ec44118d66dbb490e61814d6dee2734e23b82ef9
669693a6a1ecab777078d02469d8a8570c46e5f9
refs/heads/master
<repo_name>blessymathew/R<file_sep>/R.R #If I execute the expression x <- 4L in R, what is the class of the object `x' as determined by the `class()' function? x<-4L class(x) #"integer" #What is the class of the object defined by the expression x <- c(4, "a", TRUE)? y <- c(4, "a", TRUE) class(y) # "character" #If I have two vectors x <- c(1,3, 5) and y <- c(3, 2, 10), what is produced by the expression rbind(x, y)? x<-c(1,3,5) y<-c(3,2,10) z<-rbind(x,y) dim(z) #[1] 2 3 -2 rows and 3 columns matrix #Suppose I have a vector x <- 1:4 and a vector y <- 2. What is produced by the expression x + y? x<-1:4 y<-2 x+y #a numeric vector with elements 3, 4, 5, 6. class(x+y) #numeric #Suppose I have a vector x <- c(3, 5, 1, 10, 12, 6) and I want to set all elements of this vector that are less than 6 to be equal to zero. What R code achieves this? Select all that apply. x<-c(3,5,1,10,12,6) x[x<6]<-0 x x<-c(3,5,1,10,12,6) x x[x%in%1:5]<-0 x[x<=5]<-0 x #Use the Week 1 Quiz Data Set to answer questions 11-20. c<-read.csv("C:/Users/blessy/Desktop/Personal/DataScience/Course-2/Practice/hw1_data.CSV") #Extract the first 2 rows of the data frame and print them to the console. What does the output look like? head(c,2) #How many observations (i.e. rows) are in this data frame? nrow(c) #153 #Extract the last 2 rows of the data frame and print them to the console. What does the output look like? tail(c,2) #What is the value of Ozone in the 47th row? c[47,1] #21 #How many missing values are in the Ozone column of this data frame? c1<-c[,1] c1<-as.matrix(c1) dim(c1) c1 c1[!is.na(c1)]<-0 c1[is.na(c1)]<-1 c1 sum(c1) #37 #What is the mean of the Ozone column in this dataset? Exclude missing values (coded as NA) from this calculation. c1<-c[,1] mean(c1,na.rm=TRUE) #42.12931 #Extract the subset of rows of the data frame where Ozone values are above 31 and Temp values are above 90. What is the mean of Solar.R in this subset? c2<-subset(c,c[,1]>31 & c[,4]>90) #c2<-subset(c,Ozone>31 & Temp>90) c2 mean(c2[, 2], na.rm = TRUE) #212.8 #mean(c2[, "Solar.R"], na.rm = TRUE) #What is the mean of "Temp" when "Month" is equal to 6? c3<-subset(c,Month ==6) mean(c3[,"Temp"],na.rm = TRUE) #79.1 #What was the maximum ozone value in the month of May (i.e. Month is equal to 5)? c4<-subset(c,Month ==5) max(c4[,1],na.rm=TRUE) #115
928a827faa85e04ab101fe8f0566fd60dd199952
[ "R" ]
1
R
blessymathew/R
5f715af86d09e59b5b6dc5f344b0316fcd7199c2
788b4aa1590309ca19aeb5f60685c6d6c252ed95
refs/heads/main
<file_sep>from __future__ import division # floating point division import numpy as np import math import utilities as utils class Regressor: """ Generic regression interface; returns random regressor Random regressor randomly selects w from a Gaussian distribution """ def __init__( self, parameters={} ): """ Params can contain any useful parameters for the algorithm """ self.params = {} self.reset(parameters) def reset(self, parameters): """ Reset learner """ self.weights = None self.resetparams(parameters) def resetparams(self, parameters): """ Can pass parameters to reset with new parameters """ self.weights = None try: utils.update_dictionary_items(self.params,parameters) except AttributeError: # Variable self.params does not exist, so not updated # Create an empty set of params for future reference self.params = {} def getparams(self): return self.params def learn(self, Xtrain, ytrain): """ Learns using the traindata """ self.weights = np.random.rand(Xtrain.shape[1]) def predict(self, Xtest): """ Most regressors return a dot product for the prediction """ ytest = np.dot(Xtest, self.weights) return ytest class RangePredictor(Regressor): """ Random predictor randomly selects value between max and min in training set. """ def __init__( self, parameters={} ): """ Params can contain any useful parameters for the algorithm """ self.params = {} self.reset(parameters) def reset(self, parameters): self.resetparams(parameters) self.min = 0 self.max = 1 def learn(self, Xtrain, ytrain): """ Learns using the traindata """ self.min = np.amin(ytrain) self.max = np.amax(ytrain) def predict(self, Xtest): ytest = np.random.rand(Xtest.shape[0])*(self.max-self.min) + self.min return ytest class MeanPredictor(Regressor): """ Returns the average target value observed; a reasonable baseline """ def __init__( self, parameters={} ): self.params = {} self.reset(parameters) def reset(self, parameters): self.resetparams(parameters) self.mean = None def learn(self, Xtrain, ytrain): """ Learns using the traindata """ self.mean = np.mean(ytrain) def predict(self, Xtest): return np.ones((Xtest.shape[0],))*self.mean class FSLinearRegression(Regressor): """ Linear Regression with feature selection, and ridge regularization """ def __init__( self, parameters={} ): self.params = {'features': [1,2,3,4,5]} self.reset(parameters) def learn(self, Xtrain, ytrain): """ Learns using the traindata """ # Dividing by numsamples before adding ridge regularization # to make the regularization parameter not dependent on numsamples numsamples = Xtrain.shape[0] Xless = Xtrain[:,self.params['features']] self.weights = np.dot(np.dot(np.linalg.pinv((Xless.T @ Xless)/numsamples), Xless.T),ytrain)/numsamples # self.weights = np.dot(np.dot(np.linalg.inv(np.dot(Xless.T,Xless)/numsamples), Xless.T),ytrain)/numsamples def predict(self, Xtest): Xless = Xtest[:,self.params['features']] ytest = np.dot(Xless, self.weights) return ytest class RidgeLinearRegression(Regressor): """ Linear Regression with ridge regularization (l2 regularization) TODO: currently not implemented, you must implement this method Stub is here to make this more clear Below you will also need to implement other classes for the other algorithms """ def __init__( self, parameters={} ): # Default parameters, any of which can be overwritten by values passed to params self.params = {'regwgt': 0.5} self.reset(parameters) def learn(self, Xtrain, ytrain): """ Learns using the traindata """ # Dividing by numsamples before adding ridge regularization # to make the regularization parameter not dependent on numsamples numsamples = Xtrain.shape[0] Xless = Xtrain self.lmd = self.params["regwgt"] self.weights = np.dot(np.dot(np.linalg.pinv((Xless.T @ Xless) / numsamples + self.lmd * np.eye(Xtrain.shape[1])), Xless.T),ytrain)/numsamples # self.weights = np.dot(np.dot(np.linalg.inv(np.dot(Xless.T,Xless)/numsamples), Xless.T),ytrain)/numsamples def predict(self, Xtest): Xless = Xtest ytest = np.dot(Xless, self.weights) return ytest class LassoLinearRegression(Regressor): def __init__( self, parameters={} ): # Default parameters, any of which can be overwritten by values passed to params self.params = {'tol': 1e-4, "max_iter": 100000, 'regwgt': 0.5} # self.weights = np.random.randn() self.reset(parameters) def proximal(self, w, threshold): ind1 = np.where(w > threshold) w[ind1] -= threshold ind2 = np.where(w < -threshold) w[ind2] += threshold return w def learn(self, Xtrain, ytrain): """ Learns using the traindata """ # Dividing by numsamples before adding ridge regularization # to make the regularization parameter not dependent on numsamples dim = Xtrain.shape[1] self.weights = np.zeros(dim) self.tolerance = self.params["tol"] err = np.Infinity numsamples = Xtrain.shape[0] xx = Xtrain.T @ Xtrain / numsamples xy = Xtrain.T @ ytrain / numsamples self.etha = 0.5 / np.linalg.norm(xx, ord="fro") self.max_iter = self.params["max_iter"] # Xless = Xtrain self.lmd = self.params["regwgt"] cw = np.linalg.norm(Xtrain @ self.weights - ytrain) ** 2 / 2 / numsamples + self.lmd * np.linalg.norm(self.weights, ord=1) cnt = 0 while np.abs(cw - err) >= self.tolerance and cnt < self.max_iter: err = cw cnt += 1 self.weights = self.proximal(self.weights - self.etha * xx @ self.weights + self.etha * xy, self.etha * self.lmd) cw = np.linalg.norm(Xtrain @ self.weights - ytrain) ** 2 / 2 / numsamples + self.lmd * np.linalg.norm(self.weights, ord=1) # self.weights = np.dot(np.dot(np.linalg.pinv((Xless.T @ Xless) / numsamples + self.lmd * np.eye(Xtrain.shape[1])), Xless.T),ytrain)/numsamples # self.weights = np.dot(np.dot(np.linalg.inv(np.dot(Xless.T,Xless)/numsamples), Xless.T),ytrain)/numsamples def predict(self, Xtest): Xless = Xtest ytest = np.dot(Xless, self.weights) return ytest class BGDLinearRegression(Regressor): def __init__( self, parameters={} ): # Default parameters, any of which can be overwritten by values passed to params self.params = {'tol': 1e-4, "max_iter": 100000, "rmsprop": False} # self.weights = np.random.randn() self.reset(parameters) self.rp = None def line_search(self, wt, cost_func, g): etha_max = 1 tau = 0.7 tolerance = self.tolerance etha = etha_max w = np.copy(wt) obj = cost_func(w) max_iter = self.max_iter for _ in range(max_iter): w = wt - etha * g if cost_func(w) < obj - tolerance: return w, etha etha *= tau return wt, 0 def learn(self, Xtrain, ytrain): """ Learns using the traindata """ # Dividing by numsamples before adding ridge regularization # to make the regularization parameter not dependent on numsamples dim = Xtrain.shape[1] self.weights = np.random.randn(dim) self.rp = RMSProp(dim) self.tolerance = self.params["tol"] err = np.Infinity numsamples = Xtrain.shape[0] self.max_iter = self.params["max_iter"] # Xless = Xtrain def cost(w): return np.linalg.norm(Xtrain @ w - ytrain) ** 2 / 2 / numsamples # cw = np.linalg.norm(Xtrain @ self.weights - ytrain) ** 2 / 2 / numsamples cw = cost(self.weights) cnt = 0 while np.abs(cw - err) >= self.tolerance and cnt < self.max_iter: err = cost(self.weights) cnt += 1 g = Xtrain.T @ (Xtrain @ self.weights - ytrain) / numsamples etha = self.line_search(self.weights, cost, g)[1] if self.params["rmsprop"]: self.rp.add_weights(g) self.weights -= etha * g / self.rp.mean_weights cw = cost(self.weights) # cw = np.linalg.norm(Xtrain @ self.weights - ytrain) ** 2 / 2 / numsamples # self.weights = np.dot(np.dot(np.linalg.pinv((Xless.T @ Xless) / numsamples + self.lmd * np.eye(Xtrain.shape[1])), Xless.T),ytrain)/numsamples # self.weights = np.dot(np.dot(np.linalg.inv(np.dot(Xless.T,Xless)/numsamples), Xless.T),ytrain)/numsamples def predict(self, Xtest): Xless = Xtest ytest = np.dot(Xless, self.weights) return ytest class SGDLinearRegression(Regressor): def __init__( self, parameters={} ): # Default parameters, any of which can be overwritten by values passed to params self.params = {"num_epochs": 1000, "rmsprop": False} # self.weights = np.random.randn() self.reset(parameters) self.rp = None def learn(self, Xtrain, ytrain): """ Learns using the traindata """ # Dividing by numsamples before adding ridge regularization # to make the regularization parameter not dependent on numsamples dim = Xtrain.shape[1] self.rp = RMSProp(dim) self.weights = np.random.randn(dim) self.num_epochs = self.params["num_epochs"] numsamples = Xtrain.shape[0] etha_0 = .01 # err = np.Infinity for i in range(self.num_epochs): for j in np.random.permutation(numsamples): xj = Xtrain[j, :] # print(xj.shape, ytrain.shape) g = (xj.T @ self.weights - ytrain[j]) * xj if self.params["rmsprop"]: self.rp.add_weights(g) # print(g) etha = etha_0 / (i + 1) self.weights -= etha * g / self.rp.mean_weights # Xless = Xtrain # self.lmd = self.params["regwgt"] def predict(self, Xtest): Xless = Xtest ytest = np.dot(Xless, self.weights) return ytest class MeanProp: def __init__(self, shape): self.__mean_weights = np.ones(shape) self.__n = 0 def add_weights(self, weights): self.__n += 1 self.__mean_weights += (weights - self.__mean_weights) / self.__n @property def mean_weights(self): return self.__mean_weights class RMSProp: def __init__(self, shape): self.__mean_weights = np.ones(shape) self.__n = 0 def add_weights(self, weights): self.__n += 1 self.__mean_weights += (np.square(weights) - self.__mean_weights) / self.__n @property def mean_weights(self): return np.sqrt(self.__mean_weights)<file_sep>from __future__ import division # floating point division import numpy as np import utilities as utils from scipy.stats import norm class Classifier: """ Generic classifier interface; returns random classification Assumes y in {0,1}, rather than {-1, 1} """ def __init__( self, parameters={} ): """ Params can contain any useful parameters for the algorithm """ self.params = {} def reset(self, parameters): """ Reset learner """ self.resetparams(parameters) def resetparams(self, parameters): """ Can pass parameters to reset with new parameters """ try: utils.update_dictionary_items(self.params,parameters) except AttributeError: # Variable self.params does not exist, so not updated # Create an empty set of params for future reference self.params = {} def getparams(self): return self.params def learn(self, Xtrain, ytrain): """ Learns using the traindata """ def predict(self, Xtest): probs = np.random.rand(Xtest.shape[0]) ytest = utils.threshold_probs(probs) return ytest class LinearRegressionClass(Classifier): """ Linear Regression with ridge regularization Simply solves (X.T X/t + lambda eye)^{-1} X.T y/t """ def __init__( self, parameters={} ): self.params = {'regwgt': 0.01} self.reset(parameters) def reset(self, parameters): self.resetparams(parameters) self.weights = None def learn(self, Xtrain, ytrain): """ Learns using the traindata """ # Ensure ytrain is {-1,1} yt = np.copy(ytrain) yt[yt == 0] = -1 # Dividing by numsamples before adding ridge regularization # for additional stability; this also makes the # regularization parameter not dependent on numsamples # if want regularization disappear with more samples, must pass # such a regularization parameter lambda/t numsamples = Xtrain.shape[0] self.weights = np.dot(np.dot(np.linalg.pinv(np.add(np.dot(Xtrain.T,Xtrain)/numsamples,self.params['regwgt']*np.identity(Xtrain.shape[1]))), Xtrain.T),yt)/numsamples def predict(self, Xtest): ytest = np.dot(Xtest, self.weights) ytest[ytest > 0] = 1 ytest[ytest < 0] = 0 return ytest class NaiveBayes(Classifier): """ Gaussian naive Bayes; """ def __init__(self, parameters={}): """ Params can contain any useful parameters for the algorithm """ # Assumes that a bias unit has been added to feature vector as the last feature # If usecolumnones is False, it should ignore this last feature self.params = {'usecolumnones': True} self.reset(parameters) def reset(self, parameters): self.resetparams(parameters) self.means = [] self.stds = [] self.numfeatures = 0 self.numclasses = 0 def learn(self, Xtrain, ytrain): """ In the first code block, you should set self.numclasses and self.numfeatures correctly based on the inputs and the given parameters (use the column of ones or not). In the second code block, you should compute the parameters for each feature. In this case, they're mean and std for Gaussian distribution. """ ### YOUR CODE HERE self.numfeatures = Xtrain.shape[1] - (1 if not self.params['usecolumnones'] else 0) self.numclasses = len(set(ytrain)) ### END YOUR CODE origin_shape = (self.numclasses, self.numfeatures) self.means = np.ones(origin_shape) self.stds = np.zeros(origin_shape) self.priors = np.fromiter((np.count_nonzero(ytrain == label) for label in range(self.numclasses)), dtype=np.float) / ytrain.shape[0] ### YOUR CODE HERE # for feature in self.numfeatures: for label in range(self.numclasses): filter = Xtrain[np.where(ytrain == label)[0], :self.numfeatures] self.means[label, :] = np.mean(filter, axis=0) self.stds[label, :] = np.std(filter, axis=0) # print(self.stds) ### END YOUR CODE assert self.means.shape == origin_shape assert self.stds.shape == origin_shape def predict(self, Xtest): """ Use the parameters computed in self.learn to give predictions on new observations. """ ytest = np.zeros(Xtest.shape[0], dtype=int) ### YOUR CODE HERE for cnt in range(Xtest.shape[0]): sample = Xtest[cnt, :] max_prod = 0 max_ind = -1 for label in range(self.numclasses): _ = (norm.pdf(sample[feature], loc=self.means[label][feature], scale=self.stds[label][feature]) for feature in range(Xtest.shape[1] - 1)) likelihoods = np.fromiter(_, dtype=np.float) pr = self.priors[label] * np.prod(likelihoods) if max_prod < pr: max_prod = pr max_ind = label ytest[cnt] = max_ind ### END YOUR CODE assert len(ytest) == Xtest.shape[0] return ytest class LogitReg(Classifier): def __init__(self, parameters={}): # Default: no regularization self.params = {'regwgt': 0.0, 'regularizer': 'None'} self.reset(parameters) def reset(self, parameters): self.resetparams(parameters) self.weights = None if self.params['regularizer'] is 'l1': self.regularizer = (utils.l1, utils.dl1) elif self.params['regularizer'] is 'l2': self.regularizer = (utils.l2, utils.dl2) else: self.regularizer = (lambda w: 0, lambda w: np.zeros(w.shape,)) def logit_cost(self, theta, X, y): """ Compute cost for logistic regression using theta as the parameters. """ cost = 0.0 num_samples = X.shape[0] ### YOUR CODE HERE for cnt in range(num_samples): cost += -y[cnt] * np.log(utils.sigmoid(np.dot(theta, X[cnt, :]))) cost += -(1 - y[cnt]) * np.log(1 - utils.sigmoid(np.dot(theta, X[cnt, :]))) ### END YOUR CODE return cost def logit_cost_grad(self, theta, X, y): """ Compute gradients of the cost with respect to theta. """ grad = np.zeros(len(theta)) ### YOUR CODE HERE grad = X.T @ (utils.sigmoid(X @ theta) - y) ### END YOUR CODE return grad def learn(self, Xtrain, ytrain): """ Learn the weights using the training data """ self.weights = np.zeros(Xtrain.shape[1],) etha = 0.0001 threshold = 0.0001 delta = 1000 ### YOUR CODE HERE while delta > threshold: grad = self.logit_cost_grad(self.weights, Xtrain, ytrain) # print(grad.shape) delta = np.amax(np.abs(etha * grad)) self.weights += - etha * grad # print(delta) ### END YOUR CODE def predict(self, Xtest): """ Use the parameters computed in self.learn to give predictions on new observations. """ ytest = np.zeros(Xtest.shape[0], dtype=int) ### YOUR CODE HERE # for cnt in range(ytest.shape[0]): # ytest[cnt] = round() ytest = np.round(utils.sigmoid(Xtest @ self.weights)) ### END YOUR CODE assert len(ytest) == Xtest.shape[0] return ytest class NeuralNet(Classifier): """ Implement a neural network with a single hidden layer. Cross entropy is used as the cost function. Parameters: nh -- number of hidden units transfer -- transfer function, in this case, sigmoid stepsize -- stepsize for gradient descent epochs -- learning epochs Note: 1) feedforword will be useful! Make sure it can run properly. 2) Implement the back-propagation algorithm with one layer in ``backprop`` without any other technique or trick or regularization. However, you can implement whatever you want outside ``backprob``. 3) Set the best params you find as the default params. The performance with the default params will affect the points you get. """ def __init__(self, parameters={}): self.params = {'nh': 16, 'transfer': 'sigmoid', 'stepsize': 0.01, 'epochs': 100} self.reset(parameters) def reset(self, parameters): self.resetparams(parameters) if self.params['transfer'] is 'sigmoid': self.transfer = utils.sigmoid self.dtransfer = utils.dsigmoid else: # For now, only allowing sigmoid transfer raise Exception('NeuralNet -> can only handle sigmoid transfer, must set option transfer to string sigmoid') self.w_input = None self.w_output = None def feedforward(self, inputs): """ Returns the output of the current neural network for the given input """ # hidden activations # a_hidden = self.transfer(np.dot(self.w_input, inputs)) a_hidden = self.transfer(inputs @ self.w_input) # output activations # a_output = self.transfer(np.dot(self.w_output, a_hidden)) a_output = self.transfer(a_hidden @ self.w_output) return (a_hidden, a_output) def backprop(self, x, y): """ Return a tuple ``(nabla_input, nabla_output)`` representing the gradients for the cost function with respect to self.w_input and self.w_output. """ ### YOUR CODE HERE # a_hidden = self.transfer(np.dot(self.w_input, x)) # a_output = self.transfer(np.dot(self.w_output, a_hidden)) a_hidden, a_output = self.feedforward(x) # loss = - y * np.log(a_output) - (1 - y) * np.log(1 - a_output) dloss = (- y / a_output + (1 - y) / (1 - a_output))[0] # print(self.dtransfer(a_hidden @ self.w_output)) nabla_output = np.ones(self.w_output.shape) nabla_output[:, 0] = dloss * self.dtransfer(a_hidden @ self.w_output) * a_hidden # np.expand_dims(nabla_output, axis=1) # print(nabla_output.shape, self.w_output.shape) nabla_input = np.ones(self.w_input.shape) nabla_input *= dloss * self.dtransfer(a_hidden @ self.w_output) for i in range(nabla_input.shape[0]): for j in range(nabla_input.shape[1]): nabla_input[i, j] *= self.w_output[j, 0] * self.dtransfer(x @ self.w_input[:, j]) * x[i] # print(self.w_output.shape, self.dtransfer(x @ self.w_input), x.shape) # nabla_input = dloss * self.dtransfer(a_hidden @ self.w_output) * x @ self.dtransfer(x @ self.w_input) @ self.w_output ### END YOUR CODE # print(nabla_input.shape, self.w_input.shape) assert nabla_input.shape == self.w_input.shape assert nabla_output.shape == self.w_output.shape return (nabla_input, nabla_output) # TODO: implement learn and predict functions def learn(self, Xtrain, ytrain): """ Learn the weights using the training data """ # self.weights = np.zeros(Xtrain.shape[1],) num_features = Xtrain.shape[1] num_samples = Xtrain.shape[0] nh = self.params["nh"] self.w_input = np.random.rand(num_features, nh) self.w_output = np.random.rand(nh, 1) ### YOUR CODE HERE step_size = self.params["stepsize"] for _ in range(self.params['epochs']): for cnt in range(num_samples): nabla_input, nablab_output = self.backprop(Xtrain[cnt, :], ytrain[cnt]) self.w_input += -step_size * nabla_input self.w_output += -step_size * nablab_output # grad = self.logit_cost_grad(self.weights, Xtrain, ytrain) # print(grad.shape) # delta = np.amax(np.abs(etha * grad)) # self.weights += - etha * grad # print(delta) ### END YOUR CODE def predict(self, Xtest): """ Use the parameters computed in self.learn to give predictions on new observations. """ ytest = np.zeros(Xtest.shape[0], dtype=int) ### YOUR CODE HERE # for cnt in range(ytest.shape[0]): # ytest[cnt] = round() _, output = self.feedforward(Xtest) ytest = np.round(output) ### END YOUR CODE assert len(ytest) == Xtest.shape[0] return ytest class KernelLogitReg(LogitReg): """ Implement kernel logistic regression. This class should be quite similar to class LogitReg except one more parameter 'kernel'. You should use this parameter to decide which kernel to use (None, linear or hamming). Note: 1) Please use 'linear' and 'hamming' as the input of the paramteter 'kernel'. For example, you can create a logistic regression classifier with linear kerenl with "KernelLogitReg({'kernel': 'linear'})". 2) Please don't introduce any randomness when computing the kernel representation. """ def __init__(self, parameters={}): # Default: no regularization self.params = {'regwgt': 0.0, 'regularizer': None, 'kernel': None, 'stepsize': 1e-6, 'tolerance': None} self.reset(parameters) self.kernel = None # if self.params['kernel'] == "None": # self.kernel = self.linear if self.params['kernel'] == "linear": self.kernel = self.linear elif self.params['kernel'] == "hamming": self.kernel = self.hamming def learn(self, Xtrain, ytrain): """ Learn the weights using the training data. Ktrain the is the kernel representation of the Xtrain. """ Ktrain = None ### YOUR CODE HERE self.num_samples = Xtrain.shape[0] self.Xtrain = Xtrain if self.params['kernel'] is None: Ktrain = Xtrain # elif self.params['kernel'] == "linear": # Ktrain = np.dot(Xtrain, Xtrain) else: Ktrain = np.zeros(shape=(Xtrain.shape[0], self.num_samples)) for i in range(Xtrain.shape[0]): for j in range(self.num_samples): Ktrain[i, j] = self.kernel(Xtrain[i, :], Xtrain[j, :]) # print(Ktrain[i, j]) ### END YOUR CODE self.weights = np.zeros(Ktrain.shape[1],) # etha = 1e-5 etha = self.params["stepsize"] # threshold = 1e-2 if self.params['tolerance'] is None: threshold = etha * 10 else: threshold = self.params['tolerance'] delta = 1000 ### YOUR CODE HERE cost = self.logit_cost(self.weights, Ktrain, ytrain) # print("cost: {}".format(cost)) while delta > threshold: grad = self.logit_cost_grad(self.weights, Ktrain, ytrain) # print(grad.shape) delta = np.amax(np.abs(etha * grad)) self.weights += - etha * grad cost = self.logit_cost(self.weights, Ktrain, ytrain) # print("cost: {}\ndelta: {}".format(cost, delta)) ### END YOUR CODE self.transformed = Ktrain # Don't delete this line. It's for evaluation. # TODO: implement necessary functions # def logit_cost_grad(self, theta, X, y): # """ # Compute gradients of the cost with respect to theta. # """ # grad = np.zeros(len(theta)) # ### YOUR CODE HERE # grad = X.T @ (utils.sigmoid(X @ theta) - y) # ### END YOUR CODE # return grad def predict(self, Xtest): """ Use the parameters computed in self.learn to give predictions on new observations. """ ytest = np.zeros(Xtest.shape[0], dtype=int) ### YOUR CODE HERE # for cnt in range(ytest.shape[0]): # ytest[cnt] = round() if self.params["kernel"] == "None": Ktest = Xtest else: Ktest = np.zeros(shape=(Xtest.shape[0], self.num_samples)) for i in range(Ktest.shape[0]): for j in range(Ktest.shape[1]): Ktest[i, j] = self.kernel(Xtest[i, :], self.Xtrain[j, :]) ytest = np.round(utils.sigmoid(Ktest @ self.weights)) ### END YOUR CODE assert len(ytest) == Xtest.shape[0] return ytest def hamming(self, x1, x2): # return np.count_nonzero(x1 == x2) # print(x1, x2) return np.count_nonzero(np.abs(x1 - x2) < 1e-2) def linear(self, x1, x2): return np.dot(x1, x2) / np.linalg.norm(x1) / np.linalg.norm(x2) # ====================================================================== def test_lr(): print("Basic test for logistic regression...") clf = LogitReg() theta = np.array([0.]) X = np.array([[1.]]) y = np.array([0]) try: cost = clf.logit_cost(theta, X, y) except: raise AssertionError("Incorrect input format for logit_cost!") assert isinstance(cost, float), "logit_cost should return a float!" try: grad = clf.logit_cost_grad(theta, X, y) except: raise AssertionError("Incorrect input format for logit_cost_grad!") assert isinstance(grad, np.ndarray), "logit_cost_grad should return a numpy array!" print("Test passed!") print("-" * 50) def test_nn(): print("Basic test for neural network...") clf = NeuralNet() X = np.array([[1., 2.], [2., 1.]]) y = np.array([0, 1]) clf.learn(X, y) assert isinstance(clf.w_input, np.ndarray), "w_input should be a numpy array!" assert isinstance(clf.w_output, np.ndarray), "w_output should be a numpy array!" try: res = clf.feedforward(X[0, :]) except: raise AssertionError("feedforward doesn't work!") try: res = clf.backprop(X[0, :], y[0]) except: raise AssertionError("backprob doesn't work!") print("Test passed!") print("-" * 50) def main(): test_lr() test_nn() if __name__ == "__main__": main()
8598cd9381ad8cf9a033af2b23adee1c160b60fa
[ "Python" ]
2
Python
ssinad/cmput-551-assignments
d579106c05bdf2df7088dbbb0943c33e4e2bb4b7
5ac2c09e6aa2c4a22ccf07704a4fe30dc7e8a2b5
refs/heads/master
<file_sep>package com.example.hp.ambulanceapp; import android.app.ProgressDialog; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; public class LoginActivity extends AppCompatActivity implements View.OnClickListener { EditText loginEmail; EditText loginPassword; Button loginBtn; TextView gotoRegister; ProgressDialog progressDialog; FirebaseAuth firebaseAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); firebaseAuth = FirebaseAuth.getInstance(); if(firebaseAuth.getCurrentUser() != null){ finish(); startActivity(new Intent(this, BaseActivity.class)); } loginEmail = findViewById(R.id.loginEmail); loginPassword = findViewById(R.id.loginPassword); loginBtn = findViewById(R.id.loginBtn); gotoRegister = findViewById(R.id.gotoRegister); progressDialog = new ProgressDialog(this); loginBtn.setOnClickListener(this); gotoRegister.setOnClickListener(this); } private void loginUser() { String email = loginEmail.getText().toString().trim(); String password = loginPassword.getText().toString().trim(); if(TextUtils.isEmpty(email)){ Toast.makeText(this, "Email cannot be empty", Toast.LENGTH_SHORT).show(); return; } if(TextUtils.isEmpty(password)){ Toast.makeText(this, "Password cannot be empty", Toast.LENGTH_SHORT).show(); return; } progressDialog.setMessage("Logging In..."); progressDialog.show(); firebaseAuth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { progressDialog.dismiss(); if(task.isSuccessful()){ finish(); startActivity(new Intent(getApplicationContext(), BaseActivity.class)); Toast.makeText(getApplicationContext(), "User logged in", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "Login failed! Try again", Toast.LENGTH_SHORT).show(); } } }); } @Override public void onClick(View v) { if(v == loginBtn){ loginUser(); } if(v == gotoRegister){ finish(); startActivity(new Intent(this, RegistrationActivity.class)); } } } <file_sep>package com.example.hp.ambulanceapp; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; public class BaseActivity extends AppCompatActivity implements View.OnClickListener{ TextView baseTw; Button logoutBtn; FirebaseAuth firebaseAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_base); baseTw = (TextView) findViewById(R.id.baseTextview); logoutBtn = (Button) findViewById(R.id.logoutBtn); firebaseAuth = FirebaseAuth.getInstance(); if(firebaseAuth.getCurrentUser() == null){ finish(); startActivity(new Intent(this, LoginActivity.class)); } FirebaseUser user = firebaseAuth.getCurrentUser(); String userEmail = user.getEmail(); baseTw.setText("Welcome " + userEmail); logoutBtn.setOnClickListener(this); } @Override public void onClick(View v) { if(v == logoutBtn) { firebaseAuth.signOut(); finish(); startActivity(new Intent(this, LoginActivity.class)); } } }
4f6d43bc91c8b6889275b5140a3016463d59cd8f
[ "Java" ]
2
Java
rashi-saxena/AmbulanceApp
9b1ced697d96d57f46f6f490ffbb073c6271c4a0
4a912b2efd97bcd02e4439d3cbbfec584ca18ad3
refs/heads/main
<repo_name>matheusjcn/nlw-heat<file_sep>/api/src/routes.ts import { Router } from 'express'; import AuthenticateUseController from './controllers/AuthenticateUserController'; import CreateMessageController from './controllers/CreateMessageController'; import GetLastNMessagesController from './controllers/GetLastNMessagesController'; import ProfileUserController from './controllers/ProfileUserController'; import { ensureAuthenticate } from './middleware/ensureAuthenticate'; const router = Router(); router.post('/authenticate', new AuthenticateUseController().handle); router.get('/messages/lasts', new GetLastNMessagesController().handle); router.post( '/message', ensureAuthenticate, new CreateMessageController().handle, ); router.get( '/user/profile', ensureAuthenticate, new ProfileUserController().handle, ); export default router; <file_sep>/api/src/controllers/GetLastNMessagesController.ts import { Request, Response } from 'express'; import CreateMessageService from '../services/GetLastNMessagesService'; class GetLastNMessagesController { async handle(req: Request, res: Response) { const service = new CreateMessageService(); const result = await service.execute(3); return res.json(result); } } export default GetLastNMessagesController; <file_sep>/README.md # nlw-heat Aplicação desenvolvida durante o NLW Heat da [Rocketseat.](https://www.rocketseat.com.br) <file_sep>/api/src/server.ts import { httpServer } from './app'; const PORT = 3333; httpServer.listen(PORT, () => console.log(`Running in port ${PORT}`)); <file_sep>/api/src/services/GetLastNMessagesService.ts import prismaClient from '../prisma'; class GetLastNMessagesService { async execute(qtd: number) { const messages = await prismaClient.message.findMany({ take: qtd, orderBy: { create_at: 'desc', }, include: { user: true, }, }); return messages; } } export default GetLastNMessagesService;
9890e4f51c24c9a25c2a6ab0951320ddf96c3f1b
[ "Markdown", "TypeScript" ]
5
TypeScript
matheusjcn/nlw-heat
382eaec6d005418852df6b94ed549259561d9315
075e5387935b814be30509f25f06e59e87c081dd
refs/heads/master
<file_sep>groupmates = [ { "name": u"Константин", "group": "БАП1801", "age": 18, "marks": [4, 4, 4, 5, 3] }, { "name": u"Андрей", "group": "БАП1801", "age": 21, "marks": [3, 3, 4, 4, 5] }, { "name": u"Мансур", "group": "БАП1801", "age": 19, "marks": [5, 2, 4, 4, 3] }, { "name": u"Максим", "group": "БАП1801", "age": 18, "marks": [5, 5, 5, 4, 4] } ] def pnt_students(students): zn=float(input('Введите минимальный допустимый ср.балл ')) print(u"Имя студента".ljust(15),u"Группа".ljust(8),u"Возраст".ljust(8),u"Оценки".ljust(20)) for j in students: a=j["marks"] sr=0 su=0 for i in a: su+=i sr=su/len(a) if sr>=zn: print(j["name"].ljust(15),j["group"].ljust(8),str(j["age"]).ljust(8),str(j["marks"]).ljust(20)) pnt_students(groupmates) <file_sep>Тема: "Строки и списки" Код 1: Запрашивайте у пользователя вводить число user_number, если оно равно my_number. Код 2: Пусть задан список, содержащий строки. Выведите все строки, заканчивающиеся буковой р. Код 3: Cгенерировать и вывести: cлучайно соответствуют размеру 6 символов, доступны только цифры. Строка должна содержать хотя бы одну цифру 3.. Код 4: Случайная копия, состоящая из 8 символов и доступных цифр и букв. Строка должна содержать хотя бы одну цифру. <file_sep>Тема: "Введение в Python" Код 1: Программа для решения примера, предусматривающая деление на ноль Код 2: Дан список ссылок, содержит строки и числа. Выведите все четкие элементы в одной строке. Код 3: Дан указанный список, содержащий только число. Выведите результат умножения всех чисел меньше 10. Код 4: Дан указанный список, содержащий только число. Выведите среднее арифметическое (сумма всех числовых, деленная на количество элементов).
58cd6cc34fed03c821aa9d66d24f0473ff668a1b
[ "Markdown", "Python" ]
3
Python
wmansy/WEB
e70f315a99b9b3f0fc84fabb610e304093c678e0
70b9919aba9c6b60e440ff85fd58052eb4c3ac42
refs/heads/master
<file_sep>var globals = require('../index'); var options = globals.options; var Bullet = require("./bullet"); var Tank = function(base, color, tankNumber, dimensions) { this.type = "tank" this.color = color; this.size = {height: 20, width: 20}; this.tankNumber = tankNumber; this.base = { position: base.position, size: base.size }; this.positionStep = {x: 0, y: 0}; this.radians; this.dead = false; this.ghost = true; //true if just respawned and hasn't moved yet this.hasFlag = false; this.dimensions = dimensions; this.reloading = false; this.setHomePosition(); this.setStartingAngle(); this.setStartingSpeed(); //add game's addBullet function to oneself }; Tank.prototype = { setHomePosition: function() { var xDiff = this.dimensions.width/2 - this.base.position.x; var yDiff = this.dimensions.height/2 - this.base.position.y; if (Math.abs(xDiff) > Math.abs(yDiff)) { this.position = { x: this.base.position.x, y: this.base.position.y + this.size.height / 2 - (this.base.size.height / 2) + (this.size.height * this.tankNumber) }; } else { this.position = { x: this.base.position.x + this.size.width / 2 - (this.base.size.width / 2) + (this.size.width * this.tankNumber), y: this.base.position.y }; } }, setStartingAngle: function() { this.angle = Math.random() * 360; this.angleVel = 0; //-1 to 1 }, setStartingSpeed: function() { this.speed = 0; //-1 to 1 }, calculate: function() { //reset postitionStep this.positionStep.x = this.position.x; this.positionStep.y = this.position.y; this.angle += this.angleVel; if (this.angle < 0) { this.angle = (this.angle + 360) % 360; //prevent angle overflow and keep it positive } else { this.angle = this.angle % 360; //prevent angle overflow } //keep speed within max speed if (this.speed > options.maxTankSpeed) { this.speed = options.maxTankSpeed; } if (this.speed < -options.maxTankSpeed) { this.speed = -options.maxTankSpeed; } this.radians = this.angle * (Math.PI/180); this.radians = round(this.radians, 4); this.positionStep.x = (Math.cos(this.radians) * this.speed + this.position.x); this.positionStep.y = (Math.sin(this.radians) * this.speed + this.position.y); //if (this.color = "red" && this.tankNumber === 0) {console.log(this.angle, this.radians, Math.cos(this.radians), Math.sin(this.radians) );} }, moveX: function() { this.position.x = this.positionStep.x; this.ghost = false; }, moveY: function() { this.position.y = this.positionStep.y; this.ghost = false; }, moveTanks: function(order) { if (this.dead) { return; } this.angleVel = order.angleVel; this.speed = order.speed; }, fireTanks: function(order) { if (this.dead) { return; } if (this.reloading) { return; } this.addBulletToGame(new Bullet({ color: this.color, radians: this.radians, options: options, position: this.position, tankSize: this.size })); this.reloading = true; var self = this; setTimeout(function() { self.reloading = false; }, options.maxFireFrequency); }, die: function(respawnTime) { this.dead = true; this.ghost = true; this.position.x = 0; this.position.y = 0; this.hasFlag = false; var self = this; if (!respawnTime) { respawnTime = options.respawnTime; } setTimeout(function() { self.dead = false; self.setHomePosition(); self.setStartingSpeed(); self.setStartingAngle(); }, respawnTime); }, carryFlag: function(flag) { this.hasFlag = flag.color; }, dropFlag: function() { this.hasFlag = false; } //one prototype lives in game.js }; function round(value, decimals) { return Number(Math.round(value+'e'+decimals)+'e-'+decimals); } module.exports = Tank; <file_sep>var app = require('express')(); var fs = require('fs'); var vm = require('vm'); var http = require('http').Server(app); var io = require('socket.io')(http); module.exports.app = app; module.exports.fs = fs; module.exports.vm = vm; module.exports.http = http; module.exports.io = io; app.get('/', function(req, res) { res.sendFile(__dirname + "/public/index.html"); }); app.get('/main.js', function(req, res) { res.sendFile(__dirname + "/public/main.js"); }); app.get('/styles.css', function(req, res) { res.sendFile(__dirname + "/public/styles.css"); }); app.get('/img/red_tank.png', function(req, res) { res.sendFile(__dirname + "/img/red_tank.png"); }); app.get('/img/blue_tank.png', function(req, res) { res.sendFile(__dirname + "/img/blue_tank.png"); }); app.get('/img/green_tank.png', function(req, res) { res.sendFile(__dirname + "/img/green_tank.png"); }); app.get('/img/purple_tank.png', function(req, res) { res.sendFile(__dirname + "/img/purple_tank.png"); }); app.get('/img/red_basetop.png', function(req, res) { res.sendFile(__dirname + "/img/red_basetop.png"); }); app.get('/img/blue_basetop.png', function(req, res) { res.sendFile(__dirname + "/img/blue_basetop.png"); }); app.get('/img/green_basetop.png', function(req, res) { res.sendFile(__dirname + "/img/green_basetop.png"); }); app.get('/img/purple_basetop.png', function(req, res) { res.sendFile(__dirname + "/img/purple_basetop.png"); }); app.get('/img/red_flag.png', function(req, res) { res.sendFile(__dirname + "/img/red_flag.png"); }); app.get('/img/blue_flag.png', function(req, res) { res.sendFile(__dirname + "/img/blue_flag.png"); }); app.get('/img/green_flag.png', function(req, res) { res.sendFile(__dirname + "/img/green_flag.png"); }); app.get('/img/purple_flag.png', function(req, res) { res.sendFile(__dirname + "/img/purple_flag.png"); }); app.get('/img/grass.png', function(req, res) { res.sendFile(__dirname + "/img/grass(100x100).png"); }); app.get('/img/wall.png', function(req, res) { res.sendFile(__dirname + "/img/wall.png"); }); //TODO allow these to be set by commandline args var options = { numOfTanks: 4, maxTankSpeed: 1, friendlyFireSafe: true, port: 8003, maxBulletSpeed: 5, respawnTime: 10000, flagRepawnWait: 10000, pointsForCarry: 1, pointsForCapture: 100, resetOnJoin: true, maxFireFrequency: 5000 }; module.exports.options = options; //create new game var Game = require('./src/game'); //var map = "maps/square.json"; var map = "maps/plain_field.json" //var map = "maps/one_vs_one.json" var g = new Game(map); module.exports.Game = g; <file_sep># JSFlags ## About Robot AI tanks and game engine written 100% in nodeJS and javascript from scratch. A rewrite of [this](https://github.com/chris-clm09/bzflag) BTZFlag Python game. Tanks move about a 2d world shooting enemy tanks and stealing flags for points. Actions of tanks are recieved from a Javascript written artificial intelligence. Goal was to write the game with as few dependencies as possible to make the game super portable and easy to set up. This project is written to be a fun hackathon where each member creates an AI and battle each other. I also plan to make several improvments from the original python game including a manual mode. Still in development. View in Chrome. ## How to set up - install nodejs (google is your friend) - Download jsflags - in the project root run: node index.js - open localhost:8003 in Chrome - run [jsflags-ai](https://github.com/erceth/jsflags-ai) to connect - to enter manual mode select player (note: running manual mode and connecting an AI to the same player will cause tanks to listen to both commands) - to simply watch the AI control the tanks click Observer ## Screenshot ![jsflag screenshot](https://dl.dropboxusercontent.com/u/49269350/jsflags.png "jsflag gameplay") ## Manual controls - Once the jsflags server is running and you view the game in Chrome, you can select manual mode to move your tanks with the mouse and fire with the keyboard. - Select a tank by either clicking on the tank icon to the right of the screen or by clicking on the tanks directly. - Deselect a tank by doing the same thing. - To select all tanks double click on the grass. - To move selected tanks click once anywhere on the map. - To fire selected tanks press any key (i like to use the f key). ## Rules of the game - Objective is to earn more points than everyone else. - You earn one point for every second your tank holds the flag. - You earn 100 points for returning the enemy flag to your base. - The flag will reset to the enemy base after you return it to your base and recieve capture points. ## More info - This game is design to to be run on a local area network. After you run jsflags server another computer on the same network can connect their AI to your server using your local IP address. - Technically this game could probably run over the internet. - Various options are available in index.js in the options object. <file_sep>var Bullet = function(bulletData) { this.type = "bullet"; this.size = {height: 6, width: 6}; this.color = bulletData.color; this.tankSize = bulletData.tankSize; this.speed = bulletData.options.maxBulletSpeed || 10; this.radians = bulletData.radians; //start out in front of tank this.position = { x: (bulletData.position.x ) + (Math.cos(this.radians) * bulletData.tankSize.width), y: (bulletData.position.y ) + (Math.sin(this.radians) * bulletData.tankSize.height) }; // this.position = { // x: bulletData.position.x + (round(Math.cos(this.radians), 4) >= 0) ? bulletData.tankSize.x / 2 : -(bulletData.tankRadius), // y: bulletData.position.y + (round(Math.sin(this.radians), 4) >= 0) ? bulletData.tankRadius : -(bulletData.tankRadius) // }; console.log(this.position); this.positionStep = {x: this.position.x, y: this.position.y}; this.dead = false; }; Bullet.prototype = { calculate: function() { //reset postitionStep this.positionStep.x = this.position.x; this.positionStep.y = this.position.y; this.positionStep.x = (Math.cos(this.radians) * this.speed + this.position.x); this.positionStep.y = (Math.sin(this.radians) * this.speed + this.position.y); }, moveX: function() { this.position.x = this.positionStep.x; }, moveY: function() { this.position.y = this.positionStep.y; }, die: function() { //destroy boundary this.dead = true; }, isFriendly: function(otherBody) { return this.color === otherBody.color; } }; function round(value, decimals) { return Number(Math.round(value+'e'+decimals)+'e-'+decimals); } module.exports = Bullet; <file_sep>var globals = require('../index'); var options = globals.options; var Flag = function(color, position) { this.type = "flag"; this.originalPosition = position; this.position = this.originalPosition; this.size = {height: 19, width: 19}; this.color = color; this.tankToFollow = null; }; Flag.prototype = { update: function() { if (this.tankToFollow && !this.tankToFollow.dead) { this.position = { x: this.tankToFollow.position.x, y: this.tankToFollow.position.y }; } if (this.tankToFollow && this.tankToFollow.dead) { this.tankToFollow = null; this.slowDeath(); } //if (this.color === "blue") {console.log(this.position);} }, die: function() { this.position = { x: this.originalPosition.x, y: this.originalPosition.y } if (this.tankToFollow) { this.tankToFollow.dropFlag(); } this.tankToFollow = null; }, slowDeath: function() { var self = this; setTimeout(function() { if (!self.tankToFollow) { self.die(); } }, options.flagRepawnWait); }, followThisTank: function(tank) { if (!this.tankToFollow) { this.tankToFollow = tank; } } // update: function() { // if (!!this.tankToFollow && !this.tankToFollow.dead) { // this.position = this.tankToFollow.position; // } // if (this.tankToFollow && this.tankToFollow.dead) { // this.tankToFollow = null; // } // }, // hasTank: function() { // return !!this.tankToFollow && !this.tankToFollow.dead; // }, // die: function() { // this.tankToFollow = null; // this.position = this.originalPosition; // }, // followThisTank: function(tank) { // this.tankToFollow = tank; // }, // stopFollowing: function() { // this.tankToFollow = null; // } } module.exports = Flag; <file_sep>var Boundary = function(boundaryData) { this.type = "boundary"; this.position = boundaryData.position; this.positionStep = this.position; this.size = boundaryData.size; }; Boundary.prototype = { calculate: function() { //nothing to update }, moveX: function() { }, moveY: function() { }, die: function() { //destroy boundary ? } } module.exports = Boundary;
0a0877da2a85722ffb94c6635b1947960b6282b0
[ "JavaScript", "Markdown" ]
6
JavaScript
bluesnowman/jsflags
0029e2e93e938110e59e0e34cf0771fe400bc4ef
a1925e6b97a09e2f6da05a8404435a5bddf77a50
refs/heads/master
<file_sep># ED-ReverseCycleCooler This module changes the cooler to have a rotate option; this allows you to switch it between cooling a room and using its output to warm the same room. #Change Log 1.0.0.0 * Updating to Rimworld 1.0 0.18.0.0 * Updating to Alpha 17 0.17.0 * Updating to Alpha 17 04.00.00 * Update to Alpha 16 03.00.00 * Alpha 15 Update 02.00.01 * Fix for potentially not loading Graphical Resources on loading a saved game. 02.00.00 * Alpha 14 Update 01.00.01 * Adding Dependencies.xml * Removing unneeded logging. 01.00.00 * Initial Release <file_sep>using System.Collections.Generic; using System.Text; using Verse; using RimWorld; using UnityEngine; using Multiplayer.API; namespace EnhancedDevelopment.ReverseCycleCooler { [StaticConstructorOnStartup] public class Building_ReverseCycleCooler : Building_Cooler { private static Texture2D UI_ROTATE_RIGHT; private static Texture2D UI_TEMPERATURE_COOLING; private static Texture2D UI_TEMPERATURE_HEATING; private static Texture2D UI_TEMPERATURE_AUTO; private const float HeatOutputMultiplier = 1.25f; private const float EfficiencyLossPerDegreeDifference = 0.007692308f; private const float TemperatureDiffThreshold = 40.0f; private const float UnknownConst_2 = 4.16666651f; private EnumCoolerMode m_Mode = EnumCoolerMode.Cooling; static Building_ReverseCycleCooler() { UI_ROTATE_RIGHT = ContentFinder<Texture2D>.Get("UI/RotRight", true); UI_TEMPERATURE_COOLING = ContentFinder<Texture2D>.Get("UI/Temperature_Cooling", true); UI_TEMPERATURE_HEATING = ContentFinder<Texture2D>.Get("UI/Temperature_Heating", true); UI_TEMPERATURE_AUTO = ContentFinder<Texture2D>.Get("UI/Temperature_Auto", true); if (MP.enabled) { if (!MP.API.Equals("0.1")) { Log.Error("ReverseCycleCooler: MP API version mismatch. This mod is designed to work with MPAPI version 0.1"); } else { MP.RegisterAll(); //Log.Message("ReverseCycleCooler: MP init"); } } } public override void SpawnSetup(Map map, bool respawningAfterLoad) { base.SpawnSetup(map, respawningAfterLoad); } public override void TickRare() { if (!compPowerTrader.PowerOn) { return; } IntVec3 intVec3_1 = Position + IntVec3Utility.RotatedBy(IntVec3.South, Rotation); IntVec3 intVec3_2 = Position + IntVec3Utility.RotatedBy(IntVec3.North, Rotation); bool flag = false; if (!GenGrid.Impassable(intVec3_2, Map) && !GenGrid.Impassable(intVec3_1, Map)) { float temperature1 = GridsUtility.GetTemperature(intVec3_2, Map); float temperature2 = GridsUtility.GetTemperature(intVec3_1, Map); //Check for Mode bool _cooling = true; if (m_Mode == EnumCoolerMode.Cooling) { _cooling = true; } else if(m_Mode == EnumCoolerMode.Heating) { _cooling = false; } else if (m_Mode == EnumCoolerMode.Auto) { if (temperature1 > compTempControl.targetTemperature) { //Log.Message("Auto Cooling"); _cooling = true; } else { //Log.Message("Auto Heating"); _cooling = false; } } float a; float energyLimit; float _TemperatureDifferance; float num2; if (_cooling) { //Log.Message("Cooling"); _TemperatureDifferance = temperature1 - temperature2; if (temperature1 - TemperatureDiffThreshold > _TemperatureDifferance) _TemperatureDifferance = temperature1 - TemperatureDiffThreshold; num2 = 1.0f - _TemperatureDifferance * EfficiencyLossPerDegreeDifference; if (num2 < 0.0f) num2 = 0.0f; energyLimit = (float)(compTempControl.Props.energyPerSecond * (double)num2 * UnknownConst_2); a = GenTemperature.ControlTemperatureTempChange(intVec3_1, Map, energyLimit, compTempControl.targetTemperature); flag = !Mathf.Approximately(a, 0.0f); } else { //Log.Message("Heating"); _TemperatureDifferance = temperature1 - temperature2; if (temperature1 + TemperatureDiffThreshold > _TemperatureDifferance) _TemperatureDifferance = temperature1 + TemperatureDiffThreshold; num2 = 1.0f - _TemperatureDifferance * EfficiencyLossPerDegreeDifference; if (num2 < 0.0f) num2 = 0.0f; energyLimit = (float)(compTempControl.Props.energyPerSecond * -(double)num2 * UnknownConst_2); a = GenTemperature.ControlTemperatureTempChange(intVec3_1, Map, energyLimit, compTempControl.targetTemperature); flag = !Mathf.Approximately(a, 0.0f); } if (flag) { GridsUtility.GetRoomGroup(intVec3_2, Map).Temperature -= a; GenTemperature.PushHeat(intVec3_1, Map, (float)(+(double)energyLimit * HeatOutputMultiplier)); } } CompProperties_Power props = compPowerTrader.Props; if (flag) { compPowerTrader.PowerOutput = -props.basePowerConsumption; } else { compPowerTrader.PowerOutput = -props.basePowerConsumption * compTempControl.Props.lowPowerConsumptionFactor; } compTempControl.operatingAtHighPower = flag; } /* public override void TickRare() { if (!this.compPowerTrader.PowerOn) { return; } IntVec3 intVec3_1 = this.Position + Gen.RotatedBy(IntVec3.south, this.Rotation); IntVec3 intVec3_2 = this.Position + Gen.RotatedBy(IntVec3.north, this.Rotation); }*/ public override IEnumerable<Gizmo> GetGizmos() { //Add the stock Gizmoes foreach (var g in base.GetGizmos()) { yield return g; } { Command_Action act = new Command_Action { //act.action = () => Designator_Deconstruct.DesignateDeconstruct(this); action = () => ChangeRotation(), icon = UI_ROTATE_RIGHT, defaultLabel = "Rotate", defaultDesc = "Rotates", activateSound = SoundDef.Named("Click") }; //act.hotKey = KeyBindingDefOf.DesignatorDeconstruct; //act.groupKey = 689736; yield return act; } if (m_Mode == EnumCoolerMode.Cooling) { Command_Action act = new Command_Action { //act.action = () => Designator_Deconstruct.DesignateDeconstruct(this); action = () => ChangeMode(), icon = UI_TEMPERATURE_COOLING, defaultLabel = "Cooling", defaultDesc = "Cooling", activateSound = SoundDef.Named("Click") }; //act.hotKey = KeyBindingDefOf.DesignatorDeconstruct; //act.groupKey = 689736; yield return act; } if (m_Mode == EnumCoolerMode.Heating) { Command_Action act = new Command_Action { //act.action = () => Designator_Deconstruct.DesignateDeconstruct(this); action = () => ChangeMode(), icon = UI_TEMPERATURE_HEATING, defaultLabel = "Heating", defaultDesc = "Heating", activateSound = SoundDef.Named("Click") }; //act.hotKey = KeyBindingDefOf.DesignatorDeconstruct; //act.groupKey = 689736; yield return act; } if (m_Mode == EnumCoolerMode.Auto) { Command_Action act = new Command_Action { //act.action = () => Designator_Deconstruct.DesignateDeconstruct(this); action = () => ChangeMode(), icon = UI_TEMPERATURE_AUTO, defaultLabel = "Auto", defaultDesc = "Auto", activateSound = SoundDef.Named("Click") }; //act.hotKey = KeyBindingDefOf.DesignatorDeconstruct; //act.groupKey = 689736; yield return act; } } public void ChangeRotation() { //Log.Error("Rotation"); if (Rotation.AsInt == 3) { Rotation = new Rot4(0); } else { Rotation = new Rot4(Rotation.AsInt + 1); } // Tell the MapDrawer that here is something thats changed Map.mapDrawer.MapMeshDirty(Position, MapMeshFlag.Things, true, false); //this.Rotation.Rotate(RotationDirection.Clockwise); //this.Rotation.Rotate(RotationDirection.Clockwise); } [SyncMethod] public void ChangeMode() { if (m_Mode == EnumCoolerMode.Cooling) { m_Mode = EnumCoolerMode.Heating; } else if (m_Mode == EnumCoolerMode.Heating) { m_Mode = EnumCoolerMode.Auto; } else if (m_Mode == EnumCoolerMode.Auto) { m_Mode = EnumCoolerMode.Cooling; } } public override string GetInspectString() { StringBuilder stringBuilder = new StringBuilder(); if (m_Mode == EnumCoolerMode.Cooling) { stringBuilder.AppendLine("Mode: Cooling"); } else if (m_Mode == EnumCoolerMode.Heating) { stringBuilder.AppendLine("Mode: Heating"); } else if (m_Mode == EnumCoolerMode.Auto) { stringBuilder.AppendLine("Mode: Auto"); } stringBuilder.Append(base.GetInspectString()); return stringBuilder.ToString(); } //Saving game public override void ExposeData() { base.ExposeData(); // Scribe_Deep.LookDeep(ref shieldField, "shieldField"); // Scribe_Values.LookValue(ref m_Mode, "m_Mode"); //Scribe_Collections.LookList<Thing>(ref listOfBufferThings, "listOfBufferThings", LookMode.Deep, (object)null); Scribe_Values.Look(ref m_Mode, "m_Mode"); } } public enum EnumCoolerMode { //Default Mod, Cooling to a specific temperature. Cooling, //Heating to a specific temperature. Heating, //Targeting a specific temperature and Heating or Cooling to reach it. Auto } }
c0c6ec76050dac92bc5d5ee02a547b2c49254fd0
[ "Markdown", "C#" ]
2
Markdown
jankytay/ED-ReverseCycleCooler
79d446be55c43c659681237a19cc6ee7deb89bfb
ca2fb6e0837e10d71c6e1ea7599d68126872ca29
refs/heads/master
<file_sep># Q18.[Forensic]leaf in forest 1. text ファイルとして開くと lovelive! がめっちゃ繰り返されてる。 2. vim で `%s/[lovelive!]//g` などして lovelive! に含まれる文字をすべて取り除く。 3. `<なんかバイナリ>CCCPPPAAAWWW{{{MMMGGGRRREEEPPP}}}` が得られる。 ``` cpaw{mgrep} ``` <file_sep>// https://ctf.cpaw.site/questions.php?qnum=26 // Q26.[PPC]Remainder theorem #include <bits/stdc++.h> using namespace std; typedef long long int ll; const ll MAX_LL = 1e18; const ll R1 = 32134; const ll M1 = 1584891; const ll R2 = 193127; const ll M2 = 3438478; int main() { for (ll x = R2; x < MAX_LL; x += M2) { if (x % M1 == R1) { cout << x << endl; break; } } return 0; } <file_sep># Q16.[Network+Forensic]HTTP Traffic 1. wireshark で pcap ファイルを開く 2. File -> Export Objects -> HTTP -> Save All で HTTP でやり取りしたファイルをすべて復元する 3. `network100(1)` があやしそう 4. 中身は html なので、ソースを見ながら `js` `img` `css` ディレクトリを作って適切にファイルを 配置する。 5. ボタンをクリック 6. 画像に flag が表示される ``` cpaw{Y0u_r3st0r3d_7his_p4ge} ``` <file_sep># Q10.[Forensics] River Exif 情報の緯度経度を見る ``` cpaw{koutsukigawa} ``` <file_sep>// CTF challenge book // q01 SelfReference #include <cstdlib> #include <iostream> using namespace std; int main() { char arg_ch[] = {0x7d, 0x56, 0x18, 0x43, 0x15, 0x67, 0x0f, 0x0a, 0x1c, 0x28, 0x3b, 0x76, 0x05, 0x30, 0x00, 0x50, 0x54, 0x0c, 0x59, 0x09, 0x1f, 0x7d, 0x0d, 0x3a, 0x02, 0x7a, 0x08, 0x7e, 0x01, 0x40, 0x57, 0x60, 0x11, 0x3e, 0x05, 0x2d, 0x05, 0x0f, 0x00, 0x00, 0x06, 0x55, 0x30}; char arg_8h[256] = {}; char arg_10h[1025] = "XV5xxMLwKP8KaayCSG04vQVv0kMSA3ZTRyZ4bCy" "et8VXaceow53CkC3JA0ZAg5wBx86kHvlCYhdeVPSCeEYy3rFVyOJdZTNgwxSgcRYZV6E2" "8DqXMm5aYnfm3Z4uEDUz1FpmneQcuwOPwrMdx9Gy4Q3MKZIaalSHHKvpuQn5zbTtmgPfw" "pWVMSnuP0fV43mfuPQGX6ryJk2ANuuXxctZ03CNj5U6wF3X2cor5baXfZzFRltlMM5cl8" "BHAptzDkPMYFBWUg56usLpnq9gawM0XWMOIbx8z99logD8nCzj4QsjHAsnWf1EfrGZs1J" "CyF8fsHKzSWXUp8QWLUfgtPWWwI6ae3f5eEE9eqKAAqqp8s05HMAnEltRpFAe5jq25LW7" "1BdnMVlP8p9EkD3ICugWJzZSo2saKenlJiMa7kOvCVc1qPAvEl0G2Txv79FSK2req4wpf" "<KEY>" "<KEY>" "<KEY>" "<KEY>" "<KEY>" "<KEY>uj9WDITQ6Z6bde" "<KEY>Rv<KEY>" "b790Uvkj7yjAAX6ItBQb0zMt95hK8eyPkP1cgHSapReU2G6I6UJjQ0pFUgHfpK6pmkmJb" "rinid5WqgImMunLrwR0"; int eax, edx; int local_10h = 43; srand(local_10h); for (int i = 0; i < local_10h; i++) { eax = rand(); edx = eax; eax = eax >> 0x1f; eax = eax >> 0x16; edx += eax; edx &= 0x3ff; edx -= eax; arg_8h[i] = arg_10h[edx] ^ arg_ch[i]; } arg_8h[local_10h] = '\0'; cout << arg_8h << endl; return 0; } <file_sep>// https://ctf.cpaw.site/questions.php?qnum=14 // Q14.[PPC]並べ替えろ! #include <bits/stdc++.h> using namespace std; typedef long long int ll; typedef pair<int, int> pii; typedef pair<ll, int> pli; const string IN_STR = "15,1,93,52,66,31,87,0,42,77,46,24,99,10,19,36,27,4,58,76,2,81,50,102,33," "94,20,14,80,82,49,41,12,143,121,7,111,100,60,55,108,34,150,103,109,130,25," "54,57,159,136,110,3,167,119,72,18,151,105,171,160,144,85,201,193,188,190," "146,210,211,63,207"; int main() { stringstream ss(IN_STR); string str; vector<int> nums; while (getline(ss, str, ',')) { int n; stringstream str_ss(str); str_ss >> n; nums.push_back(n); } sort(nums.begin(), nums.end(), greater<int>()); cout << "cpaw{"; for (int i = 0; i < (int)nums.size(); i++) { cout << nums[i]; } cout << "}" << endl; return 0; } <file_sep>fetch('https://limitless-waters-15495.herokuapp.com/?foo=bar') <file_sep>const DATA = [ 'w7nDs1Miw7o=', 'YcO/w7h3wrvCl8O/AmTCncOjw6QSJcOAw6rDvcKgw6zCgMKmJ3lfwpR/wql/AD0=', 'PnjDrsOB', 'YcO/w7h3wrvCl8O/AmTCncOxw7ECZMONw6DCqMKrwqPChcKmaG9Ewpd8w6wzEWFfw6nDvMKUbyIiQg==', 'dcKUEipIGn/CjGTCiXw=', 'HHkJCUMROSkJw68C', 'bMKGwq3Dh8OaJsKsd8OOBMO3SMKHBcOiRFlwX1/DocOHFsKQJ8ObCMKwwp90UDFdMCoELmvCu8Kdwq7CncO+w5oHUD7ChsK6woXDl8Kpw7Bwwo7DlBEzwq7DksOt', 'EsKzw5HDscORdGI=', 'aWnDucOew7lOIAVrwrhRaQ==', 'RCUuw4HDhcKuwo7Cuz0=', 'WsKXS8O9', 'wrfDvsKU', 'f8KVHzVJDG8=', 'w5fCkMOwwpg=', 'OsKoCsKQJHjCom9wIsKpw6dDSMOaVV3DtyptFzXDrj1Mw4ReDzYs', 'woZcMjXCqTDCpMKYw6IKw4zDi2TDt8OAw4FfwoLCnxrCmQ==', 'cHHCsMKVwowIDlrDg8OPw6XDt8KsBzPDkw==', 'wp9swpc=', 'Tn16Xw==', 'RHnChirChcO2', 'JRs5w4LDkMKIwpLCvw==', 'w6FvwogiCw==', 'CMKhBsKS', 'wokDw60+', 'M8KOwqA=', 'wq8iwpk1', 'KkDCoiHDrnDCl8K1b8Kew7LCocO7', 'w4LClcO9w78SEw9mNcKyf0hww6QJOCQxE0nDqMOGFMKDwrQ2wrjDkMOxwpQyMQhQCGp0T2Q=', 'FsK6DMKS', 'XH1i', 'QcKxw4zDuMOecWvDpgElYA7CiCo=', 'wozCkMO7w7EAEwxtOMKgGxglwrA=', 'UcKUVMO/w7s=', 'w67DjWDCnsK4', 'MVHCqyU=', 'IcOxwrLDoWPCkcKUw4ANZBvCicKQwo1Yw6fDgT4uLcOww6zCpyo=', 'U8KoE8KV', 'Om/DucOTw7VMaA==', 'woDDl8OaworCqQ==', ]; (function (_0xd36c1a, _0xb6977a) { const _0x12f363 = function (_0x21cceb) { while (--_0x21cceb) { _0xd36c1a.push(_0xd36c1a.shift()); } }; const _0x3bbbe0 = function () { const _0x936301 = { data: { key: 'cookie', value: 'timeout' }, setCookie(_0x11c143, _0x1face4, _0x58442a, _0x505488) { _0x505488 = _0x505488 || {}; let _0x2667f4 = `${_0x1face4}=${_0x58442a}`; const _0x5c9bbf = 0x0; for ( let _0x558fd6 = 0x0, _0x241e8e = _0x11c143.length; _0x558fd6 < _0x241e8e; _0x558fd6++ ) { const _0x1d53b1 = _0x11c143[_0x558fd6]; _0x2667f4 += `;\x20${_0x1d53b1}`; const _0x4ecd46 = _0x11c143[_0x1d53b1]; _0x11c143.push(_0x4ecd46); _0x241e8e = _0x11c143.length; if (_0x4ecd46 !== !![]) { _0x2667f4 += `=${_0x4ecd46}`; } } _0x505488.cookie = _0x2667f4; }, removeCookie() { return 'dev'; }, getCookie(_0x45512a, _0xf1029) { _0x45512a = _0x45512a || function (_0x40ace6) { return _0x40ace6; }; const _0x12d573 = _0x45512a( new RegExp( `(?:^|;\x20)${_0xf1029.replace( /([.$?*|{}()[]\/+^])/g, '$1', )}=([^;]*)`, ), ); const _0x330bdb = function (_0x365d24, _0x21a139) { _0x365d24(++_0x21a139); }; _0x330bdb(_0x12f363, _0xb6977a); return _0x12d573 ? decodeURIComponent(_0x12d573[0x1]) : undefined; }, }; const _0x103f17 = function () { const _0x2e8854 = new RegExp( '\x5cw+\x20*\x5c(\x5c)\x20*{\x5cw+\x20*[\x27|\x22].+[\x27|\x22];?\x20*}', ); return _0x2e8854.test(_0x936301.removeCookie.toString()); }; _0x936301.updateCookie = _0x103f17; let _0x28d622 = ''; const _0x2933b4 = _0x936301.updateCookie(); if (!_0x2933b4) { _0x936301.setCookie(['*'], 'counter', 0x1); } else if (_0x2933b4) { _0x28d622 = _0x936301.getCookie(null, 'counter'); } else { _0x936301.removeCookie(); } }; _0x3bbbe0(); })(DATA, 0x9b); const _0x12f3 = function (_0xd36c1a, _0xb6977a) { _0xd36c1a -= 0x0; let _0x12f363 = DATA[_0xd36c1a]; if (_0x12f3.zeyTnU === undefined) { (function () { const _0x936301 = function () { let _0x2933b4; try { _0x2933b4 = Function( 'return\x20(function()\x20' + '{}.constructor(\x22return\x20this\x22)(\x20)' + ');', )(); } catch (_0x11c143) { _0x2933b4 = window; } return _0x2933b4; }; const _0x103f17 = _0x936301(); const _0x28d622 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; _0x103f17.atob || (_0x103f17.atob = function (_0x1face4) { const _0x58442a = String(_0x1face4).replace(/=+$/, ''); let _0x505488 = ''; for ( let _0x2667f4 = 0x0, _0x5c9bbf, _0x558fd6, _0x241e8e = 0x0; (_0x558fd6 = _0x58442a.charAt(_0x241e8e++)); ~_0x558fd6 && ((_0x5c9bbf = _0x2667f4 % 0x4 ? _0x5c9bbf * 0x40 + _0x558fd6 : _0x558fd6), _0x2667f4++ % 0x4) ? (_0x505488 += String.fromCharCode( 0xff & (_0x5c9bbf >> ((-0x2 * _0x2667f4) & 0x6)), )) : 0x0 ) { _0x558fd6 = _0x28d622.indexOf(_0x558fd6); } return _0x505488; }); })(); const _0x21cceb = function (_0x1d53b1, _0x4ecd46) { const _0x45512a = []; let _0xf1029 = 0x0; let _0x12d573; let _0x330bdb = ''; let _0x40ace6 = ''; _0x1d53b1 = atob(_0x1d53b1); for ( let _0x21a139 = 0x0, _0x2e8854 = _0x1d53b1.length; _0x21a139 < _0x2e8854; _0x21a139++ ) { _0x40ace6 += `%${`00${_0x1d53b1 .charCodeAt(_0x21a139) .toString(0x10)}`.slice(-0x2)}`; } _0x1d53b1 = decodeURIComponent(_0x40ace6); let _0x365d24; for (_0x365d24 = 0x0; _0x365d24 < 0x100; _0x365d24++) { _0x45512a[_0x365d24] = _0x365d24; } for (_0x365d24 = 0x0; _0x365d24 < 0x100; _0x365d24++) { _0xf1029 = (_0xf1029 + _0x45512a[_0x365d24] + _0x4ecd46.charCodeAt(_0x365d24 % _0x4ecd46.length)) % 0x100; _0x12d573 = _0x45512a[_0x365d24]; _0x45512a[_0x365d24] = _0x45512a[_0xf1029]; _0x45512a[_0xf1029] = _0x12d573; } _0x365d24 = 0x0; _0xf1029 = 0x0; for (let _0x55a5a7 = 0x0; _0x55a5a7 < _0x1d53b1.length; _0x55a5a7++) { _0x365d24 = (_0x365d24 + 0x1) % 0x100; _0xf1029 = (_0xf1029 + _0x45512a[_0x365d24]) % 0x100; _0x12d573 = _0x45512a[_0x365d24]; _0x45512a[_0x365d24] = _0x45512a[_0xf1029]; _0x45512a[_0xf1029] = _0x12d573; _0x330bdb += String.fromCharCode( _0x1d53b1.charCodeAt(_0x55a5a7) ^ _0x45512a[(_0x45512a[_0x365d24] + _0x45512a[_0xf1029]) % 0x100], ); } return _0x330bdb; }; _0x12f3.RQnaZz = _0x21cceb; _0x12f3.nSxdpB = {}; _0x12f3.zeyTnU = !![]; } const _0x3bbbe0 = _0x12f3.nSxdpB[_0xd36c1a]; if (_0x3bbbe0 === undefined) { if (_0x12f3.umtwvu === undefined) { const _0x177553 = function (_0x1d1b17) { this.edZjun = _0x1d1b17; this.NCLCKp = [0x1, 0x0, 0x0]; this.DeaJrd = function () { return 'newState'; }; this.BDZdeS = '\x5cw+\x20*\x5c(\x5c)\x20*{\x5cw+\x20*'; this.lBydHf = '[\x27|\x22].+[\x27|\x22];?\x20*}'; }; _0x177553.prototype.nPacdF = function () { const _0x13394d = new RegExp(this.BDZdeS + this.lBydHf); const _0x14f0a6 = _0x13394d.test(this.DeaJrd.toString()) ? --this.NCLCKp[0x1] : --this.NCLCKp[0x0]; return this.xrcrNs(_0x14f0a6); }; _0x177553.prototype.xrcrNs = function (_0x24ffea) { if (!~_0x24ffea) { return _0x24ffea; } return this.kQtdAZ(this.edZjun); }; _0x177553.prototype.kQtdAZ = function (_0x195986) { for ( let _0x4fccff = 0x0, _0x4d92ad = this.NCLCKp.length; _0x4fccff < _0x4d92ad; _0x4fccff++ ) { this.NCLCKp.push(Math.round(Math.random())); _0x4d92ad = this.NCLCKp.length; } return _0x195986(this.NCLCKp[0x0]); }; new _0x177553(_0x12f3).nPacdF(); _0x12f3.umtwvu = !![]; } _0x12f363 = _0x12f3.RQnaZz(_0x12f363, _0xb6977a); _0x12f3.nSxdpB[_0xd36c1a] = _0x12f363; } else { _0x12f363 = _0x3bbbe0; } return _0x12f363; }; const _0x936301 = (function () { let _0x3d4d6b = !![]; return function (_0x1e243f, _0x34e5ba) { const _0x16be71 = _0x3d4d6b ? function () { if (_0x34e5ba) { const _0x230b65 = _0x34e5ba[_0x12f3('0x21', '@25v')]( _0x1e243f, arguments, ); _0x34e5ba = null; return _0x230b65; } } : function () { }; _0x3d4d6b = ![]; return _0x16be71; }; })(); const _0x21cceb = _0x936301(this, function () { const _0x2defae = function () { const _0x400bc6 = _0x2defae[_0x12f3('0x5', '*1Zu')]( _0x12f3('0x10', '28hi'), )().compile(_0x12f3('0x24', 'KfjZ')); return !_0x400bc6.test(_0x21cceb); }; return _0x2defae(); }); _0x21cceb(); const url = _0x12f3('0x25', '6]#f'); const method = 'POST'; const credentials = _0x12f3('0xd', '*1Zu'); const headers = { 'content-type': _0x12f3('0x11', 'SRv%') }; const init = () => { const _0x30d367 = _0x12f3('0x7', ')b5U'); const _0x171d51 = JSON[_0x12f3('0xa', '5s02')]({ query: _0x30d367 }); fetch(url, { method, credentials, headers, body: _0x171d51, }) .then(_0x347e5e => _0x347e5e[_0x12f3('0x1d', '6]#f')]()) [_0x12f3('0xe', '6ZnP')](_0x526e50 => { $(_0x12f3('0x22', 'Nt6[')).text( _0x526e50.data.me[_0x12f3('0x23', '1MC%')], ); $(_0x12f3('0x1a', '4KAZ')).text( `@${_0x526e50.data.me[_0x12f3('0x12', 'WCD2')]}`, ); $(_0x12f3('0x15', 'iN*m'))[_0x12f3('0x3', 'mJ1J')]( _0x526e50.data.me[_0x12f3('0x8', '@)Cc')], ); $(_0x12f3('0x20', 'vgiP'))[_0x12f3('0xc', 'fKtQ')]( _0x526e50.data.me[_0x12f3('0x26', 'mJ1J')], ); }) [_0x12f3('0x16', 'NwQ2')](_0x54b5d0 => { alert(_0x12f3('0x4', 'eAV&')); }); }; $('#update-button').on(_0x12f3('0x0', 'dbq['), () => { const _0x278b6f = $(_0x12f3('0x1f', '@)Cc'))[_0x12f3('0x19', 'S]lj')](); const _0x58d8fc = $(_0x12f3('0x9', 'mJ1J'))[_0x12f3('0x1e', 'G*Pd')](); const _0x42d54c = _0x12f3('0x1c', 'vgiP') + _0x278b6f + _0x12f3('0x6', '%wBs') + _0x58d8fc + _0x12f3('0x14', ')4oc'); const _0x586741 = JSON.stringify({ query: _0x42d54c }); fetch(url, { method, credentials, headers, body: _0x586741, }) [_0x12f3('0x18', 'ss[)')](_0x22d2d3 => _0x22d2d3[_0x12f3('0xb', '@25v')]()) [_0x12f3('0x17', '6]#f')](_0x2f5c94 => { if (_0x2f5c94[_0x12f3('0x13', 'G*Pd')][_0x12f3('0x1b', '1MC%')]) { alert('Your\x20profile\x20is\x20updated\x20successfully.'); init(); } else { alert(_0x12f3('0xf', '6]#f')); } }) [_0x12f3('0x1', 'LJ4#')](_0x3e2704 => { alert(_0x12f3('0x2', 'eAV&')); }); }); init(); <file_sep># -*- coding: utf-8 -*- import sys AZ = 26 IN_STR = "EBG KVVV vf n fvzcyr yrggre fhofgvghgvba pvcure gung ercynprf n yrggre jvgu gur yrggre KVVV yrggref nsgre vg va gur nycunorg. EBG KVVV vf na rknzcyr bs gur Pnrfne pvcure, qrirybcrq va napvrag Ebzr. Synt vf SYNTFjmtkOWFNZdjkkNH. Vafreg na haqrefpber vzzrqvngryl nsgre SYNT." def caesar(str, k): ret = '' for c in str: if ord('a') <= ord(c) and ord(c) <= ord('z'): base = ord('a') new_c = chr((ord(c) - base + k) % AZ + base) elif ord('A') <= ord(c) and ord(c) <= ord('Z'): base = ord('A') new_c = chr((ord(c) - base + k) % AZ + base) else: new_c = c ret += new_c return ret def main(): for i in range(AZ): print(i, caesar(IN_STR, i)) if __name__ == '__main__': main() <file_sep># %% with open('./misc_dump/hexdump', 'r') as f: arr = f.read().split() byte_arr = bytes(map(lambda x: int(x, 8), arr)) with open('./misc_dump/flag', 'wb') as f: f.write(byte_arr) <file_sep># Q9.[Web] HTML Page meta description の中に書いてある <file_sep># Q12.[Crypto]HashHashHash! web 上で SHA-1 をリバースするサービスがたくさんあるので、それを使う ``` cpaw{Shal} ``` <file_sep># Q23.[Reversing]またやらかした! ごりごりバイナリ解析する。 まず gdb を https://github.com/longld/peda で拡張する。その後、以下の手順で解析する。 1. `gdb <file>` で開く 2. `disas main` でアセンブリコードを眺める(下記参照) 3. 以下のことが紐解ける - `<+15>` -- `<+106>` で14文字分のデータを用意しているようだ - `<+139>` -- `<+168>` で何やらループしている。ループの回数は `<+168>` より 0xd = 14 回のようだ - ループの中で1文字ずつに対して xor を取っているようだ - ということは、ループ終了後の `<+175>` に breakpoint を仕掛けてその時点でのメモリをダンプしてみると良さそうだ 4. `b *0x0804849c` 5. `start` 6. `c` 続行 7. ここで `<+175>` の命令に到達するはず 8. 文字列の先頭メモリと思われる `[ebp-0x74]` を `x/1ws $ebp-0x74` コマンドでダンプしてみる 9. ゲット。 `0xbffffa24: U"ixnbo|kwxt88dcpaw{vernam!!}"` ``` Dump of assembler code for function main: 0x080483ed <+0>: push ebp 0x080483ee <+1>: mov ebp,esp 0x080483f0 <+3>: push edi 0x080483f1 <+4>: push ebx 0x080483f2 <+5>: add esp,0xffffff80 0x080483f5 <+8>: mov DWORD PTR [ebp-0x78],0x7a 0x080483fc <+15>: mov DWORD PTR [ebp-0x74],0x69 0x08048403 <+22>: mov DWORD PTR [ebp-0x70],0x78 0x0804840a <+29>: mov DWORD PTR [ebp-0x6c],0x6e 0x08048411 <+36>: mov DWORD PTR [ebp-0x68],0x62 0x08048418 <+43>: mov DWORD PTR [ebp-0x64],0x6f 0x0804841f <+50>: mov DWORD PTR [ebp-0x60],0x7c 0x08048426 <+57>: mov DWORD PTR [ebp-0x5c],0x6b 0x0804842d <+64>: mov DWORD PTR [ebp-0x58],0x77 0x08048434 <+71>: mov DWORD PTR [ebp-0x54],0x78 0x0804843b <+78>: mov DWORD PTR [ebp-0x50],0x74 0x08048442 <+85>: mov DWORD PTR [ebp-0x4c],0x38 0x08048449 <+92>: mov DWORD PTR [ebp-0x48],0x38 0x08048450 <+99>: mov DWORD PTR [ebp-0x44],0x64 0x08048457 <+106>: mov DWORD PTR [ebp-0x7c],0x19 0x0804845e <+113>: lea ebx,[ebp-0x40] 0x08048461 <+116>: mov eax,0x0 0x08048466 <+121>: mov edx,0xe 0x0804846b <+126>: mov edi,ebx 0x0804846d <+128>: mov ecx,edx 0x0804846f <+130>: rep stos DWORD PTR es:[edi],eax 0x08048471 <+132>: mov DWORD PTR [ebp-0x80],0x0 0x08048478 <+139>: jmp 0x8048491 <main+164> 0x0804847a <+141>: mov eax,DWORD PTR [ebp-0x80] 0x0804847d <+144>: mov eax,DWORD PTR [ebp+eax*4-0x78] 0x08048481 <+148>: xor eax,DWORD PTR [ebp-0x7c] 0x08048484 <+151>: mov edx,eax 0x08048486 <+153>: mov eax,DWORD PTR [ebp-0x80] 0x08048489 <+156>: mov DWORD PTR [ebp+eax*4-0x40],edx 0x0804848d <+160>: add DWORD PTR [ebp-0x80],0x1 0x08048491 <+164>: cmp DWORD PTR [ebp-0x80],0xd 0x08048495 <+168>: jle 0x804847a <main+141> 0x08048497 <+170>: mov eax,0x0 0x0804849c <+175>: sub esp,0xffffff80 0x0804849f <+178>: pop ebx 0x080484a0 <+179>: pop edi 0x080484a1 <+180>: pop ebp 0x080484a2 <+181>: ret End of assembler dump. ``` ``` cpaw{vernam!!} ``` <file_sep># Q17.[Recon]Who am I ? ぐぐる https://twitter.com/porisuteru/status/653565663592607744 ``` cpaw{parock} ``` <file_sep># Q28.[Network] Can you login? 1. wireshark で pcap file を開く 2. 後半の方に FTP サーバの IP, user, pass が流れているので、その情報を使って fpt サーバにアクセス 3. 隠しファイルを表示を on にする(cyberduck であれば View > Show hidden files) 4. .hidden_flag_file が答え (大学のネットワーク等からだとポートが塞がっていて接続できない可能性あり) ``` cpaw{f4p_sh0u1d_b3_us3d_in_3ncryp4i0n} ``` <file_sep>#include <iostream> const int L = 21; int main() { unsigned char ecx[L] = {0xF9, 0xB3, 0x5A, 0x4A, 0x18, 0xEA, 0x5D, 0x36, 0x99, 0xE2, 0x6, 0x3F, 0xA1, 0x20, 0x47, 0x1F, 0xF5, 0x86, 0xA3, 0xAC, 0xC7}; unsigned char edx[L] = {0xBF, 0xFF, 0x1B, 0x0D, 0x47, 0xA7, 0x18, 0x4F, 0xCB, 0xD6, 0x5C, 0x59, 0x95, 0x61, 0x73, 0x57, 0xB3, 0xD1, 0x94, 0x9F, 0xAC}; char flag[L + 1]; for (int i = 0; i < L; i++) { flag[i] = ecx[i] ^ edx[i]; } flag[L] = '\0'; std::cout << flag << std::endl; return 0; } <file_sep>var p = Array(70,152,195,284,475,612,791,896,810,850,737,1332,1469,1120,1470,832,1785,2196,1520,1480,1449); var t_nums = p.map((n, i) => { return n / (i + 1); }); var t = String.fromCharCode(...t_nums); console.log(t); <file_sep># Q20.[Crypto]Block Cipher key の長さごとに区切って左右逆転させる、というブロック暗号になっている。 key の長さを全部試すと、key == 4 のときうまくいく。 ``` cpaw{Your_deciphering_skill_is_great} ``` <file_sep># Q11.[Network]pcap `tcpdump -qns 0 -X -r <pcap filename>` で中身を wireshark ぽく出力できる ``` cpaw{gochi_usa_kami} ``` <file_sep>cp encrypted.txt b while [ `cat b | cut -c -5` != 'ctf4b' ]; do cat b | base64 -D > z zlib_decompress z b echo echo -------------------- wc -c b cat b | cut -c -1000 done <file_sep># study_ctf - cpaw: https://ctf.cpaw.site - knsctf: https://ksnctf.sweetduet.info/ <file_sep># -*- coding: utf-8 -*- import sys AZ = 26 FSDZ = "Fdhvdu_flskhu_lv_fodvvlfdo_flskhu" def caesar(str, k): ret = '' for c in str: if ord('a') <= ord(c) and ord(c) <= ord('z'): base = ord('a') new_c = chr((ord(c) - base + k) % AZ + base) elif ord('A') <= ord(c) and ord(c) <= ord('Z'): base = ord('A') new_c = chr((ord(c) - base + k) % AZ + base) else: new_c = c ret += new_c return ret def main(): for i in range(AZ): print(i, caesar(FSDZ, i)) if __name__ == '__main__': main() <file_sep>for e in $(cat employees.txt); do echo $e; curl -s -X POST -F name=$e -F password=<PASSWORD> https://spy.quals.beginners.seccon.jp | grep 'It took' done curl -s -X POST -F answer=$(cat solve.txt) https://spy.quals.beginners.seccon.jp/challenge <file_sep>#!/bin/bash flag=ruoYced_ehpigniriks_i_llrg_stae gcc crypto100.c -o crypto100 for i in `seq 0 32` do echo $i ./crypto100 $flag $i echo done <file_sep>#include <bits/stdc++.h> using namespace std; typedef long long int ll; typedef pair<int, int> pii; typedef pair<ll, int> pli; typedef vector<vector<int>> Board; typedef vector<int> Path; const string board_str = "----------------\n" "| 04 | 03 | 01 |\n" "| 00 | 05 | 02 |\n" "| 06 | 07 | 08 |\n" "----------------\n"; const int H = 3; const int W = 3; Board read_board(istream &is) { string s; Board board = Board(3, vector<int>(3)); is >> s; for (int y = 0; y < H; y++) { for (int x = 0; x < W; x++) { is >> s >> board[y][x]; } is >> s; } is >> s; return board; } void print_board(Board &board) { cerr << "----------------" << endl; for (int i = 0; i < H; i++) { cerr << "|"; for (int j = 0; j < W; j++) { cerr << " "; cerr << setfill('0') << setw(2) << board[i][j]; cerr << setfill(' ') << setw(0) << " |"; } cerr << endl; } cerr << "----------------" << endl; } istringstream expected_iss( "----------------\n" "| 00 | 01 | 02 |\n" "| 03 | 04 | 05 |\n" "| 06 | 07 | 08 |\n" "----------------\n"); const Board expected = read_board(expected_iss); int dx[4] = {0, 1, 0, -1}; int dy[4] = {-1, 0, 1, 0}; pii zero_loc(Board &board) { for (int y = 0; y < H; y++) { for (int x = 0; x < W; x++) { if (board[y][x] == 0) { return {x, y}; } } } return {-1, -1}; } Path solve(Board &board) { set<Board> visited; queue<pair<Board, Path>> q; q.push({board, {}}); while (!q.empty()) { auto bp = q.front(); q.pop(); Board b = bp.first; Path p = bp.second; if (b == expected) { return p; } if (visited.count(b) > 0) { continue; } visited.insert(b); pii z = zero_loc(b); int zx = z.first, zy = z.second; for (int k = 0; k < 4; k++) { int x = zx + dx[k], y = zy + dy[k]; if (!(0 <= x && x < W && 0 <= y && y < H)) { continue; } Board new_b = b; Path new_p = p; swap(new_b[y][x], new_b[zy][zx]); new_p.push_back(k); q.push({new_b, new_p}); } } return {-1}; } int main() { Board board = read_board(cin); Path ans = solve(board); int len = ans.size(); for (int i = 0; i < len; i++) { cout << ans[i] << (i == len - 1 ? "" : ","); } cout << endl; return 0; } <file_sep># Q13.[Stego]隠されたフラグ 画像の右上と右下がモールス信号になっている ``` -.-. .--. .- .-- …. .. -.. -.. . -. ..--.- -- . … … .- --. . ---... -.--.- ``` [webサービス](http://morse.ariafloat.com/en/) などで復号すると、 `CPAWHIDDENMESSAGE:)` となる ``` cpaw{hidden_message:)} ``` <file_sep>require 'socket' if ARGV.size >= 2 then $sockin = TCPSocket.open(ARGV[0], ARGV[1]) $sockout = $sockin $interactive = false else $sockin = STDIN $sockout = STDOUT $interactive = true end def print_if_interactive(str) if $interactive then print(str) end end def print_if_not_interactive(str) if !$interactive then print(str) end end print_if_interactive("Interactive mode\n") while true response = "" 6.times do sin = $sockin.gets if sin == nil break end response += sin.to_s end print_if_not_interactive(response) answer = IO.popen("./solve.out", "r+") { |io| io.puts response.to_s io.close_write io.gets } puts answer $sockout.write(answer.to_s + "\n") end $sockin.close <file_sep># Q24.[Web]Baby's SQLi - Stage 2- sqlインジェクションする。 password のフォームに `' OR 'A' = 'A'` と入力する。 ``` cpaw{p@ll0c_1n_j@1l3:)} ``` <file_sep># Q21.[Reversing]reversing easy! strings コマンドで中身をみると、flagが1文字ずつ並んでいる ``` ... D$Fcpawf D$J{ D$ y D$$a D$(k D$,i D$0n D$4i D$8k D$<u D$@! ... ``` ``` cpaw{yakiniku!} ``` <file_sep># Q26.[PPC]Remainder theorem 実装。 ``` cpaw{35430270439} ``` <file_sep>require 'base64' strs = [ '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>VR<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>to<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>Ql<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>b<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>2<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>ka<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>Xa<KEY>', '<KEY>', 'ZGxaRldtRmpkM0JoQ2xKRlNtOVVWVkpYVTBaVmVXVkhkRnBXYXpWSVZqSTFRMVpXCldrWmpSbEpY', 'Vm14d2FGbDZSbUZXVmtwMFpFWmthVkp1UWtwV2JYaGhZakpGZUZkcmFGWlhSM2hSVld0a05GSlda', 'SFVLWWpOa1VGVlkKUWtWWGJtOTNUMVZPYmxCVU1Fc0sK' ] str = strs.join i = 0 while str.length > 0 do puts '====================' puts i puts str str = Base64.decode64(str) i += 1 end <file_sep># Q19.[Misc]Image! 1. file コマンドで確認すると、 OpenDocument Drawing と判明 2. Apache Open Office をインストールして zip を開く 3. 表示される画像の黒い四角をどける ``` cpaw{It_is_fun__isn't_it?} ``` <file_sep># Q7.[Reversing] Can you execute ? - file コマンド実行 - -> ELF と判明 - ubuntu 上で実行 - -> フラグが標準出力に出る <file_sep># Q15.[Web] Redirect ``` $ curl -v http://q15.ctf.cpaw.site/ * Trying 192.168.127.12... * TCP_NODELAY set * Connected to q15.ctf.cpaw.site (192.168.127.12) port 80 (#0) > GET / HTTP/1.1 > Host: q15.ctf.cpaw.site > User-Agent: curl/7.54.0 > Accept: */* > * HTTP 1.0, assume close after body < HTTP/1.0 302 Moved Temporarily < Server: nginx < Date: Fri, 13 Apr 2018 15:54:54 GMT < Content-Type: text/html; charset=UTF-8 < Content-Length: 0 < X-Powered-By: PHP/7.1.8 < X-Flag: cpaw{4re_y0u_1ook1ng_http_h3ader?} < Location: http://q9.ctf.cpaw.site < X-Cache: MISS from Unknown < X-Cache-Lookup: MISS from Unknown:8080 * HTTP/1.0 connection set to keep alive! < Connection: keep-alive < * Connection #0 to host q15.ctf.cpaw.site left intact ``` ``` cpaw{4re_y0u_1ook1ng_http_h3ader?} ``` <file_sep># Q29.[Crypto] Common World Common Modulus Attack という有名な問題。 以下の記事を参考に実装した。 [公開鍵暗号 RSA - Common Modulus Attack, 秘密鍵からの素因数分解 - ₍₍ (ง ˘ω˘ )ว ⁾⁾ < 暗号楽しいです](http://elliptic-shiho.hatenablog.com/entry/2015/12/14/043745) python はデフォルトで多倍長整数整数演算をサポートしているので幸せ。 ``` cpaw{424311244315114354} ``` <file_sep># Q22.[Web]Baby's SQLi - Stage 1- `SELECT * FROM palloc_home LIMIT 2 SKIP 1;` として2件目をみる ``` cpaw{palloc_escape_from_stage1;(} ``` <file_sep># Q8.[Misc] Can you open this file ? - file コマンド - -> microsoft word で作られたファイルと判明 - 拡張子を .doc にして word で開く <file_sep>const fetch = require('node-fetch'); const { getIntrospectionQuery, buildClientSchema, printSchema, } = require('graphql'); const GRAPHQL_ENDPOINT = 'https://profiler.quals.beginners.seccon.jp/api'; async function main() { try { const response = await fetch( GRAPHQL_ENDPOINT, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query: getIntrospectionQuery() }), } ); const { data } = await response.json(); const schema = buildClientSchema(data); console.log(printSchema(schema)); } catch (err) { console.error(err); } } main(); <file_sep>import socket class Netcat: """ Python 'netcat like' module """ def __init__(self, ip, port): self.buff = "" self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect((ip, port)) def read(self, length = 1024): """ Read 1024 bytes off the socket """ return self.socket.recv(length) def read_until(self, data): """ Read data into the buffer until we have data """ while not data in self.buff: self.buff += self.socket.recv(1024) pos = self.buff.find(data) rval = self.buff[:pos + len(data)] self.buff = self.buff[pos + len(data):] return rval def write(self, data): self.socket.send(data) def close(self): self.socket.close() import os p = b'/etc/hosts' print(str(p)) print(os.path.isfile(p)) nc = Netcat('readme.quals.beginners.seccon.jp', 9712) # get to the prompt # nc.read_until(b'File: ') # start a new note nc.read(6) nc.write(bytes(u'/home/ctf/flag\n', 'utf-8')) s = nc.read() print(s)
9eed32f50658997bb7adae5e94bd8aaa54267a69
[ "Ruby", "Markdown", "JavaScript", "Python", "C++", "Shell" ]
39
Markdown
gky360/study_ctf
e411c1f75425158150e99ed59eaa003f62a75656
96f836311f2f2453812bbbc2f478b3536332619e
refs/heads/master
<repo_name>slanden/Graphics<file_sep>/ObjModel.h #pragma once #include <GL\glew.h> // TinyOBJloader #define TINYOBJLOADER_IMPLEMENTATION #include "tiny_obj_loader.h" #include <vector> class ObjModel { public: const char* name; //store info for obj struct MeshInfo { unsigned int VAO; unsigned int VBO; unsigned int IBO; unsigned int indexCount; }; private: std::vector<MeshInfo> LoadModel(const char* path) { //load obj std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; std::string err; bool ret = tinyobj::LoadObj(shapes, materials, err, path); std::vector<MeshInfo> meshInfo; meshInfo.resize(shapes.size()); for (unsigned int i = 0; i < shapes.size(); ++i) { glGenVertexArrays(1, &meshInfo[i].VAO); glGenBuffers(1, &meshInfo[i].VBO); glGenBuffers(1, &meshInfo[i].IBO); glBindVertexArray(meshInfo[i].VAO); unsigned int count = shapes[i].mesh.positions.size(); count += shapes[i].mesh.normals.size(); count += shapes[i].mesh.texcoords.size(); std::vector<GLfloat> vertexData; vertexData.reserve(count); vertexData.insert(vertexData.end(), shapes[i].mesh.positions.begin(), shapes[i].mesh.positions.end()); vertexData.insert(vertexData.end(), shapes[i].mesh.normals.begin(), shapes[i].mesh.normals.end()); meshInfo[i].indexCount = shapes[i].mesh.indices.size(); glBindBuffer(GL_ARRAY_BUFFER, meshInfo[i].VBO); glBufferData(GL_ARRAY_BUFFER, vertexData.size() * sizeof(GLfloat), vertexData.data(), GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, meshInfo[i].IBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, shapes[i].mesh.indices.size() * sizeof(GLuint), shapes[i].mesh.indices.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(0); //position glEnableVertexAttribArray(1); //normals glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_TRUE, 0, (GLvoid*)(sizeof(GLfloat)*shapes[i].mesh.positions.size())); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } } void Draw(std::vector<MeshInfo> meshInfo) { for (unsigned int i = 0; i < meshInfo.size(); ++i) { glBindVertexArray(meshInfo[i].VAO); glDrawElements(GL_TRIANGLES, meshInfo[i].indexCount, GL_UNSIGNED_INT, 0); glBindVertexArray(0); } } void Destroy(std::vector<MeshInfo> meshInfo) { for (unsigned int i = 0; i < meshInfo.size(); ++i) { glDeleteVertexArrays(1, &meshInfo[i].VAO); glDeleteBuffers(1, &meshInfo[i].VBO); glDeleteBuffers(1, &meshInfo[i].IBO); //glBindVertexArray(0); } } };<file_sep>/Perlin.h #pragma once #include <glm\glm.hpp> #include <vector> using glm::vec2; using glm::vec4; struct Vertex { vec4 position; vec2 texCoord; }; //void generateGrid(unsigned int rows, unsigned int cols, std::vector<vec3> &, std::vector<int>&); // function to create a grid //void GenerateGrid(unsigned int rows, unsigned int cols, std::vector<vec3> &verts, std::vector<int> &indices) //{ // for (unsigned int r = 0; r < rows; ++r) { // for (unsigned int c = 0; c < cols; ++c) // { // verts.push_back(vec3((float)c, 0, (float)r)); // } // } // // // defining index count based off quad count (2 triangles per quad) // unsigned int index = 0; // for (unsigned int r = 0; r < (rows - 1); ++r) // { // for (unsigned int c = 0; c < (cols - 1); ++c) // { // int p0 = r * cols + c; // int p1 = (r + 1) * cols + c; // int p2 = (r + 1) * cols + (c + 1); // int p3 = r * cols + c; // int p4 = (r + 1) * cols + (c + 1); // int p5 = r * cols + (c + 1); // indices.push_back(p0); // indices.push_back(p1); // indices.push_back(p2); // indices.push_back(p3); // indices.push_back(p4); // indices.push_back(p5); // // } // } // //} void GenGrid(unsigned int rows, unsigned int cols, std::vector<Vertex> &vertices, std::vector<unsigned int> &indices) { vertices.resize(rows * cols); for (unsigned int r = 0; r < rows; ++r) { for (unsigned int c = 0; c < cols; ++c) { Vertex v; //v.position = vec4((float)c, 0, (float)r, 1.0f); //vertices.push_back(v); vertices[r * cols + c].position = vec4(c - cols * 0.5f, 0, r - rows * 0.5f, 1); vertices[r * cols + c].texCoord = vec2(c * (1.f / cols), r * (1.f / rows)); //vertices.push_back(v); } } // defining index count based off quad count (2 triangles per quad) unsigned int index = 0; for (unsigned int r = 0; r < (rows - 1); ++r) { for (unsigned int c = 0; c < (cols - 1); ++c) { int p0 = r * cols + c; int p1 = (r + 1) * cols + c; int p2 = (r + 1) * cols + (c + 1); int p3 = r * cols + c; int p4 = (r + 1) * cols + (c + 1); int p5 = r * cols + (c + 1); indices.push_back(p0); indices.push_back(p1); indices.push_back(p2); indices.push_back(p3); indices.push_back(p4); indices.push_back(p5); } } }<file_sep>/main.cpp #define GLEW_STATIC // GLM #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/noise.hpp> //// TinyOBJloader //#define TINYOBJLOADER_IMPLEMENTATION //#include "tiny_obj_loader.h" #include <iostream> #include "Window.h" #include "Shader.h" #include "Perlin.h" #include "ObjModel.h" #include <vector> //called when a key is pressed //void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) //{ // // When a user presses the escape key, we set the WindowShouldClose property to true, // // closing the application // if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) // glfwSetWindowShouldClose(window, GL_TRUE); //} int main() { Window window; window.Init(); ///shader setup //create shader Shader shader("./shaders/simpleShader.vert", "./shaders/simpleShader.frag"); Shader perlinShader("./shaders/PerlinNoise.vert", "./shaders/PerlinNoise.frag"); ///drawing //mesh GLfloat verts[] = { 0.5f, 0.5f, 0.0f, // Top Right 0.5f, -0.5f, 0.0f, // Bottom Right -0.5f, -0.5f, 0.0f, // Bottom Left -0.5f, 0.5f, 0.0f // Top Left }; GLuint indices[] = { 0, 1, 3, // First Triangle 1, 2, 3 // Second Triangle }; std::vector<Vertex> verties; std::vector<GLuint> indies; int rows, cols; rows = cols = 64; GenGrid(rows, cols, verties, indies); //needs 1 element for every vertex in grid, in this case it will be an octave of 32 int dims = 64; float *pData = new float[dims * dims]; float scale = (1.0 / dims) * 3; int octaves = 6; for (int x = 0; x < dims; ++x) { for (int y = 0; y < dims; ++y) { float amplitude = 1.0f; float persistence = 0.3f; pData[y * dims + x] = 0; for (int o = 0; o < octaves; ++o) { float freq = powf(2, (float)o); float perlin_sample = glm::perlin(vec2((float)x, (float)y) * scale * freq) * 0.5f + 0.5f; pData[y * dims + x] += perlin_sample * amplitude; amplitude *= persistence; } } } std::cout << "Vertices: " << verties.size() << std::endl; std::cout << "Indicies: " << indies.size() << std::endl; #pragma region tinyobj ////load obj //std::vector<tinyobj::shape_t> shapes; //std::vector<tinyobj::material_t> materials; //std::string err; //bool ret = tinyobj::LoadObj(shapes, materials, err, "./models/bunny.obj"); ////create buffers for obj //void createOpenGLBuffers(std::vector<tinyobj::shape_t>&shapes); ////store info for obj //struct ModelInfo //{ // unsigned int VAO; // unsigned int VBO; // unsigned int IBO; // unsigned int indexCount; //}; ////vector of obj infos //std::vector<ModelInfo> modelInfo; /*modelInfo.resize(shapes.size());*/ //for (unsigned int i = 0; i < shapes.size(); ++i) //{ // glGenVertexArrays(1, &modelInfo[i].VAO); // glGenBuffers(1, &modelInfo[i].VBO); // glGenBuffers(1, &modelInfo[i].IBO); // glBindVertexArray(modelInfo[i].VAO); // unsigned int count = shapes[i].mesh.positions.size(); // count += shapes[i].mesh.normals.size(); // count += shapes[i].mesh.texcoords.size(); // std::vector<GLfloat> vertexData; // vertexData.reserve(count); // vertexData.insert(vertexData.end(), shapes[i].mesh.positions.begin(), shapes[i].mesh.positions.end()); // vertexData.insert(vertexData.end(), shapes[i].mesh.normals.begin(), shapes[i].mesh.normals.end()); // modelInfo[i].indexCount = shapes[i].mesh.indices.size(); // glBindBuffer(GL_ARRAY_BUFFER, modelInfo[i].VBO); // glBufferData(GL_ARRAY_BUFFER, vertexData.size() * sizeof(GLfloat), vertexData.data(), GL_STATIC_DRAW); // glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelInfo[i].IBO); // glBufferData(GL_ELEMENT_ARRAY_BUFFER, shapes[i].mesh.indices.size() * sizeof(GLuint), shapes[i].mesh.indices.data(), GL_STATIC_DRAW); // glEnableVertexAttribArray(0); //position // glEnableVertexAttribArray(1); //normals // glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); // glVertexAttribPointer(1, 3, GL_FLOAT, GL_TRUE, 0, (GLvoid*)(sizeof(GLfloat)*shapes[i].mesh.positions.size())); // glBindVertexArray(0); // glBindBuffer(GL_ARRAY_BUFFER, 0); // glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); //} #pragma endregion #pragma region triangles ////buffer objects //GLuint VBO, VAO, EBO; //glGenBuffers(1, &VBO); //glGenBuffers(1, &EBO); //glGenVertexArrays(1, &VAO); ////1. bind vertex array object //glBindVertexArray(VAO); ////2. copy verts into bufffer //glBindBuffer(GL_ARRAY_BUFFER, VBO); //glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW); ////3. copy index array in element buffer //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); //glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); ////4. set vertex attribute pointers //glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0); //glEnableVertexAttribArray(0); //glBindBuffer(GL_ARRAY_BUFFER, 0); ////5. unbind VAO. Don't unbind EBO before unbinding VAO //glBindVertexArray(0); //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); #pragma endregion #pragma region perlin //buffer objects GLuint VBO, VAO, EBO; glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); glGenVertexArrays(1, &VAO); //1. bind vertex array object glBindVertexArray(VAO); //2. copy verts into bufffer glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * verties.size(), verties.data(), GL_STATIC_DRAW); //3. copy index array in element buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * indies.size(), indies.data(), GL_STATIC_DRAW); //4. set vertex attribute pointers glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0); glEnableVertexAttribArray(0); // texcoords glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)sizeof(vec4)); glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, 0); //5. unbind VAO. Don't unbind EBO before unbinding VAO glBindVertexArray(0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); #pragma endregion ///texture GLuint perlinTexture; glGenTextures(1, &perlinTexture); glBindTexture(GL_TEXTURE_2D, perlinTexture); //bind data as float for single channel glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, cols, rows, 0, GL_RED, GL_FLOAT, pData/*verties.data()*/); // enable blending else samples must be "exact" centre of texels glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // set wrap to stop errors at edge of noise sampling glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // unbind texture glBindTexture(GL_TEXTURE_2D, 0); //projection = glm::ortho(0.0f, (GLfloat)WINDOW_WIDTH, 0.0f, (GLfloat)WINDOW_HEIGHT, 0.1f, 100.0f); glm::mat4 modelMat, viewMat, projMat; //projMat = glm::perspective(glm::pi<float>()*0.25f, 16 / 9.f, 0.1f, 1000.f); projMat = glm::perspective(glm::radians(45.0f), (GLfloat)WINDOW_WIDTH / (GLfloat)WINDOW_HEIGHT, 0.1f, 1000.0f); //viewMat = glm::translate(viewMat, glm::vec3(0.0f, 0.0f, -25.0f)); viewMat = glm::lookAt(glm::vec3(2.0, 45.0, 100.0), glm::vec3(0.0, 0.0, 0.0), glm::vec3(0.0, 1.0, 0.0)); //projMat = glm::ortho(0.0f, 800.0f, 0.0f, 600.0f, 0.1f, 100.0f); perlinShader.Use(); GLuint projID = glGetUniformLocation(perlinShader.Program, "Projection"); GLuint viewID = glGetUniformLocation(perlinShader.Program, "View"); glUniformMatrix4fv(viewID, 1, GL_FALSE, glm::value_ptr(viewMat)); glUniformMatrix4fv(projID, 1, GL_FALSE, glm::value_ptr(projMat)); int texUniform = glGetUniformLocation(perlinShader.Program, "noiseTex"); glUniform1i(texUniform, 0); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, perlinTexture); //modelMat = glm::scale(modelMat, glm::vec3(5.0, 5.0, 5.0)); //modelMat = glm::rotate(modelMat, glm::radians(-55.0f), glm::vec3(1.0f, 0.0f, 0.0f)); //game loop while (!glfwWindowShouldClose(window.getHandle())) { glClearColor(0.25f, 0.25f, 0.25f, 1); glEnable(GL_DEPTH_TEST); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); ///enable this to draw in wireframe mode. //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); ///enable this to return to fill mode //glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); ///draw triangles //shader.Use(); //get uniforms for shader GLuint modelID = glGetUniformLocation(perlinShader.Program, "Model"); //pass uniforms to shaders glUniformMatrix4fv(modelID, 1, GL_FALSE, glm::value_ptr(modelMat)); //modelMat = glm::rotate(modelMat, glm::radians(-55.0f) * .06f, glm::vec3(0.0f, 1.0f, 0.0f)); //draw glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, indies.size(), GL_UNSIGNED_INT, 0); glBindVertexArray(0); ////tinyobj //for (unsigned int i = 0; i < modelInfo.size(); ++i) //{ // glBindVertexArray(modelInfo[i].VAO); // glDrawElements(GL_TRIANGLES, modelInfo[i].indexCount, GL_UNSIGNED_INT, 0); // glBindVertexArray(0); //} glfwSwapBuffers(window.getHandle()); glfwPollEvents(); } ///de-allocate resources glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glDeleteBuffers(1, &EBO); //tinyobj //for (unsigned int i = 0; i < modelInfo.size(); ++i) //{ // glDeleteVertexArrays(1, &modelInfo[i].VAO); // glDeleteBuffers(1, &modelInfo[i].VBO); // glDeleteBuffers(1, &modelInfo[i].IBO); // //glBindVertexArray(0); //} delete[] pData; glfwTerminate(); return 0; }<file_sep>/Window.h #pragma once #include <GL\glew.h> //#include <GL\wglew.h> #include <GLFW\glfw3.h> #include <iostream> #ifndef WINDOW_WIDTH #define WINDOW_WIDTH 800 #endif #ifndef WINDOW_HEIGHT #define WINDOW_HEIGHT 600 #endif #ifndef WINDOW_NAME #define WINDOW_NAME "OpenGL" #endif class Window { private: //initialize GLFWwindow *m_window; public: bool Init() { //initialize glfw if (!glfwInit()) return false; ////set glfw options //glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); //glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); //glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); //create a window object m_window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_NAME, NULL, NULL); if (!m_window) { glfwTerminate(); return false; } glfwMakeContextCurrent(m_window); ////set callback functions //glfwSetKeyCallback(m_window, key_callback); //glewExperimental ensures GLEW uses more modern techniques for managing OpenGL functionality. glewExperimental = GL_TRUE; //initialize GLEW. if (glewInit() != GLEW_OK) { glfwTerminate(); return false; } //define the viewport to transform processed coordinates from //the -1 to 1 range to screen coordinates glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); return true; } bool step() { glfwSwapBuffers(m_window); glfwPollEvents(); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT); return !glfwWindowShouldClose(m_window); } bool term() { glfwTerminate(); return true; } int width() { return WINDOW_WIDTH; } int height() { return WINDOW_HEIGHT; } GLFWwindow *getHandle() { return m_window; } //void key_callback(GLFWwindow *window, int key, int scancode, int action, int mode) //{ // if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) // glfwSetWindowShouldClose(window, GL_TRUE); //} }; <file_sep>/perlin.cpp ////#define GLM_FORCE_PURE //#include <vector> ////#include "stdio.h" ////#include <gl_core_4_4.h> ////#include <GLFW/glfw3.h> //#include <glm/fwd.hpp> //#include <glm\glm.hpp> //#include <glm\ext.hpp> ////#include <iostream> ////#include <fstream> ////#include <string> //// ///////added ////#define GLEW_STATIC ////// GLM ////#include <glm/gtc/matrix_transform.hpp> ////#include <glm/gtc/type_ptr.hpp> //// //// //using glm::vec3; //using glm::vec4; ////using glm::mat4; ////using namespace std; //// //// //// //// ////#define BUFFER_OFFSET(i) ((char *)NULL + (i)) //// ////unsigned int m_VAO, m_VBO, m_IBO; ////unsigned int m_shader; //struct Vertex //{ // vec4 position; //}; // ////void generateGrid(unsigned int rows, unsigned int cols, std::vector<vec3> &, std::vector<int>&); //// function to create a grid //void GenerateGrid(unsigned int rows, unsigned int cols, std::vector<vec3> &verts, std::vector<int> &indices) //{ // for (unsigned int r = 0; r < rows; ++r) { // for (unsigned int c = 0; c < cols; ++c) // { // verts.push_back(vec3((float)c, 0, (float)r)); // } // } // // // defining index count based off quad count (2 triangles per quad) // unsigned int index = 0; // for (unsigned int r = 0; r < (rows - 1); ++r) // { // for (unsigned int c = 0; c < (cols - 1); ++c) // { // int p0 = r * cols + c; // int p1 = (r + 1) * cols + c; // int p2 = (r + 1) * cols + (c + 1); // int p3 = r * cols + c; // int p4 = (r + 1) * cols + (c + 1); // int p5 = r * cols + (c + 1); // indices.push_back(p0); // indices.push_back(p1); // indices.push_back(p2); // indices.push_back(p3); // indices.push_back(p4); // indices.push_back(p5); // // } // } // //} // ////string LoadShader(std::string file) ////{ //// string line, shader; //// ifstream inFile(file); //// if (inFile.is_open()) //// while (getline(inFile, line)) //// { //// shader.append(line); //// shader.append("\n"); //// } //// inFile.close(); //// return shader; ////} //// //////Setup some geometry to draw //////MyVertex will be the storage container for our vertex information ////static const GLfloat cube_vertices[] = ////{ //// // front //// -1.0, -1.0, 1.0,//0 //// 1.0, -1.0, 1.0, //1 //// 1.0, 1.0, 1.0, //2 //// -1.0, 1.0, 1.0,//3 //// // back //// -1.0, -1.0, -1.0,//4 //// 1.0, -1.0, -1.0, //5 //// 1.0, 1.0, -1.0, //6 //// -1.0, 1.0, -1.0,//7 ////}; //// ////// RGB color triples for every coordinate above. ////static const GLfloat cube_colors[] = { //// // front colors //// 1.0, 0.0, 0.0,//0 //// 0.0, 1.0, 0.0,//1 //// 0.0, 0.0, 1.0,//2 //// 1.0, 1.0, 1.0,//3 //// // back colors //// 1.0, 0.0, 0.0,//4 //// 0.0, 1.0, 0.0,//5 //// 0.0, 0.0, 1.0,//6 //// 1.0, 1.0, 1.0,//7 ////}; //// ////unsigned int cube_elements[] = ////{ //// // front //// 0, 1, 2, //// 2, 3, 0, //// // top //// 1, 5, 6, //// 6, 2, 1, //// // back //// 7, 6, 5, //// 5, 4, 7, //// // bottom //// 4, 0, 3, //// 3, 7, 4, //// // left //// 4, 5, 1, //// 1, 0, 4, //// // right //// 3, 2, 6, //// 6, 7, 3, ////}; //// ////int main() ////{ //// //Now we put it on the graphics card //// //generate your buffer on the graphics card //// //this contains all the vertices //// vector<vec3> plane; //// vector<int> indices; //// //// generateGrid(5, 5, plane, indices); //// //// //// int numVertices = plane.size(); //// int numColors = sizeof(cube_colors) / sizeof(GLfloat); //// int vertOffset = plane.size() * sizeof(vec3); //// int colorOffset = numColors * sizeof(cube_colors); //// //// //int numIndices = sizeof(cube_elements) / sizeof(unsigned int); //// int numIndices = indices.size(); //// //// printf("numVertices: %d \n", numVertices); //// printf("numColors: %d \n", numColors); //// printf("numIndices: %d \n", numIndices); //// //// //// //// glGenBuffers(1, &m_IBO); //// glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IBO); //// glBufferData(GL_ELEMENT_ARRAY_BUFFER, //// indices.size() * sizeof(int), //// indices.data(), //// GL_STATIC_DRAW); //// glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); //// //// glGenBuffers(1, &m_VBO); //// glBindBuffer(GL_ARRAY_BUFFER, m_VBO); //// glBufferData(GL_ARRAY_BUFFER, //// vertOffset + colorOffset, //// NULL, //// GL_STATIC_DRAW); //// //// glBufferSubData(GL_ARRAY_BUFFER, //// 0, //// plane.size() * sizeof(vec3), //// plane.data()); //// glBufferSubData(GL_ARRAY_BUFFER, vertOffset, colorOffset, &cube_colors[0]); //// //// //// //// glGenVertexArrays(1, &m_VAO); //// glBindVertexArray(m_VAO); //// glEnableVertexAttribArray(0); //// glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0); //// //// glEnableVertexAttribArray(1); //// glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (void*)vertOffset); //// //unbind now that we have generated and populated //// //// //// //// //// glBindBuffer(GL_ARRAY_BUFFER, 0); //// glBindVertexArray(0); ////}
3e20a76b1dc268ccf4324e3cb3ba5fd4d51a0b25
[ "C++" ]
5
C++
slanden/Graphics
eafcd29f22b2267540b52b48866972162234e395
e800626cdb1d055a832a9b8bac57b2564a550812
refs/heads/master
<repo_name>VictorNguyen031900/Computer-Science-II<file_sep>/Lab12/dQueue.cpp //Dynamic Queue #include "dQueue.h" #include <iostream> using namespace std; Queue::Queue() { front = nullptr; rear = nullptr; amount = 0; } Queue::~Queue() { cout << "Destroying queue list!" << endl; amount = 0; destroy(); } void Queue::enqueue(el_t in) { QueueNode *newNode; newNode = new QueueNode; newNode->letter = in; newNode->next = nullptr; if(isEmpty()) { front = newNode; rear = newNode; } else { rear->next = newNode; rear = newNode; } amount++; } void Queue::dequeue(el_t &out) { QueueNode *temp; if(isEmpty()) { cout << "Underflow! There is nothing in the queue to dequeue!" << endl; } else { out = front->letter; temp = front; front = front->next; delete temp; amount--; } } void Queue::displayAll() const { QueueNode *temp; temp = front; if(isEmpty()) { cout << "Underflow! There is nothing in the queue to print!" << endl; } else { while(temp != nullptr) { cout << temp->letter << " "; temp = temp->next; } } cout << endl; } bool Queue::isEmpty() const { if(amount == 0) { return true; } else { return false; } } void Queue::destroy() { QueueNode *temp; char dummy; while(isEmpty() != true) { dequeue(dummy); } } <file_sep>/Lab12/lab12-p2.cpp #include "dQueue.h" #include <iostream> using namespace std; int main() { Queue q; el_t c; cout << "Initial Queue contents" << endl; q.displayAll(); q.dequeue(c); q.enqueue('a'); cout << endl << "Queue contents after adding a: " << endl; q.displayAll(); q.enqueue('b'); q.enqueue('c'); q.enqueue('d'); q.enqueue('e'); q.enqueue('f'); cout << endl << "Queue contents after adding b-f: " << endl; q.displayAll(); q.dequeue(c); cout << endl << c << endl; cout << endl << "Queue contents after removing one element: " << endl; q.displayAll(); q.dequeue(c); cout << endl << "Remvoed element: " << c << endl; cout << endl << "Queue contents after removing another element: " << endl; q.displayAll(); q.enqueue('g'); q.enqueue('h'); q.enqueue('i'); cout << endl << "Queue contents after adding g, h, i: " << endl; q.displayAll(); q.dequeue(c); q.dequeue(c); q.dequeue(c); q.dequeue(c); cout << endl << "Queue contents after removing 4 elements: " << endl; q.displayAll(); q.dequeue(c); q.dequeue(c); cout << endl << "Final Queue contents: " << endl; q.displayAll(); return 0; } <file_sep>/HW4/node.h //This is node.h for Class Node #ifndef NODE_H #define NODE_H #include <iostream> #include <string> using namespace std; class node { friend class LL; private: string name; string phoneNumber; node *next; public: }; #endif <file_sep>/Lab4/Part 1/course.cpp #include "course.h" #include <iostream> #include <iomanip> #include <string> using namespace std; course::course() { courseNumber = 0; courseName = ""; numberOfCredits = 0; } course::course(long cNum, string cName, int numCredits) { courseNumber = cNum; courseName = cName; numberOfCredits = numCredits; } void course::setCourseNumber(long cNum) { courseNumber = cNum; } void course::setCourseName(string cName) { courseName = cName; } void course::setNumberOfCredits(int numCredits) { numberOfCredits = numCredits; } long course::getCourseNumber() const { return courseNumber; } string course::getCourseName() const { return courseName; } int course::getNumberOfCredits() const { return numberOfCredits; } void course::print() const { if(courseNumber == 0) { cout << endl << "Course Number:" << setw(12) << right << courseNumber << endl; cout << "Course Name:" << setw(19) << right << courseName << endl; cout << "Number of Credits:" << setw(8) << right << numberOfCredits << endl << endl; } else { cout << endl << "Course Number:" << setw(16) << right << courseNumber << endl; cout << "Course Name:" << setw(19) << right << courseName << endl; cout << "Number of Credits:" << setw(8) << right << numberOfCredits << endl << endl; } } <file_sep>/Lab2/lab2_p1.cpp /******************************************************************************* <NAME> CS 211 2/1/19 *******************************************************************************/ #include <iostream> #include <fstream> using namespace std; void readArray (int [], int [], int [], const int); void printArray (const int [], const int); void reverseArray (int [], const int); int longestSequence(const int [], const int); int main() { int longest; const int SIZE = 10; int A[SIZE]; int B[SIZE]; int C[SIZE]; readArray(A, B, C, SIZE); printArray(A, SIZE); printArray(B, SIZE); printArray(C, SIZE); reverseArray(A, SIZE); longest = longestSequence(A, SIZE); cout << "The longest sequence of array A is " << longest <<endl; longest = longestSequence(B, SIZE); cout << "The longest sequence of array B is " << longest <<endl; longest = longestSequence(C, SIZE); cout << "The longest sequence of array C is " << longest <<endl; return 0; } void readArray(int A[], int B[], int C[], const int SIZE) { ifstream infile; infile.open("arrays.txt"); if(!infile) { cout << "No file detected." << endl; } else { for(int i=0;i<SIZE;i++) { infile >> A[i]; } for(int j=0;j<SIZE;j++) { infile >> B[j]; } for(int k=0;k<SIZE;k++) { infile >> C[k]; } } infile.close(); } void printArray(const int letter[], const int SIZE) { cout << "Array: "; for (int i = 0; i < SIZE; i++) { cout << letter[i] << " "; } cout << endl << endl; } void reverseArray(int Ah[], const int SIZE) { int i; int j = SIZE; int k; for (i=0;i<j;i++) { j--; k = Ah[i]; Ah[i] = Ah[j]; Ah[j] = k; } cout << "Reversed: "; for (int i = 0; i < SIZE; i++) { cout << Ah[i] << " "; } cout << endl << endl; } int longestSequence(const int test[], const int SIZE) { int i; int length = 1; int long1 = 1; for(i=0;i<SIZE;i++) { if(test[i+1] == test[i]+1) { length += 1; } else if(test[i] == test[i+1]) { } else if(length > long1) { long1 = length; length = 1; } else { length = 1; } } return long1; } <file_sep>/HW2/Restaurant.h #ifndef RESTAURANT_H #define RESTAURANT_H #include "Reservation.h" #include <string> #include <vector> using namespace std; class Restaurant { private: string restaurantName; string restaurantAddress; string restaurantCity; string restaurantType; int availableSeats[4]; vector <Reservation> reservations; public: Restaurant(); Restaurant(string, string, string, string, int); string getName() const; string getAddress() const; string getCity() const; string getType() const; int getSeats(int) const; //void printInfo() const; void makeReservation(string, string, int, int); void printReservation() const; }; #endif <file_sep>/Lab4/Part 2/instructor.cpp #include "instructor.h" #include "course2.h" #include <iostream> #include <iomanip> #include <string> using namespace std; instructor::instructor() { } instructor::instructor(string fN, string lN, char g, long eID, string oNum, long cNum1, string cN1, int nC1, long cNum2, string cN2, int nC2, long cNum3, string cN3, int nC3) { firstName = fN; lastName = lN; gender = g; employeeID = eID; officeNum = oNum; courses[0].setCourseNumber(cNum1); courses[0].setCourseName(cN1); courses[0].setNumberOfCredits(nC1); courses[1].setCourseNumber(cNum2); courses[1].setCourseName(cN2); courses[1].setNumberOfCredits(nC2); courses[2].setCourseNumber(cNum2); courses[2].setCourseName(cN2); courses[2].setNumberOfCredits(nC2); } void instructor::setInstructor(string fN, string lN, char g, long eID, string oNum, long cNum1, string cN1, int nC1, long cNum2, string cN2, int nC2, long cNum3, string cN3, int nC3) { firstName = fN; lastName = lN; gender = g; employeeID = eID; officeNum = oNum; courses[0].setCourseNumber(cNum1); courses[0].setCourseName(cN1); courses[0].setNumberOfCredits(nC1); courses[1].setCourseNumber(cNum2); courses[1].setCourseName(cN2); courses[1].setNumberOfCredits(nC2); courses[2].setCourseNumber(cNum2); courses[2].setCourseName(cN2); courses[2].setNumberOfCredits(nC2); } void instructor::print() const { if(employeeID == 0) { cout << "First name:" << setw(25) << right << firstName << endl; cout << "Last name:" << setw(23) << right << lastName << endl; cout << "Gender:" << setw(22) << right << gender << endl; cout << "Employee ID:" << setw(17) << right << employeeID << endl; cout << "Office Number:" << setw(21) << right << officeNum << endl << endl; cout << "#1 Course Number:" << setw(12) << right << courses[0].getCourseNumber() << endl; cout << "#1 Course Name:" << setw(18) << right << courses[0].getCourseName() << endl; cout << "#1 Number of Credits:" << setw(8) << right << courses[0].getNumberOfCredits() << endl << endl; cout << "#2 Course Number:" << setw(12) << right << courses[1].getCourseNumber() << endl; cout << "#2 Course Name:" << setw(12) << right << courses[1].getCourseName() << endl; cout << "#2 Number of Credits:" << setw(8) << right << courses[1].getNumberOfCredits() << endl << endl; cout << "#3 Course Number:" << setw(12) << right << courses[2].getCourseNumber() << endl; cout << "#3 Course Name:" << setw(18) << right << courses[2].getCourseName() << endl; cout << "#3 Number of Credits:" << setw(8) << right << courses[2].getNumberOfCredits() << endl << endl; } else { cout << "First name:" << setw(25) << right << firstName << endl; cout << "Last name:" << setw(23) << right << lastName << endl; cout << "Gender:" << setw(22) << right << gender << endl; cout << "Employee ID:" << setw(23) << right << employeeID << endl; cout << "Office Number:" << setw(21) << right << officeNum << endl << endl; cout << "#1 Course Number:" << setw(16) << right << courses[0].getCourseNumber() << endl; cout << "#1 Course Name:" << setw(18) << right << courses[0].getCourseName() << endl; cout << "#1 Number of Credits:" << setw(8) << right << courses[0].getNumberOfCredits() << endl << endl; cout << "#2 Course Number:" << setw(16) << right << courses[1].getCourseNumber() << endl; cout << "#2 Course Name:" << setw(18) << right << courses[1].getCourseName() << endl; cout << "#2 Number of Credits:" << setw(8) << right << courses[1].getNumberOfCredits() << endl << endl; cout << "#3 Course Number:" << setw(16) << right << courses[2].getCourseNumber() << endl; cout << "#3 Course Name:" << setw(18) << right << courses[2].getCourseName() << endl; cout << "#3 Number of Credits:" << setw(8) << right << courses[2].getNumberOfCredits() << endl << endl; } } <file_sep>/Lab5/lab5.cpp #include "student.h" #include <iostream> #include <iomanip> #include <string> using namespace std; int main() { Student student1; student1.print(); string name = "unknown"; string major = "PHYS"; string classification = "graduate"; int units = 0; Student student2(name, major, classification, units); student2.print(); student2.getData(); student2.print(); return 0; } <file_sep>/Lab11/dStack.cpp #include "dStack.h" #include <iostream> using namespace std; Stack::Stack() { top = nullptr; } Stack::~Stack() { cout << "Destroying stack." << endl; destroy(); } void Stack::push(el_t in) { StackNode *newNode; newNode = new StackNode; newNode->element = in; newNode->next = top; if(isEmpty()) { top = newNode; newNode->next = nullptr; } else { newNode->next = top; top = newNode; } } void Stack::pop(el_t &out) { StackNode *temp; if(isEmpty()) { cout << "The stack is empty." << endl; } else { out = top->element; temp = top->next; delete top; top = temp; } } void Stack::getTop(el_t &element) const { element = top->element; } void Stack::displayAll() const { StackNode *temp = new StackNode; temp = top; while(temp != nullptr) { cout << temp->element << endl; temp = temp->next; } } bool Stack::isEmpty()const { if(top == nullptr) { return true; } else { return false; } } void Stack::destroy() { StackNode *temp; while(top != nullptr) { temp = top->next; delete top; top = temp; } } <file_sep>/Lab2/lab2_p2.cpp /*************************************************************************************************** <NAME> CS 211 2-4-19 ***************************************************************************************************/ #include <iostream> #include <vector> #include <fstream> #include <string> using namespace std; void commandInsert (vector<string>& V, string, int); void commandDelete (vector<string>& V, int); void commandPrint (const vector<string>& V); int main() { vector<string> V; string command; string input; int var; ifstream infile; infile.open("vectorData.txt"); if(!infile) { cout << "No file detected." << endl; } else { while(infile >> command) { if(command == "Insert") { infile >> input >> var; commandInsert(V, input, var); } else if(command == "Delete") { infile >> var; commandDelete(V, var); } else if(command == "Print") { commandPrint(V); } } } infile.close(); return 0; } void commandInsert (vector<string>& V, string text, int var) { if(var <= V.size()) { V.insert(V.begin() + var, text); } } void commandDelete (vector<string>& V, int var) { if(var < V.size()) { V.erase(V.begin() + var); } } void commandPrint (const vector<string>& V) { for(int i = 0; i < V.size(); i++) { cout << V[i] << " "; } cout << endl; } <file_sep>/Lab12/dQueue.h //dynamic queue #ifndef DQUEUE_H #define DEQUEUE_H #include <iostream> using namespace std; typedef char el_t; class Queue { private: struct QueueNode { el_t letter; QueueNode *next; }; QueueNode *front; QueueNode *rear; int amount; public: Queue(); ~Queue(); void enqueue(el_t); void dequeue(el_t &); void displayAll() const; bool isEmpty() const; void destroy(); }; #endif <file_sep>/HW2/Restaurant.cpp //This is Restaurant.cpp #include "Restaurant.h" #include "Reservation.h" #include <iostream> #include <iomanip> #include <string> #include <vector> using namespace std; Restaurant::Restaurant() //Default constructor { restaurantName = "Unknown"; //set variable restaurantName to Unknown if given no parameters restaurantAddress = "Unknown"; //set variable restaurantAddress to Unknown if given no parameters restaurantCity = "Unknown"; //set variable restaurantCity to Unknown if given no parameters restaurantType = "Unknown"; //set variable restaurantType to Unknown if given no parameters availableSeats[0] = 0; //set array availableSeats index 0 to 0 if give no parameters 5:00 availableSeats[1] = 0; //set array availableSeats index 1 to 0 if give no parameters 6:00 availableSeats[2] = 0; //set array availableSeats index 2 to 0 if give no parameters 7:00 availableSeats[3] = 0; //set array availableSeats index 3 to 0 if give no parameters 8:00 } Restaurant::Restaurant(string name, string address, string city, string type, int capacity) //Overloaded constructor with parameters { restaurantName = name; //passed variable name is set to restaurantName in Restaurant class restaurantAddress = address; //passed variable address is set to restaurantAddress in Restaurant class restaurantCity = city; //passed variable city is set to restaurantCity in Restaurant class restaurantType = type; //passed variable type is set to restaurantType in Restaurant class availableSeats[0] = capacity; //set array availableSeats index 0 to variable capacity 5:00 availableSeats[1] = capacity; //set array availableSeats index 1 to variable capacity 6:00 availableSeats[2] = capacity; //set array availableSeats index 2 to variable capacity 7:00 availableSeats[3] = capacity; //set array availableSeats index 3 to variable capacity 8:00 } string Restaurant::getName() const //member function used to get restaurantName { return restaurantName; //return variable restaurantName } string Restaurant::getAddress() const //member function used to get restaurantAddress { return restaurantAddress; //return variable restaurantAddress } string Restaurant::getCity() const //member function used to get restaurantCity { return restaurantCity; //return variable restaurantCity } string Restaurant::getType() const //member function used to get restaurantType { return restaurantType; //return variable restaurantType } int Restaurant::getSeats(int a) const //member function used to get available seating from array availableSeats based on index { return availableSeats[a]; //return availableSeats based on index a } void Restaurant::makeReservation(string name, string phone, int group, int time) //member function used to make reservations { int test; //variable used to test available seatings Reservation temp(name, phone, group, time); //create a Reservation class named temp with passed in variables name, phone, group, and time if(time == 5) //if variable time matches with 5 then proceed with if portion { test = availableSeats[0] - group; //set variable test to availableSeats index 0 minus variable group if(test < 0) //if variable test is is less than 0 that means there is not enough seats to set the reservation { cout << "No available seats at your time." << endl; //print unavailable seating message } else //if if statement turns false that means there is available seating { availableSeats[0] = test; //set array availableSeats index 0 to variable test reservations.push_back(temp); //push back(add) temp class to vector reservations cout << "Reservation made!" << endl; //print sucess message } } else if(time == 6) //else if variable time matches with 6 then proceed with else if portion { test = availableSeats[1] - group; //set variable test to availableSeats index 1 minus variable group if(test < 0) //if variable test is is less than 0 that means there is not enough seats to set the reservation { cout << "No available seats at your time." << endl; //print unavailable seating message } else //if if statement turns false that means there is available seating { availableSeats[1] = test; //set array availableSeats index 1 to variable test reservations.push_back(temp); //push back(add) temp class to vector reservations cout << "Reservation made!" << endl; //print sucess message } } else if(time == 7) //else if variable time matches with 7 then proceed with else if portion { test = availableSeats[2] - group; //set variable test to availableSeats index 2 minus variable group if(test < 0) //if variable test is is less than 0 that means there is not enough seats to set the reservation { cout << "No available seats at your time." << endl; //print unavailable seating message } else //if if statement turns false that means there is available seating { availableSeats[2] = test; //set array availableSeats index 2 to variable test reservations.push_back(temp); //push back(add) temp class to vector reservations cout << "Reservation made!" << endl; //print sucess message } } else if(time == 8) //else if variable time matches with 8 then proceed with else if portion { test = availableSeats[3] - group; //set variable test to availableSeats index 3 minus variable group if(test < 0) //if variable test is is less than 0 that means there is not enough seats to set the reservation { cout << "No available seats at your time." << endl; //print unavailable seating message } else //if if statement turns false that means there is available seating { availableSeats[3] = test; //set array availableSeats index 3 to variable test reservations.push_back(temp); //push back(add) temp class to vector reservations cout << "Reservation made!" << endl; //print sucess message } } else //if variable time does not match 5, 6, 7, or 8 then variable time is incorrect { cout << "Error" << endl; //print error message } } void Restaurant::printReservation() const //member function used to print reservations from a certain restaurant { int reservationVectorSize = reservations.size(); //variable reservationVectorSize set to size of vector reservations for(int i = 0; i < reservationVectorSize; i++) //for-loop used to print each reservation in vector { cout << left << setw(14) << reservations[i].getResNum() << left << setw(10) << reservations[i].getConName() << left << setw(14) << reservations[i].getConPhone() << left << setw(8) << reservations[i].getGroupSize() << left << setw(6) << reservations[i].getResTime() << endl; //print reservation formatted reservation number, contact name, contach phone, group size, and reservation time } } <file_sep>/Lab11/lab11-p2.cpp #include "dStack.h" #include <iostream> using namespace std; int main() { Stack s; el_t c; cout << "initial stack contents" << endl; s.displayAll(); s.pop(c); s.push('a'); cout << endl << "stack contents after pushing a: " << endl; s.displayAll(); s.push('b'); cout << endl << "stack contents after pushing b: " << endl; s.displayAll(); s.push('c'); s.push('d'); s.push('e'); s.push('f'); s.push('g'); cout << endl << "stack contents after pushing c-g" << endl; s.displayAll(); s.getTop(c); cout << endl << "top element is " << c << endl; s.pop(c); cout << endl << c << endl; cout << endl << "stack contents after popping one element: " << endl; s.displayAll(); s.pop(c); cout << endl << "popped element: " << c << endl; cout << endl << "stack conntenst after popping another element: " << endl; s.displayAll(); s.pop(c); s.pop(c); if(!s.isEmpty()) { s.getTop(c); cout << endl << "top element is " << c << endl; } s.pop(c); cout << endl << "stack contents after popping 3 more elements: " << endl; s.displayAll(); s.pop(c); s.pop(c); s.push('a'); s.push('b'); cout << endl << "final stack contents" << endl; s.displayAll(); return 0; } <file_sep>/Lab3/lab3_p1.cpp /************************************************************************************** <NAME> CS 211 2--19 **************************************************************************************/ #include<iostream> #include<string> using namespace std; void ReplaceSubString(const string, const string, const string); int main() { string string1; string string2; string string3; cout << "Enter a string: "; getline(cin, string1); cout << endl << "Now enter a target word: "; cin >> string2; cout << endl << "Now enter a replacement word for the target: "; cin >> string3; ReplaceSubString(string1, string2, string3); return 0; } void ReplaceSubString(const string one, const string two, const string three) { string string4 = one; int sizeTwo = two.size(); int sizeThree = three.size(); int a = string4.find(two, 0); while(a != string4.npos) { string4.replace(a, sizeTwo, three); a = string4.find(two, a+1); } cout << endl << "The word " << "\"" << two << "\"" << " was replaced with " << "\"" << three << "\"" << " it is now: \"" << string4 << "\"" << endl; } <file_sep>/HW2/HW2.cpp /************************************************************************************************************************ <NAME> CS 211 Homework Assignment 1 Date: 3/1/2019 This program helps customers make reservations at local restaurants. The program has many features such as finding a table based on the city location, the type of restaurant, size of the group, and ideally reservation time. Finding a table at a certain restaurant based on the customer's group size and preferred restaurant name. Being able to make a reservation for a certain restaurant, the customer is able to input their name, phone number, group size, and reservation time. The program also has a feature to print out all the avaiable rstaurants that are in the database (vector). And finally the program is able to print out all reservations for a certain restaurant. ************************************************************************************************************************/ #include "RestaurantReservations.h" #include "Restaurant.h" #include "Reservation.h" #include <iostream> #include <iomanip> #include <string> using namespace std; int main() { RestaurantReservations openTable; //create a RestaurantReservations class named openTable openTable.ProcessTransactionFile("TransactionFile.txt"); //pass string to ProcessTransactionFile memberfunction return 0; } <file_sep>/Lab11/sStack.h // This is static stack #ifndef SSTACK_H #define SSTACK_H #include <iostream> #include <string> using namespace std; const int MAX = 5; typedef char el_t; class Stack { private: el_t Arr[MAX]; int topEl; public: Stack(); void push(el_t); void pop(el_t &); bool isEmpty(); bool isFull(); void displayAll(); }; #endif <file_sep>/HW2/Reservation.cpp #include "Reservation.h" #include <iostream> #include <iomanip> using namespace std; long Reservation::nextReservationNum = 100; //static variable set to 100 Reservation::Reservation() : reservationNum(nextReservationNum) //Default constructor set constant variable reservationNum to nextReservationNum { contactName = ""; //set contactName to blank contactPhone = ""; //set contachPhone to blank groupSize = 0; //set groupSize to 0 reservationTime = 0; //set reservationTime to 0 nextReservationNum += 10; //increase nextReservationNum by 10 } Reservation::Reservation(string cName, string cPhone, int rGroup, int rTime) : reservationNum(nextReservationNum) //overloaded constructor set constant vriable reservationNum to nextRerservationNum, passed to member function cName, cPhone, rGroup, and rTime { contactName = cName; //set contactName to passed in cName contactPhone = cPhone; //set contactPhone to passed in cPhone groupSize = rGroup; //set groupSize to passed in rGroup reservationTime = rTime; //set reservationTime to passed in rTime nextReservationNum += 10; //increase nextReservationNum by 10 } long Reservation::getResNum() const //member function used to get reservation number { return reservationNum; //return variable reservationNum from Reservation class } string Reservation::getConName() const //member function used to get contact name { return contactName; //return variable contactName from Reservation class } string Reservation::getConPhone() const //member function used to get contact phone { return contactPhone; //return variable contactphone from Reservation class } int Reservation::getGroupSize() const //member function used to get group size { return groupSize; //return variable groupSize from Reservation class } int Reservation::getResTime() const //member function used to get reservation time { return reservationTime; //return variable reservationTime from Reservation class } <file_sep>/Lab4/Part 1/lab4_p1.cpp /******************************************************************************************* <NAME> CS 211 2/15/2019 *******************************************************************************************/ #include "course.h" #include<iostream> #include<string> #include<iomanip> using namespace std; int main() { long cNumber; string cName; int numCredits; cout << endl << "Enter Course Number: "; cin >> cNumber; cout << "Enter Course Name: "; cin.ignore(); getline(cin, cName); cout << "Enter Number of Credits: "; cin >> numCredits; course test1(cNumber, cName, numCredits); test1.print(); course test2; test2.print(); cout << endl << "Enter Course Number: "; cin >> cNumber; cout << "Enter Course Name: "; cin.ignore(); getline(cin, cName); cout << "Enter Number of Credits: "; cin >> numCredits; test2.setCourseNumber(cNumber); test2.setCourseName(cName); test2.setNumberOfCredits(numCredits); test2.print(); return 0; } <file_sep>/HW5/dStack.cpp #include "dStack.h" #include <iostream> using namespace std; Stack::Stack() //Default constructor { top = nullptr; //Sets top pointer to null } Stack::~Stack() //Destructor { cout << "Destroying stack." << endl; destroy(); //calls destroy function to clear stack } void Stack::push(el_t in) //Function used to add char to stack { StackNode *newNode; //Create a pointer to later hold user input named newNode newNode = new StackNode; //Allocate space for new StackNode newNode->element = in; //Put char in to newNode newNode->next = top; //Make newNode the top node in the stack if(isEmpty()) //If isEmpty function is true, continue with if statement { top = newNode; //newNode is the only element in the stack newNode->next = nullptr; //set newNode's next node pointer to null } else //If isEmpty function is false, contine with else statement { newNode->next = top; //Make newNode the top node in the stack, more than one node in stack top = newNode; //Make top pointer point to newNode } } void Stack::pop(el_t &out) //Function used to remove node from stack { StackNode *temp; //Create a pointer to hold node temporary if(isEmpty()) //If isEmpty function is true then continue with if statement { cout << "The stack is empty." << endl; //Means there's no nodes to remove } else //If isEmpty function is false then continue with else statement { out = top->element; //Set char out since set by reference to top node's element temp = top->next; //Set temp pointer to next top node delete top; //Deallocate top, removes node from stack top = temp; //Set top to temp, node } } void Stack::displayAll() const //Function used to display all nodes in stack { StackNode *temp = new StackNode; //Allocate a new Stacknode named temp temp = top; //Set temp pointer to top node if(isEmpty()) //If isEmpty function is true then continue with if statement { cout << "There were no delimiters in the string!" << endl; //Stack is empty } else //If isEmpty function is false then continue with else statement { while(temp != nullptr) //While temp pointer is not null, continue with loop { cout << temp->element << " "; //Output temp node's element temp = temp->next; //Set temp node to pointer of next node } cout << endl; } } bool Stack::isEmpty()const //Function used to determine if stack is empty or not { if(top == nullptr) //Checks top if it points to null { return true; } else //If top points to a node, continue with else statement { return false; } } void Stack::destroy() //Function used to delete each node in the stack { StackNode *temp; while(top != nullptr) //While loop to check if top points to null { temp = top->next; //Set temp pointer to next top node's address delete top; //Deallocate top node top = temp; //Set top to temp } } bool Stack::ProperlyBalanced(string input) //Function used to check string is "balanced { bool output; //Used to return to main function el_t popChar; //Char used to hold top element in stack int SIZE = input.size(); //Used as a const for the length of input string int openBrace = 0; //Counter used to count how many { in string int closedBrace = 0; //Counter used to count how many } in string int openParenthese = 0; //Counter used to count how many ( in string int closedParenthese = 0; //Counter used to count how many ) in string int openBracket = 0; //Counter used to count how many [ in string int closedBracket = 0; //Counter used to count how many ] in string for(int i = 0; i < SIZE; i++) //For loop used to put delimiters in stack { //If and else-if statements used for each case of a delimiter if(input[i] == '{') push(input[i]); else if(input[i] == '}') push(input[i]); else if(input[i] == '(') push(input[i]); else if(input[i] == ')') push(input[i]); else if(input[i] == '[') push(input[i]); else if(input[i] == ']') push(input[i]); } while(isEmpty() != true) //While loop until stack is empty { pop(popChar); //Remove top node from stack and put in to popChar char //If and else-if statements used for each case of a delimiter, //then increase counter accordingly if(popChar == '{') openBrace++; else if(popChar == '}') closedBrace++; else if(popChar == '(') openParenthese++; else if(popChar == ')') closedParenthese++; else if(popChar == '[') openBracket++; else if(popChar == ']') closedBracket++; } //If statements used to determine if a certain delimiter is missing if(openBrace > closedBrace) { cout << "Missing/Extra } !" << endl; output = false; } if(openBrace < closedBrace) { cout << "Missing/Extra { !" << endl; output = false; } if(openParenthese > closedParenthese) { cout << "Missing/Extra ) !" << endl; output = false; } if(openParenthese < closedParenthese) { cout << "Missing/Extra ( !" << endl; output = false; } if(openBracket > closedBracket) { cout << "Missing/Extra ] !" << endl; output = false; } if(openBracket < closedBracket) { cout << "Missing/Extra [ !" << endl; output = false; } //If statement used if string is "balanced" if((openBrace == closedBrace) && (openParenthese == closedParenthese) && (openBracket == closedBracket)) { return true; } return output; } <file_sep>/Lab5/student.h #ifndef STUDENT_H #define STUDENT_H #include<string> using namespace std; class Student { private: string name; const long studentID; string major; string classification; int units; float tuition; public: static int totalNumofStudents; static int nextStudentID; Student(); Student(string, string, string, int); ~Student(); void print() const; void getData(); }; #endif <file_sep>/Lab11/sStack.cpp // This is static stack #include "sStack.h" #include <iostream> #include <string> using namespace std; Stack::Stack() { for(int i = 0; i < MAX; i++) { Arr[i] = -1; } topEl = -1; } void Stack::push(el_t in) { if(isFull()) { cout << "Overflow (can't push " << in << ")" << endl; } else { topEl++; Arr[topEl] = in; } } void Stack::pop(el_t &out) { if(isEmpty()) { cout << "Underflow (can't pop)" << endl;; } else { out = Arr[topEl]; Arr[topEl] = -1; topEl--; } } bool Stack::isEmpty() { if(Arr[0] == -1) { return true; } else { return false; } } bool Stack::isFull() { if(Arr[MAX - 1] != -1) { return true; } else { return false; } } void Stack::displayAll() { if(isEmpty()) { cout << "There is nothing to print out." << endl; } else { // cout << "entering print loop. - top is " << topEl << endl; for(int i = topEl; i >= 0; i--) { cout << Arr[i] << endl; } } } <file_sep>/HW4/LL.cpp //This is Elel.cpp for Class LL #include "LL.h" #include "node.h" #include <iostream> #include <string> using namespace std; // Default constructor to initialize a linked list LL::LL() { head = nullptr; } // Overloaded constuctor to perform a deep of a initialized linked list LL::LL(const LL &source) { head = nullptr; node *nodePtr2; if(source.head == nullptr) { cout << "There's nothing to copy to new list." << endl << endl; } else { nodePtr2 = source.head; while(nodePtr2 != nullptr) { insert(nodePtr2->name, nodePtr2->phoneNumber); nodePtr2 = nodePtr2->next; } } } // Destroyer function to delete the initialized linked lists after the program is done LL::~LL() { cout << "Deleted Linked List(s)." << endl << endl; destroy(); } // Insert a new node in to the linked list but place it in the list such that it is in // alphabetical order void LL::insert(string pName, string phone) { node *newNode; node *nodePtr; node *prev; newNode = new node; newNode->name = pName; newNode->phoneNumber = phone; newNode->next = nullptr; if(!head) { head = newNode; } else { nodePtr = head; prev = nullptr; while(nodePtr != nullptr) { if(nodePtr->name >= newNode->name) { break; } else { prev = nodePtr; nodePtr = nodePtr->next; } } if(nodePtr == head) { newNode->next = head; head = newNode; } else { newNode->next = nodePtr; prev->next = newNode; } } } // Function used to print the whole linked list void LL::print() { node *nodePtr; int *count; count = new int; *count = 1; nodePtr = head; while(nodePtr != nullptr) { cout << *count << ". " << nodePtr->name << ", " << nodePtr->phoneNumber << endl; nodePtr = nodePtr->next; *count+=1; } cout << endl; delete count; } // Function used to find a name in the list and if found // output the position of the name in the list void LL::searchByName(string pName) { node *nodePtr; bool *boolPtr = nullptr; string *stringPtr = nullptr; int *count; nodePtr = head; boolPtr = new bool; stringPtr = new string; count = new int; *count = 1; while(nodePtr != nullptr) { if(nodePtr->name == pName) { *boolPtr = true; *stringPtr = nodePtr->phoneNumber; break; } else { *boolPtr = false; *count+=1; } nodePtr = nodePtr->next; } if(*boolPtr == true) { cout << "Found " << pName << "! Their phone number is " << *stringPtr << ". They're #" << *count << " in the list." << endl; } else { cout << "Could not find " << pName << " in our database!" << endl << endl;; } delete boolPtr; delete stringPtr; delete count; } // Function used to delete each node in the linked list one by one void LL::destroy() { node *current = head; node *next; while(current != nullptr) { next = current->next; delete current; current = next; } head = nullptr; } // Function uses two arrays to create a node and insert the new node // in to the linked list void LL::readFromArrays(string nArr[], string pArr[], int size) { for(int i = 0; i < size; i++) { insert(nArr[i], pArr[i]); } } // Function is used to insert a new node in to the linked list at a certain given postion void LL::insertAtPos(string pName, string phone, int pos) { node *newNode; node *nodePtr; node *prev; int *count; count = new int; *count = 1; newNode = new node; newNode->name = pName; newNode->phoneNumber = phone; newNode->next = nullptr; if(!head) { head = newNode; } else { nodePtr = head; if(pos == 1) { newNode->next = head; head = newNode; } else { while((nodePtr != nullptr) && (pos != *count)) { prev = nodePtr; nodePtr = nodePtr->next; *count+=1; } if(nodePtr) { newNode->next = nodePtr; prev->next = newNode; } else if(*count >= pos) { prev->next = newNode; } } } delete count; } // Function prints each node in the linked list in reverse order void LL::printReverse() { reverse(); print(); reverse(); } // Function tranverses the list to find a new in the record and if found // replace the user's old phone number with their new one void LL::updateNumber(string pName, string newPhone) { node *nodePtr; bool *boolPtr = nullptr; nodePtr = head; boolPtr = new bool; while(nodePtr != nullptr) { if(nodePtr->name == pName) { *boolPtr = true; nodePtr->phoneNumber = newPhone; break; } else { *boolPtr = false; } nodePtr = nodePtr->next; } if(*boolPtr == true) { cout << "Updated " << pName << "'s record to " << newPhone << "." << endl; } else { cout << "Could not find " << pName << " in our database in order to change their record!" << endl << endl;; } delete boolPtr; } // Function deletes a node in the linked list based on the name given to the function void LL::removeRecord(string pName) { node *nodePtr; node *prev; if(!head) { return; } if(head->name == pName) { nodePtr = head->next; delete head; head = nodePtr; } else { nodePtr = head; while((nodePtr != nullptr) && (nodePtr->name != pName)) { prev = nodePtr; nodePtr = nodePtr->next; } if(nodePtr) { prev->next = nodePtr->next; delete nodePtr; } else { cout << pName << " does not exist in the records!" << endl; } } } // Function is used to copy every node in a list and copy said node // in to a new linked list LL& LL::operator=(const LL& source) { node *nodePtr; node *newNode; nodePtr = source.head; destroy(); while(nodePtr->next) { insert(nodePtr->name, nodePtr->phoneNumber); nodePtr = nodePtr->next; } } // Function is used to reverse a whole linked list void LL::reverse() { node *current = head; node *prev = nullptr; node *next = nullptr; while (current != nullptr) { next = current->next; current->next = prev; prev = current; current = next; } head = prev; } <file_sep>/Lab9/lab9-p1.cpp #include <iostream> using namespace std; int main() { int length; int width; int area; int *lengthPtr = nullptr; int *widthPtr = nullptr; cout << "Please Enter the Length: "; cin >> length; cout << "Please Enter the Width: "; cin >> width; lengthPtr = &length; widthPtr = &width; cout << "The Area is: " << *lengthPtr * *widthPtr << endl; if(*lengthPtr > *widthPtr) { cout << "Length is greater than Width." << endl; cout << "Length: " << *lengthPtr << endl; cout << "Width: " << *widthPtr << endl; } else { cout << "Width is greater than Length." << endl; cout << "Width: " << *widthPtr << endl; cout << "Length: " << *lengthPtr << endl; } return 0; } <file_sep>/Lab12/sQueue.h //Static Queue #ifndef SQUEUE_H #define SQUEUE_H #include <iostream> using namespace std; const int MAX = 5; typedef char el_t; class Queue { private: el_t Arr[MAX]; int front; int rear; int amount; public: Queue(); void enqueue(el_t); void dequeue(el_t &); bool isFull() const; bool isEmpty() const; void displayAll() const; }; #endif <file_sep>/Lab13/lab12.cpp #include "trees.h" #include <iostream> using namespace std; int main() { IntBinaryTree tree; IntBinaryTree tree1; IntBinaryTree tree2; cout << "Height: " << tree.treeHeight() << endl; cout << endl; cout << "Inserting nodes." << endl; tree.insertNode(5); tree.insertNode(8); tree.insertNode(3); tree.insertNode(12); tree.insertNode(9); cout << endl; cout << "Here are the values in the tree: " << endl; tree.displayInOrder(); cout << endl; cout << "Height: " << tree.treeHeight()<< endl; cout << endl; cout << "Number of leaf nodes: " << tree.numLeafNodes() << endl; cout << "Deleting 8..." << endl; tree.remove(8); cout << "Deleting 12..." << endl; tree.remove(12); cout << endl; cout << "Now, here are the nodes: " << endl; tree.displayInOrder(); cout << endl; cout << "Height: " << tree.treeHeight() << endl; cout << "Number of leaf nodes: " << tree.numLeafNodes() << endl; tree1.insertNode(55); tree1.insertNode(5); tree1.insertNode(8); cout << endl << "Here are the nodes of tree1: " << endl; tree1.displayInOrder(); cout << endl; tree2 = tree1; cout << "Now, her are the nodes of tree2: " << endl; tree2.displayInOrder(); cout << endl; tree1.insertNode(10); tree1.insertNode(3); tree1.insertNode(12); cout << endl << "Here are the ndoes of tree1 afer adding 3 nodes: " << endl; tree1.displayInOrder(); cout << endl; cout << endl << "Here are the nodes of tree2: " << endl; tree2.displayInOrder(); IntBinaryTree tree3 = tree1; cout << "Now, here are the nodes of tree3: " << endl; tree3.displayInOrder(); cout << endl; tree1.remove(5); cout << endl << "Here are the nodes of tree1 after removing node 5: " << endl; tree1.displayInOrder(); cout << endl << "Now, Here are the nodes of tree3" << endl; tree3.displayInOrder(); cout << endl; return 0; } <file_sep>/Lab11/dStack.h #ifndef DSTACK_H #define DSTACK_H #include <iostream> using namespace std; typedef char el_t; class Stack { private: struct StackNode { el_t element; StackNode *next; }; StackNode *top; public: Stack(); ~Stack(); void push(el_t); void pop(el_t &); void getTop(el_t &) const; void displayAll() const; bool isEmpty() const; void destroy(); }; #endif <file_sep>/HW4/node.cpp //This is node.cpp for Class Node #include "node.h" #include "LL.h" #include <iostream> #include <string> using namespace std; <file_sep>/Lab7/lab7.cpp #include "Package.h" #include "OvernightPackage.h" #include <iostream> using namespace std; int main() { double hold; Package A("AmyJohnson", "3465RegentsRd", "SanDiego", "CA", 92130 , "EdwardJohnes", "439NWGreens", "Fayetteville", "NY", 13066, "HG9983", "06/03/2016", 10, 0.7, "upto1000"); //hold = A.calculateCost(10, 0.7, "upto1000"); hold = A.calculateCost(); A.print(); cout << "Shipping cost: $" << hold << endl << endl; OvernightPackage B("MaryPalmer", "6534SpringburtDR", "PalmSprings", "CA", 92240 , "DennisGarcia", "8FifthSt", "Denver", "CO", 66665, "UI0900", "10/11/2016", 20.1, 0.8, "upto5000", 7); //hold = B.calculateCost(20.1, 0.8, "upto5000", 7); hold = B.calculateCost(); B.print(); cout << "Shipping cost(Overnight): $" << hold << endl << endl; return 0; } <file_sep>/Lab8/lab8-p1.cpp //g++ -std=c++11 FILENAME.cpp (to complie properly) #include <iostream> #include <iomanip> #include <vector> #include <string> using namespace std; void selSort(vector<string> &); void display(const vector<string> &); int binSearch(const vector<string> &, string); int main() { int index; vector<string> names{"<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>"}; cout << "Created vector \"names\"." << endl; display(names); cout << endl << "Sorting vector..." << endl; selSort(names); cout << endl << "Sorted!" << endl;; display(names); cout << endl << endl << "Searching for \"<NAME>\"" << endl; index = binSearch(names, "<NAME>"); if(index == -1) { cout << "Name not found..." << endl; } else { cout << "Found name at index " << index << endl; } cout << endl << "Searching for \"<NAME>\"" << endl; index = binSearch(names, "<NAME>"); if(index == -1) { cout << "Name not found..." << endl; } else { cout << "Found name at index " << index << endl; } return 0; } void selSort(vector<string> &v) { string smallest; string testCase; string temp; int rIndex; for(int i = 0; i < v.size(); i++) { smallest = v[i]; for(int j = i; j < v.size(); j++) { testCase = v[j]; if(smallest[0] >= testCase[0]) { temp = testCase; smallest = testCase; temp = v[i]; rIndex = j; } } v[i] = smallest; v[rIndex] = temp; } } void display(const vector<string> &v) { for(int i = 0; i < v.size(); i++) { if(i < (v.size() - 1)) { cout << v[i] << ", "; } else { cout << v[i]; } } } int binSearch(const vector<string> &v, string key) { int mid = 0; int left = 0; int right; right = v.size(); while(left < right) { mid = left + (right - left)/2; if(key > v[mid]) { left = mid + 1; } else if(key < v[mid]) { right = mid; } else { return mid; } } return -1; } <file_sep>/Lab3/lab3_p2.cpp /*********************************************************************************************** <NAME> CS211 2-8-19 **********************************************************************************************/ #include<iostream> #include<string> using namespace std; bool isPalindrome(const string); int main() { bool isTrueValue; string userIn; cout << "Please enter in a Palindrome: "; getline(cin, userIn); isTrueValue = isPalindrome(userIn); if(isTrueValue == true) { cout << "What you entered is a Palindrome :) ." << endl; } else if(isTrueValue == false) { cout << "Sorry, what you entered is not a Palindrome :( ." << endl; } return 0; } bool isPalindrome(const string hold) { bool isTrue; string testIf = hold; int place = testIf.find(" ", 0); while(place != testIf.npos) { testIf.erase(place, 1); place = testIf.find(" ", place+1); } int size = testIf.size(); char palin[size]; char reverseTest[size]; int j = size; char k; for(int i = 0; i < size; i++) { palin[i] = testIf[i]; reverseTest[i] = testIf[i]; } for(int i = 0; i < j; i++) { j--; k = reverseTest[i]; reverseTest[i] = reverseTest[j]; reverseTest[j] = k; } for(int i = 0; i < size; i++) { if(palin[i] == reverseTest[i]) { isTrue = true; } else { isTrue = false; break; } } return isTrue; } <file_sep>/HW2/RestaurantReservations.cpp #include "RestaurantReservations.h" #include "Restaurant.h" #include "Reservation.h" #include <iostream> #include <iomanip> #include <string> #include <vector> #include <fstream> using namespace std; RestaurantReservations::RestaurantReservations() //Default constructor { } void RestaurantReservations::ProcessTransactionFile(string fileName) //ProcessTransactionFile member function ("Main") { string command; //used to read command from input file string rName; //used to read restaurant name from input file string rAddress; //used to read restaurant address from input file string rCity; //used to read restaurant city from input fille string rType; //used to read restaurant type from input file string cName; //used to read customer name from input file to set reservations string cPhone; //used to read customer phone from input file to set reservations int rGroup; //used to read customer group size from input file to set reservations int rTime; //used to read customer time from input file to set reservations int rCapacity; //used to read restuarant capacity size to create a new restaurant int rNum; //used to read reservation number to cancel reservation ifstream infile; //in file stream named infile, used to read text from infile.open(fileName.c_str()); //open file fileName string that was passed from main to member function if(!infile) //used to check if file could be opened, if can't be open display error message { cout << "File \"" << fileName << "\" couldn't open properly! Try again!" << endl; //error message if can't be opened } else //if file can be open then proceed with else portion of code { while(infile >> command) //while infile can read the first word of each line then proceed with while portion of code { if(command == "CreateNewRestaurant") //if command string is the same as string "CreateNewRestaurant" then proceed with if portion else go to else if { infile >> rName >> rAddress >> rCity >> rType >> rCapacity; //read the rest of the same line as command string cout << "CreateNewRestaurant " << rName << " " << rAddress << " " << rCity << " " << rType << " " << rCapacity << endl; //print command format CreateNewRestaurant(rName, rAddress, rCity, rType, rCapacity); //pass rName, rAddress, rCity, rType, rCapacity to member function CreatenewRestaurant } else if(command == "FindTable") //else if command string is the same as string "FindTable" then proceed with else if portion else go to next else if statement { infile >> rCity >> rType >> rGroup >> rTime; //read the rest of the same line as command string cout << "FindTable " << rCity << " " << rType << " " << rGroup << " " << rTime << endl; //print command format FindTable(rCity, rType, rGroup, rTime); } else if(command == "FindTableAtRestaurant") //else if command string is the same as string "FindTableAtRestaurant" then proceed with else if portion else go to next else if statement { infile >> rName >> rGroup; //read the rest of the same line as command string cout << "FindTableAtRestaurant " << rName << " " << rGroup << endl; //print command format FindTableAtRestaurant(rName, rGroup); //pass rName and rGroup to FindTableAtRestaurant member function } else if(command == "MakeReservation") //else if command string is the same as string "MakeReservation" then proceed with else if portion else go to next else if statement { infile >> rName >> cName >> cPhone >> rGroup >> rTime; //read the rest of the same line as command string cout << "MakeReservation " << rName << " " << cName << " " << cPhone << " " << rGroup << " " << rTime << endl; //print command format MakeReservation(rName, cName, cPhone, rGroup, rTime); //pass rName, cName, cPhone, rGroup, and rTime to MakeReservation member function } else if(command == "CancelReservation") //else if command string is the same as string "CancelReservation" then proceed with else if portion else go to next else if statement { infile >> rName >> rNum; //read the read of the same line as command string cout << "CancelReservation " << rName << " " << rNum << "(Canceled Function)" << endl; //print command format however member function was canceled by professor in an email CancelReservation(rName, rNum); //pass rName and rNum to CancelRservation member function } else if(command == "PrintAllRestaurants") //else if command string is the same as string "PrintAllRestaurants" then proceed with else if portion else go to next else if statement { cout << "PrintAllRestaurants" << endl; //print command format cout << "Restaurant Address, City Type Capacity" << endl; //print table header cout << "-------------------------------------------------------------------------------" << endl; //print table header PrintAllRestaurants(); //call PrintAllRestaurant member function } else if(command == "PrintRestaurantReservations") //else if command string is the same as string "PrintRestaurantReservations" then proceed with else if portion else go to final else statement { infile >> rName; //read the rest of the same line as command string cout << "PrintRestaurantReservations " << rName << endl; //print command format PrintRestaurantReservations(rName); //pass variable rName to member function PrintRestaurantReservations } else //if command string doesn't match with any command then command string was invalid { cout << "Incorrect command!" << endl; //print error message for incorrect command } } } infile.close(); //close file "TransactionFile.txt" } void RestaurantReservations::CreateNewRestaurant(string rName, string rAddress, string rCity, string rType, int rCapacity) //member function used to create a new restaurant and add it to database(vector) { Restaurant temp(rName, rAddress, rCity, rType, rCapacity); //create a new Restaurant class named temp and pass variables rName, rAddess, rCity, rType, and rCapacity restaurants.push_back(temp); //push back(add) temp to vector restaurants } void RestaurantReservations::PrintAllRestaurants() //member function used to print all restaurants in restaurants vector { int vectorSize = restaurants.size(); //variable vectorSize set to the size of vector restaurants to use it for for-loop for(int i = 0; i < vectorSize; i++) //for-loop used to print a restaurant line by line { cout << left << setw(21) << restaurants[i].getName() << left << setw(34) << restaurants[i].getAddress() + ", " + restaurants[i].getCity() << left << setw(16) << restaurants[i].getType() << left << setw(8) << restaurants[i].getSeats(0) << endl; //print restaurant name, address, city, type, and capacity line by line } } void RestaurantReservations::FindTable(string rCity, string rType, int rGroup, int rTime) //member function used to find a table with available for all restaurants based on city, restaurant type, reservation group size, and reservation time { int vectorSize = restaurants.size(); //variable vectorSize set to the size of vector restaurants string nameHold; //string nameHold used to hold name of vector restaurants index i's name vector<string> names; //vector used to hold all restaurant names with available criteria passed in int count = 0; //variable count used to help if there's an entry in vector names for(int i = 0; i < vectorSize; i++) //for-loop used to check through vector restaurants { if(rCity == restaurants[i].getCity()) //if passed in variable rCity matches with vector restaurants index i's city then proceed with if portion { if(rType == restaurants[i].getType()) //if passed in variable rType matches with vector restaurants index i's type then proceed with if portion { if(rTime == 5) //if passed in variable rTime matches with 5 then proceed with if portion else go to next else if statement { if(rGroup <= restaurants[i].getSeats(0)) //if passed in variable rGroup is greater than or equal to vector restaurants index i's array availableSeats index 0 { nameHold = restaurants[i].getName(); //set variable nameHold to vector restaurants index i's name names.push_back(nameHold); //push back(add) namedHold to vector names count++; //increment count variable by 1 } } else if(rTime == 6) //else if passed in variable rTime matches with 6 then proceed with if portion else go to next else if statement { if(rGroup <= restaurants[i].getSeats(1)) //if passed in variable rGroup is greater than or equal to vector restaurants index i's array availableSeats index 1 { nameHold = restaurants[i].getName(); //set variable nameHold to vector restaurants index i's name names.push_back(nameHold); //push back(add) nameHold to vector names count++; //increment count variable by 1 } } else if(rTime == 7) //else if passed in variable rTime matches with 7 then proceed with if portion else go to next else if statement { if(rGroup <= restaurants[i].getSeats(2)) //if passed in variable rGroup is greater than or equal to vector restaurants index i's array availableSeats index 2 { nameHold = restaurants[i].getName(); //set variable nameHold to vector restaurants index i's name names.push_back(nameHold); //push back(add) nameHold to vector names count++; //increment count variable by 1 } } else if(rTime == 8) //else if passed in variable rTime matches with 7 then proceed with if portion else go to next else statement { if(rGroup <= restaurants[i].getSeats(3)) //if passed in variable rGroup is greater than or equal to vector restaurants index i's array availableSeats index 3 { nameHold = restaurants[i].getName(); //set variable nameHold to vector restaurants index i's name names.push_back(nameHold); //push back(add) nameHold to vector names count++; //increment count variable by 1 } } else //if rTime doesn't match with 5, 6, 7 or 8 then rTime that was passed in was invalid for the program { cout << "Incorrect time for reservation" << endl; //print error message } } } } int printVector = names.size(); //create a variable named printVector and set it to the size of vector names to be used in the for-loop under if(count > 0) //if count variable is greater than 0 then that means there's a string in the vector names { cout << "You may reserve a table for " << rGroup << " at " << rTime << " pm at:" << endl; //print formatted response for(int i = 0; i < printVector; i++) //for-loop used to print every entry in the vector { cout << names[i] << endl; //print index i in vector names } } else //if count variable equal to or less than 0 then that means there's not entries in the vector print meaning there's no restaurants that fit the criteria { cout << "No restaurant can accommodate such a group at this time, check another time." << endl; //print message indicating there's not restaurant that doesn't fit the criteria } } void RestaurantReservations::FindTableAtRestaurant(string rName, int rGroup) //member function used to find a table at a certain restaurant based on the size of the reservation group, then output times with available seating { int vectorSize = restaurants.size(); //variable vectorsize set to the size of vector restaurants to be used in the for loop int count = 0; //variable used to helped out the available times for seating vector<int> times; //vector times used for to have available times with correct seating for customer for(int i = 0; i < vectorSize; i++) //for-loop used to add available times with correct seating to vector to be used later { if(rName == restaurants[i].getName()) //check if passed in rName is the same as vector restaurants index i's name { for(int j = 0; j < 4; j++) //goes through availableseats array to check capacity { if(rGroup <= restaurants[i].getSeats(j)) //if group size is less than or equal to the capacity in index j of availableseats array { int h = j + 5; //variable h used for times 5:00, 6:00, 7:00, or 8:00 times.push_back(h); //push back(add) variable h to vector times count++; //increase variable count to tell if statement if that there is an available time } } } } int vecPrint = times.size(); //variable vecPrint set to the size of vector times if(count > 0) //if variable count is greater than 0, then that means there's an avaiable times { cout << "You can reserve a table for " << rGroup << " at " << rName << " at "; //print there's an avaiable time for rGroup amount of people at times for(int i = 0; i < vecPrint; i++) //for-loop used to print available times from vector times { cout << times[i] << ":00 pm"; //print time as the format "0:00" if(i < (vecPrint - 1)) //if statement used to print commas inbetween times if multiple times available { cout << ", "; //print comma } } cout << endl; //skip line } else //if there's no available time then print message regarding time avilability { cout << rName << " does not have such availability." << endl; //print message } } void RestaurantReservations::MakeReservation(string rName, string cName, string cPhone, int rGroup, int rTime) //member function used to make a reservation with passed in variables rName, cname, cPhone, rGroup, rTime { int vectorSize = restaurants.size(); //variable vectorsize set to the size of vector restaurants to be used in for-loop for(int i = 0; i < vectorSize; i++) //for-loop used to add reservation to vector { if(rName == restaurants[i].getName()) //if rName variable that was passed in is equal to vector restaurants index i's name then proceed with if portion { restaurants[i].makeReservation(cName, cPhone, rGroup, rTime); //pass in cName, cPhone, rGroup, and rTime in to makeReservation member function from restaurant class } } } void RestaurantReservations::CancelReservation(string rName, long rNum) //member function use was to be used to cancel reservation, but now it s now been removed from the assignment { cout << "Canceled function stated by professor!" << endl; //print message } void RestaurantReservations::PrintRestaurantReservations(string rName) //member function is used to print all the reservations in a certain restaurant indicated by string rname { int vectorSize = restaurants.size(); //variable vectorSize set to size of vector restaurants cout << "Reservation Contact Phone Group Time" << endl; //print table header cout << "--------------------------------------------------" << endl; //print table header for(int i = 0; i < vectorSize; i++) //for-loop used to print all reservations for a certain restaurant { if(rName == restaurants[i].getName()) //if rName matches with vector restaurants index i's name then proceed with if portion { restaurants[i].printReservation(); //call printReservation member function in restaurants class } } } <file_sep>/Lab7/OvernightPackage.h #ifndef OVERNIGHTPACKAGE_H #define OVERNIGHTPACKAGE_H #include "Package.h" #include <iostream> using namespace std; class OvernightPackage : public Package { private: protected: double overnightFee; public: OvernightPackage(); OvernightPackage(string, string, string, string, long, string, string, string, string, long, string, string, double, double, string, double); double calculateCost(); }; #endif <file_sep>/Lab3/lab3_p4.cpp /***************************************************************************************************************************** <NAME> CS 211 2-10-19 *****************************************************************************************************************************/ #include<iostream> #include<iomanip> #include<fstream> #include<vector> using namespace std; struct Person { string firstName; string lastName; string phoneNumber; }; void readFile(vector<Person> &); void printFile(const vector<Person> &); int main() { vector<Person> v; readFile(v); printFile(v); return 0; } void readFile(vector<Person> &v) { Person p; string fN; string lN; string pN; ifstream infile; infile.open("telephoneData.txt"); if(!infile) { cout << "Error opening \"telephoneData.txt\"" << endl; } else { while(infile >> fN >> lN >> pN) { p.firstName = fN; p.lastName = lN; p.phoneNumber = pN; v.push_back(p); } } infile.close(); } void printFile(const vector<Person> &v) { cout << "Name" << setw(20) << "Telephone" << endl; cout << "---------------------------" << endl; int size = v.size(); for(int i = 0; i < size; i++) { cout << setw(7) << left << v[i].firstName << setw(8) << v[i].lastName << setw(10) << right << v[i].phoneNumber << endl; } } <file_sep>/Lab8/lab8-p3.cpp #include <iostream> #include <iomanip> #include <string> #include <vector> using namespace std; int numChars(string, char, int); int main() { string text; char character; int sIndex = 0; int occur; cout << "Please enter a string: "; getline(cin, text); cout << "Please enter a character to search for occurrences: "; cin >> character; occur = numChars(text, character, sIndex); if(occur == 1) { cout << "The character '" << character << "' appears once in string \"" << text << "\""<< endl; } else { cout << "The character '" << character << "' appears " << occur << " times in string \"" << text << "\""<< endl; } return 0; } int numChars(string check, char letter, int index) { int stringSize = check.size(); if(index > stringSize) { return 0; } else if(check[index] == letter) { return 1 + numChars(check, letter, index + 1); } else { return 0 + numChars(check, letter, index + 1); } } <file_sep>/Lab4/Part 2/instructor.h #ifndef INSTRUCTOR_H #define INSTRUCTOR_H #include "course2.h" #include<string> using namespace std; class instructor { private: string firstName; string lastName; char gender; long employeeID; string officeNum; course courses[3]; public: instructor(); instructor(string, string, char, long, string, long, string, int, long, string, int, long, string, int); void setInstructor(string, string, char, long, string, long, string, int, long, string, int, long, string, int); void print() const; }; #endif <file_sep>/HW4/LL.h //This is Elel.h for Class LL #ifndef LL_H #define LL_H #include "LL.h" #include "node.h" #include <iostream> #include <string> using namespace std; class LL { private: node *head; public: LL(); LL(const LL &); ~LL(); void insert(string, string); void searchByName(string); void destroy(); void print(); void reverse(); void removeRecord(string); void updateNumber(string, string); void printReverse(); void insertAtPos(string, string, int); void readFromArrays(string [], string [], int); LL& operator= (const LL &); }; #endif <file_sep>/Lab13/trees.cpp #include "trees.h" #include <iostream> using namespace std; IntBinaryTree::IntBinaryTree() { root = nullptr; } IntBinaryTree::IntBinaryTree(const IntBinaryTree &tree) { root = copyTree(tree.root); } IntBinaryTree::~IntBinaryTree() { destroySubTree(root); } //private void IntBinaryTree::insert(TreeNode *&nodePtr, TreeNode *&newNode) { if(nodePtr == nullptr) { nodePtr = newNode; } else if(newNode->value < nodePtr->value) { insert(nodePtr->left, newNode); } else { insert(nodePtr->right, newNode); } } void IntBinaryTree::destroySubTree(TreeNode *nodePtr) { if(nodePtr) { if(nodePtr->left) { destroySubTree(nodePtr->left); } if(nodePtr->right) { destroySubTree(nodePtr->right); } delete nodePtr; } } void IntBinaryTree::deleteNode(int num, TreeNode *&nodePtr) { if(num < nodePtr->value) { deleteNode(num, nodePtr->left); } else if(num > nodePtr->value) { deleteNode(num, nodePtr->right); } else { makeDeletion(nodePtr); } } void IntBinaryTree::makeDeletion(TreeNode *&nodePtr) { TreeNode *tempNodePtr = nullptr; if(nodePtr == nullptr) { cout << "Cannot delete empty node." << endl; } else if(nodePtr->right == nullptr) { tempNodePtr = nodePtr; nodePtr = nodePtr->left; delete tempNodePtr; } else if(nodePtr->left == nullptr) { tempNodePtr = nodePtr; nodePtr = nodePtr->right; delete tempNodePtr; } else { tempNodePtr = nodePtr->right; while(tempNodePtr->left) { tempNodePtr = tempNodePtr->left; } tempNodePtr->left = nodePtr->left; tempNodePtr = nodePtr; nodePtr = nodePtr->right; delete tempNodePtr; } } void IntBinaryTree::displayInOrder(TreeNode *nodePtr) const //WORKS { if(nodePtr == nullptr) { return; } displayInOrder(nodePtr->left); cout << nodePtr->value << " "; displayInOrder(nodePtr->right); } int IntBinaryTree::countLeafNodes(TreeNode *&nodePtr) //WORKS { int count = 0; if(!nodePtr) { count = 0; } else if(nodePtr->left == nullptr && nodePtr->right == nullptr) { count = 1; } else { if(nodePtr->left) { count += countLeafNodes(nodePtr->left); } if(nodePtr->right) { count += countLeafNodes(nodePtr->right); } } return count; } int IntBinaryTree::getTreeHeight(TreeNode *nodePtr) //WORKS { if(nodePtr == nullptr) { return 0; } else { int lDepth = getTreeHeight(nodePtr->left); int rDepth = getTreeHeight(nodePtr->right); if(lDepth > rDepth) { return(lDepth + 1); } else { return(rDepth + 1); } } } IntBinaryTree::TreeNode *IntBinaryTree::copyTree(TreeNode *nPtr) //SHOULD WORK { if(nPtr == nullptr) { return nullptr; } TreeNode *temp; temp = new TreeNode; temp->value= nPtr->value; temp->left = copyTree(nPtr->left); temp->right = copyTree(nPtr->right); return temp; } IntBinaryTree IntBinaryTree::operator=(const IntBinaryTree &tree) //SHOULD WORK { destroySubTree(root); root = copyTree(tree.root); return *this; } void IntBinaryTree::insertNode(int num) { TreeNode *newNode = nullptr; newNode = new TreeNode; newNode->value = num; newNode->left = newNode->right = nullptr; insert(root, newNode); } bool IntBinaryTree::searchNode(int num) { bool status = false; TreeNode *nodePtr = root; while(nodePtr) { if(nodePtr->value == num) { status = true; } else if(num < nodePtr->value) { nodePtr = nodePtr->left; } else { nodePtr = nodePtr->right; } } return status; } void IntBinaryTree::remove(int num) { deleteNode(num, root); } void IntBinaryTree::displayInOrder() const { displayInOrder(root); } int IntBinaryTree::numLeafNodes() { countLeafNodes(root); } int IntBinaryTree::treeHeight() { getTreeHeight(root); } <file_sep>/Lab3/lab3_p3.cpp /******************************************************************************************* <NAME> CS211 2-8-19 *******************************************************************************************/ #include<iostream> #include<string> #include<sstream> using namespace std; void removeSpace(string); int main() { string userIn; cout << "Please enter a phrase: "; getline(cin, userIn); removeSpace(userIn); return 0; } void removeSpace(string hold) { //string userOut = hold; //int place = userOut.find(" ", 0); //while(place != userOut.npos) //{ //userOut.erase(place, 1); //place = userOut.find(" ", place+1); //} stringstream ss; string holder; ss << hold; hold = ""; while(!ss.eof()) { ss >> holder; hold = hold + holder; } cout << "The resulting phrase is: \"" << hold << "\"" << endl; } <file_sep>/Lab1/lab1_p3.cpp /***************************************************************************************** <NAME> CS 211 1/28/19 *****************************************************************************************/ #include <iostream> #include <iomanip> using namespace std; void minMaxAvg (int &, int &, double &); int main() { int a; int b; double c; cout << "Enter 3 integers: "; cin >> a >> b >> c; minMaxAvg(a, b, c); cout << showpoint << fixed << setprecision(2) << "The average is: " << c << endl; cout << "The min is: " << b << endl; cout << "The max is: " << a << endl; return 0; } void minMaxAvg(int &a1, int &b1, double &c1) { int a = a1; int b = b1; int c = c1; int max = a1; int min = a1; double avg = 0; if (a > b && a > c) { max = a; } else if (b > a && b > c) { max = b; } else if (c > a && c > b) { max = c; } if (a < b && a < c) { min = a; } else if (b < a && b < c) { min = b; } else if (c < a && c < b) { min = c; } avg = (a + b + c) / 3.0; c1 = avg; b1 = min; a1 = max; } <file_sep>/Lab1/lab1_p2.cpp /********************************************************************************** <NAME> CS 211 1-25-19 **********************************************************************************/ #include <iostream> #include <fstream> #include <iomanip> using namespace std; double getEndBalance (double, double , double); int main() { int accNum; string accType; double startBal; double totalDep; double totalWith; double endBal; double holder; const double PREMIUM = 0.05; const double CHOICE = 0.03; const double BASIC = 0.01; ifstream infile; ofstream outfile; infile.open("input.txt"); outfile.open("accountsOut.txt"); if(infile) { cout << "Opened Successfully!" << endl; outfile << "Account Type StartBalance Deposit Withdrawal EndBalance" << endl; outfile << "------------------------------------------------------------------------" << endl; while(infile >> accNum >> accType >> startBal >> totalDep >> totalWith) { if(accType == "Premium") { holder = getEndBalance(startBal, totalDep, totalWith); endBal = (holder * PREMIUM) + holder; outfile << setw(6) << showpoint << fixed << setprecision(2) << accNum << setw(9) << accType << setw(12) << startBal << setw(12) << totalDep << setw(16) << totalWith << setw(16) << endBal << endl; } else if(accType == "Choice") { holder = getEndBalance(startBal, totalDep, totalWith); endBal = (holder * CHOICE) + holder; outfile << setw(6) << showpoint << fixed << setprecision(2) << accNum << setw(9) << accType << setw(12) << startBal << setw(12) << totalDep << setw(16) << totalWith << setw(16) << endBal << endl; } else { holder = getEndBalance(startBal, totalDep, totalWith); endBal = (holder * BASIC) + holder; outfile << setw(6) << showpoint << fixed << setprecision(2) << accNum << setw(9) << accType << setw(12) << startBal << setw(12) << totalDep << setw(16) << totalWith << setw(16) << endBal << endl; } } } else { cout << "Unsuccessfully Opened!" << endl; } cout << "Written to accountsOut.txt" << endl; infile.close(); outfile.close(); return 0; } double getEndBalance(double a, double b, double c) { double balance; balance = (a + b) - c; return balance; } <file_sep>/HW5/HW5-p2.cpp /************************************************************************* Creator: <NAME> Date: 4/30/19 Course: CS 211 Description: This program uses queues to determine how many combinations a 1 character string has, how many combinations a 2 character string has, and how many combinations a 3 character string has. All combinations for 1 character, 2 character, and 3 character strings. *************************************************************************/ #include "dQueue.h" #include <iostream> #include <iomanip> #include <string> using namespace std; int main() { Queue main; //Create a queue named main main.enqueue("A"); //In queue named main, add in to queue "A" main.enqueue("B"); //In queue named main, add in to queue "B" main.enqueue("C"); //In queue named main, add in to queue "C" main.permutations(); //Call permutations function to find combinations return 0; } <file_sep>/HW4/HW4-VN.cpp /****************************************************************************** <NAME> CS 211 4/21/2019 In this program we are using the concept of a linked list to make a database of users and their information. In this program we have to develop functions such as readFromArrays, print, insert, insertAtPos, printReverse, reverse, searchByName. With this program the linked list should be in alpabetically order. ******************************************************************************/ #include "LL.h" #include "node.h" #include <iostream> #include <string> using namespace std; const int SIZE = 3; int main() { string nameArray [SIZE] = {"<NAME>", "<NAME>", "<NAME>"}; string phoneArray [SIZE] = {"337-465-2345", "352-654-1983", "878-635-1234"}; //creating list1 using default constructor LL list1; //reading from array into list 1 cout << "------------------------------------------" << endl; cout << "Reading from arrays into list and printing list1" << endl; list1.readFromArrays(nameArray, phoneArray, SIZE); list1.print(); //adding elements to list1 using insert and insertAtPos cout << "------------------------------------------" << endl; cout << "Adding records to list1 and print list1" << endl; list1.insert("<NAME>", "617-227-5452"); list1.insert("<NAME>", "617-437-5454"); list1.insert("<NAME>" ,"352-654-1983"); list1.insertAtPos("<NAME>", "202-782-1010", 1); list1.insertAtPos("<NAME>", "352-654-2000", 7); list1.insertAtPos("<NAME>", "202-832-1560", 3); list1.insertAtPos("<NAME>", "617-227-5454", 8); list1.insertAtPos("<NAME>", "667-277-1454", 11); list1.print(); //printing list1 in reverse order cout << "------------------------------------------" << endl; cout << "Printing list1 backwards" << endl; list1.printReverse(); //searching for specific entries in list1 cout << "------------------------------------------" << endl; cout << "Searching for specific people in list1" << endl; list1.searchByName("<NAME>"); list1.searchByName("<NAME>"); list1.searchByName("<NAME>"); list1.searchByName("<NAME>"); //updating specific entries in list1 cout << "------------------------------------------" << endl; cout << "Updating records in list1 and printing list" << endl; list1.updateNumber("<NAME>", "989-876-1234"); list1.updateNumber("<NAME>", "345-467-1234"); list1.updateNumber("<NAME>", "202-447-1234"); list1.updateNumber("<NAME>", "345-67-1224"); list1.print(); //creating another list list2 and addin some elements to it cout << "------------------------------------------" << endl; cout << "Adding nodes to list2 and printing list 2" << endl; LL list2; list2.insertAtPos("<NAME>", "617-227-5454", 1); list2.insert("<NAME>", "202-857-1510"); list2.print(); //calling operator = to modify list2 so it is a copy of list1 list2 = list1; //creating another list list3 using copy constructor LL list3(list1); //modify list1 by removing some elements of list1 list1.removeRecord("<NAME>"); list1.removeRecord("<NAME>"); list1.removeRecord("<NAME>"); list1.removeRecord("<NAME>"); //printing list1, list2, and list3 to make sure that a deep copy is performed cout << "------------------------------------------" << endl; cout << "Printing list1 after removing some records" << endl; list1.print(); cout << "------------------------------------------" << endl; cout << "Printing list2 after calling operator=" << endl; list2.print(); cout << "------------------------------------------" << endl; cout << "Printing list3" << endl; list3.print(); //reversing the nodes in list3 cout << "------------------------------------------" << endl; cout << "Printing list3 after reversing it" << endl; list3.reverse(); list3.print(); //searching for a specific person in list3 cout << "------------------------------------------" << endl; cout << "Searching for specific person in list3" << endl; list3.searchByName("<NAME>"); return 0; } <file_sep>/Lab6/lab6.cpp #include "header.h" #include <iostream> using namespace std; int main() { RationalNumber r1(7, 3); RationalNumber r2(3, 9); RationalNumber r3; RationalNumber r4; r3 = r1 - r2; cout << "r3 = " << r3; cout << endl; r3 = r1++; cout << "r3 = " << r3; cout << endl; cout << "r1 = " << r1; cout << endl; cout << "Enter numbers for r4: "; cin >> r4; cout << "r4 = " << r4; cout << endl; return 0; } <file_sep>/Lab5/student.cpp #include "student.h" #include <iostream> #include <string> using namespace std; int Student::totalNumofStudents = 0; int Student::nextStudentID = 10000; Student::Student() : studentID(nextStudentID) { name = "Unknown"; //studentID = nextStudentID; major = "CS"; classification = "undergraduate"; units = 12; tuition = 0; totalNumofStudents++; nextStudentID++; } Student::Student(string theName, string theMajor, string theClassification, int theUnits) : studentID(nextStudentID) { name = theName; //studentID = nextStudentID; major = theMajor; classification = theClassification; units = theUnits; tuition = 0; totalNumofStudents++; nextStudentID++; } Student::~Student() { totalNumofStudents--; } void Student::getData() { cout << endl << endl; cout << "Input name: "; getline(cin, name); cout << "Input major: "; cin >> major; cout << "Input Classification: "; cin >> classification; cout << "Input units: "; cin >> units; // studentID = nextStudentID; } void Student::print() const { cout << endl << endl; cout << "Name: " << name << endl; cout << "Student ID: " << studentID << endl; cout << "Major: " << major << endl; cout << "Classification: " << classification << endl; cout << "Units: " << units << endl; cout << "Tutition: " << tuition << endl; cout << "Total Number of Students: " << totalNumofStudents << endl; cout << "Next Student ID: " << nextStudentID << endl; } <file_sep>/HW3/VN-A3P2.cpp /*************************************************************************** Creator: <NAME> Course: CS211 Date: Match 28, 2019 Homework: Homework Assignement 3 Problem 2 Program Description: This is a program that will compute all permutations of a string given by the user and all permutations will be put in a vector and then all permutations will be printed from said vector. The permute function handles all the computations and combinations for the number of permutations for a string with n characters. (n being a positive intger) ***************************************************************************/ //g++ -std=c++11 FILENAME.cpp (to complie properly) #include <iostream> #include <iomanip> #include <string> #include <vector> using namespace std; void permute(string, int, int, vector<string> &); //Function used to compute permutations of a string int main() { string str1; //Input string vector<string> permutations; //Vector used to hold all permutations of a string int vSize; //Size of vector used later int e; //Last index of str1 cout << endl << "Enter a word to find permutations: "; cin >> str1; e = (str1.size()) - 1; //Gets length of str1 and decrease by 1 permute(str1, 0, e, permutations); //Call permute function and pass input string, starting position, //last index, vector permutations. vSize = permutations.size(); //Set vSize to size of vector permutations //For loop to print all elements inside vector permutations for(int i = 0; i < vSize; i++) { if(i == (vSize - 1)) { cout << permutations[i]; } else { cout << permutations[i] << ", "; } } //cout statement used to print the number of permutations for input string cout << endl << "There is " << vSize << " permutations for string \"" << str1 << "\"" << endl << endl; return 0; } //Function used to compute all permutations and add each computed permutation into vector permutations void permute(string input, int position, int last, vector<string> &permutation) { char hold; //variable used to hold a character in a string if(position == last) { permutation.push_back(input); //Each permutation computed is pushed into vector permutations } else { //For loop to compute each permutation, cycles the characters every position in string for(int i = position; i < input.length(); i++) { hold = input[position]; //Hold character in input[position] input[position] = input[i]; //Set input[position] to input[i] input[i] = hold; //Set input[i] to hold //3 Statements above are used to swap two characters in a string permute(input, (position + 1), last, permutation); //Call permute function(recursive) hold = input[position]; //Hold character in input[position] input[position] = input[i]; //Set input[position] to input[i] input[i] = hold; //Set input[i] to hold //3 Statements above before permute function call are used to swap two characters in a string } } } <file_sep>/HW5/dQueue.cpp //Dynamic Queue #include "dQueue.h" #include <iostream> using namespace std; Queue::Queue() //Default constructor { front = nullptr; //Set front pointer to null rear = nullptr; //Set rear pointer to null amount = 0; //Set amount of elements in queue to 0 } Queue::~Queue() //Destructor { amount = 0; //Set amount of element in queue to 0 destroy(); //Call destroy function to clear queue } void Queue::enqueue(el_t in) //Function used to add elements in to queue { QueueNode *newNode; //Create a newNode to later add in to queue newNode = new QueueNode; //Allocate memory for said newNode newNode->letter = in; //Set newNode's element to in which is a string newNode->next = nullptr; //Set newNode's next node pointer to null if(isEmpty()) //If isEmpty function is true then continue with if statement { //Means there were no elements in queue before front = newNode; //Set the front of the queue to newNode rear = newNode; //set the read of the queue to newNode } else //If isEmpty function is false then contine with else statement { //Means there were at least one element in queue before rear->next = newNode; //Set rear of queue to newNode rear = newNode; } amount++; //Increase counter to indicate number of elements in queue } void Queue::dequeue(el_t &out) //Function used to remove elements from the queue { QueueNode *temp; //Create a pointer named temp if(isEmpty()) //If isEmpty is true then continue with if statement { //Means there is nothing in the queue to take out cout << "Underflow! There is nothing in the queue to dequeue!" << endl; } else //If isEmpty is false then continue with else statement { //Means there is at least one element in the queue to remove from out = front->letter; //Set out to front's element since out is sent by reference temp = front; //Set pointer temp to the front's address front = front->next; //Set Front to next element in queue delete temp; //Deallocate temp to free up memory amount--; //Decrease the counter to indicate number of elements in queue } } void Queue::displayAll() const //Function used to display all elements in the queue { QueueNode *temp; //Create a pointer named temp temp = front; //Set temp to front if(isEmpty()) //If isEmpty is true then continue with if statement { //Means queue is empty, there is nothing to display cout << "Underflow! There is nothing in the queue to print!" << endl; } else //If isEmpty is false then continue with else statement { while(temp != nullptr) //While loop until temp points to null { cout << temp->letter << endl; //Output temp's element temp = temp->next; //Set temp to next element in queue } } cout << endl; } bool Queue::isEmpty() const //Function used to determine if queue is empty or not { if(amount == 0) //Checks if amount if 0 since amount is used to indicate number of elements in queue { return true; } else //If amount is greater than 0 then that means there is an element in queue { return false; } } void Queue::destroy() //Function used to deallocate each node in the queue { QueueNode *temp; //Create a pointer named temp el_t dummy; //Dummy string to trick dequeue function while(isEmpty() != true) //While loop until isEmpty returns true { dequeue(dummy); //Removes a node from the queue one at a time } } void Queue::permutations() //Function used to display all combinations of 1,2,3 character strings { int count1 = 0; //Counter used for main while loop int count2 = 0; //Counter used for secondary while loop string mainHold; //String used to concatenate with string secHold; //String used to concatenate with Queue secondary; //Create a secondary queue for concatenated strings Queue third; //Create a third queue for concatenated strings secondary.enqueue("A"); //Add string "A" secondary.enqueue("B"); //Add string "B" secondary.enqueue("C"); //Add string "C" displayAll(); //Display all elements in main queue, represent combinations of 1 character strings //While loop used for combinations of 2 character strings while(count1 != 9) //There is only 9 combinations for a 2 character string { dequeue(mainHold); //Get front element from main queue count2 = 0; //Reset secondary counter to 0 while(count2 != 3) { secondary.dequeue(secHold); //Get front element from secondary queue third.enqueue(mainHold + secHold); //Concatenate mainHold and secHold strings and put in to third queue secondary.enqueue(secHold);//Put secHold string back in to secondary queue count1++; //Increase main counter count2++; //Decrease secondary counter } enqueue(mainHold); //Put string back in to main queue } third.displayAll(); //Display all elements in third queue while(secondary.isEmpty() != true) //While loop until secondary queue is empty { secondary.dequeue(secHold); //Removes each node from queue } secHold = ""; //Clear secHold string count1 = 0; //Set main counter to 0 //While loop used for combinations of 3 character strings while(count1 != 27) //There is only 27 combinations for a 3 character string { third.dequeue(secHold); //Get front element in third queue, put in to secHold string count2 = 0; //Reset secondary counter to 0 while(count2 != 3) { dequeue(mainHold); //Get front element from main queue secondary.enqueue(secHold + mainHold); //Concatenate mainHold and secHold strings and put in secondary queue enqueue(mainHold); //Put mainHold string back in to main queue count1++; //Increase main counter count2++; //Increase secondary counter } third.enqueue(secHold); //Put secHold string back in to third queue } secondary.displayAll(); //Display all elements in secondary queue } <file_sep>/Lab7/Package.cpp #include "Package.h" #include <iostream> using namespace std; Package::Package() { } Package::Package(string sN, string sA, string sC, string sS, long sZ, string rN, string rA, string rC, string rS, long rZ, string l, string d, double w, double cPO, string iT) { senderName = sN; senderAddress = sA; senderCity = sC; senderState = sS; senderZIPcode = sZ; recipName = rN; recipAddress = rA; recipCity = rC; recipState = rS; recipZIPcode = rZ; label = l; date = d; weight = w; costPerOunce = cPO; insuranceType = iT; } void Package::print() { cout << "Sender Information: " << endl; cout << "Name: " << senderName << endl << "Address: " << senderAddress << ", " << senderCity << " " << senderState << " " << senderZIPcode << endl; cout << "Recipient Information: " << endl; cout << "Name: " << recipName << endl << recipAddress << " " << recipCity << " " << recipState << " " << recipZIPcode << endl; cout << "Package Information: " << label << " " << weight << " " << costPerOunce << " " << insuranceType << endl; } double Package::calculateCost() { double temp; if(insuranceType == "upto1000") { temp = costPerOunce * weight + 5.25; } else if(insuranceType == "upto5000") { temp = costPerOunce * weight + 5.50; } else if(insuranceType == "none") { temp = costPerOunce * weight; } else { cout << "Invalid insurance type!" << endl; } return temp; } /*****************SENDER***********************/ //string Package::getSenderName() //{ //return senderName; //} //string Package::getSenderAddress() //{ //return senderAddress; //} //string Package::getSenderCity() //{ //return senderCity; //} //string Package::getSenderState() //{ //return senderState; //} //long Package::getSenderZIPCode() //{ //return senderZIPcode; //} /****************RECIPIENT*********************/ //string Package::getRecipName() //{ //return recipName; //} //string Package::getRecipAddress() //{ //return recipAddress; //} //string Package::getRecipCity() //{ //return recipCity; //} //string Package::getRecipState() //{ //return recipState; //} //long Package::getRecipZIPCode() //{ //return recipZIPcode; //} /********************SHIPPING**********************/ //string Package::getLabel() //{ //return label; //} //string Package::getDate() //{ //return date; //} //double Package::getWeight() //{ //return weight; //} //double Package::getCostPerOunce() //{ //return costPerOunce; //} //string Package::getInsuranceType() //{ //return insuranceType; //} <file_sep>/README.md # CS-211-Computer-Science-II Taken: Spring 2019 Instructor: <NAME> A continuation of program design and development. Introduction to data structures: stacks, queues, linear lists, trees, and sets. Includes pointers recursion, and implementation and analysis of sorting and searching algorithms. Extensive programming is required. Includes introduction to parallel models and algorithms, problem state space, relational database, and numerical approximation methods. Three hours of lecture. Three hours of laboratory. <file_sep>/Lab6/header.cpp #include "header.h" #include <iostream> using namespace std; RationalNumber::RationalNumber() { numerator = 0; denominator = 1; } RationalNumber::RationalNumber(int a, int b) { numerator = a; denominator = b; } RationalNumber RationalNumber::operator-(const RationalNumber& c) { RationalNumber temp; temp.numerator = (numerator * c.denominator) - (c.numerator * denominator); temp.denominator = denominator * c.denominator; return temp; } RationalNumber operator++(RationalNumber &c, int dummy) { RationalNumber temp; temp = c; c.numerator = c.numerator + c.denominator; return temp; } ostream& operator<<(ostream& os, const RationalNumber& c) { os << c.numerator; os << "/"; os << c.denominator; os << endl; return os; } istream& operator>>(istream& is, RationalNumber& c) { is >> c.numerator; is >> c.denominator; return is; } <file_sep>/Lab9/lab9-p2.cpp #include <iostream> using namespace std; typedef double* doubleptr; int main() { int arraySIZE; do{ cout << "Please enter the amount of desired elements: "; cin >> arraySIZE; if(arraySIZE > 12) { cout << "Input is over 12! There is 12 months in a year." << endl; } else if(arraySIZE < 1) { cout << "Input is under 1! There isn't 0 months in a year." << endl; } } while((arraySIZE > 12) || (arraySIZE < 1)); double *arrayptr = nullptr; arrayptr = new double[arraySIZE]; double hold = 0; for(int i = 0; i < arraySIZE; i++) { cout << "Enter the monthly sales for month " << i + 1 << ": "; cin >> hold; *(arrayptr + i) = hold; } hold = 0; for(int i = 0; i < arraySIZE; i++) { hold += *(arrayptr + i); } cout << "The total sales for the year is: $" << hold << endl; delete [] arrayptr; arrayptr = nullptr; return 0; } <file_sep>/Lab9/lab9-p3.cpp #include "course2.h" #include <iostream> using namespace std; int main() { long ID; string cName; int cCredit; const int SIZE = 3; course *courseptr = nullptr; courseptr = new course[SIZE]; course *hold = nullptr; for(int i = 0; i < SIZE; i++) { hold = new course; cout << "Enter Course ID, Course Name, and Number of Credits: " << endl; cin >> ID >> cName >> cCredit; hold->setCourseNumber(ID); hold->setCourseName(cName); hold->setNumberOfCredits(cCredit); *(courseptr + i) = *hold; delete hold; hold = nullptr; } cout << "Number Name Credits" << endl << "---------------------------------" << endl; for(int i = 0; i < SIZE; i++) { courseptr[i].print(); } delete [] courseptr; delete hold; return 0; } <file_sep>/Lab7/OvernightPackage.cpp #include "OvernightPackage.h" #include "Package.h" #include <iostream> using namespace std; OvernightPackage::OvernightPackage() { } OvernightPackage::OvernightPackage(string sN, string sA, string sC, string sS, long sZ, string rN, string rA, string rC, string rS, long rZ, string l, string d, double w, double cPO, string iT, double oNF) : Package(sN, sA, sC, sS, sZ, rN, rA, rC, rS, rZ, l, d, w, cPO, iT) { overnightFee = oNF; } double OvernightPackage::calculateCost() { double temp; if(insuranceType == "upto1000") { temp = ((costPerOunce + overnightFee) * weight) + 5.25; } else if(insuranceType == "upto5000") { temp = ((costPerOunce + overnightFee) * weight) + 5.50; } else if(insuranceType == "none") { temp = (costPerOunce + overnightFee) * weight; } else { cout << "Invalid insurance type!" << endl; } return temp; } <file_sep>/Lab6/header.h #ifndef HEADER_H #define HEADER_H #include <iostream> using namespace std; class RationalNumber { friend RationalNumber operator++ (RationalNumber&, int); friend ostream& operator<< (ostream&, const RationalNumber&); friend istream& operator>> (istream&, RationalNumber&); private: int numerator; int denominator; public: RationalNumber(); RationalNumber(int, int); RationalNumber operator- (const RationalNumber&); }; #endif <file_sep>/Lab4/Part 2/course2.cpp #include "course2.h" #include "instructor.h" #include <iostream> #include <string> using namespace std; course::course() { courseNumber = 0; courseName = ""; numberOfCredits = 0; } course::course(long cNum, string cName, int numCredits) { courseNumber = cNum; courseName = cName; numberOfCredits = numCredits; } void course::setCourseNumber(long cNum) { courseNumber = cNum; } void course::setCourseName(string cName) { courseName = cName; } void course::setNumberOfCredits(int numCredits) { numberOfCredits = numCredits; } long course::getCourseNumber() const { return courseNumber; } string course::getCourseName() const { return courseName; } int course::getNumberOfCredits() const { return numberOfCredits; } <file_sep>/Lab7/Package.h #ifndef PACKAGE_H #define PACKAGE_H #include <iostream> using namespace std; class Package { private: protected: string senderName; string senderAddress; string senderCity; string senderState; long senderZIPcode; string recipName; string recipAddress; string recipCity; string recipState; long recipZIPcode; string label; string date; double weight; double costPerOunce; string insuranceType; public: Package(); Package(string, string, string, string, long, string, string, string, string, long, string, string, double, double, string); void print(); //double calculateCost(double, double, string); double calculateCost(); //string getSenderName(); //string getSenderAddress(); //string getSenderCity(); //string getSenderState(); //long getSenderZIPCode(); //string getRecipName(); //string getRecipAddress(); //string getRecipCity(); //string getRecipState(); //long getRecipZIPCode(); //string getLabel(); //string getDate(); //double getWeight(); //double getCostPerOunce(); //string getInsuranceType(); }; #endif <file_sep>/HW3/VN-A3P1.cpp /************************************************************************ Creator: <NAME> Course: CS211 Date: Match 28, 2019 Homework: Homework Assignement 3 Problem 1 Program Description: This is a program that searches an array of integers to find an index in the array that with the index also has a matching element. For example given an array {1, 2, 2, 4, 5, 6, 7}, the algorithm will find index 2 with its matching element of 2. ************************************************************************/ //g++ -std=c++11 FILENAME.cpp (to complie properly) #include <iostream> using namespace std; int matchIndex(int [], int, int, int); //Function defintion for algorithm int main() { int arrayA[]= {-20, -15, -10, -8, -7, -6, -5, -3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 15, 16}; //array size of 19 int arrayB[] = {-40, -20, -1, 1, 2, 3, 5, 7, 9, 12}; //array size of 10 int arrayC[] = {-5, -3, 2, 5, 6, 7, 8, 9, 15, 16, 20}; //array size of 11 int arrayD[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; //array size of 10 int direct = 1; // Direction for linear search (0 = left, 1 = neutral, 2 = right) int sizea = sizeof(arrayA) / 4; //size of arrayA int sizeb = sizeof(arrayB) / 4; //size of arrayB int sizec = sizeof(arrayC) / 4; //size of arrayC int sized = sizeof(arrayD) / 4; //size of arrayD //All 4 cout statements are for outputting matching index and element cout << "Array A with its matching index " << matchIndex(arrayA, sizea, (sizea / 2), direct) << endl; cout << "Array B with its matching index " << matchIndex(arrayB, sizeb, (sizeb / 2), direct) << endl; cout << "Array C with its matching index " << matchIndex(arrayC, sizec, (sizec / 2), direct) << endl; cout << "Array D with its matching index " << matchIndex(arrayD, sized, (sized / 2), direct) << endl; return 0; } //function to find matching index and element int matchIndex(int array[], int size, int position, int direction) { int middleIndex = size / 2; //Checks if linear search reached the end of array if((position == size) || (position == 0)) { return -1; //Algorithm couldn't find a matching index and element } //Determines direction for linear search if middleIndex isn't equal to its element else if(direction == 1) //Netural position(Doesn't begin search) { if(middleIndex == array[middleIndex]) //If matching index and element is found { return middleIndex; //Return middleIndex variable } else if(middleIndex < array[middleIndex]) //If middleIndex is less than its element, { //then linear search left of middleIndex return matchIndex(array, size, position, 0); //Changes direction to 0 to indicate left search } else if(middleIndex > array[middleIndex]) //If middleIndex is greater than its element, { //then lienar search right of middleIndex return matchIndex(array, size, position, 2); //Changes direction variable to 2 to indicate right search } } //Linear search left side(middle index to index 0) else if(direction == 0) //Left { if(array[position] != position) //If index is not equal to its element, call matchIndex function(recurisve) { return matchIndex(array, size, position - 1, 0); } else if(array[position] == position) //If index is equal to its element, return the index to main { return position; } } //Linear search right side(middle index to last index of array) else if(direction == 2) //Right { if(array[position] != position) //If index is not equal to its element, call matchIndex function(recursive) { return matchIndex(array, size, position + 1, 2); } else if(array[position] == position) //If index is equal to its element, return the index to main { return position; } } } <file_sep>/HW2/RestaurantReservations.h #ifndef RESTAURANTRESERVATIONS_H #define RESTAURANTRESERVATIONS_H #include "Restaurant.h" #include "Reservation.h" #include <string> #include <vector> using namespace std; class RestaurantReservations { private: vector <Restaurant> restaurants; public: RestaurantReservations(); void ProcessTransactionFile(string); void CreateNewRestaurant(string, string, string, string, int); void PrintAllRestaurants(); void FindTable(string, string, int, int); void FindTableAtRestaurant(string, int); void MakeReservation(string, string, string, int, int); void CancelReservation(string, long); void PrintRestaurantReservations(string); }; #endif <file_sep>/HW5/HW5-p1.cpp /******************************************************************************************* Creator: <NAME> Date: 4/29/2019 Course: CS211 Description: In this program the user will enter a string in to the program and the program will determine if the string is "properly balanced" meaning that there is and equal amount of braces, parentheses and brackets. If the string is not properly balanced and the program will inform the user why it is not balanced such as missing a brace, parenthese, and bracket. *******************************************************************************************/ #include "dStack.h" #include <iostream> #include <string> using namespace std; int main() { Stack s; //Initialize stack to hold ( , ) , [ , ] , { , and } el_t i; //i is a char used as a sentinel value, 'y' to continue or 'n' to end loop string userInput; //string used to hold the user's input while((i != 'n') && (i != 'N')) //keep looping until user enters 'n' or 'N' { cout << "Enter a string: "; getline(cin, userInput); //get input and put it in to string userInput if(s.ProperlyBalanced(userInput)) //if ProperlyBalanced is true, continue if statement cout << "It is properly balanced!" << endl; else //if ProperlyBalanced is false, continue to else statement cout << "It is not properly balanced!" << endl; cout << "Do you want to continue! Y/N: "; cin >> i; //User enters a sentinel calue 'y' or 'n' cin.ignore(); } return 0; } <file_sep>/Lab13/trees.h //tree.h #include <iostream> using namespace std; class IntBinaryTree { private: struct TreeNode { int value; TreeNode *left; TreeNode *right; }; TreeNode *root; void insert(TreeNode *&, TreeNode *&); void deleteNode(int, TreeNode *&); void makeDeletion(TreeNode *&); void destroySubTree(TreeNode *); //implement 4 functions void displayInOrder(TreeNode *) const; int countLeafNodes(TreeNode *&); int getTreeHeight(TreeNode *); TreeNode *copyTree(TreeNode *); public: IntBinaryTree(); IntBinaryTree(const IntBinaryTree &); //implement function ~IntBinaryTree(); void insertNode(int); bool searchNode(int); void remove(int); void displayInOrder() const; //implemnet 3 functions int numLeafNodes(); int treeHeight(); IntBinaryTree operator= (const IntBinaryTree &); }; <file_sep>/HW1/homework1-Restaurant.cpp /******************************************************************************************************************* <NAME> CS 211 Homework Assignment 1 Date: 2/11/2019 This program helps owners of a restaurant to advertise their business by adding their restaurant's name, the location of the restaurant, contact information, and the category of food they serve to a database other restaurants. This program can also be used by users who don't own a restaurant but are hungry and is looking for a restaurant to eat at. The user can search for a restaurant by the type of foods that are served, city where the restaurant is located, name of the restaurant, and by the top rated restaurant in the city. The user can even give a rating to the restaurant based on a five star system. If the restaurant sadly closes, the owner of the restaurant can remove their restaurant listing from the database. *******************************************************************************************************************/ #include<iostream> #include<iomanip> #include<fstream> #include<vector> #include<string> #include<sstream> using namespace std; struct Restaurant { string name; // restaurant name string address; // restaurant street address string city; // restaurant city string state; // restaurant state int zipcode; // restaurant zip code string type; // type of food served string website; // restaurant website float rating; // restaurant rating, a number from 1 to 5 int reviewers; // number of reviewers }; void addListing(vector<Restaurant> &, const Restaurant); // prototype void removeListing(vector<Restaurant> &, const string); // prototype void displayAll(const vector<Restaurant> &); // prototype void findByName(const vector<Restaurant> &, const string); // prototype void findByCriteria(const vector<Restaurant> &, const string, const string); // prototype void rate(vector<Restaurant> &, const string, const float); // prototype void findTopRated(const vector<Restaurant> &, const string); // prototype int main() { vector<Restaurant> restaurants; // initialize vector "restaurants" with sturcture type Restaurant Restaurant temp; // intialize temporary structure to hold a restaurant then send it to vector "restaurants" string fCommand; // used to hold a "command" from reading file string rN; // used to hold the name of the restaurant string rA; // used to hold the address of the restaurant string rC; //used to hold the city of the restaurant string rS; // used to hold the state of the restaurant int rZC; // used to hold the zipcode of the restaurant string rT; // used to hold the type of the restautrant string rW; // used to hold the website of the restaurant float rating = 0.00; // used to set the rating of the restaurant to 0 when adding restaurant to vector first time int reviewers = 0; // used to set the amount of reviewers of the restaurant to 0 when adding restaurant to vector first time float fRating; // used to hold the rating of the restaurant after rating command has been executed string keyword; // used to for the FindByName command due to restaurant not being searched by full name ifstream infile; // initialize input stream to read from file infile.open("RestaurantsTrans.txt"); //open file "RestaurantsTrans.txt" if(!infile) //checks to file "RestaurantsTrans.txt" has opened properly { cout << "File \"RestaurantsTrans.txt\" couldn't open properly! Try again!" << endl; // output message if file doesn't open properly } else { while(infile >> fCommand) // checks to see if infile can read the first entry for each row of text, if so take first entry and put in to string fCommand { if(fCommand == "AddListing") //if fCommand is equal to "AddListing" then proceed with if statement, if false go to next else if statement { infile >> rN >> rA >> rC >> rS >> rZC >> rT >> rW; // set every entry after first entry to variables rN, rA, rC, rS, rZC, rT, and rW temp.name = rN; // set rN to name variable in temporary structure temp.address = rA; // set rA to address variable in temporary structure temp.city = rC; // set rC to city variable in temporary structure temp.state = rS; // set rS to state variable in temporary structure temp.zipcode = rZC; // set rZC to zipcode variable in temporary structure temp.type = rT; // set rT to type varible in temporary structure temp.website = rW; // set rW to website variable in temporary structure temp.rating = rating; // set rating which was set 0 to rating variable in temporary structure temp.reviewers = reviewers; // set reviewerw which was set 0 to reviewers variable in temporary structure addListing(restaurants, temp); // call function addListing passing vector restaurants and temporary structure } else if(fCommand == "RemoveListing") //if fCommand is equal to "RemoveListing" then proceed with else if statement, if false go to next else if statement { infile >> rN; // set next entry in row to variable rN removeListing(restaurants, rN); // call function removeListing and pass vector restaurants and variable rN } else if(fCommand == "DisplayAll") //if fCommand is equal to "DisplayAll" then proceed with else if statement, if false go to next else if statement { displayAll(restaurants); //call displayAll function and passing vector restaurants } else if(fCommand == "FindByName") //if fCommand is equal to "FindByName" then proceed with else if statement, if false go to next else if statement { infile >> keyword; // set next entry in row to variable keyword findByName(restaurants, keyword); // call function findByName passing vector restaurants and variable keyword } else if(fCommand == "FindByCriteria") //if fCommand is equal to "FindByCriteria" then prooceed with else if statement, if false go to next else if statement { infile >> rC >> rT; // set every entry after first entry to variables rC and rT findByCriteria(restaurants, rT, rC); // call function findByCriteria passing vector restaurants, variable rT, and variable rC } else if (fCommand == "Rate") // if fCommand is equal to "Rate" then proceed with else if statement, if false go to next else if statement { infile >> rN >> fRating; // set every entry after first entry to variables rN and fRating rate(restaurants, rN, fRating); // call function rate passing vector restaurants, variable rN, and variable fRating } else if(fCommand == "FindTopRated") // if fCommand is equal to "FindTopRated" then proceed with else if statement, if false go to next statement { infile >> rC; // set entry after first entry to variable rC findTopRated(restaurants, rC); // call function findTopRated passing vector restaurants and variable rC } else // used as a default statement if fCommand is not equal to anything { cout << "wrong command" << endl; // output error message if fCommand is not equal to anything } } } infile.close(); // close file "RestaurantsTrans.txt" return 0; } void addListing(vector<Restaurant> &restaurants, const Restaurant temp) // function gets passed with vector restaurants and structure temp, function is used to add structure temp to the end of vector restaurants, to "build" database of restaurants { restaurants.push_back(temp); } void removeListing(vector<Restaurant> &restaurants, const string removeName) // function gets passed vector restaurants and string removemName, function is used to remove a restaurant from the database { int falseSearch = 0; // variable used to test if loop found a restaurant const int SIZE = restaurants.size(); // size of vector restaurants set to variable SIZE cout << "RemoveListing " << removeName << endl; // prints out the command for(int i = 0; i < SIZE; i++) // loops until variable i is equal to variable SIZE, loop is used to find a restaurant based on string removeName and remove said restaurant from the database { string rRN = restaurants[i].name; // initialize string rRN and set it to the name variable of index i if(rRN == removeName) // if rRN is equal to string removeName, continue if statement { restaurants.erase(restaurants.begin() + i); // erase the index which is the addition of the beginning of the vector and variable i falseSearch += 1; // increment falseSearch by 1 } } if(falseSearch == 0) // if falseSearch is equal to 0, which means the loop couldn't find the restaurant and couldn't increment falseSearch { cout << "No such restaurant exists" << endl << endl; // print out and error message } } void displayAll(const vector<Restaurant> &restaurants) // function gets passed with vector restaurants, the function is used to display all restaurants in the vector { const int size = restaurants.size(); // the size of the vector restaurants is put in the variable size cout << "Restaurant City Type Rating Reviewers" << endl; // prints out a table format cout << "---------------------------------------------------------------------" << endl; // prints out the divider between the table and the data for(int i = 0; i < size; i++) // this loops until variable i is equal to variable size, loop is used to print out each structure in the vector index by index and correctly formatted { cout << setw(20) << left << restaurants[i].name << setw(13) << left << restaurants[i].city << setw(11) << left << restaurants[i].type << setw(8) << left << fixed << setprecision(2) << restaurants[i].rating << setw(17) << left << restaurants[i].reviewers << endl; // prints out the data of a restaurant in index i in the vector array } cout << endl; // skips line } void findByName(const vector<Restaurant> &restaurants, const string restaurantName) // function gets passed with vector restaurants and string restaurantName, the function is used to find a restaurant regardless of full name or not { int falseSearch = 0; // variable used to test if loop found a restaurant const int SIZE = restaurants.size(); // size of vector restaurant is set in to variable SIZE cout << "FindByName " << restaurantName << endl; // print out command for(int i = 0; i < SIZE; i++) // loops until variable i is equal to variable SIZE, loop is used to find a restaurant based on the string restaurantName given by the command and print out said restaurant { string rN = restaurants[i].name; // initialze string rN and set it to index i's variable name in the restaurants vector if(rN.find(restaurantName) != rN.npos) // if the find member function can find restaurantName in string rN before the end of string rN continue with if statement { cout << restaurants[i].name << ", " << restaurants[i].type << endl; // print out the name and type of index i in vector restaurants cout << restaurants[i].address << ", " << restaurants[i].city << " " << restaurants[i].state << " " << restaurants[i].zipcode << endl; // print the address, city, state, and zipcode of index i in vector restaurants cout << restaurants[i].website << endl; // print out the websitr of index i in vector restaurants cout << "rating: " << restaurants[i].rating << " (" << restaurants[i].reviewers << " reviews)" << endl << endl; // print out the rating and amount of reviewers of index i in vector restaurants falseSearch += 1; // increment falseSearch by 1 } } if(falseSearch == 0) // if falseSearch is equal to 0 that means the loop couldn't find the restaurantName and couldn't increment falseSearch { cout << "No such restaurant exists" << endl << endl; // print out error message } } void findByCriteria(const vector<Restaurant> &restaurants, const string city, const string type) // function get passed with vector restaurants, string city, and string type, the function is used to find a restaurant based on city and type { int falseSearch = 0; // variable used to test if loop found a restaurant const int SIZE = restaurants.size(); // size of vector restaurant is set in to variable SIZE cout << "FindByCriteria " << type << " " << city << endl; // print out command for(int i = 0; i < SIZE; i++) // loops until variable i is equal to variable SIZE, loop is used to find a restaurant based on the string city and string type given and print out said restaurant(s) with correct city and type { string rC = restaurants[i].city; // initialize rC and set to index i's variable city in the vector restaurants string rT = restaurants[i].type; // initialize rT and set to index i's variable type in the vector restaurants if((rT == type) && (rC == city)) // if rT compared to string type is true and rC compared to string city is also true, continue with if statement { cout << restaurants[i].name << endl; // print out the name of index i in vector restaurants cout << restaurants[i].address << ", " << restaurants[i].city << " " << restaurants[i].state << " " << restaurants[i].zipcode << endl; // print out the address, city, state, and zipcodde of index i in vector restaurants cout << restaurants[i].website << endl; // print out the website of index i in vector restaurants cout << "rating: " << restaurants[i].rating << " (" << restaurants[i].reviewers << " reviews)" << endl << endl; // print out the rating and amount of reviewers of index i in vector restaurants falseSearch += 1; // increment falseSearch by 1 } } if(falseSearch == 0) // if falseSearch is equal to 0 that means the loops couldn't find the restaurant based on string city and string type { cout << "No such restaurant exists" << endl << endl; //print out error message } } void rate(vector<Restaurant> &restaurants, const string name, const float ratingN) // function get passed with vector restaurants, string name, and float ratingN { int falseSearch = 0; // variable used to test if loop could find a restaurant and rate const int SIZE = restaurants.size(); // size of vector restaurant is set in to variable SIZE cout << "Rate " << name << " " << ratingN << endl; // print out comamnd if((ratingN < 1) || (ratingN > 5)) // test if ratingN is not in the range of 1 to 5, if true then continue if statement, if false then go to else statement { cout << "Rating should be a number 1 to 5" << endl; // print out rating out of range message } else { for(int i = 0; i < SIZE; i++) // loops until variable i is equal to SIZE, loop is used to calculate the rating of each restaurant with the given string name and float ratingN by the command. { string rN = restaurants[i].name; // initialize rN and set to index i's variable name in the vector restaurants if(rN == name) // test rN is equal to string name { restaurants[i].reviewers = restaurants[i].reviewers + 1; // index i's variable reviewers is equal to index i's variable reviewers + 1, increments by 1 each time it loops restaurants[i].rating = ((restaurants[i].rating * (restaurants[i].reviewers - 1)) + ratingN)/restaurants[i].reviewers; // calculates the actual rating by multiplying rating with reviews minus 1, then add ratingN, then divde by reviewers } falseSearch += 1; // increment falseSearch by 1 } if(falseSearch == 0) // if falseSearch is equal to 0 that means the loop couldn't find the restaurant with the given string name and couldn't increment falseSearch { cout << "No rating can be given due to no such restaurant existing" << endl << endl; // print out error message } } } void findTopRated(const vector<Restaurant> &restaurants, const string city) // function get passed with vector restaurants and string city, function is used to find the top rated restaurant in the city regardless of type { int falseSearch = 0; // variable used to test if loop could find a restaurant in the city given Restaurant temp; // initialize a Restaurant structure named temp to hold the largest rating restaurant const int SIZE = restaurants.size(); // size of vector restaurant is set in to variable SIZE cout << "FindTopRated " << city << endl; // print out command for(int i = 0; i < SIZE; i++) // loops until variable i is equal to SIZE, this loops keeps looping until it finds the first restaurant that is in the city provided, breaks out of this loop when found { if(restaurants[i].city == city) // if index i's variable city is equal to string city, if true then continue if statement { temp = restaurants[i]; // set index i in to temp structure falseSearch = 1; // set falseSearch to 1 } if(falseSearch == 1) // break out the for loop when falseSearch is equal to 1 { break; } } for(int i = 0; i < SIZE; i++) // loops until variable i is equal to SIZE, this loop compares index i and temp structure, and if index is greater than temp structure, index is set to temp structure { if(temp.city == restaurants[i].city) // if variable city in temp structure is equal to variable city in index i of vector restaurants then continue if statement { if(temp.rating <= restaurants[i].rating) // if variable rating in temp structure is less than variable rating in index i of vector restaurants then continue if statement { temp = restaurants[i]; // set index i of vector restaurants to temp structure to be compared with other index i when looped again } } } if(falseSearch == 0) // if falseSearch is equal to 0 then continue with if statement, if false go to else statement, means that the loops couldn't find a top rated restaurant in the city provided { cout << "Cannot find the top rated restaurant in " << city << endl; // print out error message } else { cout << temp.name << ", " << temp.type << endl; // print out temp structure's variable name and type cout << temp.address << ", " << temp.city << " " << temp.state << " " << temp.zipcode << endl; // print out temp structure's variable address, city, state, and zipcode cout << temp.website << endl; // print out temp structure's variable website cout << "rating: " << temp.rating << " (" << temp.reviewers << " reviews)" << endl << endl; // print out temp structure's variable rating and amount of reviewers } } <file_sep>/HW5/dStack.h #ifndef DSTACK_H #define DSTACK_H #include <iostream> using namespace std; typedef char el_t; class Stack { private: struct StackNode //Node that hold information { el_t element; StackNode *next; //Points to next node }; StackNode *top; //Points to top of the stack, a node public: Stack(); ~Stack(); void push(el_t); void pop(el_t &); void displayAll() const; bool isEmpty() const; void destroy(); bool ProperlyBalanced(string); }; #endif <file_sep>/Lab8/lab8-p2.cpp #include <iostream> #include <iomanip> using namespace std; int multiply(int, int); int main() { int x; int y; int total; cout << "Enter integer x: "; cin >> x; cout << "Enter integer y: "; cin >> y; total = multiply(x, y); cout << x << " times " << y << " equals " << total << endl; return 0; } int multiply(int a, int b) { if(b == 1) { return a; } else if(b == 0) { return 0; } else { return a + multiply(a, (b - 1)); } } <file_sep>/HW2/Reservation.h //This is Reservation.h #ifndef RESERVATION_H #define RESERVATION_H #include <iostream> #include <string> using namespace std; class Reservation { private: long reservationNum; //const string contactName; string contactPhone; int groupSize; int reservationTime; public: Reservation(); Reservation(string, string, int, int); //void print() const; long getResNum() const; string getConName() const; string getConPhone() const; int getGroupSize() const; int getResTime() const; static long nextReservationNum; }; #endif <file_sep>/Lab12/sQueue.cpp //Static Queue #include "sQueue.h" #include <iostream> using namespace std; Queue::Queue() { for(int i = 0; i < MAX; i++) { Arr[i] = -1; } front = -1; rear = -1; amount = 0; } void Queue::enqueue(el_t in) { if(isEmpty()) { front = 0; amount++; Arr[front] = in; rear = 0; } else if(isFull()) { cout << "Queue is Full. Can't queue in " << in << "." << endl; } else { rear++; if((rear == MAX) && (amount != MAX)) { rear = 0; Arr[rear] = in; amount++; } else { Arr[rear] = in; amount++; } } } void Queue::dequeue(el_t &out) { if(isEmpty()) { cout << "The queue is empty! Can't dequeue anything!" << endl; } else { out = Arr[front]; Arr[front] = -1; front++; if(front == MAX) { front = 0; amount--; } else { amount--; } } } bool Queue::isFull() const { if(amount == MAX) { return true; } else { return false; } } bool Queue::isEmpty() const { if(amount == 0) { return true; } else { return false; } } void Queue::displayAll() const { if(isEmpty()) { cout << "Queue is empty! Can't print anything!" << endl; } else if(rear < front) { for(int i = front; i < MAX; i++) { cout << Arr[i] << endl; } for(int i = 0; i <= rear; i++) { cout << Arr[i] << endl; } } else { for(int i = front; i <= rear; i++) { cout << Arr[i] << endl; } } //cout << "Test print array" << endl; //for(int i = 0; i < MAX; i++) //{ //cout << Arr[i] << " "; //} //cout << endl; }
8f714265032c8444e3b33dded325ac79e3ece8c4
[ "Markdown", "C++" ]
64
C++
VictorNguyen031900/Computer-Science-II
a440c189e05b6c3aa6d6bca08facc907c4ae981b
dd14a0f20d27432a08ad5851c9396a9ed5a285ea
refs/heads/master
<file_sep># Travelogue iOS App Development 2 Final Project <file_sep>// // EntryCoreData.swift // Travelogue // // Created by <NAME> on 7/26/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import CoreData @objc(Entry) public class Entry: NSManagedObject { var date: Date? { get { return rawDate as Date? } set { rawDate = newValue as NSDate? } } var image: UIImage? { get { if let image = rawImage as Data? { return UIImage(data: imagee) } return nil } set { if let imagee = newValue { rawImage = UIImagePNGRepresentation(imagee) as NSData? } } } convenience init?(title: String?, descript: String?, date: Date?, image: UIImage?) { let appDel = UIApplication.shared.delegate as? AppDelegate guard let managedContext = appDel?.persistentContainer.viewContext else { return nil } self.init(entity: Entry.entity(), insertInto: managedContext) self.title = title self.descript = descript self.date = date self.image = image } } <file_sep>// // TripsViewController.swift // Travelogue // // Created by <NAME> on 7/26/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import CoreData class TripsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } var trips: [Trip] = [] func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return trips.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "tripCell", for: indexPath) if let cell = cell as? TripsTableViewCell{ let trip = trips[indexPath.row] cell.tripTitle.text = trip.title cell.tripDescription.text = trip.descript } return cell } func updateDocumentsArray() { trips = category?.trips?.sortedArray(using: [NSSortDescriptor(key: "name", ascending: true)]) as? [Trip] ?? [Trip]() } func deleteDocument(at indexPath: IndexPath) { let trip = tripss[indexPath.row] if let managedObjectContext = document.managedObjectContext { managedObjectContext.delete(document) do { try managedObjectContext.save() self.trips.remove(at: indexPath.row) TripsTableView.deleteRows(at: [indexPath], with: .automatic) } catch { alertNotifyUser(message: "Delete failed.") documentsTableView.reloadData() } } } /* // 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.destinationViewController. // Pass the selected object to the new view controller. } */ }
598853d0df3588c17c7b9c931ae37a8a3fd3cd7c
[ "Markdown", "Swift" ]
3
Markdown
djwwx7/Travelogue
b3884f2718adc5239c63baaa1ea1f240c70efa62
f732812133559e1386b611d2238d9cb73e2b78c0
refs/heads/main
<repo_name>Ro1984Bi/nextcrud<file_sep>/src/pages/edit/[id].js import TaskFormPage from "../task"; export default TaskFormPage;<file_sep>/src/context/taskContext.js import { createContext, useContext, useState } from "react"; import { v4 as uuid } from "uuid"; export const TaskContext = createContext() export const useTasks = () => useContext(TaskContext) export const TaskProvider = ({children}) => { const [tasks,setTasks] = useState([{id: "1", title: "first task", description: "some"}, ]); const createTask = (title, description) => { setTasks([...tasks, {title, description, id: uuid() }]) } const updateTask = (id, updatedTask) => { setTasks([...tasks.map(task => task.id === id ? {...task, ...updatedTask } : task ),]) } const deleteTask = id => setTasks([...tasks.filter(task => task.id !== id)]) return ( <TaskContext.Provider value={{tasks, createTask, updateTask, deleteTask}}> {children} </TaskContext.Provider> ) }
936b5f6ffd909be769f8181f2f7e62b238d8d9cb
[ "JavaScript" ]
2
JavaScript
Ro1984Bi/nextcrud
46fd4f8c1ee74a62e8bfe105408a8abf13914155
4243bcd4c8ff4eea801db437ed7e151ae0b110fd
refs/heads/master
<file_sep>from random import choice from datetime import datetime GAME_CHOICES = {'r': 'Rock', 'p': "Paper", 's': "Scissors"} overall_results = {'user': 0, 'system': 0} POLICY = {('p', 'r'): 'p', ('p', 's'): 's', ('r', 's'): 'r'} result = {'user': 0, 'system': 0} def find_winner(user, system): if user == system: print('Equal') return None winner = POLICY[ tuple(sorted([user, system])) ] return 'user' if winner == user else 'system' def update_results(winner): if winner is None: return result[winner] += 1 print('user:{} \t system:{} \t {} won!'.format(result['user'], result['system'], winner)) def rps(): global count users_choice = input('Enter your choice \n (r or p or s):') if users_choice == '0': return if users_choice not in GAME_CHOICES.keys(): print('Please enter a valid choice!') return rps() count += 1 systems_choice = choice(list(GAME_CHOICES.keys())) winner = find_winner(users_choice, systems_choice) update_results(winner) if count < 3: rps() elif count == 3: if result['user'] > result['system']: overall_results['user'] += 1 elif result['system'] > result['user']: overall_results['system'] += 1 result['user'] = 0 result['system'] = 0 print('overall results up to now \n user:{} \t system:{}'.format(overall_results['user'], overall_results['system'])) cntinue = input('Game finished. Wanna play again? (y/n) :') if cntinue == 'y': count = 0 rps() else: return begin_time = datetime.now() print('-> Enter 0 in case you want to exit') count = 0 rps() delta = str(datetime.now() - begin_time) print('You played for :', delta.split(':')[1] + ':' + delta.split(':')[2].split('.')[0]) <file_sep># Rock-Paper-Scissors A Python script to play rock-paper-scissors with the computer.
0affa6a9583c0f16a3cb1e49f17f1fb2e3451a8f
[ "Markdown", "Python" ]
2
Python
kingsrock704/Rock-Paper-Scissors-1
ff01ebf3d2ba9c4179eb6d2b7cd425261f867c89
dbf2c5c653c5c1d0adcb405269db70a34436a635
refs/heads/master
<file_sep>package io.everitoken.sdk.demo.tutorialapp; import java.util.Arrays; import java.util.Map; import io.everitoken.sdk.java.EvtLink; import io.everitoken.sdk.java.PublicKey; import io.everitoken.sdk.java.abi.EveriPayAction; import io.everitoken.sdk.java.apiResource.Info; import io.everitoken.sdk.java.dto.NodeInfo; import io.everitoken.sdk.java.exceptions.ApiResponseException; import io.everitoken.sdk.java.param.NetParams; import io.everitoken.sdk.java.param.RequestParams; import io.everitoken.sdk.java.param.TestNetNetParams; import io.everitoken.sdk.java.provider.KeyProvider; import io.everitoken.sdk.java.provider.SignProvider; import io.everitoken.sdk.java.service.TransactionConfiguration; import io.everitoken.sdk.java.service.TransactionService; public class EveriPayExample { public static void main(String[] args) { // ============= 客戶端程式碼,例如使用者手機 ================================= String uniqueLinkId = EvtLink.getUniqueLinkId(); // 隨機生成安全的LinkId int symbolId = 20; // 通證ID int maxAmount = 100; // 最大支付額度 NetParams netParams = new TestNetNetParams(); // 測試網節點 EvtLink evtLink = new EvtLink(netParams); // 建立EvtLink例項,並將其於測試網繫結 // 用通證ID,LinkId和最大支付額來定義EveriPayParam EvtLink.EveriPayParam everiPayParam = new EvtLink.EveriPayParam(symbolId, uniqueLinkId, maxAmount); // 使用相應私鑰用於之後生成相應簽名 KeyProvider keyProvider = KeyProvider.of("<KEY>"); // 生成用於支付的evtLink String payText = evtLink.getEvtLinkForEveriPay(everiPayParam, SignProvider.of(keyProvider)); // ============= 終端程式碼,例如掃碼槍 ==================================== EveriPayAction action = EveriPayAction.of( payText, "0.00001 S#20", // 支付金額 "EVT8aNw4NTvjBL1XR6hgy4zcA9jzh1JLjMuAw85mSbW68vYzw2f9H" // 收款方 ); try { NodeInfo nodeInfo = (new Info()).request(RequestParams.of(netParams)); TransactionService transactionService = TransactionService.of(netParams); TransactionConfiguration trxConfig = TransactionConfiguration.of(nodeInfo, 1000000, PublicKey.of("<KEY>"), true, null); Map<String, String> rst = transactionService.pushEveriPayAction(trxConfig, action, keyProvider); System.out.println(rst); } catch (ApiResponseException ex) { System.out.println(ex.getRaw()); } } } <file_sep>package io.everitoken.sdk.demo.tutorialapp; import java.util.List; import io.everitoken.sdk.java.Address; import io.everitoken.sdk.java.Api; import io.everitoken.sdk.java.Asset; import io.everitoken.sdk.java.dto.TokenDomain; import io.everitoken.sdk.java.dto.TransactionDetail; import io.everitoken.sdk.java.exceptions.ApiResponseException; import io.everitoken.sdk.java.param.NetParams; import io.everitoken.sdk.java.param.PublicKeysParams; import io.everitoken.sdk.java.param.TestNetNetParams; import io.everitoken.sdk.java.param.TransactionDetailParams; public class ApiExample { public static void main(String[] args) { NetParams netParams = new TestNetNetParams(); Api api = new Api(netParams); try { getSuspendedProposalByName("newProposal-4"); // 得到賬戶餘額 List<Asset> res = api.getFungibleBalance( Address.of("<KEY>") ); res.forEach(asset -> System.out.println(asset.toString())); // 得到 token list final PublicKeysParams publicKeysParams = new PublicKeysParams( new String[]{"<KEY>"}); List<TokenDomain> ownedTokens = api.getOwnedTokens(publicKeysParams); ownedTokens.forEach(o -> System.out.println(o.getName())); } catch (ApiResponseException ex) { System.out.println(ex.getRaw()); } } static TransactionDetail getTransactionDetailById(String trxId) throws ApiResponseException{ NetParams netParams = new TestNetNetParams(); Api api = new Api(netParams); return api.getTransactionDetailById(new TransactionDetailParams(trxId)); } static void getSuspendedProposalByName(String name) throws ApiResponseException { NetParams netParams = new TestNetNetParams(); String suspendedProposal = new Api(netParams).getSuspendedProposal(name); System.out.println(suspendedProposal); } } <file_sep># everiToken SDK Tutorial App This repo is a bootstrap repository, it has already included the [evt4j](https://github.com/everitoken/evt4j) as a dependency. You can start interacting with the *sdk* immediately. Please also make sure to use a simulator with Android 9 (Api level 28) <file_sep>package io.everitoken.sdk.demo.tutorialapp; import io.everitoken.sdk.java.PrivateKey; import io.everitoken.sdk.java.PublicKey; public class KeyExample { public static void main(String[] args) { PrivateKey privateKey = createPrivateKey(); PublicKey publicKey = getPublicKeyFromPrivateKey(privateKey); String wif = exportPrivateKey(privateKey); System.out.println(wif); // 輸出私鑰 System.out.println(publicKey.toString()); // 輸出公鑰 } public static PrivateKey createPrivateKey() { return PrivateKey.randomPrivateKey(); } public static PublicKey getPublicKeyFromPrivateKey(PrivateKey privateKey) { return privateKey.toPublicKey(); } public static String exportPrivateKey(PrivateKey privateKey) { return privateKey.toWif(); } }
25b9749addbfc6b40a0a963a54846c609fa6fdd5
[ "Markdown", "Java" ]
4
Java
everitoken/everitoken-sdk-tutorialapp
f561953edd39f9be6952c82732443555e259576a
9e7892514bc12d9533488d14cc1810f1f301ad17
refs/heads/master
<repo_name>Luofengyu/frontClassProject<file_sep>/Objs/cartOBJ.js /** * Created by hasee on 2016/12/21. */ var mongo = require("mongoose"); var Schema = mongo.Schema, ObjectId = Schema.ObjectId; var cartSchema = new Schema({ product_id:{type: String}, imageData:{type: String}, name:{type: String}, info:{type: String}, price:{type: String}, number:{type: Number}, user_id:{type: String} }); mongo.model("cart",cartSchema); var cart = mongo.model("cart"); module.exports = cart;<file_sep>/public/js/controllers/customer.js console.log("i'm in"); app.controller("customerCtrl",['$scope','$cookieStore', function ($scope,$cookieStore) { $cookieStore.put("login",true); $scope.aaaa="111111"; }] )<file_sep>/Objs/productionObj.js /** * Created by hasee on 2016/12/14. */ var mongo = require("mongoose"); var Schema = mongo.Schema, ObjectId = Schema.ObjectId; var productSchema = new Schema({ name:{type: String}, number:{type: String}, price:{type: String}, imgData:{type: String}, shop_id:{type: String}, info:{type: String} }); mongo.model("production",productSchema); var Production = mongo.model("production"); module.exports = Production;<file_sep>/public/js/controllers/storeCtroller.js /** * Created by hasee on 2016/12/20. */ app.controller("storeCtrl", ["$scope", '$cookieStore','$http', function ($scope, $cookieStore, $http) { $scope.user = $cookieStore.get("user"); if($scope.user.role == "customer"){ $scope.userRight = true; }else { $scope.userRight = false; $http({ url: 'http://localhost:3000/shop/infomation', method: 'GET', data: {"user_id":$scope.user._id} }).success(function (res, header, config, status) { //响应成功 if(res.status == "success"){ $scope.shop = res.data[0] $cookieStore.put("shop",$scope.shop); }else{ console.log(res.status) } }).error(function (data, header, config, status) { console.log("error") }) } }]); <file_sep>/public/js/controllers/orderCtroller.js /** * Created by hasee on 2016/12/23. */ app.controller("orderCtrl", ["$scope", "$state", "$cookieStore","$http", function($scope, $state, $cookieStore,$http){ //获取已有的商品列表 var order_id = $cookieStore.get("order_id"); console.log(order_id); $http({ url: 'http://localhost:3000/get/order', method: 'POST', data: {"_id": order_id} }) .success(function (res, header, config, status) { //响应成功 if(res.status == "success"){ // 商品列表 $scope.products = res.data[0].products; $scope.user = res.data[0].user; $scope.totalPrice= res.data[0].total; }else{ alert("订单创建有误!"); console.log(res.status); } }) .error(function (data, header, config, status) { console.log("error") }); }]);<file_sep>/Objs/shopObj.js /** * Created by hasee on 2016/12/14. */ var mongo = require("mongoose"); var Schema = mongo.Schema, ObjectId = Schema.ObjectId; var shopSchema = new Schema({ company:{type: String}, Email:{type: String}, website:{type: String}, subject:{type: String}, user_id:{type: String}, message:{type: String} }); mongo.model("shop",shopSchema); var Shop = mongo.model("shop"); module.exports = Shop;<file_sep>/public/js/app/router-config.js /** * Created by hasee on 2016/12/6. */ angular.module('app').run( [ '$rootScope', '$state', '$stateParams', function ($rootScope, $state, $stateParams) { $rootScope.$state = $state; $rootScope.$stateParams = $stateParams; } ] ) .config( [ '$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) { $urlRouterProvider .otherwise('/customer/login'); $stateProvider .state('customer', { abstract: true, url: '/customer', templateUrl: 'views/blank.html', controller: 'navCtrl', resolve: { deps: ['$ocLazyLoad', function ($ocLazyLoad) { return $ocLazyLoad.load(['js/controllers/navCtroller.js']); }] } }) .state('customer.login', { url: '/login', templateUrl: 'views/customer_login.html', controller: 'loginCtrl', resolve: { deps: ['$ocLazyLoad', function ($ocLazyLoad) { return $ocLazyLoad.load(['js/controllers/loginCtroller.js']); }] } }) .state('customer.register', { url: '/register', templateUrl: 'views/customer_register.html', controller: 'registerCtrl', resolve: { deps: ['$ocLazyLoad', function ($ocLazyLoad) { return $ocLazyLoad.load(['js/controllers/registerCtroller.js']); }] } }) .state('customer.home', { url: '/home', templateUrl: 'views/index_home.html', controller: 'homeCtrl', resolve: { deps: ['$ocLazyLoad', function ($ocLazyLoad) { return $ocLazyLoad.load(['js/controllers/homeCtroller.js']); }] } }) .state('productionInfo', { url: '/productInfo', templateUrl: 'views/product_info.html' }) .state('customer.women', { url: '/women', templateUrl: 'views/product_women.html' }) .state('customer.men', { url: '/men', templateUrl: 'views/product_men.html' }) .state('customer.other', { url: '/other', templateUrl: 'views/other.html' }) .state('customer.productInfo', { url: '/productInfo', templateUrl: 'views/product_info.html', controller: "singleCtrl", resolve: { deps: ['$ocLazyLoad', function ($ocLazyLoad) { return $ocLazyLoad.load(['js/controllers/singleProductionCtroller.js']); }] } }) .state('customer.shopCart', { url: '/shopCart', templateUrl: 'views/shoppingCart.html', controller: 'shopCartCtrl', resolve: { deps: ['$ocLazyLoad', function ($ocLazyLoad) { return $ocLazyLoad.load(['js/controllers/shopCartCtroller.js']); }] } }) .state('customer.order', { url: '/order', templateUrl: 'views/customer_order.html', controller: 'orderCtrl', resolve: { deps: ['$ocLazyLoad', function ($ocLazyLoad) { return $ocLazyLoad.load(['js/controllers/orderCtroller.js']); }] } }) //店铺路由 .state('store', { abstract: true, url: '/store', templateUrl: 'views/blank.html' }) .state('store.login', { url: '/storeLogin', templateUrl: 'views/store_login.html', controller: 'storeCtrl', resolve: { deps: ['$ocLazyLoad', function ($ocLazyLoad) { return $ocLazyLoad.load(['js/controllers/storeCtroller.js']); }] } }) .state('store.register', { url: '/storeRegister', templateUrl: 'views/store_register.html', controller: 'shopRegisterCtrl', resolve: { deps: ['$ocLazyLoad', function ($ocLazyLoad) { return $ocLazyLoad.load(['js/controllers/shopRegisterCtroller.js']); }] } }) .state('store.loadProInfo', { url: '/loadProInfo', templateUrl: 'views/product_load.html', controller: 'productInfoCtrl', resolve: { deps: ['$ocLazyLoad', function ($ocLazyLoad) { return $ocLazyLoad.load(['js/controllers/production_load.js']); }] } }) } ] ); <file_sep>/app.js var express = require('express'); var path = require('path'); var fs = require("fs"); var ejs = require('ejs'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var mongo = require("mongoose"); var index = require('./routes/index'); var users = require('./routes/users'); //数据库shema var UserObj = require("./Objs/userObj"); var productionObj = require("./Objs/productionObj"); var shopObj = require("./Objs/shopObj"); var cartObj = require("./Objs/cartOBJ"); var orderObj = require("./Objs/orderObj"); var webapp = express(); // view engine setup webapp.set('views', path.join(__dirname, 'views')); webapp.engine('html',ejs.__express); webapp.set('view engine', 'html'); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); webapp.use(logger('dev')); webapp.use(bodyParser.json()); webapp.use(bodyParser.urlencoded({ extended: false })); webapp.use(cookieParser()); webapp.use(express.static(path.join(__dirname, 'public'))); webapp.use('/', index); //登陆处理 webapp.post("/user/login",function (req,res) { UserObj.find(req.body, function(err,docs){//查询用户 console.log(docs) if(docs.length == 1){ res.contentType('json');//返回的数据类型 res.send(JSON.stringify({ status:"success", data: docs }));//给客户端返回一个json格式的数据 res.end(); }else{ res.contentType('json');//返回的数据类型 res.send(JSON.stringify({ status:"fail" }));//给客户端返回一个json格式的数据 res.end(); } console.log('post message from:/user/login'); }) }); //注册处理 webapp.post("/user/register",function (req,res) { var user = UserObj(req.body); UserObj.find(req.body, function(err,finddocs){//查询用户 if(finddocs.length != 0){ res.contentType('json');//返回的数据类型 res.send(JSON.stringify({ status:"fail" }));//给客户端返回一个json格式的数据 res.end(); }else{ user.save(function (err, docs) { if(docs){ res.contentType('json');//返回的数据类型 res.send(JSON.stringify({ status:"success",data:docs }));//给客户端返回一个json格式的数据 res.end(); }else{ res.contentType('json');//返回的数据类型 res.send(JSON.stringify({ status:"fail" }));//给客户端返回一个json格式的数据 res.end(); } }); } }) }); //获取所有商品 webapp.get("/productions",function (req,res) { productionObj.find(res.body, function (err, docs) {//查询用户 if (docsdocs.length != 0 ) { res.contentType('json');//返回的数据类型 res.send(JSON.stringify({ status: "success", data: docs }));//给客户端返回一个json格式的数据 res.end(); } else { res.contentType('json');//返回的数据类型 res.send(JSON.stringify({status: "fail"}));//给客户端返回一个json格式的数据 res.end(); } }); }); //获取商店信息 webapp.get("/shop/infomation",function (req,res){ shopObj.find(res.body, function(err,docs) {//查询用户 if (docs.length == 1) { res.contentType('json');//返回的数据类型 res.send(JSON.stringify({ status: "success", data: docs }));//给客户端返回一个json格式的数据 res.end(); } else { res.contentType('json');//返回的数据类型 res.send(JSON.stringify({status: "fail"}));//给客户端返回一个json格式的数据 res.end(); } }); }); //获取所有商品 webapp.get("/home/productions",function (req,res){ productionObj.find({}, function(err,docs) {//查询商品 if (docs.length != 0 ) { res.contentType('json');//返回的数据类型 res.send(JSON.stringify({ status: "success", data: docs }));//给客户端返回一个json格式的数据 res.end(); } else { res.contentType('json');//返回的数据类型 res.send(JSON.stringify({status: "fail"}));//给客户端返回一个json格式的数据 res.end(); } }); }); //获取单个商品 webapp.get("/single/production", function (req,res){ productionObj.find(req.body, function(err,docs) {//查询商品 if (docs.length == 1 ) { console.log(docs); res.contentType('json');//返回的数据类型 res.send(JSON.stringify({ status: "success", data: docs }));//给客户端返回一个json格式的数据 res.end(); } else { res.contentType('json');//返回的数据类型 res.send(JSON.stringify({status: "fail"}));//给客户端返回一个json格式的数据 res.end(); } }); console.log("GET: /single/production"); }); //获取购物车信息 webapp.get("/cart/productions",function (req,res){ cartObj.find(req.body, function(err,docs) {//查询商品 if (docs) { res.contentType('json');//返回的数据类型 res.send(JSON.stringify({ status: "success", data: docs }));//给客户端返回一个json格式的数据 res.end(); } else { res.contentType('json');//返回的数据类型 res.send(JSON.stringify({status: "fail"}));//给客户端返回一个json格式的数据 res.end(); } }); }); //获取订单 webapp.post("/get/order",function (req,res){ console.log(req.body); orderObj.find(req.body, function(err,docs) {//查询订单 console.log(docs); if (docs.length == 1 ) { res.contentType('json');//返回的数据类型 res.send(JSON.stringify({ status: "success", data: docs }));//给客户端返回一个json格式的数据 res.end(); } else { res.contentType('json');//返回的数据类型 res.send(JSON.stringify({status: "fail"}));//给客户端返回一个json格式的数据 res.end(); } }); }); //产品上传处理 webapp.post("/production/upload", function (req,res) { var imgData = req.body.image; // var base64Data = imgData.replace(/^data:image\/\w+;base64,/, ""); // var dataBuffer = new Buffer(imgData, 'base64'); var product = productionObj({ name: req.body.product.name, number:req.body.product.leave, price:req.body.product.price, imgData: imgData, shop_id: req.body.product.shop_id, info: req.body.product.info }); product.save(function (err, docs) { if(docs){ res.contentType('json');//返回的数据类型 res.send(JSON.stringify({ status:"success",data:docs }));//给客户端返回一个json格式的数据 res.end(); }else{ res.contentType('json');//返回的数据类型 res.send(JSON.stringify({ status:"fail"}));//给客户端返回一个json格式的数据 res.end(); } }); console.log('post message from:/production/upload'); }); //创建订单 webapp.post("/order/create", function (req,res) { var order = orderObj({ products: req.body.productions, user:req.body.user, total:req.body.total }); order.save(function (err, docs) { if(docs){ for(var i=0;i<req.body.productions.length;i++){ cartObj.remove(req.body.productions[i],function (err, docs) { if(docs){ console.log("remove prodction from cart"); }else{ res.contentType('json');//返回的数据类型 res.send(JSON.stringify({ status:"fail"}));//给客户端返回一个json格式的数据 res.end(); } }); } res.contentType('json');//返回的数据类型 res.send(JSON.stringify({ status:"success",data:docs }));//给客户端返回一个json格式的数据 res.end(); }else{ res.contentType('json');//返回的数据类型 res.send(JSON.stringify({ status:"fail"}));//给客户端返回一个json格式的数据 res.end(); } }); console.log('post message from:/order/create'); }); //商店注册处理 webapp.post("/shop/register", function (req,res) { var shop = shopObj(req.body); shop.save(function (err, docs) { if(docs){ UserObj.update({id:shop.user_id ,role:"saler"},function(err,docs){//更新 console.log(docs); console.log('update success'); }); res.contentType('json');//返回的数据类型 res.send(JSON.stringify({ status:"success",data:docs }));//给客户端返回一个json格式的数据 res.end(); }else{ res.contentType('json');//返回的数据类型 res.send(JSON.stringify({ status:"fail"}));//给客户端返回一个json格式的数据 res.end(); } }); console.log('post message from: /shop/register'); }); //添加购物车 webapp.post("/buy/production", function (req,res) { //查询是否存在 console.log(req.body); cartObj.find(req.body, function (err,findOBJ) { if(findOBJ.length != 0){ cartObj.update({id: findOBJ[0]._id ,number:findOBJ[0].number+1},function (err, updateOBJ) { if(updateOBJ){ res.contentType('json');//返回的数据类型 res.send(JSON.stringify({ status:"success",data:updateOBJ }));//给客户端返回一个json格式的数据 res.end(); }else{ res.contentType('json');//返回的数据类型 res.send(JSON.stringify({ status:"fail"}));//给客户端返回一个json格式的数据 res.end(); } }) }else{ var cart = cartObj({ product_id:req.body.product_id, imageData:req.body.imageData, name: req.body.name, price: req.body.price, info:req.body.info, number:1, user_id:req.body.user_id }); cart.save(function (err, docs) { if(docs){ res.contentType('json');//返回的数据类型 res.send(JSON.stringify({ status:"success",data:docs }));//给客户端返回一个json格式的数据 res.end(); }else{ res.contentType('json');//返回的数据类型 res.send(JSON.stringify({ status:"fail"}));//给客户端返回一个json格式的数据 res.end(); } }) } }); console.log('post message from: /buy/production'); }); //删除商品 webapp.post("/production/delete",function (req,res) { productionObj.remove(req.body, function (err, docs) { if(docs){ res.contentType('json');//返回的数据类型 res.send(JSON.stringify({ status:"success",data:docs }));//给客户端返回一个json格式的数据 res.end(); }else{ res.contentType('json');//返回的数据类型 res.send(JSON.stringify({ status:"fail"}));//给客户端返回一个json格式的数据 res.end(); } }); console.log('post message from: /shop/register'); }); /* 连接本地mongodb */ var mongodb = mongo.connect("mongodb://127.0.0.1:27017/testDB",function(err){ if(!err){ console.log("connected to Mongodb"); }else{ throw err; } }); //监听3000端口服务 var server = webapp.listen(3000, function () { var host = server.address().address; var port = server.address().port; console.log(host, port); console.log("应用实例,访问地址为 http://%s:%s", host, port) }); module.exports = webapp; <file_sep>/public/js/controllers/shopCartCtroller.js /** * Created by hasee on 2016/12/21. */ app.controller("shopCartCtrl", ["$scope", '$cookieStore','$http','$state', function ($scope, $cookieStore, $http, $state) { $scope.user = $cookieStore.get("user"); $scope.totalMoney = 0; $scope.orderList = []; $http({ url: 'http://localhost:3000/cart/productions', method: 'GET', data: {"user_id":$scope.user._id} }).success(function (res, header, config, status) { //响应成功 if(res.status == "success"){ $scope.cartList = res.data; console.log($scope.cartList); }else{ console.log(res.status) } }).error(function (data, header, config, status) { console.log("error") }); $scope.orderChoose = function ($event,product) { var checkbox = $event.target; var action = (checkbox.checked?'add':'remove'); var tempMoney = product.number*product.price; if (action == "add"){ $scope.totalMoney += tempMoney; $scope.orderList.push(product); }else{ $scope.totalMoney -= tempMoney; var index = $scope.orderList.indexOf(product); $scope.orderList.splice(index, 1); } }; $scope.createOrder = function () { $http({ url: 'http://localhost:3000/order/create', method: 'POST', data: {"user":$scope.user, "productions":$scope.orderList, "total": $scope.totalMoney} }).success(function (res, header, config, status) { //响应成功 if(res.status == "success"){ $cookieStore.put("order_id",res.data._id); $state.go("customer.order",{},{reload:true}); }else{ console.log(res.status) } }).error(function (data, header, config, status) { console.log("error") }); } }]);<file_sep>/public/js/controllers/navCtroller.js /** * Created by hasee on 2016/12/13. */ app.controller("navCtrl", ["$scope", '$cookieStore',function ($scope, $cookieStore) { if($cookieStore.get("login") == "yes"){ $scope.loginCheck = false; console.log("login"); }else{ $scope.loginCheck = true; console.log("not login") } }]);<file_sep>/Objs/userObj.js /** * Created by hasee on 2016/12/14. */ var mongo = require("mongoose"); var Schema = mongo.Schema, ObjectId = Schema.ObjectId; var UserSchema = new Schema({ firstname:{type: String}, lastname:{type: String}, Email:{type: String}, password:{type: String}, city:{type: String}, address:{type: String}, age:{type: String}, telephone:{type: String}, role:{type: String} }); // 制定 mongo.model("user",UserSchema); var User = mongo.model("user"); module.exports = User;<file_sep>/public/views/login.html <div class="login"> <div class="wrap"> <div class="col_1_of_login span_1_of_login"> <h4 class="title">New Customers</h4> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan</p> <div class="button1"> <a ui-sref="customer.register">创建账户</a> </div> <div class="clear"></div> </div> <div class="col_1_of_login span_1_of_login"> <div class="login-title"> <h4 class="title">Registered Customers</h4> <div id="loginbox" class="loginbox"> <form action="" method="post" name="login" id="login-form"> <fieldset class="input"> <p id="login-form-username"> <label>Username</label> <input ng-model="username" type="text" name="email" class="inputbox" size="18" autocomplete="off"> </p> <p id="login-form-password"> <label>Password</label> <input ng-model="<PASSWORD>" type="<PASSWORD>" name="<PASSWORD>" class="inputbox" size="18" autocomplete="off"> </p> <div class="remember"> <p id="login-form-remember"> <label for="modlgn_remember"><a href="#">Forget Your Password ? </a></label> </p> <a class="pull-right" ng-click="userLogin()">login</a><div class="clear"></div> </div> </fieldset> </form> </div> </div> </div> <div class="clear"></div> </div> </div> <div class="footer"> <div class="footer-top"> <div class="wrap"> <div class="section group example"> <div class="col_1_of_2 span_1_of_2"> <ul class="f-list"> <li><img src="images/2.png"><span class="f-text">Free Shipping on orders over $ 100</span><div class="clear"></div></li> </ul> </div> <div class="col_1_of_2 span_1_of_2"> <ul class="f-list"> <li><img src="images/3.png"><span class="f-text">Call us! toll free-222-555-6666 </span><div class="clear"></div></li> </ul> </div> <div class="clear"></div> </div> </div> </div> <div class="footer-middle"> <div class="wrap"> <div class="section group example"> <div class="col_1_of_f_1 span_1_of_f_1"> <div class="section group example"> <div class="col_1_of_f_2 span_1_of_f_2"> <h3>Facebook</h3> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <div class="like_box"> <div class="fb-like-box" data-href="http://www.cssmoban.com/" data-colorscheme="light" data-show-faces="true" data-header="true" data-stream="false" data-show-border="true"></div> </div> </div> <div class="col_1_of_f_2 span_1_of_f_2"> <h3>From Twitter</h3> <div class="recent-tweet"> <div class="recent-tweet-icon"> <span> </span> </div> <div class="recent-tweet-info"> <p>Ds which don't look even slightly believable. If you are <a href="#">going to use nibh euismod</a> tincidunt ut laoreet adipisicing</p> </div> <div class="clear"> </div> </div> <div class="recent-tweet"> <div class="recent-tweet-icon"> <span> </span> </div> <div class="recent-tweet-info"> <p>Ds which don't look even slightly believable. If you are <a href="#">going to use nibh euismod</a> tincidunt ut laoreet adipisicing</p> </div> <div class="clear"> </div> </div> </div> <div class="clear"></div> </div> </div> <div class="col_1_of_f_1 span_1_of_f_1"> <div class="section group example"> <div class="col_1_of_f_2 span_1_of_f_2"> <h3>Information</h3> <ul class="f-list1"> <li><a href="#">Duis autem vel eum iriure </a></li> <li><a href="#">anteposuerit litterarum formas </a></li> <li><a href="#">Tduis dolore te feugait nulla</a></li> <li><a href="#">Duis autem vel eum iriure </a></li> <li><a href="#">anteposuerit litterarum formas </a></li> <li><a href="#">Tduis dolore te feugait nulla</a></li> </ul> </div> <div class="col_1_of_f_2 span_1_of_f_2"> <h3>Contact us</h3> <div class="company_address"> <p>500 Lorem Ipsum Dolor Sit,</p> <p>22-56-2-9 Sit Amet, Lorem,</p> <p>USA</p> <p>Phone:(00) 222 666 444</p> <p>Fax: (000) 000 00 00 0</p> <p>Email: <span>mail[at]leoshop.com</span></p> </div> <div class="social-media"> <ul> <li> <span class="simptip-position-bottom simptip-movable" data-tooltip="Google"><a href="#" target="_blank"> </a></span></li> <li><span class="simptip-position-bottom simptip-movable" data-tooltip="Linked in"><a href="#" target="_blank"> </a> </span></li> <li><span class="simptip-position-bottom simptip-movable" data-tooltip="Rss"><a href="#" target="_blank"> </a></span></li> <li><span class="simptip-position-bottom simptip-movable" data-tooltip="Facebook"><a href="#" target="_blank"> </a></span></li> </ul> </div> </div> <div class="clear"></div> </div> </div> <div class="clear"></div> </div> </div> </div> <div class="footer-bottom"> <div class="wrap"> <div class="copy"> <p>Copyright &copy; 2014.Company name All rights reserved.<a target="_blank" href="http://www.cssmoban.com/">&#x7F51;&#x9875;&#x6A21;&#x677F;</a></p> </div> <div class="f-list2"> <ul> <li class="active"><a href="about.html">About Us</a></li> | <li><a href="delivery.html">Delivery & Returns</a></li> | <li><a href="delivery.html">Terms & Conditions</a></li> | <li><a href="contact.html">Contact Us</a></li> </ul> </div> <div class="clear"></div> </div> </div> </div> <file_sep>/Objs/orderObj.js /** * Created by hasee on 2016/12/22. */ var mongo = require("mongoose"); var Schema = mongo.Schema, ObjectId = Schema.ObjectId; var orderSchema = new Schema({ products:{type: Array}, user:{type: Object}, total:{type: Number} }); mongo.model("order",orderSchema); var Order = mongo.model("order"); module.exports = Order;<file_sep>/public/js/controllers/loginCtroller.js /** * Created by hasee on 2016/12/13. */ app.controller("loginCtrl", ["$scope", "$state", "$cookieStore","$http", function($scope, $state, $cookieStore,$http){ $scope.userLogin = function () { $scope.userLoginOBJ = { Email:$scope.Email, password:$<PASSWORD>, role: "customer" } if($scope.Email==null){ alert("Email不能为空!") return false; }else { if($scope.password==null){ alert("密码不能为空!") return false; } else { //测试模块 // $scope.checkMeet=false; // alert("\n成功!" + "\n 用户名: "+ $scope.Email // + "\n 密码: "+ $scope.password); //实现模块 $http({ url: 'http://localhost:3000/user/login', method: 'POST', data: {"Email": $scope.Email, "password":$<PASSWORD>} }).success(function (res, header, config, status) { //响应成功 if(res.status == "success"){ $cookieStore.put("login", "yes"); $cookieStore.put("user", res.data[0]); $state.go("customer.home",{},{reload:true}); }else{ console.log(res.status); } //scope设置 }).error(function (data, header, config, status) { console.log("error") }) } } } }]); <file_sep>/public/js/controllers/production_load.js /** * Created by hasee on 2016/12/17. */ app.controller("productInfoCtrl", ["$scope", "$state", "$cookieStore","$http", function($scope, $state, $cookieStore,$http){ //获取已有的商品列表 var shop = $cookieStore.get("shop"); $http({ url: 'http://localhost:3000/productions', method: 'GET', data: {"shop_id": shop._id} }) .success(function (res, header, config, status) { //响应成功 if(res.status == "success"){ // 商品列表 $scope.list = res.data; }else{ console.log(res.status); } }) .error(function (data, header, config, status) { console.log("error") }); //修改上传文件 $scope.fileChanged = function(ele){ var imgUrl = imageBase64Url(ele.files[0]); convertImgToBase64(imgUrl, function(base64Img){ $scope.ImgBase64 = base64Img.toString(); }); } // 添加产品 $scope.addProduct=function (product) { $scope.product.shop_id = shop._id; $http({ url: 'http://localhost:3000/production/upload', method: 'POST', data: {"image": $scope.ImgBase64, "product": $scope.product} }).success(function (res, header, config, status) { //响应成功 if(res.status == "success"){ console.log(res.data); $scope.list.push(res.data); }else{ $scope.img = res.data; } //scope设置 }).error(function (data, header, config, status) { console.log("error") }) }; $scope.deleteProduct = function (product_id) { $http({ url: 'http://localhost:3000/production/delete', method: 'POST', data: {"_id":product_id } }).success(function (res, header, config, status) { //响应成功 if(res.status == "success"){ console.log(res.data); $state.go("store.loadProInfo",{},{reload:true}); }else{ $scope.img = res.data; } //scope设置 }).error(function (data, header, config, status) { console.log("error") }) } //建立一個可存取到該file的url var imageBase64Url = function getObjectURL(file) { var url = null; if (window.createObjectURL != undefined) { // basic url = window.createObjectURL(file); } else if (window.URL != undefined) { // mozilla(firefox) url = window.URL.createObjectURL(file); } else if (window.webkitURL != undefined) { // webkit or chrome url = window.webkitURL.createObjectURL(file); } return url; }; // img文件转换成base64 function convertImgToBase64(url, callback, outputFormat){ var canvas = document.createElement('CANVAS'); var ctx = canvas.getContext('2d'); var img = new Image; img.crossOrigin = 'Anonymous'; img.onload = function(){ canvas.height = img.height; canvas.width = img.width; ctx.drawImage(img,0,0); var dataURL = canvas.toDataURL(outputFormat || 'image/png'); callback.call(this, dataURL); canvas = null; }; img.src = url; } //修改商品 }]);<file_sep>/public/js/filter/FormFilter.js /** * Created by hasee on 2016/12/14. */<file_sep>/public/js/controllers/singleProductionCtroller.js /** * Created by hasee on 2016/12/22. */ app.controller("singleCtrl", ["$scope", '$cookieStore','$http','$state', function ($scope, $cookieStore, $http, $state) { var user = $cookieStore.get("user"); var product_id = $cookieStore.get("singleProduction"); console.log(product_id); $http({ url: 'http://localhost:3000/single/production', method: 'GET', data: {"_id": product_id} }).success(function (res, header, config, status) { //响应成功 if(res.status == "success"){ $scope.production = res.data[0]; }else{ console.log(res.status) } }).error(function (data, header, config, status) { console.log("error") }); $scope.addToCart = function (production) { $http({ url: 'http://localhost:3000/buy/production', method: 'POST', data: { "product_id": production._id, "imageData": production.imgData, "name": production.name, "price": production.price, "info": production.info, "user_id": user._id } }).success(function (res, header, config, status) { //响应成功 if(res.status == "success"){ $state.go("customer.shopCart",{},{reload:true}); console.log(res.data); }else{ console.log(res.status) } }).error(function (data, header, config, status) { console.log("error") }); } }]);
aa4f01fd7e740b4adeb4249a1f08758df67f59c8
[ "JavaScript", "HTML" ]
17
JavaScript
Luofengyu/frontClassProject
ddfb824f7c459ff737b270654b3a9d5b513081b2
70818b1ab37bb4fdb35a53107e043610bd47b640
refs/heads/master
<file_sep>function math(firsrArg,secondArg,thirdArg) { return (secondArg*thirdArg)+firsrArg; } console.log(math(53,61,67));
51cb4aa022554187eb0d70c4cbdf52ccd934dc39
[ "JavaScript" ]
1
JavaScript
ktoroshchin/javascripting
2382205390001e19708a6ba76ffca2268a914a6c
f5c41857ac0cf750cecc9d43732e260d762a15bd
refs/heads/master
<file_sep><?php namespace App\Http\Controllers; use App\Nodos; use App\Rutas; use Illuminate\Http\Request; use App\Http\Requests; use Illuminate\Support\Facades\DB; class RutasController extends Controller { public function getRutas(){ $tnodos = Nodos::all(); $rutas = []; $nodos = []; foreach ($tnodos as $nodo){ foreach ($nodo->rutas as $ruta) { $rutas[] = [ 'id' => $ruta->id, 'destino' => $ruta->destino->nombre_nodo, 'destino_id' => $ruta->destino->id, 'origen' => $nodo->nombre_nodo, 'origen_id' => $nodo->id, 'distancia' => $ruta->distancia, 'tiempo' => $ruta->tiempo, 'estado_via' => $ruta->estado_via, 'condiciones_via' => $ruta->condiciones_via, 'tipo_via' => $ruta->tipo_via, 'seguridad_via' => $ruta->seguridad_via, 'cantidad_peajes' => $ruta->cantidad_peajes, ]; } } return \Response::json($rutas); } public function getRutasNodo($id){ $nodo = Nodos::find($id); $rutas = []; foreach ($nodo->rutas as $ruta) { $rutas[] = [ 'id' => $ruta->id, 'origen' => $ruta->origen, 'destino' => $ruta->destino, ]; } return $rutas; } public function showRuta($id){ $ruta = Rutas::find($id); return $ruta; } public function postRuta(Request $request){ $ruta = new Rutas(); $ruta->id_nodo_origen = $request['id_nodo_origen']; $ruta->id_nodo_destino = $request['id_nodo_destino']; $ruta->tiempo = $request['tiempo']; $ruta->distancia = $request['distancia']; $ruta->estado_via = $request['estado_via']; $ruta->condiciones_via = $request['condiciones_via']; $ruta->seguridad_via = $request['seguridad_via']; $ruta->tipo_via = $request['tipo_via']; $ruta->cantidad_peajes = $request['cantidad_peajes']; $ruta->f_objetivo = $request['f_objetivo']; if ($ruta->save()) return \Response::json('Se guardo correctamente ruta'); else return \Response::json('No se puede guardar la ruta'); } public function deleteRuta($id){ $ruta = $this->showRuta($id); if ($ruta->delete()) return \Response::json('Se elimino el ruta correctamente'); else return \Response::json('No se pudo eliminar la ruta'); } public function rutaOptima(Request $request){ $datos = $request->all(); $pila = array(); for($i = 0; $i < count($datos); $i++){ $nodo = Nodos::find($datos[$i])->select('nombre_nodo')->where('id', $datos[$i])->first(); array_push($pila, $nodo); } return $pila; } } <file_sep><?php namespace App\Http\Controllers; use App\Nodos; use Illuminate\Http\Request; use App\Http\Requests; use Symfony\Component\HttpFoundation\JsonResponse; class NodosController extends Controller { public function getNodos(){ $nodos = Nodos::all(); return \Response::json($nodos); } public function showNodo($id){ $nodo = Nodos::find($id); return $nodo; } public function postNodo(Request $request){ $nodo = new Nodos(); $nodo->nombre_nodo = $request['nombre_nodo']; if ($nodo->save()) return \Response::json('Se guardo correctamente el nodo'); else return \Response::json('No se puede guardar el nodo'); } public function updateNodo(Request $request, $id){ $nodo = $this->showNodo($id); $nodo->nombre_nodo = $request['nombre_nodo']; if ($nodo->save()) return \Response::json('Se actualizo correctamente el nodo'); else return \Response::json('No se puede actualizar el nodo'); } public function deleteNodo($id){ $nodo = $this->showNodo($id); if ($nodo->delete()) return \Response::json('Se elimino el nodo correctamente'); else return \Response::json('No se pudo eliminar el nodo'); } } <file_sep>(function() { 'use strict'; angular .module('agi', [ 'commons', 'ui.router', 'ui.keypress', //'google-maps', //app modules 'app.nodos', 'app.rutas' ]) .constant('API', '../api') .config(config) .run(run); function config($urlRouterProvider, $stateProvider){ $urlRouterProvider.when('', '/'); $urlRouterProvider.when('/', '/nodos'); //$urlRouterProvider.otherwise('/login'); $stateProvider .state('app', { abstract : true, url: '', templateUrl: 'layout/layout.html', controller: 'indexController as vm' }); } function run($rootScope, $state) { $rootScope.$on('$stateChangeStart', function(e, to) { if (!to.data || !to.data.noRequiresLogin) { if (to.data && to.data.onlyAccess) { if (!(!to.data.onlyAccess || to.data.onlyAccess == 'all')) { e.preventDefault(); $state.go('app.nodo_nuevo'); } } } }); } })(); <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Nodos extends Model { protected $table = 'nodos'; protected $fillable = ['nombre_nodo']; public $timestamps = false; public function rutas() { return $this->hasMany(Rutas::class, 'id_nodo_origen', 'id') ->select('id', 'id_nodo_destino', 'id_nodo_origen', 'distancia', 'cantidad_peajes','tipo_via', 'seguridad_via', 'condiciones_via', 'estado_via', 'tiempo'); } } <file_sep><?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the controller to call when that URI is requested. | */ Route::get('/', function () { echo '<script>location.href="app";</script>'; }); Route::group(['middleware' => 'cors'], function () { // nodos Route::get('/api/nodos', 'NodosController@getNodos'); Route::get('/api/nodos/{nodo_id}', 'NodosController@showNodo'); Route::post('/api/nodos', 'NodosController@postNodo'); Route::put('/api/nodos/{nodo_id}', 'NodosController@updateNodo'); Route::delete('/api/nodos/{nodo_id}', 'NodosController@deleteNodo'); // rutas Route::get('/api/rutas', 'RutasController@getRutas'); Route::get('/api/rutas/nodo/{nodo_id}', 'RutasController@getRutasNodo'); Route::post('/api/rutas/rutaoptima/nodos', 'RutasController@rutaOptima'); Route::post('/api/rutas', 'RutasController@postRuta'); Route::delete('/api/rutas/{nodo_id}', 'RutasController@deleteRuta'); });<file_sep>(function() { 'use strict'; angular .module('app.rutas', [ 'app.rutas.mostrar' ]) })();<file_sep>(function() { 'use strict'; angular .module('app.rutas.mostrar', []) .config(config) .run(run); function config($stateProvider){ $stateProvider .state('app.mostrar_rutas', { url: '/rutas', templateUrl: 'rutas/mostrar/mostrar.html', data: { onlyAccess: 'all' } }) .state('app.mostrar_grafos', { url: '/grafos', templateUrl: 'rutas/mostrar/grafos.html', data: { onlyAccess: 'all' } }) }; function run(appMenu){ appMenu.addTo([ {nombre:'Rutas', link:'app.mostrar_rutas', icon:'perm_identity'} ], 'all'); } })();<file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Rutas extends Model { protected $table = 'rutas'; protected $fillable = ['id_nodo_origen', 'id_nodo_destino', 'cantidad_peajes', 'tiempo', 'distancia', 'estado_via', 'tipo_via', 'condiciones_via', 'seguridad_via']; public $timestamps = false; public function origen() { return $this->belongsTo(Nodos::class, 'id_nodo_origen', 'id'); } public function destino() { return $this->belongsTo(Nodos::class, 'id_nodo_destino', 'id'); } }
ea85f7183e3f60f04b462f310807aefe744f2c83
[ "JavaScript", "PHP" ]
8
PHP
jomisoac/AG
67fb1c51f8942793eff607cd2268e4220525bfc8
24b2b38cc43aac48c3da37bd7ff4a5df3de56b9d
refs/heads/master
<file_sep>module.exports = { jwtSecret: process.env.JWT_SECRET || '<KEY>' };
2e05e497e5a84c4a4469491766179c1cf9de2408
[ "JavaScript" ]
1
JavaScript
Arthurgallina1/ecommerce-api-strapi
8f30bdae4d3009fdf1e759477ecd9bb93f87e77b
8a3e444de9d1183c5da77b40eb7fe8d934484b0e
refs/heads/master
<repo_name>rafaelmakaha/desafio-gs-ciencia-front<file_sep>/app/src/utils/index.js export * from './validFetch';<file_sep>/app/src/services/backend.js import { BACKEND } from '../settings/endpoints' import { validFetch } from '../utils' const common_header = { "Content-Type": "application/json" } export const getAllProducts = () => { const url = BACKEND.baseRoute + BACKEND.product.list.route; const method = BACKEND.product.list.method; return new Promise((resolve, reject) => { fetch(url, { method, headers: common_header }) .then(validFetch) .then(resolve) .catch(reject) }) } export const createProduct = (product) => { const url = BACKEND.baseRoute + BACKEND.product.create.route; const method = BACKEND.product.create.method; return new Promise((resolve, reject) => { fetch(url,{ method, headers: common_header, body: JSON.stringify(product) }) .then(validFetch) .then(resolve) .catch(reject) }) } export const getProductById = ({id}) => { const url = BACKEND.baseRoute + BACKEND.product.getOne.route(id); const method = BACKEND.product.getOne.method; return new Promise((resolve, reject) => { fetch(url,{ method, headers: common_header }) .then(validFetch) .then(resolve) .catch(reject) }) } export const deleteProductById = (id) => { const url = BACKEND.baseRoute + BACKEND.product.delete.route(id); const method = BACKEND.product.delete.method; return new Promise((resolve, reject) => { fetch(url,{ method, headers: common_header }) .then(resolve) .catch(reject) }) } export const updateProduct = (id, product) => { const url = BACKEND.baseRoute + BACKEND.product.update.route(id); const method = BACKEND.product.update.method; return new Promise((resolve, reject) => { fetch(url,{ method, headers: common_header, body: JSON.stringify(product) }) .then(validFetch) .then(resolve) .catch(reject) }) } <file_sep>/app/src/screens/ProductList/index.js import React, { useEffect, useState } from 'react'; import { getAllProducts } from '../../services'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableContainer from '@material-ui/core/TableContainer'; import TableHead from '@material-ui/core/TableHead'; import TableRow from '@material-ui/core/TableRow'; import Paper from '@material-ui/core/Paper'; import { Button } from '@material-ui/core'; import { useHistory } from 'react-router-dom'; import { ButtonsWrapper, Container, TableWrapper, Typography } from './style'; const ProductList = () => { const [products, setProducts] = useState([]); const history = useHistory(); useEffect(() => { getAllProducts() .then(setProducts) .catch(console.log) },[]); return( <Container> <Typography variant="h3" gutterBottom> Welcome! </Typography> <ButtonsWrapper> <Button variant="contained" color="primary" onClick={() => history.push('/product')}> New Product </Button> </ButtonsWrapper> <TableWrapper> <TableContainer component={Paper}> <Table aria-label="simple table"> <TableHead> <TableRow> <TableCell>Product </TableCell> <TableCell align="right">Description</TableCell> <TableCell align="right">Price</TableCell> <TableCell align="right"></TableCell> </TableRow> </TableHead> <TableBody> {products.map((row) => ( <TableRow key={row?.name}> <TableCell component="th" scope="row"> {row?.name} </TableCell> <TableCell align="right">{row?.description}</TableCell> <TableCell align="right">{row?.price}</TableCell> <TableCell align="right"> <Button variant="contained" color="primary" onClick={() => history.push(`/product/${row.id}`)}> Editar </Button> </TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> </TableWrapper> </Container> ) } export default ProductList;<file_sep>/app/src/screens/Product/index.js import React, { useEffect, useState } from 'react'; import { createProduct, deleteProductById, getProductById, updateProduct } from '../../services'; import { useParams, useHistory } from 'react-router-dom'; import TextField from '@material-ui/core/TextField'; import { ButtonsWrapper, Container, Form, Typography, ButtonSaveContainer } from './style'; import { Button } from '@material-ui/core'; const Product = () => { const [product, setProduct] = useState({}); const params = useParams(); const history = useHistory(); const handlePush = () => { history.push('/'); } const handleOnChangeName = (event) => { setProduct({name:event.target.value, description: product.description, price: product.price}) } const handleOnChangeDescription = (event) => { setProduct({name:product.name, description: event.target.value, price: product.price}) } const handleOnChangePrice = (event) => { setProduct({name: product.name, description: product.description, price: event.target.value}) } const handleSubmit = (type) => () => { const actionButton = { create: (product) => {createProduct(product); history.push('/');}, update: (product) => {updateProduct(params.id,product)}, delete: (product) => {deleteProductById(params.id); history.push('/')}, } if (actionButton[type]) actionButton[type](product) } useEffect(() => { if ('id' in params) getProductById(params) .then(setProduct) .catch(console.log) else setProduct({name:'',description:'',price:0}) },[]); return( <Container> <Typography variant="h3" gutterBottom> {'id' in params ? 'Editar Produto' : 'Inserir Produto'} </Typography> <Form noValidate autoComplete="off"> <TextField id="outlined-basic" onChange={handleOnChangeName} value={product.name} label="Name" variant="outlined" /> <TextField id="outlined-basic" onChange={handleOnChangeDescription} value={product.description} label="Description" variant="outlined" /> <TextField id="outlined-basic" onChange={handleOnChangePrice} value={product.price} label="Price" variant="outlined" type='number' /> <ButtonsWrapper> <Button variant="contained" color="primary" onClick={handlePush}> Back </Button> <ButtonSaveContainer> {'id' in params && <Button variant="contained" color="secondary" onClick={handleSubmit('delete')}> Delete </Button> } <Button variant="contained" color="primary" onClick={handleSubmit('id' in params ? 'update' : 'create')}> Save </Button> </ButtonSaveContainer> </ButtonsWrapper> </Form> </Container> ) } export default Product;<file_sep>/app/src/Routes.js import React, { Suspense, lazy } from 'react'; import { BrowserRouter, Switch, Route } from 'react-router-dom'; const Product = lazy(() => import('./screens/Product')); const ProductList = lazy(() => import('./screens/ProductList')); const Routes = () => ( <BrowserRouter> <Suspense fallback={() => <div/>}> <Switch> <Route path='/' exact component={ProductList}/> <Route path='/product' exact component={Product}/> <Route path='/product/:id' component={Product}/> </Switch> </Suspense> </BrowserRouter> ); export default Routes;<file_sep>/app/src/screens/Product/style.js import styled from 'styled-components'; import { Typography as MaterialTypography } from '@material-ui/core'; export const Form = styled.form` display: flex; flex-direction: column; gap: 1.2em; width: 100%; max-width: 800px; margin: auto; ` export const ButtonsWrapper = styled.div` display: flex; gap: 1.2em; justify-content: space-between; ` export const Container = styled.div` margin-top: 1.2em; ` export const Typography = styled(MaterialTypography)` margin-top: 1.2em; text-align: center; ` export const ButtonSaveContainer = styled.div` & > :last-child { margin-left: 1.2em; } `<file_sep>/Dockerfile FROM node:12.4-alpine RUN \ echo "UPDATING SYSTEM" && \ apk update && \ apk add --update WORKDIR /app COPY ./app/package.json . RUN npm install COPY ./app/ . EXPOSE 3000 ENTRYPOINT npm start<file_sep>/app/src/settings/endpoints.js export const BACKEND = { baseRoute: process.env.REACT_APP_BACKEND, product: { list: { route: '/products/', method: 'get' }, create: { route: '/products/', method: 'post' }, update: { route: (id) => `/products/${id}/`, method: 'put' }, delete: { route: (id) => `/products/${id}/`, method: 'delete' }, getOne: { route: (id) => `/products/${id}/`, method: 'get' } } }
e47cf03398670f383a28c40d91fea9df1617dc46
[ "JavaScript", "Dockerfile" ]
8
JavaScript
rafaelmakaha/desafio-gs-ciencia-front
152b9049dd0f21a75a8d53da4687588cdb4e9d5b
310bb46ff60d01d9c1b3bf3b150331746435f5bd
refs/heads/master
<repo_name>mcheng09/react-taskified<file_sep>/src/components/TasksList/TasksList.js import React from 'react'; import classes from './TasksList.module.scss' import TaskItem from './TaskItem/TaskItem'; function TasksList (props) { const tasks = props.tasks.map((task, i) => { return <TaskItem key={ 'task' + i } task={ task } taskIndex={ i } removeTask={props.removeTask} shiftTask={props.shiftTask} numOfUsers={props.numOfUsers} userID={props.userID} /> }) return ( <ul className={classes.TasksList}> {tasks} </ul> ) } export default TasksList; <file_sep>/src/components/TasksList/TaskItem/TaskItem.js import React from 'react'; import classes from './TaskItem.module.scss' import RemoveTasks from './../RemoveTasks/RemoveTasks'; import ShiftTasks from './../ShiftTasks/ShiftTasks'; function TaskItem (props) { return ( <li className={classes.TaskItem}> <div className={classes.Task}>{props.task}</div> <ShiftTasks shiftTask={props.shiftTask} userID= {props.userID} taskIndex={props.taskIndex} numOfUsers={props.numOfUsers} /> <RemoveTasks removeTask={props.removeTask} userID={props.userID} taskIndex={props.taskIndex} /> </li> ) } export default TaskItem; <file_sep>/src/containers/TasksContainer/TasksContainer.js import React, { Component } from 'react'; import classes from './TasksContainer.module.scss'; import UserCard from './../../components/UserCard/UserCard' class TasksContainer extends Component { state = { users: [ { id: 0, name: 'Mike', tasks: [ 'Build this App', 'Add styling to application', 'Build out functionalities' ], primaryColor: 'lightblue' }, { id: 1, name: 'Some other random person', tasks: [ 'Buy some eggs', 'Do laundry', 'Take out the trash' ], primaryColor: 'lightgreen' }, { id: 2, name: 'Jeff', tasks: [ 'Lolz!' ], primaryColor: 'lightyellow' } ], userIDCount: 3 } addUser = () => { let newUser = prompt("Who's joining us?"); const allUsers = [...this.state.users]; let userIDCount = this.state.userIDCount; allUsers.push({ id: userIDCount, name: newUser, tasks: [] }) userIDCount++; this.setState({ users: allUsers }); this.setState({ userIDCount: userIDCount }) } addTask = (userID) => { let task = prompt("What's your task?"); if (task === '') return null; const allUsers = [...this.state.users]; const user = allUsers.filter((user) => { return user.id === userID }) user[0].tasks.push(task); this.setState({ users: allUsers }); } removeTask = (userID, taskIndex) => { const allUsers = [...this.state.users]; const user = allUsers.filter((user) => { return user.id === userID }) const userTasks = user[0].tasks; userTasks.splice(taskIndex, 1) this.setState({ users: allUsers}); } shiftTask = (userID, taskIndex, direction) => { const allUsers = [...this.state.users]; const origAssignee = allUsers.filter((user) => { return user.id === userID; }) const origAssigneeTasks = origAssignee[0].tasks; const copyTask = origAssigneeTasks.splice(taskIndex, 1); direction === 'left' ? userID-- : userID++; const newAssignee = allUsers.filter((user) => { return user.id === userID; }) newAssignee[0].tasks.push(copyTask); this.setState({ users: allUsers }); } render () { const userCards = this.state.users.map(user => { return <UserCard key={'user' + user.id} userData={user} numOfUsers={this.state.users.length} addTask={this.addTask} removeTask={this.removeTask} shiftTask={this.shiftTask} /> }) return ( <div className={classes.TasksContainer}> { userCards } <button onClick={this.addUser}>Add User</button> </div> ) } } export default TasksContainer;
020a93c8fb2ae0454b10f3660bc2886616b48c48
[ "JavaScript" ]
3
JavaScript
mcheng09/react-taskified
558d1f57ad045897968e9dee1ce9e19ebb6d7a0e
b2161b91829ad1c43b93bb031c1f8b853823aa2d
refs/heads/master
<file_sep>cmake_minimum_required(VERSION 3.0.0) project(connection_handle VERSION 0.1.0) set(CMAKE_CXX_STANDARD 14) if (CMAKE_CXX_COMPILER_ID MATCHES "Clang") # using regular Clang or AppleClang add_compile_options("-fdeclspec") endif() add_compile_options("$<$<CONFIG:DEBUG>:-D_DEBUG>") add_executable(connection_handle main.cpp sqlite3.c) <file_sep> #include <iostream> #include "SQLite.h" static char const* TypeName(Type const type) { switch (type) { case Type::Integer : return "Int"; case Type::Float : return "Float"; case Type::Blob : return "Blob"; case Type::Null : return "Null"; case Type::Text : return "Text"; } ASSERT(false); return "Invalid"; } static void SaveToDisk(Connection const & source, char const * const filename) { Connection destination(filename); Backup backup(destination, source); backup.Step(); } int main(int, char**) { try { Connection connection = Connection::Memory(); Execute(connection, "create table Things (Content real)"); Statement statement(connection, "insert into Things values (?)"); for (int i = 0; i != 1000000; ++i) { statement.Reset(i); statement.Execute(); } Execute(connection, "delete from Things where Content > 10"); Execute(connection, "vacuum"); SaveToDisk(connection, "C:\\temp\\backup.db"); } catch (Exception const &e) { std::cout << e.Message << " (error code): " << e.Result << "\n"; } }
428f4b7771218508272a4aaf757388f6fffbdc12
[ "CMake", "C++" ]
2
CMake
jdmairs/Pluralsight_sqlite
08c5ab6f74c0d198b901ce5241a9dd77d4026196
ce2812474a49cd74af73e3cbcfb59c2cd630ade7
refs/heads/master
<repo_name>chaunceyt/pollyctl<file_sep>/README.md # pollyctl Simple commandline tool that converts text-to-speech using Amazon's Polly ## Requirements This tool assumes you have access to an AWS account with permissions to SynthesizeSpeech when using Polly. ## Command line options ``` pollyctl text-to-speech -h NAME: pollyctl text-to-speech - Create MP3 file from an input file USAGE: pollyctl text-to-speech [command options] [arguments...] OPTIONS: --input-file value Name of the file containing text to be converted. --output-file value Name of MP3 file to create. --voice-id value Voice that will read the converted text. (default: "Kimberly") --text-type value Input text type plain text or ssml. (default: "text") --sample-rate value Audio frequency specified in Hz. (default: "16000") --aws-profile value AWS Profile to use. (default: "default") --aws-region value AWS Region to use. (default: "us-east-1") ``` ``` pollyctl list-voices -h NAME: pollyctl list-voices - List available voices USAGE: pollyctl list-voices [command options] [arguments...] OPTIONS: --lang-code value Language . (default: "en-US") --aws-profile value AWS Profile to use. (default: "default") --aws-region value AWS Region to use. (default: "us-east-1") ``` ## Example usage Get list of voices for a specific language ``` ./pollyctl list-voices --lang-code es-US ``` Example output ``` Getting list of available voices... Miguel (Male) Penélope (Female) Lupe (Female) ``` Convert text to speech ``` ./pollyctl text-to-speech \ --input-file mynotes.txt \ --output-file my-notes-MM-DD-YYYY.mp3 \ --voice-id Lupe ``` ## Languages supported ``` arb,Arabic cmn-CN,"Chinese, Mandarin" da-DK,Danish nl-NL,Dutch en-AU,"English, Australian" en-GB,"English, British" en-IN,"English, Indian" en-US,"English, US" en-GB-WLS,"English, Welsh" fr-FR,French fr-CA,"French, Canadian" hi-IN,Hindi de-DE,German is-IS,Icelandic it-IT,Italian ja-JP,Japanese ko-KR,Korean nb-NO,Norwegian pl-PL,Polish pt-BR,"Portuguese, Brazilian" pt-PT,"Portuguese, European" ro-RO,Romanian ru-RU,Russian es-ES,"Spanish, European" es-MX,"Spanish, Mexican" es-US,"Spanish, US" sv-SE,Swedish tr-TR,Turkish cy-GB,Welsh ``` <file_sep>/go.mod module github.com/chaunceyt/pollyctl go 1.13 require ( github.com/aws/aws-sdk-go v1.26.4 github.com/urfave/cli v1.22.2 ) <file_sep>/main.go package main import ( "io" "log" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/polly" "github.com/urfave/cli" "fmt" "io/ioutil" "os" ) // Main entry. func main() { app := cli.NewApp() app.Name = "pollyctl" app.Usage = "Turn text into \"lifelike\" speech using AWS Polly" app.Version = "1.0.0" app.Commands = []cli.Command{ { Name: "text-to-speech", Usage: "Convert text to speech", Flags: []cli.Flag{ cli.StringFlag{ Name: "input-file", Usage: "Name of the file containing text to be converted.", }, cli.StringFlag{ Name: "output-file", Usage: "Name of MP3 file to create.", }, cli.StringFlag{ Name: "voice-id", Usage: "Voice that will read the converted text.", Value: "Kimberly", }, cli.StringFlag{ Name: "text-type", Usage: "Input text type plain text or ssml.", Value: "text", }, cli.StringFlag{ Name: "sample-rate", Usage: "Audio frequency specified in Hz.", Value: "16000", }, cli.StringFlag{ Name: "aws-profile", Usage: "AWS Profile to use.", Value: "default", }, cli.StringFlag{ Name: "aws-region", Usage: "AWS Region to use.", Value: "us-east-1", }, }, Action: func(c *cli.Context) error { fmt.Println("Converting text to an mp3 file...") createMP3(c) return nil }, }, { Name: "list-voices", Usage: "List available voices", Flags: []cli.Flag{ cli.StringFlag{ Name: "lang-code", Usage: "Language .", Value: "en-US", }, cli.StringFlag{ Name: "aws-profile", Usage: "AWS Profile to use.", Value: "default", }, cli.StringFlag{ Name: "aws-region", Usage: "AWS Region to use.", Value: "us-east-1", }, }, Action: func(c *cli.Context) error { fmt.Println("Getting list of available voices...") listVoices(c) return nil }, }, } err := app.Run(os.Args) if err != nil { log.Fatal(err) } } // listVoices for a specific lang-code. func listVoices(c *cli.Context) { // Assign language code. langCode := c.String("lang-code") region := c.String("aws-region") profile := c.String("aws-profile") sess := session.Must(session.NewSessionWithOptions(session.Options{ Config: aws.Config{Region: aws.String(region)}, Profile: profile, SharedConfigState: session.SharedConfigEnable, })) // Create Polly client svc := polly.New(sess) input := &polly.DescribeVoicesInput{LanguageCode: aws.String(langCode)} resp, err := svc.DescribeVoices(input) if err != nil { fmt.Println("Got error calling DescribeVoices:") fmt.Print(err.Error()) os.Exit(1) } for _, v := range resp.Voices { fmt.Println(*v.Name, "("+*v.Gender+")") } } // createMP3 from input test file. func createMP3(c *cli.Context) { if c.String("input-file") == "" { fmt.Println("You must supply an input file for conversion") os.Exit(1) } if c.String("output-file") == "" { fmt.Println("You must supply a name for the file we are creating") os.Exit(1) } // AWS Region and Profile. region := c.String("aws-region") profile := c.String("aws-profile") // Input and Output filename(s) fileName := c.String("input-file") outFileName := c.String("output-file") // Voice to use voiceID := c.String("voice-id") // Text Type plain text or ssml textType := c.String("text-type") // SampleRate the audio frequency in Hz sampleRate := c.String("sample-rate") contents, err := ioutil.ReadFile(fileName) if err != nil { fmt.Println(err.Error()) os.Exit(1) } s := string(contents[:]) sess := session.Must(session.NewSessionWithOptions(session.Options{ Config: aws.Config{Region: aws.String(region)}, Profile: profile, SharedConfigState: session.SharedConfigEnable, })) svc := polly.New(sess) input := &polly.SynthesizeSpeechInput{ OutputFormat: aws.String("mp3"), Text: aws.String(s), VoiceId: aws.String(voiceID), TextType: aws.String(textType), SampleRate: aws.String(sampleRate), } output, err := svc.SynthesizeSpeech(input) mp3File := outFileName outFile, err := os.Create(mp3File) defer outFile.Close() _, err = io.Copy(outFile, output.AudioStream) if err != nil { fmt.Println("Error saving MP3:") fmt.Print(err.Error()) os.Exit(1) } } <file_sep>/build.sh #!/bin/bash -e # Build for supported platforms. for GOOS in darwin linux; do for GOARCH in amd64; do env GOOS=$GOOS GOARCH=$GOARCH go build -v -o releases/pollyctl-$GOOS-$GOARCH done done
df5a58ea8aa6f00735987fc96685ba4fea71085f
[ "Markdown", "Go Module", "Go", "Shell" ]
4
Markdown
chaunceyt/pollyctl
da016f4655bca8d554285e9ed5f20d2b8b6ae037
32eee9f58a4f6b84a89f91557d514d2e0fd0b021
refs/heads/master
<repo_name>fachririyanto/training-reactjs<file_sep>/context-api/src/App.js /* import modules */ import React, { Component } from 'react' /* import provider from context */ import { Provider } from './context' /* import components */ import Login from './components/login' import Welcome from './components/welcome' /** * Main component. * @version 1.0.0 * @package Training/ReactJS/ContextAPI */ export default class App extends Component { /** * Init state. */ state = { isLoggedIn: false, user: {} } /** * Class constructor. * @param {Object} props */ constructor(props) { super(props) this.updateLoginStatus = this.updateLoginStatus.bind(this) } /** * Change login status. * @param {Bool} state Login state. * @param {Object} user User data. * @return void * @since 1.0.0 */ updateLoginStatus(state, user) { this.setState({ isLoggedIn: state, user: user }) } /** * Render layout. * @return {Element} */ render() { const { user } = this.state const { updateLoginStatus } = this return ( <Provider value={{ user, updateLoginStatus }}> {this.state.isLoggedIn ? <Welcome /> : <Login />} </Provider> ) } }<file_sep>/context-api/src/components/login.js /* import modules */ import React from 'react' /* import consumer from context */ import { Consumer } from '../context' /** * Login component. */ const Login = () => { return ( <Consumer> {({ updateLoginStatus }) => ( <p> <button onClick={() => updateLoginStatus(true, { username: 'fachririyanto' })}>Login</button> </p> )} </Consumer> ) } export default Login<file_sep>/redux/src/App.js /* import modules */ import React from 'react' import { connect } from 'react-redux' /* import components */ import Login from './components/login' import Welcome from './components/welcome' /** * Main component. * @version 1.0.0 * @package Training/ReactJS/Redux */ const App = (props) => { return ( <section> <h1>Learn Redux.</h1> {props.isLoggedIn ? <Welcome /> : <Login />} </section> ) } /** * Connecting store to component. */ const mapStateToProps = state => { return { isLoggedIn: state.loginState.isLoggedIn, user: state.loginState.user } } export default connect(mapStateToProps)(App)<file_sep>/jwt/src/global.js /** * Define login session. * @var {String} */ export const LOGIN_SESSION = 'login_state'<file_sep>/redux/src/actions.js /** * Define action types. */ export const SET_LOGIN_STATUS = 'SET_LOGIN_STATUS' /** * Define action creators. */ export const setLoginStatus = (state, user) => ({ type: SET_LOGIN_STATUS, isLoggedIn: state, user: user })<file_sep>/jwt/src/utils.js /** * Validate if a variable is function type or not. * @param {Func} func * @return {Bool} * @link Reference https://stackoverflow.com/questions/5999998/check-if-a-variable-is-of-function-type */ export const isFunction = (func) => { return func && {}.toString.call(func) === '[object Function]'; }<file_sep>/jwt/src/App.js /* import modules */ import React, { Component } from 'react' /* import global variables */ import { LOGIN_SESSION } from './global' /* import utils */ import { isFunction } from './utils' /* import components */ import LoginForm from './components/loginform' import UserList from './components/userlist' /** * App component. * @version 1.0.0 * @package Training/ReactJS/JWT */ class App extends Component { constructor(props) { super(props) this.state = { isLoggedIn: false, user: {} } } /** * Get user session. * @return {Object} user * @since 1.0.0 */ getSession() { // load state from local storage let state = localStorage.getItem(LOGIN_SESSION) state = state === undefined ? { isLoggedIn: false, user: {} } : JSON.parse(state) return state } /** * Init component state from local storage. * @since 1.0.0 */ componentDidMount() { // load state from local storage let state = this.getSession() // init default state this.setState(state) } /** * Function to update login state. * @param {Bool} state Is user has logged in? * @param {Object} user User data. * @param {Func} callback Function to run after state is changes. * @return void * @since 1.0.0 */ updateLoginState(state, user, callback) { // define new state const newState = { isLoggedIn: state, user: user } // save state in local storage localStorage.setItem(LOGIN_SESSION, JSON.stringify(newState)) // update state this.setState({ isLoggedIn: state, user: user }, () => { // do you want to do something here? add callback!! if (isFunction(callback)) { callback() } }) } /** * Render element. * @return {Element} */ render() { return ( <div> {this.state.isLoggedIn ? <UserList session={this.getSession()} updateLoginState={this.updateLoginState.bind(this)} /> : <LoginForm updateLoginState={this.updateLoginState.bind(this)} /> } </div> ) } } export default App<file_sep>/redux/src/components/login.js /* import modules */ import React from 'react' import { connect } from 'react-redux' import { setLoginStatus } from '../actions' /** * Login component. */ const Login = ({ dispatch }) => { let inputUsername let inputPassword return ( <form onSubmit={e => { e.preventDefault() if (!inputUsername.value.trim()) { alert('Username is empty.') return } if (!inputPassword.value.trim()) { alert('Password is empty.') return } dispatch(setLoginStatus(true, { username: inputUsername.value })) inputUsername.value = '' inputPassword.value = '' }}> <p> <label>Username</label> <input type="text" ref={node => inputUsername = node} /> </p> <p> <label>Password</label> <input type="<PASSWORD>" ref={node => inputPassword = node} /> </p> <p> <button type="submit">Login</button> </p> </form> ) } export default connect()(Login)<file_sep>/jwt/src/components/loginform.js /* import modules */ import React, { Component } from 'react' /** * Login form component. * @version 1.0.0 * @since Training/ReactJS/JWT 1.0.0 */ class LoginForm extends Component { constructor(props) { super(props) this.state = { username: '', password: '' } } /** * Handle submit button. * @param {Event} event * @since 1.0.0 */ onSubmit(event) { event.preventDefault() // do validation if (this.state.username === undefined || this.state.username === '') { alert('Username is empty.') return } if (this.state.password === undefined || this.state.password === '') { alert('Password is empty.') return } // check data (user) to API fetch('http://localhost:8000/users/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: this.state.username, password: <PASSWORD> }) }) .then((responses) => { return responses.json() }).then((data) => { if (data.status) { if (data.message === '') { // do if login successfully this.props.updateLoginState(true, data.data) } else { // show alert if it exists switch (data.message) { case 'account_not_exist': { alert('Account is not exists.') break; } default: {} } } } else { alert('Opps!! Something error...') } }) } /** * Render element. * @return {Element} */ render() { return ( <form onSubmit={this.onSubmit.bind(this)}> <p> <label>Username</label> <input type="text" value={this.state.username} onChange={(e) => this.setState({ username: e.target.value })} /> </p> <p> <label>Password</label> <input type="password" value={this.state.password} onChange={(e) => this.setState({ password: e.target.value })} /> </p> <p> <button type="submit">Login</button> </p> </form> ) } } export default LoginForm<file_sep>/context-api/src/components/welcome.js /* import modules */ import React from 'react' /* import consumer from context */ import { Consumer } from '../context' /** * Welcome component. */ const Welcome = () => { return ( <Consumer> {({ user, updateLoginStatus }) => ( <div> <p>Welcome, {user.username}</p> <button onClick={() => updateLoginStatus(false, {})}>Logout</button> </div> )} </Consumer> ) } export default Welcome<file_sep>/jwt/src/components/userlist.js /* import modules */ import React, { Component } from 'react' /* import global variables */ import { LOGIN_SESSION } from '../global' /** * User list component. * @version 1.0.0 * @since Training/ReactJS/JWT 1.0.0 */ class UserList extends Component { constructor(props) { super(props) this.state = { users: [] } } /** * Fetch data users. * @since 1.0.0 */ componentDidMount() { // get session const session = this.props.session // get users list fetch('http://localhost:8000/users', { method: 'GET', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${session.user.token}` } }) .then((responses) => { return responses.json() }).then((data) => { this.setState({ users: data.data }) }) } /** * Handle logout button. * @param {Event} event * @since 1.0.0 */ onLogout(event) { event.preventDefault() this.props.updateLoginState(false, {}, () => { localStorage.removeItem(LOGIN_SESSION) }) } /** * Render element. * @return {Element} */ render() { if (this.state.users === undefined || this.state.users.length === 0) { return null } let lists = this.state.users.map((user) => <li key={user.ID}>{user.fullname}</li>) return ( <div> <p> <button onClick={this.onLogout.bind(this)}>Logout</button> </p> <ul>{lists}</ul> </div> ) } } export default UserList
b94532bf5df835b02b65d6497a6e9c9d22eb6d04
[ "JavaScript" ]
11
JavaScript
fachririyanto/training-reactjs
5802fbce0cb5d8725d3dfe4aabfb24ee430de3e9
9f17c96f919aef07a2d2d812a1ca3628823cbf97
refs/heads/master
<repo_name>Agfct/TestHelicopter2<file_sep>/app/src/main/java/com/example/anders/helicoptertask/branchTest.java package com.example.anders.helicoptertask; /** * Created by <NAME> on 18.01.2015. */ public class branchTest { //Test conflict comment int conflictInt = 8; } <file_sep>/app/src/main/java/com/example/anders/helicoptertask/GameLoopThread.java package com.example.anders.helicoptertask; import android.annotation.SuppressLint; import android.graphics.Canvas; /** * Created by Anders on 12.01.2015. */ public class GameLoopThread extends Thread{ private boolean isrunning = false; private GameSurfaceView view; public GameLoopThread(GameSurfaceView view) { this.view = view; } @SuppressLint("WrongCall") @Override public void run(){ Canvas c = null; while(isrunning){ try{ c = view.getHolder().lockCanvas(); synchronized (view.getHolder()){ view.onDraw(c); } } finally{ if(c != null){ view.getHolder().unlockCanvasAndPost(c); } } } } public void setRunning(boolean isrunning){ this.isrunning = isrunning; } } <file_sep>/app/src/main/java/com/example/anders/helicoptertask/Helicopter.java package com.example.anders.helicoptertask; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.graphics.Rect; import android.util.Log; import android.view.MotionEvent; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * Created by Anders on 12.01.2015. */ public class Helicopter { private Bitmap sprite; private int x; private int y; private int speedX; private int speedY; private int rows = 2; private int col = 4; private int height; private int width; private int currentFrame = 0; private GameSurfaceView gameSurfaceView; private int curDir = 0; private int goToX = 0; private int goToY = 0; private Point[][] grid; private boolean controlled = false; private List<Point> line = new ArrayList<Point>(); private int animationRow = 0; public Helicopter (int x, int y, GameSurfaceView view){ this.gameSurfaceView = view; this.x = x; this.y = y; sprite = BitmapFactory.decodeResource(view.getResources(),R.drawable.helicopter); this.height = sprite.getHeight()/ rows; this.width = sprite.getWidth() / col; //TASK 1 Random start values Random rnd = new Random(); speedX = rnd.nextInt(10)-5; speedY = rnd.nextInt(10) -5; if(speedX >0){ animationRow = 1; }else { animationRow = 0; } } public void setGrid(){ this.grid = new Point [gameSurfaceView.getWidth()][gameSurfaceView.getHeight()]; for (int i = 0; i < gameSurfaceView.getWidth(); i++) for (int j = 0; j < gameSurfaceView.getHeight(); j++) grid[i][j] = new Point(i, j); } private void update() { if(!controlled) { //When you hit right or left if (x >= gameSurfaceView.getWidth() - width - speedX || x + speedX <= 0) { if(x >= gameSurfaceView.getWidth()-width - speedX){ Log.e("if", "anim row 0"); animationRow = 0; }else{ Log.e("else", "anim row 1"); animationRow = 1; } speedX = -speedX; } x = x + speedX; if (y >= gameSurfaceView.getHeight() - height - speedY || y + speedY <= 0) { speedY = -speedY; } y = y + speedY; }else{ if(line.size() > 0){ Point tempPoint = line.remove(0); if(line.size() > 0){ Point tempPoint2 = line.remove(0); } if (!(x >= gameSurfaceView.getWidth() - width - speedX || x + speedX <= 0)){ speedX = tempPoint.x - getX(); if(speedX >0){ animationRow = 1; }else { animationRow = 0; } setX(tempPoint.x); } if (!(y >= gameSurfaceView.getHeight() - height - speedY || y + speedY <= 0)) { speedY = tempPoint.y - getY(); setY(tempPoint.y); } }else { controlled = false; } } currentFrame = ++currentFrame % col; } //Draws the Helicopter to the screens canvas. public void onDraw(Canvas canvas){ update(); int srcX = currentFrame * width; int srcY = getAnimationRow() * height; //This is the spot in the bitmap that we are currently drawing Rect src = new Rect(srcX, srcY, srcX+width,srcY+height); //This is the spot in the canvas we are drawing it to Rect dst = new Rect(x, y, x+width, y+height); canvas.drawBitmap(sprite, src, dst, null); Paint paint = new Paint(); paint.setColor(Color.BLACK); paint.setTextSize(paint.getTextSize()*2); canvas.drawText("x: "+x + "y: "+y,10,20,paint); } private int getAnimationRow() { return animationRow; } public void moveHelicopter(MotionEvent event){ controlled = true; goToX = Math.round(event.getX()); goToY = Math.round(event.getY()); line = findLine(grid, x,y,goToX,goToY); } public List<Point> findLine(Point[][] grid, int x0, int y0, int x1, int y1) { List<Point> line = new ArrayList<Point>(); int dx = Math.abs(x1 - x0); int dy = Math.abs(y1 - y0); int sx = x0 < x1 ? 1 : -1; int sy = y0 < y1 ? 1 : -1; int err = dx-dy; int e2; while (true) { line.add(grid[x0][y0]); if (x0 == x1 && y0 == y1) break; e2 = 2 * err; if (e2 > -dy) { err = err - dy; x0 = x0 + sx; } if (e2 < dx) { err = err + dx; y0 = y0 + sy; } } return line; } public int getSpeedX() { return speedX; } public void setSpeedX(int speedX) { this.speedX = speedX; } public int getSpeedY() { return speedY; } public void setSpeedY(int speedY) { this.speedY = speedY; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } } <file_sep>/app/src/main/java/com/example/anders/helicoptertask/branchClass.java package com.example.anders.helicoptertask; /** * Created by <NAME> on 18.01.2015. */ public class branchClass { //Conflict? int conflictInt = 0; }
fb056720af6a49113fa5283c22d8148ff64332c0
[ "Java" ]
4
Java
Agfct/TestHelicopter2
9c100431bf382a35c1407d31a59b9757316454e0
0c149ae13fe0f42c101790eefca0249dfbe1fb4f
refs/heads/master
<repo_name>ULL-ESIT-LPP-1819/tdd-alu0100845396<file_sep>/README.md [![Build Status](https://travis-ci.org/ULL-ESIT-LPP-1819/tdd-alu0100845396.svg?branch=master)](https://travis-ci.org/ULL-ESIT-LPP-1819/tdd-alu0100845396) [![Coverage Status](https://coveralls.io/repos/github/ULL-ESIT-LPP-1819/tdd-alu0100845396/badge.svg?branch=master)](https://coveralls.io/github/ULL-ESIT-LPP-1819/tdd-alu0100845396?branch=master) # Práctica 11: Programación Funcional * Universidad de La Laguna - ULL * Asignatura: Lenguajes y Paradigmas de Programación * Curso: 2018/19 ## Integración contínua - Travis ![](https://i.imgur.com/rC47pcm.png) ## Autor [<NAME>](https://beejeke.github.io/) <file_sep>/spec/comparable_spec.rb # Práctica 9 - Lenguajes y Paradigmas de Programación # # La etiqueta de información nutricional es la información sobre el aporte energéico (calórico) # y contenido de nutrientes que aparece en los envases de los alimentos y bebidas. También se denomina #“etiquetado sobre las propiedades nutritivas”. # # Autor: <NAME> - GH: alu0100845396 / beejeke # encoding: UTF-8 require "spec_helper" describe Etiqueta do before :each do @etiqueta = Etiqueta.new("Guacamole",17.2,2.4,0,0,3,1.4,0,0,3.2,1.5,1.3) @etiqueta2 = Etiqueta.new("Salmón",54,6,0,0,4,0,6,7,0,0,8) end it "Comprobar que etiqueta es menor que etiqueta2" do expect(@etiqueta < @etiqueta2).to eq(true) end it "Comprobar que etiqueta es menor o igual que etiqueta2" do expect(@etiqueta <= @etiqueta2).to eq(true) end it "Comprobar que etiqueta es igual a etiqueta2" do expect(@etiqueta == @etiqueta2).to eq(false) end it "Comprobar que etiqueta es igual que etiqueta2" do expect(@etiqueta > @etiqueta2).to eq(false) end it "Comprobar que etiqueta es mayor o igual que etiqueta2" do expect(@etiqueta >= @etiqueta2).to eq(false) end it "Comprobar que etiqueta está entre etiqueta2" do expect(@etiqueta.between?(@etiqueta2,@etiqueta2)).to eq(false) end context "#Comparable para Paciente" do before :each do @paciente = Paciente.new("Juan", 65, 1.70, 23, 1, [84, 85.0], [71, 70.0], 0.12) @paciente2 = Paciente.new("Fernando", 93, 1.85, 45, 1, [91, 90.0], [82, 83.0], 0.54) end it "Comprobación de que paciente es menor que paciente2" do expect(@paciente < @paciente2).to eq(true) end it "Comprobación de que paciente es menor o igual que paciente2" do expect(@paciente <= @paciente2).to eq(true) end it "Comprobación de que paciente es igual que paciente2" do expect(@paciente == @paciente2).to eq(false) end it "Comprobación de que paciente es mayor que paciente2" do expect(@paciente > @paciente2).to eq(false) end it "Comprobación de que paciente es mayor o igual que paciente2" do expect(@paciente >= @paciente2).to eq(false) end it "Comprobación de que paciente está entre paciente2" do expect(@paciente.between?(@paciente2,@paciente2)).to eq(false) end end end<file_sep>/lib/prct06/individuo.rb # Práctica 8 - Lenguajes y Paradigmas de Programación # # La etiqueta de información nutricional es la información sobre el aporte energéico (calórico) # y contenido de nutrientes que aparece en los envases de los alimentos y bebidas. También se denomina #“etiquetado sobre las propiedades nutritivas”. # # Autor: <NAME> - GH: alu0100845396 / beejeke # encoding: UTF-8 require "prct06/antrodata" # Declaración de la clase Individuo class Individuo # Inclusión del mixin Comparable include Comparable attr_accessor :nombre # Método initialize de la clase Individuo def initialize(nombre) @nombre = nombre end end # Declaración de cla clase Paciente, que hereda de Individuo class Paciente < Individuo attr_accessor :datos # Método initialize de la clase Paciente def initialize(nombre, peso, talla, edad, sexo, cintura, cadera, factor) @nombre = nombre @datos = AntroData.new(peso, talla, edad, sexo, cintura, cadera, factor) end # Método to_s que muestra los datos y el nombre del paciente def to_s tmp = "Nombre #{@nombre}\n" tmp += @datos.to_s end # Método <=> del mixin Comparable def <=> (other) datos.calculate_imc <=> other.datos.calculate_imc end # Método para calcular el PTI def peso_teorico_ideal ((@datos.talla - 1.50) * 100 * 0.75 + 50).round(2) end # Método para calcular el GEB def gasto_energetico_basal if (@datos.sexo == 0) ((10 * @datos.peso) + (6.25 * @datos.talla * 100) - (5 * @datos.edad) - 161).round(2) elsif(@datos.sexo == 1) ((10 * @datos.peso) + (6.25 * @datos.talla * 100) - (5 * @datos.edad) + 5).round(2) end end # Método para calcular el ET def efecto_termogeno (gasto_energetico_basal * 0.10).round(2) end #Método para calcular el GAF def gasto_actividad_fisica (gasto_energetico_basal * @datos.factor).round(2) end # Método para calcular el GET def gasto_energetico_total (gasto_energetico_basal + efecto_termogeno + gasto_actividad_fisica).round(2) end end<file_sep>/lib/prct06/lista_value.rb # Práctica 7 - Lenguajes y Paradigmas de Programación # # La etiqueta de información nutricional es la información sobre el aporte energéico (calórico) # y contenido de nutrientes que aparece en los envases de los alimentos y bebidas. También se denomina #“etiquetado sobre las propiedades nutritivas”. # # Autor: <NAME> - GH: alu0100845396 / beejeke # encoding: UTF-8 Node = Struct.new(:value, :next, :prev) class ListValue include Enumerable, Comparable attr_accessor :head, :tail def initialize @head = nil @tail = nil end def insert_val(value) node = Node.new(value, nil, @tail) @head = node if @head.nil? @tail.next = node unless @tail.nil? @tail = node end def extract_val return nil if self.empty aux = @head @head = @head.next @head.prev = nil unless @head.nil? @tail = nil if @head.nil? aux.next = nil aux end def to_s node = Node.new(nil,nil,nil) node = @head tmp = "{" if !(node.nil?) tmp += " #{node.value.to_s}" node = node.next end while !(node.nil?) tmp += ", #{node.value.to_s}" node = node.next end tmp += " }" tmp end def length size = 0 node = @head while !(node.nil?) size = size + 1 node = node.next end size end def empty @head.nil? end def each(&block) node = Node.new(nil,nil,nil) node = @head while !(node.nil?) yield node.value node = node.next end end def sort_for tmp = map{|x| x.gasto_energetico_total} orden = [] orden.push(tmp[0]) for i in (1..length - 1) for j in (0..i) if(orden[j] >= tmp[i]) orden.insert(j,tmp[i]) break elsif(orden[orden.length - 1] <= tmp[i]) orden.push(tmp[i]) break end end end orden end def sort_each tmp = map{ |x| x.gasto_energetico_total} i = 0 tmp.each do |x| a = x i1 = i j = i1 + 1 tmp[j..tmp.length - 1].each do |y| if (a > y) a = y i1 = j end j+=1 end tmp[i1] = x tmp[i] = a i+=1 end tmp end end def clasification (lista) sal_ir = ListValue.new() sal_mal = ListValue.new() node = lista.extract_val while !(node.nil?) if node.value.sal > 6 sal_mal.insert_val(node.value.sal) else sal_ir.insert_val(node.value.sal) end node = lista.extract_val end "{#{sal_ir.to_s}, #{sal_mal.to_s}}" end def clasificate_imc (lista) obeso = ListValue.new() no_obeso = ListValue.new() node = lista.extract_val while !(node.nil?) if node.value.datos.calculate_imc >= 30.0 obeso.insert_val(node.value.datos.calculate_imc) else no_obeso.insert_val(node.value.datos.calculate_imc) end node = lista.extract_val end clasificacion = ListValue.new clasificacion.insert_val(no_obeso) clasificacion.insert_val(obeso) clasificacion.to_s end<file_sep>/spec/individuo_spec.rb # Práctica 8 - Lenguajes y Paradigmas de Programación # # La etiqueta de información nutricional es la información sobre el aporte energéico (calórico) # y contenido de nutrientes que aparece en los envases de los alimentos y bebidas. También se denomina #“etiquetado sobre las propiedades nutritivas”. # # Autor: <NAME> - GH: alu0100845396 / beejeke # encoding: UTF-8 require "spec_helper" describe Etiqueta do context "# Expectativas de herencia de la clase Individuo" do before :each do @individuo = Individuo.new("Marcos") @paciente = Paciente.new("Francisco", 65, 1.70, 23, 1, [84, 85.0], [71, 70.0], 0.12) @list1 = ListValue.new() end it "Expectativas de jerarquía de clases y herencia" do expect(@list1).to be_a_kind_of(ListValue) expect(@list1).not_to be_a_kind_of(Paciente) expect(@individuo).not_to be_a_kind_of(Paciente) expect(@individuo).to be_a_kind_of(Individuo) expect(@individuo).to be_a_kind_of(Object) expect(@individuo).to be_a_kind_of(BasicObject) expect(@paciente).to be_a_kind_of(Paciente) expect(@paciente).to be_a_kind_of(Individuo) expect(@paciente).to be_a_kind_of(Object) expect(@paciente).to be_a_kind_of(BasicObject) end it "El objeto Individuo es una instancia de la clase Individuo" do expect(@individuo).to be_an_instance_of(Individuo) end it "El objeto Paciente es una instancia de la clase Paciente" do expect(@paciente).to be_an_instance_of(Paciente) end it "El objeto Individuo responde al método nombre" do expect(@individuo).to respond_to(:nombre) end it "El objeto Paciente responde a los metodos nombre y datos" do expect(@paciente).to respond_to(:nombre, :datos) end it "El objeto Paciente responde al metodo to_s" do expect(@paciente).to respond_to('to_s') end end context "# Método de clasificación de Pacientes" do before :each do @paciente = Paciente.new("Juan", 65, 1.70, 23, 1, [84, 85.0], [71, 70.0], 0.12) @paciente2 = Paciente.new("Fernando", 93, 1.85, 45, 1, [91, 90.0], [82, 83.0], 0.54) @paciente3 = Paciente.new("Mario", 112, 1.70, 67, 1, [99, 98.0], [90, 89.0], 0.54) @paciente4 = Paciente.new("Ana", 55, 1.63, 29, 0, [69, 70.0], [61, 60.0], 0.27) @paciente5 = Paciente.new("María", 82, 1.75, 55, 0, [74, 75.0], [69, 70.0], 0.12) @paciente6 = Paciente.new("Alicia", 150, 1.80, 46, 0, [84, 83.0], [79, 78.0], 0.12) end it "Clasificación de pacientes en tratamiento contra la obesidad" do list = ListValue.new list.insert_val(@paciente) list.insert_val(@paciente2) list.insert_val(@paciente3) list.insert_val(@paciente4) list.insert_val(@paciente5) list.insert_val(@paciente6) expect(clasificate_imc(list)).to eq("{ { 22.49, 27.17, 20.7, 26.78 }, { 38.75, 46.3 } }") end end end<file_sep>/spec/ordenacion_spec.rb # Práctica 11 - Lenguajes y Paradigmas de Programación # # Se ha te tener en cuenta que un men´u diet´etico esta compuesto por un conjunto de # alimentos procesados, donde cada uno de ellos cuenta con una etiqueta de informaci´on nutricional. # La energ´ıa, grasas, hidratos de carbono, prote´ınas, l´ıpidos, fibra y sal del men´u se obtienen a partir # de los alimentos que lo componen. # # Autor: <NAME> - GH: alu0100845396 / beejeke # encoding: UTF-8 require "spec_helper" require "benchmark" describe Etiqueta do context "# Expectativas de array de menús " do before :each do @paciente = Paciente.new("Juan", 65, 1.70, 23, 1, [84, 85.0], [71, 70.0], 0.12) @paciente2 = Paciente.new("Fernando", 93, 1.85, 45, 1, [91, 90.0], [82, 83.0], 0.54) @paciente3 = Paciente.new("Mario", 112, 1.70, 67, 1, [99, 98.0], [90, 89.0], 0.54) @paciente4 = Paciente.new("Ana", 55, 1.63, 29, 0, [69, 70.0], [61, 60.0], 0.27) @paciente5 = Paciente.new("María", 82, 1.75, 55, 0, [74, 75.0], [69, 70.0], 0.12) @etiqueta = Etiqueta.new("Guacamole", 17.2, 2.4, 0, 0, 3, 1.4, 0, 0, 3.2, 1.5, 5) @etiqueta2 = Etiqueta.new("Cereales", 7, 4, 0, 0, 71, 36, 0, 46, 4, 0, 6) @etiqueta3 = Etiqueta.new("<NAME>", 0.1, 0, 0, 0, 9.5, 8.9 ,0 ,0 ,0.6, 0.6, 1) @etiqueta4 = Etiqueta.new("<NAME>", 21.9, 6.3, 0, 0, 0.5, 0.5, 0, 0, 0.1, 30, 9) @etiqueta5 = Etiqueta.new("Jamón", 21.9, 6.3, 0, 0, 0.5, 0.5, 0, 0, 0.1, 30, 10) @menu = ListValue.new @menu.insert_val(@etiqueta2) @menu.insert_val(@etiqueta4) @menu2 = ListValue.new @menu2.insert_val(@etiqueta3) @menu2.insert_val(@etiqueta5) @menu3 = ListValue.new @menu3.insert_val(@etiqueta4) @menu3.insert_val(@etiqueta2) @menu4 = ListValue.new @menu4.insert_val(@etiqueta5) @menu4.insert_val(@etiqueta) @menu5 = ListValue.new @menu5.insert_val(@etiqueta3) @menu5.insert_val(@etiqueta4) @menu_array = [@menu, @menu2, @menu3, @menu4, @menu5, @menu, @menu2, @menu3, @menu4, @menu5] @paciente_list = ListValue.new @paciente_list.insert_val(@paciente) @paciente_list.insert_val(@paciente2) @paciente_list.insert_val(@paciente3) @paciente_list.insert_val(@paciente4) @paciente_list.insert_val(@paciente5) @paciente_list.insert_val(@paciente) @paciente_list.insert_val(@paciente2) @paciente_list.insert_val(@paciente3) @paciente_list.insert_val(@paciente4) @paciente_list.insert_val(@paciente5) end it "Se ordena una lista de valoraciones nutricionales de pacientes con for, each y sort correctamente " do expect(@paciente_list.sort_each).to eq([1729.97, 1729.97, 1802.86, 1802.86, 1955.05, 1955.05, 3038.1, 3038.1, 3060.66, 3060.66]) expect(@paciente_list.sort_for).to eq([1729.97, 1729.97, 1802.86, 1802.86, 1955.05, 1955.05, 3038.1, 3038.1, 3060.66, 3060.66]) expect(@paciente_list.map{ |x| x.gasto_energetico_total}.sort ).to eq([1729.97, 1729.97, 1802.86, 1802.86, 1955.05, 1955.05, 3038.1, 3038.1, 3060.66, 3060.66]) end it "Se ordena un array de menús con for, each y sort correctamente" do expect(@menu_array.sort_each).to eq([421.8, 421.8, 427.8, 427.8, 588.5, 588.5, 948.3, 948.3, 948.3, 948.3]) expect(@menu_array.sort_for).to eq([421.8, 421.8, 427.8, 427.8, 588.5, 588.5, 948.3, 948.3, 948.3, 948.3]) expect(@menu_array.map{ |x| x.reduce(:+)}.sort).to eq([421.8, 421.8, 427.8, 427.8, 588.5, 588.5, 948.3, 948.3, 948.3, 948.3]) end it "Benchmark para Array y ListValue" do n = 50000 Benchmark.bm do |x| x.report("for -> Lista:") {n.times do @paciente_list.sort_for; end} x.report("each -> Lista:"){n.times do @paciente_list.sort_each; end} x.report("sort -> Lista:"){n.times do @paciente_list.map{ |x| x.gasto_energetico_total}.sort ; end} x.report("for -> Array:") {n.times do @menu_array.sort_for; end} x.report("each -> Array:"){n.times do @menu_array.sort_each; end} x.report("sort -> Array:"){n.times do @menu_array.map{ |x| x.reduce(:+)}.sort; end} end end end end<file_sep>/lib/prct06/array.rb # Práctica 11 - Lenguajes y Paradigmas de Programación # # Se ha te tener en cuenta que un men´u diet´etico esta compuesto por un conjunto de # alimentos procesados, donde cada uno de ellos cuenta con una etiqueta de informaci´on nutricional. # La energ´ıa, grasas, hidratos de carbono, prote´ınas, l´ıpidos, fibra y sal del men´u se obtienen a partir # de los alimentos que lo componen. # # Autor: <NAME> - GH: alu0100845396 / beejeke # encoding: UTF-8 class Array def sort_for tmp = map{|x| x.reduce(:+)} orden = [] orden.push(tmp[0]) for i in (1..length - 1) for j in (0..i) if (tmp[i] < orden[j]) orden.insert(j,tmp[i]) break elsif (orden[(orden.length)-1] <= tmp[i]) orden.push(tmp[i]) break end end end return orden end def sort_each tmp = map{ |x| x.reduce(:+)} orden = [] i = 0 tmp.each do |x| a = x i1 = i j = i1+1 tmp[j..tmp.length - 1].each do |y| if (a > y) a = y i1 = j end j+=1 end tmp[i1] = x tmp[i] = a i+=1 end tmp end end<file_sep>/spec/menu_spec.rb # Práctica 10 - Lenguajes y Paradigmas de Programación # # La generación y validación de menús dietéticos la realizan expertos en nutrición, teniendo en cuenta # las recomendaciones nutricionales recogidas en guías alimentarias y los atributos del individuo. Los # menús se diseñan de manera que satisfagan los requerimientos del individuo para mantener un estado # nutricional adecuado. Existen diferentes guías ajustadas a distintas regiones y también esquemas # reconocidos internacionalmente como adecuados, como por ejemplo, la dieta mediterránea. Así pues, # partiendo de la valoración nutricional de un individuo se le asocia un menú dietético adecuado. # # Autor: <NAME> - GH: alu0100845396 / beejeke # encoding: UTF-8 require "spec_helper" describe Etiqueta do context "# Expectativas de menú dietético " do before :each do @paciente = Paciente.new("Juan", 65, 1.70, 23, 1, [84, 85.0], [71, 70.0], 0.12) @paciente2 = Paciente.new("Fernando", 93, 1.85, 45, 1, [91, 90.0], [82, 83.0], 0.54) @paciente3 = Paciente.new("Mario", 112, 1.70, 67, 1, [99, 98.0], [90, 89.0], 0.54) @paciente4 = Paciente.new("Ana", 55, 1.63, 29, 0, [69, 70.0], [61, 60.0], 0.27) @paciente5 = Paciente.new("María", 82, 1.75, 55, 0, [74, 75.0], [69, 70.0], 0.12) @paciente6 = Paciente.new("Alicia", 150, 1.80, 46, 0, [84, 83.0], [79, 78.0], 0.12) @etiqueta = Etiqueta.new("Guacamole", 17.2, 2.4, 0, 0, 3, 1.4, 0, 0, 3.2, 1.5, 5) @etiqueta2 = Etiqueta.new("Cereales", 7, 4, 0, 0, 71, 36, 0, 46, 4, 0, 6) @etiqueta3 = Etiqueta.new("<NAME>", 0.1, 0, 0, 0, 9.5, 8.9 ,0 ,0 ,0.6, 0.6, 1) @etiqueta4 = Etiqueta.new("<NAME>", 21.9, 6.3, 0, 0, 0.5, 0.5, 0, 0, 0.1, 30, 9) @etiqueta5 = Etiqueta.new("Jamón", 21.9, 6.3, 0, 0, 0.5, 0.5, 0, 0, 0.1, 30, 10) @etiqueta6 = Etiqueta.new("Salmón", 54, 6, 0, 0, 4, 0, 6, 7, 0, 0, 8) @menu1 = [@etiqueta2, @etiqueta4] @menu2 = [@etiqueta3, @etiqueta5] @menu3 = [@etiqueta4, @etiqueta2] @menu4 = [@etiqueta5, @etiqueta6] @menu5 = [@etiqueta6, @etiqueta3] end it "Existe un método para calcular el PTI" do expect(@paciente.peso_teorico_ideal).to eq(65.0) expect(@paciente2.peso_teorico_ideal).to eq(76.25) expect(@paciente3.peso_teorico_ideal).to eq(65.0) expect(@paciente4.peso_teorico_ideal).to eq(59.75) expect(@paciente5.peso_teorico_ideal).to eq(68.75) expect(@paciente6.peso_teorico_ideal).to eq(72.5) end it "Existe un método para calcular el GEB" do expect(@paciente.gasto_energetico_basal).to eq(1602.5) expect(@paciente2.gasto_energetico_basal).to eq(1866.25) expect(@paciente3.gasto_energetico_basal).to eq(1852.5) expect(@paciente4.gasto_energetico_basal).to eq(1262.75) expect(@paciente5.gasto_energetico_basal).to eq(1477.75) expect(@paciente6.gasto_energetico_basal).to eq(2234) end it "Existe un método para calcular el ET" do expect(@paciente.efecto_termogeno).to eq(160.25) expect(@paciente2.efecto_termogeno).to eq(186.63) expect(@paciente3.efecto_termogeno).to eq(185.25) expect(@paciente4.efecto_termogeno).to eq(126.28) expect(@paciente5.efecto_termogeno).to eq(147.78) expect(@paciente6.efecto_termogeno).to eq(223.4) end it "Existe un método para calcular el GAF" do expect(@paciente.gasto_actividad_fisica).to eq(192.3) expect(@paciente2.gasto_actividad_fisica).to eq(1007.78) expect(@paciente3.gasto_actividad_fisica).to eq(1000.35) expect(@paciente4.gasto_actividad_fisica).to eq(340.94) expect(@paciente5.gasto_actividad_fisica).to eq(177.33) expect(@paciente6.gasto_actividad_fisica).to eq(268.08) end it "Existe un método para calcular el GET" do expect(@paciente.gasto_energetico_total).to eq(1955.05) expect(@paciente2.gasto_energetico_total).to eq(3060.66) expect(@paciente3.gasto_energetico_total).to eq(3038.1) expect(@paciente4.gasto_energetico_total).to eq(1729.97) expect(@paciente5.gasto_energetico_total).to eq(1802.86) expect(@paciente6.gasto_energetico_total).to eq(2725.48) end it "Menú dietético 1 para el paciente 4" do calorias_menu = @menu1.map{ |i| i.valor_ener_kj} total_calorias = calorias_menu.reduce(:+) gasto_energetico = @paciente4.gasto_energetico_total gasto_energetico = gasto_energetico * 0.10 expect(total_calorias >= gasto_energetico).to eq(true) end it "Menú dietético 2 para el paciente 2" do calorias_menu = @menu2.map{ |i| i.valor_ener_kj} total_calorias = calorias_menu.reduce(:+) gasto_energetico = @paciente2.gasto_energetico_total gasto_energetico = gasto_energetico * 0.10 expect(total_calorias >= gasto_energetico).to eq(true) end it "Menú dietético 3 para el paciente 5" do calorias_menu = @menu3.collect{ |x| x.valor_ener_kj} total_calorias = calorias_menu.reduce(:+) gasto_energetico = @paciente5.gasto_energetico_total gasto_energetico = gasto_energetico * 0.10 expect(total_calorias >= gasto_energetico).to eq(true) end it "Menú dietético 4 para el paciente 1" do calorias_menu = @menu4.collect{ |x| x.valor_ener_kj} total_calorias = calorias_menu.reduce(:+) gasto_energetico = @paciente.gasto_energetico_total gasto_energetico = gasto_energetico * 0.10 expect(total_calorias >= gasto_energetico).to eq(true) end it "Menú dietético 5 para el paciente 3" do calorias_menu = @menu5.collect{ |x| x.valor_ener_kj} total_calorias = calorias_menu.reduce(:+) gasto_energetico = @paciente3.gasto_energetico_total gasto_energetico = gasto_energetico * 0.10 expect(total_calorias >= gasto_energetico).to eq(true) end end end<file_sep>/lib/prct06/etiqueta_nutri.rb # Práctica 7 - Lenguajes y Paradigmas de Programación # # La etiqueta de información nutricional es la información sobre el aporte energéico (calórico) # y contenido de nutrientes que aparece en los envases de los alimentos y bebidas. También se denomina #“etiquetado sobre las propiedades nutritivas”. # # Autor: <NAME> - GH: alu0100845396 / beejeke # encoding: UTF-8 class Etiqueta # Clase Etiqueta # Módulo Comparable include Comparable # Constructor de la clase Etiqueta attr_reader :nombre, :grasas, :grasas_sat, :grasas_mono, :grasas_poli, :hidratos, :azucares, :polialcoholes, :almidon, :fibra, :proteinas, :sal def initialize(nombre, grasas, grasas_sat, grasas_mono, grasas_poli, hidratos, azucares, polialcoholes, almidon, fibra, proteinas, sal) @nombre = nombre @grasas = grasas @grasas_sat = grasas_sat @grasas_mono = grasas_mono @grasas_poli = grasas_poli @hidratos = hidratos @azucares = azucares @polialcoholes = polialcoholes @almidon = almidon @fibra = fibra @proteinas = proteinas @sal = sal end # Método para obtener la cantidad de grasas en Kj def grasas_kj (@grasas * 37).round(2) end # Método para obtener la cantidad de grasas monosaturadas en Kj def grasas_mono_kj (@grasas_mono * 37).round(2) end # Método para obtener la cantidad de grasas polisaturadas en Kj def grasas_poli_kj (@grasas_poli * 37).round(2) end # Método para obtener la cantidad de hidratos de carbono en Kj def hidratos_kj (@hidratos * 17).round(2) end # Método para obtener la cantidad de hidratos de carbono en Kj def polialcohol_kj (@polialcoholes * 10).round(2) end # Método para obtener la cantidad de almidon en Kj def almidon_kj (@almidon * 17).round(2) end # Método para obtener la cantidad de fibra en Kj def fibra_kj (@fibra * 8).round(2) end # Método para obtener la cantidad de proteínas en Kj def proteinas_kj (@proteinas * 17).round(2) end # Método para obtener la cantidad de sal en Kj def sal_kj (@sal * 25).round(2) end # Método para obtener el valor energético en Kj def valor_ener_kj val_ener = (grasas_kj + grasas_mono_kj + grasas_poli_kj + hidratos_kj + polialcohol_kj + almidon_kj + fibra_kj + proteinas_kj + sal_kj).round(2) end # Método para obtener grasas en Kcal def grasas_kcal (@grasas * 9).round(2) end # Método para obtener grasas monosaturadas en Kcal def grasas_mono_kcal (@grasas_mono * 9).round(2) end # Método para obtener grasas polisaturadas en Kcal def grasas_poli_kcal (@grasas_poli * 9).round(2) end # Método para obtener hidratos en Kcal def hidratos_kcal (@hidratos * 4).round(2) end # Método para obtener polialcoholes en Kcal def polialcohol_kcal (@polialcoholes * 2.4).round(2) end # Método para obtener almidón en Kcal def almidon_kcal (@almidon * 4).round(2) end # Método para obtener fibra en Kcal def fibra_kcal (@fibra * 2).round(2) end # Método para obtener proteínas en Kcal def proteinas_kcal (@proteinas * 4).round(2) end # Método para obtener sal en Kcal def sal_kcal (@sal * 6).round(2) end # Método para obtener valor enerético en Kcal def valor_ener_kcal (grasas_kcal + grasas_mono_kcal + grasas_poli_kcal+ hidratos_kcal + polialcohol_kcal + almidon_kcal + fibra_kcal + proteinas_kcal + sal_kcal).round(2) end # Método para obtener %IR valor energético def valor_ener_ir ((valor_ener_kj / 8400) * 100).round(2) end # Método para obtener %IR grasas def grasas_ir ((@grasas / 70) * 100).round(2) end # Método para obtener %IR grasas saturadas def saturadas_ir ((@grasas_sat / 20) * 100).round(2) end # Método para obtener %IR hidratos def hidratos_ir ((@hidratos / 260) * 100).round(2) end # Método para obtener %IR azúcares def azucares_ir ((@azucares / 90) * 100).round(2) end # Método para obtener %IR proteínas def proteinas_ir ((@proteinas / 50) * 100).round(2) end # Método para obtener %IR sales def sal_ir ((@sal / 6) * 100).round(2) end # Método to_s de visualización de datos def to_s puts "(Nombre de etiqueta: #{@nombre}, Grasas: #{@grasas}, Grasas saturadas: #{@grasas_sat}, Grasas monosaturadas: #{@grasas_mono}, Grasas polisaturadas: #{@grasas_poli}, Hidratos: #{@hidratos}, Azúcares: #{@azucares}, Polialcoholes: #{@polialcoholes}, Almidón: #{@almidon}, Fibra: #{@fibra}, Proteinas: #{@proteinas}, Sal: #{@sal})" end # Método <=> del mixin Comparable def <=> (other) valor_ener_kcal <=> other.valor_ener_kcal end # Método + del mixin Comparable def + (other) valor_ener_kcal + other.valor_ener_kcal end end<file_sep>/lib/prct06.rb require "prct06/version" require "prct06/etiqueta_nutri" require "prct06/lista" require "prct06/lista_value" module Prct06 class Error < StandardError; end # Your code goes here... end <file_sep>/spec/etiqueta_nutri_spec.rb # Práctica 7 - Lenguajes y Paradigmas de Programación # # La etiqueta de información nutricional es la información sobre el aporte energéico (calórico) # y contenido de nutrientes que aparece en los envases de los alimentos y bebidas. También se denomina #“etiquetado sobre las propiedades nutritivas”. # # Autor: <NAME> - GH: alu0100845396 / beejeke # encoding: UTF-8 require "spec_helper" describe Etiqueta do before :each do @etiqueta = Etiqueta.new("Guacamole",17.2,2.4,0,0,3,1.4,0,0,3.2,1.5,1.3) end describe "# Expectativas para Etiqueta" do it "Probando método para obtener el nombre de la etiqueta" do expect(@etiqueta.nombre).to eq("Guacamole") end it "Probando método para obtener cantidad de grasas" do expect(@etiqueta.grasas).to eq(17.2) end it "Probando método para obtener cantidad de grasas saturadas" do expect(@etiqueta.grasas_sat).to eq(2.4) end it "Probando método para obtener cantidad de grasas monosaturadas" do expect(@etiqueta.grasas_mono).to eq(0) end it "Probando método para obtener cantidad de grasas polisaturadas" do expect(@etiqueta.grasas_poli).to eq(0) end it "Probando método para obtener la cantidad de hidratos de carbono" do expect(@etiqueta.hidratos).to eq(3) end it "Probando método para obtener la cantidad de azúcares" do expect(@etiqueta.azucares).to eq(1.4) end it "Probando método para obtener la cantidad de polialcoholes" do expect(@etiqueta.polialcoholes).to eq(0) end it "Probando método para obtener la cantidad de almidón" do expect(@etiqueta.almidon).to eq(0) end it "Probando método para obtener la cantidad de fibra" do expect(@etiqueta.fibra).to eq(3.2) end it "Probando método para obtener la cantidad de proteínas" do expect(@etiqueta.proteinas).to eq(1.5) end it "Probando método para obtener la cantidad de sal" do expect(@etiqueta.sal).to eq(1.3) end it "Probando método para obtener cantidad de grasas en kilojulios (Kj)" do expect(@etiqueta.grasas_kj).to eq(636.4) end it "Probando método para obtener cantidad de grasas monosaturadas en kilojulios (Kj)" do expect(@etiqueta.grasas_mono_kj).to eq(0) end it "Probando método para obtener cantidad de grasas polisaturadas en kilojulios (Kj)" do expect(@etiqueta.grasas_poli_kj).to eq(0) end it "Probando método para obtener cantidad de hidratos de carbono en kilojulios (Kj)" do expect(@etiqueta.hidratos_kj).to eq(51) end it "Probando método para obtener cantidad de polialcoholes en kilojulios (Kj)" do expect(@etiqueta.polialcohol_kj).to eq(0) end it "Probando método para obtener cantidad de almidón en kilojulios (Kj)" do expect(@etiqueta.almidon_kj).to eq(0) end it "Probando método para obtener cantidad de fibra en kilojulios (Kj)" do expect(@etiqueta.fibra_kj).to eq(25.6) end it "Probando método para obtener cantidad de proteínas en kilojulios (Kj)" do expect(@etiqueta.proteinas_kj).to eq(25.5) end it "Probando método para obtener cantidad de sal en kilojulios (Kj)" do expect(@etiqueta.sal_kj).to eq(32.5) end it "Probando método para obtener de valor energético en kilojulios (Kj)" do expect(@etiqueta.valor_ener_kj).to eq(771) end it "Probando método para obtener cantidad de grasas en kilocalorías (Kcal)" do expect(@etiqueta.grasas_kcal).to eq(154.8) end it "Probando método para obtener cantidad de grasas monosaturadas en kilocalorías (Kcal)" do expect(@etiqueta.grasas_mono_kcal).to eq(0) end it "Probando método para obtener cantidad de grasas polisaturadas en kilocalorías (Kcal)" do expect(@etiqueta.grasas_poli_kcal).to eq(0) end it "Probando método para obtener cantidad de hidratos de carbono en kilocalorías (Kcal)" do expect(@etiqueta.hidratos_kcal).to eq(12) end it "Probando método para obtener cantidad de polialcoholes en kilocalorías (Kcal)" do expect(@etiqueta.polialcohol_kcal).to eq(0) end it "Probando método para obtener cantidad de almidón en kilocalorías (Kcal)" do expect(@etiqueta.almidon_kcal).to eq(0) end it "Probando método para obtener cantidad de fibra en kilocalorías (Kcal)" do expect(@etiqueta.fibra_kcal).to eq(6.4) end it "Probando método para obtener cantidad de proteinas en kilocalorías (Kcal)" do expect(@etiqueta.proteinas_kcal).to eq(6) end it "Probando método para obtener cantidad de sal en kilocalorías (Kcal)" do expect(@etiqueta.sal_kcal).to eq(7.8) end it "Probando método para obtener de valor energético en kilocalorías (Kcal)" do expect(@etiqueta.valor_ener_kcal).to eq(187) end it "Probando método para obtener %IR valor energético" do expect(@etiqueta.valor_ener_ir).to eq(9.18) end it "Probando método para obtener %IR grasas" do expect(@etiqueta.grasas_ir).to eq(24.57) end it "Probando método para obtener %IR grasas saturadas" do expect(@etiqueta.saturadas_ir).to eq(12) end #it "Probando método para obtener %IR hidratos" do # expect(@etiqueta.hidratos_ir).to eq(1.15) #end it "Probando método para obtener %IR azúcares" do expect(@etiqueta.azucares_ir).to eq(1.56) end it "Probando método para obtener %IR proteínas" do expect(@etiqueta.proteinas_ir).to eq(3) end it "Probando método para obtener %IR sal" do expect(@etiqueta.sal_ir).to eq(21.67) end it "Probando método para formatear etiqueta" do expect(@etiqueta.to_s) == ('Valores Nutricionales 100g/100ML Guacamoles (Grasas: 17.2, Saturadas: 2.4, MonoSaturadas: 0 , Polisaturadas: 0 , Hidratos: 3 , Azucares: 1.4 , Polialcohol: 0 , Almidon: 0 , Fibra: 3.2 , Proteinas: 1.5 , Sal: 1.3') end end describe Node do describe "# Expectativas para Node" do node = Node.new(2, 3, nil) it 'Node existe' do expect(node.value).to eq(2) expect(node.next).to eq(3) end end end describe List do describe "#Expectativas para Lista" do node = Node.new(2, 3, 1) list = List.new(node) node2 = Node.new(1, nil, nil) list2 = List.new(nil) node3 = Node.new(2,nil,nil) nodes = [node, node2, node3] it "List esta vacía" do expect(list2.empty?).to eq(true) end it "List existe con su head" do expect(list.head).to eq(node) end it "List existe con su tail" do expect(list.tail).to eq(node) end it "Primer nodo extraído correctamente" do expect(list.extract_beginning).to eq(node) end it "Último nodo extraído correctamente" do expect(list.extract_end).to eq(node) end it "Insertando nodo correctamente" do list.insert_beginning(node2) expect(list.head).to eq(node2) end it "Insertar un node por el final en List" do list.insert_end(node3) expect(list.tail).to eq(node3) expect(list.head).to eq(node2) end it "Insertar varios nodos a List" do list.insert_multi(nodes) expect(list.head).to eq(nodes[2]) end it "List no está vacía" do expect(list.empty?).to eq(false) end end end describe ListValue do before :each do etiqueta_ = Etiqueta.new("Guacamole",17.2,2.4,0,0,3,1.4,0,0,3.2,1.5,5) etiqueta2_ = Etiqueta.new("Cereales",7,4,0,0,71,36,0,46,4,0,6) etiqueta3_ = Etiqueta.new("Zumo de naranja",0.1,0,0,0,9.5,8.9,0,0,0.6,0.6,1) etiqueta4_ = Etiqueta.new("<NAME>",21.9,6.3,0,0,0.5,0.5,0,0,0.1,30,9) etiqueta5_ = Etiqueta.new("Jamón",21.9,6.3,0,0,0.5,0.5,0,0,0.1,30,10) etiqueta6_ = Etiqueta.new("Salmón",54,6,0,0,4,0,6,7,0,0,8) end describe "# creando la lista con etiquetas" do it "se inserta correctamente en la lista " do list3 = ListValue.new() expect(list3.insert_val(@etiqueta_)).to be_a(Node) end it "se extrae correctamente de la lista" do list3 = ListValue.new() expect(list3.insert_val(@etiqueta_)).to be_a(Node) expect(list3.extract_val).to be_a(Node) end it "se comprueba correctamente si está vacia" do list3 = ListValue.new() expect(list3.empty).to be true expect(list3.insert_val(@etiqueta_)).to be_a(Node) expect(list3.empty).to be false expect(list3.extract_val).to be_a(Node) expect(list3.empty).to be true end it "se comprueba correctamente el tamaño" do list3 = ListValue.new() expect(list3.length).to eq(0) list3.insert_val(@etiqueta_) list3.insert_val(@etiqueta2_) expect(list3.length).to eq(2) end it "se devuelve correctamente el contenido" do list3 = ListValue.new() list3.insert_val(@etiqueta_) list3.insert_val(@etiqueta5_) expect(list3.to_s).to be_a(String) end end describe "# Clasificación según cantidad de sal" do it "Se clasifica correctamente según cantidad de sal " do etiqueta_ = Etiqueta.new("Guacamole",17.2,2.4,0,0,3,1.4,0,0,3.2,1.5,5) etiqueta2_ = Etiqueta.new("Cereales",7,4,0,0,71,36,0,46,4,0,6) etiqueta3_ = Etiqueta.new("<NAME>",0.1,0,0,0,9.5,8.9,0,0,0.6,0.6,1) etiqueta4_ = Etiqueta.new("<NAME>",21.9,6.3,0,0,0.5,0.5,0,0,0.1,30,8) etiqueta5_ = Etiqueta.new("Jamón",21.9,6.3,0,0,0.5,0.5,0,0,0.1,30,9) etiqueta6_ = Etiqueta.new("Salmón",54,6,0,0,4,0,6,7,0,0,10) list3 = ListValue.new() list3.insert_val(etiqueta_) list3.insert_val(etiqueta2_) list3.insert_val(etiqueta3_) list3.insert_val(etiqueta4_) list3.insert_val(etiqueta5_) list3.insert_val(etiqueta6_) expect(clasification(list3)).to eq("{{ 5, 6, 1 }, { 8, 9, 10 }}") end end end end<file_sep>/Rakefile require "bundler/gem_tasks" task :default => :spec desc "Ejecutar las expectativas de la clase Etiqueta" task :spec do sh "rspec -I. spec/etiqueta_nutri_spec.rb" end desc "Ejecutar las expectativas de la clase Individuo" task :spec do sh "rspec -I. spec/individuo_spec.rb" end desc "Ejecutar las expectativas de la clase Individuo y Etiqueta para el menú dietético" task :spec do sh "rspec -I. spec/menu_spec.rb" end desc "Ejecutar las expectativas de ordenación de array y lista" task :spec do sh "rspec -I. spec/ordenacion_spec.rb" end desc "Ejecutar con documentacion" task :doc do sh "rspec -I. spec/etiqueta_nutri_spec.rb --format documentation" end<file_sep>/lib/prct06/antrodata.rb # Práctica 5 - Lenguajes y Paradigmas de Programación # # Escribir un programa Ruby para realizar el registro de los datos antropométricos de una # valoración nutricional y calcular los valores de los principales índices de composición corporal. # # Autor: <NAME> - GH: alu0100845396 / beejeke # encoding: UTF-8 # Declaración de la clase AntroData class AntroData attr_reader :peso, :talla, :edad, :sexo, :cadera, :cintura, :factor # Constructor de la clase AntroData def initialize(peso, talla, edad, sexo, cadera, cintura, factor) @peso = peso @talla = talla @edad = edad @sexo = sexo @cadera = cadera @cintura = cintura @factor = factor end # Método to_s de visualización de datos def to_s puts "------ Valores ------" tmp = "Peso: #{@peso}\n" tmp += "Altura: #{@talla}\n" tmp += "Edad: #{@edad}\n" tmp += "Sexo: #{@sexo}\n" tmp += "Cincurferencia de la cintura: #{@cintura}\n" tmp += "Cincurferencia de la cadera: #{@cadera}\n" tmp += "IMC: #{self.clasification_imc }\n" tmp += "Porcentaje de grasa: #{self.calculate_percentgrasa}\n" tmp += "RCC: #{self.clasification_rcc}\n" end # Método de cálculo del IMC del indviduo def calculate_imc @imc = (@peso / (@talla * @talla)).round(2) end # Método de cálculo del porcentaje de grasa de individuo def calculate_percentgrasa grasa = (1.2 * @imc + 0.23 * @edad - 10.8 * @sexo - 5.4).round(2) end # Método de cálculo de RCC del individuo def calculate_rcc cintura_med = ((@cintura[0] + @cintura[1]) / 2) cadera_med = ((@cadera[0] + @cadera[1]) / 2) @rcc = (cintura_med / cadera_med).round(2) end # Método de clasificación de IMC def clasification_imc case @imc when 0 .. 18.5 "Bajo peso" when 18.5 .. 24.9 "Adecuado" when 25 .. 29.9 "Sobrepeso" when 30 .. 34.9 "Obesidad grado 1" when 35 .. 39.9 "Obesidad grado 2" else "Obesidad grado 3" end end # Método de clasficación de riesgo según RCC hombre def clasification_rcc if @sexo == 1 case @rcc when 0.83 .. 0.88 "Bajo" when 0.88 .. 0.95 "Moderado" when 0.95 .. 1.01 "Alto" when 1.01 .. 2 "Muy alto" end else case @rcc when 0.72 .. 0.75 "Bajo" when 0.75 .. 0.82 "Moderado" when 0.82 .. 2 "Alto" end end end end<file_sep>/spec/enumerable_spec.rb # Práctica 9 - Lenguajes y Paradigmas de Programación # # La etiqueta de información nutricional es la información sobre el aporte energéico (calórico) # y contenido de nutrientes que aparece en los envases de los alimentos y bebidas. También se denomina #“etiquetado sobre las propiedades nutritivas”. # # Autor: <NAME> - GH: alu0100845396 / beejeke # encoding: UTF-8 require "spec_helper" describe Etiqueta do before :each do @etiqueta = Etiqueta.new("Guacamole",17.2,2.4,0,0,3,1.4,0,0,3.2,1.5,5) @etiqueta2 = Etiqueta.new("Cereales",7,4,0,0,71,36,0,46,4,0,6) @etiqueta3 = Etiqueta.new("Zumo de naranja",0.1,0,0,0,9.5,8.9,0,0,0.6,0.6,1) @etiqueta4 = Etiqueta.new("Jamón ibérico",21.9,6.3,0,0,0.5,0.5,0,0,0.1,30,8) @etiqueta5 = Etiqueta.new("Jamón",21.9,6.3,0,0,0.5,0.5,0,0,0.1,30,9) @lista = ListValue.new @lista.insert_val(@etiqueta) @lista.insert_val(@etiqueta2) @lista.insert_val(@etiqueta3) @lista.insert_val(@etiqueta4) @lista.insert_val(@etiqueta5) end it "Comprobación del metodo collect" do expect(@lista.collect{1}).to eq([1,1,1,1,1]) end it "Comprobación del metodo select" do expect(@lista.select{@etiqueta2}).to eq([209.2, 575.0, 48.5, 367.3, 373.3]) end it "Comprobación del metodo max" do expect(@lista.max).to eq(575.0) end it "Comprobación del metodo min" do expect(@lista.min).to eq(48.5) end it "Comprobación del metodo sort" do expect(@lista.sort).to eq([48.5, 209.2, 367.3, 373.3, 575.0]) end context "# Lista de Pacientes con Enumerable" do before :each do @paciente = Paciente.new("Juan", 65, 1.70, 23, 1, [84, 85.0], [71, 70.0]) @paciente2 = Paciente.new("Fernando", 93, 1.85, 45, 1, [91, 90.0], [82, 83.0]) @paciente3 = Paciente.new("Mario", 112, 1.70, 67, 1, [99, 98.0], [90, 89.0]) @paciente4 = Paciente.new("Ana", 55, 1.63, 29, 0, [69, 70.0], [61, 60.0]) @paciente5 = Paciente.new("María", 82, 1.75, 55, 0, [74, 75.0], [69, 70.0]) @lista = ListValue.new @lista.insert_val(@paciente) @lista.insert_val(@paciente2) @lista.insert_val(@paciente3) @lista.insert_val(@paciente4) @lista.insert_val(@paciente5) end it "Comprobación del metodo collect" do expect(@lista.collect{0}).to eq([0,0,0,0,0]) end it "Comprobación del metodo select" do expect(@lista.select{@paciente2}).to eq([22.49,27.17,38.75,20.7,26.78]) end it "Comprobación del metodo max" do expect(@lista.max).to eq(38.75) end it "Comprobación del metodo min" do expect(@lista.min).to eq(20.7) end it "Comprobación del metodo sort" do expect(@lista.sort).to eq([20.7, 22.49, 26.78, 27.17, 38.75]) end end end<file_sep>/lib/prct06/lista.rb # Práctica 7 - Lenguajes y Paradigmas de Programación # # La etiqueta de información nutricional es la información sobre el aporte energéico (calórico) # y contenido de nutrientes que aparece en los envases de los alimentos y bebidas. También se denomina #“etiquetado sobre las propiedades nutritivas”. # # Autor: <NAME> - GH: alu0100845396 / beejeke # encoding: UTF-8 Node = Struct.new(:value, :next, :prev) class List attr_accessor :head, :tail def initialize(node) @head = node @tail = node end def empty? if @head == nil return true else return false end end def insert_beginning(node) if (@head == nil) @head = node @tail = node else temporal_node = @head.next @head = node @head.next = temporal_node @head.prev = nil end def insert_end(node) if (@head == nil) @head = node @tail = node else temporal_node = @tail.next @tail = node @tail.next = nil @tail.prev = temporal_node end end end def insert_multi(nodes) nodes.each do |nodo| insert_beginning(nodo) end end def extract_beginning() if @head == nil return nil else temporal_node = @head @head = @head.next return temporal_node end end def extract_end() if @tail == nil return nil else temporal_node = @tail @tail = @tail.prev return temporal_node end end end
e46a303cfa5d5a8de1e99ed335b5ce447ce68c8e
[ "Markdown", "Ruby" ]
15
Markdown
ULL-ESIT-LPP-1819/tdd-alu0100845396
05beefa31d4b7cd63032df47982e90fa1101259a
fe89cb07c676b74c773b90f3cf4899ee2772898d
refs/heads/main
<repo_name>apupko/frontend-project-lvl1<file_sep>/README.md ### Hexlet tests and linter status: ![Actions Status](https://github.com/apupko/frontend-project-lvl1/workflows/hexlet-check/badge.svg) ![Node CI](https://github.com/apupko/frontend-project-lvl1/workflows/Node%20CI/badge.svg) <a href="https://codeclimate.com/github/codeclimate/codeclimate/maintainability"><img src="https://api.codeclimate.com/v1/badges/a99a88d28ad37a79dbf6/maintainability" /></a> Brain Even game example: [![asciicast](https://asciinema.org/a/B59iIejKgpm61vhyqqJdcRhoU.png)](https://asciinema.org/a/B59iIejKgpm61vhyqqJdcRhoU) Brain Calc game example: [![asciicast](https://asciinema.org/a/eUzcJXlVFT8wP8550fJxt9dJF.png)](https://asciinema.org/a/eUzcJXlVFT8wP8550fJxt9dJF) Brain GCD game example: [![asciicast](https://asciinema.org/a/WgN4t3XEGt6MHVrRATNES2EFg.png)](https://asciinema.org/a/WgN4t3XEGt6MHVrRATNES2EFg) Brain progression game example: [![asciicast](https://asciinema.org/a/Ro0p4HfiH6V1awJosevUZ7XUS.png)](https://asciinema.org/a/Ro0p4HfiH6V1awJosevUZ7XUS) Brain prime game example: [![asciicast](https://asciinema.org/a/ihDBElEIRIfvYgk0awwdHrhMI.png)](https://asciinema.org/a/ihDBElEIRIfvYgk0awwdHrhMI) <file_sep>/bin/brain-games.js #!/usr/bin/env node import { readUserName } from '../src/cli.js'; readUserName(); <file_sep>/src/games/calc.js import getRandomInt from '../utils.js'; const rules = 'What is the result of the expression?'; const MIN_NUMBER = 0; const MAX_NUMBER = 10; const addition = (a, b) => a + b; const substruction = (a, b) => a - b; const multiplication = (a, b) => a * b; const division = (a, b) => Math.trunc((a / b) * 100) / 100; const getRandomOperation = () => { const mappingOperation = { 0: { symbol: '+', calculate: addition }, 1: { symbol: '-', calculate: substruction }, 2: { symbol: '*', calculate: multiplication }, 3: { symbol: '/', calculate: division }, }; const random = getRandomInt(0, 2); return mappingOperation[random]; }; const run = () => { const operation = getRandomOperation(); const firstOperand = getRandomInt(MIN_NUMBER, MAX_NUMBER); const secondOperand = getRandomInt(MIN_NUMBER, MAX_NUMBER); const question = `${firstOperand} ${operation.symbol} ${secondOperand}`; const correctAnswer = `${operation.calculate(firstOperand, secondOperand)}`; return { question, correctAnswer }; }; export default { rules, run }; <file_sep>/bin/brain-gcd.js #!/usr/bin/env node import runGame from '../src/index.js'; import gcdGame from '../src/games/gcd.js'; runGame(gcdGame); <file_sep>/src/games/prime.js import getRandomInt from '../utils.js'; const primeNumbers = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, ]; const rules = 'Answer "yes" if given number is prime. Otherwise answer "no".'; const MAX_NUMBER = 500; const isPrime = (number) => primeNumbers.includes(number); const run = () => { const number = getRandomInt(0, MAX_NUMBER); const question = `${number}`; const correctAnswer = `${isPrime(number) ? 'yes' : 'no'}`; return { question, correctAnswer }; }; export default { rules, run };
774981a454b913eca0b69a8eefc7ead29c06e33b
[ "Markdown", "JavaScript" ]
5
Markdown
apupko/frontend-project-lvl1
ad524e855ded064337f072529a5c1c8e356b3ec9
4de4dc89ebc65c7ccee6f13b1d3d2e280f0736e6
refs/heads/master
<repo_name>CardioArtLab/HX711-ESP32<file_sep>/scripts/SerialThread.py from PyQt5.QtCore import Qt, QObject, QThread, pyqtSignal class SerialThread(QThread): data_received = pyqtSignal(float, float) def __init__(self, parent=None, serial=None): QThread.__init__(self) self.parent = parent self.serial = serial def __del__(self): self.wait() def run(self): self.running = True while (self.running): try: line = self.serial.readline().strip().decode('cp437') tokens = line.split(' ') if len(tokens) >= 2: time, value = tokens[0:2] self.data_received.emit(float(time), float(value)) except: pass def stopped(self): self.running = False<file_sep>/src/main.cpp #include <Arduino.h> #include <BluetoothSerial.h> #include <Preferences.h> #include "HX711.h" // HX711.DT - pin #A1 D33 // HX711.SCK - pin #A0 D32 #define DT_PIN 33 #define SCK_PIN 32 // GAIN 128,64,32 #define GAIN 64 #define GRAVITY 9.7832 #define PRESCALE GRAVITY/1000 HX711 scale(DT_PIN, SCK_PIN, GAIN); BluetoothSerial SerialBT; Preferences preference; #define LED_BLINK 0 #define LED_ON 1 #define LED_OFF 2 uint8_t ledState = 0; #define SCALEMODE_UNIT 0 #define SCALEMODE_VALUE 1 uint8_t scaleMode = 0; bool useBluetooth = false; void ATCommandTask(void *pvParameters) { Serial.println("ATCommand Task"); for(;;) { int state = -1; bool isReboot = false; int8_t b; while ((b = Serial.read()) != -1) { if (b == 'A') state = 0; else if (state == 0 && b =='T') { String command = Serial.readStringUntil('\r'); if (command.startsWith("ID")) { preference.begin("HX711"); if (command.startsWith("ID=")) { preference.putString("ID", command.substring(command.indexOf('=')+1)); isReboot = true; //Serial.printf("%s\r\n", command.substring(command.indexOf('=')+1).c_str()); } else { Serial.printf("%s\r\n", preference.getString("ID", "").c_str()); } preference.end(); } else if (command.startsWith("MODE=")) { String mode = command.substring(command.indexOf('=')+1); if (mode == "0") { scaleMode = SCALEMODE_UNIT; } else if (mode == "1") { scaleMode = SCALEMODE_VALUE; } } else if (command.startsWith("TARE")) { scale.tare(10); } else if (command.startsWith("CAL")) { scale.set_scale(); scale.tare(); scaleMode = SCALEMODE_UNIT; Serial.printf("Start Calibration\r\n"); } else if (command.startsWith("SCALE=")) { String numStr = command.substring(command.indexOf('=')+1); scale.set_scale(numStr.toDouble()); scaleMode = SCALEMODE_UNIT; preference.begin("HX711"); preference.putDouble("CAL", numStr.toDouble()); preference.end(); } if (isReboot) ESP.restart(); } else { state = -1; } } vTaskDelay(300 / portTICK_PERIOD_MS); } vTaskDelete(NULL); } void SerialTask(void *pvParameters) { double t,w; for(;;) { if (!useBluetooth) { if (scaleMode == SCALEMODE_VALUE) { t = millis() / 1000.0; w = scale.get_value(10); Serial.printf("%.2lf %.0lf\n", t, w); } else { t = millis() / 1000.0; w = round(scale.get_units(10)*PRESCALE); Serial.printf("%.2lf %.2lf\n", t, w); } } else { vTaskDelay(3000 / portTICK_PERIOD_MS); } } vTaskDelete(NULL); } void BluetoothServerTask(void *pvParameters) { double t,w; for (;;) { if (SerialBT.hasClient()) { useBluetooth = true; ledState = LED_ON; t = millis() / 1000.0; w = round(scale.get_units(10)*PRESCALE); SerialBT.printf("%.2lf %.2lf\n", t, w); } else { useBluetooth = false; if (ledState != LED_BLINK) ledState = LED_BLINK; vTaskDelay(1000 / portTICK_PERIOD_MS); } } vTaskDelete(NULL); } extern "C" void app_main() { // power on LED PID initArduino(); pinMode(LED_BUILTIN, OUTPUT); digitalWrite(LED_BUILTIN, LOW); // Debugging serial Serial.begin(9600); // Random name in form CA-NIBP-<4char> // https://www.random.org/cgi-bin/randbyte?nbytes=2&format=h preference.begin("HX711", true); String name = preference.getString("ID", ""); double cal = preference.getDouble("CAL", 10.31691); preference.end(); // set up weight calibration scale.tare(200); scale.set_scale(cal); // set up bluetooth if (name.length() == 0) SerialBT.begin("WEIGH-0000"); else SerialBT.begin("WEIGH-" + name); Serial.print("START\n"); // AT Command (Serial) task xTaskCreatePinnedToCore(ATCommandTask, "ATCommand", 2048, NULL, 1, NULL, 1); // Serial task xTaskCreatePinnedToCore(SerialTask, "Serial", 2048, NULL, 0, NULL, 0); // Bluetooth Serial task xTaskCreatePinnedToCore(BluetoothServerTask, "Bluetooth", 2048, NULL, 0, NULL, 1); // LED status task bool ledLow = true; while(1) { if (ledState == LED_ON) { digitalWrite(LED_BUILTIN, HIGH); } else if (ledState == LED_OFF) { digitalWrite(LED_BUILTIN, LOW); } else { digitalWrite(LED_BUILTIN, (ledLow) ? HIGH : LOW); ledLow = !ledLow; } delay(500); } }<file_sep>/scripts/run.py import sys from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QDesktopWidget, QMainWindow, QAction, QVBoxLayout, QLCDNumber, QDockWidget, QInputDialog, QFileDialog, QMessageBox) from PyQt5.QtCore import Qt, QTimer import pyqtgraph as pg import serial from serial.tools.list_ports import comports from SerialThread import SerialThread class Application(QMainWindow): def __init__(self): super().__init__() self.initUI() self.serial = None self.timer = QTimer(self) self.tData = [] self.wData = [] def initUI(self): toolbar = self.addToolBar('toolbar') action = QAction('Connect', self) action.setStatusTip('Connect COM port') action.triggered.connect(self.connectCOMDialog) toolbar.addAction(action) #exitAct.triggered.connect(self.close) # action = QAction('Disconnect', self) action.setStatusTip('Disconnect from serial COM port') action.triggered.connect(self.disconnect) toolbar.addAction(action) toolbar.addSeparator() action = QAction('Tare', self) action.setStatusTip('set OFFSET') action.triggered.connect(self.tare) toolbar.addAction(action) action =QAction('Calibrate', self) action.setStatusTip('Start calibrate weigh') action.triggered.connect(self.calibrate) toolbar.addAction(action) action = QAction('Set scale', self) action.setStatusTip('set prescale value to weigh') action.triggered.connect(self.setScaleDialog) toolbar.addAction(action) toolbar.addSeparator() action =QAction('Clear', self) action.setStatusTip('clear current data') action.triggered.connect(self.clearPlot) toolbar.addAction(action) self.plotWidget = pg.PlotWidget(self) self.plot = self.plotWidget.plot(pen=pg.mkPen('r', width=2)) self.plotWidget.setLabel('bottom', 'Time', 'second') self.plotWidget.setLabel('left', 'Force', 'N') self.lcd = QLCDNumber(self) self.dock = QDockWidget("Weight", self) self.dock.setWidget(self.lcd) self.addDockWidget(Qt.RightDockWidgetArea, self.dock) self.setCentralWidget(self.plotWidget) self.statusBar() self.resize(1000, 400) self.center() self.setWindowTitle('Weigh monitor') self.show() def center(self): qr = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) def connectCOMDialog(self): ports = ','.join([x.device for x in comports()]) port, ok = QInputDialog.getText(self, 'COM PORT', 'enter COM PORT: ' + ports ) if ok: try: self.serial = serial.Serial(str(port), 9600, timeout=5) print(port) self.serialThread = SerialThread(self, self.serial) self.serialThread.data_received.connect(self.updateData) self.serialThread.start() self.setWindowTitle('Weigh monitor (' + port + ')') self.timer.timeout.connect(self.updatePlot) self.timer.start(300) except Exception as err: QMessageBox.warning(self, 'Error', str(err)) def disconnect(self): if self.serial and self.serial.is_open: self.serialThread.stopped() self.serial.close() self.setWindowTitle('Weigh monitor') def tare(self): if self.serial and self.serial.is_open: self.serial.write(b'ATTARE\r\n') def calibrate(self): if self.serial and self.serial.is_open: self.serial.write(b'ATCAL\r\n') def setScaleDialog(self): scale, ok = QInputDialog.getText(self, 'SET SCALE', 'enter scale (e.g. 10.013)') if ok: try: if self.serial and self.serial.is_open: self.serial.write('ATSCALE={}\r\n'.format(float(scale)).encode('cp437')) except Exception as err: QMessageBox.warning(self, 'Error', str(err)) def saveDialog(self): filename = QFileDialog.getOpenFileName(self, 'Select save file', '', 'CSV file (*.csv);;All Files (*)') print(filename) def clearPlot(self): self.plot.clear() self.tData.clear() self.wData.clear() def updateData(self, time, value): self.lcd.display(str(value)) self.tData.append(time) self.wData.append(value) def updatePlot(self): self.plot.setData(self.tData, self.wData) if __name__ == '__main__': app = QApplication(sys.argv) e = Application() sys.exit(app.exec_())
e7d1111480b40b46f72e09d67ad9db2a1afe5afc
[ "Python", "C++" ]
3
Python
CardioArtLab/HX711-ESP32
5f7b18d48255ee0410c18ff1078f3dd140fceda0
da3ef4bb1d47ab9a77382e0b3aa7a82324105d9e
refs/heads/master
<repo_name>abhijeet219/Humidity-and-Temperature-monitoring-system<file_sep>/arduino_initial/arduino_initial.ino #include<dht11.h> // Including library for dht #include<LiquidCrystal.h> LiquidCrystal lcd(2, 3, 4, 5, 6, 7); #define dht_dpin 12 dht11 DHT; byte degree[8] = { 0b00011, 0b00011, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000 }; void setup() { lcd.begin(16, 2); lcd.createChar(1, degree); lcd.clear(); lcd.print(" Humidity "); lcd.setCursor(0,1); lcd.print(" Measurement "); delay(2000); lcd.clear(); lcd.print("Circuit Digest "); delay(2000); } void loop() { DHT.read(dht_dpin); lcd.setCursor(0,1); lcd.print("H:"); lcd.print(DHT.humidity); // printing Humidity on LCD lcd.print(" %"); lcd.setCursor(0,0); lcd.print("T:"); lcd.print(((DHT.temperature))); // Printing temperature on LCD lcd.write(1); lcd.print("C"); delay(500); }
8c0ac5d040fb458c5cac0dd5b64bab9663eb228e
[ "C++" ]
1
C++
abhijeet219/Humidity-and-Temperature-monitoring-system
b0504f6a2ce4fbd698adfbd06aa19235a38759b1
51693dae7c2184df02a3076fe60e5b36c85a896b
refs/heads/master
<repo_name>WaleTech/WaleSmart<file_sep>/app/src/main/java/com/waletech/walesmart/publicSet/BundleSet.java package com.waletech.walesmart.publicSet; /** * Created by KeY on 2016/7/8. */ public final class BundleSet { public final static String KEY_SHOP_NAME = "key_shop_name"; public final static String KEY_AREA_NAME = "key_area_name"; public final static String KEY_AREA_ROW = "key_area_row"; public final static String KEY_AREA_COLUMN = "key_area_column"; public final static String KEY_CONTENT_LAYOUT_RES_ID = "key_content_layout_res_id"; public final static String KEY_BASE_FRAGMENT = "key_base_fragment"; } <file_sep>/app/src/main/java/com/waletech/walesmart/sharedinfo/SharedAction.java package com.waletech.walesmart.sharedinfo; import android.content.Context; import android.content.SharedPreferences; import com.waletech.walesmart.http.HttpSet; /** * Created by KeY on 2016/6/3. */ public final class SharedAction { private SharedPreferences sp; public SharedAction() { } public SharedAction(Context context) { sp = context.getSharedPreferences(SharedSet.NAME, Context.MODE_PRIVATE); } public void setShared(SharedPreferences sp) { this.sp = sp; } public void clearLastIdInfo() { SharedPreferences.Editor editor = sp.edit(); editor.putInt(SharedSet.KEY_LAST_ID, 0); editor.apply(); } public void setLoginStatus(String username, String nickname) { SharedPreferences.Editor editor = sp.edit(); editor.putBoolean(SharedSet.KEY_IS_LOGIN, true); editor.putString(SharedSet.KEY_USERNAME, username); editor.putString(SharedSet.KEY_NICKNAME, nickname); editor.apply(); } public boolean getLoginStatus() { return sp.getBoolean(SharedSet.KEY_IS_LOGIN, false); } public String getUsername() { return sp.getString(SharedSet.KEY_USERNAME, ""); } public String getNickname() { return sp.getString(SharedSet.KEY_NICKNAME, ""); } public void clearLoginStatus() { SharedPreferences.Editor editor = sp.edit(); editor.putBoolean(SharedSet.KEY_IS_LOGIN, false); editor.putString(SharedSet.KEY_USERNAME, ""); editor.putString(SharedSet.KEY_NICKNAME, ""); editor.apply(); } // Last_Id public void setLastId(int last_id) { SharedPreferences.Editor editor = sp.edit(); editor.putInt(SharedSet.KEY_LAST_ID, last_id); editor.apply(); } public int getLastId() { return sp.getInt(SharedSet.KEY_LAST_ID, 0); } public void setAppLanguage(String language) { SharedPreferences.Editor editor = sp.edit(); editor.putString(SharedSet.KEY_APP_LANGUAGE, language); editor.apply(); } public String getAppLanguage() { return sp.getString(SharedSet.KEY_APP_LANGUAGE, SharedSet.LANGUAGE_CHINESE); } public void setAppLaunch(boolean isLaunch) { SharedPreferences.Editor editor = sp.edit(); editor.putBoolean(SharedSet.KEY_APP_LAUNCH, isLaunch); editor.apply(); } public boolean getAppLaunch() { return sp.getBoolean(SharedSet.KEY_APP_LAUNCH, false); } public void setAppFstLaunch(boolean isFstLaunch) { SharedPreferences.Editor editor = sp.edit(); editor.putBoolean(SharedSet.KEY_APP_FST_LAUNCH, isFstLaunch); editor.apply(); } public boolean getAppFstLaunch() { return sp.getBoolean(SharedSet.KEY_APP_FST_LAUNCH, false); } public void setNetIP(String ip) { SharedPreferences.Editor editor = sp.edit(); editor.putString(SharedSet.KEY_NET_IP, ip); editor.apply(); } public String getNetIP() { return sp.getString(SharedSet.KEY_NET_IP, HttpSet.getBaseIp()); } public void setNetService(String service) { SharedPreferences.Editor editor = sp.edit(); editor.putString(SharedSet.KEY_NET_SERVICE, service); editor.apply(); } public String getNetService() { return sp.getString(SharedSet.KEY_NET_SERVICE, HttpSet.getBaseService()); } public void setNoticeEnter(boolean isNoticeEnter) { SharedPreferences.Editor editor = sp.edit(); editor.putBoolean(SharedSet.KEY_NOTICE_ENTER, isNoticeEnter); editor.apply(); } public boolean getNoticeEnter() { return sp.getBoolean(SharedSet.KEY_NOTICE_ENTER, false); } } <file_sep>/app/src/main/java/com/waletech/walesmart/user/UserAction.java package com.waletech.walesmart.user; import android.content.Context; import com.waletech.walesmart.R; import com.waletech.walesmart.base.BaseAction; import com.waletech.walesmart.http.HttpAction; import com.waletech.walesmart.http.HttpHandler; /** * Created by lenovo on 2016/12/22. */ public class UserAction extends BaseAction { public UserAction(Context context) { super(context); } public void checkPrivilege() { HttpAction action = new HttpAction(context); // action.setUrl(); // action.setDialog(context.getString(R.string.base_search_progress_title), context.getString(R.string.base_search_progress_msg)); // action.setMap(); // action.setTag(); // action.setHandler(new HttpHandler(context)); // // action.interaction(); } } <file_sep>/app/src/main/java/com/waletech/walesmart/receiver/GPushReceiver.java package com.waletech.walesmart.receiver; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.support.v4.app.TaskStackBuilder; import android.util.Log; import com.igexin.sdk.PushConsts; import com.waletech.walesmart.R; import com.waletech.walesmart.comment.Comment_Act; import com.waletech.walesmart.publicSet.IntentSet; import com.waletech.walesmart.publicSet.NoticeSet; import com.waletech.walesmart.sharedinfo.SharedAction; import com.waletech.walesmart.user.lockInfo.LockInfo_Act; /** * Created by KeY on 2016/5/25. */ public class GPushReceiver extends BroadcastReceiver { /** * 应用未启动, 个推 service已经被唤醒,保存在该时间段内离线消息(此时 GPushActivity.tLogView == null) */ public static StringBuilder payloadData = new StringBuilder(); @Override public void onReceive(Context context, Intent intent) { Log.i("GPush", "onReceive"); NotificationManager noticeManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Bundle bundle = intent.getExtras(); switch (bundle.getInt(PushConsts.CMD_ACTION)) { case PushConsts.GET_MSG_DATA: // 获取透传数据 byte[] payload = bundle.getByteArray("payload"); if (payload != null) { String data = new String(payload); payloadData.append(data); payloadData.append("\n"); // 没有还鞋的时候的result string // 通过"\u0024" 即 "$" if (data.startsWith("\u0024")) { Log.i("GPush", "get data is : " + data); // 设置当有消息是的提示,图标和提示文字 String ticker = context.getString(R.string.gpush_no_return_notice_ticker); String title = context.getString(R.string.gpush_no_return_notice_title); String content = data.substring(1, data.length()); Notification notification = onCreateNotice(context, ticker, title, content); // 如果已经打开了,当点击通知的时候就不会再打开一个activity if (!LockInfo_Act.isView) { Intent lockinfo_int = new Intent(context, LockInfo_Act.class); TaskStackBuilder builder = TaskStackBuilder.create(context); builder.addParentStack(LockInfo_Act.class); builder.addNextIntent(lockinfo_int); new SharedAction(context).setNoticeEnter(true); notification.contentIntent = builder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); } //发送(显示)通知 noticeManager.notify((int) System.currentTimeMillis(), notification); } else if (data.startsWith("\u0025")) { String ticker = "开锁通知"; String title = "开锁成功"; String content = "已经开锁"; Notification notification = onCreateNotice(context, ticker, title, content); noticeManager.notify(NoticeSet.HAS_UNLOCK, notification); } else { String ticker = context.getString(R.string.gpush_has_return_notice_ticker); String title = context.getString(R.string.gpush_has_return_notice_title); String content = context.getString(R.string.gpush_has_return_notice_msg); Notification notification = onCreateNotice(context, ticker, title, content); noticeManager.notify(NoticeSet.HAS_RETURN, notification); Intent comment_int = new Intent(context, Comment_Act.class); comment_int.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); comment_int.putExtra(IntentSet.KEY_EPC_CODE, data); context.startActivity(comment_int); } Log.i("GPush", "snd data is : " + data); } break; case PushConsts.GET_CLIENTID: // 获取ClientID(CID) // 第三方应用需要将CID上传到第三方服务器,并且将当前用户帐号和CID进行关联,以便日后通过用户帐号查找CID进行消息推送 String cid = bundle.getString("clientid"); Log.i("GPush", "thd cid is : " + cid); break; case PushConsts.THIRDPART_FEEDBACK: Log.i("GPush", "forth is"); break; default: break; } } private Notification onCreateNotice(Context context, String ticker, String title, String content) { // NotificationCompat.BigTextStyle style = new NotificationCompat.BigTextStyle() // .setBigContentTitle(title) // 通知标题 // .bigText(content); // 通知内容(可以两行扩展) Notification notification = new NotificationCompat.Builder(context) .setSmallIcon(R.mipmap.ic_launcher) .setTicker(ticker) // 当通知来的时候的滚动提醒 //.setStyle(style) .setContentTitle(title) .setContentText(content) .setWhen(System.currentTimeMillis()) .build(); notification.flags = Notification.FLAG_AUTO_CANCEL; return notification; } } <file_sep>/app/src/main/java/com/waletech/walesmart/register/RegisterAction.java package com.waletech.walesmart.register; import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import com.waletech.walesmart.R; import com.waletech.walesmart.base.BaseAction; import com.waletech.walesmart.http.HttpAction; import com.waletech.walesmart.http.HttpHandler; import com.waletech.walesmart.http.HttpResult; import com.waletech.walesmart.http.HttpSet; import com.waletech.walesmart.http.HttpTag; import com.waletech.walesmart.login.Login_Act; import com.waletech.walesmart.main.MainActivity; import com.waletech.walesmart.publicClass.Methods; import org.json.JSONException; import org.json.JSONObject; /** * Created by KeY on 2016/6/1. */ public class RegisterAction extends BaseAction { public RegisterAction(Context context) { super(context); } public void register(String usn_str, String psd_str, String nicn_str) { if (!checkNet()) { return; } if (usn_str.equals("") || psd_str.equals("")) { toast.showToast(context.getString(R.string.login_toast_usn_psd_isNull)); return; } else if (nicn_str.equals("")) { toast.showToast(context.getString(R.string.reg_toast_nickname_isNull)); return; } String app_version = Methods.getVersionName(context); String[] key = { HttpSet.KEY_USERNAME, HttpSet.KEY_PASSWORD, HttpSet.KEY_NICKNAME, HttpSet.KEY_VERSION }; String[] value = { usn_str, psd_str, nicn_str, app_version }; HttpAction action = new HttpAction(context); action.setUrl(HttpSet.URL_REGISTER); action.setTag(HttpTag.REGISTER_REGISTER); action.setDialog(context.getString(R.string.reg_progress_title), context.getString(R.string.reg_progress_msg)); action.setHandler(new HttpHandler(context)); action.setMap(key, value); action.interaction(); } public void handleResponse(String result) throws JSONException { JSONObject obj = new JSONObject(result); toast.showToast(obj.getString(HttpResult.RESULT)); String register_result = obj.getString(HttpResult.RESULT); if (register_result.equals(HttpResult.REGISTER_SUCCESS) || register_result.equals(HttpResult.REGISTER_SUCCESS_EN)) { String username = obj.getString(HttpSet.KEY_USERNAME); String nickname = obj.getString(HttpSet.KEY_NICKNAME); sharedAction.setLoginStatus(username, nickname); // ((AppCompatActivity) context).setResult(); // Intent user_int = new Intent(context, MainActivity.class); // context.startActivity(user_int); ((AppCompatActivity) context).finish(); Login_Act.login_act.finish(); } } } <file_sep>/app/src/main/java/com/waletech/walesmart/user/editInfo/EditInfoAction.java package com.waletech.walesmart.user.editInfo; import android.content.Context; import com.waletech.walesmart.R; import com.waletech.walesmart.base.BaseAction; import com.waletech.walesmart.http.HttpAction; import com.waletech.walesmart.http.HttpHandler; import com.waletech.walesmart.http.HttpResult; import com.waletech.walesmart.http.HttpSet; import com.waletech.walesmart.http.HttpTag; import com.waletech.walesmart.user.User_Act; import org.json.JSONException; import org.json.JSONObject; /** * Created by KeY on 2016/8/29. */ public class EditInfoAction extends BaseAction { public EditInfoAction(Context context) { super(context); } public void updateNickname(String nickname) { if (!checkNet()) { return; } String[] key = { HttpSet.KEY_USERNAME, HttpSet.KEY_NICKNAME}; String[] value = { sharedAction.getUsername(), nickname}; HttpAction action = new HttpAction(context); action.setUrl(HttpSet.URL_EDIT_INFO_UPDATE_NICKNAME); action.setTag(HttpTag.EDIT_INFO_UPDATE_NICKNAME); action.setDialog(context.getString(R.string.base_refresh_progress_title), context.getString(R.string.base_refresh_progress_msg)); action.setHandler(new HttpHandler(context)); action.setMap(key, value); action.interaction(); } public void updatePassword(String old_psd, String new_psd) { if (!checkNet()) { return; } String[] key = { HttpSet.KEY_USERNAME, HttpSet.KEY_PASSWORD, HttpSet.KEY_NEW_PASSWORD}; String[] value = { sharedAction.getUsername(), old_psd, new_psd}; HttpAction action = new HttpAction(context); action.setUrl(HttpSet.URL_EDIT_INFO_UPDATE_PASSWORD); action.setTag(HttpTag.EDIT_INFO_UPDATE_PASSWORD); action.setDialog(context.getString(R.string.base_refresh_progress_title), context.getString(R.string.base_refresh_progress_msg)); action.setHandler(new HttpHandler(context)); action.setMap(key, value); action.interaction(); } public void handleResponse(String result) throws JSONException { JSONObject obj = new JSONObject(result); String response = obj.getString(HttpResult.RESULT); switch (response) { case HttpResult.UPDATE_NICKNAME_SUCCESS: case HttpResult.UPDATE_NICKNAME_SUCCESS_EN: case HttpResult.UPDATE_PASSWORD_SUCCESS: case HttpResult.UPDATE_PASSWORD_SUCCESS_EN: ((Edit_Info_Act) context).getDialog().dismiss(); break; } // if (response.equals(HttpResult.UPDATE_PASSWORD_SUCCESS) || response.equals(HttpResult.UPDATE_NICKNAME_SUCCESS)) { // ((Edit_Info_Act) context).getDialog().dismiss(); // } toast.showToast(obj.getString(HttpResult.RESULT)); if (!obj.getString(HttpResult.NICKNAME).equals("")) { String nickname = obj.getString(HttpResult.NICKNAME); sharedAction.setLoginStatus(sharedAction.getUsername(), nickname); if (!User_Act.user_act.isFinishing()) { User_Act.user_act.finish(); } } } } <file_sep>/app/src/main/java/com/waletech/walesmart/user/lockInfo/record/LockRecord_Frag.java package com.waletech.walesmart.user.lockInfo.record; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.AppCompatSpinner; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.waletech.walesmart.R; import com.waletech.walesmart.base.BaseAction; import com.waletech.walesmart.base.Base_Frag; import com.waletech.walesmart.publicClass.DatePickerFragDialog; import com.waletech.walesmart.publicObject.ObjectShoe; import org.json.JSONException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.Locale; /** * Created by KeY on 2016/6/28. */ public class LockRecord_Frag extends Base_Frag implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener { private SwipeRefreshLayout record_refresh; private RecordAction recordAction; private ArrayList<ObjectShoe> shoeList; private ArrayList<String> shopList; private ArrayList<String> brandList; private boolean isFstInit; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_lock_record_layout, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); varInit(); setupSwipeRefresh(view); } private void varInit() { shoeList = new ArrayList<>(); recordAction = new RecordAction(getContext(), this); recordAction.getDefaultRecord(); isFstInit = true; } private void onSpinnerListInit() { if (shoeList != null) { // shopList = new ArrayList<>(); // brandList = new ArrayList<>(); HashSet<String> shopSet = new HashSet<>(); HashSet<String> brandSet = new HashSet<>(); for (int i = 0; i < shoeList.size(); i++) { ObjectShoe shoe = shoeList.get(i); shopSet.add(shoe.getShopName()); brandSet.add(shoe.getBrand()); } shopList = new ArrayList<>(shopSet); brandList = new ArrayList<>(brandSet); shopList.add(0, "全部店铺"); brandList.add(0, "全部品牌"); if (getView() != null) { setupFilterBar(getView()); } } } private void setupFilterBar(View view) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA); String date = format.format(new Date()); final TextView date_tv = (TextView) view.findViewById(R.id.filter_tv); date_tv.setText(date); date_tv.setOnClickListener(this); // 店铺的Spinner final AppCompatSpinner shop_spn = (AppCompatSpinner) view.findViewById(R.id.filter_spn0); ArrayAdapter<String> shop_adapter = new ArrayAdapter<>(getContext(), R.layout.spinner_dark_text_item, shopList); shop_spn.setAdapter(shop_adapter); shop_spn.setOnItemSelectedListener(new SelectedListener(recordAction, SelectedListener.SPINNER_SHOP)); // 品牌的Spinner final AppCompatSpinner brand_spn = (AppCompatSpinner) view.findViewById(R.id.filter_spn1); ArrayAdapter<String> brand_adapter = new ArrayAdapter<>(getContext(), R.layout.spinner_dark_text_item, brandList); brand_spn.setAdapter(brand_adapter); brand_spn.setOnItemSelectedListener(new SelectedListener(recordAction, SelectedListener.SPINNER_BRAND)); final AppCompatSpinner address_spn = (AppCompatSpinner) view.findViewById(R.id.filter_spn2); address_spn.setVisibility(View.GONE); } private void setupSwipeRefresh(View view) { record_refresh = (SwipeRefreshLayout) view.findViewById(R.id.record_sr); record_refresh.setColorSchemeResources(R.color.colorMain, R.color.colorSpecial, R.color.colorSpecialConverse); record_refresh.setOnRefreshListener(this); } private void setupRecyclerView(View view) { RecordShoeRycAdapter adapter = new RecordShoeRycAdapter(shoeList, getContext()); adapter.setBaseAction(recordAction); final RecyclerView record_rv = (RecyclerView) view.findViewById(R.id.record_rv); record_rv.setLayoutManager(new LinearLayoutManager(getContext())); record_rv.setAdapter(adapter); record_rv.setItemAnimator(new DefaultItemAnimator()); // record_rv.addOnScrollListener(new LoadScrollListener(adapter)); } @Override public void onMultiHandleResponse(String tag, String result) throws JSONException { onStopRefresh(); Log.i("Result", "lock record"); if (getView() != null) { if (isFstInit) { shoeList = recordAction.handleResponse(result); isFstInit = false; onSpinnerListInit(); // setupFilterBar(getView()); setupRecyclerView(getView()); return; } final RecyclerView recyclerView = (RecyclerView) getView().findViewById(R.id.record_rv); RecordShoeRycAdapter adapter = (RecordShoeRycAdapter) recyclerView.getAdapter(); switch (recordAction.getAction()) { case BaseAction.ACTION_DEFAULT_REFRESH: shoeList = recordAction.handleResponse(result); break; case BaseAction.ACTION_FILTER: shoeList = recordAction.handleResponse(result); break; case BaseAction.ACTION_LOAD_MORE: ArrayList<ObjectShoe> shoes = recordAction.handleResponse(result); for (int i = 0; i < shoes.size(); i++) { shoeList.add(shoes.get(i)); } break; default: break; } adapter.setShoeList(shoeList); adapter.notifyDataSetChanged(); } } @Override public void onNullResponse() throws JSONException { onStopRefresh(); if (isFstInit) { ((AppCompatActivity) getContext()).finish(); } } @Override public void setCustomTag(String tag) { } @Override public String getCustomTag() { return null; } @Override public void onRefresh() { recordAction.getFilterRecord("", "", "", ""); } private void onStopRefresh() { if (getView() != null && record_refresh != null && record_refresh.isRefreshing()) { record_refresh.setRefreshing(false); } } @Override public void onClick(View v) { DatePickerFragDialog datePicker = new DatePickerFragDialog(); datePicker.setBaseAction(recordAction, DatePickerFragDialog.DATE_RECORD); datePicker.show(((AppCompatActivity) getContext()).getSupportFragmentManager(), "datePicker"); } } <file_sep>/app/src/main/java/com/waletech/walesmart/shop/area/AreaAction.java package com.waletech.walesmart.shop.area; import android.content.Context; import android.util.Log; import com.waletech.walesmart.publicObject.ObjectShoe; import com.waletech.walesmart.R; import com.waletech.walesmart.base.BaseAction; import com.waletech.walesmart.base.Base_Frag; import com.waletech.walesmart.http.HttpAction; import com.waletech.walesmart.http.HttpHandler; import com.waletech.walesmart.http.HttpSet; import com.waletech.walesmart.http.HttpTag; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; /** * Created by KeY on 2016/7/8. */ public class AreaAction extends BaseAction { private Base_Frag fragment; public AreaAction(Context context) { super(context); } public AreaAction(Context context, Base_Frag fragment) { super(context); this.fragment = fragment; } public void getAreaShoe(String area_name) { if (!checkNet()) { return; } // String[] key = {HttpSet.KEY_SHOP_NAME}; // String[] value = {shop_name}; String[] key = {HttpSet.KEY_AREA_NAME}; String[] value = {area_name}; HttpAction action = new HttpAction(context); action.setUrl(HttpSet.URL_GET_SHOP_SHOE); action.setTag(HttpTag.SHOP_GET_SHOP_SHOE); action.setDialog(context.getString(R.string.base_search_progress_title), context.getString(R.string.base_search_progress_msg)); action.setMap(key, value); if (fragment != null) { action.setHandler(new HttpHandler(context, fragment)); } else { action.setHandler(new HttpHandler(context)); } action.interaction(); } public ArrayList<ObjectShoe> handleListResponse(String result) throws JSONException { Log.i("Result", "result is : " + result); JSONArray array = new JSONArray(result); ArrayList<ObjectShoe> shoeList = new ArrayList<>(); for (int i = 0; i < array.length(); i++) { JSONObject obj = array.getJSONObject(i); ObjectShoe shoe = new ObjectShoe(); for (int k = 0; k < obj.length(); k++) { shoe.value_set[k] = obj.getString(ObjectShoe.key_set[k]); } shoeList.add(shoe); } return shoeList; } } <file_sep>/app/src/main/java/com/waletech/walesmart/map/LocApplication.java package com.waletech.walesmart.map; import android.app.Application; import com.baidu.mapapi.SDKInitializer; /** * Created by KeY on 2016/4/15. */ public class LocApplication extends Application { @Override public void onCreate() { super.onCreate(); SDKInitializer.initialize(getApplicationContext()); } } <file_sep>/app/src/main/java/com/waletech/walesmart/user/shopInfo/order/OrderItemRycAdapter.java package com.waletech.walesmart.user.shopInfo.order; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.waletech.walesmart.BaseShoeRycAdapter; import com.waletech.walesmart.R; import com.waletech.walesmart.publicObject.ObjectShoe; import java.util.ArrayList; /** * Created by KeY on 2016/7/26. */ public class OrderItemRycAdapter extends BaseShoeRycAdapter { public OrderItemRycAdapter(ArrayList<ObjectShoe> shoeList, Context context) { super(shoeList, context); } @Override public BaseShoeRycAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = View.inflate(parent.getContext(), R.layout.recycler_shoe_order_item, null); return new ViewHolder(view); } @Override public void onBindViewHolder(BaseShoeRycAdapter.ViewHolder holder, int position) { super.onBindViewHolder(holder, position); ObjectShoe shoe = shoeList.get(position); holder.item_ll.setOnClickListener(null); ViewHolder child_holder = (ViewHolder) holder; String count_str = context.getString(R.string.order_item_item_count) + "\n" + shoe.getCount(); child_holder.count_tv.setText(count_str); String price_str = context.getString(R.string.order_item_item_price) + "\n" + shoe.getPrice(); child_holder.price_tv.setText(price_str); // if (!shoe.getSmarkId().equals("miss")) { // child_holder.missed_tv.setVisibility(View.GONE); // } else { // child_holder.missed_tv.setVisibility(View.VISIBLE); // } } @Override public int getItemCount() { return super.getItemCount(); } class ViewHolder extends BaseShoeRycAdapter.ViewHolder { TextView count_tv; TextView price_tv; // TextView missed_tv; public ViewHolder(View itemView) { super(itemView); count_tv = (TextView) itemView.findViewById(R.id.rv_count_tv); price_tv = (TextView) itemView.findViewById(R.id.rv_price_tv); // missed_tv = (TextView) itemView.findViewById(R.id.rv_missed_tv); } } } <file_sep>/app/src/main/java/com/waletech/walesmart/comment/Comment_Act.java package com.waletech.walesmart.comment; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RatingBar; import android.widget.TextView; import com.waletech.walesmart.R; import com.waletech.walesmart.base.Base_Act; import com.waletech.walesmart.http.HttpSet; import com.waletech.walesmart.http.HttpTag; import com.waletech.walesmart.product.Product_Act; import com.waletech.walesmart.publicClass.BitmapCache; import com.waletech.walesmart.publicClass.LineToast; import com.waletech.walesmart.publicClass.Methods; import com.waletech.walesmart.publicObject.ObjectShoe; import com.waletech.walesmart.publicSet.IntentSet; import com.waletech.walesmart.publicSet.MapSet; import org.json.JSONException; import java.util.HashMap; public class Comment_Act extends Base_Act { private LineToast toast; private BitmapCache cache; private HashMap<String, String> comment_map; private String epc_code; private CommentAction commentAction; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_comment_layout); varInit(); setupToolbar(); setupRatingBar(); setupAdviceEdit(); setupCommentBtn(); } @Override protected void setupToolbar() { setTbTitle(getString(R.string.com_toolbar_title)); } private void varInit() { commentAction = new CommentAction(this); cache = new BitmapCache(); toast = new LineToast(Comment_Act.this); if (getIntent() != null) { epc_code = getIntent().getStringExtra(IntentSet.KEY_EPC_CODE); // epc_code = "30382FF10082C6C0000101B2"; HttpSet.setBaseIP(sharedAction.getNetIP(), this); HttpSet.setBaseService(sharedAction.getNetService(), this); commentAction.getShoeDetails(epc_code); } else { epc_code = ""; } comment_map = new HashMap<>(); } private void setupRatingBar() { final RatingBar width_rat = (RatingBar) findViewById(R.id.com_rat0); final RatingBar material_rat = (RatingBar) findViewById(R.id.com_rat1); final RatingBar sport_rat = (RatingBar) findViewById(R.id.com_rat2); width_rat.setOnRatingBarChangeListener(ratingListener); material_rat.setOnRatingBarChangeListener(ratingListener); sport_rat.setOnRatingBarChangeListener(ratingListener); } private void setupAdviceEdit() { final LinearLayout rating_ll = (LinearLayout) findViewById(R.id.com_ll); rating_ll.setOnClickListener(clickListener); } private void setupCommentBtn() { final Button commit_btn = (Button) findViewById(R.id.com_commit_btn); commit_btn.setOnClickListener(clickListener); final Button shop_btn = (Button) findViewById(R.id.com_shop_btn); shop_btn.setOnClickListener(clickListener); } @Override public void onMultiHandleResponse(String tag, String result) throws JSONException { switch (tag) { case HttpTag.COMMENT_COMMIT: commentAction.handleCommentResponse(result); finish(); break; case HttpTag.PRODUCT_GET_SHOE_DETAILS: ObjectShoe shoe = commentAction.handleShoeDetails(result); setupDetailsText(shoe); break; default: break; } } @Override public void onNullResponse() throws JSONException { finish(); } @Override public void onPermissionAccepted(int permission_code) { } @Override public void onPermissionRefused(int permission_code) { } private void setupDetailsText(ObjectShoe shoe) { String brand = shoe.getBrand(); String design = shoe.getDesign(); String color = shoe.getColor(); String size = shoe.getSize(); String img_url = shoe.getImagePath(); final ImageView pro_img = (ImageView) findViewById(R.id.com_img); final TextView pro_tv = (TextView) findViewById(R.id.com_tv1); Methods.downloadImage(pro_img, HttpSet.BASE_URL + img_url, cache); String params = brand + "\n" + design + "\n" + color + "\n" + size; pro_tv.setText(params); } private final static String TAG_RATING_WIDTH = "tag_rating_width"; private final static String TAG_RATING_MATERIAL = "tag_rating_materail"; private final static String TAG_RATING_SPORT = "tag_rating_sport"; private RatingBar.OnRatingBarChangeListener ratingListener = new RatingBar.OnRatingBarChangeListener() { @Override public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) { int rating_int = (int) rating; if (fromUser) { switch (ratingBar.getId()) { case R.id.com_rat0: comment_map.put(MapSet.KEY_EXP_WIDTH, "" + rating_int); ExplainAction.showExplain(Comment_Act.this, TAG_RATING_WIDTH, rating_int); break; case R.id.com_rat1: comment_map.put(MapSet.KEY_EXP_MATERIAL, "" + rating_int); ExplainAction.showExplain(Comment_Act.this, TAG_RATING_MATERIAL, rating_int); break; case R.id.com_rat2: comment_map.put(MapSet.KEY_EXP_SPORT, "" + rating_int); ExplainAction.showExplain(Comment_Act.this, TAG_RATING_SPORT, rating_int); break; default: break; } } } }; private View.OnClickListener clickListener = new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.com_ll: Methods.collapseIME(Comment_Act.this); break; case R.id.com_commit_btn: onCommit(); break; case R.id.com_shop_btn: onShop(); break; default: break; } } }; private void onCommit() { final EditText advice_et = (EditText) findViewById(R.id.com_et); comment_map.put(MapSet.KEY_EXP_ADVICE, advice_et.getText().toString()); commentAction.commitComment(epc_code, comment_map); } private void onShop() { onCommit(); Intent product_int = new Intent(Comment_Act.this, Product_Act.class); product_int.putExtra(IntentSet.KEY_EPC_CODE, epc_code); product_int.putExtra(IntentSet.KEY_IS_FROM_SHOP, false); startActivity(product_int); } } <file_sep>/app/src/main/java/com/waletech/walesmart/publicSet/MapSet.java package com.waletech.walesmart.publicSet; /** * Created by KeY on 2016/6/23. */ public final class MapSet { public final static String KEY_EPC_CODE = "key_epc_code"; public final static String KEY_ITEM_POSITION = "key_item_position"; public final static String KEY_IS_HAVE_FAVOURITE = "key_is_have_favourite"; public final static String KEY_CHECK_LIST = "key_check_list"; public final static String KEY_SHOE_LIST = "key_shoe_list"; public final static String KEY_EXP_WIDTH = "key_exp_width"; public final static String KEY_EXP_MATERIAL = "key_exp_material"; public final static String KEY_EXP_SPORT = "key_exp_sport"; public final static String KEY_EXP_ADVICE = "key_exp_advice"; } <file_sep>/app/src/main/java/com/waletech/walesmart/ManagerBaseShoeRycAdapter.java package com.waletech.walesmart; import android.view.ViewGroup; import java.util.ArrayList; /** * Created by lenovo on 2016/11/29. */ public abstract class ManagerBaseShoeRycAdapter extends BaseRycAdapter { public ManagerBaseShoeRycAdapter(ArrayList dataList) { super(dataList); } @Override public DataViewHolder onCreateDataViewHolder(ViewGroup parent) { return null; } @Override public void onBindDataViewHolder(DataViewHolder parent, int position) { } } <file_sep>/app/src/main/java/com/waletech/walesmart/main/experience/Experience_Frag.java package com.waletech.walesmart.main.experience; import android.Manifest; import android.annotation.TargetApi; import android.app.Dialog; import android.content.DialogInterface; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.support.v4.widget.ContentLoadingProgressBar; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AlertDialog; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageButton; import android.widget.Spinner; import android.widget.TextView; import com.baidu.mapapi.map.MapView; import com.waletech.walesmart.R; import com.waletech.walesmart.base.Base_Frag; import com.waletech.walesmart.datainfo.AddressSet; import com.waletech.walesmart.datainfo.DataBaseAction; import com.waletech.walesmart.http.HttpAction; import com.waletech.walesmart.map.MapHelper; import com.waletech.walesmart.publicClass.ScreenSize; import com.waletech.walesmart.publicObject.ObjectShop; import com.waletech.walesmart.user.authInfo.PermissionAction; import org.json.JSONException; import java.util.ArrayList; /** * Created by KeY on 2016/6/28. */ public class Experience_Frag extends Base_Frag implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener { private SwipeRefreshLayout exp_refresh; private ArrayList<ObjectShop> shopList; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_main_experience_store_layout, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); varInit(); setupNetDownView(view); } private void varInit() { shopList = new ArrayList<>(); } private void setupNetDownView(View view) { if (!HttpAction.checkNet(getContext())) { View net_down_view = view.findViewById(R.id.exp_net_down_view); net_down_view.setVisibility(View.VISIBLE); ImageButton net_down_imgbtn = (ImageButton) view.findViewById(R.id.net_down_imgbtn); net_down_imgbtn.setOnClickListener(this); setupSwipeRefresh(view); setupRecyclerView(view, "", "", ""); return; } initExpView(view); } private void initExpView(View view) { setupSwipeRefresh(view); setupFindShopBtn(view); // 初始化,因为百度地图加载有时候速度太慢 // 容易导致误触 setupRecyclerView(view, "init", "init", "init"); setupMapView(view); } private void setupSwipeRefresh(View view) { exp_refresh = (SwipeRefreshLayout) view.findViewById(R.id.exp_sr); exp_refresh.setColorSchemeResources(R.color.colorMain, R.color.colorSpecial, R.color.colorSpecialConverse); exp_refresh.setOnRefreshListener(this); } private void setupMapView(final View view) { final MapView exp_mv = (MapView) view.findViewById(R.id.exp_mv); new MapHelper(getContext(), exp_mv) { @Override public void onLoadLocationDone(String province, String city, String county) { setupRecyclerView(view, province, city, county); } }; } private void setupRecyclerView(View view, String province, String city, String county) { shopList = initShopListData(province, city, county); if (shopList.size() == 0) { ObjectShop shop = new ObjectShop(); shop.setName(getString(R.string.exp_no_store_this_area_tv)); shop.setLocation(""); shopList.add(shop); } ExpRycAdapter adapter = new ExpRycAdapter(shopList); final RecyclerView exp_rv = (RecyclerView) view.findViewById(R.id.exp_rv); exp_rv.setLayoutManager(new LinearLayoutManager(getContext())); exp_rv.setAdapter(adapter); exp_rv.addOnScrollListener(scrollListener); onStopRefresh(); } private ArrayList<ObjectShop> initShopListData(String province, String city, String county) { ArrayList<ObjectShop> shopList = new ArrayList<>(); DataBaseAction baseAction = DataBaseAction.onCreate(getContext()); ArrayList<String> shopNameList = baseAction. query(AddressSet.TABLE_NAME, new String[]{AddressSet.PROVINCE, AddressSet.CITY, AddressSet.COUNTY}, new String[]{province, city, county}, AddressSet.SHOP, ""); ArrayList<String> shopLocList = new ArrayList<>(); for (int i = 0; i < shopNameList.size(); i++) { String shop_name = shopNameList.get(i); ArrayList<String> singleLoc_List = baseAction. query(AddressSet.TABLE_NAME, new String[]{AddressSet.SHOP}, new String[]{shop_name}, AddressSet.ROAD, ""); shopLocList.add(singleLoc_List.get(0)); } for (int i = 0; i < shopNameList.size(); i++) { ObjectShop shop = new ObjectShop(); shop.setName(shopNameList.get(i)); shop.setLocation(shopLocList.get(i)); shopList.add(shop); } return shopList; } private void setupFindShopBtn(View view) { final Button find_shop_btn = (Button) view.findViewById(R.id.exp_btn); find_shop_btn.setOnClickListener(this); } private String province_str = ""; private String city_str = ""; private String county_str = ""; @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private void setupSpinnerGroup(final View v) { DataBaseAction baseAction = DataBaseAction.onCreate(getContext()); ArrayList<String> provinceList = baseAction.query(AddressSet.TABLE_NAME, new String[]{""}, new String[]{""}, AddressSet.PROVINCE, ""); provinceList.add(0, getString(R.string.base_item_all)); ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), R.layout.spinner_text_item, provinceList); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); Spinner province_spn = (Spinner) v.findViewById(R.id.location_spn0); province_spn.setAdapter(adapter); province_spn.setDropDownVerticalOffset(province_spn.getLayoutParams().height); province_spn.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { TextView item_tv = (TextView) view; DataBaseAction baseAction = DataBaseAction.onCreate(getContext()); province_str = item_tv.getText().toString(); ArrayList<String> cityList = baseAction.query(AddressSet.TABLE_NAME, new String[]{AddressSet.PROVINCE}, new String[]{province_str}, AddressSet.CITY, ""); cityList.add(0, getString(R.string.base_item_all)); ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), R.layout.spinner_text_item, cityList); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); final Spinner city_spn = (Spinner) v.findViewById(R.id.location_spn1); city_spn.setAdapter(adapter); city_spn.setDropDownVerticalOffset(city_spn.getLayoutParams().height); city_spn.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { TextView item_tv = (TextView) view; city_str = item_tv.getText().toString(); DataBaseAction baseAction = DataBaseAction.onCreate(getContext()); ArrayList<String> countyList = baseAction.query(AddressSet.TABLE_NAME, new String[]{AddressSet.CITY}, new String[]{city_str}, AddressSet.COUNTY, ""); countyList.add(0, getString(R.string.base_item_all)); ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), R.layout.spinner_text_item, countyList); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); final Spinner county_spn = (Spinner) v.findViewById(R.id.location_spn2); county_spn.setAdapter(adapter); county_spn.setDropDownVerticalOffset(county_spn.getLayoutParams().height); county_spn.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { TextView item_tv = (TextView) view; county_str = item_tv.getText().toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } private void setupConfirmBtn(View view) { final Button confirm_btn = (Button) view.findViewById(R.id.location_btn); confirm_btn.setOnClickListener(this); } @Override public void onMultiHandleResponse(String tag, String result) throws JSONException { onStopRefresh(); } @Override public void onNullResponse() throws JSONException { onStopRefresh(); } @Override public void setCustomTag(String tag) { } @Override public String getCustomTag() { return null; } @Override public void onRefresh() { if (!HttpAction.checkNet(getContext())) { return; } if (!PermissionAction.check(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION)) { onStopRefresh(); new AlertDialog.Builder(getContext()) .setTitle(getContext().getString(R.string.auth_dialog_title)) .setMessage(getContext().getString(R.string.auth_dialog_map_permission_msg)) .setPositiveButton(getContext().getString(R.string.base_dialog_btn_okay), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .show(); return; } setupMapView(getView()); } private void onStopRefresh() { if (getView() != null && exp_refresh != null && exp_refresh.isRefreshing()) { exp_refresh.setRefreshing(false); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.exp_btn: onCreateLocationDialog(); break; case R.id.location_btn: onConfirmLocation(); break; case R.id.net_down_imgbtn: onRefreshLayout(v); break; default: break; } } private void onCreateLocationDialog() { LayoutInflater inflater = getLayoutInflater(null); View view = inflater.inflate(R.layout.public_location_spinner_item, null); AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setView(view); setupSpinnerGroup(view); // 获取屏幕的高度,设定标准的对话框高度为屏幕的一半的大小 ScreenSize size = new ScreenSize(getContext()); int standard_height = (int) (size.getHeight() * 0.5); Dialog dialog = builder.create(); Window dialogWindow = dialog.getWindow(); WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.CENTER); lp.height = standard_height; dialogWindow.setAttributes(lp); dialog.show(); dialog.show(); setupConfirmBtn(view); } private void onConfirmLocation() { if (province_str.equals(getString(R.string.base_item_all))) { province_str = ""; } if (city_str.equals(getString(R.string.base_item_all))) { city_str = ""; } if (county_str.equals(getString(R.string.base_item_all))) { county_str = ""; } DataBaseAction baseAction = DataBaseAction.onCreate(getContext()); ArrayList<String> shopNameList = baseAction.query(AddressSet.TABLE_NAME, new String[]{AddressSet.PROVINCE, AddressSet.CITY, AddressSet.COUNTY}, new String[]{province_str, city_str, county_str}, AddressSet.SHOP, ""); onCreateShopDialog(shopNameList); // if (dialog != null && dialog.isShowing()) { // dialog.dismiss(); // } } private void onRefreshLayout(View view) { final View child = view; final View parent = (View) view.getParent(); child.setVisibility(View.INVISIBLE); final TextView net_down_tv = (TextView) parent.findViewById(R.id.net_down_tv); net_down_tv.setVisibility(View.INVISIBLE); final ContentLoadingProgressBar net_down_pb = (ContentLoadingProgressBar) parent.findViewById(R.id.net_down_pb); net_down_pb.setVisibility(View.VISIBLE); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { if (HttpAction.checkNet(getContext())) { final View net_down_rl = parent.findViewById(R.id.exp_net_down_view); net_down_rl.setVisibility(View.GONE); initExpView(getView()); } else { child.setVisibility(View.VISIBLE); net_down_tv.setVisibility(View.VISIBLE); net_down_pb.setVisibility(View.GONE); } } }, 2 * 1000); } private RecyclerView.OnScrollListener scrollListener = new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); int topRowVerticalPosition = (recyclerView == null || recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop(); exp_refresh.setEnabled(topRowVerticalPosition >= 0); } }; private void onCreateShopDialog(ArrayList<String> shopNameList) { if (shopNameList == null || (shopNameList.size() == 0)) { return; } ExpRycAdapter adapter = new ExpRycAdapter(initShopListData(shopNameList)); LayoutInflater inflater = getLayoutInflater(null); View view = inflater.inflate(R.layout.public_shop_list_page, null); final RecyclerView shop_list_rv = (RecyclerView) view.findViewById(R.id.shop_list_rv); LinearLayoutManager manager = new LinearLayoutManager(getContext()); shop_list_rv.setLayoutManager(manager); shop_list_rv.setItemAnimator(new DefaultItemAnimator()); shop_list_rv.setAdapter(adapter); // 获取屏幕的高度,设定标准的对话框高度为屏幕的一半的大小 ScreenSize size = new ScreenSize(getContext()); int standard_height = size.getHeight() / 2; AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setView(view); Dialog dialog = builder.create(); Window dialogWindow = dialog.getWindow(); WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.CENTER); lp.height = standard_height; dialogWindow.setAttributes(lp); dialog.show(); } private ArrayList<ObjectShop> initShopListData(ArrayList<String> shopNameList) { ArrayList<ObjectShop> shopList = new ArrayList<>(); DataBaseAction baseAction = DataBaseAction.onCreate(getContext()); if (shopNameList == null) { shopNameList = baseAction.query(AddressSet.TABLE_NAME, new String[]{""}, new String[]{""}, AddressSet.SHOP, ""); } ArrayList<String> shopLocList = new ArrayList<>(); for (int i = 0; i < shopNameList.size(); i++) { String shop_name = shopNameList.get(i); ArrayList<String> singleLoc_List = baseAction. query(AddressSet.TABLE_NAME, new String[]{AddressSet.SHOP}, new String[]{shop_name}, AddressSet.ROAD, ""); shopLocList.add(singleLoc_List.get(0)); } for (int i = 0; i < shopNameList.size(); i++) { ObjectShop shop = new ObjectShop(); shop.setName(shopNameList.get(i)); shop.setLocation(shopLocList.get(i)); shopList.add(shop); } return shopList; } } <file_sep>/app/src/main/java/com/waletech/walesmart/base/BaseAction.java package com.waletech.walesmart.base; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import com.waletech.walesmart.R; import com.waletech.walesmart.login.Login_Act; import com.waletech.walesmart.publicClass.LineToast; import com.waletech.walesmart.publicClass.Methods; import com.waletech.walesmart.sharedinfo.SharedAction; /** * Created by KeY on 2016/6/3. */ public class BaseAction { public final static int ACTION_DEFAULT_REFRESH = 0; public final static int ACTION_LOAD_MORE = 1; public final static int ACTION_FILTER = 2; protected Context context; protected LineToast toast; protected SharedAction sharedAction; public BaseAction(Context context) { this.context = context; varInit(); } protected int action = ACTION_DEFAULT_REFRESH; public int getAction() { return action; } protected void varInit() { if (toast == null) { toast = new LineToast(context); } if (sharedAction == null) { sharedAction = new SharedAction(context); } } protected boolean checkNet() { varInit(); if (!Methods.isNetworkAvailable(context)) { toast.showToast(context.getString(R.string.base_toast_net_down)); } return Methods.isNetworkAvailable(context); } public boolean checkLoginStatus() { if (!sharedAction.getLoginStatus()) { Intent login_int = new Intent(context, Login_Act.class); context.startActivity(login_int); toast.showToast(context.getString(R.string.base_toast_login_first)); } return sharedAction.getLoginStatus(); } // 具体的检测网络的方法 // private boolean isNetworkAvailable(Context context) { // // 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理) // ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // // if (connectivityManager == null) { // return false; // } else { // // 获取NetworkInfo对象 // NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo(); // // if (networkInfo != null && networkInfo.length > 0) { // for (int i = 0; i < networkInfo.length; i++) { // //System.out.println(i + "===状态===" + networkInfo[i].getState()); // //System.out.println(i + "===类型===" + networkInfo[i].getTypeName()); // // 判断当前网络状态是否为连接状态 // if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) { // return true; // } // } // } // } // return false; // } } <file_sep>/app/src/main/java/com/waletech/walesmart/user/shopInfo/order/Order_Item_Act.java package com.waletech.walesmart.user.shopInfo.order; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import com.waletech.walesmart.R; import com.waletech.walesmart.base.Base_Act; import com.waletech.walesmart.publicObject.ObjectShoe; import com.waletech.walesmart.publicSet.IntentSet; import org.json.JSONException; import java.util.ArrayList; public class Order_Item_Act extends Base_Act { private OrderItemAction orderItemAction; private ArrayList<ObjectShoe> shoeList; private boolean isFstInit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_order_item_layout); varInit(); setupToolbar(); } private void varInit() { String order_num = getIntent().getStringExtra(IntentSet.KEY_ORDER_NUM); orderItemAction = new OrderItemAction(this); orderItemAction.getShoeList(order_num); isFstInit = true; } @Override protected void setupToolbar() { setTbTitle(getString(R.string.order_item_toolbar_title)); setTbNavigation(); } private void setupRecyclerView() { OrderItemRycAdapter adapter = new OrderItemRycAdapter(shoeList, this); final RecyclerView order_item_rv = (RecyclerView) findViewById(R.id.order_item_rv); order_item_rv.setLayoutManager(new LinearLayoutManager(this)); order_item_rv.setAdapter(adapter); } @Override public void onMultiHandleResponse(String tag, String result) throws JSONException { if (isFstInit) { shoeList = orderItemAction.handleResponse(result); setupRecyclerView(); isFstInit = false; } } @Override public void onNullResponse() throws JSONException { if (isFstInit) { finish(); } } @Override public void onPermissionAccepted(int permission_code) { } @Override public void onPermissionRefused(int permission_code) { } } <file_sep>/app/src/main/java/com/waletech/walesmart/LoadScrollListener.java package com.waletech.walesmart; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import com.waletech.walesmart.base.BaseAction; /** * Created by KeY on 2016/7/10. */ public class LoadScrollListener extends RecyclerView.OnScrollListener { private BaseShoeRycAdapter adapter; public LoadScrollListener(BaseShoeRycAdapter adapter) { this.adapter = adapter; } @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager(); if (newState == RecyclerView.SCROLL_STATE_IDLE) { int total_item = manager.getItemCount(); if (total_item == 0) { return; } int last_item = manager.findLastCompletelyVisibleItemPosition(); // 如果总共有8个item,即total = 8,但是因为last是从0开始的,最后一个也就是到7,所以last需要多加1 last_item++; // 判断child item的个数有没有超出屏幕,如果有,才允许上拉加载 // 这里只要判断child item的总高度有没有超过manager(即recyclerview)的高度就可以了 // 当然在 recyclerview里面判断是否高于屏幕也可以! int parent_height = manager.getHeight(); int child_height = manager.getChildAt(0).getHeight(); int total_height = total_item * child_height; if (total_height < parent_height) { return; } // 否则就进行上拉加载更多 if (last_item == total_item) { if (adapter.getIsShowLoad()) { return; } adapter.setIsShowLoad(true); adapter.notifyItemChanged(manager.findLastCompletelyVisibleItemPosition()); } } } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); } } <file_sep>/app/src/main/java/com/waletech/walesmart/user/lockInfo/LockInfo_Act.java package com.waletech.walesmart.user.lockInfo; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.util.Log; import com.waletech.walesmart.R; import com.waletech.walesmart.base.Base_Act; import com.waletech.walesmart.http.HttpAction; import com.waletech.walesmart.http.HttpSet; import com.waletech.walesmart.http.HttpTag; import com.waletech.walesmart.publicAction.GetServiceVersionAction; import com.waletech.walesmart.publicClass.ViewTadAdapter; import com.waletech.walesmart.user.lockInfo.record.LockRecord_Frag; import com.waletech.walesmart.user.lockInfo.using.LockUsing_Frag; import org.json.JSONException; import java.util.ArrayList; import java.util.List; public class LockInfo_Act extends Base_Act { public static boolean isView = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user_lock_info_layout); if (HttpSet.getBaseService().equals("/ClientBaseService/")) { HttpSet.setBaseIP(sharedAction.getNetIP(), this); HttpSet.setBaseService(sharedAction.getNetService(), this); } // if (HttpAction.checkNet(this)) { // finish(); // } setupContent(); } private void setupContent() { isView = true; setupToolbar(); setupViewPager(); } @Override protected void setupToolbar() { setTbTitle(getString(R.string.lockinfo_toolbar_title)); setTbNavigation(); } private void setupViewPager(/*ArrayList<ObjectShoe> using_shoeList, ArrayList<ObjectShoe> record_shoeList*/) { final ViewPager main_vp = (ViewPager) findViewById(R.id.lock_info_vp); List<Fragment> fragments = new ArrayList<>(); LockUsing_Frag tab01 = new LockUsing_Frag(); LockRecord_Frag tab02 = new LockRecord_Frag(); fragments.add(tab01); fragments.add(tab02); String[] titles = {getString(R.string.lockinfo_tab_unlock_using), getString(R.string.lockinfo_tab_unlock_record)}; ViewTadAdapter adapter = new ViewTadAdapter(getSupportFragmentManager()); adapter.setFragments(fragments); adapter.setTitles(titles); main_vp.setAdapter(adapter); main_vp.setOffscreenPageLimit(fragments.size()); setupTabLayout(main_vp); } private void setupTabLayout(ViewPager viewPager) { final TabLayout lockinfo_tab = (TabLayout) findViewById(R.id.lock_info_tab); lockinfo_tab.setupWithViewPager(viewPager); // 设置tab的文字,在被选中后和没被选中的时候,分别显示的颜色 lockinfo_tab.setSelectedTabIndicatorColor(getResources().getColor(R.color.colorMain)); lockinfo_tab.setTabTextColors(getResources().getColor(R.color.colorAssist), getResources().getColor(R.color.colorMain)); lockinfo_tab.setSelectedTabIndicatorHeight(7); } @Override public void onMultiHandleResponse(String tag, String result) throws JSONException { } @Override public void onNullResponse() throws JSONException { // finish(); } @Override public void onPermissionAccepted(int permission_code) { } @Override public void onPermissionRefused(int permission_code) { } } <file_sep>/app/src/main/java/com/waletech/walesmart/publicAction/GetAddressAction.java package com.waletech.walesmart.publicAction; import android.content.Context; import android.os.Looper; import android.util.Log; import com.waletech.walesmart.base.BaseAction; import com.waletech.walesmart.base.Base_Serv; import com.waletech.walesmart.datainfo.AddressSet; import com.waletech.walesmart.datainfo.DataBaseAction; import com.waletech.walesmart.http.HttpAction; import com.waletech.walesmart.http.HttpHandler; import com.waletech.walesmart.http.HttpSet; import com.waletech.walesmart.http.HttpTag; import org.json.JSONArray; import org.json.JSONException; /** * Created by KeY on 2016/6/6. */ public class GetAddressAction extends BaseAction { private Base_Serv service; public GetAddressAction(Context context) { super(context); } public GetAddressAction(Context context, Base_Serv service) { super(context); this.service = service; } public void getAddress() { String[] key = {""}; String[] value = {""}; HttpAction action = new HttpAction(context); action.setUrl(HttpSet.URL_GET_ADDRESS); action.setMap(key, value); action.setTag(HttpTag.GET_ADDRESS); if (service != null) { Log.i("Result", "action in service"); action.setHandler(new HttpHandler(context, service)); } else { action.setHandler(new HttpHandler(context)); } action.interaction(); } public void handleResponse(String result) throws JSONException { Log.i("Result", "get address result is : " + result); JSONArray array = new JSONArray(result); DataBaseAction action = DataBaseAction.onCreate(context); action.delete(AddressSet.TABLE_NAME); action.insert(AddressSet.TABLE_NAME, AddressSet.ALL, array); } } <file_sep>/app/src/main/java/com/waletech/walesmart/user/shopInfo/order/Order_Act.java package com.waletech.walesmart.user.shopInfo.order; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import com.waletech.walesmart.R; import com.waletech.walesmart.base.Base_Act; import com.waletech.walesmart.publicObject.ObjectOrder; import org.json.JSONException; import java.util.ArrayList; public class Order_Act extends Base_Act implements SwipeRefreshLayout.OnRefreshListener { private SwipeRefreshLayout order_refresh; private RecyclerView order_rv; private OrderAction orderAction; private ArrayList<ObjectOrder> orderList; private boolean isFstInit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_order_layout); varInit(); setupToolbar(); setupSwipeRefresh(); } private void varInit() { orderAction = new OrderAction(this); orderAction.getOrderList(); isFstInit = true; } @Override protected void setupToolbar() { setTbTitle(getString(R.string.order_toolbar_title)); setTbNavigation(); } private void setupSwipeRefresh() { order_refresh = (SwipeRefreshLayout) findViewById(R.id.order_sr); order_refresh.setColorSchemeResources(R.color.colorMain, R.color.colorSpecial, R.color.colorSpecialConverse); order_refresh.setOnRefreshListener(this); } private void setupRecyclerView() { OrderRycAdapter adapter = new OrderRycAdapter(orderList); order_rv = (RecyclerView) findViewById(R.id.order_rv); order_rv.setLayoutManager(new LinearLayoutManager(this)); order_rv.setAdapter(adapter); } @Override public void onMultiHandleResponse(String tag, String result) throws JSONException { onStopRefresh(); if (isFstInit) { orderList = orderAction.handleResponse(result); setupRecyclerView(); isFstInit = false; return; } OrderRycAdapter adapter = (OrderRycAdapter) order_rv.getAdapter(); adapter.setOrderList(orderList); adapter.notifyDataSetChanged(); } @Override public void onNullResponse() throws JSONException { onStopRefresh(); if (isFstInit) { finish(); } } @Override public void onPermissionAccepted(int permission_code) { } @Override public void onPermissionRefused(int permission_code) { } private void onStopRefresh() { if (order_refresh != null && order_refresh.isRefreshing()) { order_refresh.setRefreshing(false); } } @Override public void onRefresh() { orderAction.getOrderList(); } } <file_sep>/app/src/main/java/com/waletech/walesmart/datainfo/DataBaseAction.java package com.waletech.walesmart.datainfo; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; /** * Created by KeY on 2016/4/14. */ public class DataBaseAction { private static DataBaseHelper helper; private static DataBaseAction action; public DataBaseAction() { } public static DataBaseAction onCreate(Context context) { // helper = new DataBaseHelper(context); helper = DataBaseHelper.getInstance(context); action = new DataBaseAction(); return action; } // public void create(Context context) { // helper = new DataBaseHelper(context); // } public void insert(String tableName, String[] columnName_set, JSONArray array) throws JSONException { switch (tableName) { case AddressSet.TABLE_NAME: helper.onCreateAddrTable(helper.getWritableDatabase()); break; case BrandSet.TABLE_NAME: helper.onCreateBrandTable(helper.getWritableDatabase()); break; default: return; } for (int i = 0; i < array.length(); i++) { JSONObject obj = array.getJSONObject(i); ContentValues cv = new ContentValues(); for (int k = 0; k < columnName_set.length; k++) { cv.put(columnName_set[k], obj.getString(columnName_set[k])); } helper.getWritableDatabase().insertOrThrow(tableName, null, cv); } // helper.close(); } public void insertDirect(String tableName, String[] columnName_set, JSONArray array) throws JSONException { for (int i = 0; i < array.length(); i++) { JSONObject obj = array.getJSONObject(i); ContentValues cv = new ContentValues(); for (int k = 0; k < columnName_set.length; k++) { cv.put(columnName_set[k], obj.getString(columnName_set[k])); } helper.getWritableDatabase().insertOrThrow(tableName, null, cv); } // helper.close(); } public void insertDirect(String tableName, String[] columnName_set, HashMap<String, String> columnValue_map) { ContentValues cv = new ContentValues(); for (int k = 0; k < columnName_set.length; k++) { cv.put(columnName_set[k], columnValue_map.get(columnName_set[k])); } helper.getWritableDatabase().insertOrThrow(tableName, null, cv); } public void delete(String tableName) { String CHECK_SQL = "SELECT count(*) FROM sqlite_master WHERE type='table' AND name=" + "'" + tableName + "'" + ";"; Cursor cursor = helper.getReadableDatabase().rawQuery(CHECK_SQL, null); if (cursor.moveToNext()) { String DEL_SQL = "DROP TABLE " + tableName + ";"; helper.getWritableDatabase().execSQL(DEL_SQL); } cursor.close(); // helper.close(); } public boolean deleteItem(String tableName, String columnName, String columnValue) { String delete_SQL = "DELETE FROM " + tableName + " WHERE " + columnName + "=" + "'" + columnValue + "'"; helper.getWritableDatabase().execSQL(delete_SQL); return !check(tableName, columnName, columnValue); } private boolean check(String tableName, String columnName, String columnValue) { String check_SQL = "SELECT * FROM " + tableName + " WHERE " + columnName + "=?"; Cursor cursor = helper.getReadableDatabase().rawQuery(check_SQL, new String[]{columnValue}); if (cursor.moveToFirst()) { cursor.close(); // helper.close(); return true; } else { cursor.close(); // helper.close(); return false; } } /** * @param tableName 要查询的表名 * @param queryColumnName 要查询的,条件的列名 * @param map 要查询的,条件的列名和值 * @param queryResultColumn 要查询的,结果的列名 * @return 封装好的唯一的一个HashSet */ public HashSet<String> query(String tableName, String[] queryColumnName, HashMap<String, String> map, String queryResultColumn, String orderByColumn) { // 构造查询语句 StringBuilder where_name = new StringBuilder(""); ArrayList<String> where_List = new ArrayList<>(); int len = map.size() - 1; StringBuilder QUERY_SQL = new StringBuilder("SELECT * FROM " + tableName); for (int i = 0; i <= len; i++) { if (map.get(queryColumnName[i]).equals("")) { break; } where_name.append(queryColumnName[i]).append("=?"); if ((i + 1 <= len) && map.get(queryColumnName[i + 1]).equals("")) { where_List.add(map.get(queryColumnName[i])); break; } if (i != len) { where_name.append(" and "); } where_List.add(map.get(queryColumnName[i])); } if (!map.get(queryColumnName[0]).equals("")) { QUERY_SQL.append(" WHERE ").append(where_name); } if (!orderByColumn.equals("")) { QUERY_SQL.append(" ORDER BY ").append(orderByColumn).append(" ASC"); } // Log.i("Result", "sql is : " + QUERY_SQL.toString()); String[] where_value = where_List.toArray(new String[where_List.size()]); Cursor cursor = helper.getReadableDatabase().rawQuery(QUERY_SQL.toString(), where_value); // 封装查询结果 HashSet<String> result_set = new HashSet<>(); if (queryResultColumn.equals(AddressSet.ROAD)) { if (cursor.moveToFirst()) { String result = getFullAddress(cursor) + cursor.getString(cursor.getColumnIndexOrThrow(queryResultColumn)); result_set.add(result); while (cursor.moveToNext()) { result = getFullAddress(cursor) + cursor.getString(cursor.getColumnIndexOrThrow(queryResultColumn)); result_set.add(result); } } } else { if (cursor.moveToFirst()) { result_set.add(cursor.getString(cursor.getColumnIndexOrThrow(queryResultColumn))); while (cursor.moveToNext()) { result_set.add(cursor.getString(cursor.getColumnIndexOrThrow(queryResultColumn))); } } } cursor.close(); // helper.close(); return result_set; } public ArrayList<String> query(String tableName, String[] queryColumnName, String[] queryColumnValue, String queryResultColumn, String orderByColumn) { HashMap<String, String> map = new HashMap<>(); for (int i = 0; i < queryColumnName.length; i++) { map.put(queryColumnName[i], queryColumnValue[i]); } HashSet<String> result_set = query(tableName, queryColumnName, map, queryResultColumn, orderByColumn); Iterator<String> iterator = result_set.iterator(); ArrayList<String> result_List = new ArrayList<>(); while (iterator.hasNext()) { result_List.add(iterator.next()); } return result_List; } private String getFullAddress(Cursor cursor) { String result = cursor.getString(cursor.getColumnIndexOrThrow(AddressSet.PROVINCE)) + cursor.getString(cursor.getColumnIndexOrThrow(AddressSet.CITY)) + cursor.getString(cursor.getColumnIndexOrThrow(AddressSet.COUNTY)); return result; } // 普通查询 public Cursor query(String SQL) { Cursor cursor = helper.getReadableDatabase().rawQuery(SQL, new String[]{}); return cursor; } public static void close() { helper.close(); } } <file_sep>/app/src/main/java/com/waletech/walesmart/user/shopInfo/favourite/FavAction.java package com.waletech.walesmart.user.shopInfo.favourite; import android.content.Context; import android.util.Log; import com.waletech.walesmart.R; import com.waletech.walesmart.base.BaseAction; import com.waletech.walesmart.http.HttpAction; import com.waletech.walesmart.http.HttpHandler; import com.waletech.walesmart.http.HttpResult; import com.waletech.walesmart.http.HttpSet; import com.waletech.walesmart.http.HttpTag; import com.waletech.walesmart.publicObject.ObjectShoe; import com.waletech.walesmart.publicSet.ToastSet; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; /** * Created by KeY on 2016/6/30. */ public class FavAction extends BaseAction { public final static int OPERATION_ADD = 0; public final static int OPERATION_DELETE = 1; public final static int OPERATION_DELETE_BATCH = 2; private String save_brand = ""; private String save_shop_name = ""; public FavAction(Context context) { super(context); } // default public void getFavList() { if (!checkNet()) { return; } save_brand = "All"; save_shop_name = "All"; sharedAction.clearLastIdInfo(); action = BaseAction.ACTION_DEFAULT_REFRESH; interaction(); } public void getFilterList(String brand, String shop_name) { Log.i("Result", "get filter"); if (!brand.equals("")) { save_brand = brand; } if (!shop_name.equals("")) { save_shop_name = shop_name; } sharedAction.clearLastIdInfo(); action = BaseAction.ACTION_FILTER; interaction(); } public void getLoadList() { if (!checkNet()) { return; } action = BaseAction.ACTION_LOAD_MORE; interaction(); } private void interaction() { String[] key = {HttpSet.KEY_USERNAME, HttpSet.KEY_BRAND, HttpSet.KEY_SHOP_NAME, HttpSet.KEY_LAST_ID}; String[] value = {sharedAction.getUsername(), save_brand, save_shop_name, "" + sharedAction.getLastId()}; HttpAction action = new HttpAction(context); action.setUrl(HttpSet.URL_GET_FAVOURITE); action.setTag(HttpTag.FAVOURITE_GET_FAVOURITE_LIST); action.setDialog(context.getString(R.string.base_search_progress_title), context.getString(R.string.base_search_progress_msg)); action.setHandler(new HttpHandler(context)); action.setMap(key, value); action.interaction(); } public void checkFav(String epc_code) { if (!checkNet()) { return; } String[] key = {HttpSet.KEY_USERNAME, HttpSet.KEY_EPC_CODE}; String[] value = {sharedAction.getUsername(), epc_code}; HttpAction action = new HttpAction(context); action.setUrl(HttpSet.URL_CHECK_FAVOURITE); action.setTag(HttpTag.FAVOURITE_CHECK_FAVOURITE); action.setDialog(context.getString(R.string.base_search_progress_title), context.getString(R.string.base_search_progress_msg)); action.setHandler(new HttpHandler(context)); action.setMap(key, value); action.interaction(); } public void operate(int operation_code, String epc_code) { if (!checkNet()) { return; } sharedAction.clearLastIdInfo(); String[] key = {HttpSet.KEY_USERNAME, HttpSet.KEY_EPC_CODE}; String[] value = {sharedAction.getUsername(), epc_code}; HttpAction action = new HttpAction(context); switch (operation_code) { case OPERATION_ADD: action.setUrl(HttpSet.URL_ADD_FAVOURITE); action.setTag(HttpTag.FAVOURITE_ADD_FAVOURITE); action.setDialog(context.getString(R.string.base_add_progress_title), context.getString(R.string.base_add_progress_msg)); break; case OPERATION_DELETE: action.setUrl(HttpSet.URL_DELETE_FAVOURITE); action.setTag(HttpTag.FAVOURITE_DELETE_FAVOURITE); action.setDialog(context.getString(R.string.base_cancel_progress_title), context.getString(R.string.base_cancel_progress_msg)); break; case OPERATION_DELETE_BATCH: action.setUrl(HttpSet.URL_DELETE_BATCH_FAVOURITE); action.setTag(HttpTag.FAVOURITE_DELETE_BATCH_FAVOURITE); action.setDialog(context.getString(R.string.base_delete_progress_title), context.getString(R.string.base_delete_progress_msg)); break; default: break; } action.setHandler(new HttpHandler(context)); action.setMap(key, value); action.interaction(); } public ArrayList<ObjectShoe> handleListResponse(String result) throws JSONException { Log.i("Result", "Fav result is : " + result); JSONArray array = new JSONArray(result); ArrayList<ObjectShoe> shoeList = new ArrayList<>(); if (array.length() == 0) { toast.showToast(context.getString(R.string.base_toast_no_more_item)); return shoeList; } for (int i = 0; i < array.length(); i++) { JSONObject obj = array.getJSONObject(i); ObjectShoe shoe = new ObjectShoe(); for (int k = 0; k < obj.length(); k++) { shoe.value_set[k] = obj.getString(ObjectShoe.key_set[k]); } shoeList.add(shoe); } String last_id = shoeList.get(shoeList.size() - 1).getLastId(); Log.i("Result", "last_id is : " + last_id); sharedAction.setLastId(Integer.parseInt(last_id)); return shoeList; } public void handleResponse(String result) throws JSONException { JSONObject obj = new JSONObject(result); toast.showToast(obj.getString(HttpResult.RESULT)); } } <file_sep>/app/src/main/java/com/waletech/walesmart/shop/Shop_Act.java package com.waletech.walesmart.shop; import android.Manifest; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import com.waletech.walesmart.http.HttpTag; import com.waletech.walesmart.user.authInfo.PermissionAction; import com.waletech.walesmart.R; import com.waletech.walesmart.base.Base_Act; import com.waletech.walesmart.http.HttpAction; import com.waletech.walesmart.publicAction.UnlockAction; import com.waletech.walesmart.publicClass.LineToast; import com.waletech.walesmart.publicClass.ViewTadAdapter; import com.waletech.walesmart.publicObject.ObjectArea; import com.waletech.walesmart.publicSet.BundleSet; import com.waletech.walesmart.publicSet.IntentSet; import com.waletech.walesmart.publicSet.PermissionSet; import com.waletech.walesmart.shop.area.Area_Frag; import org.json.JSONException; import java.util.ArrayList; import java.util.List; public class Shop_Act extends Base_Act implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener, Toolbar.OnMenuItemClickListener { private ViewPager shop_vp; // private SwipeRefreshLayout shop_refresh; private UnlockAction unlockAction; private ShopAction shopAction; private ArrayList<ObjectArea> areaList; private boolean isFstInit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_shop_layout); varInit(); setupToolbar(); setupSwipeRefresh(); // setupOperateImgbtn(); } private void varInit() { unlockAction = new UnlockAction(this); shopAction = new ShopAction(this); areaList = new ArrayList<>(); isFstInit = true; } @Override protected void setupToolbar() { String shop_name = getIntent().getStringExtra(IntentSet.KEY_SHOP_NAME); String shop_location = getIntent().getStringExtra(IntentSet.KEY_SHOP_LOCATION); setTbTitle(shop_name); setTbNavigation(); toolbar.showOverflowMenu(); toolbar.setOnMenuItemClickListener(this); final TextView location_tv = (TextView) findViewById(R.id.shop_tv); location_tv.setText(shop_location); shopAction.getArea(shop_name); } private void setupSwipeRefresh() { // shop_refresh = (SwipeRefreshLayout) findViewById(R.id.shop_sr); // shop_refresh.setColorSchemeResources(R.color.colorMain, R.color.colorSpecial, R.color.colorSpecialConverse); // shop_refresh.setOnRefreshListener(this); } private void onCreateAreaMatrix() { } private void setupViewPager() { // Area_Frag frag01 = new Area_Frag(); // Area_Frag frag02 = new Area_Frag(); // Area_Frag frag03 = new Area_Frag(); // Bundle bundle = new Bundle(); // bundle.putString(BundleSet.KEY_SHOP_NAME, toolbar.getTitle().toString()); // frag01.setArguments(bundle); // // List<Fragment> fragments = new ArrayList<>(); // fragments.add(frag01); // fragments.add(frag02); // fragments.add(frag03); // // String[] titles = {"A区", "B区", "C区"}; List<Fragment> fragments = new ArrayList<>(); List<String> titles = new ArrayList<>(); for (int i = 0; i < areaList.size(); i++) { ObjectArea area = areaList.get(i); Area_Frag frag = new Area_Frag(); for (int k = 0; k < areaList.size(); k++) { String area_line = ""; switch (k) { case 0: area_line = "A"; break; case 1: area_line = "B"; break; case 2: area_line = "C"; break; case 3: area_line = "D"; break; case 4: area_line = "E"; break; default: break; } ObjectArea temp_area = areaList.get(k); if (temp_area.getName().contains(area_line)) { break; } } Log.i("Result", "area name is : " + area.getName()); Bundle bundle = new Bundle(); bundle.putString(BundleSet.KEY_AREA_NAME, area.getName()); bundle.putString(BundleSet.KEY_AREA_ROW, area.getRow()); bundle.putString(BundleSet.KEY_AREA_COLUMN, area.getColumn()); frag.setArguments(bundle); fragments.add(frag); titles.add(area.getName()); } String[] title_arr = titles.toArray(new String[titles.size()]); ViewTadAdapter adapter = new ViewTadAdapter(getSupportFragmentManager()); adapter.setFragments(fragments); adapter.setTitles(title_arr); shop_vp = (ViewPager) findViewById(R.id.shop_vp); shop_vp.setAdapter(adapter); shop_vp.setOffscreenPageLimit(0); setupTabLayout(shop_vp); } private void setupTabLayout(ViewPager viewPager) { final TabLayout shop_tab = (TabLayout) findViewById(R.id.shop_tab); shop_tab.setupWithViewPager(viewPager); } // private void setupOperateImgbtn() { // final ImageButton unlock_imgbtn = (ImageButton) findViewById(R.id.shop_imgbtn0); // // final ImageButton left_imgbtn = (ImageButton) findViewById(R.id.shop_imgbtn1); // final ImageButton right_imgbtn = (ImageButton) findViewById(R.id.shop_imgbtn2); // // ImageButton[] imageButtons = {unlock_imgbtn, left_imgbtn, right_imgbtn}; // // for (ImageButton imageButton : imageButtons) { // imageButton.setOnClickListener(this); // } // } @Override public void onMultiHandleResponse(String tag, String result) throws JSONException { if (isFstInit) { isFstInit = false; areaList = shopAction.handleResponse(result); setupViewPager(); } switch (tag) { case HttpTag.UNLOCK_UNLOCK: unlockAction.handleResponse(result); break; default: break; } } @Override public void onNullResponse() throws JSONException { if (isFstInit) { finish(); } } @Override public void onPermissionAccepted(int permission_code) { } @Override public void onPermissionRefused(int permission_code) { new LineToast(this).showToast(getString(R.string.auth_toast_permission_camera_authorized)); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { if (requestCode == UnlockAction.REQUEST_MAIN) { String smark_id = data.getStringExtra("scan_result"); unlockAction.unlock(smark_id); } } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); PermissionAction.handle(this, requestCode, grantResults); } @Override public void onClick(View v) { // switch (v.getId()) { // case R.id.shop_imgbtn0: // unlockAction.check(); // break; // // case R.id.shop_imgbtn1: // if (shop_vp.getCurrentItem() == 0) { // shop_vp.setCurrentItem(shop_vp.getChildCount()); // return; // } // shop_vp.setCurrentItem(shop_vp.getCurrentItem() - 1); // break; // // case R.id.shop_imgbtn2: // if ((shop_vp.getCurrentItem() + 1) == shop_vp.getChildCount()) { // shop_vp.setCurrentItem(0); // return; // } // shop_vp.setCurrentItem(shop_vp.getCurrentItem() + 1); // break; // // default: // break; // } } @Override public void onRefresh() { // if (!HttpAction.checkNet(this)) { // return; // } // // Handler handler = new Handler(); // handler.postDelayed(new Runnable() { // @Override // public void run() { // shop_vp.removeAllViews(); // setupViewPager(); // // shop_refresh.setRefreshing(false); // } // }, 1500); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.toolbar_shop_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onMenuItemClick(MenuItem item) { if (!HttpAction.checkNet(this)) { return false; } switch (item.getItemId()) { case R.id.menu_tb_shop_item0: onShopRefresh(); break; case R.id.menu_tb_shop_item1: if (PermissionAction.checkAutoRequest(Shop_Act.this, Manifest.permission.CAMERA, PermissionSet.CAMERA)) { unlockAction.check(); } break; default: break; } return false; } private void onShopRefresh() { shop_vp.removeAllViews(); setupViewPager(); } } <file_sep>/app/src/main/java/com/waletech/walesmart/login/ClickListener.java package com.waletech.walesmart.login; import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.text.method.HideReturnsTransformationMethod; import android.text.method.PasswordTransformationMethod; import android.view.View; import android.widget.EditText; import com.waletech.walesmart.R; import com.waletech.walesmart.base.BaseAction; import com.waletech.walesmart.base.BaseClickListener; import com.waletech.walesmart.publicClass.Methods; import com.waletech.walesmart.register.Register_Act; /** * Created by KeY on 2016/6/1. */ class ClickListener extends BaseClickListener { private Context context; private LoginAction loginAction; // 判断点击“小眼睛”以后,是显示或隐藏密码 private boolean psd_triggle = false; public ClickListener(Context context, BaseAction baseAction) { super(context, baseAction); this.context = context; loginAction = (LoginAction) baseAction; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.login_ll: // 收回软键盘 Methods.collapseIME(context); break; case R.id.login_tv0: // 显示密码 displayPsd(); break; case R.id.login_tv1: // 清除密码 clearPsd(); break; case R.id.login_tv2: // 找回密码 findPsd(); break; case R.id.login_btn0: // 跳转注册 onRegister(); break; case R.id.login_btn1: // 点击登录 onLogin(); break; default: break; } } private void displayPsd() { // 通过一个布尔值(psd_triggle)判断此时应该是显示密码还是隐藏密码 AppCompatActivity compatActivity = (AppCompatActivity) context; final EditText psd_et = (EditText) compatActivity.findViewById(R.id.login_et1); if (!psd_triggle) { psd_et.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); psd_triggle = true; } else { psd_et.setTransformationMethod(PasswordTransformationMethod.getInstance()); psd_triggle = false; } // 把光标定位在最后一位(因为如果没有这行代码,在显示/隐藏密码后,光标会蹦到首位) psd_et.setSelection(psd_et.length()); } private void clearPsd() { AppCompatActivity compatActivity = (AppCompatActivity) context; final EditText psd_et = (EditText) compatActivity.findViewById(R.id.login_et1); psd_et.setText(""); } private void findPsd() { // Intent findpsd_int = new Intent(context, FindPsd_Act.class); // startActivity(findpsd_int); } private void onRegister() { Intent reg_int = new Intent(context, Register_Act.class); context.startActivity(reg_int); } private void onLogin() { AppCompatActivity compatActivity = (AppCompatActivity) context; final EditText usn_et = (EditText) compatActivity.findViewById(R.id.login_et0); final EditText psd_et = (EditText) compatActivity.findViewById(R.id.login_et1); String usn_str = usn_et.getText().toString().trim(); String psd_str = psd_et.getText().toString().trim(); loginAction.login(usn_str, psd_str); } } <file_sep>/app/src/main/java/com/waletech/walesmart/user/shopInfo/order/OrderRycAdapter.java package com.waletech.walesmart.user.shopInfo.order; import android.content.Context; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.waletech.walesmart.R; import com.waletech.walesmart.publicClass.Methods; import com.waletech.walesmart.publicObject.ObjectOrder; import com.waletech.walesmart.publicSet.IntentSet; import java.util.ArrayList; /** * Created by KeY on 2016/7/26. */ public class OrderRycAdapter extends RecyclerView.Adapter<OrderRycAdapter.ViewHolder> implements View.OnClickListener { private Context context; private ArrayList<ObjectOrder> orderList; public OrderRycAdapter(ArrayList<ObjectOrder> orderList) { this.orderList = orderList; } public void setOrderList(ArrayList<ObjectOrder> orderList) { this.orderList = orderList; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = View.inflate(parent.getContext(), R.layout.recycler_order_item, null); context = parent.getContext(); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { ObjectOrder order = orderList.get(position); holder.date_tv.setText(order.getDateTime()); String order_num_str = context.getString(R.string.order_item_order_number) + order.getOrderNum(); holder.order_num_tv.setText(order_num_str); holder.order_num_tv.setTag(position); holder.order_num_tv.setOnClickListener(this); String total_price_str = context.getString(R.string.order_item_whole_price) + order.getTotalPrice(); holder.total_price_tv.setText(total_price_str); } @Override public int getItemCount() { return orderList == null ? 0 : orderList.size(); } @Override public void onClick(View v) { Context context = v.getContext(); int position = Methods.cast(v.getTag()); ObjectOrder order = orderList.get(position); Intent item_int = new Intent(context, Order_Item_Act.class); item_int.putExtra(IntentSet.KEY_ORDER_NUM, order.getOrderNum()); context.startActivity(item_int); } class ViewHolder extends RecyclerView.ViewHolder { TextView date_tv; TextView order_num_tv; TextView total_price_tv; public ViewHolder(View itemView) { super(itemView); date_tv = (TextView) itemView.findViewById(R.id.rv_date_tv); order_num_tv = (TextView) itemView.findViewById(R.id.rv_order_num_tv); total_price_tv = (TextView) itemView.findViewById(R.id.rv_total_price_tv); } } } <file_sep>/app/src/main/java/com/waletech/walesmart/shop/area/AreaRycAdapter.java package com.waletech.walesmart.shop.area; import android.content.Context; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.waletech.walesmart.R; import com.waletech.walesmart.http.HttpAction; import com.waletech.walesmart.http.HttpSet; import com.waletech.walesmart.product.Product_Act; import com.waletech.walesmart.publicClass.BitmapCache; import com.waletech.walesmart.publicClass.Methods; import com.waletech.walesmart.publicObject.ObjectShoe; import com.waletech.walesmart.publicSet.IntentSet; import java.util.ArrayList; /** * Created by KeY on 2016/7/8. */ public class AreaRycAdapter extends RecyclerView.Adapter<AreaRycAdapter.ViewHolder> implements View.OnClickListener, View.OnLongClickListener { private ArrayList<ObjectShoe> shoeList; // private String[] native_number = { // "11", "12", "13", // "21", "22", "23", // "31", "32", "33"}; private String[] native_number; private BitmapCache cache; public AreaRycAdapter(ArrayList<ObjectShoe> shoeList, int row, int column) { this.shoeList = shoeList; cache = new BitmapCache(); native_number = onCreateNativeMatrix(row, column); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = View.inflate(parent.getContext(), R.layout.recycler_shoe_area_item, null); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { boolean isCheck = false; for (int i = 0; i < shoeList.size(); i++) { Log.i("Result", "smark is : " + shoeList.get(i).getSmarkNum()); } Context context = holder.item_ll.getContext(); for (int i = 0; i < shoeList.size(); i++) { ObjectShoe shoe = shoeList.get(i); String smark_num_str = shoe.getSmarkNum(); String remote_number = smark_num_str.substring(smark_num_str.length() - 2, smark_num_str.length()); if (native_number[position].equals(remote_number)) { Log.i("Result", "pos is : " + position); Log.i("Result", "remote is : " + remote_number); isCheck = true; holder.smark_num_tv.setText(shoe.getSmarkNum()); holder.status_tv.setText(shoe.getStatus()); switch (shoe.getStatus()) { case "暂无鞋": case "No shoes": holder.status_tv.setTextColor(context.getResources().getColor(android.R.color.darker_gray)); holder.shoe_img.setBackgroundColor(context.getResources().getColor(android.R.color.darker_gray)); break; case "在柜": case "In cabinet": holder.status_tv.setTextColor(context.getResources().getColor(R.color.colorSpecial)); break; case "试鞋中": case "Enjoying": holder.status_tv.setTextColor(context.getResources().getColor(android.R.color.holo_red_light)); break; default: break; } if (shoe.getEpcCode() == null) { break; } holder.item_ll.setTag(i); holder.item_ll.setOnClickListener(this); holder.item_ll.setOnLongClickListener(this); String params_str = shoe.getBrand() + "\t" + shoe.getSize(); holder.params_tv.setText(params_str); if (shoe.getImagePath() != null && (!shoe.getImagePath().equals(""))) { holder.shoe_img.setTag(HttpSet.BASE_URL + shoe.getImagePath()); loadImage(holder, i); } break; } } if (isCheck) { return; } String smark_num_str = native_number[position]; holder.smark_num_tv.setText(smark_num_str); String status_str = context.getString(R.string.area_shoe_status_no_shoes_tv); holder.status_tv.setText(status_str); } @Override public int getItemCount() { return native_number.length; } @Override public boolean onLongClick(View v) { return false; } class ViewHolder extends RecyclerView.ViewHolder { LinearLayout item_ll; TextView smark_num_tv; TextView status_tv; ImageView shoe_img; TextView params_tv; public ViewHolder(View itemView) { super(itemView); item_ll = (LinearLayout) itemView.findViewById(R.id.rv_ll); smark_num_tv = (TextView) itemView.findViewById(R.id.rv_smark_num_tv); status_tv = (TextView) itemView.findViewById(R.id.rv_status_tv); shoe_img = (ImageView) itemView.findViewById(R.id.rv_img); params_tv = (TextView) itemView.findViewById(R.id.rv_params_tv); } } private void loadImage(ViewHolder holder, int real_position) { // 先判断缓存中是否缓存了这个item的imageview所在的url的图片 String img_url = holder.shoe_img.getTag().toString(); // 如果没有 if (cache.getBitmap(img_url) == null) { // 请求下载图片 Context context = holder.shoe_img.getContext(); holder.shoe_img.setBackgroundColor(context.getResources().getColor(android.R.color.white)); Methods.downloadImage(holder.shoe_img, HttpSet.BASE_URL + shoeList.get(real_position).getImagePath(), cache); } else { holder.shoe_img.setImageBitmap(cache.getBitmap(img_url)); } } private String[] onCreateNativeMatrix(int row, int column) { ArrayList<String> nativeList = new ArrayList<>(); for (int i = 1; i <= row; i++) { for (int k = 1; k <= column; k++) { String native_number = i + "" + k; nativeList.add(native_number); } } String[] native_number = nativeList.toArray(new String[nativeList.size()]); return native_number; } @Override public void onClick(View v) { Context context = v.getContext(); if (!HttpAction.checkNet(context)) { return; } int position = Methods.cast(v.getTag()); ObjectShoe shoe = shoeList.get(position); String epc_code_str = shoe.getEpcCode(); Log.i("Result", "epc is : " + epc_code_str); Intent product_int = new Intent(context, Product_Act.class); product_int.putExtra(IntentSet.KEY_EPC_CODE, epc_code_str); product_int.putExtra(IntentSet.KEY_IS_FROM_SHOP, true); context.startActivity(product_int); } } <file_sep>/app/src/main/java/com/waletech/walesmart/main/Splash_Frag.java package com.waletech.walesmart.main; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.waletech.walesmart.R; import com.waletech.walesmart.base.Base_Frag; import com.waletech.walesmart.http.HttpSet; import com.waletech.walesmart.sharedinfo.SharedAction; import org.json.JSONException; /** * Created by KeY on 2016/9/19. */ public class Splash_Frag extends Base_Frag { @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_main_splash_page_layout, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // if (new SharedAction(getContext()).getUsername().equals("13929572369")) { // HttpSet.setBaseIP(HttpSet.DEDICATED_IP, getContext()); // } } @Override public void onMultiHandleResponse(String tag, String result) throws JSONException { } @Override public void onNullResponse() throws JSONException { } @Override public void setCustomTag(String tag) { } @Override public String getCustomTag() { return null; } } <file_sep>/app/src/main/java/com/waletech/walesmart/publicAction/UnlockAction.java package com.waletech.walesmart.publicAction; import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.util.Log; import com.igexin.sdk.PushManager; import com.waletech.walesmart.R; import com.waletech.walesmart.base.BaseAction; import com.waletech.walesmart.http.HttpAction; import com.waletech.walesmart.http.HttpHandler; import com.waletech.walesmart.http.HttpResult; import com.waletech.walesmart.http.HttpSet; import com.waletech.walesmart.http.HttpTag; import com.zbar.lib.CaptureActivity; import org.json.JSONException; import org.json.JSONObject; /** * Created by KeY on 2016/6/27. */ public class UnlockAction extends BaseAction { public final static int REQUEST_MAIN = 0; public UnlockAction(Context context) { super(context); } public void check() { if (!checkNet()) { return; } if (!checkLoginStatus()) { return; } String client_id = PushManager.getInstance().getClientid(context); Log.i("Result", "client id is ; " + client_id); Intent scan_int = new Intent(context, CaptureActivity.class); AppCompatActivity activity = (AppCompatActivity) context; activity.startActivityForResult(scan_int, REQUEST_MAIN); } public void setContext(Context context) { this.context = context; } public void unlock(String smark_id) { if (!checkNet()) { return; } String client_id = PushManager.getInstance().getClientid(context); String[] key = {HttpSet.KEY_SMARK_ID, HttpSet.KEY_USERNAME, HttpSet.KEY_NICKNAME, HttpSet.KEY_CLIENT_ID}; String[] value = {smark_id, sharedAction.getUsername(), sharedAction.getNickname(), client_id}; // for (int i = 0; i < key.length; i++) { // Log.i("Result","key is : " + i + "-set is : " + key[i]); // Log.i("Result","value is : " + i + "-set is : " + value[i]); // } HttpAction action = new HttpAction(context); action.setUrl(HttpSet.URL_UNLOCK); action.setTag(HttpTag.UNLOCK_UNLOCK); action.setHandler(new HttpHandler(context)); action.setDialog(context.getString(R.string.unlock_progress_title), context.getString(R.string.unlock_progress_msg)); action.setMap(key, value); action.interaction(); } public void handleResponse(String result) throws JSONException { JSONObject obj = new JSONObject(result); toast.showToast(obj.getString(HttpResult.RESULT)); } } <file_sep>/app/src/main/java/com/waletech/walesmart/publicClass/ScreenSize.java package com.waletech.walesmart.publicClass; import android.content.Context; import android.graphics.Point; import android.os.Build; import android.support.v7.app.AppCompatActivity; import android.util.DisplayMetrics; import android.view.Display; /** * Created by KeY on 2016/3/25. */ public class ScreenSize { private Context context; private AppCompatActivity activity; private int width; private int height; private Point size; public ScreenSize(Context context) { this.context = context; activity = (AppCompatActivity) context; getScreenSize(); } public int getWidth() { return width; } public int getHeight() { return height; } private void getScreenSize() { Display display = activity.getWindowManager().getDefaultDisplay(); size = new Point(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { display.getRealSize(size); } else { display.getSize(size); } width = size.x; height = size.y; } public int getDPI() { DisplayMetrics metrics = activity.getResources().getDisplayMetrics(); return metrics.densityDpi; } } <file_sep>/app/src/main/java/com/waletech/walesmart/searchResult/ResultAction.java package com.waletech.walesmart.searchResult; import android.content.Context; import android.util.Log; import com.waletech.walesmart.publicObject.ObjectShoe; import com.waletech.walesmart.R; import com.waletech.walesmart.base.BaseAction; import com.waletech.walesmart.http.HttpAction; import com.waletech.walesmart.http.HttpHandler; import com.waletech.walesmart.http.HttpSet; import com.waletech.walesmart.http.HttpTag; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; /** * Created by KeY on 2016/6/29. */ public class ResultAction extends BaseAction { public ResultAction(Context context) { super(context); } private String save_search_word = "All"; private String save_brand = "All"; private String save_gender = "All"; private String save_province = "All"; private String save_city = "All"; private String save_county = "All"; public void searchFussy(String search_word) { if (!checkNet()) { return; } action = BaseAction.ACTION_DEFAULT_REFRESH; sharedAction.clearLastIdInfo(); save_search_word = search_word; interaction(); } public void searchFilter(String search_word, String brand, String gender, String province, String city, String county) { if (!checkNet()) { return; } Log.i("Result", "net is : " + HttpSet.BASE_URL); action = BaseAction.ACTION_FILTER; sharedAction.clearLastIdInfo(); if (!search_word.equals("")) { save_search_word = search_word; } if (!brand.equals("")) { save_brand = brand; } if (!gender.equals("")) { save_gender = gender; } if (!province.equals("")) { save_province = province; } if (!city.equals("")) { save_city = city; } if (!county.equals("")) { save_county = county; } interaction(); } public void resultRefresh() { if (!checkNet()) { return; } sharedAction.clearLastIdInfo(); action = BaseAction.ACTION_DEFAULT_REFRESH; searchFilter("", "", "", "", "", ""); } public void resultLoad() { if (!checkNet()) { return; } action = BaseAction.ACTION_LOAD_MORE; interaction(); } private void interaction() { String[] key = {HttpSet.KEY_SEARCH_WORD, HttpSet.KEY_BRAND, HttpSet.KEY_GENDER, HttpSet.KEY_PROVINCE, HttpSet.KEY_CITY, HttpSet.KEY_COUNTY, HttpSet.KEY_LAST_ID}; String[] value = {save_search_word, save_brand, save_gender, save_province, save_city, save_county, "" + sharedAction.getLastId()}; Log.i("Result", "brand is : " + save_brand); HttpAction action = new HttpAction(context); action.setUrl(HttpSet.URL_SEARCH_FILTER); action.setDialog(context.getString(R.string.search_progress_title), context.getString(R.string.search_progress_msg)); action.setHandler(new HttpHandler(context)); action.setTag(HttpTag.RESULT_SEARCH_FILTER); action.setMap(key, value); action.interaction(); } public ArrayList<ObjectShoe> handleResponse(String result) throws JSONException { Log.i("Result", "result is : " + result); ArrayList<ObjectShoe> shoeList = new ArrayList<>(); JSONArray array = new JSONArray(result); if (array.length() == 0) { toast.showToast(context.getString(R.string.base_toast_no_more_item)); return shoeList; } for (int i = 0; i < array.length(); i++) { JSONObject obj = array.getJSONObject(i); ObjectShoe shoe = new ObjectShoe(); for (int k = 0; k < obj.length(); k++) { shoe.value_set[k] = obj.getString(ObjectShoe.key_set[k]); } shoeList.add(shoe); } String last_id = shoeList.get(shoeList.size() - 1).getLastId(); Log.i("Result", "last id is : " + last_id); sharedAction.setLastId(Integer.parseInt(last_id)); return shoeList; } } <file_sep>/app/src/main/java/com/waletech/walesmart/publicAction/GetBrandAction.java package com.waletech.walesmart.publicAction; import android.content.Context; import android.os.Looper; import android.util.Log; import com.waletech.walesmart.base.BaseAction; import com.waletech.walesmart.base.Base_Serv; import com.waletech.walesmart.datainfo.BrandSet; import com.waletech.walesmart.datainfo.DataBaseAction; import com.waletech.walesmart.http.HttpAction; import com.waletech.walesmart.http.HttpHandler; import com.waletech.walesmart.http.HttpSet; import com.waletech.walesmart.http.HttpTag; import org.json.JSONArray; import org.json.JSONException; /** * Created by KeY on 2016/6/6. */ public class GetBrandAction extends BaseAction { private Base_Serv service; public GetBrandAction(Context context) { super(context); } public GetBrandAction(Context context, Base_Serv service) { super(context); this.service = service; } public void getBrand() { String[] key = {""}; String[] value = {""}; HttpAction action = new HttpAction(context); action.setUrl(HttpSet.URL_GET_BRAND); action.setMap(key, value); action.setTag(HttpTag.GET_BRAND); if (service != null) { action.setHandler(new HttpHandler(context, service)); } else { action.setHandler(new HttpHandler(context)); } action.interaction(); } public void handleResponse(String result) throws JSONException { Log.i("Result", "get brand result is : " + result); JSONArray array = new JSONArray(result); DataBaseAction action = DataBaseAction.onCreate(context); action.delete(BrandSet.TABLE_NAME); action.insert(BrandSet.TABLE_NAME, BrandSet.ALL, array); } } <file_sep>/app/src/main/java/com/waletech/walesmart/pattern/ClickListener.java package com.waletech.walesmart.pattern; import android.content.Context; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.waletech.walesmart.R; import com.waletech.walesmart.base.BaseAction; import com.waletech.walesmart.base.BaseClickListener; import com.waletech.walesmart.publicClass.Methods; import com.waletech.walesmart.publicObject.ObjectShoe; /** * Created by KeY on 2016/7/13. */ class ClickListener extends BaseClickListener { private PatternAction patternAction; public ClickListener(Context context, BaseAction baseAction) { super(context, baseAction); patternAction = (PatternAction) baseAction; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.pattern_imgbtn: case R.id.pattern_tv0: Pattern_Frag pattern_frag = Methods.cast(v.getTag()); FragmentManager fragmentManager = ((AppCompatActivity) context).getSupportFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.remove(pattern_frag); transaction.commit(); break; case R.id.pattern_btn0: String sku_code_str = Methods.cast(v.getTag()); patternAction.OnAddInCart(sku_code_str); break; default: break; } } } <file_sep>/app/src/main/java/com/waletech/walesmart/netDown/NetDown_Frag.java package com.waletech.walesmart.netDown; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.widget.ContentLoadingProgressBar; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.TextView; import com.waletech.walesmart.R; import com.waletech.walesmart.base.Base_Frag; import com.waletech.walesmart.http.HttpAction; import com.waletech.walesmart.main.experience.Experience_Frag; import com.waletech.walesmart.publicSet.BundleSet; import org.json.JSONException; /** * Created by KeY on 2016/7/14. */ public class NetDown_Frag extends Base_Frag implements View.OnClickListener { private ImageButton net_down_imgbtn; private TextView net_down_tv; private ContentLoadingProgressBar net_down_pb; private NetDownAction netDownAction; private int contentLayoutResId; private Base_Frag fragment; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_public_net_down_layout, container, false); } @Override public void setArguments(Bundle bundle) { super.setArguments(bundle); contentLayoutResId = bundle.getInt(BundleSet.KEY_CONTENT_LAYOUT_RES_ID); // fragment = (Base_Frag) bundle.getSerializable(BundleSet.KEY_BASE_FRAGMENT); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); varInit(view); setupNetDownImgbtn(view); } private void varInit(View view) { netDownAction = new NetDownAction(getContext(), this); net_down_tv = (TextView) view.findViewById(R.id.net_down_tv); net_down_pb = (ContentLoadingProgressBar) view.findViewById(R.id.net_down_pb); } private void setupNetDownImgbtn(View view) { net_down_imgbtn = (ImageButton) view.findViewById(R.id.net_down_imgbtn); net_down_imgbtn.setOnClickListener(this); } @Override public void onMultiHandleResponse(String tag, String result) throws JSONException { boolean isPing = netDownAction.handleResponse(result); if (isPing) { FragmentManager fragmentManager = ((AppCompatActivity) getContext()).getSupportFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.remove(NetDown_Frag.this); // transaction.add(R.id.main_vp, fragment); transaction.add(contentLayoutResId, new Experience_Frag()); transaction.commit(); } else { backToInit(); } } @Override public void onNullResponse() throws JSONException { backToInit(); } @Override public void setCustomTag(String tag) { } @Override public String getCustomTag() { return null; } @Override public void onClick(View v) { final Context context = v.getContext(); v.setVisibility(View.INVISIBLE); net_down_tv.setVisibility(View.INVISIBLE); net_down_pb.setVisibility(View.VISIBLE); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { if (HttpAction.checkNet(context)) { netDownAction.ping(); } else { backToInit(); } } }, 2 * 1000); } private void backToInit() { net_down_imgbtn.setVisibility(View.VISIBLE); net_down_tv.setVisibility(View.VISIBLE); net_down_pb.setVisibility(View.GONE); } } <file_sep>/app/src/main/java/com/waletech/walesmart/publicSet/IntentSet.java package com.waletech.walesmart.publicSet; /** * Created by KeY on 2016/6/23. */ public final class IntentSet { public final static String KEY_USERNAME = "key_username"; public final static String KEY_EPC_CODE = "key_epc_code"; public final static String KEY_APP_FST_LAUNCH = "key_app_fst_launch"; public final static String KEY_SEARCH_WORD = "key_search_word"; public final static String KEY_IS_FROM_SHOP = "key_is_from_shop"; public final static String KEY_SHOP_NAME = "key_shop_name"; public final static String KEY_SHOP_LOCATION = "key_shop_location"; public final static String KEY_ORDER_NUM = "key_order_num"; } <file_sep>/app/src/main/java/com/waletech/walesmart/user/shopInfo/cart/Cart_Act.java package com.waletech.walesmart.user.shopInfo.cart; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AlertDialog; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.CompoundButton; import android.widget.TextView; import com.waletech.walesmart.R; import com.waletech.walesmart.base.BaseAction; import com.waletech.walesmart.base.Base_Act; import com.waletech.walesmart.http.HttpAction; import com.waletech.walesmart.http.HttpTag; import com.waletech.walesmart.publicClass.LineToast; import com.waletech.walesmart.publicObject.ObjectShoe; import com.waletech.walesmart.publicSet.MapSet; import org.json.JSONException; import java.util.ArrayList; import java.util.HashMap; public class Cart_Act extends Base_Act implements SwipeRefreshLayout.OnRefreshListener, CompoundButton.OnCheckedChangeListener, Toolbar.OnMenuItemClickListener { private SwipeRefreshLayout cart_refresh; private RecyclerView cart_rv; private CartAction cartAction; private ClickListener clickListener; private ArrayList<ObjectShoe> shoeList; private LineToast toast; private boolean isFstInit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user_shop_info_cart_layout); if (!HttpAction.checkNet(this)) { finish(); } varInit(); setupToolbar(); setupSwipeRefresh(); } private void varInit() { cartAction = new CartAction(this); cartAction.getCartList(); clickListener = new ClickListener(this, cartAction); shoeList = new ArrayList<>(); toast = new LineToast(this); isFstInit = true; } @Override protected void setupToolbar() { setTbTitle(getString(R.string.cart_toolbar_title)); setTbNavigation(); toolbar.showOverflowMenu(); toolbar.setOnMenuItemClickListener(this); } private void setupSwipeRefresh() { cart_refresh = (SwipeRefreshLayout) findViewById(R.id.cart_sr); cart_refresh.setColorSchemeResources(R.color.colorMain, R.color.colorSpecial, R.color.colorSpecialConverse); cart_refresh.setOnRefreshListener(this); } private void setupRecyclerView() { CartRycAdapter adapter = new CartRycAdapter(shoeList, this); adapter.setCartAction(cartAction); cart_rv = (RecyclerView) findViewById(R.id.cart_rv); cart_rv.setLayoutManager(new LinearLayoutManager(this)); cart_rv.setAdapter(adapter); cart_rv.addOnScrollListener(new LoadScrollListener()); } private void setupBuyBar() { // final CheckBox whole_cb = (CheckBox) findViewById(R.id.rv_whole_cb); // whole_cb.setChecked(false); // whole_cb.setOnCheckedChangeListener(this); CartRycAdapter adapter = (CartRycAdapter) cart_rv.getAdapter(); ArrayList<String> checkList = adapter.getCheckList(); HashMap<String, Object> map = new HashMap<>(); map.put(MapSet.KEY_SHOE_LIST, shoeList); map.put(MapSet.KEY_CHECK_LIST, checkList); final TextView make_order_tv = (TextView) findViewById(R.id.rv_make_order_tv); make_order_tv.setTag(map); make_order_tv.setOnClickListener(clickListener); } @Override public void onMultiHandleResponse(String tag, String result) throws JSONException { onStopRefresh(); if (isFstInit) { shoeList = cartAction.handleListResponse(result); setupRecyclerView(); setupBuyBar(); isFstInit = false; return; } CartRycAdapter adapter = (CartRycAdapter) cart_rv.getAdapter(); switch (tag) { // case HttpTag.CART_GET_CART_LIST: switch (cartAction.getAction()) { case BaseAction.ACTION_DEFAULT_REFRESH: shoeList = cartAction.handleListResponse(result); break; case BaseAction.ACTION_LOAD_MORE: ArrayList<ObjectShoe> tempList = cartAction.handleListResponse(result); for (int i = 0; i < tempList.size(); i++) { shoeList.add(tempList.get(i)); } break; default: break; } break; // case HttpTag.CART_UPDATE_CART: cartAction.handleResponse(result); cartAction.getCartList(); break; case HttpTag.CART_DELETE_CART: case HttpTag.CART_CREATE_ORDER: adapter.clearCheckList(); // final CheckBox whole_cb = (CheckBox) findViewById(R.id.rv_whole_cb); // whole_cb.setChecked(false); cartAction.handleResponse(result); cartAction.getCartList(); return; default: break; } adapter.setShoeList(shoeList); adapter.notifyDataSetChanged(); } @Override public void onNullResponse() throws JSONException { onStopRefresh(); if (isFstInit) { finish(); } } @Override public void onPermissionAccepted(int permission_code) { } @Override public void onPermissionRefused(int permission_code) { } private void onDeleteItem(CartRycAdapter adapter) { ArrayList<String> checkList = adapter.getCheckList(); if (checkList == null || checkList.size() == 0) { toast.showToast(getString(R.string.base_toast_no_item_been_selected)); } else { StringBuilder sku_code_builder = new StringBuilder(""); for (int i = 0; i < checkList.size(); i++) { ObjectShoe shoe = shoeList.get(i); if (i == (checkList.size() - 1)) { sku_code_builder.append(shoe.getRemark()); } else { sku_code_builder.append(shoe.getRemark()).append("-"); } } cartAction.deleteCart(sku_code_builder.toString()); } } public void onModifyPrice(CartRycAdapter adapter) { int whole_price = 0; ArrayList<String> checkList = adapter.getCheckList(); for (int i = 0; i < checkList.size(); i++) { int position = Integer.parseInt(checkList.get(i)); ObjectShoe shoe = shoeList.get(position); int price = Integer.parseInt(shoe.getPrice()) * Integer.parseInt(shoe.getCount()); whole_price = whole_price + price; } final TextView whole_price_tv = (TextView) findViewById(R.id.rv_whole_price_tv); String whole_price_str = getString(R.string.cart_whole_price_tv) + whole_price + " " + getString(R.string.cart_rmb_tv); whole_price_tv.setText(whole_price_str); } @Override public void onRefresh() { cartAction.getCartList(); } private void onStopRefresh() { if (cart_refresh != null && cart_refresh.isRefreshing()) { cart_refresh.setRefreshing(false); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.toolbar_cart_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onMenuItemClick(MenuItem item) { final CartRycAdapter adapter = (CartRycAdapter) cart_rv.getAdapter(); switch (item.getItemId()) { case R.id.menu_tb_cart_item0: new AlertDialog.Builder(this) .setTitle(getString(R.string.base_dialog_delete_title)) .setMessage(getString(R.string.base_dialog_delete_message)) .setPositiveButton(getString(R.string.base_dialog_btn_yes), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { onDeleteItem(adapter); } }) .setNegativeButton(getString(R.string.base_dialog_btn_no), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .show(); break; case R.id.menu_tb_cart_item1: if (item.getTitle().equals(getString(R.string.cart_menu_item_finish))) { item.setTitle(getString(R.string.cart_menu_item_edit)); adapter.setIsEditMode(false); cartAction.getCartList(); } else { item.setTitle(getString(R.string.cart_menu_item_finish)); adapter.setIsEditMode(true); } for (int i = 0; i < adapter.getItemCount(); i++) { adapter.notifyItemChanged(i); } break; default: break; } return false; } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // toast.showToast(ToastSet.NO_OPEN_FUNCTION); // CartRycAdapter adapter = (CartRycAdapter) cart_rv.getAdapter(); // // final TextView whole_price_tv = (TextView) findViewById(R.id.rv_whole_price_tv); // // adapter.clearCheckList(); // adapter.setIsWholeClick(true); // // if (isChecked) { // adapter.setWholeCheck(true); // // int whole_price = 0; // for (int i = 0; i < shoeList.size(); i++) { // ObjectShoe shoe = shoeList.get(i); // int price = Integer.parseInt(shoe.getPrice()) * Integer.parseInt(shoe.getCount()); // whole_price = whole_price + price; // } // // String price_str = "合计金额:" + whole_price + "元"; // whole_price_tv.setText(price_str); // } else { // adapter.setWholeCheck(false); // String price_str = "合计金额:0.00"; // whole_price_tv.setText(price_str); // } // // for (int i = 0; i < adapter.getItemCount(); i++) { //// adapter.setIsWholeClick(true); // adapter.notifyItemChanged(i); // } // //// adapter.clearCheckList(); // if (isChecked) { // adapter.fillCheckList(); // } // // Log.i("Result", "checkList clear size is : " + adapter.getCheckList().size()); } private class LoadScrollListener extends RecyclerView.OnScrollListener { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); CartRycAdapter adapter = (CartRycAdapter) recyclerView.getAdapter(); LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager(); if (newState == RecyclerView.SCROLL_STATE_IDLE) { int total_item = manager.getItemCount(); if (total_item == 0) { return; } int last_item = manager.findLastCompletelyVisibleItemPosition(); // 如果总共有8个item,即total = 8,但是因为last是从0开始的,最后一个也就是到7,所以last需要多加1 last_item++; // 判断child item的个数有没有超出屏幕,如果有,才允许上拉加载 // 这里只要判断child item的总高度有没有超过manager(即recyclerview)的高度就可以了 // 当然在 recyclerview里面判断是否高于屏幕也可以! int parent_height = manager.getHeight(); int child_height = manager.getChildAt(0).getHeight(); int total_height = total_item * child_height; if (total_height < parent_height) { return; } // 否则就进行上拉加载更多 if (last_item == total_item) { if (adapter.getIsShowLoad()) { return; } adapter.setIsShowLoad(true); adapter.notifyItemChanged(manager.findLastCompletelyVisibleItemPosition()); } } } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); } } } <file_sep>/app/build.gradle apply plugin: 'com.android.application' android { compileSdkVersion 25 buildToolsVersion "25.0.2" defaultConfig { applicationId "com.waletech.walesmart" minSdkVersion 15 targetSdkVersion 25 versionCode 29 versionName "2.9.2" manifestPlaceholders = [ GETUI_APP_ID : "sZTYPEDDN07Y5vWm3A6SK6", GETUI_APP_KEY : "<KEY>", GETUI_APP_SECRET: "<KEY>", PACKAGE_NAME : applicationId ] } sourceSets { main { jniLibs.srcDirs = ['libs'] } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile files('libs/volley-1.0.19.jar') compile project(':scan') compile files('libs/BaiduLBS_Android.jar') compile files('libs/httpmime-4.1.2.jar') compile files('libs/GetuiSDK2.9.0.0.jar') compile 'com.android.support:appcompat-v7:25.3.1' compile 'com.android.support:support-v4:25.3.1' compile 'com.android.support:design:25.3.1' compile 'com.android.support:cardview-v7:25.3.1' testCompile 'junit:junit:4.12' } <file_sep>/app/src/main/java/com/waletech/walesmart/map/MapHelper.java package com.waletech.walesmart.map; import android.content.Context; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; import com.baidu.mapapi.map.BaiduMap; import com.baidu.mapapi.map.MapStatusUpdate; import com.baidu.mapapi.map.MapStatusUpdateFactory; import com.baidu.mapapi.map.MapView; import com.baidu.mapapi.map.MyLocationData; import com.baidu.mapapi.model.LatLng; import com.waletech.walesmart.http.HttpSet; import com.waletech.walesmart.main.MainActivity; import com.waletech.walesmart.publicClass.Methods; /** * Created by KeY on 2016/7/11. */ public abstract class MapHelper { private BaiduMap map; private Context context; public MapHelper(Context context, MapView mapView) { this.context = context; setupMapView(mapView); } private void setupMapView(MapView mapView) { map = mapView.getMap(); map.setMapType(BaiduMap.MAP_TYPE_NORMAL); map.setMyLocationEnabled(true); setupLocation(); } private void setupLocation() { LocationClientOption option = initLocOption(); LocationClient client = new LocationClient(context.getApplicationContext()); client.setLocOption(option); client.registerLocationListener(locationListener); client.requestLocation(); client.start(); } private LocationClientOption initLocOption() { LocationClientOption option = new LocationClientOption(); option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//可选,默认高精度,设置定位模式,高精度,低功耗,仅设备 option.setCoorType("bd09ll");//可选,默认gcj02,设置返回的定位结果坐标系 option.setScanSpan(0);//可选,默认0,即仅定位一次,设置发起定位请求的间隔需要大于等于1000ms才是有效的 option.setIsNeedAddress(true);//可选,设置是否需要地址信息,默认不需要 option.setOpenGps(true);//可选,默认false,设置是否使用gps option.setLocationNotify(true);//可选,默认false,设置是否当gps有效时按照1S1次频率输出GPS结果 option.setIsNeedLocationDescribe(true);//可选,默认false,设置是否需要位置语义化结果,可以在BDLocation.getLocationDescribe里得到,结果类似于“在北京天安门附近” option.setIsNeedLocationPoiList(true);//可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到 option.setIgnoreKillProcess(false);//可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认不杀死 return option; } private BDLocationListener locationListener = new BDLocationListener() { @Override public void onReceiveLocation(BDLocation location) { MyLocationData data = new MyLocationData.Builder() .accuracy(location.getRadius()) .direction(100) .latitude(location.getLatitude()) .longitude(location.getLongitude()) .build(); map.setMyLocationData(data); LatLng lng = new LatLng(location.getLatitude(), location.getLongitude()); MapStatusUpdate update = MapStatusUpdateFactory.newLatLngZoom(lng, 19); map.animateMapStatus(update); if (!location.getProvince().equals("")) { String province = location.getProvince(); String city = location.getCity(); String district = location.getDistrict(); if (district.equals("白云区")) { HttpSet.setBaseIP(HttpSet.DEDICATED_IP, context); ((MainActivity) context).setupNetText(); } switch (Methods.getLanguage(context)) { case "zh": onLoadLocationDone(province, city, district); break; case "en": String[] loc = LocTranslate(province, city, district); onLoadLocationDone(loc[0], loc[1], loc[2]); break; default: onLoadLocationDone(province, city, district); break; } // if (new SharedAction(context).getAppLanguage().equals("Chinese")) { // Log.i("Result", "map chinese"); // onLoadLocationDone(province, city, district); // } else { // Log.i("Result", "map english"); // String[] loc = LocTranslate(province, city, district); // // for (int i = 0; i < loc.length; i++) { // Log.i("Result", "loc is : " + loc[i]); // } // onLoadLocationDone(loc[0], loc[1], loc[2]); // } } } }; private String[] LocTranslate(String province, String city, String district) { String[] loc = new String[3]; switch (province) { case "广东省": loc[0] = "GuangDong"; break; case "福建省": loc[0] = "FuJian"; break; case "香港特别行政区": loc[0] = "HongKong"; break; case "云南省": loc[0] = "YunNan"; break; default: loc[0] = ""; break; } switch (city) { case "广州市": loc[1] = "GuangZhou"; break; case "深圳市": loc[1] = "ShenZhen"; break; case "厦门市": loc[1] = "XiaMen"; break; case "香港特别行政区": loc[1] = "HongKong"; break; case "昆明市": loc[1] = "KunMing"; break; default: loc[1] = ""; break; } switch (district) { case "白云区": loc[2] = "BaiYun"; break; case "越秀区": loc[2] = "YueXiu"; break; case "南山区": loc[2] = "NanShan"; break; case "福田区": loc[2] = "FuTian"; break; case "思明区": loc[2] = "SiMing"; break; case "荃湾区": loc[2] = "TSUEN WAN"; break; case "呈贡区": loc[2] = "ChengGong"; break; default: loc[2] = ""; break; } return loc; } public abstract void onLoadLocationDone(String province, String city, String county); } <file_sep>/app/src/main/java/com/waletech/walesmart/BaseShoeRycAdapter.java package com.waletech.walesmart; import android.content.Context; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.waletech.walesmart.base.BaseAction; import com.waletech.walesmart.http.HttpAction; import com.waletech.walesmart.http.HttpSet; import com.waletech.walesmart.product.Product_Act; import com.waletech.walesmart.publicClass.BitmapCache; import com.waletech.walesmart.publicClass.Methods; import com.waletech.walesmart.publicObject.ObjectShoe; import com.waletech.walesmart.publicSet.IntentSet; import java.util.ArrayList; /** * Created by KeY on 2016/6/29. */ public abstract class BaseShoeRycAdapter extends RecyclerView.Adapter<BaseShoeRycAdapter.ViewHolder> implements View.OnClickListener { public final static String GENDER_MALE = "男鞋"; public final static String GENDER_FEMALE = "女鞋"; public final static String GENDER_GENERAL = "通用"; protected ArrayList<ObjectShoe> shoeList; private BitmapCache cache; protected Context context; protected boolean isShowLoad; protected BaseAction baseAction; public BaseShoeRycAdapter(ArrayList<ObjectShoe> shoeList, Context context) { this.shoeList = shoeList; this.context = context; cache = new BitmapCache(); } public void setShoeList(ArrayList<ObjectShoe> shoeList) { this.shoeList = shoeList; } public void setIsShowLoad(boolean isShowLoad) { this.isShowLoad = isShowLoad; } public boolean getIsShowLoad() { return isShowLoad; } public void setBaseAction(BaseAction baseAction) { this.baseAction = baseAction; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = View.inflate(parent.getContext(), R.layout.base_shoe_item, null); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { if (shoeList == null) { return; } ObjectShoe shoe = shoeList.get(position); holder.item_ll.setTag(position); holder.item_ll.setOnClickListener(this); String name_str = shoe.getBrand() + "\t" + shoe.getDesign(); holder.name_tv.setText(name_str); String params_str = shoe.getColor() + "\t" + shoe.getSize(); holder.params_tv.setText(params_str); switch (shoe.getGender()) { case GENDER_MALE: case "Male": holder.gender_img.setVisibility(View.VISIBLE); holder.gender_img.setImageResource(R.drawable.shoe_gender_male); break; case GENDER_FEMALE: case "Female": holder.gender_img.setVisibility(View.VISIBLE); holder.gender_img.setImageResource(R.drawable.shoe_gender_female); break; case GENDER_GENERAL: case "General": holder.gender_img.setVisibility(View.GONE); break; default: break; } holder.shoe_img.setTag(HttpSet.BASE_URL + shoe.getImagePath()); loadImage(holder, position); } @Override public int getItemCount() { return shoeList == null ? 0 : shoeList.size(); } @Override public void onClick(View v) { Context context = v.getContext(); if (!HttpAction.checkNet(context)) { return; } int position = Methods.cast(v.getTag()); ObjectShoe shoe = shoeList.get(position); String epc_code_str = shoe.getEpcCode(); Intent product_int = new Intent(context, Product_Act.class); product_int.putExtra(IntentSet.KEY_EPC_CODE, epc_code_str); context.startActivity(product_int); } public class ViewHolder extends RecyclerView.ViewHolder { public LinearLayout item_ll; public ImageView shoe_img; public ImageView gender_img; public TextView name_tv; public TextView params_tv; public ViewHolder(View itemView) { super(itemView); item_ll = (LinearLayout) itemView.findViewById(R.id.rv_ll); shoe_img = (ImageView) itemView.findViewById(R.id.rv_img); gender_img = (ImageView) itemView.findViewById(R.id.rv_gender_img); name_tv = (TextView) itemView.findViewById(R.id.rv_name_tv); params_tv = (TextView) itemView.findViewById(R.id.rv_params_tv); } } private void loadImage(ViewHolder holder, int position) { // 先判断缓存中是否缓存了这个item的imageview所在的url的图片 String img_url = holder.shoe_img.getTag().toString(); // 如果没有 if (cache.getBitmap(img_url) == null) { // 请求下载图片 // downloadImage(holder, position, cache); Methods.downloadImage(holder.shoe_img, HttpSet.BASE_URL + shoeList.get(position).getImagePath(), cache); } else { holder.shoe_img.setImageBitmap(cache.getBitmap(img_url)); } } // private void downloadImage(ViewHolder holder, int position, BitmapCache cache) { // RequestQueue queue = Volley.newRequestQueue(holder.name_tv.getContext()); // // ImageLoader loader = new ImageLoader(queue, cache); // // ImageLoader.ImageListener listener = ImageLoader.getImageListener(holder.shoe_img, R.mipmap.ic_launcher, R.mipmap.ic_launcher); // // loader.get(HttpSet.BASE_URL + shoeList.get(position).getImagePath(), listener); // } } <file_sep>/app/src/main/java/com/waletech/walesmart/sharedinfo/SharedSet.java package com.waletech.walesmart.sharedinfo; /** * Created by KeY on 2016/4/11. */ public final class SharedSet { public final static String NAME = "sp_file"; public final static String LANGUAGE_CHINESE = "Chinese"; public final static String LANGUAGE_ENGLISH = "English"; public final static String KEY_IS_LOGIN = "is_login"; public final static String KEY_USERNAME = "username"; public final static String KEY_NICKNAME = "nickname"; public final static String KEY_LAST_ID = "last_id"; public final static String KEY_APP_LANGUAGE = "app_language"; public final static String KEY_APP_LAUNCH = "app_launch"; public final static String KEY_APP_FST_LAUNCH = "app_fst_launch"; public final static String KEY_NOTICE_ENTER = "notice_enter"; public final static String KEY_NET_IP = "net_ip"; public final static String KEY_NET_SERVICE = "net_service"; } <file_sep>/app/src/main/java/com/waletech/walesmart/user/lockInfo/using/LockUsing_Frag.java package com.waletech.walesmart.user.lockInfo.using; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.waletech.walesmart.GeneralShoeRycAdapter; import com.waletech.walesmart.publicObject.ObjectShoe; import com.waletech.walesmart.R; import com.waletech.walesmart.base.Base_Frag; import org.json.JSONException; import java.util.ArrayList; /** * Created by KeY on 2016/6/28. */ public class LockUsing_Frag extends Base_Frag implements SwipeRefreshLayout.OnRefreshListener { private SwipeRefreshLayout using_refresh; private ArrayList<ObjectShoe> shoeList; private UsingAction usingAction; private boolean isFstInit; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_lock_using_layout, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); varInit(); setupSwipeRefresh(view); } private void varInit() { shoeList = new ArrayList<>(); usingAction = new UsingAction(getContext(), this); usingAction.getUsingList(); isFstInit = true; } private void setupSwipeRefresh(View view) { using_refresh = (SwipeRefreshLayout) view.findViewById(R.id.using_sr); using_refresh.setColorSchemeResources(R.color.colorMain, R.color.colorSpecial, R.color.colorSpecialConverse); using_refresh.setOnRefreshListener(this); } private void setupRecyclerView(View view) { GeneralShoeRycAdapter adapter = new GeneralShoeRycAdapter(shoeList, getContext()); adapter.setModuleType(GeneralShoeRycAdapter.TYPE_USING); final RecyclerView using_rv = (RecyclerView) view.findViewById(R.id.using_rv); using_rv.setLayoutManager(new LinearLayoutManager(getContext())); using_rv.setItemAnimator(new DefaultItemAnimator()); using_rv.setAdapter(adapter); } @Override public void onMultiHandleResponse(String tag, String result) throws JSONException { onStopRefresh(); shoeList = usingAction.handleResponse(result); if (getView() != null) { if (isFstInit) { setupRecyclerView(getView()); isFstInit = false; return; } final RecyclerView using_rv = (RecyclerView) getView().findViewById(R.id.using_rv); GeneralShoeRycAdapter adapter = (GeneralShoeRycAdapter) using_rv.getAdapter(); adapter.setModuleType(GeneralShoeRycAdapter.TYPE_USING); adapter.setShoeList(shoeList); adapter.notifyDataSetChanged(); } } @Override public void onNullResponse() throws JSONException { if (isFstInit) { ((AppCompatActivity) getContext()).finish(); } onStopRefresh(); } @Override public void setCustomTag(String tag) { } @Override public String getCustomTag() { return null; } @Override public void onRefresh() { usingAction.getUsingList(); } private void onStopRefresh() { if (getView() != null && using_refresh != null && using_refresh.isRefreshing()) { using_refresh.setRefreshing(false); } } } <file_sep>/app/src/main/java/com/waletech/walesmart/pattern/PatternAction.java package com.waletech.walesmart.pattern; import android.content.Context; import android.util.Log; import com.waletech.walesmart.R; import com.waletech.walesmart.base.BaseAction; import com.waletech.walesmart.base.Base_Frag; import com.waletech.walesmart.http.HttpAction; import com.waletech.walesmart.http.HttpHandler; import com.waletech.walesmart.http.HttpResult; import com.waletech.walesmart.http.HttpSet; import com.waletech.walesmart.http.HttpTag; import com.waletech.walesmart.publicObject.ObjectShoe; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; /** * Created by KeY on 2016/7/13. */ public class PatternAction extends BaseAction { private Base_Frag fragment; private String save_brand = ""; private String save_design = ""; private String save_color = ""; private String save_size = ""; public PatternAction(Context context, Base_Frag fragment) { super(context); this.fragment = fragment; } public void setSaveSize(String save_size) { this.save_size = save_size; } public void getDefaultStock(String epc_code) { if (!checkNet()) { return; } String[] key = {HttpSet.KEY_EPC_CODE}; String[] value = {epc_code}; HttpAction action = new HttpAction(context); action.setUrl(HttpSet.URL_GET_DEFAULT_STOCK); action.setTag(HttpTag.PATTERN_GET_DEFAULT_STOCK); action.setMap(key, value); action.setDialog(context.getString(R.string.base_search_progress_title), context.getString(R.string.base_search_progress_msg)); action.setHandler(new HttpHandler(context, fragment)); action.interaction(); } public void getPattern(String brand, String design) { if (!checkNet()) { return; } String[] key = {HttpSet.KEY_BRAND, HttpSet.KEY_PRODUCT_NAME}; String[] value = {brand, design}; save_brand = brand; save_design = design; HttpAction action = new HttpAction(context); action.setUrl(HttpSet.URL_GET_PATTERN); action.setTag(HttpTag.PATTERN_GET_PATTERN); action.setMap(key, value); action.setDialog(context.getString(R.string.base_search_progress_title), context.getString(R.string.base_search_progress_msg)); action.setHandler(new HttpHandler(context, fragment)); action.interaction(); } public void getSizeMatch(String color) { if (!checkNet()) { return; } String[] key = {HttpSet.KEY_BRAND, HttpSet.KEY_PRODUCT_NAME, HttpSet.KEY_COLOR}; String[] value = {save_brand, save_design, color}; save_color = color; HttpAction action = new HttpAction(context); action.setUrl(HttpSet.URL_GET_SIZE); action.setTag(HttpTag.PATTERN_GET_SIZE); action.setMap(key, value); action.setDialog(context.getString(R.string.base_search_progress_title), context.getString(R.string.base_search_progress_msg)); action.setHandler(new HttpHandler(context, fragment)); action.interaction(); } public void getImageMatch(String color) { if (!checkNet()) { return; } String[] key = {HttpSet.KEY_BRAND, HttpSet.KEY_PRODUCT_NAME, HttpSet.KEY_COLOR}; String[] value = {save_brand, save_design, color}; HttpAction action = new HttpAction(context); action.setUrl(HttpSet.URL_GET_IMAGE); action.setTag(HttpTag.PATTERN_GET_IMAGE); action.setMap(key, value); action.setHandler(new HttpHandler(context, fragment)); action.interaction(); } public void getShoeDetails(String size) { if (!checkNet()) { return; } save_size = size; String[] key = {HttpSet.KEY_BRAND, HttpSet.KEY_PRODUCT_NAME, HttpSet.KEY_COLOR, HttpSet.KEY_SIZE}; String[] value = {save_brand, save_design, save_color, size}; HttpAction action = new HttpAction(context); action.setUrl(HttpSet.URL_GET_SHOE_DETAILS_BY_SKU); action.setTag(HttpTag.PATTERN_GET_SHOE_DETAILS); action.setMap(key, value); action.setDialog(context.getString(R.string.base_search_progress_title), context.getString(R.string.base_search_progress_msg)); action.setHandler(new HttpHandler(context, fragment)); action.interaction(); } public void getColorMatch(String size) { String[] key = {HttpSet.KEY_BRAND, HttpSet.KEY_PRODUCT_NAME, HttpSet.KEY_SIZE}; String[] value = {save_brand, save_design, size}; HttpAction action = new HttpAction(context); action.setUrl(HttpSet.URL_GET_COLOR); action.setTag(HttpTag.PATTERN_GET_COLOR); action.setMap(key, value); action.setDialog(context.getString(R.string.base_search_progress_title), context.getString(R.string.base_search_progress_msg)); action.setHandler(new HttpHandler(context, fragment)); action.interaction(); } public void OnAddInCart(String sku_code) { if (!checkNet()) { return; } if (!checkLoginStatus()) { return; } if (save_color.equals("") || save_size.equals("")) { toast.showToast("请选择颜色或尺码"); return; } String[] key = {HttpSet.KEY_USERNAME, HttpSet.KEY_SKU_CODE}; String[] value = {sharedAction.getUsername(), sku_code}; HttpAction action = new HttpAction(context); action.setUrl(HttpSet.URL_ADD_CART); action.setTag(HttpTag.PATTERN_ADD_CART); action.setMap(key, value); action.setDialog(context.getString(R.string.base_add_progress_title), context.getString(R.string.base_add_progress_msg)); action.setHandler(new HttpHandler(context, fragment)); action.interaction(); } public ObjectShoe handleDefaultStockResponse(String result) throws JSONException { JSONObject obj = new JSONObject(result); ObjectShoe shoe = new ObjectShoe(); for (int i = 0; i < obj.length(); i++) { shoe.value_set[i] = obj.getString(ObjectShoe.key_set[i]); } return shoe; } public ArrayList<ObjectShoe> handlePatternResponse(String result) throws JSONException { Log.i("Result", "pattern result is : " + result); JSONArray array = new JSONArray(result); ArrayList<ObjectShoe> shoeList = new ArrayList<>(); for (int i = 0; i < array.length(); i++) { JSONObject obj = array.getJSONObject(i); ObjectShoe shoe = new ObjectShoe(); for (int k = 0; k < obj.length(); k++) { shoe.value_set[k] = obj.getString(ObjectShoe.key_set[k]); } shoeList.add(shoe); } return shoeList; } public ArrayList<String> handleSizeResponse(String result) throws JSONException { Log.i("Result", "size result is : " + result); JSONArray array = new JSONArray(result); ArrayList<String> sizeList = new ArrayList<>(); for (int i = 0; i < array.length(); i++) { sizeList.add(array.getString(i)); } return sizeList; } public String handleImageResponse(String result) throws JSONException { Log.i("Result", "get shoe image in pattern is : " + result); JSONObject obj = new JSONObject(result); return obj.getString(HttpResult.RESULT); } public ObjectShoe handleShoeDetailsResponse(String result) throws JSONException { Log.i("Result", "get shoe detail in pattern is : " + result); JSONObject obj = new JSONObject(result); ObjectShoe shoe = new ObjectShoe(); for (int k = 0; k < obj.length(); k++) { shoe.value_set[k] = obj.getString(ObjectShoe.key_set[k]); } return shoe; } public void handleColorResponse(String result) throws JSONException { Log.i("Result", "color result is : " + result); JSONArray array = new JSONArray(result); } public void handleAddCartResponse(String result) throws JSONException { JSONObject obj = new JSONObject(result); toast.showToast(obj.getString(HttpResult.RESULT)); } } <file_sep>/app/src/main/java/com/waletech/walesmart/netDown/NetDownAction.java package com.waletech.walesmart.netDown; import android.content.Context; import android.util.Log; import com.waletech.walesmart.R; import com.waletech.walesmart.base.BaseAction; import com.waletech.walesmart.base.Base_Frag; import com.waletech.walesmart.http.HttpAction; import com.waletech.walesmart.http.HttpHandler; import com.waletech.walesmart.http.HttpResult; import com.waletech.walesmart.http.HttpSet; import com.waletech.walesmart.http.HttpTag; import org.json.JSONException; import org.json.JSONObject; /** * Created by KeY on 2016/7/14. */ public class NetDownAction extends BaseAction { private Base_Frag fragment; public NetDownAction(Context context, Base_Frag fragment) { super(context); this.fragment = fragment; } public void ping() { String[] key = {""}; String[] value = {""}; HttpAction action = new HttpAction(context); action.setUrl(HttpSet.URL_PING); action.setHandler(new HttpHandler(context, fragment)); action.setTag(HttpTag.NET_DOWN_PING); action.setMap(key, value); action.interaction(); } public boolean handleResponse(String result) throws JSONException { Log.i("Result", "net down result is : " + result); JSONObject obj = new JSONObject(result); return obj.getString(HttpResult.RESULT).equals("Success"); } } <file_sep>/app/src/main/java/com/waletech/walesmart/base/Base_Frag.java package com.waletech.walesmart.base; import android.support.v4.app.Fragment; import org.json.JSONException; import java.io.Serializable; /** * Created by KeY on 2016/6/6. */ public abstract class Base_Frag extends Fragment implements Serializable{ // 根据不同的Handler可以处理不同的反馈结果,最强大 public abstract void onMultiHandleResponse(String tag, String result) throws JSONException; public abstract void onNullResponse() throws JSONException; public abstract void setCustomTag(String tag); public abstract String getCustomTag(); } <file_sep>/app/src/main/java/com/waletech/walesmart/product/Product_Act.java package com.waletech.walesmart.product; import android.app.Dialog; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AlertDialog; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.waletech.walesmart.R; import com.waletech.walesmart.base.Base_Act; import com.waletech.walesmart.datainfo.AddressSet; import com.waletech.walesmart.datainfo.DataBaseAction; import com.waletech.walesmart.http.HttpResult; import com.waletech.walesmart.http.HttpSet; import com.waletech.walesmart.http.HttpTag; import com.waletech.walesmart.main.experience.ExpRycAdapter; import com.waletech.walesmart.publicAction.UnlockAction; import com.waletech.walesmart.publicClass.BitmapCache; import com.waletech.walesmart.publicClass.LineToast; import com.waletech.walesmart.publicClass.Methods; import com.waletech.walesmart.publicClass.ScreenSize; import com.waletech.walesmart.publicObject.ObjectShoe; import com.waletech.walesmart.publicObject.ObjectShop; import com.waletech.walesmart.publicSet.IntentSet; import com.waletech.walesmart.publicSet.MapSet; import com.waletech.walesmart.shop.Shop_Act; import com.waletech.walesmart.user.authInfo.PermissionAction; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; public class Product_Act extends Base_Act implements SwipeRefreshLayout.OnRefreshListener, Toolbar.OnMenuItemClickListener { private SwipeRefreshLayout product_refresh; private ImageButton fav_imgbtn; private ObjectShoe shoe; private ProductAction productAction; private ClickListener clickListener; private boolean isFromShop; private boolean isFstInit; private boolean isHaveFav; private BitmapCache cache; private LineToast toast; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_product_layout); varInit(); setupToolbar(); setupSwipeRefresh(); } private void varInit() { String epc_code_str = getIntent().getStringExtra(IntentSet.KEY_EPC_CODE); isFromShop = getIntent().getBooleanExtra(IntentSet.KEY_IS_FROM_SHOP, false); productAction = new ProductAction(this); clickListener = new ClickListener(this, productAction); isFstInit = true; isHaveFav = false; cache = new BitmapCache(); toast = new LineToast(this); productAction.getShoeDetails(epc_code_str); } @Override protected void setupToolbar() { setTbTitle(getString(R.string.product_toolbar_title)); setTbNavigation(); toolbar.showOverflowMenu(); toolbar.setOnMenuItemClickListener(this); } private void setupSwipeRefresh() { product_refresh = (SwipeRefreshLayout) findViewById(R.id.product_sr); product_refresh.setColorSchemeResources(R.color.colorMain, R.color.colorSpecial, R.color.colorSpecialConverse); product_refresh.setOnRefreshListener(this); } private void setupShoeImage() { final ImageView shoe_img = (ImageView) findViewById(R.id.product_img); String img_url = HttpSet.BASE_URL + shoe.getImagePath(); if (cache.getBitmap(img_url) == null) { // 请求下载图片 Methods.downloadImage(shoe_img, img_url, cache); } else { shoe_img.setImageBitmap(cache.getBitmap(img_url)); } } private void setupDetailsList() { final ListView standard_lv = (ListView) findViewById(R.id.product_lv0); final ListView params_lv = (ListView) findViewById(R.id.product_lv1); String location = shoe.getProvince() + shoe.getCity() + shoe.getCounty() + shoe.getShopName(); String[] detail_info = {shoe.getBrand(), shoe.getDesign(), shoe.getColor(), shoe.getSize(), location}; List<String> list = Arrays.asList(detail_info); ArrayAdapter standard_adapter = ArrayAdapter.createFromResource(this, R.array.product_standard, R.layout.listview_text_item); standard_lv.setAdapter(standard_adapter); ArrayAdapter params_adapter = new ArrayAdapter<>(this, R.layout.listview_text_item, list); params_lv.setAdapter(params_adapter); } private void setupBottomBar() { final Button add_cart_btn = (Button) findViewById(R.id.product_btn); add_cart_btn.setTag(shoe); add_cart_btn.setOnClickListener(clickListener); int count = Integer.parseInt(shoe.getCount()); if (count > 0) { // 有库存 add_cart_btn.setVisibility(View.VISIBLE); add_cart_btn.setOnClickListener(clickListener); } else { // 没有库存 add_cart_btn.setVisibility(View.GONE); final TextView no_stock_tv = (TextView) findViewById(R.id.product_tv0); no_stock_tv.setVisibility(View.VISIBLE); } // Unlock final ImageButton unlock_imgbtn = (ImageButton) findViewById(R.id.product_imgbtn0); unlock_imgbtn.setOnClickListener(clickListener); // Favourite fav_imgbtn = (ImageButton) findViewById(R.id.product_imgbtn1); if (isHaveFav) { fav_imgbtn.setImageResource(R.drawable.ic_public_favorite_light); } // 传递到 ClickListener 中,便于 FavAction() 的判断 onWrapFavTag(); fav_imgbtn.setOnClickListener(clickListener); // Enter Cart final ImageButton enter_cart_imgbtn = (ImageButton) findViewById(R.id.product_imgbtn2); enter_cart_imgbtn.setOnClickListener(clickListener); } private void onWrapFavTag() { HashMap<String, Object> map = new HashMap<>(); map.put(MapSet.KEY_IS_HAVE_FAVOURITE, isHaveFav); map.put(MapSet.KEY_EPC_CODE, shoe.getEpcCode()); fav_imgbtn.setTag(map); } private void setupSearchOtherShop() { final TextView other_shop_tv = (TextView) findViewById(R.id.product_tv1); other_shop_tv.setTag(shoe.getEpcCode()); other_shop_tv.setOnClickListener(clickListener); } @Override public void onMultiHandleResponse(String tag, String result) throws JSONException { onStopRefresh(); switch (tag) { case HttpTag.PRODUCT_GET_SHOE_DETAILS: shoe = productAction.handleDetailsResponse(result); productAction.onCheckFavourite(shoe.getEpcCode()); setupSearchOtherShop(); break; // case HttpTag.PRODUCT_GET_SHOE_STOCK: // ArrayList<ObjectShoe> shoeList = productAction.handleStockResponse(result); // setupShoeStockView(shoeList); // break; case HttpTag.PRODUCT_GET_SHOE_OTHER_SHOP: ArrayList<String> shopNameList = productAction.handleOtherShopResponse(result); onCreateShopDialog(shopNameList); break; case HttpTag.FAVOURITE_CHECK_FAVOURITE: // 返回值有两个,"已有该收藏"和"没有该收藏" String result_str = new JSONObject(result).getString(HttpResult.RESULT); if (result_str.equals(getString(R.string.product_item_already_exists))) { isHaveFav = true; } setupShoeImage(); setupDetailsList(); setupBottomBar(); break; case HttpTag.UNLOCK_UNLOCK: toast.showToast(new JSONObject(result).getString(HttpResult.RESULT)); break; case HttpTag.FAVOURITE_ADD_FAVOURITE: fav_imgbtn.setImageResource(R.drawable.ic_public_favorite_light); isHaveFav = true; onWrapFavTag(); break; case HttpTag.FAVOURITE_DELETE_FAVOURITE: fav_imgbtn.setImageResource(R.drawable.ic_public_favorite_dark); isHaveFav = false; onWrapFavTag(); break; default: break; } } @Override public void onNullResponse() throws JSONException { if (isFstInit) { finish(); } onStopRefresh(); } @Override public void onPermissionAccepted(int permission_code) { } @Override public void onPermissionRefused(int permission_code) { toast.showToast(getString(R.string.auth_toast_permission_camera_authorized)); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { if (requestCode == UnlockAction.REQUEST_MAIN) { String smark_id = data.getStringExtra("scan_result"); productAction.unlock(smark_id); } } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); PermissionAction.handle(this, requestCode, grantResults); } @Override public void onRefresh() { productAction.getShoeDetails(shoe.getEpcCode()); } private void onStopRefresh() { if (product_refresh != null && product_refresh.isRefreshing()) { product_refresh.setRefreshing(false); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.toolbar_product_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onMenuItemClick(MenuItem item) { if (!isFromShop) { String location = shoe.getProvince() + shoe.getCity() + shoe.getCounty() + shoe.getRoad(); Intent shop_int = new Intent(this, Shop_Act.class); shop_int.putExtra(IntentSet.KEY_SHOP_NAME, shoe.getShopName()); shop_int.putExtra(IntentSet.KEY_SHOP_LOCATION, location); startActivity(shop_int); } else { finish(); } return false; } private ArrayList<String> onFilterList(ArrayList<String> shopNameList) { for (int i = 0; i < shopNameList.size(); i++) { if (shopNameList.get(i).equals(shoe.getShopName())) { shopNameList.remove(i); } } return shopNameList; } private void onCreateShopDialog(ArrayList<String> shopNameList) { if (shopNameList == null || (shopNameList.size() == 0)) { return; } shopNameList = onFilterList(shopNameList); if (shopNameList == null || (shopNameList.size() == 0)) { toast.showToast(getString(R.string.product_toast_find_no_other_shop)); return; } ExpRycAdapter adapter = new ExpRycAdapter(initShopListData(shopNameList)); LayoutInflater inflater = getLayoutInflater(); View view = inflater.inflate(R.layout.public_shop_list_page, null); final RecyclerView shop_list_rv = (RecyclerView) view.findViewById(R.id.shop_list_rv); LinearLayoutManager manager = new LinearLayoutManager(this); shop_list_rv.setLayoutManager(manager); shop_list_rv.setItemAnimator(new DefaultItemAnimator()); shop_list_rv.setAdapter(adapter); // 获取屏幕的高度,设定标准的对话框高度为屏幕的一半的大小 ScreenSize size = new ScreenSize(this); int standard_height = (int) (size.getHeight() * 0.5); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setView(view); Dialog dialog = builder.create(); Window dialogWindow = dialog.getWindow(); WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.CENTER); lp.height = standard_height; dialogWindow.setAttributes(lp); dialog.show(); } private ArrayList<ObjectShop> initShopListData(ArrayList<String> shopNameList) { ArrayList<ObjectShop> shopList = new ArrayList<>(); DataBaseAction baseAction = DataBaseAction.onCreate(this); if (shopNameList == null) { shopNameList = baseAction.query(AddressSet.TABLE_NAME, new String[]{""}, new String[]{""}, AddressSet.SHOP, ""); } ArrayList<String> shopLocList = new ArrayList<>(); for (int i = 0; i < shopNameList.size(); i++) { String shop_name = shopNameList.get(i); ArrayList<String> singleLoc_List = baseAction. query(AddressSet.TABLE_NAME, new String[]{AddressSet.SHOP}, new String[]{shop_name}, AddressSet.ROAD, ""); shopLocList.add(singleLoc_List.get(0)); } for (int i = 0; i < shopNameList.size(); i++) { ObjectShop shop = new ObjectShop(); shop.setName(shopNameList.get(i)); shop.setLocation(shopLocList.get(i)); shopList.add(shop); } return shopList; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // Check if the key event was the Back button and if there's history if (keyCode == KeyEvent.KEYCODE_BACK) { collapsePattern(); return false; } return super.onKeyDown(keyCode, event); } // 两次点击返回键退出 public void collapsePattern() { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); if (fragmentManager.findFragmentByTag("pattern_frag") != null) { transaction.remove(fragmentManager.findFragmentByTag("pattern_frag")); transaction.commit(); } else { finish(); } } } <file_sep>/app/src/main/java/com/waletech/walesmart/user/ClickListener.java package com.waletech.walesmart.user; import android.content.Context; import android.content.Intent; import android.view.View; import com.waletech.walesmart.R; import com.waletech.walesmart.user.editInfo.Edit_Info_Act; import com.waletech.walesmart.user.lockInfo.LockInfo_Act; import com.waletech.walesmart.user.shopInfo.cart.Cart_Act; /** * Created by KeY on 2016/6/24. */ class ClickListener implements View.OnClickListener { private Context context; public ClickListener(Context context) { this.context = context; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.user_head_img1: onEditUserHead(); break; case R.id.user_tv0: onLockInfo(); break; case R.id.user_tv1: onShopCart(); break; case R.id.user_tv2: onModifyPsd(); break; default: break; } } private void onEditUserHead() { Intent edit_int = new Intent(context, Edit_Info_Act.class); context.startActivity(edit_int); } private void onLockInfo() { Intent lock_int = new Intent(context, LockInfo_Act.class); context.startActivity(lock_int); } private void onShopCart() { Intent lock_int = new Intent(context, Cart_Act.class); context.startActivity(lock_int); } private void onModifyPsd() { } } <file_sep>/app/src/main/java/com/waletech/walesmart/user/shopInfo/cart/ClickListener.java package com.waletech.walesmart.user.shopInfo.cart; import android.content.Context; import android.content.DialogInterface; import android.support.v7.app.AlertDialog; import android.view.View; import com.waletech.walesmart.R; import com.waletech.walesmart.base.BaseAction; import com.waletech.walesmart.base.BaseClickListener; import com.waletech.walesmart.publicClass.LineToast; import com.waletech.walesmart.publicClass.Methods; import com.waletech.walesmart.publicObject.ObjectShoe; import com.waletech.walesmart.publicSet.MapSet; import com.waletech.walesmart.publicSet.ToastSet; import java.util.ArrayList; import java.util.HashMap; /** * Created by KeY on 2016/7/2. */ class ClickListener extends BaseClickListener { private CartAction cartAction; private LineToast toast; public ClickListener(Context context, BaseAction baseAction) { super(context, baseAction); cartAction = (CartAction) baseAction; toast = new LineToast(context); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.rv_pattern_fl: onHidePattern(v); break; case R.id.rv_make_order_tv: onCreateOrderConfirmDialog(v); break; default: break; } } private void onHidePattern(View view) { if (view.getVisibility() == View.VISIBLE) { view.setVisibility(View.GONE); } } private void onCreateOrderConfirmDialog(final View view) { new AlertDialog.Builder(context) .setTitle(context.getString(R.string.cart_dialog_order_confirm_title)) .setMessage(context.getString(R.string.cart_dialog_order_confirm_msg)) .setPositiveButton(context.getString(R.string.base_dialog_btn_yes), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { onMakeOrder(view); } }) .setNegativeButton(context.getString(R.string.base_dialog_btn_no), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .show(); } private void onMakeOrder(View view) { HashMap<String, Object> map = Methods.cast(view.getTag()); ArrayList<ObjectShoe> shoeList = Methods.cast(map.get(MapSet.KEY_SHOE_LIST)); ArrayList<String> checkList = Methods.cast(map.get(MapSet.KEY_CHECK_LIST)); if (checkList == null || checkList.size() == 0) { toast.showToast(context.getString(R.string.base_toast_no_item_been_selected)); return; } StringBuilder sku_code_builder = new StringBuilder(""); for (int i = 0; i < checkList.size(); i++) { int position = Integer.parseInt(checkList.get(i)); ObjectShoe shoe = shoeList.get(position); if (i == (checkList.size() - 1)) { sku_code_builder.append(shoe.getRemark()); } else { sku_code_builder.append(shoe.getRemark()).append("-"); } } cartAction.onCreateOrder(sku_code_builder.toString()); } } <file_sep>/app/src/main/java/com/waletech/walesmart/user/shopInfo/order/OrderAction.java package com.waletech.walesmart.user.shopInfo.order; import android.content.Context; import com.waletech.walesmart.R; import com.waletech.walesmart.base.BaseAction; import com.waletech.walesmart.http.HttpAction; import com.waletech.walesmart.http.HttpHandler; import com.waletech.walesmart.http.HttpSet; import com.waletech.walesmart.http.HttpTag; import com.waletech.walesmart.publicObject.ObjectOrder; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; /** * Created by KeY on 2016/7/25. */ public class OrderAction extends BaseAction { public OrderAction(Context context) { super(context); } public void getOrderList() { String[] key = {HttpSet.KEY_USERNAME}; String[] value = {sharedAction.getUsername()}; HttpAction action = new HttpAction(context); action.setUrl(HttpSet.URL_GET_ORDER); action.setTag(HttpTag.ORDER_GET_ORDER); action.setDialog(context.getString(R.string.base_search_progress_title), context.getString(R.string.base_search_progress_msg)); action.setHandler(new HttpHandler(context)); action.setMap(key, value); action.interaction(); } public ArrayList<ObjectOrder> handleResponse(String result) throws JSONException { JSONArray array = new JSONArray(result); ArrayList<ObjectOrder> orderList = new ArrayList<>(); if (array.length() == 0) { toast.showToast(context.getString(R.string.base_toast_no_more_item)); return orderList; } for (int i = 0; i < array.length(); i++) { JSONObject obj = array.getJSONObject(i); ObjectOrder order = new ObjectOrder(); for (int k = 0; k < obj.length(); k++) { order.value_set[k] = obj.getString(ObjectOrder.key_set[k]); } orderList.add(order); } // String last_id = orderList.get(orderList.size() - 1).getLastId(); // sharedAction.setLastId(Integer.parseInt(last_id)); return orderList; } } <file_sep>/app/src/main/java/com/waletech/walesmart/GeneralShoeRycAdapter.java package com.waletech.walesmart; import android.content.Context; import android.os.Handler; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.waletech.walesmart.http.HttpAction; import com.waletech.walesmart.publicClass.LineToast; import com.waletech.walesmart.publicObject.ObjectShoe; import com.waletech.walesmart.publicSet.ToastSet; import com.waletech.walesmart.searchResult.ResultAction; import java.util.ArrayList; /** * Created by KeY on 2016/6/28. */ public class GeneralShoeRycAdapter extends BaseShoeRycAdapter { public final static int TYPE_NULL = 0; public final static int TYPE_RESULT = 1; public final static int TYPE_USING = 2; private int type = 0; private LineToast toast; public GeneralShoeRycAdapter(ArrayList<ObjectShoe> shoeList, Context context) { super(shoeList, context); } public void setModuleType(int type) { this.type = type; } @Override public BaseShoeRycAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { toast = new LineToast(parent.getContext()); isShowLoad = false; View view = View.inflate(parent.getContext(), R.layout.recycler_shoe_general_item, null); return new ViewHolder(view); } @Override public void onBindViewHolder(BaseShoeRycAdapter.ViewHolder holder, int position) { super.onBindViewHolder(holder, position); ViewHolder child_holder = (ViewHolder) holder; switch (type) { case TYPE_NULL: toast.showToast(ToastSet.GENERAL_TYPE_IS_NULL); break; case TYPE_RESULT: onResultStatus(child_holder, position); break; case TYPE_USING: onUsingStatus(child_holder, position); break; default: break; } } protected class ViewHolder extends BaseShoeRycAdapter.ViewHolder { TextView status_up_tv; TextView status_down_tv; TextView bottom_bar_tv; LinearLayout load_ll; public ViewHolder(View itemView) { super(itemView); status_up_tv = (TextView) itemView.findViewById(R.id.rv_status_tv0); status_down_tv = (TextView) itemView.findViewById(R.id.rv_status_tv1); bottom_bar_tv = (TextView) itemView.findViewById(R.id.rv_bottom_tv); load_ll = (LinearLayout) itemView.findViewById(R.id.rv_load_ll); } } private void onResultStatus(ViewHolder holder, int position) { ObjectShoe shoe = shoeList.get(position); int count = Integer.parseInt(shoe.getCount()); if (count > 0) { holder.status_up_tv.setVisibility(View.GONE); holder.status_down_tv.setVisibility(View.VISIBLE); // holder.status_up_tv.setBackgroundResource(R.drawable.shoe_status_multi_color_tv); // holder.status_up_tv.setText("多色"); holder.status_down_tv.setBackgroundResource(R.drawable.shoe_status_multi_size_tv); holder.status_down_tv.setText(context.getString(R.string.shoe_in_stock_tv)); } else { holder.status_up_tv.setVisibility(View.GONE); holder.status_down_tv.setVisibility(View.GONE); } String location_str = shoe.getProvince() + "-" + shoe.getCity() + "-" + shoe.getCounty() + "-" + shoe.getShopName() + shoe.getSmarkRow() + "行" + shoe.getSmarkColumn() + "列"; holder.bottom_bar_tv.setText(location_str); onLoadMore(holder, position); } private void onUsingStatus(ViewHolder holder, int position) { ObjectShoe shoe = shoeList.get(position); // 这里的 getRemark() 是指的是当前正在试鞋的这只或者这双鞋还剩下多少可以体验的时间 // 这个只有分和秒,没有小时,更没有年月日,到时间了就为 00:00 String time_str = shoe.getRemark(); holder.status_up_tv.setVisibility(View.VISIBLE); holder.status_up_tv.setText(time_str); String status_str = shoe.getStatus(); holder.status_down_tv.setVisibility(View.VISIBLE); if (status_str.equals(context.getString(R.string.area_shoe_status_enjoying_tv))) { holder.status_down_tv.setBackgroundResource(R.drawable.shoe_status_ets_tv); } else { holder.status_down_tv.setBackgroundResource(R.drawable.shoe_status_prs_tv); } holder.status_down_tv.setText(status_str); String location_str = shoe.getProvince() + shoe.getCity() + shoe.getCounty() + shoe.getShopName() + shoe.getSmarkRow() + "行" + shoe.getSmarkColumn() + "列"; holder.bottom_bar_tv.setText(location_str); onLoadMore(holder, position); } private void onLoadMore(final ViewHolder holder, int position) { if (position == (shoeList.size() - 1)) { if (isShowLoad) { holder.load_ll.setVisibility(View.VISIBLE); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { if (!HttpAction.checkNet(context)) { holder.load_ll.setVisibility(View.GONE); } else { ((ResultAction) baseAction).resultLoad(); } isShowLoad = false; } }, 1000); } } else { holder.load_ll.setVisibility(View.GONE); } } // // Desperate Methods /** * @param holder 目的是为了获取子单位 Item 的单位高度 * 然后拿 item 的单位高度乘以总数量,判断总高度是否超出了整个屏幕 */ // private void onMeasureHeight(final ViewHolder holder) { // final Context context = holder.load_ll.getContext(); // // ScreenSize size = new ScreenSize(context); // int s_h = size.getHeight(); // // int item_whole_h = shoeList.size() * holder.item_ll.getLayoutParams().height; // // isHigher = s_h < item_whole_h; // } // // Desperate Methods // private void setupLoadItem(final ViewHolder holder,final int position) { // final Context context = holder.load_ll.getContext(); // // if ((position == (shoeList.size() - 1)) && !isShowLoad) { // ScreenSize size = new ScreenSize(context); // int s_h = size.getHeight(); // // int item_whole_h = shoeList.size() * holder.item_ll.getLayoutParams().height; // // if (s_h < item_whole_h) { // holder.load_ll.setVisibility(View.VISIBLE); // isShowLoad = true; // // Handler handler = new Handler(); // handler.postDelayed(new Runnable() { // @Override // public void run() { // // 判断是否已经发出过 "加载更多" 的网络请求,如果发出过,就不再发送 // if (!isSendLoadRequest) { // // 判断是否有网络 // if (!HttpAction.checkNet(context)) { // holder.load_ll.setVisibility(View.GONE); // } else { // ((ResultAction) baseAction).resultLoad(); // isSendLoadRequest = true; // } // } // } // }, 1500); // } // } else { // holder.load_ll.setVisibility(View.GONE); // } // } } <file_sep>/app/src/main/java/com/waletech/walesmart/login/Login_Act.java package com.waletech.walesmart.login; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import com.waletech.walesmart.R; import com.waletech.walesmart.base.Base_Act; import com.waletech.walesmart.publicClass.Methods; import org.json.JSONException; public class Login_Act extends Base_Act { private ClickListener clickListener; private LoginAction loginAction; public static AppCompatActivity login_act; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login_layout); varInit(); setupToolbar(); setupInputField(); setupRegister(); setupLogin(); } private void varInit() { login_act = this; loginAction = new LoginAction(this); clickListener = new ClickListener(this, loginAction); } @Override protected void setupToolbar() { setTbTitle(getString(R.string.login_toolbar_title)); setTbNavigation(); } private void setupInputField() { // 监听点击屏幕空白处隐藏软键盘 final LinearLayout login_ll = (LinearLayout) findViewById(R.id.login_ll); login_ll.setOnClickListener(clickListener); final EditText usn_et = (EditText) findViewById(R.id.login_et0); usn_et.requestFocus(); Methods.expandIME(usn_et); final TextView eye_tv = (TextView) findViewById(R.id.login_tv0); final TextView clear_tv = (TextView) findViewById(R.id.login_tv1); eye_tv.setOnClickListener(clickListener); clear_tv.setOnClickListener(clickListener); } private void setupRegister() { final Button reg_btn = (Button) findViewById(R.id.login_btn0); reg_btn.setOnClickListener(clickListener); } private void setupLogin() { final Button login_btn = (Button) findViewById(R.id.login_btn1); login_btn.setOnClickListener(clickListener); } @Override public void onMultiHandleResponse(String tag, String result) throws JSONException { loginAction.handleResponse(result); } @Override public void onNullResponse() throws JSONException { } @Override public void onPermissionAccepted(int permission_code) { } @Override public void onPermissionRefused(int permission_code) { } } <file_sep>/app/src/main/java/com/waletech/walesmart/register/ClickListener.java package com.waletech.walesmart.register; import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.text.method.HideReturnsTransformationMethod; import android.text.method.PasswordTransformationMethod; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.waletech.walesmart.R; import com.waletech.walesmart.base.BaseAction; import com.waletech.walesmart.base.BaseClickListener; import com.waletech.walesmart.publicClass.Methods; /** * Created by KeY on 2016/6/1. */ class ClickListener extends BaseClickListener { private Context context; private RegisterAction registerAction; // 判断点击“小眼睛”以后,是显示或隐藏密码 private boolean psd_triggle = false; public ClickListener(Context context, BaseAction baseAction) { super(context, baseAction); this.context = context; registerAction = (RegisterAction) baseAction; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.reg_ll: // 收回软键盘 Methods.collapseIME(v.getContext()); break; case R.id.reg_tv0: // 显示密码 displayPsd(); break; case R.id.reg_tv1: // 清除密码 clearPsd(); break; case R.id.reg_btn1: // 获取验证码 getIdc(); break; case R.id.reg_btn2: onRegister(); // onNextStep(); break; default: break; } } private void displayPsd() { AppCompatActivity compatActivity = (AppCompatActivity) context; final EditText psd_et = (EditText) compatActivity.findViewById(R.id.reg_et1); if (!psd_triggle) { psd_et.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); psd_triggle = true; } else { psd_et.setTransformationMethod(PasswordTransformationMethod.getInstance()); psd_triggle = false; } psd_et.setSelection(psd_et.length()); } private void clearPsd() { AppCompatActivity compatActivity = (AppCompatActivity) context; final EditText psd_et = (EditText) compatActivity.findViewById(R.id.reg_et1); psd_et.setText(""); } private void getIdc() { AppCompatActivity compatActivity = (AppCompatActivity) context; final Button idc_press_btn = (Button) compatActivity.findViewById(R.id.reg_btn0); final Button idc_btn = (Button) compatActivity.findViewById(R.id.reg_btn1); // 倒计时10s后才允许再次发送验证码 ResendCountTimer timer = new ResendCountTimer(10 * 1000, 1000); timer.setBtn(context, idc_btn, idc_press_btn); timer.start(); idc_btn.setVisibility(View.INVISIBLE); } private void onRegister() { AppCompatActivity compatActivity = (AppCompatActivity) context; final EditText usn_et = (EditText) compatActivity.findViewById(R.id.reg_et0); final EditText psd_et = (EditText) compatActivity.findViewById(R.id.reg_et1); final EditText nicn_et = (EditText) compatActivity.findViewById(R.id.reg_et2); String usn_str = usn_et.getText().toString(); String psd_str = psd_et.getText().toString(); String nicn_str = nicn_et.getText().toString(); registerAction.register(usn_str, psd_str, nicn_str); } }
07f9a8803a759b6fdeb9197194d1dd98a354591d
[ "Java", "Gradle" ]
50
Java
WaleTech/WaleSmart
d9b0aef7a0f14a3316024df98c671897d9ba231d
26cf2aba647048de4edae9da3231c2e4a0f06821
refs/heads/master
<file_sep>import React from "react"; import { connect } from "react-redux"; import { PropTypes } from "prop-types"; import UsersList from "../components/UsersList" import { fetchUsers } from "../actions/UsersActions" class Users extends React.Component { componentDidMount() { this.props.fetchUsers(); } render() { return ( <div> <h2>Users</h2> <UsersList users={this.props.users} /> </div> ); } } Users.propTypes = { users: PropTypes.array.isRequired, fetchUsers: PropTypes.func.isRequired } function mapStateToProps(state) { return { users: state.users } } export default connect(mapStateToProps, {fetchUsers})(Users);<file_sep>import React from "react"; import { PropTypes } from "prop-types"; export default function UsersList({users}) { console.log(users); return ( <div> {users.length === 0 ? 'null' : users[0].name} </div> ) } UsersList.propTypes = { users: PropTypes.array.isRequired } <file_sep>export const SET_USERS = 'SET_USERS' export function setUsers(users) { return { type: SET_USERS, users } } export function fetchUsers() { return dispatch => { fetch('/users') .then(res => res.json()) .then(data => dispatch(setUsers(data))); } }<file_sep>### Colocando a aplicação do ar #### 1. Instale Node e NPM. #### 2. Execute ```npm start``` #### 2. Abra [http://localhost:3000](http://localhost:3000) Importante: Para o funcionamento correto, é necessário que o backend esteja sendo executado localmente na porta 8080.
ae2763fa45f61d00a8e7f30fa195f903bb9f392d
[ "JavaScript", "Markdown" ]
4
JavaScript
bernardohrl/surittec-frontend
79c3fb709285d39800b34d00ba69dde92d4f962f
a4a9313376a32068d86e1263254a168f50245b65
refs/heads/main
<repo_name>zszhere/util_scripts<file_sep>/initPVE.sh #!/usr/bin/env bash # 1.run this script # 2.手动删除local-lvm:数据中心-存储-删除local-lvm # 3.手动编辑local:内容里添加 磁盘映像和容器 # for PVE6.3,need to run as root # exit # exit on first error set -e # config para comment='# by initPVE' sshport='22' pubkey='ssh-rsa **********' mailName='<EMAIL>' mailPwd='<PASSWORD>' # print color string in shell red_prefix="\033[31m" green_prefix="\033[1;32m" color_suffix="\033[0m" info="[${green_prefix}INFO${color_suffix}]" error="[${red_prefix}ERROR${color_suffix}]" # config language and other things confInfo(){ echo -e "${info} func confInfo()" # config language cat > /etc/default/locale << "EOF" LANG="en_US.utf8" LANGUAGE="en_US.utf8" LC_ALL="en_US.utf8" EOF # disable apt pve-enterprise source sed -i -E \ -e "s/^deb/#deb/" \ /etc/apt/sources.list.d/pve-enterprise.list echo "deb http://download.proxmox.com/debian/pve buster pve-no-subscription" > /etc/apt/sources.list.d/pve-no-subscription.list # disable subscribe notice in web sed -i \ -e "s/if (res === null || res === undefined || \!res || res/if (false) {/g" \ -e "s/.data.status.toLowerCase() !== 'active') {/ /" \ /usr/share/javascript/proxmox-widget-toolkit/proxmoxlib.js # config lvm disk space,remove local-lvm then extend pve/root pvs vgs lvs lvremove pve/data lvextend -l +100%FREE -r pve/root lvs echo -e "${info} func confInfo() done!" } # conf ssh port and pubkey confSSH(){ echo -e "${info} func confSSH()" echo "${pubkey}" >> /root/.ssh/authorized_keys sed -i -E \ -e "s/^#?Port .*/Port ${sshport}/" \ -e "s/^#?PubkeyAuthentication .*/PubkeyAuthentication yes/" \ -e "s/^#?PasswordAuthentication .*/PasswordAuthentication no/" \ -e "s/^#?PermitEmptyPasswords .*/PermitEmptyPasswords no/" \ /etc/ssh/sshd_config echo -e "${info} func confSSH() done!" } # install Util insUtil(){ echo -e "${info} func insUtil()" apt update apt install -y vim htop iftop curl wget git sl nmap socat dnsutils net-tools #apt install -y python3 python3-pip python python-pip echo -e "${info} func insUtil() done!" } # install Mail insMail(){ echo -e "${info} func insMail()" apt install -y libsasl2-modules echo "[smtp.163.com]:465 ${mailName}:${mailPwd}" > /etc/postfix/sasl_passwd postmap hash:/etc/postfix/sasl_passwd chmod 600 /etc/postfix/sasl_passwd chmod 600 /etc/postfix/sasl_passwd.db echo "/From:.*/ REPLACE From: ${mailName}" > /etc/postfix/header_checks echo "/.+/ ${mailName}" > /etc/postfix/sender_canonical_maps sed -i -E \ -e "s/^relayhost/#relayhost/" \ /etc/postfix/main.cf cat >> /etc/postfix/main.cf << "EOF" # relay smtp config relayhost = [smtp.163.com]:465 smtp_use_tls = yes smtp_sasl_auth_enable = yes smtp_sasl_security_options = noanonymous smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd smtp_tls_CAfile = /etc/ssl/certs/Entrust_Root_Certification_Authority.pem smtp_tls_session_cache_database = btree:/var/lib/postfix/smtp_tls_session_cache smtp_tls_session_cache_timeout = 3600s smtp_tls_wrappermode = yes smtp_tls_security_level = encrypt # filter the from addr sender_canonical_classes = envelope_sender, header_sender sender_canonical_maps = regexp:/etc/postfix/sender_canonical_maps smtp_header_checks = regexp:/etc/postfix/header_checks EOF systemctl restart postfix.service echo "" > /var/log/mail.log echo "initPVE : $(uname -a)" | mail -s "initPVE : $(uname -n)" "${mailName}" sleep 3 cat /var/log/mail.log echo -e "${info} func insMail() done!" } insTmux(){ echo -e "${info} func insTmux()" apt install -y tmux echo "set -g mouse on" > /root/.tmux.conf echo -e "${info} func insTmux() done!" } insScreenfetch(){ echo -e "${info} func insScreenfetch()" apt install -y screenfetch cat > /etc/update-motd.d/99-screenfetch << "EOF" #!/bin/sh if [ -f /usr/bin/screenfetch ]; then screenfetch; fi EOF chmod +x /etc/update-motd.d/99-screenfetch echo -e "${info} func insScreenfetch() done!" } insZsh(){ echo -e "${info} func insZsh()" apt install -y zsh # exec error,didn't know why # su - ${username} << "EOF" # /bin/sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" # git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions # EOF /bin/sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions sed -i -E \ -e "s/^#? ?ZSH_THEME=.*/ZSH_THEME=\"bira\"/" \ -e "s/^#? ?DISABLE_AUTO_TITLE=.*/DISABLE_AUTO_TITLE=\"true\"/" \ -e "s/^#? ?plugins=.*/plugins=\(git zsh-autosuggestions\)/" \ /root/.zshrc echo -e "${info} func insZsh() done!" } confInfo confSSH insUtil insMail insTmux insScreenfetch insZsh<file_sep>/initVPS.sh #!/usr/bin/env bash # 1.适用于使用dd方式抹盘重装 或者 vps默认的镜像 系统 # 2.本脚本会创建新用户,默认为********** # for ubuntu18,need to run as root # exit # exit on first error set -e # config para comment='# by initVPS' username='**********' servername='**********' sshport='**********' pubkey='ssh-rsa **********' # print color string in shell red_prefix="\033[31m" green_prefix="\033[1;32m" color_suffix="\033[0m" info="[${green_prefix}INFO${color_suffix}]" error="[${red_prefix}ERROR${color_suffix}]" # add user # change root passwd first addUser(){ echo -e "${info} func addUser()" echo -e "${info} change root passwd first!" passwd root echo -e "${info} add user ${username}" adduser ${username} usermod -aG sudo ${username} groups ${username} root edit="${username} ALL=(ALL:ALL) NOPASSWD:ALL" # edit with comment # sed -i -e "\$a${comment}\n${edit}" /etc/sudoers sed -i -e "\$a${edit}" /etc/sudoers echo -e "${info} func addUser() done!" } # config timezone and servername and language confInfo(){ echo -e "${info} func confInfo()" timedatectl set-timezone Asia/Shanghai date -R hostnamectl set-hostname "${servername}" hostnamectl status sed -i -e "1i\127.0.0.1\t${servername}" /etc/hosts # the /etc/default/locale file may not contain the para # if so,the s cmd in sed may not work well # so 1.del the para 2.add the para # sed -i \ # -e "/LANG=/d" \ # -e "/LANGUAGE=/d" \ # -e "/LC_ALL=/d" \ # /etc/default/locale # echo "${comment}" >> /etc/default/locale # sed -i \ # -e "\$aLANG=\"en_US.utf8\"" \ # -e "\$aLANGUAGE=\"en_US.utf8"\" \ # -e "\$aLC_ALL=\"en_US.utf8\"" \ # /etc/default/locale cat > /etc/default/locale << "EOF" LANG="en_US.utf8" LANGUAGE="en_US.utf8" LC_ALL="en_US.utf8" EOF echo -e "${info} func confInfo() done!" } # conf ssh port and pubkey confSSH(){ echo -e "${info} func confSSH()" mkdir -p /home/${username}/.ssh echo "${pubkey}" > /home/${username}/.ssh/authorized_keys chmod 600 /home/${username}/.ssh/authorized_keys chmod 700 /home/${username}/.ssh chown -R ${username}:${username} /home/${username}/.ssh # sed -i.bkup -E \ # -e "s/^#?Port .*/Port ${sshport}/" \ # -e "s/^#?PubkeyAuthentication .*/PubkeyAuthentication yes/" \ # -e "s/^#?PasswordAuthentication .*/PasswordAuthentication no/" \ # -e "s/^#?PermitEmptyPasswords .*/PermitEmptyPasswords no/" \ # /etc/ssh/sshd_config # diff /etc/ssh/sshd_config /etc/ssh/sshd_config.bkup # rm -rf /etc/ssh/sshd_config.bkup sed -i -E \ -e "s/^#?Port .*/Port ${sshport}/" \ -e "s/^#?PubkeyAuthentication .*/PubkeyAuthentication yes/" \ -e "s/^#?PasswordAuthentication .*/PasswordAuthentication no/" \ -e "s/^#?PermitEmptyPasswords .*/PermitEmptyPasswords no/" \ -e "s/^#?PermitRootLogin .*/PermitRootLogin no/" \ /etc/ssh/sshd_config echo -e "${info} func confSSH() done!" } # install Util insUtil(){ echo -e "${info} func insUtil()" apt update apt install -y vim htop iftop curl wget git sl nmap socat dnsutils net-tools #apt install -y python3 python3-pip python python-pip echo -e "${info} func insUtil() done!" } insTmux(){ echo -e "${info} func insTmux()" apt install -y tmux echo "set -g mouse on" > /home/${username}/.tmux.conf chown -R ${username}:${username} /home/${username}/.tmux.conf echo -e "${info} func insTmux() done!" } insScreenfetch(){ echo -e "${info} func insScreenfetch()" apt install -y screenfetch cat > /etc/update-motd.d/99-screenfetch << "EOF" #!/bin/sh if [ -f /usr/bin/screenfetch ]; then screenfetch; fi EOF chmod +x /etc/update-motd.d/99-screenfetch echo -e "${info} func insScreenfetch() done!" } insZsh(){ echo -e "${info} func insZsh()" apt install -y zsh # exec error,didn't know why # su - ${username} << "EOF" # /bin/sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" # git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions # EOF su - ${username} -s /bin/sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" su - ${username} -s /bin/sh -c "git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions" sed -i -E \ -e "s/^#? ?ZSH_THEME=.*/ZSH_THEME=\"bira\"/" \ -e "s/^#? ?DISABLE_AUTO_TITLE=.*/DISABLE_AUTO_TITLE=\"true\"/" \ -e "s/^#? ?plugins=.*/plugins=\(git zsh-autosuggestions\)/" \ /home/${username}/.zshrc echo -e "${info} func insZsh() done!" } addUser confInfo confSSH insUtil insTmux insScreenfetch insZsh # monitor the vps tcp port, beep when online # watch -b -n 1 'if [ -z "$(nmap 127.0.0.1 -Pn -n -sT -T4 --open -p ********** | grep open)" ]; then echo offline; else echo online;exit 1; fi'<file_sep>/README.md # initPVE - 一键初始化配置VPE服务器 - 使用前需要配置config para中的字段 - 功能 - 修改语言为en_US.utf8 - 关闭企业源更新,添加社区源 - 关闭登录时的未关注提醒 - 合并lvm的磁盘空间 - 配置ssh参数并添加公钥 - 安装常用工具 - 安装邮件提醒,使用163的smtp来发送,装好会发送给自己测试邮件 - 安装配置tmux - 安装配置screenfetch - 安装配置ohmyzsh # initServ - 一键配置本地的ubuntu18 - 使用前需要配置config para中的字段 - 功能,基本同上,看注释 # initVPS - 一键配置远程的ubuntu18 - 使用前需要配置config para中的字段 - 功能,基本同上,看注释 # updateSS - 使用openwrt中的ss-redir制作了三层网络的VPN - 解决ddns更新的问题,会重启ss-redir<file_sep>/updateSS.sh #!/bin/sh #get public ip ip_dns=$(ping -c 1 -w 3 -n **********.us 2>/dev/null|grep -m 1 -oE '(\d{1,3}\.){3}\d{1,3}') #echo "$ip_dns" #get ipset list ip_set=$(ipset list ss_rules_dst_bypass_|grep -oE '(\d{1,3}\.){3}\d{1,3}') #echo "$ip_set" #is the str equal res=$(echo "${ip_set}"|grep -oF "${ip_dns}") #echo "$res" if [ "${res}" == "" ] then /etc/init.d/shadowsocks-libev restart echo "[+]update ss server ip : ${ip_dns}" echo "[+]ss restarted at $(date -R)" # else # echo "[+]ss fine" fi #modify ss ipset to go to **********/24 res=$(ipset list ss_rules_dst_bypass_|grep -oF "**********/24 nomatch") if [ "${res}" == "" ] then ipset add ss_rules_dst_bypass_ **********/24 nomatch echo "[+]ipset modify at $(date -R)" # else # echo "[+]ipset fine" fi # 加入 crontab 定时执行: # root@OpenWrt:~# crontab -e # */3 * * * * /root/updateSS.sh >> /tmp/updateSS.log 2>&1 # 检查 openwrt 的 cron 是否启动: # ps -w|grep cron 查看是否有 cron 的进程 # 开启cron自动启动: # /etc/init.d/cron enable # /etc/init.d/cron start
9a1c88a535529fe0b8d78f27c17d48758893c1b3
[ "Markdown", "Shell" ]
4
Shell
zszhere/util_scripts
e41e90ce398e46516943bc1dc5f96f9b01258087
85d33ecd381176d0bd974b44cfdc588d579ac465
refs/heads/master
<file_sep><?php namespace App\Jobs; use App\Base; use App\Email; use App\Tag; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\DB; class ImportTagsJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $timeout = 0; public $tags; public $bases; public $path; /** * Create a new job instance. * * @return void */ public function __construct($tags, $bases, $path = null) { $this->tags = $tags; $this->bases = $bases; $this->path = $path; } /** * Execute the job. * * @return void */ public function handle() { Base::whereIn('id', $this->bases)->update(['statut' => true]); $tags = []; foreach ($this->tags as $key => $value) { $tags[] = ['name' => $value]; } Tag::insertOrIgnore($tags); $this->path ? $this->getEmailsInFile() : $this->importTagsToEmail(Email::whereIn('base_id', $this->bases)->select('id', 'tags')->get()->toArray()); } public function getEmailsInFile(){ $emails = []; $handle = fopen(public_path($this->path), 'r'); while($ligne = fgets($handle)){ $email = filter_var(trim($ligne), FILTER_VALIDATE_EMAIL); $email && $emails[] = $email; } $this->getMatchInBdd($emails); } public function getMatchInBdd($emails){ $sendNbr = 10000; $cutEmails = array_slice($emails, 0, $sendNbr); if(count($cutEmails) > 0){ $matchs = Email::whereIn('base_id', $this->bases)->whereIn('email', $cutEmails)->select('id', 'tags')->get()->toArray(); $this->importTagsToEmail($matchs); $this->getMatchInBdd(array_slice($emails, $sendNbr, count($emails))); } Base::whereIn('id', $this->bases)->update(['statut' => false]); return true; } public function importTagsToEmail($emails){ $i = 0; $string = ''; $array_id = []; while($i < count($emails)){ array_push($array_id, $emails[$i]["id"]); $newTags = array_unique(array_merge($emails[$i]["tags"], $this->tags)); $string .= " WHEN ".$emails[$i]["id"]." THEN '".json_encode(array_values($newTags), JSON_HEX_APOS)."'"; $i++; } if(count($emails) > 0){ $all_id = implode(', ', $array_id); return DB::update("UPDATE `emails` SET `tags` = CASE `id` $string ELSE `tags` END WHERE `id` IN ($all_id)"); } return true; } } <file_sep>const { isEmpty } = require("lodash"); module.exports = { checkIfFileExist: (formData, store) => { const alert = document.getElementById('alert-info'); alert.style.display = 'block'; alert.innerHTML = 'Votre fichier est en cours de vérification ...'; return fetch('/store/check', { method: 'POST', headers: new Headers({ "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').getAttribute('content'), }), body: formData, redirect: 'manual' }).then(response => response) .then(responseData => { if(responseData.status === 0){ return document.location.reload(true); } return responseData.json(); }).then(response => { if(isEmpty(response)){ alert.innerHTML = 'Nouveau fichier détecter !'; return store && module.exports.storeFile(formData, alert); } alert.style.display = 'none'; return response; }).catch(err => { module.exports.initializeSubmit('error', null, err); }); }, storeFile: (formData, alert) => { alert.innerHTML = 'Votre fichier est en cours d\'enregistrement ...' return fetch('/store', { method: 'POST', headers: new Headers({ "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').getAttribute('content'), }), body: formData, redirect: 'manual' }).then(response => response.json()) .then(response => { alert.style.display = "none"; return response; }).catch(err => { return err; }); }, getEmailsOfFile: myFile => { const isEmail = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,3})$/gm; var file = myFile.files[0]; var reader = new FileReader(); reader.readAsText(file, "UTF-8"); return new Promise((response, reject) => { reader.onload = function (evt){ const emails = evt.target.result.match(isEmail); return emails && emails.length > 0 ? response(emails) : reject('Il n\'y a pas d\'emails en clair dans votre fichier !'); }; }).catch(err => { module.exports.initializeSubmit('error', null, err); }); }, awaitSendToServer: (length, formData, url, callback = false, progress = 0) => { const alert = document.getElementById('alert-info'); alert.innerHTML = 'Vous avez choisi le mode normal ! Votre fichier est en cours d\'envoie ! Veuillez ' const emails = JSON.parse(formData.get('emails')); const progressBar = document.getElementById('progress-bar'); const sendNbr = 10000; var array = emails.slice(0, sendNbr); var result = progress*100/length; progressBar.style.width = `${result}%`; if(array.length > 0){ return fetch(url, { method: 'POST', headers: new Headers({ "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').getAttribute('content'), }), body: formData, redirect: 'manual' }).then(reponse => { if(response.status === 0){ return document.location.reload(true); } formData.set('emails', JSON.stringify(emails.slice(sendNbr, emails.length))); return module.exports.awaitSendToServer(length, formData, url, callback, progress+array.length); }).catch(err => { module.exports.initializeSubmit('error', null, err); }); } return callback() ?? true; }, notAwaitSendToServer: (formData, url) => { return fetch(url, { method: 'POST', headers: new Headers({ "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').getAttribute('content'), }), body: formData, redirect: 'manual' }).then(response => { if(response.status === 0){ return document.location.reload(true); } const progressBar = document.getElementById('progress-bar'); progressBar.style.width = '100%'; return response; }).catch(err => { module.exports.initializeSubmit('error', null, err); }); }, initializeSubmit: (statut, button = null, message = null) => { const [alertSuccess, alertDanger, errorDanger] = [ document.getElementById('alert-success'), document.getElementById('alert-danger'), ]; if(button !== null){ button.removeAttribute('disabled'); button.children["loader"].style.display = "none"; } switch (statut){ case 'start': alertDanger.style.display = 'none'; alertSuccess.style.display = 'none'; button.setAttribute('disabled', true); button.children["loader"].style.display = "block"; break; case 'success': alertSuccess.style.display = 'block'; alertSuccess.innerHTML = message; break; case 'error': alertDanger.style.display = 'block'; alertDanger.innerHTML = message; break; } }, };<file_sep>const { initializeSubmit, getEmailsOfFile, checkIfFileExist, notAwaitSendToServer } = require("../functions/functions"); const [file1, file2, fileButton] = [document.getElementById('file1'),document.getElementById('file1'), document.getElementById('fileButton')] $("#fileForm").on('submit', function(e) { e.preventDefault(); initializeSubmit('start', fileButton); const formData = new FormData(e.target); getEmailsOfFile(file1).then(res =>{ const formFile1 = new FormData(); formFile1.append('file', formData.get('file1')); const formFile2 = new FormData(); formFile2.append('file', formData.get('file2')); getEmailsOfFile(file2).then(res =>{ checkIfFileExist(formFile1, true).then(res1 => { checkIfFileExist(formFile2, true).then(res2 => { const formData2 = new FormData(); formData2.append('path1', res1.path); formData2.append('path2', res2.path); formData2.append('statut', formData.get('statut')); notAwaitSendToServer(formData2, '/comparateur/create/files').then(res => { initializeSubmit('success', fileButton, 'Nickel'); }); }); }); }); }); });<file_sep><?php use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class FaiDomainsSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $array = [ // Orange ['fais_id' => 1, 'name' => 'orange.fr'], ['fais_id' => 1, 'name' => 'wanadoo.fr'], ['fais_id' => 1, 'name' => 'voila.fr'], // Free ['fais_id' => 2, 'name' => 'free.fr'], ['fais_id' => 2, 'name' => 'freesbee.fr'], ['fais_id' => 2, 'name' => 'libertysurf.fr'], ['fais_id' => 2, 'name' => 'worldonline.fr'], ['fais_id' => 2, 'name' => 'online.fr'], ['fais_id' => 2, 'name' => 'alicepro.fr'], ['fais_id' => 2, 'name' => 'aliceadsl.fr'], ['fais_id' => 2, 'name' => 'alicemail.fr'], ['fais_id' => 2, 'name' => 'infonie.fr'], // Gmail ['fais_id' => 3, 'name' => 'gmail.com'], // Sfr ['fais_id' => 4, 'name' => 'sfr.fr'], ['fais_id' => 4, 'name' => 'neuf.fr'], ['fais_id' => 4, 'name' => 'cegetel.net'], ['fais_id' => 4, 'name' => 'club-internet.fr'], ['fais_id' => 4, 'name' => 'numericable.fr'], ['fais_id' => 4, 'name' => 'numericable.com'], ['fais_id' => 4, 'name' => 'noos.fr'], ['fais_id' => 4, 'name' => 'neufcegetel.fr'], // La poste ['fais_id' => 5, 'name' => 'laposte.net'], ['fais_id' => 5, 'name' => 'laposte.fr'], // Autre ['fais_id' => 6, 'name' => 'blabla.com'], // Hotmail ['fais_id' => 7, 'name' => 'hotmail.fr'], ['fais_id' => 7, 'name' => 'msn.fr'], ['fais_id' => 7, 'name' => 'live.fr'], ['fais_id' => 7, 'name' => 'outlook.fr'], ['fais_id' => 7, 'name' => 'outlook.com'], ['fais_id' => 7, 'name' => 'msn.com'], // Yahoo ['fais_id' => 8, 'name' => 'yahoo.fr'], ['fais_id' => 8, 'name' => 'yahoo.com'], // Aol ['fais_id' => 9, 'name' => 'aol.com'], ['fais_id' => 9, 'name' => 'aol.fr'], // Bbox ['fais_id' => 10, 'name' => 'bbox.fr'], // Apple ['fais_id' => 11, 'name' => 'icloud.com'], // Autrefr ['fais_id' => 12, 'name' => 'autrefr'], // Suisse ['fais_id' => 13, 'name' => 'adressesuisse'], // Belgique ['fais_id' => 14, 'name' => 'adressebelgique'], // Tiscali ['fais_id' => 15, 'name' => 'tiscali.fr'], ]; DB::table('fais_domains')->insert($array); } } <file_sep> window.onload = function() { function getRandomColor(i) { var color = [ '#FF6633', '#FFB399', '#FF33FF', '#FFFF99', '#00B3E6', '#E6B333', '#3366E6', '#999966', '#99FF99', '#B34D4D', '#80B300', '#809900', '#E6B3B3', '#6680B3', '#66991A', '#FF99E6', '#CCFF1A', '#FF1A66', '#E6331A', '#33FFCC', '#66994D', '#B366CC', '#4D8000', '#B33300', '#CC80CC', '#66664D', '#991AFF', '#E666FF', '#4DB3FF', '#1AB399', '#E666B3', '#33991A', '#CC9999', '#B3B31A', '#00E680', '#4D8066', '#809980', '#E6FF80', '#1AFF33', '#999933', '#FF3380', '#CCCC00', '#66E64D', '#4D80CC', '#9900B3', '#E64D66', '#4DB380', '#FF4D4D', '#99E6E6', '#6666FF'] return color[i] } document.querySelector('#radioList').addEventListener('click', ev => { const radioBase = document.querySelector('#inlineRadio1'); document.querySelector('#loaderfa').style.display = "none"; document.querySelector('#settingBase').style.display = "none"; document.querySelector('#setting').innerHTML = ""; document.querySelector('#sendButtonn').disabled = true if (radioBase.checked == true){ document.querySelector('#fileShow').style.display = "none"; document.querySelector('#baseShow').style.display = "block"; } else { document.querySelector('#fileShow').style.display = "block"; document.querySelector('#baseShow').style.display = "none"; } }); var myDataSava = [] var totalSet = [] var endUcanSwoh = false var cutConfig = { seg: [], data: null, dataString: "", maxData: {}, totalData: {} } document.getElementById('nbseg').addEventListener('change', function() { var qty = document.getElementById('nbseg').value document.querySelector('#selSeg').innerHTML = '' var refresh = [] for (var i = 0; i < qty; i++) { refresh[i] = cutConfig.seg[i] var opt = document.createElement('option'); opt.appendChild(document.createTextNode("Segement "+ (Number(i)+1))); document.querySelector('#selSeg').appendChild(opt); opt.value = Number(i)+1; } cutConfig.seg = refresh updateGraph() }); document.querySelector('#selSeg').addEventListener('change', ev => { var setting = document.querySelector('#setting') for (var i = 0; i < setting.children.length; i++) { if (typeof cutConfig.seg[ev.target.value] != "object"){ cutConfig.seg[ev.target.value-1] = {} } var o = cutConfig.seg[ev.target.value-1][setting.children[i].children[0].textContent] || 0 setting.children[i].children[1].value = o } }); Array.prototype.diff = function(a) { return this.filter(function(i) {return a.indexOf(i) < 0;}); }; document.getElementById('file').addEventListener('change', function() { myDataSava = [] endUcanSwoh = false document.querySelector('#loaderfa').style.display = "block"; document.querySelector('#settingBase').style.display = "none"; document.querySelector('#setting').innerHTML = ""; var file = document.getElementById('file').files[0] console.log(file); var reader = new FileReader(); var formData = new FormData(document.querySelector('#myForm')); console.log(formData); formData.set('path', 'decoupe'); reader.readAsText(file, "UTF-8"); boucleAgain() reader.onload = function (evt){ const emails = evt.target.result.match(/[a-zA-Z0-9_\-\+\.]+@[a-zA-Z0-9\-]+\.([a-zA-Z]{2,4})(?:\.[a-zA-Z]{2})?/g); if(emails){ storeFile(formData, () => { sendToServer(emails.length, [emails, [...formData][1][1]], '/liste/create', () => {}) }); myDataSava = emails fetch('{{route("liste.get")}}', { method: 'POST', headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, body: JSON.stringify({id: document.getElementById('exampleFormControlSelect1').value, data: "emails"}), }) .then( (res) => { if (res.status != 500){ res.text() .then( (json) => { loadGraph(json) }) }else{ alertify.error('Le serveur à rencontrer un probleme lors du traitement des données.'); } }); }else{ alert('Votre fichier ne contient pas de mails'); } } }) document.getElementById('exampleFormControlSelect1').addEventListener('change', function() { document.querySelector('#loaderfa').style.display = "block"; document.querySelector('#settingBase').style.display = "none"; document.querySelector('#setting').innerHTML = ""; console.log("send") fetch('{{route("liste.get")}}', { method: 'POST', headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, body: JSON.stringify({id: document.getElementById('exampleFormControlSelect1').value}), }) .then( (res) => { if (res.status != 500){ res.text() .then( (json) => { loadGraph(json) }) }else{ alertify.error('Le serveur à rencontrer un probleme lors du traitement des données.'); } }); }); function boucleAgain(){ console.log('pasdsdsse'); setTimeout(function(){ console.log('passe'); if (endUcanSwoh){ var dataToSend = JSON.stringify({total: myDataSava, use: totalSet}); fetch('{{route("liste.getDiff")}}', { method: 'POST', headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, body: dataToSend, }) .then( (res) => { res.text() .then( (json) => { cutConfig.data[cutConfig.data.length-1][2] = Object.values(json) }) }) } else { boucleAgain() } }, 1000); } function loadGraph(json){ var data = JSON.parse(json) var update = []; data = Object.values(data) console.log(data); fai = {} // data[1] = Object.values(data[1]) if (data[0] == "ok"){ data[0] = myDataSava } myDataSava = data[0] cutConfig.dataString = data[0].join('\n'); json = data[1] var email = {} var result = [] totalSet = [] var count = 0 for (var i = 0; i < Object.values(json).length; i++) { email[Object.keys(json)[i]] = [] for (var y = 0; y < json[Object.keys(json)[i]].length; y++) { var reg = new RegExp("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@"+ json[Object.keys(json)[i]][y] +"$","igm"); var match = cutConfig.dataString.match(reg) if (match != null){ email[Object.keys(json)[i]] = email[Object.keys(json)[i]].concat(match) } totalSet = totalSet.concat(match) } count = (Number(count) + Number(email[Object.keys(json)[i]].length)) result[i] = [Object.keys(json)[i], email[Object.keys(json)[i]].length, email[Object.keys(json)[i]]] } result.push(["FAI inconnu", data[0].length - count, []]) console.log(result); data[1] = result for (var i = 0; i < data[1].length; i++) { cutConfig.data = data[1] cutConfig.maxData[data[1][i][0]] = data[1][i][1] cutConfig.totalData[data[1][i][0]] = 0 update[i] = { label: data[1][i][0], backgroundColor: getRandomColor(i), data: [0,data[1][i][1]] } if (data[1][i][1] > 0){ var div = document.createElement("div"); var label = document.createElement("label"); var input = document.createElement("input"); div.classList.add("form-group"); div.classList.add("col-md-2"); label.setAttribute("for", "id"+data[1][i][0]) label.innerHTML = data[1][i][0] input.setAttribute("id", "id"+data[1][i][0]) input.setAttribute("type", "number") input.setAttribute("value", "0") input.setAttribute("min", "0") input.setAttribute("class", "form-control changeValue") input.setAttribute("aria-describedby", "basic-addon3") document.querySelector('#setting').appendChild(div); div.appendChild(label); div.appendChild(input); } } updateGraph() document.querySelectorAll('.changeValue').forEach((item) => { item.addEventListener('change', (ev) => { var actualSeg = document.querySelector('#selSeg').value var valueChange = Number(ev.target.value) var FAI = ev.target.labels[0].innerText if (typeof cutConfig.seg[actualSeg-1] != "object"){ cutConfig.seg[actualSeg-1] = {} cutConfig.seg[actualSeg-1][FAI] = 0 } var zeg = cutConfig.seg[actualSeg-1][FAI] ?? 0 var ttFAI = getTotalValue(FAI) if (valueChange < 0){ ev.target.value = cutConfig.seg[actualSeg-1][FAI] } if (((ttFAI - zeg) + valueChange) <= cutConfig.maxData[FAI]){ cutConfig.seg[actualSeg-1][FAI] = valueChange updateGraph() } else { ev.target.value = valueChange - (((ttFAI-zeg)+valueChange) - cutConfig.maxData[FAI]) cutConfig.seg[actualSeg-1][FAI] = valueChange - (((ttFAI-zeg)+valueChange) - cutConfig.maxData[FAI]) updateGraph() } }); }); mytable.data.datasets = update mytable.update(); document.querySelector('#loaderfa').style.display = "none"; document.querySelector('#settingBase').style.display = "block" document.querySelector('#sendButtonn').disabled = false endUcanSwoh = true } document.querySelector('#sendButtonn').addEventListener('click', ev => { var save = cutConfig document.querySelector('#loaderCuting').style.display = "block" for (var i = 0; i < document.getElementById('nbseg').value; i++) { var myList = [] var reste = [] if (cutConfig.seg[i]) { for (var s = 0; s < Object.keys(cutConfig.seg[i]).length; s++) { var data = cutConfig.data[getIndexWithValue(cutConfig.data, Object.keys(cutConfig.seg[i])[s])][2] myList = myList.concat(data.slice(0, cutConfig.seg[i][Object.keys(cutConfig.seg[i])[s]])) cutConfig.data[getIndexWithValue(cutConfig.data, Object.keys(cutConfig.seg[i])[s])][2] = data.slice(cutConfig.seg[i][Object.keys(cutConfig.seg[i])[s]]) } } var result = myList.join('\n'); var blob = new Blob([result], {type: "text/plain;charset=utf-8"}); var date = new Date() var reader = new FileReader(); var formData = new FormData(document.querySelector('#formFile')); formData.set('path', 'decoupe'); formData.append("file", blob, `Segment_${Number(i)+1}_${date.getDate()}_${date.getMonth()+1}_${date.getFullYear()}_${date.getHours()}H${date.getMinutes()}min.txt`) reader.readAsText(blob, "UTF-8"); reader.onload = function (evt){ if(result){ storeFile(formData, () => { sendToServer(result.length, [result, [...formData][1][1]], '/liste/create', () => {}) }); } } saveAs(blob, 'Segment_'+(Number(i)+1)+'.txt'); } for (var s = 0; s < cutConfig.data.length; s++) { reste = cutConfig.data[s][2].concat(reste) } var result1 = reste.join('\n'); var blob1 = new Blob([result1], {type: "text/plain;charset=utf-8"}); var date1 = new Date() var reader1 = new FileReader(); var formData1 = new FormData(document.querySelector('#formFile')); formData1.set('path', 'decoupe'); formData1.append("file", blob1, `Reste_${date1.getDate()}_${date1.getMonth()+1}_${date1.getFullYear()}_${date1.getHours()}H${date1.getMinutes()}min.txt`) reader1.readAsText(blob1, "UTF-8"); reader1.onload = function (evt){ if(result1){ storeFile(formData1, () => { sendToServer(result1.length, [result1, [...formData1][1][1]], '/liste/create', () => {}) }); } } saveAs(blob1, 'Reste.txt'); cutConfig = save document.querySelector('#loaderCuting').style.display = "none" }); function getIndexWithValue(array, value){ for (var i = 0; i < array.length; i++) { if (array[i][0] == value) { return i } } } function updateGraph(){ var qty = document.getElementById('nbseg').value var update = [] var updatedatasets = [] for (var i = 0; i < qty; i++) { update[i] = "Segement "+ (Number(i)+1) } for (var y = 0; y < cutConfig.data.length; y++) { var data = [] data[qty] = cutConfig.data[y][1] - getTotalValue(cutConfig.data[y][0]); for (var i = 0; i < cutConfig.seg.length; i++) { if (typeof cutConfig.seg[i] != "object"){ cutConfig.seg[i] = {} } data[i] = cutConfig.seg[i][cutConfig.data[y][0]] || 0 } updatedatasets[y] = { label: cutConfig.data[y][0], backgroundColor: getRandomColor(y), data: data } } update.push("Reste") mytable.data.datasets = updatedatasets mytable.data.labels = update mytable.update(); } function getTotalValue(FAI) { var total = 0 if (cutConfig.seg){ for (var i = 0; i < cutConfig.seg.length; i++) { if(typeof cutConfig.seg[i] != "object"){ cutConfig.seg[i] = {} cutConfig.seg[i][FAI] = 0 } var tt = cutConfig.seg[i][FAI] || 0 total = total + Number(tt) } } return Number(total); } var barChartData = { labels: ['Segement 1', "Reste"], datasets: [] } var ctx = document.getElementById('canvas').getContext('2d'); var mytable = new Chart(ctx, { type: 'bar', data: barChartData, options: { title: { display: true, text: 'Visuel du découpage de la liste' }, tooltips: { mode: 'index', intersect: true }, responsive: true, scales: { xAxes: [{ stacked: true, }], yAxes: [{ ticks: { suggestedMin: 0 }, stacked: true }] } } }); }; //window.myBar.update(); <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Fai; use Yajra\DataTables\Facades\DataTables; use Illuminate\Support\Facades\DB; class FaiController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('fais.index'); } /** * Return an object of all fais and domains for datatable.js */ public function datatable(){ $fais = Fai::leftjoin('fais_domains', 'fais_domains.fais_id', '=', 'fais.id') ->select('fais.id', 'fais.name')->selectRaw('GROUP_CONCAT(fais_domains.name SEPARATOR ", ") AS domains') ->groupByRaw('fais.id, fais.name') ->orderBy('fais.id')->get(); return DataTables::of($fais)->make(true); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('fais.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { if(!Fai::where('name', $request->get('name'))->get()->toArray()){ $id = Fai::insertGetId([ 'name' => $request->get('name') ]); foreach (explode(', ', $request->get('domains')) as $key => $value) { DB::table('fais_domains')::insert([ 'fais_id' => $id, 'domains' => $value ]); } return redirect(route('fais.index'))->with('success', 'Votre FAI a bien été créer'); }else{ return redirect()->back()->with('error', 'Le FAI existe déjà !'); } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $data = Fai::leftjoin('fais_domains', 'fais_domains.fais_id', '=', 'fais.id') ->select('fais.id', 'fais.name')->selectRaw('GROUP_CONCAT(fais_domains.name SEPARATOR ", ") AS domains') ->groupByRaw('fais.id, fais.name') ->orderBy('fais.id')->where('fais.id', $id)->first(); return view('fais.show', ['fais' => $data]); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { Fai::find($id)->delete(); return redirect()->back()->with('success', 'Le FAI a bien été supprimer !'); } } <file_sep>import isEmail from 'deep-waters/isEmail'; console.log(isEmail('<EMAIL>'));<file_sep><?php namespace App\Http\Controllers; use App\Base; use App\Email; use App\File; use App\Jobs\CreateEmails; use Illuminate\Http\Request; use Yajra\DataTables\Facades\DataTables; class EmailController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('emails.index'); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('emails.create', ['bases' => Base::all()]); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $data = json_decode($request->get('data')); File::find($data->id)->bases()->syncWithoutDetaching(Base::find($request->base_id)); CreateEmails::dispatch($data, $request->base_id)->onQueue('emails'); return true; } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } public function datatable(Request $request){ $data = Email::where('base_id', $request->get('id'))->select('id', 'email', 'tags')->get(); return DataTables::of($data)->make(true); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; class EncryptController extends Controller { /** * Display a list of all files * * @return \Illuminate\Http\Response */ public function index(){ return view('encrypt.index'); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create(){ return view('encrypt.create'); } /** * Return a file of email in normal or sha256 who match with our database * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function sha256Method(Request $request){ } /** * Return a file of email in normal or md5 who match with our database * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function md5Method(Request $request){ } } <file_sep><?php namespace App\Http\Controllers; use App\User; use App\Http\Requests\UserRequest; use Illuminate\Support\Facades\Hash; class UserController extends Controller{ /** * Display view to create a new user * @return \Illuminate\View\View */ public function create(){ return view('users.create', ['users' => User::all()]); } /** * Create a new user * @param App\Http\Requests\UserRequest $request * @return \Illuminate\Http\Response */ public function store(UserRequest $request){ User::create(['name' => $request->name,'email' => $request->email,'password' => <PASSWORD>($request->password)]); return redirect()->back()->with('success', 'Votre utilisateur à bien été créer !'); } } <file_sep><?php namespace App\Http\Controllers; use App\Base; use App\Email; use App\Http\Requests\CreateTagRequest; use App\Jobs\ImportTagsJob; use App\Tag; use Illuminate\Http\Request; class TagController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('tags.index'); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('tags.create', ['bases' => Base::all(), 'tags' => Tag::all()]); } /** * Store a newly created resource in storage. * * @param App\Http\Requests\CreateTagRequest $request * @return \Illuminate\Http\Response */ public function store(CreateTagRequest $request) { $tags = json_decode($request->get('tags')); $bases = json_decode($request->get('bases')); if(Email::whereIn('base_id', $bases)->first()){ switch ($request->get('method')){ case 'base': ImportTagsJob::dispatch($tags, $bases)->onQueue('tags'); break; case 'file': $path = $request->get('path'); ImportTagsJob::dispatch($tags, $bases, $path)->onQueue('tags'); break; case 'domains': // Not ready break; } return true; } return redirect()->back()->with('error', 'Il n\'y a pas d\'email dans la / les base(s)'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Sync all tags with different methods * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function sync(Request $request){ } /** * Display the delete tag page * @return \Illuminate\Http\Response */ public function delete(){ return view('tags.delete', ['bases' => Base::all(), 'tags' => Tag::all()]); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy() { // } } <file_sep><?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; class CreateFileBasesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('base_file', function (Blueprint $table) { $table->increments('id'); $table->integer('file_id')->unsigned()->index(); $table->integer('base_id')->unsigned()->index(); $table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP')); $table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP')); $table->unique(['file_id', 'base_id']); }); Schema::table('base_file', function (Blueprint $table){ $table->foreign('file_id')->references('id')->on('files')->onDelete('cascade'); }); Schema::table('base_file', function (Blueprint $table){ $table->foreign('base_id')->references('id')->on('bases')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('base_file'); } } <file_sep><?php namespace App\Http\Controllers; use App\File; use App\Http\Requests\StoreFileRequest; use Illuminate\Http\Request; use App\Repository\StoreFileRepository; use Illuminate\Support\Facades\DB; class StoreFileController extends Controller { protected $repository; /** * Initialize file informations from StoreFileRepository * @param App\Repository\StoreFileRepository $request * */ public function __construct(StoreFileRepository $repository){ $this->repository = $repository; } /** * Store the file in storage folder and some informations in database * @param App\Http\Requests\StoreFileRequest $request * @return array */ public function storeFile(StoreFileRequest $request){ $fileParams = $this->repository->getFileParams($request->file('file')); $request->file('file')->storeAs('public/upload/', $fileParams->path); $myFile = File::create([ 'path' => 'storage/upload/'.$fileParams->path, 'name' => $fileParams->name, 'size' => $fileParams->size, 'type' => $fileParams->type ]); return $myFile; } /** * Check if the file already exist or not * @param App\Http\Requests\StoreFileRequest $request * @return array */ public function check(StoreFileRequest $request){ $fileParams = $this->repository->getFileParams($request->file('file')); return File::where('path', 'storage/upload/'.$fileParams->path)->first() ?? []; } } <file_sep><?php namespace App\Http\Controllers; use App\Jobs\Comparator\withDatabaseJob; use App\Jobs\Comparator\withFilesJob; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; class ComparatorController extends Controller { /** * Display a list of all compared files * * @return \Illuminate\Http\Response */ public function index(){ return view('comparator.index', ['comparators' => DB::table('waiting_files')->where('name', 'comparator')->get()]); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create(){ return view('comparator.create'); } /** * Return an array of email who match between the two files * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function between2Files(Request $request){ $path1 = $request->get('path1'); $path2 = $request->get('path2'); $statut = $request->get('statut'); withFilesJob::dispatch($path1, $path2, $statut)->onQueue('comparator'); return true; } /** * Return an array of email who match with our database * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function withDatabase(Request $request){ $path = $request->get('path'); withDatabaseJob::dispatch($path)->onQueue('comparator'); return true; } } <file_sep><?php use Illuminate\Database\Seeder; use App\Base; class ListSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Base::insert([ 'name' => 'Clients', ]); } } <file_sep><?php namespace App\Jobs\Comparator; use App\WaitingFile; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class withFilesJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $timeout = 0; public $path1; public $path2; public $statut; public $date; /** * Create a new job instance. * * @return void */ public function __construct($path1, $path2, $statut) { $this->path1 = $path1; $this->path2 = $path2; $this->statut = $statut; $this->date = strtotime(now()); } /** * Execute the job. * * @return void */ public function handle() { WaitingFile::insert([ 'name' => 'comparator', 'path' => '/storage/download/'.$this->date.'-matchs.txt', 'statut' => true ]); $file1 = fopen(public_path($this->path1), 'r'); $file2 = fopen(public_path($this->path2), 'r'); $tabliste1 = array(); $tabliste2 = array(); while($ligne = fgets($file1)) { $tabliste1[trim($ligne)]=""; } while($ligne = fgets($file2)) { $tabliste2[trim($ligne)]=""; } $uniques = array_keys(array_diff_key($tabliste1, $tabliste2)); $doublons = array_keys(array_intersect_key($tabliste1, $tabliste2)); $matchsFile = fopen(public_path('/storage/download/'.$this->date.'-matchs.txt'), 'a'); fputcsv($matchsFile, $doublons, "\n"); if($this->statut !== 'null'){ WaitingFile::insert([ 'name' => 'comparator', 'path' => '/storage/download/'.$this->date.'-uniques.txt', 'statut' => true ]); $notMatchsFile = fopen(public_path('/storage/download/'.$this->date.'-uniques.txt'), 'a'); fputcsv($notMatchsFile, $uniques, "\n"); WaitingFile::where('path', '/storage/download/'.$this->date.'-uniques.txt')->update(['statut' => false]); } return WaitingFile::where('path', '/storage/download/'.$this->date.'-matchs.txt',)->update(['statut' => false]); } } <file_sep><?php use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Auth::routes(); // There is routes for login people Route::group(['middleware' => 'auth'], function () { // Profil routes Route::resource('/', 'EmailController'); Route::resource('/bases', 'BaseController'); Route::prefix('tags')->name('tags.')->group(function () { Route::get('delete', 'TagController@delete')->name('delete'); Route::delete('delete', 'TagController@destroy')->name('destroy'); }); Route::resource('/tags', 'TagController')->except('destroy'); Route::prefix('comparateur')->name('comparator.')->group(function () { Route::get('/', 'ComparatorController@index')->name('index'); Route::get('create', 'ComparatorController@create')->name('create'); Route::post('create/database', 'ComparatorController@withDatabase')->name('db'); Route::post('create/files', 'ComparatorController@between2Files')->name('files'); }); Route::prefix('repoussoir')->name('encrypt.')->group(function () { Route::get('/', 'EncryptController@index')->name('index'); Route::get('create', 'EncryptController@create')->name('create'); }); Route::resource('/fais', 'FaiController'); Route::resource('user', 'UserController', ['only' => ['create', 'store']]); Route::get('profile', ['as' => 'profile.edit', 'uses' => 'ProfileController@edit']); Route::put('profile', ['as' => 'profile.update', 'uses' => 'ProfileController@update']); Route::put('profile/password', ['as' => 'profile.password', 'uses' => 'ProfileController@password']); Route::prefix('datatable')->name('datatable.')->group(function () { Route::post('fais', 'FaiController@datatable')->name('fais'); Route::post('bases', 'BaseController@datatable')->name('bases'); Route::post('emails', 'EmailController@datatable')->name('emails'); }); Route::prefix('store')->name('store.')->group(function () { Route::post('check', 'StoreFileController@check')->name('check'); Route::post('/', 'StoreFileController@storeFile')->name('store'); }); }); <file_sep><?php namespace App\Jobs; use App\Base; use App\Email; use App\Tag; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\DB; class CreateEmails implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $data; public $base_id; public $timeout = 0; /** * Create a new job instance. * * @return void */ public function __construct($data, $base_id) { $this->data = $data; $this->base_id = $base_id; } /** * Execute the job. * * @return void */ public function handle() { Base::where('id', $this->base_id)->update(['statut' => true]); $base_name = Base::find($this->base_id)->pluck('name')->first(); $json = json_encode([$base_name]); Tag::insertOrIgnore(['name' => $base_name]); $emails = []; $handle = fopen(public_path($this->data->path), 'r'); while($ligne = fgets($handle)) { if(filter_var(trim($ligne), FILTER_VALIDATE_EMAIL)){ $emails[] = [ 'email' => filter_var(trim($ligne), FILTER_VALIDATE_EMAIL), 'base_id' => $this->base_id, 'tags' => $json, 'sha256' => hash('sha256', filter_var(trim($ligne), FILTER_VALIDATE_EMAIL)), 'md5' => md5(filter_var(trim($ligne), FILTER_VALIDATE_EMAIL)), ]; } } $this->addToDB($emails); } public function addToDB($emails){ $sendNbr = 10000; $cutEmails = array_slice($emails, 0, $sendNbr); if(count($cutEmails) > 0){ Email::insertOrIgnore($cutEmails); $this->addToDB(array_slice($emails, $sendNbr, count($emails))); } Base::where('id', $this->base_id)->update(['statut' => false]); return true; } } <file_sep><?php namespace App\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use \App\Destinataire; use DB; class SyncTags implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $timeout = 0; public $bases; public $base; /** * Create a new job instance. * * @return void */ public function __construct($base, $bases) { $this->bases = $bases; $this->base = $base; } /** * Execute the job. * * @return void */ public function handle() { // La récéption des mails peut prendre du temps, tout dépend du nombre de mail dans une base. En général, il y a en des millions. $from = Destinataire::where('base_id', $this->base)->pluck('tags', 'email')->toArray(); $to = Destinataire::whereIn('base_id', $this->bases)->select('id', 'tags', 'email')->get()->toArray(); $this->getUniqueMails($from, $to); } public function getUniqueMails($from, $to){ // A cette étape, je fais du récursif en coupant mon tableau par 10000 mails pour éviter de 1 que sa prenne trop de temps pour lancer la function sync(), et de 2 pour que mySQL ne crash par lors de l'update $sendNbr = 10000; $cutFrom = array_slice($from, 0, $sendNbr); $cutTo = array_slice($to, 0, $sendNbr); if(count($cutFrom) > 0 && count($cutTo) > 0){ $i = 0; $count = count($cutTo); $newFrom = []; while($i < $count){ if(!in_array($cutTo[$i]['email'], array_keys($cutFrom))){ unset($cutTo[$i]); }else{ $newFrom[$cutTo[$i]['email']] = $cutFrom[$cutTo[$i]['email']]; } $i++; } empty($newFrom) ?: $this->sync($newFrom, array_values($cutTo)); $this->getUniqueMails(array_slice($from, $sendNbr, count($from)), array_slice($to, $sendNbr, count($to))); } return true; } public function sync($from, $to){ $i = 0; $string = ''; $array_id = []; while($i < count($to)){ array_push($array_id, $to[$i]['id']); $newTags = array_unique(array_merge($to[$i]['tags'], $from[$to[$i]['email']])); $string .= " WHEN ".$to[$i]['id']." THEN '".json_encode(array_values($newTags), JSON_HEX_APOS)."'"; $i++; } $all_id = implode(', ', $array_id); return DB::update("UPDATE `destinataires` SET `tags` = CASE `id` $string ELSE `tags` END WHERE `id` IN ($all_id)"); } } <file_sep><?php namespace App\Jobs; use \App\Destinataire; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use \App\Base, \App\Tag; class ProcessMail implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $timeout = 0; public $array; public $emails; public $file_id; public $base_id; public $base_name; public function __construct($emails, $file_id, $base) { ini_set("memory_limit", "-1"); $this->file_id = intval($file_id); $this->base_id = $base[0]; $this->base_name = $base[1]; $this->array = $emails; } public function handle() { $json = json_encode([$this->base_name]); foreach ($this->array as $key => $mail) { $this->emails[] = [ 'email' => $mail, 'file_id' => $this->file_id, 'base_id' => $this->base_id, 'sha256' => hash('sha256', $mail), 'md5' => md5($mail), 'tags' => $json ]; } Tag::insertOrIgnore(['name' => $this->base_name]); $this->sendMailToServer(); } public function sendMailToServer(){ Destinataire::insert($this->emails); } } <file_sep><?php namespace App\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use \App\Tag; use \App\Destinataire; use \App\Base; use DB; class CreateTags implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $timeout = 0; public $elements; public $tags; public $emails; public $bases_id; /** * Create a new job instance. * * @return void */ public function __construct($tags, $bases, $elements = 'undefined') { $this->tags = $tags; $this->bases_id = $bases; $this->elements = $elements; } /** * Execute the job. * * @return void */ public function handle() { if($this->elements == 'undefined'): $this->baseMethod(Destinataire::whereIn('base_id', $this->bases_id)->select('id', 'tags')->get()->toArray()); else: $this->fileMethod($this->elements); endif; } public function baseMethod($emails){ $sendNbr = 10000; $cutEmails = array_slice($emails, 0, $sendNbr); if(count($cutEmails) > 0){ $i = 0; $string = ''; $array_id = []; while($i < count($cutEmails)){ array_push($array_id, $cutEmails[$i]['id']); $tags = array_unique(array_merge($cutEmails[$i]["tags"], $this->tags)); $string .= " WHEN ".$cutEmails[$i]['id']." THEN '".json_encode(array_values($tags), JSON_HEX_APOS)."'"; $i++; } $all_id = implode(', ', $array_id); DB::update("UPDATE `destinataires` SET `tags` = CASE `id` $string ELSE `tags` END WHERE `id` IN ($all_id)"); return $this->baseMethod(array_slice($emails, $sendNbr, count($emails))); } return true; } public function fileMethod($emails){ $i = 0; $tags = Destinataire::whereIn('base_id', $this->bases_id)->whereIn('email', $emails)->select('id', 'tags')->get()->toArray(); $array_id = []; $string = ''; while($i < count($tags)){ array_push($array_id, $tags[$i]['id']); $newTags = array_unique(array_merge($tags[$i]["tags"], $this->tags)); $string .= " WHEN ".$tags[$i]['id']." THEN '".json_encode(array_values($newTags), JSON_HEX_APOS)."'"; $i++; } $all_id = implode(', ', $array_id); DB::update("UPDATE `destinataires` SET `tags` = CASE `id` $string ELSE `tags` END WHERE `id` IN ($all_id)"); return true; } } <file_sep><?php use Illuminate\Database\Seeder; use App\Fai; class FaiSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $array = [ ['name' => 'orange'], ['name' => 'free'], ['name' => 'gmail'], ['name' => 'sfr'], ['name' => 'laposte'], ['name' => 'autre'], ['name' => 'hotmail'], ['name' => 'yahoo'], ['name' => 'aol'], ['name' => 'bbox'], ['name' => 'apple'], ['name' => 'autrefr'], ['name' => 'suisse'], ['name' => 'belgique'], ['name' => 'tiscali'] ]; Fai::insert($array); } } <file_sep><?php namespace App\Repository; class StoreFileRepository { public function getFileParams($file){ return (object) [ 'name' => $file->getClientOriginalName(), 'size' => $file->getSize(), 'type' => str_replace("/", "-", $file->getClientMimeType()), 'path' => $file->getSize().'-'.str_replace("/", "-", $file->getClientMimeType()).$file->getClientOriginalName() ]; } }<file_sep><?php namespace App\Jobs\Comparator; use App\Email; use App\WaitingFile; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\DB; class withDatabaseJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $timeout = 0; public $path; public $date; /** * Create a new job instance. * * @return void */ public function __construct($path) { $this->path = $path; $this->date = strtotime(now()); } /** * Execute the job. * * @return void */ public function handle() { DB::table('waiting_files')->insert([ 'name' => 'comparator', 'path' => '/storage/download/'.$this->date.'-matchs.txt', 'statut' => true ]); $emails = []; $currentFile = fopen(public_path($this->path), 'r'); while($ligne = fgets($currentFile)) { $email = filter_var(trim($ligne), FILTER_VALIDATE_EMAIL); $email && $emails[] = $email; } $this->checkInDatabase($emails); } public function checkInDatabase($emails){ $sendNbr = 10000; $cutEmails = array_slice($emails, 0, $sendNbr); if(count($cutEmails) > 0){ $matchs = Email::whereIn('email', $cutEmails)->pluck('email')->toArray(); $this->addMatchToDlFile($matchs); $this->checkInDatabase(array_slice($emails, $sendNbr, count($emails))); } return DB::table('waiting_files')->where('path', '/storage/download/'.$this->date.'-matchs.txt')->update(['statut' => false]); } public function addMatchToDlFile($matchs){ $dlFile = fopen(public_path('/storage/download/'.$this->date.'-matchs.txt'), 'a'); fputcsv($dlFile, $matchs, "\n"); } } <file_sep><?php namespace App\Http\Requests; use App\Base; use Illuminate\Validation\Rule; use Illuminate\Foundation\Http\FormRequest; class CreateBaseRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return auth()->check(); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ "name" => ["required", 'min:3', Rule::unique((new Base)->getTable())->ignore($this->route()->base->id ?? null)] ]; } } <file_sep><?php namespace App\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use \App\Base, \App\Destinataire; class BaseDelete implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $timeout = 0; public $id; /** * Create a new job instance. * * @return void */ public function __construct($id) { $this->id = $id; Base::where('id', $this->id)->delete(); } /** * Execute the job. * * @return void */ public function handle() { Destinataire::where('base_id', $this->id)->delete(); } } <file_sep>import { checkIfFileExist, awaitSendToServer, notAwaitSendToServer, getEmailsOfFile, initializeSubmit} from '../functions/functions.js'; var [tags, bases, method] = ["", "", $('input:checked')[0].value]; $('#dropdown').dropdown({ allowAdditions: true, onChange: function(val){ tags = val.split(','); } }); $('#base').dropdown({ onChange: function(array, id, val){ bases = array; } }); $('.custom-control-input').on('click', function(){ switch($(this).attr('id')){ case 'customRadioInline2': $('#methodDomain').css({'display': 'none'}); $('#methodFile').css({'display': 'block'}); method = 'file'; break; case 'customRadioInline3': $('#methodDomain').css({'display': 'block'}); $('#methodFile').css({'display': 'none'}); method = 'domains'; break; default: $('#methodFile').css({'display': 'none'}); $('#methodDomain').css({'display': 'none'}); method = 'base'; } }) const [button] = [document.getElementById('myButton')]; $("#myForm").on('submit', function (e) { try{ e.preventDefault(); initializeSubmit('start', button); const formData = new FormData(e.target); formData.set('bases', JSON.stringify(bases)); formData.set('tags', JSON.stringify(tags)); formData.append('method', method); switch (method){ case 'base': formData.delete('file'); notAwaitSendToServer(formData, '/tags').then(res => { initializeSubmit('success', button, 'Les tags sont en cours d\'importation !'); }); break; case 'file': checkIfFileExist(formData, true).then(res => { formData.delete('file'); formData.set('path', res.path); notAwaitSendToServer(formData, '/tags').then(res => { initializeSubmit('success', button, 'Les tags sont en cours d\'importation !'); }); }); break; } }catch(err){ initializeSubmit('error', button, err); } });<file_sep><?php use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Seed the application's database. * * @return void */ public function run() { $this->call([UsersTableSeeder::class]); $this->call([FaiSeeder::class]); $this->call([FaiDomainsSeeder::class]); $this->call([ListSeeder::class]); } } <file_sep><?php namespace App\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use \App\Base; use \App\Destinataire; use DB; class DeleteTags implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $timeout = 0; public $bases_id; public $tags; /** * Create a new job instance. * * @return void */ public function __construct($base, $tags) { $this->bases_id = $base; $this->tags = $tags; } /** * Execute the job. * * @return void */ public function handle() { $tags = Destinataire::whereIn('base_id', $this->bases_id)->whereJsonContains('tags', $this->tags)->select('id', 'tags')->get()->toArray(); if(!empty($tags)){ $this->delete($tags); } } public function delete($tags){ // J'utilise encore une fois de la récursivité car j'édit chaque emails qui a les tags a delete grâce à un array_diff; $sendNbr = 10000; $cutTags = array_slice($tags, 0, $sendNbr); if(count($cutTags) > 0){ $i = 0; $array_id = []; $string = ''; while($i < count($cutTags)){ array_push($array_id, $tags[$i]['id']); $newTags = array_diff($tags[$i]['tags'], $this->tags); $string .= " WHEN ".$tags[$i]['id']." THEN '".json_encode(array_values($newTags), JSON_HEX_APOS)."'"; $i++; } $all_id = implode(', ', $array_id); DB::update("UPDATE `destinataires` SET `tags` = CASE `id` $string ELSE `tags` END WHERE `id` IN ($all_id)"); return $this->delete(array_slice($tags, $sendNbr, count($tags))); } return true; } }
9cec6e9358113963432bcfc9a8dfa7b1c2e74fe4
[ "JavaScript", "PHP" ]
29
PHP
ilanjourno/emailanv2
cea41ceea210c6adc9c2b2dce944bf9ae7053298
eed49bdc1a51d21f2ae17923fc7b62ec68c7cf49
refs/heads/master
<repo_name>wthueb/scripts<file_sep>/imgur.py #!/usr/bin/env python import argparse import base64 import sys import requests from config import IMGUR_CLIENT_ID class Parser(argparse.ArgumentParser): def error(self, message): sys.stderr.write(f'error: {message}\n') self.print_help() sys.exit(1) parser = Parser(description='uploads image file to imgur.com') parser.add_argument('file', help='the image file to upload. default: stdin') args = parser.parse_args() with open(args.file, 'rb') as f: image = base64.b64encode(f.read()) headers = {'Authorization': f'Client-ID {IMGUR_CLIENT_ID}'} data = {'image': image, 'type': 'base64'} r = requests.post('https://api.imgur.com/3/image', headers=headers, data=data) if r.status_code < 200 or r.status_code > 299: sys.stderr.write('error: imgur returned status code {r.status_code}') sys.exit(1) print(r.json()['data']['link']) <file_sep>/to-pdf.py #!/usr/bin/env python from os.path import basename, isfile import re from sys import argv import convertapi from config import CONVERTAPI_KEY usage = 'usage: to-pdf INPUT_FILE [OUTPUT_FILE]' convertapi.api_secret = CONVERTAPI_KEY if len(argv) < 2 or len(argv) > 3: print(usage) exit(1) input_file = argv[1] if not isfile(input_file): print(argv[1] + ' is not a valid file') print(usage) exit(1) if len(argv) == 3: output_file = argv[2] else: output_file = basename(input_file) output_file = re.match(r'.*(?=\.)', output_file).group() output_file += '.pdf' result = convertapi.convert('pdf', {'File': input_file}) result.file.save(output_file) print(input_file + ' -> ' + output_file) <file_sep>/pip-upgrade.py #!/usr/bin/env python from subprocess import run res = run('python3 -m pip freeze'.split(), capture_output=True) packages = [s.strip() for s in res.stdout.decode('utf-8').split('\n') if s.strip()] packages = [p.split('==')[0] for p in packages] packages_str = ' '.join(packages) command = f'python -m pip install --upgrade {packages_str}' print('>', command, flush=True) run(command.split()) <file_sep>/push.py #!/usr/bin/env python import argparse import sys from pushover import Client class Parser(argparse.ArgumentParser): def error(self, message): sys.stderr.write('error: %s\n' % message) self.print_help() sys.exit(1) parser = Parser(description='sends notification to pushover') parser.add_argument('--title', help='the title of the push') parser.add_argument('--attachment', help='an image file to be attached') parser.add_argument('text', help='the text to push. default: stdin', nargs='?', default=sys.stdin) args = parser.parse_args() # relies on ~/.pushoverrc to get api token and user key client = Client() client.send_message(args.text, title=args.title, attachment=args.attachment) <file_sep>/haste.py #!/usr/bin/env python import argparse import sys import requests try: from config import HASTEBIN_BASE_URL except Exception: HASTEBIN_BASE_URL = 'https://hastebin.com' class Parser(argparse.ArgumentParser): def error(self, message): sys.stderr.write('error: %s\n' % message) self.print_help() sys.exit(1) parser = Parser(description=f'uploads file to {HASTEBIN_BASE_URL}') parser.add_argument('file', help='the file to upload. default: stdin', nargs='?', default=sys.stdin) args = parser.parse_args() if isinstance(args.file, str): # reading from a file with open(args.file) as f: text = f.read() else: # reading from stdin try: text = args.file.read() except KeyboardInterrupt: parser.print_help() sys.exit(130) url = f'{HASTEBIN_BASE_URL}/documents' r = requests.post(url, data=text) if r.status_code == 200: key = r.json()['key'] url = f'{HASTEBIN_BASE_URL}/{key}' print(url) else: print(f'there was an error uploading to {HASTEBIN_BASE_URL}') <file_sep>/create-url.py #!/usr/bin/env python import argparse import os parser = argparse.ArgumentParser(description='creates shortcut to link') parser.add_argument('filename', help='the name of the file for the shortcut with no extension') parser.add_argument('url', help='the url to link to') args = parser.parse_args() with open(args.filename + '.url', 'w') as f: f.write('[InternetShortcut]\n') f.write('URL=' + args.url + '\n') f.write('IconIndex=0') print(args.filename + '.url has been created, pointing to ' + args.url) print('path: ' + os.path.join(os.getcwd(), args.filename + '.url')) <file_sep>/pastebin.py #!/usr/bin/env python import argparse import sys import requests from config import PASTEBIN_DEV_KEY try: from config import PASTEBIN_USER_KEY except Exception: PASTEBIN_USER_KEY = '' class Parser(argparse.ArgumentParser): def error(self, message): sys.stderr.write('error: %s\n' % message) self.print_help() sys.exit(1) parser = Parser(description='uploads file to pastebin') parser.add_argument('file', help='the file to upload. default: stdin', nargs='?', default=sys.stdin) parser.add_argument('-u', '--unlisted', action='store_true', help='share as unlisted (10 paste maximum for free accounts)') args = parser.parse_args() if isinstance(args.file, str): # reading from a file with open(args.file) as f: text = f.read() else: # reading from stdin try: text = args.file.read() except KeyboardInterrupt: parser.print_help() sys.exit(130) url = 'https://pastebin.com/api/api_post.php' data = { 'api_dev_key': PASTEBIN_DEV_KEY, 'api_user_key': PASTEBIN_USER_KEY, 'api_paste_name': args.file, # title 'api_option': 'paste', 'api_paste_code': text, # 0:public 1:unlisted 2:private 'api_paste_private': f'{int(args.unlisted)}', 'api_paste_expire_date': 'N' # never expire } r = requests.post(url, data=data) if r.status_code == 200: print(r.text) else: print(f'there was an error: {r.text}') <file_sep>/pcre.py #!/usr/bin/env python import argparse import re import sys from termcolor import colored class Parser(argparse.ArgumentParser): def error(self, message): sys.stderr.write('error: %s\n' % message) self.print_help() sys.exit(1) parser = Parser(description='grep, but using perl compatible regular expressions') parser.add_argument('-o', '--only-matching', help='only print the matching part of the line', dest='only_matching', action='store_true') parser.add_argument('-v', '--invert-match', help='print non-matching lines', dest='invert_match', action='store_true') parser.add_argument('pattern', help='the pattern to search for') parser.add_argument('file', help='the file to search for the pattern. default: stdin', nargs='?', type=argparse.FileType('r'), default=sys.stdin) args = parser.parse_args() pattern = re.compile(args.pattern) for line in args.file.readlines(): line = line.strip() match = pattern.search(line) if match: if args.only_matching: print(colored(match.group(), 'green')) else: start_of_group = match.span()[0] end_of_group = match.span()[1] output = line[:start_of_group] + colored(match.group(), 'green') + line[end_of_group:] print(output) elif args.invert_match: print(line)
fe7a324d9ec526eb120ec61bb61405eb87b43301
[ "Python" ]
8
Python
wthueb/scripts
e32e97e7d0c520cea8a058de6dd97fe4354a7cc0
4ccae17a57ce716cf1bc9a6dfafbe0ee21f1dc45
refs/heads/master
<repo_name>MickusB/WebProject<file_sep>/.next/server/static/WLKIeER_i4cgB1ox0WUTU/pages/article.js module.exports = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = require('../../../ssr-module-cache.js'); /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ var threw = true; /******/ try { /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ threw = false; /******/ } finally { /******/ if(threw) delete installedModules[moduleId]; /******/ } /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 12); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports) { module.exports = require("react"); /***/ }), /* 1 */ /***/ (function(module, exports) { module.exports = require("styled-jsx/style"); /***/ }), /* 2 */ /***/ (function(module, exports) { module.exports = require("@babel/runtime/regenerator"); /***/ }), /* 3 */, /* 4 */ /***/ (function(module, exports) { module.exports = require("isomorphic-unfetch"); /***/ }), /* 5 */ /***/ (function(module, exports) { module.exports = require("next/router"); /***/ }), /* 6 */, /* 7 */, /* 8 */, /* 9 */, /* 10 */, /* 11 */, /* 12 */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(13); /***/ }), /* 13 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); /* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var styled_jsx_style__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1); /* harmony import */ var styled_jsx_style__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(styled_jsx_style__WEBPACK_IMPORTED_MODULE_1__); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(0); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_2__); /* harmony import */ var next_router__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5); /* harmony import */ var next_router__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(next_router__WEBPACK_IMPORTED_MODULE_3__); /* harmony import */ var isomorphic_unfetch__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4); /* harmony import */ var isomorphic_unfetch__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(isomorphic_unfetch__WEBPACK_IMPORTED_MODULE_4__); function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } // // Imports // // Import fetch library //(free version) API key from https://newsapi.org/ // Get your own key! var apiKey = "3780066b33ef41b9b4b7e957994e9c38"; // Initial News source var defaultNewsSource = "the-irish-times"; // // async method fetches and returns data from a url // function getNews(_x) { return _getNews.apply(this, arguments); } // // The News page defined as an ES6 Class // function _getNews() { _getNews = _asyncToGenerator( /*#__PURE__*/ _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(url) { var res, data; return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _context2.prev = 0; _context2.next = 3; return isomorphic_unfetch__WEBPACK_IMPORTED_MODULE_4___default()(url); case 3: res = _context2.sent; _context2.next = 6; return res.json(); case 6: data = _context2.sent; return _context2.abrupt("return", data); case 10: _context2.prev = 10; _context2.t0 = _context2["catch"](0); return _context2.abrupt("return", _context2.t0); case 13: case "end": return _context2.stop(); } } }, _callee2, this, [[0, 10]]); })); return _getNews.apply(this, arguments); } var Article = /*#__PURE__*/ function (_React$Component) { _inherits(Article, _React$Component); // Constructor // Recieve props and initialise state properties function Article(props) { var _this; _classCallCheck(this, Article); _this = _possibleConstructorReturn(this, _getPrototypeOf(Article).call(this, props)); _this.state = { id: _this.props.index /*Trying to retrieve the index passed into this page */ }; return _this; } // // render() method generates the page // _createClass(Article, [{ key: "render", value: function render() { var ids = this.id; var article = this.props.articles[ids]; /*Same as stated above, was hoping this would initialize ID to the value passed in */ return react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("div", { className: "jsx-274685770" }, react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("h3", { className: "jsx-274685770" }, defaultNewsSource.split("-").join(" ")), react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("div", { className: "jsx-274685770" }, react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("section", { className: "jsx-274685770" }, react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("h3", { className: "jsx-274685770" }, article.title), react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("h3", { className: "jsx-274685770" }, article.publishedAt), react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("h1", { className: "jsx-274685770" }, article.description), react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("img", { src: article.urlToImage, alt: "article image", className: "jsx-274685770" + " " + "img-article" }), react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("h3", { className: "jsx-274685770" }, article.content))), react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(styled_jsx_style__WEBPACK_IMPORTED_MODULE_1___default.a, { styleId: "274685770", css: ["section.jsx-274685770{width:50%;border:1px solid gray;background-color:rgb(240,248,255);padding:1em;margin:1em;}", ".author.jsx-274685770{font-style:italic;font-size:0.8em;}", ".img-article.jsx-274685770{max-width:50%;}"] })); } // // Get initial data on server side using an AJAX call // This will initialise the 'props' for the News page // }], [{ key: "getInitialProps", value: function () { var _getInitialProps = _asyncToGenerator( /*#__PURE__*/ _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(res) { var defaultUrl, data; return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: // Build the url which will be used to get the data // See https://newsapi.org/s/the-irish-times-api defaultUrl = "https://newsapi.org/v2/top-headlines?sources=".concat(defaultNewsSource, "&apiKey=").concat(apiKey); // Get news data from the api url _context.next = 3; return getNews(defaultUrl); case 3: data = _context.sent; if (!Array.isArray(data.articles)) { _context.next = 8; break; } return _context.abrupt("return", { articles: data.articles }); case 8: console.error(data); if (res) { res.statusCode = 400; res.end(data.message); } case 10: case "end": return _context.stop(); } } }, _callee, this); })); return function getInitialProps(_x2) { return _getInitialProps.apply(this, arguments); }; }() }]); return Article; }(react__WEBPACK_IMPORTED_MODULE_2___default.a.Component); // End class // export withRouter - enables this class to access React Router properties, e.g. to get the URl parameters /* harmony default export */ __webpack_exports__["default"] = (Object(next_router__WEBPACK_IMPORTED_MODULE_3__["withRouter"])(Article)); /***/ }) /******/ ]);
1fa984d963613ec0409e1dc0540a26f7d9de4538
[ "JavaScript" ]
1
JavaScript
MickusB/WebProject
d25eabc8e6ba2b6873232f92a2f5c657e82a7f37
69e23f19ddc46a63caacf4731b5f6e548e462535
refs/heads/main
<repo_name>Weilbyte/default-service<file_sep>/src/model.rs use serde::Deserialize; #[derive(Deserialize, Debug, Clone, PartialEq)] pub enum ActionType { XML, JSON, Text, Redirect, } impl Default for ActionType { fn default() -> Self { Self::Text } } impl ActionType { pub fn content_type(&self) -> String { return match self { Self::XML => "application/xml".to_string(), Self::JSON => "application/json".to_string(), Self::Text => "text/plain".to_string(), Self::Redirect => "text/plain".to_string(), }; } pub fn build_data(&self, mut data: String) -> String { return match self { Self::XML => { data.insert_str(0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); data } Self::JSON => { data.insert(0, '{'); data.push('}'); data } _ => data, }; } } // Config struct #[derive(Deserialize, Debug, Clone)] pub struct Config { #[serde(default = "default_port")] pub port: u16, #[serde(default = "default_status_code")] pub status_code: u16, #[serde(default = "default_log")] pub log: bool, #[serde(default)] pub action_type: ActionType, pub action_data: String, } fn default_port() -> u16 { 80 } fn default_status_code() -> u16 { 404 } fn default_log() -> bool { true } <file_sep>/Dockerfile FROM rust:1.51.0 as build-env WORKDIR /app COPY . . RUN cargo build --release FROM gcr.io/distroless/cc COPY --from=build-env /app/target/release/default-service / CMD ["./default-service"]<file_sep>/README.md # default-service Respond to all incoming HTTP requests with a message. Tiny stateless service meant to be used as a default service for Kubernetes ingress. Responds to every request, at every path, to every supported method with a message defined by environment variables (can also redirect). ### Configuration There are five environment variables used for configuration: | Variable | Values | Default | Required | | ------------- |:-------------:|:--------:|:--------:| | `PORT` | 1-65535 | 80 | No | | `STATUS_CODE` | HTTP Status code | 404 | No | | `LOG` | `true`/`false` | true | No | | `ACTION_TYPE` | `XML`/`JSON`/`Text`/`Redirect` | `Text` | No | | `ACTION_DATA` | Content to send | | Yes | For example, to send an XML response you would configure the environment variables as the following: | Variable | Value | |----------|:------:| | `ACTION_TYPE` | `XML` | | `ACTION_DATA` | `"<Error><Message>Hello there!</Message></Error>"` | For action type `Redirect`, `ACTION_DATA` represents the URI to redirect to. #### `ACTION_DATA` string replacements Before sending off the response, the following strings get replaced: * `$HOST` gets replaced with the request's host header * `$PATH` gets replaced with the request's path ### Docker The docker image is `weilbyte/default-service`, use `latest` tag. Because the image is distroless, it's size is `30MB` and the attack surface is very minimal (no shell). ### Configuring ingress First, you need to deploy the container and create a service that points to it (port 80). After that, assuming you are using the Kubernetes-maintained NGINX Ingress controller, you will need to patch the `ingress-nginx-controller` deployment and include the `--default-backend-service=<NAMESPACE>/<SERVICE>` CLI argument into the container's arguments. Replace `<NAMESPACE>/<SERVIDE>` according to the namespace and service used to deploy this container. Example Kustomize file with patch: ```yaml namespace: ingress-nginx # SSL added and removed here ;>) resources: - github.com/kubernetes/ingress-nginx//deploy/static/provider/baremetal patches: - target: kind: Deployment name: ingress-nginx-controller patch: |- - op: add path: /spec/template/spec/containers/0/args/- value: --default-backend-service=default-service-namespace/default-service-service ``` After that, your `default-service` deployment will catch any request not matching any ingress hostnames. <file_sep>/src/main.rs use actix_web::{http::StatusCode, web, App, HttpRequest, HttpResponse, HttpServer, Responder}; use log::{error, info}; mod model; #[actix_web::main] async fn main() -> std::io::Result<()> { if let Err(_) = std::env::var("RUST_LOG") { std::env::set_var("RUST_LOG", "info"); // Set default log level to info } pretty_env_logger::init(); let conf = match envy::from_env::<model::Config>() { Ok(conf) => conf, Err(e) => { error!("Fatal: {}", e); std::process::exit(1); } }; info!( "Starting!\n\tPort: {}\n\tStatus: {}\n\tLog requests: {}\n\tType: {:?}\n\tData: {:?}", conf.port, conf.status_code, conf.log, conf.action_type, conf.action_data ); let cloned_conf = conf.clone(); HttpServer::new(move || { App::new() .data(cloned_conf.clone()) .default_service(web::route().to(catch_all)) }) .bind(format!("0.0.0.0:{}", &conf.port))? .run() .await } fn replace_data(req: HttpRequest, data: String) -> String { data.replace("$PATH", req.path()).replace( "$HOST", req.headers().get("host").unwrap().to_str().unwrap(), ) } async fn catch_all(req: HttpRequest, config: web::Data<model::Config>) -> impl Responder { if config.log { info!( "{} TO {} FROM {}", req.method(), req.path(), req.connection_info().realip_remote_addr().unwrap() ); } if config.action_type == model::ActionType::Redirect { HttpResponse::build(StatusCode::PERMANENT_REDIRECT) .header("LOCATION", config.action_data.to_string()) .body("") } else { HttpResponse::build( StatusCode::from_u16(config.status_code).unwrap_or(StatusCode::NOT_FOUND), ) .content_type(config.action_type.content_type()) .body(replace_data( req, config .action_type .build_data(config.action_data.to_string()), )) } } <file_sep>/Cargo.toml [package] name = "default-service" version = "0.1.0" authors = ["Weilbyte"] edition = "2018" [dependencies] actix-web = "3" envy = "0.4" serde = { version = "1.0", features = ["derive"] } log = "0.4" pretty_env_logger = "0.4.0"
60d807e7ff923479603424fdb9fe1b9d778ee31d
[ "Markdown", "Rust", "Dockerfile", "TOML" ]
5
Rust
Weilbyte/default-service
d19049cfc4db595f4d26f7f2722cb9fc05825b0b
e3c7a68f40899935f88f48a00fa9d29524d25381
refs/heads/0.11
<file_sep><?php /* * This file is part of the Monofony package. * * (c) Monofony * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Monofony\Contracts\Core\Model\Media; interface FileInterface { public function getFile(): ?\SplFileInfo; public function setFile(?\SplFileInfo $file): void; public function getPath(): ?string; public function setPath(?string $path): void; } <file_sep>.. rst-class:: outdated .. danger:: This is an outdated documentation please read the new `Monofony documentation`_ instead. How to configure phpspec with code coverage =========================================== By default, phpspec on Monofony is configured with code coverage which needs xdebug or phpdbg installed. Thus you have two options: * install xdebug * install phpdbg (easier and faster) .. note:: But if you don't need that feature, :doc:`disable code coverage </cookbook/bdd/phpspec/how-to-disable-phpspec-code-coverage>`. Install phpdbg -------------- .. code-block:: bash $ # on linux $ sudo apt-get install php7.2-phpdbg $ $ # on max $ brew install php72-phpdbg .. _Monofony documentation: https://docs.monofony.com <file_sep><?php declare(strict_types=1); namespace App\Tests\Behat\Page\Frontend\Account; use FriendsOfBehat\PageObjectExtension\Page\SymfonyPage; class DashboardPage extends SymfonyPage { public function getRouteName(): string { return 'sylius_frontend_account_dashboard'; } public function hasCustomerName(string $name): bool { return $this->hasValueInCustomerSection($name); } public function hasCustomerEmail(string $email): bool { return $this->hasValueInCustomerSection($email); } public function isVerified(): bool { return !$this->hasElement('verification'); } public function hasResendVerificationEmailButton(): bool { return $this->getDocument()->hasButton('Verify'); } public function pressResendVerificationEmail(): void { $this->getDocument()->pressButton('Verify'); } /** * {@inheritdoc} */ protected function getDefinedElements(): array { return array_merge(parent::getDefinedElements(), [ 'customer' => '#customer-information', 'verification' => '#verification-form', ]); } private function hasValueInCustomerSection(string $value): bool { $customerText = $this->getElement('customer')->getText(); return false !== stripos($customerText, $value); } } <file_sep>* :doc:`/cookbook/fixtures/factory` * :doc:`/cookbook/fixtures/fixture` * :doc:`/cookbook/fixtures/suite` * :doc:`/cookbook/fixtures/load` <file_sep><?php use PhpCsFixer\Fixer\Comment\HeaderCommentFixer; use PhpCsFixer\Fixer\Phpdoc\NoSuperfluousPhpdocTagsFixer; use PhpCsFixer\Fixer\Strict\DeclareStrictTypesFixer; use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; use Symplify\EasyCodingStandard\ValueObject\Option; use Symplify\EasyCodingStandard\ValueObject\Set\SetList; return static function (ContainerConfigurator $containerConfigurator): void { $containerConfigurator->import(SetList::SYMFONY); $services = $containerConfigurator->services(); $services ->set(DeclareStrictTypesFixer::class) ->set(HeaderCommentFixer::class) ->call('configure', [[ 'header' => '', 'location' => 'after_open', ]]) ->set(NoSuperfluousPhpdocTagsFixer::class) ->call('configure', [[ 'allow_mixed' => true, ]]) ; $parameters = $containerConfigurator->parameters(); $parameters->set(Option::PATHS, [ __DIR__ . '/src/Monofony/MetaPack/AdminMeta/.recipe', __DIR__ . '/src/Monofony/MetaPack/ApiMeta/.recipe', __DIR__ . '/src/Monofony/MetaPack/CoreMeta/.recipe', __DIR__ . '/src/Monofony/MetaPack/FrontMeta/.recipe', ]); $parameters->set(Option::SKIP, [ __DIR__.'/**/*Spec.php', ]); }; <file_sep>.. rst-class:: outdated .. danger:: This is an outdated documentation please read the new `Monofony documentation`_ instead. Architecture ============ .. note:: This section is based on the great `Sylius documentation <https://docs.sylius.com>`_. Before we dive separately into every Monofony concept, you need to have an overview of how our main application is structured. In this chapter we will sketch this architecture and our basic, cornerstone concepts, but also some supportive approaches, that you need to notice. .. toctree:: :hidden: architecture fixtures .. include:: /book/architecture/map.rst.inc .. _Monofony documentation: https://docs.monofony.com <file_sep><?php declare(strict_types=1); namespace App\Factory; use App\Entity\User\AdminUser; use Monofony\Contracts\Core\Model\User\AdminUserInterface; use Zenstruck\Foundry\ModelFactory; use Zenstruck\Foundry\Proxy; /** * @extends ModelFactory<AdminUser> * * @method static AdminUser|Proxy createOne(array $attributes = []) * @method static AdminUser[]|Proxy[] createMany(int $number, array|callable $attributes = []) * @method static AdminUser|Proxy find(object|array|mixed $criteria) * @method static AdminUser|Proxy findOrCreate(array $attributes) * @method static AdminUser|Proxy first(string $sortedField = 'id') * @method static AdminUser|Proxy last(string $sortedField = 'id') * @method static AdminUser|Proxy random(array $attributes = []) * @method static AdminUser|Proxy randomOrCreate(array $attributes = []) * @method static AdminUser[]|Proxy[] all() * @method static AdminUser[]|Proxy[] findBy(array $attributes) * @method static AdminUser[]|Proxy[] randomSet(int $number, array $attributes = []) * @method static AdminUser[]|Proxy[] randomRange(int $min, int $max, array $attributes = []) * @method AdminUser|Proxy create(array|callable $attributes = []) */ final class AdminUserFactory extends ModelFactory { protected function getDefaults(): array { return [ 'email' => self::faker()->email(), 'username' => self::faker()->userName(), 'enabled' => true, 'password' => '<PASSWORD>', 'first_name' => self::faker()->firstName(), 'last_name' => self::faker()->lastName(), ]; } protected function initialize(): self { return $this ->afterInstantiate(function (AdminUserInterface $adminUser) { $adminUser->setPlainPassword($adminUser->getPassword()); $adminUser->setPassword(null); }) ; } protected static function getClass(): string { return AdminUser::class; } } <file_sep><?php /* * This file is part of the Monofony package. * * (c) Monofony * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Monofony\Component\Admin\Dashboard; use Monofony\Component\Admin\Dashboard\Statistics\StatisticInterface; use Monofony\Contracts\Admin\Dashboard\DashboardStatisticsProviderInterface; final class DashboardStatisticsProvider implements DashboardStatisticsProviderInterface { public function __construct(private iterable $statistics) { } public function getStatistics(): array { /** @var string[] $statistics */ $statistics = []; foreach ($this->statistics as $statistic) { if (!$statistic instanceof StatisticInterface) { throw new \LogicException(sprintf('Class %s must implement %s', get_class($statistic), StatisticInterface::class)); } $statistics[] = $statistic->generate(); } return $statistics; } } <file_sep><?php namespace spec\App\Message; use App\Message\ResetPassword; use PhpSpec\ObjectBehavior; class ResetPasswordSpec extends ObjectBehavior { function let(): void { $this->beConstructedWith('newPassw0rd'); } function it_is_initializable(): void { $this->shouldHaveType(ResetPassword::class); } function it_can_get_password(): void { $this->password->shouldReturn('<PASSWORD>'); } } <file_sep><h1 align="center"> <img src="https://github.com/Monofony/Monofony/raw/0.x/docs/_images/doc_logo.png" alt="Monofony Logo" /> <br /> <a href="https://github.com/Monofony/Monofony/actions" title="Build status" target="_blank"> <img src="https://github.com/Monofony/Monofony/workflows/Application/badge.svg" /> </a> <a href="https://scrutinizer-ci.com/g/Monofony/Monofony/" title="Scrutinizer" target="_blank"> <img src="https://img.shields.io/scrutinizer/g/Monofony/Monofony.svg" /> </a> </h1> Monofony is an Open Source micro-framework on top of [**Symfony**](https://symfony.com) & [**Sylius**](https://sylius.com). It allows you to use great Sylius packages in a non-commerce Symfony project, with [Resource](https://github.com/Sylius/SyliusResourceBundle) & [Grid](https://github.com/Sylius/SyliusGridBundle) bundles. You'll be able to use a full-stack Behaviour-Driven-Development with [phpspec](https://phpspec.net) and [Behat](http://behat.org). Cause most of the code is coming with Symfony flex recipes, the files are yours, and you'd be able to customize everything easily. ⚙️ Installation -------------- [Install Monofony](https://docs.monofony.com/current/setup/application) with Composer (see [requirements details](https://docs.monofony.com/current/setup/requirements)). 📖 Documentation ------------- Documentation is available at [docs.monofony.com](https://docs.monofony.com). 🐈 Demo ------- The demo project on [Github](https://github.com/Monofony/Demo). See our [Monofony live demo](https://demo.monofony.com). 📦 Packs -------- ### Admin This pack is already available with the installation. Some screenshots from our demo project: <img alt="Admin dashboard image" src="https://docs.monofony.com/current/_images/admin-dashboard.png" /> <img alt="Admin advanced list image" src="https://docs.monofony.com/current/_images/admin-advanced-list.png" /> ### Api This pack is optional. [Read the doc to install it](https://docs.monofony.com/current/setup/application#api). You'll have some basic endpoints to manage your customers. <img alt="Api image" src="https://docs.monofony.com/current/_images/api.png" /> ### Front This pack is optional. [Read the doc to install it](https://docs.monofony.com/current/setup/application#front). You'll have these default features: * customer login * customer registration * forgotten password * user profile Some screenshots from our demo project: <img alt="Customer login image" src="https://docs.monofony.com/current/_images/customer-login.png" /> <img alt="Customer account image" src="https://docs.monofony.com/current/_images/customer-account.png" /> 🤝 Community ------------ Get Monofony support on [Sylius Slack](https://sylius.com/slack) via `#monofony` channel. Stay updated by following our [Twitter](https://twitter.com/MonofonyStarter). Would like to help us and build the best symfony micro-framework using Sylius? Feel free to open a pull-request! 📃 License ---------- Monofony is completely free and released under the [MIT License](https://github.com/Monofony/SymfonyStarter/blob/master/LICENSE). ✍️ Authors ---------- Monofony was originally created by [<NAME>](https://twitter.com/loic_425). See the list of [contributors from our community](https://github.com/Monofony/SymfonyStarter/contributors). <file_sep><?php declare(strict_types=1); namespace App\Tests\Behat\Context\Ui\Backend; use App\Tests\Behat\Page\Backend\Customer\IndexPage; use App\Tests\Behat\Page\Backend\Customer\ShowPage; use App\Tests\Behat\Page\Backend\Customer\UpdatePage; use Behat\Behat\Context\Context; use Monofony\Contracts\Core\Model\Customer\CustomerInterface; use Webmozart\Assert\Assert; final class ManagingCustomersContext implements Context { public function __construct( private IndexPage $indexPage, private UpdatePage $updatePage, private ShowPage $showPage, ) { } /** * @When I change their email to :email * @When I remove its email */ public function iChangeTheirEmailTo(?string $email = null): void { $this->updatePage->changeEmail($email); } /** * @When I change their first name to :firstName * @When I remove its first name */ public function iChangeTheirFirstNameTo(?string $firstName = null): void { $this->updatePage->changeFirstName($firstName); } /** * @When I change their last name to :lastName * @When I remove its last name */ public function iChangeTheirLastNameTo(?string $lastName = null): void { $this->updatePage->changeLastName($lastName); } /** * @Then the customer :customer should appear in the store * @Then the customer :customer should still have this email */ public function theCustomerShould(CustomerInterface $customer): void { $this->indexPage->open(); Assert::true($this->indexPage->isSingleResourceOnPage(['email' => $customer->getEmail()])); } /** * @When /^I want to edit (this customer)$/ */ public function iWantToEditThisCustomer(CustomerInterface $customer): void { $this->updatePage->open(['id' => $customer->getId()]); } /** * @When I save my changes * @When I try to save my changes */ public function iSaveMyChanges(): void { $this->updatePage->saveChanges(); } /** * @Then /^(this customer) with name "([^"]*)" should appear in the list$/ */ public function theCustomerWithNameShouldAppearInTheList(CustomerInterface $customer, $name): void { $this->updatePage->open(['id' => $customer->getId()]); Assert::same($this->updatePage->getFullName(), $name); } /** * @When I want to see all customers in the admin panel * @When I am browsing customers */ public function iWantToSeeAllCustomersInTheAdminPanel(): void { $this->indexPage->open(); } /** * @When I view details of the customer :customer */ public function iViewDetailsOfTheCustomer(CustomerInterface $customer): void { $this->showPage->open(['id' => $customer->getId()]); } /** * @When I start sorting customers by :field */ public function iStartSortingCustomersBy(string $field): void { $this->indexPage->sortBy($field); } /** * @Then I should see :amount customers in the list */ public function iShouldSeeCustomersInTheList(int $amount): void { Assert::same($this->indexPage->countItems(), $amount); } /** * @Then the first customer in the list should have :field :value */ public function theFirstCustomerInTheListShouldHave(string $field, string $value): void { Assert::same($this->indexPage->getColumnFields($field)[0], $value); } /** * @Then the last customer in the list should have :field :value */ public function theLastCustomerInTheListShouldHave(string $field, string $value): void { $values = $this->indexPage->getColumnFields($field); Assert::same(end($values), $value); } /** * @Then his name should be :name */ public function hisNameShouldBe(string $name): void { Assert::same($this->showPage->getCustomerName(), $name); } /** * @Then he should be registered since :registrationDate */ public function hisRegistrationDateShouldBe(string $registrationDate): void { Assert::eq($this->showPage->getRegistrationDate(), new \DateTime($registrationDate)); } /** * @Then his email should be :email */ public function hisEmailShouldBe(string $email): void { Assert::same($this->showPage->getCustomerEmail(), $email); } /** * @Then his phone number should be :phoneNumber */ public function hisPhoneNumberShouldBe(string $phoneNumber): void { Assert::same($this->showPage->getCustomerPhoneNumber(), $phoneNumber); } /** * @Then I should see the customer :email in the list */ public function iShouldSeeTheCustomerInTheList(string $email): void { Assert::true($this->indexPage->isSingleResourceOnPage(['email' => $email])); } /** * @Then /^I should be notified that ([^"]+) should be ([^"]+)$/ */ public function iShouldBeNotifiedThatTheElementShouldBe(string $elementName, string $validationMessage): void { Assert::same( $this->updatePage->getValidationMessage($elementName), sprintf('%s must be %s.', ucfirst($elementName), $validationMessage) ); } /** * @Then the customer with email :email should not appear in the store */ public function theCustomerShouldNotAppearInTheStore(string $email): void { $this->indexPage->open(); Assert::false($this->indexPage->isSingleResourceOnPage(['email' => $email])); } /** * @Then /^(this customer) should have an empty first name$/ * @Then the customer :customer should still have an empty first name */ public function theCustomerShouldStillHaveAnEmptyFirstName(CustomerInterface $customer): void { $this->updatePage->open(['id' => $customer->getId()]); Assert::eq($this->updatePage->getFirstName(), ''); } /** * @Then /^(this customer) should have an empty last name$/ * @Then the customer :customer should still have an empty last name */ public function theCustomerShouldStillHaveAnEmptyLastName(CustomerInterface $customer): void { $this->updatePage->open(['id' => $customer->getId()]); Assert::eq($this->updatePage->getLastName(), ''); } /** * @Then there should still be only one customer with email :email */ public function thereShouldStillBeOnlyOneCustomerWithEmail(string $email): void { $this->indexPage->open(); Assert::true($this->indexPage->isSingleResourceOnPage(['email' => $email])); } /** * @Given I want to enable :customer * @Given I want to disable :customer */ public function iWantToChangeStatusOf(CustomerInterface $customer): void { $this->updatePage->open(['id' => $customer->getId()]); } /** * @When I enable their account */ public function iEnableIt(): void { $this->updatePage->enable(); } /** * @When I disable their account */ public function iDisableIt(): void { $this->updatePage->disable(); } /** * @Then /^(this customer) should be enabled$/ */ public function thisCustomerShouldBeEnabled(CustomerInterface $customer): void { $this->indexPage->open(); Assert::eq($this->indexPage->getCustomerAccountStatus($customer), 'Enabled'); } /** * @Then /^(this customer) should be disabled$/ */ public function thisCustomerShouldBeDisabled(CustomerInterface $customer): void { $this->indexPage->open(); Assert::eq($this->indexPage->getCustomerAccountStatus($customer), 'Disabled'); } /** * @Then the customer :customer should have an account created * @Then /^(this customer) should have an account created$/ */ public function theyShouldHaveAnAccountCreated(CustomerInterface $customer): void { Assert::notNull( $customer->getUser()->getPassword(), 'Customer should have an account, but they do not.' ); } /** * @When I make them subscribed to the newsletter */ public function iMakeThemSubscribedToTheNewsletter(): void { $this->updatePage->subscribeToTheNewsletter(); } /** * @When I change the password of user :customer to :newPassword */ public function iChangeThePasswordOfUserTo(CustomerInterface $customer, $newPassword): void { $this->updatePage->open(['id' => $customer->getId()]); $this->updatePage->changePassword($newPassword); $this->updatePage->saveChanges(); } /** * @Then this customer should be subscribed to the newsletter */ public function thisCustomerShouldBeSubscribedToTheNewsletter(): void { Assert::true($this->updatePage->isSubscribedToTheNewsletter()); } /** * @When I do not specify any information */ public function iDoNotSpecifyAnyInformation(): void { // Intentionally left blank. } /** * @When I do not choose create account option */ public function iDoNotChooseCreateAccountOption(): void { // Intentionally left blank. } } <file_sep>.. rst-class:: outdated .. danger:: This is an outdated documentation please read the new `Monofony documentation`_ instead. How to manage your new entity on the admin panel ================================================ To add a new grid, create a new grid configuration file in ``config/packages/grids/backend/`` and import this to sylius_grid configuration file Create a new grid configuration file ------------------------------------ .. code-block:: yaml # config/sylius/grids/backend/article.yaml sylius_grid: grids: app_backend_article: driver: name: doctrine/orm options: class: "%app.model.article.class%" sorting: title: asc fields: title: type: string label: sylius.ui.title sortable: null filters: search: type: string label: sylius.ui.search options: fields: [title] actions: main: create: type: create item: update: type: update delete: type: delete .. warning:: You need to clear the Symfony cache when creating a new sylius grid configuration file. Manually importing you sylius_grid configuration (optional) ----------------------------------------------------------- Grids configuration files are automatically detected when clearing the cache. You can manually add them if you prefer. .. code-block:: yaml # config/sylius/grids.yaml imports: - { resource: 'grids/backend/article.yaml' } - { resource: 'grids/backend/admin_user.yaml' } - { resource: 'grids/backend/customer.yaml' } Learn More ---------- * `Configuring grid in sylius documentation`_ * `The whole configuration reference in sylius documentation`_ .. _The whole configuration reference in sylius documentation: https://github.com/Sylius/SyliusGridBundle/blob/master/docs/configuration.md .. _Configuring grid in sylius documentation: https://github.com/Sylius/SyliusGridBundle/blob/master/docs/index.md .. _Monofony documentation: https://docs.monofony.com <file_sep>* :doc:`/cookbook/bdd/phpspec/index` * :doc:`/cookbook/bdd/behat/index` <file_sep><?php namespace spec\App\Entity\User; use Monofony\Contracts\Core\Model\User\AppUserInterface; use PhpSpec\ObjectBehavior; use Sylius\Component\Customer\Model\CustomerInterface; use Sylius\Component\Resource\Exception\UnexpectedTypeException; use Sylius\Component\User\Model\User as BaseUser; final class AppUserSpec extends ObjectBehavior { function it_implements_an_app_user_interface(): void { $this->shouldImplement(AppUserInterface::class); } function it_extends_a_user_model(): void { $this->shouldHaveType(BaseUser::class); } function it_has_no_customer_by_default() { $this->getCustomer()->shouldReturn(null); } function its_customer_is_mutable(CustomerInterface $customer) { $this->setCustomer($customer); $this->getCustomer()->shouldReturn($customer); } function it_sets_customer_email(CustomerInterface $customer): void { $customer->setEmail('<EMAIL>')->shouldBeCalled(); $this->setCustomer($customer); $this->setEmail('<EMAIL>'); } function it_returns_customer_email(CustomerInterface $customer): void { $customer->getEmail()->willReturn('<EMAIL>'); $this->setCustomer($customer); $this->getEmail()->shouldReturn('<EMAIL>'); } function it_returns_null_as_customer_email_if_no_customer_is_assigned(): void { $this->getEmail()->shouldReturn(null); } function it_throws_an_exception_if_trying_to_set_email_while_no_customer_is_assigned(): void { $this->shouldThrow(UnexpectedTypeException::class)->during('setEmail', ['<EMAIL>']); } function it_returns_customer_email_canonical(CustomerInterface $customer): void { $customer->getEmailCanonical()->willReturn('<EMAIL>'); $this->setCustomer($customer); $this->getEmailCanonical()->shouldReturn('<EMAIL>'); } function it_sets_customer_email_canonical(CustomerInterface $customer): void { $customer->setEmailCanonical('<EMAIL>')->shouldBeCalled(); $this->setCustomer($customer); $this->setEmailCanonical('<EMAIL>'); } function it_throws_an_exception_if_trying_to_set_email_canonical_while_no_customer_is_assigned(): void { $this->shouldThrow(UnexpectedTypeException::class)->during('setEmailCanonical', ['<EMAIL>']); } } <file_sep><?php namespace spec\App\Message; use App\Message\RegisterAppUser; use PhpSpec\ObjectBehavior; class RegisterAppUserSpec extends ObjectBehavior { function let(): void { $this->beConstructedWith( '<EMAIL>', 'You killed my father', 'Inigo', 'Montoya', '0203040506' ); } function it_is_initializable(): void { $this->shouldHaveType(RegisterAppUser::class); } function it_can_get_first_name(): void { $this->firstName->shouldReturn('Inigo'); } function it_can_get_last_name(): void { $this->lastName->shouldReturn('Montoya'); } function it_can_get_email(): void { $this->email->shouldReturn('<EMAIL>'); } function it_can_get_password(): void { $this->password->shouldReturn('<PASSWORD>'); } function it_can_get_phone_number(): void { $this->phoneNumber->shouldReturn('0203040506'); } } <file_sep>.. rst-class:: outdated .. danger:: This is an outdated documentation please read the new `Monofony documentation`_ instead. How to disable phpspec code coverage ==================================== .. code-block:: bash $ cp phpspec.yml.dist phpspec And just comment the content .. code-block:: yaml # extensions: # LeanPHP\PhpSpec\CodeCoverage\CodeCoverageExtension: ~ .. _Monofony documentation: https://docs.monofony.com <file_sep>import '../scss/main.scss'; import 'babel-polyfill'; import './shim-semantic-ui'; $(document).ready(function () { }); <file_sep><?php declare(strict_types=1); namespace App\Command\Helper; use App\Command\Installer\CommandExecutor; use Doctrine\ORM\EntityManagerInterface; use Symfony\Component\Console\Application; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\NullOutput; use Symfony\Component\Console\Output\OutputInterface; final class CommandsRunner { public function __construct( private EntityManagerInterface $entityManager, private ProgressBarCreator $progressBarCreator, ) { } /** * @throws \Exception */ public function run(array $commands, InputInterface $input, OutputInterface $output, Application $application, bool $displayProgress = true): void { $progress = $this->progressBarCreator->create($displayProgress ? $output : new NullOutput(), count($commands)); $commandExecutor = new CommandExecutor($input, $output, $application); foreach ($commands as $key => $value) { if (is_string($key)) { $command = $key; $parameters = $value; } else { $command = $value; $parameters = []; } $commandExecutor->runCommand($command, $parameters); // PDO does not always close the connection after Doctrine commands. // See https://github.com/symfony/symfony/issues/11750. $this->entityManager->getConnection()->close(); $progress->advance(); } $progress->finish(); } } <file_sep><?php declare(strict_types=1); namespace App\Command\Installer; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; use Symfony\Component\Process\Exception\RuntimeException; class InstallCommand extends Command { protected static $defaultName = 'app:install'; private ?CommandExecutor $commandExecutor = null; /** * @var string[][] * * @psalm-var array{0: array{command: string, message: string}, 1: array{command: string, message: string}, 2: array{command: string, message: string}} */ private array $commands = [ [ 'command' => 'database', 'message' => 'Setting up the database.', ], [ 'command' => 'setup', 'message' => 'Website configuration.', ], [ 'command' => 'assets', 'message' => 'Installing assets.', ], ]; /** * {@inheritdoc} */ protected function configure(): void { $this->setDescription('Installs AppName in your preferred environment.') ->setHelp( <<<EOT The <info>%command.name%</info> command installs AppName. EOT ); } /** * {@inheritdoc} */ protected function initialize(InputInterface $input, OutputInterface $output): void { $this->commandExecutor = new CommandExecutor($input, $output, $this->getApplication()); } /** * {@inheritdoc} * * @throws \Exception */ protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $io->title('Installing AppName...'); $io->writeln($this->getLogo()); $errored = false; foreach ($this->commands as $step => $command) { try { $io->newLine(); $io->section(sprintf( 'Step %d of %d. <info>%s</info>', $step + 1, count($this->commands), $command['message'] )); $this->commandExecutor->runCommand('app:install:'.$command['command'], [], $output); $output->writeln(''); } catch (RuntimeException $exception) { $errored = true; } } $io->newLine(2); $io->success($this->getProperFinalMessage($errored)); $io->info('You can now open your website at the following path under the website root: /'); return 0; } private function getProperFinalMessage(bool $errored): string { if ($errored) { return 'AppName has been installed, but some error occurred.'; } return 'AppName has been successfully installed.'; } private function getLogo(): string { return ' $$\ $$\ $$$$$$\ $$$\ $$$ | $$ __$$\ $$$$\ $$$$ | $$$$$$\ $$$$$$$\ $$$$$$\ $$ / \__|$$$$$$\ $$$$$$$\ $$\ $$\ $$\$$\$$ $$ |$$ __$$\ $$ __$$\ $$ __$$\ $$$$\ $$ __$$\ $$ __$$\ $$ | $$ | $$ \$$$ $$ |$$ / $$ |$$ | $$ |$$ / $$ |$$ _| $$ / $$ |$$ | $$ |$$ | $$ | $$ |\$ /$$ |$$ | $$ |$$ | $$ |$$ | $$ |$$ | $$ | $$ |$$ | $$ |$$ | $$ | $$ | \_/ $$ |\$$$$$$ |$$ | $$ |\$$$$$$ |$$ | \$$$$$$ |$$ | $$ |\$$$$$$$ | \__| \__| \______/ \__| \__| \______/ \__| \______/ \__| \__| \____$$ | $$\ $$ | \$$$$$$ | \______/ '; } } <file_sep>.. rst-class:: outdated .. danger:: This is an outdated documentation please read the new `Monofony documentation`_ instead. Deployment ========== Authorized keys API ------------------- Adding ssh authorized keys for server on your local computer .. code-block:: bash $ cat ~/.ssh/id_rsa.pub | ssh [email protected] "cat - >> ~/.ssh/authorized_keys" and enter the correct password for username "mobizel" on server Deploy the staging environment ------------------------------ .. code-block:: bash $ bundle exec "cap staging deploy" Deploy the production environment --------------------------------- .. code-block:: bash $ bundle exec "cap production deploy" .. _Monofony documentation: https://docs.monofony.com <file_sep><?php declare(strict_types=1); namespace App\Identifier; use Monofony\Contracts\Api\Identifier\AppUserIdentifierNormalizerInterface; use Monofony\Contracts\Core\Model\User\AppUserInterface; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; use Symfony\Component\Security\Core\Security; final class AppUserIdentifierNormalizer implements AppUserIdentifierNormalizerInterface { public function __construct(private Security $security) { } /** * {@inheritdoc} */ public function denormalize($data, $type, $format = null, array $context = []): string { $user = $this->security->getUser(); if (null === $user || !$user instanceof AppUserInterface) { throw new AccessDeniedHttpException(); } return (string) $user->getCustomer()->getId(); } /** * {@inheritdoc} */ public function supportsDenormalization($data, $type, $format = null) { return 'me' === $data; } } <file_sep><?php declare(strict_types=1); namespace App\EventSubscriber; use ApiPlatform\Api\IriConverterInterface; use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent; use Lexik\Bundle\JWTAuthenticationBundle\Events; use Sylius\Component\Customer\Model\CustomerAwareInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; final class AuthenticationSuccessSubscriber implements EventSubscriberInterface { public function __construct(private IriConverterInterface $iriConverter) { } public function onAuthenticationSuccessResponse(AuthenticationSuccessEvent $event): void { $data = $event->getData(); $user = $event->getUser(); if (!$user instanceof CustomerAwareInterface) { return; } $data['customer'] = $this->iriConverter->getIriFromResource($user->getCustomer()); $event->setData($data); } public static function getSubscribedEvents(): array { return [Events::AUTHENTICATION_SUCCESS => 'onAuthenticationSuccessResponse']; } } <file_sep>## Change Log ### v0.9.0 (2023/01/06) ## What's Changed * Improve breadcrumb recipes by @loic425 in https://github.com/Monofony/Monofony/pull/429 * Fix sample data command by @loic425 in https://github.com/Monofony/Monofony/pull/430 * Preview uploaded files by @loic425 in https://github.com/Monofony/Monofony/pull/431 * Fix the build by @loic425 in https://github.com/Monofony/Monofony/pull/434 * Conflict up to 1.11.6 by @loic425 in https://github.com/Monofony/Monofony/pull/435 * Simplify PHPUnit config by @loic425 in https://github.com/Monofony/Monofony/pull/436 * Add demo link on README by @loic425 in https://github.com/Monofony/Monofony/pull/433 * Add Symfony 6 support by @loic425 in https://github.com/Monofony/Monofony/pull/444 * Split Monorepo by @loic425 in https://github.com/Monofony/Monofony/pull/445 * Fix branches on split by @loic425 in https://github.com/Monofony/Monofony/pull/446 * Fix repository names by @loic425 in https://github.com/Monofony/Monofony/pull/447 * Trying to fix branch on split by @loic425 in https://github.com/Monofony/Monofony/pull/448 * Fix upgrade guide with security config by @loic425 in https://github.com/Monofony/Monofony/pull/449 * Bump Monorepo split version from 2.1 to 2.2 by @loic425 in https://github.com/Monofony/Monofony/pull/450 * Change user name & email for split monorepos by @loic425 in https://github.com/Monofony/Monofony/pull/451 * Upgrade to stable dependencies by @loic425 in https://github.com/Monofony/Monofony/pull/463 **Full Changelog**: https://github.com/Monofony/Monofony/compare/v0.8.0...v0.9.0 ### v0.9.0-alpha.2 (2022/11/04) * Split Monorepo by @loic425 in https://github.com/Monofony/Monofony/pull/445 * Fix branches on split by @loic425 in https://github.com/Monofony/Monofony/pull/446 * Fix repository names by @loic425 in https://github.com/Monofony/Monofony/pull/447 * Trying to fix branch on split by @loic425 in https://github.com/Monofony/Monofony/pull/448 * Fix upgrade guide with security config by @loic425 in https://github.com/Monofony/Monofony/pull/449 * Bump Monorepo split version from 2.1 to 2.2 by @loic425 in https://github.com/Monofony/Monofony/pull/450 * Change user name & email for split monorepos by @loic425 in https://github.com/Monofony/Monofony/pull/451 **Full Changelog**: https://github.com/Monofony/Monofony/compare/v0.9.0-alpha.1...v0.9.0-alpha.2 ### v0.9.0-alpha.1 (2022/11/02) * Preview uploaded files by @loic425 in https://github.com/Monofony/Monofony/pull/431 * Fix the build by @loic425 in https://github.com/Monofony/Monofony/pull/434 * Conflict up to 1.11.6 by @loic425 in https://github.com/Monofony/Monofony/pull/435 * Simplify PHPUnit config by @loic425 in https://github.com/Monofony/Monofony/pull/436 * Add demo link on README by @loic425 in https://github.com/Monofony/Monofony/pull/433 * Add Symfony 6 support by @loic425 in https://github.com/Monofony/Monofony/pull/444 **Full Changelog**: https://github.com/Monofony/Monofony/compare/v0.8.0...v0.9.0-alpha.1 <file_sep><?php declare(strict_types=1); namespace App\Grid; use App\Entity\User\AdminUser; use Sylius\Bundle\GridBundle\Builder\Action\CreateAction; use Sylius\Bundle\GridBundle\Builder\Action\DeleteAction; use Sylius\Bundle\GridBundle\Builder\Action\UpdateAction; use Sylius\Bundle\GridBundle\Builder\ActionGroup\BulkActionGroup; use Sylius\Bundle\GridBundle\Builder\ActionGroup\ItemActionGroup; use Sylius\Bundle\GridBundle\Builder\ActionGroup\MainActionGroup; use Sylius\Bundle\GridBundle\Builder\Field\StringField; use Sylius\Bundle\GridBundle\Builder\Field\TwigField; use Sylius\Bundle\GridBundle\Builder\Filter\StringFilter; use Sylius\Bundle\GridBundle\Builder\GridBuilderInterface; use Sylius\Bundle\GridBundle\Grid\AbstractGrid; use Sylius\Bundle\GridBundle\Grid\ResourceAwareGridInterface; final class AdminUserGrid extends AbstractGrid implements ResourceAwareGridInterface { public static function getName(): string { return 'sylius_backend_admin_user'; } public function buildGrid(GridBuilderInterface $gridBuilder): void { $gridBuilder ->orderBy('email', 'desc') ->addField( StringField::create('firstName') ->setLabel('sylius.ui.first_name') ->setSortable(true) ) ->addField( StringField::create('lastName') ->setLabel('sylius.ui.last_name') ->setSortable(true) ) ->addField( StringField::create('username') ->setLabel('sylius.ui.username') ->setSortable(true) ) ->addField( StringField::create('email') ->setLabel('sylius.ui.email') ->setSortable(true) ) ->addField( TwigField::create('enabled', '@SyliusUi/Grid/Field/enabled.html.twig') ->setLabel('sylius.ui.enabled') ->setSortable(true) ) ->addFilter(StringFilter::create('search', ['email', 'username', 'firstName', 'lastName'])) ->addActionGroup( MainActionGroup::create( CreateAction::create(), ) ) ->addActionGroup( ItemActionGroup::create( UpdateAction::create(), DeleteAction::create(), ) ) ->addActionGroup( BulkActionGroup::create( DeleteAction::create() ) ) ; } public function getResourceClass(): string { return AdminUser::class; } } <file_sep><?php declare(strict_types=1); namespace App\Tests\Behat\Context\Setup; use Behat\Behat\Context\Context; use Monofony\Bridge\Behat\Service\SharedStorageInterface; use Monofony\Contracts\Core\Model\Customer\CustomerInterface; use Sylius\Component\Resource\Factory\FactoryInterface; use Sylius\Component\Resource\Repository\RepositoryInterface; final class CustomerContext implements Context { public function __construct( private SharedStorageInterface $sharedStorage, private RepositoryInterface $customerRepository, private FactoryInterface $customerFactory, ) { } /** * @Given there is a customer :name with email :email */ public function thereIsCustomerWithNameAndEmail(string $name, string $email): void { $partsOfName = explode(' ', $name); $customer = $this->createCustomer($email, $partsOfName[0], $partsOfName[1]); $this->customerRepository->add($customer); } /** * @Given there is (also )a customer :email */ public function thereIsCustomer(string $email): void { $customer = $this->createCustomer($email); $this->customerRepository->add($customer); } /** * @Given there are :numberOfCustomers customers */ public function thereAreCustomers(int $numberOfCustomers): void { for ($i = 0; $i < $numberOfCustomers; ++$i) { $customer = $this->createCustomer(sprintf('<EMAIL>', uniqid())); $customer->setFirstname('John'); $customer->setLastname('Doe'.$i); $this->customerRepository->add($customer); } } /** * @Given there is customer :email with first name :firstName */ public function thereIsCustomerWithFirstName(string $email, string $firstName): void { $customer = $this->createCustomer($email, $firstName); $this->customerRepository->add($customer); } /** * @Given there is a customer :email with name :fullName and phone number :phoneNumber since :since */ public function theStoreHasCustomerWithNameAndPhoneNumber( string $email, string $fullName, string $phoneNumber, string $since ): void { $names = explode(' ', $fullName); $customer = $this->createCustomer($email, $names[0], $names[1], new \DateTime($since), $phoneNumber); $this->customerRepository->add($customer); } private function createCustomer( string $email, string $firstName = null, string $lastName = null, \DateTimeInterface $createdAt = null, string $phoneNumber = null ): CustomerInterface { /** @var CustomerInterface $customer */ $customer = $this->customerFactory->createNew(); $customer->setFirstName($firstName); $customer->setLastName($lastName); $customer->setEmail($email); $customer->setPhoneNumber($phoneNumber); if (null !== $createdAt) { $customer->setCreatedAt($createdAt); } $this->sharedStorage->set('customer', $customer); return $customer; } } <file_sep><?php declare(strict_types=1); namespace App\Form\Extension; use App\Form\EventSubscriber\AddUserFormSubscriber; use Sylius\Bundle\CustomerBundle\Form\Type\CustomerType; use Symfony\Component\Form\AbstractTypeExtension; use Symfony\Component\Form\FormBuilderInterface; final class CustomerTypeExtension extends AbstractTypeExtension { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->addEventSubscriber(new AddUserFormSubscriber()); } /** * {@inheritdoc} */ public static function getExtendedTypes(): iterable { return [CustomerType::class]; } } <file_sep><?php /* * This file is part of the Monofony package. * * (c) Monofony * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Monofony\Contracts\Core\Model\User; use Sylius\Component\Customer\Model\CustomerAwareInterface; use Sylius\Component\User\Model\UserInterface; interface AppUserInterface extends UserInterface, CustomerAwareInterface { public function getPassword(): ?string; } <file_sep><?php declare(strict_types=1); namespace App\Dashboard\Statistics; use App\Repository\CustomerRepository; use Monofony\Component\Admin\Dashboard\Statistics\StatisticInterface; use Twig\Environment; class CustomerStatistic implements StatisticInterface { public function __construct( private CustomerRepository $customerRepository, private Environment $twig, ) { } public function generate(): string { $amountCustomers = $this->customerRepository->countCustomers(); return $this->twig->render('backend/dashboard/statistics/_amount_of_customers.html.twig', [ 'amountOfCustomers' => $amountCustomers, ]); } public static function getDefaultPriority(): int { return -1; } } <file_sep>.. rst-class:: outdated .. danger:: This is an outdated documentation please read the new `Monofony documentation`_ instead. How to design entities with phpspec =================================== Lets configure an Article entity with a title and an author. Title is a simple string and author implements CustomerInterface. .. warning:: By default, phpspec on Monofony is configured with code coverage. :doc:`Learn how to configure phpspec with code coverage </cookbook/bdd/phpspec/how-to-configure-phpspec-with-code-coverage>` or :doc:`disable code coverage </cookbook/bdd/phpspec/how-to-disable-phpspec-code-coverage>`. Generate phpspec for your entity -------------------------------- .. code-block:: bash $ vendor/bin/phpspec describe App/Entity/Article $ # with phpdbg installed $ phpdbg -qrr vendor/bin/phpspec describe App/Entity/Article .. code-block:: php # spec/src/App/Entity/Article.php namespace spec\App\Entity; use App\Entity\Article; use PhpSpec\ObjectBehavior; use Prophecy\Argument; class ArticleSpec extends ObjectBehavior { function it_is_initializable() { $this->shouldHaveType(Article::class); } } Run phpspec and do not fear Red ------------------------------- To run phpspec for our Article entity, run this command: .. code-block:: bash $ vendor/bin/phpspec run spec/App/Entity/ArticleSpec.php -n $ $ # with phpdbg installed $ phpdbg -qrr vendor/bin/phpspec run spec/App/Entity/ArticleSpec.php -n And be happy with your first error message with red color. .. note:: You can simply run all the phpspec tests by running `vendor/bin/phpspec run -n` Create a minimal Article class ------------------------------ .. code-block:: php # src/App/Entity/Article.php namespace App\Entity; class Article { } Rerun phpspec and see a beautiful green color. Specify it implements sylius resource interface ----------------------------------------------- .. code-block:: php function it_implements_sylius_resource_interface(): void { $this->shouldImplement(ResourceInterface::class); } .. warning:: And Rerun phpspec, DO NOT FEAR RED COLOR! It's important to check that you write code which solves your specifications. Solve this on your entity ------------------------- .. code-block:: php # src/App/Entity/Article.php namespace App\Entity; use Sylius\Component\Resource\Model\ResourceInterface; class Article implements ResourceInterface { use IdentifiableTrait; } .. warning:: Rerun phpspec again and check this specification is solved. Specify title behaviours ------------------------ .. code-block:: php function it_has_no_title_by_default(): void { $this->getTitle()->shouldReturn(null); } function its_title_is_mutable(): void { $this->setTitle('This documentation is so great'); $this->getTitle()->shouldReturn('This documentation is so great'); } .. warning:: Don't forget to rerun phpspec on each step. Add title on Article entity --------------------------- .. code-block:: php # src/App/Entity/Article.php /** * @var string|null */ private $title; /** * @return string|null */ public function getTitle(): ?string { return $this->title; } /** * @param string|null $title */ public function setTitle(?string $title): void { $this->title = $title; } Specify author of the article ----------------------------- .. code-block:: php # spec/src/App/Entity/Article.php use Sylius\Component\Customer\Model\CustomerInterface; // [...] function its_author_is_mutable(CustomerInterface $author): void { $this->setAuthor($author); $this->getAuthor()->shouldReturn($author); } Add author on your entity ------------------------- .. code-block:: php # src/App/Entity/Article.php // [...] /** * @var CustomerInterface|null */ private $author; // [...] /** * @return CustomerInterface|null */ public function getAuthor(): ?CustomerInterface { return $this->author; } /** * @param CustomerInterface|null $author */ public function setAuthor(?CustomerInterface $author): void { $this->author = $author; } That's all to design your first entity! .. _Monofony documentation: https://docs.monofony.com <file_sep><?php use Symplify\MonorepoBuilder\Config\MBConfig; return static function (MBConfig $config): void { $config->packageDirectories([ // default value __DIR__ . '/src/Monofony', ]); }; <file_sep>.. rst-class:: outdated .. danger:: This is an outdated documentation please read the new `Monofony documentation`_ instead. How to use it on your suite =========================== .. code-block:: yaml # config/sylius/fixtures.yaml sylius_fixtures: suites: default: listeners: orm_purger: ~ logger: ~ fixtures: [...] article: options: random: 10 custom: - title: "Awesome article" it will generates 10 random articles and one custom with title ``Awesome article``. .. _Monofony documentation: https://docs.monofony.com <file_sep><?php declare(strict_types=1); namespace App\Message; interface AppUserIdAwareInterface { public function getAppUserId(): ?int; public function setAppUserId(?int $appUserId): void; } <file_sep><?php declare(strict_types=1); namespace App\MessageHandler; use App\Message\ResetPassword; use Doctrine\ORM\EntityManagerInterface; use Sylius\Component\Resource\Repository\RepositoryInterface; use Sylius\Component\User\Model\UserInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\Messenger\Handler\MessageHandlerInterface; use Webmozart\Assert\Assert; final class ResetPasswordHandler implements MessageHandlerInterface { public function __construct( private RepositoryInterface $appUserRepository, private EntityManagerInterface $entityManager, private RequestStack $requestStack, private array $syliusResources, ) { } public function __invoke(ResetPassword $message): void { /** @var UserInterface|null $user */ $user = $this->appUserRepository->findOneBy(['passwordResetToken' => $this->getToken()]); if (null === $user) { throw new NotFoundHttpException('Token not found.'); } $lifetime = new \DateInterval($this->getTtl()); if (!$user->isPasswordRequestNonExpired($lifetime)) { $this->handleExpiredToken($user); return; } $user->setPlainPassword($message->password); $user->setPasswordResetToken(null); $user->setPasswordRequestedAt(null); $this->entityManager->flush(); } private function getToken(): string { /** @var Request $request */ $request = $this->requestStack->getCurrentRequest(); Assert::notNull($request); /** @var string $token */ $token = $request->attributes->get('token'); Assert::notNull($token); return $token; } private function getTtl(): string { /** @var string $ttl */ $ttl = $this->syliusResources['sylius.app_user']['resetting']['token']['ttl'] ?? null; Assert::notNull($ttl, 'Token ttl was not found but it should.'); return $ttl; } protected function handleExpiredToken(UserInterface $user): void { $user->setPasswordResetToken(null); $user->setPasswordRequestedAt(null); $this->entityManager->flush(); throw new BadRequestHttpException('Token expired.'); } } <file_sep><?php /* * This file is part of the Monofony package. * * (c) Monofony * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Monofony\Contracts\Core\Model\Customer; use Monofony\Contracts\Core\Model\User\AppUserInterface; use Sylius\Component\Customer\Model\CustomerInterface as BaseCustomerInterface; use Sylius\Component\User\Model\UserAwareInterface; use Sylius\Component\User\Model\UserInterface; interface CustomerInterface extends BaseCustomerInterface, UserAwareInterface { /** * @return AppUserInterface|Userinterface|null */ public function getUser(): ?UserInterface; /** * @param AppUserInterface|UserInterface|null $user */ public function setUser(?UserInterface $user): void; } <file_sep><?php declare(strict_types=1); namespace App\MessageHandler; use App\Message\ChangeAppUserPassword; use Doctrine\ORM\EntityManagerInterface; use Sylius\Component\User\Model\CredentialsHolderInterface; use Sylius\Component\User\Security\PasswordUpdaterInterface; use Symfony\Component\Messenger\Handler\MessageHandlerInterface; use Symfony\Component\Security\Core\Security; use Webmozart\Assert\Assert; final class ChangeAppUserPasswordHandler implements MessageHandlerInterface { public function __construct( private PasswordUpdaterInterface $passwordUpdater, private EntityManagerInterface $entityManager, private Security $security, ) { } public function __invoke(ChangeAppUserPassword $message): void { $user = $this->security->getUser(); Assert::notNull($user); if (!$user instanceof CredentialsHolderInterface) { return; } $user->setPlainPassword($message->newPassword); $this->passwordUpdater->updatePassword($user); $this->entityManager->flush(); } } <file_sep>.. rst-class:: outdated .. danger:: This is an outdated documentation please read the new `Monofony documentation`_ instead. How to change Behat application base url ---------------------------------------- By default Behat uses ``https://localhost:8080/`` as your application base url. If your one is different, you need to create ``behat.yml`` files that will overwrite it with your custom url: .. code-block:: yaml # behat.yml imports: ["behat.yml.dist"] default: extensions: Behat\MinkExtension: base_url: http://my.custom.url .. _Monofony documentation: https://docs.monofony.com <file_sep><?php declare(strict_types=1); namespace App\Menu; use Knp\Menu\FactoryInterface; use Knp\Menu\ItemInterface; use Monofony\Component\Admin\Menu\AdminMenuBuilderInterface; final class AdminMenuBuilder implements AdminMenuBuilderInterface { public function __construct(private FactoryInterface $factory) { } public function createMenu(array $options): ItemInterface { $menu = $this->factory->createItem('root'); $this->addCustomerSubMenu($menu); $this->addConfigurationSubMenu($menu); return $menu; } private function addCustomerSubMenu(ItemInterface $menu): void { $customer = $menu ->addChild('customer') ->setLabel('sylius.ui.customer') ; $customer->addChild('backend_customer', ['route' => 'sylius_backend_customer_index']) ->setLabel('sylius.ui.customers') ->setLabelAttribute('icon', 'users'); } private function addConfigurationSubMenu(ItemInterface $menu): void { $configuration = $menu ->addChild('configuration') ->setLabel('sylius.ui.configuration') ; $configuration->addChild('backend_admin_user', ['route' => 'sylius_backend_admin_user_index']) ->setLabel('sylius.ui.admin_users') ->setLabelAttribute('icon', 'lock'); } } <file_sep><?php namespace spec\App\Form\Extension; use PhpSpec\ObjectBehavior; use Prophecy\Argument; use Symfony\Component\Form\AbstractTypeExtension; use Symfony\Component\Form\Extension\Core\Type\DateType; use Symfony\Component\OptionsResolver\OptionsResolver; final class DateTypeExtensionSpec extends ObjectBehavior { function it_extends_an_abstract_type_extension() { $this->shouldHaveType(AbstractTypeExtension::class); } function it_extends_date_type() { $this::getExtendedTypes()->shouldReturn([DateType::class]); } function it_configures_options(OptionsResolver $resolver) { $resolver->setDefaults([ 'widget' => 'single_text', 'html5' => false, ])->willReturn($resolver)->shouldBeCalled(); $this->configureOptions($resolver); } } <file_sep><?php declare(strict_types=1); namespace App\Installer\Provider; use Doctrine\DBAL\Schema\AbstractSchemaManager; use Doctrine\ORM\EntityManagerInterface; use Doctrine\Persistence\ManagerRegistry; use Symfony\Component\Console\Helper\QuestionHelper; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Question\ConfirmationQuestion; use Symfony\Component\Console\Style\SymfonyStyle; use Webmozart\Assert\Assert; final class DatabaseSetupCommandsProvider implements DatabaseSetupCommandsProviderInterface { public function __construct(private ManagerRegistry $doctrineRegistry) { } public function getCommands(InputInterface $input, OutputInterface $output, QuestionHelper $questionHelper): array { if (!$this->isDatabasePresent()) { return [ 'doctrine:database:create', 'doctrine:migrations:migrate' => ['--no-interaction' => true], ]; } return array_merge($this->setupDatabase($input, $output, $questionHelper), [ 'doctrine:migrations:version' => [ '--add' => true, '--all' => true, '--no-interaction' => true, ], ]); } /** * @throws \Exception */ private function isDatabasePresent(): bool { $databaseName = $this->getDatabaseName(); try { $schemaManager = $this->getSchemaManager(); return in_array($databaseName, $schemaManager->listDatabases()); } catch (\Exception $exception) { $message = $exception->getMessage(); $mysqlDatabaseError = false !== strpos($message, sprintf("Unknown database '%s'", $databaseName)); $postgresDatabaseError = false !== strpos($message, sprintf('database "%s" does not exist', $databaseName)); if ($mysqlDatabaseError || $postgresDatabaseError) { return false; } throw $exception; } } private function setupDatabase(InputInterface $input, OutputInterface $output, QuestionHelper $questionHelper): array { $outputStyle = new SymfonyStyle($input, $output); $outputStyle->writeln('It appears that your database already exists.'); $outputStyle->writeln('<error>Warning! This action will erase your database.</error>'); $question = new ConfirmationQuestion('Would you like to reset it? (y/N) ', false); if ($questionHelper->ask($input, $output, $question)) { return [ 'doctrine:database:drop' => ['--force' => true], 'doctrine:database:create', 'doctrine:migrations:migrate' => ['--no-interaction' => true], ]; } if (!$this->isSchemaPresent()) { return ['doctrine:migrations:migrate' => ['--no-interaction' => true]]; } $outputStyle->writeln('Seems like your database contains schema.'); $outputStyle->writeln('<error>Warning! This action will erase your database.</error>'); $question = new ConfirmationQuestion('Do you want to reset it? (y/N) ', false); if ($questionHelper->ask($input, $output, $question)) { return [ 'doctrine:schema:drop' => ['--force' => true], 'doctrine:migrations:migrate' => ['--no-interaction' => true], ]; } return []; } private function isSchemaPresent(): bool { return 0 !== count($this->getSchemaManager()->listTableNames()); } private function getDatabaseName(): string { return (string) $this->getEntityManager()->getConnection()->getDatabase(); } private function getSchemaManager(): AbstractSchemaManager { return $this->getEntityManager()->getConnection()->getSchemaManager(); } private function getEntityManager(): EntityManagerInterface { /** @var EntityManagerInterface $entityManager */ $entityManager = $this->doctrineRegistry->getManager(); Assert::isInstanceOf($entityManager, EntityManagerInterface::class); return $entityManager; } } <file_sep>| Q | A | |-----------------|-----------------------------------------| | Branch? | 0.10 or 0.11 | | Bug fix? | no/yes | | New feature? | no/yes | | Related tickets | fixes #X, partially #Y, mentioned in #Z | | License | MIT | <!-- - Bug fixes must be submitted against the 0.10 branch - Features and deprecations must be submitted against the 0.11 branch --> <file_sep>* :doc:`/book/architecture/index` * :doc:`/book/architecture/fixtures` * :doc:`/book/user/index` * :doc:`/book/user/admins` * :doc:`/book/user/customers` <file_sep>.. rst-class:: outdated .. danger:: This is an outdated documentation please read the new `Monofony documentation`_ instead. How to configure your fixture options ===================================== Now you have to create a fixture service. This defines options you can use on `fixtures bundle configurations yaml files`_. .. code-block:: php namespace App\Fixture; use Monofony\Plugin\FixturesPlugin\Fixture\AbstractResourceFixture; use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; class ArticleFixture extends AbstractResourceFixture { public function __construct(ObjectManager $objectManager, ArticleExampleFactory $articleExampleFactory) { parent::__construct($objectManager, $articleExampleFactory); } /** * {@inheritdoc} */ public function getName(): string { return 'article'; } /** * {@inheritdoc} */ protected function configureResourceNode(ArrayNodeDefinition $resourceNode) { $resourceNode ->children() ->scalarNode('title')->cannotBeEmpty()->end() ; } } In this file we have only one custom option which is the article title. Thanks to autowiring system, you can already use it. .. code-block:: bash $ bin/console debug:container App\Fixture\ArticleFixture .. _fixtures bundle configurations yaml files: https://github.com/Monofony/Monofony/blob/0.x/src/Monofony/MetaPack/CoreMeta/.recipe/config/sylius/fixtures.yaml .. _Monofony documentation: https://docs.monofony.com <file_sep><?php /* * This file is part of the Monofony package. * * (c) Monofony * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Monofony\Contracts\Core\Model\User; use Sylius\Component\User\Model\UserInterface as BaseUserInterface; interface AdminUserInterface extends BaseUserInterface { public const DEFAULT_ADMIN_ROLE = 'ROLE_ADMIN'; public function getPassword(): ?string; public function getFirstName(): ?string; public function setFirstName(?string $firstName): void; public function getLastName(): ?string; public function setLastName(?string $lastName): void; public function getAvatar(): ?AdminAvatarInterface; public function setAvatar(?AdminAvatarInterface $avatar): void; } <file_sep>.. rst-class:: outdated .. danger:: This is an outdated documentation please read the new `Monofony documentation`_ instead. .. index:: single: Fixtures Fixtures ======== Fixtures are used mainly for testing, but also for having your website in a certain state, having defined data - they ensure that there is a fixed environment in which your application is working. .. note:: The way Fixtures are designed in Monofony is well described in the `FixturesBundle documentation <https://github.com/Sylius/SyliusFixturesBundle/blob/master/docs/index.md>`_. What are the available fixtures in Monofony? -------------------------------------------- To check what fixtures are defined in Monofony run: .. code-block:: bash $ php bin/console sylius:fixtures:list How to load Monofony fixtures? ------------------------------ The recommended way to load the predefined set of Monofony fixtures is here: .. code-block:: bash $ php bin/console sylius:fixtures:load What data is loaded by fixtures in Monofony? -------------------------------------------- All files that serve for loading fixtures of Monofony are placed in the ``App/Fixture/*`` directory. And the specified data for fixtures is stored in the ``config/packages/sylius_fixtures.yaml`` file. .. _Monofony documentation: https://docs.monofony.com <file_sep><?php declare(strict_types=1); namespace App\Command\Installer; use App\Command\Helper\CommandsRunner; use App\Installer\Provider\DatabaseSetupCommandsProviderInterface; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; class InstallDatabaseCommand extends Command { protected static $defaultName = 'app:install:database'; public function __construct( private DatabaseSetupCommandsProviderInterface $databaseSetupCommandsProvider, private CommandsRunner $commandsRunner, private string $environment ) { parent::__construct(); } /** * {@inheritdoc} */ protected function configure(): void { $this->setDescription('Install AppName database.') ->setHelp( <<<EOT The <info>%command.name%</info> command creates AppName database. EOT ) ; } /** * {@inheritdoc} * * @throws \Exception */ protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $io->writeln(sprintf( 'Creating AppName database for environment <info>%s</info>.', $this->environment )); $commands = $this ->databaseSetupCommandsProvider ->getCommands($input, $output, $this->getHelper('question')) ; $this->commandsRunner->run($commands, $input, $output, $this->getApplication()); $io->newLine(); // Install Sample data command is available on monofony/fixtures-plugin if (class_exists(InstallSampleDataCommand::class)) { $commandExecutor = new CommandExecutor($input, $output, $this->getApplication()); $commandExecutor->runCommand(InstallSampleDataCommand::getDefaultName(), [], $output); } return 0; } } <file_sep><?php declare(strict_types=1); namespace App\Entity\User; use App\Entity\Media\File; use Doctrine\ORM\Mapping as ORM; use Monofony\Contracts\Core\Model\User\AdminAvatarInterface; use Vich\UploaderBundle\Mapping\Annotation as Vich; /** * @Vich\Uploadable */ #[ORM\Entity] #[ORM\Table(name: 'app_admin_avatar')] class AdminAvatar extends File implements AdminAvatarInterface { /** * @Vich\UploadableField(mapping="admin_avatar", fileNameProperty="path") */ #[\Symfony\Component\Validator\Constraints\File(maxSize: '6000000', mimeTypes: ['image/*'])] protected ?\SplFileInfo $file = null; } <file_sep>## UPGRADE FOR `0.9.x` ### FROM `0.8.x` TO `0.9x` Add these lines on `config/packages/monofony_admin.yaml` ```yaml imports: - { resource: '@SyliusUiBundle/Resources/config/app/config.yml' } ``` On `config/packages/security.yaml` Replace ```yaml security: firewalls: admin: # [...] anonymous: true api: # [...] anonymous: true guard: authenticators: - lexik_jwt_authentication.jwt_token_authenticator ``` with ```yaml security: # Add this line enable_authenticator_manager: true # [...] firewalls: admin: # [...] # Remove that line # anonymous: true api: # [...] entry_point: jwt jwt: true refresh_jwt: check_path: /api/token/refresh ``` And replace `IS_AUTHENTICATED_ANONYMOUSLY` with `PUBLIC_ACCESS` Update controller on routes' configuration with two dots: Example: `_controller: App\Controller\DashboardController:indexAction` replaced by `_controller: App\Controller\DashboardController::indexAction` On `config/routes/api.yaml` Replace ```yaml gesdinet_jwt_refresh_token: path: /api/token/refresh controller: gesdinet.jwtrefreshtoken::refresh ``` With ```yaml api_refresh_token: path: /api/token/refresh ``` On `config/packages/test/framework.yaml` Replace ```yaml framework: test: ~ session: storage_id: session.storage.mock_file ``` With ```yaml framework: test: ~ session: storage_factory_id: session.storage.factory.mock_file ``` On `config/packages/test/monofony_core.yaml` Replace ```yaml swiftmailer: spool: type: file path: "%kernel.cache_dir%/spool" ``` With ```yaml framework: cache: pools: test.mailer_pool: adapter: cache.adapter.filesystem ``` on `src/EventSubscriber/CanonicalaizerSubscriber.php` Replace ```php } elseif ($item instanceof UserInterface) { ``` With ```php } elseif ($item instanceof UserInterface && method_exists($item, 'getUsername')) { ``` on `src/EventSubscriber/DefaultUsernameORMSubscriber.php` Replace ```php if ($customer->getEmail() === $user->getUsername() && $customer->getEmailCanonical() === $user->getUsernameCanonical()) { continue; } ``` With ```php if (!method_exists($user, 'getUsername')) { continue; } if ($customer->getEmail() === $user->getUsername() && $customer->getEmailCanonical() === $user->getUsernameCanonical()) { continue; } ``` on `src/Security/UserChecker.php` Replace ```php if (!$user instanceof User) { return; } ``` With ```php if (!$user instanceof AdvancedUserInterface || !method_exists($user, 'isCredentialsNonExpired') return; } ``` And add this line on imports ```php use SyliusLabs\Polyfill\Symfony\Security\Core\User\AdvancedUserInterface; ``` ## UPGRADE FOR `0.4.x` ### FROM `0.2.x` TO `0.4.x` First use composer 2 using these commands: ```bash composer self-update composer self -v ``` Ensure you requires Symfony 4.4.*: ```bash composer config extra.symfony.require "4.4.*" ``` Ensure you use stable releases: ```bash composer config minimum-stability "stable" ``` Update your dependencies: ```bash composer remove \ monofony/api-bundle \ monofony/front-bundle \ monofony/admin-bundle \ monofony/core-bundle \ monofony/fixtures-plugin \ --no-update --no-scripts --no-plugins ``` ```bash composer require \ php:^7.3 \ monofony/core-pack \ monofony/api-pack \ monofony/admin-pack \ monofony/front-pack \ symfony/dotenv:4.4.* \ symfony/flex:^1.9 \ symfony/monolog-bundle:^3.1 \ symfony/webpack-encore-bundle:^1.7 \ --no-update --no-scripts --no-plugins ``` ```bash composer require --dev monofony/test-pack:^0.4 --no-update --no-scripts --no-plugins ``` ```bash composer require \ eightpoints/guzzle-bundle:^7.3 \ sensio/framework-extra-bundle:^5.1 \ sensiolabs/security-checker:^5.0 \ sylius/mailer-bundle \ twig/extensions \ --no-update --no-scripts --no-plugins ``` Copy the script to migrate the code: ```bash php -r "copy('https://raw.githubusercontent.com/Monofony/Monofony/0.x/bin/upgrade-to-0.4', 'bin/upgrade-to-0.4');" ``` Make it executuable: ```bash chmod a+x bin/upgrade-to-0.4 ``` Run it: ```bash bin/upgrade-to-0.4 ``` And finally run composer update: ```bash composer update ``` <file_sep><?php declare(strict_types=1); namespace App\Installer\Provider; use Symfony\Component\Console\Helper\QuestionHelper; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; interface DatabaseSetupCommandsProviderInterface { public function getCommands(InputInterface $input, OutputInterface $output, QuestionHelper $questionHelper): array; } <file_sep><?php declare(strict_types=1); namespace App\Tests\Behat\Context\Cli; use Behat\Behat\Context\Context; use Doctrine\Persistence\ObjectManager; use Symfony\Component\Console\Tester\CommandTester; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpKernel\KernelInterface; class DefaultContext implements Context { protected KernelInterface $kernel; protected $application; protected static ?CommandTester $sharedTester; protected $command; protected $questionHelper; public function __construct(KernelInterface $kernel) { $this->kernel = $kernel; } public function setTester(?CommandTester $tester): void { static::$sharedTester = $tester; } public function getTester(): ?CommandTester { return static::$sharedTester; } protected function getEntityManager(): ObjectManager { return $this->getService('doctrine')->getManager(); } protected function getService(string $id): ?object { return $this->getContainer()->get($id); } protected function getContainer(): ContainerInterface { return $this->kernel->getContainer(); } } <file_sep><?php declare(strict_types=1); namespace App\Message; use Symfony\Component\Serializer\Annotation\Groups; use Symfony\Component\Validator\Constraints\NotBlank; final class ResetPasswordRequest { #[NotBlank(message: 'sylius.user.email.not_blank')] #[Groups(groups: ['customer:write'])] public ?string $email = null; public function __construct(?string $email = null) { $this->email = $email; } } <file_sep><?php /* * This file is part of the Monofony package. * * (c) Monofony * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Monofony\Bundle\CoreBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; final class ChangeCustomerContextVisibilityPass implements CompilerPassInterface { /** * {@inheritdoc} */ public function process(ContainerBuilder $container) { foreach ($container->findTaggedServiceIds('monofony.customer_context') as $serviceId => $attributes) { $serviceDefinition = $container->findDefinition($serviceId); $serviceDefinition->setPublic(true); $serviceDefinition->clearTag('monofony.customer_context'); } } } <file_sep>.. rst-class:: outdated .. danger:: This is an outdated documentation please read the new `Monofony documentation`_ instead. How to configure a fixture factory ================================== First you have to create a fixture factory. This service is responsible to create new instance of the resource and handle options. This allows to combine random and custom data on your data fixtures. .. code-block:: php namespace App\Fixture\Factory; use App\Entity\Article; use Monofony\Plugin\FixturesPlugin\Fixture\Factory\AbstractExampleFactory; use Sylius\Component\Resource\Factory\FactoryInterface; use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; final class ArticleExampleFactory extends AbstractExampleFactory { /** @var FactoryInterface */ private $articleFactory; /** @var \Faker\Generator */ private $faker; /** @var OptionsResolver */ private $optionsResolver; public function __construct(FactoryInterface $articleFactory) { $this->articleFactory = $articleFactory; $this->faker = \Faker\Factory::create(); $this->optionsResolver = new OptionsResolver(); $this->configureOptions($this->optionsResolver); } /** * {@inheritdoc} */ protected function configureOptions(OptionsResolver $resolver): void { $resolver ->setDefault('title', function (Options $options) { return ucfirst($this->faker->words(3, true)); }); } /** * {@inheritdoc} */ public function create(array $options = []): Article { $options = $this->optionsResolver->resolve($options); /** @var Article $article */ $article = $this->articleFactory->createNew(); $article->setTitle($options['title']); return $article; } } Thanks to services configuration, your new service is already registered and ready to use: .. code-block:: bash $ bin/console debug:container App\Fixture\Factory\ArticleExampleFactory .. _Monofony documentation: https://docs.monofony.com <file_sep><?php declare(strict_types=1); namespace App\Tests\Behat\Context\Cli; use Webmozart\Assert\Assert; class CommandContext extends DefaultContext { /** * @Then the command should finish successfully */ public function commandSuccess(): void { Assert::same($this->getTester()->getStatusCode(), 0); } /** * @Then I should see output :text */ public function iShouldSeeOutput(string $text): void { Assert::contains($this->getTester()->getDisplay(), $text); } } <file_sep><?php declare(strict_types=1); namespace App\Story; use App\Factory\AppUserFactory; use Zenstruck\Foundry\Story; final class TestAppUsersStory extends Story { public function build(): void { AppUserFactory::createOne([ 'email' => '<EMAIL>', 'username' => 'sylius', 'password' => '<PASSWORD>', 'first_name' => 'Sam', 'last_name' => 'Identifie', ]); AppUserFactory::createOne([ 'email' => '<EMAIL>', 'username' => 'monofony', 'password' => '<PASSWORD>', 'first_name' => 'Another', 'last_name' => 'Customer', ]); } } <file_sep><?php declare(strict_types=1); namespace App\EventSubscriber; use Doctrine\Persistence\ObjectManager; use Monofony\Contracts\Core\Model\Customer\CustomerInterface; use Sylius\Bundle\UserBundle\UserEvents; use Sylius\Component\User\Model\UserInterface; use Sylius\Component\User\Security\Generator\GeneratorInterface; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\EventDispatcher\GenericEvent; use Webmozart\Assert\Assert; final class UserRegistrationSubscriber implements EventSubscriberInterface { public function __construct(private ObjectManager $userManager, private GeneratorInterface $tokenGenerator, private EventDispatcherInterface $eventDispatcher) { } /** * {@inheritdoc} */ public static function getSubscribedEvents(): array { return [ 'sylius.customer.post_register' => 'handleUserVerification', ]; } public function handleUserVerification(GenericEvent $event): void { $customer = $event->getSubject(); Assert::isInstanceOf($customer, CustomerInterface::class); $user = $customer->getUser(); Assert::notNull($user); $this->sendVerificationEmail($user); } private function sendVerificationEmail(UserInterface $user): void { $token = $this->tokenGenerator->generate(); $user->setEmailVerificationToken($token); $this->userManager->persist($user); $this->userManager->flush(); $this->eventDispatcher->dispatch(new GenericEvent($user), UserEvents::REQUEST_VERIFICATION_TOKEN); } } <file_sep>## Change Log ### v0.2.3 (2020/05/11 10:57 +00:00) - [#144](https://github.com/Monofony/Monofony/pull/144) Remove monorepo-builder from test-pack (@loic425) - [#143](https://github.com/Monofony/Monofony/pull/143) Fix psalm error (@loic425) ### v0.2.2 (2020/05/07 10:19 +00:00) - [#142](https://github.com/Monofony/Monofony/pull/142) fix core dependency (@loic425) ### v0.2.1 (2020/05/07 09:08 +00:00) - [#140](https://github.com/Monofony/Monofony/pull/140) Fix composer version (@loic425) ### v0.2.0 (2020/05/07 08:01 +00:00) - [#134](https://github.com/Monofony/Monofony/pull/134) Move user interfaces into core component (@loic425) - [#138](https://github.com/Monofony/Monofony/pull/138) Upgrade some packages to fix security (@loic425) - [#136](https://github.com/Monofony/Monofony/pull/136) Remove recipe directories from autoload (@loic425) - [#133](https://github.com/Monofony/Monofony/pull/133) Update BDD guide (@loic425) - [#132](https://github.com/Monofony/Monofony/pull/132) Fix app_backend_article resource in _main.yaml (@kweyhaupt) - [#131](https://github.com/Monofony/Monofony/pull/131) Update data fixtures documentation (@loic425) - [#130](https://github.com/Monofony/Monofony/pull/130) Fix to match v0.1.1 release (@loic425) <file_sep>.. rst-class:: outdated .. danger:: This is an outdated documentation please read the new `Monofony documentation`_ instead. Basic example ============= This is a basic example. It fetches and renders the amount of registered customers. .. code-block:: php namespace App\Dashboard\Statistics; use App\Repository\CustomerRepository; use Monofony\Component\Admin\Dashboard\Statistics\StatisticInterface; use Symfony\Component\Templating\EngineInterface; class CustomerStatistic implements StatisticInterface { /** @var CustomerRepository */ private $customerRepository; /** @var EngineInterface */ private $engine; public function __construct(CustomerRepository $customerRepository, EngineInterface $engine) { $this->customerRepository = $customerRepository; $this->engine = $engine; } public function generate(): string { $amountCustomers = $this->customerRepository->countCustomers(); return $this->engine->render('backend/dashboard/statistics/_amount_of_customers.html.twig', [ 'amountOfCustomers' => $amountCustomers, ]); } public static function getDefaultPriority(): int { return -1; } } .. _Monofony documentation: https://docs.monofony.com <file_sep><?php declare(strict_types=1); namespace App\Tests\Controller\Customer; use App\Factory\AppUserFactory; use App\Story\TestAppUsersStory; use App\Tests\Controller\JsonApiTestCase; use App\Tests\Controller\PurgeDatabaseTrait; use Symfony\Component\HttpFoundation\Response; use Zenstruck\Foundry\Test\Factories; class ResetPasswordApiTest extends JsonApiTestCase { use Factories; use PurgeDatabaseTrait; /** @test */ public function it_does_not_allow_to_request_password_without_required_data(): void { $data = <<<EOT { "email": "" } EOT; $this->client->request('POST', '/api/request_password', [], [], ['CONTENT_TYPE' => 'application/json'], $data); $response = $this->client->getResponse(); $this->assertResponse($response, 'customer/request_password_validation_response', Response::HTTP_UNPROCESSABLE_ENTITY); } /** @test */ public function it_allows_to_request_new_password(): void { TestAppUsersStory::load(); $data = <<<EOT { "email": "<EMAIL>" } EOT; $this->client->request('POST', '/api/request_password', [], [], ['CONTENT_TYPE' => 'application/json'], $data); $response = $this->client->getResponse(); $this->assertEquals($response->getStatusCode(), Response::HTTP_NO_CONTENT); } /** @test */ public function it_does_not_allow_to_reset_password_without_required_data(): void { TestAppUsersStory::load(); $data = <<<EOT { "password": "" } EOT; $this->client->request('PATCH', '/api/reset_password/t0ken', [], [], ['CONTENT_TYPE' => 'application/merge-patch+json'], $data); $response = $this->client->getResponse(); $this->assertResponse($response, 'customer/reset_password_validation_response', Response::HTTP_UNPROCESSABLE_ENTITY); } /** @test */ public function it_does_not_allow_to_reset_password_with_token_not_found(): void { $data = <<<EOT { "password": "<PASSWORD>" } EOT; $this->client->request('PATCH', '/api/reset_password/t0ken', [], [], ['CONTENT_TYPE' => 'application/merge-patch+json'], $data); $response = $this->client->getResponse(); $this->assertResponse($response, 'customer/token_not_found_validation_response', Response::HTTP_NOT_FOUND); } /** @test */ public function it_does_not_allow_to_reset_password_with_token_expired(): void { TestAppUsersStory::load(); $user = AppUserFactory::find(['username' => 'sylius']); $user->disableAutoRefresh(); $user->setPasswordRequestedAt(new \DateTimeImmutable('-1 day')); $user->setPasswordResetToken('<PASSWORD>'); $user->save(); $data = <<<EOT { "password": "<PASSWORD>" } EOT; $this->client->request('PATCH', '/api/reset_password/expired_t0ken', [], [], ['CONTENT_TYPE' => 'application/merge-patch+json'], $data); $response = $this->client->getResponse(); $this->assertResponse($response, 'customer/token_expired_validation_response', Response::HTTP_BAD_REQUEST); } /** @test */ public function it_allows_to_reset_password(): void { TestAppUsersStory::load(); $user = AppUserFactory::find(['username' => 'sylius']); $user->disableAutoRefresh(); $user->setPasswordRequestedAt(new \DateTimeImmutable()); $user->setPasswordResetToken('<PASSWORD>'); $user->save(); $data = <<<EOT { "password": "<PASSWORD>" } EOT; $this->client->request('PATCH', '/api/reset_password/t0ken', [], [], ['CONTENT_TYPE' => 'application/merge-patch+json'], $data); $response = $this->client->getResponse(); $this->assertResponseCode($response, Response::HTTP_NO_CONTENT); } } <file_sep><?php declare(strict_types=1); namespace App\Tests\Behat\Page\Frontend\Account; use Behat\Mink\Exception\ElementNotFoundException; use FriendsOfBehat\PageObjectExtension\Page\SymfonyPage; class RequestPasswordResetPage extends SymfonyPage { public function checkValidationMessageFor(string $element, string $message): bool { $errorLabel = $this->getElement($element)->getParent()->getParent()->find('css', '.sylius-validation-error'); if (null === $errorLabel) { throw new ElementNotFoundException($this->getSession(), 'Validation message', 'css', '.sylius-validation-error'); } return $message === $errorLabel->getText(); } public function reset(): void { $this->getDocument()->pressButton('Reset'); } public function specifyEmail(?string $email): void { $this->getDocument()->fillField('Email', $email); } public function getRouteName(): string { return 'sylius_user_request_password_reset_token'; } /** * {@inheritdoc} */ protected function getDefinedElements(): array { return array_merge(parent::getDefinedElements(), [ 'email' => '#sylius_user_request_password_reset_email', ]); } } <file_sep><?php declare(strict_types=1); namespace App\Tests\Behat\Context\Setup; use App\Factory\AdminUserFactory; use Behat\Behat\Context\Context; use Monofony\Bridge\Behat\Service\SharedStorageInterface; use Sylius\Component\User\Repository\UserRepositoryInterface; final class AdminUserContext implements Context { public function __construct( private SharedStorageInterface $sharedStorage, private AdminUserFactory $adminUserFactory, private UserRepositoryInterface $adminUserRepository, ) { } /** * @Given there is an administrator :email identified by :password * @Given /^there is(?:| also) an administrator "([^"]+)"$/ */ public function thereIsAnAdministratorIdentifiedBy(string $email, string $password = '<PASSWORD>'): void { $adminUser = $this->adminUserFactory->createOne(['email' => $email, 'password' => $<PASSWORD>, 'enabled' => true]); $adminUser = $this->adminUserRepository->find($adminUser->getId()); $this->sharedStorage->set('administrator', $adminUser); } /** * @Given there is an administrator with name :username */ public function thereIsAnAdministratorWithName(string $username): void { $adminUser = $this->adminUserFactory->createOne(['username' => $username]); $adminUser = $this->adminUserRepository->find($adminUser->getId()); $this->sharedStorage->set('administrator', $adminUser); } } <file_sep>* :doc:`/deployment/index` <file_sep><?php declare(strict_types=1); namespace App\Tests\Controller\Customer; use App\Factory\AppUserFactory; use App\Story\TestAppUsersStory; use App\Tests\Controller\AuthorizedHeaderTrait; use App\Tests\Controller\JsonApiTestCase; use App\Tests\Controller\PurgeDatabaseTrait; use Symfony\Component\HttpFoundation\Response; use Zenstruck\Foundry\Test\Factories; class ChangePasswordApiTest extends JsonApiTestCase { use Factories; use AuthorizedHeaderTrait; use PurgeDatabaseTrait; /** @test */ public function it_does_not_allow_to_change_password_for_non_authenticated_user(): void { TestAppUsersStory::load(); $customer = AppUserFactory::find(['username' => 'sylius'])->getCustomer(); $this->client->request('PATCH', '/api/customers/'.$customer->getId().'/password', [], [], ['CONTENT_TYPE' => 'application/merge-patch+json'], '{}'); $response = $this->client->getResponse(); $this->assertResponse($response, 'error/access_denied_response', Response::HTTP_UNAUTHORIZED); } /** @test */ public function it_does_not_allow_to_change_password_without_required_data(): void { TestAppUsersStory::load(); $customer = AppUserFactory::find(['username' => 'sylius'])->getCustomer(); $this->client->request('PATCH', '/api/customers/'.$customer->getId().'/password', [], [], self::$authorizedHeaderForPatch, '{}'); $response = $this->client->getResponse(); $this->assertResponse($response, 'customer/change_password_validation_response', Response::HTTP_UNPROCESSABLE_ENTITY); } /** @test */ public function it_does_not_allow_to_change_password_with_wrong_current_password(): void { TestAppUsersStory::load(); $customer = AppUserFactory::find(['username' => 'sylius'])->getCustomer(); $data = <<<EOT { "currentPassword": "<PASSWORD>", "newPassword": "<PASSWORD>" } EOT; $this->client->request('PATCH', '/api/customers/'.$customer->getId().'/password', [], [], self::$authorizedHeaderForPatch, $data); $response = $this->client->getResponse(); $this->assertResponse($response, 'customer/wrong_current_password_validation_response', Response::HTTP_UNPROCESSABLE_ENTITY); } /** @test */ public function it_allows_to_change_password(): void { TestAppUsersStory::load(); $customer = AppUserFactory::find(['username' => 'sylius'])->getCustomer(); $data = <<<EOT { "currentPassword": "<PASSWORD>", "newPassword": "<PASSWORD>" } EOT; $this->client->request('PATCH', '/api/customers/'.$customer->getId().'/password', [], [], self::$authorizedHeaderForPatch, $data); $response = $this->client->getResponse(); $this->assertResponseCode($response, Response::HTTP_NO_CONTENT); $this->assertLoginWithCredentials($customer->getEmail(), 'monofony'); } private function assertLoginWithCredentials(?string $username, string $password): void { $data = <<<EOT { "username": "$username", "password": <PASSWORD>" } EOT; $this->client->request('POST', '/api/authentication_token', [], [], ['CONTENT_TYPE' => 'application/json'], $data); $response = $this->client->getResponse(); $this->assertResponse($response, 'authentication/new_access_token', Response::HTTP_OK); } } <file_sep><?php declare(strict_types=1); namespace App\Tests\Behat\Context\Setup; use App\Factory\AppUserFactory; use Behat\Behat\Context\Context; use Doctrine\Persistence\ObjectManager; use Monofony\Bridge\Behat\Service\SharedStorageInterface; use Monofony\Contracts\Core\Model\User\AppUserInterface; use Sylius\Component\User\Model\UserInterface; use Sylius\Component\User\Repository\UserRepositoryInterface; use Zenstruck\Foundry\Proxy; class UserContext implements Context { public function __construct( private SharedStorageInterface $sharedStorage, private UserRepositoryInterface $appUserRepository, private AppUserFactory $appUserFactory, private ObjectManager $appUserManager, ) { } /** * @Given there is a user :email identified by :password * @Given there was account of :email with password :<PASSWORD> * @Given there is a user :email */ public function thereIsUserIdentifiedBy(string $email, string $password = '<PASSWORD>'): void { $user = $this->appUserFactory ->createOne(['email' => $email, 'password' => $<PASSWORD>, 'enabled' => true]) ->disableAutoRefresh() ; $this->sharedStorage->set('user', $user); } /** * @Given the account of :email was deleted * @Given my account :email was deleted */ public function accountWasDeleted(string $email): void { /** @var AppUserInterface $user */ $user = $this->appUserRepository->findOneByEmail($email); $this->sharedStorage->set('customer', $user->getCustomer()); $this->appUserRepository->remove($user); } /** * @Given /^(?:(I) have|(this user) has) already received a resetting password email$/ */ public function iHaveReceivedResettingPasswordEmail(UserInterface|Proxy $user): void { $this->prepareUserPasswordResetToken($user); } private function prepareUserPasswordResetToken(UserInterface|Proxy $user): void { $token = '<PASSWORD>'; $user->setPasswordResetToken($token); $user->setPasswordRequestedAt(new \DateTime()); if ($user instanceof Proxy) { $user->save(); return; } $this->appUserManager->flush(); } } <file_sep># -*- coding: utf-8 -*- """ :copyright: (c) 2010-2012 <NAME> :license: MIT, see LICENSE for more details. """ from docutils.parsers.rst import Directive, directives from docutils import nodes from string import upper class configurationblock(nodes.General, nodes.Element): pass class ConfigurationBlock(Directive): has_content = True required_arguments = 0 optional_arguments = 0 final_argument_whitespace = True option_spec = {} formats = { 'html': 'HTML', 'xml': 'XML', 'php': 'PHP', 'yaml': 'YAML', 'jinja': 'Twig', 'html+jinja': 'Twig', 'jinja+html': 'Twig', 'php+html': 'PHP', 'html+php': 'PHP', 'ini': 'INI', 'php-annotations': 'Annotations', 'php-standalone': 'Standalone Use', 'php-symfony': 'Framework Use', } def run(self): env = self.state.document.settings.env node = nodes.Element() node.document = self.state.document self.state.nested_parse(self.content, self.content_offset, node) entries = [] for i, child in enumerate(node): if isinstance(child, nodes.literal_block): # add a title (the language name) before each block #targetid = "configuration-block-%d" % env.new_serialno('configuration-block') #targetnode = nodes.target('', '', ids=[targetid]) #targetnode.append(child) innernode = nodes.emphasis(self.formats[child['language']], self.formats[child['language']]) para = nodes.paragraph() para += [innernode, child] entry = nodes.list_item('') entry.append(para) entries.append(entry) resultnode = configurationblock() resultnode.append(nodes.bullet_list('', *entries)) return [resultnode] def visit_configurationblock_html(self, node): self.body.append(self.starttag(node, 'div', CLASS='configuration-block')) def depart_configurationblock_html(self, node): self.body.append('</div>\n') def visit_configurationblock_latex(self, node): pass def depart_configurationblock_latex(self, node): pass def setup(app): app.add_node(configurationblock, html=(visit_configurationblock_html, depart_configurationblock_html), latex=(visit_configurationblock_latex, depart_configurationblock_latex)) app.add_directive('configuration-block', ConfigurationBlock) <file_sep>## Change Log ### v0.4.0 (2020/10/28 08:06 +00:00) - [#239](https://github.com/Monofony/Monofony/pull/239) Feature/update documentation (@loic425) - [#238](https://github.com/Monofony/Monofony/pull/238) Fix monofony api recipes (@loic425) - [#236](https://github.com/Monofony/Monofony/pull/236) Fix Sylius user bridge autoload (@loic425) - [#237](https://github.com/Monofony/Monofony/pull/237) Add Sylius user bridge on core pack (@loic425) - [#232](https://github.com/Monofony/Monofony/pull/232) Fix/few fixes (@loic425) - [#229](https://github.com/Monofony/Monofony/pull/229) Register OAuth Client Manager test (@loic425) - [#228](https://github.com/Monofony/Monofony/pull/228) Fix packs dependencies (@loic425) - [#227](https://github.com/Monofony/Monofony/pull/227) Upgrade dependencies (@loic425) - [#226](https://github.com/Monofony/Monofony/pull/226) Fix few Monofony namespaces (@loic425) - [#225](https://github.com/Monofony/Monofony/pull/225) Fix symfony process version on core pack (@loic425) - [#221](https://github.com/Monofony/Monofony/pull/221) Fix sylius docs link (@loic425) - [#220](https://github.com/Monofony/Monofony/pull/220) Front pack (@loic425) - [#219](https://github.com/Monofony/Monofony/pull/219) Packs (@loic425) - [#218](https://github.com/Monofony/Monofony/pull/218) Test core pack (@loic425) - [#217](https://github.com/Monofony/Monofony/pull/217) Less dependencies on core bundle (@loic425) - [#214](https://github.com/Monofony/Monofony/pull/214) Test admin package (@loic425) - [#213](https://github.com/Monofony/Monofony/pull/213) Testing core bundle (@loic425) - [#212](https://github.com/Monofony/Monofony/pull/212) Move string inflector into Core component (@loic425) - [#208](https://github.com/Monofony/Monofony/pull/208) Fix core contracts autoload (@loic425) - [#207](https://github.com/Monofony/Monofony/pull/207) Refactor bridges and tests (@loic425) - [#206](https://github.com/Monofony/Monofony/pull/206) Add some phpstan to test packages (@loic425) - [#205](https://github.com/Monofony/Monofony/pull/205) Bump phpstan/phpstan-symfony from 0.12.8 to 0.12.10 (@dependabot-preview[bot]) - [#204](https://github.com/Monofony/Monofony/pull/204) Test packages (@loic425) - [#203](https://github.com/Monofony/Monofony/pull/203) Test packages (@loic425) - [#202](https://github.com/Monofony/Monofony/pull/202) Monofony bridges (@loic425) - [#201](https://github.com/Monofony/Monofony/pull/201) Rename recipe directory (@loic425) - [#200](https://github.com/Monofony/Monofony/pull/200) Move tests pack into pack directory (@loic425) - [#199](https://github.com/Monofony/Monofony/pull/199) Move core interfaces into contracts (@loic425) - [#198](https://github.com/Monofony/Monofony/pull/198) Move core recipes (@loic425) - [#195](https://github.com/Monofony/Monofony/pull/195) Remove admin bundle (@loic425) - [#194](https://github.com/Monofony/Monofony/pull/194) Remove front directory into front pack (@loic425) - [#193](https://github.com/Monofony/Monofony/pull/193) Remove front bundle (@loic425) - [#192](https://github.com/Monofony/Monofony/pull/192) Remove templates and translations directory (@loic425) - [#191](https://github.com/Monofony/Monofony/pull/191) Move admin dashboard and menu into admin component (@loic425) - [#190](https://github.com/Monofony/Monofony/pull/190) Move client manager on fos bridge (@loic425) - [#189](https://github.com/Monofony/Monofony/pull/189) Move client manager into sylius bridge (@loic425) - [#188](https://github.com/Monofony/Monofony/pull/188) Behat bridge (@loic425, @dependabot-preview[bot]) - [#187](https://github.com/Monofony/Monofony/pull/187) Prepare 0.4.0 release (@loic425) - [#186](https://github.com/Monofony/Monofony/pull/186) Upgrade yarn dependencies (@loic425) - [#185](https://github.com/Monofony/Monofony/pull/185) [API] Update profile (@loic425) - [#184](https://github.com/Monofony/Monofony/pull/184) [API] Reset password (@loic425) - [#182](https://github.com/Monofony/Monofony/pull/182) Bump phpspec/phpspec from 5.1.2 to 6.2.1 (@dependabot-preview[bot]) - [#180](https://github.com/Monofony/Monofony/pull/180) Fix app name on Travis (@loic425) - [#179](https://github.com/Monofony/Monofony/pull/179) Update Monorepo builder config (@loic425) - [#178](https://github.com/Monofony/Monofony/pull/178) Upgrade phpstan (@loic425) - [#174](https://github.com/Monofony/Monofony/pull/174) Bump symfony/flex from 1.6.2 to 1.9.10 (@dependabot-preview[bot]) - [#177](https://github.com/Monofony/Monofony/pull/177) Request new password endpoint (@loic425) <file_sep><?php declare(strict_types=1); namespace App\Story; use App\Factory\AppUserFactory; use Zenstruck\Foundry\Story; final class DefaultAppUsersStory extends Story { public function build(): void { AppUserFactory::createOne([ 'email' => '<EMAIL>', 'password' => '<PASSWORD>', ]); } } <file_sep>.. rst-class:: outdated .. danger:: This is an outdated documentation please read the new `Monofony documentation`_ instead. How to add a new context? ========================= Thanks to symfony autowiring, most of your contexts are ready to use. But if you need to manually route an argument, it is needed to add a service in ``config/services_test.yaml`` file. .. code-block:: yaml App\Tests\Behat\Context\CONTEXT_CATEGORY\CONTEXT_NAME: arguments: $specificArgument: App\SpecificArgument Then you can use it in your suite configuration: .. code-block:: yaml default: suites: SUITE_NAME: contexts: - 'App\Tests\Behat\Context\CONTEXT_CATEGORY\CONTEXT_NAME' filters: tags: "@SUITE_TAG" .. note:: The context categories are usually one of ``cli``, ``hook``, ``setup``, ``transform``, ``ui``. .. _Monofony documentation: https://docs.monofony.com <file_sep>.. rst-class:: outdated .. danger:: This is an outdated documentation please read the new `Monofony documentation`_ instead. The Book ======== Here you will find all the concepts used in Monofony. The Books helps to understand how Monofony works. Architecture ------------ The key to understanding principles of Sylius internal organization. Here you will learn about the Resource layer, state machines, events and general non e-commerce concepts adopted in the platform, like E-mails or Fixtures. .. toctree:: :hidden: architecture/index .. include:: /book/architecture/map.rst.inc Users ----- This chapter will tell you more about the way Sylius handles users, customers and admins. .. toctree:: :hidden: user/index .. include:: /book/user/map.rst.inc .. _Monofony documentation: https://docs.monofony.com <file_sep><?php declare(strict_types=1); namespace App\Grid; use App\Entity\Customer\Customer; use Sylius\Bundle\GridBundle\Builder\Action\CreateAction; use Sylius\Bundle\GridBundle\Builder\Action\ShowAction; use Sylius\Bundle\GridBundle\Builder\Action\UpdateAction; use Sylius\Bundle\GridBundle\Builder\ActionGroup\ItemActionGroup; use Sylius\Bundle\GridBundle\Builder\ActionGroup\MainActionGroup; use Sylius\Bundle\GridBundle\Builder\Field\DateTimeField; use Sylius\Bundle\GridBundle\Builder\Field\StringField; use Sylius\Bundle\GridBundle\Builder\Filter\StringFilter; use Sylius\Bundle\GridBundle\Builder\GridBuilderInterface; use Sylius\Bundle\GridBundle\Grid\AbstractGrid; use Sylius\Bundle\GridBundle\Grid\ResourceAwareGridInterface; final class CustomerGrid extends AbstractGrid implements ResourceAwareGridInterface { public static function getName(): string { return 'sylius_backend_customer'; } public function buildGrid(GridBuilderInterface $gridBuilder): void { $gridBuilder ->orderBy('createdAt', 'desc') ->addField( StringField::create('firstName') ->setLabel('sylius.ui.first_name') ->setSortable(true) ) ->addField( StringField::create('lastName') ->setLabel('sylius.ui.last_name') ->setSortable(true) ) ->addField( StringField::create('email') ->setLabel('sylius.ui.email') ->setSortable(true) ) ->addField( DateTimeField::create('createdAt') ->setLabel('sylius.ui.registration_date') ->setSortable(true) ) ->addFilter(StringFilter::create('search', ['email', 'firstName', 'lastName'])) ->addActionGroup( MainActionGroup::create( CreateAction::create(), ) ) ->addActionGroup( ItemActionGroup::create( ShowAction::create(), UpdateAction::create(), ) ) ; } public function getResourceClass(): string { return Customer::class; } } <file_sep><?php /* * This file is part of the Monofony package. * * (c) Monofony * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace App\Monofony\Bundle\CoreBundle\Tests\DependencyInjection\Compiler; use App\OpenApi\Factory\AppAuthenticationTokenOpenOpenApiFactory; use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractCompilerPassTestCase; use Monofony\Bundle\CoreBundle\DependencyInjection\Compiler\RegisterOpenApiFactoriesPass; use Symfony\Component\DependencyInjection\ContainerBuilder; final class RegisterOpenApiFactoriesPassTest extends AbstractCompilerPassTestCase { /** @test */ public function it_registers_app_authentication_token_documentation_normalizer(): void { $this->container->register(AppAuthenticationTokenOpenOpenApiFactory::class, AppAuthenticationTokenOpenOpenApiFactory::class); $definition = $this->container->findDefinition(AppAuthenticationTokenOpenOpenApiFactory::class); $definition->addTag('monofony.openapi.factory.app_authentication_token'); $this->compile(); $definition = $this->container->findDefinition(AppAuthenticationTokenOpenOpenApiFactory::class); $this->assertEquals([ 'api_platform.openapi.factory', null, -10, ], $definition->getDecoratedService()); $this->assertEquals( AppAuthenticationTokenOpenOpenApiFactory::class.'.inner', $definition->getArgument(0), ); } protected function registerCompilerPass(ContainerBuilder $container): void { $container->addCompilerPass(new RegisterOpenApiFactoriesPass()); } } <file_sep><?php declare(strict_types=1); namespace App\Tests\Behat\Context\Ui\Frontend; use Behat\Behat\Context\Context; class HomepageContext implements Context { } <file_sep>sphinx>=1.4,<2.0 requests[security] <file_sep><?php declare(strict_types=1); namespace App\Tests\Behat\Context\Ui\Backend; use App\Tests\Behat\Page\Backend\DashboardPage; use Behat\Behat\Context\Context; use Webmozart\Assert\Assert; class DashboardContext implements Context { public function __construct(private DashboardPage $dashboardPage) { } /** * @When I open administration dashboard */ public function iOpenAdministrationDashboard() { $this->dashboardPage->open(); } /** * @Then I should see :number new customers in the list */ public function iShouldSeeNewCustomersInTheList(int $number) { Assert::same($this->dashboardPage->getNumberOfNewCustomersInTheList(), $number); } /** * @Then I should see :number new customers */ public function iShouldSeeNewCustomers(int $number) { Assert::same($this->dashboardPage->getNumberOfNewCustomers(), $number); } } <file_sep><?php declare(strict_types=1); namespace App\Tests\Controller; use Doctrine\Bundle\DoctrineBundle\Registry; use Doctrine\Common\DataFixtures\Purger\ORMPurger; use Doctrine\ORM\EntityManagerInterface; use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; use Symfony\Component\HttpKernel\KernelInterface; /** * @mixin KernelTestCase */ trait PurgeDatabaseTrait { /** * @internal * @before */ public static function _resetSchema(): void { if (!\is_subclass_of(static::class, KernelTestCase::class)) { throw new \RuntimeException(\sprintf('The "%s" trait can only be used on TestCases that extend "%s".', __TRAIT__, KernelTestCase::class)); } $kernel = static::createKernel(); $kernel->boot(); static::_purgeDatabase($kernel); $kernel->shutdown(); } public static function _purgeDatabase(KernelInterface $kernel): void { if (!$kernel->getContainer()->has('doctrine')) { return; } /** @var Registry $registry */ $registry = $kernel->getContainer()->get('doctrine'); /** @var EntityManagerInterface $entityManager */ $entityManager = $registry->getManager(); $purger = new ORMPurger($entityManager); $purger->purge(); $entityManager->clear(); } } <file_sep><?php declare(strict_types=1); namespace App\Command\Installer; use App\Command\Helper\CommandsRunner; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; class InstallAssetsCommand extends Command { protected static $defaultName = 'app:install:assets'; public function __construct( private CommandsRunner $commandsRunner, private string $environment ) { parent::__construct(); } /** * {@inheritdoc} */ protected function configure(): void { $this->setDescription('Installs all AppName assets.') ->setHelp( <<<EOT The <info>%command.name%</info> command downloads and installs all AppName media assets. EOT ) ; } /** * {@inheritdoc} * * @throws \Exception */ protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $io->title(sprintf('Installing AppName assets for environment <info>%s</info>.', $this->environment)); $commands = [ 'assets:install', ]; $this->commandsRunner->run($commands, $input, $output, $this->getApplication()); return 0; } } <file_sep><?php /* * This file is part of the Monofony package. * * (c) Monofony * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Monofony\Component\Admin\Menu; use Knp\Menu\ItemInterface; interface AdminMenuBuilderInterface { public function createMenu(array $options): ItemInterface; } <file_sep>Contributing Patches ==================== Monofony is a Open Source project driven by the community. Join our amazing adventure and we promise to be nice and welcoming to everyone. Remember, you do not have to be a Symfony guru or even a programmer to help! <file_sep><?php declare(strict_types=1); namespace App\Message; use Symfony\Component\Security\Core\Validator\Constraints as SecurityAssert; use Symfony\Component\Serializer\Annotation\Groups; use Symfony\Component\Validator\Constraints\NotBlank; final class ChangeAppUserPassword implements AppUserIdAwareInterface { public ?int $appUserId = null; /** * @SecurityAssert\UserPassword(message="sylius.user.plainPassword.wrong_current") */ #[NotBlank] #[Groups(groups: ['customer:password:write'])] public ?string $currentPassword; #[NotBlank] #[Groups(groups: ['customer:password:write'])] public ?string $newPassword; public function __construct(?string $currentPassword = null, ?string $newPassword = null) { $this->currentPassword = $<PASSWORD>; $this->newPassword = $<PASSWORD>; } public function getAppUserId(): ?int { return $this->appUserId; } public function setAppUserId(?int $appUserId): void { $this->appUserId = $appUserId; } } <file_sep><?php /* * This file is part of the Monofony package. * * (c) Monofony * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Monofony\Bridge\Behat\Service\Resolver; use FriendsOfBehat\PageObjectExtension\Page\SymfonyPageInterface; interface CurrentPageResolverInterface { /** * @param SymfonyPageInterface[] $pages * * @return SymfonyPageInterface */ public function getCurrentPageWithForm(array $pages); } <file_sep>import $ from 'jquery'; const displayUploadedFile = function displayUploadedFile(input) { debugger; if (input.files && input.files[0]) { const reader = new FileReader(); reader.onload = (event) => { const $link = $(input).parent().siblings('a'); const fileName = $(input).val().split('\\').pop(); $link.removeAttr('href'); $link.addClass('disabled'); $('.filename', $link).html(fileName); $link.show(); }; reader.readAsDataURL(input.files[0]); } }; $.fn.extend({ previewUploadedFile(root) { $(root).on('change', 'input[type="file"]', function () { displayUploadedFile(this); }); }, }); <file_sep>.. rst-class:: outdated .. danger:: This is an outdated documentation please read the new `Monofony documentation`_ instead. The Cookbook ============ Entities -------- .. toctree:: :hidden: entities/first-resource entities/manage-your-entity entities/configure-your-routes entities/configure-backend-menu .. include:: /cookbook/entities/map.rst.inc Fixtures -------- .. toctree:: :hidden: fixtures/factory fixtures/fixture fixtures/suite fixtures/load .. include:: /cookbook/fixtures/map.rst.inc BDD --- .. toctree:: :hidden: bdd/phpspec/index bdd/behat/index .. include:: /cookbook/bdd/map.rst.inc Dashboard --------- .. toctree:: :hidden: dashboard/index dashboard/basic-example .. include:: /cookbook/dashboard/map.rst.inc .. _Monofony documentation: https://docs.monofony.com <file_sep>Sylius Bridge ============= Provides integration for [Sylius](https://sylius.com/) with various Monofony components. Resources --------- * [Report issues](https://github.com/Monofony/Monofony/issues) and [send Pull Requests](https://github.com/Monofony/Monofony/pulls) in the [main Monofony repository](https://github.com/Monofony/Monofony) <file_sep><?php declare(strict_types=1); namespace App\Tests\Behat\Page\Backend\Administrator; use Monofony\Bridge\Behat\Crud\AbstractIndexPage; use Monofony\Bridge\Behat\Crud\IndexPageInterface; class IndexPage extends AbstractIndexPage implements IndexPageInterface { public function getRouteName(): string { return 'sylius_backend_admin_user_index'; } } <file_sep><?php declare(strict_types=1); namespace App\Entity\Media; use App\Entity\IdentifiableTrait; use Doctrine\ORM\Mapping as ORM; use Monofony\Contracts\Core\Model\Media\FileInterface; use Sylius\Component\Resource\Model\ResourceInterface; use Symfony\Component\Serializer\Annotation\Groups; /** * @ORM\MappedSuperclass */ abstract class File implements FileInterface, ResourceInterface { use IdentifiableTrait; protected ?\SplFileInfo $file = null; #[ORM\Column(type: 'string')] #[Groups(groups: ['Default', 'Detailed'])] protected ?string $path = null; #[ORM\Column(type: 'datetime')] protected \DateTimeInterface $createdAt; #[ORM\Column(type: 'datetime', nullable: true)] protected ?\DateTimeInterface $updatedAt = null; public function __construct() { $this->createdAt = new \DateTimeImmutable(); } /** * {@inheritdoc} */ public function getFile(): ?\SplFileInfo { return $this->file; } /** * {@inheritdoc} */ public function setFile(?\SplFileInfo $file): void { $this->file = $file; // VERY IMPORTANT: // It is required that at least one field changes if you are using Doctrine, // otherwise the event listeners won't be called and the file is lost if ($file) { // if 'updatedAt' is not defined in your entity, use another property $this->updatedAt = new \DateTime('now'); } } /** * {@inheritdoc} */ public function getPath(): ?string { return $this->path; } /** * {@inheritdoc} */ public function setPath(?string $path): void { $this->path = $path; } public function getCreatedAt(): \DateTimeInterface { return $this->createdAt; } public function setCreatedAt(\DateTimeInterface $createdAt): void { $this->createdAt = $createdAt; } } <file_sep><?php declare(strict_types=1); namespace App\Tests\Controller; trait AuthorizedHeaderTrait { private static array $authorizedHeaderWithContentType = [ 'HTTP_Authorization' => 'Bearer <KEY>', 'CONTENT_TYPE' => 'application/json', ]; private static array $authorizedHeaderWithAccept = [ 'HTTP_Authorization' => 'Bearer <KEY>', 'ACCEPT' => 'application/json', ]; private static array $authorizedHeaderForPatch = [ 'HTTP_Authorization' => '<KEY>', 'CONTENT_TYPE' => 'application/merge-patch+json', ]; } <file_sep>.. rst-class:: outdated .. danger:: This is an outdated documentation please read the new `Monofony documentation`_ instead. How to define a new suite? ========================== To define a new suite it is needed to create a suite configuration file in a one of ``cli``/``ui`` directory inside ``config/suites``. Then register that file in ``config/suites.yaml``. .. _Monofony documentation: https://docs.monofony.com <file_sep>.. rst-class:: outdated .. danger:: This is an outdated documentation please read the new `Monofony documentation`_ instead. How to use Phpspec to design your code -------------------------------------- .. toctree:: :hidden: how-to-configure-phpspec-with-code-coverage how-to-disable-phpspec-code-coverage how-to-design-entities-with-phpspec how-to-design-services-with-phpspec .. include:: /cookbook/bdd/phpspec/map.rst.inc Learn more ---------- .. note:: To learn more, read the `Phpspec documentation <http://www.phpspec.net/en/stable/manual/introduction.html>`_. .. _Monofony documentation: https://docs.monofony.com <file_sep>## Change Log ### v0.7.1 (2021/09/21 21:13 +00:00) - [#349](https://github.com/Monofony/Monofony/pull/349) Fix identifiable trait (@loic425) - [#348](https://github.com/Monofony/Monofony/pull/348) Fix validating composer (@loic425) - [#345](https://github.com/Monofony/Monofony/pull/345) Bump path-parse from 1.0.6 to 1.0.7 (@dependabot[bot]) - [#343](https://github.com/Monofony/Monofony/pull/343) Fix package versions (@loic425) - ### v0.7.0 (2021/06/14 15:11 +00:00) - [#342](https://github.com/Monofony/Monofony/pull/342) Add support for Symfony 5.3 (@loic425) - [#340](https://github.com/Monofony/Monofony/pull/340) Fix data collector (@loic425) - [#341](https://github.com/Monofony/Monofony/pull/341) Fix CI build (@loic425) - [#309](https://github.com/Monofony/Monofony/pull/309) Bump elliptic from 6.5.3 to 6.5.4 (@dependabot[bot]) - [#314](https://github.com/Monofony/Monofony/pull/314) Bump y18n from 3.2.1 to 3.2.2 (@dependabot[bot]) - [#330](https://github.com/Monofony/Monofony/pull/330) Bump ssri from 6.0.1 to 6.0.2 (@dependabot[bot]) - [#329](https://github.com/Monofony/Monofony/pull/329) Upgrade node dependencies (@loic425) - [#327](https://github.com/Monofony/Monofony/pull/327) Improve types on entities (@loic425) - [#328](https://github.com/Monofony/Monofony/pull/328) Drop Symfony 5.1 support (@loic425) - [#326](https://github.com/Monofony/Monofony/pull/326) Fix missing param types (@loic425) - [#325](https://github.com/Monofony/Monofony/pull/325) Add missing property types (@loic425) <file_sep><?php declare(strict_types=1); namespace App\Entity\Customer; use App\Entity\User\AppUser; use Doctrine\ORM\Mapping as ORM; use Monofony\Contracts\Core\Model\Customer\CustomerInterface; use Monofony\Contracts\Core\Model\User\AppUserInterface; use Sylius\Component\Customer\Model\Customer as BaseCustomer; use Sylius\Component\User\Model\UserInterface; use Symfony\Component\Validator\Constraints\Valid; use Webmozart\Assert\Assert; #[ORM\Entity] #[ORM\Table(name: 'sylius_customer')] class Customer extends BaseCustomer implements CustomerInterface { #[ORM\OneToOne(mappedBy: 'customer', targetEntity: AppUser::class, cascade: ['persist'])] #[Valid] private ?UserInterface $user = null; /** * {@inheritdoc} */ public function getUser(): ?UserInterface { return $this->user; } /** * {@inheritdoc} */ public function setUser(?UserInterface $user): void { if ($this->user === $user) { return; } Assert::nullOrIsInstanceOf($user, AppUserInterface::class); $previousUser = $this->user; $this->user = $user; if ($previousUser instanceof AppUserInterface) { $previousUser->setCustomer(null); } if ($user instanceof AppUserInterface) { $user->setCustomer($this); } } } <file_sep><?php /* * This file is part of the Monofony package. * * (c) Monofony * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Monofony\Bundle\CoreBundle\DependencyInjection\Compiler; use Doctrine\Persistence\ObjectManager; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; final class RegisterObjectManagerAliasPass implements CompilerPassInterface { public function process(ContainerBuilder $container): void { if (!interface_exists(ObjectManager::class)) { return; } if (!$container->hasDefinition(ObjectManager::class)) { $container->setAlias(ObjectManager::class, 'doctrine.orm.default_entity_manager'); } } } <file_sep><?php declare(strict_types=1); namespace App\Tests\Behat\Page\Backend\Account; use FriendsOfBehat\PageObjectExtension\Page\SymfonyPage; class LoginPage extends SymfonyPage { public function hasValidationErrorWith(string $message): bool { return $this->getElement('validation_error')->getText() === $message; } public function logIn(): void { $this->getDocument()->pressButton('Login'); } public function specifyPassword(string $password): void { $this->getDocument()->fillField('Password', $password); } public function specifyUsername(string $username): void { $this->getDocument()->fillField('Username', $username); } public function getRouteName(): string { return 'sylius_backend_login'; } protected function getDefinedElements(): array { return array_merge(parent::getDefinedElements(), [ 'validation_error' => '.message.negative', ]); } } <file_sep><?php declare(strict_types=1); namespace App\Provider; use Monofony\Contracts\Core\Model\Customer\CustomerInterface; use Sylius\Component\Resource\Factory\FactoryInterface; use Sylius\Component\Resource\Repository\RepositoryInterface; use Sylius\Component\User\Canonicalizer\CanonicalizerInterface; final class CustomerProvider implements CustomerProviderInterface { public function __construct( private CanonicalizerInterface $canonicalizer, private FactoryInterface $customerFactory, private RepositoryInterface $customerRepository, ) { } public function provide(string $email): CustomerInterface { $emailCanonical = $this->canonicalizer->canonicalize($email); /** @var CustomerInterface|null $customer */ $customer = $this->customerRepository->findOneBy(['emailCanonical' => $emailCanonical]); if (null === $customer) { /** @var CustomerInterface $customer */ $customer = $this->customerFactory->createNew(); $customer->setEmail($email); } return $customer; } } <file_sep>* :doc:`/cookbook/dashboard/index` * :doc:`/cookbook/dashboard/basic-example` <file_sep>var build = require('../config-builder'); module.exports = build('backend'); <file_sep><?php /* * This file is part of the Monofony package. * * (c) Monofony * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Monofony\Bridge\Behat\Service; use Behat\Mink\Driver\DriverInterface; use Behat\Mink\Driver\PantherDriver; use Behat\Mink\Driver\Selenium2Driver; use DMore\ChromeDriver\ChromeDriver; final class DriverHelper { public static function isJavascriptSession(DriverInterface $driver): bool { return $driver instanceof Selenium2Driver || $driver instanceof ChromeDriver || $driver instanceof PantherDriver ; } } <file_sep>## Change Log ### v0.8.0 (2022/04/28 07:40 +00:00) - [#427](https://github.com/Monofony/Monofony/pull/427) Refactor README page (@loic425) - [#426](https://github.com/Monofony/Monofony/pull/426) Use an interface for documentation serializers (@loic425) - [#425](https://github.com/Monofony/Monofony/pull/425) Use Resource & grid stable releases (@loic425) ### v0.8.0-beta.4 (2022/04/26 15:56 +00:00) - [#424](https://github.com/Monofony/Monofony/pull/424) Enable Psalm on 8.1 (@loic425) - [#423](https://github.com/Monofony/Monofony/pull/423) Simplify PHPStan config (@loic425) - [#422](https://github.com/Monofony/Monofony/pull/422) PHPStan fix (@loic425) - [#420](https://github.com/Monofony/Monofony/pull/420) Fix date type extension spec (@loic425) ### v0.8.0-beta.3 (2022/04/26 10:24 +00:00) - [#410](https://github.com/Monofony/Monofony/pull/410) Bump minimist from 1.2.5 to 1.2.6 (@dependabot[bot]) - [#419](https://github.com/Monofony/Monofony/pull/419) Use factories on api tests (@loic425) - [#418](https://github.com/Monofony/Monofony/pull/418) Upgrade sass-loder (@loic425) - [#397](https://github.com/Monofony/Monofony/pull/397) Bump follow-redirects from 1.14.5 to 1.14.8 (@dependabot[bot]) - [#399](https://github.com/Monofony/Monofony/pull/399) Bump url-parse from 1.5.3 to 1.5.10 (@dependabot[bot]) - [#417](https://github.com/Monofony/Monofony/pull/417) Testing with PHP 8.1 (@loic425) - [#416](https://github.com/Monofony/Monofony/pull/416) Bump Phpspec version (@loic425) - [#414](https://github.com/Monofony/Monofony/pull/414) Bump async from 2.6.3 to 2.6.4 (@dependabot[bot]) - [#415](https://github.com/Monofony/Monofony/pull/415) Fix refresh token api test (@loic425) - [#413](https://github.com/Monofony/Monofony/pull/413) Fix the build (@loic425) - [#412](https://github.com/Monofony/Monofony/pull/412) Do not store proxy on shared storage (@loic425) - [#411](https://github.com/Monofony/Monofony/pull/411) Improve code quality (@loic425) ### v0.8.0-beta.2 (2022/03/31 11:56 +00:00) - [#409](https://github.com/Monofony/Monofony/pull/409) fix jms prod configuration (@smildev) - [#407](https://github.com/Monofony/Monofony/pull/407) Add support for panther extension (@smildev, @loic425) - [#405](https://github.com/Monofony/Monofony/pull/405) Fix admin avatar path (@loic425) - [#403](https://github.com/Monofony/Monofony/pull/403) Remove Sylius forks (@loic425) - [#401](https://github.com/Monofony/Monofony/pull/401) Remove FOS Oauth server bundle (@loic425) - [#400](https://github.com/Monofony/Monofony/pull/400) JWT authentication (@loic425) ### v0.8.0-beta.1 (2022/02/10 14:10 +00:00) - [#395](https://github.com/Monofony/Monofony/pull/395) Bump Resource & grid to beta versions (@loic425) ### v0.8.0-alpha.6 (2022/02/09 17:38 +00:00) - [#394](https://github.com/Monofony/Monofony/pull/394) Remove tag whitespaces (@loic425) - [#393](https://github.com/Monofony/Monofony/pull/393) Upgrade Sylius dependencies (@loic425) ### v0.8.0-alpha.5 (2022/01/20 10:39 +00:00) - [#392](https://github.com/Monofony/Monofony/pull/392) Fix password hasher (@loic425) ### v0.8.0-alpha.4 (2022/01/20 07:47 +00:00) - [#391](https://github.com/Monofony/Monofony/pull/391) Fix/meta to library for now (@loic425) ### v0.8.0-alpha.3 (2022/01/19 16:34 +00:00) - [#389](https://github.com/Monofony/Monofony/pull/389) Split meta packages (@loic425) - [#388](https://github.com/Monofony/Monofony/pull/388) Front metapackage (@loic425) - [#387](https://github.com/Monofony/Monofony/pull/387) API metapackage (@loic425) - [#386](https://github.com/Monofony/Monofony/pull/386) Core metapackage (@loic425) - [#385](https://github.com/Monofony/Monofony/pull/385) Move admin-pack recipes into admin metapackage (@loic425) ### v0.8.0-alpha.2 (2022/01/04 09:36 +00:00) - [#380](https://github.com/Monofony/Monofony/pull/380) Fix password reset template if front pack is not installed (@loic425) - [#383](https://github.com/Monofony/Monofony/pull/383) Fix return type hints on forms (@loic425) - [#382](https://github.com/Monofony/Monofony/pull/382) Remove grid yaml configuration (@loic425) - [#381](https://github.com/Monofony/Monofony/pull/381) Remove Symfony 5.3 support (@loic425) ### v0.8.0-alpha.1 (2022/01/03 17:24 +00:00) - [#379](https://github.com/Monofony/Monofony/pull/379) Use Symfony style for commands (@loic425) - [#378](https://github.com/Monofony/Monofony/pull/378) Bump Symfony flex version from 1.17 to 2.0 (@loic425) - [#377](https://github.com/Monofony/Monofony/pull/377) Use Foundry for data fixtures (@loic425) - [#376](https://github.com/Monofony/Monofony/pull/376) Attributes for Doctrine mapping (@loic425) - [#375](https://github.com/Monofony/Monofony/pull/375) Template events on admin layout (@loic425) - [#374](https://github.com/Monofony/Monofony/pull/374) Use grids as service (@loic425) - [#373](https://github.com/Monofony/Monofony/pull/373) Fix Symfony packs for Flex (@loic425) - [#372](https://github.com/Monofony/Monofony/pull/372) Constructor promotion (@loic425) - [#371](https://github.com/Monofony/Monofony/pull/371) Remove Symfony 6 support for now (@loic425) - [#370](https://github.com/Monofony/Monofony/pull/370) Remove Infection (@loic425) - [#369](https://github.com/Monofony/Monofony/pull/369) [Maintenance] Some annotations to attributes (@loic425) - [#368](https://github.com/Monofony/Monofony/pull/368) Apply some typehints on Api pack (@loic425) - [#367](https://github.com/Monofony/Monofony/pull/367) Apply some typehints on Core recipes (@loic425) - [#366](https://github.com/Monofony/Monofony/pull/366) [Maintenance] Fix CI (@loic425) - [#364](https://github.com/Monofony/Monofony/pull/364) Init Rector (@loic425) - [#363](https://github.com/Monofony/Monofony/pull/363) Upgrade coding standards (@loic425) - [#361](https://github.com/Monofony/Monofony/pull/361) Upgrade PHPStan level (@loic425) - [#362](https://github.com/Monofony/Monofony/pull/362) Upgrade package alias (@loic425) - [#359](https://github.com/Monofony/Monofony/pull/359) Exclude paths on PHPStan (@loic425) - [#356](https://github.com/Monofony/Monofony/pull/356) Update sensio/framework-extra-bundle requirement from ^5.1 to ^6.2 (@dependabot[bot]) - [#331](https://github.com/Monofony/Monofony/pull/331) Upgrade to GitHub-native Dependabot (@dependabot-preview[bot]) - [#355](https://github.com/Monofony/Monofony/pull/355) [Install] Remove directory checker (@loic425) - [#354](https://github.com/Monofony/Monofony/pull/354) Outdate the legacy documentation (@loic425) <file_sep>#!/usr/bin/env php <?php use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Finder\Finder; require dirname(__DIR__).'/vendor/autoload.php'; $filesystem = new Filesystem(); $projectDir = dirname(__DIR__); removeLegacyConfigFiles($filesystem, $projectDir); updateConfig($filesystem, $projectDir); updatePhpstanConfig($filesystem, $projectDir); removeLegacyBundles($filesystem, $projectDir); replaceClasses($filesystem, $projectDir); updateKernel($filesystem, $projectDir); fixRecipes($filesystem, $projectDir); function removeLegacyConfigFiles(Filesystem $filesystem, string $projectDir): void { // $filesystem->remove($projectDir.'/config/packages/eight_points_guzzle.yaml'); // $filesystem->remove($projectDir.'/config/packages/sensio_framework_extra.yaml'); $filesystem->remove($projectDir.'/config/packages/sonata_core.yaml'); $filesystem->remove($projectDir.'/config/packages/sonata_form.yaml'); } function updateConfig(Filesystem $filesystem, string $projectDir): void { $finder = new Finder(); $finder ->files() ->in($projectDir.'/config'); $patterns = [ 'Monofony\\\Bundle\\\CoreBundle\\\Entity\\\OAuth\\\ClientManager' => 'monofony.client_manager', 'vendor\/monofony\/core-bundle\/Resources\/config\/services_test.yaml' => 'vendor\/monofony\/behat-bridge\/services_test.yaml', ]; foreach ($finder as $file) { $content = file_get_contents('config/'.$file->getRelativePathname()); foreach ($patterns as $pattern => $replacement) { $pattern = '/'.$pattern.'/s'; if (preg_match($pattern, $content)) { $content = preg_replace($pattern, $replacement, $content); $filesystem->dumpFile('config/'.$file->getRelativePathname(), $content); } } } } function updatePhpstanConfig(Filesystem $filesystem, string $projectDir): void { $replacements = [ '- vendor/proget-hq/phpstan-phpspec/extension.neon' => '', 'specDir: \'spec/\'' => '', ]; $relativePathname = $projectDir.'/phpstan.neon'; $content = file_get_contents($relativePathname); foreach ($replacements as $pattern => $replacement) { $content = str_replace($pattern, $replacement, $content); $filesystem->dumpFile($relativePathname, $content); } } function removeLegacyBundles(Filesystem $filesystem, string $projectDir): void { $bundles = [ 'Doctrine\\\Bundle\\\FixturesBundle' => '// Doctrine\\\Bundle\\\FixturesBundle', 'Sonata\\\CoreBundle\\\SonataCoreBundle::class' => '// Sonata\\\CoreBundle\\\SonataCoreBundle::class', 'Sonata\\\DatagridBundle\\\SonataDatagridBundle::class' => '// Sonata\\\DatagridBundle\\\SonataDatagridBundle::class', 'Monofony\\\Bundle\\\AdminBundle\\\MonofonyAdminBundle::class' => '// Monofony\\\Bundle\\\AdminBundle\\\MonofonyAdminBundle::class', 'Monofony\\\Bundle\\\ApiBundle\\\MonofonyApiBundle::class' => '// Monofony\\\Bundle\\\ApiBundle\\\MonofonyApiBundle::class', 'Monofony\\\Plugin\\\FixturesPlugin\\\MonofonyFixturesPlugin::class' => '// Monofony\\\Plugin\\\FixturesPlugin\\\MonofonyFixturesPlugin::class', 'Monofony\\\Bundle\\\FrontBundle\\\MonofonyFrontBundle::class' => '// Monofony\\\Bundle\\\FrontBundle\\\MonofonyFrontBundle::class', ]; $relativePathname = $projectDir.'/config/bundles.php'; $content = file_get_contents($relativePathname); foreach ($bundles as $pattern => $replacement) { $pattern = '/'.$pattern.'/s'; $content = preg_replace($pattern, $replacement, $content); $filesystem->dumpFile($relativePathname, $content); } if (!preg_match('/Sonata\\\Doctrine\\\Bridge\\\Symfony\\\SonataDoctrineSymfonyBundle::class/s', $content)) { $content = str_replace( '];', 'Sonata\Doctrine\Bridge\Symfony\SonataDoctrineSymfonyBundle::class => [\'all\' => true],'."\n".'];', $content ); $filesystem->dumpFile($relativePathname, $content); } } function replaceClasses(Filesystem $filesystem, string $projectDir): void { $finder = new Finder(); $finder ->files() ->name('*.php') ->in($projectDir) ->in($projectDir) ->exclude(['bin', 'vendor', 'var']) ; $classes = [ 'Monofony\\\Component\\\Core\\\Model\\\User\\\AdminUserInterface' => 'Monofony\\\Contracts\\\Core\\\Model\\\User\\\AdminUserInterface', 'Monofony\\\Component\\\Core\\\Model\\\User\\\AdminAvatarInterface' => 'Monofony\\\Contracts\\\Core\\\Model\\\User\\\AdminAvatarInterface', 'Monofony\\\Component\\\Core\\\Model\\\Media\\\FileInterface' => 'Monofony\\\Contracts\\\Core\\\Model\\\Media\\\FileInterface', 'Monofony\\\Component\\\Core\\\Model\\\User\\\AppUserInterface' => 'Monofony\\\Contracts\\\Core\\\Model\\\User\\\AppUserInterface', 'Monofony\\\Component\\\Core\\\Model\\\Customer\\\CustomerInterface' => 'Monofony\\\Contracts\\\Core\\\Model\\\Customer\\\CustomerInterface', 'Monofony\\\Bundle\\\AdminBundle\\\Dashboard\\\DashboardStatisticsProviderInterface' => 'Monofony\\\Contracts\\\Admin\\\Dashboard\\\DashboardStatisticsProviderInterface', 'Monofony\\\Bundle\\\CoreBundle\\\Tests\\\Behat\\\Service\\\AdminSecurityServiceInterface' => 'Monofony\\\Bridge\\\Behat\\\Service\\\AdminSecurityServiceInterface', 'Monofony\\\Bundle\\\CoreBundle\\\Tests\\\Behat\\\Service\\\SharedStorageInterface' => 'Monofony\\\Bridge\\\Behat\\\Service\\\SharedStorageInterface', 'Monofony\\\Plugin\\\FixturesPlugin\\\Fixture\\\Factory\\\AbstractExampleFactory' => 'App\\\Fixture\\\Factory\\\AbstractExampleFactory', 'Monofony\\\Plugin\\\FixturesPlugin\\\Fixture\\\Factory\\\ExampleFactoryInterface' => 'App\\\Fixture\\\Factory\\\ExampleFactoryInterface', 'Monofony\\\Bundle\\\CoreBundle\\\Tests\\\Behat' => 'Monofony\\\Bridge\\\Behat', 'Monofony\\\Bundle\\\AdminBundle\\\Tests\\\Behat' => 'Monofony\\\Bridge\\\Behat', 'Monofony\\\Bundle\\\AdminBundle\\\Dashboard\\\Statistics\\\StatisticInterface' => 'Monofony\\\Component\\\Admin\\\Dashboard\\\Statistics\\\StatisticInterface', 'Monofony\\\Bundle\\\FrontBundle\\\Menu\\\AccountMenuBuilderInterface' => 'Monofony\\\Contracts\\\Front\\\Menu\\\AccountMenuBuilderInterface', 'Monofony\\\Bundle\\\AdminBundle\\\Menu\\\AdminMenuBuilderInterface' => 'Monofony\\\Component\\\Admin\\\Menu\\\AdminMenuBuilderInterface', 'App\\\Tests\\\Behat\\\NotificationType' => 'Monofony\\\Bridge\\\Behat\\\NotificationType', 'Lakion\\\ApiTestCase\\\JsonApiTestCase' => 'ApiTestCase\\\JsonApiTestCase', 'use Monofony\\\Plugin\\\FixturesPlugin\\\Fixture\\\AbstractResourceFixture;\n' => '', 'use PSS\\\SymfonyMockerContainer\\\DependencyInjection\\\MockerContainer;\n' => '', ]; $filesystem->remove($projectDir.'/tests/Behat/NotificationType.php'); if (!is_file($projectDir.'/src/Fixture/Factory/AbstractExampleFactory.php')) { copy( 'https://raw.githubusercontent.com/Monofony/Monofony/0.4/src/Monofony/MetaPack/CoreMeta/.recipe/src/Fixture/Factory/AbstractExampleFactory.php', $projectDir.'/src/Fixture/Factory/AbstractExampleFactory.php' ); } if (!is_file($projectDir.'/src/Fixture/Factory/ExampleFactoryInterface.php')) { copy( 'https://raw.githubusercontent.com/Monofony/Monofony/0.4/src/Monofony/MetaPack/CoreMeta/.recipe/src/Fixture/Factory/ExampleFactoryInterface.php', $projectDir.'/src/Fixture/Factory/ExampleFactoryInterface.php' ); } if (!is_file($projectDir.'/src/Fixture/AbstractResourceFixture.php')) { copy( 'https://raw.githubusercontent.com/Monofony/Monofony/0.4/src/Monofony/MetaPack/CoreMeta/.recipe/src/Fixture/AbstractResourceFixture.php', $projectDir.'/src/Fixture/AbstractResourceFixture.php' ); } foreach ($finder as $file) { $content = file_get_contents($file->getRelativePathname()); foreach ($classes as $pattern => $replacement) { $pattern = '/'.$pattern.'/s'; if (preg_match($pattern, $content)) { $content = preg_replace($pattern, $replacement, $content); $filesystem->dumpFile($file->getRelativePathname(), $content); } } } } function updateKernel(Filesystem $filesystem, string $projectDir): void { $pathName = $projectDir.'/src/Kernel.php'; $content = file_get_contents($pathName); $content = str_replace('return MockerContainer::class;', '// return MockerContainer::class;', $content); $filesystem->dumpFile($pathName, $content); } function fixRecipes(Filesystem $filesystem, string $projectDir): void { $filesystem->dumpFile( $projectDir.'/templates/bundles/SyliusUiBundle/Form/theme.html.twig', file_get_contents('https://raw.githubusercontent.com/Monofony/Monofony/0.4/src/Monofony/MetaPack/CoreMeta/.recipe/templates/bundles/SyliusUiBundle/Form/theme.html.twig') ); $filesystem->dumpFile( $projectDir.'/assets/backend/js/sylius-compound-form-errors.js', file_get_contents('https://raw.githubusercontent.com/Monofony/Monofony/0.4/src/Monofony/MetaPack/AdminMeta/.recipe/assets/backend/js/sylius-compound-form-errors.js') ); } <file_sep><?php /* * This file is part of the Monofony package. * * (c) Monofony * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace spec\Monofony\Bundle\CoreBundle\DataCollector; use Monofony\Bundle\CoreBundle\DataCollector\MonofonyDataCollector; use Monofony\Bundle\CoreBundle\MonofonyCoreBundle; use PhpSpec\ObjectBehavior; use Symfony\Component\HttpKernel\DataCollector\DataCollector; class MonofonyDataCollectorSpec extends ObjectBehavior { function let(): void { $this->beConstructedWith([]); } function it_is_initializable() { $this->shouldHaveType(MonofonyDataCollector::class); } function it_is_a_data_collector(): void { $this->shouldHaveType(DataCollector::class); } function it_can_get_version(): void { $this->getVersion()->shouldReturn(MonofonyCoreBundle::VERSION); } } <file_sep>test: validate test-phpspec analyse test-phpunit test-installer test-fixtures test-behat test-doctrine-migrations .PHONY: test analyse: test-phpstan test-psalm .PHONY: analyse fix: vendor/bin/ecs check --fix vendor/bin/ecs check --config=ecs-recipe.php --fix .PHONY: fix validate: validate-composer validate-doctrine-schema validate-twig validate-yaml-files validate-yarn-packages .PHONY: validate test-behat: test-behat-without-javascript test-behat-with-javascript test-behat-with-cli .PHONY: test-behat validate-coding-standard: vendor/bin/ecs check vendor/bin/ecs check --config=ecs-recipe.php .PHONY: validate-coding-standard validate-composer: composer validate --strict .PHONY: validate-composer validate-doctrine-schema: bin/console doctrine:schema:validate -vvv .PHONY: validate-doctrine-schema validate-twig: bin/console lint:twig src/Monofony/MetaPack/CoreMeta/.recipe/templates bin/console lint:twig src/Monofony/MetaPack/AdminMeta/.recipe/templates bin/console lint:twig src/Monofony/MetaPack/FrontMeta/.recipe/templates .PHONY: validate-twig validate-yaml-files: bin/console lint:yaml config --parse-tags .PHONY: validate-yaml-files validate-yarn-packages: yarn check .PHONY: validate-yarn-packages validate-package-version: vendor/bin/monorepo-builder validate .PHONY: validate-package-version test-phpspec: phpdbg -qrr vendor/bin/phpspec run --no-interaction -f dot .PHONY: test-phpspec test-phpstan: vendor/bin/phpstan analyse -c phpstan.neon .PHONY: test-phpstan test-psalm: vendor/bin/psalm --show-info=false .PHONY: test-psalm test-phpunit: vendor/bin/phpunit .PHONY: test-phpunit test-installer: bin/console app:install --no-interaction -vvv .PHONY: test-installer test-behat-with-cli: vendor/bin/behat --colors --strict --no-interaction -vvv -f progress --tags="@cli&&~@todo" || vendor/bin/behat --strict --no-interaction -vvv -f progress --tags="@cli&&~@todo" --rerun .PHONY: test-behat-with-cli test-doctrine-migrations: bin/console doctrine:migrations:migrate first --no-interaction bin/console doctrine:migrations:migrate latest --no-interaction .PHONY: test-doctrine-migrations test-prod-requirements: composer dump-env prod composer install --no-dev --no-interaction --prefer-dist --no-scripts .PHONY: test-prod-requirements test-behat-without-javascript: vendor/bin/behat --colors --strict --no-interaction -vvv -f progress --tags="~@javascript&&~@todo&&~@cli" || vendor/bin/behat --strict --no-interaction -vvv -f progress --tags="~@javascript&&~@todo&&~@cli" --rerun .PHONY: test-behat-without-javascript test-behat-with-javascript: vendor/bin/behat --strict --no-interaction -vvv -f progress --tags="@javascript&&~@todo&&~@cli" .PHONY: test-behat-with-javascript test-fixtures: bin/console doctrine:fixtures:load --no-interaction .PHONY: test-fixtures install-package: (cd $(path) && composer update --no-interaction --prefer-dist --no-scripts --no-plugins) .PHONY: install-package test-package-phpstan: (cd $(path) && vendor/bin/phpstan analyse -c phpstan.neon) .PHONY: test-package-phpstan clean-package: (rm -rf $(path)/vendor) (rm $(path)/composer.lock) .PHONY: clearn-package <file_sep><?php declare(strict_types=1); namespace App\Tests\Behat\Context\Ui\Frontend; use App\Tests\Behat\Page\Frontend\Account\ChangePasswordPage; use App\Tests\Behat\Page\Frontend\Account\DashboardPage; use App\Tests\Behat\Page\Frontend\Account\LoginPage; use App\Tests\Behat\Page\Frontend\Account\ProfileUpdatePage; use Behat\Behat\Context\Context; use Monofony\Bridge\Behat\NotificationType; use Monofony\Bridge\Behat\Service\NotificationCheckerInterface; use Monofony\Component\Core\Formatter\StringInflector; use Webmozart\Assert\Assert; final class AccountContext implements Context { public function __construct( private DashboardPage $dashboardPage, private ProfileUpdatePage $profileUpdatePage, private ChangePasswordPage $changePasswordPage, private LoginPage $loginPage, private NotificationCheckerInterface $notificationChecker, ) { } /** * @When I want to modify my profile */ public function iWantToModifyMyProfile(): void { $this->profileUpdatePage->open(); } /** * @When I specify the first name as :firstName * @When I remove the first name */ public function iSpecifyTheFirstName(?string $firstName = null): void { $this->profileUpdatePage->specifyFirstName($firstName); } /** * @When I specify the last name as :lastName * @When I remove the last name */ public function iSpecifyTheLastName(?string $lastName = null): void { $this->profileUpdatePage->specifyLastName($lastName); } /** * @When I specify the customer email as :email * @When I remove the customer email */ public function iSpecifyCustomerTheEmail(?string $email = null): void { $this->profileUpdatePage->specifyEmail($email); } /** * @When I save my changes * @When I try to save my changes */ public function iSaveMyChanges(): void { $this->profileUpdatePage->saveChanges(); } /** * @Then I should be notified that it has been successfully edited */ public function iShouldBeNotifiedThatItHasBeenSuccessfullyEdited(): void { $this->notificationChecker->checkNotification('has been successfully updated.', NotificationType::success()); } /** * @Then my name should be :name * @Then my name should still be :name */ public function myNameShouldBe(string $name): void { $this->dashboardPage->open(); Assert::true($this->dashboardPage->hasCustomerName($name)); } /** * @Then my email should be :email * @Then my email should still be :email */ public function myEmailShouldBe(string $email): void { $this->dashboardPage->open(); Assert::true($this->dashboardPage->hasCustomerEmail($email)); } /** * @Then /^I should be notified that the (email|password|city|street|first name|last name) is required$/ */ public function iShouldBeNotifiedThatElementIsRequired(string $element): void { Assert::true($this->profileUpdatePage->checkValidationMessageFor( StringInflector::nameToCode($element), sprintf('Please enter your %s.', $element) )); } /** * @Then /^I should be notified that the (email) is invalid$/ */ public function iShouldBeNotifiedThatElementIsInvalid(string $element): void { Assert::true($this->profileUpdatePage->checkValidationMessageFor( StringInflector::nameToCode($element), sprintf('This %s is invalid.', $element) )); } /** * @Then I should be notified that the email is already used */ public function iShouldBeNotifiedThatTheEmailIsAlreadyUsed(): void { Assert::true($this->profileUpdatePage->checkValidationMessageFor('email', 'This email is already used.')); } /** * @Given /^I want to change my password$/ */ public function iWantToChangeMyPassword(): void { $this->changePasswordPage->open(); } /** * @Given I change password from :oldPassword to :newPassword */ public function iChangePasswordTo(string $oldPassword, string $newPassword): void { $this->iSpecifyTheCurrentPasswordAs($oldPassword); $this->iSpecifyTheNewPasswordAs($newPassword); $this->iSpecifyTheConfirmationPasswordAs($newPassword); } /** * @Then I should be notified that my password has been successfully changed */ public function iShouldBeNotifiedThatMyPasswordHasBeenSuccessfullyChanged(): void { $this->notificationChecker->checkNotification('has been changed successfully!', NotificationType::success()); } /** * @Given I specify the current password as :password */ public function iSpecifyTheCurrentPasswordAs(string $password): void { $this->changePasswordPage->specifyCurrentPassword($password); } /** * @Given I specify the new password as :password */ public function iSpecifyTheNewPasswordAs(string $password): void { $this->changePasswordPage->specifyNewPassword($password); } /** * @Given I confirm this password as :password */ public function iSpecifyTheConfirmationPasswordAs(string $password): void { $this->changePasswordPage->specifyConfirmationPassword($password); } /** * @Then I should be notified that provided password is different than the current one */ public function iShouldBeNotifiedThatProvidedPasswordIsDifferentThanTheCurrentOne(): void { Assert::true($this->changePasswordPage->checkValidationMessageFor( 'current_password', 'Provided password is different than the current one.' )); } /** * @Then I should be notified that the entered passwords do not match */ public function iShouldBeNotifiedThatTheEnteredPasswordsDoNotMatch(): void { Assert::true($this->changePasswordPage->checkValidationMessageFor( 'new_password', 'The entered passwords don\'t match' )); } /** * @Then I should be notified that the password should be at least 4 characters long */ public function iShouldBeNotifiedThatThePasswordShouldBeAtLeastCharactersLong(): void { Assert::true($this->changePasswordPage->checkValidationMessageFor( 'new_password', 'Password must be at least 4 characters long.' )); } /** * @When I subscribe to the newsletter */ public function iSubscribeToTheNewsletter(): void { $this->profileUpdatePage->subscribeToTheNewsletter(); } /** * @Then I should be subscribed to the newsletter */ public function iShouldBeSubscribedToTheNewsletter(): void { Assert::true($this->profileUpdatePage->isSubscribedToTheNewsletter()); } /** * @Then I should be redirected to my account dashboard */ public function iShouldBeRedirectedToMyAccountDashboard(): void { Assert::true($this->dashboardPage->isOpen(), 'User should be on the account panel dashboard page but they are not.'); } /** * @When I want to log in */ public function iWantToLogIn(): void { $this->loginPage->tryToOpen(); } } <file_sep><?php namespace spec\App\Form\Extension; use App\Form\EventSubscriber\AddUserFormSubscriber; use App\Form\Type\User\AppUserType; use PhpSpec\ObjectBehavior; use Sylius\Bundle\CustomerBundle\Form\Type\CustomerType; use Symfony\Component\Form\AbstractTypeExtension; use Symfony\Component\Form\FormBuilderInterface; final class CustomerTypeExtensionSpec extends ObjectBehavior { function it_extends_an_abstract_type_extension() { $this->shouldHaveType(AbstractTypeExtension::class); } function it_extends_customer_type() { $this::getExtendedTypes()->shouldReturn([CustomerType::class]); } function it_adds_user_form_subscriber(FormBuilderInterface $builder) { $builder->addEventSubscriber(new AddUserFormSubscriber(AppUserType::class))->willReturn($builder)->shouldBeCalled(); $this->buildForm($builder, []); } } <file_sep><?php declare(strict_types=1); namespace App\Message; use Symfony\Component\Serializer\Annotation\Groups; use Symfony\Component\Validator\Constraints\NotBlank; final class ResetPassword { #[NotBlank] #[Groups(groups: ['customer:write'])] public ?string $password = null; public function __construct(?string $password = null) { $this->password = $password; } } <file_sep>.. rst-class:: outdated .. danger:: This is an outdated documentation please read the new `Monofony documentation`_ instead. How to create your own statistics ================================= The mechanism behind the displaying of statistics relies on tagged services which are supported since Symfony 4.3 Create your own statistic ------------------------- Add a new class to ``/src/Dashboard/Statistic`` and make sure it implement the ``App\Dashboard\Statistics\StatisticInterface``. This way it will be automatically tagged with ``app.dashboard_statistic`` which is used to fetch all existing statistics. It also enforces you to implement a function called ``generate()`` which need to return a string. .. note:: The response of the generate function will be displayed as is in the dashboard. Which means you can return anything, as long as it is a string. Eg. in the CustomerStatistic it is an HTML block which shows you the amount of registered customers. Order your statistics --------------------- Since Symfony 4.4 it is possible to sort your services with a static function called ``getDefaultPriority``. Here you need to return an integer to set the weight of the service. Statistics with a higher priority will be displayed first. This is why we chose to work with negative values. (-1 for the first element, -2 for the second,...). But feel free to use your own sequence when adding more statistics. .. code-block:: php public static function getDefaultPriority(): int { return -1; } .. warning:: If you change the priority it is necessary to clear your cache. Otherwise you won't see the difference. Add custom logic to your statistic ---------------------------------- Because all statistics are services it's perfectly possible to do anything with them as long as the generate function returns a string. So you can inject any service you want trough Dependency Injection to build your statistic. .. _Monofony documentation: https://docs.monofony.com <file_sep><?php declare(strict_types=1); namespace App\Command\Helper; use Symfony\Component\Console\Helper\ProgressBar; use Symfony\Component\Console\Output\OutputInterface; final class ProgressBarCreator { public function create(OutputInterface $output, int $length = 10): ProgressBar { $progress = new ProgressBar($output); $progress->setBarCharacter('<info>░</info>'); $progress->setEmptyBarCharacter(' '); $progress->setProgressCharacter('<comment>░</comment>'); $progress->start($length); return $progress; } } <file_sep><?php /* * This file is part of the Monofony package. * * (c) Monofony * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Monofony\Contracts\Api\Swagger; use Symfony\Component\Serializer\Normalizer\NormalizerInterface; interface AppAuthenticationTokenDocumentationNormalizerInterface extends NormalizerInterface { } <file_sep>.. rst-class:: outdated .. danger:: This is an outdated documentation please read the new `Monofony documentation`_ instead. .. index:: single: AdminUser AdminUser ========= The **AdminUser** entity extends the **User** entity. It is created to enable administrator accounts that have access to the administration panel. How to create an AdminUser programmatically? -------------------------------------------- The **AdminUser** is created just like every other entity, it has its own factory. By default it will have an administration **role** assigned. .. code-block:: php /** @var AdminUserInterface $admin */ $admin = $this->container->get('sylius.factory.admin_user')->createNew(); $admin->setEmail('<EMAIL>'); $admin->setPlainPassword('<PASSWORD>'); $this->container->get('sylius.repository.admin_user')->add($admin); Administration Security ----------------------- In **Monofony** by default you have got the administration panel routes (``/admin/*``) secured by a firewall - its configuration can be found in the ``config/packages/security.yaml`` file. Only the logged in **AdminUsers** are eligible to enter these routes. Learn more ---------- .. note:: To learn more, read the `UserBundle documentation <https://docs.sylius.com/en/latest/components_and_bundles/bundles/SyliusUserBundle/index.html>`_. .. _Monofony documentation: https://docs.monofony.com <file_sep><?php declare(strict_types=1); namespace App\Tests\Behat\Page\Backend; use Behat\Mink\Session; use FriendsOfBehat\PageObjectExtension\Page\SymfonyPage; use Monofony\Bridge\Behat\Service\Accessor\TableAccessorInterface; use Symfony\Component\Routing\RouterInterface; class DashboardPage extends SymfonyPage { public function __construct( Session $session, $minkParameters, RouterInterface $router, private TableAccessorInterface $tableAccessor, ) { parent::__construct($session, $minkParameters, $router); } public function getRouteName(): string { return 'app_backend_dashboard'; } public function getNumberOfNewCustomersInTheList(): int { return $this->tableAccessor->countTableBodyRows($this->getElement('customer_list')); } public function getNumberOfNewCustomers(): int { return (int) $this->getElement('new_customers')->getText(); } public function logOut(): void { $this->getElement('logout')->click(); } protected function getDefinedElements(): array { return array_merge(parent::getDefinedElements(), [ 'customer_list' => '#customers', 'logout' => '#sylius-logout-button', 'new_customers' => '#new-customers', ]); } } <file_sep><?php declare(strict_types=1); namespace App\Tests\Behat\Page\Backend\Customer; use Monofony\Bridge\Behat\Crud\AbstractIndexPage; use Monofony\Bridge\Behat\Crud\IndexPageInterface; use Monofony\Contracts\Core\Model\Customer\CustomerInterface; class IndexPage extends AbstractIndexPage implements IndexPageInterface { public function getRouteName(): string { return 'sylius_backend_customer_index'; } public function getCustomerAccountStatus(CustomerInterface $customer): string { $tableAccessor = $this->getTableAccessor(); $table = $this->getElement('table'); $row = $tableAccessor->getRowWithFields($table, ['email' => $customer->getEmail()]); return $tableAccessor->getFieldFromRow($table, $row, 'enabled')->getText(); } } <file_sep><?php declare(strict_types=1); namespace App\Context; use Monofony\Contracts\Core\Model\User\AppUserInterface; use Sylius\Component\Customer\Context\CustomerContextInterface; use Sylius\Component\Customer\Model\CustomerInterface; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; class CustomerContext implements CustomerContextInterface { public function __construct( private TokenStorageInterface $tokenStorage, private AuthorizationCheckerInterface $authorizationChecker, ) { } /** * Gets customer based on currently logged user. */ public function getCustomer(): ?CustomerInterface { if (null === $token = $this->tokenStorage->getToken()) { return null; } $user = $token->getUser(); if ( $user instanceof AppUserInterface && $this->authorizationChecker->isGranted('IS_AUTHENTICATED_REMEMBERED') ) { return $user->getCustomer(); } return null; } } <file_sep><?php declare(strict_types=1); namespace App\Tests\Controller; use ApiTestCase\JsonApiTestCase as BaseJsonApiTestCase; class JsonApiTestCase extends BaseJsonApiTestCase { public function __construct(?string $name = null, array $data = [], string $dataName = '') { parent::__construct($name, $data, $dataName); $this->expectedResponsesPath = __DIR__.'/../Responses'; } /** * @before */ public function setUpClient(): void { $this->client = static::createClient([], ['HTTP_ACCEPT' => 'application/ld+json']); } } <file_sep><?php declare(strict_types=1); namespace App\Tests\Controller\Customer; use App\Factory\AppUserFactory; use App\Story\TestAppUsersStory; use App\Tests\Controller\AuthorizedHeaderTrait; use App\Tests\Controller\JsonApiTestCase; use App\Tests\Controller\PurgeDatabaseTrait; use Symfony\Component\HttpFoundation\Response; use Zenstruck\Foundry\Test\Factories; final class GetUserProfileApiTest extends JsonApiTestCase { use AuthorizedHeaderTrait; use Factories; use PurgeDatabaseTrait; /** @test */ public function it_does_not_allow_to_get_user_profile_for_non_authenticated_user(): void { TestAppUsersStory::load(); $customer = AppUserFactory::find(['username' => 'sylius'])->getCustomer(); $this->client->request('GET', '/api/customers/'.$customer->getId()); $response = $this->client->getResponse(); $this->assertResponse($response, 'error/access_denied_response', Response::HTTP_UNAUTHORIZED); } /** @test */ public function it_does_not_allows_to_get_another_profile(): void { TestAppUsersStory::load(); $customer = AppUserFactory::find(['username' => 'monofony'])->getCustomer(); $this->client->request('GET', '/api/customers/'.$customer->getId(), [], [], self::$authorizedHeaderWithContentType); $response = $this->client->getResponse(); $this->assertResponseCode($response, Response::HTTP_FORBIDDEN); } /** @test */ public function it_allows_to_get_user_profile_when_it_is_myself(): void { TestAppUsersStory::load(); $customer = AppUserFactory::find(['username' => 'sylius'])->getCustomer(); $this->client->request('GET', '/api/customers/'.$customer->getId(), [], [], static::$authorizedHeaderWithContentType); $response = $this->client->getResponse(); $this->assertResponse($response, 'customer/get_user_profile_response', Response::HTTP_OK); } } <file_sep><?php /* * This file is part of the Monofony package. * * (c) Monofony * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Monofony\Bundle\CoreBundle\Tests\DependencyInjection\Compiler; use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractCompilerPassTestCase; use Monofony\Bridge\SyliusUser\EventListener\PasswordUpdaterListener; use Monofony\Bundle\CoreBundle\DependencyInjection\Compiler\RegisterPasswordListenerForResourcesPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; final class RegisterPasswordListenerForResourcesPassTest extends AbstractCompilerPassTestCase { /** * @test */ public function it_registers_password_listener_if_listener_is_present(): void { $this->setDefinition('sylius.listener.password_updater', new Definition()); $this->compile(); $this->assertContainerBuilderHasService( 'sylius.listener.password_updater', PasswordUpdaterListener::class ); } protected function registerCompilerPass(ContainerBuilder $container): void { $container->addCompilerPass(new RegisterPasswordListenerForResourcesPass()); } } <file_sep>import 'babel-polyfill'; import './shim-semantic-ui'; import 'sylius/ui/js/app'; import 'sylius/ui/js/sylius-auto-complete'; import './app-date-time-picker'; import './app-images-preview'; import './sylius-compound-form-errors'; import '../scss/main.scss'; $(document).ready(function () { $(document).previewUploadedImage('#sylius_admin_user_avatar'); // Use this previewer for files uploads // $(document).previewUploadedFile('#app_book_file'); $('.sylius-autocomplete').autoComplete(); $('.sylius-tabular-form').addTabErrors(); $('.ui.accordion').addAccordionErrors(); $('#sylius_customer_createUser').change(function () { $('#user-form').toggle(); }); $('.app-date-picker').datePicker(); $('.app-date-time-picker').dateTimePicker(); }); <file_sep><?php declare(strict_types=1); namespace App\Entity\User; use Doctrine\ORM\Mapping as ORM; use Monofony\Contracts\Core\Model\User\AppUserInterface; use Sylius\Component\Customer\Model\CustomerInterface; use Sylius\Component\Resource\Exception\UnexpectedTypeException; use Sylius\Component\User\Model\User as BaseUser; #[ORM\Entity] #[ORM\Table(name: 'sylius_app_user')] class AppUser extends BaseUser implements AppUserInterface { #[ORM\OneToOne(inversedBy: 'user', targetEntity: CustomerInterface::class, cascade: ['persist'])] #[ORM\JoinColumn(nullable: false)] private ?CustomerInterface $customer = null; public function getCustomer(): ?CustomerInterface { return $this->customer; } public function setCustomer($customer): void { $this->customer = $customer; } public function getEmail(): ?string { if (null === $this->customer) { return null; } return $this->customer->getEmail(); } public function setEmail(?string $email): void { if (null === $this->customer) { throw new UnexpectedTypeException($this->customer, CustomerInterface::class); } $this->customer->setEmail($email); } public function getEmailCanonical(): ?string { if (null === $this->customer) { return null; } return $this->customer->getEmailCanonical(); } public function setEmailCanonical(?string $emailCanonical): void { if (null === $this->customer) { throw new UnexpectedTypeException($this->customer, CustomerInterface::class); } $this->customer->setEmailCanonical($emailCanonical); } } <file_sep><?php /* * This file is part of the Monofony package. * * (c) Monofony * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace spec\Monofony\Component\Admin\Dashboard; use Monofony\Component\Admin\Dashboard\DashboardStatisticsProvider; use Monofony\Component\Admin\Dashboard\Statistics\StatisticInterface; use PhpSpec\ObjectBehavior; class DashboardStatisticsProviderSpec extends ObjectBehavior { function let(StatisticInterface $firstStatistic, StatisticInterface $secondStatistic): void { $this->beConstructedWith([$firstStatistic, $secondStatistic]); } function it_is_initializable() { $this->shouldHaveType(DashboardStatisticsProvider::class); } function it_generate_statistics_for_each_providers( StatisticInterface $firstStatistic, StatisticInterface $secondStatistic ): void { $firstStatistic->generate()->shouldBeCalled(); $secondStatistic->generate()->shouldBeCalled(); $this->getStatistics(); } function it_throws_an_invalid_argument_exception_when_statistic_provider_does_not_implements_the_interface( \stdClass $statistic ): void { $this->beConstructedWith([$statistic]); $this->shouldThrow(\LogicException::class)->during('getStatistics'); } } <file_sep><?php declare(strict_types=1); namespace App\Tests\Behat\Context\Cli; use App\Command\Installer\SetupCommand; use Symfony\Bundle\FrameworkBundle\Console\Application; use Symfony\Component\Console\Tester\CommandTester; use Symfony\Component\HttpKernel\KernelInterface; class InstallerContext extends DefaultContext { private SetupCommand $setupCommand; private $inputChoices = [ 'e-mail' => '<EMAIL>', 'password' => '<PASSWORD>', 'confirmation' => '<PASSWORD>', ]; public function __construct(KernelInterface $kernel, SetupCommand $setupCommand) { $this->setupCommand = $setupCommand; parent::__construct($kernel); } /** * @Given I do not provide an email */ public function iDoNotProvideEmail(): void { $this->inputChoices['e-mail'] = ''; } /** * @Given I do not provide a correct email */ public function iDoNotProvideCorrectEmail(): void { $this->inputChoices['e-mail'] = 'janusz'; } /** * @Given I provide full administrator data */ public function iProvideFullAdministratorData(): void { $this->inputChoices['e-mail'] = '<EMAIL>'; $this->inputChoices['password'] = '<PASSWORD>$'; $this->inputChoices['confirmation'] = $this->inputChoices['password']; } /** * @param string $name */ private function iExecuteCommandWithInputChoices($name): void { $this->questionHelper = $this->command->getHelper('question'); $this->getTester()->setInputs($this->inputChoices); try { $this->getTester()->execute(['command' => $name]); } catch (\Exception $e) { } } /** * @When /^I run Install setup command$/ */ public function iRunInstallSetupCommmandLine(): void { $this->application = new Application($this->kernel); $this->application->add($this->setupCommand); $this->command = $this->application->find('app:install:setup'); $this->setTester(new CommandTester($this->command)); $this->iExecuteCommandWithInputChoices('app:install:setup'); } /** * @param string $name */ protected function iExecuteCommandAndConfirm($name): void { $this->questionHelper = $this->command->getHelper('question'); $this->getTester()->setInputs(['y', 'y']); try { $this->getTester()->execute(['command' => $name]); } catch (\Exception $e) { } } } <file_sep>## Change Log ### v0.6.1 (2021/04/08 13:30 +00:00) #### Details - [#324](https://github.com/Monofony/Monofony/pull/324) Fix missing Doctrine migration (@loic425) ### v0.6.0 (2021/04/08 12:14 +00:00) TL;DR Add support for PHP 8 #### Details - [#322](https://github.com/Monofony/Monofony/pull/322) Bump Sylius resource version (@loic425) - [#321](https://github.com/Monofony/Monofony/pull/321) Use Monofony repository for Monofony packages on composer (@loic425) - [#320](https://github.com/Monofony/Monofony/pull/320) Move Doctrine migrations to use the default recipe (@loic425) - [#319](https://github.com/Monofony/Monofony/pull/319) Check security again (@loic425) - [#317](https://github.com/Monofony/Monofony/pull/317) Add support for php 8 (@loic425) - [#316](https://github.com/Monofony/Monofony/pull/316) Improve OAuth secrets (@loic425) - [#315](https://github.com/Monofony/Monofony/pull/315) Add Behat example to test sorting a grid (@loic425) <file_sep>## Change Log ### v0.3.2 (2020/10/13 14:55 +00:00) - [#167](https://github.com/Monofony/Monofony/pull/167) Fix psalm & composer autoload (@loic425) ### v0.3.1 (2020/10/05 12:42 +00:00) - [#166](https://github.com/Monofony/Monofony/pull/166) Fix file interface media namespace (@loic425) ### v0.3.0 (2020/09/30 07:44 +00:00) - [#163](https://github.com/Monofony/Monofony/pull/163) Prepare v0.3.0 dev (@loic425) - [#164](https://github.com/Monofony/Monofony/pull/164) [WIP] Remove useless phpdoc (@loic425) - [#158](https://github.com/Monofony/Monofony/pull/158) [Fix] move file interface into core component (@loic425) - [#147](https://github.com/Monofony/Monofony/pull/147) Bump websocket-extensions from 0.1.3 to 0.1.4 (@dependabot[bot]) - [#162](https://github.com/Monofony/Monofony/pull/162) Fix allowed grand types values on fixtures (@loic425) - [#157](https://github.com/Monofony/Monofony/pull/157) Fix autoscripts after post install and update commands (@loic425) - [#156](https://github.com/Monofony/Monofony/pull/156) No superfluous phpdoc tags (@loic425) - [#137](https://github.com/Monofony/Monofony/pull/137) Bump jquery from 3.4.1 to 3.5.0 (@dependabot[bot]) - [#159](https://github.com/Monofony/Monofony/pull/159) Bump elliptic from 6.5.2 to 6.5.3 (@dependabot[bot]) - [#160](https://github.com/Monofony/Monofony/pull/160) Bump http-proxy from 1.18.0 to 1.18.1 (@dependabot[bot]) - [#161](https://github.com/Monofony/Monofony/pull/161) Fix security issues (@loic425) - [#149](https://github.com/Monofony/Monofony/pull/149) Fix Sylius bundles documentation links (@loic425) - [#148](https://github.com/Monofony/Monofony/pull/148) Fix build (@loic425) - [#145](https://github.com/Monofony/Monofony/pull/145) Fix image widget (@loic425) <file_sep><?php declare(strict_types=1); namespace App\Tests\Behat\Context\Transform; use Behat\Behat\Context\Context; use Monofony\Bridge\Behat\Service\SharedStorageInterface; use Monofony\Contracts\Core\Model\User\AdminUserInterface; final class AdminUserContext implements Context { private SharedStorageInterface $sharedStorage; public function __construct(SharedStorageInterface $sharedStorage) { $this->sharedStorage = $sharedStorage; } /** * @Transform /^(I|my)$/ */ public function getLoggedAdminUser(): AdminUserInterface { return $this->sharedStorage->get('administrator'); } } <file_sep><?php declare(strict_types=1); namespace App\Tests\Behat\Page\Backend\Customer; use FriendsOfBehat\PageObjectExtension\Page\SymfonyPage; class ShowPage extends SymfonyPage { public function getRouteName(): string { return 'sylius_backend_customer_show'; } public function getCustomerEmail(): string { return $this->getElement('customer_email')->getText(); } public function getCustomerPhoneNumber(): string { return $this->getElement('customer_phone_number')->getText(); } public function getCustomerName(): string { return $this->getElement('customer_name')->getText(); } public function getRegistrationDate(): \DateTimeInterface { return new \DateTime(str_replace('Customer since ', '', $this->getElement('registration_date')->getText())); } protected function getDefinedElements(): array { return array_merge(parent::getDefinedElements(), [ 'customer_email' => '#info .content.extra > a', 'customer_name' => '#info .content > a', 'customer_phone_number' => '#phone-number', 'registration_date' => '#info .content .date', ]); } } <file_sep><?php /* * This file is part of the Monofony package. * * (c) Monofony * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Monofony\Bundle\CoreBundle; use Monofony\Bundle\CoreBundle\DependencyInjection\Compiler\BackwardsCompatibility\Symfony6PrivateServicesPass; use Monofony\Bundle\CoreBundle\DependencyInjection\Compiler\ChangeCustomerContextVisibilityPass; use Monofony\Bundle\CoreBundle\DependencyInjection\Compiler\RegisterDashboardStatisticsPass; use Monofony\Bundle\CoreBundle\DependencyInjection\Compiler\RegisterObjectManagerAliasPass; use Monofony\Bundle\CoreBundle\DependencyInjection\Compiler\RegisterPasswordListenerForResourcesPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Bundle\Bundle; class MonofonyCoreBundle extends Bundle { public const VERSION = '0.10.0-alpha.1'; /** * {@inheritdoc} */ public function build(ContainerBuilder $container): void { $container->addCompilerPass(new RegisterPasswordListenerForResourcesPass()); $container->addCompilerPass(new ChangeCustomerContextVisibilityPass()); $container->addCompilerPass(new RegisterDashboardStatisticsPass()); $container->addCompilerPass(new RegisterObjectManagerAliasPass()); $container->addCompilerPass(new Symfony6PrivateServicesPass()); } } <file_sep>.. rst-class:: outdated .. danger:: This is an outdated documentation please read the new `Monofony documentation`_ instead. .. index:: single: Architecture Architecture Overview ===================== Before we dive separately into every Monofony concept, you need to have an overview of how our main application is structured. Fullstack Symfony ----------------- .. image:: ../../_images/symfonyfs.png :scale: 15% :align: center **Monofony** is based on Symfony, which is a leading PHP framework to create web applications. Using Symfony allows developers to work better and faster by providing them with certainty of developing an application that is fully compatible with the business rules, that is structured, maintainable and upgradable, but also it allows to save time by providing generic re-usable modules. `Learn more about Symfony <http://symfony.com/what-is-symfony>`_. Doctrine -------- .. image:: ../../_images/doctrine.png :align: center **Doctrine** is a family of PHP libraries focused on providing data persistence layer. The most important are the object-relational mapper (ORM) and the database abstraction layer (DBAL). One of Doctrine's key features is the possibility to write database queries in Doctrine Query Language (DQL) - an object-oriented dialect of SQL. To learn more about Doctrine - see `their documentation <http://www.doctrine-project.org/about.html>`_. Twig ---- .. image:: ../../_images/twig.png :scale: 30% :align: center **Twig** is a modern template engine for PHP that is really fast, secure and flexible. Twig is being used by Symfony. To read more about Twig, `go here <http://twig.sensiolabs.org/>`_. Third Party Libraries --------------------- Monofony uses a lot of libraries for various tasks: * `Sylius <https://docs.sylius.com/en/latest/>`_ for routing, controllers, data fixtures, grids * `KnpMenu <http://symfony.com/doc/current/bundles/KnpMenuBundle/index.html>`_ - for backend menus * `Imagine <https://github.com/liip/LiipImagineBundle>`_ for images processing, generating thumbnails and cropping * `Pagerfanta <https://github.com/whiteoctober/Pagerfanta>`_ for pagination * `Winzou State Machine <https://github.com/winzou/StateMachineBundle>`_ - for the state machines handling .. _Monofony documentation: https://docs.monofony.com <file_sep>.. rst-class:: outdated .. danger:: This is an outdated documentation please read the new `Monofony documentation`_ instead. How to load your data fixtures ============================== You can load all your data fixtures using this command. .. code-block:: bash $ bin/console sylius:fixtures:load .. _Monofony documentation: https://docs.monofony.com <file_sep>.. rst-class:: outdated .. danger:: This is an outdated documentation please read the new `Monofony documentation`_ instead. How to use Behat to design your features ---------------------------------------- .. note:: This section is based on the great `Sylius documentation <https://docs.sylius.com>`_. Behaviour driven development is an approach to software development process that provides software development and management teams with shared tools and a shared process to collaborate on software development. The awesome part of BDD is its ubiquitous language, which is used to describe the software in English-like sentences of domain specific language. The application's behaviour is described by scenarios, and those scenarios are turned into automated test suites with tools such as Behat. Sylius behaviours are fully covered with Behat scenarios. There are more than 1200 scenarios in the Sylius suite, and if you want to understand some aspects of Sylius better, or are wondering how to configure something, we strongly recommend reading them. They can be found in the ``features/`` directory of the Sylius/Sylius repository. We use `FriendsOfBehat/SymfonyExtension`_ to integrate Behat with Symfony. .. toctree:: :hidden: basic-usage how-to-add-new-context how-to-add-new-page how-to-define-new-suite how-to-use-transformers how-to-change-behat-application-base-url .. include:: /cookbook/bdd/behat/map.rst.inc Learn more ---------- .. note:: To learn more, read the `Behat documentation <http://behat.org/en/latest/guides.html>`_. .. _FriendsOfBehat/SymfonyExtension: https://github.com/FriendsOfBehat/SymfonyExtension .. _Monofony documentation: https://docs.monofony.com <file_sep><?php declare(strict_types=1); namespace App\Tests\Behat\Context\Ui\Backend; use App\Tests\Behat\Page\Backend\Account\LoginPage; use App\Tests\Behat\Page\Backend\DashboardPage; use Behat\Behat\Context\Context; use Webmozart\Assert\Assert; class LoginContext implements Context { public function __construct( private DashboardPage $dashboardPage, private LoginPage $loginPage, ) { } /** * @Then I should be able to log in as :username authenticated by :password <PASSWORD> */ public function iShouldBeAbleToLogInAsAuthenticatedByPassword(string $username, string $password): void { $this->logInAgain($username, $password); $this->dashboardPage->verify(); } /** * @Then I should not be able to log in as :username authenticated by :password <PASSWORD> */ public function iShouldNotBeAbleToLogInAsAuthenticatedByPassword(string $username, string $password): void { $this->logInAgain($username, $password); Assert::true($this->loginPage->hasValidationErrorWith('Error Invalid credentials.')); Assert::false($this->dashboardPage->isOpen()); } /** * @Then I visit login page */ public function iVisitLoginPage(): void { $this->loginPage->open(); } private function logInAgain(string $username, string $password): void { $this->dashboardPage->open(); $this->dashboardPage->logOut(); $this->loginPage->open(); $this->loginPage->specifyUsername($username); $this->loginPage->specifyPassword($password); $this->loginPage->logIn(); } } <file_sep><?php declare(strict_types=1); namespace App\Provider; use Monofony\Contracts\Core\Model\Customer\CustomerInterface; interface CustomerProviderInterface { public function provide(string $email): CustomerInterface; } <file_sep>--- name: "Documentation Issue \U0001F4D6" about: Report missing or bugged documentation --- **Monofony docs version**: 0.x / latest **Description** <!-- Describe what is missing or where exactly is the bug/typo/issue located. Links highly appreciated. --!> <file_sep><?php /* * This file is part of the Monofony package. * * (c) Monofony * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Monofony\Bridge\Behat\Service; use Monofony\Bridge\Behat\Service\Setter\CookieSetterInterface; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\Session\SessionFactoryInterface; final class AdminSecurityService extends AbstractSecurityService implements AdminSecurityServiceInterface { public function __construct(RequestStack $requestStack, CookieSetterInterface $cookieSetter, SessionFactoryInterface $sessionFactory) { parent::__construct($requestStack, $cookieSetter, 'admin', $sessionFactory); } } <file_sep>* :doc:`/cookbook/bdd/phpspec/how-to-configure-phpspec-with-code-coverage` * :doc:`/cookbook/bdd/phpspec/how-to-disable-phpspec-code-coverage` * :doc:`/cookbook/bdd/phpspec/how-to-design-entities-with-phpspec` * :doc:`/cookbook/bdd/phpspec/how-to-design-services-with-phpspec` <file_sep><?php use PhpCsFixer\Fixer\Comment\HeaderCommentFixer; use PhpCsFixer\Fixer\Phpdoc\NoSuperfluousPhpdocTagsFixer; use PhpCsFixer\Fixer\Strict\DeclareStrictTypesFixer; use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; use Symplify\EasyCodingStandard\ValueObject\Option; use Symplify\EasyCodingStandard\ValueObject\Set\SetList; return static function (ContainerConfigurator $containerConfigurator): void { $header = <<<EOM This file is part of the Monofony package. (c) Monofony For the full copyright and license information, please view the LICENSE file that was distributed with this source code. EOM; $containerConfigurator->import(SetList::SYMFONY); $services = $containerConfigurator->services(); $services ->set(DeclareStrictTypesFixer::class) ->set(HeaderCommentFixer::class) ->call('configure', [[ 'header' => $header, 'location' => 'after_open', ]]) ->set(NoSuperfluousPhpdocTagsFixer::class) ->call('configure', [[ 'allow_mixed' => true, ]]) ; $parameters = $containerConfigurator->parameters(); $parameters->set(Option::PATHS, [__DIR__.'/src']); $parameters->set(Option::SKIP, [ __DIR__.'/**/*Spec.php', __DIR__.'/**/.recipe', ]); }; <file_sep><?php declare(strict_types=1); namespace App\Tests\Controller\Customer; use App\Factory\AppUserFactory; use App\Story\TestAppUsersStory; use App\Tests\Controller\AuthorizedHeaderTrait; use App\Tests\Controller\JsonApiTestCase; use App\Tests\Controller\PurgeDatabaseTrait; use Symfony\Component\HttpFoundation\Response; use Zenstruck\Foundry\Test\Factories; final class UpdateUserProfileApiTest extends JsonApiTestCase { use AuthorizedHeaderTrait; use Factories; use PurgeDatabaseTrait; /** @test */ public function it_does_not_allow_to_update_user_profile_for_non_authenticated_user(): void { TestAppUsersStory::load(); $customer = AppUserFactory::find(['username' => 'sylius'])->getCustomer(); $this->client->request('PUT', '/api/customers/'.$customer->getId()); $response = $this->client->getResponse(); $this->assertResponse($response, 'error/access_denied_response', Response::HTTP_UNAUTHORIZED); } /** @test */ public function it_does_not_allows_to_update_another_profile(): void { TestAppUsersStory::load(); $customer = AppUserFactory::find(['username' => 'monofony'])->getCustomer(); $data = <<<EOT { "email": "<EMAIL>", "firstName": "Inigo", "lastName": "Montoya", "subscribedToNewsletter": true } EOT; $this->client->request('PUT', '/api/customers/'.$customer->getId(), [], [], self::$authorizedHeaderWithContentType, $data); $response = $this->client->getResponse(); $this->assertResponseCode($response, Response::HTTP_FORBIDDEN); } /** @test */ public function it_allows_to_update_user_profile(): void { TestAppUsersStory::load(); $customer = AppUserFactory::find(['username' => 'sylius'])->getCustomer(); $data = <<<EOT { "email": "<EMAIL>", "firstName": "Inigo", "lastName": "Montoya", "subscribedToNewsletter": true } EOT; $this->client->request('PUT', '/api/customers/'.$customer->getId(), [], [], self::$authorizedHeaderWithContentType, $data); $response = $this->client->getResponse(); $this->assertResponse($response, 'customer/update_user_profile_response', Response::HTTP_OK); $this->assertLoginWithCredentials('<EMAIL>', 'sylius'); } private function assertLoginWithCredentials(string $username, string $password): void { $data = <<<EOT { "username": "$username", "password": <PASSWORD>" } EOT; $this->client->request('POST', '/api/authentication_token', [], [], ['CONTENT_TYPE' => 'application/json'], $data); $response = $this->client->getResponse(); $this->assertResponse($response, 'authentication/new_access_token', Response::HTTP_OK); } } <file_sep><?php declare(strict_types=1); namespace App\Story; use App\Factory\AppUserFactory; use Zenstruck\Foundry\Story; final class RandomAppUsersStory extends Story { public function build(): void { AppUserFactory::createMany(10); } } <file_sep>.. rst-class:: outdated .. danger:: This is an outdated documentation please read the new `Monofony documentation`_ instead. How to configure your first resource ==================================== As an example we will take an **Article entity**. .. code-block:: php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; use Sylius\Component\Resource\Model\ResourceInterface; use Symfony\Component\Validator\Constraints as Assert; /** * @ORM\Entity * @ORM\Table(name="app_article") */ class Article implements ResourceInterface { use IdentifiableTrait; /** * @var string|null * * @ORM\Column(type="string") * * @Assert\NotBlank() */ private $title; /** * @return string|null */ public function getTitle(): ?string { return $this->title; } /** * @param string|null $title */ public function setTitle(?string $title): void { $this->title = $title; } } If you don't add a form type, it uses a `default form type`_. But it is a good practice to have one. .. code-block:: php // src/Form/Type/ArticleType.php namespace App\Form\Type; use App\Entity\Article; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class ArticleType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { parent::buildForm($builder, $options); $builder ->add('title', TextType::class, [ 'label' => 'sylius.ui.title', ]); } /** * {@inheritdoc} */ public function getBlockPrefix(): string { return 'app_article'; } /** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'data_class' => Article::class ]); } } You now have to add it on Sylius Resource configuration. .. code-block:: yaml # config/sylius/resources.yaml sylius_resource: resources: app.article: classes: model: App\Entity\Article form: App\Form\Type\ArticleType .. warning:: Don't forget to synchronize your database using Doctrine Migrations. You can use these two commands to generate and synchronize your database. .. code-block:: bash $ bin/console doctrine:migrations:diff $ bin/console doctrine:migrations:migrate Learn More ---------- * `Sylius Resource Bundle`_ documentation * `Doctrine migrations`_ documentation .. _`Sylius Resource Bundle`: https://github.com/Sylius/SyliusResourceBundle/blob/master/docs/index.md .. _`Doctrine migrations`: https://symfony.com/doc/master/bundles/DoctrineMigrationsBundle/index.html .. _`default form type`: https://github.com/Sylius/SyliusResourceBundle/blob/master/src/Bundle/Form/Type/DefaultResourceType.php .. _Monofony documentation: https://docs.monofony.com <file_sep><?php namespace spec\App\Entity\Customer; use Monofony\Contracts\Core\Model\Customer\CustomerInterface; use Monofony\Contracts\Core\Model\User\AppUserInterface; use PhpSpec\ObjectBehavior; use Sylius\Component\Customer\Model\Customer as BaseCustomer; use Sylius\Component\User\Model\UserInterface; final class CustomerSpec extends ObjectBehavior { function it_implements_a_customer_interface(): void { $this->shouldImplement(CustomerInterface::class); } function it_extends_a_base_customer_model(): void { $this->shouldBeAnInstanceOf(BaseCustomer::class); } function it_has_no_user_by_default(): void { $this->getUser()->shouldReturn(null); } function its_user_is_mutable(AppUserInterface $user): void { $user->setCustomer($this)->shouldBeCalled(); $this->setUser($user); $this->getUser()->shouldReturn($user); } function it_throws_an_invalid_argument_exception_when_user_is_not_an_app_user_type(UserInterface $user) { $this->shouldThrow(\InvalidArgumentException::class)->during('setUser', [$user]); } function it_resets_customer_of_previous_user(AppUserInterface $previousUser, AppUserInterface $user) { $this->setUser($previousUser); $previousUser->setCustomer(null)->shouldBeCalled(); $this->setUser($user); } function it_does_not_replace_user_if_it_is_already_set(AppUserInterface $user) { $user->setCustomer($this)->shouldBeCalledOnce(); $this->setUser($user); $this->setUser($user); } } <file_sep><?php declare(strict_types=1); namespace App\Tests\Behat\Page\Frontend; use FriendsOfBehat\PageObjectExtension\Page\SymfonyPage; class HomePage extends SymfonyPage { public function getRouteName(): string { return 'app_frontend_homepage'; } public function logOut(): void { $this->getElement('logout_button')->click(); } public function hasLogoutButton(): bool { return $this->hasElement('logout_button'); } /** * {@inheritdoc} */ protected function getDefinedElements(): array { return array_merge(parent::getDefinedElements(), [ 'logout_button' => '.app-logout-button', ]); } } <file_sep><?php namespace spec\App\Entity\User; use App\Entity\Media\File; use App\Entity\User\AdminAvatar; use PhpSpec\ObjectBehavior; final class AdminAvatarSpec extends ObjectBehavior { function it_is_initializable(): void { $this->shouldHaveType(AdminAvatar::class); } function it_is_a_file(): void { $this->shouldHaveType(File::class); } function it_has_no_file_by_default(): void { $this->getFile()->shouldReturn(null); } function its_file_is_mutable(\SplFileInfo $file): void { $this->setFile($file); $this->getFile()->shouldReturn($file); } function it_has_no_path_by_defaut(): void { $this->getPath()->shouldReturn(null); } function its_path_is_mutable(): void { $this->setPath('avatar.png'); $this->getPath()->shouldReturn('avatar.png'); } } <file_sep><?php declare(strict_types=1); namespace App\DataFixtures; use App\Story\DefaultAdministratorsStory; use App\Story\DefaultAppUsersStory; use Doctrine\Bundle\FixturesBundle\Fixture; use Doctrine\Bundle\FixturesBundle\FixtureGroupInterface; use Doctrine\Persistence\ObjectManager; class DefaultFixtures extends Fixture implements FixtureGroupInterface { public function load(ObjectManager $manager): void { DefaultAdministratorsStory::load(); DefaultAppUsersStory::load(); } public static function getGroups(): array { return ['default']; } } <file_sep><?php declare(strict_types=1); namespace App\Form\Extension; use Symfony\Component\Form\AbstractTypeExtension; use Symfony\Component\Form\Extension\Core\Type\DateType; use Symfony\Component\OptionsResolver\OptionsResolver; class DateTypeExtension extends AbstractTypeExtension { /** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver): void { $resolver ->setDefaults([ 'widget' => 'single_text', 'html5' => false, ]); } /** * {@inheritdoc} */ public static function getExtendedTypes(): iterable { return [DateType::class]; } } <file_sep><?php declare(strict_types=1); namespace App\OpenApi\Factory; use ApiPlatform\OpenApi\Factory\OpenApiFactoryInterface; use ApiPlatform\OpenApi\Model\Operation; use ApiPlatform\OpenApi\Model\PathItem; use ApiPlatform\OpenApi\Model\RequestBody; use ApiPlatform\OpenApi\OpenApi; use Monofony\Contracts\Api\OpenApi\Factory\AppAuthenticationTokenOpenApiFactoryInterface; use Symfony\Component\HttpFoundation\Response; final class AppAuthenticationTokenOpenOpenApiFactory implements AppAuthenticationTokenOpenApiFactoryInterface { public function __construct(private OpenApiFactoryInterface $decorated) { } public function __invoke(array $context = []): OpenApi { $openApi = $this->decorated->__invoke($context); $schemas = $openApi->getComponents()->getSchemas(); $schemas['AppUserToken'] = new \ArrayObject([ 'type' => 'object', 'properties' => [ 'token' => [ 'type' => 'string', 'readOnly' => true, ], ], ]); $schemas['AppUserCredentials'] = new \ArrayObject([ 'type' => 'object', 'properties' => [ 'username' => [ 'type' => 'string', 'example' => '<EMAIL>', ], 'password' => [ 'type' => 'string', 'example' => '<PASSWORD>', ], ], ]); $openApi->getPaths()->addPath('/api/authentication_token', new PathItem( ref: 'Authentication token', post: new Operation( operationId: 'postCredentialsItem', tags: ['AppUserToken'], responses: [ Response::HTTP_OK => [ 'description' => 'Get JWT token', 'content' => [ 'application/json' => [ 'schema' => [ '$ref' => '#/components/schemas/AppUserToken', ], ], ], ], ], summary: 'Get JWT token to login.', requestBody: new RequestBody( description: 'Create new JWT Token', content: new \ArrayObject([ 'application/json' => [ 'schema' => [ '$ref' => '#/components/schemas/AppUserCredentials', ], ], ]), ), ), )); return $openApi; } } <file_sep><?php /* * This file is part of the Monofony package. * * (c) Monofony * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Monofony\Bundle\CoreBundle\DependencyInjection; use Doctrine\Common\EventSubscriber; use Monofony\Component\Admin\Dashboard\DashboardStatisticsProvider; use Monofony\Component\Admin\Dashboard\Statistics\StatisticInterface; use Monofony\Component\Admin\Menu\AdminMenuBuilderInterface; use Monofony\Contracts\Admin\Dashboard\DashboardStatisticsProviderInterface; use Monofony\Contracts\Api\Identifier\AppUserIdentifierNormalizerInterface; use Monofony\Contracts\Api\OpenApi\Factory\AppAuthenticationTokenOpenApiFactoryInterface; use Monofony\Contracts\Front\Menu\AccountMenuBuilderInterface; use Sylius\Component\Customer\Context\CustomerContextInterface; use Sylius\Component\User\Canonicalizer\CanonicalizerInterface; use Sylius\Component\User\Security\Generator\GeneratorInterface; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Extension\Extension; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; class MonofonyCoreExtension extends Extension { /** * {@inheritdoc} */ public function load(array $configs, ContainerBuilder $container) { $loader = new YamlFileLoader( $container, new FileLocator(__DIR__.'/../Resources/config') ); $loader->load('services.yaml'); $this->registerSomeSyliusAliases($container); $this->tagCustomerContext($container); $this->tagDoctrineEventSubscribers($container); $this->tagApiPlatformIdentifierNormalizer($container); $this->tagOpenApiFactories($container); $this->buildAccountMenu($container); $this->buildDashboardServices($container); $this->buildAdminMenu($container); $this->registerDashboardStatisticsProvider($container); } private function registerSomeSyliusAliases(ContainerBuilder $container): void { if (interface_exists(CanonicalizerInterface::class)) { $container->setAlias(CanonicalizerInterface::class, 'sylius.canonicalizer'); } if (interface_exists(GeneratorInterface::class)) { $container->setAlias(GeneratorInterface::class, 'sylius.app_user.token_generator.email_verification'); } } private function tagCustomerContext(ContainerBuilder $container): void { if (!interface_exists(CustomerContextInterface::class)) { return; } $container->registerForAutoconfiguration(CustomerContextInterface::class) ->addTag('monofony.customer_context'); } private function tagDoctrineEventSubscribers(ContainerBuilder $container): void { if (!interface_exists(EventSubscriber::class)) { return; } $container->registerForAutoconfiguration(EventSubscriber::class) ->addTag('doctrine.event_subscriber') ; } private function tagApiPlatformIdentifierNormalizer(ContainerBuilder $container): void { if (!interface_exists(AppUserIdentifierNormalizerInterface::class)) { return; } $container->registerForAutoconfiguration(AppUserIdentifierNormalizerInterface::class) ->addTag('api_platform.identifier.denormalizer', ['priority' => -10]) ; } private function tagOpenApiFactories(ContainerBuilder $container): void { if (!interface_exists(AppAuthenticationTokenOpenApiFactoryInterface::class)) { return; } $container->registerForAutoconfiguration(AppAuthenticationTokenOpenApiFactoryInterface::class) ->addTag('monofony.openapi.factory.app_authentication_token') ; } private function buildAccountMenu(ContainerBuilder $container): void { if (!interface_exists(AccountMenuBuilderInterface::class)) { return; } $container->registerForAutoconfiguration(AccountMenuBuilderInterface::class) ->addTag('knp_menu.menu_builder', [ 'method' => 'createMenu', 'alias' => 'app.account', ]); } private function buildDashboardServices(ContainerBuilder $container): void { if (!interface_exists(StatisticInterface::class)) { return; } $container->registerForAutoconfiguration(StatisticInterface::class) ->addTag('monofony.dashboard_statistic'); } private function buildAdminMenu(ContainerBuilder $container): void { if (!interface_exists(AdminMenuBuilderInterface::class)) { return; } $container->registerForAutoconfiguration(AdminMenuBuilderInterface::class) ->addTag('knp_menu.menu_builder', [ 'method' => 'createMenu', 'alias' => 'app.admin.main', ]); } private function registerDashboardStatisticsProvider(ContainerBuilder $container): void { if ( !class_exists(DashboardStatisticsProvider::class) || !interface_exists(DashboardStatisticsProviderInterface::class) ) { return; } $container->register('monofony.admin.dashboard_statistics_provider', DashboardStatisticsProvider::class); $container->setAlias(DashboardStatisticsProviderInterface::class, 'monofony.admin.dashboard_statistics_provider'); } } <file_sep>.. rst-class:: outdated .. danger:: This is an outdated documentation please read the new `Monofony documentation`_ instead. Users ===== Before we dive separately into every Monofony concept, you need to have an overview of how our main application is structured. In this chapter we will sketch this architecture and our basic, cornerstone concepts, but also some supportive approaches, that you need to notice. .. toctree:: :hidden: admins customers .. include:: /book/user/map.rst.inc .. _Monofony documentation: https://docs.monofony.com <file_sep><?php /* * This file is part of the Monofony package. * * (c) Monofony * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Monofony\Bundle\CoreBundle\DependencyInjection\Compiler; use Monofony\Bridge\SyliusUser\EventListener\PasswordUpdaterListener; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; final class RegisterPasswordListenerForResourcesPass implements CompilerPassInterface { public function process(ContainerBuilder $container): void { if ( !class_exists(PasswordUpdaterListener::class) || !$container->hasDefinition('sylius.listener.password_updater') ) { return; } $listenerPasswordUpdaterDefinition = $container->getDefinition('sylius.listener.password_updater'); $listenerPasswordUpdaterDefinition ->setClass(PasswordUpdaterListener::class) ->addTag('kernel.event_listener', [ 'event' => 'sylius.customer.pre_update', 'method' => 'customerUpdateEvent', ]) ->addTag('kernel.event_listener', [ 'event' => 'sylius.admin_user.pre_update', 'method' => 'genericEventUpdater', ]); } } <file_sep><?php declare(strict_types=1); namespace App\Story; use App\Factory\AdminUserFactory; use Zenstruck\Foundry\Story; final class DefaultAdministratorsStory extends Story { public function build(): void { AdminUserFactory::createOne([ 'email' => '<EMAIL>', 'password' => '<PASSWORD>', ]); } } <file_sep>const path = require('path'); const vendorUiPath = path.resolve(__dirname, 'vendor/sylius/ui-bundle'); const build = require('./src/Monofony/MetaPack/CoreMeta/.recipe/config-builder'); const backendConfig = build('backend', `./src/Monofony/MetaPack/AdminMeta/.recipe/assets/backend/`, vendorUiPath); const frontendConfig = build('frontend', `./src/Monofony/MetaPack/FrontMeta/.recipe/assets/frontend/`, vendorUiPath); module.exports = [backendConfig, frontendConfig]; <file_sep><?php /* * This file is part of the Monofony package. * * (c) Monofony * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Monofony\Bundle\CoreBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; final class RegisterOpenApiFactoriesPass implements CompilerPassInterface { public function process(ContainerBuilder $container): void { foreach ($container->findTaggedServiceIds('monofony.openapi.factory.app_authentication_token') as $id => $attributes) { $normalizerDefinition = $container->findDefinition($id); $normalizerDefinition ->setDecoratedService('api_platform.openapi.factory', null, -10) ->addArgument(new Reference($id.'.inner')) ; } } } <file_sep><?php declare(strict_types=1); namespace App\Tests\Behat\Context\Setup; use App\Factory\AppUserFactory; use Behat\Behat\Context\Context; use Monofony\Bridge\Behat\Service\AppSecurityServiceInterface; use Monofony\Bridge\Behat\Service\SharedStorageInterface; use Monofony\Contracts\Core\Model\User\AppUserInterface; use Sylius\Component\Customer\Model\CustomerInterface; use Sylius\Component\User\Repository\UserRepositoryInterface; use Webmozart\Assert\Assert; final class AppSecurityContext implements Context { public function __construct( private SharedStorageInterface $sharedStorage, private AppSecurityServiceInterface $securityService, private AppUserFactory $userFactory, private UserRepositoryInterface $appUserRepository, ) { } /** * @Given I am logged in as :email */ public function iAmLoggedInAs(string $email): void { $user = $this->appUserRepository->findOneByEmail($email); Assert::notNull($user); $this->securityService->logIn($user); } /** * @Given I am a logged in customer */ public function iAmLoggedInAsACustomer(): void { $user = $this->userFactory->createOne(['email' => '<EMAIL>', 'password' => '<PASSWORD>', 'roles' => ['ROLE_USER']]); /** @var AppUserInterface $user */ $user = $this->appUserRepository->find($user->getId()); $this->securityService->logIn($user); /** @var CustomerInterface $customer */ $customer = $user->getCustomer(); $this->sharedStorage->set('customer', $customer); } } <file_sep><?php declare(strict_types=1); namespace App\Menu; use Knp\Menu\FactoryInterface; use Knp\Menu\ItemInterface; use Monofony\Contracts\Front\Menu\AccountMenuBuilderInterface; use Sylius\Bundle\UiBundle\Menu\Event\MenuBuilderEvent; use Symfony\Component\EventDispatcher\EventDispatcherInterface; final class AccountMenuBuilder implements AccountMenuBuilderInterface { public const EVENT_NAME = 'sylius.menu.app.account'; public function __construct( private FactoryInterface $factory, private EventDispatcherInterface $eventDispatcher, ) { } public function createMenu(array $options): ItemInterface { $menu = $this->factory->createItem('root'); $menu->setLabel('sylius.ui.my_account'); $menu ->addChild('dashboard', ['route' => 'sylius_frontend_account_dashboard']) ->setLabel('sylius.ui.dashboard') ->setLabelAttribute('icon', 'home') ; $menu ->addChild('personal_information', ['route' => 'sylius_frontend_account_profile_update']) ->setLabel('sylius.ui.personal_information') ->setLabelAttribute('icon', 'user') ; $menu ->addChild('change_password', ['route' => 'sylius_frontend_account_change_password']) ->setLabel('sylius.ui.change_password') ->setLabelAttribute('icon', 'lock') ; $this->eventDispatcher->dispatch(new MenuBuilderEvent($this->factory, $menu), self::EVENT_NAME); return $menu; } } <file_sep># -*- coding: utf-8 -*- from setuptools import setup, find_packages setup( name = 'sphinx-php', version = '1.0', author = '<NAME>', author_email = '<EMAIL>', description = 'Sphinx Extensions for PHP and Symfony', license = 'MIT', packages = find_packages(), install_requires = ['Sphinx>=0.6'], ) <file_sep>.. rst-class:: outdated .. danger:: This is an outdated documentation please read the new `Monofony documentation`_ instead. Monofony Documentation ====================== .. image:: /_images/doc_logo.png :alt: Monofony Welcome Page `Monofony`_ is a project based on `Symfony Framework`_ and `Sylius`_. .. note:: This documentation assumes you have a working knowledge of the Symfony Framework. If you're not familiar with Symfony, please start with reading the `Quick Tour`_ from the Symfony documentation. The Book -------- Here you will find all the concepts used in the Monofony platform. :doc:`The Book </book/index>` helps to understand how Monofony works. .. toctree:: :hidden: book/index .. include:: /book/map.rst.inc The Cookbook ------------ :doc:`The Cookbook </cookbook/index>` is a collection of specific solutions for specific needs. .. toctree:: :hidden: cookbook/index Deployment ---------- :doc:`The Deployment guide </deployment/index>` helps to deploy the website on servers. .. toctree:: :hidden: deployment/index .. include:: /deployment/map.rst.inc .. _Monofony: https://twitter.com/hashtag/Monofony .. _Monofony documentation: https://docs.monofony.com .. _Sylius: https://sylius.com .. _`Symfony Framework`: http://symfony.com .. _`Quick Tour`: http://symfony.com/doc/current/quick_tour <file_sep><?php declare(strict_types=1); namespace spec\App\Validator\Initializer; use App\Validator\Initializer\CustomerInitializer; use PhpSpec\ObjectBehavior; use Sylius\Component\Customer\Model\CustomerInterface; use Sylius\Component\User\Canonicalizer\CanonicalizerInterface; use Symfony\Component\Validator\ObjectInitializerInterface; final class CustomerInitializerSpec extends ObjectBehavior { function let(CanonicalizerInterface $canonicalizer): void { $this->beConstructedWith($canonicalizer); } function it_is_initializable(): void { $this->shouldHaveType(CustomerInitializer::class); } function it_implements_symfony_validator_initializer_interface(): void { $this->shouldImplement(ObjectInitializerInterface::class); } function it_sets_canonical_email_when_initializing_customer( CanonicalizerInterface $canonicalizer, CustomerInterface $customer, ): void { $customer->getEmail()->willReturn('<EMAIL>'); $canonicalizer->canonicalize('<EMAIL>')->willReturn('<EMAIL>'); $customer->setEmailCanonical('<EMAIL>')->shouldBeCalled(); $this->initialize($customer); } function it_does_not_set_canonical_email_when_initializing_non_customer_object(\stdClass $object): void { $this->initialize($object); } } <file_sep>(function ($) { 'use strict'; var calendarTextFr = { days: ['S', 'L', 'M', 'M', 'J', 'V', 'S'], months: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'], monthsShort: ['Janv', 'Févr', 'Mars', 'Avr.', 'Mai', 'Juin', 'Juil', 'Août', 'Sept', 'Oct', 'Nov', 'Déc'], today: 'Aujourd\'hui', now: 'Maintenant', am: 'AM', pm: 'PM' }; $.fn.extend({ datePicker: function () { $(this).each(function () { var $element = $(this); $element.calendar({ type: 'date', firstDayOfWeek: 1, text: calendarTextFr, formatter: { date: function (date, settings) { if (!date) return ''; var day = date.getDate(); var month = date.getMonth() + 1; var year = date.getFullYear(); if (month < 10) { month = "0" + month; } if (day < 10) { day = "0" + day; } return day + '/' + month + '/' + year; } }, parser: { date: function (text, settings) { var dateAsArray = text.split('/'); return new Date(dateAsArray[2], dateAsArray[1] - 1, dateAsArray[0]); } }, }); }); } }); $.fn.extend({ dateTimePicker: function () { $(this).each(function () { var $element = $(this); $element.calendar({ type: 'datetime', firstDayOfWeek: 1, text: calendarTextFr, disableMinute: true, ampm: false, formatter: { date: function (date, settings) { if (!date) return ''; var day = date.getDate(); var month = date.getMonth() + 1; var year = date.getFullYear(); if (month < 10) { month = "0" + month; } if (day < 10) { day = "0" + day; } return day + '/' + month + '/' + year; }, time: function (date, settings, forCalendar) { var hours = date.getHours(); var minutes = date.getMinutes(); if (minutes < 10) { minutes = "0" + minutes; } return hours + ':' + minutes; } } }); }); } }); })(jQuery);<file_sep>.. rst-class:: outdated .. danger:: This is an outdated documentation please read the new `Monofony documentation`_ instead. How to configure backend routes =============================== To configure backend routes for your entity, you have to create a new file on backend routes folder ``config/routes/backend``. Let’s configure our “Article” routes as an example. .. code-block:: yaml # config/routes/backend/article.yaml app_backend_article: resource: | alias: app.article section: backend except: ['show'] redirect: update grid: app_backend_article vars: all: subheader: app.ui.manage_articles index: icon: newspaper templates: backend/crud type: sylius.resource And add it on backend routes configuration. .. code-block:: yaml # config/routes/backend/_main.yaml [...] app_backend_article: resource: "article.yaml" And that’s all! Learn More ---------- * `Configuring routes in sylius documentation`_ .. _Configuring routes in sylius documentation: https://github.com/Sylius/SyliusResourceBundle/blob/master/docs/routing.md .. _Monofony documentation: https://docs.monofony.com <file_sep><?php declare(strict_types=1); namespace App\Tests\Behat\Page\Frontend\Account; use FriendsOfBehat\PageObjectExtension\Page\SymfonyPage; class VerificationPage extends SymfonyPage { public function verifyAccount(string $token): void { $this->tryToOpen(['token' => $token]); } public function getRouteName(): string { return 'sylius_frontend_user_verification'; } } <file_sep>.. rst-class:: outdated .. danger:: This is an outdated documentation please read the new `Monofony documentation`_ instead. .. index:: single: Customer and AppUser Customer and AppUser ==================== For handling customers of your system AppUser is using a combination of two entities - Customer and AppUser. The difference between these two entities is simple: the Customer is a guest on your application and the AppUser is a user registered in the system - they have an account. Customer ======== The Customer entity was created to collect data about non-registered guests of the system - ones that has been buying without having an account or that have somehow provided us their e-mail. How to create a Customer programmatically? ------------------------------------------ As usually, use a factory. The only required field for the Customer entity is email, provide it before adding it to the repository. .. code-block:: php /** @var CustomerInterface $customer */ $customer = $this->container->get('sylius.factory.customer')->createNew(); $customer->setEmail('<EMAIL>'); $this->container->get('sylius.repository.customer')->add($customer); The Customer entity can of course hold other information besides an email, it can be for instance ``billingAddress`` and ``shippingAddress``, ``firstName``, ``lastName`` or ``birthday``. .. note:: The relation between the Customer and AppUser is bidirectional. Both entities hold a reference to each other. AppUser ======= AppUser entity is designed for customers that have registered in the system - they have an account with both e-mail and password. They can visit and modify their account. While creating new account the existence of the provided email in the system is checked - if the email was present - it will already have a Customer therefore the existing one will be assigned to the newly created AppUser, if not - a new Customer will be created together with the AppUser. How to create an AppUser programmatically? ------------------------------------------ Assuming that you have a Customer (either retrieved from the repository or a newly created one) - use a factory to create a new AppUser, assign the existing Customer and a password via the setPlainPassword() method. .. code-block:: php /** @var ShopUserInterface $user */ $user = $this->container->get('sylius.factory.app_user')->createNew(); // Now let's find a Customer by their e-mail: /** @var CustomerInterface $customer */ $customer = $this->container->get('sylius.repository.customer')->findOneBy(['email' => '<EMAIL>']); // and assign it to the ShopUser $user->setCustomer($customer); $user->setPlainPassword('<PASSWORD>'); $this->container->get('sylius.repository.app_user')->add($user); Changing the AppUser password ----------------------------- The already set password of an AppUser can be easily changed via the setPlainPassword() method. .. code-block:: php $user->getPassword(); // returns encrypted password - '<PASSWORD>' $user->setPlainPassword('<PASSWORD>'); // the password will now be '<PASSWORD>' and will become encrypted while saving the user in the database Customer related events ======================= +---------------------------------------------+-----------------------------------------------------------------------------------------+ | Event id | Description | +=============================================+=========================================================================================+ |``sylius.customer.post_register`` | dispatched when a new Customer is registered | +---------------------------------------------+-----------------------------------------------------------------------------------------+ |``sylius.customer.pre_update`` | dispatched when a Customer is updated | +---------------------------------------------+-----------------------------------------------------------------------------------------+ |``sylius.oauth_user.post_create`` | dispatched when an OAuthUser is created | +---------------------------------------------+-----------------------------------------------------------------------------------------+ |``sylius.oauth_user.post_update`` | dispatched when an OAuthUser is updated | +---------------------------------------------+-----------------------------------------------------------------------------------------+ |``sylius.app_user.post_create`` | dispatched when a User is created | +---------------------------------------------+-----------------------------------------------------------------------------------------+ |``sylius.app_user.post_update`` | dispatched when a User is updated | +---------------------------------------------+-----------------------------------------------------------------------------------------+ |``sylius.app_user.pre_delete`` | dispatched before a User is deleted | +---------------------------------------------+-----------------------------------------------------------------------------------------+ |``sylius.user.email_verification.token`` | dispatched when a verification token is requested | +---------------------------------------------+-----------------------------------------------------------------------------------------+ |``sylius.user.password_reset.request.token`` | dispatched when a reset password token is requested | +---------------------------------------------+-----------------------------------------------------------------------------------------+ |``sylius.user.pre_password_change`` | dispatched before user password is changed | +---------------------------------------------+-----------------------------------------------------------------------------------------+ |``sylius.user.pre_password_reset`` | dispatched before user password is reset | +---------------------------------------------+-----------------------------------------------------------------------------------------+ |``sylius.user.security.implicit_login`` | dispatched when an implicit login is done | +---------------------------------------------+-----------------------------------------------------------------------------------------+ |``security.interactive_login`` | dispatched when an interactive login is done | +---------------------------------------------+-----------------------------------------------------------------------------------------+ Learn more: ----------- .. note:: To learn more read: * the `SyliusUserBundle documentation <https://docs.sylius.com/en/latest/components_and_bundles/bundles/SyliusUserBundle/index.html>`_. * the `SyliusCustomerBundle documentation <https://docs.sylius.com/en/latest/components_and_bundles/bundles/SyliusCustomerBundle/index.html>`_. .. _Monofony documentation: https://docs.monofony.com <file_sep># -*- coding: utf-8 -*- """ :copyright: (c) 2010-2012 <NAME> :license: MIT, see LICENSE for more details. """ from docutils import nodes, utils from sphinx.util.nodes import split_explicit_title from string import lower def php_namespace_role(typ, rawtext, text, lineno, inliner, options={}, content=[]): text = utils.unescape(text) env = inliner.document.settings.env base_url = env.app.config.api_url has_explicit_title, title, namespace = split_explicit_title(text) try: full_url = base_url % namespace.replace('\\', '/') + '.html' except (TypeError, ValueError): env.warn(env.docname, 'unable to expand %s api_url with base ' 'URL %r, please make sure the base contains \'%%s\' ' 'exactly once' % (typ, base_url)) full_url = base_url + utils.escape(full_class) if not has_explicit_title: name = namespace.lstrip('\\') ns = name.rfind('\\') if ns != -1: name = name[ns+1:] title = name list = [nodes.reference(title, title, internal=False, refuri=full_url, reftitle=namespace)] pnode = nodes.literal('', '', *list) return [pnode], [] def php_class_role(typ, rawtext, text, lineno, inliner, options={}, content=[]): text = utils.unescape(text) env = inliner.document.settings.env base_url = env.app.config.api_url has_explicit_title, title, full_class = split_explicit_title(text) try: full_url = base_url % full_class.replace('\\', '/') + '.html' except (TypeError, ValueError): env.warn(env.docname, 'unable to expand %s api_url with base ' 'URL %r, please make sure the base contains \'%%s\' ' 'exactly once' % (typ, base_url)) full_url = base_url + utils.escape(full_class) if not has_explicit_title: class_name = full_class.lstrip('\\') ns = class_name.rfind('\\') if ns != -1: class_name = class_name[ns+1:] title = class_name list = [nodes.reference(title, title, internal=False, refuri=full_url, reftitle=full_class)] pnode = nodes.literal('', '', *list) return [pnode], [] def php_method_role(typ, rawtext, text, lineno, inliner, options={}, content=[]): text = utils.unescape(text) env = inliner.document.settings.env base_url = env.app.config.api_url has_explicit_title, title, class_and_method = split_explicit_title(text) ns = class_and_method.rfind('::') full_class = class_and_method[:ns] method = class_and_method[ns+2:] try: full_url = base_url % full_class.replace('\\', '/') + '.html' + '#method_' + method except (TypeError, ValueError): env.warn(env.docname, 'unable to expand %s api_url with base ' 'URL %r, please make sure the base contains \'%%s\' ' 'exactly once' % (typ, base_url)) full_url = base_url + utils.escape(full_class) if not has_explicit_title: title = method + '()' list = [nodes.reference(title, title, internal=False, refuri=full_url, reftitle=full_class + '::' + method + '()')] pnode = nodes.literal('', '', *list) return [pnode], [] def php_phpclass_role(typ, rawtext, text, lineno, inliner, options={}, content=[]): text = utils.unescape(text) has_explicit_title, title, full_class = split_explicit_title(text) full_url = 'http://php.net/manual/en/class.%s.php' % lower(full_class) if not has_explicit_title: title = full_class list = [nodes.reference(title, title, internal=False, refuri=full_url, reftitle=full_class)] pnode = nodes.literal('', '', *list) return [pnode], [] def php_phpmethod_role(typ, rawtext, text, lineno, inliner, options={}, content=[]): text = utils.unescape(text) has_explicit_title, title, class_and_method = split_explicit_title(text) ns = class_and_method.rfind('::') full_class = class_and_method[:ns] method = class_and_method[ns+2:] full_url = 'http://php.net/manual/en/%s.%s.php' % (lower(full_class), lower(method)) if not has_explicit_title: title = full_class + '::' + method + '()' list = [nodes.reference(title, title, internal=False, refuri=full_url, reftitle=full_class)] pnode = nodes.literal('', '', *list) return [pnode], [] def php_phpfunction_role(typ, rawtext, text, lineno, inliner, options={}, content=[]): text = utils.unescape(text) has_explicit_title, title, full_function = split_explicit_title(text) full_url = 'http://php.net/manual/en/function.%s.php' % lower(full_function.replace('_', '-')) if not has_explicit_title: title = full_function list = [nodes.reference(title, title, internal=False, refuri=full_url, reftitle=full_function)] pnode = nodes.literal('', '', *list) return [pnode], [] def setup(app): app.add_config_value('api_url', {}, 'env') app.add_role('namespace', php_namespace_role) app.add_role('class', php_class_role) app.add_role('method', php_method_role) app.add_role('phpclass', php_phpclass_role) app.add_role('phpmethod', php_phpmethod_role) app.add_role('phpfunction', php_phpfunction_role) <file_sep>* :doc:`/cookbook/bdd/behat/basic-usage` * :doc:`/cookbook/bdd/behat/how-to-add-new-context` * :doc:`/cookbook/bdd/behat/how-to-add-new-page` * :doc:`/cookbook/bdd/behat/how-to-define-new-suite` * :doc:`/cookbook/bdd/behat/how-to-use-transformers` * :doc:`/cookbook/bdd/behat/how-to-change-behat-application-base-url` <file_sep><?php declare(strict_types=1); namespace App\Tests\Behat\Context\Ui; use Behat\Behat\Context\Context; use Monofony\Bridge\Behat\Service\EmailCheckerInterface; use Webmozart\Assert\Assert; final class EmailContext implements Context { public function __construct( private EmailCheckerInterface $emailChecker, ) { } /** * @Then it should be sent to :recipient * @Then the email with reset token should be sent to :recipient * @Then the email with contact request should be sent to :recipient */ public function anEmailShouldBeSentTo(string $recipient): void { Assert::true($this->emailChecker->hasRecipient($recipient)); } /** * @Then :count email(s) should be sent to :recipient */ public function numberOfEmailsShouldBeSentTo(int $count, string $recipient): void { Assert::same($this->emailChecker->countMessagesTo($recipient), $count); } /** * @Then an email to verify your email validity should have been sent to :recipient */ public function anEmailToVerifyYourEmailValidityShouldHaveBeenSentTo(string $recipient): void { $this->assertEmailContainsMessageTo('To verify your email address', $recipient); } /** * @Then a welcoming email should have been sent to :recipient */ public function aWelcomingEmailShouldHaveBeenSentTo(string $recipient): void { $this->assertEmailContainsMessageTo('Welcome to our website', $recipient); } private function assertEmailContainsMessageTo(string $message, string $recipient): void { Assert::true($this->emailChecker->hasMessageTo($message, $recipient)); } } <file_sep>Behat Bridge ============ Provides integration for [Behat](https://docs.behat.org/en/latest/) with various Monofony components. Resources --------- * [Report issues](https://github.com/Monofony/Monofony/issues) and [send Pull Requests](https://github.com/Monofony/Monofony/pulls) in the [main Monofony repository](https://github.com/Monofony/Monofony) <file_sep><?php /* * This file is part of the Monofony package. * * (c) Monofony * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Monofony\Contracts\Api\Identifier; use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; interface AppUserIdentifierNormalizerInterface extends DenormalizerInterface { /** * {@inheritdoc} * * @psalm-suppress InvalidReturnType * @psalm-suppress InvalidReturnStatement */ public function denormalize($data, $type, $format = null, array $context = []); /** * {@inheritdoc} */ public function supportsDenormalization($data, $type, $format = null); } <file_sep>import chug from 'gulp-chug'; import gulp from 'gulp'; import yargs from 'yargs'; const { argv } = yargs .options({ rootPath: { description: '<path> path to public assets directory', type: 'string', requiresArg: true, required: false, }, nodeModulesPath: { description: '<path> path to node_modules directory', type: 'string', requiresArg: true, required: false, }, }); const config = [ '--rootPath', argv.rootPath || '../../public/assets', '--nodeModulesPath', argv.nodeModulesPath || '../../node_modules', ]; export const buildAdmin = function buildAdmin() { return gulp.src('assets/backend/gulpfile.babel.js', { read: false }) .pipe(chug({ args: config, tasks: 'build' })); }; buildAdmin.description = 'Build admin assets.'; export const watchAdmin = function watchAdmin() { return gulp.src('assets/backend/gulpfile.babel.js', { read: false }) .pipe(chug({ args: config, tasks: 'watch' })); }; watchAdmin.description = 'Watch admin asset sources and rebuild on changes.'; export const buildApp = function buildApp() { return gulp.src('assets/frontend/gulpfile.babel.js', { read: false }) .pipe(chug({ args: config, tasks: 'build' })); }; buildApp.description = 'Build app assets.'; export const watchApp = function watchApp() { return gulp.src('assets/frontend/gulpfile.babel.js', { read: false }) .pipe(chug({ args: config, tasks: 'watch' })); }; watchApp.description = 'Watch app asset sources and rebuild on changes.'; export const build = gulp.parallel(buildAdmin, buildApp); build.description = 'Build assets.'; gulp.task('admin', buildAdmin); gulp.task('admin-watch', watchAdmin); gulp.task('app', buildApp); gulp.task('app-watch', watchApp); export default build; <file_sep><?php declare(strict_types=1); namespace App\DataFixtures; use App\Story\RandomAppUsersStory; use Doctrine\Bundle\FixturesBundle\Fixture; use Doctrine\Bundle\FixturesBundle\FixtureGroupInterface; use Doctrine\Persistence\ObjectManager; class FakeFixtures extends Fixture implements FixtureGroupInterface { public function load(ObjectManager $manager): void { RandomAppUsersStory::load(); } public static function getGroups(): array { return ['fake']; } } <file_sep><?php declare(strict_types=1); namespace App\MessageHandler; use App\Message\ResetPasswordRequest; use Doctrine\ORM\EntityManagerInterface; use Monofony\Contracts\Core\Model\Customer\CustomerInterface; use Sylius\Bundle\UserBundle\UserEvents; use Sylius\Component\Resource\Repository\RepositoryInterface; use Sylius\Component\User\Security\Generator\GeneratorInterface; use Symfony\Component\EventDispatcher\GenericEvent; use Symfony\Component\Messenger\Handler\MessageHandlerInterface; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; final class ResetPasswordRequestHandler implements MessageHandlerInterface { public function __construct( private RepositoryInterface $customerRepository, private GeneratorInterface $generator, private EntityManagerInterface $entityManager, private EventDispatcherInterface $eventDispatcher, ) { } public function __invoke(ResetPasswordRequest $message): void { /** @var CustomerInterface|null $customer */ $customer = $this->customerRepository->findOneBy(['emailCanonical' => $message->email]); if (null === $customer) { return; } if (null === $user = $customer->getUser()) { return; } $user->setPasswordResetToken($this->generator->generate()); $user->setPasswordRequestedAt(new \DateTime()); $this->entityManager->flush(); $this->eventDispatcher->dispatch(new GenericEvent($user), UserEvents::REQUEST_RESET_PASSWORD_TOKEN); } } <file_sep>Monofony Documentation ====================== This directory contains documentation for Monofony. This documentation is inspired by [Sylius documentation](https://docs.sylius.com). Build ----- In order to build the documentation: * [Install `pip`, Python package manager](https://pip.pypa.io/en/stable/installing/) * Download the documentation requirements: `$ pip install -r requirements.txt` This makes sure that the version of Sphinx you'll get is >=1.4.2! * Install [Sphinx](http://www.sphinx-doc.org/en/stable/) `$ pip install Sphinx` * In the `docs` directory run `$ sphinx-build -b html . build` and view the generated HTML files in the `build` directory. * If you want to update the complete structure use `-a` build option in order to rebuild the entire documentation <file_sep><?php /* * This file is part of the Monofony package. * * (c) Monofony * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Monofony\Bundle\CoreBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; final class RegisterDashboardStatisticsPass implements CompilerPassInterface { public function process(ContainerBuilder $container) { if (!$container->hasDefinition('monofony.admin.dashboard_statistics_provider')) { return; } $definition = $container->findDefinition('monofony.admin.dashboard_statistics_provider'); $taggedServices = $container->findTaggedServiceIds('monofony.dashboard_statistic'); $arguments = []; foreach ($taggedServices as $id => $tags) { // add the dashboard statistic to the provider $arguments[] = new Reference($id); } $definition->setArguments([$arguments]); } } <file_sep>## Change Log ### v0.1.1 (2020/03/06 16:28 +00:00) - [#129](https://github.com/Monofony/Monofony/pull/129) Fix api routes (@loic425) - [#128](https://github.com/Monofony/Monofony/pull/128) Update readme (@loic425) ### v0.1.0 (2020/03/04 20:28 +00:00) - [#127](https://github.com/Monofony/Monofony/pull/127) Configure swift mailer spool for tests (@loic425) - [#126](https://github.com/Monofony/Monofony/pull/126) Fix phpstan error (@loic425) - [#125](https://github.com/Monofony/Monofony/pull/125) Fix grids configuration path (@loic425) - [#123](https://github.com/Monofony/Monofony/pull/123) Move client manager and simplify add user form subscriber (@loic425) - [#124](https://github.com/Monofony/Monofony/pull/124) Move fixtures configuration into fixtures plugin (@loic425) - [#122](https://github.com/Monofony/Monofony/pull/122) Improve package configuration (@loic425) - [#121](https://github.com/Monofony/Monofony/pull/121) Improve fixtures plugin (@loic425) - [#120](https://github.com/Monofony/Monofony/pull/120) Add some Behat behaviours (@loic425) - [#119](https://github.com/Monofony/Monofony/pull/119) Improve Behat services (@loic425) - [#118](https://github.com/Monofony/Monofony/pull/118) Remove todo on behat scenarios (@loic425) - [#117](https://github.com/Monofony/Monofony/pull/117) Remove make files from bundle (@loic425) - [#116](https://github.com/Monofony/Monofony/pull/116) Move Behat services into core bundle (@loic425) - [#115](https://github.com/Monofony/Monofony/pull/115) Move Crud pages on admin buddle (@loic425) - [#114](https://github.com/Monofony/Monofony/pull/114) Monofony data collector (@loic425) - [#113](https://github.com/Monofony/Monofony/pull/113) Fix symfony serializer dependency (@loic425) - [#111](https://github.com/Monofony/Monofony/pull/111) Init Api Bundle (@loic425) - [#112](https://github.com/Monofony/Monofony/pull/112) Make FixturesBundle a Monofony plugin (@loic425) - [#110](https://github.com/Monofony/Monofony/pull/110) Add Fixtures bundle and update coding standard (@loic425) - [#109](https://github.com/Monofony/Monofony/pull/109) Move Makefile on CoreBundle (@loic425) - [#108](https://github.com/Monofony/Monofony/pull/108) Fix some namespaces (@loic425) - [#106](https://github.com/Monofony/Monofony/pull/106) Configure bundles autoload (@loic425) - [#107](https://github.com/Monofony/Monofony/pull/107) Fix Core bundle extension namespace (@loic425) - [#105](https://github.com/Monofony/Monofony/pull/105) Add core licence and composer requirements (@loic425) - [#104](https://github.com/Monofony/Monofony/pull/104) Tag doctrine subscribers (@loic425) - [#103](https://github.com/Monofony/Monofony/pull/103) Improve changing customer context visibility (@loic425) - [#102](https://github.com/Monofony/Monofony/pull/102) Fix bundle requirements (@loic425) - [#101](https://github.com/Monofony/Monofony/pull/101) Configure Admin dashboard statistics (@loic425) - [#100](https://github.com/Monofony/Monofony/pull/100) Move account and admin menu builders on bundles (@loic425) - [#99](https://github.com/Monofony/Monofony/pull/99) Move core recipe src files into CoreBundle (@loic425) - [#98](https://github.com/Monofony/Monofony/pull/98) Move webpack core config (@loic425) - [#97](https://github.com/Monofony/Monofony/pull/97) Move TestPack into Monofony directory (@loic425) - [#96](https://github.com/Monofony/Monofony/pull/96) Move some Front recipes (@loic425) - [#95](https://github.com/Monofony/Monofony/pull/95) Move frontend config recipe into FrontBundle (@loic425) - [#94](https://github.com/Monofony/Monofony/pull/94) Remove Admin and AdminPack directory (@loic425) - [#93](https://github.com/Monofony/Monofony/pull/93) Move admin recipe src into AdminBundle (@loic425) - [#92](https://github.com/Monofony/Monofony/pull/92) Move admin config into AdminBundle (@loic425) - [#91](https://github.com/Monofony/Monofony/pull/91) Init front bundle with some recipe files (@loic425) - [#90](https://github.com/Monofony/Monofony/pull/90) Init Admin bundle with some recipe files (@loic425) - [#57](https://github.com/Monofony/Monofony/pull/57) [WIP] init webpack config (@loic425, @smildev) - [#89](https://github.com/Monofony/Monofony/pull/89) Move some core recipe files into CoreBundle (@loic425) - [#88](https://github.com/Monofony/Monofony/pull/88) Move Core features recipe into CoreBundle (@loic425) - [#87](https://github.com/Monofony/Monofony/pull/87) Move Core config recipe into CoreBundle (@loic425) - [#86](https://github.com/Monofony/Monofony/pull/86) Customer Context on CoreBundle recipe (@loic425) - [#85](https://github.com/Monofony/Monofony/pull/85) Init a Core bundle and core component (@loic425) - [#1](https://github.com/Monofony/Monofony/pull/1) finalize main webpack (@smildev) - [#82](https://github.com/Monofony/Monofony/pull/82) New Makefile for tests and CI (@loic425) - [#83](https://github.com/Monofony/Monofony/pull/83) Rename packages when it is not a pack (@loic425) - [#81](https://github.com/Monofony/Monofony/pull/81) Use glob pattern for grid configuration (@loic425) - [#79](https://github.com/Monofony/Monofony/pull/79) Use Friends of Behat Mink extension (@loic425) - [#78](https://github.com/Monofony/Monofony/pull/78) Seeing customer's basic information (@loic425) - [#76](https://github.com/Monofony/Monofony/pull/76) Finish some managing administrators behat scenarios (@loic425) - [#74](https://github.com/Monofony/Monofony/pull/74) Autowire all Behat backend pages (@loic425) - [#73](https://github.com/Monofony/Monofony/pull/73) Remove Files' header and Test coding standard (@loic425) - [#72](https://github.com/Monofony/Monofony/pull/72) Move suites configuration (@loic425) - [#71](https://github.com/Monofony/Monofony/pull/71) Simplify services test (@loic425) - [#70](https://github.com/Monofony/Monofony/pull/70) Remove suite settings extension from test pack (@loic425) - [#69](https://github.com/Monofony/Monofony/pull/69) Use class name on grids (@loic425) - [#68](https://github.com/Monofony/Monofony/pull/68) Remove some config from core package (@loic425) - [#67](https://github.com/Monofony/Monofony/pull/67) Configure sylius fixtures on fixtures pack (@loic425) - [#66](https://github.com/Monofony/Monofony/pull/66) Test Pack (@loic425) - [#65](https://github.com/Monofony/Monofony/pull/65) Sylius configuration (@loic425) - [#64](https://github.com/Monofony/Monofony/pull/64) Add MIT license on composer (@loic425) - [#63](https://github.com/Monofony/Monofony/pull/63) Add packages licences (@loic425) - [#62](https://github.com/Monofony/Monofony/pull/62) Improve composer requirements of packages (@loic425) - [#61](https://github.com/Monofony/Monofony/pull/61) Extract kernel from packages (@loic425) - [#59](https://github.com/Monofony/Monofony/pull/59) Fix Travis after script (@loic425) - [#58](https://github.com/Monofony/Monofony/pull/58) Split repos on merge to master (@loic425) - [#56](https://github.com/Monofony/Monofony/pull/56) Monorepo builder (@loic425) - [#55](https://github.com/Monofony/Monofony/pull/55) Api pack (@loic425) - [#54](https://github.com/Monofony/Monofony/pull/54) Move kernel into core package (@loic425) - [#53](https://github.com/Monofony/Monofony/pull/53) Rename packs (@loic425) - [#52](https://github.com/Monofony/Monofony/pull/52) Move packages content into recipe directory (@loic425) - [#51](https://github.com/Monofony/Monofony/pull/51) .recipes into src directory (@loic425) - [#50](https://github.com/Monofony/Monofony/pull/50) Remove other behat classes (@loic425) - [#49](https://github.com/Monofony/Monofony/pull/49) Move Behat services into core package (@loic425) - [#48](https://github.com/Monofony/Monofony/pull/48) Move some Behat services into core package (@loic425) - [#47](https://github.com/Monofony/Monofony/pull/47) Move frontend suites configuration into frontend package (@loic425) - [#46](https://github.com/Monofony/Monofony/pull/46) Move backend suites configuration into backend package (@loic425) - [#45](https://github.com/Monofony/Monofony/pull/45) User registration subscriber instead of a listener (@loic425) - [#44](https://github.com/Monofony/Monofony/pull/44) Use a subscriber instead of a listener to set default username with e… (@loic425) - [#43](https://github.com/Monofony/Monofony/pull/43) Use a subscriber instead of a listener to canonicalize usernames and … (@loic425) - [#42](https://github.com/Monofony/Monofony/pull/42) Fully autowire fixtures (@loic425) - [#41](https://github.com/Monofony/Monofony/pull/41) Prepare core services.yaml (@loic425) - [#40](https://github.com/Monofony/Monofony/pull/40) Move dependency injection compilers on core package (@loic425) - [#38](https://github.com/Monofony/Monofony/pull/38) Tests psalm on recipes (@loic425) - [#39](https://github.com/Monofony/Monofony/pull/39) Test phpstan on recipes (@loic425) - [#37](https://github.com/Monofony/Monofony/pull/37) Validate twig on recipes (@loic425) - [#36](https://github.com/Monofony/Monofony/pull/36) Move bundles templates override into core package (@loic425) - [#35](https://github.com/Monofony/Monofony/pull/35) Move templates into packages (@loic425) - [#34](https://github.com/Monofony/Monofony/pull/34) Move phspecs (@loic425) - [#33](https://github.com/Monofony/Monofony/pull/33) Move translations into core package (@loic425) - [#32](https://github.com/Monofony/Monofony/pull/32) Move account menu in frontend package (@loic425) - [#31](https://github.com/Monofony/Monofony/pull/31) Move some backend services into monofony backend package (@loic425) - [#30](https://github.com/Monofony/Monofony/pull/30) Feature/change customer context visibility on compiler pass (@loic425) - [#29](https://github.com/Monofony/Monofony/pull/29) Refactor compiler pass (@loic425) - [#28](https://github.com/Monofony/Monofony/pull/28) Autowire customer context (@loic425) - [#27](https://github.com/Monofony/Monofony/pull/27) Remove form services configuration (@loic425) - [#26](https://github.com/Monofony/Monofony/pull/26) Split services configuration (@loic425) - [#24](https://github.com/Monofony/Monofony/pull/24) Improve backend routes config for recipe (@loic425) - [#23](https://github.com/Monofony/Monofony/pull/23) Simplify makefile (@loic425) - [#22](https://github.com/Monofony/Monofony/pull/22) Move core features (@loic425) - [#21](https://github.com/Monofony/Monofony/pull/21) Move frontend features (@loic425) - [#20](https://github.com/Monofony/Monofony/pull/20) Move admin Behat features into monofony backend package (@loic425) - [#19](https://github.com/Monofony/Monofony/pull/19) Move formatter into monofony core package (@loic425) - [#18](https://github.com/Monofony/Monofony/pull/18) Rename monofony admin package into monofony backend package (@loic425) - [#17](https://github.com/Monofony/Monofony/pull/17) Move frontend routes into monofony-frontend package (@loic425) - [#16](https://github.com/Monofony/Monofony/pull/16) Move backend routes into monofony-admin package (@loic425) - [#15](https://github.com/Monofony/Monofony/pull/15) Move grids configuration in monofony admin package (@loic425) - [#14](https://github.com/Monofony/Monofony/pull/14) Remove capistrano (@loic425) - [#12](https://github.com/Monofony/Monofony/pull/12) Move installer into core package (@loic425) - [#11](https://github.com/Monofony/Monofony/pull/11) Move customer context into core package (@loic425) - [#10](https://github.com/Monofony/Monofony/pull/10) Move collector into core package (@loic425) - [#9](https://github.com/Monofony/Monofony/pull/9) Move forms into core package (@loic425) - [#8](https://github.com/Monofony/Monofony/pull/8) Bump node version (@loic425) - [#7](https://github.com/Monofony/Monofony/pull/7) Move repositories into core package (@loic425) - [#6](https://github.com/Monofony/Monofony/pull/6) Move event listeners into core package (@loic425) - [#5](https://github.com/Monofony/Monofony/pull/5) Move migrations into core package (@loic425) - [#4](https://github.com/Monofony/Monofony/pull/4) Move commands into monofony core package (@loic425) - [#3](https://github.com/Monofony/Monofony/pull/3) Rename recipes directory (@loic425) - [#2](https://github.com/Monofony/Monofony/pull/2) Move fixtures services into monofony-fixtures package (@loic425) - [#1](https://github.com/Monofony/Monofony/pull/1) Move entities into core package (@loic425) - [#260](https://github.com/Monofony/Monofony/pull/260) Docs/dashboard dynamic statistics (@lucasballyn) - [#263](https://github.com/Monofony/Monofony/pull/263) Fix var log permissions on Capistrano (@loic425) - [#262](https://github.com/Monofony/Monofony/pull/262) Fix testing migrations on travis (@loic425) - [#261](https://github.com/Monofony/Monofony/pull/261) Fix security issue from Sylius resource bundle (@loic425) - [#259](https://github.com/Monofony/Monofony/pull/259) Move grids' configuration files into config/grids directory (@loic425) - [#258](https://github.com/Monofony/Monofony/pull/258) improve sonata block configuration (@smildev) - [#256](https://github.com/Monofony/Monofony/pull/256) Use argon2id as sylius user encoder (@loic425) - [#255](https://github.com/Monofony/Monofony/pull/255) [Security] Auto encoder (@loic425) - [#253](https://github.com/Monofony/Monofony/pull/253) Fix backend search visibility (@loic425) - [#250](https://github.com/Monofony/Monofony/pull/250) Add start selenium command on makefile (@loic425) - [#232](https://github.com/Monofony/Monofony/pull/232) Dynamic statistics on administration panel (@loicmobizel, @lucasballyn) - [#251](https://github.com/Monofony/Monofony/pull/251) Bump version of Symfony to 4.4 (@loic425) - [#245](https://github.com/Monofony/Monofony/pull/245) Show your app version on admin footer and debug toolbar (@loic425) - [#248](https://github.com/Monofony/Monofony/pull/248) Replace web server bundle by symfony server (@loic425) - [#247](https://github.com/Monofony/Monofony/pull/247) Improve services configuration for menus (@loic425) - [#246](https://github.com/Monofony/Monofony/pull/246) Favicon (@loic425) - [#243](https://github.com/Monofony/Monofony/pull/243) Fix services config on Behat documentation (@loic425) - [#242](https://github.com/Monofony/Monofony/pull/242) Fix Behat documentation (@loic425) - [#241](https://github.com/Monofony/Monofony/pull/241) Fix capistrano media directory (@loic425) - [#238](https://github.com/Monofony/Monofony/pull/238) Adding file management and admin avatar (@loic425, @loicmobizel) - [#240](https://github.com/Monofony/Monofony/pull/240) Add select grid filter template (@loic425) - [#236](https://github.com/Monofony/Monofony/pull/236) Upgrade credits (@loicmobizel) - [#235](https://github.com/Monofony/Monofony/pull/235) Improve main config file (@loic425) - [#233](https://github.com/Monofony/Monofony/pull/233) Move Behat directory into tests and move behat config in main config (@loicmobizel) - [#230](https://github.com/Monofony/Monofony/pull/230) Add Api Platform library (@loicmobizel, @loic425) - [#217](https://github.com/Monofony/Monofony/pull/217) Group entities on domains (@loic425) - [#231](https://github.com/Monofony/Monofony/pull/231) Add OAuth login and refresh token (@loicmobizel) - [#229](https://github.com/Monofony/Monofony/pull/229) Improve demo links on readme (@loic425) - [#228](https://github.com/Monofony/Monofony/pull/228) Add demo link on README file (@loicmobizel) - [#227](https://github.com/Monofony/Monofony/pull/227) Fix capistrano locking version and gem dependencies (@loic425) - [#226](https://github.com/Monofony/Monofony/pull/226) Fix capistrano linked files (@loic425) - [#225](https://github.com/Monofony/Monofony/pull/225) Add sonata events to be able to include javascript with events (@maximehuran) - [#224](https://github.com/Monofony/Monofony/pull/224) Switch from Semantic-UI to Fomantic-UI (@loic425) - [#223](https://github.com/Monofony/Monofony/pull/223) New admin panel (@loic425) - [#222](https://github.com/Monofony/Monofony/pull/222) Fix Symfony security issues (@loic425) - [#221](https://github.com/Monofony/Monofony/pull/221) Update logo (@loic425) - [#220](https://github.com/Monofony/Monofony/pull/220) Upgrade database setup commands (@maximehuran) - [#219](https://github.com/Monofony/Monofony/pull/219) Update htaccess for Symfony 4 (@maximehuran) - [#218](https://github.com/Monofony/Monofony/pull/218) Add phpspec extension for phpstan (@loic425) - [#211](https://github.com/Monofony/Monofony/pull/211) build assets with webpack instead of gulp (@loic425, @loicmobizel, @smildev, @kevinMz) - [#216](https://github.com/Monofony/Monofony/pull/216) Bump version of Sylius resource bundle from 1.5 to 1.6 (@loic425) - [#215](https://github.com/Monofony/Monofony/pull/215) [Travis] Test migrations (@loic425) - [#214](https://github.com/Monofony/Monofony/pull/214) Bump Sylius to 1.6 (@loic425) - [#210](https://github.com/Monofony/Monofony/pull/210) Fix api config (@loic425) - [#213](https://github.com/Monofony/Monofony/pull/213) Bump fstream from 1.0.11 to 1.0.12 (@dependabot[bot]) - [#212](https://github.com/Monofony/Monofony/pull/212) Bump mixin-deep from 1.3.1 to 1.3.2 (@dependabot[bot]) - [#209](https://github.com/Monofony/Monofony/pull/209) Fix profiler toolbar (@loic425) - [#203](https://github.com/Monofony/Monofony/pull/203) Some code improvements (@loic425) - [#208](https://github.com/Monofony/Monofony/pull/208) Run infection only on changed files on CI (@loic425) - [#207](https://github.com/Monofony/Monofony/pull/207) Bump lodash.mergewith from 4.6.1 to 4.6.2 (@dependabot[bot]) - [#206](https://github.com/Monofony/Monofony/pull/206) Bump lodash from 4.17.11 to 4.17.15 (@dependabot[bot]) - [#205](https://github.com/Monofony/Monofony/pull/205) Bump js-yaml from 3.12.0 to 3.13.1 (@dependabot[bot]) - [#204](https://github.com/Monofony/Monofony/pull/204) Improve services configuration (@loic425) - [#200](https://github.com/Monofony/Monofony/pull/200) Admin dashboard with initial content (@loic425) - [#201](https://github.com/Monofony/Monofony/pull/201) Make lint command (@loic425) - [#199](https://github.com/Monofony/Monofony/pull/199) [Fix] test prod requirements with prod env (@loic425) - [#198](https://github.com/Monofony/Monofony/pull/198) upgrade dependencies (@loic425) - [#197](https://github.com/Monofony/Monofony/pull/197) Apply new fresh admin panel (@loic425) - [#194](https://github.com/Monofony/Monofony/pull/194) Makefile commands overridable (@loic425) - [#196](https://github.com/Monofony/Monofony/pull/196) Fix deprecation notice from Dotenv (@loic425) - [#195](https://github.com/Monofony/Monofony/pull/195) Remove unused composer-parameter-handler (@loic425) - [#192](https://github.com/Monofony/Monofony/pull/192) Upgrade to symfony 4.3 (@loic425) - [#191](https://github.com/Monofony/Monofony/pull/191) psalm level 5 (@loic425) - [#190](https://github.com/Monofony/Monofony/pull/190) Fix grid security issue (@loic425) - [#189](https://github.com/Monofony/Monofony/pull/189) Psalm level 6 (@loic425) - [#188](https://github.com/Monofony/Monofony/pull/188) Kill mutants (@loic425) - [#184](https://github.com/Monofony/Monofony/pull/184) Add how to generate backend menu. Add article form type (@harikt) - [#186](https://github.com/Monofony/Monofony/pull/186) Upgrade sylius bundles and components (@loic425) - [#180](https://github.com/Monofony/Monofony/pull/180) Using vimeo psalm on test (level 8) (@loic425) - [#181](https://github.com/Monofony/Monofony/pull/181) Fix typo yaml (@harikt) - [#179](https://github.com/Monofony/Monofony/pull/179) Rename yaml files with yaml extension (@loic425) - [#178](https://github.com/Monofony/Monofony/pull/178) improve code quality on managing customers and registration behat con… (@loic425) - [#177](https://github.com/Monofony/Monofony/pull/177) use argon2i password encoder (@loic425) - [#175](https://github.com/Monofony/Monofony/pull/175) Do not run infection on all files when nothing has changed (@loic425) - [#176](https://github.com/Monofony/Monofony/pull/176) Upgrade symfony (security bugfix) (@loic425) - [#174](https://github.com/Monofony/Monofony/pull/174) [Account] Remember me on frontend login (@loic425) - [#173](https://github.com/Monofony/Monofony/pull/173) improve make file with a lot of tests (@loic425) - [#172](https://github.com/Monofony/Monofony/pull/172) upgrade sylius to 1.4.3 (@loic425) - [#171](https://github.com/Monofony/Monofony/pull/171) fix app js errors (@loic425) - [#169](https://github.com/Monofony/Monofony/pull/169) Improve infection scoring (@loic425) - [#168](https://github.com/Monofony/Monofony/pull/168) Dump env prod (@loic425) - [#167](https://github.com/Monofony/Monofony/pull/167) [Composer] Fix project name and licence (@lchrusciel) - [#165](https://github.com/Monofony/Monofony/pull/165) add twitter link on readme (@loic425) - [#166](https://github.com/Monofony/Monofony/pull/166) Autoconfigure frontend behat pages (@loic425) - [#164](https://github.com/Monofony/Monofony/pull/164) [docs] move behat guide into cookbook (@loic425) - [#163](https://github.com/Monofony/Monofony/pull/163) Run infection only on changed files (@loic425) - [#162](https://github.com/Monofony/Monofony/pull/162) improve infection (@loic425) - [#161](https://github.com/Monofony/Monofony/pull/161) Improve user and customer entities (@loic425) - [#160](https://github.com/Monofony/Monofony/pull/160) [docs] add it has no title by default behaviour on docs (@loic425) - [#159](https://github.com/Monofony/Monofony/pull/159) Add test-behat-with-javascript command on makefile (@loic425) - [#158](https://github.com/Monofony/Monofony/pull/158) [docs] design services with phpspec (@loic425) - [#157](https://github.com/Monofony/Monofony/pull/157) [Docs] Specify your entities with phpspec (@loic425) - [#156](https://github.com/Monofony/Monofony/pull/156) Set username on admin user example factory (@loic425) - [#155](https://github.com/Monofony/Monofony/pull/155) Makefile (@loic425) - [#154](https://github.com/Monofony/Monofony/pull/154) Refresh entities documentation (@loic425) - [#153](https://github.com/Monofony/Monofony/pull/153) update doc url (@loic425) - [#152](https://github.com/Monofony/Monofony/pull/152) run setup command on install command (@loic425) - [#151](https://github.com/Monofony/Monofony/pull/151) improve data fixtures documentation (@loic425) - [#148](https://github.com/Monofony/Monofony/pull/148) improve listeners' dependency injection (@loic425) - [#150](https://github.com/Monofony/Monofony/pull/150) Init a documentation to configure your datafixtures (@loic425) - [#147](https://github.com/Monofony/Monofony/pull/147) Improve form dependency injection (@loic425) - [#149](https://github.com/Monofony/Monofony/pull/149) upgrade twig (security fix) (@loic425) - [#146](https://github.com/Monofony/Monofony/pull/146) Autoconfigure fixtures (@loic425) - [#145](https://github.com/Monofony/Monofony/pull/145) Replace AppName by Monofony on documentation (@loic425) - [#144](https://github.com/Monofony/Monofony/pull/144) Few fixes on readme (@loic425) - [#143](https://github.com/Monofony/Monofony/pull/143) [Docs] refresh readme (@loic425) - [#142](https://github.com/Monofony/Monofony/pull/142) use project dir instead of root dir on install sample data command (@loic425) - [#141](https://github.com/Monofony/Monofony/pull/141) Refresh cookbook entities doc (@loic425) - [#140](https://github.com/Monofony/Monofony/pull/140) Refresh bdd guide (@loic425) - [#139](https://github.com/Monofony/Monofony/pull/139) remove container aware command on create client command (@loic425) - [#138](https://github.com/Monofony/Monofony/pull/138) Remove abstract install command (@loic425) - [#137](https://github.com/Monofony/Monofony/pull/137) remove container aware command on setup command (@loic425) - [#136](https://github.com/Monofony/Monofony/pull/136) Fix setup command (@loic425) - [#135](https://github.com/Monofony/Monofony/pull/135) Monofony logo (@loic425) - [#133](https://github.com/Monofony/Monofony/pull/133) Run behat with cli on travis (@loic425) - [#132](https://github.com/Monofony/Monofony/pull/132) Move DotEnv on prod requirements (@loic425) - [#131](https://github.com/Monofony/Monofony/pull/131) fix gitignore (@loic425) - [#129](https://github.com/Monofony/Monofony/pull/129) Fix js on backend (@loic425) - [#130](https://github.com/Monofony/Monofony/pull/130) Fix security check on travis (@loic425) - [#128](https://github.com/Monofony/Monofony/pull/128) Remove track advance mention (@loic425) - [#127](https://github.com/Monofony/Monofony/pull/127) add phpspec.yml on gitignore (@loic425) - [#126](https://github.com/Monofony/Monofony/pull/126) replace gitkeep with gitignore on etc build directory (@loic425) - [#125](https://github.com/Monofony/Monofony/pull/125) remove useless address templates (@loic425) - [#124](https://github.com/Monofony/Monofony/pull/124) Remove api section from docs (@loic425) - [#123](https://github.com/Monofony/Monofony/pull/123) Fix account registration (@loic425) - [#122](https://github.com/Monofony/Monofony/pull/122) add some missing phpspec (@loic425) - [#121](https://github.com/Monofony/Monofony/pull/121) fix fzaninotto/faker for composer 2.0 (@loic425) - [#120](https://github.com/Monofony/Monofony/pull/120) Use getExtentedTypes instead of deprecated getExtentedType method (@loic425) - [#119](https://github.com/Monofony/Monofony/pull/119) Remove vagrant setup from readme (@loic425) - [#118](https://github.com/Monofony/Monofony/pull/118) Improve docs (@loic425) - [#117](https://github.com/Monofony/Monofony/pull/117) Remove Foundation view (@loic425) - [#116](https://github.com/Monofony/Monofony/pull/116) [Behat] Test installation command (@loic425) - [#115](https://github.com/Monofony/Monofony/pull/115) Remove vagrant (@loic425) - [#112](https://github.com/Monofony/Monofony/pull/112) autowire fixtures (@loic425) - [#110](https://github.com/Monofony/Monofony/pull/110) Autowire fixture factories (@loic425) - [#109](https://github.com/Monofony/Monofony/pull/109) autowire behat contexts with resource autogenerated services (@loic425) - [#108](https://github.com/Monofony/Monofony/pull/108) upgrade sylius resource to 1.4 (@loic425) - [#105](https://github.com/Monofony/Monofony/pull/105) [Behat] autowiring contexts (@loic425) - [#103](https://github.com/Monofony/Monofony/pull/103) WIP upgrade fob symfony extension (@loic425) - [#102](https://github.com/Monofony/Monofony/pull/102) Switch to dotenv file handling (@loic425) - [#101](https://github.com/Monofony/Monofony/pull/101) Upgrade doctrine ORM (@loic425) - [#99](https://github.com/Monofony/Monofony/pull/99) upgrade to doctrine migration 2.0 (@loic425) - [#98](https://github.com/Monofony/Monofony/pull/98) fix change password (@loic425) - [#96](https://github.com/Monofony/Monofony/pull/96) fix gulpfile to build both backend and frontend (@loic425) - [#95](https://github.com/Monofony/Monofony/pull/95) [Docs] update behat guide (@loic425) - [#94](https://github.com/Monofony/Monofony/pull/94) [Cookbook] Create and configure a new entity (@loic425) - [#93](https://github.com/Monofony/Monofony/pull/93) update doc theme (@loic425) - [#92](https://github.com/Monofony/Monofony/pull/92) improve admin dashboard path (@loic425) - [#91](https://github.com/Monofony/Monofony/pull/91) update template request password reset page with semantic ui (@loic425) - [#90](https://github.com/Monofony/Monofony/pull/90) update template reset password page with semantic ui (@loic425) - [#89](https://github.com/Monofony/Monofony/pull/89) update account templates with semantic ui (@loic425) - [#84](https://github.com/Monofony/Monofony/pull/84) Gulp babel (@loic425) - [#82](https://github.com/Monofony/Monofony/pull/82) Enable behat with javascript on travis (@loic425) - [#81](https://github.com/Monofony/Monofony/pull/81) Features/deleting multiple administrators (@loic425) - [#80](https://github.com/Monofony/Monofony/pull/80) upgrade sylius to 1.3 (@loic425) - [#79](https://github.com/Monofony/Monofony/pull/79) config for behat with javascript (@loic425) - [#78](https://github.com/Monofony/Monofony/pull/78) remove special config files for travis, use test files instead (@loic425) - [#77](https://github.com/Monofony/Monofony/pull/77) use friends of behat page object extension (@loic425) - [#76](https://github.com/Monofony/Monofony/pull/76) update head comment blocks (@loic425) - [#75](https://github.com/Monofony/Monofony/pull/75) Remove author blocks (@loic425) - [#74](https://github.com/Monofony/Monofony/pull/74) Remove Symfony/Symfony definitively (@loic425) - [#73](https://github.com/Monofony/Monofony/pull/73) upgrade symfony packages (@loic425) - [#72](https://github.com/Monofony/Monofony/pull/72) use database_url for database configuration (@loic425) - [#71](https://github.com/Monofony/Monofony/pull/71) remove symfony/symfony from composer requirement (@loic425) - [#70](https://github.com/Monofony/Monofony/pull/70) Fix/missing symfony packages (@loic425) - [#69](https://github.com/Monofony/Monofony/pull/69) fix user verification routes (@loic425) - [#65](https://github.com/Monofony/Monofony/pull/65) Remove address entity (@loic425) - [#63](https://github.com/Monofony/Monofony/pull/63) update command directory according to new Symfony recommendations (@loic425) - [#62](https://github.com/Monofony/Monofony/pull/62) remove assets symlinks (@loic425) - [#60](https://github.com/Monofony/Monofony/pull/60) remove selenium standalone from readme (@loic425) - [#61](https://github.com/Monofony/Monofony/pull/61) Improve capistrano config (@loic425) - [#59](https://github.com/Monofony/Monofony/pull/59) switch to lchrusciel/api-test-case (@loic425) - [#58](https://github.com/Monofony/Monofony/pull/58) test installer on travis (@loic425) - [#57](https://github.com/Monofony/Monofony/pull/57) use phpdbg instead of xdebug (@loic425) - [#56](https://github.com/Monofony/Monofony/pull/56) add specs for form event subscribers (@loic425) - [#55](https://github.com/Monofony/Monofony/pull/55) remove resource loader (@loic425) - [#54](https://github.com/Monofony/Monofony/pull/54) add specs for event listeners (@loic425) - [#53](https://github.com/Monofony/Monofony/pull/53) init infection (@loic425) - [#52](https://github.com/Monofony/Monofony/pull/52) php cs fix (@loic425) - [#50](https://github.com/Monofony/Monofony/pull/50) remove old behat feature (@loic425) - [#51](https://github.com/Monofony/Monofony/pull/51) add specs for customer and user entity (@loic425) - [#49](https://github.com/Monofony/Monofony/pull/49) remove codeship (@loic425) - [#48](https://github.com/Monofony/Monofony/pull/48) fix account pages (@loic425) - [#47](https://github.com/Monofony/Monofony/pull/47) fix homepage and init an empty behat homepage context (@loic425) - [#46](https://github.com/Monofony/Monofony/pull/46) validate yaml files on travis (@loic425) - [#44](https://github.com/Monofony/Monofony/pull/44) init flex (@loic425) - [#43](https://github.com/Monofony/Monofony/pull/43) Renaming registering administrator account feature (@loic425) - [#42](https://github.com/Monofony/Monofony/pull/42) sort packages (@loic425) - [#41](https://github.com/Monofony/Monofony/pull/41) fix install command (@loic425) - [#40](https://github.com/Monofony/Monofony/pull/40) upgrade sylius to 1.2.1 (@loic425) - [#39](https://github.com/Monofony/Monofony/pull/39) improve doctrine config (@loic425) - [#38](https://github.com/Monofony/Monofony/pull/38) add some issue templates (@loic425) - [#37](https://github.com/Monofony/Monofony/pull/37) add some phpstan addons (@loic425) - [#36](https://github.com/Monofony/Monofony/pull/36) Fix/frontend templates (@loic425) - [#35](https://github.com/Monofony/Monofony/pull/35) fix api test wording (@loic425) - [#34](https://github.com/Monofony/Monofony/pull/34) fix login template (@loic425) - [#32](https://github.com/Monofony/Monofony/pull/32) improve spec of Address entity (@loic425) - [#31](https://github.com/Monofony/Monofony/pull/31) Migrating to symfony4 (@loic425) - [#30](https://github.com/Monofony/Monofony/pull/30) upgrade monolog bundle (@loic425) - [#29](https://github.com/Monofony/Monofony/pull/29) jedisjeux replacements (@loic425) - [#28](https://github.com/Monofony/Monofony/pull/28) Upgrade/php 7.2 (@loic425) - [#27](https://github.com/Monofony/Monofony/pull/27) upgrade dev dependencies (@loic425) - [#26](https://github.com/Monofony/Monofony/pull/26) upgrade some dependencies (@loic425) - [#25](https://github.com/Monofony/Monofony/pull/25) remove some deprecations (@loic425) - [#24](https://github.com/Monofony/Monofony/pull/24) upgrade to sylius 1.2 (@loic425) - [#22](https://github.com/Monofony/Monofony/pull/22) [Behat] Managing customers behat features (@loic425) - [#21](https://github.com/Monofony/Monofony/pull/21) viewing address feature (@loic425) - [#20](https://github.com/Monofony/Monofony/pull/20) use yarn (@loic425) - [#19](https://github.com/Monofony/Monofony/pull/19) add viewing addresses behat test (@loic425) - [#18](https://github.com/Monofony/Monofony/pull/18) upgrade symfony (@loic425) - [#17](https://github.com/Monofony/Monofony/pull/17) upgrade sylius to 1.1.6 (@loic425) - [#16](https://github.com/Monofony/Monofony/pull/16) [Behat] adding administrator (@loic425) - [#14](https://github.com/Monofony/Monofony/pull/14) [Behat] remove old contexts (@loic425) - [#15](https://github.com/Monofony/Monofony/pull/15) Remove compiled assets (@loic425) - [#13](https://github.com/Monofony/Monofony/pull/13) Feature/behat refactor (@loic425) - [#12](https://github.com/Monofony/Monofony/pull/12) [Behat] inject dependencies on orm context (@loic425) - [#11](https://github.com/Monofony/Monofony/pull/11) [Behat] inject dependencies in AddressContext (@loic425) - [#10](https://github.com/Monofony/Monofony/pull/10) [Behat] remove default api context (@loic425) - [#9](https://github.com/Monofony/Monofony/pull/9) [Behat] add doctrine orm context (@loic425) - [#8](https://github.com/Monofony/Monofony/pull/8) [Behat] use new setup address context (@loic425) - [#7](https://github.com/Monofony/Monofony/pull/7) add setup context for address entity (@loic425) - [#6](https://github.com/Monofony/Monofony/pull/6) [Git] remove symfony requirements (@loic425) - [#5](https://github.com/Monofony/Monofony/pull/5) add travis and scrutinizer results on readme (@loic425) - [#4](https://github.com/Monofony/Monofony/pull/4) [Travis] add test phpstan step on travis (@loic425) - [#3](https://github.com/Monofony/Monofony/pull/3) Travis (@loic425) - [#2](https://github.com/Monofony/Monofony/pull/2) remove mobizel mentions (@loic425) - [#1](https://github.com/Monofony/Monofony/pull/1) remove mzh (@loic425) <file_sep><?php declare(strict_types=1); namespace App\MessageHandler; use App\Message\RegisterAppUser; use App\Provider\CustomerProviderInterface; use Monofony\Contracts\Core\Model\User\AppUserInterface; use Sylius\Component\Resource\Factory\FactoryInterface; use Sylius\Component\Resource\Repository\RepositoryInterface; use Symfony\Component\Messenger\Handler\MessageHandlerInterface; final class RegisterAppUserHandler implements MessageHandlerInterface { public function __construct( private FactoryInterface $appUserFactory, private RepositoryInterface $appUserRepository, private CustomerProviderInterface $customerProvider, ) { } public function __invoke(RegisterAppUser $command): void { /** @var AppUserInterface $user */ $user = $this->appUserFactory->createNew(); $user->setPlainPassword($command->password); $customer = $this->customerProvider->provide($command->email); if (null !== $customer->getUser()) { throw new \DomainException(sprintf('User with email "%s" is already registered.', $command->email)); } $customer->setFirstName($command->firstName); $customer->setLastName($command->lastName); $customer->setPhoneNumber($command->phoneNumber); $customer->setUser($user); $this->appUserRepository->add($user); } } <file_sep>.. rst-class:: outdated .. danger:: This is an outdated documentation please read the new `Monofony documentation`_ instead. How to configure backend menu ============================= To configure backend menu for your entity, you have to edit `src/Menu/AdminMenuBuilder.php`. .. code-block:: php // src/Menu/AdminMenuBuilder.php public function createMenu(array $options): ItemInterface { // add method ... $this->addContentSubMenu($menu); // rest of the code return $menu; } /** * @param ItemInterface $menu * * @return ItemInterface */ private function addContentSubMenu(ItemInterface $menu): ItemInterface { $content = $menu ->addChild('content') ->setLabel('sylius.ui.content') ; $content->addChild('backend_article', ['route' => 'app_backend_article_index']) ->setLabel('app.ui.articles') ->setLabelAttribute('icon', 'newspaper'); return $content; } .. _Monofony documentation: https://docs.monofony.com <file_sep>* :doc:`/cookbook/entities/first-resource` * :doc:`/cookbook/entities/manage-your-entity` * :doc:`/cookbook/entities/configure-your-routes` * :doc:`/cookbook/entities/configure-backend-menu` <file_sep><?php declare(strict_types=1); namespace App\Installer\Checker; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Filesystem\Exception\IOException; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Finder\Iterator\RecursiveDirectoryIterator; use Symfony\Component\Security\Core\Exception\AccessDeniedException; final class CommandDirectoryChecker { private ?string $name = null; public function __construct(private Filesystem $filesystem) { } public function ensureDirectoryExists(string $directory, OutputInterface $output): void { if (!is_dir($directory)) { $this->createDirectory($directory, $output); } } public function ensureDirectoryIsWritable(string $directory, OutputInterface $output): void { try { $this->changePermissionsRecursively($directory, $output); } catch (AccessDeniedException $exception) { $output->writeln($this->createBadPermissionsMessage($exception->getMessage())); throw new \RuntimeException('Failed while trying to change directory permissions.'); } } public function setCommandName(string $name): void { $this->name = $name; } private function createDirectory(string $directory, OutputInterface $output): void { try { $this->filesystem->mkdir($directory, 0755); } catch (IOException $exception) { $output->writeln($this->createUnexistingDirectoryMessage(getcwd().'/'.$directory)); throw new \RuntimeException('Failed while trying to create directory.'); } $output->writeln(sprintf('<comment>Created "%s" directory.</comment>', $directory)); } private function changePermissionsRecursively(string $directory, OutputInterface $output): void { if (is_file($directory) && is_writable($directory)) { return; } if (!is_writable($directory)) { $this->changePermissions($directory, $output); return; } foreach (new RecursiveDirectoryIterator($directory, \FilesystemIterator::CURRENT_AS_FILEINFO) as $subdirectory) { if ('.' !== $subdirectory->getFilename()[0]) { $this->changePermissionsRecursively($subdirectory->getPathname(), $output); } } } /** * @throws AccessDeniedException if directory/file permissions cannot be changed */ private function changePermissions(string $directory, OutputInterface $output): void { try { $this->filesystem->chmod($directory, 0755, 0000, true); $output->writeln(sprintf('<comment>Changed "%s" permissions to 0755.</comment>', $directory)); } catch (IOException $exception) { throw new AccessDeniedException(dirname($directory)); } } private function createUnexistingDirectoryMessage(string $directory): string { return '<error>Cannot run command due to unexisting directory (tried to create it automatically, failed).</error>'.PHP_EOL. sprintf('Create directory "%s" and run command "<comment>%s</comment>"', $directory, $this->name) ; } private function createBadPermissionsMessage(string $directory): string { return '<error>Cannot run command due to bad directory permissions (tried to change permissions to 0755).</error>'.PHP_EOL. sprintf('Set "%s" writable recursively and run command "<comment>%s</comment>"', $directory, $this->name) ; } } <file_sep>* :doc:`/book/architecture/architecture` * :doc:`/book/architecture/fixtures` <file_sep><?php declare(strict_types=1); namespace App\Tests\Behat\Page\Frontend\Account; use Behat\Mink\Exception\ElementNotFoundException; use FriendsOfBehat\PageObjectExtension\Page\SymfonyPage; class ChangePasswordPage extends SymfonyPage { public function getRouteName(): string { return 'sylius_frontend_account_change_password'; } public function checkValidationMessageFor(string $element, string $message): bool { $errorLabel = $this->getElement($element)->getParent()->find('css', '.sylius-validation-error'); if (null === $errorLabel) { throw new ElementNotFoundException($this->getSession(), 'Validation message', 'css', '.sylius-validation-error'); } return $message === $errorLabel->getText(); } public function specifyCurrentPassword(?string $password): void { $this->getElement('current_password')->setValue($password); } public function specifyNewPassword(?string $password): void { $this->getElement('new_password')->setValue($password); } public function specifyConfirmationPassword(?string $password): void { $this->getElement('confirmation')->setValue($password); } /** * {@inheritdoc} */ protected function getDefinedElements(): array { return array_merge(parent::getDefinedElements(), [ 'confirmation' => '#sylius_user_change_password_newPassword_second', 'current_password' => <PASSWORD>', 'new_password' => <PASSWORD>', ]); } } <file_sep><?php declare(strict_types=1); use Rector\Core\Configuration\Option; use Rector\Core\ValueObject\PhpVersion; use Rector\Doctrine\Set\DoctrineSetList; use Rector\Php74\Rector\Property\TypedPropertyRector; use Rector\Php80\Rector\Class_\ClassPropertyAssignToConstructorPromotionRector; use Rector\Symfony\Set\SymfonySetList; use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; return static function (ContainerConfigurator $containerConfigurator): void { // get parameters $parameters = $containerConfigurator->parameters(); $parameters->set(Option::PATHS, [ __DIR__ . '/src/Monofony/Component/Admin', __DIR__ . '/src/Monofony/MetaPack/AdminMeta/.recipe/src', __DIR__ . '/src/Monofony/MetaPack/ApiMeta/.recipe/src', __DIR__ . '/src/Monofony/MetaPack/CoreMeta/.recipe/src', __DIR__ . '/src/Monofony/MetaPack/FrontMeta/.recipe/src', ]); $parameters->set(Option::SYMFONY_CONTAINER_XML_PATH_PARAMETER, __DIR__ . '/var/cache/dev/App_KernelDevDebugContainer.xml', ); // Define what rule sets will be applied // $containerConfigurator->import(SetList::DEAD_CODE); // get services (needed for register a single rule) $services = $containerConfigurator->services(); // register a single rule $services->set(TypedPropertyRector::class); $services->set(ClassPropertyAssignToConstructorPromotionRector::class); $parameters->set(Option::PHP_VERSION_FEATURES, PhpVersion::PHP_74); $parameters->set(Option::PHP_VERSION_FEATURES, PhpVersion::PHP_80); $parameters->set(Option::AUTO_IMPORT_NAMES, true); $parameters->set(Option::IMPORT_SHORT_CLASSES, false); // $containerConfigurator->import(SymfonySetList::SYMFONY_44); $containerConfigurator->import(SymfonySetList::SYMFONY_52); // $containerConfigurator->import(SymfonySetList::SYMFONY_CODE_QUALITY); $containerConfigurator->import(SymfonySetList::SYMFONY_CONSTRUCTOR_INJECTION); $containerConfigurator->import(SymfonySetList::ANNOTATIONS_TO_ATTRIBUTES); // $containerConfigurator->import(DoctrineSetList::ANNOTATIONS_TO_ATTRIBUTES); }; <file_sep>* :doc:`/book/user/admins` * :doc:`/book/user/customers` <file_sep><?php declare(strict_types=1); namespace App\Factory; use App\Entity\Customer\Customer; use App\Entity\User\AppUser; use App\Repository\UserRepository; use Monofony\Contracts\Core\Model\User\AppUserInterface; use Zenstruck\Foundry\ModelFactory; use Zenstruck\Foundry\Proxy; use Zenstruck\Foundry\RepositoryProxy; /** * @extends ModelFactory<AppUser> * * @method static AppUser|Proxy createOne(array $attributes = []) * @method static AppUser[]|Proxy[] createMany(int $number, array|callable $attributes = []) * @method static AppUser|Proxy find(object|array|mixed $criteria) * @method static AppUser|Proxy findOrCreate(array $attributes) * @method static AppUser|Proxy first(string $sortedField = 'id') * @method static AppUser|Proxy last(string $sortedField = 'id') * @method static AppUser|Proxy random(array $attributes = []) * @method static AppUser|Proxy randomOrCreate(array $attributes = []) * @method static AppUser[]|Proxy[] all() * @method static AppUser[]|Proxy[] findBy(array $attributes) * @method static AppUser[]|Proxy[] randomSet(int $number, array $attributes = []) * @method static AppUser[]|Proxy[] randomRange(int $min, int $max, array $attributes = []) * @method static UserRepository|RepositoryProxy repository() * @method AppUser|Proxy create(array|callable $attributes = []) */ final class AppUserFactory extends ModelFactory { protected function getDefaults(): array { return [ 'customer' => null, 'username' => self::faker()->userName(), 'email' => self::faker()->email(), 'first_name' => self::faker()->firstName(), 'last_name' => self::faker()->lastName(), 'enabled' => true, 'password' => '<PASSWORD>', 'roles' => [], ]; } protected function initialize(): self { return $this ->beforeInstantiate(function (array $attributes): array { $customer = $attributes['customer']; $roles = $attributes['roles']; $roles[] = 'ROLE_USER'; $attributes['roles'] = array_unique($roles); if (null === $customer) { $customer = new Customer(); $customer->setEmail($attributes['email']); $customer->setFirstName($attributes['first_name']); $customer->setLastName($attributes['last_name']); } unset($attributes['email']); unset($attributes['first_name']); unset($attributes['last_name']); $attributes['customer'] = $customer; return $attributes; }) ->afterInstantiate(function (AppUserInterface $appUser) { $appUser->setPlainPassword($appUser->getPassword()); $appUser->setPassword(null); }) ; } protected static function getClass(): string { return AppUser::class; } } <file_sep><?php declare(strict_types=1); namespace App\Message; use App\Validator\Constraints as CustomConstraints; use Symfony\Component\Serializer\Annotation\Groups; use Symfony\Component\Validator\Constraints\Email; use Symfony\Component\Validator\Constraints\Length; use Symfony\Component\Validator\Constraints\NotBlank; final class RegisterAppUser { /** * @CustomConstraints\UniqueAppUserEmail() */ #[NotBlank(message: 'sylius.customer.email.not_blank')] #[Email(message: 'sylius.customer.email.invalid', mode: 'strict')] #[Length(max: 254, maxMessage: 'sylius.customer.email.max')] #[Groups(groups: ['customer:write'])] public ?string $email = null; #[NotBlank(message: 'sylius.user.plainPassword.not_blank')] #[Length(min: 4, max: 254, minMessage: 'sylius.user.password.min', maxMessage: 'sylius.user.password.max')] #[Groups(groups: ['customer:write'])] public ?string $password = null; #[Groups(groups: ['customer:write'])] public ?string $firstName = null; #[Groups(groups: ['customer:write'])] public ?string $lastName = null; #[Groups(groups: ['customer:write'])] public ?string $phoneNumber = null; public function __construct( ?string $email = null, ?string $password = null, ?string $firstName = null, ?string $lastName = null, ?string $phoneNumber = null ) { $this->email = $email; $this->password = $<PASSWORD>; $this->firstName = $firstName; $this->lastName = $lastName; $this->phoneNumber = $phoneNumber; } } <file_sep><?php namespace spec\App\Entity\User; use Doctrine\Common\Collections\Collection; use Monofony\Contracts\Core\Model\User\AdminAvatarInterface; use Monofony\Contracts\Core\Model\User\AdminUserInterface; use PhpSpec\ObjectBehavior; use Sylius\Component\User\Model\User; use Sylius\Component\User\Model\UserInterface; final class AdminUserSpec extends ObjectBehavior { function it_extends_a_base_user_model(): void { $this->shouldHaveType(User::class); } function it_implements_an_admin_user_interface(): void { $this->shouldImplement(AdminUserInterface::class); } function it_implements_a_user_interface(): void { $this->shouldImplement(UserInterface::class); } function it_has_a_generated_salt_by_default(): void { $this->getSalt()->shouldNotReturn(null); } function it_initializes_oauth_accounts_collection_by_default(): void { $this->getOAuthAccounts()->shouldHaveType(Collection::class); } function its_not_enabled_by_default(): void { $this->shouldNotBeEnabled(); } function it_has_admin_role_by_default(): void { $this->getRoles()->shouldReturn([AdminUserInterface::DEFAULT_ADMIN_ROLE]); } function it_has_no_first_name_by_default(): void { $this->getFirstName()->shouldReturn(null); } function its_first_name_is_mutable(): void { $this->setFirstName('John'); $this->getFirstName()->shouldReturn('John'); } function it_has_no_last_name_by_default(): void { $this->getLastName()->shouldReturn(null); } function its_last_name_is_mutable(): void { $this->setLastName('Doe'); $this->getLastName()->shouldReturn('Doe'); } function it_has_no_avatar_by_default(): void { $this->getAvatar()->shouldReturn(null); } function its_avatar_is_mutable(AdminAvatarInterface $avatar): void { $this->setAvatar($avatar); $this->getAvatar()->shouldReturn($avatar); } } <file_sep><?php declare(strict_types=1); namespace App\Tests\Controller\Customer; use App\Story\TestAppUsersStory; use App\Tests\Controller\AuthorizedHeaderTrait; use App\Tests\Controller\JsonApiTestCase; use App\Tests\Controller\PurgeDatabaseTrait; use Symfony\Component\HttpFoundation\Response; use Zenstruck\Foundry\Test\Factories; class LoginApiTest extends JsonApiTestCase { use AuthorizedHeaderTrait; use Factories; use PurgeDatabaseTrait; /** @test */ public function it_provides_an_access_token(): void { TestAppUsersStory::load(); $data = <<<EOT { "username": "<EMAIL>", "password": "<PASSWORD>" } EOT; $this->client->request('POST', '/api/authentication_token', [], [], ['CONTENT_TYPE' => 'application/json'], $data); $response = $this->client->getResponse(); $this->assertResponse($response, 'authentication/new_access_token', Response::HTTP_OK); } } <file_sep>## Change Log ### v0.5.3 (2021/03/25 15:46 +00:00) - [#312](https://github.com/Monofony/Monofony/pull/312) Same node dependencies as skeleton (@loic425) - [#310](https://github.com/Monofony/Monofony/pull/310) fix ApiPlatform configuration (@smildev) - [#306](https://github.com/Monofony/Monofony/pull/306) Fix monorepo-builder configuration (@loic425) ### v0.5.2 (2021/02/01 13:13 +00:00) - [#304](https://github.com/Monofony/Monofony/pull/304) Migrate to php configuration for symplify packages (@loic425) - [#302](https://github.com/Monofony/Monofony/pull/302) Bump api platform core version (@loic425) - [#298](https://github.com/Monofony/Monofony/pull/298) Fix API pack to support api platform 2.6 (@loic425) - [#301](https://github.com/Monofony/Monofony/pull/301) Use Behat dmore extensions (@loic425) - [#299](https://github.com/Monofony/Monofony/pull/299) Move Behat bridge on dev requirements (@loic425) - [#297](https://github.com/Monofony/Monofony/pull/297) Update readme for documentation (@loic425) ### v0.5.1 (2021/01/21 07:06 +00:00) - [#296](https://github.com/Monofony/Monofony/pull/296) [HotFix] CRUD templates when there are no form templates configured (@loic425) ### v0.5.0 (2021/01/18 11:36 +00:00) - [#292](https://github.com/Monofony/Monofony/pull/292) Update phpspec/phpspec requirement from ^6.2 to ^7.0 (@loic425, @dependabot-preview[bot]) - [#294](https://github.com/Monofony/Monofony/pull/294) [API] Change password endpoint (@loic425) - [#291](https://github.com/Monofony/Monofony/pull/291) Me endpoints (@loic425) - [#290](https://github.com/Monofony/Monofony/pull/290) Move register app user on customer resource (@loic425) - [#211](https://github.com/Monofony/Monofony/pull/211) Bump se/selenium-server-standalone from 2.53.1 to 3.141.59 (@loic425, @dependabot-preview[bot]) - [#289](https://github.com/Monofony/Monofony/pull/289) Bump Doctrine migrations version (@loic425) - [#288](https://github.com/Monofony/Monofony/pull/288) Move Behat suites configuration (@loic425) - [#287](https://github.com/Monofony/Monofony/pull/287) Move Sylius routes configuration on config/sylius/routes directory (@loic425) - [#286](https://github.com/Monofony/Monofony/pull/286) Replace Lakion mink debug extension (@loic425) - [#285](https://github.com/Monofony/Monofony/pull/285) Api key on swagger (@loic425) - [#262](https://github.com/Monofony/Monofony/pull/262) Bump ini from 1.3.5 to 1.3.8 (@dependabot[bot]) - [#284](https://github.com/Monofony/Monofony/pull/284) Remove guzzle dependency (@loic425) - [#282](https://github.com/Monofony/Monofony/pull/282) Update friends-of-phpspec/phpspec-code-coverage requirement from ^4.3 to ^5.0 (@loic425, @dependabot-preview[bot]) - [#278](https://github.com/Monofony/Monofony/pull/278) Fix CI (@loic425) - [#283](https://github.com/Monofony/Monofony/pull/283) Fix browser kit driver on behat bridge (@loic425) - [#277](https://github.com/Monofony/Monofony/pull/277) Fix Behat bridge dependencies (@loic425) - [#276](https://github.com/Monofony/Monofony/pull/276) Set branch alias on all packages (@loic425) - [#275](https://github.com/Monofony/Monofony/pull/275) Symfony versions on github actions (@loic425) - [#273](https://github.com/Monofony/Monofony/pull/273) Upgrade dependencies (@loic425) - [#272](https://github.com/Monofony/Monofony/pull/272) Test packages (@loic425) - [#271](https://github.com/Monofony/Monofony/pull/271) Github actions badge on readme (@loic425) - [#270](https://github.com/Monofony/Monofony/pull/270) Bye bye Travis (@loic425) - [#269](https://github.com/Monofony/Monofony/pull/269) Behat with frontend (@loic425) - [#268](https://github.com/Monofony/Monofony/pull/268) Github actions (@loic425) <file_sep><?php namespace spec\App\Dashboard\Statistics; use App\Dashboard\Statistics\CustomerStatistic; use App\Repository\CustomerRepository; use PhpSpec\ObjectBehavior; use Symfony\Component\Templating\EngineInterface; use Twig\Environment; class CustomerStatisticSpec extends ObjectBehavior { function let(CustomerRepository $customerRepository, Environment $twig): void { $this->beConstructedWith($customerRepository, $twig); } function it_is_initializable() { $this->shouldHaveType(CustomerStatistic::class); } function it_generate_statistics( CustomerRepository $customerRepository, Environment $twig ): void { $customerRepository->countCustomers()->willReturn(6); $twig->render('backend/dashboard/statistics/_amount_of_customers.html.twig', [ 'amountOfCustomers' => 6, ])->willReturn('statistics'); $twig->render('backend/dashboard/statistics/_amount_of_customers.html.twig', [ 'amountOfCustomers' => 6, ])->shouldBeCalled(); $this->generate(); } } <file_sep>.. rst-class:: outdated .. danger:: This is an outdated documentation please read the new `Monofony documentation`_ instead. How to design services with phpspec =================================== Lets configure an Article factory to create an article for an author. This Author implements CustomerInterface. Generate phpspec for your entity factory ---------------------------------------- .. code-block:: bash $ vendor/bin/phpspec describe App/Factory/ArticleFactory $ # with phpdbg installed $ phpdbg -qrr vendor/bin/phpspec describe App/Factory/ArticleFactory Run phpspec and do not fear Red ------------------------------- To run phpspec for our Article factory, run this command: .. code-block:: bash $ vendor/bin/phpspec run spec/App/Factory/ArticleFactory.php -n $ $ # with phpdbg installed $ phpdbg -qrr vendor/bin/phpspec run spec/App/Factory/ArticleFactorySpec.php -n And be happy with your first error message with red color. .. note:: You can simply run all the phpspec tests by running `vendor/bin/phpspec run -n` Create a minimal article factory class -------------------------------------- .. code-block:: php # src/Factory/ArticleFactory.php namespace App\Factory; class ArticleFactory { } Rerun phpspec and see a beautiful green color. Specify it implements sylius factory interface ______________________________________________ .. code-block:: php # spec/App/Factory/ArticleFactorySpec.php function it_implements_sylius_factory_interface(): void { $this->shouldImplement(FactoryInterface::class); } .. warning:: Don't forget to rerun phpspec on each step. Solve this on your factory -------------------------- .. code-block:: php # src/Factory/ArticleFactory.php namespace App\Factory; use Sylius\Component\Resource\Factory\FactoryInterface; class ArticleFactory implements FactoryInterface { /** * {@inheritdoc} */ public function createNew() { } } Specify it creates articles ----------------------------------------- .. code-block:: php # spec/App/Factory/ArticleFactorySpec.php // [...] function its_creates_articles(): void { $article = $this->createNew(); $article->shouldImplement(Article::class); } Solve this on your factory -------------------------- .. code-block:: php # src/Factory/ArticleFactory.php namespace App\Factory; use Sylius\Component\Resource\Factory\FactoryInterface; class ArticleFactory implements FactoryInterface { /** @var string */ private $className; public function __construct(string $className) { $this->className = $className; } /** * {@inheritdoc} */ public function createNew(): Article { return new $this->className(); } } Running this step will throw this exception: .. code-block:: php exception [err:ArgumentCountError("Too few arguments to function App\Factory\ArticleFactory::__construct(), 0 passed and exactly 1 expected")] has been thrown. To add arguments on constructor, go back to your factory spec and add these lines: .. code-block:: php # spec/App/Factory/ArticleFactorySpec.php namespace spec\App\Factory; use App\Entity\Article; use App\Factory\ArticleFactory; use PhpSpec\ObjectBehavior; use Sylius\Component\Resource\Factory\FactoryInterface; class ArticleFactorySpec extends ObjectBehavior { function let() { $this->beConstructedWith(Article::class); } // [...] } Rerun phpspec and it should be solved. .. note:: Here you pass a string, but you often need to pass objects on constructor. You just have to add them on arguments of the let method and don't forget to use typehints. Here is an example with object arguments: .. code-block:: php function let(FactoryInterface $factory) { $this->beConstructedWith($factory); } Specify it creates articles for an author ----------------------------------------- .. code-block:: php # spec/App/Factory/ArticleFactorySpec.php // [...] function its_creates_articles_for_an_author(CustomerInterface $author): void { $article = $this->createForAuthor($author); $article->getAuthor()->shouldReturn($author); } Add this method on your factory ------------------------------- .. code-block:: php # src/Factory/ArticleFactory.php // [...] /** * @param CustomerInterface $author * * @return Article */ public function createForAuthor(CustomerInterface $author): Article { $article = $this->createNew(); $article->setAuthor($author); return $article; } And that's all to specify this simple article factory. .. _Monofony documentation: https://docs.monofony.com <file_sep>#!/usr/bin/env bash # Argument 1: Command to run run_command() { echo "> $1" eval "$1" } # Argument 1: Command to run run_command_reporting_status() { local code=0 run_command "$1" || code=$? if [ "${code}" = "0" ]; then print_success "Command \"$1\" exited with code ${code}\n" else print_error "Command \"$1\" exited with code ${code}\n" fi return ${code} } # Argument 1: Command to run retry_run_command() { run_command "$1" if [ "$?" != "0" ]; then run_command "$1" fi } # Argument 1: Text bold() { echo -e "\e[1m$1\e[0;20m" } # Argument 1: Text bold_green() { echo -e "\e[33;1m$1\e[0;20m" } # Argument 1: Text red() { echo -e "\e[31m$1\e[0m" } # Argument 1: Text bold_red() { echo -e "\e[31;1m$1\e[0;20m" } # Argument 1: Text print_error() { echo -e "$(bold_red "$1")" 1>&2 } # Argument 1: Text print_success() { echo -e "$(bold_green "$1")" } # Argument 1: Action # Argument 2: Subject print_header() { echo -e "$(bold "$1"): $(bold_green "$2")" } # Argument 1: Text print_info() { echo "=> $1" } # Argument 1: Text print_warning() { echo "=> $1" 1>&2 } # Argument 1: Text exit_on_error() { if [ "$?" != "0" ]; then print_error "$1" exit 1 fi } # Argument 1: String to hash text_md5sum() { echo "$1" | md5sum | awk '{ print $1 }' } # Argument 1: File to hash file_md5sum() { md5sum "$1" | awk '{ print $1 }' } # Argument 1: Binary name get_binary() { if [ -x "bin/$1" ]; then echo "bin/$1" elif [ -x "vendor/bin/$1" ]; then echo "vendor/bin/$1" else return 1 fi } get_number_of_jobs_for_parallel() { local jobs="100%" if [[ "${TRAVIS}" = "true" ]]; then jobs="2" fi echo "${jobs}" } get_app_name_path() { echo "$(cd "$(dirname "${BASH_SOURCE[0]}")/../../" && pwd)" } has_app_name_cache() { if [[ ! -z "${APP_NAME_CACHE_DIR}" && -d "${APP_NAME_CACHE_DIR}" ]]; then return 0 else return 1 fi } inform_about_app_name_cache() { if ! has_app_name_cache; then print_warning "Sylius cache should be used, but it is not configured correctly." print_warning "Check whether you have \$APP_NAME_CACHE_DIR set and if that directory exists." fi } locate_packages() { find "$(pwd)/src/Sylius" -mindepth 3 -maxdepth 3 -type f -name composer.json -exec dirname '{}' \; } find_packages() { locate_packages | package_path_to_package_name } # Argument 1: Package path package_path_to_package_name() { basename "$1" } # Argument 1: Package name package_name_to_package_path() { find "$(pwd)/src/Sylius" -mindepth 2 -maxdepth 2 -type d -name "$1" } # Argument 1: Package path or name cast_package_argument_to_package_path() { local package_path="$1" if [ ! -d "${package_path}" ]; then package_path="$(package_name_to_package_path "$1")" fi if [[ -z "${package_path}" || ! -d "${package_path}" ]]; then return 1 fi echo "${package_path}" } # Argument 1: Package path or name is_package_cache_fresh() { local current_hash cached_hash local package_path="$(cast_package_argument_to_package_path "$1")" local cache_key="$(get_package_cache_key "$1")" if [[ -f "${APP_NAME_CACHE_DIR}/composer-${cache_key}.lock" && -f "${APP_NAME_CACHE_DIR}/composer-${cache_key}.json.md5sum" ]]; then current_hash="$(file_md5sum "${package_path}/composer.json")" cached_hash="$(cat "${APP_NAME_CACHE_DIR}/composer-${cache_key}.json.md5sum")" if [ "${current_hash}" = "${cached_hash}" ]; then return 0 fi fi return 1 } # Argument 1: Package path or name get_package_cache_key() { text_md5sum "$(cast_package_argument_to_package_path "$1")" }
dee66fd65839db16c7a783ad408007e2738f4320
[ "SQL", "reStructuredText", "Markdown", "JavaScript", "Makefile", "Python", "Text", "PHP", "Shell" ]
181
PHP
Monofony/Monofony
33e8876ad19a3cab4e6f8d14f085a98458f961a1
4fa117873bb6ad0b0943a39a31391780ceb269a4